@capyclaw/capyclaw-workbench 0.0.0-stage → 0.1.0

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 (109) hide show
  1. package/README.md +28 -2
  2. package/contract/capabilities.json +178 -0
  3. package/lib/descriptors.mjs +33 -0
  4. package/lib/host.mjs +102 -0
  5. package/lib/session-port.mjs +104 -0
  6. package/lib/tools.mjs +166 -0
  7. package/lib/workbench.mjs +133 -0
  8. package/node_modules/@capyclaw/foundation/README.md +51 -0
  9. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  10. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  11. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  12. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  13. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  14. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  15. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  16. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  17. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  18. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  19. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  20. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  31. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  32. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  33. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  34. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  35. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  36. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  37. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  38. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
  39. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  40. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  41. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  42. package/node_modules/@capyclaw/foundation/package.json +53 -0
  43. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  44. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  45. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  46. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  47. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +143 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +41 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  73. package/node_modules/@capyclaw/service-host/README.md +86 -0
  74. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  75. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  76. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  77. package/node_modules/@capyclaw/service-host/package.json +60 -0
  78. package/node_modules/@capyclaw/service-host/src/index.mjs +571 -0
  79. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  80. package/node_modules/@capyclaw/suite-kit/README.md +238 -0
  81. package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
  82. package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
  83. package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
  84. package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
  85. package/node_modules/@capyclaw/suite-kit/package.json +54 -0
  86. package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
  87. package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
  88. package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
  89. package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
  90. package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
  91. package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
  92. package/node_modules/@capyclaw/suite-kit/src/index.mjs +10 -0
  93. package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
  94. package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
  95. package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
  96. package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
  97. package/node_modules/@capyclaw/suite-kit/suite.schema.json +112 -0
  98. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  99. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  100. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  101. package/node_modules/@capyclaw/tool-host/lib/host.mjs +16 -0
  102. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  103. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +142 -0
  104. package/node_modules/@capyclaw/tool-host/src/index.mjs +390 -0
  105. package/package.json +68 -4
  106. package/plugin.mjs +1 -0
  107. package/ui/app.js +114 -0
  108. package/ui/index.html +64 -0
  109. package/ui/style.css +54 -0
