dsh-memu-memory 1.2.2 → 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.
Files changed (58) hide show
  1. package/AGENTS.md +4 -1
  2. package/README.md +12 -16
  3. package/README.zh.md +13 -17
  4. package/docs/client-conventions.md +2 -0
  5. package/docs/contributing.md +7 -6
  6. package/docs/emotion-model-spec.md +2 -2
  7. package/docs/env-and-commands.md +63 -1
  8. package/docs/host-api.md +19 -0
  9. package/docs/memory-semantics.md +10 -1
  10. package/docs/troubleshooting.md +77 -3
  11. package/lib/activity-log.js +1 -1
  12. package/lib/binding-diagnostics.js +1 -1
  13. package/lib/client.js +223 -19
  14. package/lib/cycle.js +9 -1
  15. package/lib/embedding-catalog.js +416 -138
  16. package/lib/embedding-download.js +36 -11
  17. package/lib/freshness.js +97 -0
  18. package/lib/graph.js +244 -2
  19. package/lib/inject.js +218 -11
  20. package/lib/local-embedding-manager.js +3 -2
  21. package/lib/local-embedding-protocol.js +40 -3
  22. package/lib/local-embedding-worker.js +36 -6
  23. package/lib/local-vector-service.js +18 -4
  24. package/lib/memory.js +83 -17
  25. package/lib/memu.js +15 -7
  26. package/lib/private.js +25 -5
  27. package/lib/rpc.js +17 -3
  28. package/lib/salient-wake.js +402 -0
  29. package/lib/state.js +173 -1
  30. package/package.json +3 -2
  31. package/scripts/drive-session.mjs +864 -0
  32. package/scripts/mock-llm.mjs +903 -0
  33. package/scripts/simulate-injection.mjs +298 -0
  34. package/tests/client-render.test.mjs +69 -2
  35. package/tests/consolidation-fork.test.mjs +14 -1
  36. package/tests/drive-session.test.mjs +152 -0
  37. package/tests/embedding-catalog.test.mjs +116 -8
  38. package/tests/embedding-download.test.mjs +97 -2
  39. package/tests/embedding-runtime.test.mjs +21 -13
  40. package/tests/entity-merge.test.mjs +261 -0
  41. package/tests/fixtures/mock-llm/reply.txt +1 -0
  42. package/tests/freshness.test.mjs +140 -0
  43. package/tests/help-page.test.mjs +4 -4
  44. package/tests/injection-chain.test.mjs +176 -0
  45. package/tests/injection-rollback.test.mjs +230 -0
  46. package/tests/local-embedding-env.test.mjs +51 -0
  47. package/tests/local-embedding-manager.test.mjs +18 -0
  48. package/tests/local-embedding-protocol.test.mjs +28 -2
  49. package/tests/local-embedding-worker.test.mjs +94 -0
  50. package/tests/mock-llm.test.mjs +225 -0
  51. package/tests/open-loop-date.test.mjs +406 -0
  52. package/tests/salient-wake.test.mjs +362 -0
  53. package/tests/settings-plumbing.test.mjs +76 -0
  54. package/tests/sidebar.test.mjs +5 -1
  55. package/tests/simulate-injection.test.mjs +76 -0
  56. package/tests/stubs/dsh-schedule.js +105 -0
  57. package/tests/vector-profile.test.mjs +28 -4
  58. package/tests/webui-auth.test.mjs +4 -0
package/lib/inject.js CHANGED
@@ -4,6 +4,8 @@ import {
4
4
  getSettings, ensureSession, loadPrivateIndex, loadGlobalIndex,
5
5
  markInjected, releaseInjected, markReinjectPending, clearReinjectPending,
6
6
  armCue, getActiveCue, setSessionMood, wasAnniversaryShown, markAnniversaryShown,
7
+ recordInjectionRollback, rollbackInjectionForTurn, consumeInjectionRollback,
8
+ markOpenLoopReminded, DEFAULT_SETTINGS,
7
9
  touchSession, getSessionBinding, setSessionBinding, setRecallError, effectiveScope,
8
10
  } from './state.js'
