@capyclaw/capyclaw-workbench 0.1.0 → 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 (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 +5 -1
  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
@@ -91,7 +91,11 @@ export function createNet(host, config = {}) {
91
91
  }
92
92
  return
93
93
  }
94
- await new Promise((resolve) => setTimeout(resolve, WEB_LATE_POLL_MS))
94
+ await new Promise((resolve) => {
95
+ /* unref:迟到补挂的轮询定时器不得拖住进程退出(最长 60s 的尾延迟)。 */
96
+ const timer = setTimeout(resolve, WEB_LATE_POLL_MS)
97
+ timer.unref?.()
98
+ })
95
99
  }
96
100
  })().catch(() => {})
97
101
  }
@@ -116,7 +120,10 @@ export function createNet(host, config = {}) {
116
120
  if (!web && shouldWaitForWeb()) {
117
121
  const deadline = Date.now() + WEB_WAIT_MS
118
122
  while (!web && Date.now() < deadline && !closed) {
119
- await new Promise((resolve) => setTimeout(resolve, WEB_POLL_MS))
123
+ await new Promise((resolve) => {
124
+ const timer = setTimeout(resolve, WEB_POLL_MS)
125
+ timer.unref?.()
126
+ })
120
127
  web = webServer()
121
128
  }
122
129
  }
@@ -140,6 +147,9 @@ export function createNet(host, config = {}) {
140
147
  disposal = (async () => {
141
148
  if (!sharedHost) return
142
149
  // listen 失败由 ready/start 报告;清理仍需执行,且 close 失败不能被吞掉。
150
+ // 注意:dispose 在 listen 失败时仍 RESOLVE(错误经 ready/start 上报)——这是
151
+ // 被 network-lifecycle 测试固化的契约,close 不再二次上抛 listen 错,避免
152
+ // 破坏「清理成功即 dispose 成功」的语义。
143
153
  await listening.catch(() => {})
144
154
  // 迟到补挂的路由要一起撤掉,否则共享宿主关了、宿主网页端口上还留着分发器。
145
155
  try {
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/foundation",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "dsh 插件基石层:接口 ABI、插件加载器与内核服务 ctx.os。应用插件只声明接口,不写装配代码。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/plugin-kit",
3
- "version": "0.2.6",
3
+ "version": "0.2.7",
4
4
  "description": "DSH 插件基础设施标准件:HTTP/MCP、单实例锁、参数校验、技能 provider、journal 存储、编辑器传输与租约。",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
@@ -10,11 +10,13 @@
10
10
  "./service/mcp-http": "./src/service/mcp-http.mjs",
11
11
  "./service/server": "./src/service/server.mjs",
12
12
  "./service/api": "./src/service/api.mjs",
13
+ "./service/static": "./src/service/static.mjs",
13
14
  "./tools/validate": "./src/tools/validate.mjs",
14
15
  "./tools/result": "./src/tools/result.mjs",
15
16
  "./skills/provider": "./src/skills/provider.mjs",
16
17
  "./editor/transport": "./src/editor/transport.js",
17
18
  "./editor/lease": "./src/editor/lease.mjs",
19
+ "./editor/heartbeat": "./src/editor/heartbeat.mjs",
18
20
  "./editor/shadow": "./src/editor/shadow.mjs",
19
21
  "./store/journal-store": "./src/store/journal-store.mjs",
20
22
  "./store/blob-store": "./src/store/blob-store.mjs",
@@ -45,7 +45,10 @@ self.onmessage = function(e) {
45
45
  function startHeartbeat() {
46
46
  if (intervalHandle) clearInterval(intervalHandle);
47
47
 
48
- // 每 4 秒发送心跳(留 1 秒缓冲,避免刚好 5 秒时被判过期)
48
+ // 心跳节奏统一为 3s:单一真源是 editor/heartbeat.mjs 的 HEARTBEAT_INTERVAL_MS。
49
+ // 本文件是原样拷贝的经典 Worker,运行时不能 import npm 模块,故以字面量承载节奏,
50
+ // 由 test/heartbeat-constants.test.mjs 钉死与常量一致,防止再次漂移。
51
+ // 心跳对象是编辑器「在场租约」(editor-host /claim);两层租约语义见 heartbeat.mjs 头注。
49
52
  intervalHandle = setInterval(() => {
50
53
  if (!active) return;
51
54
 
@@ -66,7 +69,7 @@ function startHeartbeat() {
66
69
  });
67
70
  }
68
71
  });
69
- }, 4000);
72
+ }, 3000);
70
73
 
71
74
  // 立即发送第一次
72
75
  sendClaim().catch(() => {});
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 编辑器「在场租约」心跳节奏常量单一真源(P2-13b)。
3
+ *
4
+ * 背景:心跳节奏曾在两处手工对齐而漂移——plugin-kit 的 heartbeat-worker.js 写死
5
+ * 4000ms(还留着「避免 5 秒判过期」的过期注释),document-workbench 客户端却是
6
+ * 3000ms。两者必须同拍,否则编辑器判活与文档 owner 判活快慢不一。这里把节奏收敛
7
+ * 成一个常量,客户端直接 import;worker 是原样拷贝的经典 Web Worker(运行时不能
8
+ * import npm 模块),其 setInterval 字面量由 test/heartbeat-constants.test.mjs 钉死
9
+ * 等于本常量,防止再次漂移。统一取架构审查建议的 3s。
10
+ *
11
+ * 两层租约语义不同,都要保留(本常量只统一「心跳节奏」,不合并两层租约):
12
+ * 1. 在场租约(presence)——@capyclaw/plugin-kit/editor/lease.mjs 的 createEditorLease,
13
+ * 由 editor-host 的 /claim 消费,「显示即连接」:新窗口强制抢占、旧窗口静默待命;
14
+ * TTL 10s、无 epoch,靠客户端每 HEARTBEAT_INTERVAL_MS 心跳续租。
15
+ * 2. 所有权租约(owner)——@capyclaw/document-workbench/session 的 claimOwner/OWNER_TTL,
16
+ * deck/文档级所有权,带 epoch fencing(换人 +1、旧 owner 回执被丢弃)。PPT 的
17
+ * A/projects/ppt/src/server/store/lease.mjs 只是它的兼容再导出。此为套件领域件,
18
+ * 不在本次改造范围,仅在此说清两层,避免误把在场租约当成所有权租约。
19
+ * 两条租约线共用「心跳 3s、TTL 10s」的并发协议;TTL 的运行时真源仍是 lease.mjs 的
20
+ * DEFAULT_TTL 与 document-workbench 的 OWNER_TTL(均已为 10s,未漂移,不在本次改动范围)。
21
+ *
22
+ * 本文件零依赖、browser-safe(无 node:*),可被编辑器客户端 bundle 直接 import。
23
+ */
24
+
25
+ /** 心跳间隔(毫秒):在场租约与文档 owner 租约共用的续租节奏,单一真源。 */
26
+ export const HEARTBEAT_INTERVAL_MS = 3000
@@ -6,8 +6,9 @@
6
6
  */
7
7
  import { tuning } from '../tuning.mjs'
8
8
 
9
- const DEFAULT_TTL = 15 // 秒
10
- const DEFAULT_HEARTBEAT = 3 // 秒(心跳间隔应小于 TTL)
9
+ /* 与文档 owner 租约(document-workbench OWNER_TTL)对齐为 10s:
10
+ * 两条租约线共用「心跳 3s、TTL 10s」的并发协议,避免编辑器判活比文档慢半拍。 */
11
+ const DEFAULT_TTL = 10 // 秒
11
12
 
12
13
  /**
13
14
  * 创建编辑器租约仲裁器。
@@ -57,83 +58,3 @@ export function createEditorLease(opts = {}) {
57
58
  },
58
59
  }
59
60
  }
60
-
61
- /**
62
- * 编辑器端自动挂接循环。
63
- * 首次 claim 强制抢占(后打开者赢),之后静默心跳。
64
- * @param {{
65
- * clientId: string,
66
- * claim: (force: boolean) => Promise<boolean>,
67
- * release?: () => void,
68
- * onActive?: () => void,
69
- * onStandby?: () => void,
70
- * retryMs?: number,
71
- * heartbeatMs?: number,
72
- * setInterval?: (cb: () => void) => any,
73
- * clearInterval?: (handle: any) => void
74
- * }} o
75
- */
76
- export function startAutoAttach(o) {
77
- if (!o || !o.clientId) throw new Error('startAutoAttach: clientId 必填')
78
- if (typeof o.claim !== 'function') throw new Error('startAutoAttach: claim 必须是函数')
79
-
80
- const retryMs = o.retryMs || 1000
81
- const heartbeatMs = o.heartbeatMs || DEFAULT_HEARTBEAT * 1000
82
- const setI = o.setInterval || ((cb) => setInterval(cb, heartbeatMs))
83
- const clearI = o.clearInterval || ((handle) => clearInterval(handle))
84
-
85
- let active = false
86
- let heartbeat = null
87
- let disposed = false
88
-
89
- async function tryClaim(force) {
90
- try {
91
- return await o.claim(force)
92
- } catch {
93
- return false
94
- }
95
- }
96
-
97
- function goActive() {
98
- if (active) return
99
- active = true
100
- try { o.onActive && o.onActive() } catch { /* 用户回调失败不阻塞挂接 */ }
101
- heartbeat = setI(async () => {
102
- if (disposed) return
103
- const ok = await tryClaim(false)
104
- if (!ok) goStandby()
105
- })
106
- }
107
-
108
- function goStandby() {
109
- if (!active) return
110
- active = false
111
- if (heartbeat != null) {
112
- clearI(heartbeat)
113
- heartbeat = null
114
- }
115
- try { o.onStandby && o.onStandby() } catch { /* 静默 */ }
116
- }
117
-
118
- ;(async () => {
119
- let first = true
120
- while (!disposed) {
121
- const ok = await tryClaim(first)
122
- first = false
123
- if (ok) {
124
- goActive()
125
- return
126
- }
127
- await new Promise((resolve) => setTimeout(resolve, retryMs))
128
- }
129
- })()
130
-
131
- return {
132
- get active() { return active },
133
- dispose() {
134
- disposed = true
135
- goStandby()
136
- try { o.release && o.release() } catch { /* 释放失败不阻塞退出 */ }
137
- },
138
- }
139
- }
@@ -22,12 +22,19 @@ function reply(id, result) {
22
22
 
23
23
  export function createMcpHandler({
24
24
  tools = [], callTool, serverInfo, instructions,
25
- maxBodyBytes = 10 * 1024 * 1024, maxBatch = 100,
25
+ maxBodyBytes = 10 * 1024 * 1024, maxBatch = 100, listChanged = false,
26
26
  } = {}) {
27
- if (!Array.isArray(tools)) throw new Error('createMcpHandler: tools 必须是数组')
27
+ /* tools 可以是静态数组,或一个返回当前数组的函数(活引用)。活引用让
28
+ * tools/list 每次读到最新工具集——registry 动态增删工具后无需重建 handler。 */
29
+ const liveProvider = typeof tools === 'function' ? tools : null
30
+ if (!liveProvider && !Array.isArray(tools)) throw new Error('createMcpHandler: tools 必须是数组或返回数组的函数')
28
31
  if (typeof callTool !== 'function') throw new Error('createMcpHandler: callTool 必须是函数')
29
32
 
30
- const toolMap = new Map(tools.map((tool) => [tool.name, tool]))
33
+ const currentTools = () => {
34
+ const list = liveProvider ? liveProvider() : tools
35
+ return Array.isArray(list) ? list : []
36
+ }
37
+ const toolMapNow = () => new Map(currentTools().map((tool) => [tool.name, tool]))
31
38
 
32
39
  return async function handle(req, res) {
33
40
  /* 长工具调用(如截图)期间客户端可能超时断连;socket 的 'error' 事件
@@ -89,7 +96,7 @@ export function createMcpHandler({
89
96
  if (method === 'initialize') {
90
97
  const result = {
91
98
  protocolVersion: String(params?.protocolVersion || DEFAULT_PROTOCOL),
92
- capabilities: { tools: { listChanged: false } },
99
+ capabilities: { tools: { listChanged: !!listChanged } },
93
100
  serverInfo: serverInfo || { name: 'dsh-plugin', version: '0.0.0' },
94
101
  }
95
102
  if (typeof instructions === 'string' && instructions) result.instructions = instructions
@@ -101,13 +108,13 @@ export function createMcpHandler({
101
108
  if (method === 'ping') return isNotification ? null : reply(id, {})
102
109
 
103
110
  if (method === 'tools/list') {
104
- return isNotification ? null : reply(id, { tools })
111
+ return isNotification ? null : reply(id, { tools: currentTools() })
105
112
  }
106
113
 
107
114
  if (method === 'tools/call') {
108
115
  const name = params?.name
109
116
  const args = params?.arguments && typeof params.arguments === 'object' ? params.arguments : {}
110
- const tool = toolMap.get(name)
117
+ const tool = toolMapNow().get(name)
111
118
  if (!tool) {
112
119
  if (isNotification) return null
113
120
  return reply(id, {
@@ -0,0 +1,79 @@
1
+ /**
2
+ * 静态文件服务公共核心(P2-13a)。
3
+ *
4
+ * service-host 与 editor-host 各有一套静态文件服务,其中「路径穿越防护 / 挂载前缀
5
+ * 归一与命中 / 相对路径解码 / files 显式映射 / 基础响应头」这几段逻辑逐字重复。
6
+ * 这里把它们收敛成一组纯函数作为单一真源,两个宿主都 import 本文件,不再各写一份。
7
+ *
8
+ * 边界(刻意不收敛的部分):本文件只做「无 IO 的路径/头部计算」,不碰响应政策。
9
+ * 两宿主的行为差异必须各自保留——
10
+ * - 畸形百分号编码:service-host 回 400,editor-host 交还路由链(return false);
11
+ * - 目录入口补尾斜杠 301、ETag/gzip/304/vary:仅 editor-host;
12
+ * - content-type 取值:service-host 用 mimeFor(请求 rel) + explicitType,
13
+ * editor-host 用 mimeFor(落盘文件路径);
14
+ * - 读盘策略:service-host 每次 readFileSync,editor-host 走 (size,mtime) 缓存。
15
+ * 因此 decodeStaticRel 畸形时返回 null(而非抛错/替宿主回响应),由调用方决定 400 还是放行。
16
+ *
17
+ * 只依赖 node 内置(node:path),不 import 本包其它文件,不成环(与 util/http.mjs 同风格)。
18
+ */
19
+ import path from 'node:path'
20
+
21
+ /** 路径穿越防护:只允许落在 root 内(含 root 自身),越界返回 null。两宿主共用。 */
22
+ export function safeJoin(root, rel) {
23
+ const target = path.resolve(root, `.${path.sep}${rel}`)
24
+ const base = path.resolve(root)
25
+ return target === base || target.startsWith(base + path.sep) ? target : null
26
+ }
27
+
28
+ /** 挂载前缀归一:'/' → ''(挂全部);其余去掉尾斜杠。空/缺省按 '' 处理。 */
29
+ export function cleanStaticPrefix(prefix) {
30
+ return prefix === '/' ? '' : String(prefix || '').replace(/\/+$/, '')
31
+ }
32
+
33
+ /** 前缀命中:空前缀命中一切;非空须精确等于前缀或其子路径。 */
34
+ export function staticPrefixHit(pathname, prefix) {
35
+ return !prefix || pathname === prefix || pathname.startsWith(prefix + '/')
36
+ }
37
+
38
+ /** 去掉挂载前缀后的原始相对路径(未解码)。 */
39
+ export function staticRelRaw(pathname, prefix) {
40
+ return prefix ? pathname.slice(prefix.length) : pathname
41
+ }
42
+
43
+ /**
44
+ * 解码相对路径:空/'/' 落到 index;其余去掉 leading 斜杠后 decodeURIComponent。
45
+ * 畸形百分号编码(URIError)返回 null——由宿主决定回 400(service-host)还是
46
+ * 交还路由链(editor-host),本核心不替宿主做响应政策。
47
+ */
48
+ export function decodeStaticRel(relRaw, index = 'index.html') {
49
+ try {
50
+ return relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
51
+ } catch {
52
+ return null
53
+ }
54
+ }
55
+
56
+ /** files 显式映射查表:relRaw 为空时用 '/' 键;未命中返回 null(宿主交还路由链)。 */
57
+ export function staticFileHit(files, relRaw) {
58
+ if (!files) return null
59
+ return files[relRaw === '' ? '/' : relRaw] || files[relRaw] || null
60
+ }
61
+
62
+ /** 映射条目 → [文件名, 显式 content-type(可空)]。字符串条目无显式 type。 */
63
+ export function staticHitNameType(hit) {
64
+ return Array.isArray(hit) ? [hit[0], hit[1]] : [hit, undefined]
65
+ }
66
+
67
+ /**
68
+ * 静态 200 基础响应头:content-type/length + 安全与缓存政策(两宿主一致的五项)。
69
+ * no-cache = 允许缓存但每次回源校验;editor-host 会在此之上追加 etag/vary。
70
+ */
71
+ export function staticBaseHeaders(type, length) {
72
+ return {
73
+ 'content-type': type,
74
+ 'content-length': length,
75
+ 'x-content-type-options': 'nosniff',
76
+ 'referrer-policy': 'no-referrer',
77
+ 'cache-control': 'no-cache',
78
+ }
79
+ }
@@ -14,24 +14,40 @@
14
14
  * 返回恒为 {content:[...]}(object),因此 DSH 原生面 output.schema 用 object 恒满足。
15
15
  */
16
16
 
17
- /** 把任意工具返回值归一为 MCP content 形态。 */
18
- export function normalizeToolResult(out) {
17
+ /** 单个 text 块的默认上限:防 base64/大输出撑爆 LLM 上下文。image 块不受影响。 */
18
+ export const DEFAULT_MAX_TEXT_BYTES = 256 * 1024
19
+
20
+ function capText(text, max) {
21
+ if (!max || max <= 0 || typeof text !== 'string' || text.length <= max) return text
22
+ return `${text.slice(0, max)}\n…[truncated: original ${text.length} chars, limit ${max}]`
23
+ }
24
+
25
+ function capContent(content, max) {
26
+ return content.map((block) => (
27
+ block && block.type === 'text' && typeof block.text === 'string'
28
+ ? { ...block, text: capText(block.text, max) }
29
+ : block
30
+ ))
31
+ }
32
+
33
+ /** 把任意工具返回值归一为 MCP content 形态(并对超限 text 块截断+提示)。 */
34
+ export function normalizeToolResult(out, { maxTextBytes = DEFAULT_MAX_TEXT_BYTES } = {}) {
19
35
  const isError = out && typeof out.isError === 'boolean' ? { isError: out.isError } : {}
36
+ let content
20
37
  if (out && Array.isArray(out.content)) {
21
- return { content: out.content, ...isError }
22
- }
23
- if (out && typeof out.text === 'string') {
24
- return { content: [{ type: 'text', text: out.text }], ...isError }
25
- }
26
- if (typeof out === 'string') {
27
- return { content: [{ type: 'text', text: out }] }
28
- }
29
- if (out === undefined || out === null) {
30
- return { content: [{ type: 'text', text: '' }] }
38
+ content = out.content
39
+ } else if (out && typeof out.text === 'string') {
40
+ content = [{ type: 'text', text: out.text }]
41
+ } else if (typeof out === 'string') {
42
+ content = [{ type: 'text', text: out }]
43
+ } else if (out === undefined || out === null) {
44
+ content = [{ type: 'text', text: '' }]
45
+ } else {
46
+ let text
47
+ try { text = JSON.stringify(out) } catch { text = String(out) }
48
+ content = [{ type: 'text', text: text ?? String(out) }]
31
49
  }
32
- let text
33
- try { text = JSON.stringify(out) } catch { text = String(out) }
34
- return { content: [{ type: 'text', text: text ?? String(out) }] }
50
+ return { content: capContent(content, maxTextBytes), ...isError }
35
51
  }
36
52
 
37
53
  /** 从归一化结果提取纯文本(用于把失败内容拼成 Error.message)。 */
@@ -575,7 +575,7 @@ export class WorkspaceClient {
575
575
 
576
576
  /** 插件的 JournalStore 持久化接口 → 中间层 workspace。 */
577
577
  export class WorkspaceBackend {
578
- constructor({ client, workId = 'main', journalPath = null }) {
578
+ constructor({ client, workId = 'main', journalPath = null, project = null }) {
579
579
  /* 结构化契约:workspace-service 可能来自另一份 kit 快照。 */
580
580
  if (!client || typeof client.put !== 'function' || typeof client.getJson !== 'function') {
581
581
  throw new Error('WorkspaceBackend 需要 WorkspaceClient 兼容实现')
@@ -583,6 +583,9 @@ export class WorkspaceBackend {
583
583
  this.client = client
584
584
  this.workId = workId
585
585
  this.journalPath = journalPath || null
586
+ /* checkpoint 列表投影(形状声明):内核只产出通用信封,业务字段(如 PPT 的 slides)
587
+ * 由套件适配层传入 project(payload, base) 叠加。缺省纯信封,不硬编码任何业务名词。 */
588
+ this.project = typeof project === 'function' ? project : null
586
589
  this.stateKey = 'state.json'
587
590
  this.journalKey = 'journal.jsonl'
588
591
  this.checkpointPrefix = 'checkpoints/'
@@ -624,23 +627,27 @@ export class WorkspaceBackend {
624
627
  return { name, createdAt: payload.createdAt, meta: payload.meta || {} }
625
628
  }
626
629
 
627
- listCheckpoints() {
630
+ listCheckpoints(opts = {}) {
631
+ const project = typeof opts.project === 'function' ? opts.project : this.project
628
632
  return this.client.list(this.workId)
629
633
  .filter((item) => item.key.startsWith(this.checkpointPrefix) && item.key.endsWith('.json'))
630
634
  .map((item) => {
631
635
  try {
632
636
  const payload = this.client.getJson(this.workId, item.key)
633
637
  if (!payload) return null
634
- return {
638
+ /* 通用会话信封:不含任何业务名词(slides/deck 等)。业务字段经 project 叠加。
639
+ * 约定与 document-workbench projectCheckpoint 一致:project(payload, base) 只返回
640
+ * 「扩展字段」,由 backend 合并 base({...base, ...extra}),保证 name/createdAt/meta 不丢。 */
641
+ const base = {
635
642
  name: payload.name,
636
643
  seq: payload.seq,
637
644
  appliedSeq: payload.appliedSeq,
638
645
  pending: !!payload.pending,
639
646
  title: payload.title,
640
- slides: payload.slides,
641
647
  createdAt: payload.createdAt,
642
648
  meta: payload.meta || {},
643
649
  }
650
+ return project ? { ...base, ...project(payload, base) } : base
644
651
  } catch { return null }
645
652
  })
646
653
  .filter(Boolean)
@@ -650,7 +657,8 @@ export class WorkspaceBackend {
650
657
  readCheckpoint(name) {
651
658
  const key = `${this.checkpointPrefix}${name}.json`
652
659
  const payload = this.client.getJson(this.workId, key, null)
653
- if (!payload || !payload.deck) throw new Error('checkpoint 内容损坏: ' + name)
660
+ /* 只校验载荷存在;业务形状(如 PPT 的 deck)由套件适配层 / DocumentSession 的 documentKey 校验。 */
661
+ if (!payload) throw new Error('checkpoint 内容损坏: ' + name)
654
662
  return payload
655
663
  }
656
664
  }
@@ -7,7 +7,7 @@
7
7
  "packages": {
8
8
  "@capyclaw/service-host": {
9
9
  "role": "provider",
10
- "version": "^0.1.5",
10
+ "version": "^0.1.6",
11
11
  "path": ".",
12
12
  "provides": {
13
13
  "services": [
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capyclaw/service-host",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
4
4
  "description": "DSH 公共服务宿主插件:统一 HTTP 路由、健康检查、指标、单实例锁、端口复用与静态资源,向插件提供 ctx.serviceHost。",
5
5
  "type": "module",
6
6
  "main": "./lib/host.mjs",
@@ -19,6 +19,7 @@ import crypto from 'node:crypto'
19
19
  import { listen, send, sendText, readBody } from '@capyclaw/plugin-kit/service/http'
20
20
  import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
21
21
  import { isLoopbackOrigin as sharedIsLoopbackOrigin, mimeFor } from '@capyclaw/plugin-kit/util/http'
22
+ import { safeJoin, cleanStaticPrefix, staticPrefixHit, staticRelRaw, decodeStaticRel, staticFileHit, staticHitNameType, staticBaseHeaders } from '@capyclaw/plugin-kit/service/static'
22
23
  import { tuning } from './tuning.mjs'
23
24
 
24
25
  function slugOf(id) {
@@ -133,11 +134,7 @@ async function probeExisting(origin, healthPath, id) {
133
134
  }
134
135
  }
135
136
 
136
- function safeJoin(root, rel) {
137
- const target = path.resolve(root, `.${path.sep}${rel}`)
138
- const base = path.resolve(root)
139
- return target === base || target.startsWith(base + path.sep) ? target : null
140
- }
137
+ /* safeJoin 已收敛到 @capyclaw/plugin-kit/service/static(P2-13a 静态公共核心)。 */
141
138
 
142
139
  /**
143
140
  * @param {{
@@ -204,20 +201,28 @@ export function createServiceApp(options = {}) {
204
201
  })
205
202
  },
206
203
 
207
- /** 静态目录挂载。files 可给显式映射:{ '/': ['index.html','text/html'] }。 */
204
+ /** 静态目录挂载。files 可给显式映射:{ '/': ['index.html','text/html'] }。
205
+ * 路径/头部计算走 @capyclaw/plugin-kit/service/static 公共核心(P2-13a);
206
+ * 本宿主保留自己的响应政策:畸形编码回 400、content-type 取 mimeFor(请求 rel)、每次读盘。 */
208
207
  static(prefix, dir, { files = null, index = 'index.html' } = {}) {
209
- const cleanPrefix = prefix === '/' ? '' : prefix.replace(/\/+$/, '')
208
+ const cleanPrefix = cleanStaticPrefix(prefix)
210
209
  return app.use((req, res, u) => {
211
210
  if (req.method !== 'GET' && req.method !== 'HEAD') return false
212
- if (cleanPrefix && u.pathname !== cleanPrefix && !u.pathname.startsWith(cleanPrefix + '/')) return false
213
- const relRaw = cleanPrefix ? u.pathname.slice(cleanPrefix.length) : u.pathname
214
- const rel = relRaw === '' || relRaw === '/' ? index : decodeURIComponent(relRaw.replace(/^\/+/, ''))
211
+ if (!staticPrefixHit(u.pathname, cleanPrefix)) return false
212
+ const relRaw = staticRelRaw(u.pathname, cleanPrefix)
213
+ const rel = decodeStaticRel(relRaw, index)
214
+ if (rel === null) {
215
+ /* 畸形百分号编码 → URIError,不包会冒成 500;客户端错误回 400。 */
216
+ res.writeHead(400, { 'content-type': 'text/plain; charset=utf-8' })
217
+ res.end(req.method === 'HEAD' ? undefined : 'malformed path encoding')
218
+ return true
219
+ }
215
220
  let file = null
216
221
  let type = mimeFor(rel)
217
222
  if (files) {
218
- const hit = files[relRaw === '' ? '/' : relRaw] || files[relRaw]
223
+ const hit = staticFileHit(files, relRaw)
219
224
  if (!hit) return false
220
- const [name, explicitType] = Array.isArray(hit) ? hit : [hit]
225
+ const [name, explicitType] = staticHitNameType(hit)
221
226
  file = safeJoin(dir, name)
222
227
  type = explicitType || type
223
228
  } else {
@@ -226,13 +231,7 @@ export function createServiceApp(options = {}) {
226
231
  if (!file) return false
227
232
  try {
228
233
  const data = fs.readFileSync(file)
229
- res.writeHead(200, {
230
- 'content-type': type,
231
- 'content-length': data.length,
232
- 'x-content-type-options': 'nosniff',
233
- 'referrer-policy': 'no-referrer',
234
- 'cache-control': 'no-cache',
235
- })
234
+ res.writeHead(200, staticBaseHeaders(type, data.length))
236
235
  res.end(req.method === 'HEAD' ? undefined : data)
237
236
  return true
238
237
  } catch {
@@ -231,8 +231,59 @@ node scripts/build-bundle.mjs \
231
231
  `setup.mjs` 调用 `installDomain({ runPnpm: false })`,在 bundle 自带的
232
232
  `DSH_HOME` 下建立 profile 和组件链接,不依赖 pnpm,也不写用户主目录。
233
233
 
234
+ ## 双重身份:构建期库 + 运行时库(P2-12 决策记录)
235
+
236
+ 这个包同时是**构建期库**(suite/domain 清单 validate/compose/profile)与**运行时库**
237
+ (orchestration 闸/Mandate/事件/步骤、embed 握手、surface 挂载)。两类模块同包共存,
238
+ 但依赖方向严格单向:**运行时模块绝不 import 构建期模块**。
239
+
240
+ ### 构建期模块(清单校验 / 组合 / 安装,构建与安装期执行)
241
+
242
+ | 子路径 | 模块 | 职责 |
243
+ | --- | --- | --- |
244
+ | `@capyclaw/suite-kit/manifest` | `src/manifest.mjs` | suite/domain 清单读取与静态校验(`loadSuiteManifest`) |
245
+ | `@capyclaw/suite-kit/compose` | `src/compose.mjs` | 套件组合、冲突检测、`renderCordisPatch`、`composeToDir` |
246
+ | `@capyclaw/suite-kit/profile` | `src/profile.mjs` | profile 生成/安装(`installSuites`)、`doctor` 诊断 |
247
+ | `@capyclaw/suite-kit/domain` | `src/domain.mjs` | 领域解析(`resolveDomain`)与 staging(`stageDomain`) |
248
+ | `@capyclaw/suite-kit/artifacts` | `src/artifacts.mjs` | 版本化 artifact store:打包/回滚 |
249
+ | 仅根入口导出 | `src/activation-registry.mjs` | 安装期编译 launch-engine 激活注册表(无独立子路径) |
250
+ | `dsh-suite` / `dsh-domain` | `bin/` | CLI 入口 |
251
+ | `@capyclaw/suite-kit/schema` / `./domain-schema` | 两个 JSON Schema | 清单 schema |
252
+
253
+ 构建期内部依赖:`profile → compose / manifest / artifacts / activation-registry`,
254
+ `compose → manifest`,`domain → compose / manifest`。
255
+
256
+ ### 运行时模块(宿主无关的协议原语,被套件工作台在运行时 import)
257
+
258
+ | 子路径 | 模块 | 职责 | 现有消费者(grep 实证) |
259
+ | --- | --- | --- | --- |
260
+ | `@capyclaw/suite-kit/capability` | `src/capability.mjs` | 能力描述符词表/校验/匹配/发现(纯函数,无内部依赖) | capyclaw/rsp/conductor 工作台 `lib/host.mjs` |
261
+ | `@capyclaw/suite-kit/orchestration` | `src/orchestration.mjs` | 确认闸 `evaluateGate`、Mandate、事件、步骤原语(仅依赖 `node:crypto`) | conductor 工作台 `lib/engine.mjs`、`lib/plan-store.mjs` |
262
+ | `@capyclaw/suite-kit/embed` | `src/embed.mjs` | 嵌入握手协议原语(无内部依赖) | `surface.mjs` 与浏览器侧客户端 |
263
+ | `@capyclaw/suite-kit/surface` | `src/surface.mjs` | `attachSurface`:挂 `GET /embed.js` 与 `/api/surface`(import `./embed.mjs`) | capyclaw/rsp/conductor 工作台 `lib/workbench.mjs`、B/official/capyclaw-offline-ddr0 |
264
+ | `@capyclaw/suite-kit/client/embed.js` | `client/embed.js` | 浏览器侧握手客户端(经 surface 分发) | 嵌入页面 |
265
+
266
+ ### 依赖方向与使用约定
267
+
268
+ - 运行时模块(capability/orchestration/embed/surface/client)绝不 import 构建期模块;
269
+ 运行时内部唯一依赖是 `surface → embed`。
270
+ - 根入口 `export *` 同时导出两类模块:构建脚本 import 根入口会连带拉入运行时件
271
+ (均为纯函数、无副作用,不会触发安装逻辑);**运行时消费者应优先走子路径**,
272
+ 避免把构建期代码拉进运行时依赖图。
273
+
274
+ ### 为什么暂不拆包(决策记录)
275
+
276
+ 拆成 `suite-kit-build` / `suite-kit-runtime` 两个包会破坏既有项目的 import 面
277
+ (架构审查 M7/P2-12 统计涉及 9 个项目;本轮 grep 实证至少包括 A/projects 的
278
+ capyclaw/rsp/conductor 工作台、A/build 构建脚本、B/official/capyclaw-offline-ddr0、
279
+ C/tools/capyclaw-plugin-generator),所有消费者都要同步改 import 与依赖声明。
280
+ 而两类模块已按子路径隔离、依赖方向单向,实际耦合成本低。**收益不抵成本,暂不拆包**,
281
+ 改为以本节 + package.json description + 主入口头注释显式文档化双重身份。
282
+ 将来若确需拆包,应先把所有消费者迁到子路径 import,再做物理拆分。
283
+
234
284
  ## 设计边界
235
285
 
236
- - 这个包是**开发/安装工具**,不是 DSH 运行时插件;不会出现在 agent 工具面里。
286
+ - 这个包不是 DSH 运行时插件,不会出现在 agent 工具面里;但它有**双重身份**——
287
+ 构建期库 + 运行时库(运行时协议原语被套件工作台 import),见上节「双重身份」。
237
288
  - 组合层不替子包做业务;它只负责“谁和谁一起跑、怎么验证、冲突在哪”。
238
289
  - 运行时通信用 Cordis service / MCP / HTTP;suite-kit 不创建跨进程总线。
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capyclaw/suite-kit",
3
3
  "version": "0.2.0",
4
- "description": "DSH suite/domain 清单校验与组合工具:manifest 校验、compose、profile 生成、domain 解析、统一能力描述符、编排闸/授权、嵌入握手。",
4
+ "description": "DSH suite/domain 标准件(双重身份:构建期库 + 运行时库,暂不拆包,见 README「双重身份」)。构建期:manifest 校验、compose、profile 生成、domain 解析、artifact 打包;运行时:统一能力描述符、编排闸/授权、嵌入握手与 surface 挂载。",
5
5
  "type": "module",
6
6
  "main": "./src/index.mjs",
7
7
  "exports": {
@@ -13,6 +13,7 @@
13
13
  "./orchestration": "./src/orchestration.mjs",
14
14
  "./embed": "./src/embed.mjs",
15
15
  "./surface": "./src/surface.mjs",
16
+ "./host": "./src/host.mjs",
16
17
  "./client/embed.js": "./client/embed.js",
17
18
  "./profile": "./src/profile.mjs",
18
19
  "./artifacts": "./src/artifacts.mjs",
@@ -38,6 +39,9 @@
38
39
  "engines": {
39
40
  "node": ">=18"
40
41
  },
42
+ "dependencies": {
43
+ "@capyclaw/plugin-kit": "^0.2.6"
44
+ },
41
45
  "license": "MIT",
42
46
  "publishConfig": {
43
47
  "access": "public"