@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.
Files changed (59) 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 +276 -182
  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 +26 -3
  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 +47 -14
  16. package/lib/adapters/service-provider.mjs +77 -0
  17. package/lib/adapters/tool-provider.mjs +11 -4
  18. package/lib/adapters/ui-panel.mjs +11 -4
  19. package/lib/ctx-service.mjs +21 -0
  20. package/lib/host/caps.mjs +13 -5
  21. package/lib/host/contract.mjs +85 -0
  22. package/lib/host/dsh.mjs +10 -1
  23. package/lib/host/memory.mjs +44 -0
  24. package/lib/host.mjs +6 -5
  25. package/lib/kernel.mjs +92 -7
  26. package/lib/subsystems/events.mjs +6 -1
  27. package/lib/subsystems/log.mjs +23 -1
  28. package/lib/subsystems/net.mjs +154 -15
  29. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  30. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  31. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  32. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  33. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  34. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  35. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  36. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  37. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  38. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  39. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  40. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  41. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  42. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  43. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  44. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  45. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +150 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +57 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  58. package/package.json +6 -3
  59. package/runtime/index.mjs +4 -1
@@ -13,9 +13,30 @@ export function getService(ctx, name) {
13
13
  if (service !== undefined) return service
14
14
  } catch { /* 继续尝试属性访问 */ }
15
15
  }
16
+ const shared = findServiceByStore(ctx, name)
17
+ if (shared !== undefined) return shared
16
18
  try {
17
19
  return ctx[name]
18
20
  } catch {
19
21
  return undefined
20
22
  }
21
23
  }
