@capyclaw/skills-service 0.1.3 → 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.
Files changed (68) hide show
  1. package/README.md +7 -7
  2. package/node_modules/@capyclaw/foundation/README.md +51 -0
  3. package/node_modules/@capyclaw/foundation/abi/bridge.mjs +86 -0
  4. package/node_modules/@capyclaw/foundation/abi/errors.mjs +63 -0
  5. package/node_modules/@capyclaw/foundation/abi/index.mjs +35 -0
  6. package/node_modules/@capyclaw/foundation/abi/kinds.mjs +271 -0
  7. package/node_modules/@capyclaw/foundation/abi/loader.mjs +345 -0
  8. package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
  9. package/node_modules/@capyclaw/foundation/abi/spec.mjs +255 -0
  10. package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
  11. package/node_modules/@capyclaw/foundation/abi/version.mjs +82 -0
  12. package/node_modules/@capyclaw/foundation/cordis.patch.yml +5 -0
  13. package/node_modules/@capyclaw/foundation/kit/index.mjs +6 -0
  14. package/node_modules/@capyclaw/foundation/lib/adapters/client-panel.mjs +98 -0
  15. package/node_modules/@capyclaw/foundation/lib/adapters/host-event.mjs +35 -0
  16. package/node_modules/@capyclaw/foundation/lib/adapters/http-router.mjs +69 -0
  17. package/node_modules/@capyclaw/foundation/lib/adapters/lifecycle-hook.mjs +55 -0
  18. package/node_modules/@capyclaw/foundation/lib/adapters/own-server.mjs +113 -0
  19. package/node_modules/@capyclaw/foundation/lib/adapters/raw.mjs +68 -0
  20. package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +113 -0
  21. package/node_modules/@capyclaw/foundation/lib/adapters/service-provider.mjs +77 -0
  22. package/node_modules/@capyclaw/foundation/lib/adapters/skill-provider.mjs +56 -0
  23. package/node_modules/@capyclaw/foundation/lib/adapters/tool-provider.mjs +50 -0
  24. package/node_modules/@capyclaw/foundation/lib/adapters/ui-panel.mjs +64 -0
  25. package/node_modules/@capyclaw/foundation/lib/ctx-service.mjs +42 -0
  26. package/node_modules/@capyclaw/foundation/lib/host/caps.mjs +34 -0
  27. package/node_modules/@capyclaw/foundation/lib/host/contract.mjs +85 -0
  28. package/node_modules/@capyclaw/foundation/lib/host/dsh.mjs +50 -0
  29. package/node_modules/@capyclaw/foundation/lib/host/memory.mjs +160 -0
  30. package/node_modules/@capyclaw/foundation/lib/host.mjs +23 -0
  31. package/node_modules/@capyclaw/foundation/lib/kernel.mjs +185 -0
  32. package/node_modules/@capyclaw/foundation/lib/skill/scan.mjs +87 -0
  33. package/node_modules/@capyclaw/foundation/lib/subsystems/events.mjs +60 -0
  34. package/node_modules/@capyclaw/foundation/lib/subsystems/log.mjs +51 -0
  35. package/node_modules/@capyclaw/foundation/lib/subsystems/net.mjs +188 -0
  36. package/node_modules/@capyclaw/foundation/package.json +53 -0
  37. package/node_modules/@capyclaw/foundation/runtime/index.mjs +20 -0
  38. package/node_modules/@capyclaw/plugin-kit/INTEGRATION.md +100 -0
  39. package/node_modules/@capyclaw/plugin-kit/README.md +70 -0
  40. package/node_modules/@capyclaw/plugin-kit/bin/sync.mjs +103 -0
  41. package/node_modules/@capyclaw/plugin-kit/package.json +69 -0
  42. package/node_modules/@capyclaw/plugin-kit/src/cli.mjs +56 -0
  43. package/node_modules/@capyclaw/plugin-kit/src/config.mjs +142 -0
  44. package/node_modules/@capyclaw/plugin-kit/src/editor/heartbeat-worker.js +129 -0
  45. package/node_modules/@capyclaw/plugin-kit/src/editor/lease.mjs +139 -0
  46. package/node_modules/@capyclaw/plugin-kit/src/editor/shadow.mjs +219 -0
  47. package/node_modules/@capyclaw/plugin-kit/src/editor/transport.js +13 -0
  48. package/node_modules/@capyclaw/plugin-kit/src/index.mjs +13 -0
  49. package/node_modules/@capyclaw/plugin-kit/src/pack.mjs +230 -0
  50. package/node_modules/@capyclaw/plugin-kit/src/runtime/context.mjs +128 -0
  51. package/node_modules/@capyclaw/plugin-kit/src/self-contained.mjs +307 -0
  52. package/node_modules/@capyclaw/plugin-kit/src/service/api.mjs +45 -0
  53. package/node_modules/@capyclaw/plugin-kit/src/service/http.mjs +113 -0
  54. package/node_modules/@capyclaw/plugin-kit/src/service/mcp-http.mjs +143 -0
  55. package/node_modules/@capyclaw/plugin-kit/src/service/server.mjs +131 -0
  56. package/node_modules/@capyclaw/plugin-kit/src/skills/provider.mjs +82 -0
  57. package/node_modules/@capyclaw/plugin-kit/src/store/blob-store.mjs +109 -0
  58. package/node_modules/@capyclaw/plugin-kit/src/store/content-store.mjs +17 -0
  59. package/node_modules/@capyclaw/plugin-kit/src/store/journal-store.mjs +89 -0
  60. package/node_modules/@capyclaw/plugin-kit/src/tools/result.mjs +41 -0
  61. package/node_modules/@capyclaw/plugin-kit/src/tools/validate.mjs +150 -0
  62. package/node_modules/@capyclaw/plugin-kit/src/tuning.mjs +82 -0
  63. package/node_modules/@capyclaw/plugin-kit/src/util/fs-lock.mjs +132 -0
  64. package/node_modules/@capyclaw/plugin-kit/src/util/http.mjs +130 -0
  65. package/node_modules/@capyclaw/plugin-kit/src/workspace/manager.mjs +656 -0
  66. package/node_modules/@capyclaw/plugin-kit/src/zip.mjs +181 -0
  67. package/package.json +18 -2
  68. package/server.mjs +237 -201
