@capyclaw/capyclaw-workbench 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 (119) hide show
  1. package/README.md +56 -2
  2. package/contract/capabilities.json +178 -0
  3. package/lib/descriptors.mjs +33 -0
  4. package/lib/host.mjs +106 -0
  5. package/lib/session-port.mjs +178 -0
  6. package/lib/session-watch.mjs +82 -0
  7. package/lib/tools.mjs +166 -0
  8. package/lib/workbench.mjs +133 -0
  9. package/lib/workspace-attach.mjs +147 -0
  10. package/node_modules/@capyclaw/foundation/README.md +51 -0
  11. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  12. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  13. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  14. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  15. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  16. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  17. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  18. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  19. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  20. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  21. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  22. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  23. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  34. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  35. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  36. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  37. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  38. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  39. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  40. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  41. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  42. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  43. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  44. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  45. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  46. package/node_modules/@capyclaw/foundation/package.json +53 -0
  47. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  48. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  49. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  50. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  51. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  79. package/node_modules/@capyclaw/service-host/README.md +86 -0
  80. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  81. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  82. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  83. package/node_modules/@capyclaw/service-host/package.json +60 -0
  84. package/node_modules/@capyclaw/service-host/src/index.mjs +570 -0
  85. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  86. package/node_modules/@capyclaw/suite-kit/README.md +289 -0
  87. package/node_modules/@capyclaw/suite-kit/bin/dsh-domain.mjs +98 -0
  88. package/node_modules/@capyclaw/suite-kit/bin/dsh-suite.mjs +174 -0
  89. package/node_modules/@capyclaw/suite-kit/client/embed.js +35 -0
  90. package/node_modules/@capyclaw/suite-kit/domain.schema.json +129 -0
  91. package/node_modules/@capyclaw/suite-kit/package.json +58 -0
  92. package/node_modules/@capyclaw/suite-kit/src/activation-registry.mjs +184 -0
  93. package/node_modules/@capyclaw/suite-kit/src/artifacts.mjs +131 -0
  94. package/node_modules/@capyclaw/suite-kit/src/capability.mjs +181 -0
  95. package/node_modules/@capyclaw/suite-kit/src/compose.mjs +201 -0
  96. package/node_modules/@capyclaw/suite-kit/src/domain.mjs +138 -0
  97. package/node_modules/@capyclaw/suite-kit/src/embed.mjs +81 -0
  98. package/node_modules/@capyclaw/suite-kit/src/host.mjs +230 -0
  99. package/node_modules/@capyclaw/suite-kit/src/index.mjs +24 -0
  100. package/node_modules/@capyclaw/suite-kit/src/manifest.mjs +263 -0
  101. package/node_modules/@capyclaw/suite-kit/src/orchestration.mjs +100 -0
  102. package/node_modules/@capyclaw/suite-kit/src/profile.mjs +584 -0
  103. package/node_modules/@capyclaw/suite-kit/src/surface.mjs +28 -0
  104. package/node_modules/@capyclaw/suite-kit/suite.schema.json +128 -0
  105. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  106. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  107. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  108. package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
  109. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  110. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  111. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  112. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  113. package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
  114. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  115. package/package.json +68 -4
  116. package/plugin.mjs +17 -0
  117. package/ui/app.js +114 -0
  118. package/ui/index.html +64 -0
  119. package/ui/style.css +54 -0