24
+
25
+ /**
26
+ * 跨隔离查找服务实例:Cordis 的 `ctx.get(name)` 只认「本层隔离键」指向的实现,
27
+ * 同一个服务若在别的隔离分支里提供,就永远查不到(桌面宿主里的 webServer 就是这样:
28
+ * `ctx.get('webServer')` 恒 undefined,而服务本身活得好好的)。
29
+ * store 里的实现项都带 `name`,按名字扫一遍即可拿到同一个实例。
30
+ */
31
+ export function findServiceByStore(ctx, name) {
32
+ try {
33
+ const store = ctx?.root?.store
34
+ if (!store || typeof store !== 'object') return undefined
35
+ // store 的键是隔离用的 Symbol,Object.values 看不到它们,必须走 Reflect.ownKeys。
36
+ for (const key of Reflect.ownKeys(store)) {
37
+ const impl = store[key]
38
+ if (impl?.name === name && impl.value !== undefined && impl.value !== null) return impl.value
39
+ }
40
+ } catch { /* 结构不同就当没有,交给调用方的兜底 */ }
41
+ return undefined
42
+ }
package/lib/host/caps.mjs CHANGED
@@ -16,11 +16,19 @@ export const BASE_CAPABILITIES = Object.freeze({
16
16
  /** dsh 宿主:按 ctx 里实际存在的服务生成能力表。 */
17
17
  export function detectDshCapabilities(ctx) {
18
18
  const capabilities = { ...BASE_CAPABILITIES }
19
- if (getService(ctx, 'skills')?.registerProvider) capabilities['os.skills'] = '1.0.0'
19
+ const hasMethods = (service, ...methods) => methods.every((method) => typeof service?.[method] === 'function')
20
+ if (hasMethods(getService(ctx, 'skills'), 'registerProvider')) capabilities['os.skills'] = '1.0.0'
20
21
  const serviceHost = getService(ctx, 'serviceHost')
21
- if (serviceHost?.createSharedHost && serviceHost?.createApp) capabilities['os.net'] = '1.0.0'
22
- if (getService(ctx, 'toolHost')?.registerWithDsh) capabilities['os.tools'] = '1.0.0'
23
- if (getService(ctx, 'serviceBroker')?.start) capabilities['os.proc'] = '1.0.0'
24
- if (getService(ctx, 'editorHost')?.createEditorHost) capabilities['os.ui'] = '1.0.0'
22
+ if (hasMethods(serviceHost, 'createSharedHost', 'createApp')) capabilities['os.net'] = '1.0.0'
23
+ // 宿主网页端口本身(dsh 的 ctx.webServer)。有它就不该再另起端口。
24
+ if (hasMethods(getService(ctx, 'webServer'), 'register')) capabilities['os.web'] = '1.0.0'
25
+ if (hasMethods(getService(ctx, 'toolHost'), 'registerWithDsh')
26
+ && hasMethods(getService(ctx, 'tools'), 'register')) capabilities['os.tools'] = '1.0.0'
27
+ if (hasMethods(getService(ctx, 'serviceBroker'), 'start', 'stop')) capabilities['os.proc'] = '1.0.0'
28
+ if (capabilities['os.net'] && hasMethods(getService(ctx, 'editorHost'), 'createEditorHost')) capabilities['os.ui'] = '1.0.0'
29
+ if (hasMethods(getService(ctx, 'pluginManager'), 'listBundles', 'listPlugins', 'setBundleEnabled', 'setPluginEnabled')) {
30
+ capabilities['os.plugins'] = '1.0.0'
31
+ }
32
+ if (hasMethods(getService(ctx, 'assets'), 'put', 'get')) capabilities['os.assets'] = '1.0.0'
25
33
  return capabilities
26
34
  }
@@ -0,0 +1,85 @@
1
+ /** Executable Host v1 boundary; validation never registers, listens or starts resources. */
2
+ import { parseVersion } from '../../abi/version.mjs'
3
+ import { AbiError, ERROR_CODES } from '../../abi/errors.mjs'
4
+
5
+ const ACCESSORS = ['capabilities', 'log', 'skills', 'tools', 'http', 'proc', 'ui']
6
+ const SERVICES = {
7
+ 'os.skills': ['skills', ['registerProvider']],
8
+ 'os.tools': ['tools', ['register']],
9
+ 'os.net': ['http', ['createApp', 'createSharedHost']],
10
+ 'os.web': ['web', ['register']],
11
+ 'os.proc': ['proc', ['start', 'stop']],
12
+ 'os.ui': ['ui', ['createEditorHost']],
13
+ 'os.plugins': ['plugins', ['listBundles', 'listPlugins', 'setBundleEnabled', 'setPluginEnabled']],
14
+ 'os.assets': ['assets', ['put', 'get']],
15
+ }
16
+
17
+ function invalid(path, expectation) {
18
+ /* 归一成 AbiError(稳定 code + detail),不再让裸 TypeError 穿透 mount/report。
19
+ * message 保留 path+expectation 原文,既有按文案断言的测试不受影响。 */
20
+ throw new AbiError(ERROR_CODES.E_KERNEL_MISSING, `Host v1 contract: ${path} ${expectation}`, { contract: 'host-v1', path, expectation })
21
+ }
22
+
23
+ function record(value) {
24
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
25
+ }
26
+
27
+ function version(value, path) {
28
+ // Use the same version vocabulary as ABI capability matching, but require a
29
+ // complete version rather than accepting ranges or abbreviated declarations.
30
+ const parsed = parseVersion(value)
31
+ if (!parsed || !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(value)) {
32
+ invalid(path, 'must be a version such as 1.0.0 (not a range)')
33
+ }
34
+ return parsed
35
+ }
36
+
37
+ /**
38
+ * Validate a live capability snapshot and its advertised service methods.
39
+ * Returns host unchanged; throws AbiError (E_KERNEL_MISSING) with the failing path. All accessors
40
+ * are synchronous, side-effect-free lookups. Unadvertised optional services are
41
+ * not probed, so late service injection remains possible. Call at construction
42
+ * and before consuming a fresh capabilities() snapshot, not just once at boot.
43
+ * Resource-return values/disposers are checked by the shared behavior suite.
44
+ */
45
+ export function assertHostContract(host) {
46
+ if (!record(host)) invalid('host', 'must be an object')
47
+ if (typeof host.kind !== 'string' || !host.kind.trim()) invalid('host.kind', 'must be a non-empty string')
48
+ if (version(host.version, 'host.version')[0] !== 1) invalid('host.version', 'must be compatible with major version 1')
49
+ for (const method of ACCESSORS) {
50
+ if (typeof host[method] !== 'function') invalid(`host.${method}`, 'must be a function')
51
+ }
52
+
53
+ const capabilities = host.capabilities()
54
+ if (!record(capabilities) || typeof capabilities.then === 'function') {
55
+ invalid('host.capabilities()', 'must synchronously return a capability map')
56
+ }
57
+ for (const [name, value] of Object.entries(capabilities)) {
58
+ if (!/^os\.[A-Za-z][A-Za-z0-9_.-]*$/.test(name)) invalid(`capabilities[${JSON.stringify(name)}]`, 'must have an os.* name')
59
+ version(value, `capabilities[${JSON.stringify(name)}]`)
60
+ }
61
+ if (Object.hasOwn(capabilities, 'os.ui') && !Object.hasOwn(capabilities, 'os.net')) {
62
+ invalid('capabilities.os.ui', 'requires os.net and its HTTP service')
63
+ }
64
+
65
+ const logger = host.log()
66
+ if (logger != null) {
67
+ for (const method of ['debug', 'info', 'warn', 'error']) {
68
+ if (typeof logger[method] !== 'function') invalid(`host.log().${method}`, 'must be a function')
69
+ }
70
+ }
71
+ for (const [capability, [accessor, methods]] of Object.entries(SERVICES)) {
72
+ if (!Object.hasOwn(capabilities, capability)) continue
73
+ if (typeof host[accessor] !== 'function') {
74
+ invalid(`host.${accessor}`, `must be a function when advertising ${capability}`)
75
+ }
76
+ const service = host[accessor]()
77
+ if (!record(service) || typeof service.then === 'function') {
78
+ invalid(`host.${accessor}()`, `must synchronously return a service when advertising ${capability}`)
79
+ }
80
+ for (const method of methods) {
81
+ if (typeof service[method] !== 'function') invalid(`host.${accessor}().${method}`, `must be a function when advertising ${capability}`)
82
+ }
83
+ }
84
+ return host
85
+ }
package/lib/host/dsh.mjs CHANGED
@@ -12,8 +12,12 @@
12
12
  * skills() { registerProvider(factory) => dispose }
13
13
  * tools() { registerWithDsh(ctx, registry, { namespace }) => dispose }
14
14
  * http() { createApp({id}), createSharedHost({id}) }
15
+ * web() { register({kind, path, handler}) => dispose, port } | undefined
15
16
  * proc() { start(serviceSpec) => Promise<{errors?}>, stop(id) }
16
17
  * ui() { createEditorHost({ id, dir, basePath, index }) }
18
+ *
19
+ * `web()` 是宿主网页端口本身(dsh 即 ctx.webServer)。拿到它时,内核一律把 HTTP
20
+ * 挂到该端口的路径前缀下,不再另起端口;拿不到才退回 os.net 的独立监听。
17
21
  */
18
22
  import { getService } from '../ctx-service.mjs'
19
23
  import { detectDshCapabilities } from './caps.mjs'
@@ -31,11 +35,16 @@ export function createDshHost(ctx) {
31
35
  const toolHost = getService(ctx, 'toolHost')
32
36
  if (!toolHost?.registerWithDsh) return null
33
37
  return {
34
- register: (registry, options) => toolHost.registerWithDsh(ctx, registry, options),
38
+ // tool-host reads ctx.tools directly. Pass only the resolved native tool
39
+ // service, not the foundation fiber's non-injected Cordis proxy.
40
+ register: (registry, options) => toolHost.registerWithDsh({ tools: getService(ctx, 'tools') }, registry, options),
35
41
  }
36
42
  },
37
43
  http: () => getService(ctx, 'serviceHost'),
44
+ web: () => getService(ctx, 'webServer'),
38
45
  proc: () => getService(ctx, 'serviceBroker'),
39
46
  ui: () => getService(ctx, 'editorHost'),
47
+ plugins: () => getService(ctx, 'pluginManager'),
48
+ assets: () => getService(ctx, 'assets'),
40
49
  }
41
50
  }
