@capyclaw/suite-kit 0.2.0 → 0.2.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 (36) hide show
  1. package/README.md +52 -1
  2. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  3. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  4. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  5. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  6. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  7. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  8. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  9. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  10. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  11. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  12. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  13. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  14. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  15. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  16. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  17. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  18. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  19. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  20. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  21. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  22. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  23. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  24. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  25. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  26. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  27. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  28. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  29. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  30. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  31. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  32. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  33. package/package.json +9 -3
  34. package/src/host.mjs +230 -0
  35. package/src/index.mjs +14 -0
  36. package/suite.schema.json +16 -0
@@ -0,0 +1,181 @@
1
+ /**
2
+ * 极简跨平台 ZIP 读写(store + deflate 读,store 写;无外部依赖)——全仓单一真源。
3
+ *
4
+ * 之前三处实现各持一份(plugin-development 写 / tools-plugin-release 读 /
5
+ * @capyclaw/suite-kit zip-read 读),本模块合并之。旧位置保留兼容 shim。
6
+ *
7
+ * 写入:store 模式(内容不压缩,跨平台稳定,产物可被任何标准读取器读)。
8
+ * 读取:支持 store(0) 与 deflate(8);接受 Buffer 或文件路径——本地文件与
9
+ * 远端下载源共用同一条校验/解包路径。
10
+ */
11
+ import fs from 'node:fs'
12
+ import path from 'node:path'
13
+ import zlib from 'node:zlib'
14
+
15
+ /* ------------------------------------------------------------------ 写入 */
16
+
17
+ const CRC_TABLE = (() => {
18
+ const table = new Uint32Array(256)
19
+ for (let n = 0; n < 256; n++) {
20
+ let c = n
21
+ for (let k = 0; k < 8; k++) c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1)
22
+ table[n] = c >>> 0
23
+ }
24
+ return table
25
+ })()
26
+
27
+ function crc32(buffer) {
28
+ let crc = 0xffffffff
29
+ for (let i = 0; i < buffer.length; i++) crc = CRC_TABLE[(crc ^ buffer[i]) & 0xff] ^ (crc >>> 8)
30
+ return (crc ^ 0xffffffff) >>> 0
31
+ }
32
+
33
+ function dosDateTime(date = new Date()) {
34
+ const year = Math.max(1980, date.getFullYear())
35
+ const time = ((date.getHours() & 0x1f) << 11) | ((date.getMinutes() & 0x3f) << 5) | (Math.floor(date.getSeconds() / 2) & 0x1f)
36
+ const day = (((year - 1980) & 0x7f) << 9) | (((date.getMonth() + 1) & 0x0f) << 5) | (date.getDate() & 0x1f)
37
+ return { time, day }
38
+ }
39
+
40
+ function walkFiles(dir, base = dir) {
41
+ const out = []
42
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
43
+ const full = path.join(dir, entry.name)
44
+ if (entry.isDirectory()) out.push(...walkFiles(full, base))
45
+ else if (entry.isFile()) out.push(path.relative(base, full).replace(/\\/g, '/'))
46
+ }
47
+ return out.sort()
48
+ }
49
+
50
+ /** 把目录写成 store 模式 ZIP。返回打包的相对路径列表。 */
51
+ export function writeZipFromDir(sourceDir, outFile) {
52
+ const files = walkFiles(sourceDir)
53
+ const now = dosDateTime()
54
+ const localParts = []
55
+ const centralParts = []
56
+ let offset = 0
57
+
58
+ for (const name of files) {
59
+ const data = fs.readFileSync(path.join(sourceDir, name))
60
+ const nameBytes = Buffer.from(name, 'utf8')
61
+ const crc = crc32(data)
62
+
63
+ const local = Buffer.alloc(30)
64
+ local.writeUInt32LE(0x04034b50, 0)
65
+ local.writeUInt16LE(20, 4)
66
+ local.writeUInt16LE(0x0800, 6)
67
+ local.writeUInt16LE(0, 8)
68
+ local.writeUInt16LE(now.time, 10)
69
+ local.writeUInt16LE(now.day, 12)
70
+ local.writeUInt32LE(crc, 14)
71
+ local.writeUInt32LE(data.length, 18)
72
+ local.writeUInt32LE(data.length, 22)
73
+ local.writeUInt16LE(nameBytes.length, 26)
74
+ local.writeUInt16LE(0, 28)
75
+ localParts.push(local, nameBytes, data)
76
+
77
+ const central = Buffer.alloc(46)
78
+ central.writeUInt32LE(0x02014b50, 0)
79
+ central.writeUInt16LE(20, 4)
80
+ central.writeUInt16LE(20, 6)
81
+ central.writeUInt16LE(0x0800, 8)
82
+ central.writeUInt16LE(0, 10)
83
+ central.writeUInt16LE(now.time, 12)
84
+ central.writeUInt16LE(now.day, 14)
85
+ central.writeUInt32LE(crc, 16)
86
+ central.writeUInt32LE(data.length, 20)
87
+ central.writeUInt32LE(data.length, 24)
88
+ central.writeUInt16LE(nameBytes.length, 28)
89
+ central.writeUInt16LE(0, 30)
90
+ central.writeUInt16LE(0, 32)
91
+ central.writeUInt16LE(0, 34)
92
+ central.writeUInt16LE(0, 36)
93
+ central.writeUInt32LE(0, 38)
94
+ central.writeUInt32LE(offset, 42)
95
+ centralParts.push(central, nameBytes)
96
+
97
+ offset += local.length + nameBytes.length + data.length
98
+ }
99
+
100
+ const centralBuffer = Buffer.concat(centralParts)
101
+ const eocd = Buffer.alloc(22)
102
+ eocd.writeUInt32LE(0x06054b50, 0)
103
+ eocd.writeUInt16LE(0, 4)
104
+ eocd.writeUInt16LE(0, 6)
105
+ eocd.writeUInt16LE(files.length, 8)
106
+ eocd.writeUInt16LE(files.length, 10)
107
+ eocd.writeUInt32LE(centralBuffer.length, 12)
108
+ eocd.writeUInt32LE(offset, 16)
109
+ eocd.writeUInt16LE(0, 20)
110
+
111
+ fs.mkdirSync(path.dirname(outFile), { recursive: true })
112
+ fs.writeFileSync(outFile, Buffer.concat([...localParts, centralBuffer, eocd]))
113
+ return files
114
+ }
115
+
116
+ /* ------------------------------------------------------------------ 读取 */
117
+
118
+ function locateEocd(data, label) {
119
+ for (let i = data.length - 22; i >= 0; i--) {
120
+ if (data.readUInt32LE(i) === 0x06054b50) return i
121
+ }
122
+ throw new Error(`不是有效的 ZIP: ${label}`)
123
+ }
124
+
125
+ /**
126
+ * 列出 ZIP 全部条目名。
127
+ * @param {Buffer|string} input - ZIP 字节或文件路径
128
+ */
129
+ export function listZipEntryNames(input, label = 'zip') {
130
+ const data = Buffer.isBuffer(input) ? input : fs.readFileSync(input)
131
+ const eocd = locateEocd(data, label)
132
+ const count = data.readUInt16LE(eocd + 10)
133
+ let offset = data.readUInt32LE(eocd + 16)
134
+ const names = []
135
+ for (let i = 0; i < count; i++) {
136
+ if (data.readUInt32LE(offset) !== 0x02014b50) throw new Error(`ZIP 中央目录损坏: ${label}`)
137
+ const nameLength = data.readUInt16LE(offset + 28)
138
+ const extraLength = data.readUInt16LE(offset + 30)
139
+ const commentLength = data.readUInt16LE(offset + 32)
140
+ names.push(data.subarray(offset + 46, offset + 46 + nameLength).toString('utf8'))
141
+ offset += 46 + nameLength + extraLength + commentLength
142
+ }
143
+ return names
144
+ }
145
+
146
+ /**
147
+ * 从 ZIP 读单个条目的原始字节;不存在返回 undefined。
148
+ * @param {Buffer|string} input - ZIP 字节或文件路径
149
+ */
150
+ export function readZipEntryBuffer(input, entryName, label = 'zip') {
151
+ const data = Buffer.isBuffer(input) ? input : fs.readFileSync(input)
152
+ const eocd = locateEocd(data, label)
153
+ const count = data.readUInt16LE(eocd + 10)
154
+ let offset = data.readUInt32LE(eocd + 16)
155
+ for (let i = 0; i < count; i++) {
156
+ if (data.readUInt32LE(offset) !== 0x02014b50) throw new Error(`ZIP 中央目录损坏: ${label}`)
157
+ const method = data.readUInt16LE(offset + 10)
158
+ const compSize = data.readUInt32LE(offset + 20)
159
+ const nameLength = data.readUInt16LE(offset + 28)
160
+ const extraLength = data.readUInt16LE(offset + 30)
161
+ const commentLength = data.readUInt16LE(offset + 32)
162
+ const localOffset = data.readUInt32LE(offset + 42)
163
+ const name = data.subarray(offset + 46, offset + 46 + nameLength).toString('utf8')
164
+ if (name === entryName) {
165
+ const localNameLength = data.readUInt16LE(localOffset + 26)
166
+ const localExtraLength = data.readUInt16LE(localOffset + 28)
167
+ const start = localOffset + 30 + localNameLength + localExtraLength
168
+ const body = data.subarray(start, start + compSize)
169
+ if (method === 0) return body
170
+ if (method === 8) return zlib.inflateRawSync(body)
171
+ throw new Error(`不支持的 ZIP 压缩方式 ${method}: ${label}`)
172
+ }
173
+ offset += 46 + nameLength + extraLength + commentLength
174
+ }
175
+ return undefined
176
+ }
177
+
178
+ /** 读取 ZIP 中央目录条目名(文件路径版;打包自检/测试用)。 */
179
+ export function listZipEntries(file) {
180
+ return listZipEntryNames(fs.readFileSync(file), file)
181
+ }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@capyclaw/suite-kit",
3
- "version": "0.2.0",
4
- "description": "DSH suite/domain 清单校验与组合工具:manifest 校验、compose、profile 生成、domain 解析、统一能力描述符、编排闸/授权、嵌入握手。",
3
+ "version": "0.2.1",
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"
@@ -51,5 +55,7 @@
51
55
  "url": "https://github.com/Maple496/capyclaw/issues"
