@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/backfill-child.js +310 -0
- package/backfill-vectors.js +125 -0
- package/contract.js +114 -0
- package/cordis.patch.yml +7 -0
- package/cursor.js +116 -0
- package/dedupe.js +101 -0
- package/egress.js +790 -0
- package/embed-child.js +152 -0
- package/embed.js +475 -0
- package/envelope.js +368 -0
- package/extract.js +420 -0
- package/idle-interrupt.js +922 -0
- package/index.js +154 -0
- package/migrate.js +1723 -0
- package/package.json +68 -3
- package/persona.js +949 -0
- package/providers.js +786 -0
- package/query-window.js +562 -0
- package/recall-stages.js +150 -0
- package/recall-trivium.js +916 -0
- package/recall.js +129 -0
- package/remove-legacy.mjs +720 -0
- package/retention-sweep.js +124 -0
- package/serve.js +138 -0
- package/store-trivium-child.js +447 -0
- package/store-trivium.js +510 -0
- package/store.js +347 -0
- package/sweep.js +296 -0
- package/tools.js +507 -0
- package/trivium-runtime.js +1900 -0
- package/README.md +0 -3
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 保留期清扫:把 `egress.expireBefore` 从「模块能力」接到插件入口上。
|
|
3
|
+
*
|
|
4
|
+
* 启动后延迟跑一次,之后按间隔节流重跑。每个 workspace 都走**同一个进程级注册表**的门面
|
|
5
|
+
* (`runtime.withFacade`):TriviumDB 是文件级独占租约,另开句柄会与正在服务的门面撞
|
|
6
|
+
* `TDB_DATABASE_LOCKED`,所以这里绝不自己 open 库;workspace 名单来自写入路径维护的索引。
|
|
7
|
+
* 删除走与按来源删除**同一条**不可恢复路径。任何失败只记一行日志,绝不让插件或回合失败。
|
|
8
|
+
*
|
|
9
|
+
* 开关:`KANABO_MEMORY_EGRESS_SWEEP=0` 完全关闭;`KANABO_MEMORY_EGRESS_SWEEP_INTERVAL_MS`
|
|
10
|
+
* 覆盖间隔(默认 6 小时);`KANABO_MEMORY_EGRESS_SWEEP_DELAY_MS` 覆盖启动延迟(默认 2 秒,
|
|
11
|
+
* 验收设为 0)。审计默认写到库目录旁的 `egress-audit.jsonl`,可用
|
|
12
|
+
* `KANABO_MEMORY_EGRESS_AUDIT` 覆盖。
|
|
13
|
+
*/
|
|
14
|
+
import { existsSync } from 'node:fs'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
|
|
17
|
+
import { AUDIT_ENV, expireBefore } from './egress.js'
|
|
18
|
+
import * as defaultRuntime from './trivium-runtime.js'
|
|
19
|
+
import { triviumDir } from './store-trivium.js'
|
|
20
|
+
|
|
21
|
+
export const SWEEP_ENV = 'KANABO_MEMORY_EGRESS_SWEEP'
|
|
22
|
+
export const INTERVAL_ENV = 'KANABO_MEMORY_EGRESS_SWEEP_INTERVAL_MS'
|
|
23
|
+
export const DELAY_ENV = 'KANABO_MEMORY_EGRESS_SWEEP_DELAY_MS'
|
|
24
|
+
export const DEFAULT_INTERVAL_MS = 6 * 60 * 60 * 1000
|
|
25
|
+
export const DEFAULT_STARTUP_DELAY_MS = 2_000
|
|
26
|
+
|
|
27
|
+
function positiveInterval(value, fallback) {
|
|
28
|
+
const number = Number(value)
|
|
29
|
+
return Number.isInteger(number) && number > 0 ? number : fallback
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* 跑一轮清扫:对每个已知 workspace 调一次 `expireBefore`。
|
|
34
|
+
* @returns {Promise<{swept:number, deleted:number, errors:Array<{scope:string,code:string,message:string}>}>}
|
|
35
|
+
*/
|
|
36
|
+
export async function sweepExpired({ runtime = defaultRuntime, dir = triviumDir(), log = () => {}, now = Date.now(), auditPath } = {}) {
|
|
37
|
+
const errors = []
|
|
38
|
+
let swept = 0
|
|
39
|
+
let deleted = 0
|
|
40
|
+
for (const scope of runtime.knownWorkspaces({ dir })) {
|
|
41
|
+
try {
|
|
42
|
+
// 索引可能残留已删除的库;不先确认文件存在,withFacade 会把空库重建出来。
|
|
43
|
+
if (!existsSync(runtime.dbPathOf(scope, { dir }))) continue
|
|
44
|
+
const entry = await runtime.withFacade(scope, async (facade) => await expireBefore({ facade, now, auditPath }))
|
|
45
|
+
swept += 1
|
|
46
|
+
deleted += Number(entry?.deleted?.removed ?? 0)
|
|
47
|
+
} catch (error) {
|
|
48
|
+
errors.push({ scope, code: typeof error?.code === 'string' ? error.code : 'EGRESS_SWEEP', message: String(error?.message ?? error) })
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
for (const error of errors) log(`egress sweep: ${error.scope} failed (${error.code}): ${error.message}`)
|
|
52
|
+
return { swept, deleted, errors }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* 插件入口:启动一次(延迟、unref)+节流周期;返回 `{sweep, stop}` 供探针/宿主控制。
|
|
57
|
+
* `deps.enabled` / `deps.intervalMs` / `deps.startupDelayMs` / `deps.auditPath` / `deps.dir` 供验收注入。
|
|
58
|
+
*/
|
|
59
|
+
export function registerEgress(ctx, deps = {}) {
|
|
60
|
+
const log = typeof deps?.log === 'function' ? deps.log : () => {}
|
|
61
|
+
const runtime = deps?.runtime ?? defaultRuntime
|
|
62
|
+
const dir = deps?.dir ?? triviumDir()
|
|
63
|
+
const auditPath = typeof deps?.auditPath === 'string'
|
|
64
|
+
? deps.auditPath
|
|
65
|
+
: (process.env[AUDIT_ENV] ?? join(dir, 'egress-audit.jsonl'))
|
|
66
|
+
if (deps.enabled !== true && process.env[SWEEP_ENV] === '0') {
|
|
67
|
+
log('egress sweep: disabled by KANABO_MEMORY_EGRESS_SWEEP=0')
|
|
68
|
+
return { sweep: async () => ({ swept: 0, deleted: 0, errors: [], skipped: 'disabled' }), stop: () => {} }
|
|
69
|
+
}
|
|
70
|
+
const intervalMs = positiveInterval(deps.intervalMs ?? process.env[INTERVAL_ENV], DEFAULT_INTERVAL_MS)
|
|
71
|
+
const startupDelayMs = Number.isFinite(deps.startupDelayMs) && deps.startupDelayMs >= 0
|
|
72
|
+
? deps.startupDelayMs
|
|
73
|
+
: positiveInterval(process.env[DELAY_ENV], DEFAULT_STARTUP_DELAY_MS)
|
|
74
|
+
let stopped = false
|
|
75
|
+
let timer = null
|
|
76
|
+
let firstTimer = null
|
|
77
|
+
|
|
78
|
+
const run = async (kind) => {
|
|
79
|
+
if (stopped) return { swept: 0, deleted: 0, errors: [], skipped: 'stopped' }
|
|
80
|
+
try {
|
|
81
|
+
const result = await sweepExpired({ runtime, dir, log, auditPath })
|
|
82
|
+
if (result.swept > 0 || result.deleted > 0) {
|
|
83
|
+
log(`egress sweep (${kind}): workspaces=${result.swept} deleted=${result.deleted} errors=${result.errors.length}`)
|
|
84
|
+
}
|
|
85
|
+
return result
|
|
86
|
+
} catch (error) {
|
|
87
|
+
log(`egress sweep (${kind}) failed: ${error?.message ?? String(error)}; the turn continues`)
|
|
88
|
+
return { swept: 0, deleted: 0, errors: [{ scope: '*', code: 'EGRESS_SWEEP', message: String(error?.message ?? error) }] }
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const arm = () => {
|
|
93
|
+
timer = setInterval(() => {
|
|
94
|
+
void run('periodic')
|
|
95
|
+
}, intervalMs)
|
|
96
|
+
timer.unref?.()
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
firstTimer = setTimeout(() => {
|
|
100
|
+
firstTimer = null
|
|
101
|
+
void run('startup')
|
|
102
|
+
if (!stopped) arm()
|
|
103
|
+
}, startupDelayMs)
|
|
104
|
+
firstTimer.unref?.()
|
|
105
|
+
|
|
106
|
+
const stop = () => {
|
|
107
|
+
stopped = true
|
|
108
|
+
if (timer !== null) clearInterval(timer)
|
|
109
|
+
if (firstTimer !== null) clearTimeout(firstTimer)
|
|
110
|
+
timer = null
|
|
111
|
+
firstTimer = null
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
try {
|
|
115
|
+
if (typeof ctx?.effect === 'function') ctx.effect(() => stop)
|
|
116
|
+
else if (typeof ctx?.on === 'function') ctx.on('dispose', stop)
|
|
117
|
+
} catch (error) {
|
|
118
|
+
log(`egress sweep: cannot register cleanup (${error?.message ?? String(error)})`)
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return { sweep: () => run('manual'), stop, intervalMs, startupDelayMs }
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
export default registerEgress
|
package/serve.js
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
import { MAX_INJECT_BYTES, scopeOf } from './store.js'
|
|
2
|
+
import { getRecallContext, injectionMessage } from './recall.js'
|
|
3
|
+
import { buildPersonaFromMemory, renderPersona } from './persona.js'
|
|
4
|
+
import { scanWorkspace } from './trivium-runtime.js'
|
|
5
|
+
|
|
6
|
+
const DEDUPE_CAP = 500
|
|
7
|
+
const OWNED = new WeakSet()
|
|
8
|
+
const noop = () => {}
|
|
9
|
+
|
|
10
|
+
function userText(messages) {
|
|
11
|
+
for (let i = (messages?.length ?? 0) - 1; i >= 0; i -= 1) {
|
|
12
|
+
const m = messages[i]
|
|
13
|
+
if (m?.role !== 'user') continue
|
|
14
|
+
const text = (Array.isArray(m.content) ? m.content : [])
|
|
15
|
+
.filter((p) => p?.type === 'text')
|
|
16
|
+
.map((p) => p.text)
|
|
17
|
+
.join('\n')
|
|
18
|
+
.trim()
|
|
19
|
+
if (text !== '') return text
|
|
20
|
+
}
|
|
21
|
+
return ''
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function clipBytes(text, maxBytes) {
|
|
25
|
+
if (Buffer.byteLength(text, 'utf8') <= maxBytes) return text
|
|
26
|
+
let out = ''
|
|
27
|
+
for (const ch of text) {
|
|
28
|
+
if (Buffer.byteLength(out + ch, 'utf8') > maxBytes) break
|
|
29
|
+
out += ch
|
|
30
|
+
}
|
|
31
|
+
return out
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function makeHandler({
|
|
35
|
+
log = noop,
|
|
36
|
+
recall = getRecallContext,
|
|
37
|
+
personaProvider = null,
|
|
38
|
+
now = () => Date.now(),
|
|
39
|
+
} = {}) {
|
|
40
|
+
const served = new Map()
|
|
41
|
+
return async function preStep(payload, next) {
|
|
42
|
+
const decision = await next()
|
|
43
|
+
try {
|
|
44
|
+
if (decision?.kind !== 'enter') return decision
|
|
45
|
+
const session = payload?.agent?.session
|
|
46
|
+
const sessionId = typeof session?.id === 'string' ? session.id : ''
|
|
47
|
+
if (sessionId === '') return decision
|
|
48
|
+
const key = `${sessionId}:${payload?.turn ?? ''}`
|
|
49
|
+
if (served.has(key)) return decision
|
|
50
|
+
const direct = typeof payload?.prompt === 'string' ? payload.prompt.trim() : ''
|
|
51
|
+
const prompt = direct !== '' ? direct : userText(decision.messages)
|
|
52
|
+
if (prompt === '') return decision
|
|
53
|
+
let recallText = ''
|
|
54
|
+
if (process.env.KANABO_SERVE_RECALL !== '0') {
|
|
55
|
+
const r = await recall({ prompt, session })
|
|
56
|
+
recallText = typeof r?.text === 'string' ? r.text : ''
|
|
57
|
+
}
|
|
58
|
+
let personaText = ''
|
|
59
|
+
if (process.env.KANABO_SERVE_PERSONA !== '0' && typeof personaProvider === 'function') {
|
|
60
|
+
const p = await personaProvider({ prompt, session, now: now() })
|
|
61
|
+
personaText = typeof p === 'string' ? p : ''
|
|
62
|
+
}
|
|
63
|
+
let combined = [recallText, personaText].filter((s) => s !== '').join('\n\n')
|
|
64
|
+
if (combined === '') return decision
|
|
65
|
+
combined = clipBytes(combined, MAX_INJECT_BYTES)
|
|
66
|
+
served.set(key, true)
|
|
67
|
+
if (served.size > DEDUPE_CAP) served.delete(served.keys().next().value)
|
|
68
|
+
return { ...decision, messages: [...(decision.messages ?? []), injectionMessage(combined)] }
|
|
69
|
+
} catch (error) {
|
|
70
|
+
// A throwing pre-step handler fails the whole turn, so a failed injection
|
|
71
|
+
// must return the host's decision untouched.
|
|
72
|
+
log(`serve: injection skipped (${error?.message ?? String(error)})`)
|
|
73
|
+
return decision
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* 默认画像 provider(任务 55):从当前 workspace 的库构建画像并渲染成注入块。
|
|
80
|
+
*
|
|
81
|
+
* 为什么默认就要有它:任务 37 让 `serve.js` 成为 `agent/pre-step` 的唯一所有者,但默认
|
|
82
|
+
* `personaProvider` 为 null 时真实回合只注入召回、画像从不出现——「召回 + 画像成一块」只在
|
|
83
|
+
* 宿主显式接线时才成立。默认路径必须自己会组装画像。
|
|
84
|
+
*
|
|
85
|
+
* 数据来源:库里信封的 `node_metadata.persona`(`signalsFromEnvelope` 只认这种显式来源,
|
|
86
|
+
* 绝不在正文里猜)。因此按 workspace 扫描一次,把原始信封交给 `buildPersonaFromMemory`。
|
|
87
|
+
* 扫描代价按 workspace 计,与召回共用同一门面(`trivium-runtime` 的进程级注册表)。
|
|
88
|
+
*
|
|
89
|
+
* 绝不让画像拖垮回合:任何失败只记一行日志并返回空串,调用方据此只注入召回。
|
|
90
|
+
*/
|
|
91
|
+
export function makeDefaultPersonaProvider({
|
|
92
|
+
log = noop,
|
|
93
|
+
now = () => Date.now(),
|
|
94
|
+
scan = scanWorkspace,
|
|
95
|
+
build = buildPersonaFromMemory,
|
|
96
|
+
render = renderPersona,
|
|
97
|
+
} = {}) {
|
|
98
|
+
return async function defaultPersonaProvider({ session } = {}) {
|
|
99
|
+
try {
|
|
100
|
+
const scope = scopeOf(session)
|
|
101
|
+
const scanned = await scan(scope)
|
|
102
|
+
const rows = Array.isArray(scanned?.rows) ? scanned.rows : []
|
|
103
|
+
const envelopes = rows
|
|
104
|
+
.map((row) => row?.payload?.envelope)
|
|
105
|
+
.filter((envelope) => envelope !== null && typeof envelope === 'object' && !Array.isArray(envelope))
|
|
106
|
+
// 没有信封就连构建都省掉:空库是常态,渲染本来也只会得到空串。
|
|
107
|
+
if (envelopes.length === 0) return ''
|
|
108
|
+
const at = now()
|
|
109
|
+
const text = render(build({ scope, now: at, envelopes }), { now: at })
|
|
110
|
+
return typeof text === 'string' ? text : ''
|
|
111
|
+
} catch (error) {
|
|
112
|
+
// 在 provider 内部吞掉异常,而不是交给外层 handler 的 catch:
|
|
113
|
+
// 外层 catch 会连召回一起丢掉,而画像失败只该降级为「仅召回」。
|
|
114
|
+
log(`serve: persona skipped (${error?.message ?? String(error)})`)
|
|
115
|
+
return ''
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function registerServe(ctx, deps = {}) {
|
|
121
|
+
if (OWNED.has(ctx)) return
|
|
122
|
+
OWNED.add(ctx)
|
|
123
|
+
const log = deps.log ?? noop
|
|
124
|
+
const handler = makeHandler({
|
|
125
|
+
log,
|
|
126
|
+
recall: deps.recall ?? getRecallContext,
|
|
127
|
+
// 显式传入的 provider 永远赢;没传就用默认画像 provider(任务 55)。
|
|
128
|
+
personaProvider: deps.personaProvider ?? makeDefaultPersonaProvider({ log }),
|
|
129
|
+
})
|
|
130
|
+
if (typeof ctx.on === 'function') ctx.on('agent/pre-step', handler, { prepend: true })
|
|
131
|
+
if (typeof ctx.effect === 'function') {
|
|
132
|
+
ctx.effect(() => async () => {
|
|
133
|
+
OWNED.delete(ctx)
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export default registerServe
|