@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,310 @@
1
+ /**
2
+ * @capyclaw/asset-service —— 通用对象资产仓库。
3
+ *
4
+ * 功能插件不再各自实现 `/assets/<sha256>`、base64 上传、content-type 与缓存头。
5
+ * 资产按 sha256 去重,url 为 `/assets/<id>`。
6
+ *
7
+ * 两种后端:
8
+ * - workspace:storeClient(ctx.workspace 的 scoped client),资产归当前 work;
9
+ * - file:本地目录,适合无 workspace 的独立运行/测试。
10
+ */
11
+ import crypto from 'node:crypto'
12
+ import fs from 'node:fs'
13
+ import path from 'node:path'
14
+ import { send, readBody } from '@capyclaw/plugin-kit/service/http'
15
+ import { createServiceApi } from '@capyclaw/plugin-kit/service/api'
16
+ import { ASSET_URL_PREFIX } from '@capyclaw/foundation/abi'
17
+
18
+ function sha256(buffer) {
19
+ return crypto.createHash('sha256').update(buffer).digest('hex')
20
+ }
21
+
22
+ const ASSET_ID_RE = /^[a-f0-9]{64}$/
23
+
24
+ function validId(id) {
25
+ return ASSET_ID_RE.test(String(id || ''))
26
+ }
27
+
28
+ function normalizeBuffer(value) {
29
+ if (Buffer.isBuffer(value)) return value
30
+ if (value instanceof Uint8Array) return Buffer.from(value)
31
+ throw new Error('asset: 数据必须是 Buffer/Uint8Array')
32
+ }
33
+
34
+ /** 基于 ctx.workspace 的 scoped WorkspaceClient。 */
35
+ export function createWorkspaceAssetStore({ storeClient, workId = 'main' } = {}) {
36
+ if (!storeClient || typeof storeClient.put !== 'function') throw new Error('createWorkspaceAssetStore 需要 storeClient')
37
+ return {
38
+ kind: 'workspace',
39
+ async put(value, contentType = 'application/octet-stream') {
40
+ const buffer = normalizeBuffer(value)
41
+ const id = sha256(buffer)
42
+ const key = `assets/${id}`
43
+ storeClient.put(workId, key, buffer, { contentType })
44
+ return { id, key, url: `${ASSET_URL_PREFIX}${id}`, size: buffer.length, contentType }
45
+ },
46
+ get(id) {
47
+ if (!validId(id)) return null
48
+ const key = `assets/${id}`
49
+ try {
50
+ const data = storeClient.get(workId, key)
51
+ if (!data) return null
52
+ const meta = storeClient.list(workId).find((item) => item.key === key)
53
+ return { data, contentType: meta?.contentType || 'application/octet-stream' }
54
+ } catch {
55
+ /* 缺失/权限错误按 404 处理,不能把 500 泄漏给资产路由。 */
56
+ return null
57
+ }
58
+ },
59
+ has(id) {
60
+ if (!validId(id)) return false
61
+ try { return !!storeClient.get(workId, `assets/${id}`) } catch { return false }
62
+ },
63
+ }
64
+ }
65
+
66
+ /** 本地目录后端:<dir>/<sha256> + <dir>/<sha256>.meta.json。 */
67
+ export function createFileAssetStore({ dir } = {}) {
68
+ if (!dir) throw new Error('createFileAssetStore 需要 dir')
69
+ fs.mkdirSync(dir, { recursive: true })
70
+ return {
71
+ kind: 'file',
72
+ async put(value, contentType = 'application/octet-stream') {
73
+ const buffer = normalizeBuffer(value)
74
+ const id = sha256(buffer)
75
+ const file = path.join(dir, id)
76
+ const metaFile = file + '.meta.json'
77
+ const existingOk = (() => {
78
+ try { return fs.statSync(file).size === buffer.length } catch { return false }
79
+ })()
80
+ if (!existingOk) {
81
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`
82
+ fs.writeFileSync(tmp, buffer)
83
+ fs.renameSync(tmp, file)
84
+ }
85
+ const metaTmp = `${metaFile}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`
86
+ fs.writeFileSync(metaTmp, JSON.stringify({ contentType, size: buffer.length }))
87
+ fs.renameSync(metaTmp, metaFile)
88
+ return { id, key: id, url: `${ASSET_URL_PREFIX}${id}`, size: buffer.length, contentType }
89
+ },
90
+ get(id) {
91
+ if (!validId(id)) return null
92
+ const file = path.join(dir, path.basename(String(id)))
93
+ try {
94
+ const data = fs.readFileSync(file)
95
+ /* 内容寻址仓库必须复核 hash:截断/篡改的对象不能静默返回。 */
96
+ if (sha256(data) !== id) {
97
+ console.error(`[asset-service] 对象校验失败,拒绝返回: ${id}`)
98
+ return null
99
+ }
100
+ let contentType = 'application/octet-stream'
101
+ try { contentType = JSON.parse(fs.readFileSync(file + '.meta.json', 'utf8')).contentType || contentType } catch { /* 默认 */ }
102
+ return { data, contentType }
103
+ } catch {
104
+ return null
105
+ }
106
+ },
107
+ has(id) {
108
+ if (!validId(id)) return false
109
+ try { return fs.existsSync(path.join(dir, path.basename(String(id)))) } catch { return false }
110
+ },
111
+ /** 删除单个对象(data + meta)。内容寻址仓库此前只增不删,磁盘无界增长。 */
112
+ async delete(id) {
113
+ if (!validId(id)) return false
114
+ const file = path.join(dir, path.basename(String(id)))
115
+ let existed = false
116
+ try {
117
+ existed = fs.existsSync(file)
118
+ fs.rmSync(file, { force: true })
119
+ fs.rmSync(file + '.meta.json', { force: true })
120
+ } catch { /* 尽力删除 */ }
121
+ return existed
122
+ },
123
+ /**
124
+ * 垃圾回收:清崩溃残留的孤儿 .tmp、按 mtime 龄淘汰、按总量 LRU 淘汰。
125
+ * keepIds 里的对象(仍被引用)永不删。返回 {removed, freedBytes, orphanTmpRemoved}。
126
+ */
127
+ async gc({ maxAgeMs = 0, maxBytes = 0, keepIds = [] } = {}) {
128
+ const keep = new Set(keepIds)
129
+ const now = Date.now()
130
+ let removed = 0
131
+ let freedBytes = 0
132
+ let orphanTmpRemoved = 0
133
+ let names
134
+ try { names = fs.readdirSync(dir) } catch { return { removed, freedBytes, orphanTmpRemoved } }
135
+ /* 孤儿 tmp:put 中途崩溃留下的半成品,超过 1h 宽限才清(避免误删在途写入)。 */
136
+ for (const name of names) {
137
+ if (!name.includes('.tmp-')) continue
138
+ const full = path.join(dir, name)
139
+ try {
140
+ const st = fs.statSync(full)
141
+ if (now - st.mtimeMs > 3600000) { fs.rmSync(full, { force: true }); orphanTmpRemoved += 1 }
142
+ } catch { /* 忽略 */ }
143
+ }
144
+ const objects = []
145
+ for (const name of fs.readdirSync(dir)) {
146
+ if (!validId(name)) continue
147
+ const full = path.join(dir, name)
148
+ try { const st = fs.statSync(full); objects.push({ id: name, full, size: st.size, mtime: st.mtimeMs }) } catch { /* 忽略 */ }
149
+ }
150
+ const removeObject = (o) => {
151
+ try {
152
+ fs.rmSync(o.full, { force: true })
153
+ fs.rmSync(o.full + '.meta.json', { force: true })
154
+ removed += 1
155
+ freedBytes += o.size
156
+ } catch { /* 忽略 */ }
157
+ }
158
+ if (maxAgeMs > 0) {
159
+ for (const o of objects) {
160
+ if (!keep.has(o.id) && now - o.mtime > maxAgeMs) removeObject(o)
161
+ }
162
+ }
163
+ if (maxBytes > 0) {
164
+ const alive = objects.filter((o) => fs.existsSync(o.full)).sort((a, b) => a.mtime - b.mtime)
165
+ let total = alive.reduce((sum, o) => sum + o.size, 0)
166
+ for (const o of alive) {
167
+ if (total <= maxBytes) break
168
+ if (keep.has(o.id)) continue
169
+ removeObject(o)
170
+ total -= o.size
171
+ }
172
+ }
173
+ return { removed, freedBytes, orphanTmpRemoved }
174
+ },
175
+ }
176
+ }
177
+
178
+ /** 防止 text/html / svg 在 loopback 同源执行脚本;图片仍按原 MIME 内联。
179
+ * 安全类型保留原始参数(charset 等),不再一刀切剥掉——否则文本资产 charset 丢失。 */
180
+ function safeContentType(type) {
181
+ const raw = String(type || '').replace(/[\r\n]/g, '').trim()
182
+ const base = raw.split(';')[0].trim().toLowerCase() || 'application/octet-stream'
183
+ if (base === 'text/html' || base === 'application/xhtml+xml' || base === 'image/svg+xml') {
184
+ return 'text/plain; charset=utf-8'
185
+ }
186
+ return raw || 'application/octet-stream'
187
+ }
188
+
189
+ /**
190
+ * service-host 兼容的资产路由。
191
+ * GET/HEAD `/assets/<id>`(同时兼容 `<basePath>/assets/<id>`);
192
+ * POST `/assets` 或 `<basePath>/assets`(JSON: { data: base64, contentType })。
193
+ */
194
+ export function createAssetRoutes({ assetStore, basePath = '', maxUploadBytes = 10 * 1024 * 1024 } = {}) {
195
+ const prefix = basePath === '/' ? '' : String(basePath || '').replace(/\/+$/, '')
196
+ const getPrefixes = [ASSET_URL_PREFIX, prefix ? `${prefix}${ASSET_URL_PREFIX}` : null].filter(Boolean)
197
+ const postPaths = new Set(['/assets', prefix ? `${prefix}/assets` : null].filter(Boolean))
198
+ return async function assetRoutes(req, res, u) {
199
+ const p = u.pathname
200
+ if (req.method === 'GET' || req.method === 'HEAD') {
201
+ const getPrefix = getPrefixes.find((candidate) => p.startsWith(candidate))
202
+ if (getPrefix) {
203
+ if (!assetStore) { send(req, res, 404, { error: 'asset store unavailable' }); return true }
204
+ let id
205
+ try { id = decodeURIComponent(p.slice(getPrefix.length)) } catch {
206
+ /* 畸形百分号编码(如 /assets/%zz):decodeURIComponent 抛 URIError,
207
+ * 不包会一路冒成 500。这是客户端错误,回 400。 */
208
+ send(req, res, 400, { error: 'malformed asset id encoding' }); return true
209
+ }
210
+ if (!validId(id)) { send(req, res, 404, { error: 'asset not found' }); return true }
211
+ const asset = assetStore.get(id)
212
+ if (!asset) { send(req, res, 404, { error: 'asset not found' }); return true }
213
+ res.writeHead(200, {
214
+ 'content-type': safeContentType(asset.contentType),
215
+ 'content-length': asset.data.length,
216
+ 'cache-control': 'public, max-age=31536000, immutable',
217
+ 'x-content-type-options': 'nosniff',
218
+ 'referrer-policy': 'no-referrer',
219
+ })
220
+ res.end(req.method === 'HEAD' ? undefined : asset.data)
221
+ return true
222
+ }
223
+ }
224
+ if (postPaths.has(p) && req.method === 'POST') {
225
+ if (!assetStore) { send(req, res, 503, { error: 'asset store unavailable' }); return true }
226
+ let body
227
+ try { body = await readBody(req, maxUploadBytes) } catch (error) {
228
+ const status = error?.code === 'BODY_TOO_LARGE' ? 413 : 400
229
+ send(req, res, status, { error: String(error.message || error) })
230
+ return true
231
+ }
232
+ if (!body || typeof body.data !== 'string' || !body.data) {
233
+ send(req, res, 400, { error: '缺少图片数据' })
234
+ return true
235
+ }
236
+ const buffer = Buffer.from(body.data, 'base64')
237
+ /* 严格 base64:非法字符 / 错误填充 / 非规范编码一律 400,不再宽松解码把损坏
238
+ * 字节静默入库(B 轴 P0-7)。round-trip 比对同时挡住非规范填充位。 */
239
+ if (!/^[A-Za-z0-9+/]*={0,2}$/.test(body.data) || body.data.length % 4 !== 0 || buffer.toString('base64') !== body.data) {
240
+ send(req, res, 400, { error: '图片数据不是合法 base64' })
241
+ return true
242
+ }
243
+ if (!buffer.length) { send(req, res, 400, { error: '图片数据为空' }); return true }
244
+ const asset = await assetStore.put(buffer, body.contentType || 'application/octet-stream')
245
+ /* 回给与 GET 一致的 sanitized content-type(保留 charset、script 类转 text/plain)。 */
246
+ send(req, res, 200, { ok: true, ...asset, contentType: safeContentType(asset.contentType) })
247
+ return true
248
+ }
249
+ return false
250
+ }
251
+ }
252
+
253
+ export function createAssetHost(config = {}) {
254
+ const defaultStore = config.storeClient
255
+ ? createWorkspaceAssetStore({ storeClient: config.storeClient, workId: config.workId })
256
+ : config.dir
257
+ ? createFileAssetStore({ dir: config.dir })
258
+ : null
259
+
260
+ /* 能力标签如实申报:gc/delete 仅当底层 store 支持时才 advertise(file store 有,
261
+ * workspace store 无),避免「声明满足、活实例缺方法」。 */
262
+ const tags = ['workspace-store', 'file-store', 'routes', 'sha256', 'mount']
263
+ if (typeof defaultStore?.gc === 'function') tags.push('gc')
264
+ if (typeof defaultStore?.delete === 'function') tags.push('delete')
265
+
266
+ return {
267
+ api: createServiceApi('assets', '1.0.0', tags),
268
+ version: '0.1.0',
269
+ createStore: createWorkspaceAssetStore,
270
+ createFileStore: createFileAssetStore,
271
+ routes: createAssetRoutes,
272
+ store: defaultStore,
273
+ /**
274
+ * 每个 service-host app 只挂一次资产路由,避免多个插件重复争抢 /assets。
275
+ * @param {object} hostApp createServiceApp() 返回值
276
+ * @param {{ store?: object, basePath?: string }} options
277
+ */
278
+ mount(hostApp, { store = defaultStore, basePath = '' } = {}) {
279
+ if (!hostApp || typeof hostApp.use !== 'function') throw new Error('assets.mount 需要 service-host app')
280
+ if (!store) throw new Error('assets.mount: 没有可用 store')
281
+ if (hostApp.__dshAssetsMounted) return () => {}
282
+ hostApp.__dshAssetsMounted = true
283
+ const unuse = hostApp.use(createAssetRoutes({ assetStore: store, basePath }))
284
+ let disposed = false
285
+ return () => {
286
+ if (disposed) return
287
+ disposed = true
288
+ /* 真正卸载路由;否则热重载后旧 store 仍会抢答 /assets。 */
289
+ if (typeof unuse === 'function') unuse()
290
+ hostApp.__dshAssetsMounted = false
291
+ }
292
+ },
293
+ async put(value, contentType) {
294
+ if (!defaultStore) throw new Error('asset-service: 未配置 storeClient/dir')
295
+ return defaultStore.put(value, contentType)
296
+ },
297
+ get(id) {
298
+ if (!defaultStore) throw new Error('asset-service: 未配置 storeClient/dir')
299
+ return defaultStore.get(id)
300
+ },
301
+ async delete(id) {
302
+ if (typeof defaultStore?.delete !== 'function') throw new Error('asset-service: 当前 store 不支持 delete')
303
+ return defaultStore.delete(id)
304
+ },
305
+ async gc(options) {
306
+ if (typeof defaultStore?.gc !== 'function') throw new Error('asset-service: 当前 store 不支持 gc')
307
+ return defaultStore.gc(options)
308
+ },
309
+ }
310
+ }
@@ -0,0 +1,51 @@
1
+ # @capyclaw/foundation
2
+
3
+ dsh 插件基石层:接口 ABI、插件加载器与内核服务 `ctx.os`。
4
+
5
+ 应用插件不再写 `inject` / `apply` / provider 装配,只声明「我实现了哪个接口」:
6
+
7
+ ```js
8
+ import { createPlugin, skillProvider } from '@capyclaw/foundation/abi'
9
+
10
+ export const { name, inject, apply } = createPlugin({
11
+ name: 'canvas',
12
+ requires: ['canvas.runtime@^1'],
13
+ implements: [skillProvider({ skill: './skills/canvas' })],
14
+ }, import.meta.url)
15
+ ```
16
+
17
+ ## 四个入口
18
+
19
+ | 入口 | 内容 | 谁用 |
20
+ |---|---|---|
21
+ | `.` | Cordis 插件,产出 `ctx.os` | dsh profile |
22
+ | `./abi` | 描述符构建器、加载器、错误码、版本工具 | 应用插件 |
23
+ | `./kit` | plugin-kit 兼容导出,包含 Node/dsh 耦合,非纯函数库 | 兼容调用方 |
24
+ | `./runtime` | `createKernel` 等宿主 API | dsh 之外的宿主(独立技能服务、测试夹具) |
25
+
26
+ ## 状态
27
+
28
+ - 包清单当前为 `0.1.6`;0.1.6 修的是「关掉插件再启用撞 E_DUP_PLUGIN」(disposer 未登记 + 失败
29
+ 记录占名),详见下面的「生命周期」。
30
+ - 分层:应用插件 → ABI → 内核 → Host 适配器 → 本地 Node.js agent 运行时。
31
+ dsh 服务访问位于 Host 适配层;memory 只是参考实现,不证明第二个真实 agent 兼容。
32
+ HTTP/资源/进程仍有本地 Node 协议约束,详见 `docs/HOST-ADAPTER.md`。
33
+ - ABI v1,六个标准接口 + `host-event@1` + `client-panel@1` + `service-provider@1` +
34
+ `own-server@1` + 可执行 `raw@1`;基建插件使用 `defineDriver` 驱动入口。
35
+ - 能力表按 `ctx` 实际服务探测(见 `lib/kernel.mjs` 的 `detectCapabilities`),不做空头承诺。
36
+ - 当前仓库:27 个插件走标准接口,`raw@1` 当前为空,6 个基建插件走
37
+ `defineDriver` 驱动层;`meta/foundation.allowlist.json` 的模糊豁免为 0。
38
+ 详见 `docs/POLICY.md` 与 `docs/spec/plugin-abi.md`。
39
+
40
+ 设计规范见 `docs/spec/plugin-abi.md`,强制规则见 `docs/POLICY.md`。
41
+
42
+ ## 生命周期(0.1.6 起)
43
+
44
+ `createPlugin().apply` 会把 `os.mount()` 的 disposer 通过 `ctx.effect(() => () => dispose())`
45
+ 登记到本次激活的 ctx 上——**不能只靠 apply 的返回值**:Cordis 只认 `ctx.effect` 回调返回的
46
+ disposer,返回值不可靠。漏登记时,关掉插件后内核里的记录不会摘除,再次启用就会撞
47
+ `E_DUP_PLUGIN: 插件 xxx 已挂载`。
48
+
49
+ 加载器侧另有两条兜底:`mount()` 遇到 `disposed` / `failed` 的旧记录会先摘掉并尽力回收;
50
+ `start` 失败清理完成后立即让出插件名。两者共同保证「关掉 → 再启用」可重复无数次。
51
+
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 资产引用契约的单一真源(公共 ABI 常量)。
3
+ *
4
+ * 互操作标准里资产有两副面孔,前缀在这里定义一次,内核门面与资产服务都引用它,
5
+ * 避免「路由实现」与「URL 门面」各写一份 '/assets/' 而漂移:
6
+ * - 字节仓 HTTP 路由前缀 ASSET_URL_PREFIX = '/assets/' (asset-service 挂 GET/HEAD)
7
+ * - 结构化正文里的引用前缀 ASSET_REF_PREFIX = '@asset/' (work-store 信封/正文只存引用)
8
+ *
9
+ * 这是契约常量,不是宿主服务名——放 ABI 层,应用与驱动都可 import。
10
+ */
11
+
12
+ /** 资产字节仓的 HTTP 路由前缀(asset-service 实现,内核 os.assets.url 复用)。 */
13
+ export const ASSET_URL_PREFIX = '/assets/'
14
+
15
+ /** 结构化正文/产物信封里的内容寻址引用前缀(@asset/<sha256>)。 */
16
+ export const ASSET_REF_PREFIX = '@asset/'
17
+
18
+ /** 由资产 id 生成可加载 URL:/assets/<id>(id 做 URI 编码)。 */
19
+ export function assetUrl(id) {
20
+ return `${ASSET_URL_PREFIX}${encodeURIComponent(String(id))}`
21
+ }
22
+
23
+ /** 由资产 id 生成规范引用:@asset/<id>。 */
24
+ export function assetRef(id) {
25
+ return `${ASSET_REF_PREFIX}${String(id)}`
26
+ }
@@ -0,0 +1,88 @@
1
+ /**
2
+ * 桥(editor bridge)与文档模型的标准声明。
3
+ *
4
+ * 这一层只放「协议常量 + 声明校验」,不放运行时:
5
+ * - 常量:协议版本、模型版本、能力名(suite 清单与 healthz 都用它)
6
+ * - declareBridge():把工作台的声明冻结成标准形状
7
+ * - assertBridgeRuntime():启动/巡检时把「声明」与「运行时实际上报」对齐
8
+ *
9
+ * 运行时(relay / 队列 / 租约)仍在 @capyclaw/document-workbench + service-host,
10
+ * 不进 ABI 层:foundation 是所有插件的地基,不该背 HTTP/store 依赖。
11
+ *
12
+ * 能力名(与 suite 清单的 requires/provides.capabilities 对应):
13
+ * editor.bridge —— 插件提供一个编辑器权威桥(/healthz + /status + /watch + /ack)
14
+ * doc.model —— 插件提供文档模型(稳定 ID / 清单 / 定位 / 编辑计划 / 校验)
15
+ */
16
+
17
+ import { AbiError, ERROR_CODES } from './errors.mjs'
18
+
19
+ /** 桥协议版本:端点集合与状态机语义的主版本。不兼容变更才升 major。 */
20
+ export const BRIDGE_PROTOCOL_VERSION = '1.0.0'
21
+
22
+ /** 文档模型版本:清单字段、定位器语义、编辑 op 的主版本。 */
23
+ export const DOC_MODEL_VERSION = '1.0.0'
24
+
25
+ export const BRIDGE_CAPABILITY = 'editor.bridge'
26
+ export const DOC_MODEL_CAPABILITY = 'doc.model'
27
+
28
+ /** healthz 里桥声明的字段名(避免与既有的 bridge: '<name>' 字符串冲突)。 */
29
+ export const BRIDGE_INFO_FIELD = 'bridgeInfo'
30
+
31
+ const ID_RE = /^[a-z0-9][a-z0-9-]*$/
32
+ const VERSION_RE = /^\d+\.\d+\.\d+$/
33
+
34
+ /**
35
+ * 校验并冻结一份桥声明。
36
+ * @param {{ id: string, protocol?: string, model?: string|null, editor?: 'required'|'optional' }} input
37
+ */
38
+ export function declareBridge(input = {}) {
39
+ const { id, protocol = BRIDGE_PROTOCOL_VERSION, model = null, editor = 'required' } = input
40
+ const errors = []
41
+ if (typeof id !== 'string' || !ID_RE.test(id)) errors.push(`id 必须是 kebab-case:${id}`)
42
+ if (!VERSION_RE.test(protocol)) errors.push(`protocol 版本非法:${protocol}`)
43
+ if (model !== null && !VERSION_RE.test(model)) errors.push(`model 版本非法:${model}`)
44
+ if (editor !== 'required' && editor !== 'optional') errors.push(`editor 只能是 required/optional:${editor}`)
45
+ if (errors.length) throw new AbiError(ERROR_CODES.E_SCHEMA, `桥声明非法:${errors.join(';')}`, { errors })
46
+ return Object.freeze({ id, protocol, model, editor })
47
+ }
48
+
49
+ /** 桥声明 → suite 清单里的 provides.capabilities。 */
50
+ export function bridgeCapabilities(declaration) {
51
+ const decl = declaration && declaration.protocol ? declaration : declareBridge(declaration)
52
+ return Object.freeze({
53
+ [BRIDGE_CAPABILITY]: decl.protocol,
54
+ ...(decl.model ? { [DOC_MODEL_CAPABILITY]: decl.model } : {}),
55
+ })
56
+ }
57
+
58
+ /** 桥声明 → suite 清单里工具面对运行时的 requires.capabilities(skill 包用)。 */
59
+ export function bridgeConsumerRequirements(ns, { needsModel = false } = {}) {
60
+ const out = { [`${ns}.runtime`]: `^${BRIDGE_PROTOCOL_VERSION}` }
61
+ if (needsModel) out[DOC_MODEL_CAPABILITY] = `^${DOC_MODEL_VERSION}`
62
+ return Object.freeze(out)
63
+ }
64
+
65
+ /**
66
+ * 声明与运行时对账:启动或巡检时调用。
67
+ *
68
+ * @param {object} declaration declareBridge 的结果(来自插件代码/清单)
69
+ * @param {object} runtime healthz 里的 bridgeInfo(实际运行值)
70
+ * @returns {{ ok: boolean, issues: string[] }}
71
+ */
72
+ export function assertBridgeRuntime(declaration, runtime) {
73
+ const issues = []
74
+ const decl = declaration && declaration.id ? declaration : declareBridge(declaration || {})
75
+ if (!runtime || typeof runtime !== 'object') {
76
+ return { ok: false, issues: [`运行时没有上报 ${BRIDGE_INFO_FIELD}`] }
77
+ }
78
+ if (runtime.id !== decl.id) issues.push(`id 不一致:声明 ${decl.id} / 运行 ${runtime.id}`)
79
+ if (runtime.protocol !== decl.protocol) {
80
+ issues.push(`协议版本不一致:声明 ${decl.protocol} / 运行 ${runtime.protocol}`)
81
+ }
82
+ const declaredModel = decl.model || null
83
+ const runtimeModel = runtime.model || null
84
+ if (declaredModel !== runtimeModel) {
85
+ issues.push(`模型版本不一致:声明 ${declaredModel || '无'} / 运行 ${runtimeModel || '无'}`)
86
+ }
87
+ return { ok: issues.length === 0, issues }
88
+ }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * ABI 错误模型:稳定的错误码 + 结构化 detail。
3
+ *
4
+ * 约定:
5
+ * - 应用插件按 code 分支,不解析 message 文案;
6
+ * - message 面向人,detail 面向程序;
7
+ * - 所有加载期失败都必须是 AbiError,不允许裸 Error 穿透。
8
+ */
9
+
10
+ /** 稳定错误码。新增只能追加,不得改语义。 */
11
+ export const ERROR_CODES = Object.freeze({
12
+ /** 插件入口形状不对:缺 name / 没有 implements / 导出了 apply 等。 */
13
+ E_PLUGIN_SHAPE: 'E_PLUGIN_SHAPE',
14
+ /** 插件声明的 ABI 主版本与内核不兼容。 */
15
+ E_ABI_MISMATCH: 'E_ABI_MISMATCH',
16
+ /** 描述符的 kind 不在内核认识的接口表里。 */
17
+ E_KIND_UNKNOWN: 'E_KIND_UNKNOWN',
18
+ /** 描述符字段不满足接口 schema。 */
19
+ E_SCHEMA: 'E_SCHEMA',
20
+ /** 内核没有提供该能力(通常是 os.* 子系统缺失)。 */
21
+ E_CAP_MISSING: 'E_CAP_MISSING',
22
+ /** 唯一性接口被第二个插件实现(例如同 id 的 runtime-driver)。 */
23
+ E_DUP_INTERFACE: 'E_DUP_INTERFACE',
24
+ /** 同名插件被重复挂载。 */
25
+ E_DUP_PLUGIN: 'E_DUP_PLUGIN',
26
+ /** 内核没有为这个 kind 注册适配器(接口定义存在但实现未就绪)。 */
27
+ E_KIND_UNAVAILABLE: 'E_KIND_UNAVAILABLE',
28
+ /** 适配器在编译期抛错。 */
29
+ E_ADAPTER_THREW: 'E_ADAPTER_THREW',
30
+ /** 插件入口没有拿到 baseUrl,相对路径无法解析。 */
31
+ E_BASE_URL_MISSING: 'E_BASE_URL_MISSING',
32
+ /** 运行时没有 ctx.os:foundation 未安装或未启用。 */
33
+ E_KERNEL_MISSING: 'E_KERNEL_MISSING',
34
+ E_KERNEL_CLOSED: 'E_KERNEL_CLOSED',
35
+ E_NOT_READY: 'E_NOT_READY',
36
+ E_CAP_RESERVED: 'E_CAP_RESERVED',
37
+ E_CAP_CONFLICT: 'E_CAP_CONFLICT',
38
+ })
39
+
40
+ export class AbiError extends Error {
41
+ /**
42
+ * @param {string} code ERROR_CODES 中的一项
43
+ * @param {string} message 面向人的说明
44
+ * @param {Record<string, unknown>} [detail] 面向程序的结构化信息
45
+ */
46
+ constructor(code, message, detail = {}) {
47
+ super(`[${code}] ${message}`)
48
+ this.name = 'AbiError'
49
+ this.code = code
50
+ this.detail = detail
51
+ if (detail.cause instanceof Error) this.cause = detail.cause
52
+ }
53
+ }
54
+
55
+ export function isAbiError(error) {
56
+ return error instanceof AbiError
57
+ }
58
+
59
+ /** 把任意异常归一成 AbiError(已归一的原样返回)。 */
60
+ export function toAbiError(error, code = ERROR_CODES.E_ADAPTER_THREW, detail = {}) {
61
+ if (error instanceof AbiError) return error
62
+ return new AbiError(code, error?.message || String(error), { ...detail, cause: error })
63
+ }
@@ -0,0 +1,50 @@
1
+ /** 接口 ABI 的唯一入口:应用插件只需要 import 这个模块。 */
2
+ export { ABI_MAJOR, INTERFACE_KINDS, INTERFACE_KIND_NAMES, getInterfaceKind } from './kinds.mjs'
3
+ export {
4
+ defineInterface,
5
+ definePlugin,
6
+ createPlugin,
7
+ skillProvider,
8
+ toolProvider,
9
+ runtimeDriver,
10
+ httpRouter,
11
+ uiPanel,
12
+ lifecycleHook,
13
+ hostEvent,
14
+ clientPanel,
15
+ ownServer,
16
+ serviceProvider,
17
+ defineDriver,
18
+ rawPlugin,
19
+ } from './spec.mjs'
20
+ /* createLoader 是宿主/测试侧装配 API(内核 createKernel 与一致性测试用),虽从 abi 导出,
21
+ * 应用插件不应直接调用——应用只用 createPlugin + 接口 builders(见 plugin-abi.md §二)。 */
22
+ export { createLoader } from './loader.mjs'
23
+ export {
24
+ BRIDGE_CAPABILITY,
25
+ BRIDGE_INFO_FIELD,
26
+ BRIDGE_PROTOCOL_VERSION,
27
+ DOC_MODEL_CAPABILITY,
28
+ DOC_MODEL_VERSION,
29
+ assertBridgeRuntime,
30
+ bridgeCapabilities,
31
+ bridgeConsumerRequirements,
32
+ declareBridge,
33
+ } from './bridge.mjs'
34
+ export {
35
+ SURFACE_LIFECYCLE_VERSION,
36
+ SURFACE_LIFECYCLE_CAPABILITY_SUFFIX,
37
+ VISIBILITY_ACK_MESSAGE,
38
+ VISIBILITY_DEFAULTS,
39
+ VISIBILITY_MESSAGE,
40
+ VISIBILITY_STATES,
41
+ assertSurfaceLifecycle,
42
+ isVisibilityState,
43
+ normalizeVisibilityState,
44
+ surfaceLifecycleCapability,
45
+ } from './visibility.mjs'
46
+ export { ASSET_URL_PREFIX, ASSET_REF_PREFIX, assetUrl, assetRef } from './assets.mjs'
47
+ export { validateInterface } from './validate.mjs'
48
+ export { AbiError, ERROR_CODES, isAbiError, toAbiError } from './errors.mjs'
49
+ export { validateSchema } from './schema.mjs'
50
+ export { parseVersion, compareVersions, satisfies } from './version.mjs'