@capyclaw/foundation 0.1.3 → 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.
Files changed (60) hide show
  1. package/README.md +23 -6
  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 +277 -181
  7. package/abi/spec.mjs +62 -5
  8. package/kit/index.mjs +3 -4
  9. package/lib/adapters/client-panel.mjs +98 -0
  10. package/lib/adapters/host-event.mjs +35 -0
  11. package/lib/adapters/http-router.mjs +27 -5
  12. package/lib/adapters/lifecycle-hook.mjs +6 -13
  13. package/lib/adapters/own-server.mjs +113 -0
  14. package/lib/adapters/raw.mjs +68 -0
  15. package/lib/adapters/runtime-driver.mjs +49 -17
  16. package/lib/adapters/service-provider.mjs +77 -0
  17. package/lib/adapters/skill-provider.mjs +2 -3
  18. package/lib/adapters/tool-provider.mjs +14 -8
  19. package/lib/adapters/ui-panel.mjs +14 -8
  20. package/lib/ctx-service.mjs +21 -0
  21. package/lib/host/caps.mjs +34 -0
  22. package/lib/host/contract.mjs +85 -0
  23. package/lib/host/dsh.mjs +50 -0
  24. package/lib/host/memory.mjs +160 -0
  25. package/lib/host.mjs +6 -5
  26. package/lib/kernel.mjs +125 -35
  27. package/lib/subsystems/events.mjs +6 -1
  28. package/lib/subsystems/log.mjs +24 -3
  29. package/lib/subsystems/net.mjs +160 -22
  30. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  31. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  32. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  33. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  34. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  35. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  36. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  37. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  38. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  39. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  40. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  41. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  42. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  43. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  44. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  45. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  59. package/package.json +6 -3
  60. package/runtime/index.mjs +4 -1