@@ -17,7 +17,11 @@ export function createMemoryHost(options = {}) {
17
17
  tools: [],
18
18
  apps: [],
19
19
  mounts: new Map(),
20
+ web: [],
20
21
  services: new Map(),
22
+ assets: new Map(),
23
+ bundles: [],
24
+ plugins: [],
21
25
  }
22
26
  const log = options.log ?? NOOP_LOG
23
27
 
@@ -57,6 +61,21 @@ export function createMemoryHost(options = {}) {
57
61
  }
58
62
  }
59
63
 
64
+ /** 参考宿主的「网页端口」:内存里只记录注册,证明内核走了同源前缀而非新端口。 */
65
+ function web() {
66
+ return {
67
+ port: 0,
68
+ register({ kind, path, handler } = {}) {
69
+ const entry = { kind, path, handler }
70
+ state.web.push(entry)
71
+ return () => {
72
+ const index = state.web.indexOf(entry)
73
+ if (index >= 0) state.web.splice(index, 1)
74
+ }
75
+ },
76
+ }
77
+ }
78
+
60
79
  return {
61
80
  kind: 'memory',
62
81
  version: '1.0.0',
@@ -65,9 +84,12 @@ export function createMemoryHost(options = {}) {
65
84
  ...BASE_CAPABILITIES,
66
85
  'os.skills': '1.0.0',
67
86
  'os.net': '1.0.0',
87
+ 'os.web': '1.0.0',
68
88
  'os.tools': '1.0.0',
69
89
  'os.proc': '1.0.0',
70
90
  'os.ui': '1.0.0',
91
+ 'os.plugins': '1.0.0',
92
+ 'os.assets': '1.0.0',
71
93
  }),
