dsh-memu-memory 1.2.5 → 1.2.6
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 +3 -1
- package/README.md +3 -3
- package/README.zh.md +3 -3
- package/docs/env-and-commands.md +1 -0
- package/docs/host-adaptation.md +318 -0
- package/docs/host-api.md +29 -5
- package/docs/memory-semantics.md +9 -6
- package/docs/troubleshooting.md +12 -8
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +16 -10
- package/lib/consolidation-ledger.js +46 -1
- package/lib/consolidation-worker.js +1 -0
- package/lib/cycle.js +51 -17
- package/lib/index.js +8 -0
- package/lib/memu.js +318 -3
- package/lib/private.js +310 -67
- package/lib/rpc.js +13 -3
- package/lib/salient-wake.js +38 -2
- package/lib/state.js +3 -5
- package/package.json +1 -1
- package/tests/absorb-review.test.mjs +2 -1
- package/tests/backend-compensation.test.mjs +1 -1
- package/tests/consolidation-fork.test.mjs +81 -6
- package/tests/curator-absorb.test.mjs +2 -1
- package/tests/curator-clusters.test.mjs +2 -1
- package/tests/curator-commit.test.mjs +2 -1
- package/tests/curator-link.test.mjs +2 -1
- package/tests/curator-review-mode.test.mjs +2 -1
- package/tests/cycle.test.mjs +2 -2
- package/tests/managed-memory.test.mjs +1 -1
- package/tests/recall-dedup.test.mjs +1 -1
- package/tests/salient-wake.test.mjs +28 -1
- package/tests/stubs/dsh-schedule.js +35 -0
- package/tests/ui-defaults.test.mjs +1 -1
package/lib/client.js
CHANGED
|
@@ -2303,18 +2303,17 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
|
|
|
2303
2303
|
return enumText(t, DOMAIN_LABELS, raw)
|
|
2304
2304
|
}
|
|
2305
2305
|
|
|
2306
|
-
//
|
|
2306
|
+
// 情绪构成:四轴按固定顺序完整输出(喜/怒/哀/惧),不截断、不重排。
|
|
2307
|
+
// 只显示 top-2 会让“喜0.6/哀0.4”看起来像只有两种情绪,而构成本来就是四维;
|
|
2308
|
+
// 同理,阈值过滤会把小分量的轴吞掉,看不出“四轴各是多少”。
|
|
2307
2309
|
// 四轴固定且术语极短,就地映射,不为四个轴各加一个 i18n key。
|
|
2308
2310
|
const EMOTION_TAG_LABELS = { joy: '喜', anger: '怒', sorrow: '哀', fear: '惧' }
|
|
2309
2311
|
function emotionTagText(emotion) {
|
|
2310
2312
|
if (!emotion || typeof emotion !== 'object') return ''
|
|
2311
|
-
|
|
2313
|
+
const axes = Object.entries(EMOTION_TAG_LABELS)
|
|
2312
2314
|
.map(([axis, label]) => ({ label, share: Number(emotion[axis]) || 0 }))
|
|
2313
|
-
|
|
2314
|
-
|
|
2315
|
-
.slice(0, 2)
|
|
2316
|
-
.map((item) => `${item.label}${item.share.toFixed(1)}`)
|
|
2317
|
-
.join('/')
|
|
2315
|
+
if (!axes.some((item) => item.share > 0)) return ''
|
|
2316
|
+
return axes.map((item) => `${item.label}${item.share.toFixed(2)}`).join('/')
|
|
2318
2317
|
}
|
|
2319
2318
|
|
|
2320
2319
|
const EMOTION_SOURCE_LABELS = {
|
|
@@ -3101,6 +3100,11 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
|
|
|
3101
3100
|
}
|
|
3102
3101
|
|
|
3103
3102
|
const shown = detail ? { ...detail.item, ...(detail.file || {}) } : null
|
|
3103
|
+
// 详情抽屉与卡片共用同一份情绪行:四轴构成 + 激活/掌控/来源,缺哪段就少哪段。
|
|
3104
|
+
const affectText = shown
|
|
3105
|
+
? [emotionTagText(shown.emotion) ? `${t('moodTag')} ${emotionTagText(shown.emotion)}` : '', emotionMetaText(shown, t)]
|
|
3106
|
+
.filter(Boolean).join(' · ')
|
|
3107
|
+
: ''
|
|
3104
3108
|
const detailForm = detail && detail.file && !detail.readonly
|
|
3105
3109
|
? h('div', { className: 'dshm-drawer-form' },
|
|
3106
3110
|
h('input', {
|
|
@@ -3145,7 +3149,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
|
|
|
3145
3149
|
h('div', { className: 'dshm-drawer-note' },
|
|
3146
3150
|
t('decay') + ' ' + Math.round((Number(shown.decay) || 0) * 100) + '% · ' +
|
|
3147
3151
|
(shown.updatedAt ? String(shown.updatedAt).slice(0, 16).replace('T', ' ') : '')),
|
|
3148
|
-
|
|
3152
|
+
affectText ? h('div', { className: 'dshm-drawer-note' }, affectText) : null)
|
|
3149
3153
|
: detail && detail.file && detail.readonly
|
|
3150
3154
|
? (() => {
|
|
3151
3155
|
// 全局条目只读(spec §6.7 UI):详情抽屉里只读展示 links / absorbedFrom,
|
|
@@ -5345,7 +5349,7 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
|
|
|
5345
5349
|
names: settings.inboundToolNames || [], onChange: values => setSetting('inboundToolNames', values),
|
|
5346
5350
|
})),
|
|
5347
5351
|
h(Field, { label: t('sleepConsolidation') }, h('input', { type: 'checkbox', checked: settings.sleepConsolidation === true, onChange: (e) => setSetting('sleepConsolidation', e.target.checked) })),
|
|
5348
|
-
h(Field, { label: t('sleepAfterIdleMinutes') }, h('input', { type: 'number', min: 1, style: S.input, value: settings.sleepAfterIdleMinutes ??
|
|
5352
|
+
h(Field, { label: t('sleepAfterIdleMinutes') }, h('input', { type: 'number', min: 1, style: S.input, value: settings.sleepAfterIdleMinutes ?? 2, onChange: (e) => setSetting('sleepAfterIdleMinutes', Number(e.target.value)) })),
|
|
5349
5353
|
h(Field, { label: t('autoCurateEveryHours') }, h('input', { type: 'number', min: 0, style: S.input, value: settings.autoCurateEveryHours ?? 0, onChange: (e) => setSetting('autoCurateEveryHours', Number(e.target.value)) })),
|
|
5350
5354
|
h(Field, { label: t('autoCurateSessionLimit') }, h('input', { type: 'number', min: 1, max: 30, style: S.input, value: settings.autoCurateSessionLimit ?? 8, onChange: (e) => setSetting('autoCurateSessionLimit', Number(e.target.value)) })),
|
|
5351
5355
|
h(Field, { label: t('purgeArchivedAfterDays') }, h('input', { type: 'number', min: 0, style: S.input, value: settings.purgeArchivedAfterDays ?? 0, onChange: (e) => setSetting('purgeArchivedAfterDays', Number(e.target.value)) })),
|
|
@@ -5670,7 +5674,9 @@ const SOURCE_LABELS = { user_said: 'sourceUserSaid', inferred: 'sourceInferred',
|
|
|
5670
5674
|
f.salientDate
|
|
5671
5675
|
? h(Tag, null, `${/^\d{4}-\d{2}-\d{2}$/.test(f.salientDate) ? t('dueDateTag') : t('anniversaryTag')} ${f.salientDate}`)
|
|
5672
5676
|
: null,
|
|
5673
|
-
|
|
5677
|
+
// 四轴构成放在 Tag 里;激活/掌控/来源直接可见,不再只藏在悬停提示里。
|
|
5678
|
+
moodText ? h(Tag, null, `${t('moodTag')} ${moodText}`) : null,
|
|
5679
|
+
emotionMetaText(f, t) ? h('span', { style: S.muted }, emotionMetaText(f, t)) : null,
|
|
5674
5680
|
typeof f.accuracy === 'number' && typeof f.confidence === 'number' && f.accuracy <= 0.6 && f.accuracy < f.confidence - 0.1
|
|
5675
5681
|
? h(Tag, { tone: 'warn' }, `${t('accuracyTag')} ${f.accuracy}`) : null,
|
|
5676
5682
|
h(Tag, null, enumText(t, STATUS_LABELS, f.status || 'active'))),
|
|
@@ -273,6 +273,19 @@ export function failJob({ sessionId, jobId, reasonCode = 'failed', retryable = t
|
|
|
273
273
|
}
|
|
274
274
|
entry.lastReasonCode = reasonCode
|
|
275
275
|
entry.lastError = clampText(error || reasonCode)
|
|
276
|
+
// 同一快照的失败次数单独记:窗口已经很小,但同一段转录不该无限重跑。
|
|
277
|
+
// 新事件会改变 snapshotHash,自然得到一份新的操作键与新的机会。
|
|
278
|
+
if (job.snapshot?.hash) {
|
|
279
|
+
const key = operationKey({ sessionId, libraryId: job.libraryId, snapshotHash: job.snapshot.hash, scopeGeneration: job.scopeGeneration })
|
|
280
|
+
const prior = entry.operations[key]
|
|
281
|
+
entry.operations[key] = {
|
|
282
|
+
outcome: 'failed',
|
|
283
|
+
ids: Array.isArray(prior?.ids) ? prior.ids : [],
|
|
284
|
+
at: stamp(),
|
|
285
|
+
failures: (Number(prior?.failures) || 0) + 1,
|
|
286
|
+
firstFailedAt: prior?.firstFailedAt || stamp(),
|
|
287
|
+
}
|
|
288
|
+
}
|
|
276
289
|
pushHistory(entry, { jobId, status: 'failed', reasonCode, at: stamp() })
|
|
277
290
|
entry.updatedAt = stamp()
|
|
278
291
|
return { pending: entry.pending, retryAt: entry.retryAt || null, attempts: entry.attempts }
|
|
@@ -323,7 +336,8 @@ export function findOperation(sessionId, key, ledger = loadLedger()) {
|
|
|
323
336
|
export function recordOperation({ sessionId, key, outcome, ids = [], at = Date.now() }) {
|
|
324
337
|
return mutateLedger((ledger) => {
|
|
325
338
|
const entry = ensureEntry(ledger, sessionId)
|
|
326
|
-
|
|
339
|
+
// A later success clears the same-snapshot failure streak.
|
|
340
|
+
entry.operations[String(key)] = { outcome, ids: Array.isArray(ids) ? ids.slice(0, 50) : [], at: new Date(at).toISOString(), failures: 0 }
|
|
327
341
|
const keys = Object.keys(entry.operations)
|
|
328
342
|
if (keys.length > OPERATION_LIMIT) {
|
|
329
343
|
for (const stale of keys.slice(0, keys.length - OPERATION_LIMIT)) delete entry.operations[stale]
|
|
@@ -333,6 +347,37 @@ export function recordOperation({ sessionId, key, outcome, ids = [], at = Date.n
|
|
|
333
347
|
})
|
|
334
348
|
}
|
|
335
349
|
|
|
350
|
+
/**
|
|
351
|
+
* 政策跳过:评估结论是「这段本来就不值得写」(寒暄 / 没有真人回合),
|
|
352
|
+
* 不是失败也不是 worker 回执。把 checked 推进到这段快照,pending 同步裁剪,
|
|
353
|
+
* 否则 pending 会一直把同一段寒暄当成 backlog,扫描每 5 分钟重读一次。
|
|
354
|
+
*/
|
|
355
|
+
export function skipRange({ sessionId, snapshot, reasonCode = 'no-value' }) {
|
|
356
|
+
return mutateLedger((ledger) => {
|
|
357
|
+
const entry = ensureEntry(ledger, sessionId)
|
|
358
|
+
const from = Number(snapshot?.fromSeq)
|
|
359
|
+
const through = Number(snapshot?.throughSeq)
|
|
360
|
+
if (!Number.isSafeInteger(from) || !Number.isSafeInteger(through) || through < from) {
|
|
361
|
+
return { advanced: false, checked: entry.checked, pending: entry.pending }
|
|
362
|
+
}
|
|
363
|
+
entry.checked = {
|
|
364
|
+
fromSeq: from, throughSeq: through, at: stamp(), status: 'skipped',
|
|
365
|
+
outcome: 'no_value', jobId: null, reasonCode, snapshotHash: snapshot?.hash || null,
|
|
366
|
+
eventCount: snapshot?.eventCount ?? null, receipt: null,
|
|
367
|
+
}
|
|
368
|
+
const pendingThrough = Number(entry.pending?.throughSeq)
|
|
369
|
+
if (entry.pending && (!Number.isSafeInteger(pendingThrough) || pendingThrough <= through)) entry.pending = null
|
|
370
|
+
else if (entry.pending) entry.pending = { fromSeq: through + 1, throughSeq: pendingThrough, at: entry.pending.at }
|
|
371
|
+
entry.attempts = 0
|
|
372
|
+
entry.retryAt = null
|
|
373
|
+
entry.lastReasonCode = reasonCode
|
|
374
|
+
entry.lastError = null
|
|
375
|
+
pushHistory(entry, { jobId: null, status: 'skipped', outcome: 'no_value', reasonCode, at: stamp() })
|
|
376
|
+
entry.updatedAt = stamp()
|
|
377
|
+
return { advanced: true, checked: entry.checked, pending: entry.pending }
|
|
378
|
+
})
|
|
379
|
+
}
|
|
380
|
+
|
|
336
381
|
export function clearSessionState(sessionId) {
|
|
337
382
|
return mutateLedger((ledger) => {
|
|
338
383
|
delete ledger.sessions[String(sessionId || '')]
|
|
@@ -150,6 +150,7 @@ export function buildWorkerBrief({ snapshot, probe = null, contract = '', reason
|
|
|
150
150
|
'[私有整理 worker' + (jobId ? ' · ' + jobId : '') + ' · ' + (reason === 'manual' ? '手动' : '自动') + ']',
|
|
151
151
|
'你不是这场对话里的角色,也不继承上面转录的说话方式:你是后台整理私有记忆的 worker。',
|
|
152
152
|
'只处理 ' + rangeLine(snapshot) + ';范围之外的内容不要读、不要推断、不要写。',
|
|
153
|
+
'转录开头的 [memory-catalog · 已有记忆目录] 是本库已有条目,只用来去重/合并,不是对话内容,也不是用户发言。',
|
|
153
154
|
'本轮可用的工具:' + tools + '。',
|
|
154
155
|
'要做的:先按主题检索相关旧条目去重;同一事实的补充用 memu_private_update 合并(先拿到 id);真正新增、或与已有说法矛盾的内容用 memu_private_remember 一条一件;矛盾不要自己裁决,让它进待复核。',
|
|
155
156
|
'写完(remember/update 拿到 id)后调用 memu_private_link_suggest({ids:[...]}),把本轮创建/更新的 id 都传进去:高置信的记忆↔记忆关联与实体枢纽算法已经自动连好,只有不确定的候选交给你裁决。不回读整段会话,也不为这个另起一次整理。',
|
package/lib/cycle.js
CHANGED
|
@@ -4,13 +4,13 @@ import {
|
|
|
4
4
|
deleteLibrary, restoreLibrary, normalizeCwd,
|
|
5
5
|
} from './state.js'
|
|
6
6
|
import { expireShortTerm } from './memory.js'
|
|
7
|
-
import { requestPrivateConsolidation } from './private.js'
|
|
7
|
+
import { requestPrivateConsolidation, CONSOLIDATION_BACKLOG_EVENTS, CONSOLIDATION_PROBE_MINUTES } from './private.js'
|
|
8
8
|
import { startGlobalCuration } from './curator.js'
|
|
9
9
|
import { runVisibilityMigrationPass } from './migrate.js'
|
|
10
10
|
import { runSalientWakePass } from './salient-wake.js'
|
|
11
11
|
import { record } from './activity-log.js'
|
|
12
12
|
import { ACTIVE_MEMORY_POLICY, suppressionReason } from './active-memory.js'
|
|
13
|
-
import { clearSessionState } from './consolidation-ledger.js'
|
|
13
|
+
import { clearSessionState, loadLedger, sessionState } from './consolidation-ledger.js'
|
|
14
14
|
|
|
15
15
|
const SWEEP_MS = 5 * 60 * 1000
|
|
16
16
|
// Long enough that the host has restored its session list and the agent objects
|
|
@@ -77,27 +77,52 @@ export function isGoneSessionError(message) {
|
|
|
77
77
|
export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limit = 2 } = {}) {
|
|
78
78
|
const settings = getSettings()
|
|
79
79
|
if (settings.sleepConsolidation !== true) return { ran: 0, skipped: 'disabled' }
|
|
80
|
-
const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) ||
|
|
80
|
+
const idleMs = Math.max(1, Number(settings.sleepAfterIdleMinutes) || 2) * 60_000
|
|
81
|
+
const probeMs = Math.max(1, Number(CONSOLIDATION_PROBE_MINUTES) || 15) * 60_000
|
|
82
|
+
// One ledger read per sweep: pending backlog is the cheap水位 signal that does
|
|
83
|
+
// not need a transcript read.
|
|
84
|
+
let ledger = null
|
|
85
|
+
try { ledger = loadLedger() } catch { ledger = null }
|
|
81
86
|
const candidates = []
|
|
82
87
|
for (const binding of listSessionBindings()) {
|
|
83
88
|
if (binding.consolidationFork || !binding.lastTurnAt) continue
|
|
84
89
|
if (binding.sessionGone) continue
|
|
90
|
+
const lastSleepAt = getLastSleepAt(binding.sessionId)
|
|
85
91
|
const activeAt = Math.max(Date.parse(binding.lastTurnAt) || 0, Date.parse(binding.lastInboundAt) || 0, Date.parse(binding.lastAgentIdleAt) || 0)
|
|
86
|
-
|
|
92
|
+
const idle = now - activeAt >= idleMs
|
|
93
|
+
const newActivity = older(lastSleepAt, binding.lastTurnAt) < 0
|
|
94
|
+
const state = ledger ? sessionState(binding.sessionId, ledger) : null
|
|
95
|
+
const pendingEvents = state?.pending && (!state.checked || state.pending.throughSeq > state.checked.throughSeq)
|
|
96
|
+
? Number(state.pending.throughSeq) - (Number.isSafeInteger(Number(state.checked?.throughSeq)) ? Number(state.checked.throughSeq) : -1)
|
|
97
|
+
: 0
|
|
98
|
+
const backlog = pendingEvents >= CONSOLIDATION_BACKLOG_EVENTS
|
|
99
|
+
const neverSlept = !lastSleepAt
|
|
100
|
+
const lastProbe = Date.parse(binding.lastConsolidationProbeAt || '') || 0
|
|
101
|
+
const probeDue = newActivity && now - lastProbe >= probeMs
|
|
102
|
+
// Idle time alone is not new evidence: after a successful window the sleep
|
|
103
|
+
// stamp already covers the transcript, so a quiet idle sweep must not fork it again.
|
|
104
|
+
if (!newActivity && !backlog) continue
|
|
105
|
+
// Three independent reasons to look: idle (normal), a real pending backlog
|
|
106
|
+
// (watermark), or a bounded probe when new activity has arrived but not enough
|
|
107
|
+
// to know its size yet. The probe reads the transcript and decides without a
|
|
108
|
+
// fork, so it costs CPU, not tokens.
|
|
109
|
+
if (!idle && !backlog && !neverSlept && !probeDue) continue
|
|
87
110
|
// Running includes a long-lived asynchronous tool. Waiting is not proof that
|
|
88
111
|
// the conversation ended, and a fork should not race its active agent.
|
|
89
112
|
if (liveAgent(ctx, binding.sessionId)?.status === 'running') continue
|
|
90
113
|
if (binding.inbound?.pending?.length) continue
|
|
91
|
-
if (older(getLastSleepAt(binding.sessionId), binding.lastTurnAt) >= 0) continue
|
|
92
114
|
if ((Date.parse(binding.sleepRetryAt || '') || 0) > now) continue
|
|
93
|
-
|
|
115
|
+
// Backlog first, then real idle, then cheap probes: a sweep with a limited
|
|
116
|
+
// budget must not let probe-only sessions crowd out work that is actually due.
|
|
117
|
+
candidates.push({ binding, activeAt, trigger: idle ? 'idle' : 'backlog', priority: backlog ? 3 : idle ? 2 : 1 })
|
|
94
118
|
}
|
|
95
|
-
// Newest first: a catch-up run after the app was closed
|
|
96
|
-
// just lived through, not a week-old chat that has
|
|
97
|
-
|
|
119
|
+
// Newest first within the same priority: a catch-up run after the app was closed
|
|
120
|
+
// should tidy what the user just lived through, not a week-old chat that has
|
|
121
|
+
// already waited this long.
|
|
122
|
+
candidates.sort((a, b) => (b.priority - a.priority) || (b.activeAt - a.activeAt))
|
|
98
123
|
const budget = Math.max(1, Math.min(10, Number(limit) || 2))
|
|
99
124
|
let ran = 0
|
|
100
|
-
for (const { binding } of candidates.slice(0, budget)) {
|
|
125
|
+
for (const { binding, trigger } of candidates.slice(0, budget)) {
|
|
101
126
|
if (binding.useLibrary === false) {
|
|
102
127
|
setLastSleepAt(binding.sessionId)
|
|
103
128
|
continue
|
|
@@ -108,8 +133,6 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
108
133
|
// A live session used to be consolidated in place, which is exactly what put
|
|
109
134
|
// a queued draft above the user's composer and then left a housekeeping turn
|
|
110
135
|
// in their transcript for good.
|
|
111
|
-
// 近期刚整理过、或刚注入过记忆的会话不再 fork:长会话每次整理都会把整段
|
|
112
|
-
// 转录种进子会话,连续触发等于重复付同一笔 token。
|
|
113
136
|
const suppression = suppressionReason({
|
|
114
137
|
now,
|
|
115
138
|
lastSleepAt: getLastSleepAt(binding.sessionId),
|
|
@@ -117,28 +140,39 @@ export async function runSleepPass(ctx, { now = Date.now(), log = () => {}, limi
|
|
|
117
140
|
consolidatedCooldownMinutes: Number(settings.activeMemoryCooldownMinutes ?? ACTIVE_MEMORY_POLICY.consolidatedCooldownMinutes),
|
|
118
141
|
recallCooldownMinutes: Number(settings.activeMemoryRecallCooldownMinutes ?? ACTIVE_MEMORY_POLICY.recallCooldownMinutes),
|
|
119
142
|
})
|
|
120
|
-
|
|
143
|
+
// 「刚注入过记忆」只压空闲收尾,不压水位/探针:后者先读转录再决定,不合并不 fork。
|
|
144
|
+
const blocked = suppression && !(trigger === 'backlog' && suppression === 'recent-recall')
|
|
145
|
+
if (blocked) {
|
|
121
146
|
log(`sleep consolidation suppressed for ${binding.sessionId}: ${suppression}`)
|
|
122
147
|
record({
|
|
123
148
|
kind: 'check', scope: 'private', sessionId: binding.sessionId, libraryId: binding.libraryId || null, ok: true,
|
|
124
149
|
message: '闲时检查抑制:' + suppression,
|
|
125
|
-
detail: { trigger
|
|
150
|
+
detail: { trigger, reason: suppression, lastSleepAt: getLastSleepAt(binding.sessionId), lastInjectedAt: binding.lastInjectedAt || null },
|
|
126
151
|
})
|
|
127
152
|
continue
|
|
128
153
|
}
|
|
129
154
|
try {
|
|
130
|
-
const result = await requestPrivateConsolidation(ctx, binding.sessionId)
|
|
155
|
+
const result = await requestPrivateConsolidation(ctx, binding.sessionId, { trigger })
|
|
131
156
|
if (result?.ok) {
|
|
132
157
|
// 证据不足(low-score)不是"已整理":不推进游标、不计数,等空闲越过饥饿阈值
|
|
133
158
|
// 或后续证据变多再检查。否则这句话会被永久跳过。
|
|
134
159
|
if (result.settled === false) {
|
|
160
|
+
// 探针/水位不足阈值:记下这次探针时间,避免每 5 分钟重读同一段。
|
|
161
|
+
if (result.skipped === 'backlog-below-threshold' || result.deferred === true) {
|
|
162
|
+
setSessionBinding(binding.sessionId, { lastConsolidationProbeAt: new Date(now).toISOString() })
|
|
163
|
+
}
|
|
135
164
|
log(`sleep consolidation deferred for ${binding.sessionId}: ${result.skipped || 'not settled'}`)
|
|
136
165
|
continue
|
|
137
166
|
}
|
|
138
167
|
// Only cover activity this pass began with, not new messages during it.
|
|
139
168
|
setLastSleepAt(binding.sessionId, binding.lastTurnAt)
|
|
140
|
-
setSessionBinding(binding.sessionId, {
|
|
141
|
-
|
|
169
|
+
setSessionBinding(binding.sessionId, {
|
|
170
|
+
sleepRetryAt: null, sleepAttempts: 0, lastSleepError: null,
|
|
171
|
+
lastConsolidationProbeAt: new Date(now).toISOString(),
|
|
172
|
+
})
|
|
173
|
+
// A terminal policy skip (greetings, no new events) advances the sleep stamp
|
|
174
|
+
// but is not a verified worker run; `ran` must keep that distinction.
|
|
175
|
+
if (!result.skipped) ran += 1
|
|
142
176
|
} else if (isGoneSessionError(result?.error)) {
|
|
143
177
|
setSessionBinding(binding.sessionId, { sessionGone: true, sessionGoneAt: new Date(now).toISOString(), sleepRetryAt: null, sleepAttempts: 0, lastSleepError: String(result.error) })
|
|
144
178
|
try { clearSessionState(binding.sessionId) } catch {}
|
package/lib/index.js
CHANGED
|
@@ -9,6 +9,7 @@ import { getSettings, getMemoryBackend, backupDatabases, flushState, listLibrari
|
|
|
9
9
|
import { pruneOrphanEntitiesAll } from './graph.js'
|
|
10
10
|
import { closeEmbeddingWorkers } from './local-embedding-manager.js'
|
|
11
11
|
import { bootstrapLocalVector } from './local-vector-service.js'
|
|
12
|
+
import { closeMemuResident, prewarmMemuResident } from './memu.js'
|
|
12
13
|
import { vectorStatus } from './vector-profile.js'
|
|
13
14
|
import { setWarnSink } from './paths.js'
|
|
14
15
|
|
|
@@ -30,6 +31,10 @@ function startLocalVectorBootstrap(ctx) {
|
|
|
30
31
|
const catalogId = state?.active?.profile?.catalogId || state?.requested?.catalogId || null
|
|
31
32
|
if (!catalogId) return
|
|
32
33
|
const timer = setTimeout(() => {
|
|
34
|
+
// The resident interpreter only pays the MemU import once; it does not wait
|
|
35
|
+
// for the embedding worker, so warming it in parallel with the runtime
|
|
36
|
+
// bootstrap is safe and keeps the first recall from paying the cold start.
|
|
37
|
+
void prewarmMemuResident()
|
|
33
38
|
void bootstrapLocalVector({ confirmed: false }).then((ready) => {
|
|
34
39
|
try { ctx.logger?.info?.(`dsh-memu-memory: managed local embedding runtime ready (${String(ready?.model || catalogId)} ${Number(ready?.dimension) || '?'}d)`) } catch {}
|
|
35
40
|
}).catch((error) => {
|
|
@@ -162,6 +167,9 @@ export function apply(ctx, config) {
|
|
|
162
167
|
// afterwards instead of failing.
|
|
163
168
|
if (!inPreset && typeof ctx.effect === 'function') {
|
|
164
169
|
ctx.effect(() => () => { closeEmbeddingWorkers() }, 'dsh-memu-memory: embedding workers')
|
|
170
|
+
// The resident interpreter is also process-global; leaving it behind would keep
|
|
171
|
+
// a Python process (and its sqlite handles) alive after this plugin unloads.
|
|
172
|
+
ctx.effect(() => () => { closeMemuResident() }, 'dsh-memu-memory: memu resident engine')
|
|
165
173
|
}
|
|
166
174
|
|
|
167
175
|
const disposeCycle = inPreset ? null : registerCycle(ctx, {
|
package/lib/memu.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import fs from 'node:fs'
|
|
2
2
|
import path from 'node:path'
|
|
3
3
|
import { spawn } from 'node:child_process'
|
|
4
|
-
import { dataDir, ensureDir, redactSecrets, windowsSystemEnv } from './paths.js'
|
|
4
|
+
import { dataDir, ensureDir, redactSecrets, warn, windowsSystemEnv } from './paths.js'
|
|
5
5
|
import { ENGINE_VERSION, readCurrent, verifyEngine } from './engine.js'
|
|
6
|
-
import { getSettings } from './state.js'
|
|
6
|
+
import { effectiveVectorRoute, 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
9
|
import { modelIdForRole } from './local-embedding-protocol.js'
|
|
@@ -79,6 +79,316 @@ function runRaw(pythonArgs, { env, timeoutMs = 90_000, cwd } = {}) {
|
|
|
79
79
|
})
|
|
80
80
|
}
|
|
81
81
|
|
|
82
|
+
// ---- resident engine ---------------------------------------------------------
|
|
83
|
+
// MemU is a Python CLI: every command normally pays the whole import chain
|
|
84
|
+
// (~2 s), because the process exits when the command ends. Local vector mode
|
|
85
|
+
// calls the same three commands on every turn (recall) and on every write,
|
|
86
|
+
// so one warm interpreter removes that constant from both paths.
|
|
87
|
+
//
|
|
88
|
+
// The worker imports ``memu.cli`` once and calls the exact ``main(argv)`` the
|
|
89
|
+
// CLI entrypoint calls — command semantics stay in MemU's own code. One JSON
|
|
90
|
+
// object per line is the protocol on both directions. ``_close_backends`` is
|
|
91
|
+
// what keeps the per-command process model intact: a command that ends must
|
|
92
|
+
// release its sqlite handles, otherwise backup / migration / rollback would
|
|
93
|
+
// see a database still held open by a process that is supposed to be idle.
|
|
94
|
+
const RESIDENT_SCRIPT = String.raw`
|
|
95
|
+
import contextlib
|
|
96
|
+
import io
|
|
97
|
+
import json
|
|
98
|
+
import os
|
|
99
|
+
import sys
|
|
100
|
+
|
|
101
|
+
for _stream in (sys.stdin, sys.stdout, sys.stderr):
|
|
102
|
+
try:
|
|
103
|
+
_stream.reconfigure(encoding="utf-8", errors="replace")
|
|
104
|
+
except Exception:
|
|
105
|
+
pass
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _reply(payload):
|
|
109
|
+
sys.stdout.write(json.dumps(payload, ensure_ascii=False) + "\n")
|
|
110
|
+
sys.stdout.flush()
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
BASE_ENV = dict(os.environ)
|
|
114
|
+
try:
|
|
115
|
+
import memu.cli as _cli
|
|
116
|
+
except Exception as _exc:
|
|
117
|
+
_reply({"ready": False, "error": "memu import failed: %s" % (_exc,)})
|
|
118
|
+
raise SystemExit(1)
|
|
119
|
+
|
|
120
|
+
_original_build = _cli.build_agentic_memory_backend_from_env
|
|
121
|
+
_created = []
|
|
122
|
+
|
|
123
|
+
|
|
124
|
+
def _tracked_build(*args, **kwargs):
|
|
125
|
+
backend = _original_build(*args, **kwargs)
|
|
126
|
+
_created.append(backend)
|
|
127
|
+
return backend
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
_cli.build_agentic_memory_backend_from_env = _tracked_build
|
|
131
|
+
|
|
132
|
+
|
|
133
|
+
def _close_backends():
|
|
134
|
+
while _created:
|
|
135
|
+
backend = _created.pop()
|
|
136
|
+
try:
|
|
137
|
+
closer = getattr(getattr(backend, "database", None), "close", None)
|
|
138
|
+
if callable(closer):
|
|
139
|
+
closer()
|
|
140
|
+
except Exception:
|
|
141
|
+
pass
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
_reply({"ready": True})
|
|
145
|
+
|
|
146
|
+
for _line in sys.stdin:
|
|
147
|
+
_line = _line.strip()
|
|
148
|
+
if not _line:
|
|
149
|
+
continue
|
|
150
|
+
try:
|
|
151
|
+
_request = json.loads(_line)
|
|
152
|
+
except Exception:
|
|
153
|
+
continue
|
|
154
|
+
if _request.get("op") == "shutdown":
|
|
155
|
+
break
|
|
156
|
+
os.environ.clear()
|
|
157
|
+
os.environ.update(BASE_ENV)
|
|
158
|
+
for _key, _value in (_request.get("env") or {}).items():
|
|
159
|
+
if _value is None:
|
|
160
|
+
os.environ.pop(str(_key), None)
|
|
161
|
+
else:
|
|
162
|
+
os.environ[str(_key)] = str(_value)
|
|
163
|
+
_argv = [str(_item) for _item in (_request.get("argv") or [])]
|
|
164
|
+
_out = io.StringIO()
|
|
165
|
+
_err = io.StringIO()
|
|
166
|
+
_code = 1
|
|
167
|
+
try:
|
|
168
|
+
with contextlib.redirect_stdout(_out), contextlib.redirect_stderr(_err):
|
|
169
|
+
_result = _cli.main(_argv)
|
|
170
|
+
_code = 0 if _result is None else int(_result)
|
|
171
|
+
except BaseException as _exc:
|
|
172
|
+
_err.write("%s: %s\n" % (type(_exc).__name__, _exc))
|
|
173
|
+
finally:
|
|
174
|
+
_close_backends()
|
|
175
|
+
_reply({"id": _request.get("id"), "code": _code, "stdout": _out.getvalue(), "stderr": _err.getvalue()})
|
|
176
|
+
`
|
|
177
|
+
|
|
178
|
+
const RESIDENT_READY_TIMEOUT_MS = 30_000
|
|
179
|
+
const RESIDENT_LINE_LIMIT = 8 << 20
|
|
180
|
+
|
|
181
|
+
function residentKey(current) {
|
|
182
|
+
return `${current.python}\u0000${String(current.version || '')}`
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function residentBaseEnv() {
|
|
186
|
+
return {
|
|
187
|
+
...windowsSystemEnv(),
|
|
188
|
+
...process.env,
|
|
189
|
+
PYTHONUTF8: '1',
|
|
190
|
+
PYTHONIOENCODING: 'utf-8',
|
|
191
|
+
MEMU_MEMORY_MODE: memoryMode(),
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function stopResident(record, failure = null) {
|
|
196
|
+
if (!record) return
|
|
197
|
+
record.stopping = true
|
|
198
|
+
if (residentRecord === record) residentRecord = null
|
|
199
|
+
if (failure) {
|
|
200
|
+
for (const pending of record.pending.values()) {
|
|
201
|
+
clearTimeout(pending.timer)
|
|
202
|
+
pending.reject(failure)
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
record.pending.clear()
|
|
206
|
+
try { record.child?.stdin?.end() } catch {}
|
|
207
|
+
try { record.child?.kill() } catch {}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function residentFailure(pending, code, detail, timedOut = false) {
|
|
211
|
+
const stdout = redactSecrets(String(detail?.stdout || ''), pending.secrets)
|
|
212
|
+
const stderr = redactSecrets(String(detail?.stderr || ''), pending.secrets)
|
|
213
|
+
const text = (stderr || stdout || '').trim()
|
|
214
|
+
return new MemuError(
|
|
215
|
+
`memu ${pending.label} failed (exit ${code}${timedOut ? ', timeout' : ''}): ${text.slice(-2000)}`,
|
|
216
|
+
'MEMU_COMMAND_FAILED',
|
|
217
|
+
{ code, stdout, stderr, timedOut },
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function startResident(current, key) {
|
|
222
|
+
const record = { key, child: null, pending: new Map(), seq: 0, stopping: false, stderr: '', readySettled: false }
|
|
223
|
+
const abortReady = (message) => {
|
|
224
|
+
if (record.readySettled) return
|
|
225
|
+
record.readySettled = true
|
|
226
|
+
if (residentRecord === record) residentRecord = null
|
|
227
|
+
try { clearTimeout(record.bootTimer) } catch {}
|
|
228
|
+
try { record.child?.kill() } catch {}
|
|
229
|
+
record.readyReject?.(new MemuError(`failed to start memu: ${message}`, 'MEMU_SPAWN_FAILED'))
|
|
230
|
+
}
|
|
231
|
+
record.ready = new Promise((resolve, reject) => {
|
|
232
|
+
record.readyReject = reject
|
|
233
|
+
let buffer = ''
|
|
234
|
+
const settle = () => {
|
|
235
|
+
record.readySettled = true
|
|
236
|
+
try { clearTimeout(record.bootTimer) } catch {}
|
|
237
|
+
resolve(record)
|
|
238
|
+
}
|
|
239
|
+
record.bootTimer = setTimeout(() => abortReady('the memu resident process did not become ready in time'), RESIDENT_READY_TIMEOUT_MS)
|
|
240
|
+
try {
|
|
241
|
+
record.child = spawn(current.python, ['-c', RESIDENT_SCRIPT], {
|
|
242
|
+
env: residentBaseEnv(),
|
|
243
|
+
windowsHide: true,
|
|
244
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
245
|
+
})
|
|
246
|
+
} catch (error) {
|
|
247
|
+
abortReady(error.message)
|
|
248
|
+
return
|
|
249
|
+
}
|
|
250
|
+
// An unhandled 'error' event on a child pipe is an uncaught exception in the host.
|
|
251
|
+
for (const pipe of [record.child.stdin, record.child.stdout, record.child.stderr]) {
|
|
252
|
+
try { pipe?.on?.('error', () => {}) } catch {}
|
|
253
|
+
}
|
|
254
|
+
record.child.stderr?.on('data', (chunk) => {
|
|
255
|
+
record.stderr = (record.stderr + String(chunk)).slice(-4096)
|
|
256
|
+
})
|
|
257
|
+
record.child.stdout?.on('data', (chunk) => {
|
|
258
|
+
buffer += String(chunk)
|
|
259
|
+
if (buffer.length > RESIDENT_LINE_LIMIT) {
|
|
260
|
+
buffer = ''
|
|
261
|
+
abortReady('the resident engine response exceeded the line limit')
|
|
262
|
+
return
|
|
263
|
+
}
|
|
264
|
+
let newline = buffer.indexOf('\n')
|
|
265
|
+
while (newline >= 0) {
|
|
266
|
+
const line = buffer.slice(0, newline).replace(/\r+$/, '')
|
|
267
|
+
buffer = buffer.slice(newline + 1)
|
|
268
|
+
newline = buffer.indexOf('\n')
|
|
269
|
+
if (!line.trim()) continue
|
|
270
|
+
let message = null
|
|
271
|
+
try { message = JSON.parse(line) } catch { continue }
|
|
272
|
+
if (!record.readySettled) {
|
|
273
|
+
if (message.ready === true) settle()
|
|
274
|
+
else abortReady(String(message.error || 'the resident worker did not report ready'))
|
|
275
|
+
continue
|
|
276
|
+
}
|
|
277
|
+
const pending = record.pending.get(message.id)
|
|
278
|
+
if (!pending) continue
|
|
279
|
+
record.pending.delete(message.id)
|
|
280
|
+
clearTimeout(pending.timer)
|
|
281
|
+
const code = Number(message.code)
|
|
282
|
+
if (code === 0) pending.resolve({ stdout: String(message.stdout || ''), stderr: String(message.stderr || ''), code: 0 })
|
|
283
|
+
else pending.reject(residentFailure(pending, code, message))
|
|
284
|
+
}
|
|
285
|
+
})
|
|
286
|
+
record.child.on('error', (error) => abortReady(error.message))
|
|
287
|
+
record.child.on('close', (code) => {
|
|
288
|
+
if (!record.readySettled) {
|
|
289
|
+
abortReady(`the resident engine exited before it was ready (exit ${code})`)
|
|
290
|
+
return
|
|
291
|
+
}
|
|
292
|
+
if (residentRecord === record) residentRecord = null
|
|
293
|
+
if (record.stopping) return
|
|
294
|
+
const tail = redactSecrets(record.stderr.trim(), [])
|
|
295
|
+
const failure = new MemuError(
|
|
296
|
+
`memu resident process exited (exit ${code})${tail ? `: ${tail.slice(-2000)}` : ''}`,
|
|
297
|
+
'MEMU_COMMAND_FAILED',
|
|
298
|
+
{ code, timedOut: false, stderr: tail },
|
|
299
|
+
)
|
|
300
|
+
for (const pending of record.pending.values()) {
|
|
301
|
+
clearTimeout(pending.timer)
|
|
302
|
+
pending.reject(failure)
|
|
303
|
+
}
|
|
304
|
+
record.pending.clear()
|
|
305
|
+
warn('dsh-memu-memory: the resident memu engine exited; the next command will cold-start')
|
|
306
|
+
})
|
|
307
|
+
})
|
|
308
|
+
return record
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
function ensureResident(current) {
|
|
312
|
+
const key = residentKey(current)
|
|
313
|
+
if (residentRecord && residentRecord.key !== key) {
|
|
314
|
+
stopResident(residentRecord, new MemuError('the memu engine changed; the resident process was stopped', 'MEMU_COMMAND_FAILED'))
|
|
315
|
+
}
|
|
316
|
+
if (!residentRecord) residentRecord = startResident(current, key)
|
|
317
|
+
return residentRecord.ready
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
async function runResident(args, { env, timeoutMs = 90_000 } = {}) {
|
|
321
|
+
const current = currentEngine()
|
|
322
|
+
let record
|
|
323
|
+
try {
|
|
324
|
+
record = await ensureResident(current)
|
|
325
|
+
} catch (error) {
|
|
326
|
+
throw error instanceof MemuError ? error : new MemuError(String(error?.message || error), 'MEMU_SPAWN_FAILED')
|
|
327
|
+
}
|
|
328
|
+
if (!record || record.stopping) throw new MemuError('the resident memu engine is not available', 'MEMU_SPAWN_FAILED')
|
|
329
|
+
const label = args[0] || ''
|
|
330
|
+
const id = ++record.seq
|
|
331
|
+
const secrets = Object.entries({ ...process.env, ...(env || {}) })
|
|
332
|
+
.filter(([key]) => /(?:API_KEY|TOKEN|SECRET)$/.test(key)).map(([, value]) => value)
|
|
333
|
+
const payload = JSON.stringify({
|
|
334
|
+
id,
|
|
335
|
+
argv: args,
|
|
336
|
+
env: { ...(env || {}), MEMU_MEMORY_MODE: memoryMode() },
|
|
337
|
+
}) + '\n'
|
|
338
|
+
return new Promise((resolve, reject) => {
|
|
339
|
+
const timer = setTimeout(() => {
|
|
340
|
+
record.pending.delete(id)
|
|
341
|
+
const failure = new MemuError(
|
|
342
|
+
`memu ${label} failed (timeout): the resident engine did not answer in ${Math.round(timeoutMs / 1000)}s`,
|
|
343
|
+
'MEMU_COMMAND_FAILED',
|
|
344
|
+
{ code: null, stdout: '', stderr: '', timedOut: true },
|
|
345
|
+
)
|
|
346
|
+
reject(failure)
|
|
347
|
+
// A Python command cannot be cancelled from the outside, so a stuck command
|
|
348
|
+
// costs this process; the next request cold-starts a fresh one.
|
|
349
|
+
stopResident(record, failure)
|
|
350
|
+
}, timeoutMs)
|
|
351
|
+
record.pending.set(id, { resolve, reject, timer, label, secrets })
|
|
352
|
+
try {
|
|
353
|
+
record.child.stdin.write(payload)
|
|
354
|
+
} catch (error) {
|
|
355
|
+
record.pending.delete(id)
|
|
356
|
+
clearTimeout(timer)
|
|
357
|
+
const failure = new MemuError(`failed to start memu: ${error.message}`, 'MEMU_SPAWN_FAILED', { error })
|
|
358
|
+
reject(failure)
|
|
359
|
+
stopResident(record, failure)
|
|
360
|
+
}
|
|
361
|
+
})
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
/** Close the resident engine (plugin dispose, or an explicit teardown). */
|
|
365
|
+
export function closeMemuResident() {
|
|
366
|
+
const record = residentRecord
|
|
367
|
+
residentRecord = null
|
|
368
|
+
if (!record) return 0
|
|
369
|
+
stopResident(record, new MemuError('the resident memu engine is closed', 'MEMU_COMMAND_FAILED'))
|
|
370
|
+
return 1
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
/**
|
|
374
|
+
* Warm the resident engine for local vector mode. Called after the local vector
|
|
375
|
+
* bootstrap (or on the first managed-local command), and deliberately fail-open:
|
|
376
|
+
* an engine that is missing or broken must not delay plugin activation.
|
|
377
|
+
*/
|
|
378
|
+
export async function prewarmMemuResident() {
|
|
379
|
+
try {
|
|
380
|
+
if (effectiveVectorRoute() !== 'managed-local') return false
|
|
381
|
+
if (!activeProfile()) return false
|
|
382
|
+
const current = readCurrent()
|
|
383
|
+
if (!current?.python) return false
|
|
384
|
+
await ensureResident(current)
|
|
385
|
+
return true
|
|
386
|
+
} catch (error) {
|
|
387
|
+
try { warn(`dsh-memu-memory: resident memu prewarm skipped: ${error?.message || error}`) } catch {}
|
|
388
|
+
return false
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
82
392
|
async function runConfigured(args, options = {}) {
|
|
83
393
|
const route = options.route || (options.vectorProfile ? 'managed-local' : 'remote-api')
|
|
84
394
|
const useManagedLocal = route === 'managed-local'
|
|
@@ -90,7 +400,12 @@ async function runConfigured(args, options = {}) {
|
|
|
90
400
|
const env = await envFor({ ...options, route })
|
|
91
401
|
if (generation) assertVectorGeneration(generation)
|
|
92
402
|
if (migration) assertMigrationProfile(migration)
|
|
93
|
-
|
|
403
|
+
// Local vector mode is the only route this plugin can reach without a vendor key,
|
|
404
|
+
// so it is where a cold Python import is paid most often. Keep one interpreter warm
|
|
405
|
+
// there; the remote API path keeps the one-process-per-command behavior.
|
|
406
|
+
const result = useManagedLocal
|
|
407
|
+
? await runResident(args, { env, timeoutMs: options.timeoutMs })
|
|
408
|
+
: await runRaw(['-m', 'memu', ...args], { env, timeoutMs: options.timeoutMs })
|
|
94
409
|
if (generation) assertVectorGeneration(generation)
|
|
95
410
|
if (migration) assertMigrationProfile(migration)
|
|
96
411
|
return result
|