@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
package/README.md CHANGED
@@ -1,3 +1,29 @@
1
- # Temporary Holding Version
1
+ # @capyclaw/capyclaw-workbench
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ CapyClaw 子会话工作台运行时:让 AI 在同一宿主进程内发起、驱动、查询、关闭 DSH 子会话(俄罗斯套娃),并代用户读写 DSH 设置。挂在 dsh 的 `/capyclaw/capyclaw` 前缀下,能力经描述符注册供上层编排器发现。
4
+
5
+ ## 工具面(7 个)
6
+
7
+ | 工具 | 作用 |
8
+ | --- | --- |
9
+ | `capyclaw_open_session` | 创建子会话并发出第一条指令 |
10
+ | `capyclaw_send_message` | 向运行中/空闲子会话继续发消息 |
11
+ | `capyclaw_list_sessions` | 列出子会话及状态 |
12
+ | `capyclaw_session_transcript` | 读取子会话转录 |
13
+ | `capyclaw_close_session` | 关闭子会话 |
14
+ | `capyclaw_settings_get` | 读取 DSH 设置 |
15
+ | `capyclaw_settings_set` | 写入 DSH 设置 |
16
+
17
+ ## 控制台
18
+
19
+ `ui/` 提供同源嵌入 DSH GUI 的套娃控制台,可直接查看/操作子会话。
20
+
21
+ ## 承载形态
22
+
23
+ 宿主进程内插件(foundation ABI):有 `ctx.webServer` 时挂宿主路由前缀,不单独占端口;工具经 `tools.registry` / `tools.descriptors` 能力注册。
24
+
25
+ ## 测试
26
+
27
+ ```bash
28
+ npm test
29
+ ```
@@ -0,0 +1,178 @@
1
+ {
2
+ "contractVersion": "0.1.0",
3
+ "suite": "capyclaw",
4
+ "surface": {
5
+ "standalone": true,
6
+ "embeddable": true,
7
+ "embedPath": "/capyclaw/capyclaw"
8
+ },
9
+ "capabilities": [
10
+ {
11
+ "name": "capyclaw.session.open",
12
+ "capability": "session.open",
13
+ "suite": "capyclaw",
14
+ "controlMode": "interface",
15
+ "kind": "control",
16
+ "since": "0.1.0",
17
+ "description": "在同一宿主进程内创建一个 DSH 子会话(俄罗斯套娃控制面),可选立即发启动消息。",
18
+ "tool": "capyclaw_open_session",
19
+ "consumes": [],
20
+ "produces": [
21
+ "session:subsession"
22
+ ],
23
+ "auth": null,
24
+ "risk": "low",
25
+ "confirm": false,
26
+ "surface": {
27
+ "standalone": true,
28
+ "embeddable": true,
29
+ "embedPath": "/capyclaw/capyclaw",
30
+ "title": "CapyClaw 子会话工作台"
31
+ }
32
+ },
33
+ {
34
+ "name": "capyclaw.session.send",
35
+ "capability": "session.send",
36
+ "suite": "capyclaw",
37
+ "controlMode": "interface",
38
+ "kind": "write",
39
+ "since": "0.1.0",
40
+ "description": "向子会话发送用户消息,启动一轮 agent 工作。",
41
+ "tool": "capyclaw_send_message",
42
+ "consumes": [
43
+ "session:subsession"
44
+ ],
45
+ "produces": [
46
+ "session:turn"
47
+ ],
48
+ "auth": null,
49
+ "risk": "low",
50
+ "confirm": false,
51
+ "surface": {
52
+ "standalone": true,
53
+ "embeddable": true,
54
+ "embedPath": "/capyclaw/capyclaw",
55
+ "title": "CapyClaw 子会话工作台"
56
+ }
57
+ },
58
+ {
59
+ "name": "capyclaw.session.list",
60
+ "capability": "session.list",
61
+ "suite": "capyclaw",
62
+ "controlMode": "interface",
63
+ "kind": "read",
64
+ "since": "0.1.0",
65
+ "description": "列出 DSH 会话(附本套件账本标题/来源)。",
66
+ "tool": "capyclaw_list_sessions",
67
+ "consumes": [],
68
+ "produces": [
69
+ "session:list"
70
+ ],
71
+ "auth": null,
72
+ "risk": "low",
73
+ "confirm": false,
74
+ "surface": {
75
+ "standalone": true,
76
+ "embeddable": true,
77
+ "embedPath": "/capyclaw/capyclaw",
78
+ "title": "CapyClaw 子会话工作台"
79
+ }
80
+ },
81
+ {
82
+ "name": "capyclaw.session.transcript",
83
+ "capability": "session.transcript",
84
+ "suite": "capyclaw",
85
+ "controlMode": "interface",
86
+ "kind": "read",
87
+ "since": "0.1.0",
88
+ "description": "读取子会话转录/事件。",
89
+ "tool": "capyclaw_session_transcript",
90
+ "consumes": [
91
+ "session:subsession"
92
+ ],
93
+ "produces": [
94
+ "session:transcript"
95
+ ],
96
+ "auth": null,
97
+ "risk": "low",
98
+ "confirm": false,
99
+ "surface": {
100
+ "standalone": true,
101
+ "embeddable": true,
102
+ "embedPath": "/capyclaw/capyclaw",
103
+ "title": "CapyClaw 子会话工作台"
104
+ }
105
+ },
106
+ {
107
+ "name": "capyclaw.session.close",
108
+ "capability": "session.close",
109
+ "suite": "capyclaw",
110
+ "controlMode": "interface",
111
+ "kind": "control",
112
+ "since": "0.1.0",
113
+ "description": "关闭子会话:取消当前轮并标记 closed。",
114
+ "tool": "capyclaw_close_session",
115
+ "consumes": [
116
+ "session:subsession"
117
+ ],
118
+ "produces": [],
119
+ "auth": null,
120
+ "risk": "low",
121
+ "confirm": false,
122
+ "surface": {
123
+ "standalone": true,
124
+ "embeddable": true,
125
+ "embedPath": "/capyclaw/capyclaw",
126
+ "title": "CapyClaw 子会话工作台"
127
+ }
128
+ },
129
+ {
130
+ "name": "capyclaw.settings.get",
131
+ "capability": "settings.get",
132
+ "suite": "capyclaw",
133
+ "controlMode": "interface",
134
+ "kind": "read",
135
+ "since": "0.1.0",
136
+ "description": "读取 DSH 设置快照。",
137
+ "tool": "capyclaw_settings_get",
138
+ "consumes": [],
139
+ "produces": [
140
+ "settings:snapshot"
141
+ ],
142
+ "auth": null,
143
+ "risk": "low",
144
+ "confirm": false,
145
+ "surface": {
146
+ "standalone": true,
147
+ "embeddable": true,
148
+ "embedPath": "/capyclaw/capyclaw",
149
+ "title": "CapyClaw 子会话工作台"
150
+ }
151
+ },
152
+ {
153
+ "name": "capyclaw.settings.set",
154
+ "capability": "settings.set",
155
+ "suite": "capyclaw",
156
+ "controlMode": "interface",
157
+ "kind": "write",
158
+ "since": "0.1.0",
159
+ "description": "更新 DSH 设置(稀疏合并);高风险,需确认。",
160
+ "tool": "capyclaw_settings_set",
161
+ "consumes": [
162
+ "settings:patch"
163
+ ],
164
+ "produces": [
165
+ "settings:snapshot"
166
+ ],
167
+ "auth": null,
168
+ "risk": "high",
169
+ "confirm": true,
170
+ "surface": {
171
+ "standalone": true,
172
+ "embeddable": true,
173
+ "embedPath": "/capyclaw/capyclaw",
174
+ "title": "CapyClaw 子会话工作台"
175
+ }
176
+ }
177
+ ]
178
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * capyclaw 能力描述符:契约真源在 contract/capabilities.json。
3
+ * 注册进 tool-host 描述符注册表(公共层),供 conductor 这类平级编排器按类型发现。
4
+ */
5
+ import { readFileSync } from 'node:fs'
6
+ import path from 'node:path'
7
+ import { fileURLToPath } from 'node:url'
8
+
9
+ const HERE = path.dirname(fileURLToPath(import.meta.url))
10
+ const contract = JSON.parse(readFileSync(path.join(HERE, '..', 'contract', 'capabilities.json'), 'utf8'))
11
+
12
+ export const CAPYCLAW_CONTRACT_VERSION = contract.contractVersion
13
+ export const CAPYCLAW_DESCRIPTORS = Object.freeze(contract.capabilities.map((d) => Object.freeze({ ...d })))
14
+
15
+ /**
16
+ * 把 capyclaw 描述符登记进 toolHost。baseUrl=本工作台调用入口(service-host app.url)。
17
+ * @param {object} toolHost ctx.toolHost
18
+ * @param {{ baseUrl?:string, validate?:Function }} options validate 通常注入 suite-kit validateCapabilityDescriptor
19
+ */
20
+ export function registerCapyclawDescriptors(toolHost, { baseUrl = '', validate } = {}) {
21
+ if (!toolHost?.registerCapabilityDescriptor) throw new Error('toolHost 缺少描述符面(需 @capyclaw/tool-host >= 0.2.0)')
22
+ const registered = []
23
+ for (const descriptor of CAPYCLAW_DESCRIPTORS) {
24
+ if (typeof validate === 'function') {
25
+ const verdict = validate(descriptor)
26
+ if (verdict && verdict.ok === false) {
27
+ throw new Error(`capyclaw 描述符不合法 ${descriptor.name}: ${(verdict.errors || []).join('; ')}`)
28
+ }
29
+ }
30
+ registered.push(toolHost.registerCapabilityDescriptor(descriptor, { baseUrl }))
31
+ }
32
+ return registered
33
+ }
package/lib/host.mjs ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * capyclaw-workbench cordis 宿主入口:把可单测核心接进 DSH。
3
+ * 模式沿用 browser embedded-host:inject=['webServer'],其余服务 safeGet 优雅降级。
4
+ */
5
+ import fs from 'node:fs'
6
+ import os from 'node:os'
7
+ import path from 'node:path'
8
+ import { assertServiceApi } from '@capyclaw/plugin-kit/service/api'
9
+ import { validateCapabilityDescriptor } from '@capyclaw/suite-kit/capability'
10
+
11
+ /* 诊断日志默认关闭;设 CAPYCLAW_WB_DIAG=1 时写到系统临时目录(不硬编码任何本机路径)。 */
12
+ const DIAG_LOG = process.env.CAPYCLAW_WB_DIAG ? path.join(os.tmpdir(), 'capyclaw-workbench-diag.log') : null
13
+ const diag = (m) => { if (!DIAG_LOG) return; try { fs.appendFileSync(DIAG_LOG, `[${new Date().toISOString()}] ${m}\n`) } catch { /* 忽略 */ } }
14
+ import { createSessionPort } from './session-port.mjs'
15
+ import { createCapyclawWorkbench } from './workbench.mjs'
16
+ import { CAPYCLAW_DESCRIPTORS } from './descriptors.mjs'
17
+
18
+ export const name = 'capyclaw-workbench'
19
+ export const inject = ['webServer']
20
+
21
+ function safeGet(ctx, serviceName) {
22
+ try { return ctx.reflect?.get?.(serviceName) ?? ctx[serviceName] } catch { return null }
23
+ }
24
+
25
+ export function apply(ctx, config = {}) {
26
+ const log = {
27
+ info: (...a) => (ctx.logger?.info ? ctx.logger.info(...a) : console.log('[capyclaw]', ...a)),
28
+ warn: (...a) => (ctx.logger?.warn ? ctx.logger.warn(...a) : console.warn('[capyclaw]', ...a)),
29
+ }
30
+ const mountPath = config.mountPath || '/capyclaw/capyclaw'
31
+ const disposers = []
32
+
33
+ try {
34
+ const toolHost = safeGet(ctx, 'toolHost')
35
+ const serviceHost = safeGet(ctx, 'serviceHost')
36
+ diag(`capyclaw apply: toolHost=${!!toolHost} serviceHost=${!!serviceHost} webServer=${!!safeGet(ctx, 'webServer')} reflect=${!!ctx.reflect}`)
37
+ if (!toolHost || !serviceHost) {
38
+ diag('capyclaw BAIL: missing toolHost/serviceHost')
39
+ log.warn('缺少 toolHost/serviceHost 公共服务,capyclaw-suite 未激活(请安装对应基础套件)')
40
+ return () => {}
41
+ }
42
+ assertServiceApi(toolHost, { name: 'toolHost', major: 1 })
43
+ assertServiceApi(serviceHost, { name: 'serviceHost', major: 1 })
44
+
45
+ const sessionPort = createSessionPort({
46
+ sessionController: safeGet(ctx, 'sessionController'),
47
+ sessionQuery: safeGet(ctx, 'sessionQuery'),
48
+ sessions: safeGet(ctx, 'sessions'),
49
+ settings: safeGet(ctx, 'settings'),
50
+ })
51
+ if (!sessionPort.available) log.warn('宿主没有 sessionController:会话工具将返回 unavailable(设置/呈现仍可用)')
52
+
53
+ const workbench = createCapyclawWorkbench({
54
+ toolHost, serviceHost, sessionPort,
55
+ config: { mountPath, guiUrl: config.guiUrl || '/', version: config.version || '0.1.0' },
56
+ })
57
+
58
+ const webServer = safeGet(ctx, 'webServer')
59
+ const listenOpts = webServer ? { webServer, basePath: mountPath } : { port: config.port || 0 }
60
+ const listening = workbench.app.listen(listenOpts)
61
+ disposers.push(() => workbench.app.close())
62
+
63
+ // 原生工具面:safeGet 解析 tools 服务后传平对象,避免 cordis 未 inject 禁访问 ctx.tools。
64
+ const tools = safeGet(ctx, 'tools')
65
+ if (tools?.register) {
66
+ const { registerWithDsh } = toolHost
67
+ disposers.push(registerWithDsh({ tools }, workbench.registry))
68
+ }
69
+
70
+ // 能力描述符 + 调用地址 → 公共注册表(供 conductor 发现)。
71
+ if (typeof toolHost.registerCapabilityDescriptor === 'function') {
72
+ workbench.publishDescriptors(workbench.app.url, { validate: validateCapabilityDescriptor })
73
+ disposers.push(() => { for (const d of CAPYCLAW_DESCRIPTORS) toolHost.unregisterCapabilityDescriptor?.(d.name) })
74
+ } else {
75
+ log.warn('toolHost 无描述符面(需 >=0.2.0):跳过能力注册,conductor 将无法发现 capyclaw')
76
+ }
77
+
78
+ // 自检端点。
79
+ if (webServer?.register) {
80
+ const path = `${mountPath}/__host__`
81
+ const off = webServer.register({
82
+ kind: 'exact', path,
83
+ handler: (req, res) => {
84
+ res.writeHead(200, { 'content-type': 'application/json' })
85
+ res.end(JSON.stringify({ ok: true, name, mountPath, url: workbench.app.url, available: sessionPort.services }))
86
+ },
87
+ })
88
+ if (typeof off === 'function') disposers.push(off)
89
+ }
90
+
91
+ const portal = safeGet(ctx, 'portal')
92
+ portal?.recordActivity?.({ id: 'capyclaw-workbench', url: workbench.app.url, title: 'CapyClaw 子会话工作台', kind: 'service' })
93
+
94
+ log.info(`capyclaw-workbench 已挂载 ${mountPath} → ${workbench.app.url}`)
95
+ diag(`capyclaw MOUNTED ${mountPath} → ${workbench.app.url}`)
96
+ return () => { for (const d of disposers.reverse()) { try { d() } catch { /* 忽略重复释放 */ } } }
97
+ } catch (err) {
98
+ diag(`capyclaw ERROR: ${err?.stack || err}`)
99
+ log.warn('capyclaw-workbench 激活失败:', err?.stack || err)
100
+ return () => { for (const d of disposers.reverse()) { try { d() } catch { /* noop */ } } }
101
+ }
102
+ }
@@ -0,0 +1,104 @@
1
+ /**
2
+ * 会话端口:把 DSH 的会话/设置服务收敛成 capyclaw-suite 的稳定能力面。
3
+ *
4
+ * 依据 dsh-session-recon(0.2.2-rc.3):
5
+ * ctx.sessionController.create({cwd|workspaceId, agentPreset}) → {sessionId}
6
+ * ctx.sessionController.prompt({requestId, sessionId, mode, content:[{type:'text',text}]}, signal) → {accepted}
7
+ * ctx.sessionQuery.listSessions() / readSession(id)
8
+ * ctx.settings.describe() / update(ns, patch, expectedRevision)
9
+ *
10
+ * 设计口径:
11
+ * - 纯函数端口,服务全部注入(可在测试里用 fake 替换),不 import 任何 DSH 包。
12
+ * - 优雅降级:宿主没有对应服务时返回明确的 unavailable 错误,而不是静默假成功。
13
+ * - GUI 无会话深链(recon 结论):这里只负责「创建/驱动/查询」会话这一控制面;
14
+ * 「呈现哪个会话」是 UI 层的事,新建会话会经事件自动出现在 GUI 列表。
15
+ */
16
+ import { randomUUID } from 'node:crypto'
17
+
18
+ function unavailable(service) {
19
+ const err = new Error(`当前宿主没有 ${service} 服务,无法执行该会话操作`)
20
+ err.code = 'SESSION_SERVICE_UNAVAILABLE'
21
+ return err
22
+ }
23
+
24
+ /**
25
+ * @param {{ sessionController?:object, sessionQuery?:object, sessions?:object, settings?:object }} services
26
+ */
27
+ export function createSessionPort({ sessionController, sessionQuery, sessions, settings } = {}) {
28
+ const hasController = !!sessionController && typeof sessionController.create === 'function'
29
+ const hasQuery = !!sessionQuery && typeof sessionQuery.listSessions === 'function'
30
+ const hasSettings = !!settings && typeof settings.describe === 'function'
31
+
32
+ return {
33
+ available: hasController,
34
+ services: { sessionController: hasController, sessionQuery: hasQuery, settings: hasSettings },
35
+
36
+ /** 创建一个子会话(完成 workspace/preset/agent 接线)。 */
37
+ async createSession({ cwd, workspaceId, agentPreset } = {}) {
38
+ if (!hasController) throw unavailable('sessionController')
39
+ if (cwd && workspaceId) {
40
+ const err = new Error('cwd 与 workspaceId 互斥,只能给一个')
41
+ err.code = 'ARG_INVALID'
42
+ throw err
43
+ }
44
+ const request = {}
45
+ if (cwd) request.cwd = cwd
46
+ if (workspaceId) request.workspaceId = workspaceId
47
+ if (agentPreset) request.agentPreset = agentPreset
48
+ const value = await sessionController.create(request)
49
+ return { sessionId: value.sessionId, agentPreset: value.agentPreset ?? agentPreset ?? null }
50
+ },
51
+
52
+ /** 向会话发一条用户消息,启动一轮(mode: queue|steer)。 */
53
+ async prompt({ sessionId, text, mode = 'queue' } = {}) {
54
+ if (!hasController) throw unavailable('sessionController')
55
+ if (!sessionId) { const e = new Error('prompt 需要 sessionId'); e.code = 'ARG_INVALID'; throw e }
56
+ const content = Array.isArray(text)
57
+ ? text
58
+ : [{ type: 'text', text: String(text ?? '') }]
59
+ const value = await sessionController.prompt({
60
+ requestId: randomUUID(),
61
+ sessionId,
62
+ mode,
63
+ content,
64
+ })
65
+ return { accepted: value?.accepted !== false, sessionId }
66
+ },
67
+
68
+ /** 列出会话(最新在前)。优先 sessionQuery,退回活会话 sessions.list。 */
69
+ async listSessions() {
70
+ if (hasQuery) return await sessionQuery.listSessions()
71
+ if (sessions && typeof sessions.list === 'function') return await sessions.list()
72
+ throw unavailable('sessionQuery')
73
+ },
74
+
75
+ /** 读一个会话的转录/事件。 */
76
+ async readSession(sessionId) {
77
+ if (!sessionId) { const e = new Error('readSession 需要 sessionId'); e.code = 'ARG_INVALID'; throw e }
78
+ if (sessionQuery && typeof sessionQuery.readSession === 'function') return await sessionQuery.readSession(sessionId)
79
+ throw unavailable('sessionQuery.readSession')
80
+ },
81
+
82
+ /** 取消会话当前轮(best-effort;DSH 无显式 close,cancel 存在才调)。 */
83
+ async cancel(sessionId) {
84
+ if (!hasController) throw unavailable('sessionController')
85
+ if (typeof sessionController.cancel === 'function') {
86
+ try { await sessionController.cancel({ sessionId }) } catch { /* 空闲会话 cancel 可能报错,忽略 */ }
87
+ }
88
+ return { sessionId, cancelled: true }
89
+ },
90
+
91
+ /** 读设置快照。 */
92
+ async describeSettings(options) {
93
+ if (!hasSettings) throw unavailable('settings')
94
+ return await settings.describe(options)
95
+ },
96
+
97
+ /** 稀疏合并更新设置(ns=profile 条目 id;revision 不符抛 SETTINGS_CONFLICT)。 */
98
+ async updateSettings({ ns, patch, expectedRevision } = {}) {
99
+ if (!hasSettings) throw unavailable('settings')
100
+ if (!ns || typeof ns !== 'string') { const e = new Error('updateSettings 需要 ns'); e.code = 'ARG_INVALID'; throw e }
101
+ return await settings.update(ns, patch ?? {}, expectedRevision)
102
+ },
103
+ }
104
+ }
package/lib/tools.mjs ADDED
@@ -0,0 +1,166 @@
1
+ /**
2
+ * capyclaw_* 工具面:子会话生命周期 + DSH 设置。
3
+ * 全部经 tool-host DSL 声明;handler 闭包 sessionPort/ledger,不依赖 DSH exec。
4
+ */
5
+
6
+ /**
7
+ * @param {{ toolHost:object, sessionPort:object, ledger:object, mountPath:string, guiUrl:string }} deps
8
+ */
9
+ export function createCapyclawCapabilities({ toolHost, sessionPort, ledger, mountPath = '/capyclaw/capyclaw', guiUrl = '/' }) {
10
+ const { defineTool, defineCapability } = toolHost
11
+
12
+ const openSession = defineTool({
13
+ name: 'capyclaw_open_session',
14
+ description: '创建一个 DSH 子会话(同一宿主进程,非独立 dsh)。可选立即发一条启动消息。新会话会自动出现在 GUI 会话列表;返回 sessionId 供后续 send_message/transcript 使用。',
15
+ kind: 'control',
16
+ since: '0.1.0',
17
+ inputSchema: {
18
+ type: 'object',
19
+ properties: {
20
+ title: { type: 'string', description: '给子会话起的标题(仅本套件账本记录)' },
21
+ cwd: { type: 'string', description: '子会话工作目录(与 workspaceId 互斥)' },
22
+ workspaceId: { type: 'string', description: '工作区 id(与 cwd 互斥)' },
23
+ agentPreset: { type: 'string', description: 'agent 预设' },
24
+ prompt: { type: 'string', description: '创建后立即发送的启动消息(可选)' },
25
+ },
26
+ additionalProperties: false,
27
+ },
28
+ handler: async (args) => {
29
+ const { sessionId, agentPreset } = await sessionPort.createSession({
30
+ cwd: args.cwd, workspaceId: args.workspaceId, agentPreset: args.agentPreset,
31
+ })
32
+ const title = args.title || `子会话 ${sessionId.slice(0, 8)}`
33
+ ledger.record(sessionId, { title, cwd: args.cwd || null, agentPreset, parent: 'capyclaw' })
34
+ let accepted = null
35
+ if (args.prompt) {
36
+ const r = await sessionPort.prompt({ sessionId, text: args.prompt })
37
+ accepted = r.accepted
38
+ }
39
+ return {
40
+ ok: true, sessionId, title, agentPreset, accepted,
41
+ consoleUrl: mountPath, guiUrl,
42
+ note: 'GUI 无会话深链:新会话已进 GUI 列表;用 capyclaw_send_message 驱动,或在套娃控制台查看转录。',
43
+ }
44
+ },
45
+ })
46
+
47
+ const sendMessage = defineTool({
48
+ name: 'capyclaw_send_message',
49
+ description: '向指定子会话发送一条用户消息,启动一轮 agent 工作。',
50
+ kind: 'write',
51
+ since: '0.1.0',
52
+ inputSchema: {
53
+ type: 'object',
54
+ properties: {
55
+ sessionId: { type: 'string', description: '目标子会话 id' },
56
+ text: { type: 'string', description: '消息文本' },
57
+ mode: { type: 'string', enum: ['queue', 'steer'], description: 'queue=排队新轮;steer=转向当前轮' },
58
+ },
59
+ required: ['sessionId', 'text'],
60
+ additionalProperties: false,
61
+ },
62
+ handler: async (args) => {
63
+ const r = await sessionPort.prompt({ sessionId: args.sessionId, text: args.text, mode: args.mode || 'queue' })
64
+ return { ok: true, ...r }
65
+ },
66
+ })
67
+
68
+ const listSessions = defineTool({
69
+ name: 'capyclaw_list_sessions',
70
+ description: '列出 DSH 会话(最新在前),并附上本套件账本里的标题/来源标记。',
71
+ kind: 'read',
72
+ since: '0.1.0',
73
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
74
+ handler: async () => {
75
+ const records = await sessionPort.listSessions()
76
+ const items = (Array.isArray(records) ? records : []).map((rec) => {
77
+ const id = rec.sessionId || rec.id
78
+ const meta = ledger.get(id) || {}
79
+ return { sessionId: id, title: meta.title || rec.title || null, cwd: meta.cwd ?? rec.cwd ?? null, fromCapyclaw: !!meta, closed: !!meta.closed, raw: rec }
80
+ })
81
+ return { ok: true, count: items.length, items }
82
+ },
83
+ })
84
+
85
+ const transcript = defineTool({
86
+ name: 'capyclaw_session_transcript',
87
+ description: '读取指定子会话的转录/事件(供编排器或用户查看进展)。',
88
+ kind: 'read',
89
+ since: '0.1.0',
90
+ inputSchema: {
91
+ type: 'object',
92
+ properties: { sessionId: { type: 'string', description: '目标子会话 id' } },
93
+ required: ['sessionId'],
94
+ additionalProperties: false,
95
+ },
96
+ handler: async (args) => {
97
+ const data = await sessionPort.readSession(args.sessionId)
98
+ return { ok: true, sessionId: args.sessionId, transcript: data }
99
+ },
100
+ })
101
+
102
+ const closeSession = defineTool({
103
+ name: 'capyclaw_close_session',
104
+ description: '关闭子会话:取消当前轮(best-effort)并在账本标记 closed。DSH 无显式销毁,会话记录仍保留。',
105
+ kind: 'control',
106
+ since: '0.1.0',
107
+ inputSchema: {
108
+ type: 'object',
109
+ properties: { sessionId: { type: 'string', description: '目标子会话 id' } },
110
+ required: ['sessionId'],
111
+ additionalProperties: false,
112
+ },
113
+ handler: async (args) => {
114
+ const r = await sessionPort.cancel(args.sessionId)
115
+ ledger.markClosed(args.sessionId)
116
+ return { ok: true, ...r, closed: true }
117
+ },
118
+ })
119
+
120
+ const settingsGet = defineTool({
121
+ name: 'capyclaw_settings_get',
122
+ description: '读取 DSH 设置快照(describe)。帮用户查看当前配置。',
123
+ kind: 'read',
124
+ since: '0.1.0',
125
+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },
126
+ handler: async () => ({ ok: true, settings: await sessionPort.describeSettings() }),
127
+ })
128
+
129
+ const settingsSet = defineTool({
130
+ name: 'capyclaw_settings_set',
131
+ description: '更新 DSH 设置(稀疏合并)。ns=profile 条目 id;高风险操作,需确认。revision 不符会抛 SETTINGS_CONFLICT。',
132
+ kind: 'write',
133
+ since: '0.1.0',
134
+ inputSchema: {
135
+ type: 'object',
136
+ properties: {
137
+ ns: { type: 'string', description: '设置命名空间(profile 条目 id)' },
138
+ patch: { type: 'object', description: '要合并的设置补丁', additionalProperties: true },
139
+ expectedRevision: { type: 'string', description: '乐观锁 revision(可选)' },
140
+ },
141
+ required: ['ns', 'patch'],
142
+ additionalProperties: false,
143
+ },
144
+ handler: async (args) => {
145
+ const value = await sessionPort.updateSettings({ ns: args.ns, patch: args.patch, expectedRevision: args.expectedRevision })
146
+ return { ok: true, ns: args.ns, value }
147
+ },
148
+ })
149
+
150
+ return [
151
+ defineCapability({
152
+ id: 'capyclaw.sessions',
153
+ title: '子会话生命周期',
154
+ description: '在同一宿主进程内创建/驱动/查询/关闭 DSH 子会话(俄罗斯套娃的控制面)。',
155
+ tags: ['session', 'subagent'],
156
+ tools: [openSession, sendMessage, listSessions, transcript, closeSession],
157
+ }),
158
+ defineCapability({
159
+ id: 'capyclaw.settings',
160
+ title: 'DSH 设置',
161
+ description: '读取/更新 DSH 设置,帮用户完成配置。',
162
+ tags: ['settings'],
163
+ tools: [settingsGet, settingsSet],
164
+ }),
165
+ ]
166
+ }