@capyclaw/wall-suite 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 (156) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +20 -2
  3. package/composition.lock.json +48 -0
  4. package/contract/wall-contract.json +8 -0
  5. package/cordis.patch.yml +6 -0
  6. package/dsh-suite.json +128 -0
  7. package/lib/index.mjs +6 -0
  8. package/node_modules/@capyclaw/asset-service/README.md +48 -0
  9. package/node_modules/@capyclaw/asset-service/cordis.patch.yml +4 -0
  10. package/node_modules/@capyclaw/asset-service/dsh-suite.json +29 -0
  11. package/node_modules/@capyclaw/asset-service/lib/host.mjs +14 -0
  12. package/node_modules/@capyclaw/asset-service/package.json +59 -0
  13. package/node_modules/@capyclaw/asset-service/src/index.mjs +310 -0
  14. package/node_modules/@capyclaw/foundation/README.md +51 -0
  15. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  16. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  17. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  18. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  19. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  20. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  21. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  22. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  23. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  24. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  25. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  26. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  27. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  34. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  35. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  36. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  37. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  38. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  39. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  40. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  41. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  42. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  43. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  44. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  45. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  46. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  47. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  48. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  49. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  50. package/node_modules/@capyclaw/foundation/package.json +53 -0
  51. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  52. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  53. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  54. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  55. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  78. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  79. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  80. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  81. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  82. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  83. package/node_modules/@capyclaw/portal/README.md +70 -0
  84. package/node_modules/@capyclaw/portal/lib/index.mjs +387 -0
  85. package/node_modules/@capyclaw/portal/lib/ledger.mjs +194 -0
  86. package/node_modules/@capyclaw/portal/lib/portal-agent.ps1 +811 -0
  87. package/node_modules/@capyclaw/portal/lib/portal-darwin.mjs +183 -0
  88. package/node_modules/@capyclaw/portal/package.json +40 -0
  89. package/node_modules/@capyclaw/service-broker/README.md +104 -0
  90. package/node_modules/@capyclaw/service-broker/cordis.patch.yml +8 -0
  91. package/node_modules/@capyclaw/service-broker/dsh-suite.json +21 -0
  92. package/node_modules/@capyclaw/service-broker/lib/control.mjs +209 -0
  93. package/node_modules/@capyclaw/service-broker/lib/discovery.mjs +109 -0
  94. package/node_modules/@capyclaw/service-broker/lib/engine.mjs +1290 -0
  95. package/node_modules/@capyclaw/service-broker/lib/host.mjs +187 -0
  96. package/node_modules/@capyclaw/service-broker/lib/manifest.mjs +262 -0
  97. package/node_modules/@capyclaw/service-broker/lib/recovery.mjs +275 -0
  98. package/node_modules/@capyclaw/service-broker/lib/skills-client.mjs +48 -0
  99. package/node_modules/@capyclaw/service-broker/lib/spec.mjs +78 -0
  100. package/node_modules/@capyclaw/service-broker/package.json +65 -0
  101. package/node_modules/@capyclaw/service-broker/server.mjs +81 -0
  102. package/node_modules/@capyclaw/service-broker/service.schema.json +62 -0
  103. package/node_modules/@capyclaw/service-broker/services.json +3 -0
  104. package/node_modules/@capyclaw/service-host/README.md +86 -0
  105. package/node_modules/@capyclaw/service-host/cordis.patch.yml +4 -0
  106. package/node_modules/@capyclaw/service-host/dsh-suite.json +29 -0
  107. package/node_modules/@capyclaw/service-host/lib/host.mjs +22 -0
  108. package/node_modules/@capyclaw/service-host/package.json +60 -0
  109. package/node_modules/@capyclaw/service-host/src/index.mjs +570 -0
  110. package/node_modules/@capyclaw/service-host/src/tuning.mjs +63 -0
  111. package/node_modules/@capyclaw/tool-host/README.md +56 -0
  112. package/node_modules/@capyclaw/tool-host/cordis.patch.yml +4 -0
  113. package/node_modules/@capyclaw/tool-host/dsh-suite.json +30 -0
  114. package/node_modules/@capyclaw/tool-host/lib/host.mjs +46 -0
  115. package/node_modules/@capyclaw/tool-host/package.json +59 -0
  116. package/node_modules/@capyclaw/tool-host/src/admit-images.mjs +80 -0
  117. package/node_modules/@capyclaw/tool-host/src/caller-session.mjs +25 -0
  118. package/node_modules/@capyclaw/tool-host/src/descriptors.mjs +166 -0
  119. package/node_modules/@capyclaw/tool-host/src/index.mjs +461 -0
  120. package/node_modules/@capyclaw/tool-host/src/mode-gate.mjs +272 -0
  121. package/node_modules/@capyclaw/wall-workbench/README.md +58 -0
  122. package/node_modules/@capyclaw/wall-workbench/contract/wall-contract.json +8 -0
  123. package/node_modules/@capyclaw/wall-workbench/lib/host.mjs +1 -0
  124. package/node_modules/@capyclaw/wall-workbench/package.json +63 -0
  125. package/node_modules/@capyclaw/wall-workbench/plugin.mjs +13 -0
  126. package/node_modules/@capyclaw/wall-workbench/server/activate-log.mjs +66 -0
  127. package/node_modules/@capyclaw/wall-workbench/server/constants.mjs +12 -0
  128. package/node_modules/@capyclaw/wall-workbench/server/contract.mjs +12 -0
  129. package/node_modules/@capyclaw/wall-workbench/server/embedded-host.mjs +162 -0
  130. package/node_modules/@capyclaw/wall-workbench/server/infra/http.mjs +2 -0
  131. package/node_modules/@capyclaw/wall-workbench/server/infra/tuning.mjs +2 -0
  132. package/node_modules/@capyclaw/wall-workbench/server/relay.mjs +68 -0
  133. package/node_modules/@capyclaw/wall-workbench/server/routes/claim.mjs +46 -0
  134. package/node_modules/@capyclaw/wall-workbench/server/routes/workbench.mjs +29 -0
  135. package/node_modules/@capyclaw/wall-workbench/server/shared/SHARED_MANIFEST.json +70 -0
  136. package/node_modules/@capyclaw/wall-workbench/server/shared/asset-service.mjs +2 -0
  137. package/node_modules/@capyclaw/wall-workbench/server/shared/editor-host.mjs +2 -0
  138. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/editor/lease.mjs +2 -0
  139. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/api.mjs +2 -0
  140. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/http.mjs +2 -0
  141. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/service/mcp-http.mjs +2 -0
  142. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tools/validate.mjs +2 -0
  143. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/tuning.mjs +2 -0
  144. package/node_modules/@capyclaw/wall-workbench/server/shared/kit/util/fs-lock.mjs +2 -0
  145. package/node_modules/@capyclaw/wall-workbench/server/shared/service-host.mjs +2 -0
  146. package/node_modules/@capyclaw/wall-workbench/server/shared/tool-host.mjs +2 -0
  147. package/node_modules/@capyclaw/wall-workbench/server/shared/tuning.mjs +2 -0
  148. package/node_modules/@capyclaw/wall-workbench/server/tools/capabilities/index.mjs +2 -0
  149. package/node_modules/@capyclaw/wall-workbench/server/tools/index.mjs +12 -0
  150. package/node_modules/@capyclaw/wall-workbench/server/tools.mjs +2 -0
  151. package/node_modules/@capyclaw/wall-workbench/server/workbench-framework.mjs +339 -0
  152. package/node_modules/@capyclaw/wall-workbench/ui/app.js +225 -0
  153. package/node_modules/@capyclaw/wall-workbench/ui/index.html +20 -0
  154. package/node_modules/@capyclaw/wall-workbench/ui/style.css +77 -0
  155. package/package.json +72 -4
  156. package/services.json +3 -0
