From 7ed4b56940d3452d8b300eec1639a93da75ba009 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 22:52:07 +0800 Subject: [PATCH 01/24] feat(cua): serve Computer Use to MCP clients from the cua-mcp profile Add @deepseek-ai/dsh-cua-mcp, an experimental optional bundle whose profile frontend serves cua_run_code and cua_reset over MCP stdio to Codex, Claude Code, and other harnesses. One connection owns one Agent; programs run through ctx.tools.execute without a model step, the first result carries the cua API reference, and screenshots are delivered as the request version the program observed. DSH_CUA_CONSENT selects unattended approval or client elicitation; --print-client-config renders the client entry for the exact installation. Supporting changes: dsh-cua gains a configured screenshotTarget and the ctx.cuaPrograms reset/screenshot-target service, the PTC program-tool factory exposes createRunCodeToolHandle with reset control, and dsh plugin gains manifest-only enable/disable verbs for installed bundles. --- ...26-11-09-computer-use-mcp-server.i18n.yaml | 19 ++ .../2026-11-09-computer-use-mcp-server.md | 37 +++ .../2026-11-09-computer-use-mcp-server.zh.md | 37 +++ apps/cli/package.json | 1 + apps/cli/reference/README.i18n.yaml | 4 +- apps/cli/reference/README.md | 2 + apps/cli/reference/README.zh.md | 2 + apps/cli/src/args.ts | 2 +- apps/cli/src/plugin.ts | 66 ++++- apps/cli/tests/plugin.spec.ts | 55 +++- .../profiles/cua-mcp/cua-mcp.expected.e2e.ts | 105 +++++++ .../profiles/cua-mcp/expected/codex.toml | 13 + .../cua-mcp/expected/instructions.txt | 1 + .../profiles/cua-mcp/expected/reference.md | 54 ++++ .../profiles/cua-mcp/expected/tools.json | 54 ++++ .../tests/profiles/cua-mcp/fixture.patch.yml | 15 + apps/cli/tests/profiles/cua-mcp/probe.ts | 102 +++++++ docs/capability-seams.i18n.yaml | 4 +- docs/capability-seams.md | 5 + docs/capability-seams.zh.md | 5 + docs/cli-help.md | 3 +- docs/cli-help.zh.md | 3 +- docs/config-catalog.md | 23 ++ docs/config-catalog.zh.md | 23 ++ docs/event-producer-consumer.md | 2 +- docs/event-producer-consumer.zh.md | 2 +- docs/module-graph.md | 17 +- docs/module-graph.zh.md | 17 +- docs/subsystems/computer-use.i18n.yaml | 3 + docs/subsystems/computer-use.md | 36 +++ docs/subsystems/computer-use.zh.md | 36 +++ docs/subsystems/mcp.i18n.yaml | 4 +- docs/subsystems/mcp.md | 1 + docs/subsystems/mcp.zh.md | 1 + packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 2 +- packages/boot/app-boot/README.zh.md | 2 +- packages/boot/app-boot/src/index.ts | 1 + packages/boot/app-boot/tests/app-boot.spec.ts | 1 + .../core/tool-executor-ptc/README.i18n.yaml | 4 +- packages/core/tool-executor-ptc/README.md | 2 +- packages/core/tool-executor-ptc/README.zh.md | 2 +- .../core/tool-executor-ptc/src/run-code.ts | 51 +++- .../tool-executor-ptc/tests/run-code.spec.ts | 51 +++- packages/experimental/README.i18n.yaml | 4 +- packages/experimental/README.md | 1 + packages/experimental/README.zh.md | 1 + .../experimental/cua-macos/README.i18n.yaml | 4 +- packages/experimental/cua-macos/README.md | 1 + packages/experimental/cua-macos/README.zh.md | 1 + .../tests/provider-lifecycle.spec.ts | 40 ++- .../experimental/cua-mcp/README.i18n.yaml | 58 ++++ packages/experimental/cua-mcp/README.md | 148 ++++++++++ packages/experimental/cua-mcp/README.zh.md | 148 ++++++++++ .../experimental/cua-mcp/cordis.patch.yml | 54 ++++ packages/experimental/cua-mcp/icon.svg | 42 +++ packages/experimental/cua-mcp/locale/de.json | 6 + packages/experimental/cua-mcp/locale/en.json | 6 + packages/experimental/cua-mcp/locale/es.json | 6 + packages/experimental/cua-mcp/locale/fr.json | 6 + packages/experimental/cua-mcp/locale/ja.json | 6 + packages/experimental/cua-mcp/locale/pt.json | 6 + packages/experimental/cua-mcp/locale/ru.json | 6 + packages/experimental/cua-mcp/locale/zh.json | 6 + packages/experimental/cua-mcp/package.json | 91 ++++++ .../experimental/cua-mcp/src/client-config.ts | 119 ++++++++ packages/experimental/cua-mcp/src/consent.ts | 115 ++++++++ packages/experimental/cua-mcp/src/index.ts | 93 ++++++ .../experimental/cua-mcp/src/projection.ts | 58 ++++ packages/experimental/cua-mcp/src/server.ts | 208 ++++++++++++++ .../experimental/cua-mcp/tests/bundle.spec.ts | 74 +++++ .../cua-mcp/tests/client-config.spec.ts | 73 +++++ .../cua-mcp/tests/composition.spec.ts | 267 ++++++++++++++++++ .../cua-mcp/tests/consent.spec.ts | 80 ++++++ .../cua-mcp/tests/projection.spec.ts | 68 +++++ .../experimental/cua-mcp/tests/server.spec.ts | 182 ++++++++++++ .../cua-mcp/tests/startup.spec.ts | 150 ++++++++++ packages/experimental/cua-mcp/tsconfig.json | 48 ++++ packages/experimental/cua/README.i18n.yaml | 8 +- packages/experimental/cua/README.md | 4 +- packages/experimental/cua/README.zh.md | 4 +- packages/experimental/cua/src/config.ts | 26 ++ packages/experimental/cua/src/guidance.ts | 3 + packages/experimental/cua/src/index.ts | 19 +- .../experimental/cua/src/tool-registration.ts | 46 ++- .../cua/tests/agent-scopes.spec.ts | 6 + .../cua/tests/run-code-composition.spec.ts | 35 +++ .../extensions/tool-cordis/src/api-catalog.ts | 20 ++ .../skills/dsh-doc/references/packages.md | 1 + packages/util/official-bundles/src/bundles.ts | 1 + .../official-bundles/src/plugin-manager.ts | 5 +- pnpm-lock.yaml | 110 ++++++++ scripts/experimental-package-policy.ts | 1 + scripts/gen-cordis-catalog.ts | 1 + scripts/gen-doc-graphs.ts | 5 + scripts/package-dependency-policy.ts | 4 +- scripts/release/families.spec.ts | 1 + tsconfig.base.json | 1 + tsconfig.host.json | 1 + 99 files changed, 3284 insertions(+), 68 deletions(-) create mode 100644 .agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml create mode 100644 .agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md create mode 100644 .agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md create mode 100644 apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts create mode 100644 apps/cli/tests/profiles/cua-mcp/expected/codex.toml create mode 100644 apps/cli/tests/profiles/cua-mcp/expected/instructions.txt create mode 100644 apps/cli/tests/profiles/cua-mcp/expected/reference.md create mode 100644 apps/cli/tests/profiles/cua-mcp/expected/tools.json create mode 100644 apps/cli/tests/profiles/cua-mcp/fixture.patch.yml create mode 100644 apps/cli/tests/profiles/cua-mcp/probe.ts create mode 100644 packages/experimental/cua-mcp/README.i18n.yaml create mode 100644 packages/experimental/cua-mcp/README.md create mode 100644 packages/experimental/cua-mcp/README.zh.md create mode 100644 packages/experimental/cua-mcp/cordis.patch.yml create mode 100644 packages/experimental/cua-mcp/icon.svg create mode 100644 packages/experimental/cua-mcp/locale/de.json create mode 100644 packages/experimental/cua-mcp/locale/en.json create mode 100644 packages/experimental/cua-mcp/locale/es.json create mode 100644 packages/experimental/cua-mcp/locale/fr.json create mode 100644 packages/experimental/cua-mcp/locale/ja.json create mode 100644 packages/experimental/cua-mcp/locale/pt.json create mode 100644 packages/experimental/cua-mcp/locale/ru.json create mode 100644 packages/experimental/cua-mcp/locale/zh.json create mode 100644 packages/experimental/cua-mcp/package.json create mode 100644 packages/experimental/cua-mcp/src/client-config.ts create mode 100644 packages/experimental/cua-mcp/src/consent.ts create mode 100644 packages/experimental/cua-mcp/src/index.ts create mode 100644 packages/experimental/cua-mcp/src/projection.ts create mode 100644 packages/experimental/cua-mcp/src/server.ts create mode 100644 packages/experimental/cua-mcp/tests/bundle.spec.ts create mode 100644 packages/experimental/cua-mcp/tests/client-config.spec.ts create mode 100644 packages/experimental/cua-mcp/tests/composition.spec.ts create mode 100644 packages/experimental/cua-mcp/tests/consent.spec.ts create mode 100644 packages/experimental/cua-mcp/tests/projection.spec.ts create mode 100644 packages/experimental/cua-mcp/tests/server.spec.ts create mode 100644 packages/experimental/cua-mcp/tests/startup.spec.ts create mode 100644 packages/experimental/cua-mcp/tsconfig.json diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml new file mode 100644 index 0000000000..02417d58c7 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml @@ -0,0 +1,19 @@ +# Bilingual-pair consistency record for 2026-11-09-computer-use-mcp-server.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write .agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md +/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server: + en: 1e4562a8dd533e1f + zh: 4e41a369a3a88f02 +/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/problem: + en: 6050884223e0e491 + zh: eb808c298c9fb652 +/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/decision: + en: 7087ecc0b83d2759 + zh: 9008903182bb7e13 +/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/alternatives-considered: + en: cad5bdefc9bfe720 + zh: 8564660068c66fc1 +/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/consequences: + en: cb25b3b611178f0a + zh: 6234bf3e87e0e14c diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md new file mode 100644 index 0000000000..1ec8139e67 --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md @@ -0,0 +1,37 @@ +# Agent Note: Serve Computer Use to other harnesses as an MCP server + +Status: implemented + +English | [中文](2026-11-09-computer-use-mcp-server.zh.md) + +## Problem + +Computer Use training data should come from several agent harnesses, not only from DSH sessions. Codex, Claude Code, and in-house harnesses connect to capabilities through MCP stdio servers; Codex's own Computer Use is a stdio server with a persistent JavaScript REPL. DSH's `cua_run_code` already composes a retained program environment, consent, screenshots, and native connections per Agent, but only a DSH model turn could call it. The MCP form must keep those owners, persist program state across calls, and start from one documented command on every DSH distribution. + +## Decision + +`@deepseek-ai/dsh-cua-mcp` is an experimental bundle in `OPTIONAL_BUNDLES`: a profile frontend over `dsh-base` selected with `dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp` and started with `dsh --profile cua-mcp`. It is the only MCP application path; no package bin or SDK escape exists, and a shipped profile template waits for CUA promotion because templates cannot name experimental packages. + +The server runs inside the profile process and calls `ctx.tools.execute` with the connection's Agent and no model step. One stdio connection owns one Agent: creation after client initialization, disposal at stdin EOF. Agent ownership already selects the retained program process, native connection, and session-scoped grants, so connection lifetime and state lifetime coincide. The empty default preset `cua-mcp` gives that Agent `cua_run_code` and nothing else, because the provider registers program tools only for composed presets. + +Two tools form the surface. `cua_run_code` forwards `code`, an optional `description` defaulting to `CUA program`, and `timeoutMs`; its first result per connection carries the execution rules and the complete `cua` API reference, keeping the tool description within client limits. `cua_reset` releases the program environment through `ctx.cuaPrograms.reset`, which the CUA provider now exposes beside `screenshotRequestTarget`. The projection delivers each deferred screenshot as the request version the program observed, so coordinates in program text match the delivered image. The provider's new `screenshotTarget` configuration replaces the model-route lookup that a profile without a model cannot satisfy. + +Consent has two modes. `DSH_CUA_CONSENT=allow` answers every approval question of the connection's Agent with its approving label for the session. The default `elicit` forwards each question to the client as a form elicitation whose enum is the question's labels. No Session event is added: the training side consumes MCP tool results, and the connected harness's transcript records calls; DSH retains nested `tool/ptc-dispatch` events for diagnosis. + +`dsh plugin enable|disable` selects installed bundles by editing `dsh.profile.bundles` without pnpm, the same operation as the Plugins page switch, so the Python runtime wheel and offline training Hosts need no registry access. `--print-client-config codex|claude-code|json` renders the client entry for the exact installation. + +## Alternatives considered + +**An MCP server that launches `dsh --profile sdk` through the TypeScript SDK.** The SDK protocol has no request that runs a tool without a model turn; adding one changes the protocol and both SDK clients, and screenshots would cross a second process boundary. + +**A standalone CUA server outside the harness, like Codex's REPL.** Consent, sandboxing, logging, screenshot admission, and helper lifecycle would be rewritten. The in-profile server reuses those owners and remains the basis for a later extraction. + +**A `turn_ended` hidden tool with client hooks.** Its only use would be writing the client's turn boundaries into a log nobody consumes; held keys already release when a program settles. + +**Session events for root MCP calls.** The data consumers need only MCP results; a `tool/call` without a model step would invent a step the Session never ran. + +**Exposing the raw `cua` tool or program sandbox escalation.** Raw operations need per-method schemas the external model would relearn, and escalation needs an approval answerer the profile does not have. + +## Consequences + +Every installation carries the bundle and its optional macOS provider dependency; `verify-default-product-isolation` keeps it out of default templates. The required startup entry `cua-mcp` fails the profile loudly when the frontend cannot activate. Clients see state loss on process exit, `cua_reset`, or Agent disposal and recreate objects. Consent elicitation depends on the 2025 MCP request model; clients on the 2026-07-28 revision use `allow`. The reference text in the first result is pinned by the profile's expected-output test and changes with the installed CUA packages. diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md new file mode 100644 index 0000000000..a1b4a6477a --- /dev/null +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md @@ -0,0 +1,37 @@ +# Agent Note: 以 MCP 服务器向其他 harness 提供 Computer Use + +Status: implemented + +[English](2026-11-09-computer-use-mcp-server.md) | 中文 + +## 问题 + +Computer Use 的训练数据应来自多个 agent harness,而不只是 DSH 会话。Codex、Claude Code 以及内部 harness 通过 MCP stdio 服务器接入能力;Codex 自己的 Computer Use 就是一个带持久 JavaScript REPL 的 stdio 服务器。DSH 的 `cua_run_code` 已经按 Agent 组合了保留的程序环境、授权、截图和本机连接,但只有 DSH 的模型回合能调用它。MCP 形态必须保留这些所有者,在多次调用间持久化程序状态,并且在每种 DSH 分发中都能从一条有文档的命令启动。 + +## 决策 + +`@deepseek-ai/dsh-cua-mcp` 是 `OPTIONAL_BUNDLES` 中的实验性组合包:一个位于 `dsh-base` 之上的 profile 前端,用 `dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp` 选中,用 `dsh --profile cua-mcp` 启动。这是唯一的 MCP 应用路径;没有包 bin 或 SDK 逃逸,随附的 profile 模板等待 CUA 晋升,因为模板不能引用实验包。 + +服务器运行在 profile 进程内,带着连接的 Agent、不经模型步骤地调用 `ctx.tools.execute`。一个 stdio 连接拥有一个 Agent:客户端初始化后创建,stdin EOF 时销毁。Agent 归属已经决定了保留的程序进程、本机连接和会话级授权,因此连接生命周期与状态生命周期重合。空的默认 preset `cua-mcp` 让该 Agent 只获得 `cua_run_code`,因为提供方只为已组合 preset 注册程序工具。 + +工具面由两个工具构成。`cua_run_code` 转发 `code`、缺省为 `CUA program` 的可选 `description` 和 `timeoutMs`;每个连接的首个结果携带执行规则和完整的 `cua` API 参考,使工具描述保持在客户端限制之内。`cua_reset` 通过 `ctx.cuaPrograms.reset` 释放程序环境,CUA 提供方现在把它与 `screenshotRequestTarget` 一起暴露。投影把每张延后的截图按程序观察到的请求版本交付,使程序文本中的坐标与交付的图片一致。提供方新增的 `screenshotTarget` 配置取代了没有模型的 profile 无法满足的模型路由查询。 + +授权有两种模式。`DSH_CUA_CONSENT=allow` 以批准标签为本会话回答连接 Agent 的每个审批问题。默认的 `elicit` 把每个问题作为表单 elicitation 转发给客户端,枚举即问题的选项标签。不新增任何 Session 事件:训练侧只消费 MCP 工具结果,接入 harness 的 transcript 记录调用;DSH 保留嵌套的 `tool/ptc-dispatch` 事件以供诊断。 + +`dsh plugin enable|disable` 不经 pnpm、只编辑 `dsh.profile.bundles` 来选择已安装的组合包,与插件页开关是同一操作,因此 Python runtime wheel 和离线训练 Host 都不需要访问 registry。`--print-client-config codex|claude-code|json` 为当前安装渲染客户端配置项。 + +## 考虑过的替代方案 + +**通过 TypeScript SDK 启动 `dsh --profile sdk` 的 MCP 服务器。** SDK 协议没有不经模型回合直接运行工具的请求;补上它要改协议和两个 SDK 客户端,截图还要再跨一次进程边界。 + +**像 Codex 的 REPL 那样在 harness 之外的独立 CUA 服务器。** 授权、沙箱、日志、截图接入和 helper 生命周期都要重写。profile 内的服务器复用这些所有者,并仍是日后剥离的基础。 + +**带客户端 hook 的隐藏工具 `turn_ended`。** 它唯一的用途是把客户端的回合边界写进无人消费的日志;按键在程序结束时已经释放。 + +**为根 MCP 调用写 Session 事件。** 数据消费方只需要 MCP 结果;没有模型步骤的 `tool/call` 会虚构一个 Session 从未运行的步骤。 + +**暴露原始 `cua` 工具或程序沙箱提权。** 原始操作需要外部模型重新学习的逐方法 schema,提权需要该 profile 不具备的审批应答者。 + +## 后果 + +每个安装都携带该组合包及其可选的 macOS 提供方依赖;`verify-default-product-isolation` 让它留在默认模板之外。必需启动条目 `cua-mcp` 在前端无法激活时让 profile 大声失败。客户端会在进程退出、`cua_reset` 或 Agent 销毁时看到状态丢失并重新创建对象。授权 elicitation 依赖 2025 版 MCP 请求模型;使用 2026-07-28 修订版的客户端改用 `allow`。首个结果中的参考文本由 profile 的期望输出测试固定,并随已安装的 CUA 包变化。 diff --git a/apps/cli/package.json b/apps/cli/package.json index 4be57e7f46..799f71d270 100644 --- a/apps/cli/package.json +++ b/apps/cli/package.json @@ -115,6 +115,7 @@ "@deepseek-ai/dsh-experimental-session-search": "workspace:*", "@deepseek-ai/dsh-experimental-tool-worktree": "workspace:*", "@deepseek-ai/dsh-cua-bundle": "workspace:*", + "@deepseek-ai/dsh-cua-mcp": "workspace:*", "@deepseek-ai/dsh-experimental-plugin-market-bundle": "workspace:*", "@deepseek-ai/dsh-personalized-recommendations": "workspace:*", "@deepseek-ai/dsh-experimental-forge-bundle": "workspace:*" diff --git a/apps/cli/reference/README.i18n.yaml b/apps/cli/reference/README.i18n.yaml index 2c33416553..420c01973f 100644 --- a/apps/cli/reference/README.i18n.yaml +++ b/apps/cli/reference/README.i18n.yaml @@ -18,8 +18,8 @@ en: d6368bf97a02bd57 zh: 2ab7888a108961ce /dsh-cli-behavior-reference/plugin-management: - en: 8d2cfff9bab7327f - zh: 21515ab6e6798504 + en: 66fa35fcd6ec2a76 + zh: b5fbe1cd6ba9f336 /dsh-cli-behavior-reference/web-profile: en: 149c5571acd51baf zh: 300e3c2425273a92 diff --git a/apps/cli/reference/README.md b/apps/cli/reference/README.md index dc84a267d8..558b2d7e85 100644 --- a/apps/cli/reference/README.md +++ b/apps/cli/reference/README.md @@ -84,6 +84,8 @@ New directories and files request modes `0700` and `0600` on POSIX. The CLI prin `dsh plugin --profile ` initializes the profile when missing (shipped template, or `@deepseek-ai/dsh-base` alone for other names), then forwards `` to `pnpm` with the profile directory as working directory — `add`, `remove`, `why`, `update`, and every other pnpm verb work unchanged; pnpm must be on PATH. Relative path specs (`.`, `../plugin`, and their `file:`/`link:` forms) are anchored to the invoking directory first, so `add .` from a plugin checkout installs that checkout, not the profile. After every successful run, `dsh.profile.bundles` is reconciled against the installed state: each dependency resolving to a package whose manifest declares `"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }` joins the layer stack (so an `update` that gains the declaration activates it), a bundle-less dependency stays plain with a one-time warning, and a removed dependency leaves the stack. +`dsh plugin --profile enable ` and `disable ` change only `dsh.profile.bundles` and never run pnpm. `enable` selects a bundle the installation ships, such as an [optional bundle](../../../packages/util/official-bundles/README.md), or one the profile already installed, after its platform declaration and version compatibility pass; `disable` deselects it. Both refuse a bundle of the profile's shipped template, initialize a missing profile first, and print the change; a running profile applies it after a restart. + `dsh plugin` reads `--profile` only before the forwarded arguments, which start at the first token it does not recognize, so `--profile ` comes first. When the forwarded arguments begin with the pnpm command, everything after that command reaches pnpm verbatim, including `-h` and `--help`. When they begin with a pnpm option such as `--filter ` or `-r`, a later `-h` or `--help` still prints the forwarder's help instead of pnpm's, so put the pnpm command before them to reach pnpm's help. `-h` or `--help` before any forwarded argument prints the forwarder's own help and exits 0. The Codex and Claude Code subagent providers are separate optional Bundles. Add either package, both in one command, or remove either package independently: diff --git a/apps/cli/reference/README.zh.md b/apps/cli/reference/README.zh.md index 2de7755983..1785b2a163 100644 --- a/apps/cli/reference/README.zh.md +++ b/apps/cli/reference/README.zh.md @@ -84,6 +84,8 @@ dsh --profile web --patch ./extra.yml --dump-config `dsh plugin --profile ` 在 profile 缺失时先初始化它(有随附模板的用模板,其他名称只装 `@deepseek-ai/dsh-base`),然后以 profile 目录为工作目录,把 `` 转发给 `pnpm`:`add`、`remove`、`why`、`update` 及其他所有 pnpm 子命令都照常可用;pnpm 必须在 PATH 上。相对路径 spec(`.`、`../plugin` 及其 `file:`/`link:` 形式)会先锚定到调用目录,因此在插件 checkout 中执行 `add .` 安装的是该 checkout,而不是 profile。每次成功运行后,系统都会根据当前安装状态更新 `dsh.profile.bundles`:如果某项依赖解析到的包在 manifest 中声明了 `"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }`,该依赖就会加入配置层栈;如果某项依赖在 `update` 后获得该声明,也会随即激活。没有组合包声明的依赖仍作为普通依赖保留,并显示一次性警告;已移除的依赖则从配置层栈中删除。 +`dsh plugin --profile enable ` 与 `disable ` 只修改 `dsh.profile.bundles`,不运行 pnpm。`enable` 在平台声明和版本兼容性检查通过后,选择安装自带的组合包(例如[可选组合包](../../../packages/util/official-bundles/README.zh.md))或 profile 已安装的组合包;`disable` 取消选择。两者都拒绝 profile 随附模板中的组合包,会先初始化缺失的 profile 并打印变更;正在运行的 profile 在重启后应用。 + `dsh plugin` 只在被转发的参数之前读取 `--profile`;被转发的参数从它无法识别的第一个 token 开始,因此 `--profile ` 必须写在最前面。被转发的参数以 pnpm 命令开头时,该命令之后的所有内容都会原样交给 pnpm,包括 `-h` 和 `--help`。被转发的参数以 `--filter ` 或 `-r` 等 pnpm 选项开头时,后面的 `-h` 或 `--help` 仍会打印转发器的帮助而不是 pnpm 的帮助,因此要查看 pnpm 的帮助,需把 pnpm 命令写在它们之前。在任何被转发的参数之前出现的 `-h` 或 `--help` 会打印转发器自身的帮助并以 0 退出。 Codex 与 Claude Code subagent 提供方是两个彼此独立的可选组合包。可以只添加一个包、在同一命令中添加两个包,或独立移除任一包: diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts index 41d4ebeaa8..a071b6635e 100644 --- a/apps/cli/src/args.ts +++ b/apps/cli/src/args.ts @@ -193,7 +193,7 @@ export function parseDshArgs(argv: readonly string[], version: string, manageDes .passThroughOptions() .requiredOption('--profile ', 'the profile whose plugins to manage (initialized on first use)', selectProfile) .allowUnknownOption() - .argument('[args...]', 'pnpm arguments, forwarded verbatim (add , remove , why , ...)') + .argument('[args...]', 'pnpm arguments, forwarded verbatim (add , remove , why , ...), or enable|disable to select an installed bundle without pnpm') .action((args: string[], options: { profile: string }) => { if (options.profile === '') program.error('error: --profile needs a name') if (!manageDesktopProfile) rejectElectronProfile(plugin, options.profile) diff --git a/apps/cli/src/plugin.ts b/apps/cli/src/plugin.ts index baad6e32f5..bf95877ab0 100644 --- a/apps/cli/src/plugin.ts +++ b/apps/cli/src/plugin.ts @@ -1,7 +1,10 @@ -/** Profile package management and explicit, exact-version compatibility approvals. */ -import { runPluginCommand, runProfilePnpm, setProfileVersionExemption, type PackageOperationOptions } from '@deepseek-ai/dsh-plugin-manager/operations' +/** Profile package management, manifest-only bundle selection, and explicit, exact-version compatibility approvals. */ +import { bundleManifest, runPluginCommand, runProfilePnpm, setProfileVersionExemption, type PackageOperationOptions } from '@deepseek-ai/dsh-plugin-manager/operations' import { INSTALL_ANCHOR } from './profile-boot.ts' -import { initProfile, readProfileCompatibility, resolveProfileDir, type ProfileContext } from '@deepseek-ai/dsh-app-boot' +import { + assertBundlePlatform, evaluatePluginCompatibility, initProfile, pluginCompatibilityWarning, readProfileCompatibility, + readProfileManifest, readProfileVersionExemptions, resolveProfileDir, writeProfileBundles, type ProfileContext, +} from '@deepseek-ai/dsh-app-boot' import { PROFILE_TEMPLATES, DEFAULT_PROFILE_BUNDLES } from '@deepseek-ai/dsh-official-bundles' import { withFileLock } from '@deepseek-ai/dsh-atomic-write' import { existsSync } from 'node:fs' @@ -62,9 +65,62 @@ async function versionCommand(profile: string, args: readonly string[]): Promise } } +/** + * Select or deselect installed bundles by editing `dsh.profile.bundles` alone, the way the Plugins page switch does; + * pnpm never runs. `enable` admits a bundle the installation ships or the profile installed after its platform and + * version checks pass; `disable` removes a selection. Bundles of the profile's shipped template are refused. + */ +async function selectionCommand(profile: string, args: readonly string[]): Promise { + const [command, ...names] = args + if (command !== 'enable' && command !== 'disable') return undefined + try { + if (names.length === 0 || names.some(name => name.startsWith('-'))) throw new Error(`usage: dsh plugin ${command} `) + const template = PROFILE_TEMPLATES[profile]?.bundles ?? DEFAULT_PROFILE_BUNDLES + const dir = resolveProfileDir(profile) + if (profile !== 'desktop') await mkdir(dir, { recursive: true }) + await withFileLock(join(dir, 'package.json'), () => { + if (profile === 'desktop') requireDesktopProfile(dir) + else if (!existsSync(join(dir, 'package.json'))) initProfile(dir, template) + const manifest = readProfileManifest('dsh', dir) + const previous = manifest.dsh?.profile?.bundles ?? [] + const bundles = [...previous] + for (const name of names) { + if (template.includes(name)) throw new Error(`${name} is a bundle of the ${profile} profile template and cannot be ${command}d`) + if (command === 'disable') { + const index = bundles.indexOf(name) + if (index >= 0) bundles.splice(index, 1) + continue + } + let metadata: ReturnType + try { + metadata = bundleManifest(name, dir, INSTALL_ANCHOR) + } catch (error) { + throw new Error(`${name} is not installed: run 'dsh plugin --profile ${profile} add ${name}', or enable a bundle this installation ships`, { cause: error }) + } + if (metadata === undefined) throw new Error(`${name} declares no dsh.bundle; only bundles can be enabled`) + assertBundlePlatform(metadata.dsh?.bundle?.platforms, process.platform) + const issue = evaluatePluginCompatibility(metadata, readProfileVersionExemptions(dir)) + if (issue !== undefined && !issue.exempted) throw new Error(pluginCompatibilityWarning(issue)) + if (!bundles.includes(name)) bundles.push(name) + } + if (JSON.stringify(bundles) === JSON.stringify(previous)) { + process.stdout.write(`dsh: profile ${profile} already has ${names.join(', ')} ${command}d\n`) + return Promise.resolve() + } + writeProfileBundles(dir, manifest, bundles) + process.stdout.write(`dsh: ${command}d ${names.join(', ')} in profile ${profile}; restart the profile to apply\n`) + return Promise.resolve() + }, { waitMs: 120000 }) + return 0 + } catch (error) { + process.stderr.write(`dsh: ${String(error)}\n`) + return 1 + } +} + /** Run package management for a profile. * @param profile Profile name; Desktop's reserved profile must already be initialized by the application. - * @param args DSH exemption command or pnpm arguments relative to the invoking directory. + * @param args DSH exemption or bundle selection command, or pnpm arguments relative to the invoking directory. * @param packageManager Installation-owned executable and environment for pnpm operations. * @returns Zero on success; nonzero on invalid approval or package-manager failure. */ @@ -77,6 +133,8 @@ export async function runPlugin(profile: string, args: readonly string[], packag } const versionResult = await versionCommand(profile, args) if (versionResult !== undefined) return versionResult + const selectionResult = await selectionCommand(profile, args) + if (selectionResult !== undefined) return selectionResult const dir = resolveProfileDir(profile) if (existsSync(join(dir, 'package.json'))) { for (const warning of readProfileCompatibility(dir).warnings) process.stderr.write(`dsh: warning: ${warning}\n`) diff --git a/apps/cli/tests/plugin.spec.ts b/apps/cli/tests/plugin.spec.ts index 9185315cb1..94f23b88ed 100644 --- a/apps/cli/tests/plugin.spec.ts +++ b/apps/cli/tests/plugin.spec.ts @@ -1,5 +1,5 @@ /** Explicit CLI exemptions use the profile lock and never become pnpm arguments. */ -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it, onTestFinished, vi } from 'vitest' @@ -176,3 +176,56 @@ it('applies version approvals to the existing Desktop profile without replacing expect(runPluginCommand).not.toHaveBeenCalled() expect(runProfilePnpm).not.toHaveBeenCalled() }) + +/** An installed package the profile can select: a bundle, or a plain dependency without a patch. */ +function installPackage(dir: string, name: string, manifest: Record): void { + const packageDir = join(dir, 'node_modules', ...name.split('/')) + mkdirSync(packageDir, { recursive: true }) + writeFileSync(join(packageDir, 'package.json'), JSON.stringify({ name, version: '1.0.0', ...manifest })) + writeFileSync(join(packageDir, 'cordis.patch.yml'), '[]\n') +} + +function bundlesOf(dir: string): string[] { + return (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }).dsh.profile.bundles +} + +it('enables and disables an installed bundle by editing the manifest without pnpm', async () => { + const { dir, stdout } = fixture() + initProfile(dir, PROFILE_TEMPLATES.web!.bundles) + installPackage(dir, '@example/bundle', { dsh: { bundle: { patch: './cordis.patch.yml' } } }) + expect(await runPlugin('test', ['enable', '@example/bundle'])).toBe(0) + expect(bundlesOf(dir)).toEqual([...PROFILE_TEMPLATES.web!.bundles, '@example/bundle']) + expect(stdout).toHaveBeenLastCalledWith('dsh: enabled @example/bundle in profile test; restart the profile to apply\n') + expect(await runPlugin('test', ['enable', '@example/bundle'])).toBe(0) + expect(stdout).toHaveBeenLastCalledWith('dsh: profile test already has @example/bundle enabled\n') + expect(await runPlugin('test', ['disable', '@example/bundle'])).toBe(0) + expect(bundlesOf(dir)).toEqual(PROFILE_TEMPLATES.web!.bundles) + expect(runPluginCommand).not.toHaveBeenCalled() +}) + +it('initializes a missing profile from the default bundles before enabling', async () => { + const { dir } = fixture() + mkdirSync(join(dir, 'node_modules'), { recursive: true }) + installPackage(dir, '@example/bundle', { dsh: { bundle: { patch: './cordis.patch.yml' } } }) + expect(await runPlugin('test', ['enable', '@example/bundle'])).toBe(0) + expect(bundlesOf(dir)).toEqual(['@deepseek-ai/dsh-base', '@example/bundle']) +}) + +it.each([ + { args: ['enable'], message: 'usage: dsh plugin enable ' }, + { args: ['enable', '@example/absent'], message: "@example/absent is not installed: run 'dsh plugin --profile test add @example/absent'" }, + { args: ['enable', '@example/plain'], message: '@example/plain declares no dsh.bundle' }, + { args: ['enable', '@example/elsewhere'], message: `Bundle supports Host platforms ${process.platform === 'aix' ? 'sunos' : 'aix'}` }, + { args: ['enable', '@example/old'], message: 'is incompatible with dsh' }, + { args: ['disable', '@deepseek-ai/dsh-base'], message: 'bundle of the test profile template and cannot be disabled' }, +])('refuses $args without changing the selection', async ({ args, message }) => { + const { dir, stderr } = fixture() + initProfile(dir, PROFILE_TEMPLATES.web!.bundles) + installPackage(dir, '@example/plain', {}) + installPackage(dir, '@example/elsewhere', { dsh: { bundle: { patch: './cordis.patch.yml', platforms: [process.platform === 'aix' ? 'sunos' : 'aix'] } } }) + installPackage(dir, '@example/old', { dsh: { bundle: { patch: './cordis.patch.yml' } }, engines: { dsh: '^0.0.1' } }) + expect(await runPlugin('test', args)).toBe(1) + expect(stderr.mock.calls.map(call => call[0]).join('')).toContain(message) + expect(bundlesOf(dir)).toEqual(PROFILE_TEMPLATES.web!.bundles) + expect(runPluginCommand).not.toHaveBeenCalled() +}) diff --git a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts new file mode 100644 index 0000000000..5c35518c86 --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts @@ -0,0 +1,105 @@ +/** The shipped cua-mcp bundle: enabled through the real CLI, serving Computer Use programs over stdio to an MCP client. */ +import { execFile } from 'node:child_process' +import { existsSync } from 'node:fs' +import { mkdtemp, readFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' +import { promisify } from 'node:util' +import { describe, expect, it, onTestFinished } from 'vitest' +import { clearAmbientProxyEnv } from '../../../../../scripts/test-proxy-environment.ts' +import { startProbe, type McpProbe } from './probe.ts' + +const root = fileURLToPath(new URL('../../../../../', import.meta.url)) +const bin = join(root, 'apps/cli/lib/bin.js') +const fixturePatch = fileURLToPath(new URL('./fixture.patch.yml', import.meta.url)) +const execFileAsync = promisify(execFile) + +interface CallResult { + content: Array<{ type: 'text'; text: string } | { type: 'image'; data: string; mimeType: string }> + isError?: boolean +} + +function textOf(block: CallResult['content'][number] | undefined): string { + if (block?.type !== 'text') throw new Error(`expected a text block, got ${JSON.stringify(block)}`) + return block.text +} + +describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => { + it('enables the shipped bundle, prints client configuration, serves programs over stdio, and exits on EOF', async () => { + const temporary = await mkdtemp(join(tmpdir(), 'dsh-cua-mcp-profile-')) + const home = join(temporary, 'home') + const workspace = join(temporary, 'workspace') + const owned: { probe?: McpProbe } = {} + onTestFinished(async () => { + try { await owned.probe?.terminate() } finally { await rm(temporary, { recursive: true, force: true }) } + }) + const env: NodeJS.ProcessEnv = { + ...process.env, DSH_HOME: home, DSH_TELEMETRY_DISABLED: '1', DSH_PERMISSION_MODE: 'danger-full-access', DSH_CUA_CONSENT: 'allow', + } + clearAmbientProxyEnv(env) + await execFileAsync(process.execPath, ['-e', 'require("node:fs").mkdirSync(process.argv[1], { recursive: true })', workspace]) + const options = { cwd: workspace, env, timeout: 120_000, maxBuffer: 4_000_000 } + + // One command selects the installation-owned bundle without pnpm or network access. + const enabled = await execFileAsync(process.execPath, [bin, 'plugin', '--profile', 'cua-mcp', 'enable', '@deepseek-ai/dsh-cua-mcp'], options) + expect(enabled.stdout).toBe('dsh: enabled @deepseek-ai/dsh-cua-mcp in profile cua-mcp; restart the profile to apply\n') + const manifest = JSON.parse(await readFile(join(home, 'profiles', 'cua-mcp', 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } } + expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-cua-mcp']) + + const printed = await execFileAsync(process.execPath, [bin, '--profile', 'cua-mcp', '--print-client-config', 'codex'], options) + const normalized = printed.stdout + .split(JSON.stringify(process.execPath).slice(1, -1)).join('{{node}}') + .split(JSON.stringify(bin).slice(1, -1)).join('{{bin}}') + .split(JSON.stringify(home).slice(1, -1)).join('{{home}}') + await expect(normalized).toMatchFileSnapshot('./expected/codex.toml') + + const probe = owned.probe = startProbe({ args: [bin, '--profile', 'cua-mcp', '--patch', fixturePatch], cwd: workspace, env }) + const initialized = await probe.request('initialize', { + protocolVersion: '2025-06-18', capabilities: {}, clientInfo: { name: 'cua-mcp-e2e', version: '1' }, + }) as { serverInfo: { name: string; version: string }; instructions: string; capabilities: object } + probe.notify('notifications/initialized') + expect(initialized.serverInfo.name).toBe('dsh_cua') + expect(initialized.capabilities).toMatchObject({ tools: { listChanged: false } }) + await expect(`${initialized.instructions}\n`).toMatchFileSnapshot('./expected/instructions.txt') + const listed = await probe.request('tools/list') as { tools: { name: string }[] } + await expect(`${JSON.stringify(listed.tools, null, 2)}\n`).toMatchFileSnapshot('./expected/tools.json') + + const first = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: 'globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); ' + + 'await win.click("0"); await win.getScreenshot(); ({ visits, window: win.windowId, pid: process.pid })', + } }) as CallResult + expect(first.isError).toBeUndefined() + expect(first.content.map(block => block.type)).toEqual(['text', 'text', 'text', 'image']) + await expect(`${textOf(first.content[0])}\n`).toMatchFileSnapshot('./expected/reference.md') + const state = JSON.parse(textOf(first.content[1])) as { visits: number; window: number; pid: number } + expect(state).toMatchObject({ visits: 1, window: 7 }) + expect(JSON.parse(textOf(first.content[2]))).toMatchObject({ windowId: 7, coordinateSpace: 'screenshot-pixels', pixelWidth: 1, pixelHeight: 1 }) + const image = first.content[3] + if (image?.type !== 'image') throw new Error('expected an image block') + expect(image.mimeType).toMatch(/^image\//) + expect(Buffer.from(image.data, 'base64').length).toBeGreaterThan(0) + + const second = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: 'globalThis.visits++; ({ visits, sameWindow: win.windowId === 7, pid: process.pid })', description: 'Count another visit', + } }) as CallResult + expect(second.content).toHaveLength(1) + expect(JSON.parse(textOf(second.content[0]))).toEqual({ visits: 2, sameWindow: true, pid: state.pid }) + + const reset = await probe.request('tools/call', { name: 'cua_reset', arguments: {} }) as CallResult + expect(reset.isError).toBeUndefined() + expect(textOf(reset.content[0])).toContain('Program environment cleared') + const third = await probe.request('tools/call', { name: 'cua_run_code', arguments: { + code: '({ visits: globalThis.visits ?? null, hasWindow: typeof win !== "undefined", pid: process.pid })', + } }) as CallResult + expect(third.content).toHaveLength(2) + expect(textOf(third.content[0])).toContain('## cua API reference') + const afterReset = JSON.parse(textOf(third.content[1])) as { visits: null; hasWindow: boolean; pid: number } + expect(afterReset).toMatchObject({ visits: null, hasWindow: false }) + expect(afterReset.pid).not.toBe(state.pid) + + expect(await probe.close()).toEqual({ code: 0, signal: null }) + expect(probe.stderr()).not.toContain('MCP startup failed') + expect(() => process.kill(afterReset.pid, 0)).toThrow() + }) +}) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/codex.toml b/apps/cli/tests/profiles/cua-mcp/expected/codex.toml new file mode 100644 index 0000000000..3776d31179 --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/expected/codex.toml @@ -0,0 +1,13 @@ +# ~/.codex/config.toml — run once first: dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp +[mcp_servers.dsh_cua] +command = "{{node}}" +args = ["{{bin}}", "--profile", "cua-mcp"] +env = { DSH_HOME = "{{home}}", DSH_CUA_CONSENT = "allow" } +startup_timeout_sec = 120 +tool_timeout_sec = 600 +enabled_tools = ["cua_run_code", "cua_reset"] +omit_tools_from = ["code_mode", "deferred"] +# default_tools_approval_mode = "auto" + +[mcp_servers.dsh_cua.tools.cua_run_code] +output_token_limit = 25000 diff --git a/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt new file mode 100644 index 0000000000..61e473ca24 --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/expected/instructions.txt @@ -0,0 +1 @@ +DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. The first result includes the complete cua API reference; read it before planning further calls. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state. diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md new file mode 100644 index 0000000000..5e9de80508 --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -0,0 +1,54 @@ +## cua_run_code execution rules + +Run a TypeScript program to observe and operate desktop applications. The global cua object is ready to use; retain application and window objects across calls. Only tools.cua is available inside the program. Call other session tools directly. Print the values you need or leave a final expression; screenshots are attached after the program finishes. The program contains TypeScript REPL statements; only erasable syntax is accepted, with no enum or namespaces. Type annotations are advisory. Top-level declarations and await are supported; top-level return is not supported. Emit output with console.log(...) or a final lossless JSON expression. Only printed values and that final expression become program output. Variables, functions, and imported modules remain in memory for this Agent across calls. Use await import(...) for modules. Direct filesystem access follows the environment's launch-time sandbox policy; process.env starts empty. Timeout and cancellation results say whether retained variables were preserved or cleared. Restart, sandbox changes, output overflow, or process failure clears them. Recreate missing variables and resources; conversation history does not restore state. Earlier mutations and tool effects are not rolled back. Approved sandbox escalations use a fresh environment and discard its variables afterward. Do not redeclare existing let, const, or class names; reuse mutable bindings or choose new names. Await tools and cleanup before returning; unfinished tools reject. After completion, timeout, or cancellation, new tool calls are rejected and captured output is discarded; background work may still change state. Await child-process completion before returning; raw output belongs to the active evaluation. Each program starts in the Session's current directory. Running programs keep their initial directory. A sandbox escalation approves this complete program for one execution only. Nested tools retain their own policies and approvals. Request wider access only after evidence of a denial. Earlier effects may already have completed: inspect them before explicitly retrying. Programs are never replayed automatically. + +## cua API reference + +Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. + +Use void await for observations that emit, and never stringify screenshot image bytes. + +Signatures show resolved return values after await. ActionResult = { dispatched: boolean, foregroundChanged?: boolean | null }; foregroundChanged is omitted when not sampled and null when the sample is unavailable. JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue }; numbers must be finite. App is the application object with readonly app.appHandle: string (opaque) and the methods listed below for app level. Window is the window object with readonly window.windowId: number and the methods listed below for window level. Neither object carries pid. + +Setup and discovery: +- cua.getCapabilities(options?: { emit?: boolean }) -> { platform: string, permissions: { accessibility: boolean, screenRecording: boolean }, appLevelAccessibility: boolean, systemPointer: boolean, keyboard: ('app' | 'window')[], sessionLocked: boolean | null, methods: string[], coordinateSpace: 'screenshot-pixels', browser: false } — inspect reported permissions, sessionLocked, methods, and keyboard scopes without requesting permissions. +- cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. +- cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. +- cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. +- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. +- app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. +- window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. + +## Accessibility tree +Available at app or window level depending on the platform. + +Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +- listActions(elementId: string) -> string[] — list the actions an element advertises. +- invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. +- performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. +- setValue(elementId: string, value: JsonValue) -> ActionResult — write a control value. +- selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. + +## Simulated mouse +Use an explicit window for screenshots and pointer input. +- getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. +- mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. +- click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. +- scroll(options: { x: number, y: number, deltaLinesX: number, deltaLinesY: number, relative?: boolean }) -> ActionResult — scroll at a point; deltas are integers from -10 to 10 with at least one nonzero, and positive values reveal content above or left. +- drag(from: [number, number], to: [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], relative?: boolean }) -> ActionResult — drag between two points of one window. + +A string target is an element id; coordinate targets are [x, y] and are pixels in the latest returned screenshot by default. With relative: true they are integer thousandths of the window width and height from 0 to 999, based on the current AX observation or screenshot. Left clicks support one or two presses; right and middle clicks support one. FOREGROUND_REQUIRED means explain the need, then explicitly activate the target and observe again; activation is never automatic. Read fresh state after actions, and treat WINDOW_CHANGED, STALE_SNAPSHOT, and SCREENSHOT_REQUIRED as requiring the stated fresh observation or capture before any retry. + +## Simulated keyboard +Available at app or window level depending on the platform. +- typeText(text: string) -> ActionResult — type literal text at the app's current focus; line endings send Return and tabs send Tab. +- paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. +- pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. + +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. + +Maximum click holdMs: 5000 ms. diff --git a/apps/cli/tests/profiles/cua-mcp/expected/tools.json b/apps/cli/tests/profiles/cua-mcp/expected/tools.json new file mode 100644 index 0000000000..e52d049260 --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/expected/tools.json @@ -0,0 +1,54 @@ +[ + { + "name": "cua_run_code", + "title": "Computer use program", + "description": "Run a TypeScript program that observes and operates desktop applications through the global `cua` object: select an application, read its accessibility tree, capture window screenshots, click, and type. The program is a sequence of TypeScript REPL statements: top-level `await` works, top-level `return` does not. Only `console.log(...)` output and the value of the final expression come back, followed by every screenshot the program captured as an image. Variables, imported modules, and application or window objects stay in memory for this connection across calls until cua_reset. The first result of a connection starts with the complete `cua` API reference.", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": { + "code": { + "type": "string", + "minLength": 1, + "description": "TypeScript REPL statements that use the global cua object; the final expression is returned." + }, + "description": { + "description": "Short label of what the program does; omitted records \"CUA program\".", + "type": "string", + "minLength": 1 + }, + "timeoutMs": { + "description": "Elapsed-time budget in milliseconds for this program, including nested cua calls; omitted uses the profile default.", + "type": "integer", + "exclusiveMinimum": 0, + "maximum": 9007199254740991 + } + }, + "required": [ + "code" + ] + }, + "annotations": { + "readOnlyHint": false, + "destructiveHint": true, + "idempotentHint": false, + "openWorldHint": true + } + }, + { + "name": "cua_reset", + "title": "Reset computer use program state", + "description": "Discard the program environment of this connection: every variable, import, and application or window object held by earlier cua_run_code calls. Application access grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment and its result repeats the `cua` API reference. Use it when a declaration conflicts with an earlier call or the environment has become unusable.", + "inputSchema": { + "type": "object", + "$schema": "https://json-schema.org/draft/2020-12/schema", + "properties": {} + }, + "annotations": { + "readOnlyHint": false, + "destructiveHint": false, + "idempotentHint": true, + "openWorldHint": false + } + } +] diff --git a/apps/cli/tests/profiles/cua-mcp/fixture.patch.yml b/apps/cli/tests/profiles/cua-mcp/fixture.patch.yml new file mode 100644 index 0000000000..ffbc61919b --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/fixture.patch.yml @@ -0,0 +1,15 @@ +# Replace the macOS provider with the recorded desktop fixture so the profile serves on every Host. +- id: cua-mcp-provider + disabled: true + +- insert: + - id: cua-mcp-fixture-provider + name: '../../../../../snapshots/session/cua-run-code/provider.mjs' + config: + screenshotTarget: + longEdge: 1 + maxBytes: 100000 + allowedApps: + - id: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa + name: Fixture + executablePath: /fixture/app diff --git a/apps/cli/tests/profiles/cua-mcp/probe.ts b/apps/cli/tests/profiles/cua-mcp/probe.ts new file mode 100644 index 0000000000..9ab4a2e7b7 --- /dev/null +++ b/apps/cli/tests/profiles/cua-mcp/probe.ts @@ -0,0 +1,102 @@ +/** Raw JSON-RPC probe over the profile's stdio: every stdout line must be a protocol frame. */ +import { spawn } from 'node:child_process' +import { createInterface } from 'node:readline' + +/** One observed child exit; a graceful EOF exit carries code zero and no signal. */ +export interface ProbeExit { + readonly code: number | null + readonly signal: NodeJS.Signals | null +} + +/** Test-side requests and explicit process ownership. */ +export interface McpProbe { + /** + * @param method - JSON-RPC method. + * @param params - JSON params. + * @returns The matching result; a protocol error or a non-protocol stdout line rejects pending and later requests. + */ + request(method: string, params?: object): Promise + /** @param method - Notification method. @param params - JSON params. */ + notify(method: string, params?: object): void + /** @returns Captured stderr, which the protocol never uses. */ + stderr(): string + /** @returns The exit observed after stdin EOF. */ + close(): Promise + /** Stop a failed fixture and await its exit. */ + terminate(): Promise +} + +/** + * Start the built CLI with the given arguments and hold its stdio. + * @param options - Executable arguments, working directory, and environment. + * @returns The probe; `terminate` must run even after a failed assertion. + */ +export function startProbe(options: { readonly args: readonly string[]; readonly cwd: string; readonly env: NodeJS.ProcessEnv }): McpProbe { + const child = spawn(process.execPath, [...options.args], { cwd: options.cwd, env: options.env, stdio: 'pipe' }) + let stderr = '' + child.stderr.on('data', (chunk: Buffer) => { stderr += chunk.toString('utf8') }) + let nextId = 0 + let ended = false + let failure: Error | undefined + const pending = new Map() + const fail = (error: Error): void => { + failure ??= error + for (const request of pending.values()) request.reject(error) + pending.clear() + } + child.on('error', fail) + child.stdin.on('error', fail) + const closed = new Promise((resolve) => { + child.once('close', (code, signal) => { + ended = true + fail(new Error(`cua-mcp exited before replying (${String(code)}, ${String(signal)}): ${stderr}`)) + resolve({ code, signal }) + }) + }) + const reading = (async () => { + for await (const line of createInterface({ input: child.stdout })) { + let parsed: unknown + try { parsed = JSON.parse(line) } catch { parsed = undefined } + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed) || Reflect.get(parsed, 'jsonrpc') !== '2.0') { + throw new Error(`cua-mcp wrote a non-protocol line to stdout: ${line}`) + } + const frame = parsed as { id?: number; method?: string; result?: unknown; error?: unknown } + if (frame.id === undefined) continue + const request = pending.get(frame.id) + if (request === undefined) throw new Error(`cua-mcp replied to an unknown request ${String(frame.id)}`) + pending.delete(frame.id) + if (frame.error === undefined) request.resolve(frame.result) + else request.reject(new Error(`MCP request failed: ${JSON.stringify(frame.error)}`)) + } + })().catch((error: unknown) => { fail(error instanceof Error ? error : new Error(String(error))) }) + const write = (message: object): void => { child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', ...message })}\n`) } + return { + async request(method, params) { + if (failure !== undefined) throw failure + if (ended) throw new Error('cua-mcp is closed') + const id = ++nextId + const response = Promise.withResolvers() + const timer = setTimeout(() => { + pending.delete(id) + response.reject(new Error(`MCP ${method} did not reply: ${stderr}`)) + }, 90_000) + pending.set(id, { resolve: response.resolve, reject: response.reject }) + write({ id, method, ...params === undefined ? {} : { params } }) + try { return await response.promise } finally { clearTimeout(timer) } + }, + notify(method, params) { write({ method, ...params === undefined ? {} : { params } }) }, + stderr: () => stderr, + async close() { + child.stdin.end() + const exit = await closed + await reading + if (failure !== undefined && !failure.message.startsWith('cua-mcp exited before replying')) throw failure + return exit + }, + async terminate() { + if (!ended) child.kill('SIGKILL') + await closed + await reading + }, + } +} diff --git a/docs/capability-seams.i18n.yaml b/docs/capability-seams.i18n.yaml index 77f025f1e9..e235ed558b 100644 --- a/docs/capability-seams.i18n.yaml +++ b/docs/capability-seams.i18n.yaml @@ -6,5 +6,5 @@ en: 41d772192075e133 zh: 5ef3da69b4de1d8a /capability-seams-and-core-services: - en: b76743a3ff14d2f4 - zh: 82431aa3ded14a89 + en: 9a77574304af688a + zh: ff95e816c5e5a76a diff --git a/docs/capability-seams.md b/docs/capability-seams.md index 145a4f5317..a7ad2f3fd1 100644 --- a/docs/capability-seams.md +++ b/docs/capability-seams.md @@ -68,6 +68,8 @@ flowchart LR pkg_experimental_computer_use_cua_driver_native["experimental-computer-use-cua-driver-native"] pkg_cua["cua"] svc_cuaAccess["ctx.cuaAccess
Computer Use permission controls"] + svc_cuaPrograms["ctx.cuaPrograms
Computer Use program environments"] + pkg_cua_mcp["cua-mcp"] pkg_office_kit["office-kit"] svc_officeKit["ctx.officeKit
Office rendering, conversion, and recalculation"] pkg_client_ui_sidebar_documentpreview["client-ui-sidebar-documentpreview"] @@ -357,6 +359,7 @@ flowchart LR pkg_credentials --> svc_credentials pkg_credentials_local --> svc_credentials pkg_cua --> svc_cuaAccess + pkg_cua --> svc_cuaPrograms pkg_deepseek_account --> svc_deepseekAccount pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions pkg_experimental_api_speech_to_text --> svc_speechController @@ -515,6 +518,7 @@ flowchart LR svc_credentials --> pkg_llm_deepseek svc_credentials --> pkg_llm_pi_ai svc_cuaAccess --> pkg_cua + svc_cuaPrograms --> pkg_cua_mcp svc_deepseekAccount --> pkg_llm_deepseek svc_deepseekLlmApiExtensions --> pkg_llm_deepseek svc_directoryPicker --> pkg_api_workspace_controller @@ -671,6 +675,7 @@ flowchart LR | `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | One provider-owned name per service instance. Providers own their tools and browser resources per live Session; the shared service has no browser operation API. | | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | One provider-owned name per service instance. Each provider also owns its model tools; the service has no common action API, runtime selection, or Session workflow lock. | | `ctx.cuaAccess` | `core` | [`cua`](../packages/experimental/cua) | - | [`cua`](../packages/experimental/cua) | - | The native provider owns application consent and cancellation; the optional Client page queries and changes those decisions through its Remote. | +| `ctx.cuaPrograms` | `core` | [`cua`](../packages/experimental/cua) | - | [`cua-mcp`](../packages/experimental/cua-mcp) | - | The provider owns the retained cua_run_code runtime; a host without a model resets one Agent environment and reads the configured screenshot request target through it. | | `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-office`](../packages/document/tool-office) | - | Authorized Office bytes are rendered as PDFs or images, converted, or recalculated on the Host using the declared native target engine, or Node WASM when no native target is declared. | | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | The host commits accepted images before session events; provider adapters resolve authorized durable references into provider-native content. | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | Owns streaming intake, durable storage, and staged receipt lifetime; the Session controller binds receipts to accepted submissions. | diff --git a/docs/capability-seams.zh.md b/docs/capability-seams.zh.md index 5effa1f8c4..8385014c14 100644 --- a/docs/capability-seams.zh.md +++ b/docs/capability-seams.zh.md @@ -70,6 +70,8 @@ flowchart LR pkg_experimental_computer_use_cua_driver_native["experimental-computer-use-cua-driver-native"] pkg_cua["cua"] svc_cuaAccess["ctx.cuaAccess
Computer Use permission controls"] + svc_cuaPrograms["ctx.cuaPrograms
Computer Use program environments"] + pkg_cua_mcp["cua-mcp"] pkg_office_kit["office-kit"] svc_officeKit["ctx.officeKit
Office rendering, conversion, and recalculation"] pkg_client_ui_sidebar_documentpreview["client-ui-sidebar-documentpreview"] @@ -359,6 +361,7 @@ flowchart LR pkg_credentials --> svc_credentials pkg_credentials_local --> svc_credentials pkg_cua --> svc_cuaAccess + pkg_cua --> svc_cuaPrograms pkg_deepseek_account --> svc_deepseekAccount pkg_deepseek_llm_api_extensions --> svc_deepseekLlmApiExtensions pkg_experimental_api_speech_to_text --> svc_speechController @@ -517,6 +520,7 @@ flowchart LR svc_credentials --> pkg_llm_deepseek svc_credentials --> pkg_llm_pi_ai svc_cuaAccess --> pkg_cua + svc_cuaPrograms --> pkg_cua_mcp svc_deepseekAccount --> pkg_llm_deepseek svc_deepseekLlmApiExtensions --> pkg_llm_deepseek svc_directoryPicker --> pkg_api_workspace_controller @@ -673,6 +677,7 @@ flowchart LR | `ctx.browserUse` | `seam` | [`browser-use`](../packages/browser-use/browser-use) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp), [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp), [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | - | 每个服务实例注册一个提供方拥有的名称。提供方按实时 Session 拥有自己的工具与浏览器资源;共享服务不提供浏览器操作 API。 | | `ctx.computerUse` | `seam` | [`computer-use`](../packages/computer-use/computer-use) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp), [`experimental-computer-use-cua-driver-native`](../packages/experimental/computer-use-cua-driver-native) | - | 每个服务实例只注册一个提供方自定的名称。各提供方也拥有自己的模型工具;服务不提供通用操作 API、运行时选择或 Session 流程锁。 | | `ctx.cuaAccess` | `core` | [`cua`](../packages/experimental/cua) | - | [`cua`](../packages/experimental/cua) | - | 原生 provider 负责应用授权和取消操作;可选的 Client 权限页面通过 Remote 查询和修改授权。 | +| `ctx.cuaPrograms` | `core` | [`cua`](../packages/experimental/cua) | - | [`cua-mcp`](../packages/experimental/cua-mcp) | - | 提供方持有保留的 cua_run_code 运行时;没有模型的宿主通过它重置单个 Agent 的环境,并读取已配置的截图请求目标。 | | `ctx.officeKit` | `core` | [`office-kit`](../packages/document/office-kit) | - | [`client-ui-sidebar-documentpreview`](../packages/client/ui-sidebar-documentpreview), [`tool-office`](../packages/document/tool-office) | - | 已授权的 Office 字节在宿主上使用已声明的原生目标引擎渲染为 PDF 或图片、转换或重算;未声明原生目标时使用 Node WASM。 | | `ctx.attachments` | `seam` | [`attachment`](../packages/attachment/attachment) | [`attachment-local`](../packages/attachment/attachment-local) | [`api-session-controller`](../packages/api/session-controller), [`tool-fs`](../packages/fs/tool-fs), [`llm-pi-ai`](../packages/llm/llm-pi-ai), [`llm-deepseek`](../packages/llm/llm-deepseek) | - | 宿主会在会话事件之前提交已接受的图片;提供方适配器将已授权的持久引用解析为提供方原生内容。 | | `ctx.fileUploads` | `core` | [`client-file-upload`](../packages/client/file-upload) | - | [`api-session-controller`](../packages/api/session-controller) | - | 负责流式接收、持久存储和暂存回执生命周期;Session Controller 将回执绑定到已接受的提交。 | diff --git a/docs/cli-help.md b/docs/cli-help.md index 1cbc117945..7e8ba84f25 100644 --- a/docs/cli-help.md +++ b/docs/cli-help.md @@ -71,7 +71,8 @@ profile directory Arguments: args pnpm arguments, forwarded verbatim (add , remove , - why , ...) + why , ...), or enable|disable to select an + installed bundle without pnpm Options: --profile the profile whose plugins to manage (initialized on first diff --git a/docs/cli-help.zh.md b/docs/cli-help.zh.md index c682e26067..0ac9a88185 100644 --- a/docs/cli-help.zh.md +++ b/docs/cli-help.zh.md @@ -73,7 +73,8 @@ profile directory Arguments: args pnpm arguments, forwarded verbatim (add , remove , - why , ...) + why , ...), or enable|disable to select an + installed bundle without pnpm Options: --profile the profile whose plugins to manage (initialized on first diff --git a/docs/config-catalog.md b/docs/config-catalog.md index 19b1bb2f25..cb0f555c07 100644 --- a/docs/config-catalog.md +++ b/docs/config-catalog.md @@ -886,6 +886,29 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-cua-mcp` + +- `inject`: `cmdlineArgs` · `appReady` · `appExit` · `profileContext` · `agents` · `agentPresets` · `tools` · `systemPrompt` · `attachments` +- `source`: [`packages/experimental/cua-mcp/src/index.ts:24`](../packages/experimental/cua-mcp/src/index.ts) + +```ts config-catalog +/** Connection policy configurable from the profile patch. */ +export interface Config { + /** + * Who grants application and pointer consent for the connection's Agent: `allow` grants every request for + * this session without a human; `elicit` forwards each request to the MCP client as a form elicitation. + */ + consent: ConsentMode +} + +/** Who decides application and pointer consent for the connection's Agent. */ +export type ConsentMode = 'allow' | 'elicit' +``` + + diff --git a/docs/config-catalog.zh.md b/docs/config-catalog.zh.md index 833ddbce39..ada43b6512 100644 --- a/docs/config-catalog.zh.md +++ b/docs/config-catalog.zh.md @@ -888,6 +888,29 @@ export interface Config { ``` + + + +## `@deepseek-ai/dsh-cua-mcp` + +- `inject`: `cmdlineArgs` · `appReady` · `appExit` · `profileContext` · `agents` · `agentPresets` · `tools` · `systemPrompt` · `attachments` +- `source`: [`packages/experimental/cua-mcp/src/index.ts:24`](../packages/experimental/cua-mcp/src/index.ts) + +```ts config-catalog +/** Connection policy configurable from the profile patch. */ +export interface Config { + /** + * Who grants application and pointer consent for the connection's Agent: `allow` grants every request for + * this session without a human; `elicit` forwards each request to the MCP client as a form elicitation. + */ + consent: ConsentMode +} + +/** Who decides application and pointer consent for the connection's Agent. */ +export type ConsentMode = 'allow' | 'elicit' +``` + + diff --git a/docs/event-producer-consumer.md b/docs/event-producer-consumer.md index cb4129be82..1681b57d8f 100644 --- a/docs/event-producer-consumer.md +++ b/docs/event-producer-consumer.md @@ -89,7 +89,7 @@ Application listeners are outside this package matrix. Desktop Host subscribes t | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | | `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | -| `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes`, `server` | +| `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | [`cua-mcp`](../packages/experimental/cua-mcp), `remotes`, `server` | | `web/providers-changed` | `emit` | [`packages/web/web/src/types.ts:21`](../packages/web/web/src/types.ts) | [`web`](../packages/web/web) (`events.dispatch`) | `remotes` | | `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:44`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | diff --git a/docs/event-producer-consumer.zh.md b/docs/event-producer-consumer.zh.md index f367889fa4..121ac976e7 100644 --- a/docs/event-producer-consumer.zh.md +++ b/docs/event-producer-consumer.zh.md @@ -91,7 +91,7 @@ | `tools/pre-execute` | `waterfall` | [`packages/core/tools/src/events.ts:18`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`waterfall`) | `auto-review`, [`hooks-claude-code`](../packages/experimental/hooks-claude-code), [`hooks-codex`](../packages/experimental/hooks-codex), `liveshare`, [`tool-jobs`](../packages/jobs/tool-jobs), [`workspace-changes`](../packages/deliverables/workspace-changes) | | `tools/ptc-dispatch-log` | `waterfall` | [`packages/core/tool-executor-ptc/src/runtime-types.ts:46`](../packages/core/tool-executor-ptc/src/runtime-types.ts) | [`tool-executor-ptc`](../packages/core/tool-executor-ptc) (`waterfall`) | [`spill-policy`](../packages/spill/spill-policy) | | `tools/result` | `emit` | [`packages/core/tools/src/events.ts:49`](../packages/core/tools/src/events.ts) | [`tools`](../packages/core/tools) (`events.dispatch`) | [`action-cards`](../packages/experimental/action-cards), [`agent-instructions`](../packages/context/agent-instructions), `claude-code-mods`, `forge-session`, `liveshare`, [`subagent`](../packages/subagent/subagent), [`tool-office`](../packages/document/tool-office), [`tool-present`](../packages/deliverables/tool-present), `ui-trajectory` | -| `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | `remotes`, `server` | +| `user-questions/request` | `waterfall` | [`packages/interaction/user-questions/src/types.ts:174`](../packages/interaction/user-questions/src/types.ts) | [`user-questions`](../packages/interaction/user-questions) (`waterfall`) | [`cua-mcp`](../packages/experimental/cua-mcp), `remotes`, `server` | | `web/providers-changed` | `emit` | [`packages/web/web/src/types.ts:21`](../packages/web/web/src/types.ts) | [`web`](../packages/web/web) (`events.dispatch`) | `remotes` | | `webserver/index-inject` | `emit` | [`packages/host/webserver/src/index.ts:44`](../packages/host/webserver/src/index.ts) | `webserver` (`emit`) | `connection`, `inspector`, `modules`, `remote-access`, `shortcuts`, `ui-sidebar-documentpreview`, `ui-theme` | | `workflow/agent-end` | `emit` | [`packages/workflow/workflow/src/index.ts:79`](../packages/workflow/workflow/src/index.ts) | [`workflow`](../packages/workflow/workflow) (`events.dispatch`) | [`tool-workflow`](../packages/workflow/tool-workflow) | diff --git a/docs/module-graph.md b/docs/module-graph.md index 7b28621265..deec4e10fb 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -264,6 +264,7 @@ flowchart TD pkg_creation_recommendations["creation-recommendations"] pkg_cua["cua"] pkg_cua_bundle["cua-bundle"] + pkg_cua_mcp["cua-mcp"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] pkg_experimental_auto_review["experimental-auto-review"] pkg_experimental_badge_skill_bundle["experimental-badge-skill-bundle"] @@ -958,10 +959,10 @@ flowchart TD pkg_creation_recommendations --> pkg_session pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools - pkg_cua --> pkg_attachment - pkg_cua --> pkg_ptc_runtime_node - pkg_cua --> pkg_scope - pkg_cua --> pkg_user_questions + pkg_cua_mcp --> pkg_agent + pkg_cua_mcp --> pkg_attachment + pkg_cua_mcp --> pkg_system_prompt + pkg_cua_mcp --> pkg_tools pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt @@ -1129,6 +1130,11 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env + pkg_cua --> pkg_attachment + pkg_cua --> pkg_ptc_runtime_node + pkg_cua --> pkg_scope + pkg_cua --> pkg_tool_executor_ptc + pkg_cua --> pkg_user_questions pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions pkg_experimental_auto_review --> pkg_llm @@ -1831,7 +1837,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -1865,6 +1871,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 4ddd93c256..0707b65bd1 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -266,6 +266,7 @@ flowchart TD pkg_creation_recommendations["creation-recommendations"] pkg_cua["cua"] pkg_cua_bundle["cua-bundle"] + pkg_cua_mcp["cua-mcp"] pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"] pkg_experimental_auto_review["experimental-auto-review"] pkg_experimental_badge_skill_bundle["experimental-badge-skill-bundle"] @@ -960,10 +961,10 @@ flowchart TD pkg_creation_recommendations --> pkg_session pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools - pkg_cua --> pkg_attachment - pkg_cua --> pkg_ptc_runtime_node - pkg_cua --> pkg_scope - pkg_cua --> pkg_user_questions + pkg_cua_mcp --> pkg_agent + pkg_cua_mcp --> pkg_attachment + pkg_cua_mcp --> pkg_system_prompt + pkg_cua_mcp --> pkg_tools pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt @@ -1131,6 +1132,11 @@ flowchart TD pkg_api_settings_controller --> pkg_settings pkg_api_settings_controller --> pkg_typert_protocol pkg_web_app --> pkg_shell_env + pkg_cua --> pkg_attachment + pkg_cua --> pkg_ptc_runtime_node + pkg_cua --> pkg_scope + pkg_cua --> pkg_tool_executor_ptc + pkg_cua --> pkg_user_questions pkg_experimental_auto_review --> pkg_agent pkg_experimental_auto_review --> pkg_agent_instructions pkg_experimental_auto_review --> pkg_llm @@ -1833,7 +1839,7 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`user-questions`](../packages/interaction/user-questions) | +| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`agent`](../packages/core/agent), [`attachment`](../packages/attachment/attachment), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | @@ -1867,6 +1873,7 @@ flowchart TD | [`session-query`](../packages/session-query/session-query) | `session-query` | [`brand`](../packages/util/brand), [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`session-persistence`](../packages/session/session-persistence), [`session-projection`](../packages/session/session-projection), [`session-projection-cache`](../packages/session/session-projection-cache), [`session-title`](../packages/session/session-title), [`tool-todo`](../packages/todo/tool-todo) | | [`api-settings-controller`](../packages/api/settings-controller) | `api` | [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`credentials`](../packages/credentials/credentials), [`native-command`](../packages/util/native-command), [`session`](../packages/core/session), [`settings`](../packages/settings/settings), [`typert-protocol`](../packages/typert/protocol) | | [`web-app`](../packages/bundle/web-app) | `bundle` | [`shell-env`](../packages/shell/shell-env) | +| [`cua`](../packages/experimental/cua) | `experimental` | [`attachment`](../packages/attachment/attachment), [`ptc-runtime-node`](../packages/ptc-runtime/ptc-runtime-node), [`scope`](../packages/core/scope), [`tool-executor-ptc`](../packages/core/tool-executor-ptc), [`user-questions`](../packages/interaction/user-questions) | | [`experimental-auto-review`](../packages/experimental/auto-review) | `experimental` | [`agent`](../packages/core/agent), [`agent-instructions`](../packages/context/agent-instructions), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-forge-session`](../packages/experimental/forge-session) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`sandbox-policy`](../packages/sandbox/sandbox-policy), [`session`](../packages/core/session), [`session-projection`](../packages/session/session-projection), [`shell`](../packages/shell/shell), [`shell-env`](../packages/shell/shell-env), [`tools`](../packages/core/tools) | | [`webhook`](../packages/experimental/webhook) | `experimental` | [`agent`](../packages/core/agent), [`agent-default-model`](../packages/core/agent-default-model), [`agent-preset-registry`](../packages/preset/agent-preset-registry), [`llm`](../packages/llm/llm), [`permission-presets`](../packages/interaction/permission-presets), [`session`](../packages/core/session), [`session-title`](../packages/session/session-title), [`workspace`](../packages/workspace/workspace) | diff --git a/docs/subsystems/computer-use.i18n.yaml b/docs/subsystems/computer-use.i18n.yaml index 5d6db1a53a..642573ebc8 100644 --- a/docs/subsystems/computer-use.i18n.yaml +++ b/docs/subsystems/computer-use.i18n.yaml @@ -5,6 +5,9 @@ /computer-use: en: e02a2e4cc9970cba zh: 29aac6c0530a582f +/computer-use/serve-computer-use-to-another-harness: + en: a2beb91957e93f87 + zh: cf2a96b0fae0aae4 /computer-use/choose-a-provider: en: fa2e0d7b41c0450b zh: af9a799711f901e6 diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index 7b1dbee236..e95f0b1d3c 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -19,6 +19,10 @@ The CUA provider owns `ctx.cuaAccess` for system-permission status, explicit sys The [shared object API](../../packages/experimental/cua/README.md) uses `connectCua` to select an application, then `app.getWindows()` and `app.getWindow(windowId)` to select a window for screenshots and pointer input. Accessibility operations use element IDs from the latest tree for that application handle. Providers declare keyboard scopes and application-level accessibility in `getCapabilities()`. +## Serve Computer Use to another harness + +[Computer use MCP server](../../packages/experimental/cua-mcp/README.md) is a shipped optional bundle for the `cua-mcp` profile. `dsh --profile cua-mcp` serves `cua_run_code` and `cua_reset` to one MCP client such as Codex or Claude Code; each connection owns one Agent whose programs retain application and window objects, and consent is granted unattended or forwarded to the client as an elicitation. `dsh --profile cua-mcp --print-client-config codex|claude-code|json` prints the client configuration. The profile runs no model turn and records no root tool calls in its Session. + ## Choose a provider Mount [`dsh-computer-use`](../../packages/computer-use/computer-use/README.md) and one provider in the same composition. Both Cua Driver providers are experimental public npm packages and require explicit activation. @@ -136,4 +140,36 @@ Browser controls for provider-owned native permission and application decisions. ``` Source: [`packages/experimental/cua/src/access.ts`](../../packages/experimental/cua/src/access.ts) + + + +### `ctx.cuaPrograms` — `CuaPrograms` + +Host control over the dedicated `cua_run_code` environments; registered as `ctx.cuaPrograms`. + +```ts cordis-catalog +/** + * Release one Agent's retained program environment. Active programs of that Agent are cancelled, new + * programs wait for cleanup, and the next `cua_run_code` call starts a fresh process that re-creates the + * `cua` global; application grants, native connections, and the desktop applications themselves are + * unaffected. Resolves when no environment exists. + * @param agent - Agent whose `cua_run_code` state owner is released. + * @returns Completion after the process and its nested-call cleanup settle. + * @throws CodeResetFailedError when cleanup fails; programs stay blocked until a later reset succeeds. + */ +reset(agent: Agent): Promise + +/** + * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. + * A host that forwards screenshots outside a model request reads the same request version with it, so the + * image a caller sees matches the coordinate space the provider mapped. + * @param image - Durable screenshot attachment from a `cua` result. + * @returns The fixed target, or undefined when the Agent's model route selects the delivered version. + */ +screenshotRequestTarget(image: ImageAttachmentRef): ImageRequestTarget | undefined +``` + +Types: [Agent](core.md) · [ImageAttachmentRef](attachment.md) · [ImageRequestTarget](attachment.md) + +Source: [`packages/experimental/cua/src/tool-registration.ts`](../../packages/experimental/cua/src/tool-registration.ts) diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 1c35045383..82d260fd66 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -19,6 +19,10 @@ CUA provider 通过 `ctx.cuaAccess` 提供系统权限状态、用户主动申 调用[共享对象 API](../../packages/experimental/cua/README.zh.md) 时,通过 `connectCua` 连接,选择应用后用 `app.getWindows()` 和 `app.getWindow(windowId)` 选择要截图或进行鼠标操作的窗口。辅助功能操作使用该应用句柄最近一次读取的树中的元素 ID。提供方通过 `getCapabilities()` 声明键盘输入支持的范围,以及是否支持应用级辅助功能。 +## 向其他 harness 提供 Computer Use + +[Computer Use MCP 服务器](../../packages/experimental/cua-mcp/README.zh.md)是随安装提供的可选组合包,服务于 `cua-mcp` profile。`dsh --profile cua-mcp` 向一个 MCP 客户端(如 Codex 或 Claude Code)提供 `cua_run_code` 和 `cua_reset`;每个连接拥有一个 Agent,其程序保留应用与窗口对象,授权可无人值守放行或作为 elicitation 转发给客户端。`dsh --profile cua-mcp --print-client-config codex|claude-code|json` 打印客户端配置。该 profile 不运行模型回合,其 Session 中不记录根工具调用。 + ## 选择提供方 在同一组合中挂载 [`dsh-computer-use`](../../packages/computer-use/computer-use/README.zh.md) 和一个提供方。两个 Cua Driver 提供方都是公开发布到 npm 的实验性包,均需显式启用。 @@ -136,4 +140,36 @@ Browser controls for provider-owned native permission and application decisions. ``` Source: [`packages/experimental/cua/src/access.ts`](../../packages/experimental/cua/src/access.ts) + + + +### `ctx.cuaPrograms` — `CuaPrograms` + +Host control over the dedicated `cua_run_code` environments; registered as `ctx.cuaPrograms`. + +```ts cordis-catalog +/** + * Release one Agent's retained program environment. Active programs of that Agent are cancelled, new + * programs wait for cleanup, and the next `cua_run_code` call starts a fresh process that re-creates the + * `cua` global; application grants, native connections, and the desktop applications themselves are + * unaffected. Resolves when no environment exists. + * @param agent - Agent whose `cua_run_code` state owner is released. + * @returns Completion after the process and its nested-call cleanup settle. + * @throws CodeResetFailedError when cleanup fails; programs stay blocked until a later reset succeeds. + */ +reset(agent: Agent): Promise + +/** + * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. + * A host that forwards screenshots outside a model request reads the same request version with it, so the + * image a caller sees matches the coordinate space the provider mapped. + * @param image - Durable screenshot attachment from a `cua` result. + * @returns The fixed target, or undefined when the Agent's model route selects the delivered version. + */ +screenshotRequestTarget(image: ImageAttachmentRef): ImageRequestTarget | undefined +``` + +Types: [Agent](core.zh.md) · [ImageAttachmentRef](attachment.zh.md) · [ImageRequestTarget](attachment.zh.md) + +Source: [`packages/experimental/cua/src/tool-registration.ts`](../../packages/experimental/cua/src/tool-registration.ts) diff --git a/docs/subsystems/mcp.i18n.yaml b/docs/subsystems/mcp.i18n.yaml index e4fea9f3c9..2513d55f78 100644 --- a/docs/subsystems/mcp.i18n.yaml +++ b/docs/subsystems/mcp.i18n.yaml @@ -30,5 +30,5 @@ en: 27a59706525c88ed zh: 1fb1684bc03bb6ae /mcp/further-reading: - en: 1d24646cc4174154 - zh: 3cb4253d39402451 + en: b2642914c5a9def4 + zh: eb1f739949e040b0 diff --git a/docs/subsystems/mcp.md b/docs/subsystems/mcp.md index da3c4539a3..cb62adac02 100644 --- a/docs/subsystems/mcp.md +++ b/docs/subsystems/mcp.md @@ -115,6 +115,7 @@ MCP prompt templates, human-input elicitation, task-based execution, and resourc - [Resource visibility reference](../../packages/mcp/mcp-resources/README.md) — shared profile mounting and visibility from configured servers. - [Third-party memory servers](../user/guide/mcp-memory.md) — product configuration guide. - [Protocol negotiation reference](../../packages/mcp/mcp-client/README.md) — SDK ownership and compatibility decisions. +- [Computer use MCP server](../../packages/experimental/cua-mcp/README.md) — DSH as an MCP stdio server that serves Computer Use programs to other harnesses. diff --git a/docs/subsystems/mcp.zh.md b/docs/subsystems/mcp.zh.md index a2eecf3f11..0e51b7bfda 100644 --- a/docs/subsystems/mcp.zh.md +++ b/docs/subsystems/mcp.zh.md @@ -115,6 +115,7 @@ interface McpResourceProvider { - [资源可见性参考](../../packages/mcp/mcp-resources/README.zh.md) — profile 统一挂载及由已配置服务器决定的可见性。 - [第三方记忆服务器](../user/guide/mcp-memory.zh.md) — 产品配置指南。 - [协议协商参考](../../packages/mcp/mcp-client/README.zh.md) — SDK 职责与兼容性决策。 +- [Computer Use MCP 服务器](../../packages/experimental/cua-mcp/README.zh.md) — DSH 作为 MCP stdio 服务器向其他 harness 提供 Computer Use 程序。 diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index f0fecadd3b..a9a757958a 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -21,8 +21,8 @@ en: 2fdfe02f2ed4a258 zh: d748228ece579c4a /deepseek-ai-dsh-app-boot/use-this-package/starting-the-app: - en: 65bf2834b81f87da - zh: c864ac60a3005b99 + en: 964aafe2cb5bc898 + zh: fda067dd80664a30 /deepseek-ai-dsh-app-boot/use-this-package/profiles: en: 781fe487a973ee6f zh: e95188274f75f9ad diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index f480a5886d..9d926cfbcc 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -42,7 +42,7 @@ installFailLoud('dsh') const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHOT)) ``` -`installFailLoud` writes one labelled `util.inspect` diagnostic to stderr for an unhandled rejection or an uncaught exception, awaits the surface's release hook under a fixed timeout, and exits 1; control never returns to the failed operation, because only the throw site knows which state is intact, and the event loop runs only until the release settles or times out. With that entry point, startup keeps every plugin that can activate. An enabled failed plugin produces a labelled warning. A failed required entry makes startup dispose the whole app and exit nonzero; required ids absent from a profile and disabled required entries do not affect startup. The global required list covers shared Agent execution, application endpoints, and Web bootstrap/transport: `agent-loop`, `tool-executor-native`, `tool-executor-ptc`, `webserver`, `web-runtime`, `modules`, `connection`, `headless-runner`, `acp`, and `sdk-jsonrpc-server`. +`installFailLoud` writes one labelled `util.inspect` diagnostic to stderr for an unhandled rejection or an uncaught exception, awaits the surface's release hook under a fixed timeout, and exits 1; control never returns to the failed operation, because only the throw site knows which state is intact, and the event loop runs only until the release settles or times out. With that entry point, startup keeps every plugin that can activate. An enabled failed plugin produces a labelled warning. A failed required entry makes startup dispose the whole app and exit nonzero; required ids absent from a profile and disabled required entries do not affect startup. The global required list covers shared Agent execution, application endpoints, and Web bootstrap/transport: `agent-loop`, `tool-executor-native`, `tool-executor-ptc`, `webserver`, `web-runtime`, `modules`, `connection`, `headless-runner`, `acp`, `sdk-jsonrpc-server`, and `cua-mcp`. ### Profiles diff --git a/packages/boot/app-boot/README.zh.md b/packages/boot/app-boot/README.zh.md index 2a9c53a38e..db2ecde74b 100644 --- a/packages/boot/app-boot/README.zh.md +++ b/packages/boot/app-boot/README.zh.md @@ -42,7 +42,7 @@ installFailLoud('dsh') const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHOT)) ``` -`installFailLoud` 会为未处理 rejection 或未捕获异常向 stderr 写一条带标签的 `util.inspect` 诊断,在固定超时内等待界面的 release 钩子,然后以 1 退出;控制流不会回到失败的操作,因为只有抛出点知道哪些状态仍然完整,事件循环只运行到 release 结束或超时。有了这个入口,启动会保留所有能够激活的插件。启用但失败的插件会产生带标签的警告。required entry 失败时,启动会拆卸整个应用并以非零码退出;profile 中不存在的 required id 和已禁用的 required entry 不影响启动。全局 required list 覆盖共享 Agent 执行、应用 endpoint,以及 Web 启动与传输:`agent-loop`、`tool-executor-native`、`tool-executor-ptc`、`webserver`、`web-runtime`、`modules`、`connection`、`headless-runner`、`acp` 和 `sdk-jsonrpc-server`。 +`installFailLoud` 会为未处理 rejection 或未捕获异常向 stderr 写一条带标签的 `util.inspect` 诊断,在固定超时内等待界面的 release 钩子,然后以 1 退出;控制流不会回到失败的操作,因为只有抛出点知道哪些状态仍然完整,事件循环只运行到 release 结束或超时。有了这个入口,启动会保留所有能够激活的插件。启用但失败的插件会产生带标签的警告。required entry 失败时,启动会拆卸整个应用并以非零码退出;profile 中不存在的 required id 和已禁用的 required entry 不影响启动。全局 required list 覆盖共享 Agent 执行、应用 endpoint,以及 Web 启动与传输:`agent-loop`、`tool-executor-native`、`tool-executor-ptc`、`webserver`、`web-runtime`、`modules`、`connection`、`headless-runner`、`acp`、`sdk-jsonrpc-server` 和 `cua-mcp`。 ### Profile diff --git a/packages/boot/app-boot/src/index.ts b/packages/boot/app-boot/src/index.ts index 40ff3068c7..0b71716f5f 100644 --- a/packages/boot/app-boot/src/index.ts +++ b/packages/boot/app-boot/src/index.ts @@ -974,6 +974,7 @@ const requiredStartupEntryIds = new Set([ 'headless-runner', 'acp', 'sdk-jsonrpc-server', + 'cua-mcp', ]) /** Render plugin stacks, nested causes, and aggregate member failures once per error. */ diff --git a/packages/boot/app-boot/tests/app-boot.spec.ts b/packages/boot/app-boot/tests/app-boot.spec.ts index d454332317..ca647ea96a 100644 --- a/packages/boot/app-boot/tests/app-boot.spec.ts +++ b/packages/boot/app-boot/tests/app-boot.spec.ts @@ -617,6 +617,7 @@ describe('auditStartupEntries', () => { 'headless-runner', 'acp', 'sdk-jsonrpc-server', + 'cua-mcp', ] interface FakeEntry { diff --git a/packages/core/tool-executor-ptc/README.i18n.yaml b/packages/core/tool-executor-ptc/README.i18n.yaml index 3cc892055c..c81ca0603d 100644 --- a/packages/core/tool-executor-ptc/README.i18n.yaml +++ b/packages/core/tool-executor-ptc/README.i18n.yaml @@ -15,8 +15,8 @@ en: d152484eb41ac6b4 zh: 09388d293f9be9cb /deepseek-ai-dsh-tool-executor-ptc/use-this-package: - en: a616b9b4afc33711 - zh: 208d6a3e109e1a05 + en: b1728fb0012fe96e + zh: 1f7935157324b7c9 /deepseek-ai-dsh-tool-executor-ptc/understand-the-implementation: en: 78708b3779d999a9 zh: ad6173f9f01630de diff --git a/packages/core/tool-executor-ptc/README.md b/packages/core/tool-executor-ptc/README.md index de78a8ecaa..62b595d446 100644 --- a/packages/core/tool-executor-ptc/README.md +++ b/packages/core/tool-executor-ptc/README.md @@ -42,7 +42,7 @@ This package declares `ctx.ptcRuntime` and `ctx.systemPrompt` as required inject Shared dispatch events and the `ptc-mode` message-source declaration live in `@deepseek-ai/dsh-tool-executor-ptc/types`; Client code imports the same declarations through `@deepseek-ai/dsh-tool-executor-ptc/client`. Both entries exclude Host service declarations. Host policy extensions use `import type` from the package entry for `PtcDispatchLog` and `tools/ptc-dispatch-log` without mounting the executor. -The `/run-code` entry exports `createRunCodeTool` for plugins that register a named program tool alongside native tools. Supply an explicit runtime and the complete private `ToolDefinition` list, then register the returned definition in the owning scope. Programs can call only that list, even when the Agent can call other native tools; the private definitions do not enter the tool registry. Nested calls retain normal approvals, guards, dispatch logs, screenshots, deferred context, and turn completion. `RunCodeConfig` exposes the same validated call-allowance and concurrency settings as this executor. +The `/run-code` entry exports `createRunCodeTool` for plugins that register a named program tool alongside native tools. Supply an explicit runtime and the complete private `ToolDefinition` list, then register the returned definition in the owning scope. Programs can call only that list, even when the Agent can call other native tools; the private definitions do not enter the tool registry. Nested calls retain normal approvals, guards, dispatch logs, screenshots, deferred context, and turn completion. `RunCodeConfig` exposes the same validated call-allowance and concurrency settings as this executor. `createRunCodeToolHandle` returns the same definition with `reset(agent)`: it cancels that Agent's active programs, releases the retained environment, and holds new programs until cleanup settles; runtimes without retained state and failed cleanups reject with `CodeResetFailedError` (`CODE_RESET_FAILED`), and programs stay blocked until a later reset succeeds. The caller owns the supplied runtime and must keep it available until the factory's context finishes disposal. For runtimes that retain state or enforce a sandbox, disposal cancels active Agent programs and waits for nested calls; Agent disposal releases its retained environment. Optional `initialization` source executes before each program in the same environment, including temporary escalated executions, and requires a runtime that supports initialization. The factory appends runtime syntax and execution guidance to the caller's description; the caller supplies instructions for the private bindings. diff --git a/packages/core/tool-executor-ptc/README.zh.md b/packages/core/tool-executor-ptc/README.zh.md index 5d8c46a722..d3952c49ee 100644 --- a/packages/core/tool-executor-ptc/README.zh.md +++ b/packages/core/tool-executor-ptc/README.zh.md @@ -42,7 +42,7 @@ kind: "package-reference" 共享分派事件与 `ptc-mode` 消息来源声明位于 `@deepseek-ai/dsh-tool-executor-ptc/types`;Client 代码通过 `@deepseek-ai/dsh-tool-executor-ptc/client` 导入同一组声明。两个入口都不引入 Host 服务声明。Host 策略扩展通过包主入口的 `import type` 获取 `PtcDispatchLog` 与 `tools/ptc-dispatch-log`,无需挂载执行器。 -`/run-code` 入口导出 `createRunCodeTool`,供插件在原生工具旁注册具名程序工具。调用方显式传入运行时及完整的私有 `ToolDefinition` 列表,再将返回的定义注册到所属作用域。即使 Agent 能直接调用其他原生工具,程序也只能调用该列表中的工具;私有定义不进入工具注册表。嵌套调用保留正常审批、guard、派发日志、截图、延后上下文和轮次结束行为。`RunCodeConfig` 提供与本执行器相同且经过校验的调用额度与并发设置。 +`/run-code` 入口导出 `createRunCodeTool`,供插件在原生工具旁注册具名程序工具。调用方显式传入运行时及完整的私有 `ToolDefinition` 列表,再将返回的定义注册到所属作用域。即使 Agent 能直接调用其他原生工具,程序也只能调用该列表中的工具;私有定义不进入工具注册表。嵌套调用保留正常审批、guard、派发日志、截图、延后上下文和轮次结束行为。`RunCodeConfig` 提供与本执行器相同且经过校验的调用额度与并发设置。`createRunCodeToolHandle` 返回同一定义及 `reset(agent)`:取消该 Agent 正在运行的程序、释放保留环境,并在清理完成前暂停新程序;运行时不保留状态或清理失败时以 `CodeResetFailedError`(`CODE_RESET_FAILED`)拒绝,程序保持阻塞直到后续重置成功。 调用方拥有传入的运行时,必须使其可用至工厂上下文完成销毁。对于保留状态或实施沙箱的运行时,销毁会取消活动的 Agent 程序并等待嵌套调用;Agent 销毁时释放其保留环境。可选 `initialization` 源码在每次程序执行前于同一环境内运行,包括临时提权执行,并要求运行时支持初始化。工厂将运行时语法和执行说明追加到调用方提供的描述后;私有绑定的说明由调用方提供。 diff --git a/packages/core/tool-executor-ptc/src/run-code.ts b/packages/core/tool-executor-ptc/src/run-code.ts index 7bafa0c029..90c2222237 100644 --- a/packages/core/tool-executor-ptc/src/run-code.ts +++ b/packages/core/tool-executor-ptc/src/run-code.ts @@ -1,9 +1,11 @@ /** Registered program tools with an explicit runtime and private tool bindings. @module */ import type { Context } from '@deepseek-ai/cordis' +import type { Agent } from '@deepseek-ai/dsh-agent' import type { PtcRuntime } from '@deepseek-ai/dsh-ptc-runtime' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' -import { ToolExecutionPipeline } from '@deepseek-ai/dsh-tools/pipeline' +import { ToolExecutionPipeline, toolErrorMessage } from '@deepseek-ai/dsh-tools/pipeline' import { Config } from './config.ts' +import { CodeResetFailedError } from './errors.ts' import { PtcCalls } from './ptc-calls.ts' import { createRunCodeTransport } from './ptc.ts' @@ -25,25 +27,64 @@ export interface RunCodeToolOptions { readonly limits?: Partial } +/** One registered program tool and the host control over its retained environments. */ +export interface RunCodeToolHandle { + /** Unregistered definition; register it in the owning scope with `ctx.tools.register`. */ + readonly definition: ToolDefinition + /** + * Clear one Agent's retained environment without executing program code. Active programs of that + * Agent are cancelled, the runtime releases the environment, and new programs wait until cleanup + * settles; a failed cleanup blocks programs until a later reset succeeds. Completed tool effects remain. + * @param agent - Exact owner supplied to program executions. + * @returns After process and nested-call cleanup. + * @throws CodeResetFailedError if the runtime does not retain state, or when cleanup fails. + */ + reset(agent: Agent): Promise +} + /** - * Create a tool whose programs can call only the supplied private definitions. + * Create a tool whose programs can call only the supplied private definitions, with host reset control. * Nested calls retain approvals, guards, result policy, dispatch logs, and deferred contexts. * The owning context cancels and drains active Agent programs when disposed if the runtime * retains state or enforces a sandbox. Agent disposal releases retained runtime state. * @param ctx - Context with tools, lifecycle ownership, and policies; Agent calls also require workingDirectory. * @param options - Fixed runtime, tools, initialization, presentation, and configurable limits. - * @returns An unregistered definition; register it in the owning scope with ctx.tools.register. + * @returns The unregistered definition and its reset control. * @throws Error if private tool names repeat or configured limits are invalid. */ -export function createRunCodeTool(ctx: Context, options: RunCodeToolOptions): ToolDefinition { +export function createRunCodeToolHandle(ctx: Context, options: RunCodeToolOptions): RunCodeToolHandle { const definitions = new Map() for (const definition of options.tools) { if (definitions.has(definition.name)) throw new Error(`Program tool ${options.name} has duplicate binding ${definition.name}`) definitions.set(definition.name, definition) } const pipeline = new ToolExecutionPipeline(ctx, { get: name => definitions.get(name) }) - return createRunCodeTransport(ctx, pipeline, Config(options.limits ?? {}), new PtcCalls(ctx), { + const calls = new PtcCalls(ctx) + const definition = createRunCodeTransport(ctx, pipeline, Config(options.limits ?? {}), calls, { ...options, tools: [...definitions.values()], }) + return { + definition, + async reset(agent) { + if (!options.runtime.retainsState) throw new CodeResetFailedError('The program runtime does not retain an environment') + try { + await calls.reset(agent.session.id, () => options.runtime.release(agent)) + } catch (error) { + throw new CodeResetFailedError(`Program environment reset failed: ${toolErrorMessage(error)}. State may not be cleared; retry the host reset before running more code.`) + } + }, + } +} + +/** + * Create a tool whose programs can call only the supplied private definitions. + * Equivalent to {@link createRunCodeToolHandle} for callers that need no host reset control. + * @param ctx - Context with tools, lifecycle ownership, and policies; Agent calls also require workingDirectory. + * @param options - Fixed runtime, tools, initialization, presentation, and configurable limits. + * @returns An unregistered definition; register it in the owning scope with ctx.tools.register. + * @throws Error if private tool names repeat or configured limits are invalid. + */ +export function createRunCodeTool(ctx: Context, options: RunCodeToolOptions): ToolDefinition { + return createRunCodeToolHandle(ctx, options).definition } diff --git a/packages/core/tool-executor-ptc/tests/run-code.spec.ts b/packages/core/tool-executor-ptc/tests/run-code.spec.ts index ee5b3f68d5..86578003a8 100644 --- a/packages/core/tool-executor-ptc/tests/run-code.spec.ts +++ b/packages/core/tool-executor-ptc/tests/run-code.spec.ts @@ -12,7 +12,7 @@ import { NativeToolExecutor } from '@deepseek-ai/dsh-tool-executor-native' import ToolRuntime, { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools' import ApprovalService, { type ApprovalOutcome } from '@deepseek-ai/dsh-user-approval' import { describe, expect, it, onTestFinished, vi } from 'vitest' -import { createRunCodeTool, RunCodeConfig } from '../src/run-code.ts' +import { createRunCodeTool, createRunCodeToolHandle, RunCodeConfig, type RunCodeToolHandle } from '../src/run-code.ts' class ControlledRuntime extends PtcRuntime { readonly language = 'typescript' @@ -59,13 +59,16 @@ async function setup(definition: ToolDefinition, limits?: Partial session.append('turn/start', { turn: 1 }) const agent = { ctx: agentContext, id: session.id, session } as Agent const initialization = 'globalThis.cua ??= createComputer()' + let handle: RunCodeToolHandle | undefined const fiber = await ctx.plugin(Object.assign((owner: Context) => { - owner.tools.register(createRunCodeTool(owner, { + handle = createRunCodeToolHandle(owner, { name: 'cua_run_code', description: 'Run computer operations through cua.', runtime, tools: [definition], initialization, ...limits === undefined ? {} : { limits }, - })) + }) + owner.tools.register(handle.definition) }, { inject: ['tools'] })) + if (handle === undefined) throw new Error('program tool factory did not run') const execute = async (args: Record = {}, name = 'cua_run_code') => { const signal = new AbortController().signal const toolSet = await ctx.tools.resolve({ agent, modelSelection: { provider: 'test', model: 'test' }, signal }) @@ -76,7 +79,7 @@ async function setup(definition: ToolDefinition, limits?: Partial }) } finally { toolSet.dispose() } } - return { ctx, runtime, agent, agentContext, session, fiber, initialization, execute } + return { ctx, runtime, agent, agentContext, session, fiber, initialization, execute, handle } } describe('registered program tool factory', () => { @@ -235,6 +238,46 @@ describe('registered program tool factory', () => { } }) + it('resets one Agent environment through the handle, cancelling its program before admitting the next', async () => { + const entered = Promise.withResolvers() + const { runtime, agent, session, execute, handle } = await setup(privateTool()) + const release = vi.spyOn(runtime, 'release') + let programs = 0 + runtime.behavior = async (request) => { + programs += 1 + if (programs > 1) return { logs: [], value: `program ${programs}` } + entered.resolve(undefined) + await new Promise((resolve) => { request.signal?.addEventListener('abort', () => { resolve() }, { once: true }) }) + return { logs: [], error: { kind: 'abort', message: 'runtime cancelled' } } + } + const running = execute() + await entered.promise + await handle.reset(agent) + expect(release).toHaveBeenCalledExactlyOnceWith(agent) + expect((await running).results[0]?.result).toMatchObject({ isError: true, error: { info: { code: 'CODE_RUN_FAILED' } } }) + expect((await execute()).results[0]?.result).toMatchObject({ isError: false }) + expect(session.snapshotEvents().filter(event => event.type === 'tool/ptc-dispatch-start')).toHaveLength(0) + await expect(handle.reset(agent)).resolves.toBeUndefined() + expect(release).toHaveBeenCalledTimes(2) + }) + + it('reports unsupported and failed resets as CODE_RESET_FAILED and blocks programs until a reset succeeds', async () => { + const { runtime, agent, execute, handle } = await setup(privateTool()) + const release = vi.spyOn(runtime, 'release').mockRejectedValueOnce(new Error('process refused to exit')) + await expect(handle.reset(agent)).rejects.toMatchObject({ + name: 'CodeResetFailedError', code: 'CODE_RESET_FAILED', message: expect.stringContaining('process refused to exit') as string, + }) + const blocked = (await execute()).results[0]?.result + expect(blocked).toMatchObject({ isError: true, error: { info: { code: 'CODE_RUN_FAILED' } } }) + expect(JSON.stringify(blocked?.content)).toContain('Program environment unavailable') + await expect(handle.reset(agent)).resolves.toBeUndefined() + expect(release).toHaveBeenCalledTimes(2) + expect((await execute()).results[0]?.result).toMatchObject({ isError: false }) + vi.spyOn(runtime, 'retainsState', 'get').mockReturnValue(false) + await expect(handle.reset(agent)).rejects.toMatchObject({ code: 'CODE_RESET_FAILED', message: expect.stringContaining('does not retain') as string }) + expect(release).toHaveBeenCalledTimes(2) + }) + it('applies configurable call allowances using the registered tool name', async () => { const body = vi.fn(async () => 'private result') const { runtime, session, execute } = await setup(privateTool(body), { maxSubCallsPerMinute: 60, maxParallelSubCalls: 1 }) diff --git a/packages/experimental/README.i18n.yaml b/packages/experimental/README.i18n.yaml index f367bacc8d..569ecc0273 100644 --- a/packages/experimental/README.i18n.yaml +++ b/packages/experimental/README.i18n.yaml @@ -18,8 +18,8 @@ en: 55d9e37b0a8dd4d8 zh: 3acb6415f92698fb /packages-experimental/packages: - en: 53c2534fd0043ca3 - zh: d319461cf6db95b5 + en: bcfca0fe7834461b + zh: 439e2f09fc0398d1 /packages-experimental/related-documentation: en: 40797d4849455966 zh: bb91a68dd995887c diff --git a/packages/experimental/README.md b/packages/experimental/README.md index 0643185822..5ffcc83830 100644 --- a/packages/experimental/README.md +++ b/packages/experimental/README.md @@ -80,6 +80,7 @@ Promotion requires a named product role, documented public behavior and limitati | [CUA](cua/README.md) | Application/window objects, authorized execution, and permission controls. | `ctx.cuaAccess` | | [macOS CUA](cua-macos/README.md) | Swift native execution and platform preparation. | `ctx.computerUse` | | [`cua-bundle`](cua-bundle/README.md) | Optional Computer Use switch for PTC sessions | — | +| [`cua-mcp`](cua-mcp/README.md) | Computer Use as an MCP stdio server for external agent harnesses, served by the `cua-mcp` profile | — | | [`computer-use-cua-driver-mcp`](computer-use-cua-driver-mcp/README.md) | Use an installed Cua Driver through MCP | `ctx.computerUse` | | [`computer-use-cua-driver-native`](computer-use-cua-driver-native/README.md) | Embed the Cua Driver native npm runtime | `ctx.computerUse` | | [`browser-use-playwright-mcp`](browser-use-playwright-mcp/README.md) | Playwright browser tools over MCP | `ctx.browserUse` | diff --git a/packages/experimental/README.zh.md b/packages/experimental/README.zh.md index aa1cc3ee24..a3a6ad3c0e 100644 --- a/packages/experimental/README.zh.md +++ b/packages/experimental/README.zh.md @@ -80,6 +80,7 @@ kind: "package-group" | [CUA](cua/README.zh.md) | 应用与窗口对象、授权执行和权限控件。 | `ctx.cuaAccess` | | [macOS CUA](cua-macos/README.zh.md) | Swift 原生执行与平台组件准备。 | `ctx.computerUse` | | [`cua-bundle`](cua-bundle/README.zh.md) | 面向 PTC 会话、默认关闭的 Computer Use 开关 | — | +| [`cua-mcp`](cua-mcp/README.zh.md) | 由 `cua-mcp` profile 向外部 agent harness 提供的 Computer Use MCP stdio 服务器 | — | | [`computer-use-cua-driver-mcp`](computer-use-cua-driver-mcp/README.zh.md) | 通过 MCP 使用已安装的 Cua Driver | `ctx.computerUse` | | [`computer-use-cua-driver-native`](computer-use-cua-driver-native/README.zh.md) | 嵌入 Cua Driver 原生 npm 运行时 | `ctx.computerUse` | | [`browser-use-playwright-mcp`](browser-use-playwright-mcp/README.zh.md) | 通过 MCP 提供 Playwright 浏览器工具 | `ctx.browserUse` | diff --git a/packages/experimental/cua-macos/README.i18n.yaml b/packages/experimental/cua-macos/README.i18n.yaml index 2686e257bd..a0688319fd 100644 --- a/packages/experimental/cua-macos/README.i18n.yaml +++ b/packages/experimental/cua-macos/README.i18n.yaml @@ -15,8 +15,8 @@ en: 1777e7bf6785f986 zh: e3daac1074ebb74d /deepseek-ai-dsh-experimental-cua-macos/use-this-package: - en: 55ec2bb2174539a4 - zh: 1e8f6e0ae60f888d + en: a74bed5f0e15d763 + zh: 5f82a78595cc2b60 /deepseek-ai-dsh-experimental-cua-macos/use-this-package/connect-an-external-execution-environment: en: 19e71de51338e374 zh: afb6820bdbac2443 diff --git a/packages/experimental/cua-macos/README.md b/packages/experimental/cua-macos/README.md index 49d1c86229..9c369b2fae 100644 --- a/packages/experimental/cua-macos/README.md +++ b/packages/experimental/cua-macos/README.md @@ -59,6 +59,7 @@ Source builds default to `sourceSigning: ad-hoc`, without creating certificates | --- | --- | --- | | `agentPreset` | `ptc` | Give this preset raw `cua` and other composed presets `cua_run_code`; `false` registers raw `cua` globally. | | `runCode.runtime` / `runCode.executor` | shared Node / PTC limits | Resource, launch, and nested-call settings for the dedicated CUA runtime; see [CUA](../cua/README.md). | +| `screenshotTarget` | unset | Fixed `{ longEdge, maxBytes }` request-image target for screenshots. Unset resolves the target from the Agent's model route and refuses capture when that route declares no image input. | | `allowedApps` | `[]` | Legacy path/signature grants, imported once for removal; they do not authorize new bundle-ID identities. | | `helperPath` | package-owned executable | Absolute executable inside the signed helper `.app`; a bare binary fails with `NATIVE_APPLICATION_REQUIRED`. | | `requireSystemPointerApproval` | `true` | Ask on the first explicit request to move the system pointer. With `false`, only explicitly requested moves use it. | diff --git a/packages/experimental/cua-macos/README.zh.md b/packages/experimental/cua-macos/README.zh.md index cd4e49b7df..75997bc5bc 100644 --- a/packages/experimental/cua-macos/README.zh.md +++ b/packages/experimental/cua-macos/README.zh.md @@ -59,6 +59,7 @@ pnpm dsh headless --patch packages/experimental/cua-macos/examples/macos.cordis. | --- | --- | --- | | `agentPreset` | `ptc` | 为该 preset 提供原始 `cua`,为其他已组合的 preset 提供 `cua_run_code`;`false` 表示全局注册原始 `cua`。 | | `runCode.runtime` / `runCode.executor` | 共享 Node / PTC 上限 | 专用 CUA 运行时的资源、启动和嵌套调用设置;参见 [CUA](../cua/README.zh.md)。 | +| `screenshotTarget` | 未设置 | 截图使用的固定 `{ longEdge, maxBytes }` 请求图片目标。未设置时按 Agent 的模型路由解析,该路由未声明图片输入时拒绝截图。 | | `allowedApps` | `[]` | 旧路径和签名许可,只导入 profile 存储一次供撤销,不授予新 Bundle ID 身份访问权限。 | | `helperPath` | 包内可执行文件 | 已签名 helper `.app` 内可执行文件的绝对路径;裸二进制会触发 `NATIVE_APPLICATION_REQUIRED`。 | | `requireSystemPointerApproval` | `true` | 主任务首次显式请求移动系统指针时询问用户。设为 `false` 时仅本次显式移动免询问。 | diff --git a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts index d173a61b7e..be7be59553 100644 --- a/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts +++ b/packages/experimental/cua-macos/tests/provider-lifecycle.spec.ts @@ -119,7 +119,9 @@ class ImageAdapter extends LlmAdapter { const imageData = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAIAAACQd1PeAAAACXBIWXMAAAPoAAAD6AG1e1JrAAAADElEQVQImWNgZGIGAAAOAAeCcsnOAAAAAElFTkSuQmCC' const imageMetadata = { pixelWidth: 1, pixelHeight: 1, bounds: { x: 2, y: 3, width: 1, height: 1 }, coordinateSpace: 'window-points', windowId: 7 } -async function setup(model?: { provider: string; model: string }, ptc = false) { +async function setup( + model?: { provider: string; model: string }, ptc = false, overrides: Parameters[0] = {}, +) { native.connect.mockClear() native.cleanup.mockReset().mockResolvedValue({ dispatched: true }) native.request.mockReset().mockResolvedValue([]) @@ -136,7 +138,7 @@ async function setup(model?: { provider: string; model: string }, ptc = false) { await ctx.plugin(SandboxPolicy, { mode: 'danger-full-access' }) await ctx.plugin(NodeRuntime) } else await ctx.plugin(Subprocess, []) - const provider = await ctx.plugin(NativeProvider, config) + const provider = await ctx.plugin(NativeProvider, { ...config, ...overrides }) await mountAgentLoopTestHarness(ctx) const handle = await ctx.agents.create({ sessionId: SessionId('native-lifecycle'), meta: { cwd: process.cwd() }, ...model ? { agentOptions: model } : {} }) let index = 0 @@ -743,6 +745,40 @@ it('refuses screenshot capture when no attachment store is mounted', async () => expect(native.request).not.toHaveBeenCalled() }) +it('captures screenshots through a configured target without resolving a model route', async () => { + const f = await setup(undefined, false, { screenshotTarget: { longEdge: 10, maxBytes: 100_000 } }) + await selectApplication(f) + const root = await mkdtemp(join(tmpdir(), 'dsh-cua-fixed-target-')) + onTestFinished(async () => { await f.ctx.fiber.dispose(); await rm(root, { recursive: true, force: true }) }) + await f.ctx.plugin(LocalAttachmentStore, { dshHome: root }) + const resolve = vi.spyOn(f.ctx.llm, 'resolveModelInfo') + const image = await sharp({ create: { width: 40, height: 20, channels: 3, background: '#4488cc' } }).png().toBuffer() + native.request.mockResolvedValue({ ...imageMetadata, bounds: { x: 10, y: 20, width: 400, height: 200 }, + pixelWidth: 40, pixelHeight: 20, mimeType: 'image/png', data: image.toString('base64') }) + const result = await f.execute('screenshot', { appHandle: 'app-one', windowId: 7 }) + expect(result.isError, JSON.stringify(result.content)).toBe(false) + expect(resolve).not.toHaveBeenCalled() + // The long edge of 40x20 scales to 10, so the short edge rounds to 5 and coordinates map back to native points. + expect(result.value).toMatchObject({ pixelWidth: 10, pixelHeight: 5, coordinateSpace: 'screenshot-pixels' }) + expect(result.content.filter(block => block.type === 'image')).toHaveLength(1) + native.request.mockResolvedValue({ dispatched: true }) + expect((await f.execute('click', { appHandle: 'app-one', windowId: 7, x: 5, y: 2.5 })).isError).toBe(false) + expect(native.request).toHaveBeenLastCalledWith('click', { appHandle: 'app-one', windowId: 7, x: 200, y: 100 }, expect.any(AbortSignal), expect.any(String)) +}) + +it('validates the configured screenshot target as a complete integer pair', () => { + expect(NativeProvider.Config({})).not.toHaveProperty('screenshotTarget') + expect(NativeProvider.Config({ screenshotTarget: { longEdge: 2048, maxBytes: 2_097_152 } }).screenshotTarget) + .toEqual({ longEdge: 2048, maxBytes: 2_097_152 }) + const invalid = [ + { longEdge: 2048 }, { maxBytes: 4096 }, { longEdge: 0, maxBytes: 4096 }, + { longEdge: 1.5, maxBytes: 4096 }, { longEdge: 1024, maxBytes: 512 }, + ] + for (const screenshotTarget of invalid) { + expect(() => NativeProvider.Config({ screenshotTarget } as never)).toThrow() + } +}) + it.each(['unresolved', 'unknown', 'text-only', 'provider-error'] as const)( 'refuses screenshot capture and storage for a %s model route', async (route) => { const f = await setup(route === 'unresolved' ? undefined : { provider: 'image-fixture', model: 'vision' }) diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml new file mode 100644 index 0000000000..f4ae1f8766 --- /dev/null +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -0,0 +1,58 @@ +# Bilingual-pair consistency record for README.md (docs/i18n/README.md): per heading +# section, a hash of its English and Chinese blocks outside code blocks and generated regions. +# After editing either side, bring the other along and re-record with: +# pnpm run verify-translation-pairing --write packages/experimental/cua-mcp/README.md +/: + en: 837f60ce18bd6470 + zh: cb329560601b38a4 +/deepseek-ai-dsh-cua-mcp: + en: c0bca87ff2983e2e + zh: da83dd66b8feafab +/deepseek-ai-dsh-cua-mcp/summary: + en: cc170382fc781faf + zh: 846bb765f348d365 +/deepseek-ai-dsh-cua-mcp/table-of-contents: + en: dcb583a860af8206 + zh: 0a0d02b6e7e4e0b6 +/deepseek-ai-dsh-cua-mcp/use-this-package: + en: bbff250eba0f1b89 + zh: 0a618f05cc88ee2b +/deepseek-ai-dsh-cua-mcp/use-this-package/install-into-a-profile: + en: c41e73c449ec4e64 + zh: 9e4ff33e1d97f1f3 +/deepseek-ai-dsh-cua-mcp/use-this-package/connect-a-client: + en: d1c0e8f54a1a9eca + zh: 86a0f883c2f7edce +/deepseek-ai-dsh-cua-mcp/use-this-package/what-you-get: + en: 2c9cae657eb4af9d + zh: f8cb92292bf0ebf3 +/deepseek-ai-dsh-cua-mcp/configuration: + en: 8996e07a265596a5 + zh: 8cf79827c51f2a2d +/deepseek-ai-dsh-cua-mcp/understand-the-implementation: + en: 65cefb2a0a5be892 + zh: 09e22959474eda6a +/deepseek-ai-dsh-cua-mcp/further-exploration: + en: 0328a9b46caad949 + zh: a20731d490d5412a +/deepseek-ai-dsh-cua-mcp/model-experience: + en: 215e7ba838619b7b + zh: a311da3843709f90 +/deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model: + en: 75ba5b40dac5fdbc + zh: 690d784248b15542 +/deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/what-the-model-sees: + en: 9dd9bcd00366b601 + zh: 7214d47c915dc601 +/deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/token-effect: + en: c84f22846abe33ed + zh: 78c261ffea81a653 +/deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/kv-cache-effect: + en: 2c22520787915229 + zh: 21dafc45d1a4bc0d +/deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work: + en: 56925d9b123a6b2f + zh: 1c613a37f6c89d6a +/deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note: + en: e67f633dc6fe7773 + zh: 8ec3e73528ddb1a6 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md new file mode 100644 index 0000000000..4fcdb76f09 --- /dev/null +++ b/packages/experimental/cua-mcp/README.md @@ -0,0 +1,148 @@ +--- +description: "Serve Computer Use to Codex, Claude Code, and other MCP clients from the cua-mcp profile over stdio." +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-cua-mcp + +English | [中文](README.zh.md) + +## Summary + +This experimental bundle turns a `dsh` profile into an MCP stdio server for Computer Use. Every DSH installation ships it switched off; one command selects it for the `cua-mcp` profile, and `dsh --profile cua-mcp` then serves `cua_run_code` and `cua_reset` to one MCP client. One connection owns one Agent whose programs keep application and window objects in memory between calls. Consent for application and pointer access is granted without a human or forwarded to the client as an elicitation. The profile runs no model turn; the connected harness owns the model. + +## Table of Contents + +- [Use this package](#use-this-package) +- [Configuration](#configuration) +- [Understand the implementation](#understand-the-implementation) +- [Further Exploration](#further-exploration) +- [Model Experience](#model-experience) +- [Known Limitations and Deferred Work](#known-limitations-and-deferred-work) +- [Dev Note](#dev-note) + +----- + + +## Use this package + +### Install into a profile + +The bundle is a runtime dependency of the `dsh` installation, so selecting it needs neither pnpm nor network access: + +```sh +dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp +dsh plugin --profile cua-mcp disable @deepseek-ai/dsh-cua-mcp +``` + +`enable` initializes the profile from `@deepseek-ai/dsh-base` when it is missing and appends this bundle to `dsh.profile.bundles`; `disable` removes the selection. A source checkout runs the same commands through `pnpm dsh` after `pnpm run build`. The Python runtime wheel ships the same installation, so a training harness writes the profile manifest itself, or runs `enable` through the wheel's executable, and then uses that executable as the stdio command: + +```python +import json, os +from pathlib import Path +from deepseek_harness_runtime import resolve_bundled_launch_args + +home = Path(os.environ["DSH_HOME"]) +profile = home / "profiles" / "cua-mcp" +profile.mkdir(parents=True, exist_ok=True) +(profile / "package.json").write_text(json.dumps({ + "name": "dsh-profile-cua-mcp", "private": True, "dependencies": {}, + "dsh": {"profile": {"bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-cua-mcp"]}}, +})) +command = [*resolve_bundled_launch_args(), "--profile", "cua-mcp"] # the MCP stdio command +``` + +### Connect a client + +`dsh --profile cua-mcp` is the stdio command. It prints its own help with `--help`, and `--print-client-config codex|claude-code|json` prints a ready configuration for this installation and Harness home: a `~/.codex/config.toml` fragment, a `claude mcp add-json dsh_cua` command, or a generic `mcpServers` document. Each embeds the absolute executable, `DSH_HOME`, and the current `DSH_CUA_CONSENT`. The Codex fragment sets `startup_timeout_sec = 120` for first-run helper preparation, `tool_timeout_sec = 600` to match the default program maximum, exposes both tools directly instead of through tool search, and raises the `cua_run_code` output budget to 25,000 tokens. Codex forwards elicitations only with `approval_policy.granular.mcp_elicitations = true`. + +```sh +dsh --profile cua-mcp --print-client-config codex >> ~/.codex/config.toml +dsh --profile cua-mcp --print-client-config claude-code | sh +``` + +On macOS the profile prepares the signed Computer Use helper on first start and needs Accessibility and Screen Recording permissions for it; the [macOS provider](../cua-macos/README.md) owns that setup. On other Hosts the profile starts without a provider, and both tools return an error naming the missing provider. + +### What you get + +`cua_run_code` runs a TypeScript program as REPL statements against the global `cua` object through the provider's retained Node environment. The result carries the program's printed lines and final expression as text, then every screenshot the program captured as an inline image in the exact version the program observed, so pixel coordinates in the text match the image. The first result of a connection starts with the complete `cua_run_code` execution rules and the `cua` API reference; the tool description stays short. `description` is optional and defaults to `CUA program`; `timeoutMs` bounds one program. Programs run one at a time per connection in arrival order; a cancelled call cancels its program. + +`cua_reset` discards the program environment: variables, imports, and application or window objects. Application grants, native connections, and the applications themselves stay; the next program starts a fresh process and its result repeats the API reference. Use it after a conflicting declaration or an unusable environment. + +The connection's Agent is created when the client finishes initialization and disposed when the client closes stdin, which also exits the process. Application consent follows the [CUA consent rules](../cua/README.md) for that Agent: `DSH_CUA_CONSENT=allow` grants each request for the session without a human, and the default `elicit` forwards the request to the client as a form elicitation whose answers are the CUA labels; a declined form records a denial for the session, and a client without elicitation receives an error that names the `allow` mode. + +----- + + +## Configuration + +Configure the `cua-mcp` row in the profile's `cordis.patch.yml`; the bundle patch maps `DSH_CUA_CONSENT` onto it. + +| Field | Default | Meaning | +|---|---|---| +| `consent` | `elicit` | `allow` grants application and pointer consent for this session without a human; `elicit` forwards each request to the MCP client. | + +The patch also mounts the provider with `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` because no model route selects a request image here, and `agentPreset: ptc` with an empty `cua-mcp` preset so the connection's Agent receives `cua_run_code` and no other model-facing rows. Override those rows by id in the profile patch. + +----- + + +## Understand the implementation + +
+Implementation internals — click to expand + +The [patch](cordis.patch.yml) disables the title, HMR, credential, authorization, and account rows of `dsh-base`, inserts the preset registry with the empty default preset, the `computer-use` registry, the macOS provider row disabled off Darwin, and this frontend. The frontend parses the invocation with `parseCmdline`, binds stdin EOF to the launcher's bounded shutdown, and connects the official MCP server to a stdio transport after the launcher commits readiness. `cua-mcp` is a required startup entry, so a frontend that cannot activate stops the profile. + +[`server.ts`](src/server.ts) registers both tools on one `McpServer`. The connection's Agent mounts the registry's default preset and records the launch directory. `cua_run_code` runs through `ctx.tools.execute` with the Agent and the request signal and no model step, so the Session log carries nested `tool/ptc-dispatch` events but no root `tool/call`; [`projection.ts`](src/projection.ts) renders the result and its deferred screenshot contexts, reading each image through `ctx.cuaPrograms.screenshotRequestTarget`. `cua_reset` calls `ctx.cuaPrograms.reset`. [`consent.ts`](src/consent.ts) is the `user-questions/request` answerer for that Agent; [`client-config.ts`](src/client-config.ts) renders the client snippets. + +
+ +----- + + +## Further Exploration + +- [Shared CUA package](../cua/README.md) — the object API, consent rules, and `cua_run_code`. +- [macOS provider](../cua-macos/README.md) — helper preparation, permissions, and platform guidance. +- [Computer use](../../../docs/subsystems/computer-use.md) and [MCP](../../../docs/subsystems/mcp.md) — subsystem references. +- [Profile composition](../../boot/app-boot/README.md) — bundle layers and patch lifetimes. +- [Decision record](../../../.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md) — why the server runs inside a profile and owns one Agent per connection. + +----- + + +## Model Experience + +### External harness model + +#### What the model sees + +The connected harness's model sees two tools and the server instructions from `tools/list` and `initialize`. The first `cua_run_code` result of a connection, and the first after `cua_reset`, begins with the `cua_run_code` execution rules and the `cua` API reference the provider registered; later results carry only program output and captured screenshots. No DSH model request exists in this profile. + +#### Token effect + +The API reference adds about 11,000 characters once per connection or reset. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the generated Codex configuration raises the `cua_run_code` budget to 25,000 tokens. + +#### KV Cache effect + +The tool catalog and instructions are stable for one installation. The first result's reference text changes only with the installed CUA packages. + +## Known Limitations and Deferred Work + + + +- Only macOS Hosts have a provider; the Windows provider mounts here once it exists. Other Hosts serve both tools as errors. +- Elicitation uses the 2025 MCP request model; a client that negotiates the 2026-07-28 revision receives an error for consent requests and should use `DSH_CUA_CONSENT=allow`. +- Program sandbox escalation and the raw `cua` tool are not exposed; `DSH_PERMISSION_MODE` selects the launch-time file sandbox of program processes. +- Root tool calls are not Session events; the connected harness's transcript is the record of calls and results. + + +### Dev Note + +
+Working context for maintainers — click to expand + +None. + +
diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md new file mode 100644 index 0000000000..71d0683def --- /dev/null +++ b/packages/experimental/cua-mcp/README.zh.md @@ -0,0 +1,148 @@ +--- +description: "通过 cua-mcp profile 以 stdio 向 Codex、Claude Code 等 MCP 客户端提供 Computer Use。" +kind: "package-bundle" +--- + +# @deepseek-ai/dsh-cua-mcp + +[English](README.md) | 中文 + +## 概述 + +这个实验性组合包把一个 `dsh` profile 变成 Computer Use 的 MCP stdio 服务器。每个 DSH 安装都自带它且默认关闭;一条命令即可为 `cua-mcp` profile 选中它,随后 `dsh --profile cua-mcp` 向一个 MCP 客户端提供 `cua_run_code` 与 `cua_reset`。一个连接拥有一个 Agent,其程序在多次调用之间于内存中保留应用与窗口对象。应用与指针访问的授权可无人值守放行,或作为 elicitation 转发给客户端。该 profile 不运行模型回合;模型归接入的 harness 所有。 + +## 目录 + +- [使用本包](#use-this-package) +- [配置](#configuration) +- [理解实现](#understand-the-implementation) +- [进一步探索](#further-exploration) +- [模型体验](#model-experience) +- [已知限制与延后工作](#known-limitations-and-deferred-work) +- [开发备注](#dev-note) + +----- + + +## 使用本包 + +### 安装到 profile + +组合包是 `dsh` 安装的运行时依赖,因此选中它既不需要 pnpm 也不需要网络: + +```sh +dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp +dsh plugin --profile cua-mcp disable @deepseek-ai/dsh-cua-mcp +``` + +`enable` 在 profile 缺失时从 `@deepseek-ai/dsh-base` 初始化它,并把本组合包追加到 `dsh.profile.bundles`;`disable` 移除该选择。源码 checkout 在 `pnpm run build` 之后通过 `pnpm dsh` 运行同样的命令。Python runtime wheel 自带同一份安装,训练 harness 可以自行写入 profile manifest,或通过 wheel 的可执行程序运行 `enable`,然后把该可执行程序用作 stdio 命令: + +```python +import json, os +from pathlib import Path +from deepseek_harness_runtime import resolve_bundled_launch_args + +home = Path(os.environ["DSH_HOME"]) +profile = home / "profiles" / "cua-mcp" +profile.mkdir(parents=True, exist_ok=True) +(profile / "package.json").write_text(json.dumps({ + "name": "dsh-profile-cua-mcp", "private": True, "dependencies": {}, + "dsh": {"profile": {"bundles": ["@deepseek-ai/dsh-base", "@deepseek-ai/dsh-cua-mcp"]}}, +})) +command = [*resolve_bundled_launch_args(), "--profile", "cua-mcp"] # the MCP stdio command +``` + +### 接入客户端 + +`dsh --profile cua-mcp` 就是 stdio 命令。`--help` 打印它自己的帮助;`--print-client-config codex|claude-code|json` 为当前安装和 Harness home 打印可直接使用的配置:一段 `~/.codex/config.toml` 片段、一条 `claude mcp add-json dsh_cua` 命令,或一份通用 `mcpServers` 文档。三者都嵌入绝对可执行路径、`DSH_HOME` 与当前 `DSH_CUA_CONSENT`。Codex 片段把 `startup_timeout_sec = 120` 留给首次 helper 准备,用 `tool_timeout_sec = 600` 对齐默认程序上限,让两个工具直接暴露而不进入工具搜索,并把 `cua_run_code` 的输出预算提高到 25,000 token。Codex 只有在 `approval_policy.granular.mcp_elicitations = true` 时才转发 elicitation。 + +```sh +dsh --profile cua-mcp --print-client-config codex >> ~/.codex/config.toml +dsh --profile cua-mcp --print-client-config claude-code | sh +``` + +在 macOS 上,profile 首次启动时准备已签名的 Computer Use helper,并需要为其授予辅助功能与屏幕录制权限;[macOS 提供方](../cua-macos/README.zh.md)负责这部分设置。在其他 Host 上 profile 没有提供方也能启动,两个工具都返回指出缺少提供方的错误。 + +### 你会得到什么 + +`cua_run_code` 通过提供方保留的 Node 环境,把一段 TypeScript 程序作为 REPL 语句对全局 `cua` 对象运行。结果以文本携带程序打印的行和最终表达式,随后把程序捕获的每张截图以内联图片附上,且图片正是程序观察到的那一版,因此文本中的像素坐标与图片一致。一个连接的首个结果以完整的 `cua_run_code` 执行规则和 `cua` API 参考开头;工具描述保持简短。`description` 可选,缺省为 `CUA program`;`timeoutMs` 限制单个程序。同一连接的程序按到达顺序逐个运行;取消调用会取消其程序。 + +`cua_reset` 丢弃程序环境:变量、导入以及应用或窗口对象。应用授权、本机连接和应用本身保留;下一个程序在新进程中启动,其结果重复 API 参考。在声明冲突或环境不可用之后使用它。 + +连接的 Agent 在客户端完成初始化时创建,在客户端关闭 stdin 时销毁,进程随之退出。应用授权按该 Agent 遵循 [CUA 授权规则](../cua/README.zh.md):`DSH_CUA_CONSENT=allow` 在无人值守下为本会话放行每个请求;默认的 `elicit` 把请求作为表单 elicitation 转发给客户端,答案即 CUA 的选项标签;被拒绝的表单为本会话记录一次拒绝,不支持 elicitation 的客户端会收到指明 `allow` 模式的错误。 + +----- + + +## 配置 + +在 profile 的 `cordis.patch.yml` 中配置 `cua-mcp` 行;组合包 patch 把 `DSH_CUA_CONSENT` 映射到它。 + +| 字段 | 默认值 | 含义 | +|---|---|---| +| `consent` | `elicit` | `allow` 在无人值守下为本会话放行应用与指针授权;`elicit` 把每个请求转发给 MCP 客户端。 | + +patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载提供方,因为这里没有模型路由来选择请求图片;并以 `agentPreset: ptc` 搭配空的 `cua-mcp` preset,使连接的 Agent 只获得 `cua_run_code` 而没有其他面向模型的行。可在 profile patch 中按 id 覆盖这些行。 + +----- + + +## 理解实现 + +
+实现细节 — 点击展开 + +[patch](cordis.patch.yml) 禁用 `dsh-base` 的标题、HMR、凭据、授权和账号行,插入带空默认 preset 的 preset 注册表、`computer-use` 注册表、在非 Darwin 上禁用的 macOS 提供方行,以及本前端。前端用 `parseCmdline` 解析调用,把 stdin EOF 绑定到启动器的有界关闭,并在启动器提交就绪后把官方 MCP 服务器连接到 stdio 传输。`cua-mcp` 是启动必需条目,前端无法激活时 profile 停止启动。 + +[`server.ts`](src/server.ts) 在一个 `McpServer` 上注册两个工具。连接的 Agent 挂载注册表的默认 preset 并记录启动目录。`cua_run_code` 带着 Agent 和请求 signal、不经模型步骤地通过 `ctx.tools.execute` 运行,因此 Session 日志只有嵌套的 `tool/ptc-dispatch` 事件而没有根 `tool/call`;[`projection.ts`](src/projection.ts) 渲染结果及其延后的截图上下文,并通过 `ctx.cuaPrograms.screenshotRequestTarget` 读取每张图片。`cua_reset` 调用 `ctx.cuaPrograms.reset`。[`consent.ts`](src/consent.ts) 是该 Agent 的 `user-questions/request` 应答者;[`client-config.ts`](src/client-config.ts) 渲染客户端片段。 + +
+ +----- + + +## 进一步探索 + +- [共享 CUA 包](../cua/README.zh.md) — 对象 API、授权规则与 `cua_run_code`。 +- [macOS 提供方](../cua-macos/README.zh.md) — helper 准备、权限与平台指引。 +- [计算机操作](../../../docs/subsystems/computer-use.zh.md)与 [MCP](../../../docs/subsystems/mcp.zh.md) — 子系统参考。 +- [profile 组合](../../boot/app-boot/README.zh.md) — 组合包层与 patch 生命周期。 +- [决策记录](../../../.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md) — 服务器为何运行在 profile 内并为每个连接持有一个 Agent。 + +----- + + +## 模型体验 + +### 外部 harness 的模型 + +#### 模型看到什么 + +接入 harness 的模型通过 `tools/list` 和 `initialize` 看到两个工具与服务器说明。一个连接的首个 `cua_run_code` 结果,以及 `cua_reset` 之后的首个结果,以 `cua_run_code` 执行规则和提供方注册的 `cua` API 参考开头;之后的结果只携带程序输出与捕获的截图。该 profile 中不存在 DSH 模型请求。 + +#### Token 影响 + +API 参考每个连接或每次重置增加约 11,000 个字符。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;生成的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。 + +#### KV Cache 影响 + +工具目录和说明对同一安装保持稳定。首个结果的参考文本只随已安装的 CUA 包变化。 + +## 已知限制与延后工作 + + + +- 只有 macOS Host 有提供方;Windows 提供方就位后在此挂载。其他 Host 的两个工具都返回错误。 +- Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。 +- 不暴露程序沙箱提权和原始 `cua` 工具;`DSH_PERMISSION_MODE` 选择程序进程启动时的文件沙箱。 +- 根工具调用不是 Session 事件;接入 harness 的 transcript 才是调用与结果的记录。 + + +### 开发备注 + +
+维护者工作上下文 — 点击展开 + +无。 + +
diff --git a/packages/experimental/cua-mcp/cordis.patch.yml b/packages/experimental/cua-mcp/cordis.patch.yml new file mode 100644 index 0000000000..3eace2f8f2 --- /dev/null +++ b/packages/experimental/cua-mcp/cordis.patch.yml @@ -0,0 +1,54 @@ +# The Computer Use MCP application over dsh-base. Stdout belongs exclusively to +# MCP JSON-RPC; one stdio connection owns one Agent whose cua_run_code programs +# retain state until the client disconnects or calls cua_reset. + +# No model turn ever runs in this profile: titles, credentials, and the account +# provider have no consumer, and configuration applies at startup only. +- id: session-title-llm + disabled: true + +- id: hmr + disabled: true + +- id: credentials + disabled: true + +- id: authorization + disabled: true + +- id: deepseek-account + disabled: true + +- insert: + # A composed preset selects cua_run_code for the connection's Agent; the + # empty preset keeps every model-facing row out of this profile. + - id: cua-mcp-presets + name: '@deepseek-ai/dsh-agent-preset-registry' + config: + default: cua-mcp + + - id: cua-mcp-preset + name: '@deepseek-ai/dsh-agent-preset' + config: + id: cua-mcp + plugins: [] + + - id: cua-mcp-computer-use + name: '@deepseek-ai/dsh-computer-use' + + # Screenshots target a fixed request image because no model route exists here. + - id: cua-mcp-provider + name: '@deepseek-ai/dsh-experimental-cua-macos' + disabled: !!js process.platform !== 'darwin' + config: + agentPreset: ptc + screenshotTarget: + longEdge: 2048 + maxBytes: 2097152 + + # DSH_CUA_CONSENT=allow grants application and pointer access without a human; + # the default forwards each request to the MCP client as an elicitation. + - id: cua-mcp + name: '@deepseek-ai/dsh-cua-mcp' + config: + consent: !!js process.env.DSH_CUA_CONSENT ?? 'elicit' diff --git a/packages/experimental/cua-mcp/icon.svg b/packages/experimental/cua-mcp/icon.svg new file mode 100644 index 0000000000..b475396eee --- /dev/null +++ b/packages/experimental/cua-mcp/icon.svg @@ -0,0 +1,42 @@ + + + + + + + + + + + + + + + + + + + + + + + diff --git a/packages/experimental/cua-mcp/locale/de.json b/packages/experimental/cua-mcp/locale/de.json new file mode 100644 index 0000000000..d78ce75872 --- /dev/null +++ b/packages/experimental/cua-mcp/locale/de.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "MCP-Server für Computernutzung", + "description": "Stellt Computer Use aus dem Profil cua-mcp für Codex, Claude Code und andere MCP-Clients bereit: cua_run_code führt persistente Programme gegen Desktop-Anwendungen aus, cua_reset löscht sie." + } +} diff --git a/packages/experimental/cua-mcp/locale/en.json b/packages/experimental/cua-mcp/locale/en.json new file mode 100644 index 0000000000..4ad0f8be74 --- /dev/null +++ b/packages/experimental/cua-mcp/locale/en.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Computer use MCP server", + "description": "Serve Computer Use to Codex, Claude Code, and other MCP clients from the cua-mcp profile: cua_run_code runs persistent programs against desktop applications, and cua_reset clears them." + } +} diff --git a/packages/experimental/cua-mcp/locale/es.json b/packages/experimental/cua-mcp/locale/es.json new file mode 100644 index 0000000000..23b6cc07b0 --- /dev/null +++ b/packages/experimental/cua-mcp/locale/es.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Servidor MCP de uso del ordenador", + "description": "Ofrece Computer Use a Codex, Claude Code y otros clientes MCP desde el perfil cua-mcp: cua_run_code ejecuta programas persistentes sobre aplicaciones de escritorio y cua_reset los borra." + } +} diff --git a/packages/experimental/cua-mcp/locale/fr.json b/packages/experimental/cua-mcp/locale/fr.json new file mode 100644 index 0000000000..e87079d489 --- /dev/null +++ b/packages/experimental/cua-mcp/locale/fr.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Serveur MCP d’utilisation de l’ordinateur", + "description": "Fournit Computer Use à Codex, Claude Code et d’autres clients MCP depuis le profil cua-mcp : cua_run_code exécute des programmes persistants sur les applications de bureau et cua_reset les efface." + } +} diff --git a/packages/experimental/cua-mcp/locale/ja.json b/packages/experimental/cua-mcp/locale/ja.json new file mode 100644 index 0000000000..130dc7a1b2 --- /dev/null +++ b/packages/experimental/cua-mcp/locale/ja.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Computer Use MCP サーバー", + "description": "cua-mcp プロファイルから Codex、Claude Code などの MCP クライアントに Computer Use を提供します。cua_run_code はデスクトップアプリに対して永続的なプログラムを実行し、cua_reset はそれをクリアします。" + } +} diff --git a/packages/experimental/cua-mcp/locale/pt.json b/packages/experimental/cua-mcp/locale/pt.json new file mode 100644 index 0000000000..c0ea83fd43 --- /dev/null +++ b/packages/experimental/cua-mcp/locale/pt.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Servidor MCP de uso do computador", + "description": "Disponibiliza o Computer Use para Codex, Claude Code e outros clientes MCP a partir do perfil cua-mcp: cua_run_code executa programas persistentes em aplicativos de desktop e cua_reset os apaga." + } +} diff --git a/packages/experimental/cua-mcp/locale/ru.json b/packages/experimental/cua-mcp/locale/ru.json new file mode 100644 index 0000000000..8a76c77019 --- /dev/null +++ b/packages/experimental/cua-mcp/locale/ru.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "MCP-сервер управления компьютером", + "description": "Предоставляет Computer Use клиентам MCP, включая Codex и Claude Code, из профиля cua-mcp: cua_run_code выполняет постоянные программы для настольных приложений, а cua_reset очищает их." + } +} diff --git a/packages/experimental/cua-mcp/locale/zh.json b/packages/experimental/cua-mcp/locale/zh.json new file mode 100644 index 0000000000..c7a6ef179f --- /dev/null +++ b/packages/experimental/cua-mcp/locale/zh.json @@ -0,0 +1,6 @@ +{ + "meta": { + "title": "Computer Use MCP 服务器", + "description": "通过 cua-mcp profile 向 Codex、Claude Code 等 MCP 客户端提供 Computer Use:cua_run_code 对桌面应用运行持久程序,cua_reset 清空程序环境。" + } +} diff --git a/packages/experimental/cua-mcp/package.json b/packages/experimental/cua-mcp/package.json new file mode 100644 index 0000000000..3174453057 --- /dev/null +++ b/packages/experimental/cua-mcp/package.json @@ -0,0 +1,91 @@ +{ + "name": "@deepseek-ai/dsh-cua-mcp", + "description": "Computer Use as an MCP stdio server: a dsh profile bundle that exposes cua_run_code to external agent harnesses", + "version": "0.2.2-rc.1", + "icon": "./icon.svg", + "publishConfig": { + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/deepseek-ai/deepseek-harness.git", + "directory": "packages/experimental/cua-mcp" + }, + "type": "module", + "main": "lib/index.js", + "types": "lib/types/index.d.ts", + "exports": { + ".": { + "types": "./lib/types/index.d.ts", + "default": "./lib/index.js" + }, + "./cordis.patch.yml": "./cordis.patch.yml", + "./locale/*.json": "./locale/*.json", + "./src/*": "./src/*", + "./package.json": "./package.json" + }, + "files": [ + "icon.svg", + "locale/*.json", + "lib/index.js", + "cordis.patch.yml", + "lib/types/**/*.d.ts", + "lib/types/**/*.d.ts.map", + "lib/**/*.js.map", + "src" + ], + "license": "MIT", + "dsh": { + "bundle": { + "patch": "./cordis.patch.yml" + } + }, + "peerDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-app-boot": "workspace:*" + }, + "dependencies": { + "@deepseek-ai/dsh-agent-preset": "workspace:*", + "@deepseek-ai/dsh-agent-preset-registry": "workspace:*", + "@deepseek-ai/dsh-cmdline": "workspace:*", + "@deepseek-ai/dsh-computer-use": "workspace:*", + "@deepseek-ai/dsh-cua": "workspace:*", + "@deepseek-ai/dsh-llm": "workspace:*", + "@deepseek-ai/dsh-session": "workspace:*", + "@deepseek-ai/dsh-user-questions": "workspace:*", + "@deepseek-ai/schemastery": "workspace:~", + "@modelcontextprotocol/server": "2.2.0", + "commander": "^15.0.0", + "zod": "4.6.6" + }, + "optionalDependencies": { + "@deepseek-ai/dsh-experimental-cua-macos": "workspace:*" + }, + "devDependencies": { + "@deepseek-ai/cordis": "workspace:~", + "@deepseek-ai/cordis-plugin-include": "workspace:~", + "@deepseek-ai/cordis-plugin-loader": "workspace:~", + "@deepseek-ai/dsh-agent": "workspace:*", + "@deepseek-ai/dsh-agent-loop": "workspace:*", + "@deepseek-ai/dsh-app-boot": "workspace:*", + "@deepseek-ai/dsh-attachment": "workspace:*", + "@deepseek-ai/dsh-attachment-local": "workspace:*", + "@deepseek-ai/dsh-brand": "workspace:*", + "@deepseek-ai/dsh-fs-local": "workspace:*", + "@deepseek-ai/dsh-ptc-runtime-node": "workspace:*", + "@deepseek-ai/dsh-sandbox-local": "workspace:*", + "@deepseek-ai/dsh-sandbox-policy": "workspace:*", + "@deepseek-ai/dsh-session-projection": "workspace:*", + "@deepseek-ai/dsh-subprocess-local": "workspace:*", + "@deepseek-ai/dsh-system-prompt": "workspace:*", + "@deepseek-ai/dsh-tool-executor-native": "workspace:*", + "@deepseek-ai/dsh-tools": "workspace:*", + "@deepseek-ai/dsh-working-directory": "workspace:*", + "@modelcontextprotocol/client": "2.2.0", + "js-yaml": "^4.3.2" + } +} diff --git a/packages/experimental/cua-mcp/src/client-config.ts b/packages/experimental/cua-mcp/src/client-config.ts new file mode 100644 index 0000000000..22e75fcb16 --- /dev/null +++ b/packages/experimental/cua-mcp/src/client-config.ts @@ -0,0 +1,119 @@ +/** Client configuration snippets for the Computer Use MCP server. @module */ +import type { ProfileContext } from '@deepseek-ai/dsh-app-boot' +import type { ConsentMode } from './consent.ts' + +/** Clients with a generated configuration. */ +export type ClientConfigTarget = 'codex' | 'claude-code' | 'json' + +/** Every client target, in the order help lists them. */ +export const CLIENT_CONFIG_TARGETS: readonly ClientConfigTarget[] = ['codex', 'claude-code', 'json'] + +/** MCP server name clients address; external tool names become `mcp__dsh_cua__cua_run_code` in Claude Code. */ +export const MCP_SERVER_NAME = 'dsh_cua' + +/** The exact stdio command a client runs to start this profile. */ +export interface ClientLaunch { + /** Absolute executable path. */ + readonly command: string + /** Arguments in order, ending with the profile selection. */ + readonly args: readonly string[] + /** Environment the client passes to the process. */ + readonly env: Readonly> + /** Shell command that installs the profile once; rendered as a comment where the format allows one. */ + readonly setup: string +} + +/** The process facts a generated client configuration embeds. */ +export interface LaunchFacts { + readonly execPath: string + readonly execArgv: readonly string[] + readonly argv: readonly string[] + /** Whether this process is a single-file executable, which takes no script argument. */ + readonly sea: boolean +} + +/** + * Resolve the stdio command a client runs to reach this exact installation and profile. + * @param facts - Current process executable, Node options, and arguments. + * @param profile - Launched profile. + * @param consent - Consent mode the generated environment pins. + * @returns Absolute command, arguments, environment, and the one-time profile setup command. + * @throws Error when a script-launched process has no script argument. + */ +export function clientLaunch(facts: LaunchFacts, profile: Pick, consent: ConsentMode): ClientLaunch { + const selection = ['--profile', profile.name] + const script = facts.argv[1] + if (!facts.sea && script === undefined) throw new Error('cua-mcp: the launching script is unknown, so no client command can be generated') + return { + command: facts.execPath, + args: facts.sea ? selection : [...facts.execArgv, script as string, ...selection], + env: { DSH_HOME: profile.home, DSH_CUA_CONSENT: consent }, + setup: `dsh plugin --profile ${profile.name} enable @deepseek-ai/dsh-cua-mcp`, + } +} + +/** Per-call limit a client should allow; the default `cua_run_code` maximum timeout is ten minutes. */ +const TOOL_TIMEOUT_SECONDS = 600 +/** Startup allowance covering first-run native helper preparation on macOS. */ +const STARTUP_TIMEOUT_SECONDS = 120 +/** Output budget matching the Claude Code default and the Codex Computer Use plugin. */ +const OUTPUT_TOKEN_LIMIT = 25_000 + +function tomlString(value: string): string { + return JSON.stringify(value) +} + +function tomlInlineTable(values: Readonly>): string { + return `{ ${Object.entries(values).map(([key, value]) => `${key} = ${tomlString(value)}`).join(', ')} }` +} + +/** + * Render the configuration an MCP client needs to run this server. + * @param target - Client whose configuration format is rendered. + * @param launch - Resolved stdio command of this installation and profile. + * @returns Complete text ending with one newline: a TOML fragment for Codex, a `claude mcp add-json` command + * for Claude Code, or a generic `mcpServers` JSON document. + */ +export function renderClientConfig(target: ClientConfigTarget, launch: ClientLaunch): string { + const entry = { + type: 'stdio' as const, + command: launch.command, + args: [...launch.args], + env: { ...launch.env }, + } + switch (target) { + case 'codex': + return [ + `# ~/.codex/config.toml — run once first: ${launch.setup}`, + `[mcp_servers.${MCP_SERVER_NAME}]`, + `command = ${tomlString(launch.command)}`, + `args = [${launch.args.map(tomlString).join(', ')}]`, + `env = ${tomlInlineTable(launch.env)}`, + `startup_timeout_sec = ${String(STARTUP_TIMEOUT_SECONDS)}`, + `tool_timeout_sec = ${String(TOOL_TIMEOUT_SECONDS)}`, + 'enabled_tools = ["cua_run_code", "cua_reset"]', + 'omit_tools_from = ["code_mode", "deferred"]', + '# default_tools_approval_mode = "auto"', + '', + `[mcp_servers.${MCP_SERVER_NAME}.tools.cua_run_code]`, + `output_token_limit = ${String(OUTPUT_TOKEN_LIMIT)}`, + '', + ].join('\n') + case 'claude-code': { + const json = JSON.stringify({ ...entry, timeout: TOOL_TIMEOUT_SECONDS * 1000, alwaysLoad: true }) + return [ + `# run once first: ${launch.setup}`, + `claude mcp add-json ${MCP_SERVER_NAME} '${json.replaceAll("'", String.raw`'\''`)}'`, + '', + ].join('\n') + } + case 'json': + return `${JSON.stringify({ mcpServers: { [MCP_SERVER_NAME]: entry } }, null, 2)}\n` + default: + return assertNever(target) + } +} + +function assertNever(value: never): never { + throw new Error(`unknown client configuration target ${String(value)}`) +} diff --git a/packages/experimental/cua-mcp/src/consent.ts b/packages/experimental/cua-mcp/src/consent.ts new file mode 100644 index 0000000000..472d335b72 --- /dev/null +++ b/packages/experimental/cua-mcp/src/consent.ts @@ -0,0 +1,115 @@ +/** Consent answerer for the connection's Agent: unattended approval or MCP elicitation. @module */ +import type { Agent } from '@deepseek-ai/dsh-agent' +import { UserQuestionError, type AskUserQuestionAnswer, type AskUserQuestionItem } from '@deepseek-ai/dsh-user-questions' +import type { ElicitResult } from '@modelcontextprotocol/server' + +/** Who decides application and pointer consent for the connection's Agent. */ +export type ConsentMode = 'allow' | 'elicit' + +/** Every consent mode, in the order the configuration documents them. */ +export const CONSENT_MODES: readonly ConsentMode[] = ['allow', 'elicit'] + +/** The MCP client side of an elicitation round trip. */ +export interface ElicitationClient { + /** Whether the connected client declared the `elicitation` capability. */ + supportsElicitation(): boolean + /** + * Ask the client to collect one decision from its user. + * @param message - Question and detail for the user. + * @param labels - Offered answers, in display order. + * @param signal - Cancels the pending request. + * @returns The client's action and its selected label. + */ + elicit(message: string, labels: readonly string[], signal: AbortSignal | undefined): Promise +} + +/** Option labels of one question, in display order. */ +function labelsOf(question: AskUserQuestionItem): string[] { + return (question.options ?? []).map(option => option.label) +} + +/** + * Answer one CUA approval question without a human: the label its intent approves. + * @param questions - Questions of one request. + * @returns The answer, or undefined when a question is not an approval decision. + */ +export function approveAll(questions: readonly AskUserQuestionItem[]): AskUserQuestionAnswer | undefined { + const answers: AskUserQuestionAnswer['answers'] = [] + for (const question of questions) { + if (question.intent?.kind !== 'approval') return undefined + answers.push({ id: question.id, selected: [question.intent.approve] }) + } + return { answers } +} + +/** + * Forward one question to the MCP client as a form elicitation and translate its outcome. + * Decline selects the rejecting label of an approval question; cancel aborts the ask the way a dismissed + * card does, so the provider records a denial for this Agent. + * @param client - Connected MCP client. + * @param question - The question to present. + * @param signal - Cancels the pending request. + * @returns The chosen label as a user-questions answer. + * @throws UserQuestionError with code `ASK_CANCELLED` when the user cancels. + * @throws Error when the client lacks elicitation or returns no offered label. + */ +export async function elicitAnswer( + client: ElicitationClient, question: AskUserQuestionItem, signal: AbortSignal | undefined, +): Promise { + if (!client.supportsElicitation()) { + throw new Error('The connected MCP client does not support elicitation, so nobody can grant this request; ' + + 'start the server with DSH_CUA_CONSENT=allow to grant application and pointer access without a human') + } + const labels = labelsOf(question) + const message = question.detail === undefined ? question.question : `${question.question}\n\n${question.detail}` + const result = await client.elicit(message, labels, signal) + switch (result.action) { + case 'accept': { + const decision = result.content?.decision + if (typeof decision !== 'string' || !labels.includes(decision)) { + throw new Error(`The MCP client accepted the consent request without one of the offered answers: ${JSON.stringify(labels)}`) + } + return { id: question.id, selected: [decision] } + } + case 'decline': + if (question.intent?.kind === 'approval') return { id: question.id, selected: [question.intent.reject] } + throw new UserQuestionError('The MCP client declined the request', 'ASK_CANCELLED') + case 'cancel': + throw new UserQuestionError('The MCP client cancelled the request', 'ASK_CANCELLED') + default: + return assertNever(result.action) + } +} + +function assertNever(value: never): never { + throw new Error(`unknown elicitation action ${String(value)}`) +} + +/** A user-questions waterfall listener bound to one connection's Agent. */ +export type ConsentAnswerer = ( + request: { questions: AskUserQuestionItem[]; agent?: Agent; signal?: AbortSignal }, + next: () => Promise, +) => Promise + +/** + * Build the answerer for one connection. Requests of other Agents and non-approval questions in `allow` + * mode delegate to the next answerer. + * @param mode - Configured consent mode. + * @param owns - Whether a request's Agent is this connection's Agent. + * @param client - Elicitation side of the connected MCP client. + * @returns The waterfall listener. + */ +export function createConsentAnswerer( + mode: ConsentMode, owns: (agent: Agent | undefined) => boolean, client: ElicitationClient, +): ConsentAnswerer { + return async (request, next) => { + if (!owns(request.agent)) return next() + if (mode === 'allow') { + const answer = approveAll(request.questions) + return answer ?? next() + } + const answers: AskUserQuestionAnswer['answers'] = [] + for (const question of request.questions) answers.push(await elicitAnswer(client, question, request.signal)) + return { answers } + } +} diff --git a/packages/experimental/cua-mcp/src/index.ts b/packages/experimental/cua-mcp/src/index.ts new file mode 100644 index 0000000000..93aa266191 --- /dev/null +++ b/packages/experimental/cua-mcp/src/index.ts @@ -0,0 +1,93 @@ +/** + * The Computer Use MCP stdio application: a profile bundle over dsh-base whose one frontend serves + * `cua_run_code` and `cua_reset` to an external MCP client. Help and `--print-client-config` exit without + * claiming stdio; a served connection owns one Agent until the client closes stdin. + * @module @deepseek-ai/dsh-cua-mcp + */ +import { isSea } from 'node:sea' +import type { Context } from '@deepseek-ai/cordis' +import Schema from '@deepseek-ai/schemastery' +import type {} from '@deepseek-ai/dsh-app-boot' +import { exitOnStdinEnd, internals, parseCmdline } from '@deepseek-ai/dsh-cmdline' +import { StdioServerTransport } from '@modelcontextprotocol/server/stdio' +import { Command, Option } from 'commander' +import { CLIENT_CONFIG_TARGETS, clientLaunch, renderClientConfig, type ClientConfigTarget, type LaunchFacts } from './client-config.ts' +import type { ConsentMode } from './consent.ts' +import { createCuaMcpServer } from './server.ts' + +/** Cordis frontend identity. */ +export const name = 'cua-mcp' +/** Launcher facts and the Agent, preset, tool, prompt, and attachment services a served connection uses. */ +export const inject = ['cmdlineArgs', 'appReady', 'appExit', 'profileContext', 'agents', 'agentPresets', 'tools', 'systemPrompt', 'attachments'] + +/** Connection policy configurable from the profile patch. */ +export interface Config { + /** + * Who grants application and pointer consent for the connection's Agent: `allow` grants every request for + * this session without a human; `elicit` forwards each request to the MCP client as a form elicitation. + */ + consent: ConsentMode +} + +/** Validate the consent mode; the bundle patch maps `DSH_CUA_CONSENT` onto it. */ +export const Config: Schema, Config> = Schema.object({ + consent: Schema.union([Schema.const('allow'), Schema.const('elicit')]).default('elicit'), +}) + +/** + * Accept the profile invocation, print a client configuration on request, or serve MCP over stdio once the + * launcher commits readiness. Stdin EOF ends the process through the launcher's bounded shutdown. + * @param ctx - Profile context carrying the command line, readiness, exit request, and profile identity. + * @param config - Validated consent mode. + * @throws Error when the plugin runs outside the dsh profile launcher. + */ +export function apply(ctx: Context, config: Config): void { + const ready = ctx.get('appReady') + const exit = ctx.get('appExit') + const profile = ctx.get('profileContext') + if (ready === undefined || exit === undefined || profile === undefined) throw new Error('Computer Use MCP requires the dsh profile launcher') + const commandName = `dsh --profile ${profile.name}` + const program = new Command(commandName) + .description('Serve DeepSeek Harness Computer Use to an MCP client over stdio.') + .addOption(new Option('--print-client-config ', 'print the MCP client configuration for this installation and exit') + .choices([...CLIENT_CONFIG_TARGETS])) + .addHelpText('after', ` +Examples: + ${commandName} serve one MCP client until it closes stdin + ${commandName} --print-client-config codex print a ~/.codex/config.toml fragment + DSH_CUA_CONSENT=allow ${commandName} grant application access without a human +`) + let accepted: { print: ClientConfigTarget | undefined } | undefined + program.action(() => { + accepted = { print: program.opts<{ printClientConfig?: ClientConfigTarget }>().printClientConfig } + }) + parseCmdline(ctx, program) + if (accepted === undefined) return + if (accepted.print !== undefined) { + const facts: LaunchFacts = { execPath: process.execPath, execArgv: process.execArgv, argv: process.argv, sea: isSea() } + internals.stdout.write(renderClientConfig(accepted.print, clientLaunch(facts, profile, config.consent))) + exit(0) + return + } + exitOnStdinEnd(ctx, 'cua-mcp: stdin') + ctx.effect(() => { + const lifetime = new AbortController() + const adapter = createCuaMcpServer(ctx, { consent: config.consent, cwd: profile.cwd, signal: lifetime.signal }) + let opening: Promise | undefined + const stopReady = ready.onReady(() => { + opening = adapter.server.connect(new StdioServerTransport()) + void opening.catch((error: unknown) => { + if (!lifetime.signal.aborted) { + ctx.logger.error('MCP startup failed: %s', error) + exit(1) + } + }) + }) + return async () => { + stopReady() + lifetime.abort() + await opening?.catch(() => undefined) + await adapter.dispose() + } + }, 'cua-mcp: server') +} diff --git a/packages/experimental/cua-mcp/src/projection.ts b/packages/experimental/cua-mcp/src/projection.ts new file mode 100644 index 0000000000..45a96da810 --- /dev/null +++ b/packages/experimental/cua-mcp/src/projection.ts @@ -0,0 +1,58 @@ +/** MCP projection of one DSH tool execution: text passes through, screenshots become inline images. @module */ +import type { AttachmentStore, ImageAttachmentRef, ImageRequestTarget } from '@deepseek-ai/dsh-attachment' +import type { ContentBlock, UserMessage } from '@deepseek-ai/dsh-llm' +import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' +import type { CallToolResult } from '@modelcontextprotocol/server' + +/** Image delivery for one projection: the request version the program observed, or the stored image. */ +export interface ScreenshotDelivery { + /** Store that owns the durable screenshots; only its two image reads are used. */ + readonly attachments: Pick + /** Fixed request target of a screenshot, or undefined to deliver the stored normalized image. */ + readonly target: (image: ImageAttachmentRef) => ImageRequestTarget | undefined +} + +/** One text block preceding the projected result. */ +function text(value: string): CallToolResult['content'][number] { + return { type: 'text', text: value } +} + +/** + * Project a settled `cua_run_code` or `cua_reset` outcome onto an MCP call result. + * Result text keeps the model-facing rendering; images deferred by nested screenshot calls follow it, in + * capture order, as inline Base64 blocks of the version the program observed, so pixel coordinates in the + * program's text match the delivered image. Other block kinds are named, not rendered. + * @param result - Settled DSH execution outcome. + * @param deferred - Deferred context messages the execution produced, in order. + * @param delivery - Attachment store and the provider's request target. + * @param signal - Cancels pending image reads. + * @param preface - Text blocks placed before the projected result, such as the API reference. + * @returns The MCP result; `isError` mirrors the DSH outcome. + */ +export async function projectToolResult( + result: ToolExecutionResult, deferred: readonly UserMessage[], delivery: ScreenshotDelivery, + signal: AbortSignal, preface: readonly string[] = [], +): Promise { + const content: CallToolResult['content'] = preface.map(text) + const blocks: ContentBlock[] = [...result.content, ...deferred.flatMap(message => message.content)] + for (const block of blocks) { + switch (block.type) { + case 'text': + content.push(text(block.text)) + break + case 'image': { + const target = delivery.target(block.attachment) + const image = target === undefined + ? await delivery.attachments.readImage(block.attachment, signal) + .then(stored => ({ data: stored.data, mediaType: stored.ref.mediaType })) + : await delivery.attachments.readImageRequest(block.attachment, target, signal) + content.push({ type: 'image', data: Buffer.from(image.data).toString('base64'), mimeType: image.mediaType }) + break + } + default: + // Merge-extensible block kinds without an MCP rendering are named so the caller sees the omission. + content.push(text(`[${block.type} content omitted]`)) + } + } + return result.isError ? { content, isError: true } : { content } +} diff --git a/packages/experimental/cua-mcp/src/server.ts b/packages/experimental/cua-mcp/src/server.ts new file mode 100644 index 0000000000..3dd5a20b73 --- /dev/null +++ b/packages/experimental/cua-mcp/src/server.ts @@ -0,0 +1,208 @@ +/** One MCP connection projected onto one DSH Agent that runs Computer Use programs. @module */ +import { randomUUID } from 'node:crypto' +import { createRequire } from 'node:module' +import type { Context } from '@deepseek-ai/cordis' +import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent' +import type {} from '@deepseek-ai/dsh-agent-preset-registry' +import type {} from '@deepseek-ai/dsh-attachment' +import type {} from '@deepseek-ai/dsh-cua' +import { CUA_PROMPT_SECTION_NAME } from '@deepseek-ai/dsh-cua/guidance' +import { ToolCallId } from '@deepseek-ai/dsh-llm' +import { SessionId } from '@deepseek-ai/dsh-session' +import type {} from '@deepseek-ai/dsh-system-prompt' +import type {} from '@deepseek-ai/dsh-tools' +import { McpServer, type CallToolResult } from '@modelcontextprotocol/server' +import { z } from 'zod' +import { MCP_SERVER_NAME } from './client-config.ts' +import { createConsentAnswerer, type ConsentMode, type ElicitationClient } from './consent.ts' +import { projectToolResult } from './projection.ts' + +/** Connection policy and lifetime. */ +export interface CuaMcpServerOptions { + /** Who decides application and pointer consent for the connection's Agent. */ + readonly consent: ConsentMode + /** Absolute working directory recorded on the connection's Session. */ + readonly cwd: string + /** Server lifetime; abort cancels every in-flight program before disposal. */ + readonly signal: AbortSignal +} + +/** The protocol server and the disposer that releases its Agent. */ +export interface CuaMcpServer { + readonly server: McpServer + /** + * Close the protocol connection, let in-flight calls settle, and dispose the connection's Agent, which + * releases its program environment, native connections, and session-scoped application grants. + * @returns After the Agent and its retained resources are released. + */ + dispose(): Promise +} + +/** Programs run against the global `cua` object; the result repeats the API reference after a reset. */ +const RUN_CODE_DESCRIPTION = 'Run a TypeScript program that observes and operates desktop applications through the global ' + + '`cua` object: select an application, read its accessibility tree, capture window screenshots, click, and type. ' + + 'The program is a sequence of TypeScript REPL statements: top-level `await` works, top-level `return` does not. ' + + 'Only `console.log(...)` output and the value of the final expression come back, followed by every screenshot the ' + + 'program captured as an image. Variables, imported modules, and application or window objects stay in memory for ' + + 'this connection across calls until cua_reset. The first result of a connection starts with the complete `cua` API reference.' + +const RESET_DESCRIPTION = 'Discard the program environment of this connection: every variable, import, and application or ' + + 'window object held by earlier cua_run_code calls. Application access grants and the desktop applications themselves ' + + 'are unaffected; the next cua_run_code call starts a fresh environment and its result repeats the `cua` API reference. ' + + 'Use it when a declaration conflicts with an earlier call or the environment has become unusable.' + +const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. ' + + 'Call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls ' + + 'on this connection. The first result includes the complete cua API reference; read it before planning further ' + + 'calls. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state.' + +/** Label DSH records for a program when the client supplies none. */ +const DEFAULT_PROGRAM_DESCRIPTION = 'CUA program' + +const RUN_CODE_INPUT = z.object({ + code: z.string().min(1).describe('TypeScript REPL statements that use the global cua object; the final expression is returned.'), + description: z.string().min(1).optional().describe('Short label of what the program does; omitted records "CUA program".'), + timeoutMs: z.number().int().positive().optional() + .describe('Elapsed-time budget in milliseconds for this program, including nested cua calls; omitted uses the profile default.'), +}) + +const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. ' + + 'Run the server on a supported macOS Host.' + +function text(value: string): CallToolResult { + return { content: [{ type: 'text', text: value }] } +} + +function failure(value: string): CallToolResult { + return { content: [{ type: 'text', text: value }], isError: true } +} + +/** + * Create the MCP server for one stdio connection. The connection's Agent is created when the client finishes + * initialization or on its first call, mounts the profile's default preset, and lives until disposal. + * `cua_run_code` calls run one at a time in arrival order through the ordinary tool executor; `cua_reset` + * bypasses the queue and cancels the running program. Consent questions of that Agent are answered by the + * configured mode. + * @param ctx - Profile context with Agents, presets, tools, the system prompt, and the attachment store. + * @param options - Consent mode, working directory, and lifetime. + * @returns The protocol server, not yet connected to a transport, and its disposer. + */ +export function createCuaMcpServer(ctx: Context, options: CuaMcpServerOptions): CuaMcpServer { + const manifest = createRequire(import.meta.url)('../package.json') as { version: string } + const server = new McpServer({ name: MCP_SERVER_NAME, version: manifest.version }, { + capabilities: { tools: { listChanged: false } }, + instructions: INSTRUCTIONS, + }) + let agent: Agent | undefined + let creating: Promise | undefined + const connectionAgent = (): Promise => { + creating ??= ctx.agents.create({ + sessionId: SessionId(`cua-mcp-${randomUUID()}`), + meta: { cwd: options.cwd, agentPreset: ctx.agentPresets.defaultId }, + setup: async (agentCtx) => { await ctx.agentPresets.mount(agentCtx) }, + }).then((handle) => { + agent = handle.agent + return handle + }, (error: unknown) => { + creating = undefined + throw error + }) + return creating + } + server.server.oninitialized = () => { + void connectionAgent().catch((error: unknown) => { ctx.logger.error('Computer Use Agent creation failed: %s', error) }) + } + const elicitation: ElicitationClient = { + // Consent rides the 2025 server-to-client request model; the per-request envelope exists only on + // 2026-07-28 connections, which the README excludes, and such a client receives the thrown error. + // oxlint-disable-next-line typescript/no-deprecated -- 2025-era accessor, see above. + supportsElicitation: () => server.server.getClientCapabilities()?.elicitation !== undefined, + // oxlint-disable-next-line typescript/no-deprecated -- 2025-era request, see above. + elicit: (message, labels, signal) => server.server.elicitInput({ + mode: 'form', message, + requestedSchema: { type: 'object', properties: { decision: { type: 'string', title: 'Decision', enum: [...labels] } }, required: ['decision'] }, + }, signal === undefined ? {} : { signal }), + } + const unregisterAnswerer = ctx.on('user-questions/request', + createConsentAnswerer(options.consent, candidate => candidate !== undefined && candidate === agent, elicitation)) + + let referenceSent = false + let calls = 0 + let queue: Promise = Promise.resolve() + const serialize = (run: () => Promise): Promise => { + const next = queue.then(run, run) + queue = next.catch(() => undefined) + return next + } + /** Execution rules and the operation reference the provider registered for this Agent. */ + const apiReference = async (subject: Agent): Promise => { + const definition = ctx.tools.get('cua_run_code', subject) + const assembly = await ctx.systemPrompt.assemble({ scope: subject }) + const guidance = assembly.sections.find(section => section.name === CUA_PROMPT_SECTION_NAME)?.text + return [ + ...definition === undefined ? [] : ['## cua_run_code execution rules', definition.description], + ...guidance === undefined ? [] : ['## cua API reference', guidance], + ].join('\n\n') + } + const runProgram = async (args: z.infer, signal: AbortSignal): Promise => { + const programs = ctx.get('cuaPrograms') + if (programs === undefined) return failure(NO_PROVIDER) + const subject = (await connectionAgent()).agent + signal.throwIfAborted() + const preface: string[] = [] + if (!referenceSent) { + const reference = await apiReference(subject) + if (reference !== '') preface.push(reference) + referenceSent = true + } + const batch = await ctx.tools.execute({ + calls: [{ + type: 'tool-call', id: ToolCallId(`cua-mcp-${String(++calls)}`), name: 'cua_run_code', + arguments: JSON.stringify({ + code: args.code, description: args.description ?? DEFAULT_PROGRAM_DESCRIPTION, + ...args.timeoutMs === undefined ? {} : { timeoutMs: args.timeoutMs }, + }), + }], + agent: subject, signal, + }) + const outcome = batch.results[0] + if (outcome === undefined) throw new Error('The tool executor settled without a cua_run_code result') + return projectToolResult(outcome.result, batch.additionalContexts, { + attachments: ctx.attachments, target: image => programs.screenshotRequestTarget(image), + }, signal, preface) + } + + server.registerTool('cua_run_code', { + title: 'Computer use program', description: RUN_CODE_DESCRIPTION, inputSchema: RUN_CODE_INPUT, + annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true }, + }, (args, extra) => serialize(() => runProgram(args, AbortSignal.any([options.signal, extra.mcpReq.signal])))) + + server.registerTool('cua_reset', { + title: 'Reset computer use program state', description: RESET_DESCRIPTION, inputSchema: z.object({}), + annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false }, + }, async () => { + const programs = ctx.get('cuaPrograms') + if (programs === undefined) return failure(NO_PROVIDER) + const subject = (await connectionAgent()).agent + try { + await programs.reset(subject) + } catch (error) { + return failure(error instanceof Error ? error.message : String(error)) + } + referenceSent = false + return text('Program environment cleared. Application access and native connections are retained; ' + + 'the next cua_run_code call starts a fresh environment and repeats the cua API reference.') + }) + + return { + server, + async dispose() { + unregisterAnswerer() + await server.close() + await queue + if (creating === undefined) return + const handle = await creating.catch(() => undefined) + await handle?.dispose() + }, + } +} diff --git a/packages/experimental/cua-mcp/tests/bundle.spec.ts b/packages/experimental/cua-mcp/tests/bundle.spec.ts new file mode 100644 index 0000000000..5ca3adfb9a --- /dev/null +++ b/packages/experimental/cua-mcp/tests/bundle.spec.ts @@ -0,0 +1,74 @@ +/** The bundle's manifest and patch: a standalone profile frontend over dsh-base with a fixed-target CUA provider. */ +import { readFileSync, readdirSync } from 'node:fs' +import { resolve } from 'node:path' +import { fileURLToPath } from 'node:url' +import { entryListSchema } from '@deepseek-ai/cordis-plugin-include' +import type { EntryOptions } from '@deepseek-ai/cordis-plugin-loader' +import { interpolate } from '@deepseek-ai/cordis-plugin-loader' +import { load } from 'js-yaml' +import { describe, expect, it } from 'vitest' + +const root = fileURLToPath(new URL('..', import.meta.url)) + +interface Manifest { + name: string + publishConfig: { access: string } + icon: string + exports: Record + dsh: { bundle: { patch: string; platforms?: string[] } } + dependencies: Record + optionalDependencies: Record +} + +const manifest = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8')) as Manifest +const patches = load(readFileSync(resolve(root, manifest.dsh.bundle.patch), 'utf8'), { schema: entryListSchema }) as Array< + { id?: string; disabled?: unknown; insert?: EntryOptions[] } +> +const inserted = patches.flatMap(patch => patch.insert ?? []) + +describe('cua-mcp bundle', () => { + it('publishes an unprefixed experimental bundle that every Host installs and only macOS serves', () => { + expect(manifest.name).toBe('@deepseek-ai/dsh-cua-mcp') + expect(manifest.publishConfig.access).toBe('public') + expect(manifest.icon).toBe('./icon.svg') + expect(manifest.exports).toHaveProperty('./locale/*.json') + expect(manifest.dsh.bundle).toEqual({ patch: './cordis.patch.yml' }) + expect(Object.keys(manifest.optionalDependencies)).toEqual(['@deepseek-ai/dsh-experimental-cua-macos']) + expect(readdirSync(resolve(root, 'locale')).sort()).toEqual(['de.json', 'en.json', 'es.json', 'fr.json', 'ja.json', 'pt.json', 'ru.json', 'zh.json']) + }) + + it('switches off model-turn rows and inserts the preset, provider, and frontend rows', () => { + expect(patches.filter(patch => patch.disabled === true).map(patch => patch.id)) + .toEqual(['session-title-llm', 'hmr', 'credentials', 'authorization', 'deepseek-account']) + expect(inserted.map(row => [row.id, row.name])).toEqual([ + ['cua-mcp-presets', '@deepseek-ai/dsh-agent-preset-registry'], + ['cua-mcp-preset', '@deepseek-ai/dsh-agent-preset'], + ['cua-mcp-computer-use', '@deepseek-ai/dsh-computer-use'], + ['cua-mcp-provider', '@deepseek-ai/dsh-experimental-cua-macos'], + ['cua-mcp', '@deepseek-ai/dsh-cua-mcp'], + ]) + const registry = inserted.find(row => row.id === 'cua-mcp-presets') + const preset = inserted.find(row => row.id === 'cua-mcp-preset') + expect(registry?.config).toEqual({ default: 'cua-mcp' }) + expect(preset?.config).toEqual({ id: 'cua-mcp', plugins: [] }) + for (const name of inserted.map(row => row.name)) { + if (name === manifest.name) continue + expect({ ...manifest.dependencies, ...manifest.optionalDependencies }).toHaveProperty(name) + } + }) + + it('mounts the macOS provider only on Darwin, with a fixed screenshot target and the PTC raw-tool preset', () => { + const provider = inserted.find(row => row.id === 'cua-mcp-provider') + expect(provider?.config).toEqual({ agentPreset: 'ptc', screenshotTarget: { longEdge: 2048, maxBytes: 2_097_152 } }) + for (const platform of ['darwin', 'linux', 'win32']) { + expect(Boolean(interpolate({ process: { platform } }, provider?.disabled))).toBe(platform !== 'darwin') + } + }) + + it('maps DSH_CUA_CONSENT onto the frontend consent and defaults to elicitation', () => { + const frontend = inserted.find(row => row.id === 'cua-mcp') + const consent = (frontend?.config as { consent: unknown }).consent + expect(interpolate({ process: { env: {} } }, consent)).toBe('elicit') + expect(interpolate({ process: { env: { DSH_CUA_CONSENT: 'allow' } } }, consent)).toBe('allow') + }) +}) diff --git a/packages/experimental/cua-mcp/tests/client-config.spec.ts b/packages/experimental/cua-mcp/tests/client-config.spec.ts new file mode 100644 index 0000000000..00db5705c2 --- /dev/null +++ b/packages/experimental/cua-mcp/tests/client-config.spec.ts @@ -0,0 +1,73 @@ +/** Generated client configurations embed the exact launch command and quote every value. */ +import { describe, expect, it } from 'vitest' +import { CLIENT_CONFIG_TARGETS, MCP_SERVER_NAME, clientLaunch, renderClientConfig, type ClientLaunch } from '../src/client-config.ts' + +const launch: ClientLaunch = { + command: '/opt/node/bin/node', + args: ['/opt/dsh/lib/bin.js', '--profile', 'cua-mcp'], + env: { DSH_HOME: "/Users/o'neil/.dsh", DSH_CUA_CONSENT: 'elicit' }, + setup: 'dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp', +} + +describe('client configuration', () => { + it('renders a Codex TOML fragment with the launch command, limits, and the setup command as a comment', () => { + const toml = renderClientConfig('codex', launch) + expect(toml).toMatchInlineSnapshot(` + "# ~/.codex/config.toml — run once first: dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp + [mcp_servers.dsh_cua] + command = "/opt/node/bin/node" + args = ["/opt/dsh/lib/bin.js", "--profile", "cua-mcp"] + env = { DSH_HOME = "/Users/o'neil/.dsh", DSH_CUA_CONSENT = "elicit" } + startup_timeout_sec = 120 + tool_timeout_sec = 600 + enabled_tools = ["cua_run_code", "cua_reset"] + omit_tools_from = ["code_mode", "deferred"] + # default_tools_approval_mode = "auto" + + [mcp_servers.dsh_cua.tools.cua_run_code] + output_token_limit = 25000 + " + `) + }) + + it('renders a shell-safe claude mcp add-json command with the stdio entry', () => { + const command = renderClientConfig('claude-code', launch) + const [comment, line] = command.trimEnd().split('\n') + expect(comment).toBe('# run once first: dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp') + const match = /^claude mcp add-json dsh_cua '(.*)'$/.exec(line ?? '') + if (match === null) throw new Error(`unexpected command line: ${String(line)}`) + // The single-quoted shell argument closes, escapes, and reopens around the apostrophe in the home path. + const shellValue = match[1]!.replaceAll(String.raw`'\''`, "'") + expect(JSON.parse(shellValue)).toEqual({ + type: 'stdio', command: launch.command, args: launch.args, env: launch.env, timeout: 600_000, alwaysLoad: true, + }) + }) + + it('renders a generic mcpServers document without comments', () => { + expect(JSON.parse(renderClientConfig('json', launch))).toEqual({ + mcpServers: { [MCP_SERVER_NAME]: { type: 'stdio', command: launch.command, args: launch.args, env: launch.env } }, + }) + expect(CLIENT_CONFIG_TARGETS).toEqual(['codex', 'claude-code', 'json']) + expect(() => renderClientConfig('cursor' as 'json', launch)).toThrow('unknown client configuration target cursor') + }) +}) + +describe('launch resolution', () => { + const profile = { name: 'cua-mcp', home: '/home/me/.dsh' } + + it('embeds the Node executable, its options, and the launching script for a script launch', () => { + expect(clientLaunch({ execPath: '/opt/node', execArgv: ['--import', 'tsx/esm'], argv: ['/opt/node', '/repo/apps/cli/src/bin.ts', 'cua-mcp'], sea: false }, profile, 'allow')) + .toEqual({ + command: '/opt/node', args: ['--import', 'tsx/esm', '/repo/apps/cli/src/bin.ts', '--profile', 'cua-mcp'], + env: { DSH_HOME: '/home/me/.dsh', DSH_CUA_CONSENT: 'allow' }, + setup: 'dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp', + }) + }) + + it('embeds only the executable for a single-file runtime and rejects a script launch without a script', () => { + expect(clientLaunch({ execPath: '/opt/dsh-runtime', execArgv: [], argv: ['/opt/dsh-runtime', '--profile', 'cua-mcp'], sea: true }, profile, 'elicit').args) + .toEqual(['--profile', 'cua-mcp']) + expect(() => clientLaunch({ execPath: '/opt/node', execArgv: [], argv: ['/opt/node'], sea: false }, profile, 'elicit')) + .toThrow('launching script is unknown') + }) +}) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts new file mode 100644 index 0000000000..3659b2fb54 --- /dev/null +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -0,0 +1,267 @@ +/** A real Loader composition: the MCP connection runs retained Computer Use programs through a fixture desktop. */ +import { mkdtemp, rm, writeFile } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { pathToFileURL } from 'node:url' +import { Context } from '@deepseek-ai/cordis' +import Include from '@deepseek-ai/cordis-plugin-include' +import Loader from '@deepseek-ai/cordis-plugin-loader' +import AgentRegistry from '@deepseek-ai/dsh-agent' +import AgentLoop from '@deepseek-ai/dsh-agent-loop' +import AgentPreset from '@deepseek-ai/dsh-agent-preset' +import AgentPresets from '@deepseek-ai/dsh-agent-preset-registry' +import LocalAttachmentStore from '@deepseek-ai/dsh-attachment-local' +import ComputerUseRegistry from '@deepseek-ai/dsh-computer-use' +import { CuaConfig, installCua } from '@deepseek-ai/dsh-cua' +import FileSystem from '@deepseek-ai/dsh-fs-local' +import LlmRuntime from '@deepseek-ai/dsh-llm' +import NodeRuntime from '@deepseek-ai/dsh-ptc-runtime-node' +import Sandbox from '@deepseek-ai/dsh-sandbox-local' +import SandboxPolicy from '@deepseek-ai/dsh-sandbox-policy' +import SessionStore from '@deepseek-ai/dsh-session' +import SessionProjectionRegistry from '@deepseek-ai/dsh-session-projection' +import Subprocess from '@deepseek-ai/dsh-subprocess-local' +import SystemPrompt from '@deepseek-ai/dsh-system-prompt' +import * as NativeToolExecutor from '@deepseek-ai/dsh-tool-executor-native' +import ToolRuntime from '@deepseek-ai/dsh-tools' +import UserQuestions from '@deepseek-ai/dsh-user-questions' +import WorkingDirectory from '@deepseek-ai/dsh-working-directory' +import { Client, InMemoryTransport, type CallToolResult } from '@modelcontextprotocol/client' +import { describe, expect, it, onTestFinished } from 'vitest' +import { createNativeFixture } from '../../../../snapshots/session/cua-run-code/native-channel.mjs' +import type { ConsentMode } from '../src/consent.ts' +import { createCuaMcpServer } from '../src/server.ts' + +/** The elicitation fields the consent tests inspect; the SDK's own form type stays behind its request handler. */ +interface ElicitationRequest { + readonly message: string + readonly requestedSchema: unknown +} + +interface SetupOptions { + consent?: ConsentMode + /** Pre-grant the fixture application through the provider's legacy grant list. */ + granted?: boolean + /** Mount the CUA provider row; false composes a Host without Computer Use. */ + provider?: boolean + /** Elicitation handler of the client; omission advertises no elicitation capability. */ + elicit?: (request: ElicitationRequest) => Promise<{ action: 'accept' | 'decline' | 'cancel'; content?: Record }> +} + +type Block = CallToolResult['content'][number] + +function texts(result: CallToolResult): string[] { + return result.content.flatMap(block => block.type === 'text' ? [block.text] : []) +} + +function lastJson(result: CallToolResult): unknown { + const text = texts(result).at(-1) + if (text === undefined) throw new Error('result carries no text') + return JSON.parse(text) +} + +async function setup(options: SetupOptions = {}) { + const directory = await mkdtemp(join(tmpdir(), 'dsh-cua-mcp-')) + const ctx = new Context() + onTestFinished(async () => { + try { await ctx.fiber.dispose() } finally { await rm(directory, { recursive: true, force: true }) } + }) + const native = createNativeFixture() + const modules = { + llm: LlmRuntime, sessions: SessionStore, projections: SessionProjectionRegistry, systemPrompt: SystemPrompt, + tools: ToolRuntime, agents: AgentRegistry, agentLoop: AgentLoop, agentPresets: AgentPresets, preset: AgentPreset, + fs: FileSystem, workingDirectory: WorkingDirectory, subprocess: Subprocess, userQuestions: UserQuestions, + sandbox: Sandbox, sandboxPolicy: SandboxPolicy, sharedRuntime: NodeRuntime, + attachments: LocalAttachmentStore, computerUse: ComputerUseRegistry, native: NativeToolExecutor, + cua: { + inject: ['computerUse', 'subprocess', 'tools', 'systemPrompt', 'agents'], Config: CuaConfig, + apply(owner: Context, config: CuaConfig) { + installCua(owner, config, { helperPath: process.execPath, createChannel: native.createChannel, + guidance: 'Fixture CUA guidance: select test.fixture and operate window 7.', + capabilities: { platform: 'macos', methods: ['getCapabilities', 'getApp', 'getState', 'click', 'screenshot'], + appLevelAccessibility: true, keyboard: ['app'], browser: false, coordinateSpace: 'screenshot-pixels' }, + permissionParameters: (_method, permission, locale) => ({ permission, locale }), + }) + }, + }, + } + // The Host plane owns the native executor, as dsh-base does; the empty preset adds no model-facing rows. + const entries = Object.keys(modules).filter(name => options.provider !== false || name !== 'cua').map(name => ({ + id: name, name: `cordis:${name}`, + ...name === 'agentPresets' ? { config: { default: 'cua-mcp' } } : {}, + ...name === 'preset' ? { config: { id: 'cua-mcp', plugins: [] } } : {}, + ...name === 'sandboxPolicy' ? { config: { mode: 'danger-full-access', workspaceRoot: directory } } : {}, + ...name === 'sharedRuntime' ? { config: { executionMode: 'per-call' } } : {}, + ...name === 'attachments' ? { config: { dshHome: directory } } : {}, + ...name === 'cua' ? { config: { + screenshotTarget: { longEdge: 1, maxBytes: 100_000 }, + allowedApps: options.granted === false ? [] : [{ id: 'a'.repeat(64), name: 'Fixture', executablePath: '/fixture/app' }], + } } : {}, + })) + const configPath = join(directory, 'cordis.yml') + await writeFile(configPath, JSON.stringify(entries, null, 2) + '\n') + ctx.baseUrl = pathToFileURL(directory).href + '/' + await ctx.plugin(Loader) + Object.assign(ctx.loader.builtins, modules, { include: Include }) + await ctx.loader.create({ name: 'cordis:include', config: { path: pathToFileURL(configPath).href } }) + await ctx.loader.await() + for (const entry of ctx.loader.entries()) await entry.fiber?.await() + + const lifetime = new AbortController() + const adapter = createCuaMcpServer(ctx, { consent: options.consent ?? 'allow', cwd: directory, signal: lifetime.signal }) + const client = new Client({ name: 'composition', version: '1' }, options.elicit === undefined ? {} : { capabilities: { elicitation: {} } }) + const elicitations: ElicitationRequest[] = [] + if (options.elicit !== undefined) { + const answer = options.elicit + client.setRequestHandler('elicitation/create', async (request) => { + const params: ElicitationRequest = { + message: request.params.message, requestedSchema: 'requestedSchema' in request.params ? request.params.requestedSchema : undefined, + } + elicitations.push(params) + return answer(params) + }) + } + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair() + await adapter.server.connect(serverTransport) + await client.connect(clientTransport) + onTestFinished(async () => { + lifetime.abort() + await client.close() + await adapter.dispose() + }) + const run = (code: string, extra: { description?: string; timeoutMs?: number } = {}, signal?: AbortSignal) => + client.callTool({ name: 'cua_run_code', arguments: { code, ...extra } }, signal === undefined ? {} : { signal }) + return { ctx, native, directory, adapter, client, elicitations, run, lifetime } +} + +describe('Computer Use MCP composition', () => { + it('serves two tools, prefixes the first program result with the API reference, and retains program state', async () => { + const { ctx, native, client, run } = await setup() + expect(client.getInstructions()).toContain('cua_run_code') + const listed = await client.listTools() + expect(listed.tools.map(tool => tool.name)).toEqual(['cua_run_code', 'cua_reset']) + expect(listed.tools[0]?.inputSchema).toMatchObject({ type: 'object', required: ['code'] }) + expect(listed.tools[0]?.description).toContain('complete `cua` API reference') + + const first = await run('globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); ' + + 'await win.click("0"); await win.getScreenshot(); ({ visits, window: win.windowId, pid: process.pid })', { description: 'Open the fixture' }) + expect(first.isError).not.toBe(true) + const [reference, ...rest] = first.content + expect(reference).toMatchObject({ type: 'text' }) + const referenceText = (reference as Extract).text + expect(referenceText).toContain('## cua_run_code execution rules') + expect(referenceText).toContain('remain in memory for this Agent across calls') + expect(referenceText).toContain('## cua API reference') + expect(referenceText).toContain('Fixture CUA guidance: select test.fixture and operate window 7.') + expect(referenceText).toContain('Maximum click holdMs: 5000 ms.') + const result = JSON.parse((rest[0] as Extract).text) as { visits: number; window: number; pid: number } + expect(result).toMatchObject({ visits: 1, window: 7 }) + expect(result.pid).not.toBe(process.pid) + // The nested screenshot arrives after the program text: its metadata, then the image the program observed. + expect(JSON.parse((rest[1] as Extract).text)).toMatchObject({ windowId: 7, coordinateSpace: 'screenshot-pixels', pixelWidth: 1, pixelHeight: 1 }) + const image = rest[2] + if (image?.type !== 'image') throw new Error(`expected an image block, got ${JSON.stringify(image)}`) + expect(image.mimeType).toMatch(/^image\//) + expect(Buffer.from(image.data, 'base64').length).toBeGreaterThan(0) + expect(rest).toHaveLength(3) + expect(native.state).toMatchObject({ count: 1, openedChannels: 1, closedChannels: 0 }) + + const second = await run('globalThis.visits++; await win.click("0"); ({ visits, sameWindow: win.windowId === 7, pid: process.pid })') + expect(second.isError).not.toBe(true) + expect(second.content).toHaveLength(1) + expect(lastJson(second)).toEqual({ visits: 2, sameWindow: true, pid: result.pid }) + expect(native.state.count).toBe(2) + // One connection owns one Agent; root calls stay out of its Session log while nested calls are logged. + const agents = ctx.agents.list() + expect(agents).toHaveLength(1) + const events = agents[0]!.session.snapshotEvents() + expect(events.filter(event => event.type === 'tool/call')).toHaveLength(0) + const dispatches = events.filter(event => event.type === 'tool/ptc-dispatch') + expect(dispatches.length).toBeGreaterThanOrEqual(5) + expect(dispatches.every(event => event.data.name === 'cua' && !event.data.isError)).toBe(true) + }) + + it('serializes concurrent programs, reports program failures, and recovers after cancellation', async () => { + const { run, client } = await setup() + const [a, b] = await Promise.all([ + run('globalThis.order = ["a"]; await new Promise(resolve => setTimeout(resolve, 50)); "a"'), + run('globalThis.order.push("b"); globalThis.order'), + ]) + expect(a.isError).not.toBe(true) + expect(lastJson(b)).toEqual(['a', 'b']) + const failed = await run('throw new Error("boom")') + expect(failed.isError).toBe(true) + expect(texts(failed).join('\n')).toContain('boom') + const controller = new AbortController() + const hanging = run('await new Promise(resolve => setTimeout(resolve, 60_000))', {}, controller.signal) + setTimeout(() => { controller.abort() }, 100) + await expect(hanging).rejects.toThrow() + expect(lastJson(await run('1 + 1'))).toBe(2) + const invalid = await client.callTool({ name: 'cua_run_code', arguments: { code: '' } }) + expect(invalid.isError).toBe(true) + expect(texts(invalid).join('\n')).toContain('Input validation error') + }) + + it('resets the program environment while keeping the native connection, then repeats the reference', async () => { + const { native, run, client } = await setup() + const first = await run('globalThis.visits = 1; var app = await cua.getApp("test.fixture"); process.pid') + const pid = lastJson(first) as number + const reset = await client.callTool({ name: 'cua_reset', arguments: {} }) + expect(reset.isError).not.toBe(true) + expect(texts(reset)[0]).toContain('Program environment cleared') + const next = await run('({ visits: globalThis.visits ?? null, hasApp: typeof app !== "undefined", pid: process.pid })') + expect(next.content).toHaveLength(2) + expect(texts(next)[0]).toContain('## cua API reference') + const state = lastJson(next) as { visits: null; hasApp: boolean; pid: number } + expect(state).toMatchObject({ visits: null, hasApp: false }) + expect(state.pid).not.toBe(pid) + expect(() => process.kill(pid, 0)).toThrow() + expect(native.state).toMatchObject({ openedChannels: 1, closedChannels: 0 }) + }) + + it('forwards application consent to the client as an elicitation and records a refusal', async () => { + const decisions = ['Deny', 'Allow for this session'] + const { run, elicitations, native } = await setup({ + consent: 'elicit', granted: false, + elicit: async () => ({ action: 'accept', content: { decision: decisions.shift() ?? 'Deny' } }), + }) + const denied = await run('var app = await cua.getApp("test.fixture"); app.appHandle') + expect(denied.isError).toBe(true) + expect(texts(denied).join('\n')).toContain('APP_ACCESS_DENIED') + expect(elicitations).toHaveLength(1) + expect(elicitations[0]).toMatchObject({ + message: expect.stringContaining('Fixture') as string, + requestedSchema: { type: 'object', properties: { decision: { type: 'string', enum: ['Allow for this session', 'Deny'] } }, required: ['decision'] }, + }) + // A refusal is remembered for this Agent; the provider does not ask again. + const again = await run('var app = await cua.getApp("test.fixture"); app.appHandle') + expect(again.isError).toBe(true) + expect(elicitations).toHaveLength(1) + expect(native.calls.map(call => call.method)).not.toContain('getState') + }) + + it('grants consent without a human in allow mode and explains a client without elicitation', async () => { + const allowed = await setup({ consent: 'allow', granted: false }) + const result = await allowed.run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); win.windowId') + expect(result.isError).not.toBe(true) + expect(lastJson(result)).toBe(7) + + const unsupported = await setup({ consent: 'elicit', granted: false }) + const refused = await unsupported.run('var app = await cua.getApp("test.fixture"); app.appHandle') + expect(refused.isError).toBe(true) + expect(texts(refused).join('\n')).toContain('DSH_CUA_CONSENT=allow') + }) + + it('reports a Host without a CUA provider and releases the connection Agent on disposal', async () => { + const { ctx, run, client, adapter } = await setup({ provider: false }) + const result = await run('1') + expect(result.isError).toBe(true) + expect(texts(result)[0]).toContain('no active CUA provider') + const reset = await client.callTool({ name: 'cua_reset', arguments: {} }) + expect(reset.isError).toBe(true) + expect(ctx.agents.list()).toHaveLength(1) + await client.close() + await adapter.dispose() + expect(ctx.agents.list()).toHaveLength(0) + }) +}) diff --git a/packages/experimental/cua-mcp/tests/consent.spec.ts b/packages/experimental/cua-mcp/tests/consent.spec.ts new file mode 100644 index 0000000000..c50473f4d1 --- /dev/null +++ b/packages/experimental/cua-mcp/tests/consent.spec.ts @@ -0,0 +1,80 @@ +/** Consent answering: unattended approval of the connection's Agent, or an elicitation round trip. */ +import { describe, expect, it, vi } from 'vitest' +import type { Agent } from '@deepseek-ai/dsh-agent' +import { UserQuestionError, type AskUserQuestionItem } from '@deepseek-ai/dsh-user-questions' +import { approveAll, CONSENT_MODES, createConsentAnswerer, elicitAnswer, type ElicitationClient } from '../src/consent.ts' + +const approval: AskUserQuestionItem = { + id: 'cua-app-access', question: 'Allow computer use to control Notes?', detail: 'The session may read and operate the application.', + options: [{ label: 'Allow for this session' }, { label: 'Deny' }, { label: 'Always allow' }], + intent: { kind: 'approval', approve: 'Allow for this session', reject: 'Deny', always: 'Always allow' }, +} +const generic: AskUserQuestionItem = { id: 'format', question: 'Which format?', options: [{ label: 'CSV' }, { label: 'JSON' }] } +const agent = { id: 'connection' } as Agent +const other = { id: 'other' } as Agent + +function client(result: Awaited>, supported = true) { + const elicit = vi.fn(async () => result) + return { client: { supportsElicitation: () => supported, elicit } satisfies ElicitationClient, elicit } +} + +describe('allow mode', () => { + it('selects the approving label of every approval question and refuses other questions', () => { + expect(approveAll([approval])).toEqual({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }] }) + expect(approveAll([approval, generic])).toBeUndefined() + expect(CONSENT_MODES).toEqual(['allow', 'elicit']) + }) + + it('answers only the connection Agent and delegates everything else', async () => { + const next = vi.fn(async () => ({ answers: [{ id: 'format', selected: ['CSV'] }] })) + const answer = createConsentAnswerer('allow', candidate => candidate === agent, client({ action: 'cancel' }).client) + expect(await answer({ questions: [approval], agent }, next)).toEqual({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }] }) + expect(await answer({ questions: [approval], agent: other }, next)).toEqual({ answers: [{ id: 'format', selected: ['CSV'] }] }) + expect(await answer({ questions: [generic], agent }, next)).toEqual({ answers: [{ id: 'format', selected: ['CSV'] }] }) + expect(await answer({ questions: [approval] }, next)).toEqual({ answers: [{ id: 'format', selected: ['CSV'] }] }) + expect(next).toHaveBeenCalledTimes(3) + }) +}) + +describe('elicit mode', () => { + it('forwards the question with its detail and offered labels, then returns the accepted label', async () => { + const { client: forwarding, elicit } = client({ action: 'accept', content: { decision: 'Always allow' } }) + const signal = new AbortController().signal + expect(await elicitAnswer(forwarding, approval, signal)).toEqual({ id: 'cua-app-access', selected: ['Always allow'] }) + expect(elicit).toHaveBeenCalledWith( + 'Allow computer use to control Notes?\n\nThe session may read and operate the application.', + ['Allow for this session', 'Deny', 'Always allow'], signal, + ) + expect(await elicitAnswer(client({ action: 'accept', content: { decision: 'JSON' } }).client, generic, undefined)) + .toEqual({ id: 'format', selected: ['JSON'] }) + }) + + it('maps decline to the rejecting label and cancel to a cancelled ask', async () => { + expect(await elicitAnswer(client({ action: 'decline' }).client, approval, undefined)).toEqual({ id: 'cua-app-access', selected: ['Deny'] }) + await expect(elicitAnswer(client({ action: 'decline' }).client, generic, undefined)).rejects.toMatchObject({ code: 'ASK_CANCELLED' }) + await expect(elicitAnswer(client({ action: 'cancel' }).client, approval, undefined)).rejects.toSatisfy(error => + error instanceof UserQuestionError && error.code === 'ASK_CANCELLED') + }) + + it('rejects an unoffered answer, a client without elicitation, and an unknown action', async () => { + await expect(elicitAnswer(client({ action: 'accept', content: { decision: 'Maybe' } }).client, approval, undefined)) + .rejects.toThrow('without one of the offered answers') + await expect(elicitAnswer(client({ action: 'accept' }).client, approval, undefined)).rejects.toThrow('without one of the offered answers') + const { client: optionless, elicit } = client({ action: 'accept', content: { decision: 'yes' } }) + await expect(elicitAnswer(optionless, { id: 'free', question: 'Continue?' }, undefined)).rejects.toThrow('without one of the offered answers: []') + expect(elicit).toHaveBeenCalledWith('Continue?', [], undefined) + await expect(elicitAnswer(client({ action: 'accept' }, false).client, approval, undefined)).rejects.toThrow('DSH_CUA_CONSENT=allow') + await expect(elicitAnswer(client({ action: 'later' as 'accept' }).client, approval, undefined)).rejects.toThrow('unknown elicitation action later') + }) + + it('answers every question of the connection Agent in order', async () => { + const { client: forwarding, elicit } = client({ action: 'accept', content: { decision: 'Deny' } }) + elicit.mockResolvedValueOnce({ action: 'accept', content: { decision: 'Allow for this session' } }) + .mockResolvedValueOnce({ action: 'accept', content: { decision: 'CSV' } }) + const answer = createConsentAnswerer('elicit', candidate => candidate === agent, forwarding) + const next = vi.fn(async () => { throw new Error('unexpected delegation') }) + expect(await answer({ questions: [approval, generic], agent }, next)) + .toEqual({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }, { id: 'format', selected: ['CSV'] }] }) + expect(next).not.toHaveBeenCalled() + }) +}) diff --git a/packages/experimental/cua-mcp/tests/projection.spec.ts b/packages/experimental/cua-mcp/tests/projection.spec.ts new file mode 100644 index 0000000000..a7f534d1d5 --- /dev/null +++ b/packages/experimental/cua-mcp/tests/projection.spec.ts @@ -0,0 +1,68 @@ +/** Result projection: text passes through, deferred screenshots become inline images, failures keep isError. */ +import { describe, expect, it, vi } from 'vitest' +import type { AttachmentStore, ImageAttachmentRef, ImageVariantId } from '@deepseek-ai/dsh-attachment' +import { brandString } from '@deepseek-ai/dsh-brand' +import { createUserMessage } from '@deepseek-ai/dsh-llm' +import type { ToolExecutionResult } from '@deepseek-ai/dsh-tools' +import { projectToolResult } from '../src/projection.ts' + +const attachment: ImageAttachmentRef = { + attachmentId: brandString(`sha256:${'a'.repeat(64)}`), + mediaType: 'image/png', bytes: 3, width: 400, height: 200, +} + +function store() { + const readImage = vi.fn(async () => ({ ref: attachment, data: new Uint8Array([1, 2, 3]) })) + const readImageRequest = vi.fn(async () => ({ + variantId: brandString('variant'), attachment, data: new Uint8Array([9, 8]), mediaType: 'image/jpeg' as const, + bytes: 2, width: 40, height: 20, depth: 'uchar' as const, space: 'srgb' as const, hasAlpha: false, + })) + const attachments: Pick = { readImage, readImageRequest } + return { attachments, readImage, readImageRequest } +} + +const success: ToolExecutionResult = { isError: false, value: 'ok', content: [{ type: 'text', text: '{"visits":1}' }] } +const deferred = [createUserMessage({ source: { kind: 'ptc-mode' }, content: [{ type: 'text', text: '{"windowId":7}' }, { type: 'image', attachment }] })] + +describe('tool result projection', () => { + it('delivers the request version the program observed when the provider fixes a target', async () => { + const { attachments, readImageRequest, readImage } = store() + const signal = new AbortController().signal + const target = { width: 40, height: 20, maxBytes: 1024 } + const result = await projectToolResult(success, deferred, { attachments, target: () => target }, signal, ['## reference']) + expect(result).toEqual({ content: [ + { type: 'text', text: '## reference' }, + { type: 'text', text: '{"visits":1}' }, + { type: 'text', text: '{"windowId":7}' }, + { type: 'image', data: Buffer.from([9, 8]).toString('base64'), mimeType: 'image/jpeg' }, + ] }) + expect(readImageRequest).toHaveBeenCalledWith(attachment, target, signal) + expect(readImage).not.toHaveBeenCalled() + }) + + it('falls back to the stored image without a fixed target and names unrenderable blocks', async () => { + const { attachments, readImage, readImageRequest } = store() + const result = await projectToolResult( + { isError: false, value: null, content: [{ type: 'file', name: 'log.txt' } as never] }, deferred, + { attachments, target: () => undefined }, new AbortController().signal, + ) + expect(result.content).toEqual([ + { type: 'text', text: '[file content omitted]' }, + { type: 'text', text: '{"windowId":7}' }, + { type: 'image', data: Buffer.from([1, 2, 3]).toString('base64'), mimeType: 'image/png' }, + ]) + expect(readImage).toHaveBeenCalledOnce() + expect(readImageRequest).not.toHaveBeenCalled() + expect(result).not.toHaveProperty('isError') + }) + + it('keeps the failure text and flag of a failed execution', async () => { + const { attachments } = store() + const failure: ToolExecutionResult = { + isError: true, error: { message: 'code run failed (exception): boom', info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' } }, + content: [{ type: 'text', text: 'Error: code run failed (exception): boom' }], + } + expect(await projectToolResult(failure, [], { attachments, target: () => undefined }, new AbortController().signal)) + .toEqual({ content: [{ type: 'text', text: 'Error: code run failed (exception): boom' }], isError: true }) + }) +}) diff --git a/packages/experimental/cua-mcp/tests/server.spec.ts b/packages/experimental/cua-mcp/tests/server.spec.ts new file mode 100644 index 0000000000..9e9ba15dc7 --- /dev/null +++ b/packages/experimental/cua-mcp/tests/server.spec.ts @@ -0,0 +1,182 @@ +/** Server behavior that the fixture desktop cannot reach: creation failures, missing references, reset failures, and disposal. */ +import { Context } from '@deepseek-ai/cordis' +import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent' +import type { CuaPrograms } from '@deepseek-ai/dsh-cua' +import { SessionId } from '@deepseek-ai/dsh-session' +import type { ToolBatchInput, ToolBatchResult } from '@deepseek-ai/dsh-tools' +import type { AskUserQuestionItem } from '@deepseek-ai/dsh-user-questions' +import { Client, InMemoryTransport, type CallToolResult } from '@modelcontextprotocol/client' +import { describe, expect, it, onTestFinished, vi } from 'vitest' +import { createCuaMcpServer } from '../src/server.ts' + +const approval: AskUserQuestionItem = { + id: 'cua-app-access', question: 'Allow computer use to control Notes?', detail: 'Session access to the application.', + options: [{ label: 'Allow for this session' }, { label: 'Deny' }], + intent: { kind: 'approval', approve: 'Allow for this session', reject: 'Deny' }, +} + +function batch(text: string): ToolBatchResult { + return { + results: [{ callId: 'cua-mcp-1' as never, result: { isError: false, value: text, content: [{ type: 'text', text }] } }], + additionalContexts: [], concluded: false, + } +} + +interface SetupOptions { + createFailures?: number + /** Agent creation waits for this promise before it settles. */ + createGate?: Promise + programs?: Partial | false + elicitation?: boolean + reference?: boolean +} + +async function setup(options: SetupOptions = {}) { + const ctx = new Context() + const agent = { id: SessionId('cua-mcp-fake'), ctx: new Context() } as Agent + const dispose = vi.fn(async () => {}) + let failures = options.createFailures ?? 0 + const create = vi.fn(async ( + request: { setup?: (agentCtx: Context, agent: Agent) => Promise | undefined }, + ): Promise => { + await options.createGate + if (failures > 0) { + failures -= 1 + throw new Error('registry refused the Agent') + } + await request.setup?.(agent.ctx, agent) + return { agent, dispose } + }) + const mount = vi.fn(async () => ({ id: 'cua-mcp' })) + const execute = vi.fn(async (_input: ToolBatchInput): Promise => batch('program output')) + const get = vi.fn(() => options.reference === false ? undefined : { name: 'cua_run_code', description: 'Run a program.' }) + const assemble = vi.fn(async () => ({ + sections: options.reference === false ? [] : [{ name: 'computer-use:dsh-cua', text: 'Fixture guidance' }], contexts: [], variables: {}, tools: [], + })) + const reset = vi.fn(async () => {}) + ctx.provide('agents', { create } as never) + ctx.provide('agentPresets', { defaultId: 'cua-mcp', mount } as never) + ctx.provide('tools', { execute, get } as never) + ctx.provide('systemPrompt', { assemble } as never) + ctx.provide('attachments', {} as never) + if (options.programs !== false) ctx.provide('cuaPrograms', { reset, screenshotRequestTarget: () => undefined, ...options.programs } as never) + const errors = vi.spyOn(ctx.logger, 'error').mockImplementation(() => {}) + const lifetime = new AbortController() + const adapter = createCuaMcpServer(ctx, { consent: 'elicit', cwd: '/workspace', signal: lifetime.signal }) + const client = new Client({ name: 'server-spec', version: '1' }, options.elicitation ? { capabilities: { elicitation: {} } } : {}) + const elicitations: unknown[] = [] + if (options.elicitation) { + client.setRequestHandler('elicitation/create', async (request) => { + elicitations.push(request.params) + return { action: 'accept', content: { decision: 'Allow for this session' } } + }) + } + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair() + await adapter.server.connect(serverTransport) + await client.connect(clientTransport) + onTestFinished(async () => { + lifetime.abort() + await client.close() + await adapter.dispose() + await ctx.fiber.dispose() + }) + const run = (args: Record) => client.callTool({ name: 'cua_run_code', arguments: args }) + return { ctx, agent, adapter, client, run, create, mount, execute, get, assemble, reset, dispose, errors, elicitations } +} + +function texts(result: CallToolResult): string[] { + return result.content.flatMap(block => block.type === 'text' ? [block.text] : []) +} + +describe('Computer Use MCP server', () => { + it('creates the Agent once initialization completes, mounts the default preset, and forwards program arguments', async () => { + const { run, create, mount, execute, agent } = await setup() + await vi.waitFor(() => { expect(create).toHaveBeenCalledOnce() }) + expect(create.mock.calls[0]?.[0]).toMatchObject({ meta: { cwd: '/workspace', agentPreset: 'cua-mcp' } }) + expect(mount).toHaveBeenCalledWith(agent.ctx) + const first = await run({ code: '1 + 1', timeoutMs: 5000 }) + expect(texts(first)).toEqual(['## cua_run_code execution rules\n\nRun a program.\n\n## cua API reference\n\nFixture guidance', 'program output']) + expect(execute).toHaveBeenCalledOnce() + const input = execute.mock.calls[0]?.[0] + if (input === undefined) throw new Error('the executor was not called') + expect(input.agent).toBe(agent) + expect(input.calls[0]?.name).toBe('cua_run_code') + expect(JSON.parse(input.calls[0]!.arguments)).toEqual({ code: '1 + 1', description: 'CUA program', timeoutMs: 5000 }) + expect(create).toHaveBeenCalledOnce() + }) + + it('retries Agent creation after a failure and reports an executor without a result', async () => { + const { run, create, errors, execute } = await setup({ createFailures: 1 }) + await vi.waitFor(() => { expect(errors).toHaveBeenCalledOnce() }) + expect(String(errors.mock.calls[0]?.[0])).toContain('Agent creation failed') + const result = await run({ code: '1' }) + expect(result.isError).not.toBe(true) + expect(create).toHaveBeenCalledTimes(2) + execute.mockResolvedValueOnce({ results: [], additionalContexts: [], concluded: false }) + const missing = await run({ code: '2' }) + expect(missing.isError).toBe(true) + expect(texts(missing).join('')).toContain('settled without a cua_run_code result') + }) + + it('omits the preface when the provider registered no tool or guidance, and reports reset failures', async () => { + const { run, client, reset } = await setup({ reference: false }) + expect(texts(await run({ code: '1' }))).toEqual(['program output']) + reset.mockRejectedValueOnce(new Error('cleanup is incomplete')) + expect(await client.callTool({ name: 'cua_reset', arguments: {} })).toEqual({ content: [{ type: 'text', text: 'cleanup is incomplete' }], isError: true }) + reset.mockRejectedValueOnce('opaque failure') + expect(await client.callTool({ name: 'cua_reset', arguments: {} })).toEqual({ content: [{ type: 'text', text: 'opaque failure' }], isError: true }) + const ok = await client.callTool({ name: 'cua_reset', arguments: {} }) + expect(ok.isError).not.toBe(true) + expect(texts(await run({ code: '1' }))).toEqual(['program output']) + }) + + it('answers consent only for its own Agent and forwards a request without a signal', async () => { + const { ctx, agent, elicitations } = await setup({ elicitation: true }) + const next = vi.fn(async () => ({ answers: [] })) + expect(await ctx.waterfall('user-questions/request', { questions: [approval] }, next)).toEqual({ answers: [] }) + expect(await ctx.waterfall('user-questions/request', { questions: [approval], agent: { id: SessionId('other') } as Agent }, next)).toEqual({ answers: [] }) + expect(next).toHaveBeenCalledTimes(2) + // The connection Agent exists only after initialization; its requests reach the client. + await vi.waitFor(() => { expect(ctx.get('agents')).toBeDefined() }) + const answer = await ctx.waterfall('user-questions/request', { questions: [approval], agent }, next) + expect(answer).toEqual({ answers: [{ id: 'cua-app-access', selected: ['Allow for this session'] }] }) + expect(elicitations).toHaveLength(1) + expect(next).toHaveBeenCalledTimes(2) + }) + + it('disposes without an Agent, and after a creation that never succeeded', async () => { + const idle = await setup() + await vi.waitFor(() => { expect(idle.create).toHaveBeenCalledOnce() }) + await idle.client.close() + await idle.adapter.dispose() + expect(idle.dispose).toHaveBeenCalledOnce() + + const failing = await setup({ createFailures: 3, programs: false }) + const result = await failing.run({ code: '1' }) + expect(result.isError).toBe(true) + expect(texts(result).join('')).toContain('no active CUA provider') + await failing.client.close() + await failing.adapter.dispose() + expect(failing.dispose).not.toHaveBeenCalled() + + const neverCreated = await setup({ createFailures: 3 }) + const refused = await neverCreated.run({ code: '1' }) + expect(refused.isError).toBe(true) + expect(texts(refused).join('')).toContain('registry refused the Agent') + await neverCreated.client.close() + await neverCreated.adapter.dispose() + expect(neverCreated.dispose).not.toHaveBeenCalled() + + // Disposal during a pending creation that then fails releases nothing and does not reject. + const gate: PromiseWithResolvers = Promise.withResolvers() + const racing = await setup({ createFailures: 1, createGate: gate.promise }) + await vi.waitFor(() => { expect(racing.create).toHaveBeenCalledOnce() }) + await racing.client.close() + const disposing = racing.adapter.dispose() + // Disposal observes the pending creation before the timer lets it fail. + await new Promise(resolve => setTimeout(resolve, 20)) + gate.resolve() + await disposing + expect(racing.dispose).not.toHaveBeenCalled() + }) +}) diff --git a/packages/experimental/cua-mcp/tests/startup.spec.ts b/packages/experimental/cua-mcp/tests/startup.spec.ts new file mode 100644 index 0000000000..9f5a62b965 --- /dev/null +++ b/packages/experimental/cua-mcp/tests/startup.spec.ts @@ -0,0 +1,150 @@ +/** The frontend parses its invocation, prints client configuration, and serves MCP only after readiness. */ +import { EventEmitter } from 'node:events' +import { Context } from '@deepseek-ai/cordis' +import { internals, provideCmdline } from '@deepseek-ai/dsh-cmdline' +import { McpServer } from '@modelcontextprotocol/server' +import { StdioServerTransport } from '@modelcontextprotocol/server/stdio' +import { afterEach, beforeEach, describe, expect, it, vi, type Mock } from 'vitest' +import * as frontend from '../src/index.ts' +import { createCuaMcpServer } from '../src/server.ts' + +vi.mock('../src/server.ts', async original => ({ + ...await original(), createCuaMcpServer: vi.fn(), +})) +vi.mock('@modelcontextprotocol/server/stdio', () => ({ StdioServerTransport: vi.fn() })) +vi.mock('node:sea', () => ({ isSea: () => false })) + +/** Controllable stdin for one invocation. */ +class TestStdin extends EventEmitter { + readableEnded = false + + end(): void { + this.readableEnded = true + this.emit('end') + } +} + +const roots: Context[] = [] +const closers: (() => Promise)[] = [] +let connect: Mock<() => Promise> +let dispose: Mock<() => Promise> + +beforeEach(() => { + const server = new McpServer({ name: 'startup-fixture', version: '1' }) + closers.push(() => server.close()) + connect = vi.fn(async () => {}) + vi.spyOn(server, 'connect').mockImplementation(connect) + dispose = vi.fn(() => server.close()) + vi.mocked(createCuaMcpServer).mockReturnValue({ server, dispose }) +}) + +afterEach(async () => { + await Promise.all(roots.splice(0).map(ctx => ctx.fiber.dispose())) + await Promise.all(closers.splice(0).map(close => close())) + vi.restoreAllMocks() + vi.clearAllMocks() + internals.stdin = process.stdin + internals.stdout = process.stdout + internals.stderr = process.stderr +}) + +async function boot(args: string[], config: Partial = {}) { + const ctx = new Context() + roots.push(ctx) + const exit = vi.fn() + const listeners = new Set<() => void>() + let committed = false + const stdout: string[] = [] + const stderr: string[] = [] + const stdin = new TestStdin() + internals.stdin = stdin + internals.stdout = { write: (chunk) => { stdout.push(chunk); return true } } + internals.stderr = { write: (chunk) => { stderr.push(chunk); return true } } + provideCmdline(ctx, { args, exit, ready: { onReady(listener) { + if (committed) { listener(); return () => {} } + listeners.add(listener) + return () => { listeners.delete(listener) } + } } }) + // The served connection reads these services inside the mocked server; the rows only need to exist for activation. + for (const service of ['agents', 'agentPresets', 'tools', 'systemPrompt', 'attachments'] as const) ctx.provide(service, {} as never) + ctx.provide('profileContext', { + name: 'cua-mcp', dir: '/profiles/cua-mcp', patchPath: '/profiles/cua-mcp/cordis.patch.yml', + installAnchor: '/dsh/package.json', cwd: '/workspace', home: '/home/me/.dsh', + startedBundles: ['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-cua-mcp'], overlays: [], telemetryDisabledEnv: undefined, + }) + await ctx.plugin(frontend, frontend.Config(config)) + return { ctx, exit, stdout, stderr, stdin, ready: () => { + committed = true + for (const listener of [...listeners]) listener() + listeners.clear() + } } +} + +describe('Computer Use MCP startup', () => { + it('serves after readiness with the configured consent and joins disposal', async () => { + const { ctx, exit, ready, stdin } = await boot([], { consent: 'allow' }) + const options = vi.mocked(createCuaMcpServer).mock.calls[0]?.[1] + if (options === undefined) throw new Error('the frontend did not construct a server') + expect(options).toMatchObject({ consent: 'allow', cwd: '/workspace' }) + expect(connect).not.toHaveBeenCalled() + ready() + expect(connect).toHaveBeenCalledOnce() + expect(StdioServerTransport).toHaveBeenCalledOnce() + stdin.end() + expect(exit).toHaveBeenCalledWith(0) + await ctx.fiber.dispose() + expect(options.signal.aborted).toBe(true) + expect(dispose).toHaveBeenCalledOnce() + }) + + it('prints client configuration and exits without claiming stdin or constructing a server', async () => { + const { exit, stdout, ready, stdin } = await boot(['--print-client-config', 'json']) + const document = JSON.parse(stdout.join('')) as { mcpServers: Record }> } + expect(document.mcpServers.dsh_cua).toEqual({ + type: 'stdio', command: process.execPath, args: [...process.execArgv, process.argv[1], '--profile', 'cua-mcp'], + env: { DSH_HOME: '/home/me/.dsh', DSH_CUA_CONSENT: 'elicit' }, + }) + expect(exit).toHaveBeenCalledWith(0) + expect(createCuaMcpServer).not.toHaveBeenCalled() + ready() + stdin.end() + expect(exit).toHaveBeenCalledTimes(1) + }) + + it('rejects an unknown client and documents help without starting anything', async () => { + const unknown = await boot(['--print-client-config', 'cursor']) + expect(unknown.exit).toHaveBeenCalledWith(1) + expect(unknown.stderr.join('')).toContain('Allowed choices are codex, claude-code, json') + const help = await boot(['--help']) + expect(help.stdout.join('')).toContain('Usage: dsh --profile cua-mcp [options]') + expect(help.stdout.join('')).toContain('--print-client-config codex') + expect(help.stdout.join('')).toContain('DSH_CUA_CONSENT=allow') + expect(help.exit).toHaveBeenCalledWith(0) + expect(createCuaMcpServer).not.toHaveBeenCalled() + expect(StdioServerTransport).not.toHaveBeenCalled() + }) + + it('reports a transport startup failure through bounded exit, except during disposal', async () => { + connect.mockRejectedValueOnce(new Error('transport start failed')) + const failing = await boot([]) + failing.ready() + await vi.waitFor(() => { expect(failing.exit).toHaveBeenCalledWith(1) }) + const opening = Promise.withResolvers() + connect.mockImplementationOnce(async () => { await opening.promise }) + const closing = await boot([]) + closing.ready() + const disposal = closing.ctx.fiber.dispose() + opening.reject(new Error('transport released')) + await disposal + expect(closing.exit).not.toHaveBeenCalled() + }) + + it('requires the profile launcher and validates the consent mode', () => { + const ctx = new Context() + roots.push(ctx) + provideCmdline(ctx, { args: [], exit: () => {}, ready: { onReady: () => () => {} } }) + expect(() => { frontend.apply(ctx, frontend.Config({})) }).toThrow('requires the dsh profile launcher') + expect(frontend.Config({})).toEqual({ consent: 'elicit' }) + expect(() => frontend.Config({ consent: 'ask' as 'allow' })).toThrow() + }) +}) diff --git a/packages/experimental/cua-mcp/tsconfig.json b/packages/experimental/cua-mcp/tsconfig.json new file mode 100644 index 0000000000..132e683b44 --- /dev/null +++ b/packages/experimental/cua-mcp/tsconfig.json @@ -0,0 +1,48 @@ +{ + "extends": "../../../tsconfig.base.json", + "compilerOptions": { + "rootDir": "src", + "outDir": "lib/types" + }, + "include": [ + "src" + ], + "references": [ + { + "path": "../../../vendor/cordis" + }, + { + "path": "../../../vendor/schemastery" + }, + { + "path": "../../boot/cmdline" + }, + { + "path": "../../boot/app-boot" + }, + { + "path": "../../core/agent" + }, + { + "path": "../../core/tools" + }, + { + "path": "../../core/system-prompt" + }, + { + "path": "../../llm/llm" + }, + { + "path": "../../attachment/attachment" + }, + { + "path": "../../interaction/user-questions" + }, + { + "path": "../../preset/agent-preset-registry" + }, + { + "path": "../cua/tsconfig.host.json" + } + ] +} diff --git a/packages/experimental/cua/README.i18n.yaml b/packages/experimental/cua/README.i18n.yaml index fc00ea02a5..ba0130af67 100644 --- a/packages/experimental/cua/README.i18n.yaml +++ b/packages/experimental/cua/README.i18n.yaml @@ -15,14 +15,14 @@ en: 5db4d4fea25493b9 zh: 65ab64fc24eb0d09 /deepseek-ai-dsh-cua/use-this-package: - en: ebc2d6ea04122446 - zh: f09dec2da7fc828b + en: df3d4eded3c57623 + zh: 99032ff0811b49c5 /deepseek-ai-dsh-cua/use-this-package/permission-controls: en: 8941f2139fd1ca3a zh: 4c8fb953d821eaf1 /deepseek-ai-dsh-cua/understand-the-implementation: - en: 3cc775fe0364fc89 - zh: bb6b1aa8b24f3581 + en: f2faa22bd811eaa8 + zh: 1c246d3d5a75c156 /deepseek-ai-dsh-cua/further-exploration: en: c174fb5a00ea3681 zh: 039340042676881d diff --git a/packages/experimental/cua/README.md b/packages/experimental/cua/README.md index 849c520d43..432a580010 100644 --- a/packages/experimental/cua/README.md +++ b/packages/experimental/cua/README.md @@ -41,7 +41,7 @@ Keyboard methods are available in the scopes a provider declares; the provider o Observation methods emit and return their result. Use `void await app.getAccessibilityTree()` for one visible copy, or use `emit:false` and print the returned text once. `window.getScreenshot()` returns `CuaScreenshot` with `bytes`, `mimeType`, `pixelWidth`, `pixelHeight`, and `windowId`. The image sink receives the same object. Use its MIME type when selecting a file extension or declaring an image; the format can be PNG, JPEG, WebP, or GIF. Each screenshot enters the attachment pipeline once; `emit:false` only suppresses the object sink. -`tools.cua` returns operation values directly. Screenshot values retain the encoded image Base64 and add a durable `attachment` reference for the tool renderer; model content contains coordinate metadata and one image, without the encoded bytes. Before capture, the tool requires an attachment store and a resolved model route declaring image input. Admission and storage failures reject the call. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. +`tools.cua` returns operation values directly. Screenshot values retain the encoded image Base64 and add a durable `attachment` reference for the tool renderer; model content contains coordinate metadata and one image, without the encoded bytes. Before capture, the tool requires an attachment store and either a configured `screenshotTarget` or a resolved model route declaring image input. Admission and storage failures reject the call. The object bridge preserves the screenshot bytes and validated metadata without uploading or emitting the same image again. Application consent precedes launch, observation, capture, and input. Session access is stored by conversation and application identity and survives DSH restart and Computer Use disablement. Other conversations require their own consent. Saved grants require a platform-provided reusable application identity. Refusal and revocation close affected Agent connections, so their old objects require fresh selection. No input is replayed after cancellation, timeout, or reconnect. @@ -93,7 +93,7 @@ Provider unload waits for its CUA programs and native input cleanup to settle be `agentPreset` defaults to `ptc`: matching Agents receive the raw `cua` tool and PTC guidance; every other composed preset receives only `cua_run_code` and its guidance. This includes Standard, Creator, Minimal, and custom presets. Registration uses `agent/created`, `agent-preset/selected`, and Agent-owned scopes, including Agents already present when the provider loads. Agent disposal removes its registrations and releases its retained environment. Provider unload also disposes the dedicated CUA runtime. Agents without a composed preset receive neither tool. Set `agentPreset: false` to register the raw `cua` tool globally in standalone compositions. The Host owns permissions, native connections, and cancellation; preset definitions remain unchanged. -`cua_run_code` reuses the PTC program-tool factory with one isolated Node runtime owned by the CUA provider. Each Agent has a separate retained process selected by its `stateOwner`. A separate initialization program installs `cua` before model code executes in the same environment, including one-shot escalated runs. The factory binds only the private `cua` operation tool and preserves nested policy checks, guards, logs, cancellation, and screenshot delivery. The private tool is absent from the model's direct tool list. +`cua_run_code` reuses the PTC program-tool factory with one isolated Node runtime owned by the CUA provider. Each Agent has a separate retained process selected by its `stateOwner`. A separate initialization program installs `cua` before model code executes in the same environment, including one-shot escalated runs. The factory binds only the private `cua` operation tool and preserves nested policy checks, guards, logs, cancellation, and screenshot delivery. The private tool is absent from the model's direct tool list. While this runtime exists, the provider publishes `ctx.cuaPrograms`: `reset(agent)` cancels that Agent's active program, releases its retained environment without running program code, and keeps application grants and native connections, so the next program starts a fresh process and recreates `cua`; `screenshotRequestTarget(image)` returns the request-image target a configured `screenshotTarget` selected for a stored screenshot, so a host that forwards screenshots outside a model request delivers the version the program observed. [The operation schema](src/protocol.ts) is the authority for model parameters and separately declared Host-only fields. Native implementations enforce target identity, window geometry, resource limits, and operating-system access at execution. The permission store owns durable consent separately from the native protocol. diff --git a/packages/experimental/cua/README.zh.md b/packages/experimental/cua/README.zh.md index d6bbe76327..f6eef753ef 100644 --- a/packages/experimental/cua/README.zh.md +++ b/packages/experimental/cua/README.zh.md @@ -41,7 +41,7 @@ kind: "package-reference" 观察方法会输出并返回结果。使用 `void await app.getAccessibilityTree()` 只展示一份内容,或使用 `emit:false` 后打印一次返回文本。`window.getScreenshot()` 返回包含 `bytes`、`mimeType`、`pixelWidth`、`pixelHeight` 和 `windowId` 的 `CuaScreenshot`,图片输出回调接收同一个对象。选择文件后缀或声明图片时使用其中的 MIME 类型;格式可能是 PNG、JPEG、WebP 或 GIF。每张截图只进入一次附件处理链;`emit:false` 只抑制对象层的输出。 -`tools.cua` 直接返回操作结果。截图结果保留图片 Base64,并增加供工具渲染使用的持久 `attachment` 引用;模型内容只包含坐标元数据和一张图片,不包含编码字节。截图前要求附件服务可用,并确认当前模型支持图片输入。图片接入或保存失败会拒绝调用。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 +`tools.cua` 直接返回操作结果。截图结果保留图片 Base64,并增加供工具渲染使用的持久 `attachment` 引用;模型内容只包含坐标元数据和一张图片,不包含编码字节。截图前要求附件服务可用,且已配置 `screenshotTarget` 或当前模型路由声明图片输入。图片接入或保存失败会拒绝调用。对象桥接保留截图字节和已校验的元数据,不重复上传或输出同一张图片。 应用授权发生在启动、观察、截图和输入之前。会话许可按对话和应用身份持久化,重启 DSH 或关闭 Computer Use 后仍可复用,其他对话需要单独授权。长期许可要求平台提供可复用的应用身份。拒绝或撤销会关闭受影响的 Agent 连接,因此旧对象必须重新选择目标。取消、超时或重新连接后均不重放输入。 @@ -93,7 +93,7 @@ Computer Use 详情页的权限卡片、组件列表和来源信息使用 l3 边 `agentPreset` 默认为 `ptc`:匹配的 Agent 获得原始 `cua` 工具和 PTC 指引,其他已组合的 preset 只获得 `cua_run_code` 及其指引,包括标准、创造、极简和自定义 preset。注册使用 `agent/created`、`agent-preset/selected` 事件和 Agent 拥有的作用域,也处理提供方加载前已存在的 Agent。Agent 销毁会移除其注册并释放保留环境,提供方卸载还会释放专用 CUA 运行时。未组合 preset 的 Agent 不获得这两个工具。在独立组合中设置 `agentPreset: false` 可全局注册原始 `cua` 工具。Host 负责权限、本机连接和取消;preset 定义保持不变。 -`cua_run_code` 复用 PTC 程序工具工厂,由 CUA 提供方持有一个隔离的 Node 运行时。每个 Agent 通过自己的 `stateOwner` 选择独立的保留进程。独立的初始化程序在同一环境中先安装 `cua`,再执行模型代码;单次提权执行也遵守此顺序。工厂只绑定私有 `cua` 操作工具,保留嵌套策略检查、guard、日志、取消和截图交付。私有工具不会出现在模型可直接调用的工具列表中。 +`cua_run_code` 复用 PTC 程序工具工厂,由 CUA 提供方持有一个隔离的 Node 运行时。每个 Agent 通过自己的 `stateOwner` 选择独立的保留进程。独立的初始化程序在同一环境中先安装 `cua`,再执行模型代码;单次提权执行也遵守此顺序。工厂只绑定私有 `cua` 操作工具,保留嵌套策略检查、guard、日志、取消和截图交付。私有工具不会出现在模型可直接调用的工具列表中。该运行时存在期间,提供方发布 `ctx.cuaPrograms`:`reset(agent)` 取消该 Agent 正在运行的程序,在不执行程序代码的情况下释放其保留环境,并保留应用授权和本机连接,下一次程序在新进程中重新创建 `cua`;`screenshotRequestTarget(image)` 返回已配置的 `screenshotTarget` 为某张已存储截图选定的请求图片目标,使在模型请求之外转发截图的宿主交付程序观察到的那一版。 [操作 schema](src/protocol.ts) 定义模型参数,并单独声明 Host 专用字段。原生实现在执行时检查目标身份、窗口几何、资源上限和操作系统访问条件。授权存储独立于原生协议保存持久许可。 diff --git a/packages/experimental/cua/src/config.ts b/packages/experimental/cua/src/config.ts index dc67be1326..c73751b798 100644 --- a/packages/experimental/cua/src/config.ts +++ b/packages/experimental/cua/src/config.ts @@ -1,5 +1,6 @@ /** Schemastery fields for platform-specific native CUA configuration. */ import Schema from '@deepseek-ai/schemastery' +import { longEdgeDimensions, type ImageAttachmentRef, type ImageRequestTarget } from '@deepseek-ai/dsh-attachment' import NodePtcRuntime, { type Config as NodeRuntimeConfig } from '@deepseek-ai/dsh-ptc-runtime-node' import { RunCodeConfig } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' @@ -21,11 +22,36 @@ export const CuaRunCodeConfig: Schema, CuaRunCodeConfi executor: RunCodeConfig.default({}), }) +/** Fixed request-image target for screenshots when no model route selects one. */ +export interface CuaScreenshotTargetConfig { + /** Exact long-edge pixel target; a source at or below it keeps its size. */ + longEdge: number + /** Encoded-byte target before Base64 expansion; the smallest quality-ladder output is kept when no quality fits. */ + maxBytes: number +} + +/** Validate an explicit screenshot target; omission resolves the target from the Agent's model route. */ +export const CuaScreenshotTargetConfig: Schema = Schema.object({ + longEdge: Schema.number().step(1).min(1).max(16_384).required(), + maxBytes: Schema.number().step(1).min(1024).required(), +}) + +/** + * Project a configured screenshot target onto one stored image. + * @param configured - Validated `screenshotTarget`. + * @param image - Durable normalized screenshot. + * @returns The request target for that image: the long edge capped at the configured value, the configured byte budget. + */ +export function fixedScreenshotTarget(configured: CuaScreenshotTargetConfig, image: ImageAttachmentRef): ImageRequestTarget { + return { ...longEdgeDimensions(image.width, image.height, configured.longEdge), maxBytes: configured.maxBytes } +} + /** Shared configuration fields extended by native platform providers. */ export const CuaConfigFields = { requireSystemPointerApproval: Schema.boolean().default(true), agentPreset: Schema.union([Schema.string().min(1), Schema.const(false)]).default('ptc'), runCode: CuaRunCodeConfig.default({}), + screenshotTarget: Schema.union([CuaScreenshotTargetConfig, Schema.const(undefined)]), allowedApps: Schema.array(Schema.object({ id: Schema.string().pattern(/^[a-f0-9]{64}$/).required(), name: Schema.string().required(), executablePath: Schema.string().min(1), diff --git a/packages/experimental/cua/src/guidance.ts b/packages/experimental/cua/src/guidance.ts index 3400bec2c9..866304d38d 100644 --- a/packages/experimental/cua/src/guidance.ts +++ b/packages/experimental/cua/src/guidance.ts @@ -1,6 +1,9 @@ /** Shared model instructions for native application and window operations. */ const hoverSignature = 'mouseMove(target: string | [number, number], options?: { relative?: boolean })' +/** System-prompt section that carries the CUA operation guidance for one Agent. */ +export const CUA_PROMPT_SECTION_NAME = 'computer-use:dsh-cua' + /** Async method catalog with consent and observation rules, grouped by observation, mouse, and keyboard. */ export const COMMON_GUIDANCE = `Use cua to observe and operate native applications. Always use cua.getCapabilities() to confirm whether a specific API is available on the current platform; its reported capabilities take precedence over availability statements in these instructions. All methods are async; observation options default to { emit: true }, and emit: false suppresses sink output only, leaving returned values unchanged. Actions report dispatch evidence, not verified completion. If sessionLocked is true or an operation reports SESSION_LOCKED, stop UI actions and ask the user to unlock the desktop session; null or unknown means verify a usable unlocked desktop session first. cua.getApp requests user consent; if access is denied or revoked, stop using that application until the user explicitly permits another request, and never bypass a refusal or switch tools to avoid it. Never replay uncertain input without a fresh observation. diff --git a/packages/experimental/cua/src/index.ts b/packages/experimental/cua/src/index.ts index 5876ffd9e2..2edcba3fd2 100644 --- a/packages/experimental/cua/src/index.ts +++ b/packages/experimental/cua/src/index.ts @@ -8,7 +8,7 @@ import Schema from '@deepseek-ai/schemastery' import type { Agent } from '@deepseek-ai/dsh-agent' import { ComputerUseProviderName } from '@deepseek-ai/dsh-computer-use/brand' import { admitEncodedImages } from '@deepseek-ai/dsh-attachment' -import type { ImageAttachmentRef } from '@deepseek-ai/dsh-attachment' +import type { ImageAttachmentRef, ImageRequestTarget } from '@deepseek-ai/dsh-attachment' import type { ContentBlock } from '@deepseek-ai/dsh-llm' import type { JsonValue } from '@deepseek-ai/dsh-util-values' import { z } from 'zod' @@ -20,7 +20,7 @@ import { ApplicationAuthorizationResult, installCuaAccess } from './access.ts' import type { CuaApplicationGrant, CuaApplicationId, CuaSystemPermission } from './access-types.ts' import type { CuaAppHandle, CuaOperation, CuaStartupCapabilities } from './types.ts' import { ApplicationIcon, AppResult, NativeScreenshotResult, Request, SystemPointerRequest, ScreenshotResult, StateResult, WindowsResult } from './protocol.ts' -import { CuaConfigFields, type CuaRunCodeConfig } from './config.ts' +import { CuaConfigFields, fixedScreenshotTarget, type CuaRunCodeConfig, type CuaScreenshotTargetConfig } from './config.ts' import { installCuaTools } from './tool-registration.ts' import { CuaCoordinates } from './coordinates.ts' import type { ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools' @@ -31,6 +31,7 @@ import type {} from '@deepseek-ai/cordis-plugin-loader' export { CuaAccess } from './access.ts' export type { CuaStartupCapabilities } from './types.ts' +export type { CuaPrograms } from './tool-registration.ts' /** Native executable and per-operation resource bounds. */ export interface CuaConfig { @@ -40,6 +41,11 @@ export interface CuaConfig { agentPreset: string | false /** Dedicated persistent program limits, independent of the profile's PTC runtime. */ runCode: CuaRunCodeConfig + /** + * Fixed request-image target for screenshots. Omission resolves the target from the Agent's model + * route and refuses capture when that route declares no image input. + */ + screenshotTarget?: CuaScreenshotTargetConfig | undefined /** Legacy grants imported once into profile-scoped storage; later edits are ignored. */ allowedApps: Array & { /** Unbranded digest at the profile configuration boundary; admitted by the Config schema. */ @@ -108,10 +114,13 @@ function renderResult(args: unknown, value: JsonValue): ContentBlock[] { return [{ type: 'text', text: JSON.stringify(metadata) }, { type: 'image', attachment }] } -/** Resolve the exact calling model and attachment store before requesting a screenshot. */ -async function screenshotStore(ctx: Context, execution: Readonly) { +/** Resolve the attachment store and the request-image target before requesting a screenshot. */ +async function screenshotStore(ctx: Context, execution: Readonly, configured: CuaScreenshotTargetConfig | undefined) { const attachments = ctx.get('attachments') if (!attachments) throw new Error('CUA screenshots require an attachment store') + if (configured !== undefined) { + return { attachments, target: (image: ImageAttachmentRef): ImageRequestTarget => fixedScreenshotTarget(configured, image) } + } const agent = execution.agent const routed = agent.session.requestHeader()?.config const provider = routed?.provider ?? agent.options.provider @@ -243,7 +252,7 @@ export function installCua(ctx: Context, config: CuaConfig, backend: CuaBackend) : params const requestNative = () => client.request(method, nativeParams, signal, execution.callId) if (method === 'screenshot') { - const { attachments, target } = await screenshotStore(ctx, execution) + const { attachments, target } = await screenshotStore(ctx, execution, config.screenshotTarget) const screenshot = NativeScreenshotResult.parse(await requestNative()) if (screenshot.windowId !== parsedParams.windowId) throw new NativeError('NATIVE_PROTOCOL', 'Native screenshot belongs to another window') signal.throwIfAborted() diff --git a/packages/experimental/cua/src/tool-registration.ts b/packages/experimental/cua/src/tool-registration.ts index 9260f06ffb..e3e66a9e17 100644 --- a/packages/experimental/cua/src/tool-registration.ts +++ b/packages/experimental/cua/src/tool-registration.ts @@ -3,18 +3,50 @@ import type { Context } from '@deepseek-ai/cordis' import type { Agent } from '@deepseek-ai/dsh-agent' import { createScope, type Scope } from '@deepseek-ai/dsh-scope' import NodePtcRuntime from '@deepseek-ai/dsh-ptc-runtime-node' -import { createRunCodeTool } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' +import { createRunCodeToolHandle } from '@deepseek-ai/dsh-tool-executor-ptc/run-code' import type { ToolDefinition } from '@deepseek-ai/dsh-tools' +import type { ImageAttachmentRef, ImageRequestTarget } from '@deepseek-ai/dsh-attachment' import type { PromptSection } from '@deepseek-ai/dsh-system-prompt' import type {} from '@deepseek-ai/dsh-agent-preset-registry' import type {} from '@deepseek-ai/dsh-working-directory' import type { CuaConfig } from './index.ts' +import { fixedScreenshotTarget } from './config.ts' +import { CUA_PROMPT_SECTION_NAME } from './guidance.ts' const programDescription = 'Run a TypeScript program to observe and operate desktop applications. ' + 'The global cua object is ready to use; retain application and window objects across calls. ' + 'Only tools.cua is available inside the program. Call other session tools directly. ' + 'Print the values you need or leave a final expression; screenshots are attached after the program finishes.' +/** Host control over the dedicated `cua_run_code` environments; registered as `ctx.cuaPrograms`. */ +export interface CuaPrograms { + /** + * Release one Agent's retained program environment. Active programs of that Agent are cancelled, new + * programs wait for cleanup, and the next `cua_run_code` call starts a fresh process that re-creates the + * `cua` global; application grants, native connections, and the desktop applications themselves are + * unaffected. Resolves when no environment exists. + * @param agent - Agent whose `cua_run_code` state owner is released. + * @returns Completion after the process and its nested-call cleanup settle. + * @throws CodeResetFailedError when cleanup fails; programs stay blocked until a later reset succeeds. + */ + reset(agent: Agent): Promise + /** + * Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. + * A host that forwards screenshots outside a model request reads the same request version with it, so the + * image a caller sees matches the coordinate space the provider mapped. + * @param image - Durable screenshot attachment from a `cua` result. + * @returns The fixed target, or undefined when the Agent's model route selects the delivered version. + */ + screenshotRequestTarget(image: ImageAttachmentRef): ImageRequestTarget | undefined +} + +declare module '@deepseek-ai/cordis' { + interface Context { + /** Present while the CUA provider owns a dedicated program runtime. */ + cuaPrograms: CuaPrograms + } +} + /** * Register raw CUA for its configured PTC preset and a persistent program tool for other presets. * @param ctx Provider context owning native calls and registrations. @@ -25,7 +57,7 @@ const programDescription = 'Run a TypeScript program to observe and operate desk */ export function installCuaTools(ctx: Context, config: CuaConfig, tool: ToolDefinition, guidance: string): () => void | Promise { const bridgeUrl = JSON.stringify(new URL('../lib/bridge.js', import.meta.url).href) - const prompt = { name: 'computer-use:dsh-cua', order: ctx.systemPrompt.getSectionOrder('TOOL_COMPUTER_USE') } + const prompt = { name: CUA_PROMPT_SECTION_NAME, order: ctx.systemPrompt.getSectionOrder('TOOL_COMPUTER_USE') } const rawPrompt: PromptSection = { ...prompt, text: () => { const runtime = ctx.get('ptcRuntime') return !runtime?.retainsState ? guidance : `${guidance} @@ -52,11 +84,17 @@ var cua = connectCua(() => tools.cua, text => console.log(text)); const programs = runtimeCtx.plugin({ name: 'cua-program-tools', inject: ['ptcRuntime', 'tools', 'workingDirectory', 'agentPresets', 'agents', 'systemPrompt'], apply(consumer: Context) { - const program = createRunCodeTool(consumer, { + const program = createRunCodeToolHandle(consumer, { name: 'cua_run_code', description: programDescription, runtime: consumer.ptcRuntime, tools: [tool], limits: config.runCode.executor, initialization: `globalThis.cua ??= (await import(${bridgeUrl})).connectCua(() => tools.cua, text => console.log(text));`, }) + // Hosts without a model (MCP frontends) reset through this service; the factory owns call coordination. + consumer.provide('cuaPrograms', { + reset: (agent: Agent) => program.reset(agent), + screenshotRequestTarget: image => config.screenshotTarget === undefined + ? undefined : fixedScreenshotTarget(config.screenshotTarget, image), + } satisfies CuaPrograms) const scopes = new Map void } }>() consumer.effect(() => async () => { await Promise.all([...scopes.values()].map(({ scope }) => scope.dispose())) @@ -74,7 +112,7 @@ var cua = connectCua(() => tools.cua, text => console.log(text)); scopes.set(agent, entry) scope.ctx.effect(() => () => { scopes.delete(agent) }, 'cua.agent-tools') } - const remove = register(entry.scope.ctx, kind === 'raw' ? tool : program, + const remove = register(entry.scope.ctx, kind === 'raw' ? tool : program.definition, kind === 'raw' ? rawPrompt : { ...prompt, text: guidance }) entry.current = { kind, remove } } diff --git a/packages/experimental/cua/tests/agent-scopes.spec.ts b/packages/experimental/cua/tests/agent-scopes.spec.ts index 6b4eaa4309..267cb540b8 100644 --- a/packages/experimental/cua/tests/agent-scopes.spec.ts +++ b/packages/experimental/cua/tests/agent-scopes.spec.ts @@ -71,7 +71,12 @@ it('gives every other composed preset a program tool without changing the shared expect(ctx.tools.get('cua_run_code', uncomposed.agent)).toBeUndefined() expect(ctx.tools.get('cua', uncomposed.agent)).toBeUndefined() expect(ctx.get('ptcRuntime')).toMatchObject(shared) + // The host reset entry lives with the dedicated runtime and leaves with the provider. + await expect(ctx.get('cuaPrograms')?.reset(uncomposed.agent)).resolves.toBeUndefined() + const image = { attachmentId: 'sha256:' + 'b'.repeat(64), mediaType: 'image/png', bytes: 1, width: 400, height: 200 } as const + expect(ctx.get('cuaPrograms')?.screenshotRequestTarget(image as never)).toBeUndefined() await mounted.dispose() + expect(ctx.get('cuaPrograms')).toBeUndefined() }) it('keeps explicitly configured global raw-tool registration', async () => { @@ -80,6 +85,7 @@ it('keeps explicitly configured global raw-tool registration', async () => { const handle = await create('cua-global', 'standard') expect(ctx.tools.get('cua', handle.agent)).toBeDefined() expect(ctx.tools.get('cua_run_code', handle.agent)).toBeUndefined() + expect(ctx.get('cuaPrograms')).toBeUndefined() await mounted.dispose() expect(ctx.tools.get('cua', handle.agent)).toBeUndefined() }) diff --git a/packages/experimental/cua/tests/run-code-composition.spec.ts b/packages/experimental/cua/tests/run-code-composition.spec.ts index 32625f20e6..f15a291712 100644 --- a/packages/experimental/cua/tests/run-code-composition.spec.ts +++ b/packages/experimental/cua/tests/run-code-composition.spec.ts @@ -39,11 +39,14 @@ const programs = [ class ProgramModel extends LlmAdapter { readonly requests: GenerateOptions[] = [] + /** Requests a test holds back until it has finished acting between two model steps. */ + readonly gates = new Map>() constructor(private readonly programs: readonly string[]) { super() } override resolveModel(provider: string, model: string): Promise { return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] }) } async * stream(options: GenerateOptions): AsyncIterable { + await this.gates.get(this.requests.length) const code = this.programs[this.requests.length] this.requests.push(options) if (code !== undefined) { @@ -183,6 +186,38 @@ it('retains CUA objects, guards and logs hidden subcalls, forwards screenshots, expect(ctx.ptcRuntime.retainsState).toBe(false) }) +it('resets one Agent program environment through ctx.cuaPrograms while keeping its application access', async () => { + const { ctx, native, model, agent, run } = await setup([ + 'globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); process.pid', + 'typeof win === "undefined" ? ({ reset: true, visits: globalThis.visits ?? null, pid: process.pid }) : ({ reset: false, pid: process.pid })', + ]) + const programs = ctx.get('cuaPrograms') + if (programs === undefined) throw new Error('CUA provider did not publish ctx.cuaPrograms') + // Hold the second model request until the host reset between the two programs has settled. + const firstSettled: PromiseWithResolvers = Promise.withResolvers() + const resetDone: PromiseWithResolvers = Promise.withResolvers() + model.gates.set(1, resetDone.promise) + ctx.on('session/event', (session, event) => { + if (session === agent.session && event.type === 'tool/result' && event.data.message.toolCallId === 'cua-program-1') firstSettled.resolve() + }) + const completed = run() + await firstSettled.promise + await programs.reset(agent) + resetDone.resolve() + await completed + const results = agent.session.deriveMessages().filter(message => message.role === 'tool') + expect(results.map(result => result.isError)).toEqual([false, false]) + const text = (index: number) => JSON.parse(results[index]!.content.filter(block => block.type === 'text').map(block => block.text).join('\n')) as Record + const firstPid = z.number().int().positive().parse(text(0)) + const second = text(1) + expect(second).toMatchObject({ reset: true, visits: null }) + expect(second.pid).not.toBe(firstPid) + expect(() => process.kill(firstPid, 0)).toThrow() + // The native connection and its application grant survive; only the program process was replaced. + expect(native.state).toMatchObject({ openedChannels: 1, closedChannels: 0 }) + await expect(programs.reset(agent)).resolves.toBeUndefined() +}) + it('settles an in-flight native call before releasing the provider connection and program process', async () => { const { ctx, native, agent, provider, run } = await setup([ 'var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); process.pid', diff --git a/packages/extensions/tool-cordis/src/api-catalog.ts b/packages/extensions/tool-cordis/src/api-catalog.ts index 2891154907..f2141101da 100644 --- a/packages/extensions/tool-cordis/src/api-catalog.ts +++ b/packages/extensions/tool-cordis/src/api-catalog.ts @@ -976,6 +976,26 @@ export const SERVICE_API: readonly ServiceApiEntry[] = [ }, ], }, + { + key: 'cuaPrograms', + summary: 'Host control over the dedicated `cua_run_code` environments; registered as `ctx.cuaPrograms`.', + description: 'Host control over the dedicated `cua_run_code` environments; registered as `ctx.cuaPrograms`.', + methods: [ + { + signature: 'reset(agent: Agent): Promise', + description: 'Release one Agent\'s retained program environment. Active programs of that Agent are cancelled, new programs wait for cleanup, and the next `cua_run_code` call starts a fresh process that re-creates the `cua` global; application grants, native connections, and the desktop applications themselves are unaffected. Resolves when no environment exists.', + parameters: [{ name: 'agent', description: 'Agent whose `cua_run_code` state owner is released.' }], + returns: 'Completion after the process and its nested-call cleanup settle.', + throws: ['CodeResetFailedError when cleanup fails; programs stay blocked until a later reset succeeds.'], + }, + { + signature: 'screenshotRequestTarget(image: ImageAttachmentRef): ImageRequestTarget | undefined', + description: 'Request-image target the provider delivered for a stored screenshot when `screenshotTarget` is configured. A host that forwards screenshots outside a model request reads the same request version with it, so the image a caller sees matches the coordinate space the provider mapped.', + parameters: [{ name: 'image', description: 'Durable screenshot attachment from a `cua` result.' }], + returns: 'The fixed target, or undefined when the Agent\'s model route selects the delivered version.', + }, + ], + }, { key: 'deepseekAccount', summary: 'Account login, credentials, and client-safe Remote operations.', diff --git a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md index 489d3c98ce..90b34bd430 100644 --- a/packages/preset/agent-preset/skills/dsh-doc/references/packages.md +++ b/packages/preset/agent-preset/skills/dsh-doc/references/packages.md @@ -198,6 +198,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo | `@deepseek-ai/dsh-client-ui-plugin-recommendations` | no | Official plugin card body with catalog text and enabling | | `@deepseek-ai/dsh-creation-recommendations` | no | Create persistent removable interface plugins from explicit conversation needs | | `@deepseek-ai/dsh-cua` | no | Shared Computer Use application objects, authorization, and logged tool execution | +| `@deepseek-ai/dsh-cua-mcp` | yes | Computer Use as an MCP stdio server: a dsh profile bundle that exposes cua_run_code to external agent harnesses | | `@deepseek-ai/dsh-experimental-api-speech-to-text` | yes | Authenticated experimental speech transcription for browser clients | | `@deepseek-ai/dsh-experimental-auto-review` | no | Per-tool LLM authorization review for the DeepSeek Harness Auto permission preset | | `@deepseek-ai/dsh-experimental-browser-use-chrome-devtools-mcp` | yes | Experimental per-Session Chromium browser tools through chrome-devtools-mcp | diff --git a/packages/util/official-bundles/src/bundles.ts b/packages/util/official-bundles/src/bundles.ts index b84847a4aa..956ae3b1e7 100644 --- a/packages/util/official-bundles/src/bundles.ts +++ b/packages/util/official-bundles/src/bundles.ts @@ -56,6 +56,7 @@ export const DEFAULT_PROFILE_BUNDLES: readonly string[] = ['@deepseek-ai/dsh-bas export const OPTIONAL_BUNDLES: readonly string[] = [ '@deepseek-ai/dsh-personalized-recommendations', '@deepseek-ai/dsh-cua-bundle', + '@deepseek-ai/dsh-cua-mcp', '@deepseek-ai/dsh-experimental-session-search', '@deepseek-ai/dsh-experimental-ralph-bundle', '@deepseek-ai/dsh-experimental-terminal-bundle', diff --git a/packages/util/official-bundles/src/plugin-manager.ts b/packages/util/official-bundles/src/plugin-manager.ts index 64477cac6c..951d97256e 100644 --- a/packages/util/official-bundles/src/plugin-manager.ts +++ b/packages/util/official-bundles/src/plugin-manager.ts @@ -18,7 +18,8 @@ export const PROTECTED_PLUGINS: ReadonlySet = new Set([ ]) /** - * Built-in profile bundles, persistent terminals, and the standalone worktree tool, which have no plugin manager page. + * Built-in profile bundles, persistent terminals, the standalone worktree tool, and the Computer Use MCP profile + * bundle, which have no plugin manager page. * Their Host availability and activation stay intact. */ export const HIDDEN_BUNDLES: ReadonlySet = new Set([ @@ -30,6 +31,7 @@ export const HIDDEN_BUNDLES: ReadonlySet = new Set([ '@deepseek-ai/dsh-sdk-minimal', '@deepseek-ai/dsh-experimental-terminal-bundle', '@deepseek-ai/dsh-experimental-tool-worktree', + '@deepseek-ai/dsh-cua-mcp', ]) /** @@ -63,6 +65,7 @@ export const MORE_BUNDLES: readonly string[] = [ export const EXPERIMENTAL_BUNDLES: ReadonlySet = new Set([ '@deepseek-ai/dsh-personalized-recommendations', '@deepseek-ai/dsh-cua-bundle', + '@deepseek-ai/dsh-cua-mcp', '@deepseek-ai/dsh-experimental-voice-input-bundle', '@deepseek-ai/dsh-experimental-auto-review', '@deepseek-ai/dsh-experimental-inspector-profile', diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9c5adf7354..0c00984def 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -342,6 +342,9 @@ importers: '@deepseek-ai/dsh-cua-bundle': specifier: workspace:* version: link:../../packages/experimental/cua-bundle + '@deepseek-ai/dsh-cua-mcp': + specifier: workspace:* + version: link:../../packages/experimental/cua-mcp '@deepseek-ai/dsh-experimental-auto-review': specifier: workspace:* version: link:../../packages/experimental/auto-review @@ -10138,6 +10141,113 @@ importers: specifier: ^0.35.3 version: 0.35.5(@types/node@22.20.1) + packages/experimental/cua-mcp: + dependencies: + '@deepseek-ai/dsh-agent-preset': + specifier: workspace:* + version: link:../../preset/agent-preset + '@deepseek-ai/dsh-agent-preset-registry': + specifier: workspace:* + version: link:../../preset/agent-preset-registry + '@deepseek-ai/dsh-cmdline': + specifier: workspace:* + version: link:../../boot/cmdline + '@deepseek-ai/dsh-computer-use': + specifier: workspace:* + version: link:../../computer-use/computer-use + '@deepseek-ai/dsh-cua': + specifier: workspace:* + version: link:../cua + '@deepseek-ai/dsh-llm': + specifier: workspace:* + version: link:../../llm/llm + '@deepseek-ai/dsh-session': + specifier: workspace:* + version: link:../../core/session + '@deepseek-ai/dsh-user-questions': + specifier: workspace:* + version: link:../../interaction/user-questions + '@deepseek-ai/schemastery': + specifier: link:../../../vendor/schemastery + version: link:../../../vendor/schemastery + '@modelcontextprotocol/server': + specifier: 2.2.0 + version: 2.2.0 + commander: + specifier: ^15.0.0 + version: 15.0.0 + zod: + specifier: 4.6.6 + version: 4.6.6 + devDependencies: + '@deepseek-ai/cordis': + specifier: workspace:~ + version: link:../../../vendor/cordis + '@deepseek-ai/cordis-plugin-include': + specifier: workspace:~ + version: link:../../../vendor/include + '@deepseek-ai/cordis-plugin-loader': + specifier: workspace:~ + version: link:../../../vendor/loader + '@deepseek-ai/dsh-agent': + specifier: workspace:* + version: link:../../core/agent + '@deepseek-ai/dsh-agent-loop': + specifier: workspace:* + version: link:../../core/agent-loop + '@deepseek-ai/dsh-app-boot': + specifier: workspace:* + version: link:../../boot/app-boot + '@deepseek-ai/dsh-attachment': + specifier: workspace:* + version: link:../../attachment/attachment + '@deepseek-ai/dsh-attachment-local': + specifier: workspace:* + version: link:../../attachment/attachment-local + '@deepseek-ai/dsh-brand': + specifier: workspace:* + version: link:../../util/brand + '@deepseek-ai/dsh-fs-local': + specifier: workspace:* + version: link:../../fs/fs-local + '@deepseek-ai/dsh-ptc-runtime-node': + specifier: workspace:* + version: link:../../ptc-runtime/ptc-runtime-node + '@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-session-projection': + specifier: workspace:* + version: link:../../session/session-projection + '@deepseek-ai/dsh-subprocess-local': + specifier: workspace:* + version: link:../../subprocess/subprocess-local + '@deepseek-ai/dsh-system-prompt': + specifier: workspace:* + version: link:../../core/system-prompt + '@deepseek-ai/dsh-tool-executor-native': + specifier: workspace:* + version: link:../../core/tool-executor-native + '@deepseek-ai/dsh-tools': + specifier: workspace:* + version: link:../../core/tools + '@deepseek-ai/dsh-working-directory': + specifier: workspace:* + version: link:../../session/working-directory + '@modelcontextprotocol/client': + specifier: 2.2.0 + version: 2.2.0 + js-yaml: + specifier: ^4.3.2 + version: 4.3.2 + optionalDependencies: + '@deepseek-ai/dsh-experimental-cua-macos': + specifier: workspace:* + version: link:../cua-macos + packages/experimental/forge: dependencies: '@deepseek-ai/dsh-brand': diff --git a/scripts/experimental-package-policy.ts b/scripts/experimental-package-policy.ts index df85af1620..ce21ad110f 100644 --- a/scripts/experimental-package-policy.ts +++ b/scripts/experimental-package-policy.ts @@ -8,6 +8,7 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly> = { 'packages/experimental/cua': '@deepseek-ai/dsh-cua', 'packages/experimental/cua-bundle': '@deepseek-ai/dsh-cua-bundle', + 'packages/experimental/cua-mcp': '@deepseek-ai/dsh-cua-mcp', 'packages/experimental/tool-session-query': '@deepseek-ai/dsh-tool-session-query', 'packages/experimental/session-title-all-prompts-llm': '@deepseek-ai/dsh-session-title-all-prompts-llm', 'packages/experimental/tool-terminal': '@deepseek-ai/dsh-tool-terminal', diff --git a/scripts/gen-cordis-catalog.ts b/scripts/gen-cordis-catalog.ts index 92c46bf4b5..eaabc7f5bf 100644 --- a/scripts/gen-cordis-catalog.ts +++ b/scripts/gen-cordis-catalog.ts @@ -83,6 +83,7 @@ export const SERVICE_PAGE: Record = { browserUse: 'browser-use.md', computerUse: 'computer-use.md', cuaAccess: 'computer-use.md', + cuaPrograms: 'computer-use.md', commands: 'commands.md', compaction: 'compaction.md', cordisInspect: 'extensions.md', diff --git a/scripts/gen-doc-graphs.ts b/scripts/gen-doc-graphs.ts index 6643bd5b44..9f0205a343 100644 --- a/scripts/gen-doc-graphs.ts +++ b/scripts/gen-doc-graphs.ts @@ -268,6 +268,11 @@ const SERVICE_ROLES: ServiceRole[] = [ mode: 'core', consumers: ['cua'], note: 'The native provider owns application consent and cancellation; the optional Client page queries and changes those decisions through its Remote.', }, + { + key: 'cuaPrograms', pkg: 'cua', title: 'Computer Use program environments', + mode: 'core', consumers: ['cua-mcp'], + note: 'The provider owns the retained cua_run_code runtime; a host without a model resets one Agent environment and reads the configured screenshot request target through it.', + }, { key: 'officeKit', pkg: 'office-kit', title: 'Office rendering, conversion, and recalculation', mode: 'core', consumers: ['client-ui-sidebar-documentpreview', 'tool-office'], diff --git a/scripts/package-dependency-policy.ts b/scripts/package-dependency-policy.ts index 5285d3a2e6..0315348d43 100644 --- a/scripts/package-dependency-policy.ts +++ b/scripts/package-dependency-policy.ts @@ -67,6 +67,8 @@ const SAFE_HOST_DEPENDENCY_EXPORTS = { '@deepseek-ai/dsh-official-bundles': ['PROFILE_TEMPLATES'], '@deepseek-ai/dsh-llm': ['callConfigEquals'], '@deepseek-ai/dsh-session': ['SessionId'], + // Pure arithmetic over caller-owned dimensions. + '@deepseek-ai/dsh-attachment': ['longEdgeDimensions'], '@deepseek-ai/dsh-session-format': ['sessionFormatLogFilename'], '@deepseek-ai/dsh-storage-domain': ['defineDomain'], '@deepseek-ai/dsh-timeout': ['MAX_TIMER_DELAY_MS'], @@ -81,7 +83,7 @@ const PEER_REQUIRED_HOST_EXPORTS = { '@deepseek-ai/dsh-ptc-runtime-node/configuration': ['resolvePersistentExecution'], // CUA mounts the installed provider and shares executor error classes with PTC. '@deepseek-ai/dsh-ptc-runtime-node': ['default'], - '@deepseek-ai/dsh-tool-executor-ptc/run-code': ['RunCodeConfig', 'createRunCodeTool'], + '@deepseek-ai/dsh-tool-executor-ptc/run-code': ['RunCodeConfig', 'createRunCodeToolHandle'], // CUA checks UserQuestionError and preserves AttachmentError from image admission. '@deepseek-ai/dsh-attachment': ['admitEncodedImages'], '@deepseek-ai/dsh-user-questions': ['UserQuestionError'], diff --git a/scripts/release/families.spec.ts b/scripts/release/families.spec.ts index feed57673f..56aa525926 100644 --- a/scripts/release/families.spec.ts +++ b/scripts/release/families.spec.ts @@ -72,6 +72,7 @@ describe('release families', () => { '@deepseek-ai/dsh-creation-recommendations', '@deepseek-ai/dsh-cua-bundle', '@deepseek-ai/dsh-experimental-cua-macos', + '@deepseek-ai/dsh-cua-mcp', '@deepseek-ai/dsh-cua', '@deepseek-ai/dsh-experimental-forge-bundle', '@deepseek-ai/dsh-experimental-forge-github', diff --git a/tsconfig.base.json b/tsconfig.base.json index cbceac1a3f..c4dfaaac30 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -455,6 +455,7 @@ "@deepseek-ai/dsh-credentials": ["./packages/credentials/credentials/src"], "@deepseek-ai/dsh-credentials-local": ["./packages/credentials/credentials-local/src"], "@deepseek-ai/dsh-cua-bundle": ["./packages/experimental/cua-bundle/src"], + "@deepseek-ai/dsh-cua-mcp": ["./packages/experimental/cua-mcp/src"], "@deepseek-ai/dsh-deepseek-llm-api-extensions": ["./packages/llm/deepseek-llm-api-extensions/src"], "@deepseek-ai/dsh-deliverable-file-references": ["./packages/deliverables/deliverable-file-references/src"], "@deepseek-ai/dsh-deque": ["./packages/util/deque/src"], diff --git a/tsconfig.host.json b/tsconfig.host.json index c2eb718f3a..1c82bda831 100644 --- a/tsconfig.host.json +++ b/tsconfig.host.json @@ -327,6 +327,7 @@ { "path": "./packages/experimental/cua/tsconfig.host.json" }, { "path": "./packages/experimental/cua-bundle" }, { "path": "./packages/experimental/cua-macos" }, + { "path": "./packages/experimental/cua-mcp" }, { "path": "./packages/client/ui-sidebar-documentpreview/tsconfig.host.json" }, { "path": "./packages/client/ui-sidebar-browser/tsconfig.host.json" }, { "path": "./packages/client/ui-settings-general/tsconfig.host.json" }, From 9b53900b1a704667a510bccec2c7fe6d742e742d Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 23:10:08 +0800 Subject: [PATCH 02/24] test(cua-mcp): refresh the first-result reference for the AX read defaults --- apps/cli/tests/profiles/cua-mcp/expected/reference.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index 5e9de80508..0ff49a0f0a 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -26,7 +26,7 @@ Setup and discovery: Available at app or window level depending on the platform. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. -- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean }) -> string — read the tree within the provider limits; includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. +- getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean, maxElements?: number, maxDepth?: number }) -> string — set the node count or depth for one read. Omitted limits use the provider settings. includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. - performAction(elementId: string, action: string, argument?: JsonValue) -> ActionResult — perform an observed action with an optional direct JSON argument. @@ -51,4 +51,6 @@ Available at app or window level depending on the platform. Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +AX read defaults: maxElements=2000, maxDepth=25. + Maximum click holdMs: 5000 ms. From 2924feb6219416fa42d4a47f783273a801e60e0a Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Mon, 9 Nov 2026 23:45:07 +0800 Subject: [PATCH 03/24] docs(cua-mcp): state the measured first-result size and the manual permission grant --- packages/experimental/cua-mcp/README.i18n.yaml | 8 ++++---- packages/experimental/cua-mcp/README.md | 4 ++-- packages/experimental/cua-mcp/README.zh.md | 4 ++-- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index f4ae1f8766..9b17f3cdc2 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -21,8 +21,8 @@ en: c41e73c449ec4e64 zh: 9e4ff33e1d97f1f3 /deepseek-ai-dsh-cua-mcp/use-this-package/connect-a-client: - en: d1c0e8f54a1a9eca - zh: 86a0f883c2f7edce + en: ef9f2e7d9adf2b7b + zh: 09b54d8bb7e9924d /deepseek-ai-dsh-cua-mcp/use-this-package/what-you-get: en: 2c9cae657eb4af9d zh: f8cb92292bf0ebf3 @@ -45,8 +45,8 @@ en: 9dd9bcd00366b601 zh: 7214d47c915dc601 /deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/token-effect: - en: c84f22846abe33ed - zh: 78c261ffea81a653 + en: 818abe2e0564898d + zh: 5741cfcc664939e1 /deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/kv-cache-effect: en: 2c22520787915229 zh: 21dafc45d1a4bc0d diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index 4fcdb76f09..99a5ff5ef4 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -61,7 +61,7 @@ dsh --profile cua-mcp --print-client-config codex >> ~/.codex/config.toml dsh --profile cua-mcp --print-client-config claude-code | sh ``` -On macOS the profile prepares the signed Computer Use helper on first start and needs Accessibility and Screen Recording permissions for it; the [macOS provider](../cua-macos/README.md) owns that setup. On other Hosts the profile starts without a provider, and both tools return an error naming the missing provider. +On macOS the profile prepares the signed Computer Use helper on first start and needs Accessibility and Screen Recording permissions for it; the [macOS provider](../cua-macos/README.md) owns that setup. This profile has no permission page, so grant both in System Settings → Privacy & Security by adding the helper application: a source checkout prepares `DSH Computer Use Dev.app` under `packages/experimental/cua-macos/native/.build/prepared///`, where `current.json` names the selected build; an installed package ships `DSH Computer Use.app`. Until both are granted, `await cua.getCapabilities()` reports the missing flags and application operations fail; a locked desktop fails them with `SESSION_LOCKED`. On other Hosts the profile starts without a provider, and both tools return an error naming the missing provider. ### What you get @@ -122,7 +122,7 @@ The connected harness's model sees two tools and the server instructions from `t #### Token effect -The API reference adds about 11,000 characters once per connection or reset. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the generated Codex configuration raises the `cua_run_code` budget to 25,000 tokens. +The first result adds about 15,000 characters once per connection or reset with the current macOS provider: 2,200 characters of execution rules and 12,800 of API reference, about 3,800 tokens by the repository's four-character estimate. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the generated Codex configuration raises the `cua_run_code` budget to 25,000 tokens. #### KV Cache effect diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index 71d0683def..f3c2790a56 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -61,7 +61,7 @@ dsh --profile cua-mcp --print-client-config codex >> ~/.codex/config.toml dsh --profile cua-mcp --print-client-config claude-code | sh ``` -在 macOS 上,profile 首次启动时准备已签名的 Computer Use helper,并需要为其授予辅助功能与屏幕录制权限;[macOS 提供方](../cua-macos/README.zh.md)负责这部分设置。在其他 Host 上 profile 没有提供方也能启动,两个工具都返回指出缺少提供方的错误。 +在 macOS 上,profile 首次启动时准备已签名的 Computer Use helper,并需要为其授予辅助功能与屏幕录制权限;[macOS 提供方](../cua-macos/README.zh.md)负责这部分设置。本 profile 没有权限页面,因此要在「系统设置 → 隐私与安全性」中添加 helper 应用来授予这两项权限:源码检出在 `packages/experimental/cua-macos/native/.build/prepared///` 下准备 `DSH Computer Use Dev.app`,其中 `current.json` 记录当前选中的构建;已安装的包附带 `DSH Computer Use.app`。两项权限都授予之前,`await cua.getCapabilities()` 会报告缺失的标志,应用操作会失败;桌面处于锁定状态时这些操作以 `SESSION_LOCKED` 失败。在其他 Host 上 profile 没有提供方也能启动,两个工具都返回指出缺少提供方的错误。 ### 你会得到什么 @@ -122,7 +122,7 @@ patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载提 #### Token 影响 -API 参考每个连接或每次重置增加约 11,000 个字符。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;生成的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。 +使用当前 macOS 提供方时,首个结果每个连接或每次重置增加约 15,000 个字符:2,200 个字符的执行规则与 12,800 个字符的 API 参考,按仓库四字符/token 估算约 3,800 token。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;生成的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。 #### KV Cache 影响 From 7d1d9c85c5cf2c6bd6848c9948069d7ea7d02f41 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 10 Nov 2026 10:40:10 +0800 Subject: [PATCH 04/24] docs(cua-mcp): name the clients whose unattended runs need the allow consent mode --- packages/experimental/cua-mcp/README.i18n.yaml | 4 ++-- packages/experimental/cua-mcp/README.md | 2 +- packages/experimental/cua-mcp/README.zh.md | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/experimental/cua-mcp/README.i18n.yaml b/packages/experimental/cua-mcp/README.i18n.yaml index 9b17f3cdc2..8d0e86218c 100644 --- a/packages/experimental/cua-mcp/README.i18n.yaml +++ b/packages/experimental/cua-mcp/README.i18n.yaml @@ -21,8 +21,8 @@ en: c41e73c449ec4e64 zh: 9e4ff33e1d97f1f3 /deepseek-ai-dsh-cua-mcp/use-this-package/connect-a-client: - en: ef9f2e7d9adf2b7b - zh: 09b54d8bb7e9924d + en: b4db34975dce7ea2 + zh: ae55298bfd3e1c3a /deepseek-ai-dsh-cua-mcp/use-this-package/what-you-get: en: 2c9cae657eb4af9d zh: f8cb92292bf0ebf3 diff --git a/packages/experimental/cua-mcp/README.md b/packages/experimental/cua-mcp/README.md index 99a5ff5ef4..a86b011069 100644 --- a/packages/experimental/cua-mcp/README.md +++ b/packages/experimental/cua-mcp/README.md @@ -54,7 +54,7 @@ command = [*resolve_bundled_launch_args(), "--profile", "cua-mcp"] # the MCP st ### Connect a client -`dsh --profile cua-mcp` is the stdio command. It prints its own help with `--help`, and `--print-client-config codex|claude-code|json` prints a ready configuration for this installation and Harness home: a `~/.codex/config.toml` fragment, a `claude mcp add-json dsh_cua` command, or a generic `mcpServers` document. Each embeds the absolute executable, `DSH_HOME`, and the current `DSH_CUA_CONSENT`. The Codex fragment sets `startup_timeout_sec = 120` for first-run helper preparation, `tool_timeout_sec = 600` to match the default program maximum, exposes both tools directly instead of through tool search, and raises the `cua_run_code` output budget to 25,000 tokens. Codex forwards elicitations only with `approval_policy.granular.mcp_elicitations = true`. +`dsh --profile cua-mcp` is the stdio command. It prints its own help with `--help`, and `--print-client-config codex|claude-code|json` prints a ready configuration for this installation and Harness home: a `~/.codex/config.toml` fragment, a `claude mcp add-json dsh_cua` command, or a generic `mcpServers` document. Each embeds the absolute executable, `DSH_HOME`, and the current `DSH_CUA_CONSENT`. The Codex fragment sets `startup_timeout_sec = 120` for first-run helper preparation, `tool_timeout_sec = 600` to match the default program maximum, exposes both tools directly instead of through tool search, and raises the `cua_run_code` output budget to 25,000 tokens. Codex forwards elicitations only with `approval_policy.granular.mcp_elicitations = true`. DSH's own `dsh-mcp-client` declares no elicitation capability, and Claude Code 2.1 print mode declines elicitations, so unattended runs through those clients need `DSH_CUA_CONSENT=allow`. ```sh dsh --profile cua-mcp --print-client-config codex >> ~/.codex/config.toml diff --git a/packages/experimental/cua-mcp/README.zh.md b/packages/experimental/cua-mcp/README.zh.md index f3c2790a56..83ec26defa 100644 --- a/packages/experimental/cua-mcp/README.zh.md +++ b/packages/experimental/cua-mcp/README.zh.md @@ -54,7 +54,7 @@ command = [*resolve_bundled_launch_args(), "--profile", "cua-mcp"] # the MCP st ### 接入客户端 -`dsh --profile cua-mcp` 就是 stdio 命令。`--help` 打印它自己的帮助;`--print-client-config codex|claude-code|json` 为当前安装和 Harness home 打印可直接使用的配置:一段 `~/.codex/config.toml` 片段、一条 `claude mcp add-json dsh_cua` 命令,或一份通用 `mcpServers` 文档。三者都嵌入绝对可执行路径、`DSH_HOME` 与当前 `DSH_CUA_CONSENT`。Codex 片段把 `startup_timeout_sec = 120` 留给首次 helper 准备,用 `tool_timeout_sec = 600` 对齐默认程序上限,让两个工具直接暴露而不进入工具搜索,并把 `cua_run_code` 的输出预算提高到 25,000 token。Codex 只有在 `approval_policy.granular.mcp_elicitations = true` 时才转发 elicitation。 +`dsh --profile cua-mcp` 就是 stdio 命令。`--help` 打印它自己的帮助;`--print-client-config codex|claude-code|json` 为当前安装和 Harness home 打印可直接使用的配置:一段 `~/.codex/config.toml` 片段、一条 `claude mcp add-json dsh_cua` 命令,或一份通用 `mcpServers` 文档。三者都嵌入绝对可执行路径、`DSH_HOME` 与当前 `DSH_CUA_CONSENT`。Codex 片段把 `startup_timeout_sec = 120` 留给首次 helper 准备,用 `tool_timeout_sec = 600` 对齐默认程序上限,让两个工具直接暴露而不进入工具搜索,并把 `cua_run_code` 的输出预算提高到 25,000 token。Codex 只有在 `approval_policy.granular.mcp_elicitations = true` 时才转发 elicitation。DSH 自己的 `dsh-mcp-client` 未声明 elicitation 能力,Claude Code 2.1 的 print 模式会拒绝 elicitation,因此经这两类客户端的无人值守运行需要 `DSH_CUA_CONSENT=allow`。 ```sh dsh --profile cua-mcp --print-client-config codex >> ~/.codex/config.toml From 6ebf0305799fe50400c4907aff5e4af70cce47d0 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 10 Nov 2026 11:04:03 +0800 Subject: [PATCH 05/24] test(cua-mcp): read the accessibility tree before element clicks --- packages/experimental/cua-mcp/tests/composition.spec.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/experimental/cua-mcp/tests/composition.spec.ts b/packages/experimental/cua-mcp/tests/composition.spec.ts index d48d25dfec..a18760df18 100644 --- a/packages/experimental/cua-mcp/tests/composition.spec.ts +++ b/packages/experimental/cua-mcp/tests/composition.spec.ts @@ -144,7 +144,7 @@ describe('Computer Use MCP composition', () => { expect(listed.tools[0]?.description).toContain('complete `cua` API reference') const first = await run('globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); ' - + 'await win.click("0"); await win.getScreenshot(); ({ visits, window: win.windowId, pid: process.pid })', { description: 'Open the fixture' }) + + 'await win.getAccessibilityTree({ emit: false }); await win.click("0"); await win.getScreenshot(); ({ visits, window: win.windowId, pid: process.pid })', { description: 'Open the fixture' }) expect(first.isError).not.toBe(true) const [reference, ...rest] = first.content expect(reference).toMatchObject({ type: 'text' }) @@ -166,7 +166,7 @@ describe('Computer Use MCP composition', () => { expect(rest).toHaveLength(3) expect(native.state).toMatchObject({ count: 1, openedChannels: 1, closedChannels: 0 }) - const second = await run('globalThis.visits++; await win.click("0"); ({ visits, sameWindow: win.windowId === 7, pid: process.pid })') + const second = await run('globalThis.visits++; await win.getAccessibilityTree({ emit: false }); await win.click("0"); ({ visits, sameWindow: win.windowId === 7, pid: process.pid })') expect(second.isError).not.toBe(true) expect(second.content).toHaveLength(1) expect(lastJson(second)).toEqual({ visits: 2, sameWindow: true, pid: result.pid }) From 3147ec1596c32c8ede9192fe64f017dd7d853582 Mon Sep 17 00:00:00 2001 From: Yichen Jiang Date: Tue, 10 Nov 2026 12:00:17 +0800 Subject: [PATCH 06/24] feat(cua-mcp): compose the profile standalone and initialize it from the bundle declaration The cua-mcp bundle composes its profile from one insert over the empty root instead of layering on dsh-base, so no model adapter, prompt-side tool, telemetry, or session-management row loads; every row is a bundle dependency. The bundle declares the profile through dsh.bundle.profile, and app-boot's shippedProfileTemplate initializes a missing profile from that single shipped bundle for `dsh --profile`, the CLI `dsh plugin` command, and the plugin manager's pnpm path. The `dsh plugin enable|disable` subcommand is withdrawn. --- ...26-11-09-computer-use-mcp-server.i18n.yaml | 8 +- .../2026-11-09-computer-use-mcp-server.md | 8 +- .../2026-11-09-computer-use-mcp-server.zh.md | 8 +- apps/cli/reference/README.i18n.yaml | 4 +- apps/cli/reference/README.md | 2 - apps/cli/reference/README.zh.md | 2 - apps/cli/src/args.ts | 2 +- apps/cli/src/plugin.ts | 70 +---------- apps/cli/tests/plugin.spec.ts | 55 +-------- .../profiles/cua-mcp/cua-mcp.expected.e2e.ts | 15 +-- .../profiles/cua-mcp/expected/codex.toml | 2 +- .../profiles/cua-mcp/expected/reference.md | 10 +- docs/cli-help.md | 3 +- docs/cli-help.zh.md | 3 +- docs/module-graph.md | 9 +- docs/module-graph.zh.md | 9 +- docs/subsystems/computer-use.i18n.yaml | 4 +- docs/subsystems/computer-use.md | 2 +- docs/subsystems/computer-use.zh.md | 2 +- packages/boot/app-boot/README.i18n.yaml | 4 +- packages/boot/app-boot/README.md | 2 +- packages/boot/app-boot/README.zh.md | 2 +- packages/boot/app-boot/src/index.ts | 2 + packages/boot/app-boot/src/profile.ts | 48 +++++++- packages/boot/app-boot/tests/profile.spec.ts | 34 +++++- .../boot/plugin-manager/src/operations.ts | 7 +- .../experimental/cua-mcp/README.i18n.yaml | 18 +-- packages/experimental/cua-mcp/README.md | 27 +---- packages/experimental/cua-mcp/README.zh.md | 27 +---- .../experimental/cua-mcp/cordis.patch.yml | 113 ++++++++++++++---- packages/experimental/cua-mcp/package.json | 34 +++--- .../experimental/cua-mcp/src/client-config.ts | 8 +- .../experimental/cua-mcp/tests/bundle.spec.ts | 53 ++++---- .../cua-mcp/tests/client-config.spec.ts | 14 +-- .../cua-mcp/tests/startup.spec.ts | 2 +- .../util/official-bundles/README.i18n.yaml | 4 +- packages/util/official-bundles/README.md | 2 +- packages/util/official-bundles/README.zh.md | 2 +- packages/util/package-manifest/src/types.ts | 5 + pnpm-lock.yaml | 84 ++++++++----- scripts/optional-bundles.spec.ts | 18 ++- 41 files changed, 385 insertions(+), 343 deletions(-) diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml index 02417d58c7..303dc6cd10 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.i18n.yaml @@ -9,11 +9,11 @@ en: 6050884223e0e491 zh: eb808c298c9fb652 /agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/decision: - en: 7087ecc0b83d2759 - zh: 9008903182bb7e13 + en: 105a26da72fd7ff0 + zh: e00c8a688935b2bf /agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/alternatives-considered: - en: cad5bdefc9bfe720 - zh: 8564660068c66fc1 + en: b30d473439234af3 + zh: fdc0ecf85535f97b /agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/consequences: en: cb25b3b611178f0a zh: 6234bf3e87e0e14c diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md index 1ec8139e67..78e66822a3 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.md @@ -10,7 +10,7 @@ Computer Use training data should come from several agent harnesses, not only fr ## Decision -`@deepseek-ai/dsh-cua-mcp` is an experimental bundle in `OPTIONAL_BUNDLES`: a profile frontend over `dsh-base` selected with `dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp` and started with `dsh --profile cua-mcp`. It is the only MCP application path; no package bin or SDK escape exists, and a shipped profile template waits for CUA promotion because templates cannot name experimental packages. +`@deepseek-ai/dsh-cua-mcp` is an experimental bundle in `OPTIONAL_BUNDLES` that composes the standalone `cua-mcp` profile from one insert over the empty root and declares that profile through `dsh.bundle.profile`, so the first `dsh --profile cua-mcp` initializes the profile from this single bundle. It is the only MCP application path; no package bin or SDK escape exists, and the bundle stays out of `PROFILE_TEMPLATES` because templates cannot name experimental packages. The server runs inside the profile process and calls `ctx.tools.execute` with the connection's Agent and no model step. One stdio connection owns one Agent: creation after client initialization, disposal at stdin EOF. Agent ownership already selects the retained program process, native connection, and session-scoped grants, so connection lifetime and state lifetime coincide. The empty default preset `cua-mcp` gives that Agent `cua_run_code` and nothing else, because the provider registers program tools only for composed presets. @@ -18,7 +18,7 @@ Two tools form the surface. `cua_run_code` forwards `code`, an optional `descrip Consent has two modes. `DSH_CUA_CONSENT=allow` answers every approval question of the connection's Agent with its approving label for the session. The default `elicit` forwards each question to the client as a form elicitation whose enum is the question's labels. No Session event is added: the training side consumes MCP tool results, and the connected harness's transcript records calls; DSH retains nested `tool/ptc-dispatch` events for diagnosis. -`dsh plugin enable|disable` selects installed bundles by editing `dsh.profile.bundles` without pnpm, the same operation as the Plugins page switch, so the Python runtime wheel and offline training Hosts need no registry access. `--print-client-config codex|claude-code|json` renders the client entry for the exact installation. +The composition lists its dependency closure, twenty-five rows, instead of layering on `dsh-base`: no model adapter, prompt-side tool, telemetry, or session-management row loads, and a new service injection in the CUA or PTC packages fails the required startup entry loudly until the patch adds the row. Initialization needs no `dsh plugin` step, so the Python runtime wheel and offline training Hosts need no registry access. `--print-client-config codex|claude-code|json` renders the client entry for the exact installation. ## Alternatives considered @@ -32,6 +32,10 @@ Consent has two modes. `DSH_CUA_CONSENT=allow` answers every approval question o **Exposing the raw `cua` tool or program sandbox escalation.** Raw operations need per-method schemas the external model would relearn, and escalation needs an approval answerer the profile does not have. +**A profile frontend layered on `dsh-base` with model rows disabled.** The composed profile carried about a hundred rows without a consumer: model adapters, web tools, subagents, compaction, telemetry, and session management. The explicit closure is a quarter of that and fails loud on drift. + +**A `dsh plugin enable|disable` subcommand that selects the shipped bundle.** It duplicated the plugin manager's manifest-only selection inside the launcher and still produced a base-backed profile; a bundle-declared profile needs no step. + ## Consequences Every installation carries the bundle and its optional macOS provider dependency; `verify-default-product-isolation` keeps it out of default templates. The required startup entry `cua-mcp` fails the profile loudly when the frontend cannot activate. Clients see state loss on process exit, `cua_reset`, or Agent disposal and recreate objects. Consent elicitation depends on the 2025 MCP request model; clients on the 2026-07-28 revision use `allow`. The reference text in the first result is pinned by the profile's expected-output test and changes with the installed CUA packages. diff --git a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md index a1b4a6477a..eaccffabef 100644 --- a/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md +++ b/.agents/notes/implemented/architecture/2026-11-09-computer-use-mcp-server.zh.md @@ -10,7 +10,7 @@ Computer Use 的训练数据应来自多个 agent harness,而不只是 DSH 会 ## 决策 -`@deepseek-ai/dsh-cua-mcp` 是 `OPTIONAL_BUNDLES` 中的实验性组合包:一个位于 `dsh-base` 之上的 profile 前端,用 `dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp` 选中,用 `dsh --profile cua-mcp` 启动。这是唯一的 MCP 应用路径;没有包 bin 或 SDK 逃逸,随附的 profile 模板等待 CUA 晋升,因为模板不能引用实验包。 +`@deepseek-ai/dsh-cua-mcp` 是 `OPTIONAL_BUNDLES` 中的实验性组合包:它在空 profile 根上用一次 insert 组成独立的 `cua-mcp` profile,并通过 `dsh.bundle.profile` 声明该 profile,因此首次 `dsh --profile cua-mcp` 就从这一个组合包初始化 profile。这是唯一的 MCP 应用路径;没有包 bin 或 SDK 逃逸,该组合包不进入 `PROFILE_TEMPLATES`,因为模板不能引用实验包。 服务器运行在 profile 进程内,带着连接的 Agent、不经模型步骤地调用 `ctx.tools.execute`。一个 stdio 连接拥有一个 Agent:客户端初始化后创建,stdin EOF 时销毁。Agent 归属已经决定了保留的程序进程、本机连接和会话级授权,因此连接生命周期与状态生命周期重合。空的默认 preset `cua-mcp` 让该 Agent 只获得 `cua_run_code`,因为提供方只为已组合 preset 注册程序工具。 @@ -18,7 +18,7 @@ Computer Use 的训练数据应来自多个 agent harness,而不只是 DSH 会 授权有两种模式。`DSH_CUA_CONSENT=allow` 以批准标签为本会话回答连接 Agent 的每个审批问题。默认的 `elicit` 把每个问题作为表单 elicitation 转发给客户端,枚举即问题的选项标签。不新增任何 Session 事件:训练侧只消费 MCP 工具结果,接入 harness 的 transcript 记录调用;DSH 保留嵌套的 `tool/ptc-dispatch` 事件以供诊断。 -`dsh plugin enable|disable` 不经 pnpm、只编辑 `dsh.profile.bundles` 来选择已安装的组合包,与插件页开关是同一操作,因此 Python runtime wheel 和离线训练 Host 都不需要访问 registry。`--print-client-config codex|claude-code|json` 为当前安装渲染客户端配置项。 +组合列出自己的依赖闭包(25 行),而不是叠在 `dsh-base` 之上:不加载任何模型适配器、提示侧工具、遥测或会话管理行;CUA 或 PTC 包新增服务注入时,必需启动条目会大声失败,直到 patch 补上该行。初始化不需要 `dsh plugin` 步骤,因此 Python runtime wheel 和离线训练 Host 都不需要访问 registry。`--print-client-config codex|claude-code|json` 为当前安装渲染客户端配置项。 ## 考虑过的替代方案 @@ -32,6 +32,10 @@ Computer Use 的训练数据应来自多个 agent harness,而不只是 DSH 会 **暴露原始 `cua` 工具或程序沙箱提权。** 原始操作需要外部模型重新学习的逐方法 schema,提权需要该 profile 不具备的审批应答者。 +**叠在 `dsh-base` 之上、禁用模型行的 profile 前端。** 组合出的 profile 带着约一百行没有消费者的插件:模型适配器、web 工具、子代理、压缩、遥测和会话管理。显式闭包只有四分之一,且在漂移时大声失败。 + +**用 `dsh plugin enable|disable` 子命令选中随附组合包。** 它在启动器里重复了插件管理器的仅改 manifest 选择,而且仍然产生以 base 为底的 profile;组合包声明的 profile 不需要任何步骤。 + ## 后果 每个安装都携带该组合包及其可选的 macOS 提供方依赖;`verify-default-product-isolation` 让它留在默认模板之外。必需启动条目 `cua-mcp` 在前端无法激活时让 profile 大声失败。客户端会在进程退出、`cua_reset` 或 Agent 销毁时看到状态丢失并重新创建对象。授权 elicitation 依赖 2025 版 MCP 请求模型;使用 2026-07-28 修订版的客户端改用 `allow`。首个结果中的参考文本由 profile 的期望输出测试固定,并随已安装的 CUA 包变化。 diff --git a/apps/cli/reference/README.i18n.yaml b/apps/cli/reference/README.i18n.yaml index 420c01973f..2c33416553 100644 --- a/apps/cli/reference/README.i18n.yaml +++ b/apps/cli/reference/README.i18n.yaml @@ -18,8 +18,8 @@ en: d6368bf97a02bd57 zh: 2ab7888a108961ce /dsh-cli-behavior-reference/plugin-management: - en: 66fa35fcd6ec2a76 - zh: b5fbe1cd6ba9f336 + en: 8d2cfff9bab7327f + zh: 21515ab6e6798504 /dsh-cli-behavior-reference/web-profile: en: 149c5571acd51baf zh: 300e3c2425273a92 diff --git a/apps/cli/reference/README.md b/apps/cli/reference/README.md index 558b2d7e85..dc84a267d8 100644 --- a/apps/cli/reference/README.md +++ b/apps/cli/reference/README.md @@ -84,8 +84,6 @@ New directories and files request modes `0700` and `0600` on POSIX. The CLI prin `dsh plugin --profile ` initializes the profile when missing (shipped template, or `@deepseek-ai/dsh-base` alone for other names), then forwards `` to `pnpm` with the profile directory as working directory — `add`, `remove`, `why`, `update`, and every other pnpm verb work unchanged; pnpm must be on PATH. Relative path specs (`.`, `../plugin`, and their `file:`/`link:` forms) are anchored to the invoking directory first, so `add .` from a plugin checkout installs that checkout, not the profile. After every successful run, `dsh.profile.bundles` is reconciled against the installed state: each dependency resolving to a package whose manifest declares `"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }` joins the layer stack (so an `update` that gains the declaration activates it), a bundle-less dependency stays plain with a one-time warning, and a removed dependency leaves the stack. -`dsh plugin --profile enable ` and `disable ` change only `dsh.profile.bundles` and never run pnpm. `enable` selects a bundle the installation ships, such as an [optional bundle](../../../packages/util/official-bundles/README.md), or one the profile already installed, after its platform declaration and version compatibility pass; `disable` deselects it. Both refuse a bundle of the profile's shipped template, initialize a missing profile first, and print the change; a running profile applies it after a restart. - `dsh plugin` reads `--profile` only before the forwarded arguments, which start at the first token it does not recognize, so `--profile ` comes first. When the forwarded arguments begin with the pnpm command, everything after that command reaches pnpm verbatim, including `-h` and `--help`. When they begin with a pnpm option such as `--filter ` or `-r`, a later `-h` or `--help` still prints the forwarder's help instead of pnpm's, so put the pnpm command before them to reach pnpm's help. `-h` or `--help` before any forwarded argument prints the forwarder's own help and exits 0. The Codex and Claude Code subagent providers are separate optional Bundles. Add either package, both in one command, or remove either package independently: diff --git a/apps/cli/reference/README.zh.md b/apps/cli/reference/README.zh.md index 1785b2a163..2de7755983 100644 --- a/apps/cli/reference/README.zh.md +++ b/apps/cli/reference/README.zh.md @@ -84,8 +84,6 @@ dsh --profile web --patch ./extra.yml --dump-config `dsh plugin --profile ` 在 profile 缺失时先初始化它(有随附模板的用模板,其他名称只装 `@deepseek-ai/dsh-base`),然后以 profile 目录为工作目录,把 `` 转发给 `pnpm`:`add`、`remove`、`why`、`update` 及其他所有 pnpm 子命令都照常可用;pnpm 必须在 PATH 上。相对路径 spec(`.`、`../plugin` 及其 `file:`/`link:` 形式)会先锚定到调用目录,因此在插件 checkout 中执行 `add .` 安装的是该 checkout,而不是 profile。每次成功运行后,系统都会根据当前安装状态更新 `dsh.profile.bundles`:如果某项依赖解析到的包在 manifest 中声明了 `"dsh": { "bundle": { "patch": "./cordis.patch.yml" } }`,该依赖就会加入配置层栈;如果某项依赖在 `update` 后获得该声明,也会随即激活。没有组合包声明的依赖仍作为普通依赖保留,并显示一次性警告;已移除的依赖则从配置层栈中删除。 -`dsh plugin --profile enable ` 与 `disable ` 只修改 `dsh.profile.bundles`,不运行 pnpm。`enable` 在平台声明和版本兼容性检查通过后,选择安装自带的组合包(例如[可选组合包](../../../packages/util/official-bundles/README.zh.md))或 profile 已安装的组合包;`disable` 取消选择。两者都拒绝 profile 随附模板中的组合包,会先初始化缺失的 profile 并打印变更;正在运行的 profile 在重启后应用。 - `dsh plugin` 只在被转发的参数之前读取 `--profile`;被转发的参数从它无法识别的第一个 token 开始,因此 `--profile ` 必须写在最前面。被转发的参数以 pnpm 命令开头时,该命令之后的所有内容都会原样交给 pnpm,包括 `-h` 和 `--help`。被转发的参数以 `--filter ` 或 `-r` 等 pnpm 选项开头时,后面的 `-h` 或 `--help` 仍会打印转发器的帮助而不是 pnpm 的帮助,因此要查看 pnpm 的帮助,需把 pnpm 命令写在它们之前。在任何被转发的参数之前出现的 `-h` 或 `--help` 会打印转发器自身的帮助并以 0 退出。 Codex 与 Claude Code subagent 提供方是两个彼此独立的可选组合包。可以只添加一个包、在同一命令中添加两个包,或独立移除任一包: diff --git a/apps/cli/src/args.ts b/apps/cli/src/args.ts index a071b6635e..41d4ebeaa8 100644 --- a/apps/cli/src/args.ts +++ b/apps/cli/src/args.ts @@ -193,7 +193,7 @@ export function parseDshArgs(argv: readonly string[], version: string, manageDes .passThroughOptions() .requiredOption('--profile ', 'the profile whose plugins to manage (initialized on first use)', selectProfile) .allowUnknownOption() - .argument('[args...]', 'pnpm arguments, forwarded verbatim (add , remove , why , ...), or enable|disable to select an installed bundle without pnpm') + .argument('[args...]', 'pnpm arguments, forwarded verbatim (add , remove , why , ...)') .action((args: string[], options: { profile: string }) => { if (options.profile === '') program.error('error: --profile needs a name') if (!manageDesktopProfile) rejectElectronProfile(plugin, options.profile) diff --git a/apps/cli/src/plugin.ts b/apps/cli/src/plugin.ts index bf95877ab0..a1f2100877 100644 --- a/apps/cli/src/plugin.ts +++ b/apps/cli/src/plugin.ts @@ -1,11 +1,8 @@ -/** Profile package management, manifest-only bundle selection, and explicit, exact-version compatibility approvals. */ -import { bundleManifest, runPluginCommand, runProfilePnpm, setProfileVersionExemption, type PackageOperationOptions } from '@deepseek-ai/dsh-plugin-manager/operations' +/** Profile package management and explicit, exact-version compatibility approvals. */ +import { runPluginCommand, runProfilePnpm, setProfileVersionExemption, type PackageOperationOptions } from '@deepseek-ai/dsh-plugin-manager/operations' import { INSTALL_ANCHOR } from './profile-boot.ts' -import { - assertBundlePlatform, evaluatePluginCompatibility, initProfile, pluginCompatibilityWarning, readProfileCompatibility, - readProfileManifest, readProfileVersionExemptions, resolveProfileDir, writeProfileBundles, type ProfileContext, -} from '@deepseek-ai/dsh-app-boot' -import { PROFILE_TEMPLATES, DEFAULT_PROFILE_BUNDLES } from '@deepseek-ai/dsh-official-bundles' +import { initProfile, readProfileCompatibility, resolveProfileDir, shippedProfileTemplate, type ProfileContext } from '@deepseek-ai/dsh-app-boot' +import { DEFAULT_PROFILE_BUNDLES } from '@deepseek-ai/dsh-official-bundles' import { withFileLock } from '@deepseek-ai/dsh-atomic-write' import { existsSync } from 'node:fs' import { mkdir } from 'node:fs/promises' @@ -48,7 +45,7 @@ async function versionCommand(profile: string, args: readonly string[]): Promise if (profile !== 'desktop') await mkdir(dir, { recursive: true }) await withFileLock(join(dir, 'package.json'), async () => { if (profile === 'desktop') requireDesktopProfile(dir) - else if (!existsSync(join(dir, 'package.json'))) initProfile(dir, PROFILE_TEMPLATES[profile]?.bundles ?? DEFAULT_PROFILE_BUNDLES) + else if (!existsSync(join(dir, 'package.json'))) initProfile(dir, shippedProfileTemplate('dsh', profile, INSTALL_ANCHOR, dir) ?? DEFAULT_PROFILE_BUNDLES) if (request === undefined) { const { exemptions, warnings } = readProfileCompatibility(dir) for (const warning of warnings) process.stderr.write(`dsh: warning: ${warning}\n`) @@ -65,62 +62,9 @@ async function versionCommand(profile: string, args: readonly string[]): Promise } } -/** - * Select or deselect installed bundles by editing `dsh.profile.bundles` alone, the way the Plugins page switch does; - * pnpm never runs. `enable` admits a bundle the installation ships or the profile installed after its platform and - * version checks pass; `disable` removes a selection. Bundles of the profile's shipped template are refused. - */ -async function selectionCommand(profile: string, args: readonly string[]): Promise { - const [command, ...names] = args - if (command !== 'enable' && command !== 'disable') return undefined - try { - if (names.length === 0 || names.some(name => name.startsWith('-'))) throw new Error(`usage: dsh plugin ${command} `) - const template = PROFILE_TEMPLATES[profile]?.bundles ?? DEFAULT_PROFILE_BUNDLES - const dir = resolveProfileDir(profile) - if (profile !== 'desktop') await mkdir(dir, { recursive: true }) - await withFileLock(join(dir, 'package.json'), () => { - if (profile === 'desktop') requireDesktopProfile(dir) - else if (!existsSync(join(dir, 'package.json'))) initProfile(dir, template) - const manifest = readProfileManifest('dsh', dir) - const previous = manifest.dsh?.profile?.bundles ?? [] - const bundles = [...previous] - for (const name of names) { - if (template.includes(name)) throw new Error(`${name} is a bundle of the ${profile} profile template and cannot be ${command}d`) - if (command === 'disable') { - const index = bundles.indexOf(name) - if (index >= 0) bundles.splice(index, 1) - continue - } - let metadata: ReturnType - try { - metadata = bundleManifest(name, dir, INSTALL_ANCHOR) - } catch (error) { - throw new Error(`${name} is not installed: run 'dsh plugin --profile ${profile} add ${name}', or enable a bundle this installation ships`, { cause: error }) - } - if (metadata === undefined) throw new Error(`${name} declares no dsh.bundle; only bundles can be enabled`) - assertBundlePlatform(metadata.dsh?.bundle?.platforms, process.platform) - const issue = evaluatePluginCompatibility(metadata, readProfileVersionExemptions(dir)) - if (issue !== undefined && !issue.exempted) throw new Error(pluginCompatibilityWarning(issue)) - if (!bundles.includes(name)) bundles.push(name) - } - if (JSON.stringify(bundles) === JSON.stringify(previous)) { - process.stdout.write(`dsh: profile ${profile} already has ${names.join(', ')} ${command}d\n`) - return Promise.resolve() - } - writeProfileBundles(dir, manifest, bundles) - process.stdout.write(`dsh: ${command}d ${names.join(', ')} in profile ${profile}; restart the profile to apply\n`) - return Promise.resolve() - }, { waitMs: 120000 }) - return 0 - } catch (error) { - process.stderr.write(`dsh: ${String(error)}\n`) - return 1 - } -} - /** Run package management for a profile. * @param profile Profile name; Desktop's reserved profile must already be initialized by the application. - * @param args DSH exemption or bundle selection command, or pnpm arguments relative to the invoking directory. + * @param args DSH exemption command or pnpm arguments relative to the invoking directory. * @param packageManager Installation-owned executable and environment for pnpm operations. * @returns Zero on success; nonzero on invalid approval or package-manager failure. */ @@ -133,8 +77,6 @@ export async function runPlugin(profile: string, args: readonly string[], packag } const versionResult = await versionCommand(profile, args) if (versionResult !== undefined) return versionResult - const selectionResult = await selectionCommand(profile, args) - if (selectionResult !== undefined) return selectionResult const dir = resolveProfileDir(profile) if (existsSync(join(dir, 'package.json'))) { for (const warning of readProfileCompatibility(dir).warnings) process.stderr.write(`dsh: warning: ${warning}\n`) diff --git a/apps/cli/tests/plugin.spec.ts b/apps/cli/tests/plugin.spec.ts index 94f23b88ed..9185315cb1 100644 --- a/apps/cli/tests/plugin.spec.ts +++ b/apps/cli/tests/plugin.spec.ts @@ -1,5 +1,5 @@ /** Explicit CLI exemptions use the profile lock and never become pnpm arguments. */ -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' import { tmpdir } from 'node:os' import { join } from 'node:path' import { expect, it, onTestFinished, vi } from 'vitest' @@ -176,56 +176,3 @@ it('applies version approvals to the existing Desktop profile without replacing expect(runPluginCommand).not.toHaveBeenCalled() expect(runProfilePnpm).not.toHaveBeenCalled() }) - -/** An installed package the profile can select: a bundle, or a plain dependency without a patch. */ -function installPackage(dir: string, name: string, manifest: Record): void { - const packageDir = join(dir, 'node_modules', ...name.split('/')) - mkdirSync(packageDir, { recursive: true }) - writeFileSync(join(packageDir, 'package.json'), JSON.stringify({ name, version: '1.0.0', ...manifest })) - writeFileSync(join(packageDir, 'cordis.patch.yml'), '[]\n') -} - -function bundlesOf(dir: string): string[] { - return (JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } }).dsh.profile.bundles -} - -it('enables and disables an installed bundle by editing the manifest without pnpm', async () => { - const { dir, stdout } = fixture() - initProfile(dir, PROFILE_TEMPLATES.web!.bundles) - installPackage(dir, '@example/bundle', { dsh: { bundle: { patch: './cordis.patch.yml' } } }) - expect(await runPlugin('test', ['enable', '@example/bundle'])).toBe(0) - expect(bundlesOf(dir)).toEqual([...PROFILE_TEMPLATES.web!.bundles, '@example/bundle']) - expect(stdout).toHaveBeenLastCalledWith('dsh: enabled @example/bundle in profile test; restart the profile to apply\n') - expect(await runPlugin('test', ['enable', '@example/bundle'])).toBe(0) - expect(stdout).toHaveBeenLastCalledWith('dsh: profile test already has @example/bundle enabled\n') - expect(await runPlugin('test', ['disable', '@example/bundle'])).toBe(0) - expect(bundlesOf(dir)).toEqual(PROFILE_TEMPLATES.web!.bundles) - expect(runPluginCommand).not.toHaveBeenCalled() -}) - -it('initializes a missing profile from the default bundles before enabling', async () => { - const { dir } = fixture() - mkdirSync(join(dir, 'node_modules'), { recursive: true }) - installPackage(dir, '@example/bundle', { dsh: { bundle: { patch: './cordis.patch.yml' } } }) - expect(await runPlugin('test', ['enable', '@example/bundle'])).toBe(0) - expect(bundlesOf(dir)).toEqual(['@deepseek-ai/dsh-base', '@example/bundle']) -}) - -it.each([ - { args: ['enable'], message: 'usage: dsh plugin enable ' }, - { args: ['enable', '@example/absent'], message: "@example/absent is not installed: run 'dsh plugin --profile test add @example/absent'" }, - { args: ['enable', '@example/plain'], message: '@example/plain declares no dsh.bundle' }, - { args: ['enable', '@example/elsewhere'], message: `Bundle supports Host platforms ${process.platform === 'aix' ? 'sunos' : 'aix'}` }, - { args: ['enable', '@example/old'], message: 'is incompatible with dsh' }, - { args: ['disable', '@deepseek-ai/dsh-base'], message: 'bundle of the test profile template and cannot be disabled' }, -])('refuses $args without changing the selection', async ({ args, message }) => { - const { dir, stderr } = fixture() - initProfile(dir, PROFILE_TEMPLATES.web!.bundles) - installPackage(dir, '@example/plain', {}) - installPackage(dir, '@example/elsewhere', { dsh: { bundle: { patch: './cordis.patch.yml', platforms: [process.platform === 'aix' ? 'sunos' : 'aix'] } } }) - installPackage(dir, '@example/old', { dsh: { bundle: { patch: './cordis.patch.yml' } }, engines: { dsh: '^0.0.1' } }) - expect(await runPlugin('test', args)).toBe(1) - expect(stderr.mock.calls.map(call => call[0]).join('')).toContain(message) - expect(bundlesOf(dir)).toEqual(PROFILE_TEMPLATES.web!.bundles) - expect(runPluginCommand).not.toHaveBeenCalled() -}) diff --git a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts index 5c35518c86..72c05f8984 100644 --- a/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts +++ b/apps/cli/tests/profiles/cua-mcp/cua-mcp.expected.e2e.ts @@ -1,4 +1,4 @@ -/** The shipped cua-mcp bundle: enabled through the real CLI, serving Computer Use programs over stdio to an MCP client. */ +/** The shipped cua-mcp bundle: the real CLI initializes its declared profile and serves Computer Use programs over stdio. */ import { execFile } from 'node:child_process' import { existsSync } from 'node:fs' import { mkdtemp, readFile, rm } from 'node:fs/promises' @@ -26,7 +26,7 @@ function textOf(block: CallResult['content'][number] | undefined): string { } describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => { - it('enables the shipped bundle, prints client configuration, serves programs over stdio, and exits on EOF', async () => { + it('initializes the declared profile on first start, prints client configuration, serves programs over stdio, and exits on EOF', async () => { const temporary = await mkdtemp(join(tmpdir(), 'dsh-cua-mcp-profile-')) const home = join(temporary, 'home') const workspace = join(temporary, 'workspace') @@ -41,13 +41,10 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => { await execFileAsync(process.execPath, ['-e', 'require("node:fs").mkdirSync(process.argv[1], { recursive: true })', workspace]) const options = { cwd: workspace, env, timeout: 120_000, maxBuffer: 4_000_000 } - // One command selects the installation-owned bundle without pnpm or network access. - const enabled = await execFileAsync(process.execPath, [bin, 'plugin', '--profile', 'cua-mcp', 'enable', '@deepseek-ai/dsh-cua-mcp'], options) - expect(enabled.stdout).toBe('dsh: enabled @deepseek-ai/dsh-cua-mcp in profile cua-mcp; restart the profile to apply\n') - const manifest = JSON.parse(await readFile(join(home, 'profiles', 'cua-mcp', 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } } - expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-base', '@deepseek-ai/dsh-cua-mcp']) - + // The first start initializes the profile the shipped bundle declares, without pnpm or network access. const printed = await execFileAsync(process.execPath, [bin, '--profile', 'cua-mcp', '--print-client-config', 'codex'], options) + const manifest = JSON.parse(await readFile(join(home, 'profiles', 'cua-mcp', 'package.json'), 'utf8')) as { dsh: { profile: { bundles: string[] } } } + expect(manifest.dsh.profile.bundles).toEqual(['@deepseek-ai/dsh-cua-mcp']) const normalized = printed.stdout .split(JSON.stringify(process.execPath).slice(1, -1)).join('{{node}}') .split(JSON.stringify(bin).slice(1, -1)).join('{{bin}}') @@ -67,7 +64,7 @@ describe.skipIf(!existsSync(bin))('cua-mcp profile', { retry: 0 }, () => { const first = await probe.request('tools/call', { name: 'cua_run_code', arguments: { code: 'globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow(7); ' - + 'await win.click("0"); await win.getScreenshot(); ({ visits, window: win.windowId, pid: process.pid })', + + 'await win.getAccessibilityTree({ emit: false }); await win.click("0"); await win.getScreenshot(); ({ visits, window: win.windowId, pid: process.pid })', } }) as CallResult expect(first.isError).toBeUndefined() expect(first.content.map(block => block.type)).toEqual(['text', 'text', 'text', 'image']) diff --git a/apps/cli/tests/profiles/cua-mcp/expected/codex.toml b/apps/cli/tests/profiles/cua-mcp/expected/codex.toml index 3776d31179..a1613c52f7 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/codex.toml +++ b/apps/cli/tests/profiles/cua-mcp/expected/codex.toml @@ -1,4 +1,4 @@ -# ~/.codex/config.toml — run once first: dsh plugin --profile cua-mcp enable @deepseek-ai/dsh-cua-mcp +# ~/.codex/config.toml — the first start initializes the profile and prepares the Computer Use helper [mcp_servers.dsh_cua] command = "{{node}}" args = ["{{bin}}", "--profile", "cua-mcp"] diff --git a/apps/cli/tests/profiles/cua-mcp/expected/reference.md b/apps/cli/tests/profiles/cua-mcp/expected/reference.md index 0ff49a0f0a..bf0e811bab 100644 --- a/apps/cli/tests/profiles/cua-mcp/expected/reference.md +++ b/apps/cli/tests/profiles/cua-mcp/expected/reference.md @@ -15,9 +15,9 @@ Setup and discovery: - cua.listApps(options?: { emit?: boolean }) -> { id: string, displayName: string, isRunning: true, pid: number }[] — enumerate running applications. - cua.findApps(query: string, options?: { emit?: boolean }) -> ({ id: string, displayName: string, path: string } & ({ isRunning: true, pid: number } | { isRunning: false }))[] — search installed applications, including stopped matches; only running matches carry pid. - cua.getState(options?: { emit?: boolean }) -> { apps: { id: string, displayName: string, isRunning: true, pid: number }[], browsers: [] } — summarize running applications; this is not an accessibility observation. -- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and read initial AX state silently; it does not activate the app. +- cua.getApp(selector: string) -> App — select an application by name, bundle ID, absolute path, or running PID string, obtain consent, launch in the background if needed, and return without reading AX or activating the app. - app.getWindows(options?: { emit?: boolean }) -> { windowId: number, appName: string, title: string, bounds: { x: number, y: number, width: number, height: number }, isOnScreen: boolean, onCurrentSpace: boolean | null }[] — enumerate windows with global native bounds; null onCurrentSpace means unknown Space membership. -- app.getWindow(windowId: number) -> Window — select one window and read its initial AX state silently; do this before any window screenshot or coordinate input. +- app.getWindow(windowId: number) -> Window — select a window by an ID from getWindows without reading AX. Providers reject closed or foreign windows when operating on them. - app.activate() -> ActionResult — request explicit foreground activation; use only when foreground access is required. - app.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation. - window.show() -> { dispatched: boolean, windowId: number | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation. @@ -25,7 +25,7 @@ Setup and discovery: ## Accessibility tree Available at app or window level depending on the platform. -Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. +Read getAccessibilityTree explicitly before using element ids. Selection and screenshots do not read or replace the current AX snapshot. Element ids are opaque strings from the latest successful tree; the object facade keeps one current snapshot per app across its repeated app and window objects, a new read replaces it, and a failed read invalidates the previous one. Repeated strings can appear for different elements, so do not reuse an old id blindly, and element operations do not fall back to pointer input or typing. - getAccessibilityTree(options?: { emit?: boolean, includeMenus?: boolean, details?: boolean, maxElements?: number, maxDepth?: number }) -> string — set the node count or depth for one read. Omitted limits use the provider settings. includeMenus expands menu contents and details adds identifiers, native bounds, and complete action names. - listActions(elementId: string) -> string[] — list the actions an element advertises. - invoke(elementId: string) -> ActionResult — invoke the element's default action; dispatched is false when it has none. @@ -34,7 +34,7 @@ Element ids are opaque strings from the latest successful tree; the object facad - selectText(elementId: string, text: string, options?: { prefix?: string, suffix?: string, selectionType?: 'text' | 'cursor_before' | 'cursor_after' }) -> ActionResult — select one literal occurrence or place the cursor beside it, using adjacent context to disambiguate. ## Simulated mouse -Use an explicit window for screenshots and pointer input. +Use an explicit window for screenshots and pointer input. Before coordinate input, including relative coordinates, obtain a successful getAccessibilityTree observation covering that window or take its screenshot. Absolute pixel coordinates require a returned screenshot. - getScreenshot(options?: { emit?: boolean }) -> { bytes: Uint8Array, mimeType: 'image/png' | 'image/jpeg' | 'image/webp' | 'image/gif', pixelWidth: number, pixelHeight: number, windowId: number } — capture the selected window as one encoded image; bytes is a JavaScript byte array, and mimeType identifies its encoding, so do not assume PNG. - mouseMove(target: string | [number, number], options?: { relative?: boolean }) -> { dispatched: boolean, foregroundChanged?: boolean | null, hoverRoute: 'accessibility' | 'system-pointer', systemPointerMoved: boolean } — request a mouse move to the target without pressing a button; inspect hoverRoute and systemPointerMoved, and expect no automatic pointer restoration. - click(target: string | [number, number], options?: { mouseButton?: 'left' | 'right' | 'middle', clickCount?: 1 | 2, modifiers?: ('command' | 'control' | 'option' | 'shift' | 'fn')[], holdMs?: number, relative?: boolean }) -> ActionResult — click an element id or point, or perform a left-button double-click; holdMs controls the press duration of each press. @@ -49,7 +49,7 @@ Available at app or window level depending on the platform. - paste(text: string, options?: { format?: 'text' | 'html' }) -> ActionResult — deliver text or HTML through the app's Paste command, restoring prior clipboard contents unless another writer changes them; a Paste failure is surfaced without substituting typeText, and PASTE_NOT_CONSUMED means inspect before any retry. - pressKey(key: string, modifiers?: string[]) -> ActionResult — press and release one complete keystroke. For example pressKey('Tab', ['shift']) or pressKey('+'). Key and modifier names are platform-defined strings. Pass key and modifiers separately; do not pack them into a chord string. -Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree and getWindow read through raw getState; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. +Raw tools use { method, params }: include appHandle for app calls and windowId for window calls, and use snapshotId with elementId for element routes. The emit option is facade-only: emit is local output control, so raw callers must follow the raw operation schema for admitted params. getAccessibilityTree maps to getState; getWindow has no raw method; getWindows maps to listWindows; getScreenshot maps to screenshot; cua.getState maps to listApps; every other named operation uses the same method name. AX read defaults: maxElements=2000, maxDepth=25. diff --git a/docs/cli-help.md b/docs/cli-help.md index 7e8ba84f25..1cbc117945 100644 --- a/docs/cli-help.md +++ b/docs/cli-help.md @@ -71,8 +71,7 @@ profile directory Arguments: args pnpm arguments, forwarded verbatim (add , remove , - why , ...), or enable|disable to select an - installed bundle without pnpm + why , ...) Options: --profile the profile whose plugins to manage (initialized on first diff --git a/docs/cli-help.zh.md b/docs/cli-help.zh.md index 0ac9a88185..c682e26067 100644 --- a/docs/cli-help.zh.md +++ b/docs/cli-help.zh.md @@ -73,8 +73,7 @@ profile directory Arguments: args pnpm arguments, forwarded verbatim (add , remove , - why , ...), or enable|disable to select an - installed bundle without pnpm + why , ...) Options: --profile the profile whose plugins to manage (initialized on first diff --git a/docs/module-graph.md b/docs/module-graph.md index f7fbe117eb..ccd8d0bbb6 100644 --- a/docs/module-graph.md +++ b/docs/module-graph.md @@ -528,6 +528,8 @@ flowchart TD pkg_hmr --> pkg_cmdline pkg_authorization --> pkg_credentials pkg_authorization --> pkg_llm + pkg_cua_mcp --> pkg_app_boot + pkg_cua_mcp --> pkg_attachment pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_subprocess @@ -959,11 +961,6 @@ flowchart TD pkg_creation_recommendations --> pkg_session pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools - pkg_cua_mcp --> pkg_agent - pkg_cua_mcp --> pkg_app_boot - pkg_cua_mcp --> pkg_attachment - pkg_cua_mcp --> pkg_system_prompt - pkg_cua_mcp --> pkg_tools pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt @@ -1730,6 +1727,7 @@ flowchart TD | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | | [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | | [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | +| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | @@ -1838,7 +1836,6 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/module-graph.zh.md b/docs/module-graph.zh.md index 95c503b21b..79f2858b58 100644 --- a/docs/module-graph.zh.md +++ b/docs/module-graph.zh.md @@ -530,6 +530,8 @@ flowchart TD pkg_hmr --> pkg_cmdline pkg_authorization --> pkg_credentials pkg_authorization --> pkg_llm + pkg_cua_mcp --> pkg_app_boot + pkg_cua_mcp --> pkg_attachment pkg_experimental_computer_use_cua_driver_mcp --> pkg_computer_use pkg_experimental_forge_github --> pkg_experimental_forge pkg_experimental_forge_github --> pkg_subprocess @@ -961,11 +963,6 @@ flowchart TD pkg_creation_recommendations --> pkg_session pkg_creation_recommendations --> pkg_skill pkg_creation_recommendations --> pkg_tools - pkg_cua_mcp --> pkg_agent - pkg_cua_mcp --> pkg_app_boot - pkg_cua_mcp --> pkg_attachment - pkg_cua_mcp --> pkg_system_prompt - pkg_cua_mcp --> pkg_tools pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_agent pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_browser_use pkg_experimental_browser_use_chrome_devtools_mcp --> pkg_system_prompt @@ -1732,6 +1729,7 @@ flowchart TD | [`attachment-local`](../packages/attachment/attachment-local) | `attachment` | [`attachment`](../packages/attachment/attachment), [`home-paths`](../packages/util/home-paths) | | [`hmr`](../packages/boot/hmr) | `boot` | [`app-boot`](../packages/boot/app-boot), [`cmdline`](../packages/boot/cmdline) | | [`authorization`](../packages/credentials/authorization) | `credentials` | [`credentials`](../packages/credentials/credentials), [`llm`](../packages/llm/llm) | +| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) | | [`experimental-computer-use-cua-driver-mcp`](../packages/experimental/computer-use-cua-driver-mcp) | `experimental` | [`computer-use`](../packages/computer-use/computer-use) | | [`experimental-forge-github`](../packages/experimental/forge-github) | `experimental` | [`experimental-forge`](../packages/experimental/forge), [`subprocess`](../packages/subprocess/subprocess) | | [`experimental-webworker-runtime`](../packages/experimental/webworker-runtime) | `experimental` | [`client-connection`](../packages/client/connection), [`client-modules`](../packages/client/modules), [`host-webserver`](../packages/host/webserver) | @@ -1840,7 +1838,6 @@ flowchart TD | [`workspace-changes`](../packages/deliverables/workspace-changes) | `deliverables` | [`agent`](../packages/core/agent), [`fs`](../packages/fs/fs), [`session`](../packages/core/session), [`subprocess`](../packages/subprocess/subprocess), [`tools`](../packages/core/tools) | | [`action-cards`](../packages/experimental/action-cards) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`tools`](../packages/core/tools), [`typert-protocol`](../packages/typert/protocol) | | [`creation-recommendations`](../packages/experimental/creation-recommendations) | `experimental` | [`llm`](../packages/llm/llm), [`session`](../packages/core/session), [`skill`](../packages/skill/skill), [`tools`](../packages/core/tools) | -| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`agent`](../packages/core/agent), [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | | [`experimental-browser-use-chrome-devtools-mcp`](../packages/experimental/browser-use-chrome-devtools-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-playwright-mcp`](../packages/experimental/browser-use-playwright-mcp) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools), [`working-directory`](../packages/session/working-directory) | | [`experimental-browser-use-stagehand-native`](../packages/experimental/browser-use-stagehand-native) | `experimental` | [`agent`](../packages/core/agent), [`browser-use`](../packages/browser-use/browser-use), [`system-prompt`](../packages/core/system-prompt), [`tools`](../packages/core/tools) | diff --git a/docs/subsystems/computer-use.i18n.yaml b/docs/subsystems/computer-use.i18n.yaml index 642573ebc8..8d644c6906 100644 --- a/docs/subsystems/computer-use.i18n.yaml +++ b/docs/subsystems/computer-use.i18n.yaml @@ -6,8 +6,8 @@ en: e02a2e4cc9970cba zh: 29aac6c0530a582f /computer-use/serve-computer-use-to-another-harness: - en: a2beb91957e93f87 - zh: cf2a96b0fae0aae4 + en: 5c932fde2a8839f4 + zh: 8b753a0e382f5941 /computer-use/choose-a-provider: en: fa2e0d7b41c0450b zh: af9a799711f901e6 diff --git a/docs/subsystems/computer-use.md b/docs/subsystems/computer-use.md index e95f0b1d3c..e2287cac7f 100644 --- a/docs/subsystems/computer-use.md +++ b/docs/subsystems/computer-use.md @@ -21,7 +21,7 @@ The [shared object API](../../packages/experimental/cua/README.md) uses `connect ## Serve Computer Use to another harness -[Computer use MCP server](../../packages/experimental/cua-mcp/README.md) is a shipped optional bundle for the `cua-mcp` profile. `dsh --profile cua-mcp` serves `cua_run_code` and `cua_reset` to one MCP client such as Codex or Claude Code; each connection owns one Agent whose programs retain application and window objects, and consent is granted unattended or forwarded to the client as an elicitation. `dsh --profile cua-mcp --print-client-config codex|claude-code|json` prints the client configuration. The profile runs no model turn and records no root tool calls in its Session. +[Computer use MCP server](../../packages/experimental/cua-mcp/README.md) is a shipped optional bundle that composes the standalone `cua-mcp` profile; the first `dsh --profile cua-mcp` initializes it. `dsh --profile cua-mcp` serves `cua_run_code` and `cua_reset` to one MCP client such as Codex or Claude Code; each connection owns one Agent whose programs retain application and window objects, and consent is granted unattended or forwarded to the client as an elicitation. `dsh --profile cua-mcp --print-client-config codex|claude-code|json` prints the client configuration. The profile runs no model turn and records no root tool calls in its Session. ## Choose a provider diff --git a/docs/subsystems/computer-use.zh.md b/docs/subsystems/computer-use.zh.md index 82d260fd66..7ff9771273 100644 --- a/docs/subsystems/computer-use.zh.md +++ b/docs/subsystems/computer-use.zh.md @@ -21,7 +21,7 @@ CUA provider 通过 `ctx.cuaAccess` 提供系统权限状态、用户主动申 ## 向其他 harness 提供 Computer Use -[Computer Use MCP 服务器](../../packages/experimental/cua-mcp/README.zh.md)是随安装提供的可选组合包,服务于 `cua-mcp` profile。`dsh --profile cua-mcp` 向一个 MCP 客户端(如 Codex 或 Claude Code)提供 `cua_run_code` 和 `cua_reset`;每个连接拥有一个 Agent,其程序保留应用与窗口对象,授权可无人值守放行或作为 elicitation 转发给客户端。`dsh --profile cua-mcp --print-client-config codex|claude-code|json` 打印客户端配置。该 profile 不运行模型回合,其 Session 中不记录根工具调用。 +[Computer Use MCP 服务器](../../packages/experimental/cua-mcp/README.zh.md)是随安装提供的可选组合包,独立组成 `cua-mcp` profile;首次 `dsh --profile cua-mcp` 即初始化该 profile。`dsh --profile cua-mcp` 向一个 MCP 客户端(如 Codex 或 Claude Code)提供 `cua_run_code` 和 `cua_reset`;每个连接拥有一个 Agent,其程序保留应用与窗口对象,授权可无人值守放行或作为 elicitation 转发给客户端。`dsh --profile cua-mcp --print-client-config codex|claude-code|json` 打印客户端配置。该 profile 不运行模型回合,其 Session 中不记录根工具调用。 ## 选择提供方 diff --git a/packages/boot/app-boot/README.i18n.yaml b/packages/boot/app-boot/README.i18n.yaml index a9a757958a..cf93e3a3af 100644 --- a/packages/boot/app-boot/README.i18n.yaml +++ b/packages/boot/app-boot/README.i18n.yaml @@ -24,8 +24,8 @@ en: 964aafe2cb5bc898 zh: fda067dd80664a30 /deepseek-ai-dsh-app-boot/use-this-package/profiles: - en: 781fe487a973ee6f - zh: e95188274f75f9ad + en: 429a2e3a7ace95ea + zh: 2e747341f0cc08fe /deepseek-ai-dsh-app-boot/use-this-package/previewing-the-effective-configuration: en: 646a0ccdd7881ad1 zh: e3696acb1573dd7b diff --git a/packages/boot/app-boot/README.md b/packages/boot/app-boot/README.md index 9d926cfbcc..4ac257328c 100644 --- a/packages/boot/app-boot/README.md +++ b/packages/boot/app-boot/README.md @@ -49,7 +49,7 @@ const ctx = await boot('dsh', resolveConfigPath(argv[2], process.env.DSH_SNAPSHO Import profile and bundle declaration types from [`@deepseek-ai/dsh-package-manifest`](../../util/package-manifest/README.md). App-boot adapts `DshPackageManifest` to `ProfileManifest` with optional package identity because local profiles need no published version. App-boot owns profile loading, JSON validation, and resolved runtime data. -A profile is how one dsh installation ships different app surfaces: `web`, `headless`, `acp`, `sdk`, and `sdk-minimal` start distinct compositions from the same launcher. A profile lives at `$DSH_HOME/profiles/` and combines installable bundles with its own `cordis.patch.yml`. A bundle's `dsh.bundle.patch` names one patch file or an ordered list of files; `bundlePatchFiles` validates the declaration and `bundlePatchPaths` resolves it to absolute paths; the layer concatenates their patch lists in that order. The YAML composition enables or disables HMR. The shipped `web` template uses live reload, while the other shipped templates apply patches only at startup. `sdk-minimal` names only its standalone bundle; the other templates retain base-plus-mode stacks. `dsh --profile --from-default-profile