@capyclaw/foundation 0.1.4 → 0.1.9
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.
- package/README.md +23 -9
- package/abi/bridge.mjs +86 -0
- package/abi/errors.mjs +4 -0
- package/abi/index.mjs +16 -0
- package/abi/kinds.mjs +90 -2
- package/abi/loader.mjs +276 -182
- package/abi/spec.mjs +62 -5
- package/kit/index.mjs +3 -4
- package/lib/adapters/client-panel.mjs +98 -0
- package/lib/adapters/host-event.mjs +35 -0
- package/lib/adapters/http-router.mjs +26 -3
- package/lib/adapters/lifecycle-hook.mjs +6 -13
- package/lib/adapters/own-server.mjs +113 -0
- package/lib/adapters/raw.mjs +68 -0
- package/lib/adapters/runtime-driver.mjs +47 -14
- package/lib/adapters/service-provider.mjs +77 -0
- package/lib/adapters/tool-provider.mjs +11 -4
- package/lib/adapters/ui-panel.mjs +11 -4
- package/lib/ctx-service.mjs +21 -0
- package/lib/host/caps.mjs +13 -5
- package/lib/host/contract.mjs +85 -0
- package/lib/host/dsh.mjs +10 -1
- package/lib/host/memory.mjs +44 -0
- package/lib/host.mjs +6 -5
- package/lib/kernel.mjs +92 -7
- package/lib/subsystems/events.mjs +6 -1
- package/lib/subsystems/log.mjs +23 -1
- package/lib/subsystems/net.mjs +154 -15
- package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
- package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
- package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
- package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
- package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
- package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
- package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
- package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
- package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
- package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
- package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
- package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
- package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
- package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
- package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
- package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
- package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
- package/package.json +6 -3
- package/runtime/index.mjs +4 -1
package/abi/loader.mjs
CHANGED
|
@@ -1,251 +1,345 @@
|
|
|
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
5
|
import { satisfies } from './version.mjs'
|
|
16
6
|
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
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
|
-
|
|
33
|
-
|
|
34
|
-
|
|
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
|
|
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
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
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 (
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
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
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
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
|
-
|
|
135
|
+
return thenable(result) ? result.then(complete) : complete(result)
|
|
76
136
|
}
|
|
77
|
-
|
|
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 (
|
|
88
|
-
|
|
89
|
-
|
|
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
|
|
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
|
-
|
|
98
|
-
|
|
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
|
-
|
|
102
|
-
|
|
161
|
+
if (previous) {
|
|
162
|
+
// 上一次卸载没走完(宿主没登记 disposer,或清理失败)时,残留记录会一直占着 name。
|
|
163
|
+
// 这里摘掉它并尽力回收,否则「关掉插件再启用」会永久失败在 E_DUP_PLUGIN。
|
|
164
|
+
plugins.delete(spec.name)
|
|
165
|
+
void previous.handle?.dispose?.()
|
|
166
|
+
}
|
|
167
|
+
const missing = spec.requires.filter((need) => need.name.startsWith('os.')
|
|
168
|
+
&& !satisfies(capabilityMap()[need.name] || '', need.range))
|
|
169
|
+
if (missing.length) {
|
|
170
|
+
throw error(ERROR_CODES.E_CAP_MISSING, `插件 ${spec.name} 需要的能力不可用:${missing.map((r) => r.raw).join(', ')}`,
|
|
171
|
+
{ plugin: spec.name, missing })
|
|
172
|
+
}
|
|
173
|
+
const claims = []
|
|
103
174
|
for (const impl of spec.implements) {
|
|
104
175
|
const { definition, errors } = validateInterface(impl)
|
|
105
|
-
if (!definition) {
|
|
106
|
-
|
|
176
|
+
if (!definition) throw error(ERROR_CODES.E_KIND_UNKNOWN, `未知接口种类 ${impl?.kind}`)
|
|
177
|
+
if (errors.length) throw error(ERROR_CODES.E_SCHEMA, `${impl.kind} 描述符非法:${errors.join(';')}`)
|
|
178
|
+
adapterOf(impl.kind)
|
|
179
|
+
if (definition.unique) {
|
|
180
|
+
const key = definition.uniqueBy ? `${impl.kind}:${impl[definition.uniqueBy]}` : impl.kind
|
|
181
|
+
if (uniques.has(key) || claims.includes(key)) {
|
|
182
|
+
throw error(ERROR_CODES.E_DUP_INTERFACE, `接口 ${key} 已被占用`, { key })
|
|
183
|
+
}
|
|
184
|
+
claims.push(key)
|
|
107
185
|
}
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
186
|
+
}
|
|
187
|
+
for (const offered of spec.provides) {
|
|
188
|
+
if (offered.name.startsWith('os.') || Object.hasOwn(capabilityMap(), offered.name)) {
|
|
189
|
+
throw error('E_CAP_RESERVED', `应用不能提供宿主保留能力 ${offered.name}`)
|
|
111
190
|
}
|
|
112
|
-
|
|
191
|
+
const conflicting = [...plugins.values()].find((record) => !record.resourcesReleased && record.status !== 'disposed'
|
|
192
|
+
&& record.spec.provides.some((item) => item.name === offered.name && item.range !== offered.range))
|
|
193
|
+
if (conflicting) throw error('E_CAP_CONFLICT', `能力 ${offered.name} 的提供版本冲突`, { owner: conflicting.spec.name })
|
|
113
194
|
}
|
|
114
|
-
const batchUniques = claimUniqueness(spec.implements, spec.name, uniques)
|
|
115
195
|
|
|
116
|
-
|
|
117
|
-
|
|
196
|
+
const record = {
|
|
197
|
+
spec, claims, entries: [], controller: new AbortController(), status: 'starting',
|
|
198
|
+
stopRequested: false, inStart: false, cleanupStarted: false, cleanupErrors: [], startError: null,
|
|
199
|
+
}
|
|
200
|
+
for (const key of claims) uniques.set(key, record)
|
|
118
201
|
try {
|
|
119
202
|
for (const impl of spec.implements) {
|
|
120
|
-
const
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
203
|
+
const instance = adapterOf(impl.kind).compile(impl, {
|
|
204
|
+
spec, config, context, log, loader: api, signal: record.controller.signal,
|
|
205
|
+
})
|
|
206
|
+
if (thenable(instance)) throw error(ERROR_CODES.E_PLUGIN_SHAPE, 'compile 必须同步返回资源实例')
|
|
207
|
+
record.entries.push({ impl, instance: instance || {} })
|
|
208
|
+
}
|
|
209
|
+
} catch (reason) {
|
|
210
|
+
const normalized = toAbiError(reason, ERROR_CODES.E_ADAPTER_THREW, { plugin: spec.name, phase: 'compile' })
|
|
211
|
+
removeProvides(record)
|
|
212
|
+
record.status = 'failed'
|
|
213
|
+
record.startSettled = Promise.resolve()
|
|
214
|
+
record.ready = record.startSettled
|
|
215
|
+
// Reserve before invoking user cleanup: a disposer may initiate global shutdown.
|
|
216
|
+
plugins.set(spec.name, record)
|
|
217
|
+
const rollback = cleanup(record)
|
|
218
|
+
const finishRollback = (result) => {
|
|
219
|
+
if (result.ok && plugins.get(spec.name) === record) plugins.delete(spec.name)
|
|
128
220
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
throw
|
|
221
|
+
if (thenable(rollback)) rollback.then(finishRollback)
|
|
222
|
+
else finishRollback(rollback)
|
|
223
|
+
throw normalized
|
|
132
224
|
}
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
const
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
for (const capability of spec.provides) {
|
|
141
|
-
provided.set(capability.name, { plugin: spec.name, version: capability.range })
|
|
142
|
-
ownedProvides.push(capability.name)
|
|
225
|
+
plugins.set(spec.name, record)
|
|
226
|
+
// Sync-only interfaces are operational after compilation, preserving existing skill registration behavior.
|
|
227
|
+
const hasStart = record.entries.some((entry) => typeof entry.instance.start === 'function')
|
|
228
|
+
if (!hasStart) {
|
|
229
|
+
record.status = 'ready'
|
|
230
|
+
failures.delete(spec.name)
|
|
231
|
+
publishProvides(record)
|
|
143
232
|
}
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
233
|
+
record.startSettled = Promise.resolve().then(async () => {
|
|
234
|
+
if (record.stopRequested || !hasStart) return
|
|
235
|
+
record.inStart = true
|
|
236
|
+
try {
|
|
237
|
+
for (const entry of record.entries) {
|
|
238
|
+
if (record.stopRequested) break
|
|
239
|
+
if (typeof entry.instance.start === 'function') {
|
|
240
|
+
try {
|
|
241
|
+
await entry.instance.start({ signal: record.controller.signal })
|
|
242
|
+
} catch (reason) {
|
|
243
|
+
record.startError = capture(reason, spec.name, entry.impl.kind, 'start')
|
|
244
|
+
break
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
} finally {
|
|
249
|
+
record.inStart = false
|
|
250
|
+
}
|
|
251
|
+
})
|
|
252
|
+
record.ready = record.startSettled.then(async () => {
|
|
253
|
+
if (record.stopRequested) return
|
|
254
|
+
if (record.startError) {
|
|
255
|
+
record.status = 'failed'
|
|
256
|
+
removeProvides(record)
|
|
257
|
+
await cleanup(record)
|
|
258
|
+
// 启动失败的记录必须让出 name,否则重试挂载永远撞 E_DUP_PLUGIN。
|
|
259
|
+
if (plugins.get(spec.name) === record) plugins.delete(spec.name)
|
|
260
|
+
} else {
|
|
261
|
+
record.status = 'ready'
|
|
262
|
+
failures.delete(spec.name)
|
|
263
|
+
publishProvides(record)
|
|
264
|
+
}
|
|
265
|
+
})
|
|
147
266
|
const handle = {
|
|
148
|
-
name: spec.name,
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
plugins.delete(spec.name)
|
|
267
|
+
name: spec.name, spec, interfaces: record.entries.map((entry) => entry.impl.kind),
|
|
268
|
+
ready: record.ready,
|
|
269
|
+
get status() { return record.status },
|
|
270
|
+
async result() {
|
|
271
|
+
await record.ready
|
|
272
|
+
return { ok: record.status === 'ready', status: record.status, error: record.startError, cleanupErrors: [...record.cleanupErrors] }
|
|
273
|
+
},
|
|
274
|
+
async waitUntilReady() {
|
|
275
|
+
const result = await handle.result()
|
|
276
|
+
if (!result.ok) throw result.error || error('E_NOT_READY', `插件 ${spec.name} 未就绪(${result.status})`)
|
|
277
|
+
return handle
|
|
160
278
|
},
|
|
279
|
+
dispose: () => disposeRecord(record),
|
|
161
280
|
}
|
|
162
|
-
|
|
281
|
+
record.handle = handle
|
|
163
282
|
return handle
|
|
164
283
|
}
|
|
165
284
|
|
|
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
285
|
function unresolved() {
|
|
206
286
|
const out = []
|
|
207
287
|
for (const { spec } of plugins.values()) {
|
|
208
|
-
for (const
|
|
209
|
-
|
|
210
|
-
if (
|
|
211
|
-
out.push({ plugin: spec.name, capability:
|
|
288
|
+
for (const need of spec.requires) {
|
|
289
|
+
const actual = capability(need.name)
|
|
290
|
+
if (actual && satisfies(actual, need.range)) continue
|
|
291
|
+
out.push({ plugin: spec.name, capability: need.name, range: need.range,
|
|
292
|
+
actual, reason: actual ? 'incompatible' : 'missing' })
|
|
212
293
|
}
|
|
213
294
|
}
|
|
214
295
|
return out
|
|
215
296
|
}
|
|
216
297
|
|
|
217
|
-
/** 内核状态快照:给 os.report() 与健康检查用。 */
|
|
218
298
|
function report() {
|
|
219
|
-
const capabilityView = { ...capabilityMap() }
|
|
220
|
-
for (const [name, info] of provided) capabilityView[name] = info.version
|
|
221
299
|
return {
|
|
222
300
|
abiVersion: abiMajor,
|
|
223
|
-
plugins: [...plugins.values()].map((
|
|
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),
|
|
301
|
+
plugins: [...plugins.values()].map((record) => ({
|
|
302
|
+
name: record.spec.name, status: record.status,
|
|
303
|
+
interfaces: record.entries.map((entry) => entry.impl.kind),
|
|
304
|
+
requires: record.spec.requires.map((r) => r.raw), provides: record.spec.provides.map((p) => p.raw),
|
|
228
305
|
})),
|
|
229
|
-
capabilities: capabilityView,
|
|
230
|
-
|
|
231
|
-
failures: failures.map((error) => ({ code: error.code, message: error.message, detail: error.detail })),
|
|
306
|
+
capabilities: capabilityView(), unresolved: unresolved(),
|
|
307
|
+
failures: [...failures.values()].map((reason) => ({ code: reason.code, message: reason.message, detail: reason.detail })),
|
|
232
308
|
}
|
|
233
309
|
}
|
|
234
310
|
|
|
235
311
|
function disposeAll() {
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
312
|
+
if (shutdown) return shutdown
|
|
313
|
+
shuttingDown = true
|
|
314
|
+
const records = [...plugins.values()].reverse()
|
|
315
|
+
// Stop every pending start now, not after a preceding plugin's async cleanup.
|
|
316
|
+
for (const record of records) {
|
|
317
|
+
record.stopRequested = true
|
|
318
|
+
record.controller.abort()
|
|
319
|
+
}
|
|
320
|
+
const pending = sequence(records, (record) => disposeRecord(record))
|
|
321
|
+
shutdown = Promise.resolve(pending).then(() => ({ ok: ![...plugins.values()].some((r) => r.cleanupErrors.length) }))
|
|
322
|
+
return shutdown
|
|
240
323
|
}
|
|
241
324
|
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
325
|
+
/**
|
|
326
|
+
* 显式强制释放出口(运维/HMR 用):dispose 失败时「保留所有权」是有意设计,
|
|
327
|
+
* 但一次清理失败会把 name/unique 永久锁死,重挂永远撞 E_DUP_INTERFACE。
|
|
328
|
+
* 这里提供一个人工出口:释放 name/unique/provides 占用,让重挂得以进行。
|
|
329
|
+
* 它**不假装资源已清理**——cleanupErrors 原样保留并返回,调用方须知情。
|
|
330
|
+
*/
|
|
331
|
+
function forceRelease(name) {
|
|
332
|
+
const record = plugins.get(name)
|
|
333
|
+
if (!record) return { ok: false, reason: 'no-record' }
|
|
334
|
+
releaseClaims(record)
|
|
335
|
+
removeProvides(record)
|
|
336
|
+
record.resourcesReleased = true
|
|
337
|
+
record.status = 'disposed'
|
|
338
|
+
plugins.delete(name)
|
|
339
|
+
failures.delete(name)
|
|
340
|
+
return { ok: true, forced: true, cleanupErrors: [...record.cleanupErrors] }
|
|
341
|
+
}
|
|
249
342
|
|
|
343
|
+
const api = Object.freeze({ mount, report, capability, disposeAll, forceRelease, get size() { return plugins.size } })
|
|
250
344
|
return api
|
|
251
345
|
}
|
package/abi/spec.mjs
CHANGED
|
@@ -31,6 +31,10 @@ const KINDS = Object.freeze({
|
|
|
31
31
|
'http-router': 'http-router@1',
|
|
32
32
|
'ui-panel': 'ui-panel@1',
|
|
33
33
|
'lifecycle-hook': 'lifecycle-hook@1',
|
|
34
|
+
'host-event': 'host-event@1',
|
|
35
|
+
'client-panel': 'client-panel@1',
|
|
36
|
+
'own-server': 'own-server@1',
|
|
37
|
+
'service-provider': 'service-provider@1',
|
|
34
38
|
raw: 'raw@1',
|
|
35
39
|
})
|
|
36
40
|
|
|
@@ -68,6 +72,39 @@ export const runtimeDriver = (options) => defineInterface(KINDS['runtime-driver'
|
|
|
68
72
|
export const httpRouter = (options) => defineInterface(KINDS['http-router'], options)
|
|
69
73
|
export const uiPanel = (options) => defineInterface(KINDS['ui-panel'], options)
|
|
70
74
|
export const lifecycleHook = (options) => defineInterface(KINDS['lifecycle-hook'], options)
|
|
75
|
+
export const hostEvent = (options) => defineInterface(KINDS['host-event'], options)
|
|
76
|
+
export const clientPanel = (options) => defineInterface(KINDS['client-panel'], options)
|
|
77
|
+
export const ownServer = (options) => defineInterface(KINDS['own-server'], options)
|
|
78
|
+
export const serviceProvider = (options) => defineInterface(KINDS['service-provider'], options)
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* 驱动层统一入口:基建插件用 defineDriver 声明「我提供哪个 ctx 服务」。
|
|
82
|
+
*
|
|
83
|
+
* 与 createPlugin 的关键区别:不 inject os。驱动必须能在 foundation 之前/之后
|
|
84
|
+
* 独立激活,否则 foundation 的 os.net/os.tools/os.proc 会失去服务来源。
|
|
85
|
+
* apply 仍拿到原生 Cordis ctx,因为提供 ctx.provide 是驱动层的职责。
|
|
86
|
+
*/
|
|
87
|
+
export function defineDriver(options = {}) {
|
|
88
|
+
const { name, service, inject = [], apply } = options
|
|
89
|
+
if (!PLUGIN_NAME_RE.test(String(name || ''))) {
|
|
90
|
+
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `driver 名必须是 kebab-case:${name}`, { name })
|
|
91
|
+
}
|
|
92
|
+
if (typeof service !== 'string' || !service.trim()) {
|
|
93
|
+
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'driver.service 必须是非空字符串', { name, service })
|
|
94
|
+
}
|
|
95
|
+
if (!Array.isArray(inject) || inject.some((item) => typeof item !== 'string' || !item.trim())) {
|
|
96
|
+
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'driver.inject 必须是非空字符串数组', { name })
|
|
97
|
+
}
|
|
98
|
+
if (typeof apply !== 'function') {
|
|
99
|
+
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'driver.apply 必须是函数', { name, service })
|
|
100
|
+
}
|
|
101
|
+
return Object.freeze({
|
|
102
|
+
name,
|
|
103
|
+
inject: Object.freeze([...inject]),
|
|
104
|
+
apply,
|
|
105
|
+
driver: Object.freeze({ service }),
|
|
106
|
+
})
|
|
107
|
+
}
|
|
71
108
|
|
|
72
109
|
/** 逃生舱:必须同时导出 apply,且不得与其他接口混用。 */
|
|
73
110
|
export const rawPlugin = (apply) => defineInterface(KINDS.raw, { apply })
|
|
@@ -106,7 +143,9 @@ function parseCapability(entry, field) {
|
|
|
106
143
|
* }} options
|
|
107
144
|
*/
|
|
108
145
|
export function definePlugin(options = {}) {
|
|
109
|
-
const {
|
|
146
|
+
const {
|
|
147
|
+
name, apiVersion = ABI_MAJOR, description, requires = [], provides = [], inject = [], implements: impls,
|
|
148
|
+
} = options
|
|
110
149
|
|
|
111
150
|
if (!PLUGIN_NAME_RE.test(String(name || ''))) {
|
|
112
151
|
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `插件名必须是 kebab-case:${name}`, { name })
|
|
@@ -121,6 +160,14 @@ export function definePlugin(options = {}) {
|
|
|
121
160
|
if (description !== undefined && typeof description !== 'string') {
|
|
122
161
|
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'description 必须是字符串', { name })
|
|
123
162
|
}
|
|
163
|
+
/* 附加 Cordis inject 只给 raw@1 逃生舱使用:它需要保留原插件的宿主服务依赖。
|
|
164
|
+
* 普通描述符不接受这个字段,避免把宿主服务名泄漏进应用 ABI。 */
|
|
165
|
+
if (!Array.isArray(inject) || inject.some((item) => typeof item !== 'string' || !item.trim())) {
|
|
166
|
+
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'inject 必须是非空字符串数组', { name })
|
|
167
|
+
}
|
|
168
|
+
if (inject.length && !impls?.some((impl) => impl?.kind === 'raw@1')) {
|
|
169
|
+
throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, '只有 raw@1 插件可以声明额外 inject', { name })
|
|
170
|
+
}
|
|
124
171
|
|
|
125
172
|
for (const impl of impls) {
|
|
126
173
|
if (!impl || typeof impl !== 'object' || typeof impl.kind !== 'string') {
|
|
@@ -157,6 +204,7 @@ export function definePlugin(options = {}) {
|
|
|
157
204
|
description,
|
|
158
205
|
requires: Object.freeze(requiresEntries),
|
|
159
206
|
provides: Object.freeze(providesEntries),
|
|
207
|
+
inject: Object.freeze([...inject]),
|
|
160
208
|
implements: Object.freeze([...impls]),
|
|
161
209
|
})
|
|
162
210
|
}
|
|
@@ -182,17 +230,26 @@ export function createPlugin(definition, baseUrl) {
|
|
|
182
230
|
const os = ctx?.os
|
|
183
231
|
if (!os || typeof os.mount !== 'function') {
|
|
184
232
|
throw new AbiError(ERROR_CODES.E_KERNEL_MISSING,
|
|
185
|
-
'ctx.os 不可用:请先安装并启用 @capyclaw/foundation', { plugin: spec.name })
|
|
233
|
+
'ctx.os 不可用:请先安装并启用 @capyclaw/core(公共基建唯一声明者),它会连同 @capyclaw/foundation 一起挂上 os 内核', { plugin: spec.name })
|
|
186
234
|
}
|
|
187
235
|
if (!baseUrl) {
|
|
188
236
|
throw new AbiError(ERROR_CODES.E_BASE_URL_MISSING,
|
|
189
237
|
'createPlugin 需要第二参数 baseUrl(传 import.meta.url)', { plugin: spec.name })
|
|
190
238
|
}
|
|
191
|
-
const handle = os.mount(spec, config, { baseUrl })
|
|
192
|
-
|
|
239
|
+
const handle = os.mount(spec, config, { baseUrl, ctx })
|
|
240
|
+
const dispose = () => handle.dispose()
|
|
241
|
+
// Cordis 只认 ctx.effect 登记的 disposer,apply 的返回值并不可靠:
|
|
242
|
+
// 不显式登记的话,关掉插件再启用时旧记录还占着 name,会撞 E_DUP_PLUGIN。
|
|
243
|
+
if (typeof ctx?.effect === 'function') ctx.effect(() => () => { void dispose() })
|
|
244
|
+
return dispose
|
|
193
245
|
}
|
|
194
246
|
|
|
195
|
-
return Object.freeze({
|
|
247
|
+
return Object.freeze({
|
|
248
|
+
name: spec.name,
|
|
249
|
+
inject: Object.freeze(['os', ...spec.inject.filter((service) => service !== 'os')]),
|
|
250
|
+
apply,
|
|
251
|
+
spec,
|
|
252
|
+
})
|
|
196
253
|
}
|
|
197
254
|
|
|
198
255
|
export { toAbiError }
|
package/kit/index.mjs
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
*
|
|
3
|
-
*
|
|
4
|
-
*
|
|
5
|
-
* 这个入口的导出面保持不变,应用侧一行都不用改。
|
|
2
|
+
* Legacy plugin-kit compatibility exports. Includes Node resource helpers and
|
|
3
|
+
* dsh runtime-context conventions; importing this entry is not a portability proof.
|
|
4
|
+
* Preserve existing exports; new applications should prefer the descriptor ABI.
|
|
6
5
|
*/
|
|
7
6
|
export * from '@capyclaw/plugin-kit'
|