@capyclaw/skills-service 0.1.4 → 0.2.2
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 +3 -3
- package/node_modules/@capyclaw/foundation/README.md +51 -0
- package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
- package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
- package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
- package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
- package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
- package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
- package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
- package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
- package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
- package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
- package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
- package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
- package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
- package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
- package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
- package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
- package/node_modules/@capyclaw/foundation/package.json +53 -0
- package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
- 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 +143 -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 +41 -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 +10 -3
- package/server.mjs +49 -13
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh 宿主适配器:把 Cordis ctx 翻译成内核认识的 Host 接口。
|
|
3
|
+
*
|
|
4
|
+
* 这是整个 foundation 里**唯一**知道 dsh 服务名的地方。换一个 agent 运行时,
|
|
5
|
+
* 只需要照着 Host 接口写一个新的适配器(lib/host/<runtime>.mjs),
|
|
6
|
+
* 内核、ABI 与应用插件都不改。
|
|
7
|
+
*
|
|
8
|
+
* Host 接口(v1):
|
|
9
|
+
* kind 宿主标识
|
|
10
|
+
* capabilities() 返回 { 'os.xxx': '1.0.0' },用于 mount 前的能力校验
|
|
11
|
+
* log() 返回 { debug/info/warn/error } 或 undefined
|
|
12
|
+
* skills() { registerProvider(factory) => dispose }
|
|
13
|
+
* tools() { registerWithDsh(ctx, registry, { namespace }) => dispose }
|
|
14
|
+
* http() { createApp({id}), createSharedHost({id}) }
|
|
15
|
+
* web() { register({kind, path, handler}) => dispose, port } | undefined
|
|
16
|
+
* proc() { start(serviceSpec) => Promise<{errors?}>, stop(id) }
|
|
17
|
+
* ui() { createEditorHost({ id, dir, basePath, index }) }
|
|
18
|
+
*
|
|
19
|
+
* `web()` 是宿主网页端口本身(dsh 即 ctx.webServer)。拿到它时,内核一律把 HTTP
|
|
20
|
+
* 挂到该端口的路径前缀下,不再另起端口;拿不到才退回 os.net 的独立监听。
|
|
21
|
+
*/
|
|
22
|
+
import { getService } from '../ctx-service.mjs'
|
|
23
|
+
import { detectDshCapabilities } from './caps.mjs'
|
|
24
|
+
|
|
25
|
+
export const HOST_VERSION = '1.0.0'
|
|
26
|
+
|
|
27
|
+
export function createDshHost(ctx) {
|
|
28
|
+
return {
|
|
29
|
+
kind: 'dsh',
|
|
30
|
+
version: HOST_VERSION,
|
|
31
|
+
capabilities: () => detectDshCapabilities(ctx),
|
|
32
|
+
log: () => getService(ctx, 'logger'),
|
|
33
|
+
skills: () => getService(ctx, 'skills'),
|
|
34
|
+
tools: () => {
|
|
35
|
+
const toolHost = getService(ctx, 'toolHost')
|
|
36
|
+
if (!toolHost?.registerWithDsh) return null
|
|
37
|
+
return {
|
|
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),
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
http: () => getService(ctx, 'serviceHost'),
|
|
44
|
+
web: () => getService(ctx, 'webServer'),
|
|
45
|
+
proc: () => getService(ctx, 'serviceBroker'),
|
|
46
|
+
ui: () => getService(ctx, 'editorHost'),
|
|
47
|
+
plugins: () => getService(ctx, 'pluginManager'),
|
|
48
|
+
assets: () => getService(ctx, 'assets'),
|
|
49
|
+
}
|
|
50
|
+
}
|
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 内存宿主:Host 接口的参考实现,不依赖任何 agent 运行时。
|
|
3
|
+
*
|
|
4
|
+
* 用途有两个:
|
|
5
|
+
* 1. 一致性测试的基线——应用插件在这里跑通,说明它没有偷偷依赖 dsh;
|
|
6
|
+
* 2. 新宿主(别的 agent 系统)的模板——照这个接口实现即可,应用插件零改动。
|
|
7
|
+
*
|
|
8
|
+
* 它不承担真实网络/进程语义,只保证 Host 契约的形状与生命周期。
|
|
9
|
+
*/
|
|
10
|
+
import { BASE_CAPABILITIES } from './caps.mjs'
|
|
11
|
+
|
|
12
|
+
const NOOP_LOG = { debug() {}, info() {}, warn() {}, error() {} }
|
|
13
|
+
|
|
14
|
+
export function createMemoryHost(options = {}) {
|
|
15
|
+
const state = {
|
|
16
|
+
providers: [],
|
|
17
|
+
tools: [],
|
|
18
|
+
apps: [],
|
|
19
|
+
mounts: new Map(),
|
|
20
|
+
web: [],
|
|
21
|
+
services: new Map(),
|
|
22
|
+
assets: new Map(),
|
|
23
|
+
bundles: [],
|
|
24
|
+
plugins: [],
|
|
25
|
+
}
|
|
26
|
+
const log = options.log ?? NOOP_LOG
|
|
27
|
+
|
|
28
|
+
function http() {
|
|
29
|
+
return {
|
|
30
|
+
createApp({ id, title } = {}) {
|
|
31
|
+
const routes = []
|
|
32
|
+
const app = {
|
|
33
|
+
id,
|
|
34
|
+
title: title || id,
|
|
35
|
+
routes,
|
|
36
|
+
use(handler) {
|
|
37
|
+
routes.push(handler)
|
|
38
|
+
return () => {
|
|
39
|
+
const index = routes.indexOf(handler)
|
|
40
|
+
if (index >= 0) routes.splice(index, 1)
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
async dispatch() {},
|
|
44
|
+
}
|
|
45
|
+
state.apps.push(app)
|
|
46
|
+
return app
|
|
47
|
+
},
|
|
48
|
+
createSharedHost({ id } = {}) {
|
|
49
|
+
return {
|
|
50
|
+
id,
|
|
51
|
+
mount(prefix, child) {
|
|
52
|
+
if (state.mounts.has(prefix)) throw new Error(`前缀已挂载: ${prefix}`)
|
|
53
|
+
state.mounts.set(prefix, child.id)
|
|
54
|
+
return () => state.mounts.delete(prefix)
|
|
55
|
+
},
|
|
56
|
+
listen: () => Promise.resolve({ port: 0, url: `memory://${id || 'shared'}` }),
|
|
57
|
+
close: async () => {},
|
|
58
|
+
children: () => [...state.mounts.keys()],
|
|
59
|
+
}
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
}
|
|
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
|
+
|
|
79
|
+
return {
|
|
80
|
+
kind: 'memory',
|
|
81
|
+
version: '1.0.0',
|
|
82
|
+
state,
|
|
83
|
+
capabilities: () => ({
|
|
84
|
+
...BASE_CAPABILITIES,
|
|
85
|
+
'os.skills': '1.0.0',
|
|
86
|
+
'os.net': '1.0.0',
|
|
87
|
+
'os.web': '1.0.0',
|
|
88
|
+
'os.tools': '1.0.0',
|
|
89
|
+
'os.proc': '1.0.0',
|
|
90
|
+
'os.ui': '1.0.0',
|
|
91
|
+
'os.plugins': '1.0.0',
|
|
92
|
+
'os.assets': '1.0.0',
|
|
93
|
+
}),
|
|
94
|
+
log: () => log,
|
|
95
|
+
skills: () => ({
|
|
96
|
+
registerProvider(factory) {
|
|
97
|
+
const provider = factory()
|
|
98
|
+
state.providers.push(provider)
|
|
99
|
+
return () => {
|
|
100
|
+
const index = state.providers.indexOf(provider)
|
|
101
|
+
if (index >= 0) state.providers.splice(index, 1)
|
|
102
|
+
}
|
|
103
|
+
},
|
|
104
|
+
}),
|
|
105
|
+
tools: () => ({
|
|
106
|
+
register(registry, options2 = {}) {
|
|
107
|
+
const entry = { registry, namespace: options2.namespace || '' }
|
|
108
|
+
state.tools.push(entry)
|
|
109
|
+
return () => {
|
|
110
|
+
const index = state.tools.indexOf(entry)
|
|
111
|
+
if (index >= 0) state.tools.splice(index, 1)
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
}),
|
|
115
|
+
http,
|
|
116
|
+
web,
|
|
117
|
+
proc: () => ({
|
|
118
|
+
async start(serviceSpec) {
|
|
119
|
+
state.services.set(serviceSpec.id, serviceSpec)
|
|
120
|
+
return { services: [{ id: serviceSpec.id }], errors: [] }
|
|
121
|
+
},
|
|
122
|
+
stop(id) {
|
|
123
|
+
state.services.delete(id)
|
|
124
|
+
},
|
|
125
|
+
}),
|
|
126
|
+
ui: () => ({
|
|
127
|
+
createEditorHost({ id, dir, basePath, index }) {
|
|
128
|
+
return {
|
|
129
|
+
id,
|
|
130
|
+
dir,
|
|
131
|
+
basePath,
|
|
132
|
+
index,
|
|
133
|
+
routes: () => [async () => false],
|
|
134
|
+
status: () => ({ connected: false, lease: null }),
|
|
135
|
+
}
|
|
136
|
+
},
|
|
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
|
+
}),
|
|
159
|
+
}
|
|
160
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/foundation 的 Cordis 入口:向同进程插件提供 ctx.os。
|
|
3
|
+
*
|
|
4
|
+
* 这是整个工程里唯一一处「把内核交给 dsh」的接缝。应用插件不 import 这个文件,
|
|
5
|
+
* 它们只在自己的 apply 里拿到 ctx.os。
|
|
6
|
+
*/
|
|
7
|
+
import { createKernel } from './kernel.mjs'
|
|
8
|
+
|
|
9
|
+
export const name = 'capyclaw-foundation'
|
|
10
|
+
|
|
11
|
+
export function apply(ctx, config = {}) {
|
|
12
|
+
const kernel = createKernel(ctx, config)
|
|
13
|
+
const dispose = ctx.provide('os', kernel.os)
|
|
14
|
+
console.log('[foundation] ready(abi v' + kernel.os.abi + ')')
|
|
15
|
+
let cleanup
|
|
16
|
+
return () => {
|
|
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
|
|
22
|
+
}
|
|
23
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 内核装配:把 ABI 加载器、适配器与 os 子系统接到一起。
|
|
3
|
+
*
|
|
4
|
+
* 分层:应用插件 → ABI → 内核 → **Host 适配器** → agent 运行时(dsh)。
|
|
5
|
+
* 内核不认识 dsh:它只调用 Host 接口(skills/tools/http/proc/ui/log/capabilities)。
|
|
6
|
+
* 换宿主 = 写一个新的 lib/host/<runtime>.mjs,ABI 与应用插件零改动。
|
|
7
|
+
*
|
|
8
|
+
* 能力表是**每次 mount 时现查**的:宿主服务晚于 foundation 激活也能被看到。
|
|
9
|
+
* 惰性:os.net 只在第一次挂路由时创建共享宿主并 listen。
|
|
10
|
+
*/
|
|
11
|
+
import { ABI_MAJOR } from '../abi/kinds.mjs'
|
|
12
|
+
import { AbiError, ERROR_CODES, toAbiError } from '../abi/errors.mjs'
|
|
13
|
+
import { createLoader } from '../abi/loader.mjs'
|
|
14
|
+
import { BASE_CAPABILITIES, detectDshCapabilities } from './host/caps.mjs'
|
|
15
|
+
import { createDshHost } from './host/dsh.mjs'
|
|
16
|
+
import { assertHostContract } from './host/contract.mjs'
|
|
17
|
+
import { createSkillAdapter } from './adapters/skill-provider.mjs'
|
|
18
|
+
import { createToolProviderAdapter } from './adapters/tool-provider.mjs'
|
|
19
|
+
import { createRuntimeDriverAdapter } from './adapters/runtime-driver.mjs'
|
|
20
|
+
import { createHttpRouterAdapter } from './adapters/http-router.mjs'
|
|
21
|
+
import { createUiPanelAdapter } from './adapters/ui-panel.mjs'
|
|
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'
|
|
28
|
+
import { createEvents } from './subsystems/events.mjs'
|
|
29
|
+
import { createLogger } from './subsystems/log.mjs'
|
|
30
|
+
import { createNet } from './subsystems/net.mjs'
|
|
31
|
+
|
|
32
|
+
export { BASE_CAPABILITIES }
|
|
33
|
+
|
|
34
|
+
/** 兼容导出:测试与旧调用方按 ctx 探测 dsh 能力。 */
|
|
35
|
+
export function detectCapabilities(ctx) {
|
|
36
|
+
return detectDshCapabilities(ctx)
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export const KERNEL_VERSION = '0.1.0'
|
|
40
|
+
export const ABI_VERSION = ABI_MAJOR
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* @param {object} ctx dsh Cordis ctx(自定义宿主时可为 null)
|
|
44
|
+
* @param {object} config 内核配置
|
|
45
|
+
* @param {{ host?: object }} [options] 显式传入 Host 适配器(测试/其他运行时)
|
|
46
|
+
*/
|
|
47
|
+
export function createKernel(ctx, config = {}, options = {}) {
|
|
48
|
+
const host = assertHostContract(options.host ?? createDshHost(ctx))
|
|
49
|
+
let closed = false
|
|
50
|
+
let disposal
|
|
51
|
+
const log = createLogger(host, config)
|
|
52
|
+
const events = createEvents({
|
|
53
|
+
onError: (error, topic) => log.error(`事件订阅者抛错 (${topic}): ${error.message}`),
|
|
54
|
+
})
|
|
55
|
+
const hooks = createHookRegistry()
|
|
56
|
+
const net = createNet(host, config)
|
|
57
|
+
|
|
58
|
+
const adapters = {
|
|
59
|
+
'skill-provider@1': createSkillAdapter({ host, log }),
|
|
60
|
+
'tool-provider@1': createToolProviderAdapter({ host, log }),
|
|
61
|
+
'runtime-driver@1': createRuntimeDriverAdapter({ host, config, log }),
|
|
62
|
+
'http-router@1': createHttpRouterAdapter({ host, net, log }),
|
|
63
|
+
'ui-panel@1': createUiPanelAdapter({ host, net, log }),
|
|
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 }),
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/* 能力表按需现查:宿主服务可能晚于 foundation 激活。 */
|
|
73
|
+
const loader = createLoader({
|
|
74
|
+
adapters,
|
|
75
|
+
capabilities: () => assertHostContract(host).capabilities(),
|
|
76
|
+
log,
|
|
77
|
+
})
|
|
78
|
+
const startedAt = Date.now()
|
|
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
|
+
|
|
100
|
+
const os = {
|
|
101
|
+
version: KERNEL_VERSION,
|
|
102
|
+
abi: ABI_VERSION,
|
|
103
|
+
host: host.kind,
|
|
104
|
+
hostVersion: host.version || '1.0.0',
|
|
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
|
+
},
|
|
109
|
+
report: () => ({
|
|
110
|
+
kernel: {
|
|
111
|
+
version: KERNEL_VERSION,
|
|
112
|
+
abi: ABI_VERSION,
|
|
113
|
+
host: host.kind,
|
|
114
|
+
hostVersion: host.version || '1.0.0',
|
|
115
|
+
uptimeMs: Date.now() - startedAt,
|
|
116
|
+
},
|
|
117
|
+
...loader.report(),
|
|
118
|
+
}),
|
|
119
|
+
events,
|
|
120
|
+
log,
|
|
121
|
+
hooks,
|
|
122
|
+
net,
|
|
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
|
+
|
|
149
|
+
/** 能力检查与自报。 */
|
|
150
|
+
caps: {
|
|
151
|
+
list: () => Object.keys(loader.report().capabilities),
|
|
152
|
+
has: (name) => loader.capability(name) !== null,
|
|
153
|
+
version: (name) => loader.capability(name),
|
|
154
|
+
report: () => loader.report(),
|
|
155
|
+
},
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
return {
|
|
159
|
+
os,
|
|
160
|
+
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
|
|
183
|
+
},
|
|
184
|
+
}
|
|
185
|
+
}
|
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 技能扫描:SKILL.md 目录 → dsh skills provider。
|
|
3
|
+
*
|
|
4
|
+
* 这份实现是整个基石层里 skill-provider@1 的唯一实现。
|
|
5
|
+
* 此前 15 个包各自复制了一份 provider.mjs(sha256 相同),
|
|
6
|
+
* 迁移完成后由内核统一提供,应用包只声明目录。
|
|
7
|
+
*/
|
|
8
|
+
import { readFileSync } from 'node:fs'
|
|
9
|
+
import { readFile } from 'node:fs/promises'
|
|
10
|
+
import { isAbsolute, join, sep } from 'node:path'
|
|
11
|
+
|
|
12
|
+
const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
13
|
+
const DEFAULT_RANK = 600
|
|
14
|
+
|
|
15
|
+
export function parseSkill(raw, path) {
|
|
16
|
+
const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(raw)
|
|
17
|
+
if (!frontmatter?.[1]) throw new Error(`skill ${path} 缺少 YAML frontmatter`)
|
|
18
|
+
const meta = {}
|
|
19
|
+
for (const line of frontmatter[1].split(/\r?\n/)) {
|
|
20
|
+
const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line)
|
|
21
|
+
if (match) meta[match[1]] = match[2].replace(/^['"]|['"]$/g, '').trim()
|
|
22
|
+
}
|
|
23
|
+
if (!meta.name || !meta.description) throw new Error(`skill ${path} 缺少 name/description`)
|
|
24
|
+
if (!NAME_RE.test(meta.name)) throw new Error(`skill ${path} name 必须是 kebab-case`)
|
|
25
|
+
return {
|
|
26
|
+
name: meta.name,
|
|
27
|
+
description: meta.description,
|
|
28
|
+
whenToUse: meta.whenToUse || undefined,
|
|
29
|
+
content: raw.slice(frontmatter[0].length).trim(),
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* @param {{
|
|
35
|
+
* assetRoot: string,
|
|
36
|
+
* skillDirs: string[],
|
|
37
|
+
* providerName?: string,
|
|
38
|
+
* rank?: number,
|
|
39
|
+
* contract?: { version: string } | null,
|
|
40
|
+
* contractNote?: (version: string, skillName: string) => string
|
|
41
|
+
* }} config
|
|
42
|
+
*/
|
|
43
|
+
export function createSkillProvider(config) {
|
|
44
|
+
const assetRoot = config.assetRoot
|
|
45
|
+
if (!assetRoot || !isAbsolute(assetRoot)) throw new Error('createSkillProvider: assetRoot 必须是绝对路径')
|
|
46
|
+
const rank = config.rank ?? DEFAULT_RANK
|
|
47
|
+
const dirs = config.skillDirs || []
|
|
48
|
+
if (!dirs.length) throw new Error('createSkillProvider: skillDirs 不能为空')
|
|
49
|
+
|
|
50
|
+
const candidates = dirs.map((dir) => {
|
|
51
|
+
if (!NAME_RE.test(dir)) throw new Error(`skill 目录名必须是 kebab-case:${dir}`)
|
|
52
|
+
const directory = join(assetRoot, dir)
|
|
53
|
+
const locator = join(directory, 'SKILL.md')
|
|
54
|
+
const parsed = parseSkill(readFileSync(locator, 'utf8'), locator)
|
|
55
|
+
if (parsed.name !== dir) throw new Error(`skill ${locator} name 必须是 ${dir}`)
|
|
56
|
+
return {
|
|
57
|
+
name: parsed.name,
|
|
58
|
+
description: parsed.description,
|
|
59
|
+
whenToUse: parsed.whenToUse,
|
|
60
|
+
invocation: { modelInvocable: true, userInvocable: true },
|
|
61
|
+
provider: config.providerName || 'dsh-plugin',
|
|
62
|
+
source: 'bundled',
|
|
63
|
+
rank,
|
|
64
|
+
resourceBase: { kind: 'directory', path: directory.split(sep).join('/') },
|
|
65
|
+
locator,
|
|
66
|
+
}
|
|
67
|
+
})
|
|
68
|
+
|
|
69
|
+
const byName = new Map(candidates.map((candidate) => [candidate.name, candidate]))
|
|
70
|
+
const noteFor = (name) => (config.contract && config.contractNote
|
|
71
|
+
? config.contractNote(config.contract.contractVersion ?? config.contract.version, name)
|
|
72
|
+
: '')
|
|
73
|
+
|
|
74
|
+
return {
|
|
75
|
+
name: config.providerName || 'dsh-plugin',
|
|
76
|
+
list: () => Promise.resolve(candidates),
|
|
77
|
+
async get(candidate, options = {}) {
|
|
78
|
+
const hit = byName.get(candidate.name)
|
|
79
|
+
if (!hit) throw new Error(`未知 skill ${candidate.name}`)
|
|
80
|
+
const raw = await readFile(hit.locator, { encoding: 'utf8', signal: options.signal })
|
|
81
|
+
const parsed = parseSkill(raw, hit.locator)
|
|
82
|
+
const { rank: _rank, locator: _locator, ...summary } = hit
|
|
83
|
+
const note = noteFor(candidate.name)
|
|
84
|
+
return { ...summary, content: parsed.content + (note ? `\n\n---\n\n${note}` : '') }
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 进程内事件总线:插件之间唯一的广播通道。
|
|
3
|
+
*
|
|
4
|
+
* 约定:emit 永不因订阅者抛错而中断;错误交给 onError 记录。
|
|
5
|
+
*/
|
|
6
|
+
export function createEvents({ onError } = {}) {
|
|
7
|
+
const listeners = new Map()
|
|
8
|
+
|
|
9
|
+
function on(topic, handler) {
|
|
10
|
+
if (typeof handler !== 'function') throw new TypeError('events.on 需要函数')
|
|
11
|
+
if (!listeners.has(topic)) listeners.set(topic, [])
|
|
12
|
+
listeners.get(topic).push(handler)
|
|
13
|
+
return () => off(topic, handler)
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
function once(topic, handler) {
|
|
17
|
+
const dispose = on(topic, (...args) => {
|
|
18
|
+
dispose()
|
|
19
|
+
handler(...args)
|
|
20
|
+
})
|
|
21
|
+
return dispose
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function off(topic, handler) {
|
|
25
|
+
const bucket = listeners.get(topic)
|
|
26
|
+
if (!bucket) return
|
|
27
|
+
const index = bucket.indexOf(handler)
|
|
28
|
+
if (index >= 0) bucket.splice(index, 1)
|
|
29
|
+
if (!bucket.length) listeners.delete(topic)
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function emit(topic, payload) {
|
|
33
|
+
const bucket = listeners.get(topic)
|
|
34
|
+
if (!bucket) return 0
|
|
35
|
+
let delivered = 0
|
|
36
|
+
for (const handler of [...bucket]) {
|
|
37
|
+
try {
|
|
38
|
+
const result = handler(payload)
|
|
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
|
+
}
|
|
45
|
+
} catch (error) {
|
|
46
|
+
onError?.(error, topic)
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return delivered
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
return {
|
|
53
|
+
on,
|
|
54
|
+
once,
|
|
55
|
+
off,
|
|
56
|
+
emit,
|
|
57
|
+
topics: () => [...listeners.keys()],
|
|
58
|
+
clear: () => listeners.clear(),
|
|
59
|
+
}
|
|
60
|
+
}
|