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
|
@@ -0,0 +1,741 @@
|
|
|
1
|
+
// T1 构件 2(设计文档 §4/§5/§15.1 构件 2):持久整理 worker 的生命周期管理。
|
|
2
|
+
//
|
|
3
|
+
// 定位:worker 与 turn-log 一样是缓存,账本才算数(§0 铁律 1)。本模块只负责
|
|
4
|
+
// 「谁来写」与「喂什么」:三级试活(agents.get → agents.resume 能力探测 → 初生,
|
|
5
|
+
// §4.6)、epoch 记账与退役条件(只在 acquire 时检查,§4.5)、增量包/交接包组装
|
|
6
|
+
// (§4.2/§5.1)、超时计数与退役(§4.4)。每窗结算仍走 private.js 现有的
|
|
7
|
+
// decideCompletion/completeJob/lastSleepSeq/carry 链路,一行语义不改。
|
|
8
|
+
//
|
|
9
|
+
// 默认 consolidationRunner: 'fork'——本模块的全部路径只在设置显式切到 'worker'
|
|
10
|
+
// 时被 private.js 调用;'fork'(现状每窗新 fork)行为逐字节不变。
|
|
11
|
+
import { getSessionBinding, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex } from './state.js'
|
|
12
|
+
import { warn, shortHash } from './paths.js'
|
|
13
|
+
import { record } from './activity-log.js'
|
|
14
|
+
import { loadLedger, scopeGenerationOf } from './consolidation-ledger.js'
|
|
15
|
+
import { buildWorkerBrief, CORE_WRITE_TOOLS, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_TOOL_ALLOW } from './consolidation-worker.js'
|
|
16
|
+
import { registerTools } from './tools.js'
|
|
17
|
+
import { tailSlice, readIncrement, rebuildRange, buildTurnRecords } from './turn-log.js'
|
|
18
|
+
import { condenseEvents } from './curator.js'
|
|
19
|
+
|
|
20
|
+
// —— epoch 预算分档(§4.5 条件 2/3)————————————————————————————————
|
|
21
|
+
// 按模型 maxContext 自动取档:≤128k 输入窗 → 120k 字符/8 窗;其余(含 ≥1M 旗舰)→ 200k/16。
|
|
22
|
+
// 大上下文模型不再放到 400k/32:P14 实测 32 窗会把 worker 上下文堆到 174k token,
|
|
23
|
+
// 而 96.9% 的整理 token 是历史重读;压到 200k 字符/16 窗可省约七成整理 token
|
|
24
|
+
// (§9.0:每窗含思考约 13-21k)。模型 maxContext 尽力从宿主模型发现取
|
|
25
|
+
// (probeModelMaxContext);取不到按最保守的第一档。显式设置
|
|
26
|
+
// (workerEpochCharLimit / workerEpochMaxWindows(正整数,未来经 DEFAULT_SETTINGS
|
|
27
|
+
// 放开)覆盖自动档;本阶段这两个键不在设置面里,属于前向兼容钩子。
|
|
28
|
+
export const WORKER_EPOCH_TIERS = Object.freeze([
|
|
29
|
+
Object.freeze({ maxContext: 131_072, charLimit: 120_000, maxWindows: 8 }),
|
|
30
|
+
Object.freeze({ maxContext: 262_144, charLimit: 200_000, maxWindows: 16 }),
|
|
31
|
+
Object.freeze({ maxContext: Number.MAX_SAFE_INTEGER, charLimit: 200_000, maxWindows: 16 }),
|
|
32
|
+
])
|
|
33
|
+
// 产出系数(§4.5 条件 2):触发时「epoch 已累计 + 本窗增量 × 3 ≤ LIMIT」的粗估,
|
|
34
|
+
// 3 倍覆盖 worker 产出与思考;窗口跑完后按实际观测替换估算(recordEpochProgress)。
|
|
35
|
+
export const WORKER_OUTPUT_FACTOR = 3
|
|
36
|
+
// 条件 4(§4.5):距上一窗 whenIdle 完成超过缓存 TTL 即换新。只在 acquire 时检查,
|
|
37
|
+
// 不做后台定时退役;TTL 是保守方向的启发式——早换新永不吃亏。
|
|
38
|
+
export const WORKER_EPOCH_IDLE_TTL_MS = 30 * 60_000
|
|
39
|
+
// 交接包尾部预算(§5.2):min(20k, 连续回合),tailSlice 保证整回合。
|
|
40
|
+
export const WORKER_HANDOFF_TAIL_CHARS = 20_000
|
|
41
|
+
// §4.4:超时不算失败;同一 worker 连续 2 次超时升级为退役。
|
|
42
|
+
export const WORKER_TIMEOUT_LIMIT = 2
|
|
43
|
+
// 退役时等 whenIdle 的上限:卡死的 worker 不能挂住下一次整理。
|
|
44
|
+
export const WORKER_RETIRE_IDLE_WAIT_MS = 5_000
|
|
45
|
+
// §3.3 回退路径的现场压缩预算(与 requestRemoteConsolidation 同款)。
|
|
46
|
+
export const WORKER_INCREMENT_FALLBACK_CHARS = 60_000
|
|
47
|
+
|
|
48
|
+
/** 按模型 maxContext 取档;未知模型回最保守的第一档;显式设置覆盖自动档。 */
|
|
49
|
+
export function epochBudget(binding, settings = null) {
|
|
50
|
+
const explicitChars = Number(settings?.workerEpochCharLimit)
|
|
51
|
+
const explicitWindows = Number(settings?.workerEpochMaxWindows)
|
|
52
|
+
const maxContext = Number(binding?.workerEpoch?.modelMaxContext)
|
|
53
|
+
const tier = WORKER_EPOCH_TIERS.find((row) => Number.isSafeInteger(maxContext) && maxContext > 0 && maxContext <= row.maxContext) || WORKER_EPOCH_TIERS[0]
|
|
54
|
+
return {
|
|
55
|
+
charLimit: Number.isSafeInteger(explicitChars) && explicitChars > 0 ? explicitChars : tier.charLimit,
|
|
56
|
+
maxWindows: Number.isSafeInteger(explicitWindows) && explicitWindows > 0 ? explicitWindows : tier.maxWindows,
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* 预算合格制(§4.5 条件 2):epoch 已累计 + 本窗增量 × 产出系数 ≤ 字符上限。
|
|
62
|
+
* 触发时检查,粗估、宁可早换新;不做事件级精确记账(宿主 compaction 是溢出安全网)。
|
|
63
|
+
*/
|
|
64
|
+
export function budgetFit(epoch, incrementChars, settings = null) {
|
|
65
|
+
const chars = Number(epoch?.chars) || 0
|
|
66
|
+
const increment = Math.max(0, Number(incrementChars) || 0)
|
|
67
|
+
return chars + increment * WORKER_OUTPUT_FACTOR <= epochBudget({ workerEpoch: epoch }, settings).charLimit
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** 宿主模型发现的 maxContext 尽力获取;拿不到返回 null(epochBudget 落第一档)。 */
|
|
71
|
+
export async function probeModelMaxContext(ctx, agentOptions) {
|
|
72
|
+
const provider = typeof agentOptions?.provider === 'string' ? agentOptions.provider : ''
|
|
73
|
+
const model = typeof agentOptions?.model === 'string' ? agentOptions.model : ''
|
|
74
|
+
if (!provider || !model) return null
|
|
75
|
+
const llm = (() => { try { return ctx?.get?.('llm') || null } catch { return null } })()
|
|
76
|
+
if (!llm) return null
|
|
77
|
+
// 首选 resolveModelInfo:宿主唯一的容量口径在 resolved.context.contextWindow。
|
|
78
|
+
// listModels 的目录条目(LlmModelInfo)不带容量字段,读它永远落空(A4)。
|
|
79
|
+
try {
|
|
80
|
+
const resolved = await llm.resolveModelInfo?.(provider, model)
|
|
81
|
+
const contextWindow = Number(resolved?.context?.contextWindow)
|
|
82
|
+
if (Number.isSafeInteger(contextWindow) && contextWindow > 0) return contextWindow
|
|
83
|
+
} catch { /* 探测失败降级,绝不阻断整理 */ }
|
|
84
|
+
// 兜底:个别宿主/测试可能把容量直接挂在目录条目上。
|
|
85
|
+
try {
|
|
86
|
+
const models = await llm.listModels?.(provider)
|
|
87
|
+
if (Array.isArray(models)) {
|
|
88
|
+
const entry = models.find((item) => item && (item.id === model || item.name === model)) || null
|
|
89
|
+
for (const key of ['maxContext', 'contextLength', 'contextWindow', 'maxInputTokens', 'maxContextTokens']) {
|
|
90
|
+
const value = Number(entry?.[key])
|
|
91
|
+
if (Number.isSafeInteger(value) && value > 0) return value
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
} catch { /* 同上 */ }
|
|
95
|
+
return null
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// —— 工具面(自 private.js 迁入;'fork' 路径调用同一份实现,行为逐字节一致)—————
|
|
99
|
+
|
|
100
|
+
// PTC 兼容(2026-10-31 现场 worker-tools-ptc-only):PTC 会话的 header 工具表只有
|
|
101
|
+
// run_code,其余工具走 run_code 程序里的 SDK 绑定(宿主 ptc.ts 用
|
|
102
|
+
// tools.schemas(agent, toolSet) 枚举"调用 agent 的可见面")。preset 组合没列出本插件
|
|
103
|
+
// 时,fork 的注册表里根本没有 memu_*,worker 既不能原生调用也没有 SDK 绑定,回执只能
|
|
104
|
+
// 是 tools-unavailable。修法与 preset-scope.js 的注入挂载同构:把 worker 读写面挂进 fork
|
|
105
|
+
// 自己的 ctx scope —— 注册表按 scope 链取可见面,所以只对这个 worker 可见,不扩散到
|
|
106
|
+
// 其它会话;挂载点必须在 followup 之前(宿主在 step 开始时 resolve 一次 admitted set,
|
|
107
|
+
// 之后注册的工具不进本步)。失败不阻断整理:worker 会按任务书如实回执 tools-unavailable。
|
|
108
|
+
export async function attachWorkerTools(agents, childId, parentId) {
|
|
109
|
+
const wanted = [...WORKER_WRITE_TOOLS, ...WORKER_READ_TOOLS]
|
|
110
|
+
const ctxOf = (record) => {
|
|
111
|
+
try { return record?.ctx || record?.agent?.ctx || null } catch { return null }
|
|
112
|
+
}
|
|
113
|
+
let parentHasCtx = null
|
|
114
|
+
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
115
|
+
let record = null
|
|
116
|
+
try { record = agents.get?.(childId) || null } catch { record = null }
|
|
117
|
+
if (record) {
|
|
118
|
+
const actx = ctxOf(record)
|
|
119
|
+
// 有记录但没有 ctx:这版宿主不暴露 agent context(preset-scope.js 的同款限制),
|
|
120
|
+
// 重试不会变出来。ctx 在但没有 tools 服务:组合里就没有。两者都直接放弃。
|
|
121
|
+
if (!actx || !(actx.tools && typeof actx.tools.register === 'function')) break
|
|
122
|
+
try {
|
|
123
|
+
const dispose = registerTools(actx, { only: wanted })
|
|
124
|
+
// tools.js 在 disposer 上附挂实际注册成功的名单(编译 + register 都过的那部分)。
|
|
125
|
+
// 读它,不再把 wanted 全量当成"已挂载"——部分挂载必须结构化可见。
|
|
126
|
+
const attached = Array.isArray(dispose?.attached) ? [...dispose.attached] : null
|
|
127
|
+
return {
|
|
128
|
+
dispose,
|
|
129
|
+
attached,
|
|
130
|
+
requested: wanted,
|
|
131
|
+
// 名单缺失 = 无法证明挂全:partial 照实标 true,attached 落 null(与失败同口径)。
|
|
132
|
+
partial: attached ? attached.length < wanted.length : true,
|
|
133
|
+
}
|
|
134
|
+
} catch (error) {
|
|
135
|
+
warn('consolidation worker tool attach failed: ' + String(error?.message || error))
|
|
136
|
+
return null
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
// 子记录还没出现:只在这个宿主确实会暴露 ctx(父记录带 ctx)时才值得短退避等它。
|
|
140
|
+
if (parentHasCtx === null) parentHasCtx = Boolean(ctxOf(agents.get?.(parentId)))
|
|
141
|
+
if (!parentHasCtx) break
|
|
142
|
+
await new Promise(resolve => setTimeout(resolve, 100))
|
|
143
|
+
}
|
|
144
|
+
warn('consolidation worker has no tools service on its own context; the worker may be unable to write memories')
|
|
145
|
+
return null
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
// 活动日志"整理已开始"条目的挂载元数据口径(workerTools* 三件,见 private.js workerToolsMeta):
|
|
149
|
+
// workerToolsAttached 实际注册成功的工具名数组;null = 挂载没有完成或无法确认。
|
|
150
|
+
// workerToolsRequested 请求挂载的完整 wanted 名单;与 attached 全等才是全量挂载。
|
|
151
|
+
// workerToolsPartial true = 未证明 worker 拿到完整 wanted 集。
|
|
152
|
+
// A fork inherits the parent preset's plugin tools. `tools.restrict()` is scoped
|
|
153
|
+
// to the child agent, so this removes every plugin tool the worker never uses
|
|
154
|
+
// without touching the parent session. Restrict before followup: the host
|
|
155
|
+
// resolves the admitted set at step start.
|
|
156
|
+
export async function restrictWorkerTools(agents, childId, parentId) {
|
|
157
|
+
for (let attempt = 0; attempt < 6; attempt += 1) {
|
|
158
|
+
let record = null
|
|
159
|
+
try { record = agents.get?.(childId) || null } catch { record = null }
|
|
160
|
+
const actx = record?.ctx || record?.agent?.ctx || null
|
|
161
|
+
if (actx && actx.tools && typeof actx.tools.restrict === 'function') {
|
|
162
|
+
try {
|
|
163
|
+
const dispose = actx.tools.restrict({ allow: WORKER_TOOL_ALLOW })
|
|
164
|
+
return { dispose, allowed: [...WORKER_TOOL_ALLOW] }
|
|
165
|
+
} catch (error) {
|
|
166
|
+
// A host missing one of the optional tools must not lose consolidation;
|
|
167
|
+
// retry with the write/read core and let the brief tell the truth.
|
|
168
|
+
const core = [...CORE_WRITE_TOOLS]
|
|
169
|
+
try {
|
|
170
|
+
return { dispose: actx.tools.restrict({ allow: core }), allowed: core }
|
|
171
|
+
} catch (inner) {
|
|
172
|
+
warn('consolidation worker tool restriction failed: ' + String(inner?.message || inner))
|
|
173
|
+
return null
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
if (record || !(agents.get?.(parentId))) return null
|
|
178
|
+
await new Promise(resolve => setTimeout(resolve, 100))
|
|
179
|
+
}
|
|
180
|
+
return null
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
// —— epoch 句柄注册表 ————————————————————————————————————————————
|
|
184
|
+
// attach/restrict 的 disposer 是插件侧闭包,必须活过整个 epoch(跨窗复用、退役时统一
|
|
185
|
+
// dispose)。进程内 Map:重启后注册表随进程消失,resume 回来的 worker 由 acquireWorker
|
|
186
|
+
// 重新挂一次工具面(宿主的工具注册也是进程内的,本来就非重挂不可)。
|
|
187
|
+
const epochDisposables = new Map()
|
|
188
|
+
|
|
189
|
+
function disposablesOf(forkId) {
|
|
190
|
+
return epochDisposables.get(forkId) || null
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// 有界等 whenIdle:返回是否真的落到 idle(true=可安全复用/已收敛;false=时限内仍忙)。
|
|
194
|
+
// whenIdle 缺失视为 idle(老宿主/mock 无此能力时不阻塞);reject 也视为 idle(多半已 dispose)。
|
|
195
|
+
async function waitWorkerIdle(handle, idleWaitMs) {
|
|
196
|
+
if (!handle?.agent || typeof handle.agent.whenIdle !== 'function') return true
|
|
197
|
+
let idle = false
|
|
198
|
+
let timer = null
|
|
199
|
+
try {
|
|
200
|
+
await Promise.race([
|
|
201
|
+
Promise.resolve(handle.agent.whenIdle()).then(() => { idle = true }, () => { idle = true }),
|
|
202
|
+
new Promise((resolve) => { timer = setTimeout(resolve, Math.max(0, Number(idleWaitMs) || 0)) }),
|
|
203
|
+
])
|
|
204
|
+
} catch {} finally { if (timer) clearTimeout(timer) }
|
|
205
|
+
return idle
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
// —— 退役(§4.5 退役动作)———————————————————————————————————————
|
|
209
|
+
// 先 abort epoch 控制器(取消在跑回合)→ 等 idle(有上限)→ dispose 工具 restriction/handle
|
|
210
|
+
// → dispose agent → 删子绑定 → 清父绑定 workerEpoch → 活动日志记 epoch 结束。
|
|
211
|
+
// reason ∈ 'scope-change' | 'char-limit' | 'window-limit' | 'idle-ttl' | 'failure' | 'timeout-x2';
|
|
212
|
+
// scope-change / failure 不做交接(不带病工作),其余默认交接——交接包由下一窗初生时组装。
|
|
213
|
+
export async function retireWorker(ctx, forkId, reason, { handoff, now = Date.now(), idleWaitMs = WORKER_RETIRE_IDLE_WAIT_MS } = {}) {
|
|
214
|
+
const agents = (() => { try { return ctx?.get?.('agents') || null } catch { return null } })()
|
|
215
|
+
const binding = (() => { try { return getSessionBinding(forkId) } catch { return null } })()
|
|
216
|
+
const epoch = binding?.workerEpoch && typeof binding.workerEpoch === 'object' ? binding.workerEpoch : null
|
|
217
|
+
const parentSessionId = epoch?.parentSession || binding?.parentSessionId || null
|
|
218
|
+
const disposables = disposablesOf(forkId)
|
|
219
|
+
// 0. 先取消在跑回合:epoch 控制器绑定在 agent 生命周期上(A2),abort 才能让卡住的
|
|
220
|
+
// 回合尽快收敛,下面的有界 whenIdle 才不会白等满时限。
|
|
221
|
+
try { disposables?.abort?.abort() } catch {}
|
|
222
|
+
// 1. 等 whenIdle(有上限):超时退役后 worker 可能还在跑上一回合的工具。
|
|
223
|
+
let handle = null
|
|
224
|
+
try { handle = agents?.get?.(forkId) || null } catch { handle = null }
|
|
225
|
+
await waitWorkerIdle(handle, idleWaitMs)
|
|
226
|
+
// 2. dispose 工具面(本模块注册表)+ agent 本体。找不到 handle(已死/已重启)就跳过,
|
|
227
|
+
// 剩下的清理照做——「视为已死,冷启动」(§4.5 非条件项)。
|
|
228
|
+
epochDisposables.delete(forkId)
|
|
229
|
+
try { disposables?.restriction?.dispose?.() } catch {}
|
|
230
|
+
try { disposables?.tools?.dispose?.() } catch {}
|
|
231
|
+
try { await ((handle?.agent) || handle)?.dispose?.() } catch {}
|
|
232
|
+
// 3. 删子绑定;turn-log 不删(§3.4:日志比 worker 活得长)。
|
|
233
|
+
try { deleteSessionBinding(forkId) } catch {}
|
|
234
|
+
// 4. 父绑定 epoch 清零(binding.workerEpoch 清零 → 下窗走初生路径)。
|
|
235
|
+
if (parentSessionId) {
|
|
236
|
+
try {
|
|
237
|
+
const parent = getSessionBinding(parentSessionId)
|
|
238
|
+
if (parent?.workerEpoch?.forkSessionId === forkId) setSessionBinding(parentSessionId, { workerEpoch: null })
|
|
239
|
+
} catch {}
|
|
240
|
+
}
|
|
241
|
+
// 5. 活动日志记 epoch 结束(退役是常规操作而非故障:qq-bridge 类长会话周期性到点换新,§6)。
|
|
242
|
+
try {
|
|
243
|
+
record({
|
|
244
|
+
kind: 'check',
|
|
245
|
+
scope: 'private',
|
|
246
|
+
sessionId: parentSessionId || forkId,
|
|
247
|
+
libraryId: binding?.libraryId || null,
|
|
248
|
+
ok: true,
|
|
249
|
+
message: '整理 worker 退役 · ' + String(reason || 'unknown')
|
|
250
|
+
+ (handoff === true ? ' · 交接(下窗交接包冷启动)' : ' · 不交接')
|
|
251
|
+
+ ' · epoch ' + (Number(epoch?.index) || '?') + ' · ' + (Number(epoch?.windows) || 0) + ' 窗 / ' + (Number(epoch?.chars) || 0) + ' 字符',
|
|
252
|
+
detail: { forkId, reason: reason || null, handoff: handoff === true, epoch: epoch ? { index: epoch.index, chars: epoch.chars, windows: epoch.windows } : null },
|
|
253
|
+
})
|
|
254
|
+
} catch {}
|
|
255
|
+
return { ok: true, forkId, reason, handoff: handoff === true, hadHandle: Boolean(handle) }
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// —— epoch 记账 ——————————————————————————————————————————————————————
|
|
259
|
+
// 每窗一次:chars += 增量 + 观测到的 worker 产出(监听器顺手累计的 assistant/tool 体积);
|
|
260
|
+
// windows += 1;结算成功清超时计数;超时 +1(连续 2 次 → 退役,§4.4);idleAt 记
|
|
261
|
+
// whenIdle 完成时刻(条件 4 的 TTL 起算点)。binding 传父会话的(内部重读最新值再写,
|
|
262
|
+
// 避免覆盖并发的绑定补丁);子绑定里的 epoch 副本同步刷新。
|
|
263
|
+
export function recordEpochProgress(binding, { incrementChars = 0, workerOutputChars = 0, idleAt = null, settled = false, timeout = false, progress = true, now = Date.now() } = {}) {
|
|
264
|
+
const sessionId = binding?.sessionId
|
|
265
|
+
if (!sessionId) return null
|
|
266
|
+
const current = (() => { try { return getSessionBinding(sessionId) || binding } catch { return binding } })()
|
|
267
|
+
const epoch = current?.workerEpoch
|
|
268
|
+
if (!epoch || typeof epoch !== 'object' || !epoch.forkSessionId) return null
|
|
269
|
+
const timeouts = Number(epoch.timeouts) || 0
|
|
270
|
+
const next = {
|
|
271
|
+
...epoch,
|
|
272
|
+
chars: Math.max(0, Number(epoch.chars) || 0)
|
|
273
|
+
+ (progress ? Math.max(0, Number(incrementChars) || 0) + Math.max(0, Number(workerOutputChars) || 0) : 0),
|
|
274
|
+
windows: (Number(epoch.windows) || 0) + (progress ? 1 : 0),
|
|
275
|
+
timeouts: timeout ? timeouts + 1 : (settled ? 0 : timeouts),
|
|
276
|
+
lastIdleAt: idleAt ? new Date(Number(idleAt) || now).toISOString() : (epoch.lastIdleAt || null),
|
|
277
|
+
}
|
|
278
|
+
try { setSessionBinding(sessionId, { workerEpoch: next }) } catch (error) {
|
|
279
|
+
try { warn('worker epoch progress write failed: ' + String(error?.message || error)) } catch {}
|
|
280
|
+
return null
|
|
281
|
+
}
|
|
282
|
+
try {
|
|
283
|
+
const child = getSessionBinding(epoch.forkSessionId)
|
|
284
|
+
if (child) setSessionBinding(epoch.forkSessionId, { workerEpoch: next })
|
|
285
|
+
} catch {}
|
|
286
|
+
return next
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// —— 三级试活(§4.6)———————————————————————————————————————————————
|
|
290
|
+
/**
|
|
291
|
+
* 获取或初生持久 worker。退役条件全部只在 acquire 时检查(执行中不误杀,§4.5):
|
|
292
|
+
* 1. scope/库/域变化 → 立即退役,无交接(上下文已污染)
|
|
293
|
+
* 2. 预算合格制(budgetFit)→ 换新,交接
|
|
294
|
+
* 3. epoch 窗口数超限 → 换新,交接
|
|
295
|
+
* 4. 距上一窗 idle 超 TTL → 换新,交接
|
|
296
|
+
* 条件 5(失败)与超时×2 是反应式退役,由 private.js 在结算失败/超时路径调用 retireWorker。
|
|
297
|
+
*
|
|
298
|
+
* 返回:
|
|
299
|
+
* { ok:true, forkId, handle, birth, reused, resumed, epoch, tools, restriction, epochAbort, retired, handoff }
|
|
300
|
+
* | { ok:false, reasonCode, error, retired? }
|
|
301
|
+
* handoff = 本 次 获 取 是否允许交接包语义(退役原因决定;无退役的复用窗口为 false)。
|
|
302
|
+
* epochAbort = 绑在 worker 生命周期上的控制器,供调用方硬停/重验时真正停住持久 worker(A2)。
|
|
303
|
+
*/
|
|
304
|
+
export async function acquireWorker(ctx, binding, {
|
|
305
|
+
incrementChars = 0, settings = null, probe = null,
|
|
306
|
+
agentOptions = null, header = null, now = Date.now(), idleWaitMs = WORKER_RETIRE_IDLE_WAIT_MS,
|
|
307
|
+
} = {}) {
|
|
308
|
+
const sessionId = binding?.sessionId
|
|
309
|
+
if (!sessionId) return { ok: false, reasonCode: 'no-binding', error: 'acquireWorker requires a session binding' }
|
|
310
|
+
const agents = ctx?.get?.('agents')
|
|
311
|
+
if (!agents || typeof agents.create !== 'function') {
|
|
312
|
+
return { ok: false, reasonCode: 'no-agents-service', error: 'host has no agents.create; the consolidation worker cannot start' }
|
|
313
|
+
}
|
|
314
|
+
settings = settings || getSettings()
|
|
315
|
+
const liveBinding = (() => { try { return getSessionBinding(sessionId) || binding } catch { return binding } })()
|
|
316
|
+
const retired = []
|
|
317
|
+
let epoch = liveBinding?.workerEpoch && typeof liveBinding.workerEpoch === 'object' ? liveBinding.workerEpoch : null
|
|
318
|
+
let prevIndex = Number(epoch?.index) || 0
|
|
319
|
+
let handoff = true // 初生包默认带交接上下文(§5.1:初生包与 handoff 包是同一个东西)
|
|
320
|
+
|
|
321
|
+
// —— Stage A:退役条件(只在这里查)———————————————————————————————
|
|
322
|
+
if (epoch?.forkSessionId) {
|
|
323
|
+
const generation = scopeGenerationOf(liveBinding)
|
|
324
|
+
const budget = epochBudget(liveBinding, settings)
|
|
325
|
+
let reason = null
|
|
326
|
+
if (!epoch.scopeGeneration || epoch.scopeGeneration !== generation) reason = 'scope-change'
|
|
327
|
+
else if (epoch.lastIdleAt && now - (Date.parse(epoch.lastIdleAt) || 0) > WORKER_EPOCH_IDLE_TTL_MS) reason = 'idle-ttl'
|
|
328
|
+
else if (!budgetFit(epoch, incrementChars, settings)) reason = 'char-limit'
|
|
329
|
+
else if ((Number(epoch.windows) || 0) >= budget.maxWindows) reason = 'window-limit'
|
|
330
|
+
if (reason) {
|
|
331
|
+
// scope-change 不交接(§4.5 条件 1);其余三个都交接(§5.2:上下文活在文件和账本里)。
|
|
332
|
+
const withHandoff = reason !== 'scope-change'
|
|
333
|
+
const result = await retireWorker(ctx, epoch.forkSessionId, reason, { handoff: withHandoff, now, idleWaitMs })
|
|
334
|
+
retired.push({ forkId: epoch.forkSessionId, reason, handoff: withHandoff, ok: result?.ok === true })
|
|
335
|
+
handoff = withHandoff
|
|
336
|
+
epoch = null
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
// —— Stage B:试活(get 进程内 → resume 跨重启 → 都失败视为已死)—————————————————
|
|
341
|
+
// 句柄归一化(bench 实测 bug #1):宿主 create 返回 handle 包装({agent,...}),而
|
|
342
|
+
// agents.get 返回**裸 Agent**——复用分支若把裸 Agent 当 handle 返回,派发处的
|
|
343
|
+
// `handle.agent.followup` 会读 undefined 崩溃(bench arm B 实录:窗口 2 复用后
|
|
344
|
+
// exception,后续窗口全部 already-exists)。归一成 create 同形状,三种来源统一。
|
|
345
|
+
const toHandle = (raw) => (raw ? (raw.agent != null ? raw : { agent: raw }) : null)
|
|
346
|
+
if (epoch?.forkSessionId) {
|
|
347
|
+
let handle = null
|
|
348
|
+
try { handle = (typeof agents.get === 'function' && toHandle(agents.get(epoch.forkSessionId))) || null } catch { handle = null }
|
|
349
|
+
let resumed = false
|
|
350
|
+
let resumeAbort = null
|
|
351
|
+
if (!handle && typeof agents?.resume === 'function') {
|
|
352
|
+
// 能力探测(任务约束):resume 不可用/抛错都跳过此级,绝不抛错。
|
|
353
|
+
// resume 的 signal 同样被宿主绑到 agent 生命周期(initializeAgent),作为新 epoch 的 abort。
|
|
354
|
+
resumeAbort = new AbortController()
|
|
355
|
+
try { handle = toHandle(await agents.resume({ resumeSessionId: epoch.forkSessionId, signal: resumeAbort.signal })) || null } catch { handle = null }
|
|
356
|
+
resumed = Boolean(handle)
|
|
357
|
+
}
|
|
358
|
+
if (handle) {
|
|
359
|
+
let disposables = disposablesOf(epoch.forkSessionId)
|
|
360
|
+
if (resumed) {
|
|
361
|
+
// 崩溃恢复(§4.6):工具注册是进程内的,resume 回来的 worker 必须重挂读写面。
|
|
362
|
+
const tools = probe?.hasWrite === true ? null : await attachWorkerTools(agents, epoch.forkSessionId, sessionId)
|
|
363
|
+
const restriction = await restrictWorkerTools(agents, epoch.forkSessionId, sessionId)
|
|
364
|
+
disposables = { tools, restriction, abort: resumeAbort }
|
|
365
|
+
epochDisposables.set(epoch.forkSessionId, disposables)
|
|
366
|
+
}
|
|
367
|
+
// A1(设计 §4.4):复用前必须等上一回合落地(有界)。超时废回合后 worker 可能还在跑,
|
|
368
|
+
// 直接发下一窗会把上一回合的 turn/end/回执/工具轮灌进本窗监听器。等到 idle 才安全;
|
|
369
|
+
// 等不到就是卡死——退役冷启动(宁可早换新),绝不把新回合塞进一个还在忙的 worker。
|
|
370
|
+
const idle = await waitWorkerIdle(handle, idleWaitMs)
|
|
371
|
+
if (idle) {
|
|
372
|
+
return {
|
|
373
|
+
ok: true, forkId: epoch.forkSessionId, handle,
|
|
374
|
+
birth: false, reused: true, resumed, epoch, tools: disposables?.tools || null, restriction: disposables?.restriction || null,
|
|
375
|
+
epochAbort: disposables?.abort || null,
|
|
376
|
+
retired, handoff: false,
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
const result = await retireWorker(ctx, epoch.forkSessionId, 'failure', { handoff: true, now, idleWaitMs })
|
|
380
|
+
retired.push({ forkId: epoch.forkSessionId, reason: 'failure', handoff: true, stuck: true, ok: result?.ok === true })
|
|
381
|
+
handoff = true
|
|
382
|
+
epoch = null
|
|
383
|
+
} else {
|
|
384
|
+
// 死亡(重启后 resume 不可用/会话被删):冷启动 + 交接包(§8);worker 会话本身没有
|
|
385
|
+
// 可等的回合,retire 只做清理与记账。
|
|
386
|
+
const result = await retireWorker(ctx, epoch.forkSessionId, 'failure', { handoff: true, now, idleWaitMs })
|
|
387
|
+
retired.push({ forkId: epoch.forkSessionId, reason: 'failure', handoff: true, gone: true, ok: result?.ok === true })
|
|
388
|
+
handoff = true
|
|
389
|
+
epoch = null
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// —— Stage C:初生(§4.1)———————————————————————————————————————————
|
|
394
|
+
let index = prevIndex + 1
|
|
395
|
+
let forkId = 'memu-worker-' + shortHash(sessionId) + '-' + index
|
|
396
|
+
const modelMaxContext = await probeModelMaxContext(ctx, agentOptions)
|
|
397
|
+
// A2:epoch 级 abort 控制器,绑到 agent 生命周期(宿主把 create.signal 永久接到 lifetime)。
|
|
398
|
+
// 续窗的硬停/重验 abort 它才能真正停住持久 worker——窗口级 signal 只在出生那次被宿主接线。
|
|
399
|
+
const epochAbort = new AbortController()
|
|
400
|
+
// 无种子创建(宿主 0.2.2-rc.3 已核实 seed 可选):初生包改为第一条 followup 消息,
|
|
401
|
+
// worker 路径完全解除 buildForkSeed 依赖(§4.1)。
|
|
402
|
+
// 同 id 撞车(bench 实测 bug):窗口 2 派发崩溃 → retireWorker('failure') 清 epoch,
|
|
403
|
+
// 但 dispose 只关句柄不删会话文件 → 下一窗初生用同一 forkId 被宿主拒绝
|
|
404
|
+
// (worker-create-failed: already exists,bench 实测连挂 10 次)→ 增量永远整理不进库。
|
|
405
|
+
// 撞车处理:先探测旧会话——**存活就收编**(重建 epoch 记账指向它,保留其累积上下文),
|
|
406
|
+
// 已死才 index 顺延换新 id 创建(≤6 次,孤儿链上逐个跳过)。
|
|
407
|
+
let handle = null
|
|
408
|
+
for (let createAttempt = 0; createAttempt < 6; createAttempt += 1) {
|
|
409
|
+
let collided = false
|
|
410
|
+
try {
|
|
411
|
+
handle = await agents.create({
|
|
412
|
+
sessionId: forkId,
|
|
413
|
+
meta: {
|
|
414
|
+
cwd: header?.cwd,
|
|
415
|
+
parentSession: sessionId,
|
|
416
|
+
// Without this the worker is treated as an ordinary user conversation by
|
|
417
|
+
// the injection path and the sidebar session lists(与 fork 同款隔离)。
|
|
418
|
+
origin: 'subagent',
|
|
419
|
+
agentPreset: header?.agentPreset,
|
|
420
|
+
},
|
|
421
|
+
agentOptions: agentOptions || undefined,
|
|
422
|
+
signal: epochAbort.signal,
|
|
423
|
+
})
|
|
424
|
+
} catch (error) {
|
|
425
|
+
const message = String(error?.message || error)
|
|
426
|
+
if (!/already exist/i.test(message)) {
|
|
427
|
+
return {
|
|
428
|
+
ok: false, reasonCode: 'worker-create-failed', forkId, retired,
|
|
429
|
+
error: 'the host rejected the consolidation worker: ' + message,
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
collided = true
|
|
433
|
+
}
|
|
434
|
+
if (!collided) break
|
|
435
|
+
// 撞车:探测旧会话——存活收编,死亡顺延换新 id。
|
|
436
|
+
const orphan = (() => { try { return (typeof agents.get === 'function' && agents.get(forkId)) || null } catch { return null } })()
|
|
437
|
+
if (orphan) {
|
|
438
|
+
handle = toHandle(orphan)
|
|
439
|
+
break
|
|
440
|
+
}
|
|
441
|
+
index += 1
|
|
442
|
+
forkId = 'memu-worker-' + shortHash(sessionId) + '-' + index
|
|
443
|
+
}
|
|
444
|
+
// 工具面只在初生挂一次(§15.2 改动点 2);标准 preset 的名单里已有 memu_* 时不重复挂。
|
|
445
|
+
const tools = probe?.hasWrite === true ? null : await attachWorkerTools(agents, forkId, sessionId)
|
|
446
|
+
const restriction = await restrictWorkerTools(agents, forkId, sessionId)
|
|
447
|
+
epochDisposables.set(forkId, { tools, restriction, abort: epochAbort })
|
|
448
|
+
const epochRecord = {
|
|
449
|
+
forkSessionId: forkId,
|
|
450
|
+
index,
|
|
451
|
+
birthAt: new Date(Number(now) || Date.now()).toISOString(),
|
|
452
|
+
chars: 0,
|
|
453
|
+
windows: 0,
|
|
454
|
+
timeouts: 0,
|
|
455
|
+
scopeGeneration: scopeGenerationOf(liveBinding),
|
|
456
|
+
parentSession: sessionId,
|
|
457
|
+
modelMaxContext: modelMaxContext || null,
|
|
458
|
+
lastIdleAt: null,
|
|
459
|
+
}
|
|
460
|
+
try {
|
|
461
|
+
setSessionBinding(forkId, { consolidationFork: true, origin: 'subagent', workerEpoch: epochRecord })
|
|
462
|
+
setSessionBinding(sessionId, { workerEpoch: epochRecord })
|
|
463
|
+
} catch (error) {
|
|
464
|
+
// epoch 记账写不进去就不该继续用持久 worker:这次整理按失败回 pending,下窗重试。
|
|
465
|
+
try { epochAbort.abort() } catch {}
|
|
466
|
+
try { await ((handle?.agent) || handle)?.dispose?.() } catch {}
|
|
467
|
+
epochDisposables.delete(forkId)
|
|
468
|
+
return {
|
|
469
|
+
ok: false, reasonCode: 'worker-epoch-unavailable', forkId, retired,
|
|
470
|
+
error: 'the worker epoch could not be persisted: ' + String(error?.message || error),
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
return {
|
|
474
|
+
ok: true, forkId, handle,
|
|
475
|
+
birth: true, reused: false, resumed: false, epoch: epochRecord, tools, restriction,
|
|
476
|
+
epochAbort,
|
|
477
|
+
retired, handoff,
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
// —— 增量读取与缺口重建(§3.3)———————————————————————————————————————
|
|
482
|
+
/**
|
|
483
|
+
* 本窗增量的唯一入口:turn-log 优先,缺口 rebuildRange 补,重建失败退回现场
|
|
484
|
+
* condenseEvents(不写日志,本窗结算语义不变)。回合是不可分单位:返回整回合记录。
|
|
485
|
+
*
|
|
486
|
+
* 缺口按"可记录回合"判定(A3):期望记录 = 宿主事件经 buildTurnRecords 能产出的整回合;
|
|
487
|
+
* 心跳/纯注入回合本就不落行,它们的 seq 区间不是洞,不能拿裸 seq 全覆盖去卡——否则
|
|
488
|
+
* 带心跳的会话每窗都误判缺口、永远退回现场压缩。consolidationTurnLog=off 时不读不写
|
|
489
|
+
* 日志,直接现场压缩(A7,设计 §10.1)。
|
|
490
|
+
*/
|
|
491
|
+
export function loadWorkerIncrement({ sessionId, binding = null, window = null, events = [] } = {}) {
|
|
492
|
+
const fromSeq = Number(window?.fromSeq)
|
|
493
|
+
const throughSeq = Number(window?.throughSeq)
|
|
494
|
+
if (!Number.isSafeInteger(fromSeq) || !Number.isSafeInteger(throughSeq) || throughSeq < fromSeq) {
|
|
495
|
+
return { records: [], text: '', chars: 0, source: 'empty', digest: null }
|
|
496
|
+
}
|
|
497
|
+
const eventsInWindow = (Array.isArray(events) ? events : []).filter((event) => {
|
|
498
|
+
const seq = Number(event?.seq)
|
|
499
|
+
return Number.isSafeInteger(seq) && seq >= fromSeq && seq <= throughSeq
|
|
500
|
+
})
|
|
501
|
+
const condenseFallback = (why) => {
|
|
502
|
+
let text = ''
|
|
503
|
+
try { text = condenseEvents(eventsInWindow, WORKER_INCREMENT_FALLBACK_CHARS) || '' } catch { text = '' }
|
|
504
|
+
return { records: [], text: String(text), chars: String(text).length, source: 'fallback', digest: why }
|
|
505
|
+
}
|
|
506
|
+
// A7:off 时不读不写日志,直接现场压缩。
|
|
507
|
+
let turnLogOn = true
|
|
508
|
+
try { turnLogOn = getSettings().consolidationTurnLog !== 'off' } catch { turnLogOn = true }
|
|
509
|
+
if (!turnLogOn) return condenseFallback('现场压缩(turn-log 已关闭)')
|
|
510
|
+
|
|
511
|
+
const lastSleepSeq = Number(binding?.lastSleepSeq)
|
|
512
|
+
const after = Number.isSafeInteger(lastSleepSeq) && lastSleepSeq >= 0 ? lastSleepSeq : -1
|
|
513
|
+
const expected = buildTurnRecords(eventsInWindow)
|
|
514
|
+
const logRows = () => { try { return readIncrement(sessionId, -1).records || [] } catch { return [] } }
|
|
515
|
+
const covers = (rows, rec) => rows.some((row) => {
|
|
516
|
+
const s = Number(row?.seq?.[0])
|
|
517
|
+
const e = Number(row?.seq?.[1])
|
|
518
|
+
return Number.isSafeInteger(s) && Number.isSafeInteger(e) && s <= rec.seq[0] && e >= rec.seq[1]
|
|
519
|
+
})
|
|
520
|
+
let source = 'turn-log'
|
|
521
|
+
let rows = logRows()
|
|
522
|
+
let missing = expected.filter((rec) => !covers(rows, rec))
|
|
523
|
+
if (missing.length > 0) {
|
|
524
|
+
try { rebuildRange(sessionId, fromSeq, throughSeq, events) } catch {}
|
|
525
|
+
rows = logRows()
|
|
526
|
+
missing = expected.filter((rec) => !covers(rows, rec))
|
|
527
|
+
if (missing.length > 0) return condenseFallback('现场压缩(turn-log 缺口重建失败)')
|
|
528
|
+
source = 'rebuilt'
|
|
529
|
+
} else if (expected.length === 0 && eventsInWindow.length > 0) {
|
|
530
|
+
// 没有可记录的闭合回合、日志也没覆盖:可能是开回合/裸转录,现场压缩兜底,
|
|
531
|
+
// 避免把有内容的区间喂成空增量。
|
|
532
|
+
const inWindow = rows.filter((row) => {
|
|
533
|
+
const s = Number(row?.seq?.[0])
|
|
534
|
+
const e = Number(row?.seq?.[1])
|
|
535
|
+
return Number.isSafeInteger(s) && Number.isSafeInteger(e) && e > after && s <= throughSeq
|
|
536
|
+
})
|
|
537
|
+
if (inWindow.length === 0) return condenseFallback('现场压缩(无可记录回合)')
|
|
538
|
+
}
|
|
539
|
+
// 增量 = 尚未完整结算的整回合(seqEnd > lastSleepSeq)且起点在本窗内。窗口已在
|
|
540
|
+
// worker 模式对齐到整回合边界(A5),正常不会有跨骑记录;此处仍按整回合过滤兜底。
|
|
541
|
+
const records = rows.filter((row) => {
|
|
542
|
+
const start = Number(row?.seq?.[0])
|
|
543
|
+
const end = Number(row?.seq?.[1])
|
|
544
|
+
return Number.isSafeInteger(start) && Number.isSafeInteger(end) && end > after && start <= throughSeq
|
|
545
|
+
})
|
|
546
|
+
const text = records.map((row) => JSON.stringify(row)).join('\n')
|
|
547
|
+
const first = records.length > 0 ? Number(records[0]?.seq?.[0]) : null
|
|
548
|
+
const last = records.length > 0 ? Number(records[records.length - 1]?.seq?.[1]) : null
|
|
549
|
+
const digest = records.length > 0
|
|
550
|
+
? `${records.length} 回合 · seq ${first}–${last}${source === 'rebuilt' ? ' · 缺口重建' : ''}`
|
|
551
|
+
: null
|
|
552
|
+
return { records, text, chars: text.length, source, digest }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
// —— 包组装(§4.2 续窗增量包 / §5.1 初生·交接包)——————————————————————————
|
|
556
|
+
|
|
557
|
+
const PENDING_OPEN = '--- 待处理回合 ---'
|
|
558
|
+
const PENDING_CLOSE = '--- 结束 ---'
|
|
559
|
+
const TAIL_OPEN = '--- 已结算参考(勿为其写新记忆,只处理待处理区间)---'
|
|
560
|
+
const TAIL_CLOSE = '--- 已结算参考结束 ---'
|
|
561
|
+
|
|
562
|
+
function renderRecords(records) {
|
|
563
|
+
return (Array.isArray(records) ? records : []).map((row) => JSON.stringify(row)).join('\n')
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function pendingNoteLine(pendingNote, pendingHash) {
|
|
567
|
+
if (!pendingNote) return ''
|
|
568
|
+
if (typeof pendingNote === 'string' && pendingNote.trim()) return pendingNote
|
|
569
|
+
const prefix = typeof pendingHash === 'string' && pendingHash ? `(${pendingHash.slice(0, 12)}…)` : ''
|
|
570
|
+
return `[上窗未结算${prefix}] 上一窗${prefix}未结算完成:先核对库内是否已写入,勿重复写;本包与上一窗是同一段待处理区间的重发,重复写入会被去重拦下,但请先核对再动手。`
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
function catalogTextOf(catalog) {
|
|
574
|
+
if (!catalog) return ''
|
|
575
|
+
if (typeof catalog === 'string') return catalog.trim()
|
|
576
|
+
const blocks = Array.isArray(catalog?.data?.content) ? catalog.data.content : []
|
|
577
|
+
return blocks.map((block) => (block?.type === 'text' && typeof block.text === 'string' ? block.text : '')).filter(Boolean).join('\n').trim()
|
|
578
|
+
}
|
|
579
|
+
|
|
580
|
+
function catalogIdsOf(catalogText) {
|
|
581
|
+
const ids = new Set()
|
|
582
|
+
for (const match of String(catalogText || '').matchAll(/^- \[([^\]\n]+)\]/gm)) ids.add(match[1])
|
|
583
|
+
return ids
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/** 必写候选(续窗包):顺延候选 ≤4、总数 ≤8 的双闸在这里再兜一道(mergeMustCover 同语义)。 */
|
|
587
|
+
function renderCarry(rows, { max = 8, carriedMax = 4 } = {}) {
|
|
588
|
+
const list = Array.isArray(rows) ? rows : []
|
|
589
|
+
if (list.length === 0) return ''
|
|
590
|
+
const lines = ['[必写候选(先写这些;每条都必须落库,或在失败说明里写明为什么不写,不得静默跳过)]']
|
|
591
|
+
let carried = 0
|
|
592
|
+
let shown = 0
|
|
593
|
+
for (const row of list) {
|
|
594
|
+
if (shown >= Math.max(1, Number(max) || 8)) break
|
|
595
|
+
const isCarried = row?.carried === true
|
|
596
|
+
if (isCarried && carried >= Math.max(0, Number(carriedMax) || 0)) continue
|
|
597
|
+
if (isCarried) carried += 1
|
|
598
|
+
shown += 1
|
|
599
|
+
const where = isCarried
|
|
600
|
+
? '顺延' + (row?.observedAt ? ' · 事件时间 ' + row.observedAt : '')
|
|
601
|
+
: '第 ' + (Number.isSafeInteger(Number(row?.fromSeq)) ? row.fromSeq : '?') + '–'
|
|
602
|
+
+ (Number.isSafeInteger(Number(row?.throughSeq)) ? row.throughSeq : '?') + ' 条'
|
|
603
|
+
+ (row?.tag ? ' · ' + row.tag : '') + (row?.observedAt ? ' · 事件时间 ' + row.observedAt : '')
|
|
604
|
+
lines.push(`${shown}. [${where}] ${String(row?.text || '').slice(0, 120)}`)
|
|
605
|
+
}
|
|
606
|
+
return lines.length > 1 ? lines.join('\n') : ''
|
|
607
|
+
}
|
|
608
|
+
|
|
609
|
+
function sceneTimeLine(sceneTime) {
|
|
610
|
+
const value = typeof sceneTime === 'string' ? sceneTime.trim() : ''
|
|
611
|
+
if (!value) return ''
|
|
612
|
+
return `[场景时间] ${value}(时间锚点:observed_at 与今天/明天/下周X 等相对日期按这个场景时间推算,不要用真实时钟。)`
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
/**
|
|
616
|
+
* 已写入摘要(§4.2/§5.2):账本 recordOperation 历史 → 最近 20 条 id+标题 +
|
|
617
|
+
* 「另有 M 条均已在库」,与目录头按 id 去重。摘要只是省无效写入的成本优化,
|
|
618
|
+
* 不是正确性防线(铁律 1:对账与库级去重兜底)。
|
|
619
|
+
*/
|
|
620
|
+
function writtenSummary(sessionId, binding, { writtenRows = null, writtenTotal = null, catalogIds = new Set(), limit = 20 } = {}) {
|
|
621
|
+
let ids = []
|
|
622
|
+
let total = null
|
|
623
|
+
if (Array.isArray(writtenRows)) {
|
|
624
|
+
ids = writtenRows.map((row) => String(row?.id || '')).filter(Boolean)
|
|
625
|
+
total = Number.isSafeInteger(Number(writtenTotal)) ? Number(writtenTotal) : ids.length
|
|
626
|
+
} else {
|
|
627
|
+
let ops = []
|
|
628
|
+
try { ops = Object.values(loadLedger().sessions?.[String(sessionId || '')]?.operations || {}) } catch { ops = [] }
|
|
629
|
+
for (const op of ops.slice().sort((a, b) => String(b?.at || '').localeCompare(String(a?.at || '')))) {
|
|
630
|
+
for (const id of Array.isArray(op?.ids) ? op.ids : []) {
|
|
631
|
+
const key = String(id || '')
|
|
632
|
+
if (key && !ids.includes(key)) ids.push(key)
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
total = ids.length
|
|
636
|
+
}
|
|
637
|
+
const deduped = ids.filter((id) => !catalogIds.has(id))
|
|
638
|
+
const shown = deduped.slice(0, Math.max(1, Number(limit) || 20))
|
|
639
|
+
if (shown.length === 0) return ''
|
|
640
|
+
const titles = new Map()
|
|
641
|
+
if (Array.isArray(writtenRows)) {
|
|
642
|
+
for (const row of writtenRows) titles.set(String(row?.id || ''), String(row?.title || '(untitled)').slice(0, 80))
|
|
643
|
+
} else {
|
|
644
|
+
try {
|
|
645
|
+
const entries = loadPrivateIndex(binding?.libraryId)?.entries || {}
|
|
646
|
+
for (const id of shown) titles.set(id, String(entries[id]?.title || '(untitled)').slice(0, 80))
|
|
647
|
+
} catch { /* 索引缺失只降级标题,摘要照发 */ }
|
|
648
|
+
}
|
|
649
|
+
const lines = ['[已写入摘要(账本记录,防重复写;目录里已有的不再列出)]']
|
|
650
|
+
for (const id of shown) lines.push(`- [${id}] ${titles.get(id) || '(untitled)'}`)
|
|
651
|
+
const rest = Math.max(0, (Number(total) || deduped.length) - shown.length)
|
|
652
|
+
if (rest > 0) lines.push(`另有 ${rest} 条均已在库。`)
|
|
653
|
+
return lines.join('\n')
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
/** 交接尾部(§5.2):tailSlice 整回合取尾,再滤掉未结算段(seqEnd ≤ lastSleepSeq)。 */
|
|
657
|
+
function tailSection(sessionId, { lastSleepSeq = null, tailChars = WORKER_HANDOFF_TAIL_CHARS } = {}) {
|
|
658
|
+
const ceiling = Number.isSafeInteger(Number(lastSleepSeq)) && Number(lastSleepSeq) >= 0 ? Number(lastSleepSeq) : null
|
|
659
|
+
// 没有结算游标 = 整份日志都是未结算增量,没有「已结算参考」可带(尾部会与增量整段重复)。
|
|
660
|
+
if (ceiling === null) return ''
|
|
661
|
+
let slice = null
|
|
662
|
+
try { slice = tailSlice(sessionId, tailChars) } catch { return '' }
|
|
663
|
+
const records = (Array.isArray(slice?.records) ? slice.records : []).filter((row) => {
|
|
664
|
+
const end = Number(row?.seq?.[1])
|
|
665
|
+
return Number.isSafeInteger(end) && end <= ceiling
|
|
666
|
+
})
|
|
667
|
+
if (records.length === 0) return ''
|
|
668
|
+
return [TAIL_OPEN, renderRecords(records), TAIL_CLOSE].join('\n')
|
|
669
|
+
}
|
|
670
|
+
|
|
671
|
+
/**
|
|
672
|
+
* 续窗增量包(§4.2):分隔标记夹住的待处理回合 + 目录头(每窗都发)+ 必写候选
|
|
673
|
+
* (顺延 ≤4)+ 回执契约 + 场景时间(每窗重读)。已写入摘要不发(worker 上下文里
|
|
674
|
+
* 刚写过,续窗发是冗余);上一窗未结算时开头带核对说明(§4.4)。
|
|
675
|
+
*/
|
|
676
|
+
export function buildIncrementPack({
|
|
677
|
+
binding = null, incrementRecords = [], incrementText = null, catalog = null,
|
|
678
|
+
digest = null, carry = [], contract = '', sceneTime = null,
|
|
679
|
+
pendingNote = false, pendingHash = null, carryMax = 4,
|
|
680
|
+
} = {}) {
|
|
681
|
+
const sections = []
|
|
682
|
+
const note = pendingNoteLine(pendingNote, pendingHash)
|
|
683
|
+
if (note) sections.push(note)
|
|
684
|
+
if (digest) sections.push('[待处理增量] ' + String(digest))
|
|
685
|
+
sections.push(PENDING_OPEN)
|
|
686
|
+
const body = (typeof incrementText === 'string' && incrementText.trim()) ? incrementText : renderRecords(incrementRecords)
|
|
687
|
+
sections.push(body || '(本窗没有可读的回合记录)')
|
|
688
|
+
sections.push(PENDING_CLOSE)
|
|
689
|
+
const catalogText = catalogTextOf(catalog)
|
|
690
|
+
if (catalogText) sections.push(catalogText)
|
|
691
|
+
const carryText = renderCarry(carry, { carriedMax: carryMax })
|
|
692
|
+
if (carryText) sections.push(carryText)
|
|
693
|
+
if (typeof contract === 'string' && contract.trim()) sections.push(contract)
|
|
694
|
+
const sceneLine = sceneTimeLine(sceneTime)
|
|
695
|
+
if (sceneLine) sections.push(sceneLine)
|
|
696
|
+
return sections.join('\n')
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
/**
|
|
700
|
+
* 初生包 = 交接包(§5.1):身份/规则任务书(buildWorkerBrief,必写候选随它下发)+
|
|
701
|
+
* 待处理回合 + 库目录头 + 已写入摘要(最近 20 条 + 计数,与目录去重)+ turn-log 尾部
|
|
702
|
+
* (标注「已结算参考」,滤掉未结算段)+ 场景时间。退役原因 scope-change / failure 时
|
|
703
|
+
* 由调用方传 includeTail: false / writtenRows: []——「不做 handoff」= 不带旧 epoch 的
|
|
704
|
+
* 连续性材料,身份与目录照发。
|
|
705
|
+
*/
|
|
706
|
+
export function buildHandoffPack({
|
|
707
|
+
sessionId = null, binding = null, snapshot = null, probe = null, jobId = null,
|
|
708
|
+
reason = 'auto', singleOnly = false, mustCover = [], contract = '',
|
|
709
|
+
incrementRecords = [], incrementText = null, digest = null,
|
|
710
|
+
catalog = null, sceneTime = null, pendingNote = false, pendingHash = null,
|
|
711
|
+
writtenRows = null, writtenTotal = null,
|
|
712
|
+
lastSleepSeq = null, tailChars = WORKER_HANDOFF_TAIL_CHARS, includeTail = true,
|
|
713
|
+
} = {}) {
|
|
714
|
+
const brief = buildWorkerBrief({ snapshot, probe, contract, reason, jobId, mustCover, autoReceipt: true, singleOnly })
|
|
715
|
+
const sections = [brief]
|
|
716
|
+
const note = pendingNoteLine(pendingNote, pendingHash)
|
|
717
|
+
if (note) sections.push(note)
|
|
718
|
+
if (digest) sections.push('[待处理增量] ' + String(digest))
|
|
719
|
+
sections.push(PENDING_OPEN)
|
|
720
|
+
const body = (typeof incrementText === 'string' && incrementText.trim()) ? incrementText : renderRecords(incrementRecords)
|
|
721
|
+
sections.push(body || '(本窗没有可读的回合记录)')
|
|
722
|
+
sections.push(PENDING_CLOSE)
|
|
723
|
+
const catalogText = catalogTextOf(catalog)
|
|
724
|
+
if (catalogText) sections.push(catalogText)
|
|
725
|
+
const summary = writtenSummary(sessionId, binding, { writtenRows, writtenTotal, catalogIds: catalogIdsOf(catalogText) })
|
|
726
|
+
if (summary) sections.push(summary)
|
|
727
|
+
if (includeTail !== false && sessionId) {
|
|
728
|
+
const tail = tailSection(sessionId, { lastSleepSeq, tailChars })
|
|
729
|
+
if (tail) sections.push(tail)
|
|
730
|
+
}
|
|
731
|
+
const sceneLine = sceneTimeLine(sceneTime)
|
|
732
|
+
if (sceneLine) sections.push(sceneLine)
|
|
733
|
+
return sections.join('\n')
|
|
734
|
+
}
|
|
735
|
+
|
|
736
|
+
export default {
|
|
737
|
+
WORKER_EPOCH_TIERS, WORKER_OUTPUT_FACTOR, WORKER_EPOCH_IDLE_TTL_MS, WORKER_HANDOFF_TAIL_CHARS,
|
|
738
|
+
WORKER_TIMEOUT_LIMIT, WORKER_RETIRE_IDLE_WAIT_MS, WORKER_INCREMENT_FALLBACK_CHARS,
|
|
739
|
+
epochBudget, budgetFit, probeModelMaxContext, attachWorkerTools, restrictWorkerTools,
|
|
740
|
+
retireWorker, recordEpochProgress, acquireWorker, loadWorkerIncrement, buildIncrementPack, buildHandoffPack,
|
|
741
|
+
}
|