72
94
  log: () => log,
73
95
  skills: () => ({
@@ -91,6 +113,7 @@ export function createMemoryHost(options = {}) {
91
113
  },
92
114
  }),
93
115
  http,
116
+ web,
94
117
  proc: () => ({
95
118
  async start(serviceSpec) {
96
119
  state.services.set(serviceSpec.id, serviceSpec)
@@ -112,5 +135,26 @@ export function createMemoryHost(options = {}) {
112
135
  }
113
136
  },
114
137
  }),
138
+ plugins: () => ({
139
+ async listBundles() { return [...state.bundles] },
140
+ async listPlugins() { return [...state.plugins] },
141
+ async setBundleEnabled(name, enabled) {
142
+ state.bundles.push({ name, enabled, application: 'applied', changed: true })
143
+ return { application: 'applied', changed: true }
144
+ },
145
+ async setPluginEnabled(entryId, enabled) {
146
+ state.plugins.push({ entryId, enabled, application: 'applied', changed: true })
147
+ return { application: 'applied', changed: true }
148
+ },
149
+ }),
150
+ assets: () => ({
151
+ async put(value, contentType = 'application/octet-stream') {
152
+ const id = `asset-${state.assets.size + 1}`
153
+ const buffer = Buffer.isBuffer(value) ? value : Buffer.from(String(value))
154
+ state.assets.set(id, { data: buffer, contentType })
155
+ return { id, url: `/assets/${id}`, size: buffer.length, contentType }
156
+ },
157
+ get(id) { return state.assets.get(id) },
158
+ }),
115
159
  }
116
160
  }
