@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,183 @@
1
+ /**
2
+ * @capyclaw/portal — macOS 弹窗后端。
3
+ *
4
+ * win32 用常驻 PowerShell 助手(portal-agent.ps1)管窗口;macOS 没有那套 Win32
5
+ * API,这里改用「每扇窗一个独立的 Chromium --app 进程」:detached + unref,窗口
6
+ * 生命周期跟服务页面走,宿主退出不连带杀窗(对齐 win32「关窗不影响服务」的边界)。
7
+ *
8
+ * 与 win32 的能力差异(有意降级,不装作等价):
9
+ * - topmost / frameless:Chromium --app 在 macOS 不提供可靠的置顶/去边框控制,
10
+ * 这里按普通 app 窗处理(ping/move 为空操作)。
11
+ * - iconic/restore:不跟踪最小化态,restore 退化为「把窗带到前台」。
12
+ * - focus:走 System Events,需要辅助功能权限,失败静默(best-effort)。
13
+ *
14
+ * 对外暴露与 PortalAgent 相同的 request(op, payload) 语义,index.mjs 按平台选用。
15
+ */
16
+
17
+ import { spawn, spawnSync } from 'node:child_process'
18
+ import fs from 'node:fs'
19
+ import os from 'node:os'
20
+ import path from 'node:path'
21
+
22
+ /** macOS 上的 Chromium 内核浏览器候选(--app 只需要内核)。 */
23
+ export const DARWIN_BROWSERS = [
24
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
25
+ '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
26
+ '/Applications/Chromium.app/Contents/MacOS/Chromium',
27
+ '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
28
+ path.join(os.homedir(), 'Applications', 'Google Chrome.app', 'Contents', 'MacOS', 'Google Chrome'),
29
+ ]
30
+
31
+ export function findDarwinBrowser() {
32
+ for (const candidate of DARWIN_BROWSERS) {
33
+ try {
34
+ if (fs.statSync(candidate).isFile()) return candidate
35
+ } catch { /* 下一个 */ }
36
+ }
37
+ return null
38
+ }
39
+
40
+ /**
41
+ * 纯几何:把窗口声明摆进屏幕工作区。抽成纯函数便于跨平台单测(不碰 osascript)。
42
+ * @param {{x:number,y:number,width:number,height:number}} screen 屏幕工作区(左上原点)
43
+ * @param {{width:number,height:number,anchor?:string,margin?:number}} decl
44
+ * @returns {{x:number,y:number,width:number,height:number}}
45
+ */
46
+ export function computeWindowRect(screen, decl) {
47
+ const margin = Number.isFinite(decl.margin) ? decl.margin : 24
48
+ const width = Math.min(decl.width, screen.width)
49
+ const height = Math.min(decl.height, screen.height)
50
+ let x
51
+ if (decl.anchor === 'left') x = screen.x + margin
52
+ else if (decl.anchor === 'center') x = screen.x + Math.round((screen.width - width) / 2)
53
+ else x = screen.x + screen.width - width - margin // right(默认)
54
+ let y = screen.y + margin
55
+ // 夹进屏幕,避免负坐标/越界(小屏 + 大窗 + 大 margin 的组合)。
56
+ x = Math.max(screen.x, Math.min(x, screen.x + screen.width - width))
57
+ y = Math.max(screen.y, Math.min(y, screen.y + screen.height - height))
58
+ return { x, y, width, height }
59
+ }
60
+
61
+ /** 读主屏工作区;osascript 失败/超时兜底 1440x900(best-effort,不阻断开窗)。 */
62
+ function screenBounds() {
63
+ try {
64
+ const r = spawnSync('osascript', ['-e', 'tell application "Finder" to get bounds of window of desktop'], {
65
+ encoding: 'utf8',
66
+ timeout: 4000,
67
+ })
68
+ const nums = String(r.stdout || '').match(/-?\d+/g)
69
+ if (r.status === 0 && nums && nums.length >= 4) {
70
+ const [l, t, rr, b] = nums.slice(0, 4).map(Number)
71
+ if (rr > l && b > t) return { x: l, y: t, width: rr - l, height: b - t }
72
+ }
73
+ } catch { /* 兜底 */ }
74
+ return { x: 0, y: 0, width: 1440, height: 900 }
75
+ }
76
+
77
+ /** 进程是否活着(信号 0 只探测;EPERM=活着但无权限,ESRCH=确死)。 */
78
+ function alive(pid) {
79
+ if (!Number.isSafeInteger(pid) || pid <= 0) return false
80
+ try { process.kill(pid, 0); return true } catch (e) { return e.code === 'EPERM' }
81
+ }
82
+
83
+ /** 把某 pid 的进程带到前台(System Events,需辅助功能权限;失败静默)。 */
84
+ function focusPid(pid) {
85
+ try {
86
+ spawnSync('osascript', ['-e',
87
+ `tell application "System Events" to set frontmost of (first process whose unix id is ${pid}) to true`,
88
+ ], { timeout: 4000, stdio: 'ignore' })
89
+ } catch { /* best-effort */ }
90
+ }
91
+
92
+ /** macOS 弹窗助手:窗口是独立 detached 进程,这里只在内存里记账。 */
93
+ export class DarwinPortalAgent {
94
+ constructor() {
95
+ /** @type {Map<string, {pid:number,url:string,rect:object,title:string}>} */
96
+ this.windows = new Map()
97
+ }
98
+
99
+ /** 与 PortalAgent.active 对齐:有没有我们管的窗。 */
100
+ get active() { return this.windows.size > 0 }
101
+
102
+ /** 宿主退出钩子:窗口是 detached 的,留给用户/服务,不连带杀。 */
103
+ dispose() { /* no-op */ }
104
+
105
+ async stop() { /* no-op:主动关停也不杀用户的窗 */ }
106
+
107
+ /** 剪掉已死的 pid,保持账本干净。 */
108
+ prune() {
109
+ for (const [key, entry] of this.windows) {
110
+ if (!alive(entry.pid)) this.windows.delete(key)
111
+ }
112
+ }
113
+
114
+ /**
115
+ * 与 PortalAgent.request 同语义(op + payload),但在进程内直接完成,无 IPC。
116
+ * @returns {Promise<object>}
117
+ */
118
+ async request(op, payload = {}) {
119
+ const key = String(payload.key || 'default')
120
+ switch (op) {
121
+ case 'open': {
122
+ const existing = this.windows.get(key)
123
+ if (existing && alive(existing.pid)) {
124
+ if (payload.activate !== false) focusPid(existing.pid)
125
+ return { ok: true, hwnd: existing.pid, pid: existing.pid, rect: existing.rect, reused: true }
126
+ }
127
+ const exe = payload.browser || findDarwinBrowser()
128
+ if (!exe) return { ok: false, error: '没有找到 Chrome/Edge/Chromium' }
129
+ const rect = computeWindowRect(screenBounds(), {
130
+ width: payload.w, height: payload.h, anchor: payload.anchor, margin: payload.margin,
131
+ })
132
+ const child = spawn(exe, [
133
+ `--app=${payload.url}`,
134
+ `--user-data-dir=${payload.profile}`,
135
+ `--window-size=${rect.width},${rect.height}`,
136
+ `--window-position=${rect.x},${rect.y}`,
137
+ '--no-first-run',
138
+ '--no-default-browser-check',
139
+ ], { detached: true, stdio: 'ignore' })
140
+ child.on('error', () => { /* 起不来就记账失败,下面 alive 会剪掉 */ })
141
+ child.unref()
142
+ this.windows.set(key, { pid: child.pid, url: payload.url, rect, title: payload.title })
143
+ return { ok: true, hwnd: child.pid, pid: child.pid, rect, reused: false }
144
+ }
145
+ case 'focus': {
146
+ const entry = this.windows.get(key)
147
+ if (entry && alive(entry.pid)) focusPid(entry.pid)
148
+ return { ok: true, key }
149
+ }
150
+ case 'close': {
151
+ const entry = this.windows.get(key)
152
+ this.windows.delete(key)
153
+ if (!entry || !alive(entry.pid)) return { closed: false }
154
+ try { process.kill(entry.pid, 'SIGTERM') } catch { /* 已退出 */ }
155
+ return { closed: true }
156
+ }
157
+ case 'state': {
158
+ this.prune()
159
+ return {
160
+ windows: [...this.windows.entries()].map(([k, entry]) => ({
161
+ key: k, pid: entry.pid, hwnd: entry.pid, rect: entry.rect, iconic: false,
162
+ })),
163
+ }
164
+ }
165
+ case 'restore': {
166
+ // macOS 不跟踪最小化态:退化为带到前台。
167
+ const entry = this.windows.get(key)
168
+ if (entry && alive(entry.pid)) focusPid(entry.pid)
169
+ return { ok: true, key }
170
+ }
171
+ case 'ping':
172
+ case 'move':
173
+ // topmost/重定位在 macOS 无可靠对应:空操作(nudge 默认也是关的)。
174
+ return { ok: true, key }
175
+ case 'shutdown':
176
+ // 不杀用户的窗;只清账本。
177
+ this.windows.clear()
178
+ return { ok: true }
179
+ default:
180
+ return { ok: false, error: `未知操作 ${op}` }
181
+ }
182
+ }
183
+ }
@@ -0,0 +1,40 @@
1
+ {
2
+ "name": "@capyclaw/portal",
3
+ "version": "0.1.13",
4
+ "description": "DSH 基础设施标准件:服务就绪后把它的页面弹成置顶小窗(Edge/Chromium app 窗口 + Win32 几何/置顶),业务插件只需在 services.json 里声明 window。",
5
+ "type": "module",
6
+ "main": "./lib/index.mjs",
7
+ "exports": {
8
+ ".": "./lib/index.mjs",
9
+ "./package.json": "./package.json"
10
+ },
11
+ "files": [
12
+ "lib/",
13
+ "README.md"
14
+ ],
15
+ "scripts": {
16
+ "test": "node --test \"test/*.test.mjs\""
17
+ },
18
+ "engines": {
19
+ "node": ">=18"
20
+ },
21
+ "license": "MIT",
22
+ "publishConfig": {
23
+ "access": "public"
24
+ },
25
+ "repository": {
26
+ "type": "git",
27
+ "url": "git+https://github.com/Maple496/capyclaw.git",
28
+ "directory": "C/packages/capyclaw-portal"
29
+ },
30
+ "keywords": [
31
+ "dsh",
32
+ "dsh-plugin",
33
+ "window",
34
+ "portal"
35
+ ],
36
+ "bugs": {
37
+ "url": "https://github.com/Maple496/capyclaw/issues"
38
+ },
39
+ "homepage": "https://github.com/Maple496/capyclaw/tree/main/C/packages/capyclaw-portal#readme"
40
+ }
@@ -0,0 +1,104 @@
1
+ # @capyclaw/service-broker(服务编排 broker)
2
+
3
+ DSH 服务中间件。服务解耦标准的执行者:**启动清单/后端/用户不直接拉服务,
4
+ 一切结构化命令投递到这里,由中间件把每个服务作为独立进程拉起、守护、登记。**
5
+
6
+ 原则对应关系:
7
+
8
+ | 原则 | 本插件的做法 |
9
+ |------|--------------|
10
+ | 服务彼此独立 | 每个服务 = 独立进程 + 独立端口,互不感知、不互相带动 |
11
+ | 能做什么局限在自己的端口里 | 引擎只按 spec 拉起/回收,不解释服务内容 |
12
+ | 跨端口调动交给中间件 | `requires` 拓扑、端口分配、复用/冲突仲裁、discovery 都在这里 |
13
+ | 不硬耦合 | 引擎零 dsh 依赖;embedded(cordis 插件壳)与 standalone(独立端口)同一份逻辑 |
14
+
15
+ ## 变更记录
16
+
17
+ - **0.2.0**(2026-11-04):新增**统一服务 spec**——`service.schema.json`(JSON Schema)
18
+ 与 `lib/spec.mjs`(代码面校验 `validateServiceSpec`/`validateServiceManifest`),
19
+ `loadManifest` 在装载期拒绝结构非法的清单(同清单重复 id 也在此报错);
20
+ 新增 exports `./spec`、`./schema`。`stack-services.json`(dsh-stack-kit 编译)与
21
+ `service-manifest.json`(@capyclaw/suite-kit 物化)自此共用同一份 spec 契约。
22
+ - 0.1.0:初始发布。
23
+
24
+ ## 两种形态
25
+
26
+ ### standalone(桌面/外部场景的主形态)
27
+
28
+ ```bash
29
+ node server.mjs [--port 39610] [--manifest services.json] [--stop-on-exit]
30
+ ```
31
+
32
+ - 开机清单:`--manifest` 指向的 JSON(`{"services":[…spec]}` 或裸数组)幂等拉起;
33
+ - 之后外部(如桌面后端)把结构化命令投递到控制端点。
34
+
35
+ ### embedded(dsh 场景)
36
+
37
+ cordis insert 唯一一行(`cordis.patch.yml`),config:
38
+
39
+ ```yaml
40
+ - insert:
41
+ - id: service-broker
42
+ name: "@capyclaw/service-broker"
43
+ config:
44
+ manifest: "C:/…/services.json" # 开机清单(可省略=待命)
45
+ controlPort: 0 # >0 时embedded 也开控制端点
46
+ stopOnUnload: false # true=插件卸载时全停(默认服务独立存活)
47
+ skills:
48
+ url: "http://127.0.0.1:<真实端口>" # 可选 standalone 模式:ctx.skillsHttp 瘦客户端数据源(默认不启用;技能标准路径是 skillProvider@1 进程内注册,不占用原生 ctx.skills)
49
+ ```
50
+
51
+ ## 服务规格 spec(与桌面后端 works_services 契约对齐)
52
+
53
+ ```json
54
+ {
55
+ "id": "ppt-workbench",
56
+ "cmd": ["node", "…/server.mjs", "--port", "${PORT}"],
57
+ "env": { "EXAMPLE": "${SOME_VAR}" },
58
+ "cwd": "…",
59
+ "ports": { "main": "<port>", "extra": "auto" },
60
+ "url": "http://127.0.0.1:${PORT}",
61
+ "healthPath": "/healthz",
62
+ "keepAlive": true,
63
+ "requires": ["dep-service"]
64
+ }
65
+ ```
66
+
67
+ - `${PORT}` / `${PORT_<NAME>}`:端口占位符(auto 由中间件现场分配;固定端口原样使用);
68
+ cmd/env/url/cwd 里都可引用;其余 `${VAR}` 从环境展开,缺失 → 空串(诚实降级)。
69
+ - `requires`:中间件按闭包拓扑排序拉起(成环报错);只在本批内解析。
70
+ - `keepAlive`:默认 true,进程死亡由守护按**原端口**自动重启(连续失败限次)。
71
+
72
+ ## 结构化命令投递(控制端点,只绑 127.0.0.1)
73
+
74
+ ```
75
+ GET /healthz 中间件自身健康
76
+ GET /control/list 服务全量列表(含 running/pid/ports/url)
77
+ POST /control/apply { commands: [{op:"up",service:spec} | {op:"stop",id}], waitMs? }
78
+ POST /control/start { id }(重放清单/上次规格)或 { service: spec }
79
+ POST /control/stop { id }(pid 身份核验后 taskkill /T /F)
80
+ GET /control/doctor?id 存活 + 健康端点体检
81
+ ```
82
+
83
+ **`/control/*` 始终需要 `x-broker-token`**(只有 `GET /healthz` 免鉴权,且所有端点只接受 loopback 来源)。
84
+ token 取 `DSH_BROKER_TOKEN`;没设时自动用 `$DSH_HOME/broker-token`(不存在则以 `0600` 生成,路径可用
85
+ `DSH_BROKER_TOKEN_FILE` 覆盖)。启动日志会打印 token **文件路径**,不会打印 token 本身。
86
+ 控制面不返回 CORS 头,因此浏览器页面无法直接调用它。
87
+
88
+ ## discovery 注册表
89
+
90
+ `~/.dsh/services.json`(可 `--discovery`/`config.discoveryPath` 改):
91
+
92
+ ```json
93
+ { "version": 1, "updatedAt": "…", "services": {
94
+ "ppt-workbench": { "id": "…", "state": "running", "url": "http://127.0.0.1:<port>",
95
+ "healthPath": "/healthz", "pid": 1234, "ports": {"main": "<port>"},
96
+ "keepAlive": true, "reused": false, "startedAt": "…" } } }
97
+ ```
98
+
99
+ UI/侧栏/其他工具只读这张表做发现,**永远不直接拉起别人**。
100
+
101
+ ## 复用优先(幂等)
102
+
103
+ `up` 前先看目标端口:已有健康实例(`/healthz` 200 且自报 pid)→ 收编复用,
104
+ 不重启;被不健康进程占用 → 诚实失败,不抢端口。
@@ -0,0 +1,8 @@
1
+ # service-broker:唯一中间件插件。
2
+ # 服务解耦标准见 docs/SERVICE_STANDARD.md——业务/端口服务一律不 insert 进
3
+ # dsh 进程,由本插件按清单以独立进程拉起;跨端口组织只经过中间件。
4
+ # 注意:name 必须是 npm 包名 @capyclaw/service-broker(裸名 dsh-service-broker
5
+ # 已随改名废弃,写成裸名会在 profile 安装态 ERR_MODULE_NOT_FOUND,宿主永不激活)。
6
+ - insert:
7
+ - id: service-broker
8
+ name: "@capyclaw/service-broker"
@@ -0,0 +1,21 @@
1
+ {
2
+ "$schema": "../capyclaw-suite-kit/suite.schema.json",
3
+ "name": "dsh-service-broker-suite",
4
+ "version": "0.2.0",
5
+ "title": "Service Broker",
6
+ "description": "服务中间件:按清单/结构化命令以独立进程拉起各服务,负责守护、发现与控制端点。",
7
+ "packages": {
8
+ "dsh-service-broker": {
9
+ "role": "runtime",
10
+ "version": "^0.2.0",
11
+ "path": ".",
12
+ "provides": {
13
+ "services": ["serviceBroker"],
14
+ "capabilities": { "service.broker": "1.0.0" },
15
+ "ports": []
16
+ }
17
+ }
18
+ },
19
+ "rows": [{ "id": "service-broker", "name": "dsh-service-broker" }],
20
+ "checks": []
21
+ }
@@ -0,0 +1,209 @@
1
+ /**
2
+ * @capyclaw/service-broker 控制端点:外部投递结构化命令的入口。
3
+ *
4
+ * 端点(只绑 127.0.0.1):
5
+ * GET /healthz 中间件自身健康(唯一免鉴权端点)
6
+ * GET /control/list 服务全量列表
7
+ * POST /control/apply 结构化命令批投递 { commands: [...], waitMs? }
8
+ * POST /control/start { id? | service? }(id = 重放上次规格;service = 新规格)
9
+ * POST /control/stop { id }
10
+ * GET /control/doctor?id=
11
+ *
12
+ * 鉴权(**始终开启**,没有“默认放行”这一档):
13
+ * - 来源必须是 loopback(防空闲网卡/远端误绑);
14
+ * - 除 /healthz 外都要带 `x-broker-token`;
15
+ * - token 取 `DSH_BROKER_TOKEN`,没设就从 `<DSH_HOME>/broker-token` 读(不存在则以 0600 生成);
16
+ * - 比较用定长时间比较;
17
+ * - 不返回任何 CORS 头:控制面是给本机进程/CLI 用的,不该被浏览器页面打到。
18
+ */
19
+ import http from 'node:http'
20
+ import path from 'node:path'
21
+ import os from 'node:os'
22
+ import { randomBytes } from 'node:crypto'
23
+ import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs'
24
+ import { isLoopbackAddress, timingSafeEqualText } from '@capyclaw/plugin-kit/util/http'
25
+
26
+ function brokerHome() {
27
+ return process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
28
+ }
29
+
30
+ /** token 文件的默认位置(`DSH_BROKER_TOKEN_FILE` 可覆盖)。 */
31
+ export function brokerTokenPath() {
32
+ return process.env.DSH_BROKER_TOKEN_FILE || path.join(brokerHome(), 'broker-token')
33
+ }
34
+
35
+ /**
36
+ * 解析控制面 token:显式参数 → 环境变量 → token 文件(缺则生成)。
37
+ * 文件不可写时退回进程内随机 token(仍然强制鉴权,只是本机其它进程读不到)。
38
+ */
39
+ export function resolveBrokerToken(explicit) {
40
+ const given = explicit || process.env.DSH_BROKER_TOKEN
41
+ if (given) return String(given)
42
+ const file = brokerTokenPath()
43
+ try {
44
+ if (existsSync(file)) {
45
+ const saved = readFileSync(file, 'utf8').trim()
46
+ if (saved) return saved
47
+ }
48
+ mkdirSync(path.dirname(file), { recursive: true })
49
+ const generated = randomBytes(24).toString('hex')
50
+ writeFileSync(file, `${generated}\n`, { mode: 0o600 })
51
+ return generated
52
+ } catch {
53
+ return randomBytes(24).toString('hex')
54
+ }
55
+ }
56
+
57
+ function tokenMatches(expected, actual) {
58
+ if (!expected) return false
59
+ return timingSafeEqualText(actual, expected)
60
+ }
61
+
62
+ const isLoopback = isLoopbackAddress
63
+
64
+ function jsonBody(req, res, limit = 8 * 1024 * 1024) {
65
+ return new Promise((resolve, reject) => {
66
+ let size = 0
67
+ let aborted = false
68
+ const chunks = []
69
+ req.on('data', (chunk) => {
70
+ if (aborted) return
71
+ size += chunk.length
72
+ if (size > limit) {
73
+ /* 先回 413 再处理连接:客户端要能区分「体太大」与「连接被莫名掐断」。
74
+ * 不能立刻 destroy——响应字节还没刷出去就断连,客户端只会看到 ECONNRESET。
75
+ * 这里回完 413 后把剩余请求体排空丢弃(有 8MB 上限兜底,量可控),
76
+ * 让响应干净送达;病态超长上传由服务器级请求超时兜底。 */
77
+ aborted = true
78
+ if (res && !res.headersSent && !res.writableEnded) {
79
+ send(res, 413, { ok: false, error: `请求体超过上限 ${limit} 字节` })
80
+ }
81
+ reject(new Error('body too large'))
82
+ req.resume()
83
+ return
84
+ }
85
+ chunks.push(chunk)
86
+ })
87
+ req.on('end', () => {
88
+ if (aborted) return
89
+ const raw = Buffer.concat(chunks).toString('utf8')
90
+ if (!raw) return resolve({})
91
+ try { resolve(JSON.parse(raw)) } catch { reject(new Error('bad json')) }
92
+ })
93
+ req.on('error', (err) => { if (!aborted) reject(err) })
94
+ })
95
+ }
96
+
97
+ function send(res, code, value) {
98
+ const text = JSON.stringify(value)
99
+ res.writeHead(code, {
100
+ 'content-type': 'application/json; charset=utf-8',
101
+ 'content-length': Buffer.byteLength(text),
102
+ 'cache-control': 'no-store',
103
+ 'x-content-type-options': 'nosniff',
104
+ })
105
+ res.end(text)
106
+ }
107
+
108
+ const UNSAFE = /[&|<>^`\n\r]/
109
+
110
+ /**
111
+ * @param {import('./engine.mjs').ServiceEngine} engine
112
+ * @param {{ token?: string, manifestPath?: string }} options
113
+ */
114
+ export function createControlServer(engine, options = {}) {
115
+ const manifestPath = options.manifestPath
116
+ const token = resolveBrokerToken(options.token)
117
+ const tokenFile = (process.env.DSH_BROKER_TOKEN || options.token) ? '' : brokerTokenPath()
118
+
119
+ const server = http.createServer(async (req, res) => {
120
+ const url = new URL(req.url, 'http://127.0.0.1')
121
+ const route = `${req.method} ${url.pathname}`
122
+ try {
123
+ if (!isLoopback(req.socket.remoteAddress)) {
124
+ return send(res, 403, { ok: false, error: '只接受本机(loopback)请求' })
125
+ }
126
+
127
+ if (route !== 'GET /healthz') {
128
+ if (!tokenMatches(token, req.headers['x-broker-token'])) {
129
+ return send(res, 401, { ok: false, error: '需要 x-broker-token' })
130
+ }
131
+ }
132
+
133
+ if (route === 'GET /healthz') {
134
+ return send(res, 200, {
135
+ ok: true,
136
+ service: 'dsh-service-broker',
137
+ role: 'middleware',
138
+ pid: process.pid,
139
+ uptimeSec: Math.round(process.uptime()),
140
+ auth: 'token',
141
+ ...(tokenFile ? { tokenFile } : {}),
142
+ })
143
+ }
144
+
145
+ if (route === 'GET /control/list') {
146
+ return send(res, 200, { ok: true, services: await engine.list() })
147
+ }
148
+
149
+ if (route === 'POST /control/apply') {
150
+ const body = await jsonBody(req, res)
151
+ const result = await engine.apply(body.commands || [], { waitMs: body.waitMs })
152
+ return send(res, result.ok ? 200 : 207, result)
153
+ }
154
+
155
+ if (route === 'POST /control/start') {
156
+ const body = await jsonBody(req, res)
157
+ let spec = body.service
158
+ if (!spec && body.id && manifestPath && existsSync(manifestPath)) {
159
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
160
+ const services = Array.isArray(manifest) ? manifest : manifest.services
161
+ spec = (services || []).find((s) => s.id === body.id)
162
+ if (spec) spec = { ...spec, id: body.id }
163
+ }
164
+ if (!spec && body.id) {
165
+ /* 死行不能回 ok:true 假装启动(P1-5):优先用内存里可重放的规格真的拉起;
166
+ * 没有规格时,只有「确实在运行」才幂等返回 ok,否则给可操作的 409。 */
167
+ const last = typeof engine.specOf === 'function' ? engine.specOf(body.id) : null
168
+ if (last) spec = { ...last, id: body.id }
169
+ else {
170
+ const row = (await engine.list()).find((s) => s.id === body.id)
171
+ if (row?.running) return send(res, 200, { ok: true, services: [row] })
172
+ return send(res, 409, {
173
+ ok: false,
174
+ error: `服务 ${body.id} 未在运行且无可重放规格(注册表行不含 cmd);请提供 service 规格,或把它加入开机清单后重试`,
175
+ })
176
+ }
177
+ }
178
+ if (!spec) return send(res, 400, { ok: false, error: '缺 service 规格或可重放的 id' })
179
+ // 内联规格是"让 broker 执行一条命令"的权力,禁止 shell 元字符,避免被拼进 shell。
180
+ if (typeof spec.cmd === 'string' && UNSAFE.test(spec.cmd)) {
181
+ return send(res, 400, { ok: false, error: 'service.cmd 含不安全的 shell 元字符' })
182
+ }
183
+ const result = await engine.apply([{ op: 'up', service: spec }], { waitMs: body.waitMs })
184
+ return send(res, result.ok ? 200 : 207, result)
185
+ }
186
+
187
+ if (route === 'POST /control/stop') {
188
+ const body = await jsonBody(req, res)
189
+ if (!body.id) return send(res, 400, { ok: false, error: '缺 id' })
190
+ return send(res, 200, await engine.stop(body.id))
191
+ }
192
+
193
+ if (route === 'GET /control/doctor') {
194
+ const id = url.searchParams.get('id')
195
+ if (!id) return send(res, 400, { ok: false, error: '缺 id' })
196
+ return send(res, 200, await engine.doctor(id))
197
+ }
198
+
199
+ send(res, 404, { ok: false, error: `未知端点 ${route}` })
200
+ } catch (err) {
201
+ /* jsonBody 超限时已回过 413 并断连,不能再往已结束的响应上写。 */
202
+ if (!res.headersSent && !res.writableEnded) send(res, 400, { ok: false, error: err.message })
203
+ }
204
+ })
205
+ // 供宿主打日志用:只暴露位置,不暴露 token 本身。
206
+ server.brokerToken = token
207
+ server.brokerTokenFile = tokenFile
208
+ return server
209
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * discovery 注册表:中间件运行事实的唯一落点。
3
+ *
4
+ * 形状(~/.dsh/services.json):
5
+ * {
6
+ * "version": 1,
7
+ * "updatedAt": "2026-11-01T…",
8
+ * "services": {
9
+ * "<id>": { id, state, url, pid, ports, specHash, keepAlive, startedAt }
10
+ * }
11
+ * }
12
+ *
13
+ * 口径:损坏 = 空表(诚实降级,不阻塞);原子写(唯一 tmp + rename,
14
+ * tmp 名带随机段——同进程并发写不会互抢同一个 tmp)。
15
+ */
16
+ import { readFile, rename, writeFile, mkdir, open, unlink } from 'node:fs/promises'
17
+ import path from 'node:path'
18
+
19
+ /** 每个注册表文件一条写队列:整文件读改写串行化,杜绝并发互相覆盖。 */
20
+ const _writeQueues = new Map()
21
+
22
+ function enqueueWrite(filePath, task) {
23
+ const key = path.resolve(filePath).toLowerCase()
24
+ const prev = _writeQueues.get(key) || Promise.resolve()
25
+ const run = prev.then(task, task)
26
+ _writeQueues.set(key, run.then(() => {}, () => {}))
27
+ return run
28
+ }
29
+
30
+ export async function loadDiscovery(filePath) {
31
+ try {
32
+ return JSON.parse(await readFile(filePath, 'utf8'))
33
+ } catch {
34
+ return null
35
+ }
36
+ }
37
+
38
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
39
+
40
+ /** Windows 上并发读/写会让 rename 偶发 EPERM/EBUSY(实测双进程 RMW 失败率 17-27%)。
41
+ * 指数退避重试,而不是让一次偶发碰撞把整个 up 打成失败(P1-2)。 */
42
+ async function renameWithRetry(tmp, filePath, attempts = 6) {
43
+ let lastErr
44
+ for (let i = 0; i < attempts; i++) {
45
+ try { await rename(tmp, filePath); return } catch (err) {
46
+ lastErr = err
47
+ if (err.code !== 'EPERM' && err.code !== 'EBUSY' && err.code !== 'EACCES') throw err
48
+ await sleep(20 * 2 ** i)
49
+ }
50
+ }
51
+ throw lastErr
52
+ }
53
+
54
+ export function saveDiscovery(filePath, data) {
55
+ return enqueueWrite(filePath, async () => {
56
+ await mkdir(path.dirname(filePath), { recursive: true })
57
+ const tmp = path.join(
58
+ path.dirname(filePath),
59
+ `.${path.basename(filePath)}.${process.pid}.${Math.random().toString(36).slice(2, 8)}.tmp`)
60
+ await writeFile(tmp, JSON.stringify(data, null, 2), 'utf8')
61
+ try {
62
+ await renameWithRetry(tmp, filePath)
63
+ } catch (err) {
64
+ try { await unlink(tmp) } catch { /* 尽力清理 */ }
65
+ throw err
66
+ }
67
+ })
68
+ }
69
+
70
+ /* ---- 跨进程注册表锁(P1-2:embedded + standalone / 双 profile 共享同一 services.json) ---- */
71
+
72
+ const LOCK_STALE_MS = 15000
73
+ const LOCK_WAIT_MS = 10000
74
+ const LOCK_RETRY_MS = 40
75
+
76
+ function holderAlive(pid) {
77
+ if (!Number.isInteger(pid) || pid <= 0) return false
78
+ try { process.kill(pid, 0); return true } catch (err) { return err.code === 'EPERM' }
79
+ }
80
+
81
+ /** 以锁文件串行化「读-改-写」跨进程临界区:'wx' 独占创建,持有者死亡或超时视为陈旧可抢占。
82
+ * 进程内已有 _regLock 串行,这里只补跨进程一段;临界区应短(仅注册表 IO)。 */
83
+ export async function withDiscoveryLock(filePath, fn) {
84
+ const lockPath = `${filePath}.lock`
85
+ await mkdir(path.dirname(filePath), { recursive: true })
86
+ const deadline = Date.now() + LOCK_WAIT_MS
87
+ let fd = null
88
+ for (;;) {
89
+ try {
90
+ fd = await open(lockPath, 'wx')
91
+ await fd.writeFile(JSON.stringify({ pid: process.pid, at: Date.now() }))
92
+ break
93
+ } catch (err) {
94
+ if (err.code !== 'EEXIST') throw err
95
+ let holder = null
96
+ try { holder = JSON.parse(await readFile(lockPath, 'utf8')) } catch { /* 损坏视为陈旧 */ }
97
+ const stale = !holder || !holderAlive(holder.pid) || (Date.now() - (holder.at || 0) > LOCK_STALE_MS)
98
+ if (stale) { try { await unlink(lockPath) } catch { /* 已被他方抢占 */ } continue }
99
+ if (Date.now() >= deadline) throw new Error(`discovery 注册表锁等待超时(${lockPath}),请稍后重试`)
100
+ await sleep(LOCK_RETRY_MS)
101
+ }
102
+ }
103
+ try {
104
+ return await fn()
105
+ } finally {
106
+ try { await fd.close() } catch { /* 已关闭 */ }
107
+ try { await unlink(lockPath) } catch { /* 已被抢占/清理 */ }
108
+ }
109
+ }