9
11
  import {
@@ -16,8 +18,9 @@ import { record, clipQuery } from './activity-log.js'
16
18
  import { readMood } from './mood.js'
17
19
  import { loadPromptForDomain } from './prompts.js'
18
20
  import { estTokens, packToBudget, truncateToTokens } from './budget.js'
21
+ import { freshnessSignals } from './freshness.js'
19
22
  import { imageTurn, captureMediaEvent } from './media.js'
20
- import { redactSecrets } from './paths.js'
23
+ import { redactSecrets, warn } from './paths.js'
21
24
  import {
22
25
  INBOUND_TYPE, ingestInboundBatch, observeInboundEvent, hasPendingInbound, pendingInbound,
23
26
  noteNativeUserMessages, finishInbound, nextMemoryClock, advanceMemoryClock, releaseInboundSession,
@@ -395,6 +398,14 @@ export function buildAnniversary(sessionId, binding, now = new Date()) {
395
398
  lines.push('<memory-due>', '这些是你记下的带日期的约定或安排,时间到了,可以主动提一句;已经过去的不必再反复提起。')
396
399
  for (const [id, entry] of dated) {
397
400
  const ahead = salientDaysAhead(entry.salientDate, now)
401
+ // A promise reads differently from an appointment. "明天要考驾照" is a thing
402
+ // that happens; "我答应过要回电话" is a thing someone owes. The body stays out
403
+ // of the promise line: quoting a broken promise back at length sounds like an
404
+ // accusation, and the title is enough to recall the rest by id.
405
+ if (entry.openLoop === true && (ahead === 0 || ahead === 1)) {
406
+ lines.push(`- [${id}] 你之前答应过的「${entry.title || '(untitled)'}」,就是${ahead === 0 ? '今天' : '明天'}。`)
407
+ continue
408
+ }
398
409
  const when = ahead === 0 ? '就是今天' : ahead === 1 ? '就是明天' : `还有 ${ahead} 天`
399
410
  lines.push(`- [${id}] ${when}(${entry.salientDate})${entry.title || '(untitled)'}${entry.content ? `:${clip(entry.content, 200)}` : ''}`)
400
411
  }
@@ -680,27 +691,64 @@ export function buildReplay(binding, settings = getSettings(), sessionId = null)
680
691
  // what a person opens with. Retrieving it quietly among four other lines is not
681
692
  // resurfacing it, so it gets its own small block, one entry at a time, and only until
682
693
  // it has been mentioned (after which the id sits in injectedIds and is skipped).
694
+ //
695
+ // A dated promise that slipped its day is the exception: it comes back on its own
696
+ // interval (`openLoopRemindDays`) instead of vanishing after one mention, because
697
+ // "we said we would" is not resolved by having said it once. That leg is dated
698
+ // promises first (dueOpenLoops), then the ordinary 3-day loop.
683
699
  const OPEN_LOOP_DAYS = 3
684
700
  const OPEN_LOOP_TOKENS = 110
685
701
  const OPEN_LOOP_CLIP = 120
686
702
 
687
- export function buildOpenLoopNudge(binding, settings = getSettings(), sessionId = null) {
688
- if (!binding?.libraryId || binding.useLibrary === false) return { text: '', ids: [] }
703
+ // Local calendar day, matching how "today" is read everywhere else (the anniversary
704
+ // dayKey and the reminder clock both compare local days, not UTC days).
705
+ function localDayKey(now = new Date()) {
706
+ const date = now instanceof Date ? now : new Date(now)
707
+ return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
708
+ }
709
+
710
+ /**
711
+ * The `[open loop]` block, or an empty result.
712
+ *
713
+ * `skipIds` carries same-turn ids: memories another block (the anniversary) already
714
+ * put in front of the model this turnaround. `recurringIds` reports which of the
715
+ * emitted ids came from the overdue-dated leg, and only those are recorded in
716
+ * `openLoopRemindedAt` — the caller does that after the text is really sent.
717
+ */
718
+ export function buildOpenLoopNudge(binding, settings = getSettings(), sessionId = null, { skipIds = [], now = new Date() } = {}) {
719
+ const at = now instanceof Date ? now : new Date(now)
720
+ const empty = { text: '', ids: [], recurringIds: [], dayKey: localDayKey(at) }
721
+ if (!binding?.libraryId || binding.useLibrary === false) return empty
689
722
  const due = dueOpenLoops({
690
723
  libraryId: binding.libraryId,
691
724
  days: OPEN_LOOP_DAYS,
692
725
  limit: 1,
726
+ now: at.getTime(),
727
+ // The regular leg forgets an id once this conversation pushed it; the overdue leg
728
+ // only obeys its own reminder clock (see dueOpenLoops).
693
729
  skipIds: (binding.injectedIds || []).filter((id) => id !== ANCHOR_SENTINEL),
730
+ // Same-turn ids apply to both legs: the anniversary block already said this one.
731
+ excludeIds: skipIds,
732
+ remindDays: Number(settings?.openLoopRemindDays ?? DEFAULT_SETTINGS.openLoopRemindDays),
733
+ remindedAt: binding.openLoopRemindedAt || {},
734
+ includeOverdueDated: true,
735
+ sessionId,
694
736
  }).filter(({ entry }) => isAnchorEligible(entry) && visibleToSession(entry, sessionId))
695
- if (due.length === 0) return { text: '', ids: [] }
737
+ if (due.length === 0) return empty
738
+ const recurring = new Set(due.filter((item) => item.recurring).map((item) => item.id))
696
739
  const pack = packToBudget(due.map(({ id, entry }) => [id, entry]), OPEN_LOOP_TOKENS, (entry, id) => {
697
740
  const ago = relativeTime(entry.updatedAt || entry.createdAt)
698
- return `- [${id}] ${ownerPrefix(entry)}${entry.title || '(untitled)'}:${clip(entry.content || '', OPEN_LOOP_CLIP)}${ago ? ` · ${ago} 没下文了` : ''}${disclosureTag(entry)}`
741
+ // The date is what makes this leg re-raise itself; showing it lets the model say
742
+ // how late it is instead of inventing a time.
743
+ const slipped = recurring.has(id) && entry.salientDate ? ` · date=${entry.salientDate} 已经过了` : ''
744
+ return `- [${id}] ${ownerPrefix(entry)}${entry.title || '(untitled)'}${slipped}:${clip(entry.content || '', OPEN_LOOP_CLIP)}${ago ? ` · ${ago} 没下文了` : ''}${disclosureTag(entry)}`
699
745
  })
700
- if (pack.lines.length === 0) return { text: '', ids: [] }
746
+ if (pack.lines.length === 0) return empty
701
747
  return {
702
748
  text: ['[open loop] 有件事你一直没放下;合适的时候可以自己提一句,不必现在说。', ...pack.lines].join('\n'),
703
749
  ids: pack.ids,
750
+ recurringIds: pack.ids.filter((id) => recurring.has(id)),
751
+ dayKey: localDayKey(at),
704
752
  }
705
753
  }
706
754
 
@@ -753,11 +801,59 @@ function seenRecently(binding, id, turn, dedupeTurns) {
753
801
  return Number(turn) - Number(at) < Number(dedupeTurns || 8)
754
802
  }
755
803
 
804
+ // Work order D: one conditional footnote after the recall, not a second memory
805
+ // surface. It only says "if your session has a search tool, verify" — it must not
806
+ // claim that web_search exists, and it must never touch the guide or rulesKey.
807
+ function freshnessHintText(count) {
808
+ return [
809
+ '<memory-freshness>',
810
+ `上面有 ${count} 条记忆带时间敏感信号(写于较久前或提到「最新」等)。若你的会话里有可用的搜索工具,回答当前状态前先核实;没有就如实说明可能过时。`,
811
+ '</memory-freshness>',
812
+ ].join('\n')
813
+ }
814
+
815
+ function staleRecallCount(recalled, freshnessDays) {
816
+ const now = Date.now()
817
+ let stale = 0
818
+ for (const entry of recalled.values()) {
819
+ try {
820
+ if (freshnessSignals(entry, { now, freshnessDays }).stale) stale += 1
821
+ } catch (error) {
822
+ // Classification is decoration around a recall that already succeeded. A
823
+ // signal error drops at most this entry's vote, never the recall itself.
824
+ warn(`freshness hint: signal computation skipped: ${error?.message || error}`)
825
+ }
826
+ }
827
+ return stale
828
+ }
829
+
830
+ // Appended only when a non-empty <memory-context> block already exists, the query
831
+ // is long enough to have been a real ask, and the hint still fits the recall's own
832
+ // turnTokens ceiling. The ids counted are exactly the cards that reached the text.
833
+ function appendFreshnessHint(text, query, recalled, settings, budget) {
834
+ if (!text || settings.freshnessHint === false) return text
835
+ if (settings.autoInject === 'off' || settings.autoInject === 'anchor-only') return text
836
+ if (String(query ?? '').trim().length < Number(settings.minUserChars || 6)) return text
837
+ try {
838
+ const days = Number(settings.freshnessDays)
839
+ const freshnessDays = Number.isFinite(days) && days >= 1 ? days : 30
840
+ const stale = staleRecallCount(recalled, freshnessDays)
841
+ if (stale <= 0) return text
842
+ const hint = freshnessHintText(stale)
843
+ if (estTokens(`${text}\n\n${hint}`) > budget) return text
844
+ return `${text}\n\n${hint}`
845
+ } catch (error) {
846
+ warn(`freshness hint skipped: ${error?.message || error}`)
847
+ return text
848
+ }
849
+ }
850
+
756
851
  export async function buildRecall(binding, query, turn, settings = getSettings(), exec = null, sessionId = null) {
757
852
  if (!binding || !query) return { text: '', ids: [], errors: [] }
758
853
  const ids = []
759
854
  const pieces = []
760
855
  const errors = []
856
+ const recalled = new Map()
761
857
  let candidateCount = 0
762
858
  let privateRoute = null
763
859
  let globalRoute = null
@@ -864,11 +960,13 @@ export async function buildRecall(binding, query, turn, settings = getSettings()
864
960
  if (!line.includes(`[${file.name}]`)) continue
865
961
  lines.push(line)
866
962
  ids.push(file.name)
963
+ if (!recalled.has(file.name)) recalled.set(file.name, entry)
867
964
  }
868
965
  if (lines.length) blocks.push([open, intro, ...lines, close].join('\n'))
869
966
  }
870
- const text = blocks.join('\n\n')
967
+ let text = blocks.join('\n\n')
871
968
  if (!text) errors.push('recall omitted: token budget cannot fit a memory entry')
969
+ else text = appendFreshnessHint(text, query, recalled, settings, budget)
872
970
  return finish({ text, ids, errors, outcome: text ? 'injected' : 'budget', candidateCount })
873
971
  }
874
972
 
@@ -879,6 +977,36 @@ export function createMemoryMessage(text) {
879
977
  })
880
978
  }
881
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
+
882
1010
  // Every part of the first-step message is built from one binding snapshot, but
883
1011
  // retrieval awaits an external engine. During that window the conversation can be
884
1012
  // switched to another library, moved to another channel/character, or have a layer
@@ -1014,12 +1142,16 @@ function ensureUnifiedGuide(ctx, payload, decision) {
1014
1142
  if (guides.length === 0) return decision
1015
1143
  }
1016
1144
  const next = decision.messages.filter((message) => !isMemoryGuideMessage(message))
1017
- next.push(createMemoryMessage(guide.text))
1145
+ const guideMessage = createMemoryMessage(guide.text)
1146
+ next.push(guideMessage)
1018
1147
  setSessionBinding(sessionId, {
1019
1148
  guideRulesKey: guide.key,
1020
1149
  guideMessageAt: new Date().toISOString(),
1021
1150
  guideLost: false,
1022
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 {}
1023
1155
  record({
1024
1156
  kind: 'system',
1025
1157
  scope: 'private',
@@ -1163,20 +1295,28 @@ async function injectInboundForStep({ agent, decision, turn, signal, log, ctx })
1163
1295
  setRecallError(sessionId, 'inbound injection exceeded injectionTotalTokens')
1164
1296
  return decision
1165
1297
  }
1298
+ let inboundMessage = null
1166
1299
  if (text) {
1300
+ inboundMessage = createMemoryMessage(text)
1167
1301
  const pushed = [...new Set(ids)]
1302
+ const anchorPushed = anchorNeeded && Boolean(parts[0]?.startsWith('===== memory anchor'))
1168
1303
  markInjected(sessionId, pushed, clock)
1169
- if (anchorNeeded && parts[0]?.startsWith('===== memory anchor')) {
1304
+ if (anchorPushed) {
1170
1305
  markInjected(sessionId, [ANCHOR_SENTINEL], clock)
1171
1306
  clearReinjectPending(sessionId)
1172
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 {}
1173
1313
  try {
1174
1314
  if (scope.useLibrary && binding.libraryId) noteInjected({ libraryId: binding.libraryId, ids: pushed })
1175
1315
  if (scope.useGlobal) noteGlobalInjected({ ids: pushed })
1176
1316
  } catch (error) { try { log?.(`inbound injection accounting failed: ${error?.message || error}`) } catch {} }
1177
1317
  }
1178
1318
  finishInbound(sessionId, keys, clock, { reason: outcome, injectedCount: ids.length })
1179
- return text ? { ...decision, messages: [...decision.messages, createMemoryMessage(text)] } : decision
1319
+ return inboundMessage ? { ...decision, messages: [...decision.messages, inboundMessage] } : decision
1180
1320
  }
1181
1321
 
1182
1322
  export async function injectForStep({ agent, decision, turn, step, signal, log = null, ctx = null }) {
@@ -1304,22 +1444,32 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1304
1444
  }
1305
1445
  }
1306
1446
 
1447
+ // Same-turn dedup (工单 C / R1): the anniversary block and the open-loop nudge can
1448
+ // name the same memory, and saying it twice in one message reads like a glitch.
1449
+ // Only an anniversary that actually reached `parts` may suppress the nudge — one
1450
+ // the budget dropped must not silence it, because then the turn says nothing.
1451
+ let anniversaryIds = []
1452
+ let anniversaryFired = []
1307
1453
  if (!reinject) {
1308
1454
  const anniversary = buildAnniversary(sessionId, effective)
1309
1455
  if (anniversary.text && estTokens(anniversary.text) <= totalRoom()) {
1310
1456
  parts.push(anniversary.text)
1311
1457
  ids.push(...anniversary.ids)
1458
+ anniversaryIds = anniversary.ids
1459
+ anniversaryFired = anniversary.fired || []
1312
1460
  for (const id of anniversary.fired) markAnniversaryShown(sessionId, id, anniversary.dayKey)
1313
1461
  }
1314
1462
  }
1315
1463
 
1464
+ let recurringNudgeIds = []
1316
1465
  if (!reinject) {
1317
1466
  // Independent of retrieval: a loop can be worth raising in a conversation that
1318
1467
  // shares no vocabulary with it, which is exactly the case lexical recall misses.
1319
- const nudge = buildOpenLoopNudge(effective, settings, sessionId)
1468
+ const nudge = buildOpenLoopNudge(effective, settings, sessionId, { skipIds: anniversaryIds })
1320
1469
  if (nudge.text && estTokens(nudge.text) <= totalRoom()) {
1321
1470
  parts.push(nudge.text)
1322
1471
  ids.push(...nudge.ids)
1472
+ recurringNudgeIds = nudge.recurringIds
1323
1473
  }
1324
1474
  }
1325
1475
 
@@ -1401,6 +1551,21 @@ export async function injectForStep({ agent, decision, turn, step, signal, log =
1401
1551
  if (index < 0) return decision
1402
1552
  rewritten.splice(index, 0, message)
1403
1553
  markInjected(sessionId, ids, memoryClock)
1554
+ // An overdue dated promise is repeated on its own interval; that clock only starts
1555
+ // once the text is really published. Everything above this line (budget, snapshot
1556
+ // re-check) can still drop the block, and a dropped reminder must not count.
1557
+ for (const id of recurringNudgeIds) {
1558
+ try { markOpenLoopReminded(sessionId, id) } catch {}
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 {}
1404
1569
  if (reinject) {
1405
1570
  clearReinjectPending(sessionId)
1406
1571
  // The replay has been paid for; it must not ride along on the next compaction too.
@@ -1444,6 +1609,48 @@ export function registerInjection(ctx) {
1444
1609
  disposers.push(offPre)
1445
1610
 
1446
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
+ }
1447
1654
  try {
1448
1655
  observeInboundEvent(ctx, session, event)
1449
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
- if (!expected || requested !== expected) {
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
- return { model, dimension, modelDir: path.resolve(dir) }
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
- if (pooling === 'mean' && tokens > 1) {
235
- const weights = mask && mask[row] ? mask[row] : null
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
- const result = await getDownloader().download(modelId, { confirmed: options.confirmed === true })
181
- // Model and runtime downloads each require their own explicit confirmation.
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: endpoint.model, input: ['本地向量健康检查'] }),
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) {