@capyclaw/browser-workbench 0.0.0-stage → 0.1.19

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 (168) hide show
  1. package/README.md +88 -2
  2. package/contract/browser-contract.json +1349 -0
  3. package/demo/form.html +112 -0
  4. package/lib/host.mjs +1 -0
  5. package/node_modules/@capyclaw/asset-service/README.md +48 -0
  6. package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
  7. package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
  8. package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
  9. package/node_modules/@capyclaw/asset-service/package.json +59 -0
  10. package/node_modules/@capyclaw/asset-service/src/index.mjs +304 -0
  11. package/node_modules/@capyclaw/document-workbench/README.md +125 -0
  12. package/node_modules/@capyclaw/document-workbench/package.json +44 -0
  13. package/node_modules/@capyclaw/document-workbench/src/bridge/index.mjs +321 -0
  14. package/node_modules/@capyclaw/document-workbench/src/client/index.mjs +625 -0
  15. package/node_modules/@capyclaw/document-workbench/src/client/screenshot.mjs +98 -0
  16. package/node_modules/@capyclaw/document-workbench/src/index.mjs +9 -0
  17. package/node_modules/@capyclaw/document-workbench/src/model/audit.mjs +101 -0
  18. package/node_modules/@capyclaw/document-workbench/src/model/conformance.mjs +92 -0
  19. package/node_modules/@capyclaw/document-workbench/src/model/ids.mjs +56 -0
  20. package/node_modules/@capyclaw/document-workbench/src/model/index.mjs +18 -0
  21. package/node_modules/@capyclaw/document-workbench/src/model/locate.mjs +118 -0
  22. package/node_modules/@capyclaw/document-workbench/src/model/manifest.mjs +148 -0
  23. package/node_modules/@capyclaw/document-workbench/src/model/ops.mjs +160 -0
  24. package/node_modules/@capyclaw/document-workbench/src/model/validate.mjs +72 -0
  25. package/node_modules/@capyclaw/document-workbench/src/ops/index.mjs +93 -0
  26. package/node_modules/@capyclaw/document-workbench/src/session/context.mjs +103 -0
  27. package/node_modules/@capyclaw/document-workbench/src/session/index.mjs +394 -0
  28. package/node_modules/@capyclaw/document-workbench/src/session/lease.mjs +105 -0
  29. package/node_modules/@capyclaw/document-workbench/src/session/mode.mjs +80 -0
  30. package/node_modules/@capyclaw/document-workbench/src/session/sanitize.mjs +107 -0
  31. package/node_modules/@capyclaw/document-workbench/src/session/state.mjs +159 -0
  32. package/node_modules/@capyclaw/document-workbench/src/session/watch.mjs +63 -0
  33. package/node_modules/@capyclaw/document-workbench/src/store/file-backend.mjs +158 -0
  34. package/node_modules/@capyclaw/document-workbench/src/testing/index.mjs +75 -0
  35. package/node_modules/@capyclaw/foundation/README.md +51 -0
  36. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  37. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  38. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  39. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  40. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  41. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  42. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  43. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  44. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  45. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  46. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  47. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  48. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  49. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  50. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  51. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  52. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  53. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  54. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  55. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  56. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  57. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  58. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  59. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  60. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  61. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  62. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  63. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  64. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  65. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  66. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  67. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  68. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  69. package/node_modules/@capyclaw/foundation/package.json +53 -0
  70. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  71. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  72. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  73. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  74. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +58 -0
  79. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  80. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  81. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  82. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  83. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  84. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  85. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  86. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  87. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  88. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  89. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  90. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  91. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  92. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  93. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  94. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  95. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  96. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  97. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  98. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  99. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  100. package/node_modules/@capyclaw/service-host/README.md +86 -0
  101. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  102. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  103. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  104. package/node_modules/@capyclaw/service-host/package.json +60 -0
  105. package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
  106. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  107. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  108. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  109. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  110. package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
  111. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  112. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  113. package/node_modules/@capyclaw/tool-host/src/index.mjs +416 -0
  114. package/package.json +77 -4
  115. package/plugin.mjs +1 -0
  116. package/server/constants.mjs +16 -0
  117. package/server/contract-snapshots.mjs +81 -0
  118. package/server/contract.mjs +24 -0
  119. package/server/embedded-host.mjs +247 -0
  120. package/server/engine.mjs +2466 -0
  121. package/server/governor.mjs +189 -0
  122. package/server/http-utils.mjs +2 -0
  123. package/server/human.mjs +628 -0
  124. package/server/infra/http.mjs +2 -0
  125. package/server/infra/tuning.mjs +2 -0
  126. package/server/input.mjs +154 -0
  127. package/server/login-vault.mjs +109 -0
  128. package/server/mcp/handler.mjs +2 -0
  129. package/server/mcp/instructions.mjs +31 -0
  130. package/server/orphans.mjs +163 -0
  131. package/server/relay.mjs +198 -0
  132. package/server/routes/api.mjs +233 -0
  133. package/server/routes/assets.mjs +2 -0
  134. package/server/routes/mcp.mjs +17 -0
  135. package/server/routes/workbench.mjs +33 -0
  136. package/server/session-engines.mjs +223 -0
  137. package/server/shared/SHARED_MANIFEST.json +70 -0
  138. package/server/shared/asset-service.mjs +2 -0
  139. package/server/shared/editor-host.mjs +2 -0
  140. package/server/shared/kit/editor/lease.mjs +2 -0
  141. package/server/shared/kit/service/api.mjs +2 -0
  142. package/server/shared/kit/service/http.mjs +2 -0
  143. package/server/shared/kit/service/mcp-http.mjs +2 -0
  144. package/server/shared/kit/tools/validate.mjs +2 -0
  145. package/server/shared/kit/tuning.mjs +2 -0
  146. package/server/shared/kit/util/fs-lock.mjs +2 -0
  147. package/server/shared/service-host.mjs +2 -0
  148. package/server/shared/tool-host.mjs +2 -0
  149. package/server/shared/tuning.mjs +2 -0
  150. package/server/tools/capabilities/contract.mjs +55 -0
  151. package/server/tools/capabilities/evaluate.mjs +36 -0
  152. package/server/tools/capabilities/index.mjs +26 -0
  153. package/server/tools/capabilities/interaction.mjs +215 -0
  154. package/server/tools/capabilities/navigation.mjs +35 -0
  155. package/server/tools/capabilities/screenshot.mjs +50 -0
  156. package/server/tools/capabilities/session.mjs +81 -0
  157. package/server/tools/capabilities/snapshot.mjs +30 -0
  158. package/server/tools/capabilities/tabs.mjs +35 -0
  159. package/server/tools/index.mjs +12 -0
  160. package/server/tools/kernel/define.mjs +5 -0
  161. package/server/tools/kernel/output.mjs +30 -0
  162. package/server/tools/kernel/ports.mjs +59 -0
  163. package/server/tools/kernel/registry.mjs +17 -0
  164. package/server/tools.mjs +3 -0
  165. package/server/workbench-framework.mjs +305 -0
  166. package/ui/app.js +447 -0
  167. package/ui/index.html +46 -0
  168. package/ui/style.css +144 -0
