dsh-memu-memory 1.2.3 → 1.2.4
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/AGENTS.md +2 -1
- package/README.md +3 -15
- package/README.zh.md +3 -15
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +1 -1
- package/docs/env-and-commands.md +48 -6
- package/docs/troubleshooting.md +41 -0
- package/lib/binding-diagnostics.js +1 -1
- package/lib/client.js +71 -10
- package/lib/embedding-catalog.js +416 -138
- package/lib/embedding-download.js +36 -11
- package/lib/inject.js +99 -3
- package/lib/local-embedding-manager.js +3 -2
- package/lib/local-embedding-protocol.js +40 -3
- package/lib/local-embedding-worker.js +36 -6
- package/lib/local-vector-service.js +18 -4
- package/lib/memu.js +15 -7
- package/lib/private.js +25 -5
- package/lib/rpc.js +4 -1
- package/lib/state.js +81 -0
- package/package.json +3 -2
- package/scripts/drive-session.mjs +19 -8
- package/scripts/simulate-injection.mjs +298 -0
- package/tests/client-render.test.mjs +56 -1
- package/tests/consolidation-fork.test.mjs +14 -1
- package/tests/drive-session.test.mjs +152 -0
- package/tests/embedding-catalog.test.mjs +116 -8
- package/tests/embedding-download.test.mjs +97 -2
- package/tests/embedding-runtime.test.mjs +21 -13
- package/tests/injection-rollback.test.mjs +230 -0
- package/tests/local-embedding-env.test.mjs +51 -0
- package/tests/local-embedding-manager.test.mjs +18 -0
- package/tests/local-embedding-protocol.test.mjs +28 -2
- package/tests/local-embedding-worker.test.mjs +94 -0
- package/tests/simulate-injection.test.mjs +76 -0
- package/tests/vector-profile.test.mjs +28 -4
|
@@ -4,6 +4,7 @@ import crypto from 'node:crypto'
|
|
|
4
4
|
import {
|
|
5
5
|
getEmbeddingCatalog,
|
|
6
6
|
getEmbeddingModel,
|
|
7
|
+
PROVIDERS,
|
|
7
8
|
readOnnxGraphHeader,
|
|
8
9
|
resolveEmbeddingSources,
|
|
9
10
|
validateEmbeddingManifest,
|
|
@@ -23,7 +24,9 @@ export const DOWNLOAD_STATES = Object.freeze(['unknown', 'absent', 'downloading'
|
|
|
23
24
|
const INSTALL_RECORD = 'installed.json'
|
|
24
25
|
const STAGING_DIR = '.staging'
|
|
25
26
|
const TRASH_DIR = '.trash'
|
|
26
|
-
|
|
27
|
+
// 单文件上限。512 MiB 装不下已经逐字节核实过的 Qwen3-Embedding int8 图(600,223,343 B),
|
|
28
|
+
// 所以按「最大的一条 pin 住制品 + 余量」定;目录条目仍各自带 exact bytes,超限一律拒。
|
|
29
|
+
const DEFAULT_MAX_FILE_BYTES = 1024 * 1024 * 1024
|
|
27
30
|
|
|
28
31
|
function fail(code, message, extra) {
|
|
29
32
|
const error = new Error(message)
|
|
@@ -99,10 +102,13 @@ export async function verifyStagedArtifacts({ entry, dir }) {
|
|
|
99
102
|
const config = JSON.parse(configBytes.toString('utf8'))
|
|
100
103
|
if (config.hidden_size !== entry.dimension) throw new Error(`config.hidden_size ${config.hidden_size} does not match manifest dimension ${entry.dimension}`)
|
|
101
104
|
checks.push('config.hidden_size=' + config.hidden_size)
|
|
102
|
-
|
|
103
|
-
|
|
105
|
+
// 分窗不能超过制品自己声明的位置上限——超过就是必炸的输入;比它小是刻意的策略
|
|
106
|
+
// (例如 32k 上下文的模型按 8k 切,避免单条记忆把 CPU 推理拖到请求超时),
|
|
107
|
+
// 而这个选择本来就在 profile 指纹里,可复现。
|
|
108
|
+
if (entry.maxTokens !== null && config.max_position_embeddings && config.max_position_embeddings < entry.maxTokens) {
|
|
109
|
+
throw new Error(`manifest maxTokens ${entry.maxTokens} exceeds the artifact's max_position_embeddings ${config.max_position_embeddings}`)
|
|
104
110
|
}
|
|
105
|
-
if (config.max_position_embeddings) checks.push('config.max_position_embeddings=' + config.max_position_embeddings)
|
|
111
|
+
if (config.max_position_embeddings) checks.push('config.max_position_embeddings=' + config.max_position_embeddings + ' window=' + (entry.maxTokens ?? 'unset'))
|
|
106
112
|
|
|
107
113
|
const vocabBytes = bytesOf('vocab')
|
|
108
114
|
if (vocabBytes && Number.isInteger(config.vocab_size)) {
|
|
@@ -123,6 +129,10 @@ export async function verifyStagedArtifacts({ entry, dir }) {
|
|
|
123
129
|
if (poolingBytes) {
|
|
124
130
|
const pooling = JSON.parse(poolingBytes.toString('utf8'))
|
|
125
131
|
if (entry.pooling === 'cls' && pooling.pooling_mode_cls_token !== true) throw new Error('pooling config is not CLS pooling')
|
|
132
|
+
if (entry.pooling === 'mean' && pooling.pooling_mode_mean_tokens !== true) throw new Error('pooling config is not mean pooling')
|
|
133
|
+
// 因果 LM 的卡片最容易踩的坑:目录写着 last、制品其实是 mean。lasttoken 是基座自己
|
|
134
|
+
// 声明的字段,能对得上才继续。
|
|
135
|
+
if (entry.pooling === 'last' && pooling.pooling_mode_lasttoken !== true) throw new Error('pooling config is not last-token pooling')
|
|
126
136
|
if (Number.isInteger(pooling.word_embedding_dimension) && pooling.word_embedding_dimension !== entry.dimension) {
|
|
127
137
|
throw new Error(`pooling word_embedding_dimension ${pooling.word_embedding_dimension} does not match dimension ${entry.dimension}`)
|
|
128
138
|
}
|
|
@@ -149,7 +159,12 @@ export async function verifyStagedArtifacts({ entry, dir }) {
|
|
|
149
159
|
const actualOutput = header.outputs[0]
|
|
150
160
|
if (!actualOutput) throw new Error('graph has no outputs')
|
|
151
161
|
if (declaredOutput && actualOutput.name !== declaredOutput.name) throw new Error(`graph output ${actualOutput.name} does not match manifest ${declaredOutput.name}`)
|
|
152
|
-
|
|
162
|
+
// float32 与 float16 都能被 worker 池化(fp16 走 Number() 取值),但别的 dtype
|
|
163
|
+
// (int8 输出、string)不是 embedding worker 该假装能吃的东西。声明与实际必须一致。
|
|
164
|
+
if (!['float32', 'float16'].includes(actualOutput.dtype)) throw new Error(`graph output dtype ${actualOutput.dtype} is not float32/float16`)
|
|
165
|
+
if (declaredOutput && declaredOutput.dtype && actualOutput.dtype !== declaredOutput.dtype) {
|
|
166
|
+
throw new Error(`graph output dtype ${actualOutput.dtype} does not match manifest ${declaredOutput.dtype}`)
|
|
167
|
+
}
|
|
153
168
|
const lastDim = Array.isArray(actualOutput.shape) ? actualOutput.shape[actualOutput.shape.length - 1] : null
|
|
154
169
|
if (lastDim !== entry.dimension) throw new Error(`graph output last dim ${lastDim} does not match dimension ${entry.dimension}`)
|
|
155
170
|
checks.push('graph.output=' + actualOutput.name + ':' + actualOutput.dtype + '[' + lastDim + ']')
|
|
@@ -271,9 +286,12 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
271
286
|
}
|
|
272
287
|
|
|
273
288
|
async function download(id, downloadOptions = {}) {
|
|
274
|
-
const { confirmed = false, signal } = downloadOptions || {}
|
|
289
|
+
const { confirmed = false, signal, provider = null } = downloadOptions || {}
|
|
275
290
|
const entry = lookup(typeof id === 'string' ? id : String(id || ''))
|
|
276
291
|
if (!entry) throw fail('EMBEDDING_MODEL_UNKNOWN', `unknown embedding model: ${id}`)
|
|
292
|
+
if (provider !== null && !PROVIDERS[provider]) {
|
|
293
|
+
throw fail('EMBEDDING_PROVIDER_UNKNOWN', `unknown download provider: ${String(provider)}`)
|
|
294
|
+
}
|
|
277
295
|
const report = validateEmbeddingManifest(entry)
|
|
278
296
|
if (!report.ok) {
|
|
279
297
|
throw fail('EMBEDDING_MANIFEST_INVALID', `${entry.id} manifest is not installable: ${report.errors.map(item => item.code).join(', ')}`, { errors: report.errors })
|
|
@@ -286,9 +304,13 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
286
304
|
}
|
|
287
305
|
if (jobs.has(entry.id)) throw fail('EMBEDDING_DOWNLOAD_BUSY', `${entry.id} is already downloading`)
|
|
288
306
|
if (signal?.aborted) throw fail('EMBEDDING_DOWNLOAD_ABORTED', `download of ${entry.id} was aborted before it started`)
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
307
|
+
// 默认取目录顺序里第一个已固定的来源(Qwen3 卡片因此默认 hf-mirror);显式传
|
|
308
|
+
// provider 时只解析那一个,解析不出可用来源就如实报错,绝不回退到别的源去下载。
|
|
309
|
+
const resolved = provider ? resolveEmbeddingSources(entry, { providers: [provider] }) : resolveEmbeddingSources(entry)
|
|
310
|
+
const source = provider ? resolved.sources.find(item => item.provider === provider) || null : resolved.primary
|
|
311
|
+
if (!source) {
|
|
312
|
+
throw fail('EMBEDDING_SOURCE_UNAVAILABLE', `no source with a pinned revision is available for ${entry.id}${provider ? ' on ' + provider : ''}`, { skipped: resolved.skipped })
|
|
313
|
+
}
|
|
292
314
|
|
|
293
315
|
const controller = new AbortController()
|
|
294
316
|
const onAbort = () => controller.abort()
|
|
@@ -328,8 +350,11 @@ export function createEmbeddingDownloadManager(options = {}) {
|
|
|
328
350
|
if (!response || !response.ok) {
|
|
329
351
|
throw fail('EMBEDDING_HTTP_ERROR', `${source.provider} returned ${response?.status ?? 'no response'} for ${file.path}`)
|
|
330
352
|
}
|
|
331
|
-
|
|
332
|
-
|
|
353
|
+
// 没有 content-length(hf-mirror 对小文件用 chunked 传输)等于「未知」,不是 0:
|
|
354
|
+
// 当成 0 会把每个小文件都误判成大小不符。真正的门槛是下面落盘后的 sha256。
|
|
355
|
+
const declaredHeader = response.headers?.get?.('content-length')
|
|
356
|
+
const declaredLength = Number(declaredHeader)
|
|
357
|
+
if (declaredHeader != null && Number.isInteger(declaredLength) && declaredLength > 0 && declaredLength !== file.bytes) {
|
|
333
358
|
throw fail('EMBEDDING_SIZE_MISMATCH', `${file.path} content-length ${declaredLength} does not match the pinned ${file.bytes} bytes`)
|
|
334
359
|
}
|
|
335
360
|
const hash = crypto.createHash('sha256')
|
package/lib/inject.js
CHANGED
|
@@ -4,6 +4,7 @@ import {
|
|
|
4
4
|
getSettings, ensureSession, loadPrivateIndex, loadGlobalIndex,
|
|
5
5
|
markInjected, releaseInjected, markReinjectPending, clearReinjectPending,
|
|
6
6
|
armCue, getActiveCue, setSessionMood, wasAnniversaryShown, markAnniversaryShown,
|
|
7
|
+
recordInjectionRollback, rollbackInjectionForTurn, consumeInjectionRollback,
|
|
7
8
|
markOpenLoopReminded, DEFAULT_SETTINGS,
|
|
8
9
|
touchSession, getSessionBinding, setSessionBinding, setRecallError, effectiveScope,
|
|
9
10
|
} from './state.js'
|
|
@@ -976,6 +977,36 @@ export function createMemoryMessage(text) {
|
|
|
976
977
|
})
|
|
977
978
|
}
|
|
978
979
|
|
|
980
|
+
// §3.24 的第二半:回滚只该用在「请求根本没发出去」的失败上。宿主 agent-loop 的 step() 在第一次
|
|
981
|
+
// 尝试里就把本轮 decision.messages 逐条 append 进转录,之后才去连模型 —— 所以「看见自己那条注入
|
|
982
|
+
// 消息的 user/message 事件」就是它已经在转录里的实证。有实证还撤,下一轮就凭空多出第二条规则消息
|
|
983
|
+
// 和第二个锚点;没实证(配置无效、额度、取消发生在投放之前)才该把记账还回去。
|
|
984
|
+
// 证据只留在内存:进程重启后宁可什么都不做,也不要误投。
|
|
985
|
+
const injectionAdmissions = new Map()
|
|
986
|
+
|
|
987
|
+
function noteInjectedMessages(sessionId, hostTurn, messageIds) {
|
|
988
|
+
const turn = Number(hostTurn)
|
|
989
|
+
const ids = (messageIds || []).filter(Boolean)
|
|
990
|
+
if (!sessionId || !Number.isSafeInteger(turn) || ids.length === 0) return
|
|
991
|
+
const current = injectionAdmissions.get(sessionId)
|
|
992
|
+
const entry = current && current.turn === turn ? current : { turn, ids: new Set(), admitted: false }
|
|
993
|
+
for (const id of ids) entry.ids.add(id)
|
|
994
|
+
injectionAdmissions.set(sessionId, entry)
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
function observeInjectionMessage(sessionId, messageId) {
|
|
998
|
+
const entry = injectionAdmissions.get(sessionId)
|
|
999
|
+
if (!entry || !messageId || !entry.ids.has(messageId)) return false
|
|
1000
|
+
entry.admitted = true
|
|
1001
|
+
return true
|
|
1002
|
+
}
|
|
1003
|
+
|
|
1004
|
+
function injectionNeedsRollback(sessionId, hostTurn) {
|
|
1005
|
+
const entry = injectionAdmissions.get(sessionId)
|
|
1006
|
+
if (!entry || entry.turn !== Number(hostTurn)) return false
|
|
1007
|
+
return !entry.admitted
|
|
1008
|
+
}
|
|
1009
|
+
|
|
979
1010
|
// Every part of the first-step message is built from one binding snapshot, but
|
|
980
1011
|
// retrieval awaits an external engine. During that window the conversation can be
|
|
981
1012
|
// switched to another library, moved to another channel/character, or have a layer
|
|
@@ -1111,12 +1142,16 @@ function ensureUnifiedGuide(ctx, payload, decision) {
|
|
|
1111
1142
|
if (guides.length === 0) return decision
|
|
1112
1143
|
}
|
|
1113
1144
|
const next = decision.messages.filter((message) => !isMemoryGuideMessage(message))
|
|
1114
|
-
|
|
1145
|
+
const guideMessage = createMemoryMessage(guide.text)
|
|
1146
|
+
next.push(guideMessage)
|
|
1115
1147
|
setSessionBinding(sessionId, {
|
|
1116
1148
|
guideRulesKey: guide.key,
|
|
1117
1149
|
guideMessageAt: new Date().toISOString(),
|
|
1118
1150
|
guideLost: false,
|
|
1119
1151
|
})
|
|
1152
|
+
// §3.24:规则消息也是一次性的(靠 guideRulesKey 去重)。这一轮失败的话,key 要一起撤掉。
|
|
1153
|
+
try { noteInjectedMessages(sessionId, payload?.turn, [guideMessage.id]) } catch {}
|
|
1154
|
+
try { recordInjectionRollback(sessionId, { hostTurn: payload?.turn, guideKey: guide.key }) } catch {}
|
|
1120
1155
|
record({
|
|
1121
1156
|
kind: 'system',
|
|
1122
1157
|
scope: 'private',
|
|
@@ -1260,20 +1295,28 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
|
|
|
1260
1295
|
setRecallError(sessionId, 'inbound injection exceeded injectionTotalTokens')
|
|
1261
1296
|
return decision
|
|
1262
1297
|
}
|
|
1298
|
+
let inboundMessage = null
|
|
1263
1299
|
if (text) {
|
|
1300
|
+
inboundMessage = createMemoryMessage(text)
|
|
1264
1301
|
const pushed = [...new Set(ids)]
|
|
1302
|
+
const anchorPushed = anchorNeeded && Boolean(parts[0]?.startsWith('===== memory anchor'))
|
|
1265
1303
|
markInjected(sessionId, pushed, clock)
|
|
1266
|
-
if (
|
|
1304
|
+
if (anchorPushed) {
|
|
1267
1305
|
markInjected(sessionId, [ANCHOR_SENTINEL], clock)
|
|
1268
1306
|
clearReinjectPending(sessionId)
|
|
1269
1307
|
}
|
|
1308
|
+
// §3.24:与主路径同口径——这一轮若被宿主整轮回滚,锚点与这批 id 的记账要能撤回来。
|
|
1309
|
+
try { noteInjectedMessages(sessionId, turn, [inboundMessage.id]) } catch {}
|
|
1310
|
+
try {
|
|
1311
|
+
recordInjectionRollback(sessionId, { hostTurn: turn, ids: anchorPushed ? [...pushed, ANCHOR_SENTINEL] : pushed })
|
|
1312
|
+
} catch {}
|
|
1270
1313
|
try {
|
|
1271
1314
|
if (scope.useLibrary && binding.libraryId) noteInjected({ libraryId: binding.libraryId, ids: pushed })
|
|
1272
1315
|
if (scope.useGlobal) noteGlobalInjected({ ids: pushed })
|
|
1273
1316
|
} catch (error) { try { log?.(`inbound injection accounting failed: ${error?.message || error}`) } catch {} }
|
|
1274
1317
|
}
|
|
1275
1318
|
finishInbound(sessionId, keys, clock, { reason: outcome, injectedCount: ids.length })
|
|
1276
|
-
return
|
|
1319
|
+
return inboundMessage ? { ...decision, messages: [...decision.messages, inboundMessage] } : decision
|
|
1277
1320
|
}
|
|
1278
1321
|
|
|
1279
1322
|
export async function injectForStep({ agent, decision, turn, step, signal, log = null, ctx = null }) {
|
|
@@ -1406,12 +1449,14 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
1406
1449
|
// Only an anniversary that actually reached `parts` may suppress the nudge — one
|
|
1407
1450
|
// the budget dropped must not silence it, because then the turn says nothing.
|
|
1408
1451
|
let anniversaryIds = []
|
|
1452
|
+
let anniversaryFired = []
|
|
1409
1453
|
if (!reinject) {
|
|
1410
1454
|
const anniversary = buildAnniversary(sessionId, effective)
|
|
1411
1455
|
if (anniversary.text && estTokens(anniversary.text) <= totalRoom()) {
|
|
1412
1456
|
parts.push(anniversary.text)
|
|
1413
1457
|
ids.push(...anniversary.ids)
|
|
1414
1458
|
anniversaryIds = anniversary.ids
|
|
1459
|
+
anniversaryFired = anniversary.fired || []
|
|
1415
1460
|
for (const id of anniversary.fired) markAnniversaryShown(sessionId, id, anniversary.dayKey)
|
|
1416
1461
|
}
|
|
1417
1462
|
}
|
|
@@ -1512,6 +1557,15 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
|
|
|
1512
1557
|
for (const id of recurringNudgeIds) {
|
|
1513
1558
|
try { markOpenLoopReminded(sessionId, id) } catch {}
|
|
1514
1559
|
}
|
|
1560
|
+
// §3.24:本轮若被宿主整轮回滚(请求根本没发出去),这份记账要跟着撤,否则一次性内容
|
|
1561
|
+
// (锚点/纪念日/nudge 时钟)整段对话都不会再投。guide 由 ensureUnifiedGuide 另记一次。
|
|
1562
|
+
// 撤回与否由 turn/end 那里的转录实证判定,这里只管把"这一轮消费掉了什么"记下来。
|
|
1563
|
+
try { noteInjectedMessages(sessionId, turn, [message.id]) } catch {}
|
|
1564
|
+
try {
|
|
1565
|
+
recordInjectionRollback(sessionId, {
|
|
1566
|
+
hostTurn: turn, ids, nudgeIds: recurringNudgeIds, anniversaryIds: anniversaryFired,
|
|
1567
|
+
})
|
|
1568
|
+
} catch {}
|
|
1515
1569
|
if (reinject) {
|
|
1516
1570
|
clearReinjectPending(sessionId)
|
|
1517
1571
|
// The replay has been paid for; it must not ride along on the next compaction too.
|
|
@@ -1555,6 +1609,48 @@ export function registerInjection(ctx) {
|
|
|
1555
1609
|
disposers.push(offPre)
|
|
1556
1610
|
|
|
1557
1611
|
const offSession = ctx.on('session/event', async (session, event) => {
|
|
1612
|
+
// §3.24 —— 宿主会把「请求根本没发出去」的整轮回滚(真机实测:连用户消息都不留在转录里),
|
|
1613
|
+
// 插件却已经在"消息交回决策"之后就记了账。不撤销的话 guide / 锚点 / 当日纪念日 / 复提时钟
|
|
1614
|
+
// 这类一次性内容再也不投,整段对话只是"记忆像没接上",一句错都不报。
|
|
1615
|
+
// 这一段排在最前且自带 try:不能被后面任何一步抛错带走。判据是转录里到底有没有本轮那几条
|
|
1616
|
+
// 注入消息(见 injectionAdmissions)——请求已经带着它们出去过的失败,一律不撤。
|
|
1617
|
+
try {
|
|
1618
|
+
const eventSessionId = session?.header?.id
|
|
1619
|
+
if (event?.type === 'user/message') {
|
|
1620
|
+
// 看见自己投出去的那条消息被追加进转录 = 这一轮真的发出去了。
|
|
1621
|
+
try { observeInjectionMessage(eventSessionId, event?.data?.id) } catch {}
|
|
1622
|
+
}
|
|
1623
|
+
if (event?.type === 'turn/end') {
|
|
1624
|
+
const failedSessionId = eventSessionId
|
|
1625
|
+
const turnNumber = event?.data?.turn
|
|
1626
|
+
const kind = event?.data?.reason?.kind
|
|
1627
|
+
// 撤回只用于「本轮注入的消息根本没进转录」的失败:配置无效、额度、取消发生在投放之前。
|
|
1628
|
+
// 上游 500 / 超时那类失败里消息已经在转录里,撤回只会让下一轮多出第二份锚点。
|
|
1629
|
+
if ((kind === 'error' || kind === 'aborted') && injectionNeedsRollback(failedSessionId, turnNumber)) {
|
|
1630
|
+
const rolled = rollbackInjectionForTurn(failedSessionId, turnNumber)
|
|
1631
|
+
if (rolled) {
|
|
1632
|
+
const binding = getSessionBinding(failedSessionId)
|
|
1633
|
+
record({
|
|
1634
|
+
kind: 'system', scope: 'private', sessionId: failedSessionId, libraryId: binding?.libraryId || null, level: 'warn', ok: false,
|
|
1635
|
+
message: `回合 ${turnNumber} 以 ${kind} 结束且注入的消息没进转录,已撤回本轮的注入记账(一次性内容将在下一轮重投)`,
|
|
1636
|
+
detail: {
|
|
1637
|
+
turn: turnNumber ?? null, kind, ids: rolled.ids.length,
|
|
1638
|
+
anchor: rolled.ids.includes(ANCHOR_SENTINEL), guide: Boolean(rolled.guideKey),
|
|
1639
|
+
anniversaries: rolled.anniversaries, nudges: rolled.nudges,
|
|
1640
|
+
reason: String(event?.data?.reason?.error?.message || '').slice(0, 160),
|
|
1641
|
+
},
|
|
1642
|
+
})
|
|
1643
|
+
try { ctx.logger?.warn?.(`dsh-memu-memory: rolled back injection accounting for failed turn ${turnNumber}`) } catch {}
|
|
1644
|
+
}
|
|
1645
|
+
} else {
|
|
1646
|
+
// 回合正常收尾,或消息已经在转录里:消费掉这份记录,之后一条迟到的 error 事件不能再撤回它。
|
|
1647
|
+
try { consumeInjectionRollback(failedSessionId, turnNumber) } catch {}
|
|
1648
|
+
}
|
|
1649
|
+
injectionAdmissions.delete(failedSessionId)
|
|
1650
|
+
}
|
|
1651
|
+
} catch (error) {
|
|
1652
|
+
try { ctx.logger?.warn?.(`dsh-memu-memory: injection rollback check failed (fail-open): ${error?.message || error}`) } catch {}
|
|
1653
|
+
}
|
|
1558
1654
|
try {
|
|
1559
1655
|
observeInboundEvent(ctx, session, event)
|
|
1560
1656
|
await captureMediaEvent(ctx, session, event)
|
|
@@ -3,6 +3,7 @@ import { spawn } from 'node:child_process'
|
|
|
3
3
|
import { fileURLToPath } from 'node:url'
|
|
4
4
|
import { assertProfileVerified } from './vector-profile.js'
|
|
5
5
|
import { manifestModelId } from './local-embedding-worker.js'
|
|
6
|
+
import { prefixesRequireRole } from './embedding-catalog.js'
|
|
6
7
|
import { windowsSystemEnv } from './paths.js'
|
|
7
8
|
|
|
8
9
|
const entry = fileURLToPath(new URL('./local-embedding-entry.js', import.meta.url))
|
|
@@ -103,12 +104,12 @@ export function createEmbeddingWorkerManager({ spawnImpl = spawn, executable = p
|
|
|
103
104
|
if (ready.url !== undefined && ready.url !== null && String(ready.url) !== new URL(EMBEDDINGS_PATH, base).href) {
|
|
104
105
|
return { error: 'worker embeddings URL does not belong to its base URL' }
|
|
105
106
|
}
|
|
106
|
-
return { endpoint: Object.freeze({ baseUrl: base.href, model: expected.model, dimension: expected.dimension }) }
|
|
107
|
+
return { endpoint: Object.freeze({ baseUrl: base.href, model: expected.model, dimension: expected.dimension, rolesRequired: expected.rolesRequired === true }) }
|
|
107
108
|
}
|
|
108
109
|
|
|
109
110
|
function boot(profile, key, modelDir, runtimeDir) {
|
|
110
111
|
const token = crypto.randomBytes(TOKEN_BYTES).toString('hex')
|
|
111
|
-
const expected = { model: manifestModelId(profile.manifest), dimension: Number(profile.dimension) }
|
|
112
|
+
const expected = { model: manifestModelId(profile.manifest), dimension: Number(profile.dimension), rolesRequired: prefixesRequireRole(profile.manifest) }
|
|
112
113
|
const record = { key, child: null, stopping: false, settled: false, endpoint: null, reject: null }
|
|
113
114
|
// Registered before the spawn so a concurrent acquire joins this boot instead of
|
|
114
115
|
// starting a second child for the same profile.
|
|
@@ -19,6 +19,32 @@ export const MAX_VECTOR_DIMENSION = 8192
|
|
|
19
19
|
export const MAX_INPUT_CHARS = 65_536
|
|
20
20
|
export const ENCODINGS = Object.freeze(['float', 'base64'])
|
|
21
21
|
|
|
22
|
+
// §14.4: a model whose query and document prefixes differ reads the same text two
|
|
23
|
+
// ways, so the request has to say which reading it wants. MemU's envelope is
|
|
24
|
+
// {model, input, encoding_format} — there is no role field and there will not be
|
|
25
|
+
// one (we do not own it). The plugin does own which MemU process it starts, so the
|
|
26
|
+
// role rides on the model string it injects: ":query" for the retrieve process and
|
|
27
|
+
// ":passage" for the committing one. It is never inferred from the text itself.
|
|
28
|
+
export const ROLE_SUFFIXES = Object.freeze({ query: ':query', document: ':passage' })
|
|
29
|
+
export const ROLES = Object.freeze(['query', 'document'])
|
|
30
|
+
|
|
31
|
+
/** Compose the model string a client must send for one role. */
|
|
32
|
+
export function modelIdForRole(model, role = 'document') {
|
|
33
|
+
const base = String(model || '')
|
|
34
|
+
if (!base) return ''
|
|
35
|
+
return base + (ROLE_SUFFIXES[role] ?? ROLE_SUFFIXES.document)
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Split a requested model string back into { model, role } (role null when bare). */
|
|
39
|
+
export function splitModelRole(requested) {
|
|
40
|
+
const text = String(requested || '')
|
|
41
|
+
for (const role of ROLES) {
|
|
42
|
+
const suffix = ROLE_SUFFIXES[role]
|
|
43
|
+
if (text.length > suffix.length && text.endsWith(suffix)) return { model: text.slice(0, -suffix.length), role }
|
|
44
|
+
}
|
|
45
|
+
return { model: text, role: null }
|
|
46
|
+
}
|
|
47
|
+
|
|
22
48
|
export class LocalEmbeddingError extends Error {
|
|
23
49
|
constructor(message, code = 'LOCAL_VECTOR_ERROR', status = 500, detail = null) {
|
|
24
50
|
super(message)
|
|
@@ -117,7 +143,7 @@ function normalizeInputText(value, index, maxChars) {
|
|
|
117
143
|
// Accepts exactly what the SDK sends: one string or an array of strings. Anything
|
|
118
144
|
// else (token ids, nested arrays, non-string items) is a client bug, not something
|
|
119
145
|
// to coerce, because a silent coercion would embed the wrong text.
|
|
120
|
-
export function parseEmbeddingRequest(body, { model, maxBatch = DEFAULT_MAX_BATCH, maxChars = MAX_INPUT_CHARS } = {}) {
|
|
146
|
+
export function parseEmbeddingRequest(body, { model, maxBatch = DEFAULT_MAX_BATCH, maxChars = MAX_INPUT_CHARS, rolesRequired = false } = {}) {
|
|
121
147
|
if (!body || typeof body !== 'object' || Array.isArray(body)) {
|
|
122
148
|
throw badRequest('request body must be a JSON object', 'LOCAL_VECTOR_BAD_REQUEST')
|
|
123
149
|
}
|
|
@@ -126,9 +152,20 @@ export function parseEmbeddingRequest(body, { model, maxBatch = DEFAULT_MAX_BATC
|
|
|
126
152
|
if (typeof requested !== 'string' || !requested.trim()) {
|
|
127
153
|
throw badRequest('model is required', 'LOCAL_VECTOR_BAD_REQUEST')
|
|
128
154
|
}
|
|
129
|
-
|
|
155
|
+
const { model: requestedBase, role: requestedRole } = splitModelRole(requested)
|
|
156
|
+
if (!expected || requestedBase !== expected) {
|
|
130
157
|
throw badRequest('unknown model; this worker serves ' + (expected || '(none)'), 'LOCAL_VECTOR_MODEL_MISMATCH')
|
|
131
158
|
}
|
|
159
|
+
// A bare model id is only an answer when one prefix serves both sides. When the
|
|
160
|
+
// profile reads queries and documents differently, the role must be explicit:
|
|
161
|
+
// defaulting it would embed a query into the document space and still return 200.
|
|
162
|
+
let role = requestedRole
|
|
163
|
+
if (role === null) {
|
|
164
|
+
if (rolesRequired === true) {
|
|
165
|
+
throw badRequest('this model reads query and document differently; send the model id with a ' + Object.values(ROLE_SUFFIXES).join(' or ') + ' suffix', 'LOCAL_VECTOR_ROLE_REQUIRED')
|
|
166
|
+
}
|
|
167
|
+
role = 'document'
|
|
168
|
+
}
|
|
132
169
|
const encoding = body.encoding_format === undefined || body.encoding_format === null ? 'float' : body.encoding_format
|
|
133
170
|
if (typeof encoding !== 'string' || !ENCODINGS.includes(encoding)) {
|
|
134
171
|
throw badRequest('encoding_format must be one of ' + ENCODINGS.join(', '), 'LOCAL_VECTOR_BAD_ENCODING')
|
|
@@ -142,7 +179,7 @@ export function parseEmbeddingRequest(body, { model, maxBatch = DEFAULT_MAX_BATC
|
|
|
142
179
|
throw badRequest('batch of ' + list.length + ' exceeds the limit of ' + batchLimit, 'LOCAL_VECTOR_BATCH_TOO_LARGE')
|
|
143
180
|
}
|
|
144
181
|
const inputs = list.map((value, index) => normalizeInputText(value, index, maxChars))
|
|
145
|
-
return { inputs, encoding }
|
|
182
|
+
return { inputs, encoding, role }
|
|
146
183
|
}
|
|
147
184
|
|
|
148
185
|
// Token counts are only used for the usage block; the worker never claims a real
|
|
@@ -18,6 +18,7 @@ import {
|
|
|
18
18
|
errorStatus,
|
|
19
19
|
parseEmbeddingRequest,
|
|
20
20
|
} from './local-embedding-protocol.js'
|
|
21
|
+
import { prefixesRequireRole } from './embedding-catalog.js'
|
|
21
22
|
|
|
22
23
|
// §14.5: loopback only, port 0, random high-entropy token from the parent. Nothing
|
|
23
24
|
// here ever reaches the network, downloads a model, or logs a token or input text.
|
|
@@ -66,6 +67,22 @@ export function manifestDimension(manifest) {
|
|
|
66
67
|
return 0
|
|
67
68
|
}
|
|
68
69
|
|
|
70
|
+
// The prefix is a property of the model, never of the caller's text: an empty prefix
|
|
71
|
+
// is a real choice (BGE/MiniLM read both sides the same), and a missing prefixes block
|
|
72
|
+
// means exactly that. Roles are required only when the two sides differ (§14.4).
|
|
73
|
+
function manifestPrefixes(manifest) {
|
|
74
|
+
const raw = manifest && manifest.prefixes && typeof manifest.prefixes === 'object' ? manifest.prefixes : {}
|
|
75
|
+
return {
|
|
76
|
+
query: typeof raw.query === 'string' ? raw.query : '',
|
|
77
|
+
document: typeof raw.document === 'string' ? raw.document : '',
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function applyRolePrefix(inputs, prefixes, role) {
|
|
82
|
+
const prefix = role === 'query' ? prefixes.query : prefixes.document
|
|
83
|
+
return prefix ? inputs.map(text => prefix + text) : inputs
|
|
84
|
+
}
|
|
85
|
+
|
|
69
86
|
// A model is servable only when the installer marked it verified. pending /
|
|
70
87
|
// candidate / downloading entries exist in the catalog, but a half-installed
|
|
71
88
|
// artifact must never answer a request, and nothing here starts a download to
|
|
@@ -90,7 +107,8 @@ export function assertServableManifest({ manifest, modelDir } = {}) {
|
|
|
90
107
|
if (!model) throw asError('manifest is missing a stable id', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
|
|
91
108
|
const dimension = manifestDimension(manifest)
|
|
92
109
|
if (!dimension) throw asError('manifest is missing expected dimension', 'LOCAL_VECTOR_MANIFEST_INCOMPLETE', 503)
|
|
93
|
-
|
|
110
|
+
const prefixes = manifestPrefixes(manifest)
|
|
111
|
+
return { model, dimension, modelDir: path.resolve(dir), prefixes, rolesRequired: prefixesRequireRole({ prefixes }) }
|
|
94
112
|
}
|
|
95
113
|
|
|
96
114
|
// External-data graphs, tokenizer files and the model directory itself are all
|
|
@@ -220,6 +238,9 @@ async function tokenizeBatch(tokenizer, texts, maxTokens) {
|
|
|
220
238
|
throw new Error('unsupported tokenizer interface')
|
|
221
239
|
}
|
|
222
240
|
|
|
241
|
+
// 因果语言模型(Qwen3-Embedding 这一类)取最后一个非 pad token 的隐藏态:下标由
|
|
242
|
+
// attention_mask 的累加和决定,所以右侧 padding 也一样准,与官方
|
|
243
|
+
// 1_Pooling(pooling_mode_lasttoken) 的口径一致。
|
|
223
244
|
function poolTensor(tensor, { pooling, mask, normalize }) {
|
|
224
245
|
const dims = Array.from((tensor && tensor.dims) || [])
|
|
225
246
|
const data = tensor && tensor.data
|
|
@@ -231,8 +252,16 @@ function poolTensor(tensor, { pooling, mask, normalize }) {
|
|
|
231
252
|
for (let row = 0; row < batch; row++) {
|
|
232
253
|
const vector = new Array(hidden).fill(0)
|
|
233
254
|
const base = row * tokens * hidden
|
|
234
|
-
|
|
235
|
-
|
|
255
|
+
const weights = mask && mask[row] ? mask[row] : null
|
|
256
|
+
if (pooling === 'last' && tokens > 1) {
|
|
257
|
+
let last = tokens - 1
|
|
258
|
+
if (weights) {
|
|
259
|
+
for (let token = tokens - 1; token >= 0; token--) {
|
|
260
|
+
if (Number(weights[token]) || 0) { last = token; break }
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
for (let unit = 0; unit < hidden; unit++) vector[unit] = Number(data[base + last * hidden + unit])
|
|
264
|
+
} else if (pooling === 'mean' && tokens > 1) {
|
|
236
265
|
let total = 0
|
|
237
266
|
for (let token = 0; token < tokens; token++) {
|
|
238
267
|
const weight = weights ? Number(weights[token]) || 0 : 1
|
|
@@ -441,7 +470,7 @@ export async function startEmbeddingWorker(options = {}) {
|
|
|
441
470
|
maxBatch = DEFAULT_MAX_BATCH,
|
|
442
471
|
} = options
|
|
443
472
|
|
|
444
|
-
const { model, dimension } = assertServableManifest({ manifest, modelDir })
|
|
473
|
+
const { model, dimension, prefixes, rolesRequired } = assertServableManifest({ manifest, modelDir })
|
|
445
474
|
|
|
446
475
|
if (typeof token !== 'string' || token.length < MIN_TOKEN_LENGTH) {
|
|
447
476
|
throw asError('a random token of at least ' + MIN_TOKEN_LENGTH + ' characters is required', 'LOCAL_VECTOR_TOKEN_INVALID', 400)
|
|
@@ -533,6 +562,7 @@ export async function startEmbeddingWorker(options = {}) {
|
|
|
533
562
|
dimension,
|
|
534
563
|
maxBatch: batchLimit,
|
|
535
564
|
encodings: ENCODINGS,
|
|
565
|
+
rolesRequired,
|
|
536
566
|
uptimeMs: Date.now() - startedAt,
|
|
537
567
|
})
|
|
538
568
|
}
|
|
@@ -550,8 +580,8 @@ export async function startEmbeddingWorker(options = {}) {
|
|
|
550
580
|
const raw = await readBody(req, bodyLimit)
|
|
551
581
|
let body = null
|
|
552
582
|
try { body = JSON.parse(raw) } catch { throw fail('request body is not valid JSON', 'LOCAL_VECTOR_BAD_REQUEST', 400) }
|
|
553
|
-
const { inputs, encoding } = parseEmbeddingRequest(body, { model, maxBatch: batchLimit })
|
|
554
|
-
const encoded = await encodeVectors(inputs)
|
|
583
|
+
const { inputs, encoding, role } = parseEmbeddingRequest(body, { model, maxBatch: batchLimit, rolesRequired })
|
|
584
|
+
const encoded = await encodeVectors(applyRolePrefix(inputs, prefixes, role))
|
|
555
585
|
const vectors = encoded.vectors.map((vector, index) => assertVector(vector, dimension, index))
|
|
556
586
|
sendJson(res, 200, buildEmbeddingResponse({ model, vectors, encoding, usage: encoded.usage }))
|
|
557
587
|
lastError = null
|
|
@@ -3,11 +3,12 @@ import path from 'node:path'
|
|
|
3
3
|
import { downloadsDir, warn } from './paths.js'
|
|
4
4
|
import { listLibraries, loadPrivateIndex, loadGlobalIndex } from './state.js'
|
|
5
5
|
import { commit as memuCommit, listFiles as memuListFiles, forget as memuForget } from './memu.js'
|
|
6
|
-
import { getEmbeddingCatalog } from './embedding-catalog.js'
|
|
6
|
+
import { getEmbeddingCatalog, prefixesRequireRole, resolveEmbeddingSources } from './embedding-catalog.js'
|
|
7
7
|
import { createEmbeddingDownloadManager } from './embedding-download.js'
|
|
8
8
|
import { createVectorMigrator } from './vector-migration.js'
|
|
9
9
|
import { profileFromCatalog, setRequestedProfile, vectorStatus, assertProfileVerified } from './vector-profile.js'
|
|
10
10
|
import { embeddingWorkerManager } from './local-embedding-manager.js'
|
|
11
|
+
import { modelIdForRole } from './local-embedding-protocol.js'
|
|
11
12
|
import { managedEmbeddingRuntime, resetManagedEmbeddingRuntime } from './embedding-runtime.js'
|
|
12
13
|
|
|
13
14
|
const root = path.join(downloadsDir(), 'embeddings')
|
|
@@ -150,6 +151,11 @@ export function getLocalVectorState() {
|
|
|
150
151
|
availability: entry.availability,
|
|
151
152
|
dimension: entry.dimension,
|
|
152
153
|
totalBytes: entry.totalBytes,
|
|
154
|
+
languages: Array.isArray(entry.languages) ? [...entry.languages] : [],
|
|
155
|
+
rolesRequired: prefixesRequireRole(entry),
|
|
156
|
+
// 能让用户选的来源(不是目录里写了几个 provider,而是那几个真的固定了 revision)。
|
|
157
|
+
// 顺序就是默认顺序:第一个是 download() 不传 provider 时会用的那个。
|
|
158
|
+
providers: resolveEmbeddingSources(entry).sources.map(source => ({ id: source.provider, label: source.label })),
|
|
153
159
|
pendingReasons: [...(entry.pendingReasons || [])],
|
|
154
160
|
license: entry.license?.base || null,
|
|
155
161
|
}))
|
|
@@ -177,8 +183,12 @@ export function selectLocalVectorModel(id) {
|
|
|
177
183
|
|
|
178
184
|
export async function downloadLocalVectorModel(id, options = {}) {
|
|
179
185
|
const modelId = String(id)
|
|
180
|
-
|
|
181
|
-
//
|
|
186
|
+
// provider 只影响「从哪个已固定的来源取字节」;落盘前每个文件都按目录 pin 的
|
|
187
|
+
// sha256 校验,所以换源不会换向量空间,指纹里也没有 provider。
|
|
188
|
+
const result = await getDownloader().download(modelId, {
|
|
189
|
+
confirmed: options.confirmed === true,
|
|
190
|
+
...(options.provider ? { provider: String(options.provider) } : {}),
|
|
191
|
+
})
|
|
182
192
|
return { result, runtime: null, state: getLocalVectorState() }
|
|
183
193
|
}
|
|
184
194
|
|
|
@@ -209,12 +219,16 @@ export function abortLocalVectorMigration() {
|
|
|
209
219
|
export async function healthCheckLocalVector(profile, { timeoutMs = 30_000 } = {}) {
|
|
210
220
|
const endpoint = await embeddingWorkerManager().acquire(profile)
|
|
211
221
|
const url = new URL('/v1/embeddings', endpoint.baseUrl).href
|
|
222
|
+
// A profile with different query/document prefixes has no role-less reading: the
|
|
223
|
+
// worker refuses a bare model id rather than pick one. Probe it as a document, which
|
|
224
|
+
// is what the writing path (and the reindex migration) will ask for.
|
|
225
|
+
const servedModel = endpoint.rolesRequired === true ? modelIdForRole(endpoint.model, 'document') : endpoint.model
|
|
212
226
|
let response
|
|
213
227
|
try {
|
|
214
228
|
response = await fetch(url, {
|
|
215
229
|
method: 'POST',
|
|
216
230
|
headers: { 'content-type': 'application/json', authorization: 'Bearer ' + String(endpoint.token) },
|
|
217
|
-
body: JSON.stringify({ model:
|
|
231
|
+
body: JSON.stringify({ model: servedModel, input: ['本地向量健康检查'] }),
|
|
218
232
|
signal: AbortSignal.timeout(Math.max(1000, Number(timeoutMs) || 30_000)),
|
|
219
233
|
})
|
|
220
234
|
} catch (error) {
|
package/lib/memu.js
CHANGED
|
@@ -6,6 +6,7 @@ import { ENGINE_VERSION, readCurrent, verifyEngine } from './engine.js'
|
|
|
6
6
|
import { getSettings } from './state.js'
|
|
7
7
|
import { activeProfile, captureVectorGeneration, assertVectorGeneration, assertProfileVerified, assertMigrationProfile } from './vector-profile.js'
|
|
8
8
|
import { embeddingWorkerManager } from './local-embedding-manager.js'
|
|
9
|
+
import { modelIdForRole } from './local-embedding-protocol.js'
|
|
9
10
|
|
|
10
11
|
// MemU's own storage mode. 'local' keeps every row in this plugin's sqlite files;
|
|
11
12
|
// 'cloud' hands storage to MemU's backend and needs the vendor credentials in
|
|
@@ -95,12 +96,12 @@ async function runConfigured(args, options = {}) {
|
|
|
95
96
|
return result
|
|
96
97
|
}
|
|
97
98
|
|
|
98
|
-
async function envFor({ db, provider, embedModel, baseUrl, apiKey, vectorProfile, route }) {
|
|
99
|
+
async function envFor({ db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, role }) {
|
|
99
100
|
const profile = route === 'managed-local' ? (vectorProfile || activeProfile()) : null
|
|
100
101
|
if (profile) {
|
|
101
102
|
assertProfileVerified(profile)
|
|
102
103
|
const endpoint = await embeddingWorkerManager().acquire(profile)
|
|
103
|
-
return localEmbeddingEnv({ ...endpoint, db })
|
|
104
|
+
return localEmbeddingEnv({ ...endpoint, db, role })
|
|
104
105
|
}
|
|
105
106
|
if (route === 'managed-local') throw new MemuError('managed local vector profile is not active', 'VECTOR_NOT_READY')
|
|
106
107
|
const env = {}
|
|
@@ -117,7 +118,7 @@ async function envFor({ db, provider, embedModel, baseUrl, apiKey, vectorProfile
|
|
|
117
118
|
// per-process random token (env only, never argv/log/config) and the pinned
|
|
118
119
|
// embedding model id. Telemetry is switched off explicitly, because "local mode"
|
|
119
120
|
// alone is not proof that nothing leaves the machine.
|
|
120
|
-
export function localEmbeddingEnv({ baseUrl, token, model, db } = {}) {
|
|
121
|
+
export function localEmbeddingEnv({ baseUrl, token, model, rolesRequired, db, role } = {}) {
|
|
121
122
|
const env = {
|
|
122
123
|
MEMU_MEMORY_MODE: 'local',
|
|
123
124
|
MEMU_EMBED_PROVIDER: 'openai',
|
|
@@ -127,7 +128,14 @@ export function localEmbeddingEnv({ baseUrl, token, model, db } = {}) {
|
|
|
127
128
|
}
|
|
128
129
|
if (typeof baseUrl === 'string' && baseUrl.trim()) env.MEMU_BASE_URL = baseUrl.trim()
|
|
129
130
|
if (typeof token === 'string' && token.trim()) env.MEMU_API_KEY = token.trim()
|
|
130
|
-
|
|
131
|
+
// The embeddings envelope has no role field, so a profile that reads query and
|
|
132
|
+
// document differently carries its role on the model string. Only this side knows
|
|
133
|
+
// which MemU process it is starting, so only this side may say so — and it has to:
|
|
134
|
+
// the worker refuses a bare model id for such a profile rather than guess (§14.4).
|
|
135
|
+
const modelId = rolesRequired === true && typeof model === 'string' && model.trim()
|
|
136
|
+
? modelIdForRole(model, role === 'query' ? 'query' : 'document')
|
|
137
|
+
: model
|
|
138
|
+
if (typeof modelId === 'string' && modelId.trim()) env.MEMU_EMBED_MODEL = modelId.trim()
|
|
131
139
|
if (typeof db === 'string' && db.trim()) env.MEMU_DB = db.trim()
|
|
132
140
|
return env
|
|
133
141
|
}
|
|
@@ -148,7 +156,7 @@ export async function retrieve({ query, db, provider, embedModel, baseUrl, apiKe
|
|
|
148
156
|
if (!query || !String(query).trim()) {
|
|
149
157
|
throw new MemuError('retrieve requires a non-empty query', 'MEMU_BAD_ARGUMENT')
|
|
150
158
|
}
|
|
151
|
-
const res = await runConfigured(['retrieve', String(query), '--json'], { db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs })
|
|
159
|
+
const res = await runConfigured(['retrieve', String(query), '--json'], { db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs, role: 'query' })
|
|
152
160
|
const data = parseJson(res.stdout)
|
|
153
161
|
if (data === null) {
|
|
154
162
|
return { raw: res.stdout.trim(), parseWarning: 'memu retrieve returned non-JSON' }
|
|
@@ -157,7 +165,7 @@ export async function retrieve({ query, db, provider, embedModel, baseUrl, apiKe
|
|
|
157
165
|
}
|
|
158
166
|
|
|
159
167
|
export async function listFiles({ db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs = 60_000 } = {}) {
|
|
160
|
-
const res = await runConfigured(['list-files', '--json'], { db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs })
|
|
168
|
+
const res = await runConfigured(['list-files', '--json'], { db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs, role: 'document' })
|
|
161
169
|
const data = parseJson(res.stdout)
|
|
162
170
|
if (data === null) {
|
|
163
171
|
return { recall_files: [], raw: res.stdout.trim(), parseWarning: 'memu list-files returned non-JSON' }
|
|
@@ -170,7 +178,7 @@ export async function commit({ payload, db, provider, embedModel, baseUrl, apiKe
|
|
|
170
178
|
const file = path.join(tmpDir, `commit-${process.pid}-${Date.now()}.json`)
|
|
171
179
|
try {
|
|
172
180
|
fs.writeFileSync(file, JSON.stringify(payload, null, 2), 'utf8')
|
|
173
|
-
const res = await runConfigured(['commit', file, '--json'], { db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs })
|
|
181
|
+
const res = await runConfigured(['commit', file, '--json'], { db, provider, embedModel, baseUrl, apiKey, vectorProfile, route, timeoutMs, role: 'document' })
|
|
174
182
|
const data = parseJson(res.stdout)
|
|
175
183
|
if (data === null) {
|
|
176
184
|
return { raw: res.stdout.trim(), parseWarning: 'memu commit returned non-JSON' }
|