@capyclaw/windows-control 0.0.0-stage → 0.1.3

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.
Files changed (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +142 -2
  3. package/THIRD_PARTY_NOTICES.md +20 -0
  4. package/cordis.patch.yml +32 -0
  5. package/lib/config.mjs +126 -0
  6. package/lib/mcp-json.mjs +80 -0
  7. package/node_modules/@capyclaw/foundation/README.md +51 -0
  8. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  9. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  10. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  11. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  12. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  13. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  14. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  15. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  16. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  17. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  18. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  19. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  20. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  32. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  33. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  34. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  35. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  36. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  37. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  38. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  39. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  40. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  41. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  42. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  43. package/node_modules/@capyclaw/foundation/package.json +53 -0
  44. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  45. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  46. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  47. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  48. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  76. package/node_modules/@capyclaw/portal/README.md +70 -0
  77. package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
  78. package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
  79. package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
  80. package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
  81. package/node_modules/@capyclaw/portal/package.json +40 -0
  82. package/node_modules/@capyclaw/service-broker/README.md +104 -0
  83. package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
  84. package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
  85. package/node_modules/@capyclaw/service-broker/lib/control.mjs +209 -0
  86. package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
  87. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1290 -0
  88. package/node_modules/@capyclaw/service-broker/lib/host.mjs +187 -0
  89. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +262 -0
  90. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +275 -0
  91. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +48 -0
  92. package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
  93. package/node_modules/@capyclaw/service-broker/package.json +65 -0
  94. package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
  95. package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
  96. package/node_modules/@capyclaw/service-broker/services.json +3 -0
  97. package/package.json +65 -4
  98. package/plugin.mjs +32 -0
  99. package/server/relay.mjs +752 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 maple496
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,143 @@
1
- # Temporary Holding Version
1
+ # @capyclaw/windows-control
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-MCP](https://github.com/CursorTouch/Windows-MCP) 的 21 个桌面工具接入 DSH:
4
+ UIA 树快照、截图、键鼠、应用启动、PowerShell、注册表、文件、剪贴板、进程、通知。
5
+
6
+ 插件本身不做 Windows 自动化,只负责三件事:
7
+
8
+ 1. 用 `uvx` 拉起并守护 `windows-mcp serve`(Python 3.14,Streamable HTTP);
9
+ 2. 对外提供固定端口的 `/mcp` 代理与 `/healthz`;
10
+ 3. 注入本地工具 `windows_capabilities`,满足 suite 契约检查。
11
+
12
+ ```
13
+ dsh ── runtime-driver ──> relay(node, :39660) ──proxy──> windows-mcp(python, 临时端口)
14
+ │
15
+ └─ /healthz /metrics /mcp
16
+ ```
17
+
18
+ ## 工具面
19
+
20
+ 默认全量暴露 21 个上游工具(可用 `tools` / `excludeTools` 裁剪):
21
+
22
+ | 类别 | 工具 |
23
+ |---|---|
24
+ | 观察 | `Snapshot` `Screenshot` `DisplayInventory` `ControlStatus` `Wait` `WaitFor` |
25
+ | 输入 | `Click` `Type` `Scroll` `Move` `Shortcut` `MultiSelect` `MultiEdit` |
26
+ | 应用 | `App` |
27
+ | 系统 | `PowerShell` `Process` `Registry` `FileSystem` `Clipboard` `Notification` `Scrape` |
28
+
29
+ 另加 1 个本地工具:
30
+
31
+ - `windows_capabilities`:返回 `contractVersion`、上游版本/状态、工具清单与生效配置。
32
+
33
+ 模型侧看到的名字是 `mcp__windows__<Tool>`,例如 `mcp__windows__Snapshot`。
34
+
35
+ ## 运行前提
36
+
37
+ - **Windows 10 / 11**(上游要求;本插件 `dsh.platform = desktop`)
38
+ - **uv**(提供 `uvx`)。安装:`pip install uv` 或 `winget install astral-sh.uv`
39
+ - 首次运行需要网络:`uvx` 会下载 Python 3.14(约 30MB)和 86 个依赖包。
40
+ 国内网络建议配置镜像,否则会卡在 python-build-standalone 下载:
41
+
42
+ ```yaml
43
+ config:
44
+ mirror: "https://registry.npmmirror.com/-/binary/python-build-standalone"
45
+ ```
46
+
47
+ 也可以在启动 dsh 前设置 `UV_PYTHON_INSTALL_MIRROR`。
48
+
49
+ 首次启动通常 1–2 分钟;之后 `uv` 缓存命中,冷启动约数秒。
50
+
51
+ ## 启用
52
+
53
+ `cordis.patch.yml` 已包含完整 rows:
54
+
55
+ ```yaml
56
+ - insert:
57
+ - id: windows-control
58
+ name: "@capyclaw/windows-control"
59
+ config:
60
+ package: "windows-mcp==0.8.8"
61
+ python: "3.14"
62
+ telemetry: false
63
+ - id: mcp-windows
64
+ name: "@deepseek-ai/dsh-mcp-client"
65
+ config:
66
+ serverName: windows
67
+ transport: streamable-http
68
+ # 值形如 http://<relay 地址>/mcp;真实值以本包 cordis.patch.yml 为准
69
+ url: "<relay 地址>/mcp"
70
+ failOnStartupError: false
71
+ toolCallTimeoutMs: 180000
72
+ ```
73
+
74
+ 端点固定(`dsh-mcp-client` 的 URL 在 profile 注入时已确定,不能用 `auto`):具体值以本包
75
+ `cordis.patch.yml` 为准,改要两处一起改。
76
+
77
+ ## 配置
78
+
79
+ | key | 环境变量 | 默认 | 说明 |
80
+ |---|---|---|---|
81
+ | `package` | `DSH_WINDOWS_MCP_PACKAGE` | `windows-mcp==0.8.8` | 上游包与版本(升级只改这里) |
82
+ | `python` | `DSH_WINDOWS_MCP_PYTHON` | `3.14` | 上游要求的 Python 版本 |
83
+ | `uvxPath` | `DSH_WINDOWS_MCP_UVX` | `uvx` | PATH 里找不到时给绝对路径 |
84
+ | `tools` | `DSH_WINDOWS_MCP_TOOLS` | 空=全量 | 显式白名单,逗号分隔 |
85
+ | `excludeTools` | `DSH_WINDOWS_MCP_EXCLUDE_TOOLS` | 空 | 黑名单,逗号分隔(白名单优先) |
86
+ | `telemetry` | `DSH_WINDOWS_MCP_TELEMETRY` | `false` | 上游 posthog 匿名遥测,默认关闭 |
87
+ | `screenshotFlash` | `DSH_WINDOWS_MCP_FLASH` | `true` | 截图时画高亮边框 |
88
+ | `stateless` | `DSH_WINDOWS_MCP_STATELESS` | `true` | 上游无会话 HTTP,重启后客户端免重新握手 |
89
+ | `mirror` | `DSH_WINDOWS_MCP_MIRROR` | 空 | Python 下载镜像 |
90
+ | `startupTimeoutMs` | `DSH_WINDOWS_MCP_STARTUP_TIMEOUT_MS` | `180000` | 等上游就绪的上限 |
91
+ | `requestTimeoutMs` | `DSH_WINDOWS_MCP_REQUEST_TIMEOUT_MS` | `180000` | 单次代理请求超时 |
92
+ | `logDir` | `DSH_WINDOWS_MCP_LOG_DIR` | `~/.dsh-windows-control` | relay 日志目录(2MB 轮转) |
93
+
94
+ 示例:只暴露观察类工具
95
+
96
+ ```yaml
97
+ config:
98
+ tools: ["Snapshot", "Screenshot", "DisplayInventory", "ControlStatus"]
99
+ ```
100
+
101
+ ## 健康与契约
102
+
103
+ - `GET /healthz`:`{ ok, pid, contractVersion, upstream: { state, ready, port, pid, restarts }, tools }`。
104
+ 上游启动失败且重启耗尽时返回 503,broker 会明确报错而不是静默降级。
105
+ - `GET /metrics`:转发/本地应答/错误计数、上游重启次数。
106
+ - `tools/call windows_capabilities`:suite `contract` 检查读取其中的 `contractVersion`(major 必须为 1)。
107
+
108
+ ## 安全边界
109
+
110
+ **这个插件把整台机器的操作权交给模型**:`PowerShell`、`Registry`、`FileSystem`、
111
+ `Process` 都能产生不可逆副作用。启用前请确认:
112
+
113
+ - 只在受控机器/测试机上开启;生产机建议用 `tools` 白名单只放观察类工具。
114
+ - 代理只绑定 `127.0.0.1`,不对外网开放;上游端口每次随机分配。
115
+ - 上游遥测默认关闭(`ANONYMIZED_TELEMETRY=false`)。
116
+ - 上游有**控制门**:用户正在操作键鼠时,工具返回 `USER_CONTROL`,空闲约 10 秒后才交给 AI。
117
+ 这是上游 0.8.8 的固定行为,PyPI 版没有 `--no-control`;需要可配置策略时要等上游发版或改用 git 源。
118
+
119
+ ## 排障
120
+
121
+ | 现象 | 处理 |
122
+ |---|---|
123
+ | `uvx` 不存在 | 安装 uv,或用 `uvxPath` 指到 `uvx.exe` 绝对路径 |
124
+ | 首次启动卡住 | 配 `mirror`;日志见 `<logDir>/relay.log` |
125
+ | relay 端点被占 | 释放占用端口;端口写死在 patch 与 dsh-mcp-client 的 `url` 两处,改要一起改 |
126
+ | 工具列表为空 | 看 `/healthz` 的 `upstream.lastError`;上游未就绪时 dsh 客户端会重连 |
127
+ | 调用返回 `USER_CONTROL` | 人不在操作键鼠时重试;或改用 `--tools` 排除输入类工具 |
128
+ | 截图返回大图 | `toolCallTimeoutMs` 已设 180s;模型不支持图片时 dsh 会给诊断文本 |
129
+
130
+ ## 开发与测试
131
+
132
+ ```bash
133
+ npm test # 单元测试(无外部依赖)
134
+ DSH_WINDOWS_MCP_E2E=1 npm run test:e2e # 真机端到端(需 uv + 网络/缓存)
135
+ ```
136
+
137
+ 端到端会拉起 relay,验证:健康检查、`initialize`、22 个工具(21 上游 + 契约工具)、
138
+ `windows_capabilities`、`ControlStatus`。
139
+
140
+ ## 许可
141
+
142
+ 本插件 MIT。上游 windows-mcp 为 MIT,其内置的 UIAutomation 封装为 Apache-2.0;
143
+ 详见 [THIRD_PARTY_NOTICES.md](./THIRD_PARTY_NOTICES.md)。
@@ -0,0 +1,20 @@
1
+ # 第三方声明
2
+
3
+ 本插件**不内置**上游源码,运行时通过 `uvx` 从 PyPI 安装并拉起
4
+ [Windows-MCP](https://github.com/CursorTouch/Windows-MCP)(`windows-mcp` 包)。
5
+ 分发或再打包时请保留以下声明。
6
+
7
+ ## windows-mcp
8
+
9
+ - 项目:Windows-MCP(CursorTouch)
10
+ - 许可证:MIT License
11
+ - 版权:Copyright (c) 2025 JEOMON GEORGE
12
+ - 说明:MCP 服务器本体;本插件只调用它的 CLI 与 Streamable HTTP 端点。
13
+
14
+ ## Python-UIAutomation-for-Windows
15
+
16
+ - 项目:Python-UIAutomation-for-Windows(yinkaisheng)
17
+ - 许可证:Apache License 2.0
18
+ - 说明:`windows-mcp` 内置了该库的 UIAutomation 封装(`windows_mcp/uia/`)。
19
+ 如果要把 `windows-mcp` 源码拷进本仓库或 npm 包(方案 B:源码内置),
20
+ 必须同时保留 MIT 与 Apache-2.0 两份声明及 NOTICE 要求。
@@ -0,0 +1,32 @@
1
+ # windows-control bundle patch
2
+ # 托管 windows-mcp(PyPI 包,Python >= 3.14)并把 21 个桌面工具接入 DSH 工具面。
3
+ #
4
+ # 配置项(cordis config → 环境变量 → 默认值):
5
+ # package 上游包与版本 DSH_WINDOWS_MCP_PACKAGE windows-mcp==0.8.8
6
+ # python uv 托管的 Python DSH_WINDOWS_MCP_PYTHON 3.14
7
+ # uvxPath uvx 绝对路径 DSH_WINDOWS_MCP_UVX PATH 里的 uvx
8
+ # tools 显式工具白名单 DSH_WINDOWS_MCP_TOOLS 空 = 全量 21 个
9
+ # excludeTools 工具黑名单 DSH_WINDOWS_MCP_EXCLUDE_TOOLS 空
10
+ # telemetry 上报匿名遥测 DSH_WINDOWS_MCP_TELEMETRY false
11
+ # screenshotFlash 截图高亮边框 DSH_WINDOWS_MCP_FLASH true
12
+ # stateless 无会话 HTTP DSH_WINDOWS_MCP_STATELESS true
13
+ # mirror Python 下载镜像 DSH_WINDOWS_MCP_MIRROR 空
14
+ # startupTimeoutMs 等待上游就绪 DSH_WINDOWS_MCP_STARTUP_TIMEOUT_MS 180000
15
+ #
16
+ # 端口固定 39660:dsh-mcp-client 的 URL 在注入时已确定,不做 auto。
17
+
18
+ - insert:
19
+ - id: windows-control
20
+ name: "@capyclaw/windows-control"
21
+ config:
22
+ package: "windows-mcp==0.8.8"
23
+ python: "3.14"
24
+ telemetry: false
25
+ - id: mcp-windows
26
+ name: "@deepseek-ai/dsh-mcp-client"
27
+ config:
28
+ serverName: windows
29
+ transport: streamable-http
30
+ url: "http://127.0.0.1:39660/mcp"
31
+ failOnStartupError: false
32
+ toolCallTimeoutMs: 180000
package/lib/config.mjs ADDED
@@ -0,0 +1,126 @@
1
+ /**
2
+ * windows-control 配置:插件配置 → relay 环境变量 → 上游启动参数。
3
+ *
4
+ * 纯函数,无 IO;relay 与测试共用同一份口径。
5
+ */
6
+
7
+ export const DEFAULTS = Object.freeze({
8
+ /** 上游 PyPI 包与版本。升级上游只需要改这里(或插件 config.package)。 */
9
+ packageSpec: 'windows-mcp==0.8.8',
10
+ /** windows-mcp 要求 Python >= 3.14;uv 会自动下载并托管该版本。 */
11
+ python: '3.14',
12
+ /** uvx 可执行文件;PATH 里没有时用 config.uvxPath 指向绝对路径。 */
13
+ uvx: 'uvx',
14
+ host: '127.0.0.1',
15
+ port: 39660,
16
+ startupTimeoutMs: 180000,
17
+ requestTimeoutMs: 180000,
18
+ stateless: true,
19
+ telemetry: false,
20
+ screenshotFlash: true,
21
+ tools: [],
22
+ excludeTools: [],
23
+ mirror: '',
24
+ logDir: '',
25
+ })
26
+
27
+ const MAX_TIMEOUT_MS = 30 * 60 * 1000
28
+
29
+ function asBool(value, fallback) {
30
+ if (value === undefined || value === null || value === '') return fallback
31
+ if (typeof value === 'boolean') return value
32
+ const text = String(value).trim().toLowerCase()
33
+ if (['1', 'true', 'yes', 'on'].includes(text)) return true
34
+ if (['0', 'false', 'no', 'off'].includes(text)) return false
35
+ return fallback
36
+ }
37
+
38
+ function asInt(value, fallback, min = 1000) {
39
+ const num = Number(value)
40
+ if (!Number.isFinite(num)) return fallback
41
+ return Math.min(MAX_TIMEOUT_MS, Math.max(min, Math.round(num)))
42
+ }
43
+
44
+ /** 逗号/空白分隔的工具名单;空项丢弃,重复项去重。 */
45
+ export function splitList(value) {
46
+ if (Array.isArray(value)) return [...new Set(value.map((item) => String(item).trim()).filter(Boolean))]
47
+ if (typeof value !== 'string') return []
48
+ return [...new Set(value.split(/[,\s]+/).map((item) => item.trim()).filter(Boolean))]
49
+ }
50
+
51
+ /** relay 进程的完整配置(环境变量 + 默认值)。 */
52
+ export function readConfig(env = process.env) {
53
+ return {
54
+ host: env.DSH_WINDOWS_MCP_HOST || DEFAULTS.host,
55
+ port: Number(env.DSH_WINDOWS_MCP_PORT) || DEFAULTS.port,
56
+ packageSpec: env.DSH_WINDOWS_MCP_PACKAGE || DEFAULTS.packageSpec,
57
+ python: env.DSH_WINDOWS_MCP_PYTHON || DEFAULTS.python,
58
+ uvx: env.DSH_WINDOWS_MCP_UVX || DEFAULTS.uvx,
59
+ mirror: env.DSH_WINDOWS_MCP_MIRROR || DEFAULTS.mirror,
60
+ tools: splitList(env.DSH_WINDOWS_MCP_TOOLS),
61
+ excludeTools: splitList(env.DSH_WINDOWS_MCP_EXCLUDE_TOOLS),
62
+ telemetry: asBool(env.DSH_WINDOWS_MCP_TELEMETRY, DEFAULTS.telemetry),
63
+ screenshotFlash: asBool(env.DSH_WINDOWS_MCP_FLASH, DEFAULTS.screenshotFlash),
64
+ stateless: asBool(env.DSH_WINDOWS_MCP_STATELESS, DEFAULTS.stateless),
65
+ startupTimeoutMs: asInt(env.DSH_WINDOWS_MCP_STARTUP_TIMEOUT_MS, DEFAULTS.startupTimeoutMs),
66
+ requestTimeoutMs: asInt(env.DSH_WINDOWS_MCP_REQUEST_TIMEOUT_MS, DEFAULTS.requestTimeoutMs),
67
+ maxRestarts: asInt(env.DSH_WINDOWS_MCP_MAX_RESTARTS, 3, 0),
68
+ logDir: env.DSH_WINDOWS_MCP_LOG_DIR || DEFAULTS.logDir,
69
+ }
70
+ }
71
+
72
+ /**
73
+ * 上游 `windows-mcp serve` 的参数(不含可执行文件本身)。
74
+ * --tools 与 --exclude-tools 互斥:显式名单优先,传给上游由它裁决。
75
+ */
76
+ export function buildUpstreamArgs(config, port) {
77
+ const args = [
78
+ '--python', config.python,
79
+ '--from', config.packageSpec,
80
+ 'windows-mcp', 'serve',
81
+ '--transport', 'streamable-http',
82
+ '--host', DEFAULTS.host,
83
+ '--port', String(port),
84
+ ]
85
+ if (config.tools.length) args.push('--tools', config.tools.join(','))
86
+ else if (config.excludeTools.length) args.push('--exclude-tools', config.excludeTools.join(','))
87
+ if (config.stateless) args.push('--stateless-http')
88
+ return args
89
+ }
90
+
91
+ /** 上游子进程环境:默认关遥测,固定 UTF-8,镜像按需注入。 */
92
+ export function buildUpstreamEnv(config, base = process.env) {
93
+ const env = {
94
+ ...base,
95
+ ANONYMIZED_TELEMETRY: config.telemetry ? 'true' : 'false',
96
+ PYTHONUTF8: '1',
97
+ PYTHONIOENCODING: 'utf-8',
98
+ WINDOWS_MCP_DISABLE_FLASH: config.screenshotFlash ? '0' : '1',
99
+ }
100
+ if (config.mirror) env.UV_PYTHON_INSTALL_MIRROR = config.mirror
101
+ return env
102
+ }
103
+
104
+ /** 插件 config → relay 环境变量;只输出有值的键,避免 "undefined" 被展开成字符串。 */
105
+ export function configToEnv(config = {}, pkgVersion = '0.0.0') {
106
+ const env = { DSH_WINDOWS_MCP_VERSION: String(pkgVersion) }
107
+ if (config.package) env.DSH_WINDOWS_MCP_PACKAGE = String(config.package)
108
+ if (config.python) env.DSH_WINDOWS_MCP_PYTHON = String(config.python)
109
+ if (config.uvxPath) env.DSH_WINDOWS_MCP_UVX = String(config.uvxPath)
110
+ if (config.mirror) env.DSH_WINDOWS_MCP_MIRROR = String(config.mirror)
111
+ if (config.logDir) env.DSH_WINDOWS_MCP_LOG_DIR = String(config.logDir)
112
+ if (Array.isArray(config.tools) && config.tools.length) env.DSH_WINDOWS_MCP_TOOLS = config.tools.join(',')
113
+ if (Array.isArray(config.excludeTools) && config.excludeTools.length) {
114
+ env.DSH_WINDOWS_MCP_EXCLUDE_TOOLS = config.excludeTools.join(',')
115
+ }
116
+ if (config.telemetry !== undefined) env.DSH_WINDOWS_MCP_TELEMETRY = String(Boolean(config.telemetry))
117
+ if (config.screenshotFlash !== undefined) env.DSH_WINDOWS_MCP_FLASH = String(Boolean(config.screenshotFlash))
118
+ if (config.stateless !== undefined) env.DSH_WINDOWS_MCP_STATELESS = String(Boolean(config.stateless))
119
+ if (config.startupTimeoutMs !== undefined) {
120
+ env.DSH_WINDOWS_MCP_STARTUP_TIMEOUT_MS = String(config.startupTimeoutMs)
121
+ }
122
+ if (config.requestTimeoutMs !== undefined) {
123
+ env.DSH_WINDOWS_MCP_REQUEST_TIMEOUT_MS = String(config.requestTimeoutMs)
124
+ }
125
+ return env
126
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * MCP JSON-RPC 的纯函数工具:解析 SSE、注入契约工具、拼本地响应。
3
+ *
4
+ * 上游 windows-mcp 用 FastMCP,可能以 `text/event-stream` 回包;
5
+ * 代理层在这些边界上统一成 JSON,避免把 SSE 细节漏给调用方。
6
+ */
7
+
8
+ export const CAPABILITY_TOOL_NAME = 'windows_capabilities'
9
+
10
+ export const CAPABILITY_TOOL = Object.freeze({
11
+ name: CAPABILITY_TOOL_NAME,
12
+ description: '读取 Windows 控制插件的契约版本、上游 windows-mcp 版本、当前工具清单与生效配置。',
13
+ inputSchema: Object.freeze({
14
+ type: 'object',
15
+ properties: Object.freeze({}),
16
+ additionalProperties: false,
17
+ }),
18
+ })
19
+
20
+ /** SSE(多段 data:)或普通 JSON 文本 → JS 值;空文本返回 null。 */
21
+ export function parseSseOrJson(text) {
22
+ const trimmed = String(text ?? '').trim()
23
+ if (!trimmed) return null
24
+ if (trimmed.startsWith('{') || trimmed.startsWith('[') || trimmed.startsWith('"')) {
25
+ return JSON.parse(trimmed)
26
+ }
27
+ const payloads = trimmed
28
+ .split(/\r?\n/)
29
+ .filter((line) => line.startsWith('data:'))
30
+ .map((line) => line.slice(5).trim())
31
+ .filter(Boolean)
32
+ if (!payloads.length) return null
33
+ const parsed = payloads.map((item) => JSON.parse(item))
34
+ return parsed.length === 1 ? parsed[0] : parsed
35
+ }
36
+
37
+ /** 在 tools/list 响应里补一条 windows_capabilities;返回是否真的改写了。 */
38
+ export function augmentToolsList(message) {
39
+ const tools = message?.result?.tools
40
+ if (!Array.isArray(tools)) return false
41
+ if (tools.some((tool) => tool?.name === CAPABILITY_TOOL_NAME)) return false
42
+ tools.push({ ...CAPABILITY_TOOL, inputSchema: { ...CAPABILITY_TOOL.inputSchema, properties: {} } })
43
+ return true
44
+ }
45
+
46
+ /** 从 tools/list 响应提取稳定工具清单;不是工具列表则返回 null。 */
47
+ export function toolNamesFrom(message) {
48
+ const tools = message?.result?.tools
49
+ if (!Array.isArray(tools)) return null
50
+ return tools
51
+ .filter((tool) => tool && typeof tool.name === 'string' && tool.name)
52
+ .map((tool) => ({
53
+ name: tool.name,
54
+ description: typeof tool.description === 'string' ? tool.description : '',
55
+ }))
56
+ }
57
+
58
+ /** 是否是本代理本地应答的契约工具调用。 */
59
+ export function isCapabilityCall(message) {
60
+ return message?.method === 'tools/call' && message?.params?.name === CAPABILITY_TOOL_NAME
61
+ }
62
+
63
+ /** 构造本地契约工具的 JSON-RPC 响应;通知(无 id)返回 null。 */
64
+ export function capabilityResult(message, payload) {
65
+ if (message?.id === undefined || message?.id === null) return null
66
+ return {
67
+ jsonrpc: '2.0',
68
+ id: message.id,
69
+ result: {
70
+ content: [{ type: 'text', text: JSON.stringify(payload, null, 2) }],
71
+ },
72
+ }
73
+ }
74
+
75
+ /** JSON-RPC 错误响应。 */
76
+ export function rpcError(id, code, message, data) {
77
+ const error = { code, message }
78
+ if (data !== undefined) error.data = data
79
+ return { jsonrpc: '2.0', id: id ?? null, error }
80
+ }
@@ -0,0 +1,51 @@
1
+ # @capyclaw/foundation
2
+
3
+ dsh 插件基石层:接口 ABI、插件加载器与内核服务 `ctx.os`。
4
+
5
+ 应用插件不再写 `inject` / `apply` / provider 装配,只声明「我实现了哪个接口」:
6
+
7
+ ```js
8
+ import { createPlugin, skillProvider } from '@capyclaw/foundation/abi'
9
+
10
+ export const { name, inject, apply } = createPlugin({
11
+ name: 'canvas',
12
+ requires: ['canvas.runtime@^1'],
13
+ implements: [skillProvider({ skill: './skills/canvas' })],
14
+ }, import.meta.url)
15
+ ```
16
+
17
+ ## 四个入口
18
+
19
+ | 入口 | 内容 | 谁用 |
20
+ |---|---|---|
21
+ | `.` | Cordis 插件,产出 `ctx.os` | dsh profile |
22
+ | `./abi` | 描述符构建器、加载器、错误码、版本工具 | 应用插件 |
23
+ | `./kit` | plugin-kit 兼容导出,包含 Node/dsh 耦合,非纯函数库 | 兼容调用方 |
24
+ | `./runtime` | `createKernel` 等宿主 API | dsh 之外的宿主(独立技能服务、测试夹具) |
25
+
26
+ ## 状态
27
+
28
+ - 包清单当前为 `0.1.6`;0.1.6 修的是「关掉插件再启用撞 E_DUP_PLUGIN」(disposer 未登记 + 失败
29
+ 记录占名),详见下面的「生命周期」。
30
+ - 分层:应用插件 → ABI → 内核 → Host 适配器 → 本地 Node.js agent 运行时。
31
+ dsh 服务访问位于 Host 适配层;memory 只是参考实现,不证明第二个真实 agent 兼容。
32
+ HTTP/资源/进程仍有本地 Node 协议约束,详见 `docs/HOST-ADAPTER.md`。
33
+ - ABI v1,六个标准接口 + `host-event@1` + `client-panel@1` + `service-provider@1` +
34
+ `own-server@1` + 可执行 `raw@1`;基建插件使用 `defineDriver` 驱动入口。
35
+ - 能力表按 `ctx` 实际服务探测(见 `lib/kernel.mjs` 的 `detectCapabilities`),不做空头承诺。
36
+ - 当前仓库:27 个插件走标准接口,`raw@1` 当前为空,6 个基建插件走
37
+ `defineDriver` 驱动层;`meta/foundation.allowlist.json` 的模糊豁免为 0。
38
+ 详见 `docs/POLICY.md` 与 `docs/spec/plugin-abi.md`。
39
+
40
+ 设计规范见 `docs/spec/plugin-abi.md`,强制规则见 `docs/POLICY.md`。
41
+
42
+ ## 生命周期(0.1.6 起)
43
+
44
+ `createPlugin().apply` 会把 `os.mount()` 的 disposer 通过 `ctx.effect(() => () => dispose())`
45
+ 登记到本次激活的 ctx 上——**不能只靠 apply 的返回值**:Cordis 只认 `ctx.effect` 回调返回的
46
+ disposer,返回值不可靠。漏登记时,关掉插件后内核里的记录不会摘除,再次启用就会撞
47
+ `E_DUP_PLUGIN: 插件 xxx 已挂载`。
48
+
49
+ 加载器侧另有两条兜底:`mount()` 遇到 `disposed` / `failed` 的旧记录会先摘掉并尽力回收;
50
+ `start` 失败清理完成后立即让出插件名。两者共同保证「关掉 → 再启用」可重复无数次。
51
+
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 资产引用契约的单一真源(公共 ABI 常量)。
3
+ *
4
+ * 互操作标准里资产有两副面孔,前缀在这里定义一次,内核门面与资产服务都引用它,
5
+ * 避免「路由实现」与「URL 门面」各写一份 '/assets/' 而漂移:
6
+ * - 字节仓 HTTP 路由前缀 ASSET_URL_PREFIX = '/assets/' (asset-service 挂 GET/HEAD)
7
+ * - 结构化正文里的引用前缀 ASSET_REF_PREFIX = '@asset/' (work-store 信封/正文只存引用)
8
+ *
9
+ * 这是契约常量,不是宿主服务名——放 ABI 层,应用与驱动都可 import。
10
+ */
11
+
12
+ /** 资产字节仓的 HTTP 路由前缀(asset-service 实现,内核 os.assets.url 复用)。 */
13
+ export const ASSET_URL_PREFIX = '/assets/'
14
+
15
+ /** 结构化正文/产物信封里的内容寻址引用前缀(@asset/<sha256>)。 */
16
+ export const ASSET_REF_PREFIX = '@asset/'
17
+
18
+ /** 由资产 id 生成可加载 URL:/assets/<id>(id 做 URI 编码)。 */
19
+ export function assetUrl(id) {
20
+ return `${ASSET_URL_PREFIX}${encodeURIComponent(String(id))}`
21
+ }
22
+
23
+ /** 由资产 id 生成规范引用:@asset/<id>。 */
24
+ export function assetRef(id) {
25
+ return `${ASSET_REF_PREFIX}${String(id)}`
26
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 桥(editor bridge)与文档模型的标准声明。
3
+ *
4
+ * 这一层只放「协议常量 + 声明校验」,不放运行时:
5
+ * - 常量:协议版本、模型版本、能力名(suite 清单与 healthz 都用它)
6
+ * - declareBridge():把工作台的声明冻结成标准形状
7
+ * - assertBridgeRuntime():启动/巡检时把「声明」与「运行时实际上报」对齐
8
+ *
9
+ * 运行时(relay / 队列 / 租约)仍在 @capyclaw/document-workbench + service-host,
10
+ * 不进 ABI 层:foundation 是所有插件的地基,不该背 HTTP/store 依赖。
11
+ *
12
+ * 能力名(与 suite 清单的 requires/provides.capabilities 对应):
13
+ * editor.bridge —— 插件提供一个编辑器权威桥(/healthz + /status + /watch + /ack)
14
+ * doc.model —— 插件提供文档模型(稳定 ID / 清单 / 定位 / 编辑计划 / 校验)
15
+ */
16
+
17
+ import { AbiError, ERROR_CODES } from './errors.mjs'
18
+
19
+ /** 桥协议版本:端点集合与状态机语义的主版本。不兼容变更才升 major。 */
20
+ export const BRIDGE_PROTOCOL_VERSION = '1.0.0'
21
+
22
+ /** 文档模型版本:清单字段、定位器语义、编辑 op 的主版本。 */
23
+ export const DOC_MODEL_VERSION = '1.0.0'
24
+
25
+ export const BRIDGE_CAPABILITY = 'editor.bridge'
26
+ export const DOC_MODEL_CAPABILITY = 'doc.model'
27
+
28
+ /** healthz 里桥声明的字段名(避免与既有的 bridge: '<name>' 字符串冲突)。 */
29
+ export const BRIDGE_INFO_FIELD = 'bridgeInfo'
30
+
31
+ const ID_RE = /^[a-z0-9][a-z0-9-]*$/
32
+ const VERSION_RE = /^\d+\.\d+\.\d+$/
33
+
34
+ /**
35
+ * 校验并冻结一份桥声明。
36
+ * @param {{ id: string, protocol?: string, model?: string|null, editor?: 'required'|'optional' }} input
37
+ */
38
+ export function declareBridge(input = {}) {
39
+ const { id, protocol = BRIDGE_PROTOCOL_VERSION, model = null, editor = 'required' } = input
40
+ const errors = []
41
+ if (typeof id !== 'string' || !ID_RE.test(id)) errors.push(`id 必须是 kebab-case:${id}`)
42
+ if (!VERSION_RE.test(protocol)) errors.push(`protocol 版本非法:${protocol}`)
43
+ if (model !== null && !VERSION_RE.test(model)) errors.push(`model 版本非法:${model}`)
44
+ if (editor !== 'required' && editor !== 'optional') errors.push(`editor 只能是 required/optional:${editor}`)
45
+ if (errors.length) throw new AbiError(ERROR_CODES.E_SCHEMA, `桥声明非法:${errors.join(';')}`, { errors })
46
+ return Object.freeze({ id, protocol, model, editor })
47
+ }
48
+
49
+ /** 桥声明 → suite 清单里的 provides.capabilities。 */
50
+ export function bridgeCapabilities(declaration) {
51
+ const decl = declaration && declaration.protocol ? declaration : declareBridge(declaration)
52
+ return Object.freeze({
53
+ [BRIDGE_CAPABILITY]: decl.protocol,
54
+ ...(decl.model ? { [DOC_MODEL_CAPABILITY]: decl.model } : {}),
55
+ })
56
+ }
57
+
58
+ /** 桥声明 → suite 清单里工具面对运行时的 requires.capabilities(skill 包用)。 */
59
+ export function bridgeConsumerRequirements(ns, { needsModel = false } = {}) {
60
+ const out = { [`${ns}.runtime`]: `^${BRIDGE_PROTOCOL_VERSION}` }
61
+ if (needsModel) out[DOC_MODEL_CAPABILITY] = `^${DOC_MODEL_VERSION}`
62
+ return Object.freeze(out)
63
+ }
64
+
65
+ /**
66
+ * 声明与运行时对账:启动或巡检时调用。
67
+ *
68
+ * @param {object} declaration declareBridge 的结果(来自插件代码/清单)
69
+ * @param {object} runtime healthz 里的 bridgeInfo(实际运行值)
70
+ * @returns {{ ok: boolean, issues: string[] }}
71
+ */
72
+ export function assertBridgeRuntime(declaration, runtime) {
73
+ const issues = []
74
+ const decl = declaration && declaration.id ? declaration : declareBridge(declaration || {})
75
+ if (!runtime || typeof runtime !== 'object') {
76
+ return { ok: false, issues: [`运行时没有上报 ${BRIDGE_INFO_FIELD}`] }
77
+ }
78
+ if (runtime.id !== decl.id) issues.push(`id 不一致:声明 ${decl.id} / 运行 ${runtime.id}`)
79
+ if (runtime.protocol !== decl.protocol) {
80
+ issues.push(`协议版本不一致:声明 ${decl.protocol} / 运行 ${runtime.protocol}`)
81
+ }
82
+ const declaredModel = decl.model || null
83
+ const runtimeModel = runtime.model || null
84
+ if (declaredModel !== runtimeModel) {
85
+ issues.push(`模型版本不一致:声明 ${declaredModel || '无'} / 运行 ${runtimeModel || '无'}`)
86
+ }
87
+ return { ok: issues.length === 0, issues }
88
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * ABI 错误模型:稳定的错误码 + 结构化 detail。
3
+ *
4
+ * 约定:
5
+ * - 应用插件按 code 分支,不解析 message 文案;
6
+ * - message 面向人,detail 面向程序;
7
+ * - 所有加载期失败都必须是 AbiError,不允许裸 Error 穿透。
8
+ */
9
+
10
+ /** 稳定错误码。新增只能追加,不得改语义。 */
11
+ export const ERROR_CODES = Object.freeze({
12
+ /** 插件入口形状不对:缺 name / 没有 implements / 导出了 apply 等。 */
13
+ E_PLUGIN_SHAPE: 'E_PLUGIN_SHAPE',
14
+ /** 插件声明的 ABI 主版本与内核不兼容。 */
15
+ E_ABI_MISMATCH: 'E_ABI_MISMATCH',
16
+ /** 描述符的 kind 不在内核认识的接口表里。 */
17
+ E_KIND_UNKNOWN: 'E_KIND_UNKNOWN',
18
+ /** 描述符字段不满足接口 schema。 */
19
+ E_SCHEMA: 'E_SCHEMA',
20
+ /** 内核没有提供该能力(通常是 os.* 子系统缺失)。 */
21
+ E_CAP_MISSING: 'E_CAP_MISSING',
22
+ /** 唯一性接口被第二个插件实现(例如同 id 的 runtime-driver)。 */
23
+ E_DUP_INTERFACE: 'E_DUP_INTERFACE',
24
+ /** 同名插件被重复挂载。 */
25
+ E_DUP_PLUGIN: 'E_DUP_PLUGIN',
26
+ /** 内核没有为这个 kind 注册适配器(接口定义存在但实现未就绪)。 */
27
+ E_KIND_UNAVAILABLE: 'E_KIND_UNAVAILABLE',
28
+ /** 适配器在编译期抛错。 */
29
+ E_ADAPTER_THREW: 'E_ADAPTER_THREW',
30
+ /** 插件入口没有拿到 baseUrl,相对路径无法解析。 */
31
+ E_BASE_URL_MISSING: 'E_BASE_URL_MISSING',
32
+ /** 运行时没有 ctx.os:foundation 未安装或未启用。 */
33
+ E_KERNEL_MISSING: 'E_KERNEL_MISSING',
34
+ E_KERNEL_CLOSED: 'E_KERNEL_CLOSED',
35
+ E_NOT_READY: 'E_NOT_READY',
36
+ E_CAP_RESERVED: 'E_CAP_RESERVED',
37
+ E_CAP_CONFLICT: 'E_CAP_CONFLICT',
38
+ })
39
+
40
+ export class AbiError extends Error {
41
+ /**
42
+ * @param {string} code ERROR_CODES 中的一项
43
+ * @param {string} message 面向人的说明
44
+ * @param {Record<string, unknown>} [detail] 面向程序的结构化信息
45
+ */
46
+ constructor(code, message, detail = {}) {
47
+ super(`[${code}] ${message}`)
48
+ this.name = 'AbiError'
49
+ this.code = code
50
+ this.detail = detail
51
+ if (detail.cause instanceof Error) this.cause = detail.cause
52
+ }
53
+ }
54
+
55
+ export function isAbiError(error) {
56
+ return error instanceof AbiError
57
+ }
58
+
59
+ /** 把任意异常归一成 AbiError(已归一的原样返回)。 */
60
+ export function toAbiError(error, code = ERROR_CODES.E_ADAPTER_THREW, detail = {}) {
61
+ if (error instanceof AbiError) return error
62
+ return new AbiError(code, error?.message || String(error), { ...detail, cause: error })
63
+ }