@@ -0,0 +1,98 @@
1
+ /**
2
+ * client-panel@1 适配器:页面开机全局变量 + 可选静态面板。
3
+ *
4
+ * - bootGlobals 必须是同步函数;异步准备放在 prepare(start 阶段)里,
5
+ * 结果通过 state 传给 bootGlobals,避免事件发射器无法 await 的竞态。
6
+ * - 静态 root 与 ui-panel 共用 editorHost + serviceHost 共享前缀。
7
+ */
8
+ import { fileURLToPath } from 'node:url'
9
+
10
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
11
+
12
+ export const kind = 'client-panel@1'
13
+
14
+ export function createClientPanelAdapter({ host, net, log }) {
15
+ return {
16
+ kind,
17
+ compile(impl, { spec, config, context }) {
18
+ const ctx = context?.ctx
19
+ if (typeof ctx?.on !== 'function') {
20
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
21
+ 'client-panel@1 需要支持 ctx.on 的 Cordis 宿主', { plugin: spec.name })
22
+ }
23
+
24
+ let unmount
25
+ let editor
26
+ let app
27
+ if (impl.root) {
28
+ const serviceHost = host.http()
29
+ const editorHost = host.ui()
30
+ if (!serviceHost?.createApp || !editorHost?.createEditorHost) {
31
+ throw new AbiError(ERROR_CODES.E_CAP_MISSING,
32
+ 'ctx.editorHost / ctx.serviceHost 不可用:无法挂静态面板',
33
+ { plugin: spec.name, capability: 'os.ui' })
34
+ }
35
+ if (!context?.baseUrl) {
36
+ throw new AbiError(ERROR_CODES.E_BASE_URL_MISSING,
37
+ `插件 ${spec.name} 缺少 baseUrl,无法解析 ${impl.root}`, { plugin: spec.name })
38
+ }
39
+ const dir = fileURLToPath(new URL(impl.root, context.baseUrl))
40
+ editor = editorHost.createEditorHost({
41
+ id: spec.name,
42
+ dir,
43
+ basePath: '',
44
+ index: impl.index,
45
+ })
46
+ app = serviceHost.createApp({ id: spec.name, title: spec.name })
47
+ try {
48
+ for (const route of editor.routes()) app.use(route)
49
+ unmount = net.mount(impl.mount, app)
50
+ } catch (error) {
51
+ /* 装配/挂载失败回收已建 app(editor 静态宿主无 close,GC 回收)。 */
52
+ try { app.close?.() } catch { /* 尽力回收 */ }
53
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
54
+ `挂载客户端面板 ${impl.mount} 失败:${error.message}`,
55
+ { plugin: spec.name, prefix: impl.mount, cause: error })
56
+ }
57
+ }
58
+
59
+ const panelState = { ready: typeof impl.prepare !== 'function', value: undefined }
60
+ const off = ctx.on('webserver/index-inject', (table) => {
61
+ if (!impl.bootGlobals || !panelState.ready || !Array.isArray(table)) return
62
+ let globals
63
+ try {
64
+ globals = impl.bootGlobals({
65
+ spec, config, log, os: context.os, state: panelState.value,
66
+ })
67
+ } catch (error) {
68
+ log?.error?.(`[foundation] ${spec.name} bootGlobals 失败:${error.message}`)
69
+ return
70
+ }
71
+ if (!globals || typeof globals !== 'object') return
72
+ for (const [name, value] of Object.entries(globals)) {
73
+ if (value !== undefined) table.push({ kind: 'global', name, value })
74
+ }
75
+ })
76
+
77
+ return {
78
+ editor,
79
+ async start() {
80
+ if (typeof impl.prepare === 'function') {
81
+ panelState.value = await impl.prepare({
82
+ spec, config, log, os: context.os,
83
+ })
84
+ panelState.ready = true
85
+ }
86
+ if (unmount) await net.ready()
87
+ },
88
+ dispose() {
89
+ const errors = []
90
+ try { if (typeof off === 'function') off() } catch (error) { errors.push(error) }
91
+ try { if (typeof unmount === 'function') unmount() } catch (error) { errors.push(error) }
92
+ try { app?.close?.() } catch (error) { errors.push(error) }
93
+ if (errors.length) throw errors[0]
94
+ },
95
+ }
96
+ },
97
+ }
98
+ }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * host-event@1 适配器:把宿主事件订阅交给插件自己的 Cordis ctx。
3
+ *
4
+ * 应用插件只声明事件名与 handler,不接触 ctx;注销由 loader 统一回收。
5
+ */
6
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
7
+
8
+ export const kind = 'host-event@1'
9
+
10
+ export function createHostEventAdapter({ log }) {
11
+ return {
12
+ kind,
13
+ compile(impl, { spec, context }) {
14
+ const ctx = context?.ctx
15
+ if (!ctx || typeof ctx.on !== 'function') {
16
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
17
+ 'host-event@1 需要支持 ctx.on 的 Cordis 宿主', { plugin: spec.name, event: impl.event })
18
+ }
19
+
20
+ let dispose
21
+ try {
22
+ const off = ctx.on(impl.event, impl.handler)
23
+ dispose = typeof off === 'function'
24
+ ? off
25
+ : () => { if (typeof ctx.off === 'function') ctx.off(impl.event, impl.handler) }
26
+ } catch (error) {
27
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
28
+ `订阅宿主事件 ${impl.event} 失败:${error.message}`, { plugin: spec.name, event: impl.event, cause: error })
29
+ }
30
+
31
+ log?.debug?.(`[foundation] ${spec.name} 订阅宿主事件 ${impl.event}`)
32
+ return { dispose }
33
+ },
34
+ }
35
+ }
@@ -3,26 +3,38 @@
3
3
  *
4
4
  * 前缀冲突由 service-host 的 sharedHost.mount 检测(重复前缀直接抛错),
5
5
  * 应用侧不接触 server、不选端口。
6
+ *
7
+ * 增量(STANDARD v2 V2-1/V2-4 配套,纯向后兼容):
8
+ * - routes 第二参新增 service(name):跨隔离探测公共服务(getService),
9
+ * 让路由插件拿到 ctx.workStore 这类驱动提供的服务,而不必私开句柄;
10
+ * - routes() 返回函数时登记为 disposer:dispose 先 unmount 再调用,
11
+ * 路由层起的定时器/句柄有官方回收点。
6
12
  */
7
13
  import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
8
14
  import { getService } from '../ctx-service.mjs'
9
15
 
10
16
  export const kind = 'http-router@1'
11
17
 
