@capyclaw/capyclaw-workbench 0.1.0 → 0.1.2

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 (49) hide show
  1. package/README.md +29 -1
  2. package/lib/host.mjs +84 -80
  3. package/lib/session-port.mjs +89 -15
  4. package/lib/session-watch.mjs +82 -0
  5. package/lib/workspace-attach.mjs +147 -0
  6. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  7. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +3 -1
  8. package/node_modules/@capyclaw/foundation/abi/index.mjs +15 -0
  9. package/node_modules/@capyclaw/foundation/abi/loader.mjs +8 -1
  10. package/node_modules/@capyclaw/foundation/abi/spec.mjs +5 -2
  11. package/node_modules/@capyclaw/foundation/abi/version.mjs +63 -5
  12. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  13. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +21 -4
  14. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +11 -10
  15. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +8 -1
  16. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +5 -1
  17. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +5 -2
  18. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +4 -0
  19. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +29 -2
  20. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +13 -3
  21. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +31 -3
  22. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +12 -2
  23. package/node_modules/@capyclaw/foundation/package.json +1 -1
  24. package/node_modules/@capyclaw/plugin-kit/package.json +3 -1
  25. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +5 -2
  26. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  27. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +3 -82
  28. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +13 -6
  29. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  30. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +31 -15
  31. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +13 -5
  32. package/node_modules/@capyclaw/service-host/dsh-suite.json +1 -1
  33. package/node_modules/@capyclaw/service-host/package.json +1 -1
  34. package/node_modules/@capyclaw/service-host/src/index.mjs +18 -19
  35. package/node_modules/@capyclaw/suite-kit/README.md +52 -1
  36. package/node_modules/@capyclaw/suite-kit/package.json +6 -2
  37. package/node_modules/@capyclaw/suite-kit/src/host.mjs +230 -0
  38. package/node_modules/@capyclaw/suite-kit/src/index.mjs +14 -0
  39. package/node_modules/@capyclaw/suite-kit/suite.schema.json +16 -0
  40. package/node_modules/@capyclaw/tool-host/dsh-suite.json +2 -2
  41. package/node_modules/@capyclaw/tool-host/lib/host.mjs +34 -4
  42. package/node_modules/@capyclaw/tool-host/package.json +1 -1
  43. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  44. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  45. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +28 -4
  46. package/node_modules/@capyclaw/tool-host/src/index.mjs +90 -19
  47. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  48. package/package.json +2 -2
  49. package/plugin.mjs +17 -1
package/README.md CHANGED
@@ -20,10 +20,38 @@ CapyClaw 子会话工作台运行时:让 AI 在同一宿主进程内发起、
20
20
 
21
21
  ## 承载形态
22
22
 
23
- 宿主进程内插件(foundation ABI):有 `ctx.webServer` 时挂宿主路由前缀,不单独占端口;工具经 `tools.registry` / `tools.descriptors` 能力注册。
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` 注册,故端口与补登记运行器都接受零参解析函数、用的时候现取(不被一次性快照定格成缺席);服务晚注册也能用上,未就绪时静默重试。
24
46
 
25
47
  ## 测试
26
48
 
27
49
  ```bash
28
50
  npm test
29
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__ / 释放)。
package/lib/host.mjs CHANGED
@@ -1,102 +1,106 @@
1
1
  /**
2
2
  * capyclaw-workbench cordis 宿主入口:把可单测核心接进 DSH。
3
- * 模式沿用 browser embedded-host:inject=['webServer'],其余服务 safeGet 优雅降级。
3
+ * 公共胶水(safeGet/断言/缺服务降级/probe 兜底/__host__/portal/工具注册/描述符/逆序释放)
4
+ * 收敛到 @capyclaw/suite-kit/host 的 mountSuiteWorkbench(P1-9);本文件只保留 capyclaw 差异:
5
+ * sessionPort/session-watch 装配、两个固定 session-tabs drain 端点、__host__.available 字段。
4
6
  */
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 { /* 忽略 */ } }
7
+ import { mountSuiteWorkbench } from '@capyclaw/suite-kit/host'
14
8
  import { createSessionPort } from './session-port.mjs'
