@capyclaw/capyclaw 0.0.0-stage → 0.2.0

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 (81) hide show
  1. package/README.md +22 -2
  2. package/cordis.patch.yml +5 -0
  3. package/icon.svg +5 -0
  4. package/index.js +178 -0
  5. package/lib/environment.mjs +122 -0
  6. package/locale/en.json +6 -0
  7. package/locale/zh.json +6 -0
  8. package/manifest.js +18 -0
  9. package/node_modules/@capyclaw/foundation/README.md +51 -0
  10. package/node_modules/@capyclaw/foundation/abi/assets.mjs +26 -0
  11. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +88 -0
  12. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  13. package/node_modules/@capyclaw/foundation/abi/index.mjs +50 -0
  14. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  15. package/node_modules/@capyclaw/foundation/abi/loader.mjs +352 -0
  16. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  17. package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
  18. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  19. package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -0
  20. package/node_modules/@capyclaw/foundation/abi/visibility.mjs +90 -0
  21. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  22. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  25. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  26. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +72 -0
  27. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  28. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +69 -0
  29. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -0
  30. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  31. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  32. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  33. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  34. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  35. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +38 -0
  36. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +88 -0
  37. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +54 -0
  38. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +187 -0
  39. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  40. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +195 -0
  41. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +115 -0
  42. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  43. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  44. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +198 -0
  45. package/node_modules/@capyclaw/foundation/package.json +53 -0
  46. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  47. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  48. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  49. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  50. package/node_modules/@capyclaw/plugin-kit/package.json +71 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +132 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat.mjs +26 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +60 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/service/static.mjs +79 -0
  67. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  68. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  69. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  70. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  71. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  72. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  73. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  74. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  75. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  76. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +664 -0
  77. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  78. package/package.json +71 -4
  79. package/test/environment.test.mjs +68 -0
  80. package/test/package.test.mjs +24 -0
  81. package/test/plugin.test.mjs +101 -0