@@ -0,0 +1,416 @@
1
+ /**
2
+ * @capyclaw/tool-host —— 工具面标准件。
3
+ *
4
+ * 把“能力声明 → 注册表 → 工具 schema/实现 → 契约报告 → MCP 协议壳”收成一套:
5
+ * defineTool / defineCapability / createRegistry / createMcpHandler /
6
+ * createCapabilityReport / buildInstructions
7
+ *
8
+ * 功能插件只写业务能力,不再复制 kernel/registry/dispatch/validate/contract。
9
+ */
10
+ import { createMcpHandler as createKitMcpHandler } from '@capyclaw/plugin-kit/service/mcp-http'
11
+ import { validateToolArguments } from '@capyclaw/plugin-kit/tools/validate'
12
+ import { normalizeToolResult, resultText } from '@capyclaw/plugin-kit/tools/result'
13
+ import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
14
+ import { createDescriptorRegistry } from './descriptors.mjs'
15
+
16
+ export { createDescriptorRegistry } from './descriptors.mjs'
17
+
18
+ const KINDS = new Set(['read', 'write', 'control'])
19
+
20
+ export function defineTool({
21
+ name,
22
+ description = '',
23
+ inputSchema = { type: 'object', properties: {}, additionalProperties: false },
24
+ kind = 'write',
25
+ since = '1.0.0',
26
+ handler,
27
+ } = {}) {
28
+ if (!name || typeof name !== 'string') throw new Error('defineTool 需要 name')
29
+ if (typeof handler !== 'function') throw new Error(`工具 ${name} 需要 handler`)
30
+ if (!KINDS.has(kind)) throw new Error(`工具 ${name} 的 kind 非法: ${kind}`)
31
+ return Object.freeze({ name, description, inputSchema, kind, since, handler })
32
+ }
33
+
34
+ export function defineCapability({
35
+ id,
36
+ title,
37
+ description = '',
38
+ tags = [],
39
+ requires = [],
40
+ dependsOn = [],
41
+ provides = {},
42
+ features = [],
43
+ tools = [],
44
+ } = {}) {
45
+ if (!id || typeof id !== 'string') throw new Error('defineCapability 需要 id')
46
+ if (!Array.isArray(tools) || !tools.length) throw new Error(`能力 ${id} 至少需要一个工具`)
47
+ return Object.freeze({
48
+ id,
49
+ title: title || id,
50
+ description,
51
+ tags: Object.freeze([...tags]),
52
+ requires: Object.freeze([...requires]),
53
+ dependsOn: Object.freeze([...dependsOn]),
54
+ provides: Object.freeze({ ...provides }),
55
+ features: Object.freeze([...features]),
56
+ tools: Object.freeze([...tools]),
57
+ })
58
+ }
59
+
60
+ function validateCapabilities(capabilities) {
61
+ const ids = new Set()
62
+ const toolNames = new Set()
63
+ for (const cap of capabilities) {
64
+ if (ids.has(cap.id)) throw new Error(`重复的 capability id: ${cap.id}`)
65
+ ids.add(cap.id)
66
+ for (const tool of cap.tools) {
67
+ if (toolNames.has(tool.name)) throw new Error(`重复的工具名: ${tool.name}`)
68
+ toolNames.add(tool.name)
69
+ }
70
+ }
71
+ for (const cap of capabilities) {
72
+ for (const dep of cap.dependsOn) {
73
+ if (!ids.has(dep)) throw new Error(`能力 ${cap.id} 依赖不存在的能力: ${dep}`)
74
+ }
75
+ }
76
+ }
77
+
78
+ function selectCapabilities(capabilities, enabled) {
79
+ if (!enabled || !enabled.length) return capabilities
80
+ const byId = new Map(capabilities.map((cap) => [cap.id, cap]))
81
+ for (const id of enabled) {
82
+ if (!byId.has(id)) throw new Error(`enabled 里有未知能力: ${id}`)
83
+ }
84
+ const ids = new Set(enabled)
85
+ let changed = true
86
+ while (changed) {
87
+ changed = false
88
+ for (const cap of capabilities) {
89
+ if (!ids.has(cap.id)) continue
90
+ for (const dep of cap.dependsOn) {
91
+ if (!ids.has(dep)) { ids.add(dep); changed = true }
92
+ }
93
+ }
94
+ }
95
+ return capabilities.filter((cap) => ids.has(cap.id))
96
+ }
97
+
98
+ /**
99
+ * @param {Array} capabilities
100
+ * @param {{ enabled?: string[], ports?: object, report?: Function, reserved?: string[] }} options
101
+ */
102
+ export function createRegistry(capabilities, { enabled = null, ports = null, report = null, reserved = [] } = {}) {
103
+ validateCapabilities(capabilities)
104
+ const selected = selectCapabilities(capabilities, enabled)
105
+
106
+ const kernelPorts = { ...(ports || {}) }
107
+ const reservedNames = new Set([...(reserved || []), 'contract'])
108
+ const providers = new Map()
109
+ for (const cap of selected) {
110
+ for (const [ns, api] of Object.entries(cap.provides || {})) {
111
+ if (reservedNames.has(ns)) throw new Error(`能力 ${cap.id} 不能覆盖内核端口: ${ns}`)
112
+ if (providers.has(ns)) throw new Error(`服务命名空间重复: ${ns}(${providers.get(ns).cap.id} / ${cap.id})`)
113
+ providers.set(ns, { cap, api })
114
+ }
115
+ }
116
+
117
+ const available = new Set([...Object.keys(kernelPorts), ...reservedNames, ...providers.keys()])
118
+ for (const cap of selected) {
119
+ for (const req of cap.requires) {
120
+ if (!available.has(req)) throw new Error(`能力 ${cap.id} 需要未提供的端口/服务: ${req}`)
121
+ }
122
+ }
123
+
124
+ const ctx = { ...kernelPorts }
125
+ for (const [ns, { api }] of providers) {
126
+ ctx[ns] = {}
127
+ for (const [method, fn] of Object.entries(api)) {
128
+ if (typeof fn !== 'function') throw new Error(`服务 ${ns}.${method} 必须是函数`)
129
+ ctx[ns][method] = (...args) => fn(ctx, ...args)
130
+ }
131
+ }
132
+
133
+ const TOOLS = []
134
+ const TOOL_IMPL = {}
135
+ const TOOL_META = {}
136
+ const FEATURES = []
137
+ const CAPABILITIES = []
138
+
139
+ for (const cap of selected) {
140
+ for (const feature of cap.features) {
141
+ if (!FEATURES.includes(feature)) FEATURES.push(feature)
142
+ }
143
+ CAPABILITIES.push({
144
+ id: cap.id,
145
+ title: cap.title,
146
+ description: cap.description,
147
+ tags: [...cap.tags],
148
+ tools: cap.tools.map((tool) => tool.name),
149
+ })
150
+ for (const tool of cap.tools) {
151
+ TOOLS.push({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema })
152
+ TOOL_META[tool.name] = { kind: tool.kind, since: tool.since, capability: cap.id }
153
+ TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
154
+ }
155
+ }
156
+
157
+ const reportFn = report || createCapabilityReport
158
+ ctx.contract = {
159
+ report: (editorUrl = '', runtime = {}) => reportFn({
160
+ tools: TOOLS,
161
+ toolMeta: TOOL_META,
162
+ features: FEATURES,
163
+ capabilities: CAPABILITIES,
164
+ editorUrl,
165
+ runtime,
166
+ }),
167
+ }
168
+
169
+ /* 动态增删工具:配合 MCP 活引用(tools/list 读 registry.TOOLS),注册/注销后
170
+ * 客户端重新 list 即见最新工具集,无需重建 handler。旧 registry 是纯静态,
171
+ * 套件热重载/能力开关无法反映到工具面。 */
172
+ function registerTool(tool, capabilityId = '') {
173
+ if (!tool || typeof tool.name !== 'string' || !tool.name) throw new Error('registerTool 需要 tool.name')
174
+ if (typeof tool.handler !== 'function') throw new Error(`工具 ${tool.name} 需要 handler`)
175
+ if (TOOL_IMPL[tool.name]) throw new Error(`工具已存在: ${tool.name}`)
176
+ TOOLS.push({ name: tool.name, description: tool.description || '', inputSchema: tool.inputSchema || { type: 'object', properties: {} } })
177
+ TOOL_META[tool.name] = { kind: tool.kind || 'write', since: tool.since || '1.0.0', capability: capabilityId }
178
+ TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
179
+ return true
180
+ }
181
+ function unregisterTool(name) {
182
+ const index = TOOLS.findIndex((tool) => tool.name === name)
183
+ if (index < 0) return false
184
+ TOOLS.splice(index, 1)
185
+ delete TOOL_IMPL[name]
186
+ delete TOOL_META[name]
187
+ return true
188
+ }
189
+
190
+ return { TOOLS, TOOL_IMPL, TOOL_META, FEATURES, CAPABILITIES, ctx, registerTool, unregisterTool }
191
+ }
192
+
193
+ /** 与 MCP 工具面解耦:调用前统一校验。 */
194
+ export function createToolDispatcher({ tools, callTool }) {
195
+ const toolMap = new Map((tools || []).map((tool) => [tool.name, tool]))
196
+ return {
197
+ listTools() {
198
+ return { tools }
199
+ },
200
+ async callTool(name, args = {}) {
201
+ const tool = toolMap.get(name)
202
+ if (!tool) {
203
+ return { content: [{ type: 'text', text: `未知工具: ${String(name)}` }], isError: true }
204
+ }
205
+ const check = validateToolArguments(tool, args)
206
+ if (!check.ok) {
207
+ return { content: [{ type: 'text', text: '参数不合法:' + check.errors.join(';') }], isError: true }
208
+ }
209
+ const out = await callTool(name, args)
210
+ /* 与 MCP 面同一归一化:保留纯字符串/空 text/对象,不丢成 'ok'(B 轴 P0-5)。 */
211
+ return normalizeToolResult(out)
212
+ },
213
+ }
214
+ }
215
+
216
+ /**
217
+ * MCP Streamable HTTP 处理器。registry 可直接传 createRegistry 的返回值。
218
+ * 兼容两种调用:
219
+ * { registry } 或 { tools, toolImpl }
220
+ * { tools, callTool }(旧 relay 形态)
221
+ * @param {{ registry?: object, tools?: Array, toolImpl?: object, callTool?: Function, serverInfo?: object, instructions?: string }} options
222
+ */
223
+ export function createMcpHandler({ registry, tools, toolImpl, callTool, serverInfo, instructions, listChanged } = {}) {
224
+ /* registry 形态走活引用:tools/list 每次读 registry.TOOLS,callTool 读 registry.TOOL_IMPL,
225
+ * 于是 registerTool/unregisterTool 的动态增删立刻可见,无需重建 handler。 */
226
+ const useRegistry = !tools && !!registry
227
+ const impl = toolImpl || registry?.TOOL_IMPL || null
228
+ const staticList = tools || null
229
+ if (!useRegistry && (!Array.isArray(staticList) || !staticList.length)) throw new Error('createMcpHandler: 没有工具可暴露')
230
+ if (!impl && typeof callTool !== 'function') throw new Error('createMcpHandler: 需要 toolImpl 或 callTool')
231
+ return createKitMcpHandler({
232
+ tools: useRegistry ? () => registry.TOOLS : staticList,
233
+ callTool: (name, args, context) => {
234
+ if (typeof callTool === 'function' && !impl) return callTool(name, args, context)
235
+ const source = useRegistry ? registry.TOOL_IMPL : impl
236
+ const fn = source[name]
237
+ if (!fn) throw new Error(`未知工具: ${name}`)
238
+ return fn(args, context)
239
+ },
240
+ serverInfo: serverInfo || { name: 'dsh-tool-host', version: '0.1.0' },
241
+ instructions,
242
+ listChanged,
243
+ })
244
+ }
245
+
246
+ /** 把绝对地址收成同源相对路径:给人看的地址不带端口,端口是宿主的内部细节。 */
247
+ function sameOriginPath(url) {
248
+ const raw = String(url || '').trim()
249
+ if (!raw) return ''
250
+ if (raw.startsWith('/')) return raw
251
+ try {
252
+ const { pathname } = new URL(raw)
253
+ return pathname.endsWith('/') ? pathname : `${pathname}/`
254
+ } catch {
255
+ return ''
256
+ }
257
+ }
258
+
259
+ export function createCapabilityReport({
260
+ tools = [],
261
+ toolMeta = {},
262
+ features = [],
263
+ capabilities = [],
264
+ contractVersion = '1.0.0',
265
+ packageVersion = '0.0.0',
266
+ editorUrl = '',
267
+ runtime = {},
268
+ } = {}) {
269
+ return {
270
+ contractVersion,
271
+ packageVersion,
272
+ editorUrl,
273
+ editorPath: sameOriginPath(editorUrl),
274
+ ...runtime,
275
+ toolCount: tools.length,
276
+ tools: tools.map((tool) => ({
277
+ name: tool.name,
278
+ kind: toolMeta[tool.name]?.kind ?? 'write',
279
+ since: toolMeta[tool.name]?.since ?? '1.0.0',
280
+ capability: toolMeta[tool.name]?.capability ?? '',
281
+ })),
282
+ features,
283
+ capabilities: capabilities.map((cap) => ({
284
+ id: cap.id,
285
+ title: cap.title,
286
+ description: cap.description || '',
287
+ tags: cap.tags || [],
288
+ tools: cap.tools || [],
289
+ })),
290
+ }
291
+ }
292
+
293
+ /**
294
+ * 生成 MCP server instructions(≤32KB)。业务只提供数据,不再手写排版。
295
+ */
296
+ export function buildInstructions({
297
+ title = '',
298
+ intro = '',
299
+ startup = [],
300
+ capabilities = [],
301
+ tools = [],
302
+ rules = [],
303
+ output = [],
304
+ } = {}) {
305
+ const rows = capabilities.length
306
+ ? capabilities.map((cap) => `| ${cap.title} | ${cap.tools.map((name) => `\`${name}\``).join(', ')} | ${cap.description || ''} |`)
307
+ : [{
308
+ title: '工具',
309
+ tools: tools.map((tool) => tool.name),
310
+ description: '',
311
+ }].map((cap) => `| ${cap.title} | ${cap.tools.map((name) => `\`${name}\``).join(', ')} | |`)
312
+
313
+ const lines = []
314
+ if (title) lines.push(`# ${title}`, '')
315
+ if (intro) lines.push(intro, '')
316
+ if (startup.length) {
317
+ lines.push('## 启动检查')
318
+ startup.forEach((line, index) => lines.push(`${index + 1}. ${line}`))
319
+ lines.push('')
320
+ }
321
+ lines.push('## 能力面', '| 能力 | 工具 | 用途 |', '|---|---|---|', ...rows, '')
322
+ if (rules.length) {
323
+ lines.push('## 硬规则')
324
+ rules.forEach((line) => lines.push(`- ${line}`))
325
+ lines.push('')
326
+ }
327
+ if (output.length) {
328
+ lines.push('## 输出')
329
+ output.forEach((line) => lines.push(`- ${line}`))
330
+ }
331
+ return lines.join('\n')
332
+ }
333
+
334
+ /**
335
+ * 把能力注册表直接注册到 DSH 的 ctx.tools(同进程原生工具面)。
336
+ * 注册后不再需要单独的 loopback /mcp 端口和 @deepseek-ai/dsh-mcp-client row。
337
+ *
338
+ * `execute(args, exec)` 的第二个参数是 DSH 的调用上下文,`exec.agent.session.id`
339
+ * 是「哪个会话调用了这个工具」——多会话工作台要靠它把写入落到调用者的那份文档上。
340
+ * 以前这里写成 `(args) => impl(args)`,把它丢了,于是工具只能退化成"猜用户在看哪个窗口"。
341
+ *
342
+ * @param {object} ctx DSH cordis context
343
+ * @param {object} registry createRegistry() 的返回值
344
+ * @param {{ namespace?: string }} options
345
+ * @returns {() => void} 反注册全部工具
346
+ */
347
+ export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
348
+ if (!ctx?.tools?.register) throw new Error('registerWithDsh: 当前 DSH 没有 ctx.tools.register')
349
+ const disposers = []
350
+ try {
351
+ for (const tool of registry?.TOOLS || []) {
352
+ const impl = registry.TOOL_IMPL?.[tool.name]
353
+ if (typeof impl !== 'function') throw new Error(`registerWithDsh: 工具缺少实现 ${tool.name}`)
354
+ const name = namespace ? `${namespace}_${tool.name}` : tool.name
355
+ disposers.push(ctx.tools.register({
356
+ name,
357
+ description: tool.description || '',
358
+ parameters: tool.inputSchema || { type: 'object', properties: {}, additionalProperties: false },
359
+ output: {
360
+ /* execute 恒返回归一化 {content:[...]} object,故此 object schema 恒满足,
361
+ * 不再与 string/{text}/undefined 返回冲突(B 轴 P0-2)。 */
362
+ schema: { type: 'object', additionalProperties: true },
363
+ render: (args, value) => (value && Array.isArray(value.content)
364
+ ? value.content
365
+ : normalizeToolResult(value).content),
366
+ },
367
+ execute: async (args, exec) => {
368
+ const normalized = normalizeToolResult(await impl(args, exec))
369
+ /* DSH 原生面成功恒 isError:false,失败必须 throw 才走错误路径(B 轴 P0-1)。
370
+ * 把工具自报的 isError:true 转成 throw,与 MCP 面的失败语义对齐。 */
371
+ if (normalized.isError === true) {
372
+ throw new Error(resultText(normalized) || `工具 ${name} 执行失败`)
373
+ }
374
+ return normalized
375
+ },
376
+ }))
377
+ }
378
+ } catch (error) {
379
+ /* 全有或全无:任一工具注册失败,逆序释放已注册的,避免部分注册泄漏(B 轴 P0-6)。 */
380
+ for (let i = disposers.length - 1; i >= 0; i--) {
381
+ try { disposers[i]() } catch { /* 忽略释放失败 */ }
382
+ }
383
+ throw error
384
+ }
385
+ return () => {
386
+ for (const dispose of disposers) {
387
+ try { dispose() } catch { /* 忽略重复释放 */ }
388
+ }
389
+ }
390
+ }
391
+
392
+ export function createToolHost(config = {}) {
393
+ // 跨套件能力发现注册表(互联标准 §A.4/§E)。深度校验器可选注入(suite-kit)。
394
+ const descriptors = createDescriptorRegistry({ validate: config.validateDescriptor })
395
+ return {
396
+ api: createServiceApi('toolHost', '1.1.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors']),
397
+ version: '0.2.0',
398
+ defineTool,
399
+ defineCapability,
400
+ createRegistry: (capabilities, options = {}) => createRegistry(capabilities, { ...config, ...options }),
401
+ createMcpHandler,
402
+ createToolDispatcher,
403
+ createCapabilityReport,
404
+ buildInstructions,
405
+ registerWithDsh,
406
+ validateToolArguments,
407
+ // 能力描述符注册/发现(编排器按类型动态发现,套件零互依赖)。
408
+ registerCapabilityDescriptor: (descriptor, options) => descriptors.register(descriptor, options),
409
+ unregisterCapabilityDescriptor: (name) => descriptors.unregister(name),
410
+ discoverCapabilities: (query) => descriptors.discover(query),
411
+ capabilityCatalog: () => descriptors.catalog(),
412
+ listSurfaces: () => descriptors.listSurfaces(),
413
+ }
414
+ }
415
+
416
+ export { validateToolArguments }
package/package.json CHANGED
@@ -1,6 +1,79 @@
1
1
  {
2
2
  "name": "@capyclaw/browser-workbench",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.19",
4
+ "description": "浏览器操控工作台运行时:18 个 browser_* MCP 工具(导航/快照/点击/填写/按键/下拉/上传/滚动/批量连做/拖拽/标签页/截图)+ Playwright 引擎(有头可见、登录态持久化)+ 可视化工作台。",
5
+ "type": "module",
6
+ "main": "./plugin.mjs",
7
+ "exports": {
8
+ ".": "./plugin.mjs",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "engines": {
12
+ "node": ">=18",
13
+ "dsh": "^0.2.0-rc.2"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "dsh": {
19
+ "member": true,
20
+ "category": "service",
21
+ "platform": "both",
22
+ "capabilities": {
23
+ "source": "server/tools/capabilities",
24
+ "manifest": "capabilities.json"
25
+ },
26
+ "requires": {
27
+ "capabilities": {
28
+ "os.proc": "^1.0.0"
29
+ }
30
+ }
31
+ },
32
+ "meta": {
33
+ "title": "浏览器操控工作台运行时",
34
+ "description": "AI 直接操控浏览器完成互联网上的点击/打字工作:18 个 browser_* 工具 + 可视化工作台(挂在 dsh 的 /capyclaw/browser,端口由 dsh 决定)"
35
+ },
36
+ "files": [
37
+ "plugin.mjs",
38
+ "lib/",
39
+ "server/",
40
+ "ui/",
41
+ "demo/",
42
+ "!server/.relay-instance.lock",
43
+ "contract/",
44
+ "README.md"
45
+ ],
46
+ "license": "MIT",
47
+ "scripts": {},
48
+ "dependencies": {
49
+ "@capyclaw/asset-service": "^0.1.4",
50
+ "@capyclaw/document-workbench": "^0.2.2",
51
+ "@capyclaw/foundation": "^0.1.9",
52
+ "@capyclaw/plugin-kit": "^0.2.6",
53
+ "@capyclaw/service-host": "^0.1.5",
54
+ "@capyclaw/tool-host": "^0.2.0",
55
+ "playwright": "^1.64.0"
56
+ },
57
+ "author": {
58
+ "name": "CapyClaw",
59
+ "url": "https://github.com/capyclaw",
60
+ "email": "support@capyclaw.dev"
61
+ },
62
+ "repository": {
63
+ "type": "git",
64
+ "url": "git+https://github.com/Maple496/capyclaw.git",
65
+ "directory": "A/projects/browser/artifacts/plugin/capyclaw-browser-workbench"
66
+ },
67
+ "bugs": {
68
+ "url": "https://github.com/Maple496/capyclaw/issues"
69
+ },
70
+ "homepage": "https://github.com/Maple496/capyclaw/tree/main/A/projects/browser/artifacts/plugin/capyclaw-browser-workbench#readme",
71
+ "bundledDependencies": [
72
+ "@capyclaw/asset-service",
73
+ "@capyclaw/document-workbench",
74
+ "@capyclaw/foundation",
75
+ "@capyclaw/plugin-kit",
76
+ "@capyclaw/service-host",
77
+ "@capyclaw/tool-host"
78
+ ]
79
+ }
package/plugin.mjs ADDED
@@ -0,0 +1 @@
1
+ export { name, inject, apply } from './server/embedded-host.mjs'
@@ -0,0 +1,16 @@
1
+ /** 桥的稳定常量(relay/routes/tests 共用,避免循环 import)。 */
2
+
3
+ export const DEFAULT_PORT = 39315
4
+
5
+ /** 工作台静态页(白名单,杜绝路径穿越;相对 ui/)。 */
6
+ export const WORKBENCH_FILES = {
7
+ '/': ['index.html', 'text/html; charset=utf-8'],
8
+ '/index.html': ['index.html', 'text/html; charset=utf-8'],
9
+ '/app.js': ['app.js', 'text/javascript; charset=utf-8'],
10
+ '/style.css': ['style.css', 'text/css; charset=utf-8'],
11
+ }
12
+
13
+ /** 内置离线演示页(相对 demo/)。 */
14
+ export const DEMO_FILES = {
15
+ '/demo/form.html': ['form.html', 'text/html; charset=utf-8'],
16
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * 契约快照校验:workbench 与同目录 skill 包的 contract/browser-contract.json
3
+ * major 不一致时,MCP 工具调用被拒绝(browser_capabilities 除外,便于诊断)。
4
+ *
5
+ * 开发态(plugin/)和发布态里 skill 包都是 workbench 的兄弟目录。
6
+ * 机制与 canvas-bridge 的 contract-snapshots 相同,只换前缀与契约文件名。
7
+ */
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+
11
+ const SKILL_PREFIX = 'capyclaw-browser-skill-'
12
+ const SCOPED_SKILL_PREFIX = 'browser-skill-'
13
+ const CONTRACT_FILE = 'browser-contract.json'
14
+ const SCOPE_DIR = '@capyclaw'
15
+
16
+ function majorOf(version) {
17
+ return String(version || '').split('.')[0]
18
+ }
19
+
20
+ export function inspectContractSnapshots(packageDir, contractVersion) {
21
+ const expectedMajor = majorOf(contractVersion)
22
+ const report = { expected: contractVersion || '', checked: 0, ok: true, mismatched: [] }
23
+ const parent = path.dirname(packageDir)
24
+
25
+ const candidates = []
26
+ let entries
27
+ try {
28
+ entries = fs.readdirSync(parent, { withFileTypes: true })
29
+ } catch {
30
+ return report
31
+ }
32
+ const inScope = path.basename(parent) === SCOPE_DIR
33
+ for (const entry of entries) {
34
+ if (entry.name.startsWith(SKILL_PREFIX)) {
35
+ candidates.push({ name: entry.name, dir: path.join(parent, entry.name) })
36
+ } else if (inScope && entry.name.startsWith(SCOPED_SKILL_PREFIX)) {
37
+ candidates.push({ name: entry.name, dir: path.join(parent, entry.name) })
38
+ } else if (entry.name === SCOPE_DIR) {
39
+ let scoped
40
+ try {
41
+ scoped = fs.readdirSync(path.join(parent, entry.name), { withFileTypes: true })
42
+ } catch { continue }
43
+ for (const s of scoped) {
44
+ if (s.name.startsWith(SCOPED_SKILL_PREFIX)) {
45
+ candidates.push({ name: `${SCOPE_DIR}/${s.name}`, dir: path.join(parent, entry.name, s.name) })
46
+ }
47
+ }
48
+ }
49
+ }
50
+
51
+ for (const { name, dir } of candidates) {
52
+ try {
53
+ if (!fs.statSync(dir).isDirectory()) continue
54
+ } catch {
55
+ continue
56
+ }
57
+
58
+ report.checked++
59
+ const file = path.join(dir, 'contract', CONTRACT_FILE)
60
+ let snapshot = null
61
+ try {
62
+ snapshot = JSON.parse(fs.readFileSync(file, 'utf8'))
63
+ } catch {
64
+ report.mismatched.push({ package: name, expected: contractVersion, actual: null })
65
+ continue
66
+ }
67
+ const actualMajor = majorOf(snapshot.contractVersion)
68
+ if (actualMajor !== expectedMajor) {
69
+ report.mismatched.push({ package: name, expected: contractVersion, actual: snapshot.contractVersion || null })
70
+ }
71
+ }
72
+
73
+ report.ok = report.mismatched.length === 0
74
+ return report
75
+ }
76
+
77
+ export function describeMismatch(report) {
78
+ return report.mismatched
79
+ .map((item) => `${item.package}(snapshot=${item.actual || 'missing'}, runtime=${item.expected})`)
80
+ .join(';')
81
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * MCP 工具契约的唯一真源(版本 + 报告格式)。
3
+ *
4
+ * 工具/能力清单由 capabilities → registry 派生;报告结构来自 @capyclaw/tool-host。
5
+ * 新增能力只改 tools/capabilities/index.mjs。
6
+ */
7
+ import { createCapabilityReport } from './shared/tool-host.mjs'
8
+
9
+ /** 工具契约版本:工具名、参数、返回结构发生不兼容变化时升 major。 */
10
+ export const CONTRACT_VERSION = '1.3.0'
11
+
12
+ /** 工作台包版本。 */
13
+ export const PACKAGE_VERSION = '0.1.19'
14
+
15
+ /** 生成模型可读的能力报告。 */
16
+ export function capabilityReport(args, workbenchUrl = '', runtime = {}) {
17
+ return createCapabilityReport({
18
+ ...args,
19
+ contractVersion: CONTRACT_VERSION,
20
+ packageVersion: PACKAGE_VERSION,
21
+ editorUrl: workbenchUrl,
22
+ runtime,
23
+ })
24
+ }