9
+ import { createSessionWatch } from './session-watch.mjs'
10
+ import { createWorkspaceReconcile } from './workspace-attach.mjs'
15
11
  import { createCapyclawWorkbench } from './workbench.mjs'
16
12
  import { CAPYCLAW_DESCRIPTORS } from './descriptors.mjs'
17
13
 
18
14
  export const name = 'capyclaw-workbench'
19
15
  export const inject = ['webServer']
20
16
 
21
- function safeGet(ctx, serviceName) {
22
- try { return ctx.reflect?.get?.(serviceName) ?? ctx[serviceName] } catch { return null }
23
- }
24
-
25
17
  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 })
18
+ return mountSuiteWorkbench(ctx, config, {
19
+ ns: name,
20
+ suite: 'capyclaw',
21
+ mountPath: '/capyclaw/capyclaw',
22
+ title: 'CapyClaw 子会话工作台',
23
+ descriptors: CAPYCLAW_DESCRIPTORS,
44
24
 
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(设置/呈现仍可用)')
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
+ })
52
36
 
53
- const workbench = createCapyclawWorkbench({
54
- toolHost, serviceHost, sessionPort,
55
- config: { mountPath, guiUrl: config.guiUrl || '/', version: config.version || '0.1.0' },
56
- })
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())
57
47
 
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())
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
+ },
62
61
 
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
- }
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
+ }),
69
66
 
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
- }
67
+ hostInfo: (workbench, { sessionPort }) => ({ available: sessionPort.services }),
77
68
 
78
- // 自检端点。
79
- if (webServer?.register) {
80
- const path = `${mountPath}/__host__`
81
- const off = webServer.register({
82
- kind: 'exact', path,
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',
83
76
  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 }))
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()))
86
84
  },
87
85
  })
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' })
86
+ if (typeof offAgent === 'function') push(offAgent)
93
87
 
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
- }
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
+ })
102
106
  }
@@ -11,9 +11,15 @@
11
11
  * - 纯函数端口,服务全部注入(可在测试里用 fake 替换),不 import 任何 DSH 包。
12
12
  * - 优雅降级:宿主没有对应服务时返回明确的 unavailable 错误,而不是静默假成功。
13
13
  * - GUI 无会话深链(recon 结论):这里只负责「创建/驱动/查询」会话这一控制面;
14
- * 「呈现哪个会话」是 UI 层的事,新建会话会经事件自动出现在 GUI 列表。
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,不新建工作区)。
15
20
  */
16
21
  import { randomUUID } from 'node:crypto'
22
+ import { attachSessionByCwd } from './workspace-attach.mjs'
17
23
 
