@restregular/dsh-memory 0.34.1 → 0.35.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/CHANGELOG.md +21 -0
- package/README.md +36 -1
- package/lib/client.js +412 -27
- package/lib/index.js +12 -1
- package/lib/inject/apply.js +43 -12
- package/lib/panel.js +1717 -1616
- package/lib/provider/apply.js +54 -0
- package/lib/provider/approval-audit.js +1 -1
- package/lib/provider/hooks.js +597 -0
- package/lib/provider/index.js +292 -3
- package/lib/skills.js +157 -0
- package/lib/tools/apply.js +6 -1
- package/lib/tools/index.js +436 -1
- package/lib/tools/render.js +78 -1
- package/package.json +2 -1
- package/skills/memory-hook-scripts/SKILL.md +142 -0
- package/skills/memory-hook-scripts/references/examples.md +159 -0
package/lib/provider/apply.js
CHANGED
|
@@ -380,6 +380,60 @@ export class CordisMemoryService extends Service {
|
|
|
380
380
|
return this.impl.injectSettings()
|
|
381
381
|
}
|
|
382
382
|
|
|
383
|
+
// ---------------------------------------------------------------- 记忆钩子(0.35.0)
|
|
384
|
+
/**
|
|
385
|
+
* 钩子能力必须在这里**逐个转发**:面板与工具拿到的都是本包装实例,
|
|
386
|
+
* 少转一个方法就是 undefined(0.32.0 的归档/屏蔽就整体这样失效过,
|
|
387
|
+
* 而单测直接 new LocalMemoryService 完全看不见)。
|
|
388
|
+
*/
|
|
389
|
+
hookSettings() {
|
|
390
|
+
return this.impl.hookSettings()
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
updateHookSettings(patch ) {
|
|
394
|
+
return this.impl.updateHookSettings(patch)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
listHooks() {
|
|
398
|
+
return this.impl.listHooks()
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
getHook(id ) {
|
|
402
|
+
return this.impl.getHook(id)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
saveHook(input ) {
|
|
406
|
+
return this.impl.saveHook(input)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
deleteHook(id ) {
|
|
410
|
+
return this.impl.deleteHook(id)
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
approveHook(id ) {
|
|
414
|
+
return this.impl.approveHook(id)
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
hookPendingApproval(id ) {
|
|
418
|
+
return this.impl.hookPendingApproval(id)
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
requestHookApproval(
|
|
422
|
+
agent ,
|
|
423
|
+
id ,
|
|
424
|
+
options ,
|
|
425
|
+
) {
|
|
426
|
+
return this.impl.requestHookApproval(agent, id, options)
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
runHooks(phase , input ) {
|
|
430
|
+
return this.impl.runHooks(phase, input)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
parseForInject(records , sessionId ) {
|
|
434
|
+
return this.impl.parseForInject(records, sessionId)
|
|
435
|
+
}
|
|
436
|
+
|
|
383
437
|
/** 面板改设置:落盘后广播,注入半边下一步就能按新设置跑。 */
|
|
384
438
|
updateInjectSettings(patch ) {
|
|
385
439
|
const next = this.impl.updateInjectSettings(patch)
|
|
@@ -0,0 +1,597 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 记忆钩子(memory hooks):给规则记忆附带可执行代码,并在明确的时机由插件运行。
|
|
3
|
+
*
|
|
4
|
+
* 为什么要有它
|
|
5
|
+
* ------------
|
|
6
|
+
* `kind=rule` 的记忆只是"写给模型看的话"。模型可能记错、漏做、或者压根不看。
|
|
7
|
+
* 「概括 + :+ 正文」这类**能写成检查**的规则,应该由代码强制,而不是靠模型自觉。
|
|
8
|
+
* 所以规则记忆可以附带一段脚本,插件在三个时机运行它:
|
|
9
|
+
*
|
|
10
|
+
* before-save 保存前校验。脚本可以说"不合规"从而**拒绝这次保存**(veto)。
|
|
11
|
+
* after-save 保存后观察。只记录/附注,不改写、不阻断。
|
|
12
|
+
* before-inject 注入前解析。可以改写即将进入上下文的正文,或整条丢弃。
|
|
13
|
+
*
|
|
14
|
+
* 三条硬约定
|
|
15
|
+
* ----------
|
|
16
|
+
* 1) **代码不纳入记忆检索。** 钩子存在 `<storeDir>/hooks.json`,与
|
|
17
|
+
* scopes.json / settings.json 同级;它们不是记忆记录、不进 JSONL、不进向量索引,
|
|
18
|
+
* search / list / digest / recall 都看不见。只有 memory_hooks 与面板能取到代码。
|
|
19
|
+
* 2) **沙箱执行。** node:vm 新上下文、禁用 eval/new Function、无 require / process /
|
|
20
|
+
* fs / net、无定时器;数据以 JSON 文本**在沙箱内**解析,宿主对象一个都不进上下文。
|
|
21
|
+
* 模块体与每次调用都套 `timeout`,死循环会被中断而不是挂住 DSH。
|
|
22
|
+
* 3) **脚本崩溃不等于校验不通过。** 返回 `{ok:false}` 是它的职责(阻断写入);
|
|
23
|
+
* 脚本抛异常 / 超时是它自己坏了 —— 那就只告警、不阻断,否则一条写坏的校验器
|
|
24
|
+
* 会让整个记忆系统无法写入,等于丢数据。错误计数进 lastOutcome,面板上一眼可见。
|
|
25
|
+
*
|
|
26
|
+
* 审批
|
|
27
|
+
* ----
|
|
28
|
+
* 带代码的规则在首次保存时向用户审批一次(默认开启,见 config.hooks.requireApproval)。
|
|
29
|
+
* 批准记的是**代码指纹**(sha256),所以"同一段代码"不会再问第二遍,而只要代码变了
|
|
30
|
+
* 就必须重新批准 —— 否则改两个字符就能让用户批准过的权限继续生效。
|
|
31
|
+
*/
|
|
32
|
+
import { createHash, randomUUID } from 'node:crypto'
|
|
33
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
34
|
+
import { dirname, join } from 'node:path'
|
|
35
|
+
import * as vm from 'node:vm'
|
|
36
|
+
|
|
37
|
+
// ---------------------------------------------------------------- 类型
|
|
38
|
+
|
|
39
|
+
/** 可运行脚本的三个时机。 */
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
export const HOOK_PHASES = ['before-save', 'after-save', 'before-inject']
|
|
43
|
+
|
|
44
|
+
/** 每个时机默认找的函数名(最后都兜底接受 `main`)。 */
|
|
45
|
+
const PHASE_ENTRY = {
|
|
46
|
+
'before-save': ['verify', 'verifyMemoryContent', 'main'],
|
|
47
|
+
'after-save': ['observe', 'afterSave', 'main'],
|
|
48
|
+
'before-inject': ['parse', 'parseMemory', 'main'],
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** 一个钩子(持久化形态)。 */
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
/** 新建 / 更新钩子的入参。`id` 存在 = 更新。 */
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
/** 运行脚本时喂进去的一条记忆(纯数据)。 */
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
/** 一次运行的输入。 */
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
/** 单个钩子的运行结果。 */
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
export const DEFAULT_HOOK_SETTINGS = {
|
|
145
|
+
enabled: true,
|
|
146
|
+
timeoutMs: 120,
|
|
147
|
+
requireApproval: true,
|
|
148
|
+
maxCodeChars: 16_000,
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** 代码指纹:审批与编译缓存都以它为准。 */
|
|
152
|
+
export function hashHookCode(code ) {
|
|
153
|
+
return createHash('sha256').update(code).digest('hex')
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 空数组 / 含 '*' → 匹配全部。 */
|
|
157
|
+
function matchesFilter(list , value ) {
|
|
158
|
+
if (list.length === 0) return true
|
|
159
|
+
return list.some((item) => item === '*' || item === value)
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
export function hookApplies(hook , input ) {
|
|
163
|
+
return matchesFilter(hook.scopes, input.scope) && matchesFilter(hook.kinds, input.kind)
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 这个钩子当前是否还需要用户批准(代码改过也算需要)。 */
|
|
167
|
+
export function hookNeedsApproval(
|
|
168
|
+
hook ,
|
|
169
|
+
settings ,
|
|
170
|
+
) {
|
|
171
|
+
if (!settings.requireApproval) return false
|
|
172
|
+
return hook.approvedHash !== hashHookCode(hook.code)
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// ---------------------------------------------------------------- 沙箱
|
|
176
|
+
|
|
177
|
+
/** 编译产物:一个已建好的上下文 + 入口函数名。 */
|
|
178
|
+
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 沙箱预置的**纯计算**全局。
|
|
185
|
+
*
|
|
186
|
+
* 刻意**不放**:require / process / Buffer / setTimeout / fetch / console 之外的宿主对象。
|
|
187
|
+
* `globalThis` 在 vm 上下文里指向沙箱自己,逃不出去;`codeGeneration.strings=false`
|
|
188
|
+
* 已经把 eval 与 new Function 关掉。
|
|
189
|
+
*/
|
|
190
|
+
const SANDBOX_PRELUDE = `
|
|
191
|
+
'use strict';
|
|
192
|
+
globalThis.__dshHookLogs = [];
|
|
193
|
+
globalThis.log = function () {
|
|
194
|
+
var parts = [];
|
|
195
|
+
for (var i = 0; i < arguments.length; i++) {
|
|
196
|
+
var value = arguments[i];
|
|
197
|
+
var text;
|
|
198
|
+
if (typeof value === 'string') text = value;
|
|
199
|
+
else {
|
|
200
|
+
try { text = JSON.stringify(value); } catch (e) { text = String(value); }
|
|
201
|
+
if (typeof text !== 'string') text = String(value);
|
|
202
|
+
}
|
|
203
|
+
parts.push(text.slice(0, 500));
|
|
204
|
+
}
|
|
205
|
+
__dshHookLogs.push(parts.join(' ').slice(0, 1000));
|
|
206
|
+
};
|
|
207
|
+
`
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* 把一段用户代码编译进新的 vm 上下文。
|
|
211
|
+
*
|
|
212
|
+
* 约定:代码是**模块体**,需要定义入口函数。按 phase 找 `verify` / `observe` / `parse`
|
|
213
|
+
* (`main` 兜底)。入口函数同步返回结论,见 normalizeHookResult。
|
|
214
|
+
*/
|
|
215
|
+
function compile(code , phase , label , timeoutMs ) {
|
|
216
|
+
const context = vm.createContext(Object.create(null), {
|
|
217
|
+
// 关掉从字符串生成代码:`eval` 与 `new Function` 都被禁。
|
|
218
|
+
codeGeneration: { strings: false, wasm: false },
|
|
219
|
+
})
|
|
220
|
+
// 预置 log():每次运行前清空,脚本里的 log 会随结果回给调用方。
|
|
221
|
+
new vm.Script(SANDBOX_PRELUDE, { filename: 'memory-hook:prelude' })
|
|
222
|
+
.runInContext(context, { timeout: Math.max(50, timeoutMs) })
|
|
223
|
+
// 只执行模块体(定义函数),同样受超时约束,防止顶层死循环。
|
|
224
|
+
new vm.Script(code, { filename: `memory-hook:${label}` })
|
|
225
|
+
.runInContext(context, { timeout: Math.max(50, timeoutMs) })
|
|
226
|
+
|
|
227
|
+
for (const name of PHASE_ENTRY[phase]) {
|
|
228
|
+
const candidate = (context )[name]
|
|
229
|
+
if (typeof candidate === 'function') return { context, entryName: name }
|
|
230
|
+
}
|
|
231
|
+
const expected = PHASE_ENTRY[phase].slice(0, -1).map((n) => `${n}()`).join(' 或 ')
|
|
232
|
+
throw new Error(`脚本里找不到入口函数:需要定义 ${expected}(main() 也可以)`)
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/**
|
|
236
|
+
* 规范化脚本返回值。
|
|
237
|
+
*
|
|
238
|
+
* 接受:undefined / true / false / 字符串 / {ok,message,note,content,drop,reject}。
|
|
239
|
+
* 其余(数字、数组…)当"通过"处理并忽略 —— 不让一个笔误把写入永久卡住。
|
|
240
|
+
*/
|
|
241
|
+
export function normalizeHookResult(raw ) {
|
|
242
|
+
if (raw === undefined || raw === null || raw === true) return { ok: true }
|
|
243
|
+
if (raw === false) return { ok: false }
|
|
244
|
+
if (typeof raw === 'string') {
|
|
245
|
+
const text = raw.trim()
|
|
246
|
+
return text === '' ? { ok: true } : { ok: false, message: text }
|
|
247
|
+
}
|
|
248
|
+
if (typeof raw === 'object') {
|
|
249
|
+
const value = raw
|
|
250
|
+
const ok = value.ok !== undefined ? value.ok !== false : value.reject !== true
|
|
251
|
+
const out = { ok }
|
|
252
|
+
const message = typeof value.message === 'string' && value.message.trim() !== ''
|
|
253
|
+
? value.message.trim()
|
|
254
|
+
: typeof value.note === 'string' && value.note.trim() !== '' ? value.note.trim() : undefined
|
|
255
|
+
if (message !== undefined) out.message = message.slice(0, 500)
|
|
256
|
+
if (typeof value.content === 'string') out.content = value.content
|
|
257
|
+
if (value.drop === true) out.drop = true
|
|
258
|
+
return out
|
|
259
|
+
}
|
|
260
|
+
return { ok: true }
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
/** 编译缓存:key = `${phase}:${codeHash}`。代码一改就自然换 key。 */
|
|
264
|
+
const compileCache = new Map ()
|
|
265
|
+
const COMPILE_CACHE_MAX = 64
|
|
266
|
+
|
|
267
|
+
/**
|
|
268
|
+
* 运行一段脚本。**永不抛错** —— 所有失败都折成 `{ ok:true, error }`,
|
|
269
|
+
* 由调用方决定是告警还是阻断。
|
|
270
|
+
*
|
|
271
|
+
* 调用也走 `runInContext`(而不是直接调 fn),这样 `timeout` 对**函数体**同样生效。
|
|
272
|
+
*/
|
|
273
|
+
export function runHookCode(
|
|
274
|
+
code ,
|
|
275
|
+
phase ,
|
|
276
|
+
input ,
|
|
277
|
+
settings ,
|
|
278
|
+
) {
|
|
279
|
+
const timeout = Math.max(20, Math.min(5000, settings.timeoutMs))
|
|
280
|
+
const key = `${phase}:${hashHookCode(code)}`
|
|
281
|
+
let compiled = compileCache.get(key)
|
|
282
|
+
if (compiled === undefined) {
|
|
283
|
+
try {
|
|
284
|
+
compiled = compile(code, phase, phase, timeout)
|
|
285
|
+
} catch (error) {
|
|
286
|
+
return { ok: true, error: `脚本无法加载:${error instanceof Error ? error.message : String(error)}`, logs: [] }
|
|
287
|
+
}
|
|
288
|
+
if (compileCache.size >= COMPILE_CACHE_MAX) compileCache.clear()
|
|
289
|
+
compileCache.set(key, compiled)
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const context = compiled.context
|
|
293
|
+
// 每次运行清空 log 缓冲,避免上一次的日志串到这一次。
|
|
294
|
+
context.__dshHookLogs = []
|
|
295
|
+
// 数据以 **JSON 文本**进沙箱,在沙箱内 parse —— 宿主对象一个都不进上下文。
|
|
296
|
+
const memoryJson = JSON.stringify({ ...input.memory })
|
|
297
|
+
const ctxJson = JSON.stringify({
|
|
298
|
+
phase,
|
|
299
|
+
...(input.tool !== undefined ? { tool: input.tool } : {}),
|
|
300
|
+
...(input.sessionId !== undefined ? { sessionId: input.sessionId } : {}),
|
|
301
|
+
...(input.description !== undefined ? { description: input.description } : {}),
|
|
302
|
+
now: Date.now(),
|
|
303
|
+
})
|
|
304
|
+
const driver = new vm.Script(
|
|
305
|
+
`__dshHookResult = ${compiled.entryName}(JSON.parse(${JSON.stringify(memoryJson)}), JSON.parse(${JSON.stringify(ctxJson)}));`,
|
|
306
|
+
{ filename: 'memory-hook:invoke' },
|
|
307
|
+
)
|
|
308
|
+
try {
|
|
309
|
+
driver.runInContext(compiled.context, { timeout })
|
|
310
|
+
const raw = context.__dshHookResult
|
|
311
|
+
const logs = readLogs(context)
|
|
312
|
+
if (raw !== null && typeof raw === 'object' && typeof (raw ).then === 'function') {
|
|
313
|
+
return { ok: true, error: '脚本返回了 Promise:钩子必须是同步函数(不允许 await)', logs }
|
|
314
|
+
}
|
|
315
|
+
return { ...normalizeHookResult(raw), logs }
|
|
316
|
+
} catch (error) {
|
|
317
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
318
|
+
const timedOut = /timed out|Script execution timed out/i.test(message)
|
|
319
|
+
return {
|
|
320
|
+
ok: true,
|
|
321
|
+
error: timedOut ? `脚本执行超时(上限 ${timeout}ms)` : `脚本抛错:${message}`,
|
|
322
|
+
logs: readLogs(context),
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
/** 取走沙箱里 log() 攒下的内容。 */
|
|
328
|
+
function readLogs(context ) {
|
|
329
|
+
const buffer = context.__dshHookLogs
|
|
330
|
+
if (!Array.isArray(buffer)) return []
|
|
331
|
+
const copy = buffer.slice(0, 20).map((item) => String(item).slice(0, 500))
|
|
332
|
+
context.__dshHookLogs = []
|
|
333
|
+
return copy
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ---------------------------------------------------------------- 存储
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
const FILE_VERSION = 1
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* 钩子存储:单个 JSON 文件 + 原子写。
|
|
347
|
+
*
|
|
348
|
+
* 与记忆分开存放是**功能要求**而不是实现细节:记忆记录会进向量索引、会被
|
|
349
|
+
* search/recall/digest 读出来,而代码不该出现在任何一条"记忆"里。
|
|
350
|
+
*/
|
|
351
|
+
export class HookStore {
|
|
352
|
+
file
|
|
353
|
+
hooks = []
|
|
354
|
+
loaded = false
|
|
355
|
+
onWarn
|
|
356
|
+
|
|
357
|
+
constructor(options ) {
|
|
358
|
+
this.file = join(options.root, 'hooks.json')
|
|
359
|
+
this.onWarn = options.onWarn ?? (() => {})
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
load() {
|
|
363
|
+
if (this.loaded) return
|
|
364
|
+
this.loaded = true
|
|
365
|
+
try {
|
|
366
|
+
if (!existsSync(this.file)) return
|
|
367
|
+
const text = readFileSync(this.file, 'utf8')
|
|
368
|
+
if (text.trim() === '') return
|
|
369
|
+
const parsed = JSON.parse(text)
|
|
370
|
+
const list = Array.isArray(parsed.hooks) ? parsed.hooks : []
|
|
371
|
+
this.hooks = list.filter((hook) =>
|
|
372
|
+
hook !== null && typeof hook === 'object' && typeof hook.id === 'string' && typeof hook.code === 'string')
|
|
373
|
+
// 老文件可能缺统计字段:补齐,避免调用方到处判空。
|
|
374
|
+
.map((hook) => ({
|
|
375
|
+
...hook,
|
|
376
|
+
enabled: hook.enabled !== false,
|
|
377
|
+
scopes: Array.isArray(hook.scopes) ? hook.scopes : [],
|
|
378
|
+
kinds: Array.isArray(hook.kinds) ? hook.kinds : [],
|
|
379
|
+
runCount: Number(hook.runCount) || 0,
|
|
380
|
+
errorCount: Number(hook.errorCount) || 0,
|
|
381
|
+
rejectCount: Number(hook.rejectCount) || 0,
|
|
382
|
+
}))
|
|
383
|
+
} catch (error) {
|
|
384
|
+
// 坏文件不能让记忆整体不可用:退化成"没有钩子",并在日志里说清楚。
|
|
385
|
+
this.onWarn(`hooks.json 读取失败(按无钩子继续):${error instanceof Error ? error.message : String(error)}`)
|
|
386
|
+
this.hooks = []
|
|
387
|
+
}
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
persist() {
|
|
391
|
+
const payload = { schemaVersion: FILE_VERSION, hooks: this.hooks }
|
|
392
|
+
try {
|
|
393
|
+
mkdirSync(dirname(this.file), { recursive: true })
|
|
394
|
+
const tmp = `${this.file}.${process.pid}.tmp`
|
|
395
|
+
writeFileSync(tmp, `${JSON.stringify(payload, null, 2)}\n`, 'utf8')
|
|
396
|
+
renameSync(tmp, this.file)
|
|
397
|
+
} catch (error) {
|
|
398
|
+
this.onWarn(`hooks.json 写入失败:${error instanceof Error ? error.message : String(error)}`)
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
list() {
|
|
403
|
+
this.load()
|
|
404
|
+
return [...this.hooks]
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
get(id ) {
|
|
408
|
+
this.load()
|
|
409
|
+
return this.hooks.find((hook) => hook.id === id)
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
/**
|
|
413
|
+
* 命中某次运行的全部钩子(已启用 + 作用域/类型匹配 + **已获批准**)。
|
|
414
|
+
*
|
|
415
|
+
* 审批是在这里守住的:一个还没被用户批准的脚本,`list()` 里看得见、面板里能编辑,
|
|
416
|
+
* 但**永远不会被执行**。把闸门放在存储层而不是各个调用点,是因为调用点有四个
|
|
417
|
+
* (保存前 / 保存后 / 注入前 / 试跑),漏一个就是一条绕过审批的路径。
|
|
418
|
+
*/
|
|
419
|
+
forRun(phase , target , settings ) {
|
|
420
|
+
this.load()
|
|
421
|
+
return this.hooks.filter((hook) =>
|
|
422
|
+
hook.enabled
|
|
423
|
+
&& hook.phase === phase
|
|
424
|
+
&& hookApplies(hook, target)
|
|
425
|
+
&& !hookNeedsApproval(hook, settings))
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
save(input , settings ) {
|
|
429
|
+
this.load()
|
|
430
|
+
const code = input.code
|
|
431
|
+
if (typeof code !== 'string' || code.trim() === '') throw new Error('code 不能为空')
|
|
432
|
+
if (code.length > settings.maxCodeChars) throw new Error(`code 超过 ${settings.maxCodeChars} 字符上限`)
|
|
433
|
+
if (!HOOK_PHASES.includes(input.phase)) throw new Error(`phase 必须是 ${HOOK_PHASES.join(' / ')}`)
|
|
434
|
+
|
|
435
|
+
const now = Date.now()
|
|
436
|
+
const existing = input.id !== undefined && input.id !== ''
|
|
437
|
+
? this.hooks.find((hook) => hook.id === input.id)
|
|
438
|
+
: undefined
|
|
439
|
+
if (existing !== undefined) {
|
|
440
|
+
const codeChanged = existing.code !== code
|
|
441
|
+
existing.name = (input.name ?? existing.name).trim() || existing.name
|
|
442
|
+
existing.phase = input.phase
|
|
443
|
+
existing.code = code
|
|
444
|
+
existing.enabled = input.enabled ?? existing.enabled
|
|
445
|
+
if (Array.isArray(input.scopes)) existing.scopes = input.scopes.map(String)
|
|
446
|
+
if (Array.isArray(input.kinds)) existing.kinds = input.kinds.map(String)
|
|
447
|
+
if (input.description !== undefined) existing.description = input.description
|
|
448
|
+
if (input.ruleId !== undefined) existing.ruleId = input.ruleId
|
|
449
|
+
existing.updatedAt = now
|
|
450
|
+
// 代码变了 = 旧的审批作废;明确给新指纹(审批就是针对新代码做的)时采用它。
|
|
451
|
+
if (input.approvedHash !== undefined) existing.approvedHash = input.approvedHash
|
|
452
|
+
else if (codeChanged) delete existing.approvedHash
|
|
453
|
+
if (codeChanged) {
|
|
454
|
+
// 换了代码就是换了一个校验器:旧统计不再有意义。
|
|
455
|
+
existing.runCount = 0
|
|
456
|
+
existing.errorCount = 0
|
|
457
|
+
existing.rejectCount = 0
|
|
458
|
+
delete existing.lastOutcome
|
|
459
|
+
delete existing.lastMessage
|
|
460
|
+
delete existing.lastRunAt
|
|
461
|
+
}
|
|
462
|
+
this.persist()
|
|
463
|
+
return existing
|
|
464
|
+
}
|
|
465
|
+
|
|
466
|
+
const hook = {
|
|
467
|
+
id: `hook-${randomUUID().slice(0, 8)}`,
|
|
468
|
+
name: (input.name ?? '').trim() || `${input.phase} 规则`,
|
|
469
|
+
phase: input.phase,
|
|
470
|
+
code,
|
|
471
|
+
enabled: input.enabled ?? true,
|
|
472
|
+
scopes: Array.isArray(input.scopes) ? input.scopes.map(String) : [],
|
|
473
|
+
kinds: Array.isArray(input.kinds) ? input.kinds.map(String) : [],
|
|
474
|
+
...(input.description !== undefined ? { description: input.description } : {}),
|
|
475
|
+
...(input.ruleId !== undefined ? { ruleId: input.ruleId } : {}),
|
|
476
|
+
...(input.approvedHash !== undefined ? { approvedHash: input.approvedHash } : {}),
|
|
477
|
+
createdBy: input.createdBy ?? 'agent',
|
|
478
|
+
createdAt: now,
|
|
479
|
+
updatedAt: now,
|
|
480
|
+
runCount: 0,
|
|
481
|
+
errorCount: 0,
|
|
482
|
+
rejectCount: 0,
|
|
483
|
+
}
|
|
484
|
+
this.hooks.push(hook)
|
|
485
|
+
this.persist()
|
|
486
|
+
return hook
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
delete(id ) {
|
|
490
|
+
this.load()
|
|
491
|
+
const before = this.hooks.length
|
|
492
|
+
this.hooks = this.hooks.filter((hook) => hook.id !== id)
|
|
493
|
+
if (this.hooks.length === before) return false
|
|
494
|
+
this.persist()
|
|
495
|
+
return true
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
/** 记一次运行结果(统计 + 最近一次结局)。 */
|
|
499
|
+
recordRun(id , outcome ) {
|
|
500
|
+
this.load()
|
|
501
|
+
const hook = this.hooks.find((item) => item.id === id)
|
|
502
|
+
if (hook === undefined) return
|
|
503
|
+
hook.runCount += 1
|
|
504
|
+
hook.lastRunAt = Date.now()
|
|
505
|
+
if (outcome.crashed) {
|
|
506
|
+
hook.errorCount += 1
|
|
507
|
+
hook.lastOutcome = 'error'
|
|
508
|
+
} else if (!outcome.ok) {
|
|
509
|
+
hook.rejectCount += 1
|
|
510
|
+
hook.lastOutcome = 'rejected'
|
|
511
|
+
} else {
|
|
512
|
+
hook.lastOutcome = 'ok'
|
|
513
|
+
}
|
|
514
|
+
if (outcome.message !== undefined) hook.lastMessage = outcome.message.slice(0, 300)
|
|
515
|
+
else if (hook.lastOutcome === 'ok') delete hook.lastMessage
|
|
516
|
+
this.persist()
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/** 记一次审批指纹。 */
|
|
520
|
+
approve(id , hash ) {
|
|
521
|
+
this.load()
|
|
522
|
+
const hook = this.hooks.find((item) => item.id === id)
|
|
523
|
+
if (hook === undefined) return false
|
|
524
|
+
hook.approvedHash = hash
|
|
525
|
+
hook.updatedAt = Date.now()
|
|
526
|
+
this.persist()
|
|
527
|
+
return true
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
/** 测试用:绕过缓存重新读盘。 */
|
|
531
|
+
reload() {
|
|
532
|
+
this.loaded = false
|
|
533
|
+
this.load()
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
// ---------------------------------------------------------------- 运行器
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* 按时机运行一批钩子。
|
|
541
|
+
*
|
|
542
|
+
* - 顺序执行;任一 before-save 返回 ok:false 就**立即停止**(后面的钩子没必要跑)。
|
|
543
|
+
* - 崩溃 / 超时只告警,不阻断(见文件头注释第 3 条)。
|
|
544
|
+
*/
|
|
545
|
+
export function runHooks(
|
|
546
|
+
store ,
|
|
547
|
+
phase ,
|
|
548
|
+
input ,
|
|
549
|
+
settings ,
|
|
550
|
+
) {
|
|
551
|
+
if (!settings.enabled) return []
|
|
552
|
+
const out = []
|
|
553
|
+
for (const hook of store.forRun(phase, { scope: input.memory.scope, kind: input.memory.kind }, settings)) {
|
|
554
|
+
const started = Date.now()
|
|
555
|
+
const result = runHookCode(hook.code, phase, input, settings)
|
|
556
|
+
const crashed = result.error !== undefined
|
|
557
|
+
const outcome = {
|
|
558
|
+
hook: { id: hook.id, name: hook.name, phase },
|
|
559
|
+
// 崩溃时 ok 恒 true —— 调用方据此"不阻断"。
|
|
560
|
+
ok: crashed ? true : result.ok,
|
|
561
|
+
durationMs: Date.now() - started,
|
|
562
|
+
...(result.message !== undefined ? { message: result.message } : {}),
|
|
563
|
+
...(result.content !== undefined ? { content: result.content } : {}),
|
|
564
|
+
...(result.drop === true ? { drop: true } : {}),
|
|
565
|
+
...(crashed ? { error: result.error } : {}),
|
|
566
|
+
...(result.logs.length > 0 ? { logs: result.logs.slice(0, 20) } : {}),
|
|
567
|
+
}
|
|
568
|
+
try {
|
|
569
|
+
store.recordRun(hook.id, {
|
|
570
|
+
ok: outcome.ok,
|
|
571
|
+
crashed,
|
|
572
|
+
...(outcome.message !== undefined ? { message: outcome.message } : {}),
|
|
573
|
+
})
|
|
574
|
+
} catch { /* 统计写失败不影响本次运行 */ }
|
|
575
|
+
out.push(outcome)
|
|
576
|
+
// before-save 的否决不需要再跑后续钩子:结论已经定了。
|
|
577
|
+
if (phase === 'before-save' && !crashed && !result.ok) break
|
|
578
|
+
}
|
|
579
|
+
return out
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
/** 把一批结果折成给模型看的一段文字(没有内容时返回空串)。 */
|
|
583
|
+
export function describeOutcomes(outcomes ) {
|
|
584
|
+
const lines = []
|
|
585
|
+
for (const outcome of outcomes) {
|
|
586
|
+
if (outcome.error !== undefined) {
|
|
587
|
+
lines.push(`⚠ 钩子「${outcome.hook.name}」运行失败(不影响结果):${outcome.error}`)
|
|
588
|
+
continue
|
|
589
|
+
}
|
|
590
|
+
if (!outcome.ok && outcome.message !== undefined) lines.push(outcome.message)
|
|
591
|
+
else if (outcome.message !== undefined) lines.push(`钩子「${outcome.hook.name}」:${outcome.message}`)
|
|
592
|
+
}
|
|
593
|
+
return lines.join('\n')
|
|
594
|
+
}
|
|
595
|
+
|
|
596
|
+
|
|
597
|
+
//# sourceURL=source/memory-local/src/hooks.ts
|