dsh-zcode-cua 0.0.0-stage → 1.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,231 @@
1
+ /**
2
+ * Locate the ZCode Computer Use runtime pieces on this machine.
3
+ *
4
+ * Three things are needed and all three can be overridden:
5
+ * - upstream: the `node-repl-host` MCP server that owns the `js` tool
6
+ * - client: the `computer-use` plugin that ships `setupComputerUseRuntime`
7
+ * - helper: the native Windows helper (`ax_native.node` + its entry)
8
+ *
9
+ * Nothing here is required at module load: a missing piece produces a
10
+ * diagnostic, not a crash, because the MCP server must still start and answer
11
+ * `tools/list` so DSH can surface a usable error to the user instead of a dead
12
+ * tool.
13
+ *
14
+ * @module dsh-zcode-cua/paths
15
+ */
16
+ import { execFileSync } from "node:child_process";
17
+ import { existsSync, readdirSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { homedir } from "node:os";
20
+
21
+ /** Candidate roots for ZCode's plugin cache, most specific first. */
22
+ function pluginCacheRoots() {
23
+ const home = homedir();
24
+ return [join(home, ".zcode", "cli", "plugins", "cache", "zcode-plugins-official")];
25
+ }
26
+
27
+ /** Version-sorted descendants of `root/name`, newest last. */
28
+ function versionsOf(root, name) {
29
+ const base = join(root, name);
30
+ if (!existsSync(base)) return [];
31
+ try {
32
+ // Versions sort lexicographically only by accident; the caller picks the
33
+ // last entry and ZCode ships plain dotted versions, so a natural compare
34
+ // keeps `0.10.0` after `0.9.0` instead of before it.
35
+ const entries = readdirSync(base, { withFileTypes: true });
36
+ return entries
37
+ .filter((entry) => entry.isDirectory())
38
+ .map((entry) => entry.name)
39
+ .sort(compareVersions);
40
+ } catch {
41
+ return [];
42
+ }
43
+ }
44
+
45
+ /** Compare dotted numeric versions, ignoring any prerelease suffix. */
46
+ function compareVersions(a, b) {
47
+ const num = (v) => v.split("-")[0].split(".").map((part) => Number(part) || 0);
48
+ const left = num(a);
49
+ const right = num(b);
50
+ const length = Math.max(left.length, right.length);
51
+ for (let i = 0; i < length; i += 1) {
52
+ const diff = (left[i] ?? 0) - (right[i] ?? 0);
53
+ if (diff !== 0) return diff;
54
+ }
55
+ return 0;
56
+ }
57
+
58
+ /**
59
+ * Every installed version directory of `name`, newest first.
60
+ *
61
+ * Newest first, not newest only: a ZCode update that leaves a half-written
62
+ * version directory behind is a real failure mode (an interrupted download, an
63
+ * antivirus quarantine, a disk that filled up). Taking only the newest turns
64
+ * that into "Computer Use unavailable" with a path that looks correct, while
65
+ * the previous version sitting right beside it would have worked. Callers probe
66
+ * each candidate and take the first one that is actually complete.
67
+ */
68
+ function versionsNewestFirst(root, name) {
69
+ return versionsOf(root, name)
70
+ .reverse()
71
+ .map((version) => join(root, name, version));
72
+ }
73
+
74
+ /**
75
+ * The upstream MCP server that owns the `js` tool.
76
+ *
77
+ * Override: `ZCODE_BRIDGE_SERVER`.
78
+ */
79
+ export function resolveUpstreamServer() {
80
+ const explicit = process.env.ZCODE_BRIDGE_SERVER?.trim();
81
+ if (explicit) return explicit;
82
+ for (const root of pluginCacheRoots()) {
83
+ for (const dir of versionsNewestFirst(root, "node-repl-host")) {
84
+ const entry = join(dir, "dist", "mcp", "server.js");
85
+ if (existsSync(entry)) return entry;
86
+ }
87
+ }
88
+ return undefined;
89
+ }
90
+
91
+ /**
92
+ * The `computer-use` plugin root, which holds `scripts/computer-use-client.mjs`
93
+ * and `docs/computer-use.md`. The model's bootstrap imports from here.
94
+ *
95
+ * Override: `ZCODE_CUA_PLUGIN_ROOT`.
96
+ */
97
+ export function resolveCuaPluginRoot() {
98
+ const explicit = process.env.ZCODE_CUA_PLUGIN_ROOT?.trim();
99
+ if (explicit) return explicit;
100
+ for (const root of pluginCacheRoots()) {
101
+ for (const dir of versionsNewestFirst(root, "computer-use")) {
102
+ if (existsSync(join(dir, "scripts", "computer-use-client.mjs"))) return dir;
103
+ }
104
+ }
105
+ return undefined;
106
+ }
107
+
108
+ /**
109
+ * Installation directories ZCode may occupy, best guess first.
110
+ *
111
+ * ZCode has no npm package and no PATH entry, so the install location is not
112
+ * derivable from the executable name alone. Three sources are tried, in order
113
+ * of reliability:
114
+ *
115
+ * 1. the uninstall registry, which is the only record that survives a
116
+ * non-default install drive (the measured case: ZCode on `D:`);
117
+ * 2. the environment variable the user set explicitly;
118
+ * 3. the conventional per-user and per-machine layouts.
119
+ *
120
+ * A wrong guess costs one `existsSync`; a missing source costs a broken
121
+ * install, so all three are consulted before giving up.
122
+ */
123
+ function zcodeInstallCandidates() {
124
+ const candidates = [];
125
+
126
+ for (const root of [
127
+ "HKLM\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
128
+ "HKLM\\SOFTWARE\\WOW6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
129
+ "HKCU\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
130
+ ]) {
131
+ const found = readInstallLocationFromRegistry(root);
132
+ if (found) candidates.push(found);
133
+ }
134
+
135
+ const explicit = process.env.ZCODE_HOME?.trim();
136
+ if (explicit) candidates.push(explicit);
137
+
138
+ const localAppData = process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local");
139
+ const roamingAppData = process.env.APPDATA ?? join(homedir(), "AppData", "Roaming");
140
+ for (const base of [localAppData, roamingAppData, process.env.ProgramFiles, process.env["ProgramFiles(x86)"]]) {
141
+ if (!base) continue;
142
+ candidates.push(join(base, "ZCode"));
143
+ candidates.push(join(base, "Programs", "ZCode"));
144
+ }
145
+
146
+ return candidates;
147
+ }
148
+
149
+ /** InstallLocation of the ZCode uninstall entry under one registry root. */
150
+ function readInstallLocationFromRegistry(key) {
151
+ try {
152
+ // `reg query` rather than a registry module: this package has no
153
+ // dependencies, and spawning `reg` is cheaper than requiring `winreg`
154
+ // to be present on every machine.
155
+ const out = execFileSync("reg", ["query", key, "/s", "/f", "ZCode", "/d"], {
156
+ encoding: "utf8",
157
+ stdio: ["ignore", "pipe", "ignore"],
158
+ timeout: 5000,
159
+ windowsHide: true,
160
+ });
161
+ const match = /InstallLocation\s+REG_\w+\s+(.+)/i.exec(out);
162
+ const value = match?.[1]?.trim();
163
+ return value && value !== "" ? value : undefined;
164
+ } catch {
165
+ return undefined;
166
+ }
167
+ }
168
+
169
+ /**
170
+ * The native Windows helper directory.
171
+ *
172
+ * ZCode ships it beside its own executable under `resources/tools/cua-helper`.
173
+ * The helper entry must exist AND the addon must be loadable — a half-unpacked
174
+ * install produces the same "CUA unavailable" symptom as no install at all, so
175
+ * both are checked here and reported separately by {@link describeRuntime}.
176
+ *
177
+ * Override: `ZCODE_BRIDGE_HELPER_ROOT`.
178
+ */
179
+ export function resolveHelperRoot() {
180
+ const explicit = process.env.ZCODE_BRIDGE_HELPER_ROOT?.trim();
181
+ if (explicit) return explicit;
182
+ const candidates = zcodeInstallCandidates().map((dir) =>
183
+ join(dir, "resources", "tools", "cua-helper"),
184
+ );
185
+ for (const candidate of candidates) {
186
+ if (existsSync(join(candidate, "build", "Release", "ax_native.node"))) return candidate;
187
+ }
188
+ // Fall through to the first candidate that at least exists, so the diagnostic
189
+ // can name the directory the user was expected to have.
190
+ return candidates.find((candidate) => existsSync(candidate));
191
+ }
192
+
193
+ /** Everything the server needs, resolved once at startup. */
194
+ export function resolveRuntime() {
195
+ const upstream = resolveUpstreamServer();
196
+ const cuaPluginRoot = resolveCuaPluginRoot();
197
+ const helperRoot = resolveHelperRoot();
198
+ const helperEntry = helperRoot ? join(helperRoot, "dist", "windows-helper.js") : undefined;
199
+ const helperAddon = helperRoot ? join(helperRoot, "build", "Release", "ax_native.node") : undefined;
200
+ return {
201
+ upstream,
202
+ cuaPluginRoot,
203
+ helperRoot,
204
+ helperEntry: helperEntry && existsSync(helperEntry) ? helperEntry : undefined,
205
+ helperAddon: helperAddon && existsSync(helperAddon) ? helperAddon : undefined,
206
+ };
207
+ }
208
+
209
+ /**
210
+ * Human-readable account of what resolved and what did not.
211
+ *
212
+ * Reported through MCP `instructions` and a startup stderr line: the two
213
+ * failure modes that actually happen (ZCode updated to a layout this plugin
214
+ * does not know, and the helper present but its addon missing) both look
215
+ * identical from the model's side — "Computer Use is unavailable" — and neither
216
+ * is fixable without naming the path that was probed.
217
+ */
218
+ export function describeRuntime(runtime) {
219
+ const lines = [];
220
+ lines.push(`upstream: ${runtime.upstream ?? "NOT FOUND"}`);
221
+ lines.push(`cua plugin: ${runtime.cuaPluginRoot ?? "NOT FOUND"}`);
222
+ lines.push(`helper root: ${runtime.helperRoot ?? "NOT FOUND"}`);
223
+ lines.push(`helper entry: ${runtime.helperEntry ?? "NOT FOUND"}`);
224
+ lines.push(`helper addon: ${runtime.helperAddon ?? "NOT FOUND"}`);
225
+ return lines.join("\n");
226
+ }
227
+
228
+ /** Whether every piece needed for a real desktop action is present. */
229
+ export function runtimeIsComplete(runtime) {
230
+ return Boolean(runtime.upstream && runtime.cuaPluginRoot && runtime.helperEntry && runtime.helperAddon);
231
+ }
@@ -0,0 +1,304 @@
1
+ ---
2
+ name: zcode-computer-use
3
+ description: "用 ZCode 原生的电脑控制(Computer Use / CUA)操作桌面应用:点击、打字、截图、读 AX 树、拖拽、滚轮、快捷键。当需要操作本机原生桌面应用的 UI(不是网页内部),例如开关软件、填写本地表单、点击桌面按钮、查看窗口内容、截图确认界面状态时使用。工具是 mcp__zcode-cua__js,每个 cell 内必须先 bootstrap 再调 agent.computerUse.*。"
4
+ ---
5
+
6
+ # ZCode 电脑控制(原汁原味)
7
+
8
+ 本 skill 把 ZCode 官方桌面端自带的 Computer Use 完整搬到 DSH:走的是 ZCode 自己的
9
+ `node-repl-host` MCP server 与 `cua-helper` 原生执行体,只是外面套了一层协议翻译,
10
+ 所以工具描述、执行环境、返回内容与在 ZCode 里完全一致。
11
+
12
+ ## 工具
13
+
14
+ 唯一工具:`mcp__zcode-cua__js`
15
+
16
+ 参数:
17
+
18
+ | 参数 | 必填 | 说明 |
19
+ |---|---|---|
20
+ | `code` | 是 | 在**全新的** Node.js 内核里执行的 JS,支持顶层 await |
21
+ | `title` | 是 | 一句话中文描述这次要做什么,不要提 js / JavaScript / node_repl |
22
+ | `timeout_ms` | 视情况 | 默认 60000;预计超过 30 秒时必须显式给,且 ≤ 120000 |
23
+
24
+ **每个 cell 都是全新内核**:变量、import、模块缓存全部消失,所以 `const app` 活不到下一个
25
+ cell。UI 状态本身是活的,重新绑定很便宜。
26
+
27
+ ## 每次调用先 bootstrap
28
+
29
+ bootstrap 必须和实际操作放在**同一个 cell** 里,且放在最前面:
30
+
31
+ ```js
32
+ const root =
33
+ process.env.ZCODE_CUA_PLUGIN_ROOT ??
34
+ process.env.ZCODE_PLUGIN_ROOT ??
35
+ process.env.CLAUDE_PLUGIN_ROOT;
36
+ const { join } = await import("node:path");
37
+ const { pathToFileURL } = await import("node:url");
38
+ const { setupComputerUseRuntime } = await import(
39
+ pathToFileURL(join(root, "scripts", "computer-use-client.mjs")).href
40
+ );
41
+ await setupComputerUseRuntime({ globals: globalThis });
42
+ // 之后才能用 agent.computerUse.*
43
+ ```
44
+
45
+ ## 辅助功能优先(Accessibility first)
46
+
47
+ 辅助功能是主路径:语义精确、能操作后台应用、不抢用户焦点。
48
+
49
+ 1. **先观察**,在返回的 AX 树里按 role / name / title / value 找目标元素。
50
+ 2. 找到就用**索引**操作;元素自报语义动作时也可以用 `performSecondaryAction`。
51
+ 3. 可设置的元素优先 `setValue`,不要打字或粘贴;只有目标不可设置或内容是富文本时才用 `paste`。
52
+ 4. **键盘是兜底**:只有没有元素能表达该操作,或用户明确要求键盘时才用 `pressKey`。
53
+ 5. **坐标是最后手段**:仅用于 canvas、游戏、Electron 内容这类辅助功能看不见的地方。
54
+
55
+ 不要因为快捷键更短就把可用的元素操作换成快捷键;同一个操作不要同时走辅助功能和视觉两条路。
56
+
57
+ **观察在后台应用上也有效,包括截图** —— 任何显示器、包括负坐标的窗口。
58
+ `has_image: false` 只表示这次没要像素(`getAXState`),不是截图失败。
59
+
60
+ **成功指的是 API 接受了动作,不等于应用照做了**。往网页内容编辑器里打字经常被接受但毫无变化,
61
+ 所以要重新观察确认文字真的落进去了。
62
+
63
+ ## API
64
+
65
+ ```typescript
66
+ type Vec2 = [x: number, y: number];
67
+ type ObservationOptions = { emit?: boolean };
68
+ type StateOptions = ObservationOptions & { disableDiffing?: boolean };
69
+ type StateAndScreenshot = { state: string; screenshot?: Uint8Array };
70
+ type Direction = "up" | "down" | "left" | "right" | "u" | "d" | "l" | "r";
71
+ type MouseButton = "left" | "right" | "middle" | "l" | "r" | "m";
72
+ type SelectionType = "text" | "cursor_before" | "cursor_after";
73
+ type Strategy = "auto" | "a11y" | "event";
74
+
75
+ type ClickOptions = {
76
+ mouseButton?: MouseButton;
77
+ clickCount?: number;
78
+ modifiers?: string;
79
+ strategy?: Strategy;
80
+ };
81
+ type SelectTextOptions = { prefix?: string; suffix?: string; selectionType?: SelectionType };
82
+ type PasteOptions = { format?: "text" | "md" | "html" };
83
+ type PressKeyOptions = { holdSeconds?: number; strategy?: Strategy };
84
+
85
+ interface Target {
86
+ getAXState(options?: StateOptions): Promise<string>;
87
+ getScreenshot(options?: ObservationOptions): Promise<Uint8Array>;
88
+ getAXStateAndScreenshot(options?: StateOptions): Promise<StateAndScreenshot>;
89
+ elements(): Promise<{ index: number; kind: string; title: string | null; value: string | null; actions: string[] }[]>;
90
+
91
+ paste(text: string, options?: PasteOptions): Promise<void>;
92
+ click(target: number | Vec2, options?: ClickOptions): Promise<void>;
93
+ drag(from: number | Vec2, to: number | Vec2, options?: { modifiers?: string }): Promise<void>;
94
+ pressKey(key: string, options?: PressKeyOptions): Promise<void>;
95
+ scroll(target: number | Vec2, direction: Direction, pages?: number): Promise<void>;
96
+ selectText(elementIndex: number, text: string, options?: SelectTextOptions): Promise<void>;
97
+ setValue(elementIndex: number, value: string): Promise<void>;
98
+ typeText(text: string): Promise<void>;
99
+ performSecondaryAction(elementIndex: number, action: string): Promise<void>;
100
+ }
101
+
102
+ interface App extends Target {}
103
+
104
+ type AppRef = { name?: string; bundle_id?: string; pid?: number; window_id?: number };
105
+ type AppInfo = { pid: number; name: string | null; bundle_id: string | null; active: boolean };
106
+ type State = { apps: AppInfo[] };
107
+
108
+ declare const agent: {
109
+ computerUse: {
110
+ getState(options?: ObservationOptions): Promise<State>;
111
+ getApp(target: string | AppRef): Promise<App>;
112
+ listApps(options?: ObservationOptions): Promise<AppInfo[]>;
113
+ computer: Record<string, (args: object) => Promise<unknown>>;
114
+
115
+ requestAccess(capabilities?: string[]): Promise<Record<string, unknown>>;
116
+ stop(reason?: string): Promise<void>;
117
+ };
118
+ };
119
+ ```
120
+
121
+ 完整参考在 `agent.documentation.get("computer-use")`,按需取;只在本页没给出的参数形状或
122
+ 响应字段上才去读它。
123
+
124
+ ## 主循环
125
+
126
+ **观察一次 → 操作 → 再观察**,然后决定下一步。
127
+
128
+ `agent.computerUse.getApp(...)` 只绑定应用,不显示任何东西;要看状态得调 `getAXState`。
129
+ 绑定也会顺带启动应用(没有单独的 launch 工具)。参数是显示名或 bundle id —— 和
130
+ `listApps()` 返回的字符串一致 —— 或一个 `AppRef`。
131
+
132
+ 用户点名某个应用时,**逐字符照抄**那个标识符,不要翻译、本地化、归一化、缩写或去掉后缀:
133
+ `{"name":"网易云音乐app"}` 不是 `{"name":"网易云音乐"}`;`{"name":"日历"}` 不是
134
+ `{"name":"Calendar"}`。改写过的名字会解析到别的应用或解析不到,报错是 "app not found"。
135
+ 精确字符串解析不到时,调一次 `agent.computerUse.listApps()` 挑出匹配的标识符。
136
+
137
+ 相关动作和最后一次收尾观察可以放在同一个 cell:
138
+
139
+ ```js
140
+ const app = await agent.computerUse.getApp("记事本");
141
+ await app.click(box);
142
+ await app.typeText("hello");
143
+ await app.pressKey("Return");
144
+ await app.getAXState();
145
+ ```
146
+
147
+ 元素索引指向该应用**最近一次观察**,所以几个动作可以复用同一个索引,不必中间重新观察 ——
148
+ 同一个 cell 里点完索引接着往里打字是合法的。**观察会重新编号**,索引要从最新那次取。
149
+ 元素消失了会 fail closed,报 `ELEMENT_UNAVAILABLE`。
150
+
151
+ **树默认只回 diff**:只列相对本 cell 已展示过的树有增删改的元素,没变的行省略但索引仍然有效。
152
+ 绑定后的第一棵树、以及 `getScreenshot` 或 `elements()` 之后的第一棵,永远是完整的。
153
+ 需要完整树时传 `{ disableDiffing: true }`。如果一次独立观察报告无变化,不要在没有中间动作的
154
+ 情况下立刻重复它。
155
+
156
+ 大树会按优先级裁剪(保留祖先),表头会说明,此时索引会跳号。`app.elements()` 返回全部元素
157
+ (含被裁掉的)及其索引 —— 在 JS 里过滤,**绝不要猜索引**。
158
+
159
+ 一次捕获只针对一个窗口:不给 `window_id` 时主/键窗口每次观察都会重新解析,所以刚弹出的模态框
160
+ 会成为被捕获的窗口。动作失败或树读起来像应用的另一部分时,检查观察结果里的 `window` ——
161
+ 对话框会出现在那里。读了它再去操作,或者关掉它(Escape 或它自己的取消)再重新观察。
162
+ **元素缺失不是动作成功的证据**。要用 `getApp({pid, window_id})` 钉住某个窗口,`list_windows`
163
+ 能给 id。
164
+
165
+ ## 输出
166
+
167
+ 观察类调用会自己显示结果:`getAXState`、`getScreenshot`、`getAXStateAndScreenshot`、`getState`
168
+ 和 `listApps` 都会 emit 自己的结果。
169
+
170
+ **绝不要把它们的返回值再喂给 `nodeRepl.write(...)` 或 `nodeRepl.emitImage(...)`**:一个结果里
171
+ 出现第二张栅格图会破坏 one-raster 规则,整个帧会被丢弃,结果你一张图都看不到。
172
+ 想拿到值又不想显示,传 `{ emit: false }`。
173
+
174
+ 动作类方法不显示任何东西。
175
+
176
+ ## 坐标
177
+
178
+ `x` 和 `y` 只能**看着当前返回的栅格图**来选,且 `0 <= x < width`、`0 <= y < height` 针对那张
179
+ 栅格。这些整数原样提交;CUA 内部绑定当前栅格,并负责从返回栅格到原生派发的全部变换。
180
+ 元素的窗口边界是诊断用的全局屏幕坐标点,**绝不能**拿来当坐标用。开始走视觉兜底时,丢弃此前
181
+ 文本或辅助功能结果里的所有坐标类数字。
182
+
183
+ 目标明确时就在当前栅格上操作;太小或太模糊就重新观察,不要猜几何。
184
+
185
+ 指针动作被接受但毫无变化,通常意味着应用在真实指针所在的位置做了动作,重复也没用 ——
186
+ 改用元素索引或键盘。
187
+
188
+ 坐标被拒可能提示了一个意料之外的属主,或者说帧已过期 —— 窗口移动、缩放或被替换了。
189
+ 重新观察拿当前栅格,或者改用元素索引(不依赖窗口几何)。
190
+ **绝不要为了坐标能落点而移动、缩放或关闭窗口**。
191
+
192
+ ## 键盘
193
+
194
+ `pressKey` 接受单个键或用 `+` 连接的组合键,短名和 X keysym 风格都认:`"a"`、`"Return"`、
195
+ `"Tab"`、`"Control_L+a"`、`"super+c"`、`"Up"`。macOS 用 `cmd`;Linux 和 Windows 用 `ctrl`。
196
+ 用 `{ holdSeconds }` 保持按住一段时长,而不是模拟重复按键。
197
+
198
+ 键盘输入要绑定到应用或元素,**绝不发不绑定的键盘**。`paste` 用于富文本,或 `setValue`
199
+ 设不进去的目标 —— 不是用来给可设置元素塞纯文本的。
200
+
201
+ `performSecondaryAction` 只接受当前树里该元素**自报**的动作,不要猜动作名。
202
+
203
+ 同一时刻最多一个元素是 `focused`(持有键盘焦点);缺失表示无法确定。
204
+
205
+ `selectText` 在可编辑元素里定位文本。用 `prefix`/`suffix` 区分重复匹配,用 `selectionType`
206
+ 放置光标而不是选中。歧义匹配会被拒绝,而不是取第一个命中。
207
+
208
+ ## 等待
209
+
210
+ 观察本身会等 UI 稳定后再捕获。**不要在读状态前停顿或延迟** —— 不要 `setTimeout`,不要轮询循环。
211
+
212
+ ## 错误与停止
213
+
214
+ 动作成功 resolve 为 `undefined`,否则抛 `ComputerUseError`:
215
+
216
+ - `code` —— `PERMISSION_DENIED`、`NOT_AUTHORIZED`、`APP_NOT_FOUND`、`AMBIGUOUS_APP`、
217
+ `LAUNCH_FAILED`、`INVALID_APP`、`ELEMENT_UNAVAILABLE`、`STALE_STATE`、`NOT_SETTABLE`、
218
+ `NOT_SELECTABLE`、`ACTION_UNAVAILABLE`、`FOREGROUND_REQUIRED`、`CONTROLLER_BUSY`、
219
+ `CONTROL_STOPPED`、`SCREEN_LOCKED`、`HELPER_UNAVAILABLE`、`VERSION_MISMATCH`、`TIMEOUT`、
220
+ `STRUCTURED_STATE_UNAVAILABLE`、`INTERNAL`。
221
+ - `actionSent` —— 动作是否可能已经到达应用。非幂等动作只在它为 `false` 时重试;否则先观察,
222
+ 再根据看到的东西决定。
223
+ - `retry` —— `"reobserve"`、`"retry"` 或 `"never"`。
224
+
225
+ `CONTROLLER_BUSY` 表示另一个存活的 ZCode Computer Use 会话占着输入。它**永远不可重试**:
226
+ 报告错误里的属主,请用户关掉那个会话。
227
+
228
+ 遇到 `agent.computerUse.stop()`、kill switch、权限拒绝或不可重试的错误后**立即停止**。
229
+ 访问被拒后不要改用另一种 UI 自动化技术。
230
+
231
+ **坚持到请求真正完成**:尝试了动作不算完成,要验证返回的状态里确实体现了结果。如果状态没变或
232
+ 只是中间态,换别的方法。只有当请求的状态确实出现,或者你解释了一个自己解决不了的具体阻塞,
233
+ 才回复用户。
234
+
235
+ ## 低层工具面
236
+
237
+ `agent.computerUse.computer.<tool>(args)` 是低层接口。优先用上面的绑定对象 API;只有 API
238
+ 表达不了的时候才用工具(窗口枚举、按键重复、在同一次调用里读回状态)。参数是严格的,
239
+ 未声明的键会被拒绝。每个工具接受**一个**参数对象 —— 下面的名字是它的键,不是位置参数:
240
+ `get_app_state({ app_ref: { bundle_id: "com.apple.Notes" }, include_screenshot: true })`。
241
+
242
+ 应用名用操作系统列出的名字(Windows:开始菜单里的名字,不是窗口标题)。
243
+ 除了 Windows 上启动非打包应用、以及 `include_screenshot=true` 会取消最小化之外,
244
+ **没有别的操作会抢走用户焦点** —— 最小化状态的树完全可用,所以保持默认。
245
+
246
+ ```
247
+ list_apps({})
248
+ list_windows({app_ref})
249
+ get_app_state({app_ref, include_screenshot?=false, disable_diffing?=false})
250
+
251
+ left_click({target, mouse_button?="left", click_count?=1, modifiers?="",
252
+ strategy?, app_ref?, return_state?})
253
+ left_click_drag({from_target, to, modifiers?="", strategy?, app_ref?,
254
+ return_state?})
255
+ scroll({target, scroll_direction, scroll_amount, strategy?, app_ref?,
256
+ return_state?})
257
+
258
+ type({text, target?, app_ref?, strategy?, return_state?})
259
+ set_value({target, value, strategy?, app_ref?, return_state?})
260
+ select_text({target, text_range?, app_ref?, return_state?})
261
+ key({text, repeat?, hold_seconds?, app_ref?, strategy?, return_state?})
262
+ paste({text, format?="text", app_ref?, return_state?})
263
+ perform_action({target, action, app_ref?, return_state?})
264
+
265
+ request_access({capabilities?})
266
+ stop_computer_control({reason?})
267
+ ```
268
+
269
+ 参数形状:`app_ref` / `app` 是 `AppRef`,但这里的裸字符串会被当作 bundle id,
270
+ 所以显示名要传 `{name: "记事本"}`。`scroll_direction` 是 `up|down|left|right`,
271
+ `scroll_amount` 是页数,`strategy` 是 `auto|a11y|event`,`return_state` 是
272
+ `compact|full|none`(在同一次调用里一并返回应用状态)。
273
+ `target`、`text_range`、`modifiers` 和响应形状见
274
+ `nodeRepl.write(await agent.documentation.get("computer-use"))`。
275
+
276
+ ## 使用边界
277
+
278
+ - 能用专用 connector、API、CLI 或 skill 完成任务时,优先用它们。
279
+ - 浏览器和网页内部的任务用 Browser Use(本机未接),不要用 CUA 去点网页。
280
+ - 除用户明确要求外,不要用 AppleScript、`osascript`、JXA、System Events、shell 命令或
281
+ 其它 UI 自动化技术。
282
+ - **仅限主 agent**,绝不要把 Computer Use 委派给子 agent。
283
+ - **同一时刻只让一个会话操作桌面。** 整条链路上只有一份 helper——`@deepseek-ai/dsh-mcp-client`
284
+ 是 profile 级插件,DSH 只起一个实例、一个子进程。真正起作用的是上游的串行锁:桥接层给
285
+ 所有 DSH 会话传同一个进程级 `session_id`(`dsh-<uuid>`,进程启动时生成一次),上游
286
+ `server.js` 用 `serialized(sessionKey, ...)` 把每次 `js` 执行按这个 id 排队,所以两个会话
287
+ 不会同时点击;代价是一个会话的长调用会把其它会话的 `js` 调用全堵在后面。如果你判断到
288
+ 另一个会话可能正在操作桌面,先向用户确认,不要两边同时动手。
289
+
290
+ ## 运行环境
291
+
292
+ - 工具名前缀:`mcp__zcode-cua__js`
293
+ - 上游是 ZCode 官方的 `node-repl-host`;插件自己解析 ZCode 的三处安装位置
294
+ (`node-repl-host` 的 MCP server、`computer-use` 插件根、`cua-helper` 原生执行体),
295
+ 都在 ZCode 的安装目录与插件缓存里。
296
+
297
+ **不要在技能正文里写死任何路径。** 上游升级后旧路径会失效。需要确认当前解析结果时,
298
+ 调用一次 `js` 并 `nodeRepl.write(process.env.ZCODE_CUA_PLUGIN_ROOT)`。
299
+
300
+ **Browser Use 在本插件中不可用。** 上游 `node-repl-host` 确实实现了 Browser Use 桥
301
+ (`createBrowserBridgeGlobals`),但它需要宿主提供 `browserBroker`,而本插件只接了
302
+ Computer Use 桥。调用浏览器能力会得到
303
+ `Browser control is unavailable for this node_repl session`。需要操作网页时,用专门的
304
+ 浏览器工具或让用户手动操作,不要退化成用坐标去点网页。