@capyclaw/wall-suite 0.0.0-stage → 0.1.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.
Files changed (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/composition.lock.json +48 -0
  4. package/contract/wall-contract.json +8 -0
  5. package/cordis.patch.yml +6 -0
  6. package/dsh-suite.json +128 -0
  7. package/lib/index.mjs +6 -0
  8. package/node_modules/@capyclaw/asset-service/README.md +48 -0
  9. package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
  10. package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
  11. package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
  12. package/node_modules/@capyclaw/asset-service/package.json +59 -0
  13. package/node_modules/@capyclaw/asset-service/src/index.mjs +310 -0
  14. package/node_modules/@capyclaw/foundation/README.md +51 -0
  15. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  16. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  17. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  18. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  19. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  20. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  21. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  22. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  23. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  24. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  25. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  26. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  27. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  34. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  35. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  36. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  37. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  38. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  39. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  40. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  41. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  42. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  43. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  44. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  45. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  46. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  47. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  48. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  49. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  50. package/node_modules/@capyclaw/foundation/package.json +53 -0
  51. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  52. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  53. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  54. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  55. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  79. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  80. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  81. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  82. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  83. package/node_modules/@capyclaw/portal/README.md +70 -0
  84. package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
  85. package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
  86. package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
  87. package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
  88. package/node_modules/@capyclaw/portal/package.json +40 -0
  89. package/node_modules/@capyclaw/service-broker/README.md +104 -0
  90. package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
  91. package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
  92. package/node_modules/@capyclaw/service-broker/lib/control.mjs +209 -0
  93. package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
  94. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1290 -0
  95. package/node_modules/@capyclaw/service-broker/lib/host.mjs +187 -0
  96. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +262 -0
  97. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +275 -0
  98. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +48 -0
  99. package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
  100. package/node_modules/@capyclaw/service-broker/package.json +65 -0
  101. package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
  102. package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
  103. package/node_modules/@capyclaw/service-broker/services.json +3 -0
  104. package/node_modules/@capyclaw/service-host/README.md +86 -0
  105. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  106. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  107. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  108. package/node_modules/@capyclaw/service-host/package.json +60 -0
  109. package/node_modules/@capyclaw/service-host/src/index.mjs +570 -0
  110. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  111. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  112. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  113. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  114. package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
  115. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  116. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  117. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  118. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  119. package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
  120. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  121. package/node_modules/@capyclaw/wall-workbench/README.md +58 -0
  122. package/node_modules/@capyclaw/wall-workbench/contract/wall-contract.json +8 -0
  123. package/node_modules/@capyclaw/wall-workbench/lib/host.mjs +1 -0
  124. package/node_modules/@capyclaw/wall-workbench/package.json +63 -0
  125. package/node_modules/@capyclaw/wall-workbench/plugin.mjs +13 -0
  126. package/node_modules/@capyclaw/wall-workbench/server/activate-log.mjs +66 -0
  127. package/node_modules/@capyclaw/wall-workbench/server/constants.mjs +12 -0
  128. package/node_modules/@capyclaw/wall-workbench/server/contract.mjs +12 -0
  129. package/node_modules/@capyclaw/wall-workbench/server/embedded-host.mjs +162 -0
  130. package/node_modules/@capyclaw/wall-workbench/server/infra/http.mjs +2 -0
  131. package/node_modules/@capyclaw/wall-workbench/server/infra/tuning.mjs +2 -0
  132. package/node_modules/@capyclaw/wall-workbench/server/relay.mjs +68 -0
  133. package/node_modules/@capyclaw/wall-workbench/server/routes/claim.mjs +46 -0
  134. package/node_modules/@capyclaw/wall-workbench/server/routes/workbench.mjs +29 -0
  135. package/node_modules/@capyclaw/wall-workbench/server/shared/SHARED_MANIFEST.json +70 -0
  136. package/node_modules/@capyclaw/wall-workbench/server/shared/asset-service.mjs +2 -0
  137. package/node_modules/@capyclaw/wall-workbench/server/shared/editor-host.mjs +2 -0
  138. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/editor/lease.mjs +2 -0
  139. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/api.mjs +2 -0
  140. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/http.mjs +2 -0
  141. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/mcp-http.mjs +2 -0
  142. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tools/validate.mjs +2 -0
  143. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tuning.mjs +2 -0
  144. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/util/fs-lock.mjs +2 -0
  145. package/node_modules/@capyclaw/wall-workbench/server/shared/service-host.mjs +2 -0
  146. package/node_modules/@capyclaw/wall-workbench/server/shared/tool-host.mjs +2 -0
  147. package/node_modules/@capyclaw/wall-workbench/server/shared/tuning.mjs +2 -0
  148. package/node_modules/@capyclaw/wall-workbench/server/tools/capabilities/index.mjs +2 -0
  149. package/node_modules/@capyclaw/wall-workbench/server/tools/index.mjs +12 -0
  150. package/node_modules/@capyclaw/wall-workbench/server/tools.mjs +2 -0
  151. package/node_modules/@capyclaw/wall-workbench/server/workbench-framework.mjs +339 -0
  152. package/node_modules/@capyclaw/wall-workbench/ui/app.js +225 -0
  153. package/node_modules/@capyclaw/wall-workbench/ui/index.html +20 -0
  154. package/node_modules/@capyclaw/wall-workbench/ui/style.css +77 -0
  155. package/package.json +72 -4
  156. package/services.json +3 -0
@@ -0,0 +1,461 @@
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
+ import { createModeGate } from './mode-gate.mjs'
16
+ import { runWithCallerSession, currentCallerSession } from './caller-session.mjs'
17
+ import { admitToolResultImages, resolveAttachments } from './admit-images.mjs'
18
+
19
+ export { admitToolResultImages, resolveAttachments } from './admit-images.mjs'
20
+ export { createDescriptorRegistry } from './descriptors.mjs'
21
+ export { createModeGate } from './mode-gate.mjs'
22
+ export { runWithCallerSession, currentCallerSession } from './caller-session.mjs'
23
+
24
+ const KINDS = new Set(['read', 'write', 'control'])
25
+
26
+ export function defineTool({
27
+ name,
28
+ description = '',
29
+ inputSchema = { type: 'object', properties: {}, additionalProperties: false },
30
+ kind = 'write',
31
+ since = '1.0.0',
32
+ domain = '',
33
+ handler,
34
+ } = {}) {
35
+ if (!name || typeof name !== 'string') throw new Error('defineTool 需要 name')
36
+ if (typeof handler !== 'function') throw new Error(`工具 ${name} 需要 handler`)
37
+ if (!KINDS.has(kind)) throw new Error(`工具 ${name} 的 kind 非法: ${kind}`)
38
+ return Object.freeze({ name, description, inputSchema, kind, since, domain: String(domain || ''), handler })
39
+ }
40
+
41
+ export function defineCapability({
42
+ id,
43
+ title,
44
+ description = '',
45
+ tags = [],
46
+ requires = [],
47
+ dependsOn = [],
48
+ provides = {},
49
+ features = [],
50
+ domain = '',
51
+ tools = [],
52
+ } = {}) {
53
+ if (!id || typeof id !== 'string') throw new Error('defineCapability 需要 id')
54
+ if (!Array.isArray(tools) || !tools.length) throw new Error(`能力 ${id} 至少需要一个工具`)
55
+ return Object.freeze({
56
+ id,
57
+ title: title || id,
58
+ description,
59
+ tags: Object.freeze([...tags]),
60
+ requires: Object.freeze([...requires]),
61
+ dependsOn: Object.freeze([...dependsOn]),
62
+ provides: Object.freeze({ ...provides }),
63
+ features: Object.freeze([...features]),
64
+ domain: String(domain || ''),
65
+ tools: Object.freeze([...tools]),
66
+ })
67
+ }
68
+
69
+ function validateCapabilities(capabilities) {
70
+ const ids = new Set()
71
+ const toolNames = new Set()
72
+ for (const cap of capabilities) {
73
+ if (ids.has(cap.id)) throw new Error(`重复的 capability id: ${cap.id}`)
74
+ ids.add(cap.id)
75
+ for (const tool of cap.tools) {
76
+ if (toolNames.has(tool.name)) throw new Error(`重复的工具名: ${tool.name}`)
77
+ toolNames.add(tool.name)
78
+ }
79
+ }
80
+ for (const cap of capabilities) {
81
+ for (const dep of cap.dependsOn) {
82
+ if (!ids.has(dep)) throw new Error(`能力 ${cap.id} 依赖不存在的能力: ${dep}`)
83
+ }
84
+ }
85
+ }
86
+
87
+ function selectCapabilities(capabilities, enabled) {
88
+ if (!enabled || !enabled.length) return capabilities
89
+ const byId = new Map(capabilities.map((cap) => [cap.id, cap]))
90
+ for (const id of enabled) {
91
+ if (!byId.has(id)) throw new Error(`enabled 里有未知能力: ${id}`)
92
+ }
93
+ const ids = new Set(enabled)
94
+ let changed = true
95
+ while (changed) {
96
+ changed = false
97
+ for (const cap of capabilities) {
98
+ if (!ids.has(cap.id)) continue
99
+ for (const dep of cap.dependsOn) {
100
+ if (!ids.has(dep)) { ids.add(dep); changed = true }
101
+ }
102
+ }
103
+ }
104
+ return capabilities.filter((cap) => ids.has(cap.id))
105
+ }
106
+
107
+ /**
108
+ * @param {Array} capabilities
109
+ * @param {{ enabled?: string[], ports?: object, report?: Function, reserved?: string[] }} options
110
+ */
111
+ export function createRegistry(capabilities, { enabled = null, ports = null, report = null, reserved = [], domain = '' } = {}) {
112
+ validateCapabilities(capabilities)
113
+ const selected = selectCapabilities(capabilities, enabled)
114
+
115
+ const kernelPorts = { ...(ports || {}) }
116
+ const reservedNames = new Set([...(reserved || []), 'contract'])
117
+ const providers = new Map()
118
+ for (const cap of selected) {
119
+ for (const [ns, api] of Object.entries(cap.provides || {})) {
120
+ if (reservedNames.has(ns)) throw new Error(`能力 ${cap.id} 不能覆盖内核端口: ${ns}`)
121
+ if (providers.has(ns)) throw new Error(`服务命名空间重复: ${ns}(${providers.get(ns).cap.id} / ${cap.id})`)
122
+ providers.set(ns, { cap, api })
123
+ }
124
+ }
125
+
126
+ const available = new Set([...Object.keys(kernelPorts), ...reservedNames, ...providers.keys()])
127
+ for (const cap of selected) {
128
+ for (const req of cap.requires) {
129
+ if (!available.has(req)) throw new Error(`能力 ${cap.id} 需要未提供的端口/服务: ${req}`)
130
+ }
131
+ }
132
+
133
+ const ctx = { ...kernelPorts }
134
+ for (const [ns, { api }] of providers) {
135
+ ctx[ns] = {}
136
+ for (const [method, fn] of Object.entries(api)) {
137
+ if (typeof fn !== 'function') throw new Error(`服务 ${ns}.${method} 必须是函数`)
138
+ ctx[ns][method] = (...args) => fn(ctx, ...args)
139
+ }
140
+ }
141
+
142
+ const TOOLS = []
143
+ const TOOL_IMPL = {}
144
+ const TOOL_META = {}
145
+ const FEATURES = []
146
+ const CAPABILITIES = []
147
+
148
+ for (const cap of selected) {
149
+ for (const feature of cap.features) {
150
+ if (!FEATURES.includes(feature)) FEATURES.push(feature)
151
+ }
152
+ CAPABILITIES.push({
153
+ id: cap.id,
154
+ title: cap.title,
155
+ description: cap.description,
156
+ tags: [...cap.tags],
157
+ domain: cap.domain || domain || '',
158
+ tools: cap.tools.map((tool) => tool.name),
159
+ })
160
+ for (const tool of cap.tools) {
161
+ TOOLS.push({ name: tool.name, description: tool.description, inputSchema: tool.inputSchema })
162
+ TOOL_META[tool.name] = { kind: tool.kind, since: tool.since, capability: cap.id, domain: tool.domain || cap.domain || domain || '' }
163
+ TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
164
+ }
165
+ }
166
+
167
+ const reportFn = report || createCapabilityReport
168
+ ctx.contract = {
169
+ report: (editorUrl = '', runtime = {}) => reportFn({
170
+ tools: TOOLS,
171
+ toolMeta: TOOL_META,
172
+ features: FEATURES,
173
+ capabilities: CAPABILITIES,
174
+ editorUrl,
175
+ runtime,
176
+ }),
177
+ }
178
+
179
+ /* 动态增删工具:配合 MCP 活引用(tools/list 读 registry.TOOLS),注册/注销后
180
+ * 客户端重新 list 即见最新工具集,无需重建 handler。旧 registry 是纯静态,
181
+ * 套件热重载/能力开关无法反映到工具面。 */
182
+ function registerTool(tool, capabilityId = '') {
183
+ if (!tool || typeof tool.name !== 'string' || !tool.name) throw new Error('registerTool 需要 tool.name')
184
+ if (typeof tool.handler !== 'function') throw new Error(`工具 ${tool.name} 需要 handler`)
185
+ if (TOOL_IMPL[tool.name]) throw new Error(`工具已存在: ${tool.name}`)
186
+ TOOLS.push({ name: tool.name, description: tool.description || '', inputSchema: tool.inputSchema || { type: 'object', properties: {} } })
187
+ TOOL_META[tool.name] = { kind: tool.kind || 'write', since: tool.since || '1.0.0', capability: capabilityId, domain: tool.domain || domain || '' }
188
+ TOOL_IMPL[tool.name] = (args) => tool.handler(args || {}, ctx)
189
+ return true
190
+ }
191
+ function unregisterTool(name) {
192
+ const index = TOOLS.findIndex((tool) => tool.name === name)
193
+ if (index < 0) return false
194
+ TOOLS.splice(index, 1)
195
+ delete TOOL_IMPL[name]
196
+ delete TOOL_META[name]
197
+ return true
198
+ }
199
+
200
+ return { TOOLS, TOOL_IMPL, TOOL_META, FEATURES, CAPABILITIES, ctx, registerTool, unregisterTool }
201
+ }
202
+
203
+ /** 与 MCP 工具面解耦:调用前统一校验。 */
204
+ export function createToolDispatcher({ tools, callTool }) {
205
+ const toolMap = new Map((tools || []).map((tool) => [tool.name, tool]))
206
+ return {
207
+ listTools() {
208
+ return { tools }
209
+ },
210
+ async callTool(name, args = {}) {
211
+ const tool = toolMap.get(name)
212
+ if (!tool) {
213
+ return { content: [{ type: 'text', text: `未知工具: ${String(name)}` }], isError: true }
214
+ }
215
+ const check = validateToolArguments(tool, args)
216
+ if (!check.ok) {
217
+ return { content: [{ type: 'text', text: '参数不合法:' + check.errors.join(';') }], isError: true }
218
+ }
219
+ const out = await callTool(name, args)
220
+ /* 与 MCP 面同一归一化:保留纯字符串/空 text/对象,不丢成 'ok'(B 轴 P0-5)。 */
221
+ return normalizeToolResult(out)
222
+ },
223
+ }
224
+ }
225
+
226
+ /**
227
+ * MCP Streamable HTTP 处理器。registry 可直接传 createRegistry 的返回值。
228
+ * 兼容两种调用:
229
+ * { registry } 或 { tools, toolImpl }
230
+ * { tools, callTool }(旧 relay 形态)
231
+ * @param {{ registry?: object, tools?: Array, toolImpl?: object, callTool?: Function, serverInfo?: object, instructions?: string }} options
232
+ */
233
+ export function createMcpHandler({ registry, tools, toolImpl, callTool, serverInfo, instructions, listChanged } = {}) {
234
+ /* registry 形态走活引用:tools/list 每次读 registry.TOOLS,callTool 读 registry.TOOL_IMPL,
235
+ * 于是 registerTool/unregisterTool 的动态增删立刻可见,无需重建 handler。 */
236
+ const useRegistry = !tools && !!registry
237
+ const impl = toolImpl || registry?.TOOL_IMPL || null
238
+ const staticList = tools || null
239
+ if (!useRegistry && (!Array.isArray(staticList) || !staticList.length)) throw new Error('createMcpHandler: 没有工具可暴露')
240
+ if (!impl && typeof callTool !== 'function') throw new Error('createMcpHandler: 需要 toolImpl 或 callTool')
241
+ return createKitMcpHandler({
242
+ tools: useRegistry ? () => registry.TOOLS : staticList,
243
+ callTool: (name, args, context) => {
244
+ if (typeof callTool === 'function' && !impl) return callTool(name, args, context)
245
+ const source = useRegistry ? registry.TOOL_IMPL : impl
246
+ const fn = source[name]
247
+ if (!fn) throw new Error(`未知工具: ${name}`)
248
+ return fn(args, context)
249
+ },
250
+ serverInfo: serverInfo || { name: 'dsh-tool-host', version: '0.1.0' },
251
+ instructions,
252
+ listChanged,
253
+ })
254
+ }
255
+
256
+ /** 把绝对地址收成同源相对路径:给人看的地址不带端口,端口是宿主的内部细节。 */
257
+ function sameOriginPath(url) {
258
+ const raw = String(url || '').trim()
259
+ if (!raw) return ''
260
+ if (raw.startsWith('/')) return raw
261
+ try {
262
+ const { pathname } = new URL(raw)
263
+ return pathname.endsWith('/') ? pathname : `${pathname}/`
264
+ } catch {
265
+ return ''
266
+ }
267
+ }
268
+
269
+ export function createCapabilityReport({
270
+ tools = [],
271
+ toolMeta = {},
272
+ features = [],
273
+ capabilities = [],
274
+ contractVersion = '1.0.0',
275
+ packageVersion = '0.0.0',
276
+ editorUrl = '',
277
+ runtime = {},
278
+ } = {}) {
279
+ return {
280
+ contractVersion,
281
+ packageVersion,
282
+ editorUrl,
283
+ editorPath: sameOriginPath(editorUrl),
284
+ ...runtime,
285
+ toolCount: tools.length,
286
+ tools: tools.map((tool) => ({
287
+ name: tool.name,
288
+ kind: toolMeta[tool.name]?.kind ?? 'write',
289
+ since: toolMeta[tool.name]?.since ?? '1.0.0',
290
+ capability: toolMeta[tool.name]?.capability ?? '',
291
+ })),
292
+ features,
293
+ capabilities: capabilities.map((cap) => ({
294
+ id: cap.id,
295
+ title: cap.title,
296
+ description: cap.description || '',
297
+ tags: cap.tags || [],
298
+ tools: cap.tools || [],
299
+ })),
300
+ }
301
+ }
302
+
303
+ /**
304
+ * 生成 MCP server instructions(≤32KB)。业务只提供数据,不再手写排版。
305
+ */
306
+ export function buildInstructions({
307
+ title = '',
308
+ intro = '',
309
+ startup = [],
310
+ capabilities = [],
311
+ tools = [],
312
+ rules = [],
313
+ output = [],
314
+ } = {}) {
315
+ const rows = capabilities.length
316
+ ? capabilities.map((cap) => `| ${cap.title} | ${cap.tools.map((name) => `\`${name}\``).join(', ')} | ${cap.description || ''} |`)
317
+ : [{
318
+ title: '工具',
319
+ tools: tools.map((tool) => tool.name),
320
+ description: '',
321
+ }].map((cap) => `| ${cap.title} | ${cap.tools.map((name) => `\`${name}\``).join(', ')} | |`)
322
+
323
+ const lines = []
324
+ if (title) lines.push(`# ${title}`, '')
325
+ if (intro) lines.push(intro, '')
326
+ if (startup.length) {
327
+ lines.push('## 启动检查')
328
+ startup.forEach((line, index) => lines.push(`${index + 1}. ${line}`))
329
+ lines.push('')
330
+ }
331
+ lines.push('## 能力面', '| 能力 | 工具 | 用途 |', '|---|---|---|', ...rows, '')
332
+ if (rules.length) {
333
+ lines.push('## 硬规则')
334
+ rules.forEach((line) => lines.push(`- ${line}`))
335
+ lines.push('')
336
+ }
337
+ if (output.length) {
338
+ lines.push('## 输出')
339
+ output.forEach((line) => lines.push(`- ${line}`))
340
+ }
341
+ return lines.join('\n')
342
+ }
343
+
344
+ /**
345
+ * 把能力注册表直接注册到 DSH 的 ctx.tools(同进程原生工具面)。
346
+ * 注册后不再需要单独的 loopback /mcp 端口和 @deepseek-ai/dsh-mcp-client row。
347
+ *
348
+ * `execute(args, exec)` 的第二个参数是 DSH 的调用上下文,`exec.agent.session.id`
349
+ * 是「哪个会话调用了这个工具」——多会话工作台要靠它把写入落到调用者的那份文档上。
350
+ * 以前这里写成 `(args) => impl(args)`,把它丢了,于是工具只能退化成"猜用户在看哪个窗口"。
351
+ *
352
+ * @param {object} ctx DSH cordis context
353
+ * @param {object} registry createRegistry() 的返回值
354
+ * @param {{ namespace?: string, domain?: string, modeGate?: object }} options
355
+ * domain:本 registry 的兜底领域(工具/能力未各自声明时用);
356
+ * modeGate:会话模式锁闸(createToolHost 服务级自动注入;独立调用可显式传)。
357
+ * @returns {() => void} 反注册全部工具
358
+ */
359
+ export function registerWithDsh(ctx, registry, { namespace = '', domain = '', modeGate = null } = {}) {
360
+ if (!ctx?.tools?.register) throw new Error('registerWithDsh: 当前 DSH 没有 ctx.tools.register')
361
+ /* 领域工具一旦注册即声明给模式锁,并挂全局 guard 兜底(幂等)。
362
+ * install 的引用计数 disposer 必须随本次注册一起释放(旧写法丢弃⇒核心工具/guard 泄漏)。 */
363
+ const gateDispose = modeGate ? modeGate.install(ctx.tools) : null
364
+ const disposers = []
365
+ if (typeof gateDispose === 'function') disposers.push(gateDispose)
366
+ /* 感知闸补挂(幂等):driver apply 那一刻 systemPrompt 可能尚未就绪,套件注册时再挂一次。
367
+ * 引用计数 disposer 随本次注册一起释放。cordis 服务缺席时访问可能抛错,try 包裹降级。 */
368
+ if (modeGate && typeof modeGate.installPrompt === 'function') {
369
+ let systemPrompt = null
370
+ try { systemPrompt = ctx.systemPrompt } catch { systemPrompt = null }
371
+ if (systemPrompt && typeof systemPrompt.section === 'function') {
372
+ const promptDispose = modeGate.installPrompt(systemPrompt)
373
+ if (typeof promptDispose === 'function') disposers.push(promptDispose)
374
+ }
375
+ }
376
+ try {
377
+ for (const tool of registry?.TOOLS || []) {
378
+ const impl = registry.TOOL_IMPL?.[tool.name]
379
+ if (typeof impl !== 'function') throw new Error(`registerWithDsh: 工具缺少实现 ${tool.name}`)
380
+ const name = namespace ? `${namespace}_${tool.name}` : tool.name
381
+ const toolDomain = registry.TOOL_META?.[tool.name]?.domain || domain || ''
382
+ let when
383
+ if (modeGate && toolDomain) {
384
+ modeGate.declareTools(toolDomain, [name])
385
+ when = modeGate.whenFor(name)
386
+ }
387
+ disposers.push(ctx.tools.register({
388
+ name,
389
+ description: tool.description || '',
390
+ parameters: tool.inputSchema || { type: 'object', properties: {}, additionalProperties: false },
391
+ output: {
392
+ /* execute 恒返回归一化 {content:[...]} object,故此 object schema 恒满足,
393
+ * 不再与 string/{text}/undefined 返回冲突(B 轴 P0-2)。 */
394
+ schema: { type: 'object', additionalProperties: true },
395
+ render: (args, value) => (value && Array.isArray(value.content)
396
+ ? value.content
397
+ : normalizeToolResult(value).content),
398
+ },
399
+ execute: async (args, exec) => runWithCallerSession(exec?.agent?.session?.id, async () => {
400
+ const normalized = normalizeToolResult(await impl(args, exec))
401
+ /* DSH 原生面成功恒 isError:false,失败必须 throw 才走错误路径(B 轴 P0-1)。
402
+ * 把工具自报的 isError:true 转成 throw,与 MCP 面的失败语义对齐。 */
403
+ if (normalized.isError === true) {
404
+ throw new Error(resultText(normalized) || `工具 ${name} 执行失败`)
405
+ }
406
+ /* 图像准入:裸 base64 图像块(rsp_screen/browser_screenshot 等)必须先持久化成
407
+ * attachment ref 再入 session 日志,否则下一步序列化读 block.attachment.attachmentId
408
+ * 抛错、永久毒化该会话(2026-11-22 根因)。MCP 面不走这里,保留 wire 形态。 */
409
+ const content = await admitToolResultImages(normalized.content, resolveAttachments(exec, ctx), { name })
410
+ return { ...normalized, content }
411
+ }),
412
+ }, when ? { when } : {}))
413
+ }
414
+ } catch (error) {
415
+ /* 全有或全无:任一工具注册失败,逆序释放已注册的,避免部分注册泄漏(B 轴 P0-6)。 */
416
+ for (let i = disposers.length - 1; i >= 0; i--) {
417
+ try { disposers[i]() } catch { /* 忽略释放失败 */ }
418
+ }
419
+ throw error
420
+ }
421
+ return () => {
422
+ for (const dispose of disposers) {
423
+ try { dispose() } catch { /* 忽略重复释放 */ }
424
+ }
425
+ }
426
+ }
427
+
428
+ export function createToolHost(config = {}) {
429
+ // 跨套件能力发现注册表(互联标准 §A.4/§E)。深度校验器可选注入(suite-kit)。
430
+ const descriptors = createDescriptorRegistry({ validate: config.validateDescriptor })
431
+ // 会话模式锁:全服务共享一个闸实例(所有套件的注册都经此)。getWorkStore 惰性解析
432
+ // (driver 注入 () => safeGet(ctx,'workStore'));底座缺席则降级为恒可见、不拒。
433
+ const modeGate = createModeGate({ getWorkStore: config.getWorkStore })
434
+ return {
435
+ // M12 对齐:自报以 package.json 为权威——dsh.apiVersion=1.1.0(对外契约,
436
+ // 消费者 assertServiceApi 只断言 major 1),version=0.3.1。旧自报 1.2.0/0.3.0 是漂移。
437
+ api: createServiceApi('toolHost', '1.1.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors', 'mode-gate']),
438
+ version: '0.3.1',
439
+ defineTool,
440
+ defineCapability,
441
+ createRegistry: (capabilities, options = {}) => createRegistry(capabilities, { ...config, ...options }),
442
+ createMcpHandler,
443
+ createToolDispatcher,
444
+ createCapabilityReport,
445
+ buildInstructions,
446
+ // 服务级注册自动带会话模式锁(when 可见性 + guard 硬拒 + 感知提示 + 调用者会话 ALS),套件零接线。
447
+ registerWithDsh: (ctx, registry, options = {}) => registerWithDsh(ctx, registry, { modeGate, ...options }),
448
+ validateToolArguments,
449
+ modeGate,
450
+ // 能力描述符注册/发现(编排器按类型动态发现,套件零互依赖)。
451
+ registerCapabilityDescriptor: (descriptor, options) => descriptors.register(descriptor, options),
452
+ unregisterCapabilityDescriptor: (name) => descriptors.unregister(name),
453
+ // 发现面按调用者会话过滤:原生工具调用里自动从 ALS 取会话(conductor_discover 无需接线);
454
+ // HTTP/墙等管理面无会话 → 不过滤(全局视图)。query.sessionId 可显式覆盖。
455
+ discoverCapabilities: (query = {}) => modeGate.filterEntries(descriptors.discover(query), query.sessionId || currentCallerSession()),
456
+ capabilityCatalog: () => descriptors.catalog(),
457
+ listSurfaces: () => descriptors.listSurfaces(),
458
+ }
459
+ }
460
+
461
+ export { validateToolArguments }