18
24
  function unavailable(service) {
19
25
  const err = new Error(`当前宿主没有 ${service} 服务,无法执行该会话操作`)
@@ -22,20 +28,46 @@ function unavailable(service) {
22
28
  }
23
29
 
24
30
  /**
25
- * @param {{ sessionController?:object, sessionQuery?:object, sessions?:object, settings?:object }} services
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 晚注册导致补登记/创建静默失效的教训)。
26
35
  */
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'
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 = []
31
60
 
32
61
  return {
33
- available: hasController,
34
- services: { sessionController: hasController, sessionQuery: hasQuery, settings: hasSettings },
62
+ get available() { return !!controller() },
63
+ get services() {
64
+ return { sessionController: !!controller(), sessionQuery: !!query(), settings: !!settingsSvc(), workspaceRegistry: !!registry() }
65
+ },
35
66
 
36
67
  /** 创建一个子会话(完成 workspace/preset/agent 接线)。 */
37
68
  async createSession({ cwd, workspaceId, agentPreset } = {}) {
38
- if (!hasController) throw unavailable('sessionController')
69
+ const sessionController = controller()
70
+ if (!sessionController) throw unavailable('sessionController')
39
71
  if (cwd && workspaceId) {
40
72
  const err = new Error('cwd 与 workspaceId 互斥,只能给一个')
41
73
  err.code = 'ARG_INVALID'
@@ -46,12 +78,48 @@ export function createSessionPort({ sessionController, sessionQuery, sessions, s
46
78
  if (workspaceId) request.workspaceId = workspaceId
47
79
  if (agentPreset) request.agentPreset = agentPreset
48
80
  const value = await sessionController.create(request)
49
- return { sessionId: value.sessionId, agentPreset: value.agentPreset ?? agentPreset ?? null }
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) }
50
117
  },
51
118
 
52
119
  /** 向会话发一条用户消息,启动一轮(mode: queue|steer)。 */
53
120
  async prompt({ sessionId, text, mode = 'queue' } = {}) {
54
- if (!hasController) throw unavailable('sessionController')
121
+ const sessionController = controller()
122
+ if (!sessionController) throw unavailable('sessionController')
55
123
  if (!sessionId) { const e = new Error('prompt 需要 sessionId'); e.code = 'ARG_INVALID'; throw e }
56
124
  const content = Array.isArray(text)
57
125
  ? text
@@ -67,7 +135,9 @@ export function createSessionPort({ sessionController, sessionQuery, sessions, s
67
135
 
68
136
  /** 列出会话(最新在前)。优先 sessionQuery,退回活会话 sessions.list。 */
69
137
  async listSessions() {
70
- if (hasQuery) return await sessionQuery.listSessions()
138
+ const sessionQuery = query()
139
+ if (sessionQuery) return await sessionQuery.listSessions()
140
+ const sessions = resolve('sessions')
71
141
  if (sessions && typeof sessions.list === 'function') return await sessions.list()
72
142
  throw unavailable('sessionQuery')
73
143
  },
@@ -75,13 +145,15 @@ export function createSessionPort({ sessionController, sessionQuery, sessions, s
75
145
  /** 读一个会话的转录/事件。 */
76
146
  async readSession(sessionId) {
77
147
  if (!sessionId) { const e = new Error('readSession 需要 sessionId'); e.code = 'ARG_INVALID'; throw e }
148
+ const sessionQuery = resolve('sessionQuery')
78
149
  if (sessionQuery && typeof sessionQuery.readSession === 'function') return await sessionQuery.readSession(sessionId)
79
150
  throw unavailable('sessionQuery.readSession')
80
151
  },
81
152
 
82
153
  /** 取消会话当前轮(best-effort;DSH 无显式 close,cancel 存在才调)。 */
83
154
  async cancel(sessionId) {
84
- if (!hasController) throw unavailable('sessionController')
155
+ const sessionController = controller()
156
+ if (!sessionController) throw unavailable('sessionController')
85
157
  if (typeof sessionController.cancel === 'function') {
86
158
  try { await sessionController.cancel({ sessionId }) } catch { /* 空闲会话 cancel 可能报错,忽略 */ }
87
159
  }
@@ -90,13 +162,15 @@ export function createSessionPort({ sessionController, sessionQuery, sessions, s
90
162
 
91
163
  /** 读设置快照。 */
92
164
  async describeSettings(options) {
93
- if (!hasSettings) throw unavailable('settings')
165
+ const settings = settingsSvc()
166
+ if (!settings) throw unavailable('settings')
94
167
  return await settings.describe(options)
95
168
  },
96
169
 
97
170
  /** 稀疏合并更新设置(ns=profile 条目 id;revision 不符抛 SETTINGS_CONFLICT)。 */
98
171
  async updateSettings({ ns, patch, expectedRevision } = {}) {
99
- if (!hasSettings) throw unavailable('settings')
172
+ const settings = settingsSvc()
173
+ if (!settings) throw unavailable('settings')
100
174
  if (!ns || typeof ns !== 'string') { const e = new Error('updateSettings 需要 ns'); e.code = 'ARG_INVALID'; throw e }
101
175
  return await settings.update(ns, patch ?? {}, expectedRevision)
102
176
  },
@@ -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
+ }
@@ -0,0 +1,147 @@
1
+ /**
2
+ * 工作区登记:让「只传 cwd」创建的会话归属到对应的已存在工作区。
3
+ *
4
+ * 背景(2026-11-23):DSH 的 session.create 只有传 workspaceId 才登记工作区成员
5
+ * (dsh-api-session-controller commands.create);只传 cwd 创建不登记 ⇒ 会话落进
6
+ * 「未分组」桶,不出现在对应目录的工作区清单里。远程客户端(工作台 GUI)新建恰恰
7
+ * 只传 cwd,故 capyclaw 侧补登记:
8
+ * - attachSessionByCwd:createSession 成功后按 cwd 登记进匹配的已存在工作区(best-effort);
9
+ * - reconcileWorkspaceMembership:对「运行中、非子代理、未被任何工作区认领」的会话补登记;
10
+ * - createWorkspaceReconcile:周期补登记运行器(带 handled 集合:已处理过的会话不再重纳,
11
+ * 尊重用户手动移出;冷转 live 的会话会在变 live 后被捕捉)。
12
+ *
13
+ * 服务懒解析:workspaceRegistry 可传对象或零参解析函数(宿主装配可能早于服务注册,
14
+ * 用的时候现取,避免被一次性快照定格成缺席——2026-11-23 教训)。
15
+ *
16
+ * 设计口径:纯函数、服务全部注入、不 import DSH 包。只登记进【已存在】的工作区,
17
+ * 绝不擅自新建工作区;子代理(origin==='subagent')不参与;已被任何工作区认领的
18
+ * 会话不动(尊重用户手动摆放)。路径匹配用字符串规范化(分隔符/尾斜杠/Windows
19
+ * 不区分大小写);attachSession 自身还会按 realpath 校验 cwd,不匹配会拒绝写入,
20
+ * 因此不会误登记。
21
+ */
22
+
23
+ /** 规范化路径用于比较:统一分隔符、去尾斜杠、Windows 不区分大小写。 */
24
+ function normPath(p, platform) {
25
+ if (typeof p !== 'string' || !p) return ''
26
+ let s = p.replace(/\\/g, '/').replace(/\/+$/, '')
27
+ if (s === '') s = '/'
28
+ if (platform === 'win32') s = s.toLowerCase()
29
+ return s
30
+ }
31
+
32
+ /** 两个路径是否指向同一工作区目录(字符串规范化比较)。 */
33
+ export function sameWorkspacePath(a, b, platform = process.platform) {
34
+ const na = normPath(a, platform)
35
+ const nb = normPath(b, platform)
36
+ return na !== '' && na === nb
37
+ }
38
+
39
+ /** 在已存在工作区里找 path 与 cwd 匹配的那一个;没有则 undefined(不新建)。 */
40
+ export function findWorkspaceByCwd(workspaces, cwd, platform = process.platform) {
41
+ if (!Array.isArray(workspaces) || typeof cwd !== 'string' || !cwd) return undefined
42
+ return workspaces.find((w) => w && sameWorkspacePath(w.path, cwd, platform))
43
+ }
44
+
45
+ /**
46
+ * 把会话登记进 cwd 匹配的已存在工作区。best-effort:无匹配/无服务/登记失败都返回
47
+ * false 而不抛错(调用方不应因登记失败而失败)。已是成员则幂等返回 true。
48
+ */
49
+ export async function attachSessionByCwd(workspaceRegistry, sessionId, cwd, platform = process.platform) {
50
+ try {
51
+ if (!workspaceRegistry || typeof workspaceRegistry.list !== 'function') return false
52
+ if (typeof sessionId !== 'string' || !sessionId) return false
53
+ const ws = findWorkspaceByCwd(workspaceRegistry.list(), cwd, platform)
54
+ if (!ws || typeof ws.attachSession !== 'function') return false
55
+ if (Array.isArray(ws.sessionIds) && ws.sessionIds.includes(sessionId)) return true
56
+ await ws.attachSession(sessionId)
57
+ return true
58
+ } catch {
59
+ return false
60
+ }
61
+ }
62
+
63
+ /**
64
+ * 补登记:遍历宿主会话,把「运行中(live)、非子代理、未被任何工作区认领、cwd 匹配某
65
+ * 已存在工作区」的会话登记进去。返回 { attached, ready };依赖缺失时 ready=false
66
+ * (调用方可稍后重试)。list() 抛错(如 registry 尚未初始化)向上传播,由运行器捕获重试。
67
+ *
68
+ * handled(可选 Set):已处理过的会话 id。已在集合里的跳过;本次「已成功登记」或
69
+ * 「已被某工作区认领」的会话记入集合——日后用户手动移出也不重纳(尊重摆放)。冷会话、
70
+ * 无匹配工作区、登记失败的不记入,留待后续拍捕捉(冷转 live / 稍后新建工作区)。
71
+ * workspaceRegistry 可为对象或零参解析函数。
72
+ */
73
+ export async function reconcileWorkspaceMembership({ listSessions, workspaceRegistry, handled, platform = process.platform } = {}) {
74
+ const registry = typeof workspaceRegistry === 'function' ? workspaceRegistry() : workspaceRegistry
75
+ if (typeof listSessions !== 'function' || !registry || typeof registry.list !== 'function') {
76
+ return { attached: [], ready: false }
77
+ }
78
+ const workspaces = registry.list()
79
+ const accounted = new Set()
80
+ for (const w of workspaces) {
81
+ for (const id of (w?.sessionIds ?? [])) accounted.add(id)
82
+ }
83
+ const records = await listSessions()
84
+ const items = Array.isArray(records) ? records : []
85
+ const attached = []
86
+ for (const record of items) {
87
+ const header = record?.header ?? record
88
+ const id = header?.id ?? header?.sessionId
89
+ if (typeof id !== 'string' || !id) continue
90
+ if (handled && handled.has(id)) continue // 已处理过 ⇒ 尊重用户摆放,不重纳
91
+ if (record?.live === false) continue // 只补登记运行中的(冷转 live 后再捕捉)
92
+ if (header?.origin === 'subagent') continue // 子代理嵌套展示,不占工作区成员
93
+ if (accounted.has(id)) { // 已被某工作区认领 ⇒ 尊重现有摆放
94
+ if (handled) handled.add(id)
95
+ continue
96
+ }
97
+ const cwd = header?.cwd
98
+ if (typeof cwd !== 'string' || !cwd) continue
99
+ const ok = await attachSessionByCwd(registry, id, cwd, platform)
100
+ if (ok) { attached.push(id); accounted.add(id); if (handled) handled.add(id) }
101
+ }
102
+ return { attached, ready: true }
103
+ }
104
+
105
+ /** 补登记运行器的重试间隔(与 session-watch 同口径)。 */
106
+ export const WORKSPACE_RECONCILE_INTERVAL_MS = 5000
107
+
108
+ /**
109
+ * 周期补登记运行器:每 intervalMs 跑一次 reconcileWorkspaceMembership,持续到 stop()。
110
+ * 带 handled 集合:已登记/已认领的会话不再重纳(尊重用户手动移出);冷转 live、稍后
111
+ * 新建工作区的会话会在后续拍被捕捉。服务未就绪(ready=false)或抛错时静默重试。
112
+ * workspaceRegistry 可为对象或零参解析函数(懒解析,装配早于服务注册也不丢)。
113
+ */
114
+ export function createWorkspaceReconcile({ listSessions, workspaceRegistry, intervalMs = WORKSPACE_RECONCILE_INTERVAL_MS, platform } = {}) {
115
+ if (typeof listSessions !== 'function') throw new Error('createWorkspaceReconcile 需要 listSessions 函数')
116
+ if (workspaceRegistry == null) throw new Error('createWorkspaceReconcile 需要 workspaceRegistry(对象或解析函数)')
117
+ let timer = null
118
+ let stopped = false
119
+ let busy = false
120
+ const handled = new Set()
121
+
122
+ async function tick() {
123
+ if (stopped || busy) return null
124
+ busy = true
125
+ try {
126
+ return await reconcileWorkspaceMembership({ listSessions, workspaceRegistry, handled, platform })
127
+ } catch {
128
+ return null // 服务未就绪等 ⇒ 下一拍重试
129
+ } finally {
130
+ busy = false
131
+ }
132
+ }
133
+
134
+ function start() {
135
+ if (timer || stopped) return
136
+ void tick()
137
+ timer = setInterval(tick, intervalMs)
138
+ timer.unref?.()
139
+ }
140
+
141
+ function stop() {
142
+ stopped = true
143
+ if (timer) { clearInterval(timer); timer = null }
144
+ }
145
+
146
+ return { start, stop, tick, get handledCount() { return handled.size } }
147
+ }