dsh-plugin-cua-win 0.0.0-stage → 0.2.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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-plugin-cua-win contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,265 @@
1
- # Temporary Holding Version
1
+ # dsh-plugin-cua-win
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把远端 Windows 的文件、命令和图形界面操作,变成 DSH 里的 `win_*` 工具。
4
+
5
+ > **先决条件:远端 Windows 上必须有 [cua-win-daemon](https://codeberg.org/lisztvan/cua-win-daemon)。**
6
+ > 本插件只是客户端,不含任何 Windows 侧代码。只装插件是跑不起来的——所有工具都会报
7
+ > `daemon_unreachable`。完整的 daemon 安装步骤见下面「第一半」。
8
+
9
+ 本插件是守护进程的 **MCP 客户端**:一条 `ssh -L` 隧道上的长连接,讲 JSON-RPC 2.0。
10
+ 守护进程跑在远端**交互会话(Session 1+)**。
11
+ 为什么必须这样:`sshd` 在 Session 0,而 Session 0 没有用户桌面——那里 `EnumWindows`、
12
+ UIA、`PrintWindow`、`SendInput` 全部返回空结果,看起来像工具坏了,其实是 Windows 的会话隔离。
13
+
14
+ ## 安装
15
+
16
+ **这个插件本身不驱动 Windows,它只是客户端。** 真正干活的是跑在远端 Windows
17
+ 交互会话里的 **[cua-win-daemon](https://codeberg.org/lisztvan/cua-win-daemon)**。
18
+ 没有它,插件装上也连不上:所有工具都会报 `daemon_unreachable`。
19
+
20
+ 所以安装分两半:**先装守护进程**(在 Windows 上),**再装插件**(在这台机器上)。
21
+
22
+ ---
23
+
24
+ ### 第一半:远端 Windows 装守护进程
25
+
26
+ #### 需要什么
27
+
28
+ | 要求 | 说明 |
29
+ |---|---|
30
+ | **Windows 10/11 x64** | 守护进程依赖 Win32 / UIA / WTS API,**没有 Linux/macOS 版本** |
31
+ | **账户至少交互登录过一次** | 控制台或 RDP 均可,登录后可以直接断开。Windows 不会为从未登录过的账户创建会话,这种账户**不支持**:`autostart kick` 会报 `the task started but nothing is listening`(此时任务本身 `LastTaskResult=0`,不是失败) |
32
+ | **SSH 可达** | 装和日常调用都走 SSH,不需要开着 RDP |
33
+ | .NET SDK / 运行时 | **不需要**。二进制自带 CoreCLR 与 WPF/WinForms 框架 |
34
+ | `ffmpeg`(可选) | 缺了 `start_recording` 会返回 `recording_unavailable` |
35
+ | PowerShell 7(可选) | 缺了 `pwsh` 的 `shell:"7"` 会 `spawn_failed`;`shell:"5.1"` 始终可用 |
36
+
37
+ #### 1. 下载二进制
38
+
39
+ 从 Codeberg Releases 取最新版(当前 **v1.3.0**,约 71 MiB):
40
+
41
+ ```
42
+ https://codeberg.org/lisztvan/cua-win-daemon/releases/download/v1.3.0/cua-win-daemon-1.3.0-win-x64.zip
43
+ ```
44
+
45
+ > 版本对应关系:`read_bytes` / `write_bytes` 和图片附加需要 **daemon ≥ 1.2.0**;
46
+ > 本插件按 **1.3.0** 的工具清单开发与测试。更老版本能连上,但会缺少部分工具。
47
+
48
+ #### 2. 解压并加入 PATH
49
+
50
+ zip 内有一层 `cua-win-daemon-<version>-win-x64\` 目录,用 `--strip-components=1` 去掉它:
51
+
52
+ ```powershell
53
+ mkdir "%USERPROFILE%\bin\cua-win-daemon"
54
+ tar -xf cua-win-daemon-1.3.0-win-x64.zip -C "%USERPROFILE%\bin\cua-win-daemon" --strip-components=1
55
+ setx PATH "%PATH%;%USERPROFILE%\bin\cua-win-daemon"
56
+ ```
57
+
58
+ > `setx` 会**新开** shell 才生效,且 `%PATH%` 超过 1024 字符会被截断。
59
+ > PATH 很长时改用:
60
+ > ```powershell
61
+ > [Environment]::SetEnvironmentVariable('Path',
62
+ > [Environment]::GetEnvironmentVariable('Path','User') + ';%USERPROFILE%\bin\cua-win-daemon','User')
63
+ > ```
64
+
65
+ <details>
66
+ <summary>如果 <code>tar --strip-components</code> 在你的机器上不可用</summary>
67
+
68
+ Windows 10 1803+ 自带 bsdtar,通常可以直接用。万一不行,用 `Expand-Archive` 解出再搬一层:
69
+
70
+ ```powershell
71
+ Expand-Archive cua-win-daemon-1.3.0-win-x64.zip -DestinationPath $env:TEMP\cua-win
72
+ Move-Item "$env:TEMP\cua-win\cua-win-daemon-1.3.0-win-x64\*" "%USERPROFILE%\bin\cua-win-daemon"
73
+ ```
74
+ </details>
75
+
76
+ 不想改 PATH 也行,后面每条命令用绝对路径 `"%USERPROFILE%\bin\cua-win-daemon\cua-win-daemon.exe"`。
77
+
78
+ #### 3. 注册交互式计划任务(只需一次)
79
+
80
+ 在**普通 SSH 会话**里执行即可。这步的作用是把守护进程送进 **Session 1+**——
81
+ 直接 `ssh win cua-win-daemon serve` 只会起在 Session 0,那样窗口、UIA、截图全是空的。
82
+
83
+ ```powershell
84
+ cua-win-daemon autostart enable --run-level highest
85
+ cua-win-daemon autostart kick
86
+ ```
87
+
88
+ `--run-level highest` 在 SSH 登录已持有未过滤管理员令牌时(`sshd` 以 `LocalSystem` 运行,
89
+ 这是常态)能拿到 **High 完整性且不弹 UAC**。如果你的交互会话权限较低,就从提权 shell 执行这一条。
90
+
91
+ #### 4. 验证守护进程真的在工作
92
+
93
+ ```powershell
94
+ cua-win-daemon client ping
95
+ ```
96
+
97
+ 必须看到这四项,缺一不可:
98
+
99
+ ```json
100
+ { "session_id": 1, "integrity": "High",
101
+ "has_interactive_desktop": true, "window_station": "WinSta0" }
102
+ ```
103
+
104
+ - `session_id` 为 `0` → 还在 Session 0,回到第 3 步
105
+ - `has_interactive_desktop: false` → 会话已断开,跑 `cua-win-daemon client activate` 或重新登录一次
106
+
107
+ > 在**启动守护进程之前**于 SSH 里跑 `cua-win-daemon doctor`,会看到 `session_not_zero: fail`——
108
+ > 那是正常的,不是安装失败。
109
+
110
+ ---
111
+
112
+ ### 第二半:本机装插件
113
+
114
+ #### 5. 建 SSH 隧道
115
+
116
+ ```bash
117
+ ssh -N -L 9000:127.0.0.1:9000 -L 9001:127.0.0.1:9001 alice@win \
118
+ -o ServerAliveInterval=15 -o ServerAliveCountMax=3
119
+ ```
120
+
121
+ - **9000** 是 MCP 端口,插件用
122
+ - **9001** 是信封端口,只有你在远端机跑 `cua-win-daemon client ...` 时才需要
123
+
124
+ 守护进程只绑 `127.0.0.1`,**永不 `0.0.0.0`**;网络可达性完全由这条隧道负责。
125
+
126
+ #### 6. 装插件
127
+
128
+ ```bash
129
+ # a) npm(推荐)
130
+ plugin_manager install_bundle target=dsh-plugin-cua-win
131
+
132
+ # b) 锁定版本
133
+ plugin_manager install_bundle target=dsh-plugin-cua-win@0.2.1
134
+
135
+ # c) 源码 / 本地开发
136
+ git clone https://codeberg.org/lisztvan/dsh-plugin-cua-win.git
137
+ plugin_manager install_bundle target=/path/to/dsh-plugin-cua-win
138
+ ```
139
+
140
+ 也可以走界面:**插件** → **添加插件** → 填包名或选本地目录。
141
+
142
+ #### 7. 配置 `sshHost`
143
+
144
+ ```yaml
145
+ sshHost: alice@win # 或 ~/.ssh/config 里的 Host 别名
146
+ ```
147
+
148
+ **不需要手工拷 token。** 填了 `sshHost` 后,插件每次握手前自己从远端读
149
+ `%LOCALAPPDATA%\cua-win-daemon\token`。这一步只是省掉手工搬运,安全边界没变——
150
+ 能 SSH 进去的人本来就能读到那个文件。
151
+
152
+ #### 8. 验证
153
+
154
+ 在 DSH 里调 `win_ping`,应当看到 `session_id ≥ 1` 和 `has_interactive_desktop: true`。
155
+ 再调一次 `win_screenshot({ inline: true })`——如果模型能描述画面内容,链路就通了。
156
+
157
+ ### token 是自动取的,但本地副本会过期
158
+
159
+ 配置了 `sshHost` 时插件每次握手前都会现取 token,所以**你不需要手工维护 `~/.cua-win/token`**。
160
+ 但如果你写脚本直连守护进程,那个文件可能是旧的,症状是 `unauthorized: send params.token on initialize`。
161
+ 修复办法是重新从远端取一次:
162
+
163
+ ```bash
164
+ ssh alice@win 'cmd /c type %LOCALAPPDATA%\cua-win-daemon\token' | tr -d '\r\n' > ~/.cua-win/token
165
+ chmod 600 ~/.cua-win/token
166
+ ```
167
+
168
+ ### 装不上时的对照表
169
+
170
+ | 症状 | 大概率原因 | 怎么办 |
171
+ |---|---|---|
172
+ | 所有工具报 `daemon_unreachable` | 隧道没建,或守护进程没起 | 第 5 步建隧道;远端 `cua-win-daemon client ping` |
173
+ | `handshake_failed` | token 不对,或隧道端口接到了 9001 | 检查 `sshHost`;确认映射的是 **9000** |
174
+ | `session_owner_mismatch` | 标签被别的连接占着 | 插件会自己重领一次;仍失败则远端 `client session end dsh` |
175
+ | `client ping` 的 `session_id` 是 0 | 守护进程跑在 Session 0 | 回到第 3 步,用计划任务拉起 |
176
+ | `autostart kick` 说 "started but nothing is listening" | 账户从未交互登录过 | 先 RDP/控制台登录一次 |
177
+ | 截图全黑 / `fell_back: true` | 会话断开,桌面没渲染 | `cua-win-daemon client activate` |
178
+ | `recording_unavailable` | 没装 ffmpeg | `winget install Gyan.FFmpeg` |
179
+
180
+ ## 配置
181
+
182
+ | 键 | 默认 | 说明 |
183
+ |---|---|---|
184
+ | `host` | `127.0.0.1` | 隧道本地端 |
185
+ | `port` | `9000` | 与 `ssh -L` 的本地端口一致 |
186
+ | `token` / `tokenFile` | 空 / `~/.cua-win/token` | 也读环境变量 `CUA_WIN_TOKEN` |
187
+ | `sshHost` | 空 | ssh 别名。设了它、又没配 token 时,插件**自己**从远端读 token,无需手工拷贝 |
188
+ | `sshConfig` | 空 | 读 token 时用的 ssh 配置文件(默认走 ssh 自己的逻辑) |
189
+ | `tokenAuto` | `true` | 是否允许上面那种自动读取。关掉就要求显式提供 token |
190
+ | `sessionId` | `dsh` | 所有调用绑定的逻辑会话;空表示不绑定 |
191
+ | `toolPrefix` | `win_` | 工具名前缀 |
192
+ | `readonly` | `false` | 只注册只读工具(不是注册了再拒绝) |
193
+ | `claimSession` | `true` | 每次连上(含重连)都调 `cua_win_start_session` 认领会话标签。守护进程把标签绑定到连接:连接一断就变 `owner_orphaned`,只有显式 `start_session` 能拿回来,否则后续调用全是 `session_owner_mismatch` |
194
+ | `heartbeatIntervalMs` | `10000` | 心跳间隔 |
195
+ | `pongDeadlineMs` | `25000` | 超过此时长无 pong 即判连接死亡 |
196
+ | `autoReconnect` | `true` | 指数退避重连(500ms 起,上限 30s,±20% 抖动) |
197
+
198
+ ## 三层名字,各自的理由
199
+
200
+ | 层 | 例子 | 为什么 |
201
+ |---|---|---|
202
+ | 守护进程内部 | `click` | 实现与日志用短名 |
203
+ | MCP | `cua_win_click` | MCP 客户端会把多个 server 的工具汇总到一个命名空间,`read`/`ping` 必撞 |
204
+ | DSH | `win_click` | DSH 已内置 `read`/`write`/`pwsh`,注册重名会抛错 |
205
+
206
+ 映射都在 `lib/tools.js`(`toMcpName` / `toWireName`),有测试保证往返一致。
207
+
208
+ ## MCP 交互要点
209
+
210
+ - **握手**:`initialize` → `notifications/initialized` → `tools/list`。工具列表在 READY 之前取到,
211
+ 所以 `ready` 事件的监听者看到的清单已经是准确的。
212
+ - **能力来源**:以 `tools/list` 为准,不硬编码。守护进程换构建后 `listTools()` 可刷新。
213
+ - **失败语义**:工具执行失败是 `isError:true` 的**结果**,直接交给模型;只有请求本身非法
214
+ (未知工具 `-32602`、未知方法 `-32601`)才是 JSON-RPC 错误并抛出。
215
+ - **`busy` 不重试写操作**:只读工具会退避重试一次,写/输入类永不重试(点两次是真实副作用)。
216
+
217
+ ## 断线时的表现
218
+
219
+ 工具调用**不会挂住等重连**,而是立刻失败并给出可区分的码:
220
+
221
+ | 错误码 | 含义 | 该怎么做 |
222
+ |---|---|---|
223
+ | `daemon_unreachable` | 从没连上 | 起隧道,再 `client ping` 确认 |
224
+ | `daemon_reconnecting` | 曾连上,正在重连 | 重连后重试一次(该错误不带重试时间字段) |
225
+ | `handshake_failed` | token 或协议版本不对 | 停下,这是配置问题 |
226
+ | `connection_closed` | 调用在途时连接断了 | 只读工具可重试;**写与输入类不要自动重试** |
227
+
228
+ 最后一条是刻意的:`win_click`、`win_type_text`、`win_write` 有真实副作用,静默重放会点两次、写两遍。
229
+
230
+ ## 三条使用要点
231
+
232
+ 1. **先 `win_ping`**。`session_id` 为 0 说明守护进程位置不对,需重新在交互会话拉起;若 `session_id >= 1` 但 `has_interactive_desktop` 为 false(会话断开),可调用 `win_activate_desktop` 激活控制台。
233
+ 2. **`target.mode` 必填**:`uia` / `window_xy` / `screen_xy`。三种模式**不会互相回退**,
234
+ 失败就给对应的错误码。
235
+ 3. **后台点击需要复核**。`window_xy` 走 `PostMessage`,`effect:"unverifiable"`——
236
+ 要确认效果就再取一次 `win_get_window_state`。
237
+
238
+ ## 测试
239
+
240
+ ```bash
241
+ node --test test/
242
+ # 52 tests, 50 pass, 0 fail, 2 skipped
243
+ ```
244
+
245
+ 不需要 Windows,也不需要 DSH:测试用真实 TCP 的假 MCP 服务端覆盖握手、分帧、并发、
246
+ id 关联、错误语义分工、心跳判死、断线结算与退避。
247
+
248
+ 那 2 个跳过项是 DSH 输出校验器相关(需要从 DSH 安装树解析校验器,本仓库独立克隆时没有)。
249
+ 在装了 DSH 的环境里它们也会跑。
250
+
251
+ ## 改了代码,怎么让运行中的实例生效
252
+
253
+ **不用重启 `dsh web`,也不用卸载重装**——但"新开一个会话"也不够,
254
+ 因为 Node 的 ESM 缓存是**按进程**的,新会话不会重新 `import`。
255
+
256
+ 在插件管理里**禁用再启用**本插件即可:`dsh-hmr` 会比对已加载模块与磁盘,
257
+ 逐出变化的模块并重启对应 entry,从而从磁盘重新导入。
258
+
259
+ 细节与一个真实的排查案例见 [docs/DETAIL.md](docs/DETAIL.md#改了插件代码怎么让它生效)。
260
+
261
+ ## 与守护进程的关系
262
+
263
+ 插件只认协议,不认识 Windows;守护进程只认协议,不认识 DSH。两侧唯一的耦合是
264
+ `cua-win-daemon/protocol/` 下的 schema 与 conformance 样例。本目录的 `schema/` 是那两份文档的副本,
265
+ 用于把工具参数原样交给 DSH(**不手抄**,否则必然漂移)。
@@ -0,0 +1,9 @@
1
+ # Host-only bundle: no client half, no build step. The plugin is an MCP client: it holds ONE TCP
2
+ # connection to the Windows daemon (through an ssh -L tunnel), speaks JSON-RPC 2.0, and registers the
3
+ # `cua_win_*` tools the daemon advertises as DSH `win_*` tools.
4
+ - insert:
5
+ - id: cua-win
6
+ name: dsh-plugin-cua-win
7
+ config:
8
+ host: 127.0.0.1
9
+ port: 9000
package/docs/DETAIL.md ADDED
@@ -0,0 +1,94 @@
1
+ # 远程 Windows 桌面
2
+
3
+ 把远端 Windows 的文件、命令和图形界面操作,变成这一台机器上的工具。
4
+
5
+ 守护进程跑在**用户的交互会话(Session 1+)**里,而不是 `sshd` 所在的 Session 0。
6
+ 这样窗口枚举、UIA、截图、输入注入才看得见真正的桌面——Session 0 里这些 API 会返回空结果,
7
+ 看起来像工具坏了,其实是 Windows 的会话隔离。
8
+
9
+ ## 它提供什么
10
+
11
+ | 类别 | 工具 |
12
+ |---|---|
13
+ | 文件与命令 | `win_pwsh`、`win_read`、`win_write`、`win_list`、`win_read_bytes`、`win_write_bytes` |
14
+ | 窗口与元素 | `win_list_windows`、`win_list_apps`、`win_get_window_state` |
15
+ | 输入 | `win_click`、`win_double_click`、`win_right_click`、`win_scroll`、`win_drag`、`win_type_text`、`win_press_key`、`win_hotkey`、`win_set_value` |
16
+ | 窗口控制 | `win_launch_app`、`win_bring_to_front`、`win_set_window_frame` |
17
+ | 截屏与录屏 | `win_screenshot`、`win_start_recording`、`win_stop_recording`、`win_get_screen_size` |
18
+ | 图片与二进制 | `win_read_bytes`(含 `inline:true` 图片附加)、`win_write_bytes`(分块 + sha256 校验) |
19
+ | 光标 | `win_get_cursor_position`、`win_set_cursor_position` |
20
+ | 会话与诊断 | `win_ping`、`win_doctor`、`win_activate_desktop`、`win_start_session`、`win_end_session`、`win_shutdown` |
21
+
22
+ ## 使用顺序
23
+
24
+ 1. **先 `win_ping`**。看 `session_id` 是否 ≥ 1、`has_interactive_desktop` 是否为 true。
25
+ 这两项不对,后面所有 GUI 工具都会失败——不是工具的问题,是守护进程的位置不对。
26
+ 2. **照一张快照再动手**。`win_get_window_state` 返回的 `element_index` 只对那一次快照有效;
27
+ 动作前重新取,动作后再取一次确认效果。
28
+ 3. **寻址要写清楚**。每个输入工具的 `target.mode` 必填:`uia`(按元素)、`window_xy`(按窗口内坐标)、
29
+ `screen_xy`(按屏幕坐标)。三种模式**不会互相回退**,失败就报对应的错误码。
30
+
31
+ ## 三条必须知道的限制
32
+
33
+ - **后台点击的成功信号很弱。** `window_xy` 走 `PostMessage`,返回值只证明消息进了队列,
34
+ 不证明程序处理了它(UWP 的指针输入根本不读 HWND 消息队列)。所以结果是 `effect:"unverifiable"`,
35
+ 需要重新快照来确认。要真实输入就显式用 `delivery:"sendinput"`,它可能把窗口前置。
36
+ - **跨 Windows 会话列不到窗口。** `win_list_windows` 的 `windows[]` 是**本会话**的窗口,
37
+ 每条带 `session_id`;`other_sessions[]` 只给会话级摘要并标 `reachable:false`。
38
+ Windows 没有公开 API 能枚举另一个会话的 HWND,声称能做到的都是往那个会话注入了进程。
39
+ - **录屏需要已渲染的桌面。** 会话断开(RDP 挂断、控制台分离)时 gdigrab 抓不到画面,
40
+ `win_start_recording` 会以 `recording_unavailable` 明确失败,并带上 ffmpeg 的原始报错。
41
+
42
+ ## 改了插件代码,怎么让它生效
43
+
44
+ **不需要重启 `dsh web`,也不需要卸载重装。** 但也不是"新开一个会话"就够——
45
+ Node 的 ESM 模块缓存是**按进程**的,开新会话只是新增一个 agent,不会重新 `import` 插件。
46
+
47
+ 正确的做法是让 DSH 的 HMR 走一次 reconcile:**在插件管理里禁用再启用本插件**。
48
+ `dsh-hmr` 的 `reconcileProfile()` 会拿已加载模块与磁盘比对,把变化的 URL 交给
49
+ `planReplacement()` → `stopPlanned()`:逐出 ESM 缓存、停掉对应 fiber,
50
+ 之后 `recomposeProfile` 重启该 entry 时**从磁盘重新导入**。
51
+
52
+ 这条路径对 `link:` 安装的插件有效:`profileRoots()` 会把 profile 的 `node_modules`
53
+ 里所有符号链接指向的真实路径也纳入比对根目录。
54
+
55
+ `npm` / `tgz` 安装的插件同理,只是比对根目录不同。
56
+
57
+ ### 一个真实的踩坑记录
58
+
59
+ 症状:`win_screenshot({inline:true})` 的 daemon 侧明明返回了 image block,
60
+ `saveImages` 也写成功,但模型上下文里**没有图**,也没有任何诊断信息。
61
+
62
+ 定位过程说明了为什么这个坑很难看出来:
63
+
64
+ | 检查点 | 结果 |
65
+ |---|---|
66
+ | 绕过插件直连 daemon | ✅ 真的发了 image block |
67
+ | `attachments.saveImages` | ✅ 对象已在库中(内容寻址,与旧图去重) |
68
+ | 最终 tool result | ❌ 只有 text,无 image,无 `[image unavailable: …]` |
69
+ | 内置 `read_image` 读同一张 PNG | ✅ 图能进上下文 |
70
+
71
+ 四处全好,只有投影这一环丢了。根因是 `execute` 已经把返回值从字符串改成对象,
72
+ 而 `projectContent` 还在用 `!==` 做引用比较:
73
+
74
+ ```js
75
+ if (result?.value !== projection.value) return undefined // 旧代码
76
+ ```
77
+
78
+ DSH 的 pipeline 会对返回值做 `snapshotJsonValue()` + `deepFreeze()`,
79
+ 交给 `projectContent` 的是**结构相同但引用不同**的对象。`!==` 恒真,投影被静默丢弃。
80
+ 改用 `isDeepStrictEqual`(DSH 官方 MCP client 用的也是它)后恢复正常。
81
+
82
+ 教训有两条:
83
+
84
+ 1. **"各层都报成功"不等于链路通了。** daemon 说发出去了、存储说写成功了、
85
+ 投影说登记了,三者都对,但只要中间有一次引用比较失败,结果就是模型看不见。
86
+ 2. **测试可能固化错误的语义。** 当时的测试断言"结构相同但不同对象不该被识别",
87
+ 它通过了,但真实链路是坏的。现在改为断言克隆对象**必须**投影成功。
88
+
89
+ ### 留意 `image_attached`
90
+
91
+ daemon 的 `image_attached` 只表示"daemon 侧附加了图片",**不代表它进了模型上下文**。
92
+ 要确认端到端通没通,唯一可靠的办法是看模型能不能描述画面内容。
93
+
94
+ 请以 [说明文档](../../cua-win-daemon/docs/tools.md) 为准:每个工具的参数与返回示例都在那里。
package/index.js ADDED
@@ -0,0 +1,218 @@
1
+ // dsh-plugin-cua-win — Host plugin entry point.
2
+ //
3
+ // Shape: a plain Cordis plugin (`name`, `inject`, `Config`, `apply`). Tools are registered through
4
+ // `ctx.tools.register` with object literals rather than `defineTool`, because the DSH internals
5
+ // that export `defineTool` are not published to npm and do not resolve from a profile directory;
6
+ // registering the same shape is what the working third-party plugins in this profile do.
7
+ //
8
+ // The connection is created once, at activation, and held for the plugin's lifetime: a per-call
9
+ // connect would add a TCP handshake to every tool call and would make session ownership
10
+ // meaningless.
11
+
12
+ import z from '@deepseek-ai/schemastery'
13
+ import { readFileSync } from 'node:fs'
14
+ import { homedir } from 'node:os'
15
+ import { join } from 'node:path'
16
+ import { Connection, DaemonError, STATE } from './lib/connection.js'
17
+ import { buildTools, READONLY_TOOLS } from './lib/tools.js'
18
+
19
+ export const name = 'cua-win'
20
+
21
+ /** Only the tool registry is required; everything else degrades gracefully. */
22
+ export const inject = ['tools']
23
+
24
+ const defaultTokenFile = () => join(homedir(), '.cua-win', 'token')
25
+
26
+ export const Config = z.object({
27
+ host: z.string().default('127.0.0.1').description('Local end of the ssh -L tunnel.'),
28
+ port: z.natural().min(1).max(65535).default(9000)
29
+ .description('Local port of the tunnel, i.e. ssh -L <port>:127.0.0.1:<port>.'),
30
+ token: z.string().default('').description('Bearer token. Overrides tokenFile and CUA_WIN_TOKEN.'),
31
+ tokenFile: z.string().default('').description('File holding the daemon token; defaults to ~/.cua-win/token.'),
32
+ sshHost: z.string().default('')
33
+ .description('ssh alias for the Windows host. When set and no token is configured, the plugin reads the token from the host itself, so it never has to be copied by hand.'),
34
+ sshConfig: z.string().default('')
35
+ .description('ssh config file to use for the token fetch (default: ssh does). Set this when your hosts live in a non-default file.'),
36
+ tokenAuto: z.boolean().default(true)
37
+ .description('Fetch the token over ssh when none is configured. Turn off to require an explicit token.'),
38
+ sessionId: z.string().default('dsh')
39
+ .description('Logical session label every call is bound to. Empty means unbound.'),
40
+ toolPrefix: z.string().default('win_')
41
+ .description('Prefix on the DSH tool names. The daemon uses unprefixed names; the prefix only avoids clashing with built-in tools.'),
42
+ readonly: z.boolean().default(false)
43
+ .description('Register only the read-only tools. Mutating tools are not registered at all, so the model cannot see them.'),
44
+ callTimeoutMs: z.natural().default(30_000).description('Default deadline for one call.'),
45
+ heartbeatIntervalMs: z.natural().default(10_000).description('How often to ping an idle connection.'),
46
+ pongDeadlineMs: z.natural().default(25_000)
47
+ .description('Treat the connection as dead after this much silence. This is the only way to notice a daemon that died behind an SSH tunnel.'),
48
+ reconnectInitialMs: z.natural().default(500),
49
+ reconnectMaxMs: z.natural().default(30_000),
50
+ autoReconnect: z.boolean().default(true),
51
+ claimSession: z.boolean().default(true)
52
+ .description('On connect, call the daemon start_session tool for sessionId so its per-session state is ready.'),
53
+ })
54
+
55
+ /**
56
+ * Order of precedence for the token: explicit config, environment, file.
57
+ *
58
+ * Returns the source too, because a file copy is a cache that may be stale: `serve` writes a new
59
+ * token whenever its state directory is recreated, and the old copy then fails the handshake with
60
+ * an opaque bad_token. A file-sourced token is therefore refreshable over ssh; an explicit one
61
+ * never is.
62
+ */
63
+ function resolveToken(config) {
64
+ if (config.token) return { token: config.token, refreshable: false }
65
+ if (process.env.CUA_WIN_TOKEN) return { token: process.env.CUA_WIN_TOKEN, refreshable: false }
66
+ const file = config.tokenFile || defaultTokenFile()
67
+ try {
68
+ const value = readFileSync(file, 'utf8').trim()
69
+ // No token is not itself fatal: the daemon may be running without one for local debugging,
70
+ // and a missing file should not mask the real handshake error.
71
+ return value.length > 0 ? { token: value, refreshable: true } : { token: '', refreshable: false }
72
+ } catch {
73
+ return { token: '', refreshable: false }
74
+ }
75
+ }
76
+
77
+ /**
78
+ * Register the tools. Exported separately from `apply` so tests can exercise registration against
79
+ * a stub context without a live daemon.
80
+ */
81
+ export function registerTools(ctx, config, connection, claimSession, forceClaim, sessionState) {
82
+ const tools = buildTools(connection, {
83
+ ctx,
84
+ prefix: config.toolPrefix,
85
+ sessionId: config.sessionId,
86
+ readonly: config.readonly,
87
+ claimSession,
88
+ forceClaim,
89
+ sessionState,
90
+ })
91
+
92
+ for (const tool of tools) {
93
+ ctx.effect(() => ctx.tools.register(tool), `cua-win: ${tool.name}`)
94
+ }
95
+
96
+ return tools
97
+ }
98
+
99
+ export function apply(ctx, config = {}) {
100
+ const resolved = resolveToken(config)
101
+
102
+ const connection = new Connection({
103
+ host: config.host,
104
+ port: config.port,
105
+ token: resolved.token,
106
+ tokenRefreshable: resolved.refreshable,
107
+ sshHost: config.sshHost,
108
+ sshConfig: config.sshConfig,
109
+ tokenAuto: config.tokenAuto,
110
+ callTimeoutMs: config.callTimeoutMs,
111
+ heartbeatIntervalMs: config.heartbeatIntervalMs,
112
+ pongDeadlineMs: config.pongDeadlineMs,
113
+ reconnectInitialMs: config.reconnectInitialMs,
114
+ reconnectMaxMs: config.reconnectMaxMs,
115
+ autoReconnect: config.autoReconnect,
116
+ })
117
+
118
+ // Surface connection problems in the log instead of letting a tool call be the first sign.
119
+ connection.on('disconnected', (reason) => {
120
+ ctx.logger?.('cua-win')?.warn?.(`connection lost: ${reason}`)
121
+ })
122
+ // The daemon owns the session label and ties it to the connection: when this connection goes
123
+ // away it marks the label OwnerOrphaned, and only an explicit start_session takes it back. A
124
+ // reconnect therefore has to re-claim, or every session-bound call fails with
125
+ // session_owner_mismatch until the 300s TTL reaps it. `ready` fires on every connect attempt,
126
+ // including the first, so this is the one place that covers both cases.
127
+ let claimInFlight = null
128
+ let claimGeneration = 0
129
+ let claimed = false
130
+ const sessionState = { explicitlyEnded: false }
131
+ connection.on('disconnected', () => {
132
+ claimGeneration++
133
+ claimed = false
134
+ claimInFlight = null
135
+ })
136
+ const claimSession = (why) => {
137
+ if (!config.claimSession || !config.sessionId) return Promise.resolve()
138
+ if (claimed) return Promise.resolve()
139
+ if (claimInFlight) return claimInFlight
140
+ const generation = claimGeneration
141
+ const attempt = (async () => {
142
+ try {
143
+ const result = await connection.callTool('cua_win_start_session', { id: config.sessionId })
144
+ if (result?.isError) throw new Error(result.content?.[0]?.text ?? 'session claim failed')
145
+ if (generation === claimGeneration) claimed = true
146
+ } catch (error) {
147
+ // Do NOT mark this generation claimed: a failed claim used to be swallowed here and then
148
+ // every gated call went out anyway, so the model saw `session_ended` on the first tool call
149
+ // of a session while the plugin believed the label was already Active.
150
+ ctx.logger?.('cua-win')?.warn?.(
151
+ `could not start session "${config.sessionId}"${why ? ` (${why})` : ''}: ${error.message}`)
152
+ } finally {
153
+ if (generation === claimGeneration) claimInFlight = null
154
+ }
155
+ })()
156
+ claimInFlight = attempt
157
+ return claimInFlight
158
+ }
159
+
160
+ /**
161
+ * Claim the label unconditionally, ignoring the "already claimed" shortcut.
162
+ *
163
+ * Called when a gated call comes back with a session-state refusal, which means the daemon's
164
+ * view of the label drifted from ours (idle TTL, another connection, a restart that persisted
165
+ * the tombstone). Resetting `claimed` alone would be wrong: with a claim already in flight the
166
+ * shortcut would hand back that stale attempt instead of a fresh one.
167
+ */
168
+ const forceClaim = (why) => {
169
+ claimed = false
170
+ claimInFlight = null
171
+ claimGeneration++
172
+ return claimSession(why)
173
+ }
174
+
175
+ connection.on('ready', (server) => {
176
+ sessionState.explicitlyEnded = false
177
+ ctx.logger?.('cua-win')?.info?.(
178
+ `connected over MCP ${connection.protocolVersion}: ${connection.availableTools.size} tools, `
179
+ + `host session ${server?.sessionId ?? '?'}`,
180
+ )
181
+ // Re-claim on every (re)connect. A failure is logged, never fatal.
182
+ void claimSession('connect')
183
+ })
184
+ connection.on('warning', (text) => ctx.logger?.('cua-win')?.warn?.(text))
185
+
186
+ // Connect in the background: activation must not block on an unreachable host, and the tools
187
+ // should still be visible so a call can report daemon_unreachable with an actionable message.
188
+ const bootstrap = (async () => {
189
+ try {
190
+ // `ready` performs the initial claim too, so there is no second start_session here.
191
+ await connection.start()
192
+ await claimSession('connect')
193
+ } catch (error) {
194
+ ctx.logger?.('cua-win')?.warn?.(
195
+ `not connected (${error.code ?? 'error'}): ${error.message}. `
196
+ + 'Start the tunnel with `ssh -N -L <port>:127.0.0.1:<port> <user>@<host>`; the tools will '
197
+ + 'answer daemon_unreachable until it is reachable.',
198
+ )
199
+ connection.startAutoReconnect()
200
+ }
201
+ })()
202
+
203
+ registerTools(ctx, config, connection, claimSession, forceClaim, sessionState)
204
+
205
+ ctx.effect(() => () => {
206
+ connection.dispose()
207
+ }, 'cua-win: connection')
208
+
209
+ // Expose a tiny diagnostic without registering a tool for it.
210
+ ctx.on?.('dispose', () => connection.dispose())
211
+
212
+ // Keep the promise referenced so an unhandled rejection can never escape activation.
213
+ bootstrap.catch(() => {})
214
+
215
+ return { connection }
216
+ }
217
+
218
+ export { Connection, DaemonError, STATE, READONLY_TOOLS }