52
56
  },
53
57
  "homepage": "https://github.com/Maple496/capyclaw/tree/main/C/packages/capyclaw-suite-kit#readme",
54
- "bundledDependencies": []
58
+ "bundledDependencies": [
59
+ "@capyclaw/plugin-kit"
60
+ ]
55
61
  }
package/src/host.mjs ADDED
@@ -0,0 +1,230 @@
1
+ /**
2
+ * 套件宿主脚手架(P1-9「新套件宿主胶水抽共享」):capyclaw/conductor/rsp 三个
3
+ * 「新套件」宿主 lib/host.mjs 的公共胶水收敛到这里,未来新套件按同一 spec 接入。
4
+ *
5
+ * 封装的公共胶水(与三宿主原实现行为等价):
6
+ * 1. safeGet 服务懒解析(ctx.reflect.get 优先,回退 ctx[name],异常→null);
7
+ * 2. toolHost/serviceHost 缺席 bail+warn(降级不崩宿主)+ assertServiceApi major 断言;
8
+ * 3. 路由冲突先 probe 占位再 listen(2026-11-19 崩溃教训:前缀路由全局唯一,
9
+ * service-host app.listen 是 async,冲突变 rejected Promise 逃出 try/catch,
10
+ * 被 cordis 当 load failure 杀掉整个宿主);listen rejection 再 .catch 兜底;
11
+ * 4. 原生工具面 registerWithDsh(safeGet 解析 tools 服务后传平对象);
12
+ * 5. 能力描述符 publish/unpublish(validateCapabilityDescriptor 深度校验);
13
+ * 6. `${mountPath}/__host__` 自检端点(hostInfo 钩子补各套件差异字段);
14
+ * 7. portal.recordActivity(portal 可选);
15
+ * 8. disposers 逆序释放(每个 try/catch,重复释放安全);
16
+ * 9. DIAG 日志 env 门控(CAPYCLAW_WB_DIAG=1 才写 os.tmpdir()/<ns>-diag.log,默认不写盘)。
17
+ *
18
+ * 宿主差异经 spec 钩子注入(prepare/afterListen/afterTools/routes/hostInfo),
19
+ * 钩子拿到的 push() 把 disposer 压入公共栈,释放顺序与手写时代一致。
20
+ *
21
+ * 依赖方向:运行时模块。内部仅 import ./capability.mjs;外部仅
22
+ * @capyclaw/plugin-kit/service/api(纯契约断言,无副作用)。不 import 构建期模块。
23
+ */
24
+ import fs from 'node:fs'
25
+ import os from 'node:os'
26
+ import path from 'node:path'
27
+ import { assertServiceApi } from '@capyclaw/plugin-kit/service/api'
28
+ import { validateCapabilityDescriptor } from './capability.mjs'
29
+
30
+ /**
31
+ * 服务懒解析:cordis 未 inject 的服务直接访问 ctx[name] 可能抛错,
32
+ * 统一走 reflect.get(权威)→ ctx[name](兜底)→ null(缺席降级)。
33
+ * @param {object} ctx cordis 上下文
34
+ * @param {string} serviceName 服务名
35
+ * @returns {object|null}
36
+ */
37
+ export function safeGet(ctx, serviceName) {
38
+ try { return ctx.reflect?.get?.(serviceName) ?? ctx[serviceName] } catch { return null }
39
+ }
40
+
41
+ /**
42
+ * workStore 可选解析:优先 foundation 的 os.works 能力面(内核 getter 返回
43
+ * work-store 服务或 null),回退 safeGet(ctx,'workStore')。两者皆缺席返回 null,
44
+ * 消费者自行降级内存态(语义与旧 safeGet 裸摸一致)。
45
+ * @param {object} ctx cordis 上下文
46
+ * @returns {object|null}
47
+ */
48
+ export function resolveWorkStore(ctx) {
49
+ try {
50
+ const osSvc = safeGet(ctx, 'os')
51
+ const works = osSvc ? osSvc.works : null
52
+ if (works) return works
53
+ } catch { /* os.works getter 异常 → 落回裸摸兜底 */ }
54
+ return safeGet(ctx, 'workStore') ?? null
55
+ }
56
+
57
+ /**
58
+ * @typedef {object} SuiteHostSpec
59
+ * @property {string} ns 宿主名(如 'conductor-workbench'):__host__.name / portal id /
60
+ * 日志与警告前缀 / diag 文件名 `<ns>-diag.log`。
61
+ * @property {string} suite 套件短名(如 'conductor'):缺服务 bail 警告里的 `<suite>-suite`。
62
+ * @property {string} mountPath 默认挂载前缀(config.mountPath 可覆盖)。
63
+ * @property {string} title portal.recordActivity 标题。
64
+ * @property {Array<{name:string}>} descriptors 本套件描述符清单(释放时逐个 unregister)。
65
+ * @property {(api:HostApi & {extra:object}) => object} createWorkbench 工厂:返回
66
+ * { app, registry, publishDescriptors(baseUrl,{validate}), ... }(各套件 workbench.mjs)。
67
+ * @property {(api:HostApi) => object|false} [prepare] 断言后、建 workbench 前的差异装配
68
+ * (capyclaw 的 sessionPort/session-watch、conductor 的 discoverCapabilities 闸 + workStore)。
69
+ * 返回 false(或 {bail:true})= 放弃挂载(钩子内已自行 warn/diag),返回对象 = extra。
70
+ * @property {(api:HostApi & {workbench:object, extra:object, webServer:object|null}) => void} [afterListen]
71
+ * listen 之后、工具注册之前的钩子(rsp:manager.close disposer + bindToolsToSessionMode)。
72
+ * @property {(api:HostApi & {workbench:object, extra:object, webServer:object|null}) => void} [afterTools]
73
+ * 工具注册之后、描述符发布之前的钩子(rsp:startPersistent)。
74
+ * @property {(args:{webServer:object, workbench:object, extra:object, push:(d:Function)=>void, log:object}) => void} [routes]
75
+ * __host__ 之后的额外固定端点(capyclaw 的 agent-pending/host-pending)。仅 webServer.register 可用时调用。
76
+ * @property {(workbench:object, extra:object) => object} [hostInfo] __host__ 响应附加字段
77
+ * (请求时求值;capyclaw: available、conductor: persisted、rsp: protocol/status)。
78
+ * @property {boolean} [descriptorsRequired] true = 无条件 publish(conductor 已在 prepare
79
+ * 里因缺 discoverCapabilities bail,描述符面必然在场);缺省 = 探测
80
+ * registerCapabilityDescriptor,缺席 warn 跳过(capyclaw/rsp 降级语义)。
81
+ * @property {string} [diagTag] diag 消息短标签(缺省 ns 去掉 '-workbench' 后缀)。
82
+ * @property {(toolHost:object|null) => string} [diagApplyExtra] apply diag 行附加段
83
+ * (conductor 的 ` discover=...`)。
84
+ */
85
+
86
+ /**
87
+ * 钩子公共参数面。
88
+ * @typedef {object} HostApi
89
+ * @property {object} ctx cordis 上下文
90
+ * @property {object} config 插件配置(mountPath/port/version/...)
91
+ * @property {string} mountPath 生效挂载前缀(config.mountPath || spec.mountPath)
92
+ * @property {object} toolHost 已断言 major 1 的工具宿主服务
93
+ * @property {object} serviceHost 已断言 major 1 的服务宿主服务
94
+ * @property {(ctx:object, name:string) => object|null} safeGet 服务懒解析
95
+ * @property {{info:Function, warn:Function}} log ctx.logger 优先、console 兜底
96
+ * @property {(m:string) => void} diag env 门控诊断日志(默认不写盘)
97
+ * @property {(d:Function) => void} push 压入公共 disposer 栈(逆序释放)
98
+ */
99
+
100
+ /**
101
+ * 挂载一个套件工作台:返回 disposer(与 cordis apply 契约一致)。
102
+ * 任何失败都降级为 warn + 安全 disposer,绝不把路由冲突/服务缺席升级成宿主崩溃。
103
+ * @param {object} ctx cordis 上下文
104
+ * @param {object} [config] 插件配置
105
+ * @param {SuiteHostSpec} spec 套件差异规格
106
+ * @returns {() => void} disposer(逆序释放全部已登记资源;重复调用安全)
107
+ */
108
+ export function mountSuiteWorkbench(ctx, config = {}, spec) {
109
+ const { ns, suite, title, descriptors = [], createWorkbench } = spec
110
+ const tag = spec.diagTag || String(ns || '').replace(/-workbench$/, '')
111
+ /* 诊断日志默认关闭;设 CAPYCLAW_WB_DIAG=1 时写到系统临时目录(不硬编码任何本机路径)。 */
112
+ const DIAG_LOG = process.env.CAPYCLAW_WB_DIAG ? path.join(os.tmpdir(), `${ns}-diag.log`) : null
113
+ const diag = (m) => { if (!DIAG_LOG) return; try { fs.appendFileSync(DIAG_LOG, `[${new Date().toISOString()}] ${m}\n`) } catch { /* 忽略 */ } }
114
+ const log = {
115
+ info: (...a) => (ctx.logger?.info ? ctx.logger.info(...a) : console.log(`[${tag}]`, ...a)),
116
+ warn: (...a) => (ctx.logger?.warn ? ctx.logger.warn(...a) : console.warn(`[${tag}]`, ...a)),
117
+ }
118
+ const mountPath = config.mountPath || spec.mountPath
119
+ const disposers = []
120
+ const push = (d) => { if (typeof d === 'function') disposers.push(d) }
121
+ // splice(0) 清空栈再逆序:首次释放顺序与手写时代一致,重复释放是真 no-op
122
+ // (原 disposers.reverse() 原地反转,二次调用会重跑——与「忽略重复释放」注释意图相悖)。
123
+ const releaseAll = () => { for (const d of disposers.splice(0).reverse()) { try { d() } catch { /* 忽略重复释放 */ } } }
124
+ const noop = () => {}
125
+
126
+ try {
127
+ if (!ns || !suite || !mountPath || !title || typeof createWorkbench !== 'function') {
128
+ throw new Error('mountSuiteWorkbench: spec 需要 ns/suite/mountPath/title/createWorkbench')
129
+ }
130
+ const toolHost = safeGet(ctx, 'toolHost')
131
+ const serviceHost = safeGet(ctx, 'serviceHost')
132
+ diag(`${tag} apply: toolHost=${!!toolHost} serviceHost=${!!serviceHost} webServer=${!!safeGet(ctx, 'webServer')} reflect=${!!ctx.reflect}${spec.diagApplyExtra ? spec.diagApplyExtra(toolHost) : ''}`)
133
+ if (!toolHost || !serviceHost) {
134
+ diag(`${tag} BAIL: missing toolHost/serviceHost`)
135
+ log.warn(`缺少 toolHost/serviceHost 公共服务,${suite}-suite 未激活(请安装对应基础套件)`)
136
+ return noop
137
+ }
138
+ assertServiceApi(toolHost, { name: 'toolHost', major: 1 })
139
+ assertServiceApi(serviceHost, { name: 'serviceHost', major: 1 })
140
+
141
+ /** @type {HostApi} */
142
+ const api = { ctx, config, mountPath, toolHost, serviceHost, safeGet, log, diag, push }
143
+ let extra = {}
144
+ if (spec.prepare) {
145
+ const prepared = spec.prepare(api)
146
+ if (prepared === false || (prepared && prepared.bail === true)) return noop
147
+ if (prepared && typeof prepared === 'object') extra = prepared
148
+ }
149
+
150
+ const workbench = createWorkbench({ ...api, extra })
151
+
152
+ const webServer = safeGet(ctx, 'webServer')
153
+
154
+ // 前缀路由是全局唯一的(dsh-host-webserver 的 register 遇到同 (kind,path) 直接抛)。
155
+ // service-host 的 app.listen 是 async:冲突会变成 rejected Promise,而不是同步抛错。
156
+ // 不 await、也不 .catch 的话,冲突逃出外层 try/catch,被 cordis 当成 load failure
157
+ // 杀掉整个宿主(2026-11-19 两次:安全模式回滚把用户 patch 层清空)。
158
+ // 先探一次占位,冲突就只警告并退出本条目,绝不把路由冲突升级成宿主崩溃。
159
+ if (webServer && typeof webServer.register === 'function') {
160
+ let taken = false
161
+ try {
162
+ const probe = webServer.register({ kind: 'prefix', path: mountPath, handler: () => {} })
163
+ if (typeof probe === 'function') probe()
164
+ } catch {
165
+ taken = true
166
+ }
167
+ if (taken) {
168
+ diag(`${tag} BAIL: prefix ${mountPath} already registered`)
169
+ log.warn(`${ns}: 路由前缀 ${mountPath} 已被占用,本条目不挂载(不影响其它插件)`)
170
+ return noop
171
+ }
172
+ }
173
+
174
+ const listenOpts = webServer ? { webServer, basePath: mountPath } : { port: config.port || 0 }
175
+ const listening = workbench.app.listen(listenOpts)
176
+ // 兜底:即使上面的探测有竞态,也把 rejection 收在这里,不让它变成未处理拒绝。
177
+ if (listening && typeof listening.catch === 'function') {
178
+ listening.catch((err) => {
179
+ diag(`${tag} listen rejected: ${err?.stack || err}`)
180
+ log.warn(`${ns}: 挂载 ${mountPath} 失败,本条目不生效:`, err?.message || err)
181
+ try { workbench.app.close() } catch { /* 忽略 */ }
182
+ })
183
+ }
184
+ push(() => workbench.app.close())
185
+
186
+ if (spec.afterListen) spec.afterListen({ ...api, workbench, extra, webServer })
187
+
188
+ // 原生工具面:safeGet 解析 tools 服务后传平对象,避免 cordis 未 inject 禁访问 ctx.tools。
189
+ const tools = safeGet(ctx, 'tools')
190
+ if (tools?.register) {
191
+ const { registerWithDsh } = toolHost
192
+ push(registerWithDsh({ tools }, workbench.registry))
193
+ }
194
+
195
+ if (spec.afterTools) spec.afterTools({ ...api, workbench, extra, webServer })
196
+
197
+ // 能力描述符 + 调用地址 → 公共注册表(供 conductor 发现)。
198
+ if (spec.descriptorsRequired || typeof toolHost.registerCapabilityDescriptor === 'function') {
199
+ workbench.publishDescriptors(workbench.app.url, { validate: validateCapabilityDescriptor })
200
+ push(() => { for (const d of descriptors) toolHost.unregisterCapabilityDescriptor?.(d.name) })
201
+ } else {
202
+ log.warn(`toolHost 无描述符面(需 >=0.2.0):跳过能力注册,conductor 将无法发现 ${suite}`)
203
+ }
204
+
205
+ // 自检端点。
206
+ if (webServer?.register) {
207
+ const off = webServer.register({
208
+ kind: 'exact', path: `${mountPath}/__host__`,
209
+ handler: (req, res) => {
210
+ res.writeHead(200, { 'content-type': 'application/json' })
211
+ res.end(JSON.stringify({ ok: true, name: ns, mountPath, url: workbench.app.url, ...(spec.hostInfo ? spec.hostInfo(workbench, extra) : {}) }))
212
+ },
213
+ })
214
+ push(off)
215
+ }
216
+
217
+ if (spec.routes && webServer?.register) spec.routes({ webServer, workbench, extra, push, log })
218
+
219
+ const portal = safeGet(ctx, 'portal')
220
+ portal?.recordActivity?.({ id: ns, url: workbench.app.url, title, kind: 'service' })
221
+
222
+ log.info(`${ns} 已挂载 ${mountPath} → ${workbench.app.url}`)
223
+ diag(`${tag} MOUNTED ${mountPath} → ${workbench.app.url}`)
224
+ return releaseAll
225
+ } catch (err) {
226
+ diag(`${tag} ERROR: ${err?.stack || err}`)
227
+ log.warn(`${ns} 激活失败:`, err?.stack || err)
228
+ return releaseAll
229
+ }
230
+ }
package/src/index.mjs CHANGED
@@ -1,8 +1,22 @@
1
+ // @capyclaw/suite-kit 主入口(P2-12:双重身份显式文档化,暂不拆包)。
2
+ // 本包同时是:
3
+ // 构建期库 —— manifest/compose/profile/domain/artifacts/activation-registry
4
+ // (清单校验、组合、profile 安装、领域解析、artifact 打包);
5
+ // 运行时库 —— capability/orchestration/embed/surface/host(能力描述符、编排闸/Mandate/
6
+ // 事件、嵌入握手、surface 挂载、套件宿主脚手架),被 capyclaw/rsp/conductor 等
7
+ // 套件工作台在运行时 import。
8
+ // 依赖方向严格单向:运行时模块绝不 import 构建期模块(运行时内部 surface → embed、
9
+ // host → capability;host 另依赖 @capyclaw/plugin-kit/service/api 纯契约断言)。
10
+ // 根入口 export * 同时导出两类;运行时消费者应优先走子路径(./capability 等),
11
+ // 避免把构建期代码拉进运行时依赖图。
12
+ // 为什么不拆:拆包会破坏 9 个项目的 import 面,收益不抵成本;
13
+ // 决策记录与模块归属清单见 README「双重身份:构建期库 + 运行时库」。
1
14
  export * from './manifest.mjs'
