@onigeya/dsh-kanabo-memory 0.0.0-stage → 0.1.0
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 +304 -0
- package/backfill-vectors.js +125 -0
- package/contract.js +114 -0
- package/cursor.js +116 -0
- package/egress.js +788 -0
- package/embed-child.js +142 -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 +153 -0
- package/migrate.js +1722 -0
- package/package.json +48 -3
- package/persona.js +949 -0
- package/query-window.js +561 -0
- package/recall-trivium.js +873 -0
- package/recall.js +113 -0
- package/remove-legacy.mjs +720 -0
- package/serve.js +138 -0
- package/store-trivium-child.js +447 -0
- package/store-trivium.js +507 -0
- package/store.js +347 -0
- package/sweep.js +296 -0
- package/tools.js +423 -0
- package/trivium-runtime.js +1794 -0
- package/README.md +0 -3
package/tools.js
ADDED
|
@@ -0,0 +1,423 @@
|
|
|
1
|
+
import { MAX_ENTRIES, MAX_ENTRY_BYTES, scopeOf, textOf, tokens } from './store.js'
|
|
2
|
+
import { validateEnvelope } from './envelope.js'
|
|
3
|
+
import { applySignal, createPersona, signalsFromEnvelope } from './persona.js'
|
|
4
|
+
import * as defaultRuntime from './trivium-runtime.js'
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 金棒记忆的三个模型可调用工具:记忆(remember)、召回(recall)、推理(reflect)。
|
|
8
|
+
*
|
|
9
|
+
* 两条实测约束决定了这里的形状,改动前请先读事实文件(`.omo/evidence/dsh-kanabo-memory-measured-facts.md`):
|
|
10
|
+
* §A 本插件不得 import 任何 DSH 包、也不得用其工具定义辅助函数——链接安装下带 DSH import 的形态无法解析;
|
|
11
|
+
* 代价是原始 JSON Schema 工具要自己校验入参(`docs/cookbook/adding-a-tool.md`)。
|
|
12
|
+
* §B/§G 被校验的输出 schema 里任何层级都不得出现 `required`,否则注册抛
|
|
13
|
+
* `JsonSchemaError`,该行只留一条 `did not activate` 警告,运行时看起来就是「没有这个工具」。
|
|
14
|
+
* `output.render` 则是注册的必需字段,缺了直接抛 `TypeError`。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const DEFAULT_RECALL_LIMIT = 10
|
|
18
|
+
const DEFAULT_REFLECT_LIMIT = 20
|
|
19
|
+
const MAX_LIMIT = MAX_ENTRIES
|
|
20
|
+
/**
|
|
21
|
+
* 工具路径召回的总期限:比 `recall-trivium.js` 的 5s 默认宽,因为向量臂冷启动要加载模型。
|
|
22
|
+
* 真正的嵌入预算在 `EMBED_SERVICE_TIMEOUT_MS`(6s)——超出后向量臂降级、文本+图照常返回。
|
|
23
|
+
*/
|
|
24
|
+
const RECALL_TIMEOUT_MS = 15_000
|
|
25
|
+
/** 降级重试(文本+图)沿用 pre-52 的 5s 默认:它不再有机会等模型,没理由也给 15s。 */
|
|
26
|
+
const RETRY_TIMEOUT_MS = 5_000
|
|
27
|
+
|
|
28
|
+
function toolError(code, message) {
|
|
29
|
+
const error = new Error(message)
|
|
30
|
+
error.code = code
|
|
31
|
+
return error
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* 取一条入库向量:失败/降级/超时都折成 `{ vector: null, reason }`,绝不抛错。
|
|
36
|
+
* 文本与回填 worker 完全同一段(`embedTextOf(payload)`)、同一个 `passage: ` 前缀,
|
|
37
|
+
* 这样 remember 现在写进去的向量和以后回填算出来的向量是同一个口径。
|
|
38
|
+
*/
|
|
39
|
+
async function embedSafely(runtime, text) {
|
|
40
|
+
try {
|
|
41
|
+
const { PASSAGE_PREFIX } = await import('./recall-trivium.js')
|
|
42
|
+
const result = await runtime.embedTexts([text], { prefix: PASSAGE_PREFIX })
|
|
43
|
+
const vector = result.vectors?.[0] ?? null
|
|
44
|
+
if (vector === null) return { vector: null, reason: result.reason ?? 'vector_unavailable', ms: result.ms }
|
|
45
|
+
return { vector, reason: null, ms: result.ms }
|
|
46
|
+
} catch (error) {
|
|
47
|
+
return {
|
|
48
|
+
vector: null,
|
|
49
|
+
reason: typeof error?.code === 'string' ? error.code : 'KANABO_MEMORY_EMBED',
|
|
50
|
+
ms: 0,
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** 磁盘降级的入口已随 JSON 写入路径退休:三个工具与活写入共用 TriviumDB 的同一门面。 */
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* `sessionId` 是条目身份的一维(去重键),缺失说明调用不在 agent 会话内,
|
|
59
|
+
* 此时照实报错,而不是写入一个无主条目。turn 读不到就不猜,store.js 会记为 null。
|
|
60
|
+
*/
|
|
61
|
+
function identityOf(exec, ctx) {
|
|
62
|
+
const session = exec?.agent?.session
|
|
63
|
+
const sessionId = session?.id
|
|
64
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) {
|
|
65
|
+
throw toolError(
|
|
66
|
+
'KANABO_MEMORY_NO_SESSION',
|
|
67
|
+
'工具需要一个 agent 会话上下文(exec.agent.session.id),但当前调用没有可用会话;请从一次正常的 agent 回合里调用。')
|
|
68
|
+
}
|
|
69
|
+
const scope = scopeOf(session)
|
|
70
|
+
let turn = null
|
|
71
|
+
try {
|
|
72
|
+
const boundary = ctx.get?.('agents')?.turnBoundaryOf?.(session)
|
|
73
|
+
if (boundary !== undefined && Number.isSafeInteger(boundary.lastTurn)) turn = boundary.lastTurn
|
|
74
|
+
} catch {
|
|
75
|
+
// agents 服务缺席或投影未就绪:身份仍由 scope + sessionId 携带。
|
|
76
|
+
}
|
|
77
|
+
return { scope, sessionId, turn }
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function validatedText(raw) {
|
|
81
|
+
if (typeof raw !== 'string' || raw.trim().length === 0) {
|
|
82
|
+
throw toolError(
|
|
83
|
+
'KANABO_MEMORY_TEXT_BLANK',
|
|
84
|
+
`remember: 参数 "text" 不能为空或全空白(收到了 ${JSON.stringify(raw)});请给出要记住的事实正文。`)
|
|
85
|
+
}
|
|
86
|
+
const bytes = Buffer.byteLength(raw, 'utf8')
|
|
87
|
+
if (bytes > MAX_ENTRY_BYTES) {
|
|
88
|
+
throw toolError(
|
|
89
|
+
'KANABO_MEMORY_TEXT_TOO_LARGE',
|
|
90
|
+
`remember: 参数 "text" 为 ${bytes} 字节,超过单条上限 ${MAX_ENTRY_BYTES} 字节;请拆成更小的条目后重试。`)
|
|
91
|
+
}
|
|
92
|
+
return { text: raw, bytes }
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function optionalString(raw, field, tool) {
|
|
96
|
+
if (raw === undefined) return undefined
|
|
97
|
+
if (typeof raw !== 'string') {
|
|
98
|
+
throw toolError('KANABO_MEMORY_BAD_ARGUMENT', `${tool}: 参数 "${field}" 必须是字符串(收到了 ${JSON.stringify(raw)})。`)
|
|
99
|
+
}
|
|
100
|
+
if (Buffer.byteLength(raw, 'utf8') > MAX_ENTRY_BYTES) {
|
|
101
|
+
throw toolError(
|
|
102
|
+
'KANABO_MEMORY_ARGUMENT_TOO_LARGE',
|
|
103
|
+
`${tool}: 参数 "${field}" 超过 ${MAX_ENTRY_BYTES} 字节上限;请缩短后重试。`)
|
|
104
|
+
}
|
|
105
|
+
return raw
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function validatedLimit(raw, tool, fallback) {
|
|
109
|
+
if (raw === undefined) return fallback
|
|
110
|
+
if (!Number.isInteger(raw) || raw < 1 || raw > MAX_LIMIT) {
|
|
111
|
+
throw toolError(
|
|
112
|
+
'KANABO_MEMORY_LIMIT_RANGE',
|
|
113
|
+
`${tool}: 参数 "limit" 必须是 1..${MAX_LIMIT} 之间的整数(收到了 ${JSON.stringify(raw)})。`)
|
|
114
|
+
}
|
|
115
|
+
return raw
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
const entryView = (entry) => ({
|
|
119
|
+
id: String(entry?.id ?? ''), topic: String(entry?.topic ?? ''), text: textOf(entry),
|
|
120
|
+
ts: Number.isSafeInteger(Number(entry?.ts)) ? Number(entry.ts) : 0,
|
|
121
|
+
})
|
|
122
|
+
|
|
123
|
+
/** 嵌套 array-of-object 的条目 schema:照 §B/§G,带 `required` 会让整行不激活。 */
|
|
124
|
+
const ENTRY_ITEM_SCHEMA = {
|
|
125
|
+
type: 'object',
|
|
126
|
+
additionalProperties: false,
|
|
127
|
+
properties: {
|
|
128
|
+
id: { type: 'string', description: '条目 id' },
|
|
129
|
+
topic: { type: 'string', description: '条目的主题标签,可能为空字符串' },
|
|
130
|
+
text: { type: 'string', description: '条目正文' },
|
|
131
|
+
ts: { type: 'integer', description: '写入时间戳(Unix 毫秒)' },
|
|
132
|
+
},
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* remember 的可选画像信号:`{ path, value, confidence }` 三键,与 `signalsFromEnvelope` 读的
|
|
137
|
+
* `node_metadata.persona` 完全同一形状——来源不写在信号里,而由信封本身派生
|
|
138
|
+
* (`{ kind: 'envelope', ref: <记忆 id>, at: <ts>, source_type: 'CONVERSATION' }`)。
|
|
139
|
+
*/
|
|
140
|
+
const PERSONA_SIGNAL_SCHEMA = {
|
|
141
|
+
type: 'object',
|
|
142
|
+
additionalProperties: false,
|
|
143
|
+
properties: {
|
|
144
|
+
path: { type: 'string', description: '画像字段路径,必须是 persona.js FIELD_SCHEMA 声明的路径(user.* / self.*)' },
|
|
145
|
+
value: { description: '字段值;按该字段的 schema 校验(字符串/枚举/数字),越界会被拒' },
|
|
146
|
+
confidence: { type: 'number', description: '0..1 之间的置信度' },
|
|
147
|
+
},
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* 把 remember 的可选 `persona` 挂到信封的 `node_metadata.persona` 上,**先按真实消费路径空跑**:
|
|
152
|
+
* 同一份 `signalsFromEnvelope` → `applySignal` 会拒绝未知路径、类型/范围越界、以及该字段不接受
|
|
153
|
+
* `envelope` 来源种类的信号。任何一条非法就整块丢弃、只记一行日志,记忆正文照常写入——
|
|
154
|
+
* 画像是最佳努力,绝不让 remember 失败,也绝不让非法信号落库。
|
|
155
|
+
* 没提供(或提供空数组)时不写 `persona` 键,不产生空信号。
|
|
156
|
+
*/
|
|
157
|
+
function attachPersona(envelope, rawPersona, log) {
|
|
158
|
+
if (rawPersona === undefined || rawPersona === null) return envelope
|
|
159
|
+
const items = Array.isArray(rawPersona) ? rawPersona : [rawPersona]
|
|
160
|
+
if (items.length === 0) return envelope
|
|
161
|
+
try {
|
|
162
|
+
const candidate = validateEnvelope({
|
|
163
|
+
...envelope,
|
|
164
|
+
node_metadata: { ...envelope.node_metadata, persona: items },
|
|
165
|
+
})
|
|
166
|
+
let scratch = createPersona({ scope: candidate.session?.scope ?? 'unknown-workspace', now: candidate.ts })
|
|
167
|
+
for (const signal of signalsFromEnvelope(candidate)) {
|
|
168
|
+
scratch = applySignal(scratch, signal, { now: candidate.ts }).persona
|
|
169
|
+
}
|
|
170
|
+
return candidate
|
|
171
|
+
} catch (error) {
|
|
172
|
+
log(`remember: 丢弃非法画像信号(${typeof error?.code === 'string' ? error.code : 'error'}: ${error?.message ?? String(error)});记忆正文仍照常写入`)
|
|
173
|
+
return envelope
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
export function registerTools(ctx, deps) {
|
|
178
|
+
if (ctx?.tools === undefined || typeof ctx.tools.register !== 'function') {
|
|
179
|
+
throw toolError(
|
|
180
|
+
'KANABO_MEMORY_NO_TOOLS',
|
|
181
|
+
'kanabo-memory tools: ctx.tools.register 不可用(缺少 tools 服务);请确认宿主提供了 tools 服务,且本插件在 inject 中声明了 "tools"。')
|
|
182
|
+
}
|
|
183
|
+
const runtime = deps?.runtime ?? defaultRuntime
|
|
184
|
+
const log = typeof deps?.log === 'function' ? deps.log : () => {}
|
|
185
|
+
|
|
186
|
+
const remember = {
|
|
187
|
+
name: 'remember',
|
|
188
|
+
description:
|
|
189
|
+
'把一条事实写入当前 workspace 的记忆存储。记忆是按工作目录分域的持久记录,'
|
|
190
|
+
+ '同一 workspace 的后续会话都能召回它;写入后可用 recall 检索、用 reflect 查看存储概况。'
|
|
191
|
+
+ 'text 是唯一必填字段,单条上限 4096 字节;topic 是可选的分类标签。'
|
|
192
|
+
+ 'persona 可选:随这条记忆写入结构化画像信号({ path, value, confidence } 或其数组),'
|
|
193
|
+
+ '只有 persona.js 声明过的字段与来源合法的信号才会落库,非法信号被丢弃而记忆照常保存。',
|
|
194
|
+
parameters: {
|
|
195
|
+
type: 'object',
|
|
196
|
+
properties: {
|
|
197
|
+
text: { type: 'string', description: '要记住的事实正文(必填,非空白,≤4096 字节)' },
|
|
198
|
+
topic: { type: 'string', description: '可选的主题标签,便于按主题过滤与反思' },
|
|
199
|
+
persona: {
|
|
200
|
+
oneOf: [
|
|
201
|
+
PERSONA_SIGNAL_SCHEMA,
|
|
202
|
+
{ type: 'array', items: PERSONA_SIGNAL_SCHEMA },
|
|
203
|
+
],
|
|
204
|
+
description: '可选的画像信号:一个 { path, value, confidence } 对象或这样的数组;'
|
|
205
|
+
+ 'path 必须是 persona.js 声明过的字段(FIELD_PATHS)。来源由信封本身提供'
|
|
206
|
+
+ '(kind=envelope),没有合法信号就不写 persona 键。',
|
|
207
|
+
},
|
|
208
|
+
},
|
|
209
|
+
required: ['text'],
|
|
210
|
+
},
|
|
211
|
+
output: {
|
|
212
|
+
schema: {
|
|
213
|
+
type: 'object',
|
|
214
|
+
additionalProperties: false,
|
|
215
|
+
properties: {
|
|
216
|
+
id: { type: 'string', description: '新条目的 id' },
|
|
217
|
+
topic: { type: 'string', description: '保存的 topic,可能为空字符串' },
|
|
218
|
+
bytes: { type: 'integer', description: 'text 的 UTF-8 字节数' },
|
|
219
|
+
totalEntries: { type: 'integer', description: '该 workspace 存储中的总条目数' },
|
|
220
|
+
storePath: { type: 'string', description: '存储文件路径;降级到内存镜像时以 memory: 开头' },
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
render(_args, value) {
|
|
224
|
+
return [{
|
|
225
|
+
type: 'text',
|
|
226
|
+
text: `已记住 ${value.bytes} 字节(topic=${value.topic || '无'},当前共 ${value.totalEntries} 条)→ ${value.storePath}`,
|
|
227
|
+
}]
|
|
228
|
+
},
|
|
229
|
+
},
|
|
230
|
+
async execute(args, exec) {
|
|
231
|
+
const { scope, sessionId, turn } = identityOf(exec, ctx)
|
|
232
|
+
const { text, bytes } = validatedText(args?.text)
|
|
233
|
+
const topic = optionalString(args?.topic, 'topic', 'remember') ?? ''
|
|
234
|
+
const baseEnvelope = validateEnvelope({
|
|
235
|
+
id: runtime.entryId(),
|
|
236
|
+
source_type: 'CONVERSATION',
|
|
237
|
+
session: { id: sessionId, scope },
|
|
238
|
+
turn: Number.isSafeInteger(turn) && turn >= 0 ? turn : 0,
|
|
239
|
+
ts: Date.now(),
|
|
240
|
+
evidence_trace: { kind: 'EXTRACTED', source: 'remember-tool', detail: { tool: 'remember' } },
|
|
241
|
+
node_metadata: { topic, scope, bytes },
|
|
242
|
+
dynamic_relations: [],
|
|
243
|
+
text,
|
|
244
|
+
})
|
|
245
|
+
// 画像信号是随记忆写的结构化声明,来源由信封 id/ts/source_type 提供;非法整块丢弃,记忆照写。
|
|
246
|
+
const envelope = attachPersona(baseEnvelope, args?.persona, log)
|
|
247
|
+
// 入库向量就地算(选的是「单条内联回填」那一支,只是把向量放进同一次 batch,见任务 52 证据):
|
|
248
|
+
// 与回填 worker 完全同一段文本、同一个 `passage: ` 前缀,代价以 `EMBED_SERVICE_TIMEOUT_MS` 为上限。
|
|
249
|
+
// 失败不阻塞写入:照原样写零向量,下一次回填再补——与任务 50 的失败语义一致。
|
|
250
|
+
const embedText = runtime.embedTextOf(runtime.payloadFor(scope, envelope))
|
|
251
|
+
const embedded = await embedSafely(runtime, embedText)
|
|
252
|
+
if (embedded.vector === null) {
|
|
253
|
+
log(`remember: 条目 ${envelope.id} 以零向量写入(${embedded.reason});向量回填会稍后补上`)
|
|
254
|
+
}
|
|
255
|
+
const written = await runtime.withLock(scope, async () => {
|
|
256
|
+
const scan = await runtime.scanWorkspace(scope)
|
|
257
|
+
runtime.assertQuota({ count: scan.count, bytes: scan.bytes }, { entries: 1, bytes })
|
|
258
|
+
await runtime.appendEnvelopes(scope, [envelope], {
|
|
259
|
+
vectors: embedded.vector === null ? undefined : [embedded.vector],
|
|
260
|
+
})
|
|
261
|
+
return { total: scan.count + 1 }
|
|
262
|
+
})
|
|
263
|
+
return { id: envelope.id, topic, bytes, totalEntries: written.total, storePath: runtime.dbPathOf(scope) }
|
|
264
|
+
},
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const recall = {
|
|
268
|
+
name: 'recall',
|
|
269
|
+
description:
|
|
270
|
+
'从当前 workspace 的记忆里检索与 query 相关的事实(文本 BM25 + 向量语义 + 图扩散的相关度排序)。'
|
|
271
|
+
+ '存储按工作目录分域、跨会话共享;不提供 query 时返回最近记住的事实。'
|
|
272
|
+
+ '没有匹配是正常的成功结果(entries 为空数组),不是错误。',
|
|
273
|
+
parameters: {
|
|
274
|
+
type: 'object',
|
|
275
|
+
properties: {
|
|
276
|
+
query: { type: 'string', description: '检索词;省略时按时间倒序返回最近的事实' },
|
|
277
|
+
limit: { type: 'integer', description: `最多返回多少条(1..${MAX_LIMIT},默认 ${DEFAULT_RECALL_LIMIT})` },
|
|
278
|
+
},
|
|
279
|
+
},
|
|
280
|
+
output: {
|
|
281
|
+
schema: {
|
|
282
|
+
type: 'object',
|
|
283
|
+
additionalProperties: false,
|
|
284
|
+
properties: {
|
|
285
|
+
entries: { type: 'array', items: ENTRY_ITEM_SCHEMA, description: '命中的条目,最多 limit 条' },
|
|
286
|
+
total: { type: 'integer', description: '全部命中的条目数(含被 limit 截断的部分)' },
|
|
287
|
+
truncated: { type: 'boolean', description: 'total 是否大于返回的 entries 数量' },
|
|
288
|
+
},
|
|
289
|
+
},
|
|
290
|
+
render(_args, value) {
|
|
291
|
+
if (value.entries.length === 0) {
|
|
292
|
+
return [{ type: 'text', text: '没有匹配的记忆条目。' }]
|
|
293
|
+
}
|
|
294
|
+
const lines = value.entries.map((entry) => `- [${entry.topic || '无主题'}] ${entry.text}`)
|
|
295
|
+
const suffix = value.truncated ? `(共 ${value.total} 条,已截断)` : ''
|
|
296
|
+
return [{ type: 'text', text: `召回 ${value.entries.length} 条记忆${suffix}:\n${lines.join('\n')}` }]
|
|
297
|
+
},
|
|
298
|
+
},
|
|
299
|
+
async execute(args, exec) {
|
|
300
|
+
const { scope } = identityOf(exec, ctx)
|
|
301
|
+
const query = optionalString(args?.query, 'query', 'recall')
|
|
302
|
+
const limit = validatedLimit(args?.limit, 'recall', DEFAULT_RECALL_LIMIT)
|
|
303
|
+
const asked = typeof query === 'string' && query.trim().length > 0
|
|
304
|
+
if (asked && tokens(query).length === 0) return { entries: [], total: 0, truncated: false }
|
|
305
|
+
if (!asked) {
|
|
306
|
+
const scan = await runtime.scanWorkspace(scope)
|
|
307
|
+
const newestFirst = [...scan.entries].sort((left, right) => (right.ts || 0) - (left.ts || 0))
|
|
308
|
+
const entries = newestFirst.slice(0, limit).map(entryView)
|
|
309
|
+
return { entries, total: scan.count, truncated: scan.count > entries.length }
|
|
310
|
+
}
|
|
311
|
+
const { createTriviumRecall } = await import('./recall-trivium.js')
|
|
312
|
+
const runRecall = async (arms, embedder, timeoutMs = RECALL_TIMEOUT_MS) => runtime.withFacade(scope, async (facade) => {
|
|
313
|
+
const recall = createTriviumRecall({ store: facade, arms, embedder, timeoutMs })
|
|
314
|
+
try {
|
|
315
|
+
return await recall.recall(query, { limit, budgetChars: Number.MAX_SAFE_INTEGER })
|
|
316
|
+
} finally {
|
|
317
|
+
await recall.close()
|
|
318
|
+
}
|
|
319
|
+
})
|
|
320
|
+
const textGraph = { text: true, vector: false, graph: true }
|
|
321
|
+
let result
|
|
322
|
+
let vectorFailure = null
|
|
323
|
+
try {
|
|
324
|
+
result = await runRecall({ text: true, vector: true, graph: true }, runtime.createServiceEmbedder())
|
|
325
|
+
const vectorArm = result.arms?.vector
|
|
326
|
+
if (vectorArm !== undefined && vectorArm.ok === false) {
|
|
327
|
+
vectorFailure = `${vectorArm.error?.code ?? 'KANABO_RECALL_ARM'}: ${vectorArm.error?.message ?? ''}`
|
|
328
|
+
} else if (typeof vectorArm?.degraded === 'string') {
|
|
329
|
+
vectorFailure = vectorArm.degraded
|
|
330
|
+
}
|
|
331
|
+
} catch (error) {
|
|
332
|
+
// 向量臂(含冷启动加载)失败不得让工具失败:退回文本+图,结果照常返回,失败如实记日志。
|
|
333
|
+
vectorFailure = `${typeof error?.code === 'string' ? error.code : 'KANABO_RECALL'}: ${String(error?.message ?? error)}`
|
|
334
|
+
result = await runRecall(textGraph, null, RETRY_TIMEOUT_MS)
|
|
335
|
+
}
|
|
336
|
+
if (vectorFailure !== null) {
|
|
337
|
+
log(`recall: 向量臂降级(${vectorFailure});已用文本+图返回 ${result.hits.length} 条`)
|
|
338
|
+
}
|
|
339
|
+
const meta = await runtime.readByNodeIds(scope, result.hits.map((hit) => hit.nodeId))
|
|
340
|
+
const entries = result.hits.map((hit) => {
|
|
341
|
+
const row = meta.get(hit.nodeId)
|
|
342
|
+
return {
|
|
343
|
+
id: String(hit.id ?? row?.id ?? ''),
|
|
344
|
+
topic: String(row?.topic ?? ''),
|
|
345
|
+
text: typeof hit.text === 'string' && hit.text.length > 0 ? hit.text : String(row?.text ?? ''),
|
|
346
|
+
ts: Number.isSafeInteger(Number(hit.ts)) ? Number(hit.ts) : Number(row?.ts ?? 0),
|
|
347
|
+
}
|
|
348
|
+
})
|
|
349
|
+
const total = Math.max(Number(result.candidates) || 0, entries.length)
|
|
350
|
+
return { entries, total, truncated: total > entries.length }
|
|
351
|
+
},
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
const reflect = {
|
|
355
|
+
name: 'reflect',
|
|
356
|
+
description:
|
|
357
|
+
'只读地审视当前 workspace 记忆存储里已经记下了什么:条目数、总字节数、最新条目时间,'
|
|
358
|
+
+ '并返回最新的若干条条目。reflect 绝不修改存储;与 recall 的按相关度检索不同,'
|
|
359
|
+
+ '它回答的是「记忆的概况与内容」这个问题。',
|
|
360
|
+
parameters: {
|
|
361
|
+
type: 'object',
|
|
362
|
+
properties: {
|
|
363
|
+
topic: { type: 'string', description: '只统计包含该主题/文本的条目;省略或空白时统计全部' },
|
|
364
|
+
limit: { type: 'integer', description: `最多返回多少条(1..${MAX_LIMIT},默认 ${DEFAULT_REFLECT_LIMIT})` },
|
|
365
|
+
},
|
|
366
|
+
},
|
|
367
|
+
output: {
|
|
368
|
+
schema: {
|
|
369
|
+
type: 'object',
|
|
370
|
+
additionalProperties: false,
|
|
371
|
+
properties: {
|
|
372
|
+
count: { type: 'integer', description: '统计范围内的条目数' },
|
|
373
|
+
bytes: { type: 'integer', description: '统计范围内正文的 UTF-8 总字节数' },
|
|
374
|
+
newestAt: {
|
|
375
|
+
oneOf: [{ type: 'integer' }, { type: 'null' }],
|
|
376
|
+
description: '最新条目的写入时间戳(Unix 毫秒);没有条目时为 null',
|
|
377
|
+
},
|
|
378
|
+
entries: { type: 'array', items: ENTRY_ITEM_SCHEMA, description: '最新的最多 limit 条条目' },
|
|
379
|
+
storePath: { type: 'string', description: '存储文件路径;降级到内存镜像时以 memory: 开头' },
|
|
380
|
+
},
|
|
381
|
+
},
|
|
382
|
+
render(_args, value) {
|
|
383
|
+
const lines = value.entries.map((entry) => `- [${entry.topic || '无主题'}] ${entry.text}`)
|
|
384
|
+
return [{
|
|
385
|
+
type: 'text',
|
|
386
|
+
text: `记忆存储:${value.count} 条 / ${value.bytes} 字节,最新 ${value.newestAt ?? '无'} → ${value.storePath}`
|
|
387
|
+
+ `\nentries:\n${lines.length === 0 ? '(空)' : lines.join('\n')}`,
|
|
388
|
+
}]
|
|
389
|
+
},
|
|
390
|
+
},
|
|
391
|
+
async execute(args, exec) {
|
|
392
|
+
const { scope } = identityOf(exec, ctx)
|
|
393
|
+
const topic = optionalString(args?.topic, 'topic', 'reflect')
|
|
394
|
+
const limit = validatedLimit(args?.limit, 'reflect', DEFAULT_REFLECT_LIMIT)
|
|
395
|
+
const scan = await runtime.scanWorkspace(scope)
|
|
396
|
+
const all = scan.entries
|
|
397
|
+
const needle = typeof topic === 'string' ? topic.trim().toLowerCase() : ''
|
|
398
|
+
// 只读:filter/sort/map 都产生新数组,绝不回写任何存储。
|
|
399
|
+
const scoped = needle.length === 0
|
|
400
|
+
? [...all]
|
|
401
|
+
: all.filter((entry) => String(entry.topic ?? '').toLowerCase().includes(needle)
|
|
402
|
+
|| String(entry.text ?? '').toLowerCase().includes(needle))
|
|
403
|
+
const newestFirst = scoped.sort((left, right) => (right.ts || 0) - (left.ts || 0))
|
|
404
|
+
const entries = newestFirst.slice(0, limit).map(entryView)
|
|
405
|
+
let bytes = 0
|
|
406
|
+
let newestAt = null
|
|
407
|
+
for (const entry of scoped) {
|
|
408
|
+
bytes += Buffer.byteLength(String(entry.text ?? ''), 'utf8')
|
|
409
|
+
const ts = Number(entry.ts)
|
|
410
|
+
if (Number.isSafeInteger(ts) && (newestAt === null || ts > newestAt)) newestAt = ts
|
|
411
|
+
}
|
|
412
|
+
return {
|
|
413
|
+
count: needle.length === 0 ? scan.count : scoped.length,
|
|
414
|
+
bytes: needle.length === 0 ? scan.bytes : bytes,
|
|
415
|
+
newestAt,
|
|
416
|
+
entries,
|
|
417
|
+
storePath: runtime.dbPathOf(scope),
|
|
418
|
+
}
|
|
419
|
+
},
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
for (const tool of [remember, recall, reflect]) ctx.tools.register(tool)
|
|
423
|
+
}
|