dsh-memu-memory 1.3.7 → 1.3.8
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 +1 -1
- package/CHANGELOG.md +58 -0
- package/README.md +7 -7
- package/README.zh.md +7 -7
- package/docs/client-conventions.md +1 -0
- package/docs/contributing.md +2 -2
- package/docs/memory-semantics.md +7 -6
- package/docs/troubleshooting.md +74 -7
- package/lib/binding-diagnostics.js +2 -2
- package/lib/client.js +150 -81
- package/lib/consolidation-ledger.js +6 -2
- package/lib/inbound.js +24 -9
- package/lib/inject.js +379 -215
- package/lib/memory.js +704 -181
- package/lib/paths.js +24 -0
- package/lib/private.js +242 -132
- package/lib/rpc.js +53 -6
- package/lib/snippet.js +49 -28
- package/lib/state.js +185 -26
- package/lib/tools.js +137 -28
- package/lib/webui.js +25 -1
- package/lib/worker-pool.js +260 -26
- package/package.json +1 -1
- package/scripts/check-i18n.mjs +19 -0
- package/scripts/recall-bench.mjs +4 -4
- package/scripts/simulate-injection.mjs +3 -0
- package/tests/activity-wiring.test.mjs +52 -0
- package/tests/client-render.test.mjs +207 -0
- package/tests/consolidation-feed.test.mjs +26 -0
- package/tests/consolidation-fork.test.mjs +587 -26
- package/tests/cross-library-recall.test.mjs +156 -0
- package/tests/cue.test.mjs +15 -2
- package/tests/hybrid-recall.test.mjs +488 -0
- package/tests/inbound.test.mjs +49 -4
- package/tests/inject-conflict.test.mjs +70 -9
- package/tests/inject-guide.test.mjs +13 -1
- package/tests/inject.test.mjs +10 -0
- package/tests/injection-budget.test.mjs +101 -0
- package/tests/injection-chain.test.mjs +37 -0
- package/tests/injection-rollback.test.mjs +172 -9
- package/tests/issue2-chain.test.mjs +169 -0
- package/tests/lexicon-inject.test.mjs +33 -5
- package/tests/managed-memory.test.mjs +625 -1
- package/tests/media.test.mjs +1 -1
- package/tests/new-session-gate.test.mjs +280 -25
- package/tests/open-loop-date.test.mjs +11 -1
- package/tests/recall-intent.test.mjs +52 -3
- package/tests/simulate-injection.test.mjs +4 -4
- package/tests/snippet.test.mjs +33 -1
- package/tests/state.test.mjs +8 -3
- package/tests/tool-schema.test.mjs +52 -0
- package/tests/tools.test.mjs +394 -0
- package/tests/webui.test.mjs +16 -2
- package/tests/worker-lifecycle.test.mjs +419 -36
package/lib/worker-pool.js
CHANGED
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
// 默认 consolidationRunner: 'fork'——本模块的全部路径只在设置显式切到 'worker'
|
|
10
10
|
// 时被 private.js 调用;'fork'(现状每窗新 fork)行为逐字节不变。
|
|
11
11
|
import { getSessionBinding, getSettings, setSessionBinding, deleteSessionBinding, loadPrivateIndex } from './state.js'
|
|
12
|
-
import
|
|
12
|
+
import fs from 'node:fs'
|
|
13
|
+
import { warn, shortHash, dataDir } from './paths.js'
|
|
14
|
+
import { estTokens } from './budget.js'
|
|
13
15
|
import { record } from './activity-log.js'
|
|
14
16
|
import { loadLedger, scopeGenerationOf } from './consolidation-ledger.js'
|
|
15
17
|
import { buildWorkerBrief, CORE_WRITE_TOOLS, WORKER_READ_TOOLS, WORKER_WRITE_TOOLS, WORKER_TOOL_ALLOW } from './consolidation-worker.js'
|
|
@@ -67,6 +69,136 @@ export function budgetFit(epoch, incrementChars, settings = null) {
|
|
|
67
69
|
return chars + increment * WORKER_OUTPUT_FACTOR <= epochBudget({ workerEpoch: epoch }, settings).charLimit
|
|
68
70
|
}
|
|
69
71
|
|
|
72
|
+
/** Never repair a user's path or change host permissions; only select a usable cwd. */
|
|
73
|
+
export function resolveConsolidationCwd(headerCwd, fallback = dataDir()) {
|
|
74
|
+
try {
|
|
75
|
+
if (typeof headerCwd === 'string' && headerCwd && fs.statSync(headerCwd).isDirectory()) return headerCwd
|
|
76
|
+
} catch { /* Deleted/inaccessible cwd: use the plugin data directory. */ }
|
|
77
|
+
return fallback
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function measurePacket(text, kind = 'increment') {
|
|
81
|
+
const value = String(text ?? '')
|
|
82
|
+
return { kind, inputChars: value.length, estimatedTokens: estTokens(value) }
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function packetBudgetFit(epoch, packet, settings = null) {
|
|
86
|
+
return budgetFit(epoch, packet?.inputChars, settings)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const USAGE_FIELDS = ['inputTokens', 'cacheReadTokens', 'cacheWriteTokens', 'outputTokens', 'reasoningTokens']
|
|
90
|
+
|
|
91
|
+
/** Per-window counters only. Event/call identities stay in closure, never bodies. */
|
|
92
|
+
export function createConsolidationMeasurement(runner, { sessionId = '', afterSeq = null } = {}) {
|
|
93
|
+
const measurement = {
|
|
94
|
+
schemaVersion: 2, measurementVersion: 2, runner,
|
|
95
|
+
packet: null,
|
|
96
|
+
dispatched: { inputChars: 0, estimatedTokens: 0, followups: 0, wrapupChars: 0 },
|
|
97
|
+
observed: { outputTextChars: 0, toolArgumentsChars: 0, toolResultsChars: 0, reasoningChars: null, estimatedTokens: 0 },
|
|
98
|
+
usage: { ...Object.fromEntries(USAGE_FIELDS.map(key => [key, null])), source: 'unavailable', requests: 0 },
|
|
99
|
+
serializationErrors: 0,
|
|
100
|
+
toolEvents: 0, logicalToolCalls: 0,
|
|
101
|
+
lastEventSeq: Number.isSafeInteger(afterSeq) ? afterSeq : null,
|
|
102
|
+
}
|
|
103
|
+
const events = new Set()
|
|
104
|
+
const calls = new Set()
|
|
105
|
+
const requests = new Map()
|
|
106
|
+
const objects = new WeakSet()
|
|
107
|
+
let anonymousEvent = 0
|
|
108
|
+
const serialized = (value) => {
|
|
109
|
+
if (typeof value === 'string') return value
|
|
110
|
+
if (value == null) return ''
|
|
111
|
+
try { return JSON.stringify(value) ?? '' } catch {
|
|
112
|
+
measurement.serializationErrors += 1
|
|
113
|
+
warn('consolidation measurement: tool payload could not be serialized; size is unknown')
|
|
114
|
+
return null
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
const add = (key, text, retained = true) => {
|
|
118
|
+
if (text === null) {
|
|
119
|
+
measurement.observed[key] = null
|
|
120
|
+
if (retained) measurement.observed.estimatedTokens = null
|
|
121
|
+
return
|
|
122
|
+
}
|
|
123
|
+
if (measurement.observed[key] !== null || key === 'reasoningChars') {
|
|
124
|
+
// reasoning is unknown until a real reasoning block is observed.
|
|
125
|
+
measurement.observed[key] = (measurement.observed[key] ?? 0) + text.length
|
|
126
|
+
}
|
|
127
|
+
if (retained && measurement.observed.estimatedTokens !== null) measurement.observed.estimatedTokens += estTokens(text)
|
|
128
|
+
}
|
|
129
|
+
const tool = (phase, id, payload, fallback) => {
|
|
130
|
+
const callId = typeof id === 'string' || Number.isSafeInteger(id) ? id : fallback
|
|
131
|
+
const key = JSON.stringify([phase, callId])
|
|
132
|
+
if (calls.has(key)) return
|
|
133
|
+
if (payload === undefined) return
|
|
134
|
+
calls.add(key)
|
|
135
|
+
if (phase === 'arguments') measurement.logicalToolCalls += 1
|
|
136
|
+
add(phase === 'arguments' ? 'toolArgumentsChars' : 'toolResultsChars', serialized(payload))
|
|
137
|
+
}
|
|
138
|
+
const observe = (event) => {
|
|
139
|
+
if (!event || typeof event !== 'object') return false
|
|
140
|
+
const seq = event.seq
|
|
141
|
+
const eventId = typeof event.id === 'string' || Number.isSafeInteger(event.id) ? event.id : null
|
|
142
|
+
const key = Number.isSafeInteger(seq) ? JSON.stringify([sessionId, seq]) : (eventId !== null ? JSON.stringify([sessionId, eventId]) : null)
|
|
143
|
+
if (Number.isSafeInteger(seq) && Number.isSafeInteger(afterSeq) && seq <= afterSeq) return false
|
|
144
|
+
if (key ? events.has(key) : objects.has(event)) return false
|
|
145
|
+
if (key) events.add(key)
|
|
146
|
+
else objects.add(event)
|
|
147
|
+
if (Number.isSafeInteger(seq)) measurement.lastEventSeq = Math.max(measurement.lastEventSeq ?? -1, seq)
|
|
148
|
+
const fallback = key || 'anonymous-' + (++anonymousEvent)
|
|
149
|
+
const data = event.data || {}
|
|
150
|
+
if (['tool/call', 'tool/result', 'tool/ptc-dispatch-start', 'tool/ptc-dispatch'].includes(event.type)) measurement.toolEvents += 1
|
|
151
|
+
if (event.type === 'assistant/message') {
|
|
152
|
+
for (const [index, block] of (Array.isArray(data.message?.content) ? data.message.content : []).entries()) {
|
|
153
|
+
if (block?.type === 'text' && typeof block.text === 'string') add('outputTextChars', block.text)
|
|
154
|
+
if (block?.type === 'reasoning' && typeof block.text === 'string') add('reasoningChars', block.text, false)
|
|
155
|
+
if (block?.type === 'tool-call') tool('arguments', block.id, block.arguments, fallback + ':' + index)
|
|
156
|
+
}
|
|
157
|
+
// Verified public assistant/message.data.usage only: input is non-cached;
|
|
158
|
+
// output includes reasoning when supplied. Never sum reasoning into output.
|
|
159
|
+
const requestId = typeof data.requestId === 'string' || Number.isSafeInteger(data.requestId) ? data.requestId : null
|
|
160
|
+
const requestKey = requestId !== null ? JSON.stringify([sessionId, requestId]) : key || fallback
|
|
161
|
+
const previous = requests.get(requestKey) || {}
|
|
162
|
+
let known = false
|
|
163
|
+
for (const field of USAGE_FIELDS) {
|
|
164
|
+
const value = data.usage?.[field]
|
|
165
|
+
if (!Number.isSafeInteger(value) || value < 0 || previous[field] !== undefined) continue
|
|
166
|
+
previous[field] = value
|
|
167
|
+
known = true
|
|
168
|
+
}
|
|
169
|
+
requests.set(requestKey, previous)
|
|
170
|
+
for (const field of USAGE_FIELDS) {
|
|
171
|
+
const rows = [...requests.values()]
|
|
172
|
+
measurement.usage[field] = rows.every(row => row[field] !== undefined)
|
|
173
|
+
? rows.reduce((sum, row) => sum + row[field], 0) : null
|
|
174
|
+
}
|
|
175
|
+
measurement.usage.requests = requests.size
|
|
176
|
+
if (known) measurement.usage.source = 'assistant/message.data.usage'
|
|
177
|
+
}
|
|
178
|
+
if (event.type === 'tool/call' || event.type === 'tool/ptc-dispatch-start') {
|
|
179
|
+
tool('arguments', data.subCallId ?? data.callId, data.arguments, fallback)
|
|
180
|
+
}
|
|
181
|
+
if (event.type === 'tool/ptc-dispatch') {
|
|
182
|
+
if (data.arguments !== undefined) tool('arguments', data.subCallId ?? data.callId, data.arguments, fallback)
|
|
183
|
+
tool('results', data.subCallId ?? data.callId, data.content ?? event.content ?? data.message?.content, fallback)
|
|
184
|
+
}
|
|
185
|
+
if (event.type === 'tool/result') {
|
|
186
|
+
tool('results', data.message?.callId ?? data.callId, data.message?.content ?? data.content ?? event.content, fallback)
|
|
187
|
+
}
|
|
188
|
+
return true
|
|
189
|
+
}
|
|
190
|
+
const dispatch = (text, kind) => {
|
|
191
|
+
const packet = measurePacket(text, kind)
|
|
192
|
+
if (!measurement.packet) measurement.packet = packet
|
|
193
|
+
measurement.dispatched.inputChars += packet.inputChars
|
|
194
|
+
measurement.dispatched.estimatedTokens += packet.estimatedTokens
|
|
195
|
+
measurement.dispatched.followups += 1
|
|
196
|
+
if (kind === 'wrapup') measurement.dispatched.wrapupChars += packet.inputChars
|
|
197
|
+
return packet
|
|
198
|
+
}
|
|
199
|
+
return { measurement, observe, dispatch }
|
|
200
|
+
}
|
|
201
|
+
|
|
70
202
|
/** 宿主模型发现的 maxContext 尽力获取;拿不到返回 null(epochBudget 落第一档)。 */
|
|
71
203
|
export async function probeModelMaxContext(ctx, agentOptions) {
|
|
72
204
|
const provider = typeof agentOptions?.provider === 'string' ? agentOptions.provider : ''
|
|
@@ -205,6 +337,46 @@ async function waitWorkerIdle(handle, idleWaitMs) {
|
|
|
205
337
|
return idle
|
|
206
338
|
}
|
|
207
339
|
|
|
340
|
+
// Read the public child's cursor AFTER idle, before subscribing to a new window.
|
|
341
|
+
// Catch up output that landed with the old listener detached, charging its epoch
|
|
342
|
+
// without adding a window. Fence its replay off from the next job's counters.
|
|
343
|
+
async function workerEventCursor(ctx, forkId, previous = null, measureTail = false) {
|
|
344
|
+
let lease = null
|
|
345
|
+
try {
|
|
346
|
+
const query = ctx?.get?.('sessionQuery')
|
|
347
|
+
if (typeof query?.observeSession === 'function') lease = await query.observeSession(forkId, { projectionMode: 'none' })
|
|
348
|
+
else if (typeof query?.readSession === 'function') lease = await query.readSession(forkId)
|
|
349
|
+
let cursor = Number.isSafeInteger(previous) ? previous : null
|
|
350
|
+
if (Number.isSafeInteger(lease?.cursor)) cursor = Math.max(cursor ?? -1, lease.cursor)
|
|
351
|
+
const rows = Array.isArray(lease?.events) ? lease.events : []
|
|
352
|
+
for (const event of rows) {
|
|
353
|
+
if (Number.isSafeInteger(event?.seq)) cursor = Math.max(cursor ?? -1, event.seq)
|
|
354
|
+
}
|
|
355
|
+
let tail = null
|
|
356
|
+
if (measureTail && cursor !== null && cursor > (previous ?? -1)) {
|
|
357
|
+
// Seed identities from the old prefix, then take only the new counters.
|
|
358
|
+
// PTC start/result and repeated request usage can straddle the timeout.
|
|
359
|
+
const tracker = createConsolidationMeasurement('worker', { sessionId: forkId })
|
|
360
|
+
const prefix = rows.filter(event => Number.isSafeInteger(event?.seq) && event.seq <= (previous ?? -1))
|
|
361
|
+
const added = rows.filter(event => Number.isSafeInteger(event?.seq) && event.seq > (previous ?? -1))
|
|
362
|
+
if (added.length === 0) return { cursor, tail: null, unavailable: true }
|
|
363
|
+
for (const event of prefix) tracker.observe(event)
|
|
364
|
+
const before = { ...tracker.measurement.observed }
|
|
365
|
+
for (const event of added) tracker.observe(event)
|
|
366
|
+
tail = tracker.measurement
|
|
367
|
+
for (const key of ['outputTextChars', 'toolArgumentsChars', 'toolResultsChars', 'estimatedTokens']) {
|
|
368
|
+
if (tail.observed[key] !== null) tail.observed[key] -= before[key] ?? 0
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
return { cursor, tail }
|
|
372
|
+
} catch {
|
|
373
|
+
warn('consolidation worker event cursor unavailable; using the last measured cursor')
|
|
374
|
+
return { cursor: previous, tail: null, unavailable: true }
|
|
375
|
+
} finally {
|
|
376
|
+
try { lease?.[Symbol.dispose]?.() } catch {}
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
208
380
|
// —— 退役(§4.5 退役动作)———————————————————————————————————————
|
|
209
381
|
// 先 abort epoch 控制器(取消在跑回合)→ 等 idle(有上限)→ dispose 工具 restriction/handle
|
|
210
382
|
// → dispose agent → 删子绑定 → 清父绑定 workerEpoch → 活动日志记 epoch 结束。
|
|
@@ -260,18 +432,39 @@ export async function retireWorker(ctx, forkId, reason, { handoff, now = Date.no
|
|
|
260
432
|
// windows += 1;结算成功清超时计数;超时 +1(连续 2 次 → 退役,§4.4);idleAt 记
|
|
261
433
|
// whenIdle 完成时刻(条件 4 的 TTL 起算点)。binding 传父会话的(内部重读最新值再写,
|
|
262
434
|
// 避免覆盖并发的绑定补丁);子绑定里的 epoch 副本同步刷新。
|
|
263
|
-
export function recordEpochProgress(binding, { incrementChars = 0, workerOutputChars = 0, idleAt = null, settled = false, timeout = false, progress = true, now = Date.now() } = {}) {
|
|
435
|
+
export function recordEpochProgress(binding, { measurement = null, incrementChars = 0, workerOutputChars = 0, idleAt = null, settled = false, timeout = false, progress = true, countWindow = true, usageTotals = false, now = Date.now() } = {}) {
|
|
264
436
|
const sessionId = binding?.sessionId
|
|
265
437
|
if (!sessionId) return null
|
|
266
438
|
const current = (() => { try { return getSessionBinding(sessionId) || binding } catch { return binding } })()
|
|
267
439
|
const epoch = current?.workerEpoch
|
|
268
440
|
if (!epoch || typeof epoch !== 'object' || !epoch.forkSessionId) return null
|
|
269
441
|
const timeouts = Number(epoch.timeouts) || 0
|
|
442
|
+
const inputChars = measurement ? measurement.dispatched.inputChars : incrementChars
|
|
443
|
+
const outputChars = measurement
|
|
444
|
+
? ['outputTextChars', 'toolArgumentsChars', 'toolResultsChars'].reduce((sum, key) => sum + (measurement.observed[key] ?? 0), 0)
|
|
445
|
+
: workerOutputChars
|
|
446
|
+
const usage = { ...(epoch.usage || Object.fromEntries(USAGE_FIELDS.map(key => [key, null]))) }
|
|
447
|
+
if (progress && measurement) {
|
|
448
|
+
for (const key of USAGE_FIELDS) {
|
|
449
|
+
usage[key] = usageTotals ? measurement.usage[key]
|
|
450
|
+
: measurement.usage[key] === null || ((Number(epoch.windows) || 0) > 0 && usage[key] === null)
|
|
451
|
+
? null : (usage[key] ?? 0) + measurement.usage[key]
|
|
452
|
+
}
|
|
453
|
+
}
|
|
270
454
|
const next = {
|
|
271
455
|
...epoch,
|
|
272
456
|
chars: Math.max(0, Number(epoch.chars) || 0)
|
|
273
|
-
+ (progress ? Math.max(0, Number(
|
|
274
|
-
|
|
457
|
+
+ (progress ? Math.max(0, Number(inputChars) || 0) + Math.max(0, Number(outputChars) || 0) : 0),
|
|
458
|
+
// Legacy callers/unknown serialization must never certify a partially measured epoch.
|
|
459
|
+
measurementVersion: progress ? (measurement && measurement.serializationErrors === 0 ? 2 : null) : epoch.measurementVersion,
|
|
460
|
+
estimatedTokens: progress
|
|
461
|
+
? (!measurement || epoch.estimatedTokens === null || measurement.observed.estimatedTokens === null ? null
|
|
462
|
+
: (Number(epoch.estimatedTokens) || 0) + measurement.dispatched.estimatedTokens + measurement.observed.estimatedTokens)
|
|
463
|
+
: epoch.estimatedTokens ?? null,
|
|
464
|
+
usage,
|
|
465
|
+
lastEventSeq: measurement?.lastEventSeq ?? epoch.lastEventSeq ?? null,
|
|
466
|
+
lateOutputChars: (Number(epoch.lateOutputChars) || 0) + (progress && !countWindow ? outputChars : 0),
|
|
467
|
+
windows: (Number(epoch.windows) || 0) + (progress && countWindow ? 1 : 0),
|
|
275
468
|
timeouts: timeout ? timeouts + 1 : (settled ? 0 : timeouts),
|
|
276
469
|
lastIdleAt: idleAt ? new Date(Number(idleAt) || now).toISOString() : (epoch.lastIdleAt || null),
|
|
277
470
|
}
|
|
@@ -303,7 +496,7 @@ export function recordEpochProgress(binding, { incrementChars = 0, workerOutputC
|
|
|
303
496
|
*/
|
|
304
497
|
export async function acquireWorker(ctx, binding, {
|
|
305
498
|
incrementChars = 0, settings = null, probe = null,
|
|
306
|
-
agentOptions = null, header = null, now = Date.now(), idleWaitMs = WORKER_RETIRE_IDLE_WAIT_MS,
|
|
499
|
+
agentOptions = null, header = null, afterEpochIndex = 0, now = Date.now(), idleWaitMs = WORKER_RETIRE_IDLE_WAIT_MS,
|
|
307
500
|
} = {}) {
|
|
308
501
|
const sessionId = binding?.sessionId
|
|
309
502
|
if (!sessionId) return { ok: false, reasonCode: 'no-binding', error: 'acquireWorker requires a session binding' }
|
|
@@ -315,7 +508,7 @@ export async function acquireWorker(ctx, binding, {
|
|
|
315
508
|
const liveBinding = (() => { try { return getSessionBinding(sessionId) || binding } catch { return binding } })()
|
|
316
509
|
const retired = []
|
|
317
510
|
let epoch = liveBinding?.workerEpoch && typeof liveBinding.workerEpoch === 'object' ? liveBinding.workerEpoch : null
|
|
318
|
-
|
|
511
|
+
const prevIndex = Math.max(Number(epoch?.index) || 0, Number(afterEpochIndex) || 0)
|
|
319
512
|
let handoff = true // 初生包默认带交接上下文(§5.1:初生包与 handoff 包是同一个东西)
|
|
320
513
|
|
|
321
514
|
// —— Stage A:退役条件(只在这里查)———————————————————————————————
|
|
@@ -324,6 +517,7 @@ export async function acquireWorker(ctx, binding, {
|
|
|
324
517
|
const budget = epochBudget(liveBinding, settings)
|
|
325
518
|
let reason = null
|
|
326
519
|
if (!epoch.scopeGeneration || epoch.scopeGeneration !== generation) reason = 'scope-change'
|
|
520
|
+
else if (epoch.measurementVersion !== 2) reason = 'measurement-upgrade'
|
|
327
521
|
else if (epoch.lastIdleAt && now - (Date.parse(epoch.lastIdleAt) || 0) > WORKER_EPOCH_IDLE_TTL_MS) reason = 'idle-ttl'
|
|
328
522
|
else if (!budgetFit(epoch, incrementChars, settings)) reason = 'char-limit'
|
|
329
523
|
else if ((Number(epoch.windows) || 0) >= budget.maxWindows) reason = 'window-limit'
|
|
@@ -355,6 +549,17 @@ export async function acquireWorker(ctx, binding, {
|
|
|
355
549
|
try { handle = toHandle(await agents.resume({ resumeSessionId: epoch.forkSessionId, signal: resumeAbort.signal })) || null } catch { handle = null }
|
|
356
550
|
resumed = Boolean(handle)
|
|
357
551
|
}
|
|
552
|
+
// A persisted header cannot be repaired through create.meta on resume. Retire
|
|
553
|
+
// instead of changing the user's filesystem or keeping an unusable cwd.
|
|
554
|
+
const workerCwd = handle?.agent?.session?.header?.cwd
|
|
555
|
+
if (handle && typeof workerCwd === 'string' && resolveConsolidationCwd(workerCwd, null) !== workerCwd) {
|
|
556
|
+
try { resumeAbort?.abort() } catch {}
|
|
557
|
+
const result = await retireWorker(ctx, epoch.forkSessionId, 'cwd-invalid', { handoff: true, now, idleWaitMs })
|
|
558
|
+
retired.push({ forkId: epoch.forkSessionId, reason: 'cwd-invalid', handoff: true, ok: result?.ok === true })
|
|
559
|
+
handoff = true
|
|
560
|
+
epoch = null
|
|
561
|
+
handle = null
|
|
562
|
+
}
|
|
358
563
|
if (handle) {
|
|
359
564
|
let disposables = disposablesOf(epoch.forkSessionId)
|
|
360
565
|
if (resumed) {
|
|
@@ -369,18 +574,39 @@ export async function acquireWorker(ctx, binding, {
|
|
|
369
574
|
// 等不到就是卡死——退役冷启动(宁可早换新),绝不把新回合塞进一个还在忙的 worker。
|
|
370
575
|
const idle = await waitWorkerIdle(handle, idleWaitMs)
|
|
371
576
|
if (idle) {
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
577
|
+
const eventState = await workerEventCursor(ctx, epoch.forkSessionId, epoch.lastEventSeq, (Number(epoch.windows) || 0) > 0)
|
|
578
|
+
if ((eventState.unavailable && (Number(epoch.timeouts) || 0) > 0) || eventState.tail?.serializationErrors > 0) {
|
|
579
|
+
await retireWorker(ctx, epoch.forkSessionId, 'measurement-unavailable', { handoff: true, now, idleWaitMs })
|
|
580
|
+
return { ok: false, reasonCode: 'worker-measurement-unavailable', retired, error: 'the late worker output could not be measured; the range stays pending for a fresh worker' }
|
|
581
|
+
}
|
|
582
|
+
if (eventState.tail) {
|
|
583
|
+
const measured = recordEpochProgress({ sessionId }, { measurement: eventState.tail, countWindow: false, usageTotals: true, now })
|
|
584
|
+
if (!measured) return { ok: false, reasonCode: 'worker-epoch-unavailable', retired, error: 'the late worker output measurement could not be persisted' }
|
|
585
|
+
epoch = measured
|
|
586
|
+
}
|
|
587
|
+
const optionsChanged = agentOptions && handle.agent.options && ['provider', 'model', 'reasoningEffort', 'maxTokens']
|
|
588
|
+
.some(key => (agentOptions[key] ?? null) !== (handle.agent.options[key] ?? null))
|
|
589
|
+
if (!optionsChanged) {
|
|
590
|
+
return {
|
|
591
|
+
ok: true, forkId: epoch.forkSessionId, handle,
|
|
592
|
+
birth: false, reused: true, resumed, epoch,
|
|
593
|
+
eventCursor: eventState.cursor,
|
|
594
|
+
tools: disposables?.tools || null, restriction: disposables?.restriction || null,
|
|
595
|
+
epochAbort: disposables?.abort || null,
|
|
596
|
+
retired, handoff: false,
|
|
597
|
+
}
|
|
377
598
|
}
|
|
599
|
+
const result = await retireWorker(ctx, epoch.forkSessionId, 'model-options-change', { handoff: true, now, idleWaitMs })
|
|
600
|
+
retired.push({ forkId: epoch.forkSessionId, reason: 'model-options-change', handoff: true, ok: result?.ok === true })
|
|
601
|
+
handoff = true
|
|
602
|
+
epoch = null
|
|
603
|
+
} else {
|
|
604
|
+
const result = await retireWorker(ctx, epoch.forkSessionId, 'failure', { handoff: true, now, idleWaitMs })
|
|
605
|
+
retired.push({ forkId: epoch.forkSessionId, reason: 'failure', handoff: true, stuck: true, ok: result?.ok === true })
|
|
606
|
+
handoff = true
|
|
607
|
+
epoch = null
|
|
378
608
|
}
|
|
379
|
-
|
|
380
|
-
retired.push({ forkId: epoch.forkSessionId, reason: 'failure', handoff: true, stuck: true, ok: result?.ok === true })
|
|
381
|
-
handoff = true
|
|
382
|
-
epoch = null
|
|
383
|
-
} else {
|
|
609
|
+
} else if (epoch?.forkSessionId) {
|
|
384
610
|
// 死亡(重启后 resume 不可用/会话被删):冷启动 + 交接包(§8);worker 会话本身没有
|
|
385
611
|
// 可等的回合,retire 只做清理与记账。
|
|
386
612
|
const result = await retireWorker(ctx, epoch.forkSessionId, 'failure', { handoff: true, now, idleWaitMs })
|
|
@@ -402,8 +628,8 @@ export async function acquireWorker(ctx, binding, {
|
|
|
402
628
|
// 同 id 撞车(bench 实测 bug):窗口 2 派发崩溃 → retireWorker('failure') 清 epoch,
|
|
403
629
|
// 但 dispose 只关句柄不删会话文件 → 下一窗初生用同一 forkId 被宿主拒绝
|
|
404
630
|
// (worker-create-failed: already exists,bench 实测连挂 10 次)→ 增量永远整理不进库。
|
|
405
|
-
//
|
|
406
|
-
//
|
|
631
|
+
// 撞车处理:无法证明旧上下文尺寸的孤儿保守退役,index 顺延换新 id
|
|
632
|
+
// (≤6 次,逐个跳过已占用的持久 id),绝不把既有上下文记成零。
|
|
407
633
|
let handle = null
|
|
408
634
|
for (let createAttempt = 0; createAttempt < 6; createAttempt += 1) {
|
|
409
635
|
let collided = false
|
|
@@ -411,7 +637,7 @@ export async function acquireWorker(ctx, binding, {
|
|
|
411
637
|
handle = await agents.create({
|
|
412
638
|
sessionId: forkId,
|
|
413
639
|
meta: {
|
|
414
|
-
cwd: header?.cwd,
|
|
640
|
+
cwd: resolveConsolidationCwd(header?.cwd),
|
|
415
641
|
parentSession: sessionId,
|
|
416
642
|
// Without this the worker is treated as an ordinary user conversation by
|
|
417
643
|
// the injection path and the sidebar session lists(与 fork 同款隔离)。
|
|
@@ -432,15 +658,17 @@ export async function acquireWorker(ctx, binding, {
|
|
|
432
658
|
collided = true
|
|
433
659
|
}
|
|
434
660
|
if (!collided) break
|
|
435
|
-
//
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
break
|
|
440
|
-
}
|
|
661
|
+
// An orphan's existing context is not zero-sized. Retire it conservatively;
|
|
662
|
+
// never adopt it with freshly reset counters or reuse its persisted id.
|
|
663
|
+
const result = await retireWorker(ctx, forkId, 'orphan-unmeasured', { handoff: true, now, idleWaitMs })
|
|
664
|
+
retired.push({ forkId, reason: 'orphan-unmeasured', handoff: true, ok: result?.ok === true })
|
|
441
665
|
index += 1
|
|
442
666
|
forkId = 'memu-worker-' + shortHash(sessionId) + '-' + index
|
|
443
667
|
}
|
|
668
|
+
if (!handle?.agent && !handle?.followup) {
|
|
669
|
+
return { ok: false, reasonCode: 'worker-create-failed', forkId, retired, error: 'no worker handle after bounded create attempts' }
|
|
670
|
+
}
|
|
671
|
+
handle = toHandle(handle)
|
|
444
672
|
// 工具面只在初生挂一次(§15.2 改动点 2);标准 preset 的名单里已有 memu_* 时不重复挂。
|
|
445
673
|
const tools = probe?.hasWrite === true ? null : await attachWorkerTools(agents, forkId, sessionId)
|
|
446
674
|
const restriction = await restrictWorkerTools(agents, forkId, sessionId)
|
|
@@ -450,6 +678,11 @@ export async function acquireWorker(ctx, binding, {
|
|
|
450
678
|
index,
|
|
451
679
|
birthAt: new Date(Number(now) || Date.now()).toISOString(),
|
|
452
680
|
chars: 0,
|
|
681
|
+
schemaVersion: 2,
|
|
682
|
+
measurementVersion: 2,
|
|
683
|
+
estimatedTokens: 0,
|
|
684
|
+
usage: Object.fromEntries(USAGE_FIELDS.map(key => [key, null])),
|
|
685
|
+
lastEventSeq: null,
|
|
453
686
|
windows: 0,
|
|
454
687
|
timeouts: 0,
|
|
455
688
|
scopeGeneration: scopeGenerationOf(liveBinding),
|
|
@@ -736,6 +969,7 @@ export function buildHandoffPack({
|
|
|
736
969
|
export default {
|
|
737
970
|
WORKER_EPOCH_TIERS, WORKER_OUTPUT_FACTOR, WORKER_EPOCH_IDLE_TTL_MS, WORKER_HANDOFF_TAIL_CHARS,
|
|
738
971
|
WORKER_TIMEOUT_LIMIT, WORKER_RETIRE_IDLE_WAIT_MS, WORKER_INCREMENT_FALLBACK_CHARS,
|
|
739
|
-
epochBudget, budgetFit,
|
|
972
|
+
epochBudget, budgetFit, packetBudgetFit, measurePacket, createConsolidationMeasurement,
|
|
973
|
+
resolveConsolidationCwd, probeModelMaxContext, attachWorkerTools, restrictWorkerTools,
|
|
740
974
|
retireWorker, recordEpochProgress, acquireWorker, loadWorkerIncrement, buildIncrementPack, buildHandoffPack,
|
|
741
975
|
}
|
package/package.json
CHANGED
package/scripts/check-i18n.mjs
CHANGED
|
@@ -18,8 +18,24 @@ const dict = (name) => {
|
|
|
18
18
|
const body = src.slice(start, end)
|
|
19
19
|
return new Set([...body.matchAll(/^\s+([a-zA-Z][a-zA-Z0-9]*):/gm)].map((m) => m[1]))
|
|
20
20
|
}
|
|
21
|
+
// 同一语言表里重复定义同一个键:对象字面量后者静默覆盖前者,先定义的文案成了
|
|
22
|
+
// 死键——「整理提醒」行曾经因此渲染出整理按钮的通知长模板,把侧边栏撑出卡片
|
|
23
|
+
// 右缘(consolidateDone/deleteForever 双定义)。这里按硬门禁拦住整类事故。
|
|
24
|
+
const duplicateKeys = (name) => {
|
|
25
|
+
const start = src.indexOf(`const ${name} = {`)
|
|
26
|
+
const end = src.indexOf('\n }', start)
|
|
27
|
+
const body = src.slice(start, end)
|
|
28
|
+
const seen = new Map()
|
|
29
|
+
for (const m of body.matchAll(/^\s+([a-zA-Z][a-zA-Z0-9]*):/gm)) {
|
|
30
|
+
if (!seen.has(m[1])) seen.set(m[1], 0)
|
|
31
|
+
seen.set(m[1], seen.get(m[1]) + 1)
|
|
32
|
+
}
|
|
33
|
+
return [...seen.entries()].filter(([, n]) => n > 1).map(([k, n]) => `${k} ×${n}`)
|
|
34
|
+
}
|
|
21
35
|
const zh = dict('zh')
|
|
22
36
|
const en = dict('en')
|
|
37
|
+
const zhDupes = duplicateKeys('zh')
|
|
38
|
+
const enDupes = duplicateKeys('en')
|
|
23
39
|
|
|
24
40
|
const missing = (d, label) => [...used].filter((k) => !d.has(k)).map((k) => `${label}: ${k}`)
|
|
25
41
|
const unused = (d, label) => [...d].filter((k) => !used.has(k)).map((k) => `${label} unused: ${k}`)
|
|
@@ -61,4 +77,7 @@ if (standaloneOk) console.log('standalone zh/en + page keys complete')
|
|
|
61
77
|
|
|
62
78
|
const i18nOk = !missing(zh, 'zh').length && !missing(en, 'en').length
|
|
63
79
|
&& ![...zh].some((key) => !en.has(key)) && ![...en].some((key) => !zh.has(key))
|
|
80
|
+
&& !zhDupes.length && !enDupes.length
|
|
81
|
+
if (zhDupes.length) console.log('DUPLICATE-ZH:', zhDupes.join(', '))
|
|
82
|
+
if (enDupes.length) console.log('DUPLICATE-EN:', enDupes.join(', '))
|
|
64
83
|
if (!i18nOk || !standaloneOk) process.exitCode = 1
|
package/scripts/recall-bench.mjs
CHANGED
|
@@ -428,10 +428,10 @@ function entryForSample(source, sample) {
|
|
|
428
428
|
}
|
|
429
429
|
}
|
|
430
430
|
|
|
431
|
-
function seedSample(state, sample, entries,
|
|
431
|
+
function seedSample(state, sample, entries, suffix = '') {
|
|
432
432
|
const library = state.createLibrary({
|
|
433
433
|
name: `bench-${sample.id}${suffix}`,
|
|
434
|
-
scopeKey: path.join(
|
|
434
|
+
scopeKey: path.join(os.tmpdir(), 'dsh-memu-recall-bench-identities', `${sample.id}${suffix}`),
|
|
435
435
|
})
|
|
436
436
|
const index = { version: 1, entries: {} }
|
|
437
437
|
for (const id of sample.library) {
|
|
@@ -570,7 +570,7 @@ export async function runBenchmark(options = {}) {
|
|
|
570
570
|
for (const sample of samples) {
|
|
571
571
|
const sampleNow = Date.parse(sample.time)
|
|
572
572
|
clock.set(sampleNow)
|
|
573
|
-
const automatic = seedSample(state, sample, dataset.entries,
|
|
573
|
+
const automatic = seedSample(state, sample, dataset.entries, '')
|
|
574
574
|
const autoExec = execFor(automatic.sessionId, root)
|
|
575
575
|
const settings = {
|
|
576
576
|
...state.getSettings(),
|
|
@@ -602,7 +602,7 @@ export async function runBenchmark(options = {}) {
|
|
|
602
602
|
|
|
603
603
|
let explicitIds = []
|
|
604
604
|
if (Array.isArray(sample.explicitExpectedIds) && sample.explicitExpectedIds.length > 0) {
|
|
605
|
-
const explicit = seedSample(state, sample, dataset.entries,
|
|
605
|
+
const explicit = seedSample(state, sample, dataset.entries, '-explicit')
|
|
606
606
|
const explicitExec = execFor(explicit.sessionId, root)
|
|
607
607
|
const explicitResult = await memory.privateRecall({
|
|
608
608
|
exec: explicitExec,
|
|
@@ -238,6 +238,9 @@ for (let turn = 1; turn <= parsed.turns; turn += 1) {
|
|
|
238
238
|
titleCardBodyLineMax = Math.max(titleCardBodyLineMax, Number(analysis.context?.bodyLines || 0))
|
|
239
239
|
}
|
|
240
240
|
history = messages
|
|
241
|
+
for (const message of messages.filter(item => !known.has(item) && item.role === 'user')) {
|
|
242
|
+
await handlers.get('session/event')?.(agent.session, { type: 'user/message', data: message })
|
|
243
|
+
}
|
|
241
244
|
const payload = [
|
|
242
245
|
{ role: 'system', content: SYSTEM_PROMPT },
|
|
243
246
|
...messages.map((message) => ({ role: message.role === 'assistant' ? 'assistant' : 'user', content: textOf(message) })),
|
|
@@ -57,6 +57,17 @@ test('a turn recall records the ids it injected and the route it took', async ()
|
|
|
57
57
|
assert.ok(result.ids.includes(written.id), 'the seeded memory is what got recalled')
|
|
58
58
|
assert.equal(rows[0].detail.route, undefined, 'the route is reported per layer')
|
|
59
59
|
assert.ok(['local', 'managed-vector-rrf'].includes(rows[0].detail.privateRoute))
|
|
60
|
+
assert.equal(rows[0].detail.schemaVersion, 2)
|
|
61
|
+
assert.equal(rows[0].detail.stage, 'rendered')
|
|
62
|
+
assert.equal(rows[0].detail.outcome, 'packed')
|
|
63
|
+
assert.equal(rows[0].detail.counts.renderedRows, result.ids.length)
|
|
64
|
+
assert.equal(rows[0].detail.counts.injectedRows, null, 'packing is not proof the host accepted the message')
|
|
65
|
+
assert.equal(rows[0].detail.counts.injectedGroups, null)
|
|
66
|
+
assert.ok(rows[0].detail.tokens.estimated > 0)
|
|
67
|
+
assert.equal(rows[0].detail.tokens.measured, null)
|
|
68
|
+
assert.ok(rows[0].detail.timing.retrievalMs >= 0)
|
|
69
|
+
assert.ok(rows[0].detail.timing.selectionMs >= 0)
|
|
70
|
+
assert.ok(rows[0].detail.timing.renderMs >= 0)
|
|
60
71
|
})
|
|
61
72
|
|
|
62
73
|
test('a recall with a degraded semantic leg is logged as not-ok', async () => {
|
|
@@ -70,6 +81,47 @@ test('a recall with a degraded semantic leg is logged as not-ok', async () => {
|
|
|
70
81
|
assert.ok(result.errors.length > 0, 'the caller still sees the error')
|
|
71
82
|
})
|
|
72
83
|
|
|
84
|
+
test('recall diagnostics distinguish no match, recently seen, and omitted by budget', async () => {
|
|
85
|
+
const { exec } = bind('wiring-outcomes')
|
|
86
|
+
state.setSessionBinding('wiring-outcomes', { useGlobal: false })
|
|
87
|
+
let binding = state.getSessionBinding('wiring-outcomes')
|
|
88
|
+
await inject.buildRecall(binding, 'independent-rare-token', 1, state.getSettings(), exec, 'wiring-outcomes')
|
|
89
|
+
let row = activity.listEvents({ kind: 'recall' })[0]
|
|
90
|
+
assert.equal(row.detail.outcome, 'no-match')
|
|
91
|
+
assert.equal(row.detail.counts.renderedRows, 0)
|
|
92
|
+
const written = await memory.privateRemember({ exec, title: 'independent-rare-token', content: 'independent-rare-token is a relevant fact' })
|
|
93
|
+
const firstRecall = await memory.privateRecall({ exec, query: 'independent-rare-token', purpose: 'automatic' })
|
|
94
|
+
state.markInjectedRefs('wiring-outcomes', firstRecall.refs, 1, { messageId: 'wiring-admitted-memory', hostTurn: 1 })
|
|
95
|
+
binding = state.getSessionBinding('wiring-outcomes')
|
|
96
|
+
await inject.buildRecall(binding, 'independent-rare-token', 2, state.getSettings(), exec, 'wiring-outcomes')
|
|
97
|
+
row = activity.listEvents({ kind: 'recall' })[0]
|
|
98
|
+
assert.equal(row.detail.outcome, 'deduped')
|
|
99
|
+
assert.equal(row.detail.counts.recentRows, 1)
|
|
100
|
+
assert.equal(row.detail.counts.renderedRows, 0)
|
|
101
|
+
state.releaseInjected('wiring-outcomes')
|
|
102
|
+
binding = state.getSessionBinding('wiring-outcomes')
|
|
103
|
+
await inject.buildRecall(binding, 'independent-rare-token', 3, { ...state.getSettings(), turnTokens: 0 }, exec, 'wiring-outcomes')
|
|
104
|
+
row = activity.listEvents({ kind: 'recall' })[0]
|
|
105
|
+
assert.equal(row.detail.outcome, 'budget')
|
|
106
|
+
assert.equal(row.detail.counts.budgetOmittedRows, 1)
|
|
107
|
+
assert.equal(row.detail.counts.renderedRows, 0)
|
|
108
|
+
assert.equal(row.detail.tokens.estimated, 0)
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
test('global semantic degradation reaches the combined recall diagnostics', async () => {
|
|
112
|
+
const { exec } = bind('wiring-global-error')
|
|
113
|
+
state.setSessionBinding('wiring-global-error', { useLibrary: false, useGlobal: true })
|
|
114
|
+
state.updateSettings({ memoryBackend: 'api', vectorSource: 'local' })
|
|
115
|
+
const binding = state.getSessionBinding('wiring-global-error')
|
|
116
|
+
const result = await inject.buildRecall(binding, 'anything', 1, state.getSettings(), exec, 'wiring-global-error')
|
|
117
|
+
const row = activity.listEvents({ kind: 'recall' })[0]
|
|
118
|
+
assert.ok(result.errors.length > 0)
|
|
119
|
+
assert.ok(row.detail.errors.some(error => error.includes('semantic recall failed')))
|
|
120
|
+
assert.equal(row.ok, false)
|
|
121
|
+
assert.equal(row.detail.privateRoute, null)
|
|
122
|
+
assert.equal(row.detail.globalRoute, 'local-fallback')
|
|
123
|
+
})
|
|
124
|
+
|
|
73
125
|
test('a consolidation that cannot start is logged with its reason', async () => {
|
|
74
126
|
bind('wiring-consolidate')
|
|
75
127
|
const result = await requestPrivateConsolidation({ get: () => undefined }, 'wiring-consolidate')
|