dsh-memu-memory 1.3.2 → 1.3.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 +11 -3
- package/CHANGELOG.md +57 -3
- package/README.md +6 -11
- package/README.zh.md +6 -11
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/stats.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +21 -0
- package/docs/contributing.md +5 -2
- package/docs/memory-semantics.md +17 -0
- package/docs/troubleshooting.md +44 -0
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +125 -18
- package/lib/consolidation-snapshot.js +101 -5
- package/lib/consolidation-worker.js +1 -1
- package/lib/cycle.js +19 -1
- package/lib/index.js +83 -2
- package/lib/private.js +450 -165
- package/lib/rpc.js +14 -1
- package/lib/state.js +11 -1
- package/lib/turn-log.js +522 -0
- package/lib/webui/graph-view.bundle.js +1 -1
- package/lib/webui/graph-view.js +53 -25
- package/lib/webui/standalone.css +4 -29
- package/lib/worker-pool.js +741 -0
- package/package.json +1 -1
- package/scripts/acceptance-local.mjs +6 -5
- package/scripts/build-graph.mjs +32 -4
- package/scripts/check-all.mjs +2 -0
- package/scripts/check-idle-compositing.mjs +61 -0
- package/scripts/make-readme-shots.mjs +59 -0
- package/scripts/prune-turnlogs.mjs +30 -0
- package/tests/browser.test.mjs +27 -0
- package/tests/client-render.test.mjs +171 -0
- package/tests/consolidation-snapshot.test.mjs +89 -1
- package/tests/graph-view.test.mjs +60 -3
- package/tests/loader.mjs +2 -0
- package/tests/salience-domain.test.mjs +139 -0
- package/tests/settings-coverage.test.mjs +97 -0
- package/tests/stubs/dsh-session-query.js +26 -0
- package/tests/turn-log.test.mjs +474 -0
- package/tests/webui.test.mjs +19 -0
- package/tests/worker-lifecycle.test.mjs +1046 -0
- package/docs/recall-benchmark.md +0 -238
package/lib/private.js
CHANGED
|
@@ -174,6 +174,10 @@ export const CONSOLIDATION_MIN_HUMAN_TURNS = 3
|
|
|
174
174
|
// wrappers. 300 events therefore bought only ~50 turns of transcript. 500 keeps
|
|
175
175
|
// the same seed size in practice but cuts one fork for a 200-turn catch-up.
|
|
176
176
|
export const CONSOLIDATION_WINDOW_EVENTS = 500
|
|
177
|
+
// worker 模式按回合扩展窗口:500 事件切在回合中间时,向后补到该回合的 turn/end。
|
|
178
|
+
// worker 的包是 turn-log 记录(单条最多 4000 字符),扩展窗口不会放大模型上下文;
|
|
179
|
+
// 它只避免同一回合被连续两窗整条重发。20k 事件是防御上限,正常回合远小于它。
|
|
180
|
+
export const WORKER_WINDOW_EXTEND_EVENTS = 20_000
|
|
177
181
|
export const CONSOLIDATION_PROBE_MINUTES = 15
|
|
178
182
|
export const CONSOLIDATION_SNAPSHOT_FAILURE_LIMIT = 2
|
|
179
183
|
const SEED_TOOL_RESULT_CHARS = 1_100
|
|
@@ -387,8 +391,55 @@ export function compactSeedEvents(events, prelude = null) {
|
|
|
387
391
|
// identities) count double; generic preference/social words count once. Whole
|
|
388
392
|
// turns are kept, plus the turn before/after for context. If nothing looks
|
|
389
393
|
// salient, keep everything rather than silently dropping the window.
|
|
390
|
-
|
|
391
|
-
|
|
394
|
+
//
|
|
395
|
+
// §6.1 分域强度词表:domain 取 domainOf(binding)(general/rp/coding/mixed,
|
|
396
|
+
// 未知域回退 general)。CJK 词条保持子串匹配——general/rp 的 CJK 部分与旧
|
|
397
|
+
// 全域表逐字一致,默认行为下中文得分不变;Latin 词条统一 `\b` 词边界 +
|
|
398
|
+
// 大小写不敏感(fix 不命中 fixture/prefix,FIX/Fixed 要命中)。分数语义
|
|
399
|
+
// 不变:强 ×2 + 弱 ×1。
|
|
400
|
+
const latin = (words) => words.map((word) => `\\b(?:${word})\\b`)
|
|
401
|
+
|
|
402
|
+
// 生活/中性对话:现状全域表逐字保留(顺序不变,保证中文得分与旧代码一致)+ 英文补充。
|
|
403
|
+
const GENERAL_STRONG = [
|
|
404
|
+
'今天', '明天', '昨天', '前天', '后天', '大后天', '下周', '上周', '这周', '月底', '月初', '年初', '年底',
|
|
405
|
+
'生日', '纪念日', '周年', '星期[一二三四五六日天]', '周[一二三四五六日天]',
|
|
406
|
+
'\\d{1,2}\\s*[月日号]', '\\d{4}\\s*[-/年]', '\\d{1,2}\\s*[点时]',
|
|
407
|
+
'答应', '约定', '说好', '提醒', '帮我', '帮忙', '欠', '借', '还', '截止', '到期', '记得', '别忘', '改口', '说错', '更正', '其实', '矛盾', '两版', '之前说',
|
|
408
|
+
...latin(['birthday', 'anniversary', 'promised?', 'deadline', 'due', 'owe', 'borrowed', 'changed my mind', 'corrected', 'actually']),
|
|
409
|
+
]
|
|
410
|
+
const GENERAL_WEAK = [
|
|
411
|
+
'喜欢', '讨厌', '不吃', '不要', '不能', '不想', '边界', '秘密', '别说', '打算', '计划', '准备', '要去', '想去', '叫', '称呼', '名字', '岁', '住', '工作', '职业', '负责', '接手', '登记', '换', '孩子', '父亲', '母亲', '老公', '老婆', '朋友', '同事', '邻居',
|
|
412
|
+
...latin(['prefers?', 'allergic', "can['’]t eat", 'boundaries?', 'secrets?', 'plans?', 'planned', 'called', 'named', 'ages?', 'lives at', 'works at', 'friends?', 'colleagues?']),
|
|
413
|
+
]
|
|
414
|
+
// 剧情人际:现状表即 rp 向(沿用 general 的生活词 + 现有人际词),补剧情词与英文同人词。
|
|
415
|
+
const RP_STRONG = [...GENERAL_STRONG]
|
|
416
|
+
const RP_WEAK = [
|
|
417
|
+
...GENERAL_WEAK,
|
|
418
|
+
'上位', '下位', '设定', '世界观', '剧情', '人设',
|
|
419
|
+
...latin(['personas?', 'canon', 'lore', 'headcanons?', 'backstory', 'in character', 'out of character']),
|
|
420
|
+
]
|
|
421
|
+
// 工程事实(新表):改了什么/为什么/什么时候上线。bugs 与截止日来自 §6.1 设计表。
|
|
422
|
+
const CODING_STRONG = [
|
|
423
|
+
'修复', '修好', '发布', '上线', '部署', '版本', '回滚', '迁移', '破坏性', '依赖升级', '环境变量', '报错', '崩溃', '回归', '截止日',
|
|
424
|
+
...latin([
|
|
425
|
+
'bugs?', 'fixed', 'fixes', 'fix\\b(?!ture|ing)', 'broke', 'broken', 'deploy(?:ed|s|ing)?', 'release[ds]?',
|
|
426
|
+
'shipped?', 'hotfix(?:es|ed)?', 'rollback(?:ed|s)?', 'migrat(?:e|ed|ion|ing)s?', 'breaking changes?', 'root causes?', 'crash(?:ed|es)?', 'regressions?',
|
|
427
|
+
]),
|
|
428
|
+
]
|
|
429
|
+
const CODING_WEAK = [
|
|
430
|
+
'重构', '优化', '测试', '文档', '依赖', '配置', '接口', '日志', '构建', '打包', '命名',
|
|
431
|
+
...latin(['refactor(?:ed|s|ing)?', 'optimiz(?:e|ed|ing)', 'config(?:s|uration)?', 'env', 'dependenc(?:y|ies)', 'builds?', 'lints?', 'rename[ds]?', 'apis?']),
|
|
432
|
+
]
|
|
433
|
+
// mixed:rp ∪ coding 并集去重。
|
|
434
|
+
const MIXED_STRONG = [...new Set([...RP_STRONG, ...CODING_STRONG])]
|
|
435
|
+
const MIXED_WEAK = [...new Set([...RP_WEAK, ...CODING_WEAK])]
|
|
436
|
+
const compileSalience = (parts) => new RegExp(parts.join('|'), 'gi')
|
|
437
|
+
const SALIENCE_TABLE = {
|
|
438
|
+
general: { strong: compileSalience(GENERAL_STRONG), weak: compileSalience(GENERAL_WEAK) },
|
|
439
|
+
rp: { strong: compileSalience(RP_STRONG), weak: compileSalience(RP_WEAK) },
|
|
440
|
+
coding: { strong: compileSalience(CODING_STRONG), weak: compileSalience(CODING_WEAK) },
|
|
441
|
+
mixed: { strong: compileSalience(MIXED_STRONG), weak: compileSalience(MIXED_WEAK) },
|
|
442
|
+
}
|
|
392
443
|
|
|
393
444
|
function turnText(events) {
|
|
394
445
|
const parts = []
|
|
@@ -402,14 +453,17 @@ function turnText(events) {
|
|
|
402
453
|
return parts.join('\n')
|
|
403
454
|
}
|
|
404
455
|
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
const
|
|
456
|
+
/** 强 ×2 + 弱 ×1;domain 取 domainOf(binding)(四域),未知域回退 general。 */
|
|
457
|
+
export function salienceScore(text, domain = 'general') {
|
|
458
|
+
const table = SALIENCE_TABLE[domain] || SALIENCE_TABLE.general
|
|
459
|
+
const value = String(text)
|
|
460
|
+
const strong = (value.match(table.strong) || []).length
|
|
461
|
+
const weak = (value.match(table.weak) || []).length
|
|
408
462
|
return strong * 2 + weak
|
|
409
463
|
}
|
|
410
464
|
|
|
411
465
|
/** Keep salient complete turns and one neighbour on each side. */
|
|
412
|
-
export function candidateSeedEvents(events, { maxTurns = 60 } = {}) {
|
|
466
|
+
export function candidateSeedEvents(events, { maxTurns = 60, domain = 'general' } = {}) {
|
|
413
467
|
const groups = []
|
|
414
468
|
let current = null
|
|
415
469
|
for (const event of Array.isArray(events) ? events : []) {
|
|
@@ -422,7 +476,7 @@ export function candidateSeedEvents(events, { maxTurns = 60 } = {}) {
|
|
|
422
476
|
}
|
|
423
477
|
const kept = new Set()
|
|
424
478
|
groups.forEach((group, index) => {
|
|
425
|
-
if (salienceScore(turnText(group)) >= 2) kept.add(index)
|
|
479
|
+
if (salienceScore(turnText(group), domain) >= 2) kept.add(index)
|
|
426
480
|
})
|
|
427
481
|
if (kept.size === 0) return Array.isArray(events) ? [...events] : []
|
|
428
482
|
const expanded = new Set(kept)
|
|
@@ -441,7 +495,7 @@ export function candidateSeedEvents(events, { maxTurns = 60 } = {}) {
|
|
|
441
495
|
// 不低,却在模型的 topic selection 里没有位置。给它就是一份带 seq 的短清单:要么
|
|
442
496
|
// 写,要么在回执里说明为什么不写,不能静默跳过。
|
|
443
497
|
const MUST_COVER_PERSON = /叫|自称|称呼|换|接手|改成|换成|新来|同事|师傅|阿姨|房东|店长|老板|邻居|朋友|家人/
|
|
444
|
-
export function mustCoverCandidates(events, { max = 8, minScore = 3 } = {}) {
|
|
498
|
+
export function mustCoverCandidates(events, { max = 8, minScore = 3, domain = 'general' } = {}) {
|
|
445
499
|
const groups = []
|
|
446
500
|
let current = null
|
|
447
501
|
for (const event of Array.isArray(events) ? events : []) {
|
|
@@ -456,7 +510,7 @@ export function mustCoverCandidates(events, { max = 8, minScore = 3 } = {}) {
|
|
|
456
510
|
const seen = new Set()
|
|
457
511
|
groups.forEach((group) => {
|
|
458
512
|
const text = turnText(group)
|
|
459
|
-
const score = salienceScore(text)
|
|
513
|
+
const score = salienceScore(text, domain)
|
|
460
514
|
if (score < minScore) return
|
|
461
515
|
const userText = group
|
|
462
516
|
.filter((event) => event?.type === 'user/message' && event.data?.source?.kind === 'user')
|
|
@@ -637,6 +691,83 @@ export function selectConsolidationWindow(events, limit = CONSOLIDATION_WINDOW_E
|
|
|
637
691
|
}
|
|
638
692
|
}
|
|
639
693
|
|
|
694
|
+
/** worker 模式把窗口对齐到最后一个完整回合(§3.3,A5):切在回合中间的窗口回退到
|
|
695
|
+
* 窗内最后一个 turn/end,跨骑回合整条推到下窗。这样快照 throughSeq = 游标落在回合边界,
|
|
696
|
+
* 增量不会把同一回合连续两窗整条重发。窗内没有闭合回合时原样返回(交上层兜底)。
|
|
697
|
+
* 仅 worker 路径调用;fork 路径窗口定义不变。
|
|
698
|
+
*
|
|
699
|
+
* 尾部只有一个 session 级事件(例如 session/end-seed)时不能回退:那会把游标从 5099
|
|
700
|
+
* 拉回 5098。只有「最后 turn/end 之后又出现了 turn/start」才是真的切在新回合中间。 */
|
|
701
|
+
export function alignWindowToTurn(window) {
|
|
702
|
+
const events = Array.isArray(window?.events) ? window.events : []
|
|
703
|
+
let lastEnd = null
|
|
704
|
+
for (const event of events) {
|
|
705
|
+
if (event?.type !== 'turn/end') continue
|
|
706
|
+
const seq = eventSeq(event)
|
|
707
|
+
if (seq !== null && (lastEnd === null || seq > lastEnd)) lastEnd = seq
|
|
708
|
+
}
|
|
709
|
+
if (lastEnd === null || lastEnd === window.throughSeq) return window
|
|
710
|
+
const trailing = events.filter((event) => {
|
|
711
|
+
const seq = eventSeq(event)
|
|
712
|
+
return seq !== null && seq > lastEnd
|
|
713
|
+
})
|
|
714
|
+
// 最后回合结束后只剩宿主元数据:整段保留,别为了对齐丢掉转录末尾的事件。
|
|
715
|
+
if (!trailing.some((event) => event?.type === 'turn/start')) return window
|
|
716
|
+
const aligned = events.filter((event) => {
|
|
717
|
+
const seq = eventSeq(event)
|
|
718
|
+
return seq !== null && seq <= lastEnd
|
|
719
|
+
})
|
|
720
|
+
if (aligned.length === 0) return window
|
|
721
|
+
return {
|
|
722
|
+
events: aligned,
|
|
723
|
+
fromSeq: window.fromSeq,
|
|
724
|
+
throughSeq: lastEnd,
|
|
725
|
+
remaining: (Number(window.remaining) || 0) + (events.length - aligned.length),
|
|
726
|
+
}
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
/**
|
|
730
|
+
* worker 窗口:先按事件数取窗,再向后补到当前回合的 turn/end。500 事件切在回合中间时,
|
|
731
|
+
* 旧路径会把这个回合整条留给下一窗;turn-log 记录是整回合单位,于是同一回合被连续
|
|
732
|
+
* 两窗整条重发(实测 556 事件回合)。worker 的包按记录算字符,向后补齐不会放大上下文,
|
|
733
|
+
* 所以这里直接补到回合末。补不到(超过防御上限)就退回旧行为。
|
|
734
|
+
*/
|
|
735
|
+
export function selectWorkerWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS, maxExtend = WORKER_WINDOW_EXTEND_EVENTS) {
|
|
736
|
+
const list = (Array.isArray(events) ? events : []).filter((event) => eventSeq(event) !== null)
|
|
737
|
+
const initial = selectConsolidationWindow(list, limit)
|
|
738
|
+
if (!initial.events || initial.events.length === 0) return initial
|
|
739
|
+
const lastEndIndex = (() => {
|
|
740
|
+
for (let i = initial.events.length - 1; i >= 0; i -= 1) {
|
|
741
|
+
if (initial.events[i]?.type === 'turn/end') return i
|
|
742
|
+
}
|
|
743
|
+
return -1
|
|
744
|
+
})()
|
|
745
|
+
const openAfter = lastEndIndex < 0
|
|
746
|
+
|| initial.events.slice(lastEndIndex + 1).some((event) => event?.type === 'turn/start')
|
|
747
|
+
if (!openAfter) return alignWindowToTurn(initial)
|
|
748
|
+
const extraBudget = Math.max(0, Number(maxExtend) || 0)
|
|
749
|
+
if (extraBudget === 0) return alignWindowToTurn(initial)
|
|
750
|
+
const nextEnd = list
|
|
751
|
+
.filter((event) => eventSeq(event) > initial.throughSeq)
|
|
752
|
+
.slice(0, extraBudget)
|
|
753
|
+
.find((event) => event?.type === 'turn/end')
|
|
754
|
+
if (!nextEnd) return alignWindowToTurn(initial)
|
|
755
|
+
const through = eventSeq(nextEnd)
|
|
756
|
+
const extended = list.filter((event) => {
|
|
757
|
+
const seq = eventSeq(event)
|
|
758
|
+
return seq >= initial.fromSeq && seq <= through
|
|
759
|
+
})
|
|
760
|
+
const safe = safePrefix(extended, { requireClosedTurn: false })
|
|
761
|
+
const chosen = safe.ok && safe.events.length > 0 ? safe.events : extended
|
|
762
|
+
const chosenThrough = eventSeq(chosen[chosen.length - 1])
|
|
763
|
+
return {
|
|
764
|
+
events: chosen,
|
|
765
|
+
fromSeq: eventSeq(chosen[0]),
|
|
766
|
+
throughSeq: chosenThrough,
|
|
767
|
+
remaining: list.filter((event) => eventSeq(event) > chosenThrough).length,
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
|
|
640
771
|
/** Last complete turn window, for a manual re-check when the cursor is already at the end. */
|
|
641
772
|
export function selectTailTurnWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS) {
|
|
642
773
|
const list = (Array.isArray(events) ? events : []).filter(event => eventSeq(event) !== null)
|
|
@@ -655,6 +786,22 @@ export function selectTailTurnWindow(events, limit = CONSOLIDATION_WINDOW_EVENTS
|
|
|
655
786
|
return { events: chosen, fromSeq: eventSeq(chosen[0]), throughSeq: eventSeq(chosen[chosen.length - 1]), remaining: 0 }
|
|
656
787
|
}
|
|
657
788
|
|
|
789
|
+
/**
|
|
790
|
+
* 整理游标只能前进:尾部人工重检选中最后一个回合时,窗口可能比已有游标更靠前
|
|
791
|
+
* (例如已经结算过 turn/end 后的 session/end-seed),直接写回会把 lastSleepSeq
|
|
792
|
+
* 从 5099 拉回 5098。统一走这里,取当前值与新值的较大者。
|
|
793
|
+
*/
|
|
794
|
+
function advanceSleepCursor(sessionId, seq, patch = {}) {
|
|
795
|
+
const next = Number(seq)
|
|
796
|
+
if (!Number.isSafeInteger(next) || next < 0) return null
|
|
797
|
+
const current = (() => {
|
|
798
|
+
try { return Number(getSessionBinding(sessionId)?.lastSleepSeq) } catch { return NaN }
|
|
799
|
+
})()
|
|
800
|
+
const value = Number.isSafeInteger(current) && current >= 0 ? Math.max(current, next) : next
|
|
801
|
+
setSessionBinding(sessionId, { lastSleepSeq: value, ...patch })
|
|
802
|
+
return value
|
|
803
|
+
}
|
|
804
|
+
|
|
658
805
|
export async function requestPrivateConsolidation(ctx, sessionId, options = {}) {
|
|
659
806
|
const binding = getSessionBinding(sessionId)
|
|
660
807
|
if (!binding) return { ok: false, error: 'session is not bound to a memory library; bind it first' }
|
|
@@ -717,7 +864,7 @@ export async function requestRemoteConsolidation(ctx, sessionId, { signal, timeo
|
|
|
717
864
|
else if (outcome?.entry?.status === 'pending_review') held += 1
|
|
718
865
|
else written += 1
|
|
719
866
|
}
|
|
720
|
-
|
|
867
|
+
advanceSleepCursor(sessionId, events[events.length - 1]?.seq)
|
|
721
868
|
const result = { ok: true, sessionId, backend: 'api', count: written, deduped, held }
|
|
722
869
|
record({
|
|
723
870
|
kind: 'consolidate', scope: 'private', sessionId, libraryId: binding.libraryId || null, ok: true,
|
|
@@ -765,15 +912,33 @@ function agentOptionsFromConfig(config) {
|
|
|
765
912
|
// an older request/header event is the only equivalent for a closed session. Without
|
|
766
913
|
// one of these, the standard preset cannot resolve {{model}} and every fork dies before
|
|
767
914
|
// its first step, so refuse to create that fork instead of queueing another doomed seed.
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
915
|
+
//
|
|
916
|
+
// 第四路(2026-11-14,bench P16 实测):纯 RPC 追加历史的种子会话(seed 流程只 append
|
|
917
|
+
// 不跑回合)连一个 request/header 都不会有;宿主重启或驱动被杀还会把 agent 从进程内
|
|
918
|
+
// 注册表注销——前三路全空,继承必然失败。resume() 是公开的重挂路径:只重新注册该
|
|
919
|
+
// 会话自己的 agent loop(不跑回合、不发模型调用),让它的路由重新可读。探测不可用
|
|
920
|
+
// 或失败一律降级回原行为(返回 null 拒绝 fork)。
|
|
921
|
+
async function inheritedAgentOptions(ctx, sessionId, events) {
|
|
922
|
+
let agents = null
|
|
923
|
+
try { agents = ctx.get?.('agents') || null } catch {}
|
|
924
|
+
const probe = (agent) => {
|
|
925
|
+
try {
|
|
926
|
+
const fromRequest = agentOptionsFromConfig(agent?.session?.requestHeader?.()?.config)
|
|
927
|
+
if (fromRequest) return fromRequest
|
|
928
|
+
} catch {}
|
|
929
|
+
return agentOptionsFromConfig(agent?.options)
|
|
930
|
+
}
|
|
931
|
+
let live = null
|
|
932
|
+
try { live = agents?.get?.(sessionId) || null } catch {}
|
|
933
|
+
const direct = probe(live)
|
|
934
|
+
if (direct) return direct
|
|
935
|
+
if (agents && typeof agents.resume === 'function') {
|
|
936
|
+
try {
|
|
937
|
+
const resumed = await agents.resume({ resumeSessionId: sessionId })
|
|
938
|
+
const fromResumed = probe(resumed?.agent || resumed)
|
|
939
|
+
if (fromResumed) return fromResumed
|
|
940
|
+
} catch {}
|
|
941
|
+
}
|
|
777
942
|
for (let i = events.length - 1; i >= 0; i -= 1) {
|
|
778
943
|
if (events[i]?.type !== 'request/header') continue
|
|
779
944
|
const fromEvent = agentOptionsFromConfig(events[i]?.data?.header?.config)
|
|
@@ -790,53 +955,8 @@ function turnEndFailure(event) {
|
|
|
790
955
|
return 'the fork turn ended ' + (reason.kind || 'without a reason') + (message ? ': ' + message : '')
|
|
791
956
|
}
|
|
792
957
|
|
|
793
|
-
//
|
|
794
|
-
//
|
|
795
|
-
// tools.schemas(agent, toolSet) 枚举"调用 agent 的可见面")。preset 组合没列出本插件
|
|
796
|
-
// 时,fork 的注册表里根本没有 memu_*,worker 既不能原生调用也没有 SDK 绑定,回执只能
|
|
797
|
-
// 是 tools-unavailable。修法与 preset-scope.js 的注入挂载同构:把 worker 读写面挂进 fork
|
|
798
|
-
// 自己的 ctx scope —— 注册表按 scope 链取可见面,所以只对这个 worker 可见,不扩散到
|
|
799
|
-
// 其它会话;挂载点必须在 followup 之前(宿主在 step 开始时 resolve 一次 admitted set,
|
|
800
|
-
// 之后注册的工具不进本步)。失败不阻断整理:worker 会按任务书如实回执 tools-unavailable。
|
|
801
|
-
async function attachWorkerTools(agents, childId, parentId) {
|
|
802
|
-
const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
|
|
803
|
-
const ctxOf = (record) => {
|
|
804
|
-
try { return record?.ctx || record?.agent?.ctx || null } catch { return null }
|
|
805
|
-
}
|
|
806
|
-
let parentHasCtx = null
|
|
807
|
-
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
808
|
-
let record = null
|
|
809
|
-
try { record = agents.get?.(childId) || null } catch { record = null }
|
|
810
|
-
if (record) {
|
|
811
|
-
const actx = ctxOf(record)
|
|
812
|
-
// 有记录但没有 ctx:这版宿主不暴露 agent context(preset-scope.js 的同款限制),
|
|
813
|
-
// 重试不会变出来。ctx 在但没有 tools 服务:组合里就没有。两者都直接放弃。
|
|
814
|
-
if (!actx || !(actx.tools && typeof actx.tools.register === 'function')) break
|
|
815
|
-
try {
|
|
816
|
-
const dispose = registerTools(actx, { only: wanted })
|
|
817
|
-
// tools.js 在 disposer 上附挂实际注册成功的名单(编译 + register 都过的那部分)。
|
|
818
|
-
// 读它,不再把 wanted 全量当成"已挂载"——部分挂载必须结构化可见。
|
|
819
|
-
const attached = Array.isArray(dispose?.attached) ? [...dispose.attached] : null
|
|
820
|
-
return {
|
|
821
|
-
dispose,
|
|
822
|
-
attached,
|
|
823
|
-
requested: wanted,
|
|
824
|
-
// 名单缺失 = 无法证明挂全:partial 照实标 true,attached 落 null(与失败同口径)。
|
|
825
|
-
partial: attached ? attached.length < wanted.length : true,
|
|
826
|
-
}
|
|
827
|
-
} catch (error) {
|
|
828
|
-
warn('consolidation worker tool attach failed: ' + String(error?.message || error))
|
|
829
|
-
return null
|
|
830
|
-
}
|
|
831
|
-
}
|
|
832
|
-
// 子记录还没出现:只在这个宿主确实会暴露 ctx(父记录带 ctx)时才值得短退避等它。
|
|
833
|
-
if (parentHasCtx === null) parentHasCtx = Boolean(ctxOf(agents.get?.(parentId)))
|
|
834
|
-
if (!parentHasCtx) break
|
|
835
|
-
await new Promise(resolve => setTimeout(resolve, 100))
|
|
836
|
-
}
|
|
837
|
-
warn('consolidation worker has no tools service on its own context; the worker may be unable to write memories')
|
|
838
|
-
return null
|
|
839
|
-
}
|
|
958
|
+
// attachWorkerTools / restrictWorkerTools 已迁到 lib/worker-pool.js(T1 持久整理 worker
|
|
959
|
+
// 与 'fork' 路径共用同一份实现,见 worker-pool.js 顶部说明);本文件经 import 使用。
|
|
840
960
|
|
|
841
961
|
// 活动日志"整理已开始"条目的挂载元数据口径(workerTools* 三件):
|
|
842
962
|
// workerToolsAttached 实际注册成功的工具名数组;null = 挂载没有完成或无法确认
|
|
@@ -847,37 +967,6 @@ async function attachWorkerTools(agents, childId, parentId) {
|
|
|
847
967
|
// workerToolsPartial true = 未证明 worker 拿到完整 wanted 集(子集、空集、或挂载
|
|
848
968
|
// 整体失败)。刻意把"一件都没挂上"也标 true:若失败标 false,
|
|
849
969
|
// false 会被一眼读成"全量挂载",元数据又不准了。
|
|
850
|
-
// A fork inherits the parent preset's plugin tools. `tools.restrict()` is scoped
|
|
851
|
-
// to the child agent, so this removes every plugin tool the worker never uses
|
|
852
|
-
// without touching the parent session. Restrict before followup: the host
|
|
853
|
-
// resolves the admitted set at step start.
|
|
854
|
-
async function restrictWorkerTools(agents, childId, parentId) {
|
|
855
|
-
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
856
|
-
let record = null
|
|
857
|
-
try { record = agents.get?.(childId) || null } catch { record = null }
|
|
858
|
-
const actx = record?.ctx || record?.agent?.ctx || null
|
|
859
|
-
if (actx && actx.tools && typeof actx.tools.restrict === 'function') {
|
|
860
|
-
try {
|
|
861
|
-
const dispose = actx.tools.restrict({ allow: WORKER_TOOL_ALLOW })
|
|
862
|
-
return { dispose, allowed: [...WORKER_TOOL_ALLOW] }
|
|
863
|
-
} catch (error) {
|
|
864
|
-
// A host missing one of the optional tools must not lose consolidation;
|
|
865
|
-
// retry with the write/read core and let the brief tell the truth.
|
|
866
|
-
const core = [...CORE_WRITE_TOOLS]
|
|
867
|
-
try {
|
|
868
|
-
return { dispose: actx.tools.restrict({ allow: core }), allowed: core }
|
|
869
|
-
} catch (inner) {
|
|
870
|
-
warn('consolidation worker tool restriction failed: ' + String(inner?.message || inner))
|
|
871
|
-
return null
|
|
872
|
-
}
|
|
873
|
-
}
|
|
874
|
-
}
|
|
875
|
-
if (record || !(agents.get?.(parentId))) return null
|
|
876
|
-
await new Promise(resolve => setTimeout(resolve, 100))
|
|
877
|
-
}
|
|
878
|
-
return null
|
|
879
|
-
}
|
|
880
|
-
|
|
881
970
|
function workerToolsMeta(workerTools) {
|
|
882
971
|
const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
|
|
883
972
|
if (!workerTools) {
|
|
@@ -908,11 +997,16 @@ import {
|
|
|
908
997
|
readCarryCandidates, setCarryCandidates,
|
|
909
998
|
} from './consolidation-ledger.js'
|
|
910
999
|
import { decideCompletion, receiptContractText } from './consolidation-receipt.js'
|
|
911
|
-
import { buildWorkerBrief, probeToolSurface,
|
|
1000
|
+
import { buildWorkerBrief, probeToolSurface, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_WRAPUP_ROUND, WORKER_HARD_STOP_ROUND, workerRoundGuidance } from './consolidation-worker.js'
|
|
1001
|
+
// T1 持久整理 worker(lib/worker-pool.js):三级试活/退役/epoch 记账/包组装都在那里;
|
|
1002
|
+
// attachWorkerTools/restrictWorkerTools 也已迁到该模块,'fork' 路径调用同一份实现。
|
|
1003
|
+
import {
|
|
1004
|
+
acquireWorker, attachWorkerTools, buildHandoffPack, buildIncrementPack, loadWorkerIncrement,
|
|
1005
|
+
recordEpochProgress, retireWorker, restrictWorkerTools, WORKER_TIMEOUT_LIMIT,
|
|
1006
|
+
} from './worker-pool.js'
|
|
912
1007
|
import { tokenize, buildCorpus, bm25 } from './text-retrieval.js'
|
|
913
1008
|
import { isGoneSessionError } from './cycle.js'
|
|
914
1009
|
import { autoLinkPrivateMemories } from './private-links.js'
|
|
915
|
-
import { registerTools } from './tools.js'
|
|
916
1010
|
import { resolveConsolidationAgentOptions, ensureConsolidationRoute } from './fork-model.js'
|
|
917
1011
|
|
|
918
1012
|
// 账本异常必须可见;调用方只有拿到明确的持久租约才可启动 worker。
|
|
@@ -1016,6 +1110,12 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1016
1110
|
let scopeChanged = null
|
|
1017
1111
|
let workerTools = null
|
|
1018
1112
|
let workerRestriction = null
|
|
1113
|
+
// 执行器选择在 try 内赋值;finally 需要 workerMode 来决定清理口径(worker 模式
|
|
1114
|
+
// 不销毁 worker——它的生命周期归 epoch,见 §15.2 改动点 6)。
|
|
1115
|
+
let workerMode = false
|
|
1116
|
+
// A2:worker 生命周期上绑定的 epoch abort(acquireWorker 返回)。续窗的硬停/重验必须
|
|
1117
|
+
// abort 它才停得住持久 worker——窗口级 abort 只在出生那次被宿主接进生命周期。
|
|
1118
|
+
let workerEpochAbort = null
|
|
1019
1119
|
const assistantTexts = []
|
|
1020
1120
|
let childId = null
|
|
1021
1121
|
// 每次整理都要在活动日志里留一条:谁触发(手动/空闲)、fork 有没有建、结果是完成、
|
|
@@ -1127,7 +1227,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1127
1227
|
// otherwise the same greetings stay pending forever and the sweep keeps
|
|
1128
1228
|
// treating them as a real backlog.
|
|
1129
1229
|
safeLedger(() => skipRange({ sessionId, snapshot: fullSnapshot, reasonCode: value.reason }))
|
|
1130
|
-
|
|
1230
|
+
advanceSleepCursor(sessionId, fullSnapshot.throughSeq)
|
|
1131
1231
|
return finish({
|
|
1132
1232
|
ok: true, sessionId, skipped: value.reason, settled: true, deferred: false,
|
|
1133
1233
|
reasonCode: value.reason, assessment: value, snapshot: snapshotMetaOf(fullSnapshot),
|
|
@@ -1193,7 +1293,14 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1193
1293
|
// 前半段先结算,剩余留给下一次。
|
|
1194
1294
|
const sleepAttempt = Number(binding.sleepAttempts || 0)
|
|
1195
1295
|
const windowLimit = sleepAttempt > 0 ? Math.floor(CONSOLIDATION_WINDOW_EVENTS / 2) : CONSOLIDATION_WINDOW_EVENTS
|
|
1196
|
-
|
|
1296
|
+
// 执行器选择提前到窗口选择处(A5 需要按 runner 决定是否回合对齐);settings 复用至模型路由。
|
|
1297
|
+
const settings = getSettings()
|
|
1298
|
+
workerMode = settings.consolidationRunner === 'worker'
|
|
1299
|
+
// A5:worker 模式按回合取窗(切在回合中间时向后补到 turn/end,避免同一回合
|
|
1300
|
+
// 被连续两窗整条重发);fork 路径窗口定义不变。
|
|
1301
|
+
let window = workerMode
|
|
1302
|
+
? selectWorkerWindow(candidateEvents, windowLimit)
|
|
1303
|
+
: selectConsolidationWindow(candidateEvents, windowLimit)
|
|
1197
1304
|
if (window.events.length === 0) {
|
|
1198
1305
|
return finish({ ok: true, sessionId, skipped: 'empty-window', settled: true, snapshot: snapshotMetaOf(fullSnapshot) })
|
|
1199
1306
|
}
|
|
@@ -1210,8 +1317,9 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1210
1317
|
const budgetMs = Number.isInteger(maxWaitMs) && maxWaitMs > 0 ? maxWaitMs : consolidationWaitBudget(window.events.length)
|
|
1211
1318
|
// 1.3.1:目录与本地召回命中在种子开头一次给全,worker 不再开只读回合。
|
|
1212
1319
|
const carry = safeLedger(() => readCarryCandidates(sessionId), [])
|
|
1213
|
-
const
|
|
1214
|
-
const
|
|
1320
|
+
const domain = domainOf(binding)
|
|
1321
|
+
const mustCover = mergeMustCover(carry, mustCoverCandidates(window.events, { domain }))
|
|
1322
|
+
const seedEvents = compactSeedEvents(candidateSeedEvents(window.events, { domain }), [
|
|
1215
1323
|
memoryCatalogEvent({ ...binding, sessionId }),
|
|
1216
1324
|
memoryRecallEvent({ binding: { ...binding, sessionId }, candidates: mustCover, events: window.events }),
|
|
1217
1325
|
])
|
|
@@ -1279,9 +1387,16 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1279
1387
|
// host 直接指名宿主已激活 route;custom 要先在宿主 llm 注册表确认本插件私有 route
|
|
1280
1388
|
// 可用(能力缺失/注册失败/服务性探测不过 → 降级回 inherit 或拒绝本次整理,warn 一
|
|
1281
1389
|
// 行,绝不 fail closed)。fork 的 AgentOptions 没有 baseURL/apiKey 通道,custom 的
|
|
1282
|
-
// 自定义端点只能走注册 route
|
|
1283
|
-
|
|
1284
|
-
|
|
1390
|
+
// 自定义端点只能走注册 route。(settings 已在窗口选择处读取。)
|
|
1391
|
+
//
|
|
1392
|
+
// host/custom 不需要父会话 route:这里不探测父会话,也避免 inheritedAgentOptions 的
|
|
1393
|
+
// resume 回退把父会话挂成宿主活视图——活视图会钉住 sessionQuery 的快照,外部追加的
|
|
1394
|
+
// 持久日志(bench 种子)就再也读不到(S1 冻结)。custom 真失败时才惰性回退探测。
|
|
1395
|
+
const modelModeSetting = settings.consolidationModelMode || 'inherit'
|
|
1396
|
+
let inherited = null
|
|
1397
|
+
if (modelModeSetting !== 'host' && modelModeSetting !== 'custom') {
|
|
1398
|
+
inherited = await inheritedAgentOptions(ctx, sessionId, events)
|
|
1399
|
+
}
|
|
1285
1400
|
const resolved = resolveConsolidationAgentOptions(settings, inherited)
|
|
1286
1401
|
let agentOptions = resolved.options
|
|
1287
1402
|
let modelMode = resolved.reason
|
|
@@ -1306,6 +1421,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1306
1421
|
const ensured = await ensureConsolidationRoute(ctx, settings)
|
|
1307
1422
|
if (!ensured.ok) {
|
|
1308
1423
|
warn('consolidation custom model route unavailable (' + ensured.reason + (ensured.error ? ': ' + ensured.error : '') + '); falling back to the inherited route')
|
|
1424
|
+
if (!inherited) inherited = await inheritedAgentOptions(ctx, sessionId, events)
|
|
1309
1425
|
if (inherited) {
|
|
1310
1426
|
agentOptions = inherited
|
|
1311
1427
|
modelMode = 'inherit-fallback'
|
|
@@ -1316,46 +1432,85 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1316
1432
|
}
|
|
1317
1433
|
}
|
|
1318
1434
|
|
|
1319
|
-
|
|
1320
|
-
//
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
agentPreset: header.agentPreset,
|
|
1334
|
-
},
|
|
1335
|
-
inheritedEventCount: seedEvents.length,
|
|
1336
|
-
seed: buildForkSeed(seedEvents, seedEvents.length - 1),
|
|
1435
|
+
// 执行器分叉(T1,设计文档 §10.2):workerMode 已在窗口选择处确定(A5)。
|
|
1436
|
+
// 默认 'fork'(现状路径,逐字节不变);显式 'worker' 走持久整理 worker(lib/worker-pool.js)。
|
|
1437
|
+
let workerAcquired = null
|
|
1438
|
+
let workerEpochRecord = null
|
|
1439
|
+
let workerIncrement = null
|
|
1440
|
+
if (workerMode) {
|
|
1441
|
+
// 先读增量再 acquire:退役条件 2(预算合格制)需要本窗增量的字符量(§4.5)。
|
|
1442
|
+
// binding 是入口捕获对象,不带 sessionId 字段——worker-pool 的入参用展开补齐。
|
|
1443
|
+
const workerBinding = { ...binding, sessionId }
|
|
1444
|
+
workerIncrement = loadWorkerIncrement({ sessionId, binding: workerBinding, window, events: window.events })
|
|
1445
|
+
workerAcquired = await acquireWorker(ctx, workerBinding, {
|
|
1446
|
+
incrementChars: workerIncrement.chars,
|
|
1447
|
+
settings,
|
|
1448
|
+
probe,
|
|
1337
1449
|
agentOptions,
|
|
1338
|
-
|
|
1339
|
-
})
|
|
1340
|
-
} catch (error) {
|
|
1341
|
-
// 宿主拒绝种子时最需要的诊断信息就在这条错误里("seed event at index …"),
|
|
1342
|
-
// 用独立 reasonCode 写进活动日志,别让它塌成一句 exception。
|
|
1343
|
-
const failure = String(error?.message || error)
|
|
1344
|
-
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'fork-create-failed', retryable: true, error: failure }))
|
|
1345
|
-
return finish({
|
|
1346
|
-
ok: false, sessionId, childId, settled: false, retryable: true,
|
|
1347
|
-
reasonCode: 'fork-create-failed',
|
|
1348
|
-
error: 'the host rejected the consolidation fork: ' + failure,
|
|
1450
|
+
header,
|
|
1349
1451
|
})
|
|
1452
|
+
if (!workerAcquired.ok) {
|
|
1453
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed', retryable: true, error: workerAcquired.error || null }))
|
|
1454
|
+
return finish({
|
|
1455
|
+
ok: false, sessionId, settled: false, retryable: true,
|
|
1456
|
+
reasonCode: workerAcquired.reasonCode || 'worker-acquire-failed',
|
|
1457
|
+
error: workerAcquired.error || 'the consolidation worker could not be acquired',
|
|
1458
|
+
})
|
|
1459
|
+
}
|
|
1460
|
+
childId = workerAcquired.forkId
|
|
1461
|
+
handle = workerAcquired.handle
|
|
1462
|
+
workerTools = workerAcquired.tools
|
|
1463
|
+
workerRestriction = workerAcquired.restriction
|
|
1464
|
+
workerEpochRecord = workerAcquired.epoch
|
|
1465
|
+
workerEpochAbort = workerAcquired.epochAbort || null
|
|
1466
|
+
} else {
|
|
1467
|
+
childId = 'memu-consolidate-' + Date.now().toString(36) + '-' + crypto.randomBytes(3).toString('hex')
|
|
1468
|
+
// 种子只种这一窗:worker 看到的世界就是它要对账的那一段,窗口之外的事件
|
|
1469
|
+
// 留给下一批。seq 已按 compactSeedEvents 重排成从 0 连续,inheritedEventCount
|
|
1470
|
+
// 必须等于种子长度(不是父会话的 throughSeq),否则宿主会拒绝这份种子。
|
|
1471
|
+
try {
|
|
1472
|
+
handle = await agents.create({
|
|
1473
|
+
sessionId: childId,
|
|
1474
|
+
meta: {
|
|
1475
|
+
cwd: header.cwd,
|
|
1476
|
+
parentSession: sessionId,
|
|
1477
|
+
isSeeded: true,
|
|
1478
|
+
// Without this the fork is treated as an ordinary user conversation by
|
|
1479
|
+
// the injection path and the sidebar session lists.
|
|
1480
|
+
origin: 'subagent',
|
|
1481
|
+
agentPreset: header.agentPreset,
|
|
1482
|
+
},
|
|
1483
|
+
inheritedEventCount: seedEvents.length,
|
|
1484
|
+
seed: buildForkSeed(seedEvents, seedEvents.length - 1),
|
|
1485
|
+
agentOptions,
|
|
1486
|
+
signal: abort.signal,
|
|
1487
|
+
})
|
|
1488
|
+
} catch (error) {
|
|
1489
|
+
// 宿主拒绝种子时最需要的诊断信息就在这条错误里("seed event at index …"),
|
|
1490
|
+
// 用独立 reasonCode 写进活动日志,别让它塌成一句 exception。
|
|
1491
|
+
const failure = String(error?.message || error)
|
|
1492
|
+
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'fork-create-failed', retryable: true, error: failure }))
|
|
1493
|
+
return finish({
|
|
1494
|
+
ok: false, sessionId, childId, settled: false, retryable: true,
|
|
1495
|
+
reasonCode: 'fork-create-failed',
|
|
1496
|
+
error: 'the host rejected the consolidation fork: ' + failure,
|
|
1497
|
+
})
|
|
1498
|
+
}
|
|
1350
1499
|
}
|
|
1351
1500
|
|
|
1352
1501
|
// header 无法证明 worker 有写工具时(PTC 会话名单只有 run_code / 旧会话没有名单),
|
|
1353
1502
|
// 把 worker 读写面挂进 fork 自己的 scope,保证 SDK 面(PTC)与原生面(普通会话)都真能写入。
|
|
1354
1503
|
// 标准 preset 的 fork 名单里已有 memu_*(probe.hasWrite === true),不重复挂。
|
|
1355
|
-
|
|
1356
|
-
|
|
1504
|
+
// worker 模式:工具面只在初生挂一次(acquireWorker 内部处理),续窗跳过(§15.2 改动点 2)。
|
|
1505
|
+
if (!workerMode) {
|
|
1506
|
+
if (probe.hasWrite !== true) {
|
|
1507
|
+
workerTools = await attachWorkerTools(agents, childId, sessionId)
|
|
1508
|
+
}
|
|
1509
|
+
workerRestriction = await restrictWorkerTools(agents, childId, sessionId)
|
|
1357
1510
|
}
|
|
1358
|
-
|
|
1511
|
+
// worker 模式:本窗 worker 产出体积(assistant 正文 + 工具参数/结果)由下面挂的
|
|
1512
|
+
// per-window 监听顺手累计,窗口结束后并入 epoch.chars(recordEpochProgress)。
|
|
1513
|
+
let workerOutputChars = 0
|
|
1359
1514
|
|
|
1360
1515
|
// 先记"已开始"再等结果:一个大会话的 fork 可能跑好几分钟,没有这条记录,
|
|
1361
1516
|
// 侧边栏和日志页在等待期间只会显示上一次的结果,用户会以为按钮没生效。
|
|
@@ -1393,7 +1548,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1393
1548
|
message: '整理作废:父会话授权变化(' + source + ')',
|
|
1394
1549
|
detail: { jobId, childId, ...scopeChanged },
|
|
1395
1550
|
})
|
|
1396
|
-
try { abort.abort() } catch {}
|
|
1551
|
+
try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
|
|
1397
1552
|
}
|
|
1398
1553
|
if (typeof ctx.on === 'function' && childSession) {
|
|
1399
1554
|
try {
|
|
@@ -1404,17 +1559,27 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1404
1559
|
const blocks = event?.data?.message?.content
|
|
1405
1560
|
if (Array.isArray(blocks)) {
|
|
1406
1561
|
for (const block of blocks) {
|
|
1407
|
-
if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim())
|
|
1562
|
+
if (block?.type === 'text' && typeof block.text === 'string' && block.text.trim()) {
|
|
1563
|
+
assistantTexts.push(block.text)
|
|
1564
|
+
if (workerMode) workerOutputChars += block.text.length
|
|
1565
|
+
}
|
|
1408
1566
|
}
|
|
1409
1567
|
}
|
|
1410
1568
|
return
|
|
1411
1569
|
}
|
|
1412
1570
|
// 工具动作是写入的落点:每出现一次就重验一次父授权,变了立刻停掉这条 fork。
|
|
1413
1571
|
if (event?.type === 'tool/call' || event?.type === 'tool/result' || event?.type === 'tool/ptc-dispatch' || event?.type === 'tool/ptc-dispatch-start') {
|
|
1572
|
+
if (workerMode) {
|
|
1573
|
+
workerOutputChars += event?.type === 'tool/call'
|
|
1574
|
+
? String(event?.data?.arguments ?? '').length
|
|
1575
|
+
: JSON.stringify(event?.data?.message?.content ?? '').length
|
|
1576
|
+
}
|
|
1414
1577
|
revalidate('worker-write')
|
|
1415
1578
|
workerToolRounds += 1
|
|
1416
1579
|
if (workerToolRounds >= WORKER_HARD_STOP_ROUND) {
|
|
1417
|
-
|
|
1580
|
+
// A2:worker 模式 abort 的是绑在生命周期上的 epoch 控制器,硬停才真正生效;
|
|
1581
|
+
// 回合以 aborted 收尾 → turnEndFailure → 退役。fork 模式仍 abort 窗口 signal。
|
|
1582
|
+
try { (workerMode && workerEpochAbort ? workerEpochAbort : abort).abort() } catch {}
|
|
1418
1583
|
} else {
|
|
1419
1584
|
const guidance = workerRoundGuidance(workerToolRounds)
|
|
1420
1585
|
if (guidance && workerToolRounds === WORKER_WRAPUP_ROUND) {
|
|
@@ -1460,10 +1625,20 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1460
1625
|
domain: binding.domain,
|
|
1461
1626
|
domainOverride: binding.domainOverride || null,
|
|
1462
1627
|
})
|
|
1628
|
+
// worker 模式(§15.2 改动点 3):子绑定补 epoch 副本;sceneTime 每窗重读父绑定
|
|
1629
|
+
// (RP 剧情可能推进;现状 fork 是诞生时定死一次,worker 路径每窗刷新,§6)。
|
|
1630
|
+
if (workerMode && workerEpochRecord) {
|
|
1631
|
+
const sceneTimeNow = (() => {
|
|
1632
|
+
try { return getSessionBinding(sessionId)?.sceneTime || binding.sceneTime || null } catch { return binding.sceneTime || null }
|
|
1633
|
+
})()
|
|
1634
|
+
setSessionBinding(childId, { workerEpoch: workerEpochRecord, sceneTime: sceneTimeNow })
|
|
1635
|
+
}
|
|
1463
1636
|
|
|
1464
1637
|
// 写入前最后一次重验:这次的授权还成立吗?不成立就别把 prompt 发出去。
|
|
1465
1638
|
revalidate('pre-dispatch')
|
|
1466
1639
|
if (scopeChanged) {
|
|
1640
|
+
// worker 模式:scope 已污染,立即退役且不交接(§4.5 条件 1)。
|
|
1641
|
+
if (workerMode && childId) { try { await retireWorker(ctx, childId, 'scope-change', { handoff: false }) } catch {} }
|
|
1467
1642
|
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'parent-scope-changed', retryable: false, error: 'the parent conversation changed scope before dispatch' }))
|
|
1468
1643
|
return finish({
|
|
1469
1644
|
ok: false, sessionId, childId, settled: false, retryable: false, reasonCode: 'parent-scope-changed',
|
|
@@ -1471,18 +1646,77 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1471
1646
|
})
|
|
1472
1647
|
}
|
|
1473
1648
|
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
autoReceipt: true
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1649
|
+
// 任务书 + followup(§15.2 改动点 4):fork 每窗发整份任务书;worker 模式初生发
|
|
1650
|
+
// 交接包(= 初生包,§5.1),续窗只发增量包(目录头/契约/场景时间每窗都发,
|
|
1651
|
+
// 已写入摘要只在初生/交接包携带——worker 上下文里刚写过,续窗发是冗余)。
|
|
1652
|
+
if (workerMode && workerAcquired) {
|
|
1653
|
+
const sceneTimeNow = (() => {
|
|
1654
|
+
try { return getSessionBinding(sessionId)?.sceneTime || binding.sceneTime || null } catch { return binding.sceneTime || null }
|
|
1655
|
+
})()
|
|
1656
|
+
const contract = receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true })
|
|
1657
|
+
const catalog = memoryCatalogEvent({ ...binding, sessionId })
|
|
1658
|
+
// 上一窗是否结清(§4.4):结算成功时清除,超时时落 consolidationPending;
|
|
1659
|
+
// binding 是入口捕获的旧对象,必须重读。
|
|
1660
|
+
const pendingNote = (() => {
|
|
1661
|
+
try { return Boolean(getSessionBinding(sessionId)?.consolidationPending) } catch { return false }
|
|
1662
|
+
})()
|
|
1663
|
+
const pendingHash = (() => {
|
|
1664
|
+
try { return getSessionBinding(sessionId)?.consolidationPending?.snapshotHash || null } catch { return null }
|
|
1665
|
+
})()
|
|
1666
|
+
if (workerAcquired.birth) {
|
|
1667
|
+
const pack = buildHandoffPack({
|
|
1668
|
+
sessionId,
|
|
1669
|
+
binding: { ...binding, sessionId },
|
|
1670
|
+
snapshot,
|
|
1671
|
+
probe,
|
|
1672
|
+
jobId,
|
|
1673
|
+
reason: force ? 'manual' : 'auto',
|
|
1674
|
+
singleOnly: Boolean(binding.consolidationSingleOnly),
|
|
1675
|
+
mustCover,
|
|
1676
|
+
contract,
|
|
1677
|
+
incrementRecords: workerIncrement.records,
|
|
1678
|
+
incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
|
|
1679
|
+
digest: workerIncrement.digest,
|
|
1680
|
+
catalog,
|
|
1681
|
+
sceneTime: sceneTimeNow,
|
|
1682
|
+
pendingNote,
|
|
1683
|
+
pendingHash,
|
|
1684
|
+
// 「不做 handoff」= 不带旧 epoch 的连续性材料(尾部 + 已写入摘要);
|
|
1685
|
+
// 身份任务书与目录头照发(§8:冷启动新包)。
|
|
1686
|
+
includeTail: workerAcquired.handoff !== false,
|
|
1687
|
+
writtenRows: workerAcquired.handoff === false ? [] : null,
|
|
1688
|
+
lastSleepSeq: binding.lastSleepSeq ?? null,
|
|
1689
|
+
})
|
|
1690
|
+
handle.agent.followup(noticeMessage([buildPrivateConsolidationPrompt(sessionId), '', pack].join('\n'), '整理这场对话的私有记忆'))
|
|
1691
|
+
} else {
|
|
1692
|
+
const pack = buildIncrementPack({
|
|
1693
|
+
binding: { ...binding, sessionId },
|
|
1694
|
+
incrementRecords: workerIncrement.records,
|
|
1695
|
+
incrementText: workerIncrement.source === 'fallback' ? workerIncrement.text : null,
|
|
1696
|
+
digest: workerIncrement.digest,
|
|
1697
|
+
catalog,
|
|
1698
|
+
carry: mustCover,
|
|
1699
|
+
contract,
|
|
1700
|
+
sceneTime: sceneTimeNow,
|
|
1701
|
+
pendingNote,
|
|
1702
|
+
pendingHash,
|
|
1703
|
+
})
|
|
1704
|
+
handle.agent.followup(noticeMessage(pack, '整理这场对话的私有记忆'))
|
|
1705
|
+
}
|
|
1706
|
+
} else {
|
|
1707
|
+
const brief = buildWorkerBrief({
|
|
1708
|
+
snapshot,
|
|
1709
|
+
probe,
|
|
1710
|
+
contract: receiptContractText({ jobId, snapshotHash: snapshot.hash, autoReceipt: true }),
|
|
1711
|
+
reason: force ? 'manual' : 'auto',
|
|
1712
|
+
jobId,
|
|
1713
|
+
mustCover,
|
|
1714
|
+
autoReceipt: true,
|
|
1715
|
+
// 上一轮 batch 参数 JSON 畸形:这一轮只让模型逐条 remember,降低再次整段失败的概率。
|
|
1716
|
+
singleOnly: Boolean(binding.consolidationSingleOnly),
|
|
1717
|
+
})
|
|
1718
|
+
handle.agent.followup(noticeMessage([buildPrivateConsolidationPrompt(sessionId), '', brief].join('\n'), '整理这场对话的私有记忆'))
|
|
1719
|
+
}
|
|
1486
1720
|
// followup only queues. whenIdle says the driver stopped; turn/end says
|
|
1487
1721
|
// whether that turn actually succeeded, so both are checked below.
|
|
1488
1722
|
idle = typeof handle.agent.whenIdle === 'function' ? handle.agent.whenIdle() : Promise.resolve()
|
|
@@ -1493,6 +1727,17 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1493
1727
|
outcome = await Promise.race([idle.then(() => 'done'), wait])
|
|
1494
1728
|
} finally { clearTimeout(timer) }
|
|
1495
1729
|
|
|
1730
|
+
// worker 模式 epoch 记账(§4.5/§15.2 改动点 3):本窗增量 + 观测到的 worker 产出
|
|
1731
|
+
// 并入 chars、windows +1;whenIdle 正常完成记 lastIdleAt(条件 4 的 TTL 起算点)。
|
|
1732
|
+
// 结算成功后的超时清零在 completeJob 之后单独落一次。
|
|
1733
|
+
if (workerMode) {
|
|
1734
|
+
workerEpochRecord = recordEpochProgress({ sessionId }, {
|
|
1735
|
+
incrementChars: workerIncrement.chars,
|
|
1736
|
+
workerOutputChars,
|
|
1737
|
+
idleAt: outcome === 'done' ? Date.now() : null,
|
|
1738
|
+
}) || workerEpochRecord
|
|
1739
|
+
}
|
|
1740
|
+
|
|
1496
1741
|
let wrote = null
|
|
1497
1742
|
let decision = null
|
|
1498
1743
|
let completion = null
|
|
@@ -1505,6 +1750,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1505
1750
|
&& /JSON|Expected ','|after array element/.test(String(failure))
|
|
1506
1751
|
const reasonCode = batchJsonInvalid ? 'batch-json-invalid' : 'fork-turn-failed'
|
|
1507
1752
|
if (batchJsonInvalid) setSessionBinding(sessionId, { consolidationSingleOnly: true })
|
|
1753
|
+
// worker 模式:回合失败即退役条件 5,不带病工作、不做交接(§4.5)。
|
|
1754
|
+
if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
|
|
1508
1755
|
safeLedger(() => failJob({ sessionId, jobId, reasonCode, retryable: batchJsonInvalid, error: failure }))
|
|
1509
1756
|
return finish({
|
|
1510
1757
|
ok: false, error: 'consolidation fork failed: ' + failure, sessionId, childId,
|
|
@@ -1514,6 +1761,7 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1514
1761
|
// 父授权重验:写入可能已经落了一部分,但凭证只有在授权还成立时才算数。
|
|
1515
1762
|
const generationNow = scopeGenerationOf(getSessionBinding(sessionId))
|
|
1516
1763
|
if (scopeChanged || (generationAtStart && generationNow !== generationAtStart)) {
|
|
1764
|
+
if (workerMode && childId) { try { await retireWorker(ctx, childId, 'scope-change', { handoff: false }) } catch {} }
|
|
1517
1765
|
safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'parent-scope-changed', retryable: false, error: 'the parent conversation changed scope during consolidation' }))
|
|
1518
1766
|
return finish({
|
|
1519
1767
|
ok: false, sessionId, childId, settled: false, retryable: false, reasonCode: 'parent-scope-changed',
|
|
@@ -1544,6 +1792,8 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1544
1792
|
})
|
|
1545
1793
|
|
|
1546
1794
|
if (!decision.advance) {
|
|
1795
|
+
// worker 模式:对账不过 = 退役条件 5(无交接);已写入的条目保留,区间回 pending。
|
|
1796
|
+
if (workerMode && childId) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
|
|
1547
1797
|
safeLedger(() => failJob({
|
|
1548
1798
|
sessionId, jobId, reasonCode: decision.reasonCode || 'not-settled',
|
|
1549
1799
|
retryable: decision.retryable !== false, error: decision.error || null,
|
|
@@ -1570,13 +1820,20 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1570
1820
|
reasonCode: 'ledger-not-advanced', snapshot: snapshotMeta,
|
|
1571
1821
|
error: 'the consolidation ledger could not verify the covered snapshot range' })
|
|
1572
1822
|
}
|
|
1573
|
-
|
|
1823
|
+
advanceSleepCursor(sessionId, snapshot.throughSeq, { consolidationSingleOnly: false })
|
|
1824
|
+
// worker 模式:结算成功清超时连击、清「上窗未结算」标记(下一窗增量包不再带核对说明)。
|
|
1825
|
+
if (workerMode) {
|
|
1826
|
+
workerEpochRecord = recordEpochProgress({ sessionId }, { settled: true, progress: false }) || workerEpochRecord
|
|
1827
|
+
setSessionBinding(sessionId, { consolidationPending: null })
|
|
1828
|
+
}
|
|
1574
1829
|
// 候选跨窗顺延:本窗没写进库的候选留给下一窗的必写清单;最后一窗也在同一份
|
|
1575
1830
|
// brief 里见到它们,不需要为了补写再开一次整窗 fork。核验纯本地,0 Token。
|
|
1576
1831
|
const writtenIds = [...(decision.createdIds || []), ...(decision.updatedIds || []), ...(decision.heldIds || [])]
|
|
1577
1832
|
const missed = mustCover.filter((candidate) => !candidateCovered(candidate, writtenIds, index))
|
|
1578
1833
|
safeLedger(() => setCarryCandidates(sessionId, missed))
|
|
1579
|
-
|
|
1834
|
+
// A8:摘要要覆盖 created/updated/held 全部落库 id(设计 §4.2),不只 created——
|
|
1835
|
+
// 否则续窗 worker 看不到已 update/held 的条目,可能重复尝试。ids 仅供摘要,不参与判同。
|
|
1836
|
+
safeLedger(() => recordOperation({ sessionId, key: opKey, outcome: decision.status, ids: writtenIds }))
|
|
1580
1837
|
// 私有自动关联(§5.6 兜底):只在整理真的对账并推进边界之后跑,纯算法,
|
|
1581
1838
|
// 0 token。worker 若已调用 memu_private_link_suggest,这一遍是幂等的(已有的
|
|
1582
1839
|
// relation/person 边会跳过)。link 只是图元数据:失败只记 warn,绝不能让一次
|
|
@@ -1597,11 +1854,28 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1597
1854
|
// `result.error` and an empty string there is indistinguishable from a click
|
|
1598
1855
|
// that did nothing at all (observed: two clicks, no feedback, no memories).
|
|
1599
1856
|
if (outcome === 'timeout') {
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
|
|
1603
|
-
|
|
1604
|
-
|
|
1857
|
+
if (workerMode) {
|
|
1858
|
+
// 持久模式(§4.4):超时 = 废弃本回合的结算,不废弃 worker。已写入的条目保留
|
|
1859
|
+
// (本来如此);游标不进(failJob 照旧);区间回 pending;下一窗增量包开头带
|
|
1860
|
+
// 「上窗未结算」核对说明(consolidationPending 标记)。连续 2 次超时升级退役
|
|
1861
|
+
// (防反复卡死吃窗口),退役允许交接——worker 上下文没坏,只是慢。
|
|
1862
|
+
workerEpochRecord = recordEpochProgress({ sessionId }, { timeout: true, progress: false }) || workerEpochRecord
|
|
1863
|
+
setSessionBinding(sessionId, { consolidationPending: { snapshotHash: snapshot.hash, jobId, at: new Date().toISOString() } })
|
|
1864
|
+
if ((Number(workerEpochRecord?.timeouts) || 0) >= WORKER_TIMEOUT_LIMIT) {
|
|
1865
|
+
try { await retireWorker(ctx, childId, 'timeout-x2', { handoff: true }) } catch {}
|
|
1866
|
+
}
|
|
1867
|
+
} else {
|
|
1868
|
+
// Stop the writer before releasing the range, not after. Waiting matters here
|
|
1869
|
+
// because a tool call already in flight can still land a memory on disk, and the
|
|
1870
|
+
// range going back to pending is what lets the next pass redo this window.
|
|
1871
|
+
await stopWorker()
|
|
1872
|
+
}
|
|
1873
|
+
safeLedger(() => failJob({
|
|
1874
|
+
sessionId, jobId, reasonCode: 'timeout',
|
|
1875
|
+
error: workerMode
|
|
1876
|
+
? 'timed out before a receipt; the turn was abandoned and the range is pending again (a tool call already in flight may have written; the worker is kept for the next window)'
|
|
1877
|
+
: 'timed out before a receipt; the worker was stopped first, but a tool call already in flight may have written',
|
|
1878
|
+
}))
|
|
1605
1879
|
return finish({
|
|
1606
1880
|
ok: false,
|
|
1607
1881
|
sessionId,
|
|
@@ -1612,7 +1886,9 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1612
1886
|
// The next pass must not assume this window left nothing behind: the range is
|
|
1613
1887
|
// pending again and some writes may already have landed.
|
|
1614
1888
|
partialWritesPossible: true,
|
|
1615
|
-
error:
|
|
1889
|
+
error: workerMode
|
|
1890
|
+
? 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the turn was abandoned and the range was released (memories written before the timeout are kept, the worker is kept). Retry, or consolidate a shorter conversation.'
|
|
1891
|
+
: 'consolidation timed out after ' + Math.round(budgetMs / 1000) + 's over ' + window.events.length + ' events; the fork was stopped before the range was released (memories written before the timeout are kept). Retry, or consolidate a shorter conversation.',
|
|
1616
1892
|
})
|
|
1617
1893
|
}
|
|
1618
1894
|
return finish({
|
|
@@ -1640,14 +1916,23 @@ export async function requestHistoricalConsolidation(ctx, sessionId, options = {
|
|
|
1640
1916
|
wrote,
|
|
1641
1917
|
})
|
|
1642
1918
|
} catch (error) {
|
|
1919
|
+
// worker 模式:异常 = 退役条件 5(无交接);fork 模式的销毁留给 finally。
|
|
1920
|
+
if (workerMode && childId && handle) { try { await retireWorker(ctx, childId, 'failure', { handoff: false }) } catch {} }
|
|
1643
1921
|
if (jobId) safeLedger(() => failJob({ sessionId, jobId, reasonCode: 'exception', error: String(error?.message || error) }))
|
|
1644
1922
|
return finish({ ok: false, sessionId, settled: false, reasonCode: 'exception', error: String(error?.message || error) })
|
|
1645
1923
|
} finally {
|
|
1646
1924
|
inFlight.delete(sessionId)
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1650
|
-
|
|
1925
|
+
if (workerMode) {
|
|
1926
|
+
// 持久 worker(§15.2 改动点 6):每窗 finally 只清 inFlight 与本轮局部资源——
|
|
1927
|
+
// per-window 重验监听随窗摘除;worker 本体、工具面与子绑定留给 epoch
|
|
1928
|
+
// (retireWorker 与插件停用负责销毁)。'fork' 路径的清理原样保留。
|
|
1929
|
+
try { offSession?.() } catch {}
|
|
1930
|
+
} else {
|
|
1931
|
+
try { await stopWorker() } catch {}
|
|
1932
|
+
try { workerTools?.dispose?.() } catch {}
|
|
1933
|
+
try { workerRestriction?.dispose?.() } catch {}
|
|
1934
|
+
try { if (childId) deleteSessionBinding(childId) } catch {}
|
|
1935
|
+
}
|
|
1651
1936
|
}
|
|
1652
1937
|
}
|
|
1653
1938
|
export function isConsolidating(sessionId) {
|