2
15
  export * from './capability.mjs'
3
16
  export * from './orchestration.mjs'
4
17
  export * from './embed.mjs'
5
18
  export * from './surface.mjs'
19
+ export * from './host.mjs'
6
20
  export * from './compose.mjs'
7
21
  export * from './profile.mjs'
8
22
  export * from './domain.mjs'
package/suite.schema.json CHANGED
@@ -54,6 +54,22 @@
54
54
  "additionalProperties": { "type": "string", "minLength": 1 }
55
55
  }
56
56
  }
57
+ },
58
+ "surfaceLifecycle": {
59
+ "type": "object",
60
+ "additionalProperties": false,
61
+ "required": ["hooks", "headlessObservation"],
62
+ "description": "表面可见性生命周期标准声明(docs/SURFACE-LIFECYCLE-STANDARD.md §6):四个渲染面钩子齐全 + 无头观察兜底。协议真源 C/packages/capyclaw-foundation/abi/visibility.mjs。",
63
+ "properties": {
64
+ "hooks": {
65
+ "type": "array",
66
+ "items": { "enum": ["onVisibility", "suspendRender", "resumeRender", "rehydrate"] },
67
+ "minItems": 4,
68
+ "maxItems": 4,
69
+ "uniqueItems": true
70
+ },
71
+ "headlessObservation": { "const": true }
72
+ }
57
73
  }
58
74
  }
59
75
  }