@capyclaw/session-keeper 0.0.0-stage → 0.1.1
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 +43 -2
- package/client/client.js +319 -0
- package/cordis.patch.yml +9 -0
- package/index.js +12 -0
- 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 +352 -0
- package/node_modules/@capyclaw/foundation/abi/schema.mjs +98 -0
- package/node_modules/@capyclaw/foundation/abi/spec.mjs +258 -0
- package/node_modules/@capyclaw/foundation/abi/validate.mjs +24 -0
- package/node_modules/@capyclaw/foundation/abi/version.mjs +140 -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 +69 -0
- package/node_modules/@capyclaw/foundation/lib/adapters/runtime-driver.mjs +120 -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 +187 -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 +115 -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 +198 -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 +60 -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 +150 -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 +57 -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 +44 -4
|
@@ -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'
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
/** 通用耐久状态存储:原子 JSON 快照 + append-only journal + 命名 checkpoint。 */
|
|
2
|
+
import fs from 'node:fs'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { tuning } from '../tuning.mjs'
|
|
5
|
+
|
|
6
|
+
export class JournalStore {
|
|
7
|
+
constructor({ file, initialDoc = {} }) {
|
|
8
|
+
this.file = file
|
|
9
|
+
this.dir = path.dirname(file)
|
|
10
|
+
this.journalFile = path.join(this.dir, 'journal.jsonl')
|
|
11
|
+
this.checkpointDir = path.join(this.dir, 'checkpoints')
|
|
12
|
+
this.doc = this._load(initialDoc)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
_load(initialDoc) {
|
|
16
|
+
try {
|
|
17
|
+
const parsed = JSON.parse(fs.readFileSync(this.file, 'utf8'))
|
|
18
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
19
|
+
return { ...initialDoc, ...parsed }
|
|
20
|
+
}
|
|
21
|
+
} catch { /* 缺文件/坏 JSON = 初始空态 */ }
|
|
22
|
+
return { ...initialDoc }
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
save() {
|
|
26
|
+
fs.mkdirSync(this.dir, { recursive: true })
|
|
27
|
+
const tmp = this.file + '.tmp'
|
|
28
|
+
fs.writeFileSync(tmp, JSON.stringify(this.doc))
|
|
29
|
+
fs.renameSync(tmp, this.file)
|
|
30
|
+
return this.doc
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
get() { return this.doc }
|
|
34
|
+
|
|
35
|
+
journal(event) {
|
|
36
|
+
try {
|
|
37
|
+
fs.mkdirSync(this.dir, { recursive: true })
|
|
38
|
+
fs.appendFileSync(this.journalFile, JSON.stringify({ ...event, ts: Date.now() / 1000 }) + '\n')
|
|
39
|
+
if (fs.statSync(this.journalFile).size > tuning().journalMaxBytes) {
|
|
40
|
+
const rotated = this.journalFile + '.1'
|
|
41
|
+
try { fs.rmSync(rotated, { force: true }) } catch { /* 忽略 */ }
|
|
42
|
+
fs.renameSync(this.journalFile, rotated)
|
|
43
|
+
}
|
|
44
|
+
} catch { /* journal 失败不阻塞主状态 */ }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
journalTail(limit = tuning().journalTailLimit) {
|
|
48
|
+
try {
|
|
49
|
+
const lines = fs.readFileSync(this.journalFile, 'utf8').trim().split(/\r?\n/).filter(Boolean)
|
|
50
|
+
return lines.slice(-limit).map((line) => {
|
|
51
|
+
try { return JSON.parse(line) } catch { return { type: 'invalid', raw: line.slice(0, 120) } }
|
|
52
|
+
})
|
|
53
|
+
} catch { return [] }
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
checkpoint(name, snapshot, meta = {}) {
|
|
57
|
+
const safe = String(name || '')
|
|
58
|
+
if (!/^[a-zA-Z0-9._-]{1,64}$/.test(safe)) throw new Error('checkpoint 名称必须是 1-64 位字母/数字/._-')
|
|
59
|
+
fs.mkdirSync(this.checkpointDir, { recursive: true })
|
|
60
|
+
const file = path.join(this.checkpointDir, safe + '.json')
|
|
61
|
+
const payload = { name: safe, snapshot, meta: meta && typeof meta === 'object' ? meta : {}, createdAt: new Date().toISOString() }
|
|
62
|
+
const tmp = file + '.tmp'
|
|
63
|
+
fs.writeFileSync(tmp, JSON.stringify(payload))
|
|
64
|
+
fs.renameSync(tmp, file)
|
|
65
|
+
this.journal({ type: 'checkpoint', name: safe })
|
|
66
|
+
return { name: safe, createdAt: payload.createdAt, meta: payload.meta }
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
listCheckpoints() {
|
|
70
|
+
try {
|
|
71
|
+
return fs.readdirSync(this.checkpointDir)
|
|
72
|
+
.filter((name) => name.endsWith('.json'))
|
|
73
|
+
.map((name) => {
|
|
74
|
+
try {
|
|
75
|
+
const payload = JSON.parse(fs.readFileSync(path.join(this.checkpointDir, name), 'utf8'))
|
|
76
|
+
return { name: payload.name, createdAt: payload.createdAt, meta: payload.meta || {} }
|
|
77
|
+
} catch { return null }
|
|
78
|
+
})
|
|
79
|
+
.filter(Boolean)
|
|
80
|
+
.sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))
|
|
81
|
+
} catch { return [] }
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
readCheckpoint(name) {
|
|
85
|
+
const safe = String(name || '')
|
|
86
|
+
if (!/^[a-zA-Z0-9._-]{1,64}$/.test(safe)) throw new Error('checkpoint 名称必须是 1-64 位字母/数字/._-')
|
|
87
|
+
return JSON.parse(fs.readFileSync(path.join(this.checkpointDir, safe + '.json'), 'utf8'))
|
|
88
|
+
}
|
|
89
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 工具结果归一化 —— MCP 面与 DSH 原生面共用,保证「两面给 LLM 的内容一致」。
|
|
3
|
+
*
|
|
4
|
+
* 背景(B 轴 P0):工具 handler 的返回值形态不一({content}、{text}、纯字符串、
|
|
5
|
+
* 普通对象、undefined)。旧代码用 `out?.text || 'ok'` 兜底,把纯字符串/普通对象/
|
|
6
|
+
* 空 text 一律丢成无信息占位符 'ok',LLM 误判工具「啥也没做/成功」。这里统一归一为
|
|
7
|
+
* MCP content 块,**保留空串、不伪造 'ok'**:
|
|
8
|
+
* - {content:[...]} → 原样(透传 isError)
|
|
9
|
+
* - {text:'...'} → 单个 text 块(空串也保留;透传 isError)
|
|
10
|
+
* - '字符串' → 单个 text 块
|
|
11
|
+
* - undefined / null → 空 text 块(诚实表示「无输出」,而非 'ok')
|
|
12
|
+
* - 其它对象/值 → JSON 序列化为 text 块
|
|
13
|
+
*
|
|
14
|
+
* 返回恒为 {content:[...]}(object),因此 DSH 原生面 output.schema 用 object 恒满足。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** 单个 text 块的默认上限:防 base64/大输出撑爆 LLM 上下文。image 块不受影响。 */
|
|
18
|
+
export const DEFAULT_MAX_TEXT_BYTES = 256 * 1024
|
|
19
|
+
|
|
20
|
+
function capText(text, max) {
|
|
21
|
+
if (!max || max <= 0 || typeof text !== 'string' || text.length <= max) return text
|
|
22
|
+
return `${text.slice(0, max)}\n…[truncated: original ${text.length} chars, limit ${max}]`
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function capContent(content, max) {
|
|
26
|
+
return content.map((block) => (
|
|
27
|
+
block && block.type === 'text' && typeof block.text === 'string'
|
|
28
|
+
? { ...block, text: capText(block.text, max) }
|
|
29
|
+
: block
|
|
30
|
+
))
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** 把任意工具返回值归一为 MCP content 形态(并对超限 text 块截断+提示)。 */
|
|
34
|
+
export function normalizeToolResult(out, { maxTextBytes = DEFAULT_MAX_TEXT_BYTES } = {}) {
|
|
35
|
+
const isError = out && typeof out.isError === 'boolean' ? { isError: out.isError } : {}
|
|
36
|
+
let content
|
|
37
|
+
if (out && Array.isArray(out.content)) {
|
|
38
|
+
content = out.content
|
|
39
|
+
} else if (out && typeof out.text === 'string') {
|
|
40
|
+
content = [{ type: 'text', text: out.text }]
|
|
41
|
+
} else if (typeof out === 'string') {
|
|
42
|
+
content = [{ type: 'text', text: out }]
|
|
43
|
+
} else if (out === undefined || out === null) {
|
|
44
|
+
content = [{ type: 'text', text: '' }]
|
|
45
|
+
} else {
|
|
46
|
+
let text
|
|
47
|
+
try { text = JSON.stringify(out) } catch { text = String(out) }
|
|
48
|
+
content = [{ type: 'text', text: text ?? String(out) }]
|
|
49
|
+
}
|
|
50
|
+
return { content: capContent(content, maxTextBytes), ...isError }
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** 从归一化结果提取纯文本(用于把失败内容拼成 Error.message)。 */
|
|
54
|
+
export function resultText(normalized) {
|
|
55
|
+
if (!normalized || !Array.isArray(normalized.content)) return ''
|
|
56
|
+
return normalized.content.map((c) => (c && typeof c.text === 'string' ? c.text : '')).join('\n')
|
|
57
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 轻量 JSON Schema 参数校验(覆盖本工具面用到的子集)。
|
|
3
|
+
* MCP server 不会替我们执行 inputSchema,必须在调用实现前自己挡住坏参数。
|
|
4
|
+
*
|
|
5
|
+
* 原则「声明=行为」:schema 里声明的约束会真的被执行(而不是原样透传给 LLM 却不校验)。
|
|
6
|
+
* 支持 anyOf / type / enum / default 注入 / minimum / maximum / exclusiveMinimum /
|
|
7
|
+
* exclusiveMaximum / minLength / maxLength / pattern / minItems / maxItems / items /
|
|
8
|
+
* properties / required / additionalProperties。object 校验不依赖显式 type:'object'
|
|
9
|
+
* (有 properties/required/additionalProperties:false 即生效)。
|
|
10
|
+
*
|
|
11
|
+
* 编译缓存:schema 对象通常随工具定义长期存在,按 schema 对象(WeakMap)编译成
|
|
12
|
+
* 闭包树,重复调用不再逐层遍历 schema/创建临时数组。类型不符仍立即短路。
|
|
13
|
+
* 基准:50 元素数组参数校验从 ~0.029ms 降到 ~0.01ms(evolution/hotpath-bench.mjs H11)。
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const TYPE_CHECKS = {
|
|
17
|
+
string: (v) => typeof v === 'string',
|
|
18
|
+
number: (v) => typeof v === 'number' && Number.isFinite(v),
|
|
19
|
+
integer: (v) => typeof v === 'number' && Number.isInteger(v),
|
|
20
|
+
boolean: (v) => typeof v === 'boolean',
|
|
21
|
+
array: (v) => Array.isArray(v),
|
|
22
|
+
object: (v) => v !== null && typeof v === 'object' && !Array.isArray(v),
|
|
23
|
+
null: (v) => v === null,
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** schema 对象 → 编译后的校验闭包。 */
|
|
27
|
+
const compiledCache = new WeakMap()
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* 把 schema 编译成 `(value, path, errors) => void` 闭包树。
|
|
31
|
+
* 纯结构性编译,不依赖运行时数据;同一 schema 对象只编译一次。
|
|
32
|
+
*/
|
|
33
|
+
function compileSchema(schema) {
|
|
34
|
+
if (!schema || typeof schema !== 'object') return () => {}
|
|
35
|
+
|
|
36
|
+
/* anyOf:与解释版一致——任一支路无错误即通过,且通过后不再执行其余规则。 */
|
|
37
|
+
if (schema.anyOf) {
|
|
38
|
+
const branches = schema.anyOf.map(compileSchema)
|
|
39
|
+
return (value, path, errors) => {
|
|
40
|
+
const matched = branches.some((branch) => {
|
|
41
|
+
const local = []
|
|
42
|
+
branch(value, path, local)
|
|
43
|
+
return local.length === 0
|
|
44
|
+
})
|
|
45
|
+
if (!matched) errors.push(`${path} 不符合 anyOf`)
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const typeCheck = schema.type ? TYPE_CHECKS[schema.type] : null
|
|
50
|
+
const enumValues = schema.enum ? schema.enum : null
|
|
51
|
+
const maxLength = schema.maxLength != null ? schema.maxLength : null
|
|
52
|
+
const minLength = schema.minLength != null ? schema.minLength : null
|
|
53
|
+
let pattern = null
|
|
54
|
+
if (schema.pattern != null) { try { pattern = new RegExp(schema.pattern) } catch { pattern = null } }
|
|
55
|
+
const minimum = schema.minimum != null ? schema.minimum : null
|
|
56
|
+
const maximum = schema.maximum != null ? schema.maximum : null
|
|
57
|
+
const exclusiveMinimum = schema.exclusiveMinimum != null ? schema.exclusiveMinimum : null
|
|
58
|
+
const exclusiveMaximum = schema.exclusiveMaximum != null ? schema.exclusiveMaximum : null
|
|
59
|
+
const maxItems = schema.type === 'array' && schema.maxItems != null ? schema.maxItems : null
|
|
60
|
+
const minItems = schema.minItems != null ? schema.minItems : null
|
|
61
|
+
const validateItem = schema.type === 'array' && schema.items ? compileSchema(schema.items) : null
|
|
62
|
+
/* P0-3:有 properties / required / additionalProperties:false 即按 object 校验,
|
|
63
|
+
* 不再依赖显式 type:'object'——漏写 type 时 required/多余键/子属性不再静默跳过。 */
|
|
64
|
+
const isObjectSchema = schema.type === 'object' || !!schema.properties || Array.isArray(schema.required) || schema.additionalProperties === false
|
|
65
|
+
const properties = isObjectSchema ? (schema.properties || {}) : null
|
|
66
|
+
const propValidators = properties
|
|
67
|
+
? Object.entries(properties).map(([key, child]) => [key, compileSchema(child)])
|
|
68
|
+
: null
|
|
69
|
+
const required = properties && Array.isArray(schema.required) ? schema.required : null
|
|
70
|
+
const noAdditional = properties && schema.additionalProperties === false
|
|
71
|
+
/* P0-4:default 注入(先于 required,使带默认值的键满足必填)。原地写入 args,
|
|
72
|
+
* 调用方随后把 args 交给工具实现,工具即拿到补全默认值后的参数。 */
|
|
73
|
+
const defaults = properties
|
|
74
|
+
? Object.entries(properties)
|
|
75
|
+
.filter(([, child]) => child && typeof child === 'object' && child.default !== undefined)
|
|
76
|
+
.map(([key, child]) => [key, child.default])
|
|
77
|
+
: null
|
|
78
|
+
|
|
79
|
+
return (value, path, errors) => {
|
|
80
|
+
/* 类型不符:解释版立即返回,不再做深层校验(保持该短路语义)。 */
|
|
81
|
+
if (typeCheck && !typeCheck(value)) {
|
|
82
|
+
errors.push(`${path} 应为 ${schema.type}`)
|
|
83
|
+
return
|
|
84
|
+
}
|
|
85
|
+
if (enumValues && !enumValues.includes(value)) {
|
|
86
|
+
errors.push(`${path} 必须是 ${enumValues.join(' / ')}`)
|
|
87
|
+
}
|
|
88
|
+
if (typeof value === 'string') {
|
|
89
|
+
if (maxLength != null && value.length > maxLength) errors.push(`${path} 超过最大长度 ${maxLength}`)
|
|
90
|
+
if (minLength != null && value.length < minLength) errors.push(`${path} 短于最小长度 ${minLength}`)
|
|
91
|
+
if (pattern && !pattern.test(value)) errors.push(`${path} 不匹配格式 ${schema.pattern}`)
|
|
92
|
+
}
|
|
93
|
+
if (typeof value === 'number' && Number.isFinite(value)) {
|
|
94
|
+
if (minimum != null && value < minimum) errors.push(`${path} 不得小于 ${minimum}`)
|
|
95
|
+
if (maximum != null && value > maximum) errors.push(`${path} 不得大于 ${maximum}`)
|
|
96
|
+
if (exclusiveMinimum != null && value <= exclusiveMinimum) errors.push(`${path} 必须大于 ${exclusiveMinimum}`)
|
|
97
|
+
if (exclusiveMaximum != null && value >= exclusiveMaximum) errors.push(`${path} 必须小于 ${exclusiveMaximum}`)
|
|
98
|
+
}
|
|
99
|
+
if (Array.isArray(value)) {
|
|
100
|
+
if (maxItems != null && value.length > maxItems) errors.push(`${path} 最多 ${maxItems} 项`)
|
|
101
|
+
if (minItems != null && value.length < minItems) errors.push(`${path} 至少 ${minItems} 项`)
|
|
102
|
+
if (validateItem) value.forEach((item, i) => validateItem(item, `${path}[${i}]`, errors))
|
|
103
|
+
}
|
|
104
|
+
if (properties && value !== null && typeof value === 'object' && !Array.isArray(value)) {
|
|
105
|
+
if (defaults && defaults.length) {
|
|
106
|
+
for (const [key, def] of defaults) {
|
|
107
|
+
if (value[key] === undefined) value[key] = def
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (required) {
|
|
111
|
+
for (const key of required) {
|
|
112
|
+
if (value[key] === undefined || value[key] === null) errors.push(`${path}.${key} 必填`)
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
if (noAdditional) {
|
|
116
|
+
for (const key of Object.keys(value)) {
|
|
117
|
+
if (!properties[key]) errors.push(`${path}.${key} 不是允许的参数`)
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
for (const [key, validateChild] of propValidators) {
|
|
121
|
+
if (value[key] === undefined) continue
|
|
122
|
+
validateChild(value[key], `${path}.${key}`, errors)
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** 取(或编译)schema 的校验闭包。 */
|
|
129
|
+
function validatorOf(schema) {
|
|
130
|
+
if (!schema || typeof schema !== 'object') return compileSchema(schema)
|
|
131
|
+
const cached = compiledCache.get(schema)
|
|
132
|
+
if (cached) return cached
|
|
133
|
+
const compiled = compileSchema(schema)
|
|
134
|
+
compiledCache.set(schema, compiled)
|
|
135
|
+
return compiled
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* @returns {{ok: boolean, errors: string[]}}
|
|
140
|
+
*/
|
|
141
|
+
export function validateToolArguments(tool, args) {
|
|
142
|
+
const errors = []
|
|
143
|
+
if (!tool || !tool.inputSchema) {
|
|
144
|
+
if (args != null && (typeof args !== 'object' || Array.isArray(args))) errors.push('arguments 必须是 object')
|
|
145
|
+
return { ok: errors.length === 0, errors }
|
|
146
|
+
}
|
|
147
|
+
if (args == null) args = {}
|
|
148
|
+
validatorOf(tool.inputSchema)(args, 'arguments', errors)
|
|
149
|
+
return { ok: errors.length === 0, errors }
|
|
150
|
+
}
|