@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.
- package/README.md +7 -7
- 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 +18 -2
- package/server.mjs +237 -201
|
@@ -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,41 @@
|
|
|
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
|
+
/** 把任意工具返回值归一为 MCP content 形态。 */
|
|
18
|
+
export function normalizeToolResult(out) {
|
|
19
|
+
const isError = out && typeof out.isError === 'boolean' ? { isError: out.isError } : {}
|
|
20
|
+
if (out && Array.isArray(out.content)) {
|
|
21
|
+
return { content: out.content, ...isError }
|
|
22
|
+
}
|
|
23
|
+
if (out && typeof out.text === 'string') {
|
|
24
|
+
return { content: [{ type: 'text', text: out.text }], ...isError }
|
|
25
|
+
}
|
|
26
|
+
if (typeof out === 'string') {
|
|
27
|
+
return { content: [{ type: 'text', text: out }] }
|
|
28
|
+
}
|
|
29
|
+
if (out === undefined || out === null) {
|
|
30
|
+
return { content: [{ type: 'text', text: '' }] }
|
|
31
|
+
}
|
|
32
|
+
let text
|
|
33
|
+
try { text = JSON.stringify(out) } catch { text = String(out) }
|
|
34
|
+
return { content: [{ type: 'text', text: text ?? String(out) }] }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** 从归一化结果提取纯文本(用于把失败内容拼成 Error.message)。 */
|
|
38
|
+
export function resultText(normalized) {
|
|
39
|
+
if (!normalized || !Array.isArray(normalized.content)) return ''
|
|
40
|
+
return normalized.content.map((c) => (c && typeof c.text === 'string' ? c.text : '')).join('\n')
|
|
41
|
+
}
|
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @capyclaw/plugin-kit 运行时调优层。
|
|
3
|
+
*
|
|
4
|
+
* 默认值与进化搜索(evolution/ NSGA-II)的 founder 基线保持一致;
|
|
5
|
+
* 生产环境可用 DSH_TUNING_JSON 覆盖(按包名分组),测试/评估用 setTuning 注入。
|
|
6
|
+
*
|
|
7
|
+
* DSH_TUNING_JSON 形如:
|
|
8
|
+
* {"@capyclaw/plugin-kit": {"fileLockPollMs": 25, "journalMaxBytes": 2097152}}
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
const DEFAULTS = {
|
|
12
|
+
/* fs-lock:元数据文件锁
|
|
13
|
+
* pollMs=10 由 NSGA-II 进化搜索固化(evolution/,2026-11-01):
|
|
14
|
+
* 24 路竞争延迟 2202→1400ms;10ms 为延迟与轮询 IO 的膝点。 */
|
|
15
|
+
fileLockSyncTimeoutMs: 10000,
|
|
16
|
+
fileLockSyncStaleMs: 30000,
|
|
17
|
+
fileLockAsyncTimeoutMs: 30000,
|
|
18
|
+
fileLockPollMs: 10,
|
|
19
|
+
fileLockFreshGraceMs: 2000,
|
|
20
|
+
|
|
21
|
+
/* 编辑器租约:wait() 轮询节奏 */
|
|
22
|
+
leaseWaitPollMs: 200,
|
|
23
|
+
leaseWaitTimeoutMs: 4000,
|
|
24
|
+
|
|
25
|
+
/* JournalStore:journal 轮转阈值与尾读默认行数
|
|
26
|
+
* 512KB 由进化搜索固化:尾读 p95 4.3→1.9ms、磁盘 -70%、追加吞吐 +8%。 */
|
|
27
|
+
journalMaxBytes: 512 * 1024,
|
|
28
|
+
journalTailLimit: 8,
|
|
29
|
+
|
|
30
|
+
/* WorkspaceManager catalog 写节流(降低全局 catalog 锁竞争) */
|
|
31
|
+
catalogThrottleMs: 5000,
|
|
32
|
+
|
|
33
|
+
/* WorkspaceClient token 校验缓存 */
|
|
34
|
+
tokenVerifyCacheMs: 30000,
|
|
35
|
+
|
|
36
|
+
/* HTTP 服务三级超时(keepAliveTimeoutMs 必须小于 headersTimeoutMs) */
|
|
37
|
+
requestTimeoutMs: 30000,
|
|
38
|
+
headersTimeoutMs: 10000,
|
|
39
|
+
keepAliveTimeoutMs: 5000,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
let overrides = {}
|
|
43
|
+
let envLoaded = false
|
|
44
|
+
|
|
45
|
+
function loadEnv() {
|
|
46
|
+
if (envLoaded) return
|
|
47
|
+
envLoaded = true
|
|
48
|
+
try {
|
|
49
|
+
const raw = process.env.DSH_TUNING_JSON
|
|
50
|
+
if (!raw) return
|
|
51
|
+
const parsed = JSON.parse(raw)
|
|
52
|
+
if (!parsed || typeof parsed !== 'object') return
|
|
53
|
+
const own = parsed['@capyclaw/plugin-kit'] && typeof parsed['@capyclaw/plugin-kit'] === 'object'
|
|
54
|
+
? parsed['@capyclaw/plugin-kit']
|
|
55
|
+
: parsed
|
|
56
|
+
for (const key of Object.keys(DEFAULTS)) {
|
|
57
|
+
if (own[key] !== undefined) overrides[key] = own[key]
|
|
58
|
+
}
|
|
59
|
+
} catch { /* 非法 JSON 静默忽略:调优失败不能阻塞启动 */ }
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** 当前生效参数(默认值 + env + setTuning 覆盖)。 */
|
|
63
|
+
export function tuning() {
|
|
64
|
+
loadEnv()
|
|
65
|
+
return { ...DEFAULTS, ...overrides }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** 测试/评估注入。只接受已知键,避免拼写错误静默生效。 */
|
|
69
|
+
export function setTuning(patch = {}) {
|
|
70
|
+
loadEnv()
|
|
71
|
+
for (const [key, value] of Object.entries(patch)) {
|
|
72
|
+
if (key in DEFAULTS) overrides[key] = value
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 恢复到默认值 + env 覆盖。 */
|
|
77
|
+
export function resetTuning() {
|
|
78
|
+
overrides = {}
|
|
79
|
+
envLoaded = false
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export const TUNING_DEFAULTS = { ...DEFAULTS }
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/** 同步文件锁:给 registry / workspace manifest 这类元数据用。 */
|
|
2
|
+
import crypto from 'node:crypto'
|
|
3
|
+
import fs from 'node:fs'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { tuning } from '../tuning.mjs'
|
|
6
|
+
|
|
7
|
+
const sleepCell = new Int32Array(new SharedArrayBuffer(4))
|
|
8
|
+
|
|
9
|
+
export function sleepSync(ms) {
|
|
10
|
+
Atomics.wait(sleepCell, 0, 0, ms)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function pidDead(pid) {
|
|
14
|
+
if (!Number.isSafeInteger(pid) || pid <= 0) return false
|
|
15
|
+
try { process.kill(pid, 0); return false } catch (error) { return error.code === 'ESRCH' }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function newToken() {
|
|
19
|
+
return crypto.randomBytes(12).toString('hex')
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function tryCreate(lockFile, token) {
|
|
23
|
+
fs.mkdirSync(path.dirname(lockFile), { recursive: true })
|
|
24
|
+
let fd
|
|
25
|
+
try {
|
|
26
|
+
fd = fs.openSync(lockFile, 'wx')
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (error.code === 'EEXIST') return false
|
|
29
|
+
throw error
|
|
30
|
+
}
|
|
31
|
+
try {
|
|
32
|
+
fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, token, ts: Date.now() }))
|
|
33
|
+
try { fs.fsyncSync(fd) } catch { /* 部分文件系统不支持 */ }
|
|
34
|
+
} finally {
|
|
35
|
+
fs.closeSync(fd)
|
|
36
|
+
}
|
|
37
|
+
return true
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Only a complete record whose owner is provably dead can be reclaimed. A
|
|
41
|
+
// record-specific claim serializes competing reclaimers, including across
|
|
42
|
+
// successive lock owners. An abandoned claim is intentionally not reclaimed.
|
|
43
|
+
function reclaimDead(lockFile, staleMs) {
|
|
44
|
+
let raw, info, stat
|
|
45
|
+
try {
|
|
46
|
+
raw = fs.readFileSync(lockFile, 'utf8')
|
|
47
|
+
info = JSON.parse(raw)
|
|
48
|
+
stat = fs.statSync(lockFile)
|
|
49
|
+
} catch { return false }
|
|
50
|
+
if (!/^[a-f0-9]{24}$/.test(info?.token || '') || !pidDead(info.pid) || Date.now() - stat.mtimeMs <= staleMs) return false
|
|
51
|
+
const claim = `${lockFile}.reclaim-${crypto.createHash('sha256').update(raw).digest('hex')}`
|
|
52
|
+
let fd
|
|
53
|
+
try { fd = fs.openSync(claim, 'wx') } catch { return false }
|
|
54
|
+
try {
|
|
55
|
+
try {
|
|
56
|
+
if (fs.readFileSync(lockFile, 'utf8') !== raw || !pidDead(info.pid)) return false
|
|
57
|
+
fs.rmSync(lockFile)
|
|
58
|
+
return true
|
|
59
|
+
} catch { return false }
|
|
60
|
+
} finally {
|
|
61
|
+
fs.closeSync(fd)
|
|
62
|
+
try { fs.rmSync(claim, { force: true }) } catch { /* 保留未知状态 */ }
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function releaseOwned(lockFile, token) {
|
|
67
|
+
try {
|
|
68
|
+
const info = JSON.parse(fs.readFileSync(lockFile, 'utf8'))
|
|
69
|
+
if (info.token === token) fs.rmSync(lockFile, { force: true })
|
|
70
|
+
} catch { /* 已被删除或被接管 */ }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function acquireSync(lockFile, { timeoutMs, staleMs }) {
|
|
74
|
+
const token = newToken()
|
|
75
|
+
const deadline = Date.now() + timeoutMs
|
|
76
|
+
const { fileLockPollMs: pollMs } = tuning()
|
|
77
|
+
while (true) {
|
|
78
|
+
if (tryCreate(lockFile, token)) return token
|
|
79
|
+
if (reclaimDead(lockFile, staleMs)) continue
|
|
80
|
+
if (Date.now() >= deadline) throw new Error(`等待文件锁超时: ${lockFile}`)
|
|
81
|
+
sleepSync(Math.min(pollMs, Math.max(1, deadline - Date.now())))
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
async function acquireAsync(lockFile, { timeoutMs, staleMs }) {
|
|
86
|
+
const token = newToken()
|
|
87
|
+
const deadline = Date.now() + timeoutMs
|
|
88
|
+
const { fileLockPollMs: pollMs } = tuning()
|
|
89
|
+
while (true) {
|
|
90
|
+
if (tryCreate(lockFile, token)) return token
|
|
91
|
+
if (reclaimDead(lockFile, staleMs)) continue
|
|
92
|
+
if (Date.now() >= deadline) throw new Error(`等待文件锁超时: ${lockFile}`)
|
|
93
|
+
await new Promise((resolve) => setTimeout(resolve, Math.min(pollMs, Math.max(1, deadline - Date.now()))))
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function withFileLock(lockFile, fn, opts = {}) {
|
|
98
|
+
const defaults = tuning()
|
|
99
|
+
const { timeoutMs = defaults.fileLockSyncTimeoutMs, staleMs = defaults.fileLockSyncStaleMs } = opts
|
|
100
|
+
const token = acquireSync(lockFile, { timeoutMs, staleMs })
|
|
101
|
+
try {
|
|
102
|
+
return fn()
|
|
103
|
+
} finally {
|
|
104
|
+
releaseOwned(lockFile, token)
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** 异步版本:用于分配端口这类需要 await 探测的场景。 */
|
|
109
|
+
export async function withAsyncFileLock(lockFile, fn, opts = {}) {
|
|
110
|
+
const defaults = tuning()
|
|
111
|
+
const { timeoutMs = defaults.fileLockAsyncTimeoutMs, staleMs = defaults.fileLockSyncStaleMs } = opts
|
|
112
|
+
const token = await acquireAsync(lockFile, { timeoutMs, staleMs })
|
|
113
|
+
try {
|
|
114
|
+
return await fn()
|
|
115
|
+
} finally {
|
|
116
|
+
releaseOwned(lockFile, token)
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function writeJsonAtomic(file, value) {
|
|
121
|
+
fs.mkdirSync(path.dirname(file), { recursive: true })
|
|
122
|
+
const tmp = `${file}.tmp-${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`
|
|
123
|
+
fs.writeFileSync(tmp, JSON.stringify(value, null, 2) + '\n')
|
|
124
|
+
try { fs.renameSync(tmp, file) } catch {
|
|
125
|
+
try { fs.rmSync(file, { force: true }) } catch { /* 忽略 */ }
|
|
126
|
+
fs.renameSync(tmp, file)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export function readJson(file, fallback = null) {
|
|
131
|
+
try { return JSON.parse(fs.readFileSync(file, 'utf8')) } catch { return fallback }
|
|
132
|
+
}
|
|
@@ -0,0 +1,130 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* HTTP 小工具的唯一实现:MIME 表、HTML 转义、loopback 判定、常量时间比较。
|
|
3
|
+
*
|
|
4
|
+
* 这几件事原本在服务宿主、编辑器宿主、网关和若干插件里各抄了一份(MIME 表 8 份、
|
|
5
|
+
* loopback 判定 7 份、escapeHtml 4 份、token 比较 4 份),抄出来的行为还不完全一致
|
|
6
|
+
* (比如 .json 有的带 charset 有 的不带、loopback 有的放行 localhost 有的不放行)。
|
|
7
|
+
* 统一放这里,谁要用谁 import,改一处全仓生效。
|
|
8
|
+
*
|
|
9
|
+
* 只依赖 node 内置模块,不 import 本包其它文件,因此不会被任何模块反向依赖成环。
|
|
10
|
+
*/
|
|
11
|
+
import path from 'node:path'
|
|
12
|
+
import { timingSafeEqual } from 'node:crypto'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 扩展名 → Content-Type。取全仓并集,统一带 charset。
|
|
16
|
+
* 键一律小写带点(`'.html'`),查询时也按小写处理。
|
|
17
|
+
*/
|
|
18
|
+
export const MIME_TYPES = Object.freeze({
|
|
19
|
+
'.html': 'text/html; charset=utf-8',
|
|
20
|
+
'.htm': 'text/html; charset=utf-8',
|
|
21
|
+
'.js': 'text/javascript; charset=utf-8',
|
|
22
|
+
'.mjs': 'text/javascript; charset=utf-8',
|
|
23
|
+
'.cjs': 'text/javascript; charset=utf-8',
|
|
24
|
+
'.css': 'text/css; charset=utf-8',
|
|
25
|
+
'.json': 'application/json; charset=utf-8',
|
|
26
|
+
'.map': 'application/json; charset=utf-8',
|
|
27
|
+
'.txt': 'text/plain; charset=utf-8',
|
|
28
|
+
'.md': 'text/markdown; charset=utf-8',
|
|
29
|
+
'.csv': 'text/csv; charset=utf-8',
|
|
30
|
+
'.xml': 'application/xml; charset=utf-8',
|
|
31
|
+
'.svg': 'image/svg+xml',
|
|
32
|
+
'.png': 'image/png',
|
|
33
|
+
'.jpg': 'image/jpeg',
|
|
34
|
+
'.jpeg': 'image/jpeg',
|
|
35
|
+
'.webp': 'image/webp',
|
|
36
|
+
'.avif': 'image/avif',
|
|
37
|
+
'.gif': 'image/gif',
|
|
38
|
+
'.ico': 'image/x-icon',
|
|
39
|
+
'.woff': 'font/woff',
|
|
40
|
+
'.woff2': 'font/woff2',
|
|
41
|
+
'.ttf': 'font/ttf',
|
|
42
|
+
'.otf': 'font/otf',
|
|
43
|
+
'.pdf': 'application/pdf',
|
|
44
|
+
'.mp4': 'video/mp4',
|
|
45
|
+
'.webm': 'video/webm',
|
|
46
|
+
'.mp3': 'audio/mpeg',
|
|
47
|
+
'.wav': 'audio/wav',
|
|
48
|
+
'.wasm': 'application/wasm',
|
|
49
|
+
'.zip': 'application/zip',
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
export const DEFAULT_MIME = 'application/octet-stream'
|
|
53
|
+
|
|
54
|
+
/** 按扩展名给 Content-Type;认不出来给 octet-stream(不猜内容)。 */
|
|
55
|
+
export function mimeFor(file) {
|
|
56
|
+
return MIME_TYPES[path.extname(String(file ?? '')).toLowerCase()] || DEFAULT_MIME
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** 是否是 HTML:`text/html` 及其带参数的写法。 */
|
|
60
|
+
export function isHtmlMime(mime) {
|
|
61
|
+
return /^text\/html\b/i.test(String(mime ?? ''))
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const HTML_ENTITIES = Object.freeze({
|
|
65
|
+
'&': '&',
|
|
66
|
+
'<': '<',
|
|
67
|
+
'>': '>',
|
|
68
|
+
'"': '"',
|
|
69
|
+
"'": ''',
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
/** 往 HTML 里插值前转义五个字符;null/undefined 变空串。 */
|
|
73
|
+
export function escapeHtml(value) {
|
|
74
|
+
return String(value ?? '').replace(/[&<>"']/g, (ch) => HTML_ENTITIES[ch])
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const IPV4_LOOPBACK = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
|
|
78
|
+
|
|
79
|
+
function bareHost(host) {
|
|
80
|
+
return String(host ?? '').trim().toLowerCase().replace(/^\[|\]$/g, '')
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* 判定一个「地址字面量」是不是本机回环:`127.x.x.x`、`::1`、
|
|
85
|
+
* `::ffff:127.x.x.x`(IPv4-mapped),以及主机名 `localhost`。
|
|
86
|
+
* 传进来的应该是 `socket.remoteAddress` 或 `url.hostname` 这类值。
|
|
87
|
+
*/
|
|
88
|
+
export function isLoopbackAddress(address) {
|
|
89
|
+
const host = bareHost(address)
|
|
90
|
+
if (!host) return false
|
|
91
|
+
if (host === 'localhost' || host === '::1') return true
|
|
92
|
+
if (host.startsWith('::ffff:')) return IPV4_LOOPBACK.test(host.slice(7))
|
|
93
|
+
return IPV4_LOOPBACK.test(host)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 判定请求是否来自本机回环(看 `req.socket.remoteAddress`)。 */
|
|
97
|
+
export function isLoopbackRequest(req) {
|
|
98
|
+
return isLoopbackAddress(req?.socket?.remoteAddress)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* 判定浏览器 Origin 头是否属于本机页面。
|
|
103
|
+
*
|
|
104
|
+
* 与 `isLoopbackAddress` 语义不同,不能互换:这里接受空 Origin(同源导航、
|
|
105
|
+
* curl 这类非浏览器请求都不带 Origin),也接受 `localhost` 这种主机名。
|
|
106
|
+
* `strict` 时把空 Origin 判为 false,用于「必须证明是同源页面」的写操作。
|
|
107
|
+
*/
|
|
108
|
+
export function isLoopbackOrigin(origin, { strict = false } = {}) {
|
|
109
|
+
if (!origin) return !strict
|
|
110
|
+
try {
|
|
111
|
+
return isLoopbackAddress(new URL(String(origin)).hostname)
|
|
112
|
+
} catch {
|
|
113
|
+
return false
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* 常量时间比较两个字符串(token、共享密钥用)。
|
|
119
|
+
* 长度不等直接 false——`timingSafeEqual` 遇到不等长会抛,这里兜住。
|
|
120
|
+
*/
|
|
121
|
+
export function timingSafeEqualText(actual, expected) {
|
|
122
|
+
const left = Buffer.from(String(actual ?? ''), 'utf8')
|
|
123
|
+
const right = Buffer.from(String(expected ?? ''), 'utf8')
|
|
124
|
+
if (!left.length || left.length !== right.length) return false
|
|
125
|
+
try {
|
|
126
|
+
return timingSafeEqual(left, right)
|
|
127
|
+
} catch {
|
|
128
|
+
return false
|
|
129
|
+
}
|
|
130
|
+
}
|