package/README.md CHANGED
@@ -1,3 +1,57 @@
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` 能力注册。公共胶水收敛在 `@capyclaw/suite-kit/host` 的 `mountSuiteWorkbench`;`lib/host.mjs` 只保留 capyclaw 差异(sessionPort/session-watch 装配 + 两个 drain 端点)。
24
+
25
+ ## 顶栏标签通道(宿主 → 客户端 keeper)
26
+
27
+ 顶栏标签由 `@capyclaw/session-keeper` 按来源白名单纳入。本工作台提供两条固定 drain 端点(路径独立于 mountPath,GET 返回 `{ ids }`,取走即清空,`no-store`):
28
+
29
+ | 端点 | 来源 | 喂入方 |
30
+ | --- | --- | --- |
31
+ | `/capyclaw/session-tabs/agent-pending` | `agent` | `session-port.createSession`(AI 派发创建的会话) |
32
+ | `/capyclaw/session-tabs/host-pending` | `host` | `lib/session-watch.mjs` 周期差分宿主会话列表 |
33
+
34
+ `session-watch`(规则④)每 5s 差分 `sessionQuery.listSessions()`,把**运行中(live)的非子代理会话**入队——覆盖远程 LiveShare fork、定时任务等不走 `createSession` 的路径,含启动前就在跑的会话;冷会话不纳入,变 live 时再纳入;子代理(`header.origin==='subagent'`)不占标签。没有 `sessionQuery` 时不启动。keeper 取走后以 `host` 来源纳入顶栏(enroll 会 retain,连带把会话 materialize 进客户端目录,会话记录可见性一并解决)。
35
+
36
+ ## 工作区登记(规则⑤)
37
+
38
+ DSH 的 `session.create` 只有传 `workspaceId` 才登记工作区成员;**只传 `cwd` 创建不登记**,会话落「未分组」桶,不出现在对应目录的工作区清单里。远程客户端(工作台 GUI)新建恰恰只传 `cwd`,故本工作台经 `lib/workspace-attach.mjs` 补登记:
39
+
40
+ - **创建时**:`session-port.createSession` 成功后按 `cwd` 把会话登记进路径匹配的**已存在**工作区(best-effort,失败不阻断创建;传 `workspaceId` 时 DSH 已登记,不重复处理)。
41
+ - **周期补登记**:`createWorkspaceReconcile` 每 5s 把「运行中、非子代理、未被任何工作区认领」的会话按 `cwd` 补登记进匹配的已存在工作区(修复重启前已存在的远程会话,如 46d7)。带 `handled` 集合:已登记/已认领的会话不再重纳(尊重用户手动移出);冷转 live、稍后新建工作区的会话会在后续拍被捕捉。
42
+
43
+ 口径:**只登记进已存在的工作区,绝不擅自新建**;已被任何工作区认领的会话不搬动;子代理不参与。路径匹配用字符串规范化(分隔符/尾斜杠/Windows 不区分大小写),`attachSession` 自身再按 realpath 校验兜底。
44
+
45
+ **服务懒解析**:工作台装配可能早于 `sessionController`/`workspaceRegistry` 注册,故端口与补登记运行器都接受零参解析函数、用的时候现取(不被一次性快照定格成缺席);服务晚注册也能用上,未就绪时静默重试。
46
+
47
+ ## 测试
48
+
49
+ ```bash
50
+ npm test
51
+ ```
52
+
53
+ - `test/workbench.test.mjs`:核心工具面 / HTTP / MCP / 描述符 / 呈现面。
54
+ - `test/session-port.test.mjs`:会话端口 + 两条标签队列(入队/去重/上限/drain)+ 创建时工作区登记。
55
+ - `test/session-watch.test.mjs`:宿主探测(live 纳入 / 冷转 live / 子代理跳过 / 容错 / 防重入)。
56
+ - `test/workspace-attach.test.mjs`:工作区登记(路径匹配 / 幂等 / 只登记已存在 / 补登记跳过规则 / 周期运行器 + handled / 懒解析)。
57
+ - `test/host.test.mjs`:宿主装配(两个 drain 端点 / watch 接线 / 工作区补登记接线 / __host__ / 释放)。
@@ -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,106 @@
1
+ /**
2
+ * capyclaw-workbench cordis 宿主入口:把可单测核心接进 DSH。
3
+ * 公共胶水(safeGet/断言/缺服务降级/probe 兜底/__host__/portal/工具注册/描述符/逆序释放)
4
+ * 收敛到 @capyclaw/suite-kit/host 的 mountSuiteWorkbench(P1-9);本文件只保留 capyclaw 差异:
5
+ * sessionPort/session-watch 装配、两个固定 session-tabs drain 端点、__host__.available 字段。
6
+ */
7
+ import { mountSuiteWorkbench } from '@capyclaw/suite-kit/host'
8
+ import { createSessionPort } from './session-port.mjs'
9
+ import { createSessionWatch } from './session-watch.mjs'
10
+ import { createWorkspaceReconcile } from './workspace-attach.mjs'
11
+ import { createCapyclawWorkbench } from './workbench.mjs'
12
+ import { CAPYCLAW_DESCRIPTORS } from './descriptors.mjs'
13
+
14
+ export const name = 'capyclaw-workbench'
15
+ export const inject = ['webServer']
16
+
17
+ export function apply(ctx, config = {}) {
18
+ return mountSuiteWorkbench(ctx, config, {
19
+ ns: name,
20
+ suite: 'capyclaw',
21
+ mountPath: '/capyclaw/capyclaw',
22
+ title: 'CapyClaw 子会话工作台',
23
+ descriptors: CAPYCLAW_DESCRIPTORS,
24
+
25
+ prepare: ({ ctx, safeGet, log, push }) => {
26
+ // 服务懒解析:工作台装配可能早于 sessionController/workspaceRegistry 注册,
27
+ // 一次性 safeGet 会把缺席定格成永久 false(2026-11-23 重启后补登记/创建静默失效
28
+ // 的教训)。这里传零参解析函数,端口在每次调用时现取,服务晚注册也能用上。
29
+ const sessionPort = createSessionPort({
30
+ sessionController: () => safeGet(ctx, 'sessionController'),
31
+ sessionQuery: () => safeGet(ctx, 'sessionQuery'),
32
+ sessions: () => safeGet(ctx, 'sessions'),
33
+ settings: () => safeGet(ctx, 'settings'),
34
+ workspaceRegistry: () => safeGet(ctx, 'workspaceRegistry'),
35
+ })
36
+
37
+ // 规则④(宿主新会话探测):周期差分宿主会话列表,把运行中(live)的非子代理会话
38
+ // (远程 LiveShare fork、定时任务等不走 createSession 的路径,含启动前就在跑的)
39
+ // 入队,供下方 host-pending 端点取走。sessionQuery 晚注册也无妨——listSessions
40
+ // 懒解析,未就绪时抛错被 watch 捕获、下一拍重试。
41
+ const sessionWatch = createSessionWatch({
42
+ listSessions: () => sessionPort.listSessions(),
43
+ enqueue: (ids) => sessionPort.noteHostTabs(ids),
44
+ })
45
+ sessionWatch.start()
46
+ push(() => sessionWatch.stop())
47
+
48
+ // 工作区登记(周期补登记):远程「只传 cwd」创建的会话 DSH 不登记工作区成员,
49
+ // 落「未分组」、不出现在对应工作区清单。这里把运行中、非子代理、未被任何工作区
50
+ // 认领的会话按 cwd 补登记进匹配的已存在工作区(不新建工作区)。带 handled 集合:
51
+ // 已登记/已认领的不重纳(尊重用户手动移出);冷转 live 的会话变 live 后被捕捉。
52
+ // workspaceRegistry 懒解析,晚注册也不丢。
53
+ const workspaceReconcile = createWorkspaceReconcile({
54
+ listSessions: () => sessionPort.listSessions(),
55
+ workspaceRegistry: () => safeGet(ctx, 'workspaceRegistry'),
56
+ })
57
+ workspaceReconcile.start()
58
+ push(() => workspaceReconcile.stop())
59
+ return { sessionPort }
60
+ },
61
+
62
+ createWorkbench: ({ toolHost, serviceHost, extra, config, mountPath }) => createCapyclawWorkbench({
63
+ toolHost, serviceHost, sessionPort: extra.sessionPort,
64
+ config: { mountPath, guiUrl: config.guiUrl || '/', version: config.version || '0.1.0' },
65
+ }),
66
+
67
+ hostInfo: (workbench, { sessionPort }) => ({ available: sessionPort.services }),
68
+
69
+ routes: ({ webServer, extra, push }) => {
70
+ const { sessionPort } = extra
71
+ // 规则③(AI 派发标签)宿主→客户端固定端点:路径独立于 mountPath,客户端 keeper
72
+ // 以固定路径周期轮询,取走 AI 派发创建的会话 id 并以 'agent' 来源纳入顶栏标签。
73
+ // GET 返回 { ids }(取走即清空)。这是 AI 加标签的唯一合法通道(心跳不自动纳入)。
74
+ const offAgent = webServer.register({
75
+ kind: 'exact', path: '/capyclaw/session-tabs/agent-pending',
76
+ handler: (req, res) => {
77
+ if (req.method !== 'GET') {
78
+ res.writeHead(405, { 'content-type': 'application/json' })
79
+ res.end(JSON.stringify({ error: 'GET only' }))
80
+ return
81
+ }
82
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
83
+ res.end(JSON.stringify(sessionPort.drainAgentTabs()))
84
+ },
85
+ })
86
+ if (typeof offAgent === 'function') push(offAgent)
87
+
88
+ // 规则④(宿主新会话探测)宿主→客户端固定端点:与 agent-pending 同构。客户端 keeper
89
+ // 以固定路径周期轮询,取走宿主探测到的新会话 id(远程 fork/定时任务等)并以 'host'
90
+ // 来源纳入顶栏标签。GET 返回 { ids }(取走即清空)。
91
+ const offHost = webServer.register({
92
+ kind: 'exact', path: '/capyclaw/session-tabs/host-pending',
93
+ handler: (req, res) => {
94
+ if (req.method !== 'GET') {
95
+ res.writeHead(405, { 'content-type': 'application/json' })
96
+ res.end(JSON.stringify({ error: 'GET only' }))
97
+ return
98
+ }
99
+ res.writeHead(200, { 'content-type': 'application/json', 'cache-control': 'no-store' })
100
+ res.end(JSON.stringify(sessionPort.drainHostTabs()))
101
+ },
102
+ })
103
+ if (typeof offHost === 'function') push(offHost)
104
+ },
105
+ })
106
+ }
@@ -0,0 +1,178 @@
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 层的事。经 createSession 新建的会话走 agent-pending 通道;
15
+ * 不经此端口的新建会话(远程 LiveShare fork、定时任务等)由 session-watch 差分
16
+ * 发现后走 host-pending 通道(规则④),两条通道都供客户端 keeper 纳入顶栏。
17
+ * - 工作区登记:DSH 只给传 workspaceId 的创建登记工作区成员,只传 cwd 不登记
18
+ * (会话落「未分组」)。createSession 成功后按 cwd 补登记进匹配的已存在工作区
19
+ * (workspace-attach,best-effort,不新建工作区)。
20
+ */
21
+ import { randomUUID } from 'node:crypto'
22
+ import { attachSessionByCwd } from './workspace-attach.mjs'
23
+
24
+ function unavailable(service) {
25
+ const err = new Error(`当前宿主没有 ${service} 服务,无法执行该会话操作`)
26
+ err.code = 'SESSION_SERVICE_UNAVAILABLE'
27
+ return err
28
+ }
29
+
30
+ /**
31
+ * @param {{ sessionController?:object|Function, sessionQuery?:object|Function, sessions?:object|Function, settings?:object|Function, workspaceRegistry?:object|Function }} services
32
+ * 每个服务既可传对象(测试 fake),也可传零参解析函数(宿主懒解析:用的时候现取,
33
+ * 避免装配早于服务注册被一次性快照定格成缺席——2026-11-23 重启后 workspaceRegistry/
34
+ * sessionController 晚注册导致补登记/创建静默失效的教训)。
35
+ */
36
+ export function createSessionPort(services = {}) {
37
+ const resolve = (name) => {
38
+ const v = services[name]
39
+ return typeof v === 'function' ? v() : v
40
+ }
41
+ const controller = () => { const c = resolve('sessionController'); return c && typeof c.create === 'function' ? c : null }
42
+ const query = () => { const q = resolve('sessionQuery'); return q && typeof q.listSessions === 'function' ? q : null }
43
+ const settingsSvc = () => { const s = resolve('settings'); return s && typeof s.describe === 'function' ? s : null }
44
+ const registry = () => { const w = resolve('workspaceRegistry'); return w && typeof w.list === 'function' ? w : null }
45
+
46
+ /* 规则③(AI 派发标签)宿主侧待取队列:createSession 成功后记入 sessionId,
47
+ 由 host.mjs 固定端点 /capyclaw/session-tabs/agent-pending 供客户端 keeper 周期取走,
48
+ 以 'agent' 来源纳入顶栏。这是 AI 加标签的唯一合法通道(心跳不再自动纳入)。
49
+ 上限防「无客户端消费」时无界增长;去重防同一会话重复入队。 */
50
+ const AGENT_TAB_QUEUE_CAP = 200
51
+ const pendingAgentTabs = []
52
+
53
+ /* 规则④(宿主新会话探测)宿主侧待取队列:session-watch 差分宿主会话列表,把
54
+ 「运行中(live)的非子代理会话」(远程 LiveShare fork、定时任务等不走 createSession
55
+ 的路径,含启动前就在跑的)记入这里,由 host.mjs 固定端点
56
+ /capyclaw/session-tabs/host-pending 供客户端 keeper 周期取走、以 'host' 来源纳入顶栏。
57
+ 上限/去重口径与 AI 队列一致。 */
58
+ const HOST_TAB_QUEUE_CAP = 200
59
+ const pendingHostTabs = []
60
+
61
+ return {
62
+ get available() { return !!controller() },
63
+ get services() {
64
+ return { sessionController: !!controller(), sessionQuery: !!query(), settings: !!settingsSvc(), workspaceRegistry: !!registry() }
65
+ },
66
+
67
+ /** 创建一个子会话(完成 workspace/preset/agent 接线)。 */
68
+ async createSession({ cwd, workspaceId, agentPreset } = {}) {
69
+ const sessionController = controller()
70
+ if (!sessionController) throw unavailable('sessionController')
71
+ if (cwd && workspaceId) {
72
+ const err = new Error('cwd 与 workspaceId 互斥,只能给一个')
73
+ err.code = 'ARG_INVALID'
74
+ throw err
75
+ }
76
+ const request = {}
77
+ if (cwd) request.cwd = cwd
78
+ if (workspaceId) request.workspaceId = workspaceId
79
+ if (agentPreset) request.agentPreset = agentPreset
80
+ const value = await sessionController.create(request)
81
+ const sessionId = value.sessionId
82
+ if (sessionId && pendingAgentTabs.indexOf(sessionId) < 0) {
83
+ pendingAgentTabs.push(sessionId)
84
+ if (pendingAgentTabs.length > AGENT_TAB_QUEUE_CAP) {
85
+ pendingAgentTabs.splice(0, pendingAgentTabs.length - AGENT_TAB_QUEUE_CAP)
86
+ }
87
+ }
88
+ // 工作区登记:只传 cwd 的创建 DSH 不登记成员 ⇒ 会话落「未分组」。这里按 cwd
89
+ // 补登记进匹配的已存在工作区(best-effort:失败不影响创建结果;传 workspaceId
90
+ // 时 DSH 已登记,不重复处理;无 cwd 时无法匹配,交给周期补登记)。
91
+ const workspaceRegistry = registry()
92
+ if (sessionId && cwd && !workspaceId && workspaceRegistry) {
93
+ await attachSessionByCwd(workspaceRegistry, sessionId, cwd)
94
+ }
95
+ return { sessionId, agentPreset: value.agentPreset ?? agentPreset ?? null }
96
+ },
97
+
98
+ /** 取走并清空 AI 派发标签请求(规则③宿主→客户端通道的 drain 端)。返回 { ids }。 */
99
+ drainAgentTabs() {
100
+ return { ids: pendingAgentTabs.splice(0, pendingAgentTabs.length) }
101
+ },
102
+
103
+ /** 记入宿主探测到的新会话 id(session-watch 调用)。去重 + 上限防无界增长。 */
104
+ noteHostTabs(ids) {
105
+ if (!Array.isArray(ids)) return
106
+ for (const id of ids) {
107
+ if (typeof id === 'string' && id && pendingHostTabs.indexOf(id) < 0) pendingHostTabs.push(id)
108
+ }
109
+ if (pendingHostTabs.length > HOST_TAB_QUEUE_CAP) {
110
+ pendingHostTabs.splice(0, pendingHostTabs.length - HOST_TAB_QUEUE_CAP)
111
+ }
112
+ },
113
+
114
+ /** 取走并清空宿主新会话标签请求(规则④宿主→客户端通道的 drain 端)。返回 { ids }。 */
115
+ drainHostTabs() {
116
+ return { ids: pendingHostTabs.splice(0, pendingHostTabs.length) }
117
+ },
118
+
119
+ /** 向会话发一条用户消息,启动一轮(mode: queue|steer)。 */
120
+ async prompt({ sessionId, text, mode = 'queue' } = {}) {
121
+ const sessionController = controller()
122
+ if (!sessionController) throw unavailable('sessionController')
123
+ if (!sessionId) { const e = new Error('prompt 需要 sessionId'); e.code = 'ARG_INVALID'; throw e }
124
+ const content = Array.isArray(text)
125
+ ? text
126
+ : [{ type: 'text', text: String(text ?? '') }]
127
+ const value = await sessionController.prompt({
128
+ requestId: randomUUID(),
129
+ sessionId,
130
+ mode,
131
+ content,
132
+ })
133
+ return { accepted: value?.accepted !== false, sessionId }
134
+ },
135
+
136
+ /** 列出会话(最新在前)。优先 sessionQuery,退回活会话 sessions.list。 */
137
+ async listSessions() {
138
+ const sessionQuery = query()
139
+ if (sessionQuery) return await sessionQuery.listSessions()
140
+ const sessions = resolve('sessions')
141
+ if (sessions && typeof sessions.list === 'function') return await sessions.list()
142
+ throw unavailable('sessionQuery')
143
+ },
144
+
145
+ /** 读一个会话的转录/事件。 */
146
+ async readSession(sessionId) {
147
+ if (!sessionId) { const e = new Error('readSession 需要 sessionId'); e.code = 'ARG_INVALID'; throw e }
148
+ const sessionQuery = resolve('sessionQuery')
149
+ if (sessionQuery && typeof sessionQuery.readSession === 'function') return await sessionQuery.readSession(sessionId)
150
+ throw unavailable('sessionQuery.readSession')
151
+ },
152
+
153
+ /** 取消会话当前轮(best-effort;DSH 无显式 close,cancel 存在才调)。 */
154
+ async cancel(sessionId) {
155
+ const sessionController = controller()
156
+ if (!sessionController) throw unavailable('sessionController')
157
+ if (typeof sessionController.cancel === 'function') {
158
+ try { await sessionController.cancel({ sessionId }) } catch { /* 空闲会话 cancel 可能报错,忽略 */ }
159
+ }
160
+ return { sessionId, cancelled: true }
161
+ },
162
+
163
+ /** 读设置快照。 */
164
+ async describeSettings(options) {
165
+ const settings = settingsSvc()
166
+ if (!settings) throw unavailable('settings')
167
+ return await settings.describe(options)
168
+ },
169
+
170
+ /** 稀疏合并更新设置(ns=profile 条目 id;revision 不符抛 SETTINGS_CONFLICT)。 */
171
+ async updateSettings({ ns, patch, expectedRevision } = {}) {
172
+ const settings = settingsSvc()
173
+ if (!settings) throw unavailable('settings')
174
+ if (!ns || typeof ns !== 'string') { const e = new Error('updateSettings 需要 ns'); e.code = 'ARG_INVALID'; throw e }
175
+ return await settings.update(ns, patch ?? {}, expectedRevision)
176
+ },
177
+ }
178
+ }
@@ -0,0 +1,82 @@
1
+ /**
2
+ * 宿主会话探测(规则④):周期差分宿主会话列表,把「运行中(live)的非子代理会话」入队。
3
+ *
4
+ * 背景(2026-11-23):远程 LiveShare viewer fork、定时任务等路径创建的会话不经工作台
5
+ * createSession,进不了 agent-pending 队列,顶栏 keeper 的来源白名单也不认识它们——
6
+ * 于是这些会话在宿主后台真实运行,却不出现在顶栏标签里(用户报告的会话管理漏洞)。
7
+ * 这里周期差分 sessionQuery.listSessions()(宿主权威会话语料,含未激活的持久会话),
8
+ * 把运行中的会话喂给 session-port 的 host 队列,客户端 keeper 经固定端点
9
+ * /capyclaw/session-tabs/host-pending 取走、以 'host' 来源纳入顶栏(enroll 会 retain,
10
+ * 连带把会话 materialize 进宿主客户端目录,会话记录可见性一并解决)。
11
+ *
12
+ * 设计口径(用户规则:所有会话不管前台后台都遵循同一套管理规则):
13
+ * - 纯函数,listSessions/enqueue 全部注入(测试可 fake),不 import 任何 DSH 包。
14
+ * - 纳入判据 = record.live !== false(运行中/已激活),不看创建时间:启动前就在跑的
15
+ * 远程会话首拍即纳入;冷会话(live:false)不纳入,日后被远程唤醒变 live 时再纳入。
16
+ * (第一版「首拍只 seed」会漏掉重启前已存在的运行中远程会话,2026-11-23 已废弃。)
17
+ * - 子代理(header.origin==='subagent',DSH 官方分类器;parentSession 存在本身不能
18
+ * 分类子代理)不占顶栏标签(它们嵌套展示在父会话里)。
19
+ * - enrolled 记录已入队 id,每拍修剪到当前语料 id,内存有界。用户关掉的标签只要会话
20
+ * 还在语料里就一直留在 enrolled,不会被重新入队——尊重「关闭只由用户、不自动加回」。
21
+ * - busy 防重入;查询失败容错,下一拍再试,绝不崩宿主。
22
+ */
23
+
24
+ export const HOST_WATCH_INTERVAL_MS = 5000
25
+
26
+ /**
27
+ * @param {{ listSessions: () => Promise<Array<object>>, enqueue: (ids: string[]) => void, intervalMs?: number }} opts
28
+ * listSessions 返回宿主会话记录(SessionRecord[]:{header:{id,origin,...},live,persisted};
29
+ * 兼容无 header 包装、直接带 id/sessionId 的活会话列表——无 live 字段视为 live)。
30
+ */
31
+ export function createSessionWatch({ listSessions, enqueue, intervalMs = HOST_WATCH_INTERVAL_MS } = {}) {
32
+ if (typeof listSessions !== 'function') throw new Error('createSessionWatch 需要 listSessions 函数')
33
+ if (typeof enqueue !== 'function') throw new Error('createSessionWatch 需要 enqueue 函数')
34
+ const enrolled = new Set()
35
+ let busy = false
36
+ let stopped = false
37
+ let timer = null
38
+
39
+ async function tick() {
40
+ if (stopped || busy) return
41
+ busy = true
42
+ try {
43
+ const records = await listSessions()
44
+ const items = Array.isArray(records) ? records : []
45
+ const current = new Set()
46
+ const fresh = []
47
+ for (const record of items) {
48
+ const header = record && record.header ? record.header : record
49
+ const id = header && (header.id ?? header.sessionId)
50
+ if (typeof id !== 'string' || !id) continue
51
+ current.add(id)
52
+ /* 子代理不占顶栏标签(嵌套展示在父会话里)。 */
53
+ if (header.origin === 'subagent') continue
54
+ /* 只纳入运行中/已激活的会话;冷持久会话等它变 live 再说。
55
+ 无 live 字段的兼容形态(活会话列表)视为 live。 */
56
+ if (record && record.live === false) continue
57
+ if (enrolled.has(id)) continue
58
+ enrolled.add(id)
59
+ fresh.push(id)
60
+ }
61
+ /* enrolled 修剪到当前语料:内存有界;仍在语料里的 id 保留,
62
+ 用户关掉的标签不会被自动加回。 */
63
+ for (const id of enrolled) { if (!current.has(id)) enrolled.delete(id) }
64
+ if (fresh.length) enqueue(fresh)
65
+ } catch { /* 宿主查询失败:下一拍再试 */ }
66
+ finally { busy = false }
67
+ }
68
+
69
+ function start() {
70
+ if (timer || stopped) return
71
+ void tick()
72
+ timer = setInterval(() => { void tick() }, intervalMs)
73
+ if (timer && typeof timer.unref === 'function') timer.unref()
74
+ }
75
+
76
+ function stop() {
77
+ stopped = true
78
+ if (timer) { clearInterval(timer); timer = null }
79
+ }
80
+
81
+ return { start, stop, tick }
82
+ }