Merge remote-tracking branch 'origin/master' into fix/chat-image-current-working-directory
This commit is contained in:
commit
4e44fea3ce
91 files changed
+4144
-45
No files matched your search
@@ -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: ab004152e8a43f7d
|
||||
zh: 2eb2de8b91d8c405
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/alternatives-considered:
|
||||
en: 7bba46bed1b1baa3
|
||||
zh: 54f31bd327ee222d
|
||||
/agent-note-serve-computer-use-to-other-harnesses-as-an-mcp-server/consequences:
|
||||
en: 74494a208b1909f9
|
||||
zh: 0e4378667c751f54
|
||||
@@ -0,0 +1,55 @@
|
||||
# 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` that composes the standalone `cua-mcp` profile from one insert over the empty root. A profile manifest that selects it as the only bundle is the whole installation step: the launcher loads an existing manifest without consulting `PROFILE_TEMPLATES`, and the installation already ships the bundle, so no pnpm or registry access is involved. 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 before the stdio transport opens, disposal at stdin EOF. Each program call runs as that Agent's maintenance activity, so Agent disposal cancels an in-flight call and waits for it and its nested calls before the Session closes. 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. The Agent works in a dedicated workspace, `DSH_CUA_WORKSPACE` or `cua-mcp/workspace` under the Harness home: an Agent's working directory is the `workspace-write` root of its programs, and the directory a client launches the server from can be `/`.
|
||||
|
||||
Three tools form the surface. `cua_run_code` is the Agent's DSH registration served through the protocol server's low-level `tools/list` and `tools/call` handlers: each listing projects name, description, and parameters from the tool registry, and a call passes its arguments to the tool executor unchanged inside the Agent's initiator scope, so the provider's definition is the only schema, `description` is required as that definition declares, and validation and unknown names are answered by DSH; the one trim is the registration's sandbox-escalation fields, which the projection omits and a call may not name. `cua_get_api_reference` returns the `cua` API reference, the provider's guidance registered for the Agent, and keeps no state, so any conversation on the connection can read it at any time. `cua_reset` ends the Agent's program environment and keeps the Agent: the frontend cancels the running program and calls `ctx.cuaPrograms.release`, with which the provider's program runtime releases the environment of that state owner and which the CUA provider exposes beside `screenshotRequestTarget`; the next program starts a fresh process, while the native connection and the session's consent decisions stay. The frontend orders its own calls around the release: a reset answers after the cancelled program has settled, and programs wait for a release in progress. The projection delivers each inspected 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.
|
||||
|
||||
The composition lists its dependency closure, twenty-six rows, instead of layering on `dsh-base`: no model adapter, prompt-side tool, telemetry, or session-management row loads. `cua-mcp` is not a required startup entry, so a row that cannot activate is reported by the launcher on stderr: an inactive provider leaves `cua_run_code` out of the listing, and an inactive frontend serves nothing. Client entries are documented in the README instead of generated.
|
||||
|
||||
## 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.
|
||||
|
||||
**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; the documented manifest is three lines and needs no launcher change.
|
||||
|
||||
**A `dsh.bundle.profile` declaration that app-boot initializes on the first `dsh --profile cua-mcp`.** It made the first start zero-step, at the price of a new manifest field and a `shippedProfileTemplate` lookup in app-boot, the CLI `dsh plugin` command, and the plugin manager for one experimental bundle; the plain manifest costs one documented step and leaves those packages untouched. Once CUA graduates from experimental, a `PROFILE_TEMPLATES` entry gives the same zero-step start.
|
||||
|
||||
**A hand-written MCP schema and description for `cua_run_code`.** The second copy drifted within days: 663 against 2,164 characters of description and an optional against a required `description`. Projecting the registration removes the copy; the SDK's `registerTool` accepts only Standard Schema values and refuses to share `tools/list` and `tools/call` with custom handlers, so both tools use the low-level handlers.
|
||||
|
||||
**The `cua` API reference inside the tool description or the server instructions.** Claude Code 2.1.309 forwards the first 4,096 characters of an MCP tool description, and of the server instructions, and appends `… [truncated]`, measured on 2026-11-10 with 20,000-character probe texts; `dsh-mcp-client` forwards the same description intact. The reference is about 13,000 characters, so it travels as a tool result, and the registration's 3,200-character description stays within the budget.
|
||||
|
||||
**The reference at the head of the first program result of each environment.** The server cannot observe which results a model keeps: a client such as `dsh-mcp-client` holds one connection for several conversations, a cancelled or failed first call discards its result, and context compaction drops the text later. The flag that recorded delivery was written by program calls and by resets without a common ordering point. A read tool without state lets the model that lacks the reference ask for it; in fifteen probe conversations on 2026-11-11, through `dsh-mcp-client` with a DeepSeek model and through Claude Code 2.1.309, every model called it before its first program.
|
||||
|
||||
**A reset operation on the PTC program-tool factory.** A factory handle with `reset(agent)` made the tool executor a second owner of environment recovery, with its own blocked state after a failed cleanup. The program runtime's owner release already ends an environment, and the next run for the same owner starts a new one; the frontend serializes the connection's calls, so it is the caller that orders them around the release.
|
||||
|
||||
**Replacing the connection's Agent on reset.** A new Agent has a new Session: the native connection closes, session consent is asked again, and a refusal is forgotten, which is what reconnecting does. A reset discards what programs hold; consent and the native connection belong to the connection and are no part of the program environment. Disposing an Agent also waits for the runtime's stop grace, three seconds by default, when the running program cannot be interrupted.
|
||||
|
||||
**A `--print-client-config codex|claude-code|json` option.** Rendering the exact command of an installation needs `node:sea` to tell a single-file executable from a script launch, and the browser worker image, which packs every optional bundle, registers no `node:sea`; the documented entries carry the same timeouts and output budget without that dependency.
|
||||
|
||||
## Consequences
|
||||
|
||||
Every installation carries the bundle; its native providers, macOS and Windows, are optional dependencies, each mounted by a row that loads only on its own Host, and `verify-default-product-isolation` keeps the bundle out of default templates. A profile that layers the bundle over `dsh-base` duplicates row ids and is unsupported; the Web plugin page hides the bundle through `HIDDEN_BUNDLES` while the Host inventory still reports it as optional. Hosts without a provider list `cua_get_api_reference` and `cua_reset`, which both name the missing provider, and a `cua_run_code` call fails as `unknown tool`. 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 tool descriptions, the server instructions, and the reference text are pinned by the profile's expected-output test; the program description and the reference change with the installed CUA packages. A model receives the reference only by calling `cua_get_api_reference`, so a client that withholds that tool leaves it with the execution rules alone. A provider description longer than 4,096 characters reaches Claude Code models cut.
|
||||
@@ -0,0 +1,55 @@
|
||||
# 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` 中的实验性组合包:它在空 profile 根上用一次 insert 组成独立的 `cua-mcp` profile。只选它这一个组合包的 profile manifest 就是全部安装步骤:启动器加载已存在的 manifest 时不查 `PROFILE_TEMPLATES`,而安装本身已自带该组合包,因此不涉及 pnpm 或 registry。这是唯一的 MCP 应用路径;没有包 bin 或 SDK 逃逸,该组合包不进入 `PROFILE_TEMPLATES`,因为模板不能引用实验包。
|
||||
|
||||
服务器运行在 profile 进程内,带着连接的 Agent、不经模型步骤地调用 `ctx.tools.execute`。一个 stdio 连接拥有一个 Agent:在 stdio 传输打开之前创建,stdin EOF 时销毁。每次程序调用都作为该 Agent 的维护活动运行,因此 Agent 销毁时会取消进行中的调用,并等它及其嵌套调用结算之后才关闭 Session。Agent 归属已经决定了保留的程序进程、本机连接和会话级授权,因此连接生命周期与状态生命周期重合。空的默认 preset `cua-mcp` 让该 Agent 只获得 `cua_run_code`,因为提供方只为已组合 preset 注册程序工具。该 Agent 在专用工作区中工作,即 `DSH_CUA_WORKSPACE`,未设置时为 Harness home 下的 `cua-mcp/workspace`:Agent 的工作目录就是其程序的 `workspace-write` 根,而客户端启动服务器的目录可能是 `/`。
|
||||
|
||||
工具面由三个工具构成。`cua_run_code` 就是该 Agent 的 DSH 注册项,经协议服务器的低层 `tools/list` 与 `tools/call` handler 提供:每次列表都从工具注册表投影名称、描述和参数,调用则在 Agent 的 initiator 作用域内把参数原样交给工具执行器,因此提供方的定义是唯一 schema,`description` 按该定义必填,校验与未知名称由 DSH 回答;唯一的剪裁是注册项中的沙箱提权字段,投影省略它们,调用也不得指定。`cua_get_api_reference` 返回 `cua` API 参考,即提供方为该 Agent 注册的指引;它不保存状态,因此连接上的任何对话随时都能读取。`cua_reset` 结束该 Agent 的程序环境并保留 Agent:前端取消正在运行的程序,再调用 `ctx.cuaPrograms.release`,由提供方的程序运行时释放该 state owner 的环境,CUA 提供方把它与 `screenshotRequestTarget` 一起暴露;下一个程序在新进程中启动,本机连接和本会话的授权决定保留。前端围绕这次释放安排自己的调用:reset 在被取消的程序结算之后才返回,程序则等待进行中的释放。投影把每张被 inspect 的截图按程序观察到的请求版本交付,使程序文本中的坐标与交付的图片一致。提供方新增的 `screenshotTarget` 配置取代了没有模型的 profile 无法满足的模型路由查询。
|
||||
|
||||
授权有两种模式。`DSH_CUA_CONSENT=allow` 以批准标签为本会话回答连接 Agent 的每个审批问题。默认的 `elicit` 把每个问题作为表单 elicitation 转发给客户端,枚举即问题的选项标签。不新增任何 Session 事件:训练侧只消费 MCP 工具结果,接入 harness 的 transcript 记录调用;DSH 保留嵌套的 `tool/ptc-dispatch` 事件以供诊断。
|
||||
|
||||
组合列出自己的依赖闭包(26 行),而不是叠在 `dsh-base` 之上:不加载任何模型适配器、提示侧工具、遥测或会话管理行。`cua-mcp` 不是启动必需条目,无法激活的行由启动器在 stderr 上报告:提供方行未激活时列表里没有 `cua_run_code`,前端未激活时不提供任何服务。客户端配置项由 README 给出,而不是由程序生成。
|
||||
|
||||
## 考虑过的替代方案
|
||||
|
||||
**通过 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 不具备的审批应答者。
|
||||
|
||||
**叠在 `dsh-base` 之上、禁用模型行的 profile 前端。** 组合出的 profile 带着约一百行没有消费者的插件:模型适配器、web 工具、子代理、压缩、遥测和会话管理。显式闭包只有四分之一,且在漂移时大声失败。
|
||||
|
||||
**用 `dsh plugin enable|disable` 子命令选中随附组合包。** 它在启动器里重复了插件管理器的仅改 manifest 选择,而且仍然产生以 base 为底的 profile;文档给出的 manifest 只有三行,不需要改启动器。
|
||||
|
||||
**由 app-boot 在首次 `dsh --profile cua-mcp` 时初始化的 `dsh.bundle.profile` 声明。** 它让首次启动零步可用,代价是为一个实验组合包在 manifest 新增字段,并在 app-boot、CLI `dsh plugin` 命令和插件管理器里加入 `shippedProfileTemplate` 查找;普通 manifest 只多一个有文档的步骤,且不触碰这些包。CUA 从实验状态毕业后,一条 `PROFILE_TEMPLATES` 条目就能得到同样的零步启动。
|
||||
|
||||
**为 `cua_run_code` 手写 MCP schema 与描述。** 第二份定义几天内就漂移了:描述 663 对 2,164 个字符,`description` 可选对必填。投影注册项去掉了这份副本;SDK 的 `registerTool` 只接受 Standard Schema 值,且不允许 `tools/list`、`tools/call` 与自定义 handler 混用,所以两个工具都走低层 handler。
|
||||
|
||||
**把 `cua` API 参考放进工具描述或服务器说明。** Claude Code 2.1.309 对 MCP 工具描述和服务器说明都只转发前 4,096 个字符并追加 `… [truncated]`,2026-11-10 用 20,000 个字符的探针文本测得;`dsh-mcp-client` 原样转发同一描述。参考约 13,000 个字符,因此作为工具结果传递,注册项 3,200 个字符的描述留在预算之内。
|
||||
|
||||
**把参考放在每个环境首个程序结果的开头。** 服务器观察不到模型保留了哪些结果:`dsh-mcp-client` 这类客户端用一个连接承载多次对话,被取消或失败的首次调用会丢弃其结果,上下文压缩之后这段文本也会消失。记录已交付的标志由程序调用和重置两处写入,二者没有共同的排序点。无状态的只读工具让缺少参考的模型自己去取;2026-11-11 的十五次探针对话中,经 `dsh-mcp-client` 的 DeepSeek 模型与 Claude Code 2.1.309 都在首个程序之前调用了它。
|
||||
|
||||
**在 PTC 程序工具工厂上提供 reset 操作。** 带 `reset(agent)` 的工厂句柄让工具执行器成为环境恢复的第二个所有者,清理失败后还带着自己的阻塞状态。程序运行时的 owner release 本来就能结束一个环境,同一所有者的下一次运行会启动新环境;前端串行化该连接的调用,因此由它这个调用方围绕释放来安排这些调用。
|
||||
|
||||
**reset 时更换连接的 Agent。** 新 Agent 意味着新 Session:本机连接关闭,会话授权要重新询问,拒绝记录也被遗忘,这正是重新连接的效果。reset 丢弃的是程序持有的东西;授权和本机连接属于连接,不是程序环境的一部分。销毁 Agent 时,如果正在运行的程序无法被中断,还要等待运行时的停止宽限期,默认三秒。
|
||||
|
||||
**`--print-client-config codex|claude-code|json` 选项。** 为当前安装渲染准确命令需要 `node:sea` 来区分单文件可执行程序与脚本启动,而打包全部可选组合包的浏览器 worker 镜像没有注册 `node:sea`;文档给出的配置项带有同样的超时与输出预算,不需要这项依赖。
|
||||
|
||||
## 后果
|
||||
|
||||
每个安装都携带该组合包;macOS 与 Windows 两个原生提供方是它的可选依赖,各由一行挂载,且只在对应的 Host 上加载,`verify-default-product-isolation` 让该组合包留在默认模板之外。把组合包叠在 `dsh-base` 之上的 profile 会出现重复的行 id,不受支持;Web 插件页通过 `HIDDEN_BUNDLES` 隐藏该组合包,而 Host 清单仍把它报告为可选组合包。没有提供方的 Host 列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方,调用 `cua_run_code` 以 `unknown tool` 失败。客户端会在进程退出、`cua_reset` 或 Agent 销毁时看到状态丢失并重新创建对象。授权 elicitation 依赖 2025 版 MCP 请求模型;使用 2026-07-28 修订版的客户端改用 `allow`。工具描述、服务器说明与参考文本由 profile 的期望输出测试固定;程序工具的描述和参考随已安装的 CUA 包变化。模型只有调用 `cua_get_api_reference` 才能得到参考,因此不放行该工具的客户端,其模型只有执行规则可用。提供方描述超过 4,096 个字符时,Claude Code 的模型只看到被截断的部分。
|
||||
@@ -495,6 +495,9 @@ jobs:
|
||||
console.log(JSON.stringify({ arch: process.arch, cpus: os.cpus().length,
|
||||
memoryGiB: Math.round(os.totalmem() / 2 ** 30) }))"
|
||||
|
||||
# No archive cache: this manual matrix includes the persistent 64/96-core
|
||||
# fleet rows, and a `~` cache written by an ephemeral runner does not
|
||||
# restore into the preparation directory there.
|
||||
- name: Install and prepare Linux
|
||||
if: matrix.platform == 'linux'
|
||||
run: |
|
||||
|
||||
@@ -179,6 +179,16 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-node-${{ env.PRIMARY_NODE_VERSION }}-pnpm-
|
||||
|
||||
# The persistent self-hosted pool keeps ~/.cache between jobs on its own
|
||||
# layout, so the archive cache follows the hosted-only pnpm store guard.
|
||||
- name: Restore verified bubblewrap archive
|
||||
id: bubblewrap-cache
|
||||
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Install dependencies and prepare bubblewrap
|
||||
run: |
|
||||
pnpm install --frozen-lockfile &
|
||||
@@ -192,6 +202,16 @@ jobs:
|
||||
if (( install_status != 0 )); then exit "$install_status"; fi
|
||||
exit "$sandbox_status"
|
||||
|
||||
# The save step is skipped on a hit. A restored archive whose digest fails
|
||||
# is re-downloaded but not re-saved (the key already exists), so a tampered
|
||||
# entry survives until eviction; that needs deliberate cache poisoning.
|
||||
- name: Save verified bubblewrap archive
|
||||
if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Run exhaustive coverage
|
||||
run: pnpm run check:ci:coverage
|
||||
|
||||
@@ -406,6 +426,16 @@ jobs:
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
# The persistent self-hosted pool keeps ~/.cache between jobs on its own
|
||||
# layout, so the archive cache follows the hosted-only pnpm store guard.
|
||||
- name: Restore verified bubblewrap archive
|
||||
id: bubblewrap-cache
|
||||
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Install dependencies and prepare bubblewrap
|
||||
run: |
|
||||
pnpm install --frozen-lockfile &
|
||||
@@ -419,6 +449,13 @@ jobs:
|
||||
if (( install_status != 0 )); then exit "$install_status"; fi
|
||||
exit "$sandbox_status"
|
||||
|
||||
- name: Save verified bubblewrap archive
|
||||
if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
# Blacksmith's Ubuntu HTTP archive endpoints can be unreachable while HTTPS works.
|
||||
- name: Use HTTPS for Ubuntu archives on Blacksmith
|
||||
if: vars.DSH_CI_FAILOVER_LINUX == 'blacksmith'
|
||||
@@ -532,9 +569,26 @@ jobs:
|
||||
- name: Install (immutable)
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
# The persistent self-hosted pool keeps ~/.cache between jobs on its own
|
||||
# layout, so the archive cache follows the hosted-only pnpm store guard.
|
||||
- name: Restore verified bubblewrap archive
|
||||
id: bubblewrap-cache
|
||||
if: vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Prepare bubblewrap (unrestrict userns)
|
||||
run: bash scripts/prepare-ci-bubblewrap.sh
|
||||
|
||||
- name: Save verified bubblewrap archive
|
||||
if: (vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]') && steps.bubblewrap-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
- name: Run compatibility smokes
|
||||
env:
|
||||
DSH_BUILD_CLIENT_PROFILE: official
|
||||
|
||||
@@ -79,12 +79,29 @@ jobs:
|
||||
- name: Install (immutable)
|
||||
run: pnpm install --frozen-lockfile
|
||||
|
||||
- name: Restore verified bubblewrap archive
|
||||
id: bubblewrap-cache
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
# The with-key escalation e2e self-skips without a usable runner. Prepare
|
||||
# bwrap so trusted CI exercises it; the functional probe remains the
|
||||
# authority on whether the runner can use the sandbox.
|
||||
- name: Prepare bubblewrap (unrestrict userns)
|
||||
run: bash scripts/prepare-ci-bubblewrap.sh
|
||||
|
||||
# A restored archive whose digest fails is re-downloaded but not re-saved
|
||||
# (the hit key already exists), so a tampered entry survives until
|
||||
# eviction; that needs deliberate cache poisoning.
|
||||
- name: Save verified bubblewrap archive
|
||||
if: steps.bubblewrap-cache.outputs.cache-hit != 'true'
|
||||
uses: actions/cache/[email protected]
|
||||
with:
|
||||
path: ~/.cache/dsh-ci/bubblewrap
|
||||
key: bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}
|
||||
|
||||
# Guard against a false green: the e2e suites self-skip when the key is
|
||||
# absent, so a missing/misconfigured secret would otherwise pass as
|
||||
# "all skipped". This job only runs on trusted events (the `if:` above
|
||||
|
||||
@@ -52,6 +52,7 @@ External packages installed for runtime use or embedded in distributed Host or b
|
||||
| [`@lexical/utils`](https://github.com/facebook/lexical) | MIT |
|
||||
| [`@modelcontextprotocol/client`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@modelcontextprotocol/sdk`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@modelcontextprotocol/server`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@noble/hashes`](https://github.com/paulmillr/noble-hashes) | MIT |
|
||||
| [`@octokit/webhooks`](https://github.com/octokit/webhooks.js) | MIT |
|
||||
| [`@openai/codex`](https://github.com/openai/codex) | Apache-2.0 |
|
||||
@@ -212,7 +213,6 @@ External packages **directly declared** for development, tests, types, or toolin
|
||||
| [`@electron/notarize`](https://github.com/electron/notarize) | MIT |
|
||||
| [`@lexical/headless`](https://github.com/facebook/lexical) | MIT |
|
||||
| [`@modelcontextprotocol/node`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@modelcontextprotocol/server`](https://github.com/modelcontextprotocol/typescript-sdk) | MIT |
|
||||
| [`@modelcontextprotocol/server-everything`](https://github.com/modelcontextprotocol/servers) | MIT / Apache-2.0 |
|
||||
| [`@modelcontextprotocol/server-filesystem`](https://github.com/modelcontextprotocol/servers) | MIT / Apache-2.0 |
|
||||
| [`@panzoom/panzoom`](https://github.com/timmywil/panzoom) | MIT |
|
||||
|
||||
@@ -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:*"
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
/** The shipped cua-mcp bundle: the real CLI loads a profile that selects only this bundle and serves Computer Use programs over stdio. */
|
||||
import { execFile } from 'node:child_process'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdir, mkdtemp, realpath, rm, writeFile } 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('serves programs over stdio from a profile that selects only this bundle, and exits on EOF', async () => {
|
||||
const temporary = await mkdtemp(join(tmpdir(), 'dsh-cua-mcp-profile-'))
|
||||
const home = join(temporary, 'home')
|
||||
// The directory the client launches the server from; programs must not start there.
|
||||
const launch = join(temporary, 'launch')
|
||||
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)
|
||||
// The default workspace is under test, whatever the developer's shell exports.
|
||||
delete env.DSH_CUA_WORKSPACE
|
||||
await execFileAsync(process.execPath, ['-e', 'require("node:fs").mkdirSync(process.argv[1], { recursive: true })', launch])
|
||||
// The profile manifest the README documents: the installation's shipped bundle as the only layer, no pnpm step.
|
||||
const profileDir = join(home, 'profiles', 'cua-mcp')
|
||||
await mkdir(profileDir, { recursive: true })
|
||||
await writeFile(join(profileDir, 'package.json'), `${JSON.stringify({
|
||||
name: 'dsh-profile-cua-mcp', private: true, dependencies: {}, dsh: { profile: { bundles: ['@deepseek-ai/dsh-cua-mcp'] } },
|
||||
}, null, 2)}\n`)
|
||||
|
||||
const probe = owned.probe = startProbe({ args: [bin, '--profile', 'cua-mcp', '--patch', fixturePatch], cwd: launch, 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 reference = await probe.request('tools/call', { name: 'cua_get_api_reference', arguments: {} }) as CallResult
|
||||
expect(reference.isError).toBeUndefined()
|
||||
expect(reference.content).toHaveLength(1)
|
||||
await expect(`${textOf(reference.content[0])}\n`).toMatchFileSnapshot('./expected/reference.md')
|
||||
|
||||
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.getAccessibilityTree(); await win.click("0"); '
|
||||
+ 'inspect(JSON.stringify({ visits, window: win.windowId, pid: process.pid, cwd: process.cwd() }), await win.getScreenshot())',
|
||||
description: 'Open the fixture window',
|
||||
} }) as CallResult
|
||||
expect(first.isError).toBeUndefined()
|
||||
expect(first.content.map(block => block.type)).toEqual(['text', 'image'])
|
||||
const state = JSON.parse(textOf(first.content[0])) as { visits: number; window: string; pid: number; cwd: string }
|
||||
expect(state).toMatchObject({ visits: 1, window: '7' })
|
||||
// Without DSH_CUA_WORKSPACE the profile creates its workspace inside the Harness home and starts programs there.
|
||||
// Both spellings are resolved: the temporary directory is a symlink on macOS and an 8.3 short name on Windows.
|
||||
const programDirectory = await realpath(state.cwd)
|
||||
expect(programDirectory).toBe(await realpath(join(home, 'cua-mcp', 'workspace')))
|
||||
expect(programDirectory).not.toBe(await realpath(launch))
|
||||
const image = first.content[1]
|
||||
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++; inspect(JSON.stringify({ 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: 'inspect(JSON.stringify({ visits: globalThis.visits ?? null, hasWindow: typeof win !== "undefined", pid: process.pid }))', description: 'Inspect the fresh environment',
|
||||
} }) as CallResult
|
||||
expect(third.content).toHaveLength(1)
|
||||
const afterReset = JSON.parse(textOf(third.content[0])) 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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua object; program state persists across calls on this connection. A call may ask the user for application or pointer consent before it proceeds. Call cua_reset to discard program state.
|
||||
@@ -0,0 +1,52 @@
|
||||
## 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. 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.
|
||||
|
||||
Call inspect(...values) to display selected observation results.
|
||||
|
||||
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: string and the methods listed below for window level. Window IDs are opaque provider-issued strings; preserve them verbatim.
|
||||
|
||||
Setup and discovery:
|
||||
- cua.getCapabilities() -> { 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() -> { id: string, displayName: string, isRunning: boolean, pid?: number }[] — list applications the provider exposes for selection with their current running state; pass the returned id unchanged to cua.getApp.
|
||||
- cua.findApps(query: string) -> { id: string, displayName: string, path: string, isRunning: boolean, pid?: number }[] — search installed applications, including stopped matches.
|
||||
- cua.getState() -> { apps: { id: string, displayName: string, isRunning: boolean, pid?: number }[], browsers: [] } — summarize the same provider discovery; this is not an accessibility observation.
|
||||
- cua.getApp(selector: string) -> App — select an application by provider-issued discovery ID, name, bundle ID, or absolute path where supported, obtain consent, start a stopped application in the background only where the provider supports launch, and return without reading AX or activating the app.
|
||||
- app.getWindows() -> { windowId: string, 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: string) -> 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: string | null, foregroundChanged: boolean | null } — unhide the app and restore its selected, focused, main, or sole window without activation.
|
||||
- window.show() -> { dispatched: boolean, windowId: string | null, foregroundChanged: boolean | null } — unhide and restore that explicit window without activation.
|
||||
|
||||
## Accessibility tree
|
||||
Available at app or window level depending on the platform.
|
||||
|
||||
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?: { 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.
|
||||
- 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. 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() -> Image — capture the selected window as a stored image with readonly attachmentId, path, width, and height. Pass selected screenshots to inspect(...values) to display them; read the window ID from window.windowId.
|
||||
- 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. 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.
|
||||
|
||||
Maximum click holdMs: 5000 ms.
|
||||
@@ -0,0 +1,64 @@
|
||||
[
|
||||
{
|
||||
"name": "cua_get_api_reference",
|
||||
"title": "Computer use API reference",
|
||||
"description": "Return the complete `cua` API reference that every cua_run_code program must follow: methods, signatures, and operating rules. Call it before the first cua_run_code program of a conversation, and again whenever the reference is no longer in your context or a program fails on an unknown `cua` method. It only reads: nothing on the desktop or in the program environment changes.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"annotations": {
|
||||
"readOnlyHint": true,
|
||||
"destructiveHint": false,
|
||||
"idempotentHint": true,
|
||||
"openWorldHint": false
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "cua_run_code",
|
||||
"title": "Computer use program",
|
||||
"description": "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. Use inspect(...values) to display selected text and images. 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. Use inspect(...values) to display output. Do not use console. The program runs in strict mode: assigning an undeclared name throws, so use globalThis for intentional globals; eval and new Function are unavailable. Variables, functions, and imported modules remain in memory for this Agent across calls. Each call starts with copies of the top-level bindings left by earlier calls and may declare any of those names again with any keyword. A new declaration applies to this and later calls; functions and still-running code from earlier calls keep the values they captured. Assigning to an earlier name without declaring it, even one declared with const, changes only the copy seen by this and later calls. A let, const, or class declaration cannot read the earlier value of its own name, so let total = total + 1 throws; assign to the name or use a new name instead. A var declaration of an earlier name starts from the earlier value. var declarations become top-level names of the call even inside blocks; other declarations inside blocks stay in their block. Assignments that earlier code makes later, such as from timers, are not visible to later calls; keep shared mutable state in objects. If a call fails before a let, const, class, or var declaration of an existing name finishes, later calls keep that name's earlier value. Use await import(...) for modules; require is unavailable, and relative specifiers resolve from the working directory of this environment's first call. 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. 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.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"code": {
|
||||
"type": "string",
|
||||
"description": "The TypeScript program to execute, following this tool's execution instructions."
|
||||
},
|
||||
"description": {
|
||||
"type": "string",
|
||||
"description": "Clear, concise description of what this program does in active voice, 5-10 words (shown in the UI). Examples: \"Count TODO markers across packages\"; \"Read failing test and its fixture\"; \"Rename config key in every cordis.yml\"."
|
||||
},
|
||||
"timeoutMs": {
|
||||
"type": "number",
|
||||
"description": "Positive elapsed-time budget in milliseconds, including nested tool and approval waits. Default 120000; capped at 600000. Zero does not disable the deadline."
|
||||
}
|
||||
},
|
||||
"required": [
|
||||
"code",
|
||||
"description"
|
||||
]
|
||||
},
|
||||
"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. A running cua_run_code program is cancelled. Application access grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment. Use it when the environment has become unusable or its retained state must not carry into the next task.",
|
||||
"inputSchema": {
|
||||
"type": "object",
|
||||
"properties": {}
|
||||
},
|
||||
"annotations": {
|
||||
"readOnlyHint": false,
|
||||
"destructiveHint": false,
|
||||
"idempotentHint": true,
|
||||
"openWorldHint": false
|
||||
}
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,18 @@
|
||||
# Replace both native providers with the recorded desktop fixture so the profile serves on every Host.
|
||||
- id: cua-mcp-provider
|
||||
disabled: true
|
||||
|
||||
- id: cua-mcp-provider-windows
|
||||
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
|
||||
@@ -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<unknown>
|
||||
/** @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<ProbeExit>
|
||||
/** Stop a failed fixture and await its exit. */
|
||||
terminate(): Promise<void>
|
||||
}
|
||||
|
||||
/**
|
||||
* 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<number, { resolve(value: unknown): void; reject(error: Error): void }>()
|
||||
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<ProbeExit>((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<unknown>()
|
||||
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
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -51,6 +51,8 @@ import { captureStableAria, compareOrRefreshGolden, webSnapshotMode } from './sc
|
||||
import { expandOwningTurnProcess, newEnglishPage, REPO_ROOT, saveFailureShot } from './support.ts'
|
||||
|
||||
const DIST_ROOT = fileURLToPath(new URL('../dist', import.meta.url))
|
||||
/** Optional bundles that compose a profile of their own; the Web plugin page hides them, the Host inventory still reports them. */
|
||||
const STANDALONE_PROFILE_BUNDLES: readonly string[] = ['@deepseek-ai/dsh-cua-mcp']
|
||||
|
||||
/** Where the client looks for the image: the runtime's own name, beside the page. */
|
||||
const IMAGE_FILE = join(DIST_ROOT, 'preview', IMAGE_FILE_NAME)
|
||||
@@ -611,8 +613,8 @@ async function requestLazyChunk(page: Page, site: Site, manifest: ImageManifest)
|
||||
|
||||
/**
|
||||
* Open the Plugins page, prove every optional bundle and installed plugin reads
|
||||
* its metadata, then switch each optional bundle on and off. Both changes apply
|
||||
* live; the session-titles layer applies after the base layers, and the
|
||||
* its metadata, then switch each layerable optional bundle on and off. Both changes
|
||||
* apply live; the session-titles layer applies after the base layers, and the
|
||||
* Inspector bundle runs Session Inspector without the NodeJS Inspector Worker.
|
||||
* @param page - Booted preview page.
|
||||
*/
|
||||
@@ -638,7 +640,8 @@ async function toggleOptionalBundles(page: Page): Promise<void> {
|
||||
expect(mask.url).toMatch(/^blob:/u)
|
||||
expect(mask.unresolved).toBe(false)
|
||||
expect(mask.width).toBeGreaterThan(0)
|
||||
const result = await page.evaluate(async () => {
|
||||
const standalone = STANDALONE_PROFILE_BUNDLES
|
||||
const result = await page.evaluate(async ({ standalone }) => {
|
||||
type Result<T> = { result: { ok: true; value: T } | { ok: false; error: { message: string } } }
|
||||
const transport = (globalThis as typeof globalThis & {
|
||||
__DSH_TRANSPORT__?: { fetch(input: string, init: RequestInit): Promise<Response> }
|
||||
@@ -682,9 +685,11 @@ async function toggleOptionalBundles(page: Page): Promise<void> {
|
||||
}> = []
|
||||
// The packed worker composition cannot mount the Liveshare declaration row and its share host in
|
||||
// the same patch batch without racing the declaration service; the ordinary Web scaffold covers
|
||||
// that bundle's enable/disable path (plugin-manager.e2e.ts), so the packed toggle list skips it.
|
||||
// that bundle's enable/disable path (plugin-manager.e2e.ts), so the packed toggle list skips it. A bundle that
|
||||
// composes a profile of its own is reported by the Host inventory but never layered over the Web profile, so the
|
||||
// toggle list skips it too.
|
||||
for (const entry of bundles.filter(candidate => candidate.optional
|
||||
&& candidate.name !== '@deepseek-ai/dsh-experimental-liveshare')) {
|
||||
&& candidate.name !== '@deepseek-ai/dsh-experimental-liveshare' && !standalone.includes(candidate.name))) {
|
||||
const enable = await remote<{ application: string; error?: unknown }>('pluginManager/setBundleEnabled', { name: entry.name, enabled: true })
|
||||
const plugins = await remote<Plugin[]>('pluginManager/listPlugins', {})
|
||||
const disable = await remote<{ application: string }>('pluginManager/setBundleEnabled', { name: entry.name, enabled: false })
|
||||
@@ -710,8 +715,10 @@ async function toggleOptionalBundles(page: Page): Promise<void> {
|
||||
.map(row => ({ moduleName: row.moduleName, error: row.meta?.error })),
|
||||
toggles,
|
||||
}
|
||||
})
|
||||
}, { standalone })
|
||||
expect(result.optional.map(entry => entry.name).sort()).toEqual([...OPTIONAL_BUNDLES].sort())
|
||||
// The Host inventory reports the standalone bundle with its metadata, switched off; no toggle targets it.
|
||||
expect(result.toggles.map(toggle => toggle.name).filter(name => standalone.includes(name))).toEqual([])
|
||||
expect(result.optional.filter(entry => entry.enabled || entry.availability !== 'installation')).toEqual([])
|
||||
expect(result.optional.filter(entry => entry.error !== null)).toEqual([
|
||||
expect.objectContaining({ name: '@deepseek-ai/dsh-cua-bundle', error: { code: 'unsupported-platform' } }),
|
||||
|
||||
@@ -6,5 +6,5 @@
|
||||
en: 41d772192075e133
|
||||
zh: 5ef3da69b4de1d8a
|
||||
/capability-seams-and-core-services:
|
||||
en: 6ee59b1e20c0478a
|
||||
zh: 263c1cbe08a5c6ee
|
||||
en: 9f66fbb344cf1074
|
||||
zh: 7f985c73b1e6a34e
|
||||
@@ -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<br/>Computer Use permission controls"]
|
||||
svc_cuaPrograms["ctx.cuaPrograms<br/>Computer Use program environments"]
|
||||
pkg_cua_mcp["cua-mcp"]
|
||||
pkg_office_kit["office-kit"]
|
||||
svc_officeKit["ctx.officeKit<br/>Office rendering, conversion, and recalculation"]
|
||||
pkg_client_ui_sidebar_documentpreview["client-ui-sidebar-documentpreview"]
|
||||
@@ -356,6 +358,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
|
||||
@@ -513,6 +516,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
|
||||
@@ -669,6 +673,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 releases one Agent's 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. |
|
||||
|
||||
@@ -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<br/>Computer Use permission controls"]
|
||||
svc_cuaPrograms["ctx.cuaPrograms<br/>Computer Use program environments"]
|
||||
pkg_cua_mcp["cua-mcp"]
|
||||
pkg_office_kit["office-kit"]
|
||||
svc_officeKit["ctx.officeKit<br/>Office rendering, conversion, and recalculation"]
|
||||
pkg_client_ui_sidebar_documentpreview["client-ui-sidebar-documentpreview"]
|
||||
@@ -358,6 +360,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) | - | 每个服务实例注册一个提供方拥有的名称。提供方按实时 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 将回执绑定到已接受的提交。 |
|
||||
|
||||
@@ -918,6 +918,35 @@ export type SourceSigning = 'ad-hoc' | {
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-cua-macos -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-cua-mcp -->
|
||||
<a id="deepseek-aidsh-cua-mcp"></a>
|
||||
|
||||
## `@deepseek-ai/dsh-cua-mcp`
|
||||
|
||||
- `inject`: `cmdlineArgs` · `appReady` · `appExit` · `profileContext` · `agents` · `agentPresets` · `tools` · `systemPrompt` · `attachments`
|
||||
- `source`: [`packages/experimental/cua-mcp/src/index.ts:25`](../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
|
||||
/**
|
||||
* Absolute directory the connection's Agent works in: its programs start there, and it is their
|
||||
* `workspace-write` root. Startup creates it when missing; a relative path or a directory that cannot be
|
||||
* created is reported on stderr and ends the process with exit code 1.
|
||||
*/
|
||||
workspace: string
|
||||
}
|
||||
|
||||
/** Who decides application and pointer consent for the connection's Agent. */
|
||||
export type ConsentMode = 'allow' | 'elicit'
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-cua-mcp -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-cua-windows -->
|
||||
<a id="deepseek-aidsh-cua-windows"></a>
|
||||
|
||||
|
||||
@@ -920,6 +920,35 @@ export type SourceSigning = 'ad-hoc' | {
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-cua-macos -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-cua-mcp -->
|
||||
<a id="deepseek-aidsh-cua-mcp"></a>
|
||||
|
||||
## `@deepseek-ai/dsh-cua-mcp`
|
||||
|
||||
- `inject`: `cmdlineArgs` · `appReady` · `appExit` · `profileContext` · `agents` · `agentPresets` · `tools` · `systemPrompt` · `attachments`
|
||||
- `source`: [`packages/experimental/cua-mcp/src/index.ts:25`](../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
|
||||
/**
|
||||
* Absolute directory the connection's Agent works in: its programs start there, and it is their
|
||||
* `workspace-write` root. Startup creates it when missing; a relative path or a directory that cannot be
|
||||
* created is reported on stderr and ends the process with exit code 1.
|
||||
*/
|
||||
workspace: string
|
||||
}
|
||||
|
||||
/** Who decides application and pointer consent for the connection's Agent. */
|
||||
export type ConsentMode = 'allow' | 'elicit'
|
||||
```
|
||||
<!-- END GENERATED config-catalog:@deepseek-ai/dsh-cua-mcp -->
|
||||
|
||||
<!-- BEGIN GENERATED config-catalog:@deepseek-ai/dsh-cua-windows -->
|
||||
<a id="deepseek-aidsh-cua-windows"></a>
|
||||
|
||||
|
||||
@@ -90,7 +90,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) |
|
||||
|
||||
@@ -92,7 +92,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) |
|
||||
|
||||
@@ -266,6 +266,7 @@ flowchart TD
|
||||
pkg_cua["cua"]
|
||||
pkg_cua_bundle["cua-bundle"]
|
||||
pkg_cua_macos["cua-macos"]
|
||||
pkg_cua_mcp["cua-mcp"]
|
||||
pkg_cua_windows["cua-windows"]
|
||||
pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"]
|
||||
pkg_experimental_auto_review["experimental-auto-review"]
|
||||
@@ -527,6 +528,8 @@ flowchart TD
|
||||
pkg_credentials_local --> pkg_credentials
|
||||
pkg_credentials_local --> pkg_home_paths
|
||||
pkg_credentials_local --> pkg_launch_environment
|
||||
pkg_cua_mcp --> pkg_app_boot
|
||||
pkg_cua_mcp --> pkg_attachment
|
||||
pkg_experimental_forge_github --> pkg_experimental_forge
|
||||
pkg_experimental_forge_github --> pkg_subprocess
|
||||
pkg_experimental_webworker_runtime --> pkg_client_connection
|
||||
@@ -1719,6 +1722,7 @@ flowchart TD
|
||||
| [`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) |
|
||||
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
|
||||
| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) |
|
||||
| [`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) |
|
||||
| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) |
|
||||
|
||||
@@ -268,6 +268,7 @@ flowchart TD
|
||||
pkg_cua["cua"]
|
||||
pkg_cua_bundle["cua-bundle"]
|
||||
pkg_cua_macos["cua-macos"]
|
||||
pkg_cua_mcp["cua-mcp"]
|
||||
pkg_cua_windows["cua-windows"]
|
||||
pkg_experimental_api_speech_to_text["experimental-api-speech-to-text"]
|
||||
pkg_experimental_auto_review["experimental-auto-review"]
|
||||
@@ -529,6 +530,8 @@ flowchart TD
|
||||
pkg_credentials_local --> pkg_credentials
|
||||
pkg_credentials_local --> pkg_home_paths
|
||||
pkg_credentials_local --> pkg_launch_environment
|
||||
pkg_cua_mcp --> pkg_app_boot
|
||||
pkg_cua_mcp --> pkg_attachment
|
||||
pkg_experimental_forge_github --> pkg_experimental_forge
|
||||
pkg_experimental_forge_github --> pkg_subprocess
|
||||
pkg_experimental_webworker_runtime --> pkg_client_connection
|
||||
@@ -1721,6 +1724,7 @@ flowchart TD
|
||||
| [`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) |
|
||||
| [`credentials-local`](../packages/credentials/credentials-local) | `credentials` | [`atomic-write`](../packages/util/atomic-write), [`credentials`](../packages/credentials/credentials), [`home-paths`](../packages/util/home-paths), [`launch-environment`](../packages/util/launch-environment) |
|
||||
| [`cua-mcp`](../packages/experimental/cua-mcp) | `experimental` | [`app-boot`](../packages/boot/app-boot), [`attachment`](../packages/attachment/attachment) |
|
||||
| [`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) |
|
||||
| [`host-directory-picker-auto`](../packages/host/directory-picker-auto) | `host` | [`client-connection`](../packages/client/connection), [`client-ui-directory-picker-browse`](../packages/client/ui-directory-picker-browse), [`client-ui-directory-picker-native`](../packages/client/ui-directory-picker-native), [`host-directory-picker-browse`](../packages/host/directory-picker-browse), [`host-directory-picker-native`](../packages/host/directory-picker-native), [`host-webserver`](../packages/host/webserver) |
|
||||
|
||||
@@ -5,6 +5,9 @@
|
||||
/computer-use:
|
||||
en: 45a0f430190937de
|
||||
zh: 7b48603bebfcd1c6
|
||||
/computer-use/serve-computer-use-to-another-harness:
|
||||
en: 6424dd8388f342fb
|
||||
zh: c5ecebb60ab1f50f
|
||||
/computer-use/choose-a-provider:
|
||||
en: 4a72c1987678a47b
|
||||
zh: b039d15b4e782cc4
|
||||
|
||||
@@ -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 that composes the standalone `cua-mcp` profile; a profile manifest that selects it alone is the whole setup. `dsh --profile cua-mcp` serves `cua_get_api_reference`, `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. 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. The Computer Use bundle selects the native provider for the host platform. Custom compositions can also mount a provider directly.
|
||||
@@ -138,4 +142,38 @@ Browser controls for provider-owned native permission and application decisions.
|
||||
```
|
||||
|
||||
Source: [`packages/experimental/cua/src/access.ts`](../../packages/experimental/cua/src/access.ts)
|
||||
|
||||
<a id="ctxcuaprograms--cuaprograms"></a>
|
||||
|
||||
### `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 with the dedicated runtime's owner release. The program
|
||||
* process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code`
|
||||
* call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native
|
||||
* connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's
|
||||
* programs until the release settles, so the caller holds them back; after a failed release it rejects them
|
||||
* until a later release succeeds. Resolves when no environment exists.
|
||||
* @param agent - Agent whose `cua_run_code` state owner is released.
|
||||
* @returns Completion after the process has exited and its output has drained.
|
||||
* @throws When the process cleanup fails.
|
||||
*/
|
||||
release(agent: Agent): Promise<void>
|
||||
|
||||
/**
|
||||
* 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)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
@@ -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;只选它的 profile manifest 就是全部设置。`dsh --profile cua-mcp` 向一个 MCP 客户端(如 Codex 或 Claude Code)提供 `cua_get_api_reference`、`cua_run_code` 和 `cua_reset`;每个连接拥有一个 Agent,其程序保留应用与窗口对象,授权可无人值守放行或作为 elicitation 转发给客户端。该 profile 不运行模型回合,其 Session 中不记录根工具调用。
|
||||
|
||||
## 选择提供方
|
||||
|
||||
在同一组合中挂载 [`dsh-computer-use`](../../packages/computer-use/computer-use/README.zh.md) 和一个提供方。Computer Use 组合会按宿主平台选择原生提供方。自定义组合也可以直接挂载提供方。
|
||||
@@ -138,4 +142,38 @@ Browser controls for provider-owned native permission and application decisions.
|
||||
```
|
||||
|
||||
Source: [`packages/experimental/cua/src/access.ts`](../../packages/experimental/cua/src/access.ts)
|
||||
|
||||
<a id="ctxcuaprograms--cuaprograms"></a>
|
||||
|
||||
### `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 with the dedicated runtime's owner release. The program
|
||||
* process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code`
|
||||
* call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native
|
||||
* connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's
|
||||
* programs until the release settles, so the caller holds them back; after a failed release it rejects them
|
||||
* until a later release succeeds. Resolves when no environment exists.
|
||||
* @param agent - Agent whose `cua_run_code` state owner is released.
|
||||
* @returns Completion after the process has exited and its output has drained.
|
||||
* @throws When the process cleanup fails.
|
||||
*/
|
||||
release(agent: Agent): Promise<void>
|
||||
|
||||
/**
|
||||
* 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)
|
||||
<!-- END GENERATED cordis-surface -->
|
||||
@@ -30,5 +30,5 @@
|
||||
en: 27a59706525c88ed
|
||||
zh: 1fb1684bc03bb6ae
|
||||
/mcp/further-reading:
|
||||
en: 1d24646cc4174154
|
||||
zh: 3cb4253d39402451
|
||||
en: b2642914c5a9def4
|
||||
zh: eb1f739949e040b0
|
||||
@@ -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.
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
|
||||
@@ -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 程序。
|
||||
|
||||
<!-- BEGIN GENERATED cordis-surface (gen-cordis-catalog.ts) — do not edit between markers -->
|
||||
|
||||
|
||||
@@ -18,8 +18,8 @@
|
||||
en: 55d9e37b0a8dd4d8
|
||||
zh: 3acb6415f92698fb
|
||||
/packages-experimental/packages:
|
||||
en: cf70b6a5639b3fc1
|
||||
zh: 20c29b9115809246
|
||||
en: e769f9f0a455c2b6
|
||||
zh: b9ee012a83a4a0ad
|
||||
/packages-experimental/related-documentation:
|
||||
en: 40797d4849455966
|
||||
zh: bb91a68dd995887c
|
||||
|
||||
@@ -80,6 +80,7 @@ Promotion requires a named product role, documented public behavior and limitati
|
||||
| [macOS CUA](cua-macos/README.md) | Swift native execution and platform preparation. | `ctx.computerUse` |
|
||||
| [Windows CUA](cua-windows/README.md) | Native application and window operations through Windows UI Automation. | `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` |
|
||||
|
||||
@@ -80,6 +80,7 @@ kind: "package-group"
|
||||
| [macOS CUA](cua-macos/README.zh.md) | Swift 原生执行与平台组件准备。 | `ctx.computerUse` |
|
||||
| [Windows CUA](cua-windows/README.zh.md) | 通过 Windows UI Automation 操作应用与窗口。 | `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` |
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
en: 1777e7bf6785f986
|
||||
zh: e3daac1074ebb74d
|
||||
/deepseek-ai-dsh-cua-macos/use-this-package:
|
||||
en: d9843ea5d0bc7703
|
||||
zh: 28911258d10d680e
|
||||
en: 5c79725ad2f7b3ea
|
||||
zh: 43cd51fc152bf9b5
|
||||
/deepseek-ai-dsh-cua-macos/use-this-package/connect-an-external-execution-environment:
|
||||
en: 7058be5d1b778643
|
||||
zh: 821de6b0ad7aba27
|
||||
|
||||
@@ -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. |
|
||||
| `standaloneRunCode.runtime` / `standaloneRunCode.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. |
|
||||
|
||||
@@ -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`。 |
|
||||
| `standaloneRunCode.runtime` / `standaloneRunCode.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` 时仅本次显式移动免询问。 |
|
||||
|
||||
@@ -143,7 +143,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<typeof NativeProvider.Config>[0] = {},
|
||||
) {
|
||||
native.connect.mockClear()
|
||||
native.cleanup.mockReset().mockResolvedValue({ dispatched: true })
|
||||
native.request.mockReset().mockResolvedValue([])
|
||||
@@ -160,7 +162,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: brandString<SessionId>('native-lifecycle'), meta: { cwd: process.cwd() }, ...model ? { agentOptions: model } : {} })
|
||||
let index = 0
|
||||
@@ -785,6 +787,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' })
|
||||
|
||||
@@ -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: bc050868d6516402
|
||||
zh: b87be90c2ad7fe19
|
||||
/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/start-the-server:
|
||||
en: ce44d68f2ede2c0f
|
||||
zh: 1d7bbd8a9aabc7f5
|
||||
/deepseek-ai-dsh-cua-mcp/use-this-package/connect-a-client:
|
||||
en: 67ead744db140e08
|
||||
zh: eac0c52840b65922
|
||||
/deepseek-ai-dsh-cua-mcp/use-this-package/what-you-get:
|
||||
en: 44044e39f455e46f
|
||||
zh: 657393ce56a7a3b5
|
||||
/deepseek-ai-dsh-cua-mcp/configuration:
|
||||
en: 3fc42ffbb107d5ac
|
||||
zh: 1fda41e53d3b4c9f
|
||||
/deepseek-ai-dsh-cua-mcp/understand-the-implementation:
|
||||
en: 7e685c1041391819
|
||||
zh: 5a80112fd5f3d82f
|
||||
/deepseek-ai-dsh-cua-mcp/further-exploration:
|
||||
en: 5b8bd3e71ebbb316
|
||||
zh: f1c8b9ae63ce3aac
|
||||
/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: b4b85192e7287a64
|
||||
zh: 82457adbaa7c2454
|
||||
/deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/token-effect:
|
||||
en: eea25b57964fd62e
|
||||
zh: fbd23924f1562960
|
||||
/deepseek-ai-dsh-cua-mcp/model-experience/external-harness-model/kv-cache-effect:
|
||||
en: 0b0c63281111993b
|
||||
zh: 45716a56b5a5ad12
|
||||
/deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work:
|
||||
en: 7d592e6b49063ae8
|
||||
zh: 6f58f0e3a00dd2a8
|
||||
/deepseek-ai-dsh-cua-mcp/known-limitations-and-deferred-work/dev-note:
|
||||
en: e67f633dc6fe7773
|
||||
zh: 8ec3e73528ddb1a6
|
||||
@@ -0,0 +1,189 @@
|
||||
---
|
||||
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 composes the standalone `cua-mcp` profile, an MCP stdio server for Computer Use. Every DSH installation ships it; a profile manifest that selects this bundle alone lets `dsh --profile cua-mcp` serve `cua_get_api_reference`, `cua_run_code`, and `cua_reset` to one MCP client. The profile is this bundle alone: no model adapter, prompt-side tool, or telemetry row loads. 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 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)
|
||||
|
||||
-----
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## Use this package
|
||||
|
||||
### Start the server
|
||||
|
||||
The bundle is a runtime dependency of the `dsh` installation, so a profile that selects it as its only layer loads it from the installation; no pnpm, registry, or network access is involved. Create the profile once under the Harness home (`$DSH_HOME`, by default `~/.dsh`); `dsh --profile cua-mcp` is then the stdio command, and a source checkout runs it through `pnpm dsh` after `pnpm run build`. Do not add the bundle to a profile that already composes `dsh-base`, such as the one `dsh plugin --profile cua-mcp add` creates: both compositions declare the same row ids, which is also why the Web plugin page hides this bundle while the Host inventory still reports it as optional.
|
||||
|
||||
```sh
|
||||
mkdir -p "${DSH_HOME:-$HOME/.dsh}/profiles/cua-mcp"
|
||||
printf '%s\n' '{ "name": "dsh-profile-cua-mcp", "private": true, "dependencies": {}, "dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-cua-mcp"] } } }' > "${DSH_HOME:-$HOME/.dsh}/profiles/cua-mcp/package.json"
|
||||
```
|
||||
|
||||
The Python runtime wheel ships the same installation: write the same manifest under the home the harness passes as `DSH_HOME`, then use its executable as the stdio command:
|
||||
|
||||
```python
|
||||
from deepseek_harness_runtime import resolve_bundled_launch_args
|
||||
|
||||
command = [*resolve_bundled_launch_args(), "--profile", "cua-mcp"] # the MCP stdio command
|
||||
```
|
||||
|
||||
### Connect a client
|
||||
|
||||
`dsh --profile cua-mcp` is the stdio command, and `--help` prints its own help. A client entry names the installation's `dsh` executable by absolute path, passes `--profile cua-mcp`, sets `DSH_HOME` when the server should use a Harness home other than the default, `DSH_CUA_CONSENT` for the consent mode, and `DSH_CUA_WORKSPACE` when programs should work in a directory other than the default workspace; from a source checkout the command is `node` with `<checkout>/apps/cli/lib/bin.js` as its first argument, after `pnpm run build`. For Codex, add to `~/.codex/config.toml`:
|
||||
|
||||
```toml
|
||||
[mcp_servers.dsh_cua]
|
||||
command = "/absolute/path/to/dsh"
|
||||
args = ["--profile", "cua-mcp"]
|
||||
env = { DSH_HOME = "/absolute/path/to/dsh-home", DSH_CUA_CONSENT = "elicit" }
|
||||
required = true
|
||||
startup_timeout_sec = 120
|
||||
tool_timeout_sec = 600
|
||||
enabled_tools = ["cua_get_api_reference", "cua_run_code", "cua_reset"]
|
||||
omit_tools_from = ["code_mode", "deferred"]
|
||||
|
||||
[mcp_servers.dsh_cua.tools.cua_run_code]
|
||||
output_token_limit = 25000
|
||||
```
|
||||
|
||||
`required = true` makes Codex wait for the server before its first model request and end the session when the server does not start; without it Codex waits `mcp_optional_startup_grace_ms`, one second by default, and the first request can go out without the three tools. `startup_timeout_sec = 120` bounds that wait and covers first-run helper preparation, `tool_timeout_sec = 600` matches the default program maximum, `enabled_tools` with `omit_tools_from` exposes the three tools directly instead of through tool search, and `output_token_limit` raises the `cua_run_code` output budget to 25,000 tokens.
|
||||
|
||||
`codex exec` runs with the approval policy `never`, under which Codex refuses `cua_run_code`, the one tool this server annotates as destructive and open-world, with `MCP tool call requires approval, but approval policy is never` (observed on codex-cli 0.153.2). An unattended run therefore adds `approval_mode = "approve"` to the `cua_run_code` table and sets `DSH_CUA_CONSENT = "allow"`.
|
||||
|
||||
For Claude Code, register the same entry with a ten-minute tool timeout:
|
||||
|
||||
```sh
|
||||
claude mcp add-json dsh_cua '{"type":"stdio","command":"/absolute/path/to/dsh","args":["--profile","cua-mcp"],"env":{"DSH_HOME":"/absolute/path/to/dsh-home","DSH_CUA_CONSENT":"elicit"},"timeout":600000,"alwaysLoad":true}'
|
||||
```
|
||||
|
||||
Other clients take the same `command`, `args`, and `env` under `mcpServers`. The Claude Code, `dsh-mcp-client`, and Codex entries were exercised against a real macOS desktop, Codex through `codex exec` on codex-cli 0.153.2 and 0.166.0-alpha.5.1 with `DSH_CUA_CONSENT=allow`; no client has driven a Windows desktop through this profile. Codex's interactive approval prompts and its elicitation forwarding were not exercised here; per the Codex configuration reference as of 2026-11-11, 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`.
|
||||
|
||||
A client that allows tools by name must allow all three: without `cua_get_api_reference` its model has no `cua` API reference. Give the server a Harness home that no profile with uncompressed Session logs shares: this profile writes zstd-compressed logs under `sessions`, and a profile that sets `compression: none`, such as `sdk-minimal`, fails Session queries on a directory that holds them.
|
||||
|
||||
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 the macOS provider package's `native/.build/prepared/<arch>/<build>/` directory, 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 native Windows the profile mounts the [Windows provider](../cua-windows/README.md), which owns helper setup: a source checkout builds the helper with the .NET 10 SDK on PATH, and an npm installation ships none. For such an installation, name the helper with `helperPath` on the `cua-mcp-provider-windows` row in the profile's `cordis.patch.yml`: the absolute path of `dsh-cua-windows.exe`, from the extracted standalone ZIP on x64 or a matching build on ARM64. A patch replaces the row's whole config, so restate the bundle's fields:
|
||||
|
||||
```yaml
|
||||
- id: cua-mcp-provider-windows
|
||||
config:
|
||||
agentPreset: ptc
|
||||
screenshotTarget:
|
||||
longEdge: 2048
|
||||
maxBytes: 2097152
|
||||
helperPath: 'C:\absolute\path\to\dsh-cua-windows.exe'
|
||||
```
|
||||
|
||||
That provider does not launch applications and offers no `Always allow` grant: open the application before a program selects it, and under `elicit` every connection asks for consent again. The profile does not mount it under WSL.
|
||||
|
||||
On other Hosts the profile starts without a provider: the listing carries `cua_get_api_reference` and `cua_reset`, each of which returns an error naming the missing provider, and a `cua_run_code` call fails as `unknown tool`. A provider row that fails to activate, such as the Windows row without a helper, leaves the same listing, and the launcher names the failure on stderr.
|
||||
|
||||
### What you get
|
||||
|
||||
`cua_get_api_reference` returns the `cua` API reference: the guidance the provider registers for the connection's Agent, with every method signature and operating rule, which a DSH model receives in its system prompt. It takes no arguments, runs no program, and touches neither the desktop nor the program environment, so it also answers while a program is running. The server instructions ask the model to call it at the start of every conversation, and its description asks for another call when the reference has left the model's context or a program fails on an unknown `cua` method.
|
||||
|
||||
`cua_run_code` is the Agent's DSH registration served as an MCP tool: every `tools/list` reads its name, description, and parameter schema from the tool registry, so the provider's definition is the only source, `description` is required as that definition declares, and `timeoutMs` bounds one program. The projection omits the registration's sandbox-escalation fields, `sandbox_permissions` and `justification`, and a call naming them is refused before execution; every other argument passes to the DSH tool executor unchanged, which validates them and answers unknown names, so an invalid call returns DSH's error result. The program runs as TypeScript REPL statements against the global `cua` object in the provider's retained Node environment. The result carries what the program passes to `inspect(...)`: text as text blocks and each inspected screenshot as an inline image in the exact version the program observed, so pixel coordinates in the text match the image; a program that inspects nothing returns a completion notice. The tool description carries the execution rules. Programs start in the workspace and run one at a time per connection in arrival order; a cancelled call cancels its program. A failed call returns DSH's failure message with `isError` set and without DSH's `Error:` prefix.
|
||||
|
||||
`cua_reset` discards the program environment and nothing else. The program process ends, so its variables, imports, and application and window objects are gone; a `cua_run_code` program that is still running is cancelled, and the reset answers after that program has. The connection's Agent stays with its native connection and its consent decisions: an application granted for the session is not asked again, a refused one stays refused, and saved grants and the helper's system permissions are untouched. The next program starts a fresh process with a new `cua` object and selects applications again with `cua.getApp`; a program that arrives during a reset runs after it. A reset whose process cleanup fails returns an error, and programs fail until a later `cua_reset` succeeds. Use it after an unusable environment, or to keep retained state out of the next task.
|
||||
|
||||
The connection's Agent is created in the workspace before the stdio transport opens, so the first listing already carries its registration, and disposed when the client closes stdin, which also exits the process. The workspace is `DSH_CUA_WORKSPACE`, or `cua-mcp/workspace` under the Harness home when the variable is unset; the profile creates it, programs start there, and it is the directory the default `workspace-write` sandbox lets them write, whatever directory the client launched the server from. 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.
|
||||
|
||||
-----
|
||||
|
||||
<a id="configuration"></a>
|
||||
## Configuration
|
||||
|
||||
Configure the `cua-mcp` row in the profile's `cordis.patch.yml`; the bundle patch maps `DSH_CUA_CONSENT` and `DSH_CUA_WORKSPACE` 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. |
|
||||
| `workspace` | `cua-mcp/workspace` under the Harness home | Absolute directory the connection's Agent works in. Programs start there and it is their `workspace-write` root. Startup creates it when missing; a relative path or a directory that cannot be created is reported on stderr and ends the process with exit code 1. |
|
||||
|
||||
The patch also mounts the Host's native provider, row `cua-mcp-provider` on macOS and row `cua-mcp-provider-windows` on native Windows, 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; an override replaces the row's whole config, so restate the fields it keeps. The `sandbox-policy` row's `workspaceRoot` resolves the same directory as `workspace`; a program's root is its Agent's working directory, so that field covers only calls without a Session.
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## Understand the implementation
|
||||
|
||||
<details>
|
||||
<summary>Implementation internals — click to expand</summary>
|
||||
|
||||
The [patch](cordis.patch.yml) composes the whole profile over the empty root: sessions with JSONL persistence and projections, attachments, storage for application grants, the subprocess, sandbox, approval, and filesystem seams program processes run under, tools with the native executor, the system prompt, user questions, the llm hub without an adapter, the Agent registry with the agent-loop factory, the preset registry with the empty default preset, the `computer-use` registry, one native provider row per Host, macOS on Darwin and Windows on native Windows, and this frontend. A profile manifest that lists this bundle alone selects the composition; the launcher loads it from the installation without a template. The frontend parses the invocation with `parseCmdline`, binds stdin EOF to the launcher's bounded shutdown, and after the launcher commits readiness creates the workspace and connects the official MCP server to a stdio transport. `cua-mcp` is not a required startup entry: the launcher reports an inactive row on stderr instead of stopping the profile.
|
||||
|
||||
[`server.ts`](src/server.ts) serves the three tools through the protocol server's low-level `tools/list` and `tools/call` handlers: the listing projects the Agent's `cua_run_code` registration, checked against the protocol's tool type, between the two tools that file defines. The connection's Agent mounts the registry's default preset and records the workspace as its working directory, which the sandbox policy resolves as the `workspace-write` root of its programs. `cua_get_api_reference` reads the provider's prompt section for that Agent through `ctx.systemPrompt.assemble` and keeps no state. A `cua_run_code` call runs through `ctx.tools.execute` inside `ctx.agents.withInitiator` 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` cancels the Agent's running program with `agent.cancel`, calls `ctx.cuaPrograms.release`, with which the provider's program runtime releases the environment of that state owner, and answers once the Agent is idle; one release runs at a time, and program calls wait for it because the runtime rejects a program while the previous process is exiting. [`consent.ts`](src/consent.ts) is the `user-questions/request` answerer for that Agent. A `cua_run_code` call runs as the Agent's maintenance activity, so an Agent disposed while a call is in flight cancels the call and waits for it and its nested calls to settle before it releases its native connection and closes its Session.
|
||||
|
||||
</details>
|
||||
|
||||
-----
|
||||
|
||||
<a id="further-exploration"></a>
|
||||
## 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.
|
||||
- [Windows provider](../cua-windows/README.md) — helper setup, interaction rules, and platform limits.
|
||||
- [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.
|
||||
|
||||
-----
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## Model Experience
|
||||
|
||||
### External harness model
|
||||
|
||||
#### What the model sees
|
||||
|
||||
The connected harness's model sees `cua_get_api_reference`, the Agent's `cua_run_code` definition, `cua_reset`, and the server instructions from `tools/list` and `initialize`. The `cua` API reference the provider registered enters its context as the result of a `cua_get_api_reference` call, which the instructions request at the start of every conversation; `cua_run_code` results carry only program output and inspected screenshots. No DSH model request exists in this profile.
|
||||
|
||||
#### Token effect
|
||||
|
||||
The tool description carries the registration's execution rules, about 3,200 characters; a `cua_get_api_reference` result is the API reference, about 13,000 characters with the current macOS provider, about 3,300 tokens by the repository's four-character estimate, spent once per call. Screenshots are inline images at the provider's `screenshotTarget` size. Clients cap tool output; the documented Codex configuration raises the `cua_run_code` budget to 25,000 tokens. Clients also cap tool descriptions and server instructions: Claude Code 2.1.309 forwards the first 4,096 characters of either and appends `… [truncated]`; DSH's `dsh-mcp-client` forwards a 20,000-character description intact. The registration's description and the instructions, about 500 characters, fit that budget; the reference does not and travels as a tool result.
|
||||
|
||||
#### KV Cache effect
|
||||
|
||||
The tool catalog and instructions are stable for one installation. The reference text changes only with the installed CUA packages and enters a conversation as an ordinary tool result.
|
||||
|
||||
## Known Limitations and Deferred Work
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- macOS and native Windows Hosts have a provider. Other Hosts, WSL included, list `cua_get_api_reference` and `cua_reset`, which both name the missing provider; a `cua_run_code` call fails as `unknown tool`.
|
||||
- On Windows the [provider's limits](../cua-windows/README.md#known-limitations-and-deferred-work) apply through MCP: it does not launch applications, grants no `Always allow`, and an npm installation needs `helperPath`.
|
||||
- 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, and the workspace is its `workspace-write` root.
|
||||
- The `cua` API reference reaches a model only when it calls `cua_get_api_reference`. The server cannot observe a new conversation on an existing connection or a compacted context, so the instructions and the tool description carry that request; a client that withholds the tool leaves its model with the execution rules alone.
|
||||
- The server does not bound result text. A program that inspects a large value returns all of it, up to the program runtime's 64 MiB output limit, and only the client's own output limit protects its context.
|
||||
- The registration's description still carries the PTC sandbox-escalation guidance ("A sandbox escalation approves this complete program …"); a program that follows it is refused before execution and told that `DSH_PERMISSION_MODE` selects the sandbox.
|
||||
- A provider description longer than 4,096 characters reaches Claude Code 2.1.309 models cut; the projection does not shorten it.
|
||||
- Root tool calls are not Session events; the connected harness's transcript is the record of calls and results.
|
||||
- The patch lists the profile's dependency closure explicitly; a new service injection in the CUA or PTC packages leaves the provider row inactive, reported on stderr, and `cua_run_code` out of the listing until the patch adds the row.
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### Dev Note
|
||||
|
||||
<details>
|
||||
<summary>Working context for maintainers — click to expand</summary>
|
||||
|
||||
None.
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,189 @@
|
||||
---
|
||||
description: "通过 cua-mcp profile 以 stdio 向 Codex、Claude Code 等 MCP 客户端提供 Computer Use。"
|
||||
kind: "package-bundle"
|
||||
---
|
||||
|
||||
# @deepseek-ai/dsh-cua-mcp
|
||||
|
||||
[English](README.md) | 中文
|
||||
|
||||
## 概述
|
||||
|
||||
这个实验性组合包独立组成 `cua-mcp` profile,即 Computer Use 的 MCP stdio 服务器。每个 DSH 安装都自带它;只选本组合包的 profile manifest 就能让 `dsh --profile cua-mcp` 向一个 MCP 客户端提供 `cua_get_api_reference`、`cua_run_code` 与 `cua_reset`。该 profile 只由本组合包构成:不加载任何模型适配器、提示侧工具或遥测行。一个连接拥有一个 Agent,其程序在多次调用之间于内存中保留应用与窗口对象。应用与指针访问的授权可无人值守放行,或作为 elicitation 转发给客户端;模型归接入的 harness 所有。
|
||||
|
||||
## 目录
|
||||
|
||||
- [使用本包](#use-this-package)
|
||||
- [配置](#configuration)
|
||||
- [理解实现](#understand-the-implementation)
|
||||
- [进一步探索](#further-exploration)
|
||||
- [模型体验](#model-experience)
|
||||
- [已知限制与延后工作](#known-limitations-and-deferred-work)
|
||||
- [开发备注](#dev-note)
|
||||
|
||||
-----
|
||||
|
||||
<a id="use-this-package"></a>
|
||||
## 使用本包
|
||||
|
||||
### 启动服务器
|
||||
|
||||
组合包是 `dsh` 安装的运行时依赖,因此只选它这一层的 profile 直接从安装中加载它;不涉及 pnpm、registry 或网络。在 Harness home(`$DSH_HOME`,默认 `~/.dsh`)下创建一次 profile,之后 `dsh --profile cua-mcp` 就是 stdio 命令,源码检出在 `pnpm run build` 之后通过 `pnpm dsh` 运行它。不要把组合包加进已经组合了 `dsh-base` 的 profile(例如 `dsh plugin --profile cua-mcp add` 创建的那种):两套组合声明同样的行 id,Web 插件页也因此隐藏本组合包,而 Host 清单仍把它报告为可选组合包。
|
||||
|
||||
```sh
|
||||
mkdir -p "${DSH_HOME:-$HOME/.dsh}/profiles/cua-mcp"
|
||||
printf '%s\n' '{ "name": "dsh-profile-cua-mcp", "private": true, "dependencies": {}, "dsh": { "profile": { "bundles": ["@deepseek-ai/dsh-cua-mcp"] } } }' > "${DSH_HOME:-$HOME/.dsh}/profiles/cua-mcp/package.json"
|
||||
```
|
||||
|
||||
Python runtime wheel 自带同一份安装:在 harness 以 `DSH_HOME` 传入的 home 下写入同样的 manifest,然后把它的可执行程序用作 stdio 命令:
|
||||
|
||||
```python
|
||||
from deepseek_harness_runtime import resolve_bundled_launch_args
|
||||
|
||||
command = [*resolve_bundled_launch_args(), "--profile", "cua-mcp"] # the MCP stdio command
|
||||
```
|
||||
|
||||
### 接入客户端
|
||||
|
||||
`dsh --profile cua-mcp` 就是 stdio 命令,`--help` 打印它自己的帮助。客户端配置项以绝对路径指向安装的 `dsh` 可执行程序,传入 `--profile cua-mcp`,在服务器应使用非默认 Harness home 时设置 `DSH_HOME`,用 `DSH_CUA_CONSENT` 设置授权模式,并在程序应工作于默认工作区之外的目录时设置 `DSH_CUA_WORKSPACE`;源码检出在 `pnpm run build` 之后以 `node` 为命令、`<checkout>/apps/cli/lib/bin.js` 为首个参数。Codex 在 `~/.codex/config.toml` 中加入:
|
||||
|
||||
```toml
|
||||
[mcp_servers.dsh_cua]
|
||||
command = "/absolute/path/to/dsh"
|
||||
args = ["--profile", "cua-mcp"]
|
||||
env = { DSH_HOME = "/absolute/path/to/dsh-home", DSH_CUA_CONSENT = "elicit" }
|
||||
required = true
|
||||
startup_timeout_sec = 120
|
||||
tool_timeout_sec = 600
|
||||
enabled_tools = ["cua_get_api_reference", "cua_run_code", "cua_reset"]
|
||||
omit_tools_from = ["code_mode", "deferred"]
|
||||
|
||||
[mcp_servers.dsh_cua.tools.cua_run_code]
|
||||
output_token_limit = 25000
|
||||
```
|
||||
|
||||
`required = true` 让 Codex 在首个模型请求之前等待服务器就绪,并在服务器无法启动时结束会话;不设置时 Codex 只等待 `mcp_optional_startup_grace_ms`(默认一秒),首个请求可能不带这三个工具。`startup_timeout_sec = 120` 限定这段等待并留给首次 helper 准备,`tool_timeout_sec = 600` 对齐默认程序上限,`enabled_tools` 配合 `omit_tools_from` 让三个工具直接暴露而不进入工具搜索,`output_token_limit` 把 `cua_run_code` 的输出预算提高到 25,000 token。
|
||||
|
||||
`codex exec` 以审批策略 `never` 运行,此时 Codex 会拒绝 `cua_run_code`(本服务器唯一标注为 destructive 与 open-world 的工具),错误为 `MCP tool call requires approval, but approval policy is never`(在 codex-cli 0.153.2 上观察到)。因此无人值守运行要在 `cua_run_code` 表中加入 `approval_mode = "approve"`,并设置 `DSH_CUA_CONSENT = "allow"`。
|
||||
|
||||
Claude Code 以十分钟工具超时注册同一配置项:
|
||||
|
||||
```sh
|
||||
claude mcp add-json dsh_cua '{"type":"stdio","command":"/absolute/path/to/dsh","args":["--profile","cua-mcp"],"env":{"DSH_HOME":"/absolute/path/to/dsh-home","DSH_CUA_CONSENT":"elicit"},"timeout":600000,"alwaysLoad":true}'
|
||||
```
|
||||
|
||||
其他客户端在 `mcpServers` 下使用同样的 `command`、`args` 与 `env`。Claude Code、`dsh-mcp-client` 与 Codex 三条配置都经真实 macOS 桌面验证,其中 Codex 是在 codex-cli 0.153.2 与 0.166.0-alpha.5.1 上通过 `codex exec` 并以 `DSH_CUA_CONSENT=allow` 验证的;没有客户端经本 profile 操作过 Windows 桌面。Codex 的交互式审批提示及其 elicitation 转发未在此实测;按 Codex 配置参考,截至 2026-11-11,Codex 只有在 `approval_policy.granular.mcp_elicitations = true` 时才转发 elicitation。DSH 自己的 `dsh-mcp-client` 未声明 elicitation 能力,Claude Code 2.1 的 print 模式会拒绝 elicitation,因此经这两类客户端的无人值守运行需要 `DSH_CUA_CONSENT=allow`。
|
||||
|
||||
按名称放行工具的客户端必须放行全部三个:缺少 `cua_get_api_reference` 时,它的模型拿不到 `cua` API 参考。服务器使用的 Harness home 不要与采用未压缩 Session 日志的 profile 共用:本 profile 在 `sessions` 下写入 zstd 压缩的日志,设置了 `compression: none` 的 profile(例如 `sdk-minimal`)在含有这些日志的目录上查询 Session 会失败。
|
||||
|
||||
在 macOS 上,profile 首次启动时准备已签名的 Computer Use helper,并需要为其授予辅助功能与屏幕录制权限;[macOS 提供方](../cua-macos/README.zh.md)负责这部分设置。本 profile 没有权限页面,因此要在「系统设置 → 隐私与安全性」中添加 helper 应用来授予这两项权限:源码检出在 macOS 提供方包的 `native/.build/prepared/<arch>/<build>/` 目录下准备 `DSH Computer Use Dev.app`,其中 `current.json` 记录当前选中的构建;已安装的包附带 `DSH Computer Use.app`。两项权限都授予之前,`await cua.getCapabilities()` 会报告缺失的标志,应用操作会失败;桌面处于锁定状态时这些操作以 `SESSION_LOCKED` 失败。
|
||||
|
||||
在原生 Windows 上,profile 挂载 [Windows 提供方](../cua-windows/README.zh.md),helper 的准备由它负责:源码检出用 PATH 上的 .NET 10 SDK 构建 helper;npm 安装不附带 helper。此时要在 profile 的 `cordis.patch.yml` 中用 `cua-mcp-provider-windows` 行的 `helperPath` 指明 helper:即 `dsh-cua-windows.exe` 的绝对路径,x64 取自解压后的独立 ZIP,ARM64 取自对应架构的构建。patch 会替换该行的整个 config,因此要重述组合包的字段:
|
||||
|
||||
```yaml
|
||||
- id: cua-mcp-provider-windows
|
||||
config:
|
||||
agentPreset: ptc
|
||||
screenshotTarget:
|
||||
longEdge: 2048
|
||||
maxBytes: 2097152
|
||||
helperPath: 'C:\absolute\path\to\dsh-cua-windows.exe'
|
||||
```
|
||||
|
||||
该提供方不启动应用,也不提供 `Always allow` 授权:程序选中应用之前要先打开它,在 `elicit` 模式下每个连接都会重新询问授权。profile 不在 WSL 下挂载它。
|
||||
|
||||
在其他 Host 上 profile 没有提供方也能启动:列表有 `cua_get_api_reference` 与 `cua_reset`,二者都返回指出缺少提供方的错误,调用 `cua_run_code` 以 `unknown tool` 失败。提供方行无法激活时(例如 Windows 行缺少 helper)列表相同,启动器会在 stderr 上指出失败原因。
|
||||
|
||||
### 你会得到什么
|
||||
|
||||
`cua_get_api_reference` 返回 `cua` API 参考:提供方为连接的 Agent 注册的指引,包含每个方法的签名与操作规则,也就是 DSH 模型在系统提示中收到的那段文本。它不带参数,不运行程序,也不触碰桌面和程序环境,因此程序运行期间同样可以应答。服务器说明要求模型在每次对话开始时调用它;它的描述要求在参考已不在模型上下文中、或程序因未知的 `cua` 方法失败时再调用一次。
|
||||
|
||||
`cua_run_code` 就是该 Agent 的 DSH 注册项以 MCP 工具的形式提供:每次 `tools/list` 都从工具注册表读取它的名称、描述和参数 schema,因此提供方的定义是唯一来源,`description` 按该定义必填,`timeoutMs` 限制单个程序。投影省略注册项中的沙箱提权字段 `sandbox_permissions` 与 `justification`,指定它们的调用在执行前被拒绝;其余参数原样交给 DSH 工具执行器,由它校验参数并回答未知名称,因此非法调用返回 DSH 的错误结果。程序作为 TypeScript REPL 语句在提供方保留的 Node 环境中对全局 `cua` 对象运行。结果携带程序传给 `inspect(...)` 的内容:文本成为文本块,每张被 inspect 的截图成为内联图片,且图片正是程序观察到的那一版,因此文本中的像素坐标与图片一致;没有 inspect 任何值的程序返回一条完成提示。执行规则在工具描述里。程序在工作区中启动,同一连接的程序按到达顺序逐个运行;取消调用会取消其程序。失败的调用返回 DSH 的失败信息并设置 `isError`,不带 DSH 的 `Error:` 前缀。
|
||||
|
||||
`cua_reset` 只丢弃程序环境。程序进程结束,因此其中的变量、导入以及应用和窗口对象都不复存在;仍在运行的 `cua_run_code` 程序被取消,reset 在该程序返回之后才返回。连接的 Agent 连同其本机连接和授权决定都保留:本会话已放行的应用不会再次询问,已拒绝的应用保持拒绝,已保存的授权和 helper 的系统权限不受影响。下一个程序在新进程中启动,拥有新的 `cua` 对象,并通过 `cua.getApp` 重新选择应用;reset 期间到达的程序在它之后运行。进程清理失败的 reset 返回错误,此后程序会失败,直到后续的 `cua_reset` 成功。在环境不可用之后,或不希望保留的状态带入下一个任务时使用它。
|
||||
|
||||
连接的 Agent 在 stdio 传输打开之前创建于工作区中,因此首次列表就带有它的注册项;客户端关闭 stdin 时销毁,进程随之退出。工作区是 `DSH_CUA_WORKSPACE`,变量未设置时为 Harness home 下的 `cua-mcp/workspace`;profile 会创建它,程序在其中启动,默认的 `workspace-write` 沙箱允许程序写入的也是这个目录,与客户端从哪个目录启动服务器无关。应用授权按该 Agent 遵循 [CUA 授权规则](../cua/README.zh.md):`DSH_CUA_CONSENT=allow` 在无人值守下为本会话放行每个请求;默认的 `elicit` 把请求作为表单 elicitation 转发给客户端,答案即 CUA 的选项标签;被拒绝的表单为本会话记录一次拒绝,不支持 elicitation 的客户端会收到指明 `allow` 模式的错误。
|
||||
|
||||
-----
|
||||
|
||||
<a id="configuration"></a>
|
||||
## 配置
|
||||
|
||||
在 profile 的 `cordis.patch.yml` 中配置 `cua-mcp` 行;组合包 patch 把 `DSH_CUA_CONSENT` 与 `DSH_CUA_WORKSPACE` 映射到它。
|
||||
|
||||
| 字段 | 默认值 | 含义 |
|
||||
|---|---|---|
|
||||
| `consent` | `elicit` | `allow` 在无人值守下为本会话放行应用与指针授权;`elicit` 把每个请求转发给 MCP 客户端。 |
|
||||
| `workspace` | Harness home 下的 `cua-mcp/workspace` | 连接的 Agent 工作所在的绝对目录。程序在其中启动,它也是程序的 `workspace-write` 根。启动时在目录不存在时创建它;路径为相对路径或目录无法创建时,在 stderr 报告并以退出码 1 结束。 |
|
||||
|
||||
patch 还以 `screenshotTarget: { longEdge: 2048, maxBytes: 2097152 }` 挂载该 Host 的原生提供方(macOS 上是 `cua-mcp-provider` 行,原生 Windows 上是 `cua-mcp-provider-windows` 行),因为这里没有模型路由来选择请求图片;并以 `agentPreset: ptc` 搭配空的 `cua-mcp` preset,使连接的 Agent 只获得 `cua_run_code` 而没有其他面向模型的行。可在 profile patch 中按 id 覆盖这些行;覆盖会替换该行的整个 config,因此要重述需要保留的字段。`sandbox-policy` 行的 `workspaceRoot` 与 `workspace` 解析为同一目录;程序的根是其 Agent 的工作目录,因此该字段只作用于没有 Session 的调用。
|
||||
|
||||
-----
|
||||
|
||||
<a id="understand-the-implementation"></a>
|
||||
## 理解实现
|
||||
|
||||
<details>
|
||||
<summary>实现细节 — 点击展开</summary>
|
||||
|
||||
[patch](cordis.patch.yml) 在空根上组成整个 profile:带 JSONL 持久化与投影的会话、附件、保存应用授权的存储、程序进程所依赖的子进程、沙箱、审批与文件系统 seam、带原生执行器的工具、系统提示、用户提问、不挂适配器的 llm hub、带 agent-loop 工厂的 Agent 注册表、带空默认 preset 的 preset 注册表、`computer-use` 注册表、每种 Host 一行的原生提供方(Darwin 上是 macOS,原生 Windows 上是 Windows),以及本前端。只列出本组合包的 profile manifest 选中这套组合;启动器不经模板直接从安装中加载它。前端用 `parseCmdline` 解析调用,把 stdin EOF 绑定到启动器的有界关闭,并在启动器提交就绪后创建工作区、把官方 MCP 服务器连接到 stdio 传输。`cua-mcp` 不是启动必需条目:行无法激活时启动器在 stderr 上报告,而不是停止 profile。
|
||||
|
||||
[`server.ts`](src/server.ts) 通过协议服务器的低层 `tools/list` 与 `tools/call` handler 提供三个工具:列表把该 Agent 的 `cua_run_code` 注册项按协议的工具类型校验后投影出来,排在该文件定义的两个工具之间。连接的 Agent 挂载注册表的默认 preset,并把工作区记录为自己的工作目录,沙箱策略据此解析其程序的 `workspace-write` 根。`cua_get_api_reference` 通过 `ctx.systemPrompt.assemble` 读取提供方为该 Agent 注册的提示段,不保存任何状态。`cua_run_code` 调用在 `ctx.agents.withInitiator` 内带着 Agent 和请求 signal、不经模型步骤地通过 `ctx.tools.execute` 运行,因此 Session 日志只有嵌套的 `tool/ptc-dispatch` 事件而没有根 `tool/call`;[`projection.ts`](src/projection.ts) 渲染结果及其延后的截图上下文,并通过 `ctx.cuaPrograms.screenshotRequestTarget` 读取每张图片。`cua_reset` 用 `agent.cancel` 取消该 Agent 正在运行的程序,调用 `ctx.cuaPrograms.release`,由提供方的程序运行时释放该 state owner 的环境,并在 Agent 空闲后返回;同一时刻只进行一次释放,程序调用会等待它,因为前一个进程尚在退出时运行时会拒绝程序。[`consent.ts`](src/consent.ts) 是该 Agent 的 `user-questions/request` 应答者。`cua_run_code` 调用作为该 Agent 的维护活动运行,因此 Agent 在调用进行中被销毁时会取消该调用,等它及其嵌套调用结算之后才释放本机连接并关闭 Session。
|
||||
|
||||
</details>
|
||||
|
||||
-----
|
||||
|
||||
<a id="further-exploration"></a>
|
||||
## 进一步探索
|
||||
|
||||
- [共享 CUA 包](../cua/README.zh.md) — 对象 API、授权规则与 `cua_run_code`。
|
||||
- [macOS 提供方](../cua-macos/README.zh.md) — helper 准备、权限与平台指引。
|
||||
- [Windows 提供方](../cua-windows/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。
|
||||
|
||||
-----
|
||||
|
||||
<a id="model-experience"></a>
|
||||
## 模型体验
|
||||
|
||||
### 外部 harness 的模型
|
||||
|
||||
#### 模型看到什么
|
||||
|
||||
接入 harness 的模型通过 `tools/list` 和 `initialize` 看到 `cua_get_api_reference`、该 Agent 的 `cua_run_code` 定义、`cua_reset` 与服务器说明。提供方注册的 `cua` API 参考作为 `cua_get_api_reference` 调用的结果进入其上下文,服务器说明要求每次对话开始时调用它;`cua_run_code` 的结果只携带程序输出与被 inspect 的截图。该 profile 中不存在 DSH 模型请求。
|
||||
|
||||
#### Token 影响
|
||||
|
||||
工具描述携带注册项的执行规则,约 3,200 个字符;一次 `cua_get_api_reference` 的结果就是 API 参考,使用当前 macOS 提供方时约 13,000 个字符,按仓库四字符/token 估算约 3,300 token,每次调用支付一次。截图是提供方 `screenshotTarget` 尺寸的内联图片。客户端会限制工具输出;文档给出的 Codex 配置把 `cua_run_code` 的预算提高到 25,000 token。客户端同样限制工具描述和服务器说明:Claude Code 2.1.309 对二者都只转发前 4,096 个字符并追加 `… [truncated]`;DSH 的 `dsh-mcp-client` 原样转发 20,000 个字符的描述。注册项的描述和约 500 个字符的服务器说明都在该预算之内;参考超出预算,因此作为工具结果传递。
|
||||
|
||||
#### KV Cache 影响
|
||||
|
||||
工具目录和说明对同一安装保持稳定。参考文本只随已安装的 CUA 包变化,并作为普通的工具结果进入对话。
|
||||
|
||||
## 已知限制与延后工作
|
||||
|
||||
<a id="known-limitations-and-deferred-work"></a>
|
||||
|
||||
- macOS 与原生 Windows Host 有提供方。其他 Host(包括 WSL)列出 `cua_get_api_reference` 与 `cua_reset`,二者都指出缺少提供方;调用 `cua_run_code` 以 `unknown tool` 失败。
|
||||
- 在 Windows 上,[提供方的限制](../cua-windows/README.zh.md#known-limitations-and-deferred-work)经 MCP 同样适用:它不启动应用,不提供 `Always allow` 授权,npm 安装需要配置 `helperPath`。
|
||||
- Elicitation 使用 2025 版 MCP 请求模型;协商到 2026-07-28 修订版的客户端在授权请求时收到错误,应改用 `DSH_CUA_CONSENT=allow`。
|
||||
- 不暴露程序沙箱提权和原始 `cua` 工具;`DSH_PERMISSION_MODE` 选择程序进程启动时的文件沙箱,工作区是它的 `workspace-write` 根。
|
||||
- `cua` API 参考只有在模型调用 `cua_get_api_reference` 时才到达模型。服务器观察不到既有连接上的新对话,也观察不到上下文压缩,因此由服务器说明和工具描述提出这一要求;不放行该工具的客户端,其模型只有执行规则可用。
|
||||
- 服务器不限制结果文本的大小。程序 inspect 一个很大的值时会原样返回全部内容,上限是程序运行时 64 MiB 的输出限制,只有客户端自己的输出上限能保护其上下文。
|
||||
- 注册项的描述仍带有 PTC 的沙箱提权说明("A sandbox escalation approves this complete program …");按它请求提权的程序会在执行前被拒绝,并被告知 `DSH_PERMISSION_MODE` 决定沙箱。
|
||||
- 提供方描述超过 4,096 个字符时,Claude Code 2.1.309 的模型只看到被截断的部分;投影不会缩短它。
|
||||
- 根工具调用不是 Session 事件;接入 harness 的 transcript 才是调用与结果的记录。
|
||||
- patch 显式列出该 profile 的依赖闭包;CUA 或 PTC 包新增服务注入时,提供方行无法激活并在 stderr 上报告,列表里没有 `cua_run_code`,直到 patch 补上该行。
|
||||
|
||||
<a id="dev-note"></a>
|
||||
### 开发备注
|
||||
|
||||
<details>
|
||||
<summary>维护者工作上下文 — 点击展开</summary>
|
||||
|
||||
无。
|
||||
|
||||
</details>
|
||||
@@ -0,0 +1,145 @@
|
||||
# The Computer Use MCP application: a standalone profile composed from this one
|
||||
# insert over the empty profile root. No model turn ever runs here, so the
|
||||
# composition carries no model adapter, prompt-side tools, telemetry, or
|
||||
# session-management rows; stdout belongs exclusively to MCP JSON-RPC, and one
|
||||
# stdio connection owns one Agent whose cua_run_code programs retain state until
|
||||
# the client disconnects or calls cua_reset.
|
||||
#
|
||||
# Row ids match dsh-base where the plugin is the same, so a profile or home
|
||||
# cordis.patch.yml written for a base-backed profile addresses them unchanged.
|
||||
|
||||
- insert:
|
||||
# Sessions: the connection Agent's Session log (nested tool/ptc-dispatch events
|
||||
# and screenshots) and the projections that approval, sandbox policy, and the
|
||||
# Agent registry derive from it.
|
||||
- id: session
|
||||
name: '@deepseek-ai/dsh-session'
|
||||
|
||||
- id: session-persistence-jsonl
|
||||
name: '@deepseek-ai/dsh-session-persistence-jsonl'
|
||||
config:
|
||||
root: !!js dshHomePath('sessions')
|
||||
|
||||
- id: session-projection
|
||||
name: '@deepseek-ai/dsh-session-projection'
|
||||
|
||||
- id: attachment-local
|
||||
name: '@deepseek-ai/dsh-attachment-local'
|
||||
|
||||
- id: working-directory
|
||||
name: '@deepseek-ai/dsh-working-directory'
|
||||
|
||||
# Durable KV storage for the provider's application grants.
|
||||
- id: storage
|
||||
name: '@deepseek-ai/dsh-storage'
|
||||
|
||||
- id: storage-json
|
||||
name: '@deepseek-ai/dsh-storage-json'
|
||||
config:
|
||||
root: !!js dshHomePath('storages')
|
||||
|
||||
- id: storage-domain
|
||||
name: '@deepseek-ai/dsh-storage-domain'
|
||||
config:
|
||||
backend: json
|
||||
|
||||
# Program processes: the dedicated CUA runtime launches under the same
|
||||
# file-effect boundary as every shipped CLI mode. A program's workspace-write
|
||||
# root is its Agent's working directory, which the cua-mcp row sets to the
|
||||
# workspace below; this row's root covers calls without a Session.
|
||||
- id: subprocess
|
||||
name: '@deepseek-ai/dsh-subprocess-local'
|
||||
|
||||
- id: sandbox
|
||||
name: '@deepseek-ai/dsh-sandbox-local'
|
||||
|
||||
- id: sandbox-policy
|
||||
name: '@deepseek-ai/dsh-sandbox-policy'
|
||||
config:
|
||||
mode: !!js process.env.DSH_PERMISSION_MODE ?? 'workspace-write'
|
||||
workspaceRoot: !!js process.env.DSH_CUA_WORKSPACE ?? dshHomePath('cua-mcp', 'workspace')
|
||||
|
||||
- id: approval
|
||||
name: '@deepseek-ai/dsh-user-approval'
|
||||
config:
|
||||
policy: !!js "(process.env.DSH_PERMISSION_MODE ?? 'workspace-write') === 'danger-full-access' ? 'never' : 'ask'"
|
||||
|
||||
- id: fs-sandbox
|
||||
name: '@deepseek-ai/dsh-fs-sandbox'
|
||||
|
||||
# Tool execution and the Agent that owns the connection.
|
||||
- id: tools
|
||||
name: '@deepseek-ai/dsh-tools'
|
||||
|
||||
- id: tool-executor-native
|
||||
name: '@deepseek-ai/dsh-tool-executor-native'
|
||||
|
||||
- id: system-prompt
|
||||
name: '@deepseek-ai/dsh-system-prompt'
|
||||
config:
|
||||
personaPrefix: ''
|
||||
|
||||
- id: user-questions
|
||||
name: '@deepseek-ai/dsh-user-questions'
|
||||
|
||||
# The Agent registry creates the connection Agent through the agent-loop
|
||||
# factory; no model adapter is mounted on the llm hub, so no turn can run.
|
||||
- id: llm
|
||||
name: '@deepseek-ai/dsh-llm'
|
||||
|
||||
- id: agent
|
||||
name: '@deepseek-ai/dsh-agent'
|
||||
|
||||
- id: agent-loop
|
||||
name: '@deepseek-ai/dsh-agent-loop'
|
||||
config:
|
||||
agents: []
|
||||
|
||||
# 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'
|
||||
|
||||
# One native provider per Host: macOS, and native Windows (not WSL). Both
|
||||
# are optional dependencies that an installation on another platform can
|
||||
# lack, so each row is disabled off its own Host.
|
||||
# Screenshots target a fixed request image because no model route exists here.
|
||||
- id: cua-mcp-provider
|
||||
name: '@deepseek-ai/dsh-cua-macos'
|
||||
disabled: !!js process.platform !== 'darwin'
|
||||
config:
|
||||
agentPreset: ptc
|
||||
screenshotTarget:
|
||||
longEdge: 2048
|
||||
maxBytes: 2097152
|
||||
|
||||
- id: cua-mcp-provider-windows
|
||||
name: '@deepseek-ai/dsh-cua-windows'
|
||||
disabled: !!js process.platform !== 'win32'
|
||||
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.
|
||||
# DSH_CUA_WORKSPACE is the directory programs start in and may write under
|
||||
# workspace-write; the default stays inside the Harness home whatever
|
||||
# directory the client started the server in.
|
||||
- id: cua-mcp
|
||||
name: '@deepseek-ai/dsh-cua-mcp'
|
||||
config:
|
||||
consent: !!js process.env.DSH_CUA_CONSENT ?? 'elicit'
|
||||
workspace: !!js process.env.DSH_CUA_WORKSPACE ?? dshHomePath('cua-mcp', 'workspace')
|
||||
@@ -0,0 +1,42 @@
|
||||
<svg width="36" height="36" viewBox="0 0 36 36" fill="none" xmlns="http://www.w3.org/2000/svg">
|
||||
<!--
|
||||
Computer Use MCP server plugin icon.
|
||||
Adapted from Lucide "mouse-pointer-click" (https://lucide.dev/icons/mouse-pointer-click) with a
|
||||
connection bar below the pointer. Changes: solid-filled pointer, project palette, 36x36 canvas.
|
||||
|
||||
ISC License
|
||||
Copyright (c) 2026 Lucide Icons and Contributors
|
||||
https://github.com/lucide-icons/lucide/blob/main/LICENSE
|
||||
|
||||
Permission to use, copy, modify, and/or distribute this software for any
|
||||
purpose with or without fee is hereby granted, provided that the above
|
||||
copyright notice and this permission notice appear in all copies.
|
||||
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
|
||||
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
|
||||
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
|
||||
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
|
||||
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
|
||||
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
|
||||
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
|
||||
-->
|
||||
<g transform="translate(5.5 3) scale(1.05)">
|
||||
<path d="M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z" fill="url(#cua-mcp-pointer)" stroke="url(#cua-mcp-pointer)" stroke-width="2" stroke-linejoin="round" />
|
||||
<path d="M14 4.1 12 6" stroke="#51CFDB" stroke-width="2" stroke-linecap="round" />
|
||||
<path d="m5.1 8-2.9-.8" stroke="#51CFDB" stroke-width="2" stroke-linecap="round" />
|
||||
<path d="m6 12-1.9 2" stroke="#51CFDB" stroke-width="2" stroke-linecap="round" />
|
||||
<path d="M7.2 2.2 8 5.1" stroke="#51CFDB" stroke-width="2" stroke-linecap="round" />
|
||||
</g>
|
||||
<rect x="6" y="28" width="24" height="4" rx="2" fill="url(#cua-mcp-link)" />
|
||||
<circle cx="10" cy="30" r="1.2" fill="#FFFFFF" />
|
||||
<circle cx="26" cy="30" r="1.2" fill="#FFFFFF" />
|
||||
<defs>
|
||||
<linearGradient id="cua-mcp-pointer" x1="9" y1="9" x2="21" y2="21" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#86B8F5" />
|
||||
<stop offset="1" stop-color="#5269E1" />
|
||||
</linearGradient>
|
||||
<linearGradient id="cua-mcp-link" x1="6" y1="30" x2="30" y2="30" gradientUnits="userSpaceOnUse">
|
||||
<stop stop-color="#5269E1" />
|
||||
<stop offset="1" stop-color="#51CFDB" />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 2.4 KiB |
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Computer Use MCP サーバー",
|
||||
"description": "cua-mcp プロファイルから Codex、Claude Code などの MCP クライアントに Computer Use を提供します。cua_run_code はデスクトップアプリに対して永続的なプログラムを実行し、cua_reset はそれをクリアします。"
|
||||
}
|
||||
}
|
||||
@@ -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."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "MCP-сервер управления компьютером",
|
||||
"description": "Предоставляет Computer Use клиентам MCP, включая Codex и Claude Code, из профиля cua-mcp: cua_run_code выполняет постоянные программы для настольных приложений, а cua_reset очищает их."
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"meta": {
|
||||
"title": "Computer Use MCP 服务器",
|
||||
"description": "通过 cua-mcp profile 向 Codex、Claude Code 等 MCP 客户端提供 Computer Use:cua_run_code 对桌面应用运行持久程序,cua_reset 清空程序环境。"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
{
|
||||
"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.2",
|
||||
"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-attachment": "workspace:*",
|
||||
"@deepseek-ai/dsh-app-boot": "workspace:*"
|
||||
},
|
||||
"dependencies": {
|
||||
"@deepseek-ai/dsh-agent": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-loop": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-preset": "workspace:*",
|
||||
"@deepseek-ai/dsh-agent-preset-registry": "workspace:*",
|
||||
"@deepseek-ai/dsh-attachment-local": "workspace:*",
|
||||
"@deepseek-ai/dsh-brand": "workspace:*",
|
||||
"@deepseek-ai/dsh-cmdline": "workspace:*",
|
||||
"@deepseek-ai/dsh-computer-use": "workspace:*",
|
||||
"@deepseek-ai/dsh-cua": "workspace:*",
|
||||
"@deepseek-ai/dsh-fs-sandbox": "workspace:*",
|
||||
"@deepseek-ai/dsh-llm": "workspace:*",
|
||||
"@deepseek-ai/dsh-sandbox-local": "workspace:*",
|
||||
"@deepseek-ai/dsh-sandbox-policy": "workspace:*",
|
||||
"@deepseek-ai/dsh-session": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-persistence-jsonl": "workspace:*",
|
||||
"@deepseek-ai/dsh-session-projection": "workspace:*",
|
||||
"@deepseek-ai/dsh-storage": "workspace:*",
|
||||
"@deepseek-ai/dsh-storage-domain": "workspace:*",
|
||||
"@deepseek-ai/dsh-storage-json": "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-user-approval": "workspace:*",
|
||||
"@deepseek-ai/dsh-user-questions": "workspace:*",
|
||||
"@deepseek-ai/dsh-working-directory": "workspace:*",
|
||||
"@deepseek-ai/schemastery": "workspace:~",
|
||||
"@modelcontextprotocol/server": "2.2.0",
|
||||
"commander": "^15.0.0"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@deepseek-ai/dsh-cua-macos": "workspace:*",
|
||||
"@deepseek-ai/dsh-cua-windows": "workspace:*"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@deepseek-ai/cordis": "workspace:~",
|
||||
"@deepseek-ai/cordis-plugin-include": "workspace:~",
|
||||
"@deepseek-ai/cordis-plugin-loader": "workspace:~",
|
||||
"@deepseek-ai/dsh-app-boot": "workspace:*",
|
||||
"@deepseek-ai/dsh-attachment": "workspace:*",
|
||||
"@deepseek-ai/dsh-fs-local": "workspace:*",
|
||||
"@deepseek-ai/dsh-ptc-runtime-node": "workspace:*",
|
||||
"@modelcontextprotocol/client": "2.2.0",
|
||||
"js-yaml": "^4.3.2"
|
||||
}
|
||||
}
|
||||
@@ -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<ElicitResult>
|
||||
}
|
||||
|
||||
/** 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<AskUserQuestionAnswer['answers'][number]> {
|
||||
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<AskUserQuestionAnswer>,
|
||||
) => Promise<AskUserQuestionAnswer>
|
||||
|
||||
/**
|
||||
* 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 }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
/**
|
||||
* The Computer Use MCP stdio application: the standalone cua-mcp profile's frontend, serving the `cua` API
|
||||
* reference, the Agent's `cua_run_code` registration, and `cua_reset` to an external MCP client. Help exits
|
||||
* without claiming stdio; a served connection owns one Agent, created in the configured workspace before the
|
||||
* transport opens, until the client closes stdin.
|
||||
* @module @deepseek-ai/dsh-cua-mcp
|
||||
*/
|
||||
import { mkdir } from 'node:fs/promises'
|
||||
import { isAbsolute } from 'node:path'
|
||||
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 } from 'commander'
|
||||
import type { ConsentMode } from './consent.ts'
|
||||
import { createCuaMcpServer, type CuaMcpServer } 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
|
||||
/**
|
||||
* Absolute directory the connection's Agent works in: its programs start there, and it is their
|
||||
* `workspace-write` root. Startup creates it when missing; a relative path or a directory that cannot be
|
||||
* created is reported on stderr and ends the process with exit code 1.
|
||||
*/
|
||||
workspace: string
|
||||
}
|
||||
|
||||
/** Validate the consent mode and require a workspace; the bundle patch maps `DSH_CUA_CONSENT` and `DSH_CUA_WORKSPACE` onto them. */
|
||||
export const Config: Schema<Partial<Config>, Config> = Schema.object({
|
||||
consent: Schema.union([Schema.const('allow'), Schema.const('elicit')]).default('elicit'),
|
||||
workspace: Schema.string().required(),
|
||||
})
|
||||
|
||||
/**
|
||||
* Create the directory a served connection works in.
|
||||
* @param workspace - Configured workspace path.
|
||||
* @returns After the directory exists.
|
||||
* @throws Error naming the configured path when it is relative or the directory cannot be created.
|
||||
*/
|
||||
async function prepareWorkspace(workspace: string): Promise<void> {
|
||||
if (!isAbsolute(workspace)) {
|
||||
throw new Error(`the workspace ${JSON.stringify(workspace)} is not an absolute directory path; set DSH_CUA_WORKSPACE to an absolute path`)
|
||||
}
|
||||
await mkdir(workspace, { recursive: true }).catch((error: unknown) => {
|
||||
throw new Error(`the workspace directory ${JSON.stringify(workspace)} cannot be created (${String(error)}); set DSH_CUA_WORKSPACE to a writable location`, { cause: error })
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept the profile invocation and, once the launcher commits readiness, create the workspace and serve MCP over
|
||||
* stdio; help exits before anything starts. A startup failure, including a relative workspace path or a workspace
|
||||
* directory that cannot be created, is reported on stderr and ends the process with exit code 1. 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 and workspace directory.
|
||||
* @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.')
|
||||
.addHelpText('after', `
|
||||
Examples:
|
||||
${commandName} serve one MCP client until it closes stdin
|
||||
DSH_CUA_CONSENT=allow ${commandName} grant application access without a human
|
||||
DSH_CUA_WORKSPACE=/work ${commandName} start programs in /work and let them write there
|
||||
`)
|
||||
let accepted: true | undefined
|
||||
program.action(() => { accepted = true })
|
||||
parseCmdline(ctx, program)
|
||||
if (accepted === undefined) return
|
||||
exitOnStdinEnd(ctx, 'cua-mcp: stdin')
|
||||
ctx.effect(() => {
|
||||
const lifetime = new AbortController()
|
||||
let adapter: Promise<CuaMcpServer> | undefined
|
||||
let opening: Promise<void> | undefined
|
||||
const stopReady = ready.onReady(() => {
|
||||
// The workspace exists, and then the Agent with the provider's tools registered for it, before the client can
|
||||
// list or call anything.
|
||||
adapter = prepareWorkspace(config.workspace)
|
||||
.then(() => createCuaMcpServer(ctx, { consent: config.consent, cwd: config.workspace, signal: lifetime.signal }))
|
||||
opening = adapter.then(created => created.server.connect(new StdioServerTransport()))
|
||||
void opening.catch((error: unknown) => {
|
||||
if (lifetime.signal.aborted) return
|
||||
// The profile mounts no log sink, and stdout belongs to the protocol: stderr is the only place a client or its user sees this.
|
||||
internals.stderr.write(`dsh: MCP startup failed: ${error instanceof Error ? error.message : String(error)}\n`)
|
||||
exit(1)
|
||||
})
|
||||
})
|
||||
return async () => {
|
||||
stopReady()
|
||||
lifetime.abort()
|
||||
await opening?.catch(() => undefined)
|
||||
const created = await adapter?.catch(() => undefined)
|
||||
await created?.dispose()
|
||||
}
|
||||
}, 'cua-mcp: server')
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/** 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<AttachmentStore, 'readImage' | 'readImageRequest'>
|
||||
/** Fixed request target of a screenshot, or undefined to deliver the stored normalized image. */
|
||||
readonly target: (image: ImageAttachmentRef) => ImageRequestTarget | undefined
|
||||
}
|
||||
|
||||
/** One projected text block. */
|
||||
function text(value: string): CallToolResult['content'][number] {
|
||||
return { type: 'text', text: value }
|
||||
}
|
||||
|
||||
/**
|
||||
* Project a settled `cua_run_code` outcome onto an MCP call result.
|
||||
* Result text keeps the model-facing rendering, except that a failure's message drops DSH's `Error: ` prefix because
|
||||
* `isError` already marks it. Images the program inspected, and any image a nested call deferred, follow in
|
||||
* emission 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.
|
||||
* @returns The MCP result; `isError` mirrors the DSH outcome.
|
||||
*/
|
||||
export async function projectToolResult(
|
||||
result: ToolExecutionResult, deferred: readonly UserMessage[], delivery: ScreenshotDelivery, signal: AbortSignal,
|
||||
): Promise<CallToolResult> {
|
||||
const content: CallToolResult['content'] = []
|
||||
const failure = result.isError ? result.error.message : undefined
|
||||
const blocks: ContentBlock[] = [...result.content, ...deferred.flatMap(message => message.content)]
|
||||
for (const block of blocks) {
|
||||
switch (block.type) {
|
||||
case 'text':
|
||||
// A client that renders isError results adds its own error marker, which DSH's rendering of the message would repeat.
|
||||
content.push(text(failure !== undefined && block.text === `Error: ${failure}` ? failure : 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 }
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
/** 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 } from '@deepseek-ai/dsh-agent'
|
||||
import type {} from '@deepseek-ai/dsh-agent-preset-registry'
|
||||
import type {} from '@deepseek-ai/dsh-attachment'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type {} from '@deepseek-ai/dsh-cua'
|
||||
import { CUA_PROMPT_SECTION_NAME } from '@deepseek-ai/dsh-cua/guidance'
|
||||
import type { ToolCallId } from '@deepseek-ai/dsh-llm'
|
||||
import type { SessionId } from '@deepseek-ai/dsh-session'
|
||||
import type {} from '@deepseek-ai/dsh-system-prompt'
|
||||
import type { ToolDefinition } from '@deepseek-ai/dsh-tools'
|
||||
import { Server, specTypeSchemas, type CallToolResult, type Tool } from '@modelcontextprotocol/server'
|
||||
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, the Agent it serves, and the disposer that releases both. */
|
||||
export interface CuaMcpServer {
|
||||
/** Low-level protocol server, not yet connected to a transport. */
|
||||
// oxlint-disable-next-line typescript/no-deprecated -- the SDK keeps this class for dynamic tool lists, see createCuaMcpServer.
|
||||
readonly server: Server
|
||||
/** The connection's Agent: owner of the program environment, native connection, and session grants. */
|
||||
readonly agent: Agent
|
||||
/**
|
||||
* Close the protocol connection, let a reset in progress and 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<void>
|
||||
}
|
||||
|
||||
/** MCP server name clients address; external tool names become `mcp__dsh_cua__cua_run_code` in Claude Code. */
|
||||
const MCP_SERVER_NAME = 'dsh_cua'
|
||||
|
||||
/** The DSH tool whose registration for the connection's Agent is served as the MCP tool of the same name. */
|
||||
const PROGRAM_TOOL = 'cua_run_code'
|
||||
|
||||
/**
|
||||
* Registration fields a program may not use through MCP: a sandbox escalation needs an approval answerer this
|
||||
* profile does not have, so the projection omits them and a call naming them is refused before execution.
|
||||
*/
|
||||
const ESCALATION_FIELDS = ['sandbox_permissions', 'justification'] as const
|
||||
|
||||
function isEscalationField(field: string): field is typeof ESCALATION_FIELDS[number] {
|
||||
return (ESCALATION_FIELDS as readonly string[]).includes(field)
|
||||
}
|
||||
|
||||
/** MCP presentation of the program tool; its name, description, and schema come from the registration. */
|
||||
const PROGRAM_TOOL_PRESENTATION = {
|
||||
title: 'Computer use program',
|
||||
annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
|
||||
} as const
|
||||
|
||||
/**
|
||||
* The reference tool is not a DSH tool: it serves the provider's `cua` guidance registered for the connection's
|
||||
* Agent, the text a DSH model receives in its system prompt.
|
||||
*/
|
||||
const REFERENCE_TOOL: Tool = {
|
||||
name: 'cua_get_api_reference',
|
||||
title: 'Computer use API reference',
|
||||
description: 'Return the complete `cua` API reference that every cua_run_code program must follow: methods, signatures, '
|
||||
+ 'and operating rules. Call it before the first cua_run_code program of a conversation, and again whenever the reference '
|
||||
+ 'is no longer in your context or a program fails on an unknown `cua` method. It only reads: nothing on the desktop or '
|
||||
+ 'in the program environment changes.',
|
||||
inputSchema: { type: 'object', properties: {} },
|
||||
annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
||||
}
|
||||
|
||||
/** The host-level reset is not a DSH tool, so its definition lives here. */
|
||||
const RESET_TOOL: Tool = {
|
||||
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. A running cua_run_code program is cancelled. Application access '
|
||||
+ 'grants and the desktop applications themselves are unaffected; the next cua_run_code call starts a fresh environment. '
|
||||
+ 'Use it when the environment has become unusable or its retained state must not carry into the next task.',
|
||||
inputSchema: { type: 'object', properties: {} },
|
||||
annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: true, openWorldHint: false },
|
||||
}
|
||||
|
||||
const INSTRUCTIONS = 'DeepSeek Harness Computer Use: observe and operate desktop applications on this machine. '
|
||||
+ 'Start every conversation by calling cua_get_api_reference: it returns the complete cua API reference, and programs '
|
||||
+ 'written without it guess the API wrong. Then call cua_run_code with a TypeScript program that uses the global cua '
|
||||
+ 'object; program state persists across calls on this connection. A call may ask the user for application or pointer '
|
||||
+ 'consent before it proceeds. Call cua_reset to discard program state.'
|
||||
|
||||
const NO_PROVIDER = 'Computer Use is not available on this Host: the cua-mcp profile has no active CUA provider. '
|
||||
+ 'Providers exist for macOS and native Windows; on those Hosts the server\'s stderr names why the provider did not start.'
|
||||
|
||||
function text(value: string): CallToolResult {
|
||||
return { content: [{ type: 'text', text: value }] }
|
||||
}
|
||||
|
||||
function failure(value: string): CallToolResult {
|
||||
return { content: [{ type: 'text', text: value }], isError: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Project the Agent's `cua_run_code` registration onto an MCP tool: name, description, and parameters as registered,
|
||||
* minus the sandbox-escalation fields, checked against the protocol's tool type so an unrepresentable schema fails
|
||||
* the listing instead of the client.
|
||||
*/
|
||||
function projectProgramTool(definition: ToolDefinition): Tool {
|
||||
const { properties, required, ...rest } = definition.parameters
|
||||
const inputSchema = {
|
||||
...rest,
|
||||
...properties === undefined ? {} : {
|
||||
properties: Object.fromEntries(Object.entries(properties as Record<string, unknown>).filter(([field]) => !isEscalationField(field))),
|
||||
},
|
||||
...Array.isArray(required) ? { required: (required as string[]).filter(field => !isEscalationField(field)) } : {},
|
||||
}
|
||||
const result = specTypeSchemas.Tool['~standard'].validate({
|
||||
name: definition.name, description: definition.description, inputSchema, ...PROGRAM_TOOL_PRESENTATION,
|
||||
})
|
||||
if (result.issues !== undefined) {
|
||||
throw new Error(`The ${definition.name} registration is not an MCP tool: ${result.issues.map(issue => issue.message).join('; ')}`)
|
||||
}
|
||||
return result.value
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the MCP server for one stdio connection. The connection's Agent is created first, mounts the profile's
|
||||
* default preset, and lives until disposal; the provider registers `cua_run_code` for it, and each `tools/list`
|
||||
* re-reads that registration beside the two tools defined here. A call names a listed tool or fails as an unknown
|
||||
* tool before it reaches the executor, so a tool another row registers for the Agent is never callable without
|
||||
* being listed. `cua_get_api_reference` returns the provider's `cua` guidance for the Agent and keeps no state.
|
||||
* `cua_run_code` calls pass their arguments to the ordinary tool executor unchanged, one at a time in arrival
|
||||
* order, each as the Agent's maintenance activity: argument validation is answered by DSH, and disposing the Agent
|
||||
* cancels the running call and waits for it to settle. `cua_reset` bypasses the queue: it cancels the running program,
|
||||
* releases the Agent's program environment through `ctx.cuaPrograms`, answers after the cancelled program has settled,
|
||||
* and holds back programs that arrive meanwhile; the Agent, its native connection, and its application grants stay,
|
||||
* and the next program starts a fresh process. Concurrent resets share one release.
|
||||
* Consent questions of that Agent are answered by the configured mode. A call the executor cannot settle,
|
||||
* including a cancelled one, fails as a protocol error.
|
||||
* @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, its Agent, and its disposer.
|
||||
* @throws Error when the Agent cannot be created; nothing is served then.
|
||||
*/
|
||||
export async function createCuaMcpServer(ctx: Context, options: CuaMcpServerOptions): Promise<CuaMcpServer> {
|
||||
const manifest = createRequire(import.meta.url)('../package.json') as { version: string }
|
||||
const handle = await ctx.agents.create({
|
||||
sessionId: brandString<SessionId>(`cua-mcp-${randomUUID()}`),
|
||||
meta: { cwd: options.cwd, agentPreset: ctx.agentPresets.defaultId },
|
||||
setup: async (agentCtx) => { await ctx.agentPresets.mount(agentCtx) },
|
||||
})
|
||||
const { agent } = handle
|
||||
// The listing is projected from the registry at each request; McpServer owns tools/list and tools/call once a tool
|
||||
// is registered on it, so this advanced use builds on the low-level protocol server the SDK keeps for that case.
|
||||
// oxlint-disable-next-line typescript/no-deprecated -- low-level server for a dynamic tool list, see above.
|
||||
const server = new Server({ name: MCP_SERVER_NAME, version: manifest.version }, {
|
||||
capabilities: { tools: { listChanged: false } },
|
||||
instructions: INSTRUCTIONS,
|
||||
})
|
||||
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.getClientCapabilities()?.elicitation !== undefined,
|
||||
// oxlint-disable-next-line typescript/no-deprecated -- 2025-era request, see above.
|
||||
elicit: (message, labels, signal) => 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 === agent, elicitation))
|
||||
|
||||
let calls = 0
|
||||
let queue: Promise<unknown> = Promise.resolve()
|
||||
const serialize = <T>(run: () => Promise<T>): Promise<T> => {
|
||||
const next = queue.then(run, run)
|
||||
queue = next.catch(() => undefined)
|
||||
return next
|
||||
}
|
||||
/** The reset in progress; concurrent `cua_reset` calls share it, and programs wait for it. */
|
||||
let resetting: Promise<CallToolResult> | undefined
|
||||
/** The provider's `cua` guidance for this Agent. It holds no connection state, so any conversation can read it at any time. */
|
||||
const apiReference = async (): Promise<CallToolResult> => {
|
||||
const assembly = await ctx.systemPrompt.assemble({ scope: agent })
|
||||
const guidance = assembly.sections.find(section => section.name === CUA_PROMPT_SECTION_NAME)?.text
|
||||
return guidance === undefined ? failure(NO_PROVIDER) : text(`## cua API reference\n\n${guidance}`)
|
||||
}
|
||||
const runTool = async (args: Record<string, unknown>, signal: AbortSignal): Promise<CallToolResult> => {
|
||||
const escalation = ESCALATION_FIELDS.filter(field => field in args)
|
||||
if (escalation.length > 0) {
|
||||
return failure(`Program sandbox escalation is not available through cua-mcp: remove ${escalation.join(' and ')}. `
|
||||
+ 'The launch-time DSH_PERMISSION_MODE selects the file sandbox of program processes.')
|
||||
}
|
||||
// The program runtime rejects a run while the Agent's previous process is still exiting.
|
||||
while (resetting !== undefined) await resetting
|
||||
// The call is the Agent's maintenance activity: Agent disposal cancels it and waits for it, with its nested
|
||||
// calls, to settle before the Agent's scope and Session close.
|
||||
const batch = await agent.runMaintenance(maintenance => ctx.agents.withInitiator(agent, () => ctx.tools.execute({
|
||||
calls: [{
|
||||
type: 'tool-call', id: brandString<ToolCallId>(`cua-mcp-${String(++calls)}`), name: PROGRAM_TOOL, arguments: JSON.stringify(args),
|
||||
}],
|
||||
agent, signal: AbortSignal.any([signal, maintenance]),
|
||||
})))
|
||||
const outcome = batch.results[0]
|
||||
if (outcome === undefined) throw new Error(`The tool executor settled without a ${PROGRAM_TOOL} result`)
|
||||
const programs = ctx.get('cuaPrograms')
|
||||
return projectToolResult(outcome.result, batch.additionalContexts, {
|
||||
attachments: ctx.attachments, target: image => programs?.screenshotRequestTarget(image),
|
||||
}, signal)
|
||||
}
|
||||
const resetEnvironment = (): CallToolResult | Promise<CallToolResult> => {
|
||||
const programs = ctx.get('cuaPrograms')
|
||||
if (programs === undefined) return failure(NO_PROVIDER)
|
||||
resetting ??= (async () => {
|
||||
// The running program is cancelled wherever its call stands; releasing its environment then ends the process
|
||||
// without the runtime's wait for the program to yield.
|
||||
agent.cancel({ kind: 'user' }, { keepInbox: true })
|
||||
let outcome: CallToolResult
|
||||
try {
|
||||
await programs.release(agent)
|
||||
outcome = text('Program environment cleared: variables, imports, and application and window objects from earlier calls '
|
||||
+ 'are gone. Application access granted earlier still applies; select applications again with cua.getApp.')
|
||||
} catch (error) {
|
||||
outcome = failure(`Program environment reset failed: ${error instanceof Error ? error.message : String(error)}. `
|
||||
+ 'Call cua_reset again before running another program.')
|
||||
}
|
||||
// The cancelled program answers before the reset does.
|
||||
await agent.whenIdle()
|
||||
return outcome
|
||||
})().finally(() => { resetting = undefined })
|
||||
return resetting
|
||||
}
|
||||
|
||||
server.setRequestHandler('tools/list', () => {
|
||||
const definition = ctx.tools.get(PROGRAM_TOOL, agent)
|
||||
return { tools: [REFERENCE_TOOL, ...definition === undefined ? [] : [projectProgramTool(definition)], RESET_TOOL] }
|
||||
})
|
||||
server.setRequestHandler('tools/call', (request, extra) => {
|
||||
const { name, arguments: args = {} } = request.params
|
||||
if (name === REFERENCE_TOOL.name) return apiReference()
|
||||
if (name === RESET_TOOL.name) return resetEnvironment()
|
||||
// The same judgement as tools/list: only the listed registration reaches the executor.
|
||||
if (name !== PROGRAM_TOOL || ctx.tools.get(PROGRAM_TOOL, agent) === undefined) return failure(`unknown tool ${JSON.stringify(name)}`)
|
||||
return serialize(() => runTool(args, AbortSignal.any([options.signal, extra.mcpReq.signal])))
|
||||
})
|
||||
|
||||
return {
|
||||
server,
|
||||
agent,
|
||||
async dispose() {
|
||||
unregisterAnswerer()
|
||||
try {
|
||||
await server.close()
|
||||
} finally {
|
||||
await resetting
|
||||
await queue
|
||||
await handle.dispose()
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
/** The bundle's manifest and patch: a standalone profile composed from one insert over the empty root. */
|
||||
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<string, unknown>
|
||||
dsh: { bundle: { patch: string; platforms?: string[] } }
|
||||
dependencies: Record<string, string>
|
||||
optionalDependencies: Record<string, string>
|
||||
}
|
||||
|
||||
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 ?? [])
|
||||
const row = (id: string) => inserted.find(entry => entry.id === id)
|
||||
|
||||
describe('cua-mcp bundle', () => {
|
||||
it('publishes an unprefixed experimental bundle whose patch is its only declaration, with both native providers optional', () => {
|
||||
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-cua-macos', '@deepseek-ai/dsh-cua-windows'])
|
||||
expect(readdirSync(resolve(root, 'locale')).sort()).toEqual(['de.json', 'en.json', 'es.json', 'fr.json', 'ja.json', 'pt.json', 'ru.json', 'zh.json'])
|
||||
})
|
||||
|
||||
it('composes the standalone profile from one insert without model adapters, prompt tools, or telemetry', () => {
|
||||
expect(patches.map(patch => Object.keys(patch))).toEqual([['insert']])
|
||||
expect(inserted.map(entry => entry.id)).toEqual([
|
||||
'session', 'session-persistence-jsonl', 'session-projection', 'attachment-local', 'working-directory',
|
||||
'storage', 'storage-json', 'storage-domain',
|
||||
'subprocess', 'sandbox', 'sandbox-policy', 'approval', 'fs-sandbox',
|
||||
'tools', 'tool-executor-native', 'system-prompt', 'user-questions', 'llm', 'agent', 'agent-loop',
|
||||
'cua-mcp-presets', 'cua-mcp-preset', 'cua-mcp-computer-use', 'cua-mcp-provider', 'cua-mcp-provider-windows', 'cua-mcp',
|
||||
])
|
||||
// The llm hub carries no adapter row, so no model request can leave this profile.
|
||||
expect(inserted.map(entry => entry.name).filter(name => /llm|telemetry|otel|web|subagent|compaction|skill|plugin-manager/.test(name)))
|
||||
.toEqual(['@deepseek-ai/dsh-llm'])
|
||||
expect(row('agent-loop')?.config).toEqual({ agents: [] })
|
||||
expect(row('cua-mcp-presets')?.config).toEqual({ default: 'cua-mcp' })
|
||||
expect(row('cua-mcp-preset')?.config).toEqual({ id: 'cua-mcp', plugins: [] })
|
||||
for (const name of inserted.map(entry => entry.name)) {
|
||||
if (name === manifest.name) continue
|
||||
expect({ ...manifest.dependencies, ...manifest.optionalDependencies }).toHaveProperty(name)
|
||||
}
|
||||
})
|
||||
|
||||
it('pins the file-effect boundary of every shipped CLI mode for program processes', () => {
|
||||
const policy = row('sandbox-policy')?.config as { mode: unknown; workspaceRoot: unknown }
|
||||
const approval = row('approval')?.config as { policy: unknown }
|
||||
expect(interpolate({ process: { env: {} } }, policy.mode)).toBe('workspace-write')
|
||||
expect(interpolate({ process: { env: { DSH_PERMISSION_MODE: 'danger-full-access' } } }, policy.mode)).toBe('danger-full-access')
|
||||
expect(interpolate({ process: { env: {} } }, approval.policy)).toBe('ask')
|
||||
expect(interpolate({ process: { env: { DSH_PERMISSION_MODE: 'danger-full-access' } } }, approval.policy)).toBe('never')
|
||||
})
|
||||
|
||||
it('keeps programs in a workspace inside the Harness home unless DSH_CUA_WORKSPACE names another directory', () => {
|
||||
const dshHomePath = (...segments: string[]) => ['/home/me/.dsh', ...segments].join('/')
|
||||
// The directory the client launched the server from is never the workspace.
|
||||
const launched = { env: {}, cwd: () => '/' }
|
||||
const pinned = { env: { DSH_CUA_WORKSPACE: '/projects/desk' }, cwd: () => '/' }
|
||||
// The frontend row sets the Agent's working directory, which is a program's workspace-write root; the policy
|
||||
// row's root is the fallback for calls without a Session, so both rows resolve the same directory.
|
||||
for (const value of [(row('cua-mcp')?.config as { workspace: unknown }).workspace, (row('sandbox-policy')?.config as { workspaceRoot: unknown }).workspaceRoot]) {
|
||||
expect(interpolate({ process: launched, dshHomePath }, value)).toBe('/home/me/.dsh/cua-mcp/workspace')
|
||||
expect(interpolate({ process: pinned, dshHomePath }, value)).toBe('/projects/desk')
|
||||
}
|
||||
})
|
||||
|
||||
it('mounts one native provider per Host, each with a fixed screenshot target and the PTC raw-tool preset', () => {
|
||||
const providers = { darwin: row('cua-mcp-provider'), win32: row('cua-mcp-provider-windows') }
|
||||
expect(providers.darwin?.name).toBe('@deepseek-ai/dsh-cua-macos')
|
||||
expect(providers.win32?.name).toBe('@deepseek-ai/dsh-cua-windows')
|
||||
for (const [host, provider] of Object.entries(providers)) {
|
||||
expect(provider?.config).toEqual({ agentPreset: 'ptc', screenshotTarget: { longEdge: 2048, maxBytes: 2_097_152 } })
|
||||
// Each row loads on its own Host only: elsewhere its optional provider package can be absent.
|
||||
for (const platform of ['darwin', 'linux', 'win32']) {
|
||||
expect(Boolean(interpolate({ process: { platform } }, provider?.disabled))).toBe(platform !== host)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
it('maps DSH_CUA_CONSENT onto the frontend consent and defaults to elicitation', () => {
|
||||
const consent = (row('cua-mcp')?.config as { consent: unknown }).consent
|
||||
expect(interpolate({ process: { env: {} } }, consent)).toBe('elicit')
|
||||
expect(interpolate({ process: { env: { DSH_CUA_CONSENT: 'allow' } } }, consent)).toBe('allow')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,463 @@
|
||||
/** A real Loader composition: the MCP connection runs retained Computer Use programs through a fixture desktop. */
|
||||
import { mkdtemp, realpath, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { createInterface } from 'node:readline'
|
||||
import { PassThrough } from 'node:stream'
|
||||
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 type { NativeChannelFactory } from '@deepseek-ai/dsh-cua/native-client'
|
||||
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, vi } from 'vitest'
|
||||
import { createNativeFixture } from '../../../../snapshots/session/cua-run-code/native-channel.mjs'
|
||||
import type { ConsentMode } from '../src/consent.ts'
|
||||
import { createCuaMcpServer, type CuaMcpServer } 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
|
||||
/** Hold the fixture desktop's cancellation acknowledgements back this long, as a native operation that is slow to stop does. */
|
||||
cancellationAcknowledgementMs?: number
|
||||
/** How long the program runtime waits for a cancelled program to yield before it stops the process. */
|
||||
stopGraceMs?: number
|
||||
/** Elicitation handler of the client; omission advertises no elicitation capability. */
|
||||
elicit?: (request: ElicitationRequest) => Promise<{ action: 'accept' | 'decline' | 'cancel'; content?: Record<string, string> }>
|
||||
}
|
||||
|
||||
function texts(result: CallToolResult): string[] {
|
||||
return result.content.flatMap(block => block.type === 'text' ? [block.text] : [])
|
||||
}
|
||||
|
||||
/** Forward a native channel's replies, delaying each cancellation acknowledgement and reporting its late delivery. */
|
||||
function delayCancellation(create: NativeChannelFactory, delayMs: number, delivered: () => void): NativeChannelFactory {
|
||||
return (owner, config) => {
|
||||
const channel = create(owner, config)
|
||||
const stdout = new PassThrough()
|
||||
void (async () => {
|
||||
const held: Promise<void>[] = []
|
||||
for await (const line of createInterface({ input: channel.stdout })) {
|
||||
if (!line.includes('NATIVE_CANCELLED')) {
|
||||
stdout.write(`${line}\n`)
|
||||
continue
|
||||
}
|
||||
held.push(new Promise((resolve) => {
|
||||
setTimeout(() => {
|
||||
stdout.write(`${line}\n`)
|
||||
delivered()
|
||||
resolve()
|
||||
}, delayMs)
|
||||
}))
|
||||
}
|
||||
await Promise.all(held)
|
||||
stdout.end()
|
||||
})()
|
||||
return { ...channel, stdout }
|
||||
}
|
||||
}
|
||||
|
||||
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: options.cancellationAcknowledgementMs === undefined
|
||||
? native.createChannel
|
||||
: delayCancellation(native.createChannel, options.cancellationAcknowledgementMs, () => { native.events.push('cancellation-acknowledged') }),
|
||||
getGuidance: () => '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' }],
|
||||
...options.stopGraceMs === undefined ? {} : { standaloneRunCode: { runtime: { stopGraceMs: options.stopGraceMs } } },
|
||||
} } : {},
|
||||
}))
|
||||
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()
|
||||
// The server is created from a fiber of its own, as the profile frontend creates it, so a test can unload that owner.
|
||||
const created = Promise.withResolvers<CuaMcpServer>()
|
||||
const frontend = await ctx.plugin({
|
||||
name: 'cua-mcp-composition-frontend',
|
||||
inject: ['agents', 'agentPresets', 'tools', 'systemPrompt', 'attachments'],
|
||||
apply(owner: Context) {
|
||||
createCuaMcpServer(owner, { consent: options.consent ?? 'allow', cwd: directory, signal: lifetime.signal })
|
||||
.then(created.resolve, created.reject)
|
||||
},
|
||||
})
|
||||
const adapter = await created.promise
|
||||
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()
|
||||
})
|
||||
// The native registration requires a description; tests name their programs unless they supply one.
|
||||
const run = (code: string, extra: { description?: string; timeoutMs?: number } = {}, signal?: AbortSignal) =>
|
||||
client.callTool({ name: 'cua_run_code', arguments: { code, description: 'Test program', ...extra } }, signal === undefined ? {} : { signal })
|
||||
return { ctx, native, directory, adapter, frontend, client, elicitations, run, lifetime }
|
||||
}
|
||||
|
||||
describe('Computer Use MCP composition', () => {
|
||||
it('serves three tools, returns the API reference on request, and retains program state in the workspace', async () => {
|
||||
const { ctx, native, client, run, adapter, directory } = await setup()
|
||||
expect(client.getInstructions()).toContain('Start every conversation by calling cua_get_api_reference')
|
||||
const listed = await client.listTools()
|
||||
expect(listed.tools.map(tool => tool.name)).toEqual(['cua_get_api_reference', 'cua_run_code', 'cua_reset'])
|
||||
// The MCP tool is the Agent's registration: name, description, and parameters field for field.
|
||||
const registered = ctx.tools.schemas(adapter.agent).find(tool => tool.name === 'cua_run_code')
|
||||
if (registered === undefined) throw new Error('the provider registered no cua_run_code for the connection Agent')
|
||||
// Field for field, minus the sandbox-escalation controls the registration carries and this profile refuses.
|
||||
const { properties, ...schema } = registered.parameters as { properties: Record<string, unknown> }
|
||||
const { sandbox_permissions: escalationMode, justification, ...served } = properties
|
||||
expect(escalationMode).toBeDefined()
|
||||
expect(justification).toBeDefined()
|
||||
expect(listed.tools[1]).toMatchObject({
|
||||
name: registered.name, description: registered.description, inputSchema: { ...schema, properties: served },
|
||||
})
|
||||
expect(registered.parameters).toMatchObject({ required: expect.arrayContaining(['code', 'description']) as string[] })
|
||||
expect(registered.description.length).toBeGreaterThan(1000)
|
||||
|
||||
// The reference is the provider's guidance for the connection Agent, served before any program has run.
|
||||
const reference = await client.callTool({ name: 'cua_get_api_reference', arguments: {} })
|
||||
expect(reference.isError).not.toBe(true)
|
||||
expect(reference.content).toHaveLength(1)
|
||||
const referenceText = texts(reference)[0] ?? ''
|
||||
expect(referenceText.startsWith('## cua API reference')).toBe(true)
|
||||
expect(referenceText).not.toContain('execution rules')
|
||||
expect(referenceText).toContain('Fixture CUA guidance: select test.fixture and operate window 7.')
|
||||
expect(referenceText).toContain('Maximum click holdMs: 5000 ms.')
|
||||
expect(native.calls).toEqual([])
|
||||
|
||||
const first = await run('globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); '
|
||||
+ 'await win.getAccessibilityTree(); await win.click("0"); '
|
||||
+ 'inspect(JSON.stringify({ visits, window: win.windowId, pid: process.pid, cwd: process.cwd() }), await win.getScreenshot())', { description: 'Open the fixture' })
|
||||
expect(first.isError).not.toBe(true)
|
||||
// A program result is the program's own output: the inspected text, then the screenshot the program observed.
|
||||
const result = JSON.parse(texts(first)[0] ?? '') as { visits: number; window: string; pid: number; cwd: string }
|
||||
expect(result).toMatchObject({ visits: 1, window: '7' })
|
||||
expect(result.pid).not.toBe(process.pid)
|
||||
// Programs start in the directory the connection's Agent was created in. Both spellings are resolved: the
|
||||
// temporary directory is a symlink on macOS and an 8.3 short name on Windows.
|
||||
expect(await realpath(result.cwd)).toBe(await realpath(directory))
|
||||
const image = first.content[1]
|
||||
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(first.content).toHaveLength(2)
|
||||
expect(native.state).toMatchObject({ count: 1, openedChannels: 1, closedChannels: 0 })
|
||||
|
||||
const second = await run('globalThis.visits++; await win.getAccessibilityTree(); await win.click("0"); inspect(JSON.stringify({ 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)); inspect("a")'),
|
||||
run('globalThis.order.push("b"); inspect(JSON.stringify(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)
|
||||
// The client marks the error; the text is DSH's failure message without its `Error: ` prefix.
|
||||
expect(texts(failed)[0]).toMatch(/^code run failed \(exception\): .*boom/s)
|
||||
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('inspect(1 + 1)'))).toBe(2)
|
||||
// Argument validation belongs to the DSH executor: a program without the required description is refused there.
|
||||
const invalid = await client.callTool({ name: 'cua_run_code', arguments: { code: '1' } })
|
||||
expect(invalid.isError).toBe(true)
|
||||
expect(texts(invalid)).toEqual(['invalid arguments: missing required property "description"'])
|
||||
})
|
||||
|
||||
it('resets only the program environment: a fresh process and cua object, the same Agent and native connection', async () => {
|
||||
const { ctx, native, run, client, adapter } = await setup()
|
||||
const first = await run('globalThis.visits = 1; var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); inspect(process.pid)')
|
||||
const pid = lastJson(first) as number
|
||||
const { agent } = adapter
|
||||
const reset = await client.callTool({ name: 'cua_reset', arguments: {} })
|
||||
expect(reset.isError).not.toBe(true)
|
||||
expect(texts(reset)).toEqual(['Program environment cleared: variables, imports, and application and window objects from earlier calls '
|
||||
+ 'are gone. Application access granted earlier still applies; select applications again with cua.getApp.'])
|
||||
const next = await run('inspect(JSON.stringify({ visits: globalThis.visits ?? null, hasApp: typeof app !== "undefined", cua: typeof cua, pid: process.pid }))')
|
||||
expect(next.content).toHaveLength(1)
|
||||
const state = lastJson(next) as { visits: null; hasApp: boolean; cua: string; pid: number }
|
||||
// The fresh process re-created the cua object; the variables and application objects of the previous one are gone.
|
||||
expect(state).toMatchObject({ visits: null, hasApp: false, cua: 'object' })
|
||||
expect(state.pid).not.toBe(pid)
|
||||
expect(() => process.kill(pid, 0)).toThrow()
|
||||
// The program selects the application and its window again and operates them over the connection the Agent kept.
|
||||
const again = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); await win.click("0"); inspect(JSON.stringify(win.windowId))')
|
||||
expect(lastJson(again)).toBe('7')
|
||||
expect(native.state).toMatchObject({ count: 1, openedChannels: 1, closedChannels: 0 })
|
||||
expect(ctx.agents.list()).toEqual([agent])
|
||||
expect(texts(await client.callTool({ name: 'cua_get_api_reference', arguments: {} }))[0]).toContain('## cua API reference')
|
||||
})
|
||||
|
||||
it('keeps session consent across a reset: a granted application is selected again without a request, and a refusal stays', async () => {
|
||||
const select = (served: Awaited<ReturnType<typeof setup>>) => served.run('var app = await cua.getApp("test.fixture"); inspect("selected")')
|
||||
const granted = await setup({
|
||||
consent: 'elicit', granted: false, elicit: async () => ({ action: 'accept', content: { decision: 'Allow for this session' } }),
|
||||
})
|
||||
expect((await select(granted)).isError).not.toBe(true)
|
||||
await granted.client.callTool({ name: 'cua_reset', arguments: {} })
|
||||
expect((await select(granted)).isError).not.toBe(true)
|
||||
expect(granted.elicitations).toHaveLength(1)
|
||||
|
||||
const refused = await setup({
|
||||
consent: 'elicit', granted: false, elicit: async () => ({ action: 'accept', content: { decision: 'Deny' } }),
|
||||
})
|
||||
expect((await select(refused)).isError).toBe(true)
|
||||
await refused.client.callTool({ name: 'cua_reset', arguments: {} })
|
||||
const again = await select(refused)
|
||||
expect(again.isError).toBe(true)
|
||||
expect(texts(again).join('\n')).toContain('APP_ACCESS_DENIED')
|
||||
expect(refused.elicitations).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('cancels the running program on reset, answers after it has settled, and runs a queued program in the fresh environment', async () => {
|
||||
// The native operation takes 200 ms to acknowledge cancellation, so the cancelled program stays in flight that long.
|
||||
const { native, run, client } = await setup({ cancellationAcknowledgementMs: 200 })
|
||||
const ready = await run('globalThis.generation = "first"; var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); inspect(process.pid)')
|
||||
const pid = lastJson(ready) as number
|
||||
const held = native.holdNextClick()
|
||||
const running = run('await win.click("0")')
|
||||
await held
|
||||
// Queued behind the running program, before the reset arrives.
|
||||
const queued = run('inspect(JSON.stringify({ generation: globalThis.generation ?? null, pid: process.pid }))')
|
||||
const reset = await client.callTool({ name: 'cua_reset', arguments: {} })
|
||||
// The reset answered after the cancelled program's native operation had acknowledged the cancellation.
|
||||
expect(native.events).toEqual(['native-cancelled', 'cancellation-acknowledged'])
|
||||
expect(reset.isError).not.toBe(true)
|
||||
const cancelled = await running
|
||||
expect(cancelled.isError).toBe(true)
|
||||
expect(texts(cancelled).join('\n')).toContain('tool call aborted')
|
||||
const fresh = lastJson(await queued) as { generation: null; pid: number }
|
||||
expect(fresh.generation).toBeNull()
|
||||
expect(fresh.pid).not.toBe(pid)
|
||||
expect(() => process.kill(pid, 0)).toThrow()
|
||||
// Nothing closed the Agent's native connection.
|
||||
expect(native.events).not.toContain('native-close')
|
||||
expect(native.state).toMatchObject({ openedChannels: 1, closedChannels: 0 })
|
||||
})
|
||||
|
||||
it('holds a program that arrives during a reset until the previous process has exited', async () => {
|
||||
const { run, client } = await setup()
|
||||
await run('globalThis.kept = 1; inspect("ready")')
|
||||
// The runtime rejects a program for an Agent whose previous process is still exiting.
|
||||
const [reset, program] = await Promise.all([
|
||||
client.callTool({ name: 'cua_reset', arguments: {} }),
|
||||
run('inspect(JSON.stringify({ kept: globalThis.kept ?? null }))'),
|
||||
])
|
||||
expect(reset.isError).not.toBe(true)
|
||||
expect(program.isError).not.toBe(true)
|
||||
expect(lastJson(program)).toEqual({ kept: null })
|
||||
})
|
||||
|
||||
it('ends a program that cannot be interrupted on reset without waiting for the runtime to stop it', async () => {
|
||||
// A cancelled program gets ten minutes to settle before the runtime stops its process, longer than any test
|
||||
// budget: this reset answers only because releasing the environment ends that wait.
|
||||
const { ctx, run, client, adapter } = await setup({ stopGraceMs: 600_000 })
|
||||
const pid = lastJson(await run('globalThis.kept = 1; inspect(process.pid)')) as number
|
||||
// The looping process below is stopped even when the reset fails to stop it.
|
||||
onTestFinished(() => {
|
||||
try { process.kill(pid, 'SIGKILL') } catch (_error: unknown) { /* The reset already ended the process. */ }
|
||||
})
|
||||
const observed: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
ctx.on('session/event', (candidate, event) => {
|
||||
if (candidate === adapter.agent.session && event.type === 'tool/ptc-dispatch' && event.data.rootCallId === 'cua-mcp-2') observed.resolve()
|
||||
})
|
||||
// The program enters its loop as soon as the nested call's result reaches it, before any later message.
|
||||
const looping = run('await cua.getCapabilities(); while (true) {}')
|
||||
await observed.promise
|
||||
const reset = await client.callTool({ name: 'cua_reset', arguments: {} })
|
||||
expect(reset.isError).not.toBe(true)
|
||||
const cancelled = await looping
|
||||
expect(cancelled.isError).toBe(true)
|
||||
expect(texts(cancelled).join('\n')).toContain('tool call aborted')
|
||||
expect(() => process.kill(pid, 0)).toThrow()
|
||||
expect(lastJson(await run('inspect(JSON.stringify({ kept: globalThis.kept ?? null }))'))).toEqual({ kept: null })
|
||||
})
|
||||
|
||||
it('cancels an in-flight program and waits for its nested call to settle before a disposed Agent releases anything', async () => {
|
||||
// The native operation takes 200 ms to acknowledge cancellation, so the cancelled call stays in flight that long.
|
||||
const { ctx, native, run, adapter, frontend } = await setup({ cancellationAcknowledgementMs: 200 })
|
||||
const opened = await run('var app = await cua.getApp("test.fixture"); var win = await app.getWindow("7"); await win.getAccessibilityTree(); inspect("ready")')
|
||||
expect(opened.isError).not.toBe(true)
|
||||
const { session } = adapter.agent
|
||||
const order: string[] = []
|
||||
ctx.on('session/event', (candidate, event) => {
|
||||
if (candidate === session && event.type === 'tool/ptc-dispatch' && event.data.rootCallId === 'cua-mcp-2') order.push('nested call recorded')
|
||||
})
|
||||
const reported = vi.spyOn(ctx.logger, 'error')
|
||||
const held = native.holdNextClick()
|
||||
const program = run('await win.click("0")')
|
||||
await held
|
||||
// The fiber that owns the Agent unloads while the call is in flight; nothing has closed or drained the server.
|
||||
await frontend.dispose()
|
||||
order.push('Agent disposed')
|
||||
// The call was cancelled, its native operation acknowledged the cancellation, and its nested call was
|
||||
// recorded, all before the Agent released its native connection and closed its Session.
|
||||
expect(native.events).toEqual(['native-cancelled', 'cancellation-acknowledged', 'native-close'])
|
||||
expect(order).toEqual(['nested call recorded', 'Agent disposed'])
|
||||
const result = await program
|
||||
expect(result.isError).toBe(true)
|
||||
expect(texts(result).join('\n')).toContain('tool call aborted')
|
||||
expect(ctx.agents.list()).toHaveLength(0)
|
||||
const interrupted = session.snapshotEvents()
|
||||
.filter(event => (event.type === 'tool/ptc-dispatch-start' || event.type === 'tool/ptc-dispatch') && event.data.rootCallId === 'cua-mcp-2')
|
||||
expect(interrupted.map(event => event.type)).toEqual(['tool/ptc-dispatch-start', 'tool/ptc-dispatch'])
|
||||
expect(interrupted[1]?.data).toMatchObject({ name: 'cua', isError: true })
|
||||
expect(reported).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
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"); inspect(JSON.stringify(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('lists no program tool on a Host without a CUA provider and releases the connection Agent on disposal', async () => {
|
||||
const { ctx, run, client, adapter } = await setup({ provider: false })
|
||||
expect((await client.listTools()).tools.map(tool => tool.name)).toEqual(['cua_get_api_reference', 'cua_reset'])
|
||||
const reference = await client.callTool({ name: 'cua_get_api_reference', arguments: {} })
|
||||
expect(reference.isError).toBe(true)
|
||||
expect(texts(reference)[0]).toContain('no active CUA provider')
|
||||
// No registration exists for the Agent, so the call is refused as an unknown tool before it reaches the executor.
|
||||
const result = await run('1')
|
||||
expect(result.isError).toBe(true)
|
||||
expect(texts(result)[0]).toContain('unknown tool "cua_run_code"')
|
||||
const reset = await client.callTool({ name: 'cua_reset', arguments: {} })
|
||||
expect(reset.isError).toBe(true)
|
||||
expect(texts(reset)[0]).toContain('no active CUA provider')
|
||||
expect(ctx.agents.list()).toHaveLength(1)
|
||||
await client.close()
|
||||
await adapter.dispose()
|
||||
expect(ctx.agents.list()).toHaveLength(0)
|
||||
})
|
||||
})
|
||||
@@ -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<ReturnType<ElicitationClient['elicit']>>, supported = true) {
|
||||
const elicit = vi.fn<ElicitationClient['elicit']>(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()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,73 @@
|
||||
/** Result projection: text passes through, screenshots become inline images, failures keep isError without DSH's error prefix. */
|
||||
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<ImageAttachmentRef['attachmentId']>(`sha256:${'a'.repeat(64)}`),
|
||||
mediaType: 'image/png', bytes: 3, width: 400, height: 200,
|
||||
}
|
||||
|
||||
function store() {
|
||||
const readImage = vi.fn<AttachmentStore['readImage']>(async () => ({ ref: attachment, data: new Uint8Array([1, 2, 3]) }))
|
||||
const readImageRequest = vi.fn<AttachmentStore['readImageRequest']>(async () => ({
|
||||
variantId: brandString<ImageVariantId>('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<AttachmentStore, 'readImage' | 'readImageRequest'> = { 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)
|
||||
expect(result).toEqual({ content: [
|
||||
{ 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 flag of a failed execution and reports its message once, without the DSH error prefix', async () => {
|
||||
const { attachments } = store()
|
||||
const failure: ToolExecutionResult = {
|
||||
isError: true, error: { message: 'code run failed (exception): boom', info: { name: 'CodeRunFailedError', code: 'CODE_RUN_FAILED' } },
|
||||
// The failure rendering, then output the program displayed before it failed; only the rendering carries the prefix.
|
||||
content: [{ type: 'text', text: 'Error: code run failed (exception): boom' }, { type: 'text', text: 'Error: shown by the program' }],
|
||||
}
|
||||
expect(await projectToolResult(failure, [], { attachments, target: () => undefined }, new AbortController().signal)).toEqual({
|
||||
content: [{ type: 'text', text: 'code run failed (exception): boom' }, { type: 'text', text: 'Error: shown by the program' }], isError: true,
|
||||
})
|
||||
// A successful program that displays the same words keeps them.
|
||||
const shown: ToolExecutionResult = { isError: false, value: 'ok', content: [{ type: 'text', text: 'Error: code run failed (exception): boom' }] }
|
||||
expect(await projectToolResult(shown, [], { attachments, target: () => undefined }, new AbortController().signal))
|
||||
.toEqual({ content: [{ type: 'text', text: 'Error: code run failed (exception): boom' }] })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,350 @@
|
||||
/** Server behavior beyond the fixture desktop: registry projection, the reference tool, unknown tools, and reset ordering. */
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import type { Agent, AgentHandle } from '@deepseek-ai/dsh-agent'
|
||||
import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
import type { CuaPrograms } from '@deepseek-ai/dsh-cua'
|
||||
import type { 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' },
|
||||
}
|
||||
|
||||
/** The registration the fixture provider publishes for the connection's Agent. */
|
||||
const registration = {
|
||||
name: 'cua_run_code',
|
||||
description: 'Run a program against the global cua object.',
|
||||
parameters: {
|
||||
type: 'object',
|
||||
properties: {
|
||||
code: { type: 'string' }, description: { type: 'string' }, timeoutMs: { type: 'number' },
|
||||
sandbox_permissions: { type: 'string', enum: ['danger-full-access'] }, justification: { type: 'string' },
|
||||
},
|
||||
required: ['code', 'description'], additionalProperties: false,
|
||||
},
|
||||
}
|
||||
|
||||
/** The projection of that registration: the sandbox-escalation fields are not served. */
|
||||
const projectedSchema = {
|
||||
type: 'object',
|
||||
properties: { code: { type: 'string' }, description: { type: 'string' }, timeoutMs: { type: 'number' } },
|
||||
required: ['code', 'description'], additionalProperties: false,
|
||||
}
|
||||
|
||||
function batch(text: string, isError = false): ToolBatchResult {
|
||||
return {
|
||||
results: [{ callId: 'cua-mcp-1' as never, result: isError
|
||||
? { isError: true, error: { message: text, info: { name: 'ToolNotFoundError', code: 'UNKNOWN_TOOL' } }, content: [{ type: 'text', text }] }
|
||||
: { isError: false, value: text, content: [{ type: 'text', text }] } }],
|
||||
additionalContexts: [], concluded: false,
|
||||
}
|
||||
}
|
||||
|
||||
interface SetupOptions {
|
||||
createFailures?: number
|
||||
programs?: Partial<CuaPrograms> | false
|
||||
elicitation?: boolean
|
||||
/** Whether the provider registered `cua_run_code` for the Agent. */
|
||||
registered?: boolean
|
||||
/** Parameter schema of that registration; the default is representable as an MCP tool. */
|
||||
parameters?: Record<string, unknown>
|
||||
/** Whether the provider registered its `cua` guidance for the Agent. */
|
||||
reference?: boolean
|
||||
}
|
||||
|
||||
function fixture(options: SetupOptions = {}) {
|
||||
const ctx = new Context()
|
||||
// The Agent runs a maintenance task at once and cancels it through this controller, as its cancel and disposal do.
|
||||
const maintenance = new AbortController()
|
||||
const members: Pick<Agent, 'id' | 'ctx' | 'runMaintenance' | 'cancel' | 'whenIdle'> = {
|
||||
id: brandString<SessionId>('cua-mcp-fake'), ctx: new Context(), runMaintenance: task => task(maintenance.signal),
|
||||
cancel: (cause) => { maintenance.abort(cause) }, whenIdle: async () => {},
|
||||
}
|
||||
const runMaintenance = vi.spyOn(members, 'runMaintenance')
|
||||
const cancel = vi.spyOn(members, 'cancel')
|
||||
const whenIdle = vi.spyOn(members, 'whenIdle')
|
||||
const agent = members as Agent
|
||||
const dispose = vi.fn(async () => {})
|
||||
let failures = options.createFailures ?? 0
|
||||
const create = vi.fn(async (
|
||||
request: { setup?: (agentCtx: Context, agent: Agent) => Promise<unknown> | undefined },
|
||||
): Promise<AgentHandle> => {
|
||||
if (failures > 0) {
|
||||
failures -= 1
|
||||
throw new Error('registry refused the Agent')
|
||||
}
|
||||
await request.setup?.(agent.ctx, agent)
|
||||
return { agent, dispose }
|
||||
})
|
||||
const initiators: Agent[] = []
|
||||
const withInitiator = vi.fn(<T>(initiator: Agent, operation: () => T): T => { initiators.push(initiator); return operation() })
|
||||
const mount = vi.fn(async () => ({ id: 'cua-mcp' }))
|
||||
const execute = vi.fn(async (input: ToolBatchInput): Promise<ToolBatchResult> => {
|
||||
const call = input.calls[0]
|
||||
if (call === undefined) throw new Error('no call')
|
||||
return options.registered === false || call.name !== 'cua_run_code' ? batch(`unknown tool "${call.name}"`, true) : batch('program output')
|
||||
})
|
||||
const get = vi.fn(() => options.registered === false
|
||||
? undefined
|
||||
: { ...registration, parameters: options.parameters ?? registration.parameters })
|
||||
const assemble = vi.fn(async () => ({
|
||||
sections: options.reference === false ? [] : [{ name: 'computer-use:dsh-cua', text: 'Fixture guidance' }], contexts: [], variables: {}, tools: [],
|
||||
}))
|
||||
const release = vi.fn(async () => {})
|
||||
ctx.provide('agents', { create, withInitiator } 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', { release, screenshotRequestTarget: () => undefined, ...options.programs } as never)
|
||||
onTestFinished(async () => { await ctx.fiber.dispose() })
|
||||
return {
|
||||
ctx, agent, maintenance, runMaintenance, cancel, whenIdle, create, withInitiator, initiators, mount, execute, get, assemble,
|
||||
release, dispose,
|
||||
}
|
||||
}
|
||||
|
||||
async function setup(options: SetupOptions = {}) {
|
||||
const parts = fixture(options)
|
||||
const lifetime = new AbortController()
|
||||
const adapter = await createCuaMcpServer(parts.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()
|
||||
})
|
||||
const run = (args: Record<string, unknown>) => client.callTool({ name: 'cua_run_code', arguments: args })
|
||||
const reset = () => client.callTool({ name: 'cua_reset', arguments: {} })
|
||||
return { ...parts, adapter, client, run, reset, 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 before serving, projects its registration verbatim, and runs programs as Agent maintenance inside the initiator scope', async () => {
|
||||
const { adapter, client, run, create, mount, execute, withInitiator, initiators, agent, runMaintenance, maintenance } = await setup()
|
||||
expect(create).toHaveBeenCalledOnce()
|
||||
expect(create.mock.calls[0]?.[0]).toMatchObject({ meta: { cwd: '/workspace', agentPreset: 'cua-mcp' } })
|
||||
expect(mount).toHaveBeenCalledWith(agent.ctx)
|
||||
expect(adapter.agent).toBe(agent)
|
||||
const listed = await client.listTools()
|
||||
expect(listed.tools.map(tool => tool.name)).toEqual(['cua_get_api_reference', 'cua_run_code', 'cua_reset'])
|
||||
const program = listed.tools[1]
|
||||
expect(program).toMatchObject({
|
||||
name: registration.name, description: registration.description, inputSchema: projectedSchema, title: 'Computer use program',
|
||||
})
|
||||
expect(program?.inputSchema.properties).not.toHaveProperty('sandbox_permissions')
|
||||
const escalation = await run({ code: '1', description: 'Escalate', sandbox_permissions: 'danger-full-access', justification: 'test' })
|
||||
expect(escalation.isError).toBe(true)
|
||||
expect(texts(escalation)[0]).toContain('remove sandbox_permissions and justification')
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
expect(runMaintenance).not.toHaveBeenCalled()
|
||||
const first = await run({ code: '1 + 1', description: 'Add', timeoutMs: 5000 })
|
||||
expect(texts(first)).toEqual(['program output'])
|
||||
expect(execute).toHaveBeenCalledOnce()
|
||||
expect(runMaintenance).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: 'Add', timeoutMs: 5000 })
|
||||
expect(withInitiator).toHaveBeenCalledOnce()
|
||||
expect(initiators).toEqual([agent])
|
||||
expect(texts(await run({ code: '2', description: 'Again' }))).toEqual(['program output'])
|
||||
// Cancelling the Agent's maintenance activity, as its disposal does, cancels the program's execution.
|
||||
expect(input.signal.aborted).toBe(false)
|
||||
maintenance.abort()
|
||||
expect(input.signal.aborted).toBe(true)
|
||||
})
|
||||
|
||||
it('fails the listing when the registration is not representable as an MCP tool', async () => {
|
||||
const { client } = await setup({ parameters: { type: 'string' } })
|
||||
await expect(client.listTools()).rejects.toThrow('The cua_run_code registration is not an MCP tool')
|
||||
})
|
||||
|
||||
it('refuses to serve when the Agent cannot be created', async () => {
|
||||
const { ctx, dispose } = fixture({ createFailures: 1 })
|
||||
await expect(createCuaMcpServer(ctx, { consent: 'allow', cwd: '/workspace', signal: new AbortController().signal }))
|
||||
.rejects.toThrow('registry refused the Agent')
|
||||
expect(dispose).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('lists no program tool without a registration, names the missing provider, and refuses every unlisted name before the executor', async () => {
|
||||
const { client, run, reset, execute, cancel } = await setup({ registered: false, programs: false, reference: false })
|
||||
expect((await client.listTools()).tools.map(tool => tool.name)).toEqual(['cua_get_api_reference', 'cua_reset'])
|
||||
const reference = await client.callTool({ name: 'cua_get_api_reference', arguments: {} })
|
||||
expect(reference.isError).toBe(true)
|
||||
expect(texts(reference).join('')).toContain('no active CUA provider')
|
||||
const unknown = await run({ code: '1', description: 'Probe' })
|
||||
expect(unknown.isError).toBe(true)
|
||||
expect(texts(unknown)).toEqual(['unknown tool "cua_run_code"'])
|
||||
const other = await client.callTool({ name: 'cua_other', arguments: {} })
|
||||
expect(other.isError).toBe(true)
|
||||
expect(texts(other)).toEqual(['unknown tool "cua_other"'])
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
const refused = await reset()
|
||||
expect(refused.isError).toBe(true)
|
||||
expect(texts(refused).join('')).toContain('no active CUA provider')
|
||||
expect(cancel).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('serves the API reference whenever asked, without running a program, waiting for one, or changing program results', async () => {
|
||||
const { client, run, reset, execute, runMaintenance, assemble, agent } = await setup()
|
||||
const reference = () => client.callTool({ name: 'cua_get_api_reference', arguments: {} })
|
||||
expect(await reference()).toEqual({ content: [{ type: 'text', text: '## cua API reference\n\nFixture guidance' }] })
|
||||
expect(assemble).toHaveBeenCalledWith({ scope: agent })
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
expect(runMaintenance).not.toHaveBeenCalled()
|
||||
expect(texts(await run({ code: '1', description: 'First' }))).toEqual(['program output'])
|
||||
await reset()
|
||||
expect(texts(await reference())).toEqual(['## cua API reference\n\nFixture guidance'])
|
||||
expect(texts(await run({ code: '2', description: 'Second' }))).toEqual(['program output'])
|
||||
// A running program does not delay the reference: the read is not queued behind it.
|
||||
const held = Promise.withResolvers<ToolBatchResult>()
|
||||
execute.mockReturnValueOnce(held.promise)
|
||||
const running = run({ code: '3', description: 'Held' })
|
||||
expect(texts(await reference())).toEqual(['## cua API reference\n\nFixture guidance'])
|
||||
held.resolve(batch('held output'))
|
||||
expect(texts(await running)).toEqual(['held output'])
|
||||
expect(execute).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('refuses a registered tool the listing does not carry', async () => {
|
||||
const { client, execute } = await setup()
|
||||
const other = await client.callTool({ name: 'cua_other', arguments: { sandbox_permissions: 'danger-full-access' } })
|
||||
expect(other.isError).toBe(true)
|
||||
expect(texts(other)).toEqual(['unknown tool "cua_other"'])
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('fails the call as a protocol error when the executor settles without a result', async () => {
|
||||
const { run, execute } = await setup()
|
||||
execute.mockResolvedValueOnce({ results: [], additionalContexts: [], concluded: false })
|
||||
await expect(run({ code: '2', description: 'Lost' })).rejects.toThrow('settled without a cua_run_code result')
|
||||
})
|
||||
|
||||
it('resets by cancelling the running program, releasing its environment, and answering after that program settled', async () => {
|
||||
const { run, reset, agent, cancel, release, whenIdle, execute } = await setup()
|
||||
const order: string[] = []
|
||||
cancel.mockImplementationOnce(() => { order.push('cancel') })
|
||||
release.mockImplementationOnce(async () => { order.push('release') })
|
||||
// The cancelled program takes this long to settle; the Agent is idle only afterwards.
|
||||
const settled = Promise.withResolvers<undefined>()
|
||||
onTestFinished(() => { settled.resolve(undefined) })
|
||||
whenIdle.mockImplementationOnce(async () => { order.push('wait for the cancelled program'); await settled.promise })
|
||||
let answered = false
|
||||
const pending = reset().then((result) => { answered = true; return result })
|
||||
await vi.waitFor(() => { expect(order).toEqual(['cancel', 'release', 'wait for the cancelled program']) })
|
||||
expect(cancel).toHaveBeenCalledExactlyOnceWith({ kind: 'user' }, { keepInbox: true })
|
||||
expect(release).toHaveBeenCalledExactlyOnceWith(agent)
|
||||
expect(answered).toBe(false)
|
||||
settled.resolve(undefined)
|
||||
expect(await pending).toEqual({ content: [{
|
||||
type: 'text',
|
||||
text: 'Program environment cleared: variables, imports, and application and window objects from earlier calls are gone. '
|
||||
+ 'Application access granted earlier still applies; select applications again with cua.getApp.',
|
||||
}] })
|
||||
// The Agent serves the next program: only its environment was replaced.
|
||||
expect(texts(await run({ code: '1', description: 'Fresh' }))).toEqual(['program output'])
|
||||
expect(execute.mock.calls[0]?.[0].agent).toBe(agent)
|
||||
})
|
||||
|
||||
it('reports a failed release, asks for another reset, and still waits for the cancelled program', async () => {
|
||||
const { reset, release, whenIdle } = await setup()
|
||||
release.mockRejectedValueOnce(new Error('the program process did not exit'))
|
||||
expect(await reset()).toEqual({ isError: true, content: [{
|
||||
type: 'text',
|
||||
text: 'Program environment reset failed: the program process did not exit. Call cua_reset again before running another program.',
|
||||
}] })
|
||||
release.mockRejectedValueOnce('opaque failure')
|
||||
expect(texts(await reset())).toEqual(['Program environment reset failed: opaque failure. Call cua_reset again before running another program.'])
|
||||
expect(whenIdle).toHaveBeenCalledTimes(2)
|
||||
expect((await reset()).isError).not.toBe(true)
|
||||
expect(release).toHaveBeenCalledTimes(3)
|
||||
})
|
||||
|
||||
it('shares one release between concurrent resets and holds back programs that arrive during it', async () => {
|
||||
const { run, reset, release, cancel, execute } = await setup()
|
||||
const released = Promise.withResolvers<undefined>()
|
||||
onTestFinished(() => { released.resolve(undefined) })
|
||||
release.mockImplementationOnce(() => released.promise)
|
||||
const resets = Promise.all([reset(), reset()])
|
||||
const program = run({ code: '1', description: 'Arrives during the reset' })
|
||||
await vi.waitFor(() => { expect(release).toHaveBeenCalledOnce() })
|
||||
// The runtime rejects a program while the previous process is still exiting, so the call has not reached it.
|
||||
expect(execute).not.toHaveBeenCalled()
|
||||
released.resolve(undefined)
|
||||
const [first, second] = await resets
|
||||
expect(first.isError).not.toBe(true)
|
||||
expect(second).toEqual(first)
|
||||
expect(texts(await program)).toEqual(['program output'])
|
||||
expect(release).toHaveBeenCalledOnce()
|
||||
expect(cancel).toHaveBeenCalledOnce()
|
||||
// A later reset is a release of its own.
|
||||
await reset()
|
||||
expect(release).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
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: brandString<SessionId>('other') } as Agent }, next)).toEqual({ answers: [] })
|
||||
expect(next).toHaveBeenCalledTimes(2)
|
||||
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 the Agent after the connection closes', async () => {
|
||||
const served = await setup()
|
||||
await served.client.close()
|
||||
await served.adapter.dispose()
|
||||
expect(served.dispose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('lets a reset in progress settle before disposing the Agent', async () => {
|
||||
const served = await setup()
|
||||
const released = Promise.withResolvers<undefined>()
|
||||
onTestFinished(() => { released.resolve(undefined) })
|
||||
served.release.mockImplementationOnce(() => released.promise)
|
||||
// The client's request ends with its connection; the server finishes the release regardless.
|
||||
const reset = served.reset().then(() => 'answered', () => 'connection closed')
|
||||
await vi.waitFor(() => { expect(served.release).toHaveBeenCalledOnce() })
|
||||
const disposed = served.adapter.dispose()
|
||||
expect(await reset).toBe('connection closed')
|
||||
expect(served.dispose).not.toHaveBeenCalled()
|
||||
released.resolve(undefined)
|
||||
await disposed
|
||||
expect(served.dispose).toHaveBeenCalledOnce()
|
||||
await served.client.close()
|
||||
})
|
||||
|
||||
it('disposes the Agent when closing the protocol server fails', async () => {
|
||||
const served = await setup()
|
||||
vi.spyOn(served.adapter.server, 'close').mockRejectedValueOnce(new Error('transport is broken'))
|
||||
await expect(served.adapter.dispose()).rejects.toThrow('transport is broken')
|
||||
expect(served.dispose).toHaveBeenCalledOnce()
|
||||
await served.client.close()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,201 @@
|
||||
/** The frontend parses its invocation and, only after readiness, creates the workspace and serves MCP. */
|
||||
import { EventEmitter } from 'node:events'
|
||||
import { existsSync } from 'node:fs'
|
||||
import { mkdtemp, rm, stat, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { Context } from '@deepseek-ai/cordis'
|
||||
import { internals, provideCmdline } from '@deepseek-ai/dsh-cmdline'
|
||||
import { Server } 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, type CuaMcpServer } from '../src/server.ts'
|
||||
|
||||
vi.mock('../src/server.ts', async original => ({
|
||||
...await original<typeof import('../src/server.ts')>(), createCuaMcpServer: vi.fn(),
|
||||
}))
|
||||
vi.mock('@modelcontextprotocol/server/stdio', () => ({ StdioServerTransport: vi.fn() }))
|
||||
|
||||
/** 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<void>)[] = []
|
||||
let connect: Mock<() => Promise<void>>
|
||||
let dispose: Mock<() => Promise<void>>
|
||||
/** The server every boot serves unless a test replaces one creation. */
|
||||
let served: CuaMcpServer
|
||||
/** Scratch directory of one test; the default workspace is a directory inside it that does not exist yet. */
|
||||
let scratch: string
|
||||
let workspace: string
|
||||
|
||||
beforeEach(async () => {
|
||||
scratch = await mkdtemp(join(tmpdir(), 'dsh-cua-mcp-startup-'))
|
||||
workspace = join(scratch, 'home', 'workspace')
|
||||
// oxlint-disable-next-line typescript/no-deprecated -- the frontend serves the SDK's low-level server.
|
||||
const server = new Server({ name: 'startup-fixture', version: '1' })
|
||||
closers.push(() => server.close())
|
||||
connect = vi.fn(async () => {})
|
||||
vi.spyOn(server, 'connect').mockImplementation(connect)
|
||||
dispose = vi.fn(() => server.close())
|
||||
served = { server, agent: {} as never, dispose }
|
||||
vi.mocked(createCuaMcpServer).mockResolvedValue(served)
|
||||
})
|
||||
|
||||
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
|
||||
await rm(scratch, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
/** Launcher facts of the profile; the launch directory is deliberately not the workspace. */
|
||||
const profileContext = {
|
||||
name: 'cua-mcp', dir: '/profiles/cua-mcp', patchPath: '/profiles/cua-mcp/cordis.patch.yml',
|
||||
installAnchor: '/dsh/package.json', cwd: '/launch', home: '/home/me/.dsh',
|
||||
startedBundles: ['@deepseek-ai/dsh-cua-mcp'], overlays: [], telemetryDisabledEnv: undefined,
|
||||
}
|
||||
|
||||
async function boot(args: string[], config: Partial<frontend.Config> = {}) {
|
||||
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', profileContext)
|
||||
await ctx.plugin(frontend, frontend.Config({ workspace, ...config }))
|
||||
return { ctx, exit, stdout, stderr, stdin, ready: () => {
|
||||
committed = true
|
||||
for (const listener of [...listeners]) listener()
|
||||
listeners.clear()
|
||||
} }
|
||||
}
|
||||
|
||||
describe('Computer Use MCP startup', () => {
|
||||
it('creates the workspace after readiness, then serves with the configured consent and joins disposal', async () => {
|
||||
let workspaceExistedAtCreation: boolean | undefined
|
||||
vi.mocked(createCuaMcpServer).mockImplementationOnce(async () => {
|
||||
workspaceExistedAtCreation = existsSync(workspace)
|
||||
return served
|
||||
})
|
||||
const { ctx, exit, ready, stdin } = await boot([], { consent: 'allow' })
|
||||
// Before readiness nothing is created: neither the workspace nor an Agent.
|
||||
expect(createCuaMcpServer).not.toHaveBeenCalled()
|
||||
expect(existsSync(workspace)).toBe(false)
|
||||
ready()
|
||||
await vi.waitFor(() => { expect(connect).toHaveBeenCalledOnce() })
|
||||
const options = vi.mocked(createCuaMcpServer).mock.calls[0]?.[1]
|
||||
if (options === undefined) throw new Error('the frontend did not construct a server')
|
||||
// The Agent works in the workspace, which exists before it, not in the directory the client launched the profile from.
|
||||
expect(options).toMatchObject({ consent: 'allow', cwd: workspace })
|
||||
expect(workspaceExistedAtCreation).toBe(true)
|
||||
expect((await stat(workspace)).isDirectory()).toBe(true)
|
||||
expect(StdioServerTransport).toHaveBeenCalledOnce()
|
||||
stdin.end()
|
||||
expect(exit).toHaveBeenCalledWith(0)
|
||||
await ctx.fiber.dispose()
|
||||
expect(options.signal.aborted).toBe(true)
|
||||
expect(dispose).toHaveBeenCalledOnce()
|
||||
})
|
||||
|
||||
it('rejects an unknown option and documents help without starting anything', async () => {
|
||||
const unknown = await boot(['--print-client-config', 'json'])
|
||||
expect(unknown.exit).toHaveBeenCalledWith(1)
|
||||
expect(unknown.stderr.join('')).toContain("unknown option '--print-client-config'")
|
||||
expect(unknown.stdout.join('')).toBe('')
|
||||
const help = await boot(['--help'])
|
||||
expect(help.stdout.join('')).toContain('Usage: dsh --profile cua-mcp [options]')
|
||||
expect(help.stdout.join('')).toContain('DSH_CUA_CONSENT=allow')
|
||||
expect(help.stdout.join('')).toContain('DSH_CUA_WORKSPACE=/work')
|
||||
expect(help.exit).toHaveBeenCalledWith(0)
|
||||
// Neither invocation serves, so readiness creates neither the workspace nor an Agent.
|
||||
unknown.ready()
|
||||
help.ready()
|
||||
expect(existsSync(workspace)).toBe(false)
|
||||
expect(createCuaMcpServer).not.toHaveBeenCalled()
|
||||
expect(StdioServerTransport).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports a relative or uncreatable workspace on stderr and exits with code 1 before any Agent exists', async () => {
|
||||
const relative = await boot([], { workspace: 'relative/workspace' })
|
||||
relative.ready()
|
||||
await vi.waitFor(() => { expect(relative.exit).toHaveBeenCalledWith(1) })
|
||||
expect(relative.stderr).toEqual([
|
||||
'dsh: MCP startup failed: the workspace "relative/workspace" is not an absolute directory path; set DSH_CUA_WORKSPACE to an absolute path\n',
|
||||
])
|
||||
// A file occupies the parent, so the directory cannot be created.
|
||||
await writeFile(join(scratch, 'occupied'), '')
|
||||
const occupied = join(scratch, 'occupied', 'workspace')
|
||||
const blocked = await boot([], { workspace: occupied })
|
||||
blocked.ready()
|
||||
await vi.waitFor(() => { expect(blocked.exit).toHaveBeenCalledWith(1) })
|
||||
expect(blocked.stderr).toHaveLength(1)
|
||||
expect(blocked.stderr[0]).toContain(`dsh: MCP startup failed: the workspace directory ${JSON.stringify(occupied)} cannot be created (Error: ENOTDIR`)
|
||||
expect(blocked.stderr[0]).toContain('set DSH_CUA_WORKSPACE to a writable location\n')
|
||||
expect(blocked.stdout).toEqual([])
|
||||
expect(createCuaMcpServer).not.toHaveBeenCalled()
|
||||
expect(connect).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('reports an Agent creation or transport startup failure on stderr through bounded exit, except during disposal', async () => {
|
||||
vi.mocked(createCuaMcpServer).mockRejectedValueOnce(new Error('registry refused the Agent'))
|
||||
const refused = await boot([])
|
||||
refused.ready()
|
||||
await vi.waitFor(() => { expect(refused.exit).toHaveBeenCalledWith(1) })
|
||||
expect(refused.stderr).toEqual(['dsh: MCP startup failed: registry refused the Agent\n'])
|
||||
expect(connect).not.toHaveBeenCalled()
|
||||
await refused.ctx.fiber.dispose()
|
||||
// A rejection that is not an Error is reported as its string form.
|
||||
connect.mockRejectedValueOnce('transport start failed')
|
||||
const failing = await boot([])
|
||||
failing.ready()
|
||||
await vi.waitFor(() => { expect(failing.exit).toHaveBeenCalledWith(1) })
|
||||
expect(failing.stderr).toEqual(['dsh: MCP startup failed: transport start failed\n'])
|
||||
// A transport that fails while the frontend is being disposed is not a startup failure.
|
||||
const opening = Promise.withResolvers<undefined>()
|
||||
connect.mockImplementationOnce(async () => { await opening.promise })
|
||||
const closing = await boot([])
|
||||
closing.ready()
|
||||
await vi.waitFor(() => { expect(connect).toHaveBeenCalledTimes(2) })
|
||||
const disposal = closing.ctx.fiber.dispose()
|
||||
opening.reject(new Error('transport released'))
|
||||
await disposal
|
||||
expect(closing.exit).not.toHaveBeenCalled()
|
||||
expect(closing.stderr).toEqual([])
|
||||
})
|
||||
|
||||
it('requires the profile launcher, a workspace, and a known consent mode', () => {
|
||||
const ctx = new Context()
|
||||
roots.push(ctx)
|
||||
provideCmdline(ctx, { args: [], exit: () => {}, ready: { onReady: () => () => {} } })
|
||||
expect(() => { frontend.apply(ctx, frontend.Config({ workspace })) }).toThrow('requires the dsh profile launcher')
|
||||
expect(frontend.Config({ workspace })).toEqual({ consent: 'elicit', workspace })
|
||||
expect(() => frontend.Config({})).toThrow()
|
||||
expect(() => frontend.Config({ workspace, consent: 'ask' as 'allow' })).toThrow()
|
||||
})
|
||||
})
|
||||
@@ -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"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -15,14 +15,14 @@
|
||||
en: 5db4d4fea25493b9
|
||||
zh: 65ab64fc24eb0d09
|
||||
/deepseek-ai-dsh-cua/use-this-package:
|
||||
en: bbb23504e4251095
|
||||
zh: 4ca645ba0e88b00b
|
||||
en: c59986e14b6cf9ad
|
||||
zh: 10c7f6acef208342
|
||||
/deepseek-ai-dsh-cua/use-this-package/permission-controls:
|
||||
en: 754ca69ec462325a
|
||||
zh: 440d76acf2666689
|
||||
/deepseek-ai-dsh-cua/understand-the-implementation:
|
||||
en: d2addba1374dac8a
|
||||
zh: fbec5f1010c5c0d1
|
||||
en: 9e755327bfdb71fa
|
||||
zh: 38e80a91e290800e
|
||||
/deepseek-ai-dsh-cua/further-exploration:
|
||||
en: c174fb5a00ea3681
|
||||
zh: 039340042676881d
|
||||
|
||||
@@ -45,7 +45,7 @@ Keyboard methods are available in the scopes a provider declares; the provider o
|
||||
|
||||
Connect PTC with `connectCua(() => tools.cua)` or supply a custom dispatcher to `createCuaApi(dispatch)`. Observation methods return their results to the program. Call `inspect(await app.getWindows())` to display a result, or pass a filtered value. `window.getScreenshot()` returns an `Image` whose `path` is readable by the program and whose `width` and `height` describe the stored pixels. Use `inspect("before", before, "after", after)` to display selected screenshots. Read the window ID from `window.windowId`.
|
||||
|
||||
`tools.cua` screenshot operations return `Image` in TypeScript programs. Host-side canonical screenshot results carry encoded image data and a durable `attachment` reference; the native renderer projects coordinate metadata and the image into model content. Capture requires an attachment store and a resolved model route declaring image input. Admission and storage failures reject the call.
|
||||
`tools.cua` screenshot operations return `Image` in TypeScript programs. Host-side canonical screenshot results carry encoded image data and a durable `attachment` reference; the native renderer projects coordinate metadata and the image into model content. Capture requires an attachment store and either a configured `screenshotTarget` or a resolved model route declaring image input. Admission and storage failures reject the call.
|
||||
|
||||
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.
|
||||
|
||||
@@ -101,7 +101,7 @@ Graceful connection closure waits for registered cleanup. Native cleanup refusal
|
||||
|
||||
`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. A base owner uses `agent/created`, `agent-preset/selected`, and Agent-owned scopes, including Agents already present when the provider loads. It replaces each tool and prompt pair synchronously by definition identity; unavailable program services withdraw only the program definition, leaving raw registrations intact. 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`. CUA registers an environment initializer on that runtime; it installs `cua` once per new process, including temporary escalated runs. Its owner depends only on the runtime and retains the registration while program-tool dependencies reload. Program tools are disposed and drained before the initializer unregisters and the runtime closes. 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`. CUA registers an environment initializer on that runtime; it installs `cua` once per new process, including temporary escalated runs. Its owner depends only on the runtime and retains the registration while program-tool dependencies reload. Program tools are disposed and drained before the initializer unregisters and the runtime closes. 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`: `release(agent)` is the runtime's owner release for that Agent, so its program process exits, a program that is still running fails as aborted, and the next program starts a fresh process whose initializer recreates `cua`, while application grants and native connections stay; the runtime rejects that Agent's programs until the release settles, so the caller holds them back; `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 Host-supplied request fields. [Native observations](src/native-observation.ts) decode private window reply fields before updating coordinates and returning public results. 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.
|
||||
|
||||
|
||||
@@ -45,7 +45,7 @@ kind: "package-reference"
|
||||
|
||||
通过 `connectCua(() => tools.cua)` 连接 PTC,或将自定义分派器传给 `createCuaApi(dispatch)`。观察方法返回结果供程序使用。需要展示时,调用 `inspect(await app.getWindows())` 或传入筛选后的值。`window.getScreenshot()` 返回 `Image`,其 `path` 指向程序可读取的附件文件,`width` 和 `height` 是图片的像素尺寸。使用 `inspect("操作前", before, "操作后", after)` 展示选中的截图,从 `window.windowId` 读取窗口 ID。
|
||||
|
||||
`tools.cua` 的截图操作在 TypeScript 程序中返回 `Image`。宿主侧的规范化截图结果包含编码图像数据与持久的 `attachment` 引用;原生渲染器将坐标元数据和图片投影为模型内容。截图前要求附件服务可用,并确认当前模型支持图片输入。图片接入或保存失败会拒绝调用。
|
||||
`tools.cua` 的截图操作在 TypeScript 程序中返回 `Image`。宿主侧的规范化截图结果包含编码图像数据与持久的 `attachment` 引用;原生渲染器将坐标元数据和图片投影为模型内容。截图前要求附件服务可用,且已配置 `screenshotTarget` 或当前模型路由声明图片输入。图片接入或保存失败会拒绝调用。
|
||||
|
||||
应用授权发生在启动、观察、截图和输入之前。会话许可按对话和应用身份持久化,重启 DSH 或关闭 Computer Use 后仍可复用,其他对话需要单独授权。长期许可要求平台提供可复用的应用身份。拒绝或撤销会关闭受影响的 Agent 连接,因此旧对象必须重新选择目标。取消、超时或重新连接后均不重放输入。
|
||||
|
||||
@@ -101,7 +101,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`,包括临时提权执行。初始化程序的所属作用域只依赖运行时,程序工具的依赖重载时仍保留这项注册。先销毁程序工具并等待其执行结束,再注销初始化程序并关闭运行时。工厂只绑定私有 `cua` 操作工具,保留嵌套策略检查、guard、日志、取消和截图交付。私有工具不会出现在模型可直接调用的工具列表中。
|
||||
`cua_run_code` 复用 PTC 程序工具工厂,由 CUA 提供方持有一个隔离的 Node 运行时。每个 Agent 通过自己的 `stateOwner` 选择独立的保留进程。CUA 在该运行时注册环境初始化程序,为每个新进程安装一次 `cua`,包括临时提权执行。初始化程序的所属作用域只依赖运行时,程序工具的依赖重载时仍保留这项注册。先销毁程序工具并等待其执行结束,再注销初始化程序并关闭运行时。工厂只绑定私有 `cua` 操作工具,保留嵌套策略检查、guard、日志、取消和截图交付。私有工具不会出现在模型可直接调用的工具列表中。该运行时存在期间,提供方发布 `ctx.cuaPrograms`:`release(agent)` 就是运行时对该 Agent 的 owner release,因此其程序进程退出,仍在运行的程序以中止失败,下一次程序在新进程中由初始化程序重新创建 `cua`,应用授权和本机连接则保留;释放结算之前运行时会拒绝该 Agent 的程序,因此由调用方把它们挡在后面;`screenshotRequestTarget(image)` 返回已配置的 `screenshotTarget` 为某张已存储截图选定的请求图片目标,使在模型请求之外转发截图的宿主交付程序观察到的那一版。
|
||||
|
||||
[操作 schema](src/protocol.ts) 定义模型参数,以及 Host 补充的请求字段。[原生观察](src/native-observation.ts) 解析窗口回复的私有字段,更新坐标记录后返回公开结果。原生实现在执行时检查目标身份、窗口几何、资源上限和操作系统访问条件。授权存储独立于原生协议保存持久许可。
|
||||
|
||||
|
||||
@@ -23,11 +23,26 @@ export const CuaStandaloneRunCodeConfig: Schema<Partial<CuaStandaloneRunCodeConf
|
||||
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<CuaScreenshotTargetConfig> = Schema.object({
|
||||
longEdge: Schema.number().step(1).min(1).max(16_384).required(),
|
||||
maxBytes: Schema.number().step(1).min(1024).required(),
|
||||
})
|
||||
|
||||
/** 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'),
|
||||
standaloneRunCode: CuaStandaloneRunCodeConfig.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),
|
||||
|
||||
@@ -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. 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.
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import Schema from '@deepseek-ai/schemastery'
|
||||
import type { Agent } from '@deepseek-ai/dsh-agent'
|
||||
import type { ComputerUseProviderName } from '@deepseek-ai/dsh-computer-use/types'
|
||||
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,8 +20,8 @@ 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 } from './protocol.ts'
|
||||
import { CuaConfigFields, type CuaStandaloneRunCodeConfig } from './config.ts'
|
||||
import { installCuaTools } from './tool-registration.ts'
|
||||
import { CuaConfigFields, type CuaScreenshotTargetConfig, type CuaStandaloneRunCodeConfig } from './config.ts'
|
||||
import { fixedScreenshotTarget, installCuaTools } from './tool-registration.ts'
|
||||
import { CuaCoordinates } from './coordinates.ts'
|
||||
import { observeNativeWindows } from './native-observation.ts'
|
||||
import type { ToolDefinition, ToolExecution } from '@deepseek-ai/dsh-tools'
|
||||
@@ -33,6 +33,7 @@ import { brandString } from '@deepseek-ai/dsh-brand'
|
||||
|
||||
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 {
|
||||
@@ -42,6 +43,11 @@ export interface CuaConfig {
|
||||
agentPreset: string | false
|
||||
/** Dedicated persistent program limits, independent of the profile's PTC runtime. */
|
||||
standaloneRunCode: CuaStandaloneRunCodeConfig
|
||||
/**
|
||||
* 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<Omit<CuaApplicationGrant, 'id'> & {
|
||||
/** Unbranded digest at the profile configuration boundary; admitted by the Config schema. */
|
||||
@@ -112,10 +118,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<CuaExecution>) {
|
||||
/** Resolve the attachment store and the request-image target before requesting a screenshot. */
|
||||
async function screenshotStore(ctx: Context, execution: Readonly<CuaExecution>, 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
|
||||
@@ -250,7 +259,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()
|
||||
|
||||
@@ -6,16 +6,60 @@ 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 type { ToolDefinition } from '@deepseek-ai/dsh-tools'
|
||||
import { longEdgeDimensions, type ImageAttachmentRef, type 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 type { CuaScreenshotTargetConfig } 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. '
|
||||
+ 'Use inspect(...values) to display selected text and images.'
|
||||
|
||||
/** Host control over the dedicated `cua_run_code` environments; registered as `ctx.cuaPrograms`. */
|
||||
export interface CuaPrograms {
|
||||
/**
|
||||
* Release one Agent's retained program environment with the dedicated runtime's owner release. The program
|
||||
* process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code`
|
||||
* call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native
|
||||
* connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent's
|
||||
* programs until the release settles, so the caller holds them back; after a failed release it rejects them
|
||||
* until a later release succeeds. Resolves when no environment exists.
|
||||
* @param agent - Agent whose `cua_run_code` state owner is released.
|
||||
* @returns Completion after the process has exited and its output has drained.
|
||||
* @throws When the process cleanup fails.
|
||||
*/
|
||||
release(agent: Agent): Promise<void>
|
||||
/**
|
||||
* 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
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 }
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
@@ -31,7 +75,7 @@ export function installCuaTools(
|
||||
// PTC publishes the installed JS entry; automatic CUA initialization follows the Host's code format.
|
||||
const ptcBridgeUrl = JSON.stringify(new URL('../lib/bridge.js', import.meta.url).href)
|
||||
const programBridgeUrl = JSON.stringify(new URL(`./bridge${extname(new URL(import.meta.url).pathname)}`, 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}
|
||||
@@ -101,6 +145,12 @@ var cua = connectCua(() => tools.cua);
|
||||
name: 'cua_run_code', description: programDescription, runtime: consumer.ptcRuntime,
|
||||
tools: [tool], limits: config.standaloneRunCode.executor,
|
||||
})
|
||||
// Hosts without a model (MCP frontends) end an Agent's environment with the runtime's owner release.
|
||||
consumer.provide('cuaPrograms', {
|
||||
release: (agent: Agent) => consumer.ptcRuntime.release(agent),
|
||||
screenshotRequestTarget: image => config.screenshotTarget === undefined
|
||||
? undefined : fixedScreenshotTarget(config.screenshotTarget, image),
|
||||
} satisfies CuaPrograms)
|
||||
consumer.effect(function* () {
|
||||
yield () => {
|
||||
if (program !== definition) return
|
||||
|
||||
@@ -91,7 +91,13 @@ 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 program service lives with the dedicated runtime and leaves with the provider; an Agent without an
|
||||
// environment has nothing to release.
|
||||
await expect(ctx.get('cuaPrograms')?.release(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 () => {
|
||||
@@ -100,6 +106,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()
|
||||
})
|
||||
|
||||
@@ -40,11 +40,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<number, Promise<void>>()
|
||||
constructor(private readonly programs: readonly string[]) { super() }
|
||||
override resolveModel(provider: string, model: string): Promise<LlmResolvedModelInfo> {
|
||||
return Promise.resolve({ provider, id: model, name: model, inputModalities: ['text', 'image'] })
|
||||
}
|
||||
async * stream(options: GenerateOptions): AsyncIterable<StreamChunk> {
|
||||
await this.gates.get(this.requests.length)
|
||||
const code = this.programs[this.requests.length]
|
||||
this.requests.push(options)
|
||||
if (code !== undefined) {
|
||||
@@ -186,6 +189,65 @@ it('retains CUA objects, guards and logs hidden subcalls, forwards screenshots,
|
||||
expect(ctx.ptcRuntime.retainsState).toBe(false)
|
||||
})
|
||||
|
||||
it('releases 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"); inspect(process.pid)',
|
||||
'inspect(JSON.stringify(typeof win === "undefined" ? { fresh: true, visits: globalThis.visits ?? null, pid: process.pid } : { fresh: false, pid: process.pid }))',
|
||||
])
|
||||
const programs = ctx.get('cuaPrograms')
|
||||
if (programs === undefined) throw new Error('CUA provider did not publish ctx.cuaPrograms')
|
||||
// The caller holds the next program back until the release has settled: the second model request waits for it.
|
||||
const firstSettled: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
const released: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
model.gates.set(1, released.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.release(agent)
|
||||
released.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<string, unknown>
|
||||
const firstPid = z.number().int().positive().parse(text(0))
|
||||
const second = text(1)
|
||||
expect(second).toMatchObject({ fresh: 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.release(agent)).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('fails a running program as aborted when its environment is released and starts the next program fresh', async () => {
|
||||
const { ctx, native, model, agent, run } = await setup([
|
||||
'globalThis.visits = 1; var app = await cua.getApp("test.fixture"); await new Promise(() => {})',
|
||||
'inspect(JSON.stringify({ visits: globalThis.visits ?? null, hasApp: typeof app !== "undefined" }))',
|
||||
])
|
||||
const programs = ctx.get('cuaPrograms')
|
||||
if (programs === undefined) throw new Error('CUA provider did not publish ctx.cuaPrograms')
|
||||
const released: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
model.gates.set(1, released.promise)
|
||||
// The first program is running inside its environment once its application selection has settled.
|
||||
const selected: PromiseWithResolvers<void> = Promise.withResolvers()
|
||||
ctx.on('session/event', (session, event) => {
|
||||
if (session === agent.session && event.type === 'tool/ptc-dispatch' && event.data.rootCallId === 'cua-program-1') selected.resolve()
|
||||
})
|
||||
const completed = run()
|
||||
await selected.promise
|
||||
await programs.release(agent)
|
||||
released.resolve()
|
||||
await completed
|
||||
const results = agent.session.deriveMessages().filter(message => message.role === 'tool')
|
||||
const text = (index: number) => results[index]!.content.filter(block => block.type === 'text').map(block => block.text).join('\n')
|
||||
expect(results.map(result => result.isError)).toEqual([true, false])
|
||||
expect(text(0)).toContain('code run failed (abort)')
|
||||
expect(JSON.parse(text(1))).toEqual({ visits: null, hasApp: false })
|
||||
expect(native.state).toMatchObject({ openedChannels: 1, closedChannels: 0 })
|
||||
})
|
||||
|
||||
it('recreates the automatic facade when its environment is rebuilt', async () => {
|
||||
const { agent, run } = await setup([
|
||||
'var previousCua = cua; inspect("created")',
|
||||
|
||||
@@ -371,7 +371,12 @@ describe('experimental Inspector real Worker', () => {
|
||||
})
|
||||
|
||||
it('cancels Client Runtime work when the Worker deadline expires', async () => {
|
||||
inspector = await startInspector({ port: 0, captureFetch: false, clientRuntimeTimeoutMs: 20 })
|
||||
// The follow-up evaluation shares this deadline, so it must exceed one real
|
||||
// Client Runtime round trip under concurrent CI load and stay below
|
||||
// CDP_CALL_TIMEOUT_MS and the 5 s default test budget. The never-settling
|
||||
// promise makes the deadline fire regardless of its value.
|
||||
const deadlineMs = 1_000
|
||||
inspector = await startInspector({ port: 0, captureFetch: false, clientRuntimeTimeoutMs: deadlineMs })
|
||||
client = await InspectorClientFixture.start(inspector.endpoint.client, { label: 'Timeout Client' })
|
||||
cdp = await TestCdpClient.connect(inspector.endpoint.webSocketDebuggerUrl)
|
||||
await cdp.call('Runtime.enable')
|
||||
@@ -382,7 +387,7 @@ describe('experimental Inspector real Worker', () => {
|
||||
contextId,
|
||||
awaitPromise: true,
|
||||
})
|
||||
expect(timedOut.error?.message).toContain('timed out after 20ms')
|
||||
expect(timedOut.error?.message).toContain(`timed out after ${String(deadlineMs)}ms`)
|
||||
expect((await cdp.call('Runtime.evaluate', {
|
||||
expression: '42',
|
||||
contextId,
|
||||
|
||||
@@ -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: 'release(agent: Agent): Promise<void>',
|
||||
description: 'Release one Agent\'s retained program environment with the dedicated runtime\'s owner release. The program process exits, a program of that Agent that is still running fails as aborted, and the next `cua_run_code` call starts a fresh process that re-creates the `cua` global. The Agent, its application grants and native connection, and the desktop applications themselves are unaffected. The runtime rejects that Agent\'s programs until the release settles, so the caller holds them back; after a failed release it rejects them until a later release succeeds. Resolves when no environment exists.',
|
||||
parameters: [{ name: 'agent', description: 'Agent whose `cua_run_code` state owner is released.' }],
|
||||
returns: 'Completion after the process has exited and its output has drained.',
|
||||
throws: ['When the process cleanup fails.'],
|
||||
},
|
||||
{
|
||||
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.',
|
||||
|
||||
@@ -200,6 +200,7 @@ Every package below exports a Cordis plugin that a bundle patch can name in a Lo
|
||||
| `@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-macos` | yes | macOS native provider for shared Computer Use application and window objects |
|
||||
| `@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-cua-windows` | yes | Windows C# computer use through shared application and window objects |
|
||||
| `@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 |
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -18,7 +18,8 @@ export const PROTECTED_PLUGINS: ReadonlySet<string> = 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<string> = new Set([
|
||||
@@ -30,6 +31,7 @@ export const HIDDEN_BUNDLES: ReadonlySet<string> = 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<string> = 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',
|
||||
|
||||
Generated
+128
@@ -348,6 +348,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
|
||||
@@ -10370,6 +10373,131 @@ importers:
|
||||
specifier: ^0.35.3
|
||||
version: 0.35.5(@types/[email protected])
|
||||
|
||||
packages/experimental/cua-mcp:
|
||||
dependencies:
|
||||
'@deepseek-ai/dsh-agent':
|
||||
specifier: workspace:*
|
||||
version: link:../../core/agent
|
||||
'@deepseek-ai/dsh-agent-loop':
|
||||
specifier: workspace:*
|
||||
version: link:../../core/agent-loop
|
||||
'@deepseek-ai/dsh-agent-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-attachment-local':
|
||||
specifier: workspace:*
|
||||
version: link:../../attachment/attachment-local
|
||||
'@deepseek-ai/dsh-brand':
|
||||
specifier: workspace:*
|
||||
version: link:../../util/brand
|
||||
'@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-fs-sandbox':
|
||||
specifier: workspace:*
|
||||
version: link:../../fs/fs-sandbox
|
||||
'@deepseek-ai/dsh-llm':
|
||||
specifier: workspace:*
|
||||
version: link:../../llm/llm
|
||||
'@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':
|
||||
specifier: workspace:*
|
||||
version: link:../../core/session
|
||||
'@deepseek-ai/dsh-session-persistence-jsonl':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/session-persistence-jsonl
|
||||
'@deepseek-ai/dsh-session-projection':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/session-projection
|
||||
'@deepseek-ai/dsh-storage':
|
||||
specifier: workspace:*
|
||||
version: link:../../storage/storage
|
||||
'@deepseek-ai/dsh-storage-domain':
|
||||
specifier: workspace:*
|
||||
version: link:../../storage/storage-domain
|
||||
'@deepseek-ai/dsh-storage-json':
|
||||
specifier: workspace:*
|
||||
version: link:../../storage/storage-json
|
||||
'@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-user-approval':
|
||||
specifier: workspace:*
|
||||
version: link:../../interaction/user-approval
|
||||
'@deepseek-ai/dsh-user-questions':
|
||||
specifier: workspace:*
|
||||
version: link:../../interaction/user-questions
|
||||
'@deepseek-ai/dsh-working-directory':
|
||||
specifier: workspace:*
|
||||
version: link:../../session/working-directory
|
||||
'@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
|
||||
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-app-boot':
|
||||
specifier: workspace:*
|
||||
version: link:../../boot/app-boot
|
||||
'@deepseek-ai/dsh-attachment':
|
||||
specifier: workspace:*
|
||||
version: link:../../attachment/attachment
|
||||
'@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
|
||||
'@modelcontextprotocol/client':
|
||||
specifier: 2.2.0
|
||||
version: 2.2.0
|
||||
js-yaml:
|
||||
specifier: ^4.3.2
|
||||
version: 4.3.2
|
||||
optionalDependencies:
|
||||
'@deepseek-ai/dsh-cua-macos':
|
||||
specifier: workspace:*
|
||||
version: link:../cua-macos
|
||||
'@deepseek-ai/dsh-cua-windows':
|
||||
specifier: workspace:*
|
||||
version: link:../cua-windows
|
||||
|
||||
packages/experimental/cua-windows:
|
||||
dependencies:
|
||||
'@deepseek-ai/dsh-atomic-write':
|
||||
|
||||
@@ -108,7 +108,11 @@ describe('Node compatibility self-hosted routing', () => {
|
||||
)
|
||||
}
|
||||
expect(job.steps[0]?.with).toEqual({ 'persist-credentials': false })
|
||||
expect(job.steps.some(step => step.uses?.startsWith('actions/cache/'))).toBe(false)
|
||||
// The verified bubblewrap archive is the one remote cache this job restores
|
||||
// and saves; it must stay excluded from the persistent self-hosted pool.
|
||||
const remoteCaches = job.steps.filter(step => step.uses?.startsWith('actions/cache/'))
|
||||
expect(remoteCaches.length).toBeGreaterThan(0)
|
||||
for (const step of remoteCaches) expect(step.if).toContain("vars.DSH_CI_FAILOVER_LINUX != 'selfhosted'")
|
||||
})
|
||||
|
||||
it('overrides runner exports inside setup-node without affecting later Node processes', () => {
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
# shellcheck shell=bash
|
||||
# Sourced by CI preparation scripts; defines functions only.
|
||||
|
||||
# Prints the SHA-256 digest of <file>.
|
||||
#
|
||||
# CI runners do not all provide the same tool: GNU coreutils ships `sha256sum`,
|
||||
# while macOS ships `shasum -a 256`. Probing both keeps a missing tool from
|
||||
# being reported as a digest mismatch, which would discard a verified cached
|
||||
# archive and send the next run back to a possibly unavailable download host.
|
||||
sha256_digest() {
|
||||
local output
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
output="$(sha256sum < "$1")"
|
||||
elif command -v shasum >/dev/null 2>&1; then
|
||||
output="$(shasum -a 256 < "$1")"
|
||||
else
|
||||
echo 'No SHA-256 tool found: need sha256sum or shasum -a 256' >&2
|
||||
return 2
|
||||
fi
|
||||
printf '%s\n' "${output%% *}"
|
||||
}
|
||||
|
||||
# Succeeds when <file> has the SHA-256 digest <sha256>. Returns 2, reporting the
|
||||
# missing tool on stderr, when neither digest tool exists.
|
||||
#
|
||||
# Usage: verified_sha256 <sha256> <file>
|
||||
verified_sha256() {
|
||||
local actual status=0
|
||||
actual="$(sha256_digest "$2")" || status=$?
|
||||
if (( status != 0 )); then
|
||||
return "$status"
|
||||
fi
|
||||
[[ "$actual" == "$1" ]]
|
||||
}
|
||||
|
||||
# Leaves a copy of <url> whose SHA-256 digest is <sha256> at <cache-file>.
|
||||
#
|
||||
# A cached file with the expected digest is used without network access, so a
|
||||
# restored Actions cache keeps CI independent of the download host. A cached
|
||||
# file with any other digest is discarded. A download is verified before it
|
||||
# replaces <cache-file> atomically, so the cache only ever holds a verified
|
||||
# payload. A failed download or verification leaves nothing at <cache-file> and
|
||||
# reports the URL on stderr. A missing SHA-256 tool returns 2 instead of
|
||||
# treating the payload as mismatched. Each attempt is bounded so a stalled host
|
||||
# fails within minutes.
|
||||
#
|
||||
# Usage: acquire_verified_archive <url> <sha256> <cache-file>
|
||||
acquire_verified_archive() {
|
||||
local url="$1" sha256="$2" cache_file="$3" cache_dir
|
||||
cache_dir="$(dirname -- "$cache_file")"
|
||||
|
||||
# Probe before the network work: a runner without a digest tool must fail
|
||||
# immediately instead of downloading a payload it cannot verify.
|
||||
sha256_digest /dev/null >/dev/null
|
||||
|
||||
if [[ -f "$cache_file" ]]; then
|
||||
local cache_status=0
|
||||
verified_sha256 "$sha256" "$cache_file" || cache_status=$?
|
||||
if (( cache_status == 0 )); then
|
||||
echo "Using verified cached archive $cache_file"
|
||||
return 0
|
||||
fi
|
||||
if (( cache_status != 1 )); then
|
||||
return "$cache_status"
|
||||
fi
|
||||
echo "Discarding cached archive $cache_file: SHA-256 mismatch" >&2
|
||||
rm -f -- "$cache_file"
|
||||
fi
|
||||
|
||||
if ! mkdir -p -- "$cache_dir"; then
|
||||
echo "Failed to create $cache_dir while preparing $url" >&2
|
||||
return 1
|
||||
fi
|
||||
local partial
|
||||
if ! partial="$(mktemp "${cache_file}.partial.XXXXXX")"; then
|
||||
echo "Failed to create a temporary file in $cache_dir while preparing $url" >&2
|
||||
return 1
|
||||
fi
|
||||
# A cancelled job must not leave a partial payload in the directory that
|
||||
# actions/cache/save uploads.
|
||||
trap 'rm -f -- "$partial"' EXIT
|
||||
|
||||
if ! curl --fail --silent --show-error --location \
|
||||
--connect-timeout 15 --max-time 60 \
|
||||
--retry 8 --retry-all-errors --retry-max-time 240 \
|
||||
--output "$partial" "$url"; then
|
||||
rm -f -- "$partial"
|
||||
trap - EXIT
|
||||
echo "Failed to download $url and no verified cached copy exists at $cache_file" >&2
|
||||
return 1
|
||||
fi
|
||||
local download_status=0
|
||||
verified_sha256 "$sha256" "$partial" || download_status=$?
|
||||
if (( download_status != 0 )); then
|
||||
rm -f -- "$partial"
|
||||
trap - EXIT
|
||||
if (( download_status != 1 )); then
|
||||
return "$download_status"
|
||||
fi
|
||||
echo "Downloaded $url does not have SHA-256 $sha256" >&2
|
||||
return 1
|
||||
fi
|
||||
mv -f -- "$partial" "$cache_file"
|
||||
trap - EXIT
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
import { spawnSync } from 'node:child_process'
|
||||
import { createHash } from 'node:crypto'
|
||||
import {
|
||||
chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, symlinkSync, writeFileSync,
|
||||
} from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { delimiter, join, resolve } from 'node:path'
|
||||
import { afterEach, describe, expect, it } from 'vitest'
|
||||
|
||||
const library = resolve(import.meta.dirname, 'ci-verified-download.sh')
|
||||
const url = 'https://downloads.invalid/payload.deb'
|
||||
const payload = Buffer.from('verified payload\n')
|
||||
const payloadSha256 = createHash('sha256').update(payload).digest('hex')
|
||||
const bash = ['/bin/bash', '/usr/bin/bash'].find(candidate => existsSync(candidate)) ?? 'bash'
|
||||
|
||||
// Records each invocation, then copies FAKE_CURL_SOURCE to the --output path
|
||||
// or fails as curl does for an HTTP error when no source is configured.
|
||||
const fakeCurl = `#!/usr/bin/env bash
|
||||
printf '%s\\n' "$*" >> "$FAKE_CURL_LOG"
|
||||
output=''
|
||||
while (( $# > 0 )); do
|
||||
if [[ "$1" == --output ]]; then output="$2"; shift; fi
|
||||
shift
|
||||
done
|
||||
if [[ -z "\${FAKE_CURL_SOURCE:-}" ]]; then
|
||||
echo 'curl: (22) The requested URL returned error: 503' >&2
|
||||
exit 22
|
||||
fi
|
||||
cp "$FAKE_CURL_SOURCE" "$output"
|
||||
`
|
||||
|
||||
interface Fixture {
|
||||
readonly root: string
|
||||
readonly cacheDir: string
|
||||
readonly cacheFile: string
|
||||
readonly curlLog: string
|
||||
readonly env: NodeJS.ProcessEnv
|
||||
}
|
||||
|
||||
const fixtureRoots: string[] = []
|
||||
|
||||
afterEach(() => {
|
||||
for (const root of fixtureRoots.splice(0)) rmSync(root, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
function createFixture(served?: Buffer): Fixture {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dsh-ci-verified-download-'))
|
||||
fixtureRoots.push(root)
|
||||
const bin = join(root, 'bin')
|
||||
mkdirSync(bin)
|
||||
writeFileSync(join(bin, 'curl'), fakeCurl)
|
||||
chmodSync(join(bin, 'curl'), 0o755)
|
||||
const curlLog = join(root, 'curl.log')
|
||||
writeFileSync(curlLog, '')
|
||||
const env: NodeJS.ProcessEnv = { ...process.env, PATH: bin + delimiter + (process.env.PATH ?? ''), FAKE_CURL_LOG: curlLog }
|
||||
delete env.FAKE_CURL_SOURCE
|
||||
if (served !== undefined) {
|
||||
const source = join(root, 'served.deb')
|
||||
writeFileSync(source, served)
|
||||
env.FAKE_CURL_SOURCE = source
|
||||
}
|
||||
const cacheDir = join(root, 'cache', 'bubblewrap')
|
||||
return { root, cacheDir, cacheFile: join(cacheDir, 'payload.deb'), curlLog, env }
|
||||
}
|
||||
|
||||
interface AcquireResult {
|
||||
readonly status: number | null
|
||||
readonly signal: NodeJS.Signals | null
|
||||
readonly stderr: string
|
||||
}
|
||||
|
||||
function acquire(fixture: Fixture, env: NodeJS.ProcessEnv = fixture.env): AcquireResult {
|
||||
const result = spawnSync(
|
||||
bash,
|
||||
['-c', 'set -euo pipefail; source "$1"; acquire_verified_archive "$2" "$3" "$4"', 'acquire', library, url, payloadSha256, fixture.cacheFile],
|
||||
{ encoding: 'utf8', env, timeout: 30_000 },
|
||||
)
|
||||
return { status: result.status, signal: result.signal, stderr: result.stderr }
|
||||
}
|
||||
|
||||
function curlCalls(fixture: Fixture): string[] {
|
||||
return readFileSync(fixture.curlLog, 'utf8').split('\n').filter(line => line !== '')
|
||||
}
|
||||
|
||||
function seedCache(fixture: Fixture, content: Buffer): void {
|
||||
mkdirSync(fixture.cacheDir, { recursive: true })
|
||||
writeFileSync(fixture.cacheFile, content)
|
||||
}
|
||||
|
||||
// Builds a PATH that reaches only the named executables plus the fixture's fake
|
||||
// curl, so a child can run on a host that provides a SHA-256 tool but see none.
|
||||
function restrictedPath(fixture: Fixture, names: readonly string[]): string {
|
||||
const bin = join(fixture.root, 'restricted-bin')
|
||||
mkdirSync(bin, { recursive: true })
|
||||
for (const name of names) {
|
||||
const resolved = spawnSync('sh', ['-c', `command -v ${name}`], { encoding: 'utf8' }).stdout.trim()
|
||||
if (resolved === '') throw new Error(`the test host does not provide ${name}`)
|
||||
symlinkSync(resolved, join(bin, name))
|
||||
}
|
||||
return [bin, join(fixture.root, 'bin')].join(delimiter)
|
||||
}
|
||||
|
||||
function hasDigestTool(): boolean {
|
||||
return spawnSync('sh', ['-c', 'command -v sha256sum || command -v shasum'], { stdio: 'ignore' }).status === 0
|
||||
}
|
||||
|
||||
// The library targets Linux CI runners; the suite needs bash and a SHA-256 tool
|
||||
// (sha256sum or shasum -a 256) and skips elsewhere.
|
||||
describe.skipIf(process.platform === 'win32' || !hasDigestTool())('acquire_verified_archive', () => {
|
||||
it('uses a verified cached archive without contacting the download host', () => {
|
||||
const fixture = createFixture()
|
||||
seedCache(fixture, payload)
|
||||
|
||||
const result = acquire(fixture)
|
||||
|
||||
expect(result.signal).toBeNull()
|
||||
expect(result.status).toBe(0)
|
||||
expect(curlCalls(fixture)).toEqual([])
|
||||
expect(readFileSync(fixture.cacheFile)).toEqual(payload)
|
||||
})
|
||||
|
||||
it('fails with the URL when the download fails and no cached archive exists', () => {
|
||||
const fixture = createFixture()
|
||||
|
||||
const result = acquire(fixture)
|
||||
|
||||
expect(result.signal).toBeNull()
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stderr).toContain(`Failed to download ${url} and no verified cached copy exists at ${fixture.cacheFile}`)
|
||||
expect(curlCalls(fixture)).toHaveLength(1)
|
||||
expect(readdirSync(fixture.cacheDir)).toEqual([])
|
||||
})
|
||||
|
||||
it('bounds every download attempt and the retry window', () => {
|
||||
const fixture = createFixture(payload)
|
||||
|
||||
expect(acquire(fixture).status).toBe(0)
|
||||
|
||||
const [call] = curlCalls(fixture)
|
||||
expect(call).toContain('--connect-timeout 15 ')
|
||||
expect(call).toContain('--max-time 60 ')
|
||||
expect(call).toContain('--retry 8 ')
|
||||
// The last attempt may still run for its full --max-time, so the bounded
|
||||
// failure time is this window plus 60 seconds.
|
||||
expect(call).toContain('--retry-max-time 240 ')
|
||||
expect(call).toContain(url)
|
||||
})
|
||||
|
||||
it('fails immediately and reports the missing tool instead of a digest mismatch', () => {
|
||||
const fixture = createFixture(payload)
|
||||
const env = { ...fixture.env, PATH: restrictedPath(fixture, ['bash', 'dirname', 'mkdir', 'mktemp', 'mv', 'rm']) }
|
||||
|
||||
const result = acquire(fixture, env)
|
||||
|
||||
expect(result.signal).toBeNull()
|
||||
expect(result.status).toBe(2)
|
||||
expect(result.stderr).toContain('No SHA-256 tool found')
|
||||
expect(curlCalls(fixture)).toEqual([])
|
||||
expect(existsSync(fixture.cacheFile)).toBe(false)
|
||||
})
|
||||
|
||||
it('replaces a cached archive whose digest does not match with a verified download', () => {
|
||||
const fixture = createFixture(payload)
|
||||
seedCache(fixture, Buffer.from('corrupted payload\n'))
|
||||
|
||||
const result = acquire(fixture)
|
||||
|
||||
expect(result.signal).toBeNull()
|
||||
expect(result.status).toBe(0)
|
||||
expect(result.stderr).toContain('SHA-256 mismatch')
|
||||
expect(curlCalls(fixture)).toHaveLength(1)
|
||||
expect(readdirSync(fixture.cacheDir)).toEqual(['payload.deb'])
|
||||
expect(readFileSync(fixture.cacheFile)).toEqual(payload)
|
||||
})
|
||||
|
||||
it('rejects a downloaded archive whose digest does not match without caching it', () => {
|
||||
const fixture = createFixture(Buffer.from('tampered payload\n'))
|
||||
|
||||
const result = acquire(fixture)
|
||||
|
||||
expect(result.signal).toBeNull()
|
||||
expect(result.status).toBe(1)
|
||||
expect(result.stderr).toContain(`Downloaded ${url} does not have SHA-256 ${payloadSha256}`)
|
||||
expect(existsSync(fixture.cacheFile)).toBe(false)
|
||||
expect(readdirSync(fixture.cacheDir)).toEqual([])
|
||||
})
|
||||
})
|
||||
@@ -1112,6 +1112,76 @@ describe('bubblewrap preparation script', () => {
|
||||
// Ubuntu removes superseded versions from its live package pool.
|
||||
expect(script).not.toMatch(/https?:\/\/[^/'"\s]+\/ubuntu(?:-ports)?\/pool\//u)
|
||||
})
|
||||
|
||||
it('verifies the archive against the pinned digest', () => {
|
||||
const script = readFileSync(resolve(root, 'scripts/prepare-ci-bubblewrap.sh'), 'utf8')
|
||||
|
||||
expect(script).toMatch(/^readonly BUBBLEWRAP_SHA256='[0-9a-f]{64}'$/mu)
|
||||
expect(script).toContain('acquire_verified_archive "$BUBBLEWRAP_URL" "$BUBBLEWRAP_SHA256" "$archive"')
|
||||
})
|
||||
|
||||
// Ephemeral runners share a `~` layout: GitHub-hosted runners and Blacksmith
|
||||
// (whose runners register as self-hosted but keep /home/runner as HOME). The
|
||||
// in-house `vm-backup` pool keeps `~/.cache` on a different, persistent
|
||||
// layout, so lanes that can select it must not restore or save this cache.
|
||||
// `ci-master.yml` prepares bubblewrap only on lanes that can select the
|
||||
// persistent runners, and the manual benchmark matrix includes their 64/96-core
|
||||
// rows, so neither carries cache steps.
|
||||
const hostedOnly = "vars.DSH_CI_FAILOVER_LINUX != 'selfhosted' || github.event.pull_request.user.login == 'dependabot[bot]'"
|
||||
const cachedJobs = new Map<string, string | undefined>([
|
||||
['ci.yml:node-24-coverage', hostedOnly],
|
||||
['ci.yml:node-24-consumers', hostedOnly],
|
||||
['ci.yml:node-compat', hostedOnly],
|
||||
['e2e.yml:e2e', undefined],
|
||||
])
|
||||
|
||||
it.each(['ci.yml', 'ci-master.yml', 'e2e.yml'])(
|
||||
'%s caches the verified archive only on the lanes that run on ephemeral runners',
|
||||
(name) => {
|
||||
const script = readFileSync(resolve(root, 'scripts/prepare-ci-bubblewrap.sh'), 'utf8')
|
||||
expect(script).toContain('readonly BUBBLEWRAP_CACHE_DIR="${HOME}/.cache/dsh-ci/bubblewrap"')
|
||||
const cache = {
|
||||
path: '~/.cache/dsh-ci/bubblewrap',
|
||||
key: "bubblewrap-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('scripts/prepare-ci-bubblewrap.sh') }}",
|
||||
}
|
||||
const workflow = loadWorkflow('.github/workflows/' + name)
|
||||
if (!isRecord(workflow.jobs)) throw new TypeError(`${name} must define jobs`)
|
||||
|
||||
let preparations = 0
|
||||
for (const [jobName, job] of Object.entries(workflow.jobs)) {
|
||||
if (!isRecord(job) || !Array.isArray(job.steps)) continue
|
||||
const steps = job.steps.filter(isRecord)
|
||||
const preparation = steps.findIndex(step =>
|
||||
typeof step.run === 'string' && step.run.includes('bash scripts/prepare-ci-bubblewrap.sh'))
|
||||
if (preparation < 0) continue
|
||||
preparations += 1
|
||||
const key = `${name}:${jobName}`
|
||||
if (!cachedJobs.has(key)) {
|
||||
expect(
|
||||
steps.filter(step => typeof step.uses === 'string' && step.uses.startsWith('actions/cache/')),
|
||||
key,
|
||||
).toEqual([])
|
||||
continue
|
||||
}
|
||||
const guard = cachedJobs.get(key)
|
||||
const cacheHit = "steps.bubblewrap-cache.outputs.cache-hit != 'true'"
|
||||
expect(steps[preparation - 1]).toEqual({
|
||||
name: 'Restore verified bubblewrap archive',
|
||||
id: 'bubblewrap-cache',
|
||||
...(guard === undefined ? {} : { if: guard }),
|
||||
uses: 'actions/cache/[email protected]',
|
||||
with: cache,
|
||||
})
|
||||
expect(steps[preparation + 1]).toEqual({
|
||||
name: 'Save verified bubblewrap archive',
|
||||
if: guard === undefined ? cacheHit : `(${guard}) && ${cacheHit}`,
|
||||
uses: 'actions/cache/[email protected]',
|
||||
with: cache,
|
||||
})
|
||||
}
|
||||
expect(preparations).toBeGreaterThan(0)
|
||||
},
|
||||
)
|
||||
})
|
||||
|
||||
describe('DeepSeek e2e workflow', () => {
|
||||
|
||||
@@ -9,6 +9,7 @@ export const EXPERIMENTAL_PACKAGE_NAME_EXCEPTIONS: Readonly<Record<string, strin
|
||||
'packages/experimental/cua': '@deepseek-ai/dsh-cua',
|
||||
'packages/experimental/cua-bundle': '@deepseek-ai/dsh-cua-bundle',
|
||||
'packages/experimental/cua-macos': '@deepseek-ai/dsh-cua-macos',
|
||||
'packages/experimental/cua-mcp': '@deepseek-ai/dsh-cua-mcp',
|
||||
'packages/experimental/cua-windows': '@deepseek-ai/dsh-cua-windows',
|
||||
'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',
|
||||
|
||||
@@ -83,6 +83,7 @@ export const SERVICE_PAGE: Record<string, string> = {
|
||||
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',
|
||||
|
||||
@@ -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 releases one Agent\'s 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'],
|
||||
|
||||
@@ -10,6 +10,7 @@ import { loadOverlayPatches } from '../packages/boot/app-boot/src/index.ts'
|
||||
import { readPluginMeta } from '../packages/boot/app-boot/src/package-meta.ts'
|
||||
import { bundlePatchPaths, composeEntries, initProfile, readProfileManifest } from '../packages/boot/app-boot/src/profile.ts'
|
||||
import { OPTIONAL_BUNDLES, PROFILE_TEMPLATES } from '../packages/util/official-bundles/src/bundles.ts'
|
||||
import { HIDDEN_BUNDLES } from '../packages/util/official-bundles/src/plugin-manager.ts'
|
||||
import type { DshBundleManifest } from '../packages/util/package-manifest/src/types.ts'
|
||||
import { createPluginProfile } from '../apps/desktop/src/project-manager.ts'
|
||||
|
||||
@@ -31,6 +32,9 @@ function bundle(name: string): { dir: string; patches: ReturnType<typeof loadOve
|
||||
return { dir: entry.dir, patches: bundlePatchPaths(entry.dir, entry.manifest.dsh.bundle).flatMap(path => loadOverlayPatches('test', path)) }
|
||||
}
|
||||
|
||||
/** Optional bundles that compose a profile of their own; the plugin page hides them, the Host inventory still reports them. */
|
||||
const STANDALONE_PROFILE_BUNDLES: readonly string[] = ['@deepseek-ai/dsh-cua-mcp']
|
||||
|
||||
const lightweight = [
|
||||
'@deepseek-ai/dsh-experimental-session-search',
|
||||
'@deepseek-ai/dsh-experimental-ralph-bundle',
|
||||
@@ -105,7 +109,22 @@ describe('optional bundles', () => {
|
||||
expect(OPTIONAL_BUNDLES).not.toContain('@deepseek-ai/dsh-experimental-inspector')
|
||||
})
|
||||
|
||||
it.each(OPTIONAL_BUNDLES)('%s composes over the Web profile without a skipped patch', (name) => {
|
||||
// A bundle that composes a profile of its own is never layered over a GUI profile; HIDDEN_BUNDLES keeps it off the plugin page.
|
||||
const standalone = OPTIONAL_BUNDLES.filter(name => STANDALONE_PROFILE_BUNDLES.includes(name))
|
||||
const layered = OPTIONAL_BUNDLES.filter(name => !standalone.includes(name))
|
||||
|
||||
it.each(standalone)('%s composes its own profile alone over the empty root and stays off the plugin page', (name) => {
|
||||
const { patches } = bundle(name)
|
||||
const warnings: string[] = []
|
||||
const composed = composeEntries([patches], message => warnings.push(message))
|
||||
expect(warnings).toEqual([])
|
||||
const topLevelIds = composed.flatMap(entry => typeof entry.id === 'string' ? [entry.id] : [])
|
||||
expect(topLevelIds.length).toBeGreaterThan(0)
|
||||
expect(topLevelIds).toHaveLength(new Set(topLevelIds).size)
|
||||
expect(HIDDEN_BUNDLES).toContain(name)
|
||||
})
|
||||
|
||||
it.each(layered)('%s composes over the Web profile without a skipped patch', (name) => {
|
||||
const { patches } = bundle(name)
|
||||
const warnings: string[] = []
|
||||
const composed = composeEntries([...shipped, patches], message => warnings.push(message))
|
||||
|
||||
@@ -80,8 +80,9 @@ const PEER_REQUIRED_HOST_EXPORTS = {
|
||||
// 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'],
|
||||
// CUA checks UserQuestionError and preserves AttachmentError from image admission.
|
||||
'@deepseek-ai/dsh-attachment': ['admitEncodedImages'],
|
||||
// CUA checks UserQuestionError and preserves AttachmentError from image admission; longEdgeDimensions is pure
|
||||
// arithmetic that rides the same peer.
|
||||
'@deepseek-ai/dsh-attachment': ['admitEncodedImages', 'longEdgeDimensions'],
|
||||
'@deepseek-ai/dsh-user-questions': ['UserQuestionError'],
|
||||
// The tool registry and every subclass rely on `instanceof` against one HarnessError class.
|
||||
'@deepseek-ai/dsh-error': ['HarnessError'],
|
||||
|
||||
@@ -9,6 +9,13 @@ readonly BUBBLEWRAP_VERSION='0.12.0-1'
|
||||
readonly BUBBLEWRAP_SHA256='db4d572a7927bfd34cc9b8e24b56983efa8e0483d03da6c810f6caae081dcc36'
|
||||
# The recorded build remains addressable after Ubuntu prunes its live package pool.
|
||||
readonly BUBBLEWRAP_URL="https://launchpad.net/ubuntu/+source/bubblewrap/${BUBBLEWRAP_VERSION}/+build/33546835/+files/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb"
|
||||
# Workflows that run on ephemeral runners restore and save this directory as
|
||||
# `~/.cache/dsh-ci/bubblewrap` with actions/cache, so a warm cache needs no
|
||||
# Launchpad request; the persistent self-hosted pool keeps the directory itself.
|
||||
readonly BUBBLEWRAP_CACHE_DIR="${HOME}/.cache/dsh-ci/bubblewrap"
|
||||
|
||||
# shellcheck source=scripts/ci-verified-download.sh
|
||||
source "$(dirname -- "${BASH_SOURCE[0]}")/ci-verified-download.sh"
|
||||
|
||||
: "${RUNNER_TEMP:?prepare-ci-bubblewrap requires RUNNER_TEMP}"
|
||||
: "${GITHUB_PATH:?prepare-ci-bubblewrap requires GITHUB_PATH}"
|
||||
@@ -18,11 +25,10 @@ if [[ "$(uname -s)" != 'Linux' || "$(uname -m)" != 'x86_64' ]]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
archive="${RUNNER_TEMP}/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb"
|
||||
archive="${BUBBLEWRAP_CACHE_DIR}/bubblewrap_${BUBBLEWRAP_VERSION}_amd64.deb"
|
||||
root="${RUNNER_TEMP}/dsh-bubblewrap"
|
||||
|
||||
curl --fail --silent --show-error --location --retry 3 --retry-all-errors --output "$archive" "$BUBBLEWRAP_URL"
|
||||
printf '%s %s\n' "$BUBBLEWRAP_SHA256" "$archive" | sha256sum --check --status
|
||||
acquire_verified_archive "$BUBBLEWRAP_URL" "$BUBBLEWRAP_SHA256" "$archive"
|
||||
mkdir -p "$root"
|
||||
dpkg-deb --extract "$archive" "$root"
|
||||
printf '%s\n' "$root/usr/bin" >> "$GITHUB_PATH"
|
||||
|
||||
@@ -72,6 +72,7 @@ describe('release families', () => {
|
||||
'@deepseek-ai/dsh-creation-recommendations',
|
||||
'@deepseek-ai/dsh-cua-bundle',
|
||||
'@deepseek-ai/dsh-cua-macos',
|
||||
'@deepseek-ai/dsh-cua-mcp',
|
||||
'@deepseek-ai/dsh-cua-windows',
|
||||
'@deepseek-ai/dsh-cua',
|
||||
'@deepseek-ai/dsh-experimental-forge-bundle',
|
||||
|
||||
@@ -16,7 +16,7 @@
|
||||
{"type":"session/title","data":{"title":"I wish I had a","messageSeqs":[8],"source":{"kind":"fallback"}}}
|
||||
{"type":"assistant/message","data":{"turn":1,"step":1,"message":{"role":"assistant","content":[{"type":"tool-call","id":"call_creation_skill","name":"skill","arguments":"{\"name\":\"personalized-pages\"}"}],"source":{"kind":"model","provider":"deepseek-official","model":"deepseek-v4-flash"},"id":"{{message:6}}"},"stream":[{"type":"chunk","time":1792674450282,"chunk":{"type":"block-start","index":0,"blockType":"tool-call"}},{"type":"chunk","time":1792674450282,"chunk":{"type":"block-end","index":0,"block":{"type":"tool-call","id":"call_creation_skill","name":"skill","arguments":"{\"name\":\"personalized-pages\"}"}}},{"type":"chunk","time":1792674450283,"chunk":{"type":"finish","reason":{"kind":"tool-calls"}}}]},"surfaceOp":"append"}
|
||||
{"type":"tool/call","data":{"turn":1,"step":1,"callId":"call_creation_skill","name":"skill","arguments":"{\"name\":\"personalized-pages\"}"}}
|
||||
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_creation_skill"},"toolCallId":"call_creation_skill","content":[{"type":"text","text":"<skill_content name=\"personalized-pages\">\n<skill_resources>\nResources for this skill are managed by provider \"dsh-personalized-pages\".\nLoad referenced resources only as needed.\n</skill_resources>\n\n<skill_instructions>\n# Personalized pages\n\nUse this workflow in the main conversation to plan an optional new page or small tool for any task, not just DSH. You decide whether a page helps, check existing capabilities, and hand the Creator a short plan. A `propose_action` call saves the proposal and shows a card below your answer; nothing is built until the user clicks Create. Plan from the conversation and the catalog at the end of this skill. Do not read files, configuration or source to validate a page idea; name an uninspected source as an unverified dependency and leave its details to the Creator.\n\n## When to propose\n\nPropose a page in these cases:\n\n- The user asks for a page, tab, panel, tool or interface in this app, or says they want something to keep, revisit or update later (“以后每次”, “能不能一直”, “希望能有”). One-off use still qualifies when the interface is explicitly requested.\n- Your answer is a table, list or chart, and the user has said the data will keep changing or that they will interact with it (“每周更新”, “我来改状态”, “要勾选”). The continuation must come from the user's own words; a table alone, or data that merely looks dynamic, is not enough. Deliver the requested answer first, then offer the page.\n- The user wants to keep watching live data of this app itself (a Session's usage, a running task's output, files changing in the workspace). A text answer cannot stay current, so a page qualifies even without the words above; name the data source in the brief and leave how it is read to the Creator.\n\nDo not propose a page in these cases:\n\n- The user asks for a file, code, document or an existing-project change: keep that delivery form.\n- The wish appears inside quoted text, pasted content, a web page or a tool result rather than the user's own request.\n- The user only wants to discuss, asks how an existing feature works, or has declined recommendations or asked for text only: stay silent on pages for the rest of this conversation.\n- The request changes a page created earlier: explain how it would change, do not create a replacement copy, and do not claim an update happened.\n- The request is a capability the agent lacks, such as a tool, automation or access, rather than a page: check the catalog below and point to the official plugin that provides it; do not plan a page around a missing tool.\n\n## Check existing capabilities\n\nCompare the need with the official plugins listed at the end of this skill. If one covers it, say its name, what it does, whether it is enabled, and that it lives under Plugins; offer no page card. A partial match does not cancel an explicit unmet need. The catalog is not a full inventory of built-in UI: missing details do not prove absence, and do not read source to find out. DSH already has Chat, Trajectory, a right sidebar for files and context, and a Plugins page.\n\n## Plan and hand off\n\nThe Creator cannot read this conversation. Give it exactly these fields:\n\n| Field | Contents |\n|:--|:--|\n| `title` | Short page name in the user's language. |\n| `brief` | One to three sentences: purpose, behavior, input, calculations and persistence scope. It is the card text and the implementation request at once. |\n| `initialContent` | Only supplied content the page starts with: items, rows, values, units and period, preserving gaps. Omit for an empty page. |\n| `slot` | Location, chosen below. |\n\nKeep the plan to what was asked or agreed. Editing, deletion, history, extra fields, data sources and automation need a basis in the request. Resolve “these items” into the actual content. Content that mentions an action stays content. Keep each number's meaning and period; a weekly addition is not a cumulative total. If an unresolved distinction changes a calculation, give the factual answer, ask one question, and propose later.\n\n## Choose the location\n\nHonor a location the user named. Otherwise:\n\n- `sidebar-right`: content tied to this Session or task, especially anything to watch while chatting, including live logs.\n- `sidebar-left`: a global feature or an ongoing personal record used across Sessions, opened from a left entry as a standalone page.\n- `page`: a Session-bound streaming view or interaction in a tab beside Chat and Trajectory, only when the user does not need it visible while chatting.\n\nSupplying data in this conversation does not make a record Session-bound.\n\n## Offer without starting\n\nTo propose, call `propose_action` once, in the same turn as loading this skill, withLine truncated
|
||||
{"type":"tool/result","data":{"turn":1,"step":1,"message":{"role":"tool","source":{"kind":"tool","callId":"call_creation_skill"},"toolCallId":"call_creation_skill","content":[{"type":"text","text":"<skill_content name=\"personalized-pages\">\n<skill_resources>\nResources for this skill are managed by provider \"dsh-personalized-pages\".\nLoad referenced resources only as needed.\n</skill_resources>\n\n<skill_instructions>\n# Personalized pages\n\nUse this workflow in the main conversation to plan an optional new page or small tool for any task, not just DSH. You decide whether a page helps, check existing capabilities, and hand the Creator a short plan. A `propose_action` call saves the proposal and shows a card below your answer; nothing is built until the user clicks Create. Plan from the conversation and the catalog at the end of this skill. Do not read files, configuration or source to validate a page idea; name an uninspected source as an unverified dependency and leave its details to the Creator.\n\n## When to propose\n\nPropose a page in these cases:\n\n- The user asks for a page, tab, panel, tool or interface in this app, or says they want something to keep, revisit or update later (“以后每次”, “能不能一直”, “希望能有”). One-off use still qualifies when the interface is explicitly requested.\n- Your answer is a table, list or chart, and the user has said the data will keep changing or that they will interact with it (“每周更新”, “我来改状态”, “要勾选”). The continuation must come from the user's own words; a table alone, or data that merely looks dynamic, is not enough. Deliver the requested answer first, then offer the page.\n- The user wants to keep watching live data of this app itself (a Session's usage, a running task's output, files changing in the workspace). A text answer cannot stay current, so a page qualifies even without the words above; name the data source in the brief and leave how it is read to the Creator.\n\nDo not propose a page in these cases:\n\n- The user asks for a file, code, document or an existing-project change: keep that delivery form.\n- The wish appears inside quoted text, pasted content, a web page or a tool result rather than the user's own request.\n- The user only wants to discuss, asks how an existing feature works, or has declined recommendations or asked for text only: stay silent on pages for the rest of this conversation.\n- The request changes a page created earlier: explain how it would change, do not create a replacement copy, and do not claim an update happened.\n- The request is a capability the agent lacks, such as a tool, automation or access, rather than a page: check the catalog below and point to the official plugin that provides it; do not plan a page around a missing tool.\n\n## Check existing capabilities\n\nCompare the need with the official plugins listed at the end of this skill. If one covers it, say its name, what it does, whether it is enabled, and that it lives under Plugins; offer no page card. A partial match does not cancel an explicit unmet need. The catalog is not a full inventory of built-in UI: missing details do not prove absence, and do not read source to find out. DSH already has Chat, Trajectory, a right sidebar for files and context, and a Plugins page.\n\n## Plan and hand off\n\nThe Creator cannot read this conversation. Give it exactly these fields:\n\n| Field | Contents |\n|:--|:--|\n| `title` | Short page name in the user's language. |\n| `brief` | One to three sentences: purpose, behavior, input, calculations and persistence scope. It is the card text and the implementation request at once. |\n| `initialContent` | Only supplied content the page starts with: items, rows, values, units and period, preserving gaps. Omit for an empty page. |\n| `slot` | Location, chosen below. |\n\nKeep the plan to what was asked or agreed. Editing, deletion, history, extra fields, data sources and automation need a basis in the request. Resolve “these items” into the actual content. Content that mentions an action stays content. Keep each number's meaning and period; a weekly addition is not a cumulative total. If an unresolved distinction changes a calculation, give the factual answer, ask one question, and propose later.\n\n## Choose the location\n\nHonor a location the user named. Otherwise:\n\n- `sidebar-right`: content tied to this Session or task, especially anything to watch while chatting, including live logs.\n- `sidebar-left`: a global feature or an ongoing personal record used across Sessions, opened from a left entry as a standalone page.\n- `page`: a Session-bound streaming view or interaction in a tab beside Chat and Trajectory, only when the user does not need it visible while chatting.\n\nSupplying data in this conversation does not make a record Session-bound.\n\n## Offer without starting\n\nTo propose, call `propose_action` once, in the same turn as loading this skill, withLine truncated
|
||||
{"type":"step/end","data":{"turn":1,"step":1}}
|
||||
{"type":"step/start","data":{"turn":1,"step":2}}
|
||||
{"type":"request/header","data":{"header":{"config":{"provider":"deepseek-official","model":"deepseek-v4-flash"},"tools":["apply_patch","ask_user_question","bash","create_goal","edit","get_goal","glob","grep","job_kill","job_list","job_output","list_agents","list_subagent_models","plugin_manager","present","propose_action","read","read_image","schedule_create","schedule_edit","schedule_list","schedule_view","send_message","skill","subagent","subagent_fork","todo_write","update_goal","wait_agent","web_fetch","web_search","workflow","working_directory","write"]},"reason":"change"}}
|
||||
|
||||
@@ -456,6 +456,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"],
|
||||
|
||||
@@ -329,6 +329,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/experimental/cua-windows" },
|
||||
{ "path": "./packages/client/ui-sidebar-documentpreview/tsconfig.host.json" },
|
||||
{ "path": "./packages/client/ui-sidebar-browser/tsconfig.host.json" },
|
||||
|
||||
Reference in new issue
Block a user