@@ -0,0 +1,98 @@
1
+ /**
2
+ * 极简 schema 校验器:只覆盖 ABI 描述符需要的子集,不引入依赖。
3
+ *
4
+ * 支持的约束:type(含类型数组)/ required / properties / additionalProperties /
5
+ * items / minItems / enum / pattern / min / max / minLength / maxLength。
6
+ *
7
+ * 刻意不做的事:$ref、oneOf/anyOf、format、默认值填充。描述符是代码不是配置文件,
8
+ * 需要更强表达力时写 `extra()` 校验,而不是把 schema 语言做大。
9
+ */
10
+
11
+ const TYPE_CHECKS = {
12
+ string: (v) => typeof v === 'string',
13
+ number: (v) => typeof v === 'number' && Number.isFinite(v),
14
+ integer: (v) => Number.isInteger(v),
15
+ boolean: (v) => typeof v === 'boolean',
16
+ object: (v) => v !== null && typeof v === 'object' && !Array.isArray(v),
17
+ array: (v) => Array.isArray(v),
18
+ function: (v) => typeof v === 'function',
19
+ }
20
+
21
+ function describe(value) {
22
+ if (value === null) return 'null'
23
+ if (Array.isArray(value)) return 'array'
24
+ return typeof value
25
+ }
26
+
27
+ /**
28
+ * @param {unknown} value
29
+ * @param {object} schema
30
+ * @param {string} [path] 出错时的字段路径根
31
+ * @returns {string[]} 错误列表;空数组表示通过
32
+ */
33
+ export function validateSchema(value, schema, path = '$') {
34
+ const errors = []
35
+ visit(value, schema, path, errors)
36
+ return errors
37
+ }
38
+
39
+ function visit(value, schema, path, errors) {
40
+ if (!schema) return
41
+
42
+ if (schema.type !== undefined) {
43
+ const types = Array.isArray(schema.type) ? schema.type : [schema.type]
44
+ const known = types.filter((type) => TYPE_CHECKS[type])
45
+ if (known.length !== types.length) {
46
+ errors.push(`${path} 的 schema 声明了未知类型 ${types.join('|')}`)
47
+ return
48
+ }
49
+ if (!types.some((type) => TYPE_CHECKS[type](value))) {
50
+ errors.push(`${path} 应为 ${types.join('|')},实际 ${describe(value)}`)
51
+ return
52
+ }
53
+ }
54
+
55
+ if (typeof value === 'string') {
56
+ if (schema.minLength !== undefined && value.length < schema.minLength) {
57
+ errors.push(`${path} 长度不得小于 ${schema.minLength}`)
58
+ }
59
+ if (schema.maxLength !== undefined && value.length > schema.maxLength) {
60
+ errors.push(`${path} 长度不得大于 ${schema.maxLength}`)
61
+ }
62
+ if (schema.pattern && !new RegExp(schema.pattern).test(value)) {
63
+ errors.push(`${path} 不匹配 ${schema.pattern}`)
64
+ }
65
+ if (schema.enum && !schema.enum.includes(value)) {
66
+ errors.push(`${path} 必须是 ${schema.enum.join(' | ')} 之一`)
67
+ }
68
+ }
69
+
70
+ if (typeof value === 'number') {
71
+ if (schema.min !== undefined && value < schema.min) errors.push(`${path} 不得小于 ${schema.min}`)
72
+ if (schema.max !== undefined && value > schema.max) errors.push(`${path} 不得大于 ${schema.max}`)
73
+ }
74
+
75
+ if (Array.isArray(value)) {
76
+ if (schema.minItems !== undefined && value.length < schema.minItems) {
77
+ errors.push(`${path} 至少需要 ${schema.minItems} 项`)
78
+ }
79
+ if (schema.items) {
80
+ value.forEach((item, index) => visit(item, schema.items, `${path}[${index}]`, errors))
81
+ }
82
+ }
83
+
84
+ if (value !== null && typeof value === 'object' && !Array.isArray(value)) {
85
+ const props = schema.properties || {}
86
+ for (const key of schema.required || []) {
87
+ if (value[key] === undefined) errors.push(`${path}.${key} 必填`)
88
+ }
89
+ if (schema.additionalProperties === false) {
90
+ for (const key of Object.keys(value)) {
91
+ if (!(key in props)) errors.push(`${path}.${key} 未知字段`)
92
+ }
93
+ }
94
+ for (const [key, sub] of Object.entries(props)) {
95
+ if (value[key] !== undefined) visit(value[key], sub, `${path}.${key}`, errors)
96
+ }
97
+ }
98
+ }
@@ -0,0 +1,258 @@
1
+ /**
2
+ * 插件描述符:应用插件唯一需要写的东西。
3
+ *
4
+ * import { createPlugin, skillProvider } from '@capyclaw/foundation/abi'
5
+ *
6
+ * export const { name, inject, apply } = createPlugin({
7
+ * name: 'canvas',
8
+ * requires: ['canvas.runtime@^1'],
9
+ * implements: [skillProvider({ skill: './skills/canvas' })],
10
+ * }, import.meta.url)
11
+ *
12
+ * 设计要点:
13
+ * - 构建器在模块加载期就校验 schema,坏描述符不会活到 activate;
14
+ * - 描述符是纯数据 + 函数,不 import 内核、不持有 ctx;
15
+ * - createPlugin 产出的是普通 Cordis 插件形状(name/inject/apply),
16
+ * 装配细节全部收回内核的 mount。
17
+ */
18
+ import { ABI_MAJOR, getInterfaceKind } from './kinds.mjs'
19
+ import { validateSchema } from './schema.mjs'
20
+ import { validateInterface } from './validate.mjs'
21
+ import { AbiError, ERROR_CODES, toAbiError } from './errors.mjs'
22
+
23
+ const PLUGIN_NAME_RE = /^[a-z0-9][a-z0-9-]*$/
24
+ const CAPABILITY_NAME_RE = /^[a-zA-Z][a-zA-Z0-9]*(?:[.-][a-zA-Z0-9*]+)*$/
25
+ const RANGE_RE = /^(?:\^|~|>=|<=|>|<|=)?[0-9x*][0-9A-Za-z.*-]*$/
26
+
27
+ const KINDS = Object.freeze({
28
+ 'skill-provider': 'skill-provider@1',
29
+ 'tool-provider': 'tool-provider@1',
30
+ 'runtime-driver': 'runtime-driver@1',
31
+ 'http-router': 'http-router@1',
32
+ 'ui-panel': 'ui-panel@1',
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',
38
+ raw: 'raw@1',
39
+ })
40
+
41
+ /**
42
+ * 校验并冻结一个接口描述符。
43
+ * @param {string} kind
44
+ * @param {object} options
45
+ */
46
+ export function defineInterface(kind, options) {
47
+ const definition = getInterfaceKind(kind)
48
+ if (!definition) {
49
+ throw new AbiError(ERROR_CODES.E_KIND_UNKNOWN, `未知接口种类 ${kind}`, {
50
+ kind,
51
+ known: Object.keys(KINDS).map((key) => KINDS[key]),
52
+ })
53
+ }
54
+ if (options === null || typeof options !== 'object' || Array.isArray(options)) {
55
+ throw new AbiError(ERROR_CODES.E_SCHEMA, `${kind} 的描述符必须是对象`, { kind })
56
+ }
57
+ const errors = validateSchema(options, definition.schema)
58
+ definition.extra?.(options, errors)
59
+ if (errors.length) {
60
+ throw new AbiError(ERROR_CODES.E_SCHEMA, `${kind} 描述符非法:${errors.join(';')}`, { kind, errors })
61
+ }
62
+ return Object.freeze({ kind, ...options })
63
+ }
64
+
65
+ /* ------------------------------------------------------------------------- */
66
+ /* 六个接口构建器 + 逃生舱 */
67
+ /* ------------------------------------------------------------------------- */
68
+
69
+ export const skillProvider = (options) => defineInterface(KINDS['skill-provider'], options)
70
+ export const toolProvider = (options) => defineInterface(KINDS['tool-provider'], options)
71
+ export const runtimeDriver = (options) => defineInterface(KINDS['runtime-driver'], options)
72
+ export const httpRouter = (options) => defineInterface(KINDS['http-router'], options)
73
+ export const uiPanel = (options) => defineInterface(KINDS['ui-panel'], options)
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
+ }
108
+
109
+ /** 逃生舱:必须同时导出 apply,且不得与其他接口混用。 */
110
+ export const rawPlugin = (apply) => defineInterface(KINDS.raw, { apply })
111
+
112
+ /* ------------------------------------------------------------------------- */
113
+ /* 插件定义 */
114
+ /* ------------------------------------------------------------------------- */
115
+
116
+ function parseCapability(entry, field) {
117
+ if (typeof entry !== 'string' || !entry.trim()) {
118
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `${field} 的每一项必须是非空字符串`, { entry })
119
+ }
120
+ const at = entry.lastIndexOf('@')
121
+ if (at <= 0 || at === entry.length - 1) {
122
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `${field} 项 "${entry}" 必须写成 name@range`, { entry })
123
+ }
124
+ const name = entry.slice(0, at)
125
+ const range = entry.slice(at + 1)
126
+ if (!CAPABILITY_NAME_RE.test(name)) {
127
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `${field} 项 "${entry}" 的能力名非法`, { entry, name })
128
+ }
129
+ if (!RANGE_RE.test(range)) {
130
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `${field} 项 "${entry}" 的版本范围非法`, { entry, range })
131
+ }
132
+ return Object.freeze({ name, range, raw: entry })
133
+ }
134
+
135
+ /**
136
+ * @param {{
137
+ * name: string,
138
+ * apiVersion?: number,
139
+ * description?: string,
140
+ * requires?: string[],
141
+ * provides?: string[],
142
+ * implements: object[]
143
+ * }} options
144
+ */
145
+ export function definePlugin(options = {}) {
146
+ const {
147
+ name, apiVersion = ABI_MAJOR, description, requires = [], provides = [], inject = [], implements: impls,
148
+ } = options
149
+
150
+ if (!PLUGIN_NAME_RE.test(String(name || ''))) {
151
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, `插件名必须是 kebab-case:${name}`, { name })
152
+ }
153
+ if (!Number.isInteger(apiVersion) || apiVersion !== ABI_MAJOR) {
154
+ throw new AbiError(ERROR_CODES.E_ABI_MISMATCH,
155
+ `插件声明 ABI v${apiVersion},内核只支持 v${ABI_MAJOR}`, { name, apiVersion, supported: ABI_MAJOR })
156
+ }
157
+ if (!Array.isArray(impls) || impls.length === 0) {
158
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, '插件必须实现至少一个接口', { name })
159
+ }
160
+ if (description !== undefined && typeof description !== 'string') {
161
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'description 必须是字符串', { name })
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
+ }
171
+
172
+ for (const impl of impls) {
173
+ if (!impl || typeof impl !== 'object' || typeof impl.kind !== 'string') {
174
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'implements 的每一项必须是 define* 产出的描述符', { name })
175
+ }
176
+ const { definition, errors } = validateInterface(impl)
177
+ if (!definition) {
178
+ throw new AbiError(ERROR_CODES.E_KIND_UNKNOWN, `未知接口种类 ${impl.kind}`, { name, kind: impl.kind })
179
+ }
180
+ if (errors.length) {
181
+ throw new AbiError(ERROR_CODES.E_SCHEMA, `${impl.kind} 描述符非法:${errors.join(';')}`, {
182
+ name, kind: impl.kind, errors,
183
+ })
184
+ }
185
+ }
186
+
187
+ if (impls.some((impl) => getInterfaceKind(impl.kind)?.exclusive) && impls.length > 1) {
188
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE, 'raw@1 不得与其他接口混用', { name })
189
+ }
190
+
191
+ const requiresEntries = requires.map((entry) => parseCapability(entry, 'requires'))
192
+ const providesEntries = provides.map((entry) => parseCapability(entry, 'provides'))
193
+ for (const entry of providesEntries) {
194
+ /* 白名单而非黑名单:provides 必须是完整 x.y.z(可带 prerelease)。旧实现只拒
195
+ * ^~<>= 前缀,'1.x' / '1.*' / 裸 '1' 漏网被当成版本发布,消费方 parseVersion
196
+ * 解析不了 → satisfies 恒 false,能力永远「不可用」。 */
197
+ if (!/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(entry.range)) {
198
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE,
199
+ `provides 必须写精确版本(x.y.z),不能写范围:${entry.raw}`, { entry: entry.raw })
200
+ }
201
+ }
202
+
203
+ return Object.freeze({
204
+ kind: 'plugin',
205
+ name,
206
+ apiVersion,
207
+ description,
208
+ requires: Object.freeze(requiresEntries),
209
+ provides: Object.freeze(providesEntries),
210
+ inject: Object.freeze([...inject]),
211
+ implements: Object.freeze([...impls]),
212
+ })
213
+ }
214
+
215
+ /* ------------------------------------------------------------------------- */
216
+ /* Cordis 接缝 */
217
+ /* ------------------------------------------------------------------------- */
218
+
219
+ /**
220
+ * 把插件定义编译成普通 Cordis 插件:{ name, inject, apply }。
221
+ *
222
+ * apply 的返回值是 disposer(与仓内既有插件一致),内核在卸载时调用。
223
+ * 形状错误(schema / 能力 / 唯一性)同步抛出,让插件加载直接失败;
224
+ * 运行时就绪(子进程拉起等)异步进行,通过 os.report() 观测。
225
+ *
226
+ * @param {object} definition definePlugin 的结果,或直接传 definePlugin 的入参
227
+ * @param {string} baseUrl 插件入口的 import.meta.url,用于解析相对路径
228
+ */
229
+ export function createPlugin(definition, baseUrl) {
230
+ const spec = definition?.kind === 'plugin' ? definition : definePlugin(definition)
231
+
232
+ function apply(ctx, config = {}) {
233
+ const os = ctx?.os
234
+ if (!os || typeof os.mount !== 'function') {
235
+ throw new AbiError(ERROR_CODES.E_KERNEL_MISSING,
236
+ 'ctx.os 不可用:请先安装并启用 @capyclaw/core(公共基建唯一声明者),它会连同 @capyclaw/foundation 一起挂上 os 内核', { plugin: spec.name })
237
+ }
238
+ if (!baseUrl) {
239
+ throw new AbiError(ERROR_CODES.E_BASE_URL_MISSING,
240
+ 'createPlugin 需要第二参数 baseUrl(传 import.meta.url)', { plugin: spec.name })
241
+ }
242
+ const handle = os.mount(spec, config, { baseUrl, ctx })
243
+ const dispose = () => handle.dispose()
244
+ // Cordis 只认 ctx.effect 登记的 disposer,apply 的返回值并不可靠:
245
+ // 不显式登记的话,关掉插件再启用时旧记录还占着 name,会撞 E_DUP_PLUGIN。
246
+ if (typeof ctx?.effect === 'function') ctx.effect(() => () => { void dispose() })
247
+ return dispose
248
+ }
249
+
250
+ return Object.freeze({
251
+ name: spec.name,
252
+ inject: Object.freeze(['os', ...spec.inject.filter((service) => service !== 'os')]),
253
+ apply,
254
+ spec,
255
+ })
256
+ }
257
+
258
+ export { toAbiError }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 描述符校验:把「kind 之外的全部字段」交给对应接口的 schema。
3
+ *
4
+ * 单独成模块,是因为 spec(构建期)与 loader(加载期)必须用同一套判定;
5
+ * 只要两处各写一遍,迟早会出现「构建能过、加载失败」或反过来。
6
+ */
7
+ import { getInterfaceKind } from './kinds.mjs'
8
+ import { validateSchema } from './schema.mjs'
9
+
10
+ /**
11
+ * @param {object} impl 描述符(含 kind)
12
+ * @returns {{ definition: object|null, errors: string[] }}
13
+ */
14
+ export function validateInterface(impl) {
15
+ const definition = getInterfaceKind(impl?.kind)
16
+ if (!definition) {
17
+ return { definition: null, errors: [`未知接口种类 ${impl?.kind}`] }
18
+ }
19
+ const body = { ...impl }
20
+ delete body.kind
21
+ const errors = validateSchema(body, definition.schema)
22
+ definition.extra?.(body, errors)
23
+ return { definition, errors }
24
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * 版本与范围:能力声明用 `^1` / `^1.2.0` / `>=1.2` / `1.x` / 精确版本。
3
+ *
4
+ * 只实现这份 ABI 需要的语义,不引入 semver 依赖:
5
+ * - `^1.2.3` → >=1.2.3 且同主版本;`^0.2.3` → >=0.2.3 且同次版本;
6
+ * `^0.0.3` → >=0.0.3 且同补丁(0.0.x 约定,semver 标准)
7
+ * - `~1.2.3` → >=1.2.3 且同次版本
8
+ * - `1.x` / `1.*` → 同主版本
9
+ * - `>=` `>` `<=` `<` `=` 前缀
10
+ * - 裸版本 → 精确匹配(比较时忽略末位 0)
11
+ * - prerelease 保留并参与比较:1.0.0-beta < 1.0.0;带 prerelease 的版本只满足
12
+ * 同 [major,minor,patch] 且同样带 prerelease 的范围(semver 标准,避免预发布
13
+ * 版本被当成正式版本放行)。
14
+ */
15
+
16
+ export function parseVersion(text) {
17
+ if (typeof text !== 'string') return null
18
+ const match = /^v?(\d+)(?:\.(\d+))?(?:\.(\d+))?(?:-([0-9A-Za-z.-]+))?$/.exec(text.trim())
19
+ if (!match) return null
20
+ const parts = [Number(match[1]), Number(match[2] || 0), Number(match[3] || 0)]
21
+ parts.prerelease = match[4] || null
22
+ return parts
23
+ }
24
+
25
+ function comparePrerelease(a, b) {
26
+ /* 无 prerelease > 有 prerelease(1.0.0 > 1.0.0-beta)。 */
27
+ if (!a && !b) return 0
28
+ if (!a) return 1
29
+ if (!b) return -1
30
+ const left = a.split('.')
31
+ const right = b.split('.')
32
+ for (let i = 0; i < Math.max(left.length, right.length); i++) {
33
+ const x = left[i]
34
+ const y = right[i]
35
+ if (x === undefined) return -1
36
+ if (y === undefined) return 1
37
+ const xn = /^\d+$/.test(x)
38
+ const yn = /^\d+$/.test(y)
39
+ if (xn && yn) {
40
+ const d = Number(x) - Number(y)
41
+ if (d !== 0) return d < 0 ? -1 : 1
42
+ } else if (xn !== yn) {
43
+ return xn ? -1 : 1 // 数字标识符 < 字母数字标识符
44
+ } else if (x !== y) {
45
+ return x < y ? -1 : 1
46
+ }
47
+ }
48
+ return 0
49
+ }
50
+
51
+ function compareParts(a, b) {
52
+ for (let i = 0; i < 3; i++) {
53
+ if (a[i] !== b[i]) return a[i] < b[i] ? -1 : 1
54
+ }
55
+ return comparePrerelease(a.prerelease || null, b.prerelease || null)
56
+ }
57
+
58
+ export function compareVersions(a, b) {
59
+ const left = typeof a === 'string' ? parseVersion(a) : a
60
+ const right = typeof b === 'string' ? parseVersion(b) : b
61
+ if (!left || !right) return NaN
62
+ return compareParts(left, right)
63
+ }
64
+
65
+ /**
66
+ * @param {string} version 提供方版本,如 '1.2.3'
67
+ * @param {string} range 需求范围,如 '^1'
68
+ * @returns {boolean}
69
+ */
70
+ export function satisfies(version, range) {
71
+ const current = parseVersion(version)
72
+ if (!current) return false
73
+ const raw = String(range ?? '').trim()
74
+ if (!raw || raw === '*' || raw === 'x') return true
75
+
76
+ if (raw.startsWith('^')) {
77
+ const base = parseVersion(raw.slice(1))
78
+ if (!base) return false
79
+ /* prerelease 只满足同 [major,minor,patch] 且带 prerelease 的范围(semver 标准),
80
+ * 避免 1.1.0-beta 被 ^1.0.0 当正式版本放行。 */
81
+ if (current.prerelease && (!base.prerelease
82
+ || current[0] !== base[0] || current[1] !== base[1] || current[2] !== base[2])) return false
83
+ if (compareParts(current, base) < 0) return false
84
+ if (base[0] === 0) {
85
+ /* 0.0.x caret 收紧到补丁位:^0.0.3 只容 0.0.3,不容 0.0.9。 */
86
+ if (base[1] === 0) return current[0] === 0 && current[1] === 0 && current[2] === base[2]
87
+ return current[0] === 0 && current[1] === base[1]
88
+ }
89
+ return current[0] === base[0]
90
+ }
91
+ if (raw.startsWith('~')) {
92
+ const base = parseVersion(raw.slice(1))
93
+ if (!base) return false
94
+ if (current.prerelease && (!base.prerelease
95
+ || current[0] !== base[0] || current[1] !== base[1] || current[2] !== base[2])) return false
96
+ return compareParts(current, base) >= 0 && current[0] === base[0] && current[1] === base[1]
97
+ }
98
+ if (raw.startsWith('>=')) {
99
+ const base = parseVersion(raw.slice(2))
100
+ return Boolean(base) && compareParts(current, base) >= 0
101
+ }
102
+ if (raw.startsWith('<=')) {
103
+ const base = parseVersion(raw.slice(2))
104
+ return Boolean(base) && compareParts(current, base) <= 0
105
+ }
106
+ if (raw.startsWith('>')) {
107
+ const base = parseVersion(raw.slice(1))
108
+ return Boolean(base) && compareParts(current, base) > 0
109
+ }
110
+ if (raw.startsWith('<')) {
111
+ const base = parseVersion(raw.slice(1))
112
+ return Boolean(base) && compareParts(current, base) < 0
113
+ }
114
+ if (raw.startsWith('=')) return satisfies(version, raw.slice(1))
115
+
116
+ const xRange = /^(\d+)(?:\.(\d+))?\.[x*]$/.exec(raw)
117
+ if (xRange) {
118
+ const major = Number(xRange[1])
119
+ const minor = xRange[2] === undefined ? null : Number(xRange[2])
120
+ return current[0] === major && (minor === null || current[1] === minor)
121
+ }
122
+
123
+ const exact = parseVersion(raw)
124
+ return Boolean(exact) && compareParts(current, exact) === 0
125
+ }
126
+
127
+ /**
128
+ * 范围是否「语义合法」(区别于「合法但不满足」)。供加载器把非法范围单独报
129
+ * E_SCHEMA,而不是误归因成「能力不可用」误导排障。空范围视为「任意」,合法。
130
+ */
131
+ export function isValidRange(range) {
132
+ const raw = String(range ?? '').trim()
133
+ if (!raw || raw === '*' || raw === 'x') return true
134
+ if (/^[\^~]/.test(raw)) return Boolean(parseVersion(raw.slice(1)))
135
+ if (/^(>=|<=)/.test(raw)) return Boolean(parseVersion(raw.slice(2)))
136
+ if (/^[><]/.test(raw)) return Boolean(parseVersion(raw.slice(1)))
137
+ if (raw.startsWith('=')) return isValidRange(raw.slice(1))
138
+ if (/^(\d+)(?:\.(\d+))?\.[x*]$/.test(raw)) return true
139
+ return Boolean(parseVersion(raw))
140
+ }
@@ -0,0 +1,90 @@
1
+ /**
2
+ * 表面生命周期(surface lifecycle)的标准声明。
3
+ *
4
+ * 与 bridge.mjs 同层:只放「协议常量 + 声明校验」,不放运行时。
5
+ * 依据 docs/SURFACE-LIFECYCLE-STANDARD.md:
6
+ * - 宿主(portal-hud + window-kit)是表面可见性的唯一真源,经统一 postMessage
7
+ * 信号通道下发给 iframe;iframe 内 document.hidden 只反映顶层 tab,不能用来
8
+ * 推断「被宿主藏起来」,所以表面可见性必须宿主显式告知。
9
+ * - 只有渲染面响应可见性;权威/数据面与桥接/仲裁面(租约心跳、apply/ack)
10
+ * 永远在线,与可见性无关。
11
+ *
12
+ * 消费方:
13
+ * - 宿主侧:@capyclaw/window-kit 的 visibility 驱动器(CJS 自包含叶子,无法
14
+ * import 本 ESM 模块,内联同名常量,由 parity 测试钉死一致)。
15
+ * - iframe 侧:@capyclaw/document-workbench/client 的 visibility 订阅器,
16
+ * 以及各编辑器前端(ppt/canvas/browser)。
17
+ * - 注册面:suite 清单 provides.capabilities 的 <ns>.surfaceLifecycle。
18
+ */
19
+
20
+ import { AbiError, ERROR_CODES } from './errors.mjs'
21
+
22
+ /** 表面生命周期契约版本:状态机语义与信号形状的主版本。不兼容变更才升 major。 */
23
+ export const SURFACE_LIFECYCLE_VERSION = '1.0.0'
24
+
25
+ /** 宿主 → iframe 的可见性信号:{ type, state, sid },targetOrigin 同源。 */
26
+ export const VISIBILITY_MESSAGE = 'capyclaw:workbench:visibility'
27
+
28
+ /** iframe → 宿主 的回执:{ type, state, sid }。detached 由宿主直接卸载,无需回执。 */
29
+ export const VISIBILITY_ACK_MESSAGE = 'capyclaw:workbench:visibility-ack'
30
+
31
+ /**
32
+ * 可见性状态(标准 §3):
33
+ * foreground 前台可见全速;background 可见非焦点(降速,SHOULD 档);
34
+ * hidden 不再绘制(渲染面必须挂起);detached 久藏卸载(影子编辑器接管)。
35
+ */
36
+ export const VISIBILITY_STATES = Object.freeze(['foreground', 'background', 'hidden', 'detached'])
37
+
38
+ /**
39
+ * 节奏/预算默认值(标准 §3/§4/§5)。运行时经 tuning 单一真源可调;
40
+ * 这里是协议默认,不是各插件私设的第二份。
41
+ * detachAfterMs hidden 持续多久才卸载 iframe(编辑器权威型可更长)
42
+ * visibilityAckTimeoutMs 信号发出后多久没回执算半挂起(宿主可强制重载)
43
+ * hiddenGraceMs shown→hidden 的去抖宽限,避免快速切换抖动
44
+ */
45
+ export const VISIBILITY_DEFAULTS = Object.freeze({
46
+ detachAfterMs: 120000,
47
+ visibilityAckTimeoutMs: 1500,
48
+ hiddenGraceMs: 250,
49
+ })
50
+
51
+ /** 能力名后缀:与 suite 清单 provides.capabilities 的 <ns>.surfaceLifecycle 对应。 */
52
+ export const SURFACE_LIFECYCLE_CAPABILITY_SUFFIX = 'surfaceLifecycle'
53
+
54
+ const STATE_SET = new Set(VISIBILITY_STATES)
55
+
56
+ /** 是否合法状态。 */
57
+ export function isVisibilityState(value) {
58
+ return typeof value === 'string' && STATE_SET.has(value)
59
+ }
60
+
61
+ /** 归一化:非法/缺省一律退回 foreground(宁可多渲染,不可假挂起)。 */
62
+ export function normalizeVisibilityState(value) {
63
+ return isVisibilityState(value) ? value : 'foreground'
64
+ }
65
+
66
+ /** 注册声明 → suite 清单 provides.capabilities(标准 §6)。 */
67
+ export function surfaceLifecycleCapability(ns, version = SURFACE_LIFECYCLE_VERSION) {
68
+ if (typeof ns !== 'string' || !/^[a-z0-9][a-z0-9-]*$/.test(ns)) {
69
+ throw new AbiError(ERROR_CODES.E_SCHEMA, `surfaceLifecycle 命名空间必须是 kebab-case:${ns}`)
70
+ }
71
+ return Object.freeze({ [`${ns}.${SURFACE_LIFECYCLE_CAPABILITY_SUFFIX}`]: version })
72
+ }
73
+
74
+ /**
75
+ * 校验一份表面生命周期声明(注册契约,标准 §6)。
76
+ * 渲染面四钩子必须齐;editor-gated 观察必须声明无头兜底。
77
+ * @param {{ hooks?: string[], headlessObservation?: boolean }} input
78
+ */
79
+ export function assertSurfaceLifecycle(input = {}) {
80
+ const required = ['onVisibility', 'suspendRender', 'resumeRender', 'rehydrate']
81
+ const hooks = Array.isArray(input.hooks) ? input.hooks : []
82
+ const issues = []
83
+ for (const hook of required) {
84
+ if (!hooks.includes(hook)) issues.push(`缺少渲染面钩子 ${hook}`)
85
+ }
86
+ if (input.headlessObservation !== true) {
87
+ issues.push('editor-gated 观察必须声明无头兜底(headlessObservation:true)')
88
+ }
89
+ return { ok: issues.length === 0, issues }
90
+ }
@@ -0,0 +1,5 @@
1
+ # @capyclaw/foundation 的 bundle patch:在 Cordis 树里登记内核,产出 ctx.os。
2
+ # 应用插件由 loader 在各自的 apply 里挂载,不再单独产生 patch 行。
3
+ - insert:
4
+ - id: capyclaw-foundation
5
+ name: '@capyclaw/foundation'
@@ -0,0 +1,6 @@
1
+ /**
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.
5
+ */
6
+ export * from '@capyclaw/plugin-kit'