@onigeya/dsh-kanabo-memory 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/index.js ADDED
@@ -0,0 +1,154 @@
1
+ import { existsSync } from 'node:fs'
2
+ import * as runtime from './trivium-runtime.js'
3
+
4
+ /** 金棒记忆:插件名,供 DSH loader 显示与寻址。 */
5
+ export const name = 'kanabo-memory'
6
+
7
+ /**
8
+ * 本插件触碰的全部宿主服务,缺一不可。
9
+ * 未在 inject 中声明就访问 ctx.tools / ctx.systemPrompt / ctx.sessionQuery / ctx.sessionPersistence,
10
+ * 激活时会抛 `cannot get property "…" without inject`,并让**整行**失效(实测,见事实文件 §F/§Q2)。
11
+ */
12
+ export const inject = ['tools', 'systemPrompt', 'sessionQuery', 'sessionPersistence']
13
+
14
+ /**
15
+ * 路径模块表:数组顺序即加载与注册顺序(store 最先,sweep 最后)。
16
+ * `register` 是该模块必须导出的注册函数名;模块缺席时整张表仍可工作——
17
+ * 这正是 T1 阶段(尚无任何路径模块)要求的行为,后续单元只需创建对应文件。
18
+ *
19
+ * `recall` 不再有 `register`:它已退休为纯 provider(导出 `getRecallContext()`),
20
+ * `agent/pre-step` 的唯一注册者是任务 37 的 `serve.js`。这里只加载它,不挂任何钩子。
21
+ */
22
+ const PATHS = [
23
+ { module: 'store', file: './store.js' },
24
+ { module: 'cursor', file: './cursor.js' },
25
+ { module: 'tools', file: './tools.js', register: 'registerTools' },
26
+ { module: 'recall', file: './recall.js' },
27
+ { module: 'serve', file: './serve.js', register: 'registerServe' },
28
+ { module: 'extract', file: './extract.js', register: 'registerExtract' },
29
+ { module: 'sweep', file: './sweep.js', register: 'startSweeper' },
30
+ { module: 'retention-sweep', file: './retention-sweep.js', register: 'registerEgress' },
31
+ ]
32
+
33
+ /** 安全写一行:日志本身出错也绝不冒泡(记忆故障不得让用户的回合失败)。 */
34
+ function writeLine(stream, text) {
35
+ try {
36
+ stream.write(`${text}\n`)
37
+ } catch {
38
+ // 忽略:stdout/stderr 不可写时没有比沉默更安全的动作。
39
+ }
40
+ }
41
+
42
+ /**
43
+ * 插件入口:逐个加载路径模块,并在导出对应注册函数时调用它。
44
+ * 任何一步失败都只记一行日志、继续下一个模块,绝不让这一行失效(fail-open)。
45
+ */
46
+ export async function apply(ctx) {
47
+ const log = (text) => writeLine(process.stderr, `kanabo-memory: ${text}`)
48
+ /** 传给注册函数的依赖;后续单元在此追加存储句柄、游标等,无需改动加载循环。 */
49
+ const deps = { log }
50
+ const loaded = []
51
+ /** store 模块成功加载后记录存储路径(IS-8):日志失败只警告,绝不让激活失效。 */
52
+ const logStorePath = (mod) => {
53
+ try {
54
+ log(`store at ${mod.storeDir()}`)
55
+ } catch (error) {
56
+ log(`store path unavailable: ${error?.message ?? String(error)}`)
57
+ }
58
+ }
59
+
60
+ try {
61
+ for (const path of PATHS) {
62
+ let mod
63
+ try {
64
+ mod = await import(path.file)
65
+ } catch (error) {
66
+ const built = existsSync(new URL(path.file, import.meta.url))
67
+ if (built) log(`${path.module} path failed to load: ${error?.message ?? String(error)}`)
68
+ else log(`${path.module} path not built yet`)
69
+ continue
70
+ }
71
+ loaded.push(path.module)
72
+ if (path.module === 'store') logStorePath(mod)
73
+ // 画像默认 provider(任务 55):serve.js 是 `agent/pre-step` 的唯一注册者,默认就得会组装
74
+ // 画像,否则真实回合永远只有召回。在模块已加载处补依赖而不是顶层静态 import,是为了保留
75
+ // 「路径模块缺席仍能加载」的契约;显式传入的 `deps.personaProvider` 不会被覆盖。
76
+ if (path.module === 'serve' && deps.personaProvider === undefined
77
+ && typeof mod.makeDefaultPersonaProvider === 'function') {
78
+ deps.personaProvider = mod.makeDefaultPersonaProvider({ log })
79
+ }
80
+ if (path.register === undefined) continue
81
+ const register = mod[path.register]
82
+ if (typeof register !== 'function') {
83
+ log(`${path.module} loaded without ${path.register}; skipping registration`)
84
+ continue
85
+ }
86
+ try {
87
+ await register(ctx, deps)
88
+ } catch (error) {
89
+ log(`${path.module}: ${path.register} threw; continuing (${error?.message ?? String(error)})`)
90
+ }
91
+ }
92
+ } catch (error) {
93
+ log(`loader failed: ${error?.message ?? String(error)}`)
94
+ }
95
+
96
+ try {
97
+ log(`trivium at ${runtime.triviumDir()}`)
98
+ } catch (error) {
99
+ log(`trivium path unavailable: ${error?.message ?? String(error)}`)
100
+ }
101
+ registerShutdown(ctx, log)
102
+
103
+ writeLine(process.stdout, `kanabo-memory active: ${loaded.length === 0 ? 'no paths yet' : loaded.join(', ')}`)
104
+ }
105
+
106
+ /**
107
+ * 两阶段关闭的挂点:先 `requestShutdown()`(拒绝新请求、开始排空),再 `close({ timeoutMs })`
108
+ * (限时等门面关完、子进程退出、文件租约释放)。失败只记一行,绝不冒泡——
109
+ * 卸载流程不得因为记忆存储的故障而失败。
110
+ */
111
+ async function shutdownRuntime(log) {
112
+ try {
113
+ const { drainRetainChain } = await import('./extract.js')
114
+ let timer
115
+ const drained = await Promise.race([
116
+ drainRetainChain().then(() => true, () => false),
117
+ new Promise((resolveWait) => {
118
+ timer = setTimeout(() => resolveWait(false), 10_000)
119
+ timer.unref?.()
120
+ }),
121
+ ])
122
+ clearTimeout(timer)
123
+ if (drained !== true) log('trivium shutdown: retain drain did not settle within 10000ms; closing anyway')
124
+ const phase = runtime.requestShutdown()
125
+ const result = await runtime.close({ timeoutMs: 15_000 })
126
+ const pids = result.leftoverPids ?? []
127
+ const suffix = pids.length === 0 ? 'no child left' : `leftover children: ${pids.join(',')}`
128
+ log(`trivium shutdown: requested ${phase.facades} facade(s), closed=${result.closed}, timedOut=${result.timedOut}, ${suffix}`)
129
+ } catch (error) {
130
+ log(`trivium shutdown failed: ${error?.message ?? String(error)}`)
131
+ }
132
+ }
133
+
134
+ function registerShutdown(ctx, log) {
135
+ try {
136
+ if (typeof ctx?.effect === 'function') {
137
+ ctx.effect(() => async () => {
138
+ await shutdownRuntime(log)
139
+ })
140
+ return
141
+ }
142
+ } catch (error) {
143
+ log(`cannot register shutdown via effect: ${error?.message ?? String(error)}`)
144
+ }
145
+ try {
146
+ if (typeof ctx?.on === 'function') {
147
+ ctx.on('dispose', () => {
148
+ void shutdownRuntime(log)
149
+ })
150
+ }
151
+ } catch (error) {
152
+ log(`cannot register shutdown via dispose: ${error?.message ?? String(error)}`)
153
+ }
154
+ }