@capyclaw/foundation 0.1.4 → 0.1.10

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 (61) hide show
  1. package/README.md +23 -9
  2. package/abi/bridge.mjs +86 -0
  3. package/abi/errors.mjs +4 -0
  4. package/abi/index.mjs +16 -0
  5. package/abi/kinds.mjs +90 -2
  6. package/abi/loader.mjs +285 -184
  7. package/abi/spec.mjs +67 -7
  8. package/abi/version.mjs +63 -5
  9. package/kit/index.mjs +3 -4
  10. package/lib/adapters/client-panel.mjs +98 -0
  11. package/lib/adapters/host-event.mjs +35 -0
  12. package/lib/adapters/http-router.mjs +26 -3
  13. package/lib/adapters/lifecycle-hook.mjs +6 -13
  14. package/lib/adapters/own-server.mjs +113 -0
  15. package/lib/adapters/raw.mjs +69 -0
  16. package/lib/adapters/runtime-driver.mjs +55 -15
  17. package/lib/adapters/service-provider.mjs +77 -0
  18. package/lib/adapters/tool-provider.mjs +11 -4
  19. package/lib/adapters/ui-panel.mjs +11 -4
  20. package/lib/ctx-service.mjs +21 -0
  21. package/lib/host/caps.mjs +13 -5
  22. package/lib/host/contract.mjs +85 -0
  23. package/lib/host/dsh.mjs +10 -1
  24. package/lib/host/memory.mjs +71 -0
  25. package/lib/host.mjs +6 -5
  26. package/lib/kernel.mjs +92 -7
  27. package/lib/skill/scan.mjs +31 -3
  28. package/lib/subsystems/events.mjs +6 -1
  29. package/lib/subsystems/log.mjs +23 -1
  30. package/lib/subsystems/net.mjs +164 -15
  31. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  32. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  33. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  34. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  35. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  36. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  37. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  38. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  39. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  40. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  41. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  42. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  43. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  44. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  45. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  60. package/package.json +6 -3
  61. package/runtime/index.mjs +4 -1
package/abi/loader.mjs CHANGED
@@ -1,251 +1,352 @@
1
- /**
2
- * 插件加载器:把描述符编译成运行时实例。
3
- *
4
- * 四段式,任何副作用都在最后一段:
5
- * 1. validate 纯检查(形状 / 版本 / 能力 / 唯一性),不碰任何资源;
6
- * 2. compile 逐个接口交给适配器;失败则回滚已编译的实例;
7
- * 3. start 运行时就绪(子进程拉起、监听等),异步,失败进 failures;
8
- * 4. commit 登记插件、能力与唯一性占用。
9
- *
10
- * 这样保证:坏描述符不会产生半个插件,也不会留下悬挂端口或子进程。
11
- */
1
+ /** Descriptor loader: synchronous validation/mount, observable asynchronous readiness and cleanup. */
12
2
  import { ABI_MAJOR, getInterfaceKind } from './kinds.mjs'
13
3
  import { validateInterface } from './validate.mjs'
14
4
  import { AbiError, ERROR_CODES, toAbiError } from './errors.mjs'