@@ -0,0 +1,45 @@
1
+ /** 公共服务 API 契约:插件之间只通过这份描述判断兼容性。 */
2
+
3
+ /**
4
+ * @param {string} name 服务名(ctx.<name>)
5
+ * @param {string} version API 版本(semver;major 变化 = 不兼容)
6
+ * @param {string[]} capabilities 能力标签
7
+ */
8
+ export function createServiceApi(name, version = '1.0.0', capabilities = []) {
9
+ if (!name) throw new Error('createServiceApi 需要 name')
10
+ return Object.freeze({
11
+ name,
12
+ version,
13
+ capabilities: Object.freeze([...capabilities]),
14
+ })
15
+ }
16
+
17
+ /**
18
+ * 断言一个已注入的服务对象满足消费者要求。
19
+ * 缺失服务或 major 不一致时抛出明确错误,避免“看起来能跑”的静默不兼容。
20
+ * @param {object} service
21
+ * @param {{ name: string, major?: number|string, version?: string }} expected
22
+ */
23
+ export function assertServiceApi(service, expected = {}) {
24
+ const name = expected.name
25
+ if (!name) throw new Error('assertServiceApi 需要 expected.name')
26
+ const major = String(expected.major ?? String(expected.version || '1').split('.')[0])
27
+ if (!service) throw new Error(`缺少公共服务: ctx.${name}`)
28
+ const api = service.api
29
+ if (!api || typeof api !== 'object') {
30
+ throw new Error(`服务 ctx.${name} 没有声明 api 契约;请升级提供方插件`)
31
+ }
32
+ if (api.name !== name) {
33
+ throw new Error(`服务 ctx.${name} 的 api.name=${api.name},与消费者期望的 ${name} 不一致`)
34
+ }
35
+ const gotMajor = String(api.version || '').split('.')[0]
36
+ if (gotMajor !== major) {
37
+ throw new Error(`服务 ctx.${name} API major=${gotMajor},消费者要求 major=${major}(提供方版本 ${api.version})`)
38
+ }
39
+ return api
40
+ }
41
+
42
+ export function serviceApiSummary(service) {
43
+ const api = service?.api
44
+ return api ? { name: api.name, version: api.version, capabilities: [...(api.capabilities || [])] } : null
45
+ }
@@ -0,0 +1,113 @@
1
+ /** 本机插件 HTTP 传输:安全响应头、body 上限、查询解析、loopback 监听。 */
2
+ import http from 'node:http'
3
+ import { tuning } from '../tuning.mjs'
4
+
5
+ export const SECURITY_HEADERS = {
6
+ 'x-content-type-options': 'nosniff',
7
+ 'referrer-policy': 'no-referrer',
8
+ 'cache-control': 'no-store, no-cache, must-revalidate',
9
+ }
10
+
11
+ /** 客户端已断开时放弃写入:长请求(截图/长轮询)在 handler 完成前客户端超时
12
+ * 断连是常态,写已销毁的 socket 会触发无人监听的 'error' 事件打崩进程。 */
13
+ function resDead(res) {
14
+ return res.destroyed || res.writableEnded
15
+ }
16
+
17
+ export function send(req, res, code, obj, extraHeaders = {}) {
18
+ if (resDead(res)) return
19
+ const body = obj === undefined ? '' : JSON.stringify(obj)
20
+ try {
21
+ res.writeHead(code, {
22
+ 'content-type': 'application/json',
23
+ 'content-length': Buffer.byteLength(body),
24
+ ...SECURITY_HEADERS,
25
+ ...extraHeaders,
26
+ })
27
+ res.end(req.method === 'HEAD' ? undefined : body)
28
+ } catch { /* socket 已死:响应无人接收,静默放弃 */ }
29
+ }
30
+
31
+ export function sendText(req, res, code, text, contentType = 'text/plain; charset=utf-8', extraHeaders = {}) {
32
+ if (resDead(res)) return
33
+ const body = text === undefined || text === null ? '' : String(text)
34
+ try {
35
+ res.writeHead(code, {
36
+ 'content-type': contentType,
37
+ 'content-length': Buffer.byteLength(body),
38
+ ...SECURITY_HEADERS,
39
+ ...extraHeaders,
40
+ })
41
+ res.end(req.method === 'HEAD' ? undefined : body)
42
+ } catch { /* socket 已死:响应无人接收,静默放弃 */ }
43
+ }
44
+
45
+ function bodyError(code, message) {
46
+ const error = new Error(message)
47
+ error.code = code
48
+ return error
49
+ }
50
+
51
+ export function readBody(req, limit = 10 * 1024 * 1024) {
52
+ return new Promise((resolve, reject) => {
53
+ let size = 0
54
+ const chunks = []
55
+ let settled = false
56
+ const fail = (error) => {
57
+ if (settled) return
58
+ settled = true
59
+ reject(error)
60
+ }
61
+ req.on('data', (chunk) => {
62
+ if (settled) return
63
+ size += chunk.length
64
+ if (size > limit) {
65
+ /* 先让路由回 413;立即 destroy 会让客户端只看到 connection reset。 */
66
+ fail(bodyError('BODY_TOO_LARGE', 'body too large'))
67
+ req.resume()
68
+ return
69
+ }
70
+ chunks.push(chunk)
71
+ })
72
+ req.on('end', () => {
73
+ if (settled) return
74
+ settled = true
75
+ const raw = Buffer.concat(chunks).toString('utf8')
76
+ if (!raw) return resolve({})
77
+ try { resolve(JSON.parse(raw)) } catch { reject(bodyError('BAD_JSON', 'bad json')) }
78
+ })
79
+ req.on('error', (error) => fail(error))
80
+ /* 客户端中途断连且未触发 error/aborted 时(如 curl -m 超时),close 兜底,
81
+ 否则 promise 永远 pending,handler 泄漏。 */
82
+ req.on('close', () => {
83
+ if (!req.readableEnded) fail(bodyError('CLIENT_ABORTED', 'client aborted'))
84
+ })
85
+ })
86
+ }
87
+
88
+ export function intQ(url, name) {
89
+ const value = parseInt(url.searchParams.get(name) || '0', 10)
90
+ return Number.isFinite(value) && value >= 0 ? value : 0
91
+ }
92
+
93
+ export function listen(port, opts = {}) {
94
+ const defaults = tuning()
95
+ const {
96
+ host = '127.0.0.1',
97
+ requestTimeoutMs = defaults.requestTimeoutMs,
98
+ headersTimeoutMs = defaults.headersTimeoutMs,
99
+ keepAliveTimeoutMs = defaults.keepAliveTimeoutMs,
100
+ handler,
101
+ } = opts
102
+ return new Promise((resolve, reject) => {
103
+ const server = handler ? http.createServer(handler) : http.createServer()
104
+ server.requestTimeout = requestTimeoutMs
105
+ server.headersTimeout = headersTimeoutMs
106
+ server.keepAliveTimeout = keepAliveTimeoutMs
107
+ server.on('clientError', (error, socket) => {
108
+ if (socket.writable) socket.end('HTTP/1.1 400 Bad Request\r\n\r\n')
109
+ })
110
+ server.on('error', reject)
111
+ server.listen(port, host, () => resolve(server))
112
+ })
113
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * 通用 MCP Streamable HTTP 处理器。
3
+ *
4
+ * 只实现工具面所需的最小协议:initialize / ping / tools/list / tools/call。
5
+ * 所有工具调用在进入业务实现前先经过 validateToolArguments。
6
+ */
7
+ import { readBody, send } from './http.mjs'
8
+ import { validateToolArguments } from '../tools/validate.mjs'
9
+ import { normalizeToolResult } from '../tools/result.mjs'
10
+
11
+ const DEFAULT_PROTOCOL = '2024-11-05'
12
+
13
+ function rpcError(id, code, message, data) {
14
+ const error = { code, message }
15
+ if (data !== undefined) error.data = data
16
+ return { jsonrpc: '2.0', id: id ?? null, error }
17
+ }
18
+
19
+ function reply(id, result) {
20
+ return { jsonrpc: '2.0', id, result }
21
+ }
22
+
23
+ export function createMcpHandler({
24
+ tools = [], callTool, serverInfo, instructions,
25
+ maxBodyBytes = 10 * 1024 * 1024, maxBatch = 100,
26
+ } = {}) {
27
+ if (!Array.isArray(tools)) throw new Error('createMcpHandler: tools 必须是数组')
28
+ if (typeof callTool !== 'function') throw new Error('createMcpHandler: callTool 必须是函数')
29
+
30
+ const toolMap = new Map(tools.map((tool) => [tool.name, tool]))
31
+
32
+ return async function handle(req, res) {
33
+ /* 长工具调用(如截图)期间客户端可能超时断连;socket 的 'error' 事件
34
+ 无人监听会打崩进程。挂空处理器,配合 send() 的断连防护。 */
35
+ res.on('error', () => {})
36
+ if (req.method !== 'POST') {
37
+ if (res.destroyed) return
38
+ res.writeHead(405, { allow: 'POST', 'content-type': 'text/plain; charset=utf-8' })
39
+ return res.end('MCP endpoint: POST only')
40
+ }
41
+
42
+ let msg
43
+ try {
44
+ msg = await readBody(req, maxBodyBytes)
45
+ } catch (error) {
46
+ if (error?.code === 'BODY_TOO_LARGE') {
47
+ return send(req, res, 413, rpcError(null, -32600, 'Request body too large'))
48
+ }
49
+ return send(req, res, 400, rpcError(null, -32700, 'Parse error'))
50
+ }
51
+
52
+ if (!msg || typeof msg !== 'object') {
53
+ return send(req, res, 400, rpcError(null, -32600, 'Invalid Request'))
54
+ }
55
+
56
+ const batch = Array.isArray(msg)
57
+ if (batch && msg.length === 0) {
58
+ return send(req, res, 400, rpcError(null, -32600, 'Invalid Request'))
59
+ }
60
+ if (batch && msg.length > maxBatch) {
61
+ return send(req, res, 400, rpcError(null, -32600, `Batch too large (max ${maxBatch})`))
62
+ }
63
+ const messages = batch ? msg : [msg]
64
+ const replies = []
65
+ for (const message of messages) {
66
+ const result = await handleOne(message, req)
67
+ if (result !== null) replies.push(result)
68
+ }
69
+ if (!replies.length) {
70
+ if (res.destroyed) return
71
+ res.writeHead(202, { 'content-length': 0 })
72
+ return res.end()
73
+ }
74
+ return send(req, res, 200, batch ? replies : replies[0])
75
+ }
76
+
77
+ async function handleOne(message, req) {
78
+ if (!message || typeof message !== 'object' || Array.isArray(message)) {
79
+ return rpcError(null, -32600, 'Invalid Request')
80
+ }
81
+
82
+ const { id, method, params } = message
83
+ const isNotification = id === undefined || id === null
84
+
85
+ if (typeof method !== 'string' || !method) {
86
+ return isNotification ? null : rpcError(id, -32600, 'Invalid Request')
87
+ }
88
+
89
+ if (method === 'initialize') {
90
+ const result = {
91
+ protocolVersion: String(params?.protocolVersion || DEFAULT_PROTOCOL),
92
+ capabilities: { tools: { listChanged: false } },
93
+ serverInfo: serverInfo || { name: 'dsh-plugin', version: '0.0.0' },
94
+ }
95
+ if (typeof instructions === 'string' && instructions) result.instructions = instructions
96
+ return isNotification ? null : reply(id, result)
97
+ }
98
+
99
+ if (method === 'notifications/initialized' || method === 'initialized') return null
100
+ if (method === 'notifications/cancelled' || method === 'notifications/cancel') return null
101
+ if (method === 'ping') return isNotification ? null : reply(id, {})
102
+
103
+ if (method === 'tools/list') {
104
+ return isNotification ? null : reply(id, { tools })
105
+ }
106
+
107
+ if (method === 'tools/call') {
108
+ const name = params?.name
109
+ const args = params?.arguments && typeof params.arguments === 'object' ? params.arguments : {}
110
+ const tool = toolMap.get(name)
111
+ if (!tool) {
112
+ if (isNotification) return null
113
+ return reply(id, {
114
+ content: [{ type: 'text', text: `未知工具: ${String(name)}` }],
115
+ isError: true,
116
+ })
117
+ }
118
+
119
+ const check = validateToolArguments(tool, args)
120
+ if (!check.ok) {
121
+ if (isNotification) return null
122
+ return reply(id, {
123
+ content: [{ type: 'text', text: '参数不合法:' + check.errors.join(';') }],
124
+ isError: true,
125
+ })
126
+ }
127
+
128
+ try {
129
+ const out = await callTool(name, args, { req })
130
+ /* 归一化保留纯字符串/空 text/对象,不再用 `|| 'ok'` 丢成无信息占位符(B 轴 P0-5)。 */
131
+ return reply(id, normalizeToolResult(out))
132
+ } catch (error) {
133
+ if (isNotification) return null
134
+ return reply(id, {
135
+ content: [{ type: 'text', text: '工具失败:' + String((error && error.message) || error) }],
136
+ isError: true,
137
+ })
138
+ }
139
+ }
140
+
141
+ return isNotification ? null : rpcError(id, -32601, `Method not found: ${method}`)
142
+ }
143
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * 独立 HTTP 服务通用启动器:loopback bind、标准 healthz、HTTP 超时与关闭。
3
+ * 业务路由/认证/静态文件白名单仍由服务自己实现。
4
+ */
5
+ import { listen, send } from './http.mjs'
6
+
7
+ const LOOPBACK = new Set(['127.0.0.1', 'localhost', '::1', '[::1]'])
8
+
9
+ /**
10
+ * @param {object} options
11
+ * @param {string} options.service 服务 id(broker spec.id)
12
+ * @param {number} [options.port=0] 0 表示让 OS 分配端口
13
+ * @param {string} [options.host='127.0.0.1'] 仅允许 loopback
14
+ * @param {(req: import('node:http').IncomingMessage, res: import('node:http').ServerResponse) => any} options.handler 业务路由
15
+ * @param {() => object|Promise<object>} [options.health] healthz 的额外字段
16
+ * @param {string} [options.healthPath='/healthz']
17
+ */
18
+ export async function startStandaloneService(options = {}) {
19
+ const {
20
+ service,
21
+ port = 0,
22
+ host = '127.0.0.1',
23
+ handler,
24
+ health = () => ({}),
25
+ healthPath = '/healthz',
26
+ requestTimeoutMs,
27
+ headersTimeoutMs,
28
+ keepAliveTimeoutMs,
29
+ } = options
30
+
31
+ if (typeof service !== 'string' || !service.trim()) throw new Error('startStandaloneService 需要 service id')
32
+ if (!LOOPBACK.has(host)) throw new Error(`服务只能绑定 loopback 地址,收到: ${host}`)
33
+ if (!Number.isInteger(Number(port)) || Number(port) < 0 || Number(port) > 65535) {
34
+ throw new Error(`port 必须是 0-65535 整数: ${port}`)
35
+ }
36
+ if (typeof handler !== 'function') throw new Error('startStandaloneService 需要 handler')
37
+ if (typeof health !== 'function') throw new Error('health 必须是函数')
38
+
39
+ let actualPort = Number(port)
40
+ const server = await listen(actualPort, {
41
+ host,
42
+ requestTimeoutMs,
43
+ headersTimeoutMs,
44
+ keepAliveTimeoutMs,
45
+ handler: async (req, res) => {
46
+ let pathname
47
+ try { pathname = new URL(req.url, `http://${host}`).pathname } catch { pathname = '' }
48
+ if (req.method === 'GET' && pathname === healthPath) {
49
+ try {
50
+ const extra = await health({ service, host, port: actualPort })
51
+ send(req, res, 200, {
52
+ ...(extra && typeof extra === 'object' ? extra : {}),
53
+ ok: true,
54
+ service,
55
+ pid: process.pid,
56
+ port: actualPort,
57
+ })
58
+ } catch (error) {
59
+ send(req, res, 503, {
60
+ ok: false,
61
+ service,
62
+ pid: process.pid,
63
+ port: actualPort,
64
+ error: String(error?.message || error),
65
+ })
66
+ }
67
+ return
68
+ }
69
+ return handler(req, res)
70
+ },
71
+ })
72
+
73
+ const address = server.address()
74
+ actualPort = address && typeof address === 'object' ? address.port : actualPort
75
+ let closePromise
76
+ const close = () => {
77
+ if (closePromise) return closePromise
78
+ closePromise = new Promise((resolve, reject) => {
79
+ if (!server.listening) return resolve()
80
+ server.close((error) => error ? reject(error) : resolve())
81
+ server.closeIdleConnections?.()
82
+ })
83
+ return closePromise
84
+ }
85
+
86
+ return {
87
+ server,
88
+ service,
89
+ host,
90
+ port: actualPort,
91
+ url: `http://${host.includes(':') && !host.startsWith('[') ? `[${host}]` : host}:${actualPort}`,
92
+ close,
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Standalone entrypoint helper for broker-managed services. Call this only from
98
+ * the executable entrypoint, never from a Cordis apply().
99
+ */
100
+ export function installServiceSignalHandlers(instance, {
101
+ processRef = process,
102
+ logger = console,
103
+ exit = (code) => processRef.exit(code),
104
+ timeoutMs = 3000,
105
+ } = {}) {
106
+ if (!instance || typeof instance.close !== 'function') throw new Error('需要 startStandaloneService 返回的 instance')
107
+ let closing = false
108
+ const handlers = new Map()
109
+ for (const signal of ['SIGINT', 'SIGTERM']) {
110
+ const handler = () => {
111
+ if (closing) return
112
+ closing = true
113
+ logger.info?.(`[${instance.service}] 收到 ${signal},正在关闭`)
114
+ const timer = setTimeout(() => exit(1), timeoutMs)
115
+ timer.unref?.()
116
+ Promise.resolve(instance.close()).then(() => {
117
+ clearTimeout(timer)
118
+ exit(0)
119
+ }, (error) => {
120
+ clearTimeout(timer)
121
+ logger.error?.(`[${instance.service}] 关闭失败: ${error.message}`)
122
+ exit(1)
123
+ })
124
+ }
125
+ handlers.set(signal, handler)
126
+ processRef.once(signal, handler)
127
+ }
128
+ return () => {
129
+ for (const [signal, handler] of handlers) processRef.removeListener(signal, handler)
130
+ }
131
+ }
@@ -0,0 +1,82 @@
1
+ /** 通用 skill provider:从目录扫描 kebab-case SKILL.md,按需加载正文。 */
2
+ import { readFileSync } from 'node:fs'
3
+ import { readFile } from 'node:fs/promises'
4
+ import { isAbsolute, join, sep } from 'node:path'
5
+
6
+ const NAME_RE = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
7
+ const RANK = 600
8
+
9
+ function parseSkill(raw, path) {
10
+ const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/u.exec(raw)
11
+ if (!frontmatter?.[1]) throw new Error(`skill ${path} 缺少 YAML frontmatter`)
12
+ const meta = {}
13
+ for (const line of frontmatter[1].split(/\r?\n/)) {
14
+ const match = /^([A-Za-z0-9_-]+):\s*(.*)$/.exec(line)
15
+ if (match) meta[match[1]] = match[2].replace(/^['"]|['"]$/g, '').trim()
16
+ }
17
+ if (!meta.name || !meta.description) throw new Error(`skill ${path} 缺少 name/description`)
18
+ if (!NAME_RE.test(meta.name)) throw new Error(`skill ${path} name 必须是 kebab-case`)
19
+ return {
20
+ name: meta.name,
21
+ description: meta.description,
22
+ whenToUse: meta.whenToUse || undefined,
23
+ content: raw.slice(frontmatter[0].length).trim(),
24
+ }
25
+ }
26
+
27
+ /**
28
+ * @param {{
29
+ * assetRoot: string,
30
+ * skillDirs: string[],
31
+ * providerName?: string,
32
+ * contractRoot?: string,
33
+ * contractNote?: (version: string) => string
34
+ * }} config
35
+ */
36
+ export function createSkillProvider(config) {
37
+ const assetRoot = config.assetRoot
38
+ if (!assetRoot || !isAbsolute(assetRoot)) throw new Error('createSkillProvider: assetRoot 必须是绝对路径')
39
+ let contract = null
40
+ if (config.contractRoot) {
41
+ try {
42
+ contract = JSON.parse(readFileSync(join(config.contractRoot, config.contractFile || 'contract.json'), 'utf8'))
43
+ } catch { /* 非技能包可以没有契约快照 */ }
44
+ }
45
+ const dirs = config.skillDirs || []
46
+ if (!dirs.length) throw new Error('createSkillProvider: skillDirs 不能为空')
47
+ const candidates = dirs.map((dir) => {
48
+ const directory = join(assetRoot, dir)
49
+ const locator = join(directory, 'SKILL.md')
50
+ const parsed = parseSkill(readFileSync(locator, 'utf8'), locator)
51
+ if (parsed.name !== dir) throw new Error(`skill ${locator} name 必须是 ${dir}`)
52
+ return {
53
+ name: parsed.name,
54
+ description: parsed.description,
55
+ whenToUse: parsed.whenToUse,
56
+ invocation: { modelInvocable: true, userInvocable: true },
57
+ provider: config.providerName || 'dsh-plugin',
58
+ source: 'bundled',
59
+ rank: RANK,
60
+ resourceBase: { kind: 'directory', path: directory.split(sep).join('/') },
61
+ locator,
62
+ }
63
+ })
64
+ const byName = new Map(candidates.map((candidate) => [candidate.name, candidate]))
65
+ const noteFor = (name) => (contract && config.contractNote
66
+ ? config.contractNote(contract.contractVersion, name)
67
+ : '')
68
+
69
+ return {
70
+ name: config.providerName || 'dsh-plugin',
71
+ list: () => Promise.resolve(candidates),
72
+ async get(candidate, options = {}) {
73
+ const hit = byName.get(candidate.name)
74
+ if (!hit) throw new Error(`未知 skill ${candidate.name}`)
75
+ const raw = await readFile(hit.locator, { encoding: 'utf8', signal: options.signal })
76
+ const parsed = parseSkill(raw, hit.locator)
77
+ const { rank: _rank, locator: _locator, ...summary } = hit
78
+ const note = noteFor(candidate.name)
79
+ return { ...summary, content: parsed.content + (note ? `\n\n---\n\n${note}` : '') }
80
+ },
81
+ }
82
+ }
@@ -0,0 +1,109 @@
1
+ /**
2
+ * 纯内容仓库:只负责按 sha256 存取不可变字节。
3
+ *
4
+ * 这里刻意不保存 manifest、不关心哪些文件属于同一个作品、不解释文件名。
5
+ * 文件关系、归属、版本和生命周期全部由 workspace/manager.mjs 的中间层负责。
6
+ */
7
+ import crypto from 'node:crypto'
8
+ import fs from 'node:fs'
9
+ import path from 'node:path'
10
+
11
+ export class BlobStore {
12
+ constructor({ root }) {
13
+ if (!root) throw new Error('BlobStore 需要 root')
14
+ this.root = path.resolve(root)
15
+ this.objectsRoot = path.join(this.root, 'objects')
16
+ }
17
+
18
+ init() {
19
+ fs.mkdirSync(this.objectsRoot, { recursive: true })
20
+ return this
21
+ }
22
+
23
+ blobPath(hash) {
24
+ if (!/^[a-f0-9]{64}$/.test(String(hash || ''))) throw new Error(`非法对象 hash: ${hash}`)
25
+ return path.join(this.objectsRoot, hash.slice(0, 2), hash)
26
+ }
27
+
28
+ put(data) {
29
+ const buffer = Buffer.isBuffer(data) ? data : Buffer.from(data)
30
+ const hash = crypto.createHash('sha256').update(buffer).digest('hex')
31
+ const file = this.blobPath(hash)
32
+ if (!fs.existsSync(file)) {
33
+ fs.mkdirSync(path.dirname(file), { recursive: true })
34
+ const tmp = `${file}.tmp-${process.pid}-${crypto.randomBytes(4).toString('hex')}`
35
+ fs.writeFileSync(tmp, buffer)
36
+ try {
37
+ fs.renameSync(tmp, file)
38
+ } catch (error) {
39
+ /* 并发写同一 hash 时目标可能已出现;目标有效就复用,绝不删除目标。 */
40
+ if (fs.existsSync(file)) {
41
+ try { fs.rmSync(tmp, { force: true }) } catch { /* 忽略 */ }
42
+ return { hash, size: buffer.length }
43
+ }
44
+ try { fs.rmSync(tmp, { force: true }) } catch { /* 忽略 */ }
45
+ throw error
46
+ }
47
+ }
48
+ return { hash, size: buffer.length }
49
+ }
50
+
51
+ get(hash) {
52
+ const data = fs.readFileSync(this.blobPath(hash))
53
+ /* 内容寻址仓库的读取必须复核 sha256:截断/篡改对象不能静默使用。 */
54
+ const actual = crypto.createHash('sha256').update(data).digest('hex')
55
+ if (actual !== String(hash)) {
56
+ throw new Error(`BlobStore 对象校验失败: ${hash} (actual ${actual})`)
57
+ }
58
+ return data
59
+ }
60
+
61
+ has(hash) {
62
+ try { return fs.existsSync(this.blobPath(hash)) } catch { return false }
63
+ }
64
+
65
+ delete(hash) {
66
+ const file = this.blobPath(hash)
67
+ if (!fs.existsSync(file)) return false
68
+ fs.rmSync(file, { force: true })
69
+ return true
70
+ }
71
+
72
+ list() {
73
+ const out = []
74
+ let prefixes = []
75
+ try {
76
+ prefixes = fs.readdirSync(this.objectsRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory())
77
+ } catch {
78
+ return out
79
+ }
80
+ for (const prefix of prefixes) {
81
+ const dir = path.join(this.objectsRoot, prefix.name)
82
+ for (const name of fs.readdirSync(dir)) {
83
+ if (!/^[a-f0-9]{64}$/.test(name)) continue
84
+ const file = path.join(dir, name)
85
+ out.push({ hash: name, size: fs.statSync(file).size })
86
+ }
87
+ }
88
+ return out
89
+ }
90
+
91
+ /** 仓库只按中间层给的引用集合做物理清理,不自己判断文件关系。 */
92
+ gc(referencedHashes, { minAgeMs = 0 } = {}) {
93
+ const referenced = referencedHashes instanceof Set ? referencedHashes : new Set(referencedHashes || [])
94
+ const cutoff = Date.now() - Math.max(0, Number(minAgeMs) || 0)
95
+ let removed = 0
96
+ let skipped = 0
97
+ for (const { hash, size } of this.list()) {
98
+ if (referenced.has(hash)) continue
99
+ if (minAgeMs > 0) {
100
+ try {
101
+ if (fs.statSync(this.blobPath(hash)).mtimeMs > cutoff) { skipped++; continue }
102
+ } catch { continue }
103
+ }
104
+ this.delete(hash)
105
+ removed++
106
+ }
107
+ return { removed, skipped, referenced: referenced.size }
108
+ }
109
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * 兼容导出:旧的 content-store 名称映射到新的职责分层。
3
+ *
4
+ * 新代码请直接使用:
5
+ * store/blob-store.mjs 纯对象仓库(不关心文件关系)
6
+ * workspace/manager.mjs 文件关系 / 归属 / 版本 / 生命周期中间层
7
+ */
8
+ export { BlobStore } from './blob-store.mjs'
9
+ export {
10
+ WorkspaceManager as ContentStore,
11
+ WorkspaceClient as ContentStoreClient,
12
+ WorkspaceBackend as ContentStoreBackend,
13
+ WorkspaceConflictError as StoreConflictError,
14
+ WorkspaceAccessError as StoreAccessError,
15
+ NamespaceRegistry,
16
+ } from '../workspace/manager.mjs'
17
+ export { withFileLock, writeJsonAtomic, readJson, sleepSync } from '../util/fs-lock.mjs'