12
- export function createHttpRouterAdapter({ ctx, net, log }) {
18
+ export function createHttpRouterAdapter({ host, net, log }) {
13
19
  return {
14
20
  kind,
15
- compile(impl, { spec, config }) {
16
- const serviceHost = getService(ctx, 'serviceHost')
21
+ compile(impl, { spec, config, context }) {
22
+ const serviceHost = host.http()
17
23
  if (!serviceHost?.createApp) {
18
24
  throw new AbiError(ERROR_CODES.E_CAP_MISSING,
19
25
  'ctx.serviceHost 不可用:无法创建子 app', { plugin: spec.name, capability: 'os.net' })
20
26
  }
21
27
 
22
28
  const app = serviceHost.createApp({ id: spec.name, title: spec.name })
29
+ const service = (name) => getService(context?.ctx, name)
30
+ let cleanup
23
31
  try {
24
- impl.routes(app, { spec, config, log })
32
+ const returned = impl.routes(app, { spec, config, log, os: context?.os, service })
33
+ if (typeof returned === 'function') cleanup = returned
25
34
  } catch (error) {
35
+ /* routes 抛错时 app 已创建:此 entry 尚未入 loader entries,编译回滚够不到,
36
+ * 必须就地回收,否则子 app/句柄泄漏。 */
37
+ try { app.close?.() } catch { /* 尽力回收 */ }
26
38
  throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
27
39
  `路由注册失败:${error.message}`, { plugin: spec.name, cause: error })
28
40
  }
@@ -31,6 +43,9 @@ export function createHttpRouterAdapter({ ctx, net, log }) {
31
43
  try {
32
44
  unmount = net.mount(impl.mount, app)
33
45
  } catch (error) {
46
+ /* mount 失败同样回收已建的 app 与 routes 返回的 cleanup。 */
47
+ try { if (cleanup) cleanup() } catch { /* 尽力回收 */ }
48
+ try { app.close?.() } catch { /* 尽力回收 */ }
34
49
  throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
35
50
  `挂载前缀 ${impl.mount} 失败:${error.message}`, { plugin: spec.name, prefix: impl.mount, cause: error })
36
51
  }
@@ -38,8 +53,15 @@ export function createHttpRouterAdapter({ ctx, net, log }) {
38
53
  log?.debug?.(`[foundation] ${spec.name} 路由挂到 ${impl.mount}`)
39
54
  return {
40
55
  app,
56
+ start: () => net.ready(),
41
57
  dispose: () => {
42
- if (typeof unmount === 'function') unmount()
58
+ /* unmount 与 cleanup 都要执行;cleanup 错误不再吞掉(旧实现 log.warn 后
59
+ * 假装成功,loader 会释放 claims 但定时器/句柄实际泄漏)。错误上抛进
60
+ * loader cleanupErrors,保留「失败保留所有权」语义。 */
61
+ const errors = []
62
+ try { if (typeof unmount === 'function') unmount() } catch (error) { errors.push(error) }
63
+ if (cleanup) { try { cleanup() } catch (error) { errors.push(error) } }
64
+ if (errors.length) throw errors[0]
43
65
  },
44
66
  }
45
67
  },
@@ -31,7 +31,7 @@ export function createHookRegistry() {
31
31
  export function createLifecycleAdapter({ hooks, log }) {
32
32
  return {
33
33
  kind,
34
- compile(impl, { spec }) {
34
+ compile(impl, { spec, config, context }) {
35
35
  const removers = []
36
36
  if (typeof impl.onInstall === 'function') {
37
37
  removers.push(hooks.register('install', { plugin: spec.name, run: impl.onInstall }))
@@ -39,22 +39,15 @@ export function createLifecycleAdapter({ hooks, log }) {
39
39
  if (typeof impl.onUpgrade === 'function') {
40
40
  removers.push(hooks.register('upgrade', { plugin: spec.name, run: impl.onUpgrade }))
41
41
  }
42
+ let entered = false
42
43
  return {
43
- async start() {
44
- if (typeof impl.onStart === 'function') await impl.onStart({ plugin: spec.name })
44
+ async start({ signal } = {}) {
45
+ entered = true
46
+ if (typeof impl.onStart === 'function') await impl.onStart({ plugin: spec.name, config, log, os: context?.os, signal })
45
47
  },
46
48
  dispose() {
47
- if (typeof impl.onStop === 'function') {
48
- try {
49
- const result = impl.onStop({ plugin: spec.name })
50
- if (result && typeof result.then === 'function') {
51
- result.catch((error) => log?.error?.(`[foundation] ${spec.name} onStop 失败: ${error.message}`))
52
- }
53
- } catch (error) {
54
- log?.error?.(`[foundation] ${spec.name} onStop 失败: ${error.message}`)
55
- }
56
- }
57
49
  for (const remove of removers) remove()
50
+ if (entered && typeof impl.onStop === 'function') return impl.onStop({ plugin: spec.name, config, log, os: context?.os })
58
51
  },
59
52
  }
60
53
  },
@@ -0,0 +1,113 @@
1
+ /**
2
+ * own-server@1 适配器:托管一个 HTTP 面。
3
+ *
4
+ * 宿主提供 `web()`(dsh 即 `ctx.webServer`)时,这个面挂到宿主网页端口的路径前缀
5
+ * (`impl.mount`,默认 `/plugins/<id>`)下,**不再新起端口**;只有拿不到 web() 的
6
+ * 宿主才退回 service-host 的独立 loopback origin(凭据中转等必须独立 origin 的场景)。
7
+ *
8
+ * 应用只提供 handler(req,res,api) 与可选 start/stop;监听、端口、锁、健康检查、
9
+ * 关闭全部由宿主 service-host 负责。
10
+ */
11
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
12
+
13
+ export const kind = 'own-server@1'
14
+
15
+ function resolvePort(impl, spec, config, fallback) {
16
+ const value = typeof impl.port === 'function' ? impl.port({ spec, config }) : impl.port
17
+ if (value === 'auto') return 0
18
+ if (Number.isInteger(value) && value >= 0 && value <= 65535) return value
19
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE,
20
+ `own-server port 必须是 0-65535 整数或 "auto",收到 ${String(value)}`,
21
+ { plugin: spec.name, id: impl.id, port: value, fallback })
22
+ }
23
+
24
+ export function createOwnServerAdapter({ host, log }) {
25
+ return {
26
+ kind,
27
+ compile(impl, { spec, config, context }) {
28
+ const serviceHost = host.http()
29
+ if (!serviceHost?.createApp) {
30
+ throw new AbiError(ERROR_CODES.E_CAP_MISSING,
31
+ 'ctx.serviceHost 不可用:无法托管自有 origin',
32
+ { plugin: spec.name, capability: 'os.net' })
33
+ }
34
+
35
+ const app = serviceHost.createApp({ id: impl.id, title: spec.name })
36
+ const web = typeof host.web === 'function' ? host.web() : null
37
+ const canEmbed = !!(web && typeof web.register === 'function')
38
+ const mount = typeof impl.mount === 'string' && impl.mount
39
+ ? impl.mount
40
+ : `/plugins/${impl.id}`
41
+ /* 错误响应必须防 write-after-end:handler 已 res.end() 后再失败(流式响应后
42
+ * 异步出错是常见形态)时,再写会抛 ERR_STREAM_WRITE_AFTER_END——在 .catch 回调
43
+ * 里就是未捕获 rejection,可拖垮整个宿主。已结束只记日志;写本身也包 try/catch。 */
44
+ const failResponse = (res, error) => {
45
+ log?.error?.(`[foundation] ${spec.name} own-server handler 失败:${error?.message || error}`)
46
+ try {
47
+ if (res.writableEnded || res.destroyed) return
48
+ if (!res.headersSent) res.writeHead(500, { 'content-type': 'application/json' })
49
+ res.end(JSON.stringify({ error: 'handler failed' }))
50
+ } catch (writeError) {
51
+ log?.error?.(`[foundation] ${spec.name} own-server 错误响应写入失败:${writeError?.message || writeError}`)
52
+ }
53
+ }
54
+ app.use((req, res, url) => {
55
+ try {
56
+ const result = impl.handler(req, res, {
57
+ spec, config, log, os: context?.os, url, mount, embedded: canEmbed,
58
+ })
59
+ if (result && typeof result.then === 'function') {
60
+ result.catch((error) => failResponse(res, error))
61
+ }
62
+ } catch (error) {
63
+ failResponse(res, error)
64
+ }
65
+ return true
66
+ })
67
+
68
+ let info
69
+ let started = false
70
+ let stopped = false
71
+ return {
72
+ app,
73
+ /** true = 挂在宿主网页端口的前缀下,没有新起端口。 */
74
+ embedded: canEmbed,
75
+ mount,
76
+ async start() {
77
+ started = true
78
+ info = await app.listen(canEmbed
79
+ ? { webServer: web, basePath: mount }
80
+ : { port: resolvePort(impl, spec, config), host: impl.host })
81
+ if (typeof impl.start === 'function') {
82
+ await impl.start({ app, info, spec, config, log, os: context?.os, embedded: canEmbed, mount })
83
+ }
84
+ log?.info?.(`[foundation] ${spec.name} own-server ${impl.id} ${canEmbed ? '挂载' : '监听'} ${info.url}`)
85
+ },
86
+ async dispose() {
87
+ if (stopped) return
88
+ stopped = true
89
+ /* 资源闭合必须在 finally:impl.stop 抛错不能跳过 app.close,否则端口/
90
+ * 监听器永久泄漏且 stopped=true 使重试 no-op(HMR 重挂 EADDRINUSE)。
91
+ * 与 service-provider 的 try{stop}finally{withdraw} 同构。错误仍上抛,
92
+ * 让 loader 记 cleanupErrors(保留所有权语义),但资源已经释放。 */
93
+ const errors = []
94
+ try {
95
+ if (typeof impl.stop === 'function') {
96
+ await impl.stop({ app, info, spec, config, log, os: context?.os, embedded: canEmbed, mount })
97
+ }
98
+ } catch (error) {
99
+ errors.push(error)
100
+ } finally {
101
+ if (started) {
102
+ try { await app.close() } catch (error) { errors.push(error) }
103
+ }
104
+ }
105
+ if (errors.length > 1) {
106
+ log?.error?.(`[foundation] ${spec.name} own-server dispose 多个错误:${errors.map((e) => e?.message || e).join(';')}`)
107
+ }
108
+ if (errors.length) throw errors[0]
109
+ },
110
+ }
111
+ },
112
+ }
113
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * raw@1 适配器:逃生舱。
3
+ *
4
+ * 描述符只提供 apply;适配器把插件自己的 Cordis ctx 交给它,并统一处理
5
+ * 同步/异步返回值与 dispose。raw 插件必须登记在 meta/foundation.allowlist.json
6
+ * 的 raw 段,准入闸会把它与普通应用插件分开统计。
7
+ */
8
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
9
+
10
+ export const kind = 'raw@1'
11
+
12
+ const thenable = (value) => value && typeof value.then === 'function'
13
+
14
+ function normalize(value) {
15
+ if (typeof value === 'function') return { dispose: value }
16
+ if (value && typeof value === 'object') {
17
+ const instance = {}
18
+ if (typeof value.start === 'function') instance.start = value.start.bind(value)
19
+ if (typeof value.dispose === 'function') instance.dispose = value.dispose.bind(value)
20
+ return instance
21
+ }
22
+ return {}
23
+ }
24
+
25
+ export function createRawAdapter({ log }) {
26
+ return {
27
+ kind,
28
+ compile(impl, { spec, config, context }) {
29
+ const ctx = context?.ctx
30
+ if (!ctx) {
31
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
32
+ 'raw@1 需要 Cordis ctx:请通过 createPlugin 挂载', { plugin: spec.name })
33
+ }
34
+
35
+ let result
36
+ try {
37
+ result = impl.apply({
38
+ ctx, spec, config, log, baseUrl: context.baseUrl, os: context.os,
39
+ })
40
+ } catch (error) {
41
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
42
+ `raw apply 失败:${error.message}`, { plugin: spec.name, cause: error })
43
+ }
44
+
45
+ if (thenable(result)) {
46
+ let instance = {}
47
+ let settled = false
48
+ const started = Promise.resolve(result).then((value) => {
49
+ instance = normalize(value)
50
+ settled = true
51
+ return instance.start ? instance.start() : undefined
52
+ })
53
+ return {
54
+ start: () => started,
55
+ dispose: async () => {
56
+ if (!settled) {
57
+ try { await started } catch { /* start 失败由 loader 记录 */ }
58
+ }
59
+ if (typeof instance.dispose === 'function') return instance.dispose()
60
+ },
61
+ }
62
+ }
63
+
64
+ log?.debug?.(`[foundation] ${spec.name} 使用 raw@1 逃生舱`)
65
+ return normalize(result)
66
+ },
67
+ }
68
+ }
@@ -7,17 +7,30 @@
7
7
  import { fileURLToPath } from 'node:url'
8
8
 
9
9
  import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
10
- import { getService } from '../ctx-service.mjs'
11
10
 
12
11
  export const kind = 'runtime-driver@1'
13
12
 
14
- export function createRuntimeDriverAdapter({ ctx, config, log }) {
15
- const defaultPort = config.driverPort ?? 0
13
+ export function createRuntimeDriverAdapter({ host, config, log }) {
14
+ const defaultPort = config.driverPort ?? 'auto'
16
15
 
17
16
  return {
18
17
  kind,
19
18
  compile(impl, mountContext) {
20
- const broker = getService(ctx, 'serviceBroker')
19
+ let enabled = true
20
+ if (typeof impl.when === 'function') {
21
+ try {
22
+ enabled = impl.when({ spec: mountContext.spec, config: mountContext.config }) !== false
23
+ } catch (error) {
24
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
25
+ `runtime-driver when() 失败:${error.message}`, { plugin: mountContext.spec.name, id: impl.id, cause: error })
26
+ }
27
+ }
28
+ if (!enabled) {
29
+ log?.info?.(`[foundation] ${mountContext.spec.name} 跳过 runtime-driver ${impl.id}(when=false)`)
30
+ return { skipped: true, dispose() {} }
31
+ }
32
+
33
+ const broker = host.proc()
21
34
  if (!broker?.start || !broker?.stop) {
22
35
  throw new AbiError(ERROR_CODES.E_CAP_MISSING,
23
36
  'ctx.serviceBroker 不可用:无法拉起长驻进程',
@@ -30,13 +43,22 @@ export function createRuntimeDriverAdapter({ ctx, config, log }) {
30
43
  }
31
44
 
32
45
  const entryPath = fileURLToPath(new URL(impl.entry, mountContext.context.baseUrl))
33
- const port = impl.port ?? defaultPort
46
+ const resolvedPort = typeof impl.port === 'function'
47
+ ? impl.port({ spec: mountContext.spec, config: mountContext.config })
48
+ : impl.port
49
+ if (resolvedPort !== undefined && resolvedPort !== 'auto'
50
+ && !(Number.isInteger(resolvedPort) && resolvedPort > 0 && resolvedPort <= 65535)) {
51
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE,
52
+ `runtime-driver port 必须是 1-65535 整数或 "auto",收到 ${String(resolvedPort)}`,
53
+ { plugin: mountContext.spec.name, id: impl.id, port: resolvedPort })
54
+ }
55
+ const port = resolvedPort ?? defaultPort
34
56
  const portArg = impl.portArg || '--port'
35
57
  const cmd = [
36
58
  process.execPath,
37
59
  entryPath,
38
60
  portArg,
39
- String(port),
61
+ port === 'auto' ? '${PORT}' : String(port),
40
62
  ...(impl.args || []),
41
63
  ]
42
64
 
@@ -51,14 +73,20 @@ export function createRuntimeDriverAdapter({ ctx, config, log }) {
51
73
  if (impl.dir) {
52
74
  serviceSpec.cwd = fileURLToPath(new URL(impl.dir, mountContext.context.baseUrl))
53
75
  }
54
- const env = impl.env?.({ spec: mountContext.spec, config: mountContext.config })
76
+ const env = impl.env?.({
77
+ spec: mountContext.spec,
78
+ config: mountContext.config,
79
+ os: mountContext.context?.os,
80
+ })
55
81
  if (env && typeof env === 'object') serviceSpec.env = env
56
82
 
57
- let stopped = false
83
+ let entered = false
84
+ let stopPromise
58
85
  return {
59
86
  serviceSpec,
60
- async start() {
61
- const result = await broker.start(serviceSpec)
87
+ async start({ signal } = {}) {
88
+ entered = true
89
+ const result = await broker.start(serviceSpec, { signal })
62
90
  const failure = (result?.errors || []).find((item) => item.id === impl.id)
63
91
  if (failure) {
64
92
  throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
@@ -67,13 +95,17 @@ export function createRuntimeDriverAdapter({ ctx, config, log }) {
67
95
  log?.info?.(`[foundation] ${impl.id} 已由 broker 拉起(port ${port})`)
68
96
  },
69
97
  dispose() {
70
- if (stopped) return
71
- stopped = true
72
- try {
73
- broker.stop(impl.id)
74
- } catch (error) {
75
- log?.warn?.(`[foundation] 停止 ${impl.id} 失败: ${error.message}`)
76
- }
98
+ if (!entered) return
99
+ if (!stopPromise) stopPromise = Promise.resolve().then(async () => {
100
+ const result = await broker.stop(impl.id)
101
+ if (result?.stopped === false) {
102
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
103
+ `长驻进程 ${impl.id} 未停止:${result.reason || 'broker rejected stop'}`,
104
+ { plugin: mountContext.spec.name, id: impl.id, result })
105
+ }
106
+ return result
107
+ })
108
+ return stopPromise
77
109
  },
78
110
  }
79
111
  },
@@ -0,0 +1,77 @@
1
+ /**
2
+ * service-provider@1 适配器:向插件自己的 Cordis ctx 提供一个具名服务。
3
+ *
4
+ * 服务工厂必须同步;需要异步初始化的资源放在 start 钩子里。
5
+ * 注销顺序:先 stop(如果提供),再撤销 ctx.provide。
6
+ */
7
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
8
+
9
+ export const kind = 'service-provider@1'
10
+
11
+ const thenable = (value) => value && typeof value.then === 'function'
12
+
13
+ export function createServiceProviderAdapter({ log }) {
14
+ return {
15
+ kind,
16
+ compile(impl, { spec, config, context }) {
17
+ if (typeof impl.when === 'function') {
18
+ let enabled
19
+ try {
20
+ enabled = impl.when({ spec, config, log, os: context.os }) !== false
21
+ } catch (error) {
22
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
23
+ `service-provider when() 失败:${error.message}`, { plugin: spec.name, service: impl.service, cause: error })
24
+ }
25
+ if (!enabled) {
26
+ log?.info?.(`[foundation] ${spec.name} 跳过 service-provider ${impl.service}(when=false)`)
27
+ return { skipped: true, dispose() {} }
28
+ }
29
+ }
30
+ const ctx = context?.ctx
31
+ if (!ctx || typeof ctx.provide !== 'function') {
32
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
33
+ 'service-provider@1 需要支持 ctx.provide 的 Cordis 宿主', { plugin: spec.name, service: impl.service })
34
+ }
35
+
36
+ let service
37
+ try {
38
+ service = impl.provide({ spec, config, log, os: context.os })
39
+ } catch (error) {
40
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
41
+ `服务 ${impl.service} 构建失败:${error.message}`, { plugin: spec.name, service: impl.service, cause: error })
42
+ }
43
+ if (thenable(service)) {
44
+ /* 异步 provide 不被允许;但被拒的 promise 必须先接住,否则抛出
45
+ * E_PLUGIN_SHAPE 之外还泄漏一个 unhandledRejection(可崩宿主)。 */
46
+ service.catch(() => {})
47
+ throw new AbiError(ERROR_CODES.E_PLUGIN_SHAPE,
48
+ `服务 ${impl.service} 的 provide() 必须同步返回服务对象`, { plugin: spec.name, service: impl.service })
49
+ }
50
+
51
+ let withdraw
52
+ try {
53
+ withdraw = ctx.provide(impl.service, service)
54
+ } catch (error) {
55
+ throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
56
+ `注册服务 ${impl.service} 失败:${error.message}`, { plugin: spec.name, service: impl.service, cause: error })
57
+ }
58
+
59
+ let stopped = false
60
+ return {
61
+ service,
62
+ start: typeof impl.start === 'function'
63
+ ? () => impl.start({ service, spec, config, log, os: context.os })
64
+ : undefined,
65
+ async dispose() {
66
+ if (stopped) return
67
+ stopped = true
68
+ try {
69
+ if (typeof impl.stop === 'function') await impl.stop({ service, spec, config, log, os: context.os })
70
+ } finally {
71
+ if (typeof withdraw === 'function') withdraw()
72
+ }
73
+ },
74
+ }
75
+ },
76
+ }
77
+ }
@@ -9,16 +9,15 @@ import { basename, dirname } from 'node:path'
9
9
  import { fileURLToPath } from 'node:url'
10
10
 
11
11
  import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
12
- import { getService } from '../ctx-service.mjs'
13
12
  import { createSkillProvider } from '../skill/scan.mjs'
14
13
 
15
14
  export const kind = 'skill-provider@1'
16
15
 
17
- export function createSkillAdapter({ ctx, log }) {
16
+ export function createSkillAdapter({ host, log }) {
18
17
  return {
19
18
  kind,
20
19
  compile(impl, { spec, context }) {
21
- const skills = getService(ctx, 'skills')
20
+ const skills = host.skills()
22
21
  if (!skills || typeof skills.registerProvider !== 'function') {
23
22
  throw new AbiError(ERROR_CODES.E_CAP_MISSING,
24
23
  'ctx.skills.registerProvider 不可用:skills 服务未加载', { plugin: spec.name })
@@ -7,23 +7,22 @@
7
7
  * 工具实现不经过 foundation,foundation 只决定「什么时候挂上去、挂到哪个命名空间」。
8
8
  */
9
9
  import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
10
- import { getService } from '../ctx-service.mjs'
11
10
 
12
11
  export const kind = 'tool-provider@1'
13
12
 
14
- export function createToolProviderAdapter({ ctx, log }) {
13
+ export function createToolProviderAdapter({ host, log }) {
15
14
  return {
16
15
  kind,
17
- compile(impl, { spec, config }) {
18
- const toolHost = getService(ctx, 'toolHost')
19
- if (!toolHost?.registerWithDsh) {
16
+ compile(impl, { spec, config, context }) {
17
+ const tools = host.tools()
18
+ if (!tools?.register) {
20
19
  throw new AbiError(ERROR_CODES.E_CAP_MISSING,
21
20
  'ctx.toolHost 不可用:无法注册工具面', { plugin: spec.name, capability: 'os.tools' })
22
21
  }
23
22
 
24
23
  let registry
25
24
  try {
26
- registry = impl.provide({ spec, config, log })
25
+ registry = impl.provide({ spec, config, log, os: context?.os })
27
26
  } catch (error) {
28
27
  throw new AbiError(ERROR_CODES.E_ADAPTER_THREW,
29
28
  `工具注册表构建失败:${error.message}`, { plugin: spec.name, cause: error })
@@ -33,8 +32,15 @@ export function createToolProviderAdapter({ ctx, log }) {
33
32
  'provide() 必须返回 { TOOLS, TOOL_IMPL } 形状的注册表', { plugin: spec.name })
34
33
  }
35
34
 
36
- const dispose = toolHost.registerWithDsh(ctx, registry, { namespace: impl.namespace })
37
- log?.debug?.(`[foundation] ${spec.name} 注册 ${registry.TOOLS.length} 个工具(${impl.namespace})`)
35
+ /* prefixNamespace=false 用于工具名已经自带命名空间的存量注册表,
36
+ * 避免 browser_navigate 被注册成 browser_browser_navigate。 */
37
+ const namespace = impl.prefixNamespace === false ? '' : impl.namespace
38
+ const dispose = tools.register(registry, {
39
+ namespace,
40
+ instructions: impl.instructions,
41
+ capabilities: impl.capabilities,
42
+ })
43
+ log?.debug?.(`[foundation] ${spec.name} 注册 ${registry.TOOLS.length} 个工具(${namespace || '无前缀'})`)
38
44
  return {
39
45
  registry,
40
46
  dispose: typeof dispose === 'function' ? dispose : () => {},