15
- import { satisfies } from './version.mjs'
16
-
17
- /**
18
- * @param {{
19
- * adapters: Record<string, { kind: string, compile: Function }>,
20
- * capabilities?: Record<string, string>,
21
- * log?: object,
22
- * abiMajor?: number
23
- * }} options
24
- */
5
+ import { satisfies, isValidRange } from './version.mjs'
6
+
7
+ const thenable = (value) => value && typeof value.then === 'function'
8
+
9
+ /** Run in order, retaining immediate effects when all operations are synchronous. */
10
+ function sequence(items, operation) {
11
+ let pending
12
+ for (const item of items) {
13
+ if (pending) pending = pending.then(() => operation(item))
14
+ else {
15
+ const result = operation(item)
16
+ if (thenable(result)) pending = Promise.resolve(result)
17
+ }
18
+ }
19
+ return pending
20
+ }
21
+
25
22
  export function createLoader({ adapters = {}, capabilities = {}, log = null, abiMajor = ABI_MAJOR } = {}) {
26
- /** 能力表可以是对象,也可以是函数(宿主服务晚到时可现查)。 */
27
23
  const capabilityMap = () => (typeof capabilities === 'function' ? capabilities() : capabilities)
28
- /** @type {Map<string, { spec: object, entries: object[], handle: object }>} */
29
24
  const plugins = new Map()
30
- /** 唯一性占用:key -> 插件名 */
31
25
  const uniques = new Map()
32
- /** 已提供能力:name -> { plugin, version } */
33
- const provided = new Map()
34
- /** 运行期失败(start / 异步就绪) */
35
- const failures = []
26
+ const providers = new Map()
27
+ /* 失败按插件 name 键控:同一插件重试成功后清除旧失败,健康检查不再永久红。
28
+ * 旧实现是只增数组,一次瞬时失败就让 failures.length===0 的断言永远失败。 */
29
+ const failures = new Map()
30
+ let shuttingDown = false
31
+ let shutdown
32
+
33
+ function error(code, message, detail = {}) {
34
+ return new AbiError(code, message, detail)
35
+ }
36
+
37
+ function capture(reason, plugin, kind, phase) {
38
+ const normalized = toAbiError(reason, ERROR_CODES.E_ADAPTER_THREW, { plugin, kind, phase })
39
+ normalized.detail = { ...normalized.detail, plugin, kind, phase }
40
+ failures.set(plugin, normalized)
41
+ log?.error?.(`[foundation] ${normalized.message}`)
42
+ return normalized
43
+ }
36
44
 
37
45
  function adapterOf(kind) {
38
46
  const adapter = adapters[kind]
39
47
  if (!adapter || typeof adapter.compile !== 'function') {
40
- throw new AbiError(ERROR_CODES.E_KIND_UNAVAILABLE,
41
- `接口 ${kind} 已定义但内核没有注册适配器`, { kind, available: Object.keys(adapters) })
48
+ throw error(ERROR_CODES.E_KIND_UNAVAILABLE, `接口 ${kind} 已定义但内核没有注册适配器`, { kind })
42
49
  }
43
50
  return adapter
44
51
  }
45
52
 
46
- function assertCapabilities(spec) {
47
- const missing = []
48
- for (const requirement of spec.requires) {
49
- if (!requirement.name.startsWith('os.')) continue // 跨插件能力由 suite 组合期校验,运行时只报告
50
- const version = capabilityMap()[requirement.name]
51
- if (!version) {
52
- missing.push({ name: requirement.name, range: requirement.range, reason: '未提供' })
53
- } else if (!satisfies(version, requirement.range)) {
54
- missing.push({ name: requirement.name, range: requirement.range, reason: `提供 ${version}` })
53
+ function capability(name) {
54
+ const native = capabilityMap()[name]
55
+ if (native) return native
56
+ const owners = providers.get(name)
57
+ return owners?.values().next().value?.version || null
58
+ }
59
+
60
+ function capabilityView() {
61
+ const view = { ...capabilityMap() }
62
+ for (const name of providers.keys()) view[name] ??= capability(name)
63
+ return view
64
+ }
65
+
66
+ function removeProvides(record) {
67
+ for (const offered of record.spec.provides) {
68
+ const owners = providers.get(offered.name)
69
+ owners?.delete(record)
70
+ if (!owners?.size) providers.delete(offered.name)
71
+ }
72
+ }
73
+
74
+ function publishProvides(record) {
75
+ for (const offered of record.spec.provides) {
76
+ if (!providers.has(offered.name)) providers.set(offered.name, new Map())
77
+ providers.get(offered.name).set(record, { version: offered.range })
78
+ }
79
+ }
80
+
81
+ function releaseClaims(record) {
82
+ for (const key of record.claims) {
83
+ if (uniques.get(key) === record) uniques.delete(key)
84
+ }
85
+ }
86
+
87
+ function cleanup(record) {
88
+ if (record.cleanupStarted) return record.cleanupResult || record.cleanupTask
89
+ record.cleanupStarted = true
90
+ let settle
91
+ record.cleanupTask = new Promise((resolve) => { settle = resolve })
92
+ const clean = sequence([...record.entries].reverse(), (entry) => {
93
+ try {
94
+ const result = entry.instance.dispose?.()
95
+ if (thenable(result)) {
96
+ return Promise.resolve(result).catch((reason) => {
97
+ record.cleanupErrors.push(capture(reason, record.spec.name, entry.impl.kind, 'dispose'))
98
+ })
99
+ }
100
+ } catch (reason) {
101
+ record.cleanupErrors.push(capture(reason, record.spec.name, entry.impl.kind, 'dispose'))
55
102
  }
103
+ })
104
+ const done = () => {
105
+ record.resourcesReleased = record.cleanupErrors.length === 0
106
+ if (record.resourcesReleased) releaseClaims(record)
107
+ record.cleanupResult = { ok: record.resourcesReleased, errors: [...record.cleanupErrors] }
108
+ settle(record.cleanupResult)
109
+ return record.cleanupResult
56
110
  }
57
- if (missing.length) {
58
- throw new AbiError(ERROR_CODES.E_CAP_MISSING,
59
- `插件 ${spec.name} 需要的能力不可用:${missing.map((m) => `${m.name}@${m.range}(${m.reason})`).join(',')}`,
60
- { plugin: spec.name, missing })
111
+ if (thenable(clean)) {
112
+ /* done 必达:即便清理序列意外 reject,也要结算 cleanupTask,避免挂起。 */
113
+ clean.then(done, done)
114
+ return record.cleanupTask
61
115
  }
116
+ return done()
62
117
  }
63
118
 
64
- function claimUniqueness(impls, pluginName, committed) {
65
- const batch = new Map()
66
- for (const impl of impls) {
67
- const definition = getInterfaceKind(impl.kind)
68
- if (!definition?.unique) continue
69
- const key = definition.uniqueBy ? `${impl.kind}:${impl[definition.uniqueBy]}` : impl.kind
70
- const owner = committed.get(key) || batch.get(key)
71
- if (owner) {
72
- throw new AbiError(ERROR_CODES.E_DUP_INTERFACE,
73
- `接口 ${key} 已被 ${owner} 占用,${pluginName} 不能重复实现`, { key, owner, plugin: pluginName })
119
+ function disposeRecord(record) {
120
+ if (record.disposal) return record.disposal
121
+ let settle
122
+ // Publish the task before abort/cleanup callbacks; either can reenter disposal.
123
+ record.disposal = new Promise((resolve) => { settle = resolve })
124
+ record.stopRequested = true
125
+ record.controller.abort()
126
+ record.status = 'disposing'
127
+ removeProvides(record)
128
+ const finish = () => {
129
+ const result = cleanup(record)
130
+ const complete = (outcome) => {
131
+ record.status = outcome.ok ? 'disposed' : 'failed'
132
+ if (outcome.ok && plugins.get(record.spec.name) === record) plugins.delete(record.spec.name)
133
+ return outcome
74
134
  }
75
- batch.set(key, pluginName)
135
+ return thenable(result) ? result.then(complete) : complete(result)
76
136
  }
77
- return batch
137
+ // An in-flight start must settle before stop, otherwise resources could reappear after unload.
138
+ const result = record.inStart ? record.startSettled.then(finish) : finish()
139
+ /* settle 必达:result 一旦 reject(如 startSettled 链意外抛错),旧 .then(settle)
140
+ * 不会执行 → disposal 永久挂起 + unhandledRejection。这里补 rejection 分支。 */
141
+ Promise.resolve(result).then(settle, (reason) => {
142
+ record.status = 'failed'
143
+ settle({ ok: false, errors: [toAbiError(reason, ERROR_CODES.E_ADAPTER_THREW, { plugin: record.spec.name, phase: 'dispose' })] })
144
+ })
145
+ return record.disposal
78
146
  }
79
147
 
80
- /**
81
- * 挂载一个插件。同步完成校验与注册,返回 handle。
82
- * @param {object} spec definePlugin 的结果
83
- * @param {object} [config]
84
- * @param {{ baseUrl?: string }} [context]
85
- */
86
148
  function mount(spec, config = {}, context = {}) {
87
- if (!spec || spec.kind !== 'plugin') {
88
- throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'mount 需要 definePlugin 产出的插件描述符', {
89
- got: spec?.kind ?? typeof spec,
90
- })
149
+ if (shuttingDown) throw error('E_KERNEL_CLOSED', '内核已关闭,不能挂载插件')
150
+ if (!spec || spec.kind !== 'plugin' || !Array.isArray(spec.implements)
151
+ || !Array.isArray(spec.requires) || !Array.isArray(spec.provides)) {
152
+ throw error(ERROR_CODES.E_PLUGIN_SHAPE, 'mount 需要 definePlugin 产出的插件描述符')
91
153
  }
92
154
  if (spec.apiVersion !== abiMajor) {
93
- throw new AbiError(ERROR_CODES.E_ABI_MISMATCH,
94
- `插件 ${spec.name} 声明 ABI v${spec.apiVersion},内核为 v${abiMajor}`,
95
- { plugin: spec.name, apiVersion: spec.apiVersion, abiMajor })
155
+ throw error(ERROR_CODES.E_ABI_MISMATCH, `插件 ${spec.name} 声明 ABI v${spec.apiVersion},内核为 v${abiMajor}`)
96
156
  }
97
- if (plugins.has(spec.name)) {
98
- throw new AbiError(ERROR_CODES.E_DUP_PLUGIN, `插件 ${spec.name} 已挂载`, { plugin: spec.name })
157
+ const previous = plugins.get(spec.name)
158
+ if (previous && previous.status !== 'disposed' && previous.status !== 'failed') {
159
+ throw error(ERROR_CODES.E_DUP_PLUGIN, `插件 ${spec.name} 已挂载`)
99
160
  }
100
-
101
- /* 1. validate —— 纯检查,无副作用 */
102
- assertCapabilities(spec)
161
+ if (previous) {
162
+ // 上一次卸载没走完(宿主没登记 disposer,或清理失败)时,残留记录会一直占着 name。
163
+ // 这里摘掉它并尽力回收,否则「关掉插件再启用」会永久失败在 E_DUP_PLUGIN。
164
+ plugins.delete(spec.name)
165
+ void previous.handle?.dispose?.()
166
+ }
167
+ /* 非法范围单独报 E_SCHEMA:旧实现把「range 写错」和「能力真缺」都归成
168
+ * E_CAP_MISSING「能力不可用」,误导排障。先区分两者。 */
169
+ const badRanges = spec.requires.filter((need) => need.name.startsWith('os.') && !isValidRange(need.range))
170
+ if (badRanges.length) {
171
+ throw error(ERROR_CODES.E_SCHEMA, `插件 ${spec.name} 能力范围非法:${badRanges.map((r) => r.raw).join(', ')}`,
172
+ { plugin: spec.name, invalid: badRanges })
173
+ }
174
+ const missing = spec.requires.filter((need) => need.name.startsWith('os.')
175
+ && !satisfies(capabilityMap()[need.name] || '', need.range))
176
+ if (missing.length) {
177
+ throw error(ERROR_CODES.E_CAP_MISSING, `插件 ${spec.name} 需要的能力不可用:${missing.map((r) => r.raw).join(', ')}`,
178
+ { plugin: spec.name, missing })
179
+ }
180
+ const claims = []
103
181
  for (const impl of spec.implements) {
104
182
  const { definition, errors } = validateInterface(impl)
105
- if (!definition) {
106
- throw new AbiError(ERROR_CODES.E_KIND_UNKNOWN, `未知接口种类 ${impl.kind}`, { plugin: spec.name, kind: impl.kind })
183
+ if (!definition) throw error(ERROR_CODES.E_KIND_UNKNOWN, `未知接口种类 ${impl?.kind}`)
184
+ if (errors.length) throw error(ERROR_CODES.E_SCHEMA, `${impl.kind} 描述符非法:${errors.join(';')}`)
185
+ adapterOf(impl.kind)
186
+ if (definition.unique) {
187
+ const key = definition.uniqueBy ? `${impl.kind}:${impl[definition.uniqueBy]}` : impl.kind
188
+ if (uniques.has(key) || claims.includes(key)) {
189
+ throw error(ERROR_CODES.E_DUP_INTERFACE, `接口 ${key} 已被占用`, { key })
190
+ }
191
+ claims.push(key)
107
192
  }
108
- if (errors.length) {
109
- throw new AbiError(ERROR_CODES.E_SCHEMA, `${impl.kind} 描述符非法:${errors.join(';')}`,
110
- { plugin: spec.name, kind: impl.kind, errors })
193
+ }
194
+ for (const offered of spec.provides) {
195
+ if (offered.name.startsWith('os.') || Object.hasOwn(capabilityMap(), offered.name)) {
196
+ throw error('E_CAP_RESERVED', `应用不能提供宿主保留能力 ${offered.name}`)
111
197
  }
112
- adapterOf(impl.kind)
198
+ const conflicting = [...plugins.values()].find((record) => !record.resourcesReleased && record.status !== 'disposed'
199
+ && record.spec.provides.some((item) => item.name === offered.name && item.range !== offered.range))
200
+ if (conflicting) throw error('E_CAP_CONFLICT', `能力 ${offered.name} 的提供版本冲突`, { owner: conflicting.spec.name })
113
201
  }
114
- const batchUniques = claimUniqueness(spec.implements, spec.name, uniques)
115
202
 
116
- /* 2. compile —— 失败回滚 */
117
- const entries = []
203
+ const record = {
204
+ spec, claims, entries: [], controller: new AbortController(), status: 'starting',
205
+ stopRequested: false, inStart: false, cleanupStarted: false, cleanupErrors: [], startError: null,
206
+ }
207
+ for (const key of claims) uniques.set(key, record)
118
208
  try {
119
209
  for (const impl of spec.implements) {
120
- const adapter = adapterOf(impl.kind)
121
- let instance
122
- try {
123
- instance = adapter.compile(impl, { spec, config, context, log, loader: api })
124
- } catch (error) {
125
- throw toAbiError(error, ERROR_CODES.E_ADAPTER_THREW, { plugin: spec.name, kind: impl.kind })
126
- }
127
- entries.push({ impl, instance: instance || {} })
210
+ const instance = adapterOf(impl.kind).compile(impl, {
211
+ spec, config, context, log, loader: api, signal: record.controller.signal,
212
+ })
213
+ if (thenable(instance)) throw error(ERROR_CODES.E_PLUGIN_SHAPE, 'compile 必须同步返回资源实例')
214
+ record.entries.push({ impl, instance: instance || {} })
128
215
  }
129
- } catch (error) {
130
- disposeEntries(entries)
131
- throw error
216
+ } catch (reason) {
217
+ const normalized = toAbiError(reason, ERROR_CODES.E_ADAPTER_THREW, { plugin: spec.name, phase: 'compile' })
218
+ removeProvides(record)
219
+ record.status = 'failed'
220
+ record.startSettled = Promise.resolve()
221
+ record.ready = record.startSettled
222
+ // Reserve before invoking user cleanup: a disposer may initiate global shutdown.
223
+ plugins.set(spec.name, record)
224
+ const rollback = cleanup(record)
225
+ const finishRollback = (result) => {
226
+ if (result.ok && plugins.get(spec.name) === record) plugins.delete(spec.name)
227
+ }
228
+ if (thenable(rollback)) rollback.then(finishRollback)
229
+ else finishRollback(rollback)
230
+ throw normalized
132
231
  }
133
-
134
- /* 3. start —— 异步就绪,失败记录不抛出 */
135
- const state = { disposed: false }
136
- const ready = startEntries(spec, entries, state)
137
-
138
- /* 4. commit */
139
- const ownedProvides = []
140
- for (const capability of spec.provides) {
141
- provided.set(capability.name, { plugin: spec.name, version: capability.range })
142
- ownedProvides.push(capability.name)
232
+ plugins.set(spec.name, record)
233
+ // Sync-only interfaces are operational after compilation, preserving existing skill registration behavior.
234
+ const hasStart = record.entries.some((entry) => typeof entry.instance.start === 'function')
235
+ if (!hasStart) {
236
+ record.status = 'ready'
237
+ failures.delete(spec.name)
238
+ publishProvides(record)
143
239
  }
144
- for (const [key, owner] of batchUniques) uniques.set(key, owner)
145
-
146
- let disposed = false
240
+ record.startSettled = Promise.resolve().then(async () => {
241
+ if (record.stopRequested || !hasStart) return
242
+ record.inStart = true
243
+ try {
244
+ for (const entry of record.entries) {
245
+ if (record.stopRequested) break
246
+ if (typeof entry.instance.start === 'function') {
247
+ try {
248
+ await entry.instance.start({ signal: record.controller.signal })
249
+ } catch (reason) {
250
+ record.startError = capture(reason, spec.name, entry.impl.kind, 'start')
251
+ break
252
+ }
253
+ }
254
+ }
255
+ } finally {
256
+ record.inStart = false
257
+ }
258
+ })
259
+ record.ready = record.startSettled.then(async () => {
260
+ if (record.stopRequested) return
261
+ if (record.startError) {
262
+ record.status = 'failed'
263
+ removeProvides(record)
264
+ await cleanup(record)
265
+ // 启动失败的记录必须让出 name,否则重试挂载永远撞 E_DUP_PLUGIN。
266
+ if (plugins.get(spec.name) === record) plugins.delete(spec.name)
267
+ } else {
268
+ record.status = 'ready'
269
+ failures.delete(spec.name)
270
+ publishProvides(record)
271
+ }
272
+ })
147
273
  const handle = {
148
- name: spec.name,
149
- spec,
150
- interfaces: entries.map((entry) => entry.impl.kind),
151
- ready,
152
- dispose() {
153
- if (disposed) return
154
- disposed = true
155
- state.disposed = true
156
- disposeEntries(entries)
157
- for (const key of batchUniques.keys()) uniques.delete(key)
158
- for (const name of ownedProvides) provided.delete(name)
159
- plugins.delete(spec.name)
274
+ name: spec.name, spec, interfaces: record.entries.map((entry) => entry.impl.kind),
275
+ ready: record.ready,
276
+ get status() { return record.status },
277
+ async result() {
278
+ await record.ready
279
+ return { ok: record.status === 'ready', status: record.status, error: record.startError, cleanupErrors: [...record.cleanupErrors] }
160
280
  },
281
+ async waitUntilReady() {
282
+ const result = await handle.result()
283
+ if (!result.ok) throw result.error || error('E_NOT_READY', `插件 ${spec.name} 未就绪(${result.status})`)
284
+ return handle
285
+ },
286
+ dispose: () => disposeRecord(record),
161
287
  }
162
- plugins.set(spec.name, { spec, entries, handle })
288
+ record.handle = handle
163
289
  return handle
164
290
  }
165
291
 
166
- function startEntries(spec, entries, state) {
167
- const pending = []
168
- for (const entry of entries) {
169
- if (typeof entry.instance.start !== 'function') continue
170
- pending.push(Promise.resolve()
171
- .then(() => {
172
- if (state.disposed) return undefined
173
- return entry.instance.start()
174
- })
175
- .catch((error) => {
176
- const normalized = toAbiError(error, ERROR_CODES.E_ADAPTER_THREW,
177
- { plugin: spec.name, kind: entry.impl.kind, phase: 'start' })
178
- failures.push(normalized)
179
- log?.error?.(`[foundation] ${normalized.message}`)
180
- }))
181
- }
182
- return Promise.all(pending).then(() => undefined)
183
- }
184
-
185
- function disposeEntries(entries) {
186
- for (const entry of [...entries].reverse()) {
187
- try {
188
- entry.instance?.dispose?.()
189
- } catch (error) {
190
- const normalized = toAbiError(error, ERROR_CODES.E_ADAPTER_THREW,
191
- { plugin: entry.impl.kind, phase: 'dispose' })
192
- failures.push(normalized)
193
- log?.error?.(`[foundation] ${normalized.message}`)
194
- }
195
- }
196
- entries.length = 0
197
- }
198
-
199
- /** 当前可用的能力版本:内核承诺优先,其次插件提供。 */
200
- function capability(name) {
201
- return capabilityMap()[name] || provided.get(name)?.version || null
202
- }
203
-
204
- /** 未解析的跨插件能力(运行时只报告,组合期才是硬闸)。 */
205
292
  function unresolved() {
206
293
  const out = []
207
294
  for (const { spec } of plugins.values()) {
208
- for (const requirement of spec.requires) {
209
- if (requirement.name.startsWith('os.')) continue
210
- if (provided.has(requirement.name) || capabilityMap()[requirement.name]) continue
211
- out.push({ plugin: spec.name, capability: requirement.name, range: requirement.range })
295
+ for (const need of spec.requires) {
296
+ const actual = capability(need.name)
297
+ if (actual && satisfies(actual, need.range)) continue
298
+ out.push({ plugin: spec.name, capability: need.name, range: need.range,
299
+ actual, reason: actual ? 'incompatible' : 'missing' })
212
300
  }
213
301
  }
214
302
  return out
215
303
  }
216
304
 
217
- /** 内核状态快照:给 os.report() 与健康检查用。 */
218
305
  function report() {
219
- const capabilityView = { ...capabilityMap() }
220
- for (const [name, info] of provided) capabilityView[name] = info.version
221
306
  return {
222
307
  abiVersion: abiMajor,
223
- plugins: [...plugins.values()].map(({ spec, entries }) => ({
224
- name: spec.name,
225
- interfaces: entries.map((entry) => entry.impl.kind),
226
- requires: spec.requires.map((r) => r.raw),
227
- provides: spec.provides.map((p) => p.raw),
308
+ plugins: [...plugins.values()].map((record) => ({
309
+ name: record.spec.name, status: record.status,
310
+ interfaces: record.entries.map((entry) => entry.impl.kind),
311
+ requires: record.spec.requires.map((r) => r.raw), provides: record.spec.provides.map((p) => p.raw),
228
312
  })),
229
- capabilities: capabilityView,
230
- unresolved: unresolved(),
231
- failures: failures.map((error) => ({ code: error.code, message: error.message, detail: error.detail })),
313
+ capabilities: capabilityView(), unresolved: unresolved(),
314
+ failures: [...failures.values()].map((reason) => ({ code: reason.code, message: reason.message, detail: reason.detail })),
232
315
  }
233
316
  }
234
317
 
235
318
  function disposeAll() {
236
- for (const { handle } of [...plugins.values()].reverse()) handle.dispose()
237
- plugins.clear()
238
- uniques.clear()
239
- provided.clear()
319
+ if (shutdown) return shutdown
320
+ shuttingDown = true
321
+ const records = [...plugins.values()].reverse()
322
+ // Stop every pending start now, not after a preceding plugin's async cleanup.
323
+ for (const record of records) {
324
+ record.stopRequested = true
325
+ record.controller.abort()
326
+ }
327
+ const pending = sequence(records, (record) => disposeRecord(record))
328
+ shutdown = Promise.resolve(pending).then(() => ({ ok: ![...plugins.values()].some((r) => r.cleanupErrors.length) }))
329
+ return shutdown
240
330
  }
241
331
 
242
- const api = Object.freeze({
243
- mount,
244
- report,
245
- capability,
246
- disposeAll,
247
- get size() { return plugins.size },
248
- })
332
+ /**
333
+ * 显式强制释放出口(运维/HMR 用):dispose 失败时「保留所有权」是有意设计,
334
+ * 但一次清理失败会把 name/unique 永久锁死,重挂永远撞 E_DUP_INTERFACE。
335
+ * 这里提供一个人工出口:释放 name/unique/provides 占用,让重挂得以进行。
336
+ * 它**不假装资源已清理**——cleanupErrors 原样保留并返回,调用方须知情。
337
+ */
338
+ function forceRelease(name) {
339
+ const record = plugins.get(name)
340
+ if (!record) return { ok: false, reason: 'no-record' }
341
+ releaseClaims(record)
342
+ removeProvides(record)
343
+ record.resourcesReleased = true
344
+ record.status = 'disposed'
345
+ plugins.delete(name)
346
+ failures.delete(name)
347
+ return { ok: true, forced: true, cleanupErrors: [...record.cleanupErrors] }
348
+ }
249
349
 
350
+ const api = Object.freeze({ mount, report, capability, disposeAll, forceRelease, get size() { return plugins.size } })
250
351
  return api
251
352
  }