@@ -0,0 +1,187 @@
1
+ /**
2
+ * @capyclaw/service-broker:中间件插件(cordis 入口)。
3
+ *
4
+ * 这是 dsh 进程内**唯一**允许存在的插件角色——它不承载任何业务,
5
+ * 只做三件事:
6
+ * 1. 按清单(config.manifest 指向 services.json)把各服务作为独立进程拉起;
7
+ * 2. 向同进程提供 ctx.serviceBroker(list/start/stop/apply 控制面);
8
+ * 3. 可选:config.skills.url 指向技能服务时,提供 ctx.skillsHttp 瘦客户端
9
+ * (数据来自 HTTP)。技能的标准路径是 skillProvider@1 进程内注册 →
10
+ * DSH 原生 SkillRegistry(ctx.skills);此 HTTP 路是 standalone 可选模式,
11
+ * 默认不启用。服务名用 skillsHttp 而非 skills,避免遮蔽原生注册表
12
+ * (详见 lib/skills-client.mjs 头注释,P1-10 决策)。
13
+ *
14
+ * 生命周期:keepAlive 服务(默认)不随插件卸载停止——服务独立于 dsh;
15
+ * config.stopOnUnload === true 时才随卸载全停。
16
+ */
17
+ import { defineDriver } from '@capyclaw/foundation/abi'
18
+ import { ServiceEngine } from './engine.mjs'
19
+ import { createControlServer } from './control.mjs'
20
+ import { createSkillsClient } from './skills-client.mjs'
21
+ import { loadManifest } from './manifest.mjs'
22
+
23
+ export const { name, inject, apply } = defineDriver({
24
+ name: 'service-broker',
25
+ service: 'serviceBroker',
26
+ async apply(ctx, config = {}) {
27
+ const engine = new ServiceEngine({
28
+ discoveryPath: config.discoveryPath,
29
+ logDir: config.logDir,
30
+ log: (msg) => console.log(`[service-broker] ${msg}`),
31
+ defaultWaitMs: Number(config.waitMs) || 20000,
32
+ })
33
+
34
+ const api = {
35
+ api: { name: 'serviceBroker', version: '1.0.0', capabilities: ['apply', 'start', 'stop', 'list', 'doctor'] },
36
+ engine,
37
+ discoveryPath: engine.discoveryPath,
38
+ list: () => engine.list(),
39
+ start: (spec, options) => engine.apply([{ op: 'up', service: spec }], options),
40
+ stop: (id) => engine.stop(id),
41
+ apply: (commands, options) => engine.apply(commands, options),
42
+ doctor: (id) => engine.doctor(id),
43
+ }
44
+ const disposeService = ctx.provide('serviceBroker', api)
45
+
46
+ // 技能瘦客户端(可选 standalone 模式,默认不启用):list/get 形状与进程内
47
+ // 注册表一致,数据源改为 HTTP 技能服务。服务名 skillsHttp——'skills' 归 DSH
48
+ // 原生 SkillRegistry,provide('skills') 会遮蔽它并令 skillProvider@1 插件
49
+ // 因缺 registerProvider 挂载失败(P1-10 决策,见 lib/skills-client.mjs)。
50
+ let disposeSkills = null
51
+ if (config.skills?.url) {
52
+ const client = createSkillsClient(config.skills.url)
53
+ disposeSkills = ctx.provide('skillsHttp', client)
54
+ console.log(`[service-broker] skillsHttp ← ${config.skills.url}`)
55
+ }
56
+
57
+ // 开机清单:有清单就按 up 命令投递给自己(幂等,复用优先)
58
+ //
59
+ // 这里**故意不阻塞**插件加载:broker 的依赖(relay)是独立进程,等它可能耗到
60
+ // 数十秒,而 dsh 的启动不该被一个慢服务拖住。代价是"服务就绪"与"消费者连接"
61
+ // 之间存在竞态,因此:
62
+ // - 暴露 `ctx.serviceBroker.ready`:需要确定性的调用方可以 await;
63
+ // - 失败时打印可操作的一行,而不是静默;
64
+ // - MCP 客户端侧用足够的 reconnect 预算兜住(见 A/build/bridge-build.mjs)。
65
+ const bootState = { done: false, ok: false, services: [], errors: [] }
66
+ let retryTimer = null
67
+ let disposed = false
68
+ const bootPromise = (async () => {
69
+ let services = []
70
+ /* manifest 显式给定时只吃那一份;只给 discover 时合并本 profile 全部套件。 */
71
+ const manifestRef = config.manifest ?? (config.discover ? 'auto' : undefined)
72
+ try { services = loadManifest(manifestRef) } catch (err) {
73
+ bootState.done = true
74
+ bootState.errors = [{ id: 'manifest', error: err.message }]
75
+ console.warn(`[service-broker] 清单加载失败: ${err.message}`)
76
+ return bootState
77
+ }
78
+ if (!services.length) {
79
+ bootState.done = true
80
+ bootState.ok = true
81
+ console.log('[service-broker] 无开机清单,待命(服务可经控制端点/ctx.serviceBroker 投递)')
82
+ return bootState
83
+ }
84
+ try {
85
+ const result = await engine.apply(services.map((service) => ({ op: 'up', service })))
86
+ bootState.done = true
87
+ bootState.services = result.services
88
+ bootState.errors = result.errors
89
+ bootState.ok = result.errors.length === 0
90
+ for (const err of result.errors) console.warn(`[service-broker] ✗ ${err.id}: ${err.error}`)
91
+ if (bootState.ok) {
92
+ console.log(`[service-broker] 开机清单完成:${result.services.length} 个服务就绪`)
93
+ } else {
94
+ console.warn(`[service-broker] 开机清单部分失败:${result.services.length} 就绪 / ${result.errors.length} 失败;按退避重试`)
95
+ retryFailed(services, new Set(result.errors.map((err) => err.id)))
96
+ }
97
+ } catch (err) {
98
+ bootState.done = true
99
+ bootState.errors = [{ id: 'boot', error: err.message }]
100
+ console.warn(`[service-broker] 开机清单投递失败: ${err.message}`)
101
+ retryFailed(services, new Set(services.map((service) => service.id)))
102
+ }
103
+ return bootState
104
+ })()
105
+
106
+ /**
107
+ * 开机失败退避重试:一次性失败(端口刚被释放、上一个进程还在退出、
108
+ * 磁盘/杀软偶发拦截)不该让服务整个会话都缺席。最多 6 次,3s 起步翻倍。
109
+ */
110
+ function retryFailed(all, failed, attempt = 0) {
111
+ if (disposed || !failed.size || attempt >= 6) return
112
+ const delay = Math.min(60000, 3000 * 2 ** attempt)
113
+ retryTimer = setTimeout(async () => {
114
+ retryTimer = null
115
+ if (disposed) return
116
+ const pending = all.filter((service) => failed.has(service.id))
117
+ if (!pending.length) return
118
+ try {
119
+ const result = await engine.apply(pending.map((service) => ({ op: 'up', service })))
120
+ for (const err of result.errors) console.warn(`[service-broker] ✗ 重试 ${err.id}: ${err.error}`)
121
+ const still = new Set(result.errors.map((err) => err.id))
122
+ if (still.size) retryFailed(all, still, attempt + 1)
123
+ else console.log(`[service-broker] 开机重试成功:${pending.length} 个服务就绪`)
124
+ } catch (err) {
125
+ console.warn(`[service-broker] 开机重试失败: ${err.message}`)
126
+ retryFailed(all, failed, attempt + 1)
127
+ }
128
+ }, delay)
129
+ retryTimer.unref?.()
130
+ }
131
+ api.ready = bootPromise
132
+ api.bootState = () => ({ ...bootState })
133
+
134
+ /* 可选的有限等待:只有显式配置 awaitBootMs 才阻塞激活,且绝不会超过该值。
135
+ * 给"必须等服务起来才继续"的宿主用;默认 0 = 不阻塞。 */
136
+ const awaitBootMs = Number(config.awaitBootMs) || 0
137
+ if (awaitBootMs > 0) {
138
+ await Promise.race([
139
+ bootPromise,
140
+ new Promise((resolve) => {
141
+ const timer = setTimeout(resolve, awaitBootMs)
142
+ timer.unref?.()
143
+ }),
144
+ ])
145
+ }
146
+
147
+ // 可选控制端点(embedded 一般不需要;外部投递走 standalone 形态)
148
+ let controlServer = null
149
+ if (Number(config.controlPort) > 0) {
150
+ controlServer = createControlServer(engine, {
151
+ token: process.env.DSH_BROKER_TOKEN,
152
+ manifestPath: config.manifest,
153
+ })
154
+ /* listen 是 async:端口冲突会变 rejected/error 事件。不接住就是未捕获异常,
155
+ * 被 cordis 当 load failure 杀掉整个宿主(与 conductor 2026-11-19 事故同类)。
156
+ * embedded 降级:控制面不可用但服务照常守护,绝不把端口冲突升级成宿主崩溃(P1-6)。 */
157
+ controlServer.on('error', (err) => {
158
+ console.error(`[service-broker] 控制端点启动失败(${err.code || err.message}):控制面不可用,服务照常守护;端口冲突请调整 controlPort`)
159
+ })
160
+ controlServer.listen(Number(config.controlPort), '127.0.0.1', () => {
161
+ console.log(`[service-broker] 控制端点 http://127.0.0.1:${config.controlPort}/control/*`)
162
+ console.log(controlServer.brokerTokenFile
163
+ ? `[service-broker] 控制面鉴权: 需要 x-broker-token,token 见 ${controlServer.brokerTokenFile}`
164
+ : '[service-broker] 控制面鉴权: 需要 x-broker-token(来自环境变量)')
165
+ })
166
+ }
167
+
168
+ engine.startGuard({
169
+ /* 2s 一轮存活检查:进程/端口一死,2 秒内拉回来("马上复活")。 */
170
+ intervalMs: Number(config.guardIntervalMs) || 2000,
171
+ maxConsecutive: Number(config.guardMaxConsecutive) || 3,
172
+ maxUnhealthy: Number(config.guardMaxUnhealthy) || 3,
173
+ requireTools: config.guardRequireTools !== false,
174
+ /* 健康+工具的深探按 15s 节流,避免频繁打 HTTP。 */
175
+ probeEveryMs: Number(config.guardProbeEveryMs) || 15000,
176
+ })
177
+
178
+ return async () => {
179
+ disposed = true
180
+ if (retryTimer) { clearTimeout(retryTimer); retryTimer = null }
181
+ if (controlServer) await new Promise((resolve) => controlServer.close(resolve))
182
+ if (typeof disposeService === 'function') await disposeService()
183
+ if (typeof disposeSkills === 'function') await disposeSkills()
184
+ await engine.shutdown({ stopAll: config.stopOnUnload === true })
185
+ }
186
+ },
187
+ })
@@ -0,0 +1,262 @@
1
+ /**
2
+ * 清单加载(host.mjs 与 server.mjs 共用)。
3
+ *
4
+ * - 未显式传 manifest 时,先按 **套件布局** 自动发现(从 broker 包目录向上找最近的
5
+ * 同时含 dsh-suite.json 与 services.json 的目录),找不到才退回本包 services.json;
6
+ * - manifest 里的 `${SUITE_DIR}` 展开为上面发现的套件根——套件 patch 用它把
7
+ * “服务中间件该拉什么”这件事写死成可移植字符串;
8
+ * - manifest 路径为相对路径时,相对 **broker 包目录**解析;
9
+ * - 清单里的 `${PACKAGE_DIR}` 展开为 **清单文件所在目录**——套件捆绑布局
10
+ * (zip 产物 / 源内 plugin 目录)下即套件根(services.json 与 node_modules/*
11
+ * 同层),同一份清单在 dev 树与安装态都能解析出正确绝对路径;
12
+ * - dsh 原生安装(pnpm hoisted / npm 提升)会把套件依赖提升到 profile 根
13
+ * node_modules,套件目录内没有 node_modules/<pkg>:展开后的脚本路径不存在
14
+ * 时,沿清单目录向上逐级定位提升后的真实位置(resolveHoistedScriptPath),
15
+ * 捆绑布局(路径本就存在)行为不变。
16
+ */
17
+ import { existsSync, readFileSync, readdirSync, realpathSync } from 'node:fs'
18
+ import os from 'node:os'
19
+ import path from 'node:path'
20
+ import { fileURLToPath } from 'node:url'
21
+ import { validateServiceManifest } from './spec.mjs'
22
+
23
+ export const PKG_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..')
24
+
25
+ /**
26
+ * 从 startDir 向上找“套件根”:同时存在 dsh-suite.json 与 services.json 的最近目录。
27
+ *
28
+ * 捆绑/源内布局:`<suite>/node_modules/@capyclaw/service-broker` → `<suite>`。
29
+ * pnpm 提升布局下 broker 可能被提到 profile 根,向上找不到套件根 → 返回 null,
30
+ * 调用方退回本包 services.json(standby),行为与原实现一致。
31
+ */
32
+ export function findSuiteRoot(startDir = path.dirname(PKG_DIR)) {
33
+ let dir = path.resolve(startDir)
34
+ for (;;) {
35
+ if (dir !== path.resolve(PKG_DIR) && isSuiteRoot(dir)) return dir
36
+ const parent = path.dirname(dir)
37
+ if (parent === dir) return null
38
+ dir = parent
39
+ }
40
+ }
41
+
42
+ /** 读 JSON 并剥 UTF-8 BOM:带 BOM 的清单会让 JSON.parse 抛「Unexpected token」,
43
+ * 表现为 boot 永久失败且极难归因(文件看着完全正常)。统一在此剥掉。 */
44
+ function parseJsonFile(file) {
45
+ return JSON.parse(readFileSync(file, 'utf8').replace(/^\uFEFF/, ''))
46
+ }
47
+
48
+ /** 套件根判据:含 dsh-suite.json + services.json,且不是 broker 自带的 dsh-suite.json。 */
49
+ function isSuiteRoot(dir) {
50
+ const suiteFile = path.join(dir, 'dsh-suite.json')
51
+ if (!existsSync(suiteFile) || !existsSync(path.join(dir, 'services.json'))) return false
52
+ try {
53
+ const manifest = parseJsonFile(suiteFile)
54
+ return Boolean(manifest) && typeof manifest === 'object' && manifest.name !== 'dsh-service-broker-suite'
55
+ } catch {
56
+ return false
57
+ }
58
+ }
59
+
60
+ export function resolveManifestPath(manifestPath) {
61
+ if (!manifestPath || manifestPath === 'auto') {
62
+ const suite = findSuiteRoot()
63
+ return suite ? path.join(suite, 'services.json') : path.join(PKG_DIR, 'services.json')
64
+ }
65
+ const expanded = String(manifestPath).replaceAll('${SUITE_DIR}', () => {
66
+ const suite = findSuiteRoot() || process.env.DSH_SUITE_DIR || null
67
+ if (!suite) {
68
+ throw new Error(`manifest 含 \${SUITE_DIR},但从 ${PKG_DIR} 向上找不到套件根(dsh-suite.json + services.json);可用 DSH_SUITE_DIR 显式指定`)
69
+ }
70
+ return suite
71
+ })
72
+ /* 统一走 resolve:既拼接相对路径,也把 ${SUITE_DIR}/x 产生的前斜杠归一化。 */
73
+ return path.resolve(path.isAbsolute(expanded) ? expanded : path.join(PKG_DIR, expanded))
74
+ }
75
+
76
+ /**
77
+ * 发现同一个 node_modules 作用域里**所有已安装的套件**。
78
+ *
79
+ * 为什么必须这样:cordis 的 loader 用 `tree.store[id] ??= new Entry()` 建节点,
80
+ * 同 id 的 insert 会被折叠成**一个**实例。三个套件都 insert `service-broker`,
81
+ * 于是同时装多个时只有一个 broker 存活,而它只吃其中一个套件的 services.json —
82
+ * 其余套件的 relay 永远没人拉起,表现为"装了两个,只有一个能用"。
83
+ *
84
+ * 解决:broker 不看"自己属于哪个套件",而是把当前 profile 下所有
85
+ * `node_modules/@capyclaw/*-suite/services.json` 合并成一份清单。
86
+ */
87
+ export function discoverSuites(startDir = process.env.DSH_SUITE_DISCOVERY_ROOT || PKG_DIR) {
88
+ /* 1) pnpm link 安装态:套件真实路径在 drop 目录,**向上走不回 profile**。
89
+ * 改用「谁的 node_modules 里装着本 broker」来定位当前 profile,
90
+ * 这样多 profile 共存也不会串台。 */
91
+ if (!process.env.DSH_SUITE_DISCOVERY_ROOT) {
92
+ const owning = findOwningProfile()
93
+ if (owning) {
94
+ /* 注意:suitesUnder 收的是 **node_modules** 目录,不是 @capyclaw 子目录
95
+ * (传错会拼成 @capyclaw/@capyclaw,永远扫到 0 个套件)。 */
96
+ const suites = suitesUnder(owning.nodeModules)
97
+ if (suites.length) return { root: owning.root, suites, matched: true }
98
+ }
99
+ }
100
+ /* 2) 捆绑布局(zip 内):沿路径向上找带 @capyclaw/*-suite 的 node_modules。 */
101
+ let dir = path.resolve(startDir)
102
+ for (;;) {
103
+ const suites = suitesUnder(path.join(dir, 'node_modules'))
104
+ if (suites.length) return { root: dir, suites, matched: true }
105
+ const parent = path.dirname(dir)
106
+ if (parent === dir) break
107
+ dir = parent
108
+ }
109
+ return { root: null, suites: [], matched: false }
110
+ }
111
+
112
+ /**
113
+ * 找出「本 broker 所属的 profile」。
114
+ *
115
+ * broker 可能来自两处,两处都要认:
116
+ * 1. 套件内嵌:`<profile>/node_modules/@capyclaw/<suite>/node_modules/@capyclaw/service-broker`
117
+ * (旧布局,套件自己带 broker);
118
+ * 2. profile 作用域直挂:`<profile>/node_modules/@capyclaw/service-broker`
119
+ * (@capyclaw/core 布局——core 声明六行基建,broker 由 core 提供,
120
+ * 此时套件里那份是各自的副本,realpath 与 self 不同)。
121
+ *
122
+ * 只认 1 会在 core 托管时把整份清单扫成 0 个套件,表现为「服务一个都不拉,
123
+ * 但旧进程还在跑」,极难排查。
124
+ */
125
+ function findOwningProfile() {
126
+ const home = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
127
+ const profilesDir = path.join(home, 'profiles')
128
+ let profiles = []
129
+ try { profiles = readdirSync(profilesDir) } catch { return null }
130
+ let self
131
+ try { self = realpathSync(PKG_DIR) } catch { return null }
132
+ for (const name of profiles) {
133
+ const nodeModules = path.join(profilesDir, name, 'node_modules')
134
+ const scope = path.join(nodeModules, '@capyclaw')
135
+ let entries = []
136
+ try { entries = readdirSync(scope) } catch { continue }
137
+
138
+ /* 2) 作用域直挂(core 托管):先认这个,最省事也最常见。 */
139
+ try {
140
+ if (realpathSync(path.join(scope, 'service-broker')) === self) {
141
+ return { root: path.join(profilesDir, name), nodeModules }
142
+ }
143
+ } catch { /* 没直挂,继续看套件内嵌 */ }
144
+
145
+ /* 1) 内嵌(套件自带 broker,或 core 这类聚合包自带 broker) */
146
+ for (const owner of entries) {
147
+ const embedded = path.join(scope, owner, 'node_modules', '@capyclaw', 'service-broker')
148
+ try {
149
+ if (realpathSync(embedded) === self) return { root: path.join(profilesDir, name), nodeModules }
150
+ } catch { /* 这个包没有独立 broker(提升安装) */ }
151
+ }
152
+ }
153
+ return null
154
+ }
155
+
156
+ function suitesUnder(nodeModules) {
157
+ const scope = path.join(nodeModules, '@capyclaw')
158
+ let names = []
159
+ try { names = readdirSync(scope) } catch { return [] }
160
+ const out = []
161
+ const seen = new Set()
162
+ for (const name of names) {
163
+ if (!name.endsWith('-suite')) continue
164
+ const manifestFile = path.join(scope, name, 'services.json')
165
+ if (!existsSync(manifestFile)) continue
166
+ /* pnpm link 会同时出现在链接名与真实目录下,按真实路径去重,避免重复服务。 */
167
+ let real
168
+ try { real = realpathSync(manifestFile) } catch { real = manifestFile }
169
+ if (seen.has(real)) continue
170
+ seen.add(real)
171
+ out.push({ name, file: manifestFile })
172
+ }
173
+ return out
174
+ }
175
+
176
+ /** 合并多份清单:同 id 且等价 → 去重;同 id 但定义不同 → 报冲突(不静默覆盖)。 */
177
+ function mergeManifests(entries) {
178
+ const merged = []
179
+ const seen = new Map()
180
+ for (const { file } of entries) {
181
+ for (const service of loadFile(file)) {
182
+ const previous = seen.get(service.id)
183
+ if (!previous) {
184
+ seen.set(service.id, { service, file })
185
+ merged.push(service)
186
+ continue
187
+ }
188
+ if (JSON.stringify(previous.service) === JSON.stringify(service)) continue
189
+ throw new Error(
190
+ `服务 id 冲突: ${service.id}\n- ${previous.file}\n- ${file}\n` +
191
+ '同一 profile 里两个套件声明了同一个服务 id 且定义不同,拒绝启动(否则会互相覆盖)。',
192
+ )
193
+ }
194
+ }
195
+ return merged
196
+ }
197
+
198
+ export function loadManifest(manifestPath) {
199
+ if (!manifestPath || manifestPath === 'auto') {
200
+ const discovered = discoverSuites()
201
+ if (discovered.suites.length) return mergeManifests(discovered.suites)
202
+ /* 单套件捆绑布局(zip 内):node_modules 里没有 *-suite,退回套件根发现。 */
203
+ return loadFile(resolveManifestPath(undefined))
204
+ }
205
+ return loadFile(resolveManifestPath(manifestPath))
206
+ }
207
+
208
+ function loadFile(file) {
209
+ if (!existsSync(file)) return []
210
+ const raw = parseJsonFile(file)
211
+ const services = Array.isArray(raw) ? raw : raw.services
212
+ if (!Array.isArray(services)) throw new Error(`manifest 格式非法(缺 services 数组): ${file}`)
213
+ const specErrors = validateServiceManifest(services, file)
214
+ if (specErrors.length) throw new Error(`manifest 服务 spec 非法:\n- ${specErrors.join('\n- ')}`)
215
+ const base = path.dirname(file)
216
+ return services.map((service) => expandPackageDir(service, base))
217
+ }
218
+
219
+ /**
220
+ * 提升布局回退:`${PACKAGE_DIR}/node_modules/<pkg>/…` 展开后不存在时,沿 base
221
+ * 向上逐级找 node_modules/<pkg>/…(npm/pnpm 提升后的落点)。找不到时原样返回,
222
+ * 由引擎按既有行为报错,不在此处吞掉。
223
+ */
224
+ function resolveHoistedScriptPath(expanded, base) {
225
+ if (existsSync(expanded)) return expanded
226
+ const norm = String(expanded).replace(/\\/g, '/')
227
+ const marker = '/node_modules/'
228
+ /* 取最内层 node_modules 段:展开路径可能同时含 profile 根与套件内嵌两级 */
229
+ const idx = norm.lastIndexOf(marker)
230
+ if (idx < 0) return expanded
231
+ const rest = norm.slice(idx + marker.length).split('/')
232
+ let dir = path.resolve(base)
233
+ for (;;) {
234
+ const candidate = path.join(dir, 'node_modules', ...rest)
235
+ if (existsSync(candidate)) return candidate
236
+ const parent = path.dirname(dir)
237
+ if (parent === dir) return expanded
238
+ dir = parent
239
+ }
240
+ }
241
+
242
+ function expandPackageDir(service, base) {
243
+ const out = { ...service, env: { ...service.env } }
244
+ if (Array.isArray(out.cmd)) {
245
+ out.cmd = out.cmd.map((a) => {
246
+ const str = String(a)
247
+ if (!str.includes('${PACKAGE_DIR}')) return str
248
+ return resolveHoistedScriptPath(str.replaceAll('${PACKAGE_DIR}', base), base)
249
+ })
250
+ }
251
+ for (const key of ['url', 'cwd', 'logFile']) {
252
+ if (typeof out[key] === 'string') out[key] = String(out[key]).replaceAll('${PACKAGE_DIR}', base)
253
+ }
254
+ /* env 值同样展开 ${PACKAGE_DIR}:旧实现只展开 url/cwd/logFile,env 里引用
255
+ * ${PACKAGE_DIR} 的变量(如自定义数据目录/脚本路径)原样传给子进程 → 路径错。 */
256
+ for (const [key, value] of Object.entries(out.env)) {
257
+ if (typeof value === 'string' && value.includes('${PACKAGE_DIR}')) {
258
+ out.env[key] = value.replaceAll('${PACKAGE_DIR}', base)
259
+ }
260
+ }
261
+ return out
262
+ }