package/lib/host.mjs CHANGED
@@ -12,11 +12,12 @@ export function apply(ctx, config = {}) {
12
12
  const kernel = createKernel(ctx, config)
13
13
  const dispose = ctx.provide('os', kernel.os)
14
14
  console.log('[foundation] ready(abi v' + kernel.os.abi + ')')
15
+ let cleanup
15
16
  return () => {
16
- try {
17
- kernel.dispose()
18
- } finally {
19
- if (typeof dispose === 'function') dispose()
20
- }
17
+ if (cleanup) return cleanup
18
+ // Withdraw the service immediately; retained references reject new mounts.
19
+ cleanup = kernel.dispose()
20
+ if (typeof dispose === 'function') dispose()
21
+ return cleanup
21
22
  }
22
23
  }
package/lib/kernel.mjs CHANGED
@@ -9,15 +9,22 @@
9
9
  * 惰性:os.net 只在第一次挂路由时创建共享宿主并 listen。
10
10
  */
11
11
  import { ABI_MAJOR } from '../abi/kinds.mjs'
12
+ import { AbiError, ERROR_CODES, toAbiError } from '../abi/errors.mjs'
12
13
  import { createLoader } from '../abi/loader.mjs'
13
14
  import { BASE_CAPABILITIES, detectDshCapabilities } from './host/caps.mjs'
14
15
  import { createDshHost } from './host/dsh.mjs'
16
+ import { assertHostContract } from './host/contract.mjs'
15
17
  import { createSkillAdapter } from './adapters/skill-provider.mjs'
16
18
  import { createToolProviderAdapter } from './adapters/tool-provider.mjs'
17
19
  import { createRuntimeDriverAdapter } from './adapters/runtime-driver.mjs'
18
20
  import { createHttpRouterAdapter } from './adapters/http-router.mjs'
19
21
  import { createUiPanelAdapter } from './adapters/ui-panel.mjs'
20
22
  import { createHookRegistry, createLifecycleAdapter } from './adapters/lifecycle-hook.mjs'
23
+ import { createHostEventAdapter } from './adapters/host-event.mjs'
24
+ import { createClientPanelAdapter } from './adapters/client-panel.mjs'
25
+ import { createOwnServerAdapter } from './adapters/own-server.mjs'
26
+ import { createServiceProviderAdapter } from './adapters/service-provider.mjs'
27
+ import { createRawAdapter } from './adapters/raw.mjs'
21
28
  import { createEvents } from './subsystems/events.mjs'
22
29
  import { createLogger } from './subsystems/log.mjs'
23
30
  import { createNet } from './subsystems/net.mjs'
@@ -38,7 +45,9 @@ export const ABI_VERSION = ABI_MAJOR
38
45
  * @param {{ host?: object }} [options] 显式传入 Host 适配器(测试/其他运行时)
39
46
  */