@@ -0,0 +1,390 @@
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
+ return { TOOLS, TOOL_IMPL, TOOL_META, FEATURES, CAPABILITIES, ctx }
170
+ }
171
+
172
+ /** 与 MCP 工具面解耦:调用前统一校验。 */
173
+ export function createToolDispatcher({ tools, callTool }) {
174
+ const toolMap = new Map((tools || []).map((tool) => [tool.name, tool]))
175
+ return {
176
+ listTools() {
177
+ return { tools }
178
+ },
179
+ async callTool(name, args = {}) {
180
+ const tool = toolMap.get(name)
181
+ if (!tool) {
182
+ return { content: [{ type: 'text', text: `未知工具: ${String(name)}` }], isError: true }
183
+ }
184
+ const check = validateToolArguments(tool, args)
185
+ if (!check.ok) {
186
+ return { content: [{ type: 'text', text: '参数不合法:' + check.errors.join(';') }], isError: true }
187
+ }
188
+ const out = await callTool(name, args)
189
+ /* 与 MCP 面同一归一化:保留纯字符串/空 text/对象,不丢成 'ok'(B 轴 P0-5)。 */
190
+ return normalizeToolResult(out)
191
+ },
192
+ }
193
+ }
194
+
195
+ /**
196
+ * MCP Streamable HTTP 处理器。registry 可直接传 createRegistry 的返回值。
197
+ * 兼容两种调用:
198
+ * { registry } 或 { tools, toolImpl }
199
+ * { tools, callTool }(旧 relay 形态)
200
+ * @param {{ registry?: object, tools?: Array, toolImpl?: object, callTool?: Function, serverInfo?: object, instructions?: string }} options
201
+ */
202
+ export function createMcpHandler({ registry, tools, toolImpl, callTool, serverInfo, instructions } = {}) {
203
+ const list = tools || registry?.TOOLS || []
204
+ const impl = toolImpl || registry?.TOOL_IMPL || null
205
+ if (!Array.isArray(list) || !list.length) throw new Error('createMcpHandler: 没有工具可暴露')
206
+ if (!impl && typeof callTool !== 'function') throw new Error('createMcpHandler: 需要 toolImpl 或 callTool')
207
+ return createKitMcpHandler({
208
+ tools: list,
209
+ callTool: (name, args, context) => {
210
+ if (typeof callTool === 'function' && !impl) return callTool(name, args, context)
211
+ const fn = impl[name]
212
+ if (!fn) throw new Error(`未知工具: ${name}`)
213
+ return fn(args, context)
214
+ },
215
+ serverInfo: serverInfo || { name: 'dsh-tool-host', version: '0.1.0' },
216
+ instructions,
217
+ })
218
+ }
219
+
220
+ /** 把绝对地址收成同源相对路径:给人看的地址不带端口,端口是宿主的内部细节。 */
221
+ function sameOriginPath(url) {
222
+ const raw = String(url || '').trim()
223
+ if (!raw) return ''
224
+ if (raw.startsWith('/')) return raw
225
+ try {
226
+ const { pathname } = new URL(raw)
227
+ return pathname.endsWith('/') ? pathname : `${pathname}/`
228
+ } catch {
229
+ return ''
230
+ }
231
+ }
232
+
233
+ export function createCapabilityReport({
234
+ tools = [],
235
+ toolMeta = {},
236
+ features = [],
237
+ capabilities = [],
238
+ contractVersion = '1.0.0',
239
+ packageVersion = '0.0.0',
240
+ editorUrl = '',
241
+ runtime = {},
242
+ } = {}) {
243
+ return {
244
+ contractVersion,
245
+ packageVersion,
246
+ editorUrl,
247
+ editorPath: sameOriginPath(editorUrl),
248
+ ...runtime,
249
+ toolCount: tools.length,
250
+ tools: tools.map((tool) => ({
251
+ name: tool.name,
252
+ kind: toolMeta[tool.name]?.kind ?? 'write',
253
+ since: toolMeta[tool.name]?.since ?? '1.0.0',
254
+ capability: toolMeta[tool.name]?.capability ?? '',
255
+ })),
256
+ features,
257
+ capabilities: capabilities.map((cap) => ({
258
+ id: cap.id,
259
+ title: cap.title,
260
+ description: cap.description || '',
261
+ tags: cap.tags || [],
262
+ tools: cap.tools || [],
263
+ })),
264
+ }
265
+ }
266
+
267
+ /**
268
+ * 生成 MCP server instructions(≤32KB)。业务只提供数据,不再手写排版。
269
+ */
270
+ export function buildInstructions({
271
+ title = '',
272
+ intro = '',
273
+ startup = [],
274
+ capabilities = [],
275
+ tools = [],
276
+ rules = [],
277
+ output = [],
278
+ } = {}) {
279
+ const rows = capabilities.length
280
+ ? capabilities.map((cap) => `| ${cap.title} | ${cap.tools.map((name) => `\`${name}\``).join(', ')} | ${cap.description || ''} |`)
281
+ : [{
282
+ title: '工具',
283
+ tools: tools.map((tool) => tool.name),
284
+ description: '',
285
+ }].map((cap) => `| ${cap.title} | ${cap.tools.map((name) => `\`${name}\``).join(', ')} | |`)
286
+
287
+ const lines = []
288
+ if (title) lines.push(`# ${title}`, '')
289
+ if (intro) lines.push(intro, '')
290
+ if (startup.length) {
291
+ lines.push('## 启动检查')
292
+ startup.forEach((line, index) => lines.push(`${index + 1}. ${line}`))
293
+ lines.push('')
294
+ }
295
+ lines.push('## 能力面', '| 能力 | 工具 | 用途 |', '|---|---|---|', ...rows, '')
296
+ if (rules.length) {
297
+ lines.push('## 硬规则')
298
+ rules.forEach((line) => lines.push(`- ${line}`))
299
+ lines.push('')
300
+ }
301
+ if (output.length) {
302
+ lines.push('## 输出')
303
+ output.forEach((line) => lines.push(`- ${line}`))
304
+ }
305
+ return lines.join('\n')
306
+ }
307
+
308
+ /**
309
+ * 把能力注册表直接注册到 DSH 的 ctx.tools(同进程原生工具面)。
310
+ * 注册后不再需要单独的 loopback /mcp 端口和 @deepseek-ai/dsh-mcp-client row。
311
+ *
312
+ * `execute(args, exec)` 的第二个参数是 DSH 的调用上下文,`exec.agent.session.id`
313
+ * 是「哪个会话调用了这个工具」——多会话工作台要靠它把写入落到调用者的那份文档上。
314
+ * 以前这里写成 `(args) => impl(args)`,把它丢了,于是工具只能退化成"猜用户在看哪个窗口"。
315
+ *
316
+ * @param {object} ctx DSH cordis context
317
+ * @param {object} registry createRegistry() 的返回值
318
+ * @param {{ namespace?: string }} options
319
+ * @returns {() => void} 反注册全部工具
320
+ */
321
+ export function registerWithDsh(ctx, registry, { namespace = '' } = {}) {
322
+ if (!ctx?.tools?.register) throw new Error('registerWithDsh: 当前 DSH 没有 ctx.tools.register')
323
+ const disposers = []
324
+ try {
325
+ for (const tool of registry?.TOOLS || []) {
326
+ const impl = registry.TOOL_IMPL?.[tool.name]
327
+ if (typeof impl !== 'function') throw new Error(`registerWithDsh: 工具缺少实现 ${tool.name}`)
328
+ const name = namespace ? `${namespace}_${tool.name}` : tool.name
329
+ disposers.push(ctx.tools.register({
330
+ name,
331
+ description: tool.description || '',
332
+ parameters: tool.inputSchema || { type: 'object', properties: {}, additionalProperties: false },
333
+ output: {
334
+ /* execute 恒返回归一化 {content:[...]} object,故此 object schema 恒满足,
335
+ * 不再与 string/{text}/undefined 返回冲突(B 轴 P0-2)。 */
336
+ schema: { type: 'object', additionalProperties: true },
337
+ render: (args, value) => (value && Array.isArray(value.content)
338
+ ? value.content
339
+ : normalizeToolResult(value).content),
340
+ },
341
+ execute: async (args, exec) => {
342
+ const normalized = normalizeToolResult(await impl(args, exec))
343
+ /* DSH 原生面成功恒 isError:false,失败必须 throw 才走错误路径(B 轴 P0-1)。
344
+ * 把工具自报的 isError:true 转成 throw,与 MCP 面的失败语义对齐。 */
345
+ if (normalized.isError === true) {
346
+ throw new Error(resultText(normalized) || `工具 ${name} 执行失败`)
347
+ }
348
+ return normalized
349
+ },
350
+ }))
351
+ }
352
+ } catch (error) {
353
+ /* 全有或全无:任一工具注册失败,逆序释放已注册的,避免部分注册泄漏(B 轴 P0-6)。 */
354
+ for (let i = disposers.length - 1; i >= 0; i--) {
355
+ try { disposers[i]() } catch { /* 忽略释放失败 */ }
356
+ }
357
+ throw error
358
+ }
359
+ return () => {
360
+ for (const dispose of disposers) {
361
+ try { dispose() } catch { /* 忽略重复释放 */ }
362
+ }
363
+ }
364
+ }
365
+
366
+ export function createToolHost(config = {}) {
367
+ // 跨套件能力发现注册表(互联标准 §A.4/§E)。深度校验器可选注入(suite-kit)。
368
+ const descriptors = createDescriptorRegistry({ validate: config.validateDescriptor })
369
+ return {
370
+ api: createServiceApi('toolHost', '1.1.0', ['dsl', 'registry', 'validate', 'contract', 'mcp', 'instructions', 'native-tools', 'descriptors']),
371
+ version: '0.2.0',
372
+ defineTool,
373
+ defineCapability,
374
+ createRegistry: (capabilities, options = {}) => createRegistry(capabilities, { ...config, ...options }),
375
+ createMcpHandler,
376
+ createToolDispatcher,
377
+ createCapabilityReport,
378
+ buildInstructions,
379
+ registerWithDsh,
380
+ validateToolArguments,
381
+ // 能力描述符注册/发现(编排器按类型动态发现,套件零互依赖)。
382
+ registerCapabilityDescriptor: (descriptor, options) => descriptors.register(descriptor, options),
383
+ unregisterCapabilityDescriptor: (name) => descriptors.unregister(name),
384
+ discoverCapabilities: (query) => descriptors.discover(query),
385
+ capabilityCatalog: () => descriptors.catalog(),
386
+ listSurfaces: () => descriptors.listSurfaces(),
387
+ }
388
+ }
389
+
390
+ export { validateToolArguments }
package/package.json CHANGED
@@ -1,6 +1,70 @@
1
1
  {
2
2
  "name": "@capyclaw/capyclaw-workbench",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "CapyClaw 子会话工作台运行时:7 个 capyclaw_* 工具(创建/驱动/查询/关闭 DSH 子会话 + 读写设置)+ 俄罗斯套娃控制台(同源嵌入 DSH GUI)。挂在 dsh 的 /capyclaw/capyclaw。",
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
+ "manifest": "contract/capabilities.json"
24
+ },
25
+ "requires": {
26
+ "capabilities": {
27
+ "tools.registry": "^1.0.0",
28
+ "tools.descriptors": "^1.1.0"
29
+ }
30
+ }
31
+ },
32
+ "meta": {
33
+ "title": "CapyClaw 子会话工作台运行时",
34
+ "description": "AI 在同一宿主进程内发起/驱动 DSH 子会话(俄罗斯套娃),并帮用户完成 DSH 设置;能力经描述符注册供上层编排器发现。"
35
+ },
36
+ "files": [
37
+ "plugin.mjs",
38
+ "lib/",
39
+ "ui/",
40
+ "contract/",
41
+ "README.md"
42
+ ],
43
+ "license": "MIT",
44
+ "scripts": {
45
+ "test": "node --test --test-isolation=none test/*.test.mjs"
46
+ },
47
+ "dependencies": {
48
+ "@capyclaw/foundation": "^0.1.9",
49
+ "@capyclaw/plugin-kit": "^0.2.6",
50
+ "@capyclaw/service-host": "^0.1.5",
51
+ "@capyclaw/suite-kit": "^0.2.0",
52
+ "@capyclaw/tool-host": "^0.2.0"
53
+ },
54
+ "author": {
55
+ "name": "CapyClaw",
56
+ "url": "https://github.com/capyclaw"
57
+ },
58
+ "repository": {
59
+ "type": "git",
60
+ "url": "git+https://github.com/Maple496/capyclaw.git",
61
+ "directory": "A/projects/capyclaw/workbench"
62
+ },
63
+ "bundledDependencies": [
64
+ "@capyclaw/foundation",
65
+ "@capyclaw/plugin-kit",
66
+ "@capyclaw/service-host",
67
+ "@capyclaw/suite-kit",
68
+ "@capyclaw/tool-host"
69
+ ]
70
+ }
package/plugin.mjs ADDED
@@ -0,0 +1 @@
1
+ export { name, inject, apply } from './lib/host.mjs'
package/ui/app.js ADDED
@@ -0,0 +1,114 @@
1
+ /* CapyClaw 子会话工作台 UI。控制面与呈现面分离:工具/HTTP 同一接口,模式只是呈现层状态。 */
2
+ (function () {
3
+ const $ = (s, r) => (r || document).querySelector(s)
4
+ const $$ = (s, r) => [...(r || document).querySelectorAll(s)]
5
+ const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' }[c]))
6
+ let CFG = { guiUrl: '/', mountPath: '/capyclaw/capyclaw', available: {} }
7
+
8
+ if (window.CapyclawEmbed) window.CapyclawEmbed.setSuite('capyclaw')
9
+ const emit = (kind, payload) => { try { window.CapyclawEmbed && window.CapyclawEmbed.sendEvent({ kind, suite: 'capyclaw', at: Date.now(), ...payload }) } catch {} }
10
+
11
+ function toast(msg, isErr) {
12
+ const t = $('#toast'); t.textContent = msg; t.className = 'toast show' + (isErr ? ' err' : '')
13
+ clearTimeout(t._h); t._h = setTimeout(() => { t.className = 'toast' }, 2600)
14
+ }
15
+ async function api(method, url, body) {
16
+ const opt = { method, headers: {} }
17
+ if (body !== undefined) { opt.headers['content-type'] = 'application/json'; opt.body = JSON.stringify(body) }
18
+ const res = await fetch(url, opt)
19
+ let data = {}; try { data = await res.json() } catch {}
20
+ if (!res.ok || data.ok === false) throw new Error(data.error || ('HTTP ' + res.status))
21
+ return data
22
+ }
23
+
24
+ // ---- 配置 / 可用性 ----
25
+ async function loadConfig() {
26
+ try {
27
+ CFG = await api('GET', './api/config')
28
+ $('#gui').src = CFG.guiUrl || '/'
29
+ $('#gui-open').href = CFG.guiUrl || '/'
30
+ const a = CFG.available || {}
31
+ const on = a.sessionController
32
+ const pill = $('#avail'); pill.textContent = on ? '会话服务可用' : '会话服务不可用'
33
+ pill.className = 'pill ' + (on ? 'ok' : 'bad')
34
+ } catch (e) { toast('配置加载失败:' + e.message, true) }
35
+ }
36
+
37
+ // ---- 子会话 ----
38
+ async function loadSessions() {
39
+ const box = $('#session-list')
40
+ try {
41
+ const { items } = await api('GET', './api/sessions')
42
+ if (!items.length) { box.innerHTML = '<div class="empty">还没有子会话。创建一个,让 AI 在同一宿主里替你干活。</div>'; return }
43
+ box.innerHTML = items.map((s) => {
44
+ const id = esc(s.sessionId || s.id)
45
+ return `<div class="session ${s.closed ? 'closed' : ''}" data-id="${id}">
46
+ <div class="s-title"><span>${esc(s.title || '子会话')}</span>${s.closed ? '<span class="pill">已关闭</span>' : ''}</div>
47
+ <div class="s-id">${id}</div>
48
+ <div class="s-prompt"><input placeholder="下发指令…" data-act="prompt-input"><button class="btn small" data-act="send">发送</button></div>
49
+ <div class="s-actions">
50
+ <button class="btn small" data-act="transcript">转录</button>
51
+ <button class="btn small" data-act="close">关闭</button>
52
+ </div>
53
+ <details hidden><pre class="code" data-out></pre></details>
54
+ </div>`
55
+ }).join('')
56
+ } catch (e) { box.innerHTML = '<div class="empty">加载失败:' + esc(e.message) + '</div>' }
57
+ }
58
+
59
+ $('#create-form').addEventListener('submit', async (ev) => {
60
+ ev.preventDefault()
61
+ const f = ev.target
62
+ const body = { title: f.title.value.trim() || undefined, cwd: f.cwd.value.trim() || undefined, prompt: f.prompt.value.trim() || undefined }
63
+ try {
64
+ const r = await api('POST', './api/sessions', body)
65
+ toast('已创建 ' + r.sessionId.slice(0, 8)); emit('result', { action: 'session.open', sessionId: r.sessionId })
66
+ f.reset(); await loadSessions()
67
+ } catch (e) { toast('创建失败:' + e.message, true); emit('error', { action: 'session.open', message: e.message }) }
68
+ })
69
+
70
+ $('#session-list').addEventListener('click', async (ev) => {
71
+ const btn = ev.target.closest('[data-act]'); if (!btn) return
72
+ const card = btn.closest('.session'); const id = card.dataset.id; const act = btn.dataset.act
73
+ try {
74
+ if (act === 'send') {
75
+ const input = $('[data-act="prompt-input"]', card); const text = input.value.trim()
76
+ if (!text) return toast('先写指令', true)
77
+ const r = await api('POST', './api/sessions/prompt', { sessionId: id, text })
78
+ input.value = ''; toast(r.accepted ? '已下发' : '已排队'); emit('progress', { action: 'session.prompt', sessionId: id })
79
+ } else if (act === 'transcript') {
80
+ const det = $('details', card); const out = $('[data-out]', card)
81
+ const r = await api('GET', './api/sessions/transcript?sessionId=' + encodeURIComponent(id))
82
+ out.textContent = JSON.stringify(r.transcript, null, 2); det.hidden = false
83
+ } else if (act === 'close') {
84
+ await api('POST', './api/sessions/close', { sessionId: id })
85
+ toast('已关闭'); emit('result', { action: 'session.close', sessionId: id }); await loadSessions()
86
+ }
87
+ } catch (e) { toast(e.message, true); emit('error', { action: act, sessionId: id, message: e.message }) }
88
+ })
89
+
90
+ // ---- 设置 ----
91
+ $('#settings-load').addEventListener('click', async () => {
92
+ try { const r = await api('GET', './api/settings'); $('#settings-view').textContent = JSON.stringify(r.settings, null, 2) }
93
+ catch (e) { toast('读取失败:' + e.message, true) }
94
+ })
95
+ $('#settings-form').addEventListener('submit', async (ev) => {
96
+ ev.preventDefault(); const f = ev.target
97
+ let patch; try { patch = JSON.parse(f.patch.value || '{}') } catch { return toast('patch 不是合法 JSON', true) }
98
+ if (!confirm('设置更新为高风险操作,确认提交?')) return
99
+ try {
100
+ const r = await api('POST', './api/settings', { ns: f.ns.value.trim(), patch })
101
+ $('#settings-view').textContent = JSON.stringify(r.value, null, 2)
102
+ toast('设置已更新'); emit('result', { action: 'settings.set', ns: f.ns.value.trim() })
103
+ } catch (e) { toast('更新失败:' + e.message, true); emit('error', { action: 'settings.set', message: e.message }) }
104
+ })
105
+
106
+ // ---- tabs / refresh ----
107
+ $$('.tab').forEach((t) => t.addEventListener('click', () => {
108
+ $$('.tab').forEach((x) => x.classList.toggle('active', x === t))
109
+ $$('.tabpane').forEach((p) => p.classList.toggle('active', p.id === 'tab-' + t.dataset.tab))
110
+ }))
111
+ $('#refresh').addEventListener('click', loadSessions)
112
+
113
+ loadConfig().then(loadSessions)
114
+ })()
package/ui/index.html ADDED
@@ -0,0 +1,64 @@
1
+ <!doctype html>
2
+ <html lang="zh">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>CapyClaw 子会话工作台</title>
7
+ <link rel="stylesheet" href="./style.css">
8
+ </head>
9
+ <body>
10
+ <header class="topbar standalone-chrome">
11
+ <div class="brand">🪆 CapyClaw <span class="sub">子会话工作台 · 同一宿主进程</span></div>
12
+ <div class="top-actions">
13
+ <span id="avail" class="pill">检测中…</span>
14
+ <button id="refresh" class="btn ghost">刷新</button>
15
+ </div>
16
+ </header>
17
+
18
+ <div class="layout">
19
+ <aside class="panel">
20
+ <nav class="tabs">
21
+ <button class="tab active" data-tab="sessions">子会话</button>
22
+ <button class="tab" data-tab="settings">DSH 设置</button>
23
+ </nav>
24
+
25
+ <section id="tab-sessions" class="tabpane active">
26
+ <form id="create-form" class="card">
27
+ <h3>发起子会话</h3>
28
+ <label>标题<input name="title" placeholder="例如:调研竞品"></label>
29
+ <label>工作目录 cwd<input name="cwd" placeholder="留空=宿主默认"></label>
30
+ <label>首条指令<textarea name="prompt" rows="2" placeholder="可选:创建后立即下发"></textarea></label>
31
+ <button class="btn primary" type="submit">创建</button>
32
+ </form>
33
+ <div id="session-list" class="list"></div>
34
+ </section>
35
+
36
+ <section id="tab-settings" class="tabpane">
37
+ <div class="card">
38
+ <h3>读取设置</h3>
39
+ <button id="settings-load" class="btn">加载 describe</button>
40
+ <pre id="settings-view" class="code"></pre>
41
+ </div>
42
+ <form id="settings-form" class="card">
43
+ <h3>更新设置(高风险,需确认)</h3>
44
+ <label>命名空间 ns<input name="ns" placeholder="profile 条目 id"></label>
45
+ <label>patch(JSON)<textarea name="patch" rows="3" placeholder='{"key":"value"}'></textarea></label>
46
+ <button class="btn danger" type="submit">提交更新</button>
47
+ </form>
48
+ </section>
49
+ </aside>
50
+
51
+ <main class="stage">
52
+ <div class="stage-head standalone-chrome">
53
+ <span>宿主 GUI(俄罗斯套娃 · 同源嵌入)</span>
54
+ <a id="gui-open" class="btn ghost" target="_blank" rel="noopener">新窗打开</a>
55
+ </div>
56
+ <iframe id="gui" class="gui" title="DSH GUI" src="about:blank"></iframe>
57
+ </main>
58
+ </div>
59
+
60
+ <div id="toast" class="toast"></div>
61
+ <script src="./embed.js"></script>
62
+ <script src="./app.js"></script>
63
+ </body>
64
+ </html>