40
47
  export function createKernel(ctx, config = {}, options = {}) {
41
- const host = options.host ?? createDshHost(ctx)
48
+ const host = assertHostContract(options.host ?? createDshHost(ctx))
49
+ let closed = false
50
+ let disposal
42
51
  const log = createLogger(host, config)
43
52
  const events = createEvents({
44
53
  onError: (error, topic) => log.error(`事件订阅者抛错 (${topic}): ${error.message}`),
@@ -53,18 +62,50 @@ export function createKernel(ctx, config = {}, options = {}) {
53
62
  'http-router@1': createHttpRouterAdapter({ host, net, log }),
54
63
  'ui-panel@1': createUiPanelAdapter({ host, net, log }),
55
64
  'lifecycle-hook@1': createLifecycleAdapter({ hooks, log }),
65
+ 'host-event@1': createHostEventAdapter({ log }),
66
+ 'client-panel@1': createClientPanelAdapter({ host, net, log }),
67
+ 'own-server@1': createOwnServerAdapter({ host, log }),
68
+ 'service-provider@1': createServiceProviderAdapter({ log }),
69
+ 'raw@1': createRawAdapter({ log }),
56
70
  }
57
71
 
58
72
  /* 能力表按需现查:宿主服务可能晚于 foundation 激活。 */
59
- const loader = createLoader({ adapters, capabilities: () => host.capabilities(), log })
73
+ const loader = createLoader({
74
+ adapters,
75
+ capabilities: () => assertHostContract(host).capabilities(),
76
+ log,
77
+ })
60
78
  const startedAt = Date.now()
61
79
 
80
+ function hostService(accessor, capability) {
81
+ const service = typeof host[accessor] === 'function' ? host[accessor]() : null
82
+ if (!service || typeof service.then === 'function') {
83
+ throw new AbiError(ERROR_CODES.E_CAP_MISSING,
84
+ `${capability} 不可用:宿主没有提供 ${accessor} 服务`, { capability })
85
+ }
86
+ return service
87
+ }
88
+
89
+ function pluginManager() {
90
+ const service = hostService('plugins', 'os.plugins')
91
+ for (const method of ['listBundles', 'listPlugins', 'setBundleEnabled', 'setPluginEnabled']) {
92
+ if (typeof service[method] !== 'function') {
93
+ throw new AbiError(ERROR_CODES.E_CAP_MISSING,
94
+ `os.plugins 不可用:pluginManager 缺少 ${method}`, { capability: 'os.plugins', method })
95
+ }
96
+ }
97
+ return service
98
+ }
99
+
62
100
  const os = {
63
101
  version: KERNEL_VERSION,
64
102
  abi: ABI_VERSION,
65
103
  host: host.kind,
66
104
  hostVersion: host.version || '1.0.0',
67
- mount: (spec, mountConfig = {}, meta = {}) => loader.mount(spec, mountConfig, meta),
105
+ mount: (spec, mountConfig = {}, meta = {}) => {
106
+ if (closed) throw new AbiError(ERROR_CODES.E_KERNEL_CLOSED, 'kernel is shutting down')
107
+ return loader.mount(spec, mountConfig, { ...meta, os })
108
+ },
68
109
  report: () => ({
69
110
  kernel: {
70
111
  version: KERNEL_VERSION,
@@ -80,9 +121,34 @@ export function createKernel(ctx, config = {}, options = {}) {
80
121
  hooks,
81
122
  net,
82
123
 
124
+ /** 进程门面:长驻服务由宿主 broker 持有。 */
125
+ proc: {
126
+ start: (spec, options) => hostService('proc', 'os.proc').start(spec, options),
127
+ stop: (id) => hostService('proc', 'os.proc').stop(id),
128
+ list: () => {
129
+ const service = hostService('proc', 'os.proc')
130
+ return typeof service.list === 'function' ? service.list() : []
131
+ },
132
+ },
133
+
134
+ /** 宿主插件控制面:开关只有宿主自己实现,内核只做门面。 */
135
+ plugins: {
136
+ listBundles: () => pluginManager().listBundles(),
137
+ listPlugins: () => pluginManager().listPlugins(),
138
+ setBundleEnabled: (name, enabled) => pluginManager().setBundleEnabled(name, enabled),
139
+ setPluginEnabled: (entryId, enabled) => pluginManager().setPluginEnabled(entryId, enabled),
140
+ },
141
+
142
+ /** 资产仓库门面:put/get 走宿主 assets 服务,url 是统一引用格式。 */
143
+ assets: {
144
+ put: (value, contentType) => hostService('assets', 'os.assets').put(value, contentType),
145
+ get: (id) => hostService('assets', 'os.assets').get(id),
146
+ url: (id) => `/assets/${encodeURIComponent(String(id))}`,
147
+ },
148
+
83
149
  /** 能力检查与自报。 */
84
150
  caps: {
85
- list: () => Object.keys(host.capabilities()),
151
+ list: () => Object.keys(loader.report().capabilities),
86
152
  has: (name) => loader.capability(name) !== null,
87
153
  version: (name) => loader.capability(name),
88
154
  report: () => loader.report(),
@@ -92,9 +158,28 @@ export function createKernel(ctx, config = {}, options = {}) {
92
158
  return {
93
159
  os,
94
160
  dispose() {
95
- loader.disposeAll()
96
- events.clear()
97
- void net.dispose()
161
+ if (disposal) return disposal
162
+ closed = true
163
+ const cleanup = loader.disposeAll()
164
+ disposal = Promise.resolve(cleanup).then(async (result) => {
165
+ /* net.dispose 失败不得吞掉 loader 的清理结果,也不得让整体 disposal reject
166
+ * (宿主会据此误判卸载失败):并入 errors,始终返回 loader 结果。 */
167
+ let netError = null
168
+ try {
169
+ await net.dispose()
170
+ } catch (error) {
171
+ netError = error
172
+ }
173
+ /* events.clear 移到结算后:旧实现在 dispose 完成前就 clear,
174
+ * 卸载期间 onStop 等 emit 会丢失。 */
175
+ events.clear()
176
+ if (netError) {
177
+ const errors = [...(result?.errors || []), toAbiError(netError, ERROR_CODES.E_ADAPTER_THREW, { phase: 'net.dispose' })]
178
+ return { ...(result || {}), ok: false, errors }
179
+ }
180
+ return result
181
+ })
182
+ return disposal
98
183
  },
99
184
  }
100
185
  }
@@ -35,8 +35,13 @@ export function createEvents({ onError } = {}) {
35
35
  let delivered = 0
36
36
  for (const handler of [...bucket]) {
37
37
  try {
38
- handler(payload)
38
+ const result = handler(payload)
39
39
  delivered++
40
+ /* async 订阅者的 rejection 也要接住:旧实现只 catch 同步抛错,
41
+ * async handler 的 rejected promise 无人处理 → unhandledRejection。 */
42
+ if (result && typeof result.then === 'function') {
43
+ result.catch((error) => onError?.(error, topic))
44
+ }
40
45
  } catch (error) {
41
46
  onError?.(error, topic)
42
47
  }
@@ -7,12 +7,34 @@
7
7
  import { getService } from '../ctx-service.mjs'
8
8
 
9
9
  const LEVELS = ['debug', 'info', 'warn', 'error']
10
+
11
+ /* 安全格式化:日志调用绝不能反过来崩掉调用方。
12
+ * - Error 特判取 stack/message(JSON.stringify(Error) 是 '{}',根因会彻底丢失);
13
+ * - 循环引用用 replacer 标 '[Circular]',不再抛 Converting circular structure;
14
+ * - 其余 stringify 失败(BigInt 等)退回 String。 */
15
+ function format(arg) {
16
+ if (typeof arg === 'string') return arg
17
+ if (arg instanceof Error) return arg.stack || `${arg.name}: ${arg.message}`
18
+ const seen = new WeakSet()
19
+ try {
20
+ return JSON.stringify(arg, (_key, value) => {
21
+ if (typeof value === 'object' && value !== null) {
22
+ if (seen.has(value)) return '[Circular]'
23
+ seen.add(value)
24
+ }
25
+ return value
26
+ })
27
+ } catch {
28
+ return String(arg)
29
+ }
30
+ }
31
+
10
32
  function createScoped(underlying, scope) {
11
33
  const prefix = scope ? `[${scope}]` : ''
12
34
  const scoped = {}
13
35
  for (const level of LEVELS) {
14
36
  scoped[level] = (...args) => {
15
- const message = args.map((arg) => (typeof arg === 'string' ? arg : JSON.stringify(arg))).join(' ')
37
+ const message = args.map(format).join(' ')
16
38
  const line = `${prefix} ${message}`.trim()
17
39
  const fn = underlying?.[level]
18
40
  if (typeof fn === 'function') fn.call(underlying, line)