dsh-context-manager 1.6.0 → 1.7.1
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/CHANGELOG.md +24 -0
- package/README.md +151 -10
- package/client.js +231 -10
- package/core.js +273 -13
- package/docs/DETAIL.md +17 -0
- package/docs/DETAIL.zh.md +17 -0
- package/index.js +523 -43
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -30,13 +30,18 @@ import { randomUUID } from 'node:crypto'
|
|
|
30
30
|
import { join } from 'node:path'
|
|
31
31
|
import { pathToFileURL } from 'node:url'
|
|
32
32
|
import {
|
|
33
|
+
addTurnTokens,
|
|
34
|
+
buildRecall,
|
|
33
35
|
deletedFromSurface,
|
|
36
|
+
formatBatches,
|
|
37
|
+
matchUndoBatches,
|
|
34
38
|
foldSurface,
|
|
35
39
|
formatList,
|
|
36
40
|
formatTurns,
|
|
37
41
|
hasToolChange,
|
|
38
42
|
isTombstoneKind,
|
|
39
43
|
itemsFromSurface,
|
|
44
|
+
planClean,
|
|
40
45
|
planDeletion,
|
|
41
46
|
tombstoneData,
|
|
42
47
|
turnsFromSurface,
|
|
@@ -72,6 +77,8 @@ export const inject = ['sessions', 'agents', 'commands', 'tools']
|
|
|
72
77
|
const RESTORED_PREFIX = 'restored-assistant-'
|
|
73
78
|
const PENDING_TYPE = 'plugin:context-manager/pending'
|
|
74
79
|
const ACK_TYPE = 'plugin:context-manager/ack'
|
|
80
|
+
/** Audit ledger: one record per user-visible batch operation. */
|
|
81
|
+
const BATCH_TYPE = 'plugin:context-manager/batch'
|
|
75
82
|
/** Queue record types older releases wrote; still applied after an upgrade. */
|
|
76
83
|
const LEGACY_PENDING_TYPES = ['plugin:message-manager/pending']
|
|
77
84
|
const LEGACY_ACK_TYPES = ['plugin:message-manager/ack']
|
|
@@ -106,6 +113,25 @@ function surfaceEventsSync(session) {
|
|
|
106
113
|
.filter((event) => event !== undefined)
|
|
107
114
|
}
|
|
108
115
|
|
|
116
|
+
/** Build an optional seq→tokens map from the token-meter service (when available). */
|
|
117
|
+
function buildTokensBySeq(ctx, session) {
|
|
118
|
+
try {
|
|
119
|
+
const meter = ctx.tokenMeter
|
|
120
|
+
if (meter === undefined || meter === null || typeof meter.measure !== 'function') return undefined
|
|
121
|
+
const measurement = meter.measure(session)
|
|
122
|
+
if (measurement === undefined || measurement === null || !Array.isArray(measurement.nodes)) return undefined
|
|
123
|
+
const map = new Map()
|
|
124
|
+
for (const node of measurement.nodes) {
|
|
125
|
+
if (node !== null && typeof node === 'object' && Number.isSafeInteger(node.seq)) {
|
|
126
|
+
map.set(node.seq, node.tokens)
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return map
|
|
130
|
+
} catch (_error) {
|
|
131
|
+
return undefined
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
109
135
|
/**
|
|
110
136
|
* Read the turn/step that is open at the very end of the live log.
|
|
111
137
|
* Scans backward: the last boundary marker decides the state, so an open step
|
|
@@ -158,13 +184,14 @@ function openStepOf(session) {
|
|
|
158
184
|
}
|
|
159
185
|
|
|
160
186
|
/** Append tombstone replacements for one plan inside an open turn/step. */
|
|
161
|
-
function appendTombstones(session, runs, turn, step) {
|
|
187
|
+
function appendTombstones(session, runs, turn, step, batchId = undefined) {
|
|
162
188
|
const tombstoneSeqs = []
|
|
163
189
|
try {
|
|
164
190
|
for (const run of runs) {
|
|
165
191
|
const event = session.append(
|
|
166
192
|
'developer/message',
|
|
167
|
-
tombstoneData(turn, step, randomUUID()
|
|
193
|
+
tombstoneData(turn, step, randomUUID(), batchId,
|
|
194
|
+
buildRecall(run.seqs.map((seq) => session.eventAt(seq)).filter((event) => event !== undefined))),
|
|
168
195
|
{
|
|
169
196
|
surfaceOp: { op: 'replace', startSeq: run.startSeq, endSeq: run.endSeq },
|
|
170
197
|
sourceEventSeqs: run.seqs,
|
|
@@ -220,8 +247,11 @@ function durableQueue(ctx, session) {
|
|
|
220
247
|
cache = new Map()
|
|
221
248
|
queueCaches.set(ctx, cache)
|
|
222
249
|
}
|
|
223
|
-
|
|
224
|
-
|
|
250
|
+
// `snapshotEvents(n)` consumes n already-read EVENTS, not seq N: keep a consumed
|
|
251
|
+
// count (the same projection the agent loop uses) so the window can never land
|
|
252
|
+
// past the end of the log and silently skip records.
|
|
253
|
+
const state = cache.get(session.id) ?? { checkedCount: 0, pending: new Map() }
|
|
254
|
+
const events = session.snapshotEvents(state.checkedCount)
|
|
225
255
|
for (const event of events) {
|
|
226
256
|
const record = pluginRecordOf(event)
|
|
227
257
|
if (record === undefined) continue
|
|
@@ -231,19 +261,29 @@ function durableQueue(ctx, session) {
|
|
|
231
261
|
} else if (record.type === PENDING_TYPE || LEGACY_PENDING_TYPES.includes(record.type)) {
|
|
232
262
|
const op = record.data?.op
|
|
233
263
|
const targetSeq = record.data?.targetSeq
|
|
264
|
+
const batchId = record.data?.batchId
|
|
234
265
|
if ((op === 'delete' || op === 'restore' || op === 'delete-turn') && Number.isSafeInteger(targetSeq)) {
|
|
235
|
-
state.pending.set(record.seq, {
|
|
266
|
+
state.pending.set(record.seq, {
|
|
267
|
+
recordSeq: record.seq,
|
|
268
|
+
op,
|
|
269
|
+
targetSeq,
|
|
270
|
+
batchId: typeof batchId === 'string' ? batchId : undefined,
|
|
271
|
+
})
|
|
236
272
|
}
|
|
237
273
|
}
|
|
238
274
|
}
|
|
239
|
-
if (events.length > 0) state.
|
|
275
|
+
if (events.length > 0) state.checkedCount += events.length
|
|
240
276
|
cache.set(session.id, state)
|
|
241
277
|
return [...state.pending.values()]
|
|
242
278
|
}
|
|
243
279
|
|
|
244
280
|
/** Durably enqueue one operation; plugin records need no open turn/step. */
|
|
245
|
-
function appendPending(session, op, targetSeq) {
|
|
246
|
-
return appendPluginRecord(session, PENDING_TYPE, {
|
|
281
|
+
function appendPending(session, op, targetSeq, batchId = undefined) {
|
|
282
|
+
return appendPluginRecord(session, PENDING_TYPE, {
|
|
283
|
+
op,
|
|
284
|
+
targetSeq,
|
|
285
|
+
...typeof batchId === 'string' && batchId.length > 0 ? { batchId } : {},
|
|
286
|
+
})
|
|
247
287
|
}
|
|
248
288
|
|
|
249
289
|
/** Acknowledge one pending record so restarts and replays leave it alone. */
|
|
@@ -255,6 +295,207 @@ function appendAck(session, pendingSeq, result, detail) {
|
|
|
255
295
|
})
|
|
256
296
|
}
|
|
257
297
|
|
|
298
|
+
/** Append one audit ledger record; plugin records need no open turn/step. */
|
|
299
|
+
function appendBatchLedger(session, entry) {
|
|
300
|
+
return appendPluginRecord(session, BATCH_TYPE, {
|
|
301
|
+
batchId: entry.batchId,
|
|
302
|
+
op: entry.op,
|
|
303
|
+
seqs: Array.isArray(entry.seqs) ? entry.seqs.slice(0, 200) : [],
|
|
304
|
+
tombstoneSeqs: Array.isArray(entry.tombstoneSeqs) ? entry.tombstoneSeqs.slice(0, 200) : [],
|
|
305
|
+
...Number.isSafeInteger(entry.count) && entry.count > 0 ? { count: entry.count } : {},
|
|
306
|
+
estimatedFreedTokens: Number.isSafeInteger(entry.estimatedFreedTokens) ? entry.estimatedFreedTokens : 0,
|
|
307
|
+
result: entry.result,
|
|
308
|
+
...typeof entry.reason === 'string' && entry.reason.length > 0 ? { reason: entry.reason.slice(0, 300) } : {},
|
|
309
|
+
})
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
/**
|
|
313
|
+
* Batch ledger entries in log order.
|
|
314
|
+
*
|
|
315
|
+
* The ledger is a plugin record inside the append-only session log, so the
|
|
316
|
+
* audit trail travels with the session, survives restarts, and never rewrites
|
|
317
|
+
* a past record. Each record carries the batch id, the target seqs, the
|
|
318
|
+
* tombstones it wrote, the estimated relief, and the outcome.
|
|
319
|
+
*
|
|
320
|
+
* The whole log is rescanned on every call: `snapshotEvents(n)` takes a log
|
|
321
|
+
* OFFSET, not a seq, so an incremental "scan from seq N" cursor silently
|
|
322
|
+
* reads an empty window when N and the remaining count disagree. The ledger
|
|
323
|
+
* is only read by a user-invoked command, and one pass over the in-memory log
|
|
324
|
+
* is cheap, so correctness wins over a cursor here.
|
|
325
|
+
*/
|
|
326
|
+
function batchesFromLog(ctx, session) {
|
|
327
|
+
const entries = []
|
|
328
|
+
const events = session.snapshotEvents()
|
|
329
|
+
for (const event of events) {
|
|
330
|
+
const record = pluginRecordOf(event)
|
|
331
|
+
if (record === undefined || record.type !== BATCH_TYPE) continue
|
|
332
|
+
const data = record.data ?? {}
|
|
333
|
+
if (typeof data.batchId !== 'string') continue
|
|
334
|
+
entries.push({
|
|
335
|
+
recordSeq: record.seq,
|
|
336
|
+
time: event.time,
|
|
337
|
+
batchId: data.batchId,
|
|
338
|
+
op: typeof data.op === 'string' ? data.op : 'delete',
|
|
339
|
+
seqs: Array.isArray(data.seqs) ? data.seqs : [],
|
|
340
|
+
tombstoneSeqs: Array.isArray(data.tombstoneSeqs) ? data.tombstoneSeqs : [],
|
|
341
|
+
count: Number.isSafeInteger(data.count) ? data.count : undefined,
|
|
342
|
+
estimatedFreedTokens: Number.isSafeInteger(data.estimatedFreedTokens) ? data.estimatedFreedTokens : 0,
|
|
343
|
+
result: typeof data.result === 'string' ? data.result : 'applied',
|
|
344
|
+
reason: typeof data.reason === 'string' ? data.reason : undefined,
|
|
345
|
+
})
|
|
346
|
+
}
|
|
347
|
+
return entries
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
/** List the audit ledger for one live session. */
|
|
351
|
+
async function listBatches(ctx, agent) {
|
|
352
|
+
const session = liveSession(ctx, agent)
|
|
353
|
+
const batches = batchesFromLog(ctx, session)
|
|
354
|
+
return { text: formatBatches(batches), batches }
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Compact exactly one user-selected surface span into a summary node.
|
|
359
|
+
*
|
|
360
|
+
* This is the only place this plugin borrows the official compaction engine,
|
|
361
|
+
* and it stays deliberately narrow: the span is whatever the user named by
|
|
362
|
+
* surface position, never a global pressure threshold (that is the compaction
|
|
363
|
+
* backend's own policy). Both edges must already be tool-pairing balanced; the
|
|
364
|
+
* engine rejects an unbalanced range, and we surface that reason verbatim.
|
|
365
|
+
*/
|
|
366
|
+
async function compactSelection(ctx, agent, start, end) {
|
|
367
|
+
const session = liveSession(ctx, agent)
|
|
368
|
+
const controller = new AbortController()
|
|
369
|
+
try {
|
|
370
|
+
// Resolve the optional service through ctx.get: compaction is not a hard
|
|
371
|
+
// dependency of this plugin, and reading ctx.compaction would make Cordis
|
|
372
|
+
// throw "cannot get property" for users who never loaded a backend.
|
|
373
|
+
const engine = ctx.get('compaction')
|
|
374
|
+
if (engine === undefined || engine === null || typeof engine.compactRegion !== 'function') {
|
|
375
|
+
throw new Error('当前环境没有加载 compaction 服务(ctx.compaction);请先启用 dsh-compaction-basic 之类的压缩后端。')
|
|
376
|
+
}
|
|
377
|
+
const nodes = session.surface.nodes
|
|
378
|
+
if (!nodes.includes(start)) throw new Error(`起始序号 #${start} 不在当前表面上(/ctxmgr list 查看)。`)
|
|
379
|
+
if (!nodes.includes(end)) throw new Error(`结束序号 #${end} 不在当前表面上(/ctxmgr list 查看)。`)
|
|
380
|
+
if (nodes.indexOf(start) > nodes.indexOf(end)) {
|
|
381
|
+
throw new Error('起始序号必须位于结束序号之前(按表面位置,不是数值大小)。')
|
|
382
|
+
}
|
|
383
|
+
const options = agent !== null && typeof agent === 'object'
|
|
384
|
+
&& agent.options !== null && typeof agent.options === 'object'
|
|
385
|
+
? agent.options
|
|
386
|
+
: {}
|
|
387
|
+
const agentCtx = { session, options }
|
|
388
|
+
const result = await engine.compactRegion(start, end, agentCtx, controller.signal)
|
|
389
|
+
const shadowedSeqs = Array.isArray(result?.shadowedSeqs) ? result.shadowedSeqs : []
|
|
390
|
+
const tokens = Number.isSafeInteger(result?.shadowedTokenCount) ? result.shadowedTokenCount : 0
|
|
391
|
+
// Node count and token count use different scopes: our tombstones are real
|
|
392
|
+
// surface nodes (so they are counted) but derive no message (so they cost 0).
|
|
393
|
+
// Reporting only the live message count keeps the number meaningful.
|
|
394
|
+
let liveCount = 0
|
|
395
|
+
let tombstoneCount = 0
|
|
396
|
+
for (const seq of shadowedSeqs) {
|
|
397
|
+
if (isTombstone(session.eventAt(seq))) tombstoneCount += 1
|
|
398
|
+
else liveCount += 1
|
|
399
|
+
}
|
|
400
|
+
appendBatchLedger(session, {
|
|
401
|
+
batchId: randomUUID(),
|
|
402
|
+
op: 'compact',
|
|
403
|
+
seqs: [start, end],
|
|
404
|
+
tombstoneSeqs: [],
|
|
405
|
+
count: liveCount,
|
|
406
|
+
estimatedFreedTokens: 0,
|
|
407
|
+
result: 'applied',
|
|
408
|
+
reason: `shadowed ${liveCount} messages + ${tombstoneCount} tombstones / ${tokens} tokens`,
|
|
409
|
+
})
|
|
410
|
+
const tombNote = tombstoneCount > 0 ? `(另有 ${tombstoneCount} 个墓碑节点一并折叠,它们本就不占上下文)` : ''
|
|
411
|
+
return {
|
|
412
|
+
text: `已把表面区间 #${start}…#${end}(${liveCount} 条消息,估算 ${tokens.toLocaleString('en-US')} tokens${tombNote})压缩成一条摘要消息。原始会话日志与聊天记录仍保留;这只作用于你选中的区间,不做全局阈值压缩。`,
|
|
413
|
+
count: liveCount,
|
|
414
|
+
tokens,
|
|
415
|
+
}
|
|
416
|
+
} catch (error) {
|
|
417
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
418
|
+
// The backend prices the shrink check against model-visible content only, so
|
|
419
|
+
// a span whose live content is mostly already deleted cannot be summarized.
|
|
420
|
+
// Say that plainly, and keep the ledger in the same language as the reply.
|
|
421
|
+
const shrink = /summary is not smaller than the shadowed content \((\d+) estimated framed tokens >= (\d+)\)/.exec(message)
|
|
422
|
+
const explanation = shrink !== null
|
|
423
|
+
? `选区内模型可见内容只剩约 ${shrink[2]} tokens(墓碑不算内容),而摘要本身就约 ${shrink[1]} tokens,官方压缩会拒绝「摘要不比原文小」的情况。`
|
|
424
|
+
: message
|
|
425
|
+
appendBatchLedger(session, {
|
|
426
|
+
batchId: randomUUID(),
|
|
427
|
+
op: 'compact',
|
|
428
|
+
seqs: [start, end],
|
|
429
|
+
tombstoneSeqs: [],
|
|
430
|
+
estimatedFreedTokens: 0,
|
|
431
|
+
result: 'failed',
|
|
432
|
+
reason: explanation,
|
|
433
|
+
})
|
|
434
|
+
if (shrink !== null) {
|
|
435
|
+
throw new Error(`局部压缩失败:${explanation}建议改用 /ctxmgr delete 或 /ctxmgr clean 直接移出这段,而不是压缩它。`)
|
|
436
|
+
}
|
|
437
|
+
throw new Error(`局部压缩失败:${message}`)
|
|
438
|
+
}
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* Undo one batch by restoring the tombstones it wrote.
|
|
443
|
+
*
|
|
444
|
+
* Undo never invents a new restore mechanism: it reuses the queued restore
|
|
445
|
+
* path, so the raw log stays append-only and the restore keeps its usual
|
|
446
|
+
* semantics (user/context at position, assistant content at the tail).
|
|
447
|
+
*/
|
|
448
|
+
async function undoBatch(ctx, agent, batchId) {
|
|
449
|
+
const session = liveSession(ctx, agent)
|
|
450
|
+
const batches = batchesFromLog(ctx, session)
|
|
451
|
+
const matches = matchUndoBatches(batches, batchId)
|
|
452
|
+
const isNamed = typeof batchId === 'string' && batchId.length > 0
|
|
453
|
+
if (isNamed && matches.length > 1 && !matches.some((entry) => entry.batchId === batchId)) {
|
|
454
|
+
throw new Error(`批次前缀有歧义(匹配 ${matches.length} 条),请给更长的前缀或完整 batchId(/ctxmgr batches 查看台账)。`)
|
|
455
|
+
}
|
|
456
|
+
// A batch counts as already undone when an undo ledger entry names it, or when
|
|
457
|
+
// none of its tombstones is on the surface any more. The ledger signal matters:
|
|
458
|
+
// a queued restore only lands on the next request, so back-to-back tool calls
|
|
459
|
+
// can still see the tombstone while the undo is already recorded.
|
|
460
|
+
const undoneIds = new Set(batches
|
|
461
|
+
.filter((entry) => entry.op === 'undo' && typeof entry.reason === 'string')
|
|
462
|
+
.map((entry) => entry.reason))
|
|
463
|
+
const stillOnSurface = matches.filter((entry) => !undoneIds.has(entry.batchId)
|
|
464
|
+
&& entry.tombstoneSeqs.some((seq) => session.surface.nodes.includes(seq)))
|
|
465
|
+
const target = stillOnSurface.length === 0
|
|
466
|
+
? undefined
|
|
467
|
+
: isNamed
|
|
468
|
+
? stillOnSurface.find((entry) => entry.batchId === batchId)
|
|
469
|
+
?? stillOnSurface.find((entry) => entry.batchId.startsWith(batchId))
|
|
470
|
+
: stillOnSurface[stillOnSurface.length - 1]
|
|
471
|
+
if (target === undefined) {
|
|
472
|
+
throw new Error(typeof batchId === 'string' && batchId.length > 0
|
|
473
|
+
? '找不到该批次记录(/ctxmgr batches 查看台账)。'
|
|
474
|
+
: '还没有可撤销的批次记录(台账为空、这些批次都已撤销,或只有恢复类操作)。')
|
|
475
|
+
}
|
|
476
|
+
const restoreSeqs = target.tombstoneSeqs.filter((seq) => session.surface.nodes.includes(seq))
|
|
477
|
+
if (restoreSeqs.length === 0) throw new Error('该批次已没有仍在表面的删除记录(可能已恢复过)。')
|
|
478
|
+
const undoBatchId = randomUUID()
|
|
479
|
+
const result = await restoreMessages(ctx, agent, restoreSeqs, { batchId: undoBatchId })
|
|
480
|
+
appendBatchLedger(session, {
|
|
481
|
+
batchId: undoBatchId,
|
|
482
|
+
op: 'undo',
|
|
483
|
+
seqs: restoreSeqs,
|
|
484
|
+
tombstoneSeqs: [],
|
|
485
|
+
count: restoreSeqs.length,
|
|
486
|
+
estimatedFreedTokens: 0,
|
|
487
|
+
result: 'queued',
|
|
488
|
+
reason: target.batchId,
|
|
489
|
+
})
|
|
490
|
+
const short = target.batchId.slice(0, 8)
|
|
491
|
+
return {
|
|
492
|
+
text: `撤销批次 ${short}(${target.op}):${result.text}`,
|
|
493
|
+
note: '用户与上下文消息回到原位;助手内容与工具结果会追加到末尾(序号会变)。',
|
|
494
|
+
batchId: target.batchId,
|
|
495
|
+
count: restoreSeqs.length,
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
258
499
|
/**
|
|
259
500
|
* Classify one tombstone into a restore plan without mutating the Session.
|
|
260
501
|
* @throws when the tombstone or its original group cannot be restored safely.
|
|
@@ -405,7 +646,8 @@ function restoreOne(session, tombstoneSeq, turn, step) {
|
|
|
405
646
|
async function listMessages(ctx, agent) {
|
|
406
647
|
const session = liveSession(ctx, agent)
|
|
407
648
|
const events = await readSurfaceEvents(ctx, session)
|
|
408
|
-
const
|
|
649
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
650
|
+
const items = itemsFromSurface(events, tokensBySeq)
|
|
409
651
|
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
410
652
|
const deleted = deletedFromSurface(events, bySeq)
|
|
411
653
|
const pending = durableQueue(ctx, session)
|
|
@@ -413,18 +655,26 @@ async function listMessages(ctx, agent) {
|
|
|
413
655
|
}
|
|
414
656
|
|
|
415
657
|
/** Delete one or more messages now when safe, otherwise queue them durably. */
|
|
416
|
-
async function deleteMessages(ctx, agent, seqs) {
|
|
658
|
+
async function deleteMessages(ctx, agent, seqs, options = {}) {
|
|
417
659
|
const unique = [...new Set(seqs)]
|
|
418
660
|
if (unique.length === 0 || unique.some((seq) => !Number.isSafeInteger(seq) || seq < 0)) {
|
|
419
661
|
throw new Error('序号必须是非负整数。')
|
|
420
662
|
}
|
|
663
|
+
const batchId = typeof options.batchId === 'string' && options.batchId.length > 0
|
|
664
|
+
? options.batchId
|
|
665
|
+
: randomUUID()
|
|
666
|
+
const opName = typeof options.op === 'string' && options.op.length > 0 ? options.op : 'delete'
|
|
421
667
|
const session = liveSession(ctx, agent)
|
|
422
668
|
const events = await readSurfaceEvents(ctx, session)
|
|
669
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
423
670
|
const targets = []
|
|
424
671
|
for (const seq of unique) {
|
|
425
672
|
const plan = planDeletion(events, seq)
|
|
426
673
|
if (!plan.ok) {
|
|
427
674
|
if (plan.reason === 'system') throw new Error('系统提示词不是可删除的对话消息。')
|
|
675
|
+
if (plan.reason === 'tombstone') {
|
|
676
|
+
throw new Error('该序号是一条删除记录(墓碑),不是消息;要回到上下文请用 /ctxmgr restore。')
|
|
677
|
+
}
|
|
428
678
|
if (plan.reason === 'not-found') {
|
|
429
679
|
if (unique.length === 1) throw new Error('该消息已不在当前模型上下文中,可能已被删除;请刷新后重试。')
|
|
430
680
|
continue
|
|
@@ -435,23 +685,45 @@ async function deleteMessages(ctx, agent, seqs) {
|
|
|
435
685
|
}
|
|
436
686
|
if (targets.length === 0) throw new Error('选中的消息都已不在当前模型上下文中。')
|
|
437
687
|
|
|
688
|
+
// Items are always priced (meter when available, else the local heuristic),
|
|
689
|
+
// so the reported relief never collapses to 0 when the meter is absent.
|
|
690
|
+
const tokensOfSeq = new Map(itemsFromSurface(events, tokensBySeq).map((item) => [item.seq, item.tokens ?? 0]))
|
|
691
|
+
let estimatedFreedTokens = 0
|
|
692
|
+
for (const target of targets) {
|
|
693
|
+
for (const run of target.plan.runs) {
|
|
694
|
+
for (const seq of run.seqs) estimatedFreedTokens += tokensOfSeq.get(seq) ?? 0
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
438
698
|
const open = openStepOf(session)
|
|
439
699
|
const touchesOpenStep = open !== undefined
|
|
440
700
|
&& targets.some((target) => target.plan.indices.some((index) => events[index].seq >= open.startSeq))
|
|
441
701
|
if (open !== undefined && !touchesOpenStep) {
|
|
442
702
|
let count = 0
|
|
703
|
+
const tombstoneSeqs = []
|
|
443
704
|
for (const target of targets) {
|
|
444
705
|
// Re-plan against the live surface because an earlier target may have
|
|
445
706
|
// already removed this target as part of the same tool group.
|
|
446
707
|
const current = surfaceEventsSync(session)
|
|
447
708
|
const plan = planDeletion(current, target.seq)
|
|
448
709
|
if (!plan.ok) continue
|
|
449
|
-
appendTombstones(session, plan.runs, open.turn, open.step)
|
|
710
|
+
tombstoneSeqs.push(...appendTombstones(session, plan.runs, open.turn, open.step, batchId))
|
|
450
711
|
count += plan.count
|
|
451
712
|
}
|
|
713
|
+
appendBatchLedger(session, {
|
|
714
|
+
batchId,
|
|
715
|
+
op: opName,
|
|
716
|
+
seqs: targets.map((target) => target.seq),
|
|
717
|
+
tombstoneSeqs,
|
|
718
|
+
count,
|
|
719
|
+
estimatedFreedTokens,
|
|
720
|
+
result: 'applied',
|
|
721
|
+
})
|
|
452
722
|
return {
|
|
453
|
-
text: `已从模型上下文删除 ${count}
|
|
723
|
+
text: `已从模型上下文删除 ${count} 条消息,估算释放约 ${estimatedFreedTokens.toLocaleString('en-US')} tokens(会话日志与聊天记录仍保留)。批次 ${batchId.slice(0, 8)},可用 /ctxmgr undo-batch 撤销。`,
|
|
454
724
|
count,
|
|
725
|
+
estimatedFreedTokens,
|
|
726
|
+
batchId,
|
|
455
727
|
queued: false,
|
|
456
728
|
}
|
|
457
729
|
}
|
|
@@ -462,7 +734,7 @@ async function deleteMessages(ctx, agent, seqs) {
|
|
|
462
734
|
let added = 0
|
|
463
735
|
for (const target of targets) {
|
|
464
736
|
if (queuedTargets.has(target.seq)) continue
|
|
465
|
-
appendPending(session, 'delete', target.seq)
|
|
737
|
+
appendPending(session, 'delete', target.seq, batchId)
|
|
466
738
|
queuedTargets.add(target.seq)
|
|
467
739
|
added += 1
|
|
468
740
|
}
|
|
@@ -471,15 +743,44 @@ async function deleteMessages(ctx, agent, seqs) {
|
|
|
471
743
|
}
|
|
472
744
|
return {
|
|
473
745
|
text: added === 0
|
|
474
|
-
? '
|
|
475
|
-
: `已加入删除队列:${added}
|
|
746
|
+
? '选中的消息已在删除队列中,将在下一次请求开始时生效。'
|
|
747
|
+
: `已加入删除队列:${added} 条消息将在下一次请求开始时从模型上下文移除,估算释放约 ${estimatedFreedTokens.toLocaleString('en-US')} tokens(会话日志与聊天记录仍保留)。批次 ${batchId.slice(0, 8)},下一次请求生效后可用 /ctxmgr undo-batch 撤销。`,
|
|
476
748
|
count: added,
|
|
749
|
+
estimatedFreedTokens,
|
|
750
|
+
batchId,
|
|
477
751
|
queued: true,
|
|
478
752
|
}
|
|
479
753
|
}
|
|
480
754
|
|
|
755
|
+
/** Token-budget cleanup: plan candidates then delete them via the normal pipeline. */
|
|
756
|
+
async function cleanMessages(ctx, agent, targetTokens, options) {
|
|
757
|
+
const session = liveSession(ctx, agent)
|
|
758
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
759
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
760
|
+
const items = itemsFromSurface(events, tokensBySeq)
|
|
761
|
+
const cleanPlan = planClean(items, targetTokens, options)
|
|
762
|
+
if (cleanPlan.chosen.length === 0) {
|
|
763
|
+
return {
|
|
764
|
+
text: '没有可清理的消息(只有用户/上下文消息,或剩余消息都太小、太新被保护)。token 数为启发式估算,实际可能略少。',
|
|
765
|
+
count: 0,
|
|
766
|
+
estimatedFreedTokens: 0,
|
|
767
|
+
queued: false,
|
|
768
|
+
}
|
|
769
|
+
}
|
|
770
|
+
const result = await deleteMessages(ctx, agent, cleanPlan.chosen, { op: 'clean' })
|
|
771
|
+
return {
|
|
772
|
+
text: `clean:目标 ${targetTokens.toLocaleString('en-US')} tokens,实际估算释放约 ${result.estimatedFreedTokens.toLocaleString('en-US')} tokens(token 数为启发式估算)。${result.text}`,
|
|
773
|
+
count: result.count,
|
|
774
|
+
estimatedFreedTokens: result.estimatedFreedTokens,
|
|
775
|
+
queued: result.queued,
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
481
779
|
/** Queue one or more tombstones for restore at the next request. */
|
|
482
|
-
async function restoreMessages(ctx, agent, tombstoneSeqs) {
|
|
780
|
+
async function restoreMessages(ctx, agent, tombstoneSeqs, options = {}) {
|
|
781
|
+
const batchId = typeof options.batchId === 'string' && options.batchId.length > 0
|
|
782
|
+
? options.batchId
|
|
783
|
+
: undefined
|
|
483
784
|
const unique = [...new Set(tombstoneSeqs)]
|
|
484
785
|
if (unique.length === 0 || unique.some((seq) => !Number.isSafeInteger(seq) || seq < 0)) {
|
|
485
786
|
throw new Error('删除记录序号必须是非负整数。')
|
|
@@ -505,7 +806,7 @@ async function restoreMessages(ctx, agent, tombstoneSeqs) {
|
|
|
505
806
|
let added = 0
|
|
506
807
|
for (const seq of accepted) {
|
|
507
808
|
if (queuedTargets.has(seq)) continue
|
|
508
|
-
appendPending(session, 'restore', seq)
|
|
809
|
+
appendPending(session, 'restore', seq, batchId)
|
|
509
810
|
queuedTargets.add(seq)
|
|
510
811
|
added += 1
|
|
511
812
|
}
|
|
@@ -514,8 +815,8 @@ async function restoreMessages(ctx, agent, tombstoneSeqs) {
|
|
|
514
815
|
}
|
|
515
816
|
return {
|
|
516
817
|
text: added === 0
|
|
517
|
-
? '
|
|
518
|
-
: `已加入恢复队列:${added}
|
|
818
|
+
? '选中的删除记录已在恢复队列中,将在下一次请求开始时恢复。'
|
|
819
|
+
: `已加入恢复队列:${added} 条删除记录将在下一次请求开始时恢复到模型上下文。`,
|
|
519
820
|
count: added,
|
|
520
821
|
queued: true,
|
|
521
822
|
}
|
|
@@ -527,15 +828,20 @@ async function listTurns(ctx, agent) {
|
|
|
527
828
|
const events = await readSurfaceEvents(ctx, session)
|
|
528
829
|
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
529
830
|
const open = openStepOf(session)
|
|
530
|
-
const
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
831
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
832
|
+
const items = itemsFromSurface(events, tokensBySeq)
|
|
833
|
+
const turns = addTurnTokens(
|
|
834
|
+
turnsFromSurface(events, bySeq).map((turn) => ({
|
|
835
|
+
...turn,
|
|
836
|
+
inProgress: open !== undefined && turn.seqs.some((seq) => seq >= open.startSeq),
|
|
837
|
+
})),
|
|
838
|
+
items,
|
|
839
|
+
)
|
|
534
840
|
return { text: formatTurns(turns), turns }
|
|
535
841
|
}
|
|
536
842
|
|
|
537
843
|
/** Delete whole conversation turns now when safe, otherwise queue them durably. */
|
|
538
|
-
async function deleteTurns(ctx, agent, turnNums) {
|
|
844
|
+
async function deleteTurns(ctx, agent, turnNums, options = {}) {
|
|
539
845
|
const unique = [...new Set(turnNums)]
|
|
540
846
|
if (unique.length === 0 || unique.some((num) => !Number.isSafeInteger(num) || num < 0)) {
|
|
541
847
|
throw new Error('轮号必须是非负整数(list-turns 查看)。')
|
|
@@ -544,7 +850,20 @@ async function deleteTurns(ctx, agent, turnNums) {
|
|
|
544
850
|
const events = await readSurfaceEvents(ctx, session)
|
|
545
851
|
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
546
852
|
const open = openStepOf(session)
|
|
547
|
-
const
|
|
853
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
854
|
+
const batchId = typeof options.batchId === 'string' && options.batchId.length > 0
|
|
855
|
+
? options.batchId
|
|
856
|
+
: randomUUID()
|
|
857
|
+
const items = itemsFromSurface(events, tokensBySeq)
|
|
858
|
+
// Attribute each item's tokens to its turn (same rule as turn grouping).
|
|
859
|
+
const tokensByTurn = new Map()
|
|
860
|
+
for (const item of items) {
|
|
861
|
+
tokensByTurn.set(item.turn, (tokensByTurn.get(item.turn) ?? 0) + (item.tokens ?? 0))
|
|
862
|
+
}
|
|
863
|
+
const all = turnsFromSurface(events, bySeq).map((turn) => ({
|
|
864
|
+
...turn,
|
|
865
|
+
tokens: tokensByTurn.get(turn.turn) ?? 0,
|
|
866
|
+
}))
|
|
548
867
|
const targets = []
|
|
549
868
|
for (const num of unique) {
|
|
550
869
|
const turn = all.find((entry) => entry.turn === num)
|
|
@@ -556,22 +875,37 @@ async function deleteTurns(ctx, agent, turnNums) {
|
|
|
556
875
|
}
|
|
557
876
|
if (targets.length === 0) throw new Error('选中的轮都已不在当前上下文中。')
|
|
558
877
|
|
|
878
|
+
const estimatedFreedTokens = targets.reduce((total, turn) => total + (turn.tokens ?? 0), 0)
|
|
879
|
+
|
|
559
880
|
const touchesOpen = open !== undefined
|
|
560
881
|
&& targets.some((turn) => turn.seqs.some((seq) => seq >= open.startSeq))
|
|
561
882
|
if (open !== undefined && !touchesOpen) {
|
|
562
883
|
let turns = 0
|
|
563
884
|
let messages = 0
|
|
885
|
+
const tombstoneSeqs = []
|
|
564
886
|
for (const turn of targets) {
|
|
565
|
-
const done = deleteTurnNow(session, turn.turn, open.turn, open.step)
|
|
887
|
+
const done = deleteTurnNow(session, turn.turn, open.turn, open.step, batchId)
|
|
566
888
|
if (done !== null) {
|
|
567
889
|
turns += 1
|
|
568
|
-
messages += done
|
|
890
|
+
messages += done.count
|
|
891
|
+
tombstoneSeqs.push(...done.tombstoneSeqs)
|
|
569
892
|
}
|
|
570
893
|
}
|
|
894
|
+
appendBatchLedger(session, {
|
|
895
|
+
batchId,
|
|
896
|
+
op: 'delete-turn',
|
|
897
|
+
seqs: targets.map((turn) => turn.turn),
|
|
898
|
+
tombstoneSeqs,
|
|
899
|
+
count: messages,
|
|
900
|
+
estimatedFreedTokens,
|
|
901
|
+
result: 'applied',
|
|
902
|
+
})
|
|
571
903
|
return {
|
|
572
|
-
text: `已从模型上下文删除 ${turns} 轮对话(共 ${messages}
|
|
904
|
+
text: `已从模型上下文删除 ${turns} 轮对话(共 ${messages} 条消息,估算释放约 ${estimatedFreedTokens.toLocaleString('en-US')} tokens;会话日志与聊天记录仍保留)。批次 ${batchId.slice(0, 8)},可用 /ctxmgr undo-batch 撤销。`,
|
|
573
905
|
turns,
|
|
574
906
|
messages,
|
|
907
|
+
estimatedFreedTokens,
|
|
908
|
+
batchId,
|
|
575
909
|
queued: false,
|
|
576
910
|
}
|
|
577
911
|
}
|
|
@@ -582,7 +916,7 @@ async function deleteTurns(ctx, agent, turnNums) {
|
|
|
582
916
|
let added = 0
|
|
583
917
|
for (const turn of targets) {
|
|
584
918
|
if (queued.has(turn.turn)) continue
|
|
585
|
-
appendPending(session, 'delete-turn', turn.turn)
|
|
919
|
+
appendPending(session, 'delete-turn', turn.turn, batchId)
|
|
586
920
|
queued.add(turn.turn)
|
|
587
921
|
added += 1
|
|
588
922
|
}
|
|
@@ -591,9 +925,11 @@ async function deleteTurns(ctx, agent, turnNums) {
|
|
|
591
925
|
}
|
|
592
926
|
return {
|
|
593
927
|
text: added === 0
|
|
594
|
-
? '
|
|
595
|
-
: `已加入删除队列:${added}
|
|
928
|
+
? '选中的轮已在删除队列中,将在下一次请求开始时生效。'
|
|
929
|
+
: `已加入删除队列:${added} 轮对话将在下一次请求开始时从模型上下文移除,估算释放约 ${estimatedFreedTokens.toLocaleString('en-US')} tokens(会话日志与聊天记录仍保留)。`,
|
|
596
930
|
turns: added,
|
|
931
|
+
estimatedFreedTokens,
|
|
932
|
+
batchId,
|
|
597
933
|
queued: true,
|
|
598
934
|
}
|
|
599
935
|
}
|
|
@@ -605,12 +941,13 @@ async function deleteTurns(ctx, agent, turnNums) {
|
|
|
605
941
|
* and text at the tail). Tombstones already on the surface stay untouched.
|
|
606
942
|
* @returns the number of messages removed, or null when none remain.
|
|
607
943
|
*/
|
|
608
|
-
function deleteTurnNow(session, turnNum, curTurn, curStep) {
|
|
944
|
+
function deleteTurnNow(session, turnNum, curTurn, curStep, batchId = undefined) {
|
|
609
945
|
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
610
946
|
const turn = turnsFromSurface(surfaceEventsSync(session), bySeq)
|
|
611
947
|
.find((entry) => entry.turn === turnNum)
|
|
612
948
|
if (turn === undefined || turn.seqs.length === 0) return null
|
|
613
949
|
const planned = new Set()
|
|
950
|
+
const tombstoneSeqs = []
|
|
614
951
|
let count = 0
|
|
615
952
|
for (const seq of turn.seqs) {
|
|
616
953
|
if (planned.has(seq)) continue
|
|
@@ -619,11 +956,11 @@ function deleteTurnNow(session, turnNum, curTurn, curStep) {
|
|
|
619
956
|
const current = surfaceEventsSync(session)
|
|
620
957
|
const plan = planDeletion(current, seq)
|
|
621
958
|
if (!plan.ok) continue
|
|
622
|
-
appendTombstones(session, plan.runs, curTurn, curStep)
|
|
959
|
+
tombstoneSeqs.push(...appendTombstones(session, plan.runs, curTurn, curStep, batchId))
|
|
623
960
|
for (const index of plan.indices) planned.add(current[index].seq)
|
|
624
961
|
count += plan.count
|
|
625
962
|
}
|
|
626
|
-
return count
|
|
963
|
+
return { count, tombstoneSeqs }
|
|
627
964
|
}
|
|
628
965
|
|
|
629
966
|
/** Per-plugin-instance agent listener registries, keyed by plugin ctx. */
|
|
@@ -650,26 +987,85 @@ function applyQueuedOperations(ctx, agent, turn, step) {
|
|
|
650
987
|
if (session === undefined) return
|
|
651
988
|
const queue = durableQueue(ctx, session)
|
|
652
989
|
if (queue.length === 0) return
|
|
990
|
+
// Price the current surface once, so a replayed entry records the relief it
|
|
991
|
+
// actually produced instead of a zero placeholder.
|
|
992
|
+
const pricedItems = itemsFromSurface(surfaceEventsSync(session), buildTokensBySeq(ctx, session))
|
|
993
|
+
const tokensOfSeq = new Map(pricedItems.map((item) => [item.seq, item.tokens ?? 0]))
|
|
994
|
+
const tokensByTurn = new Map()
|
|
995
|
+
for (const item of pricedItems) {
|
|
996
|
+
tokensByTurn.set(item.turn, (tokensByTurn.get(item.turn) ?? 0) + (item.tokens ?? 0))
|
|
997
|
+
}
|
|
998
|
+
const freedOfPlan = (plan) => plan.runs.reduce((sum, run) => sum
|
|
999
|
+
+ run.seqs.reduce((inner, seq) => inner + (tokensOfSeq.get(seq) ?? 0), 0), 0)
|
|
653
1000
|
for (const entry of queue) {
|
|
654
1001
|
try {
|
|
655
1002
|
if (entry.op === 'delete') {
|
|
656
1003
|
const plan = planDeletion(surfaceEventsSync(session), entry.targetSeq)
|
|
657
1004
|
if (!plan.ok) {
|
|
658
1005
|
appendAck(session, entry.recordSeq, 'skipped', `target #${entry.targetSeq} ${plan.reason}`)
|
|
1006
|
+
appendBatchLedger(session, {
|
|
1007
|
+
batchId: entry.batchId ?? `pending-${entry.recordSeq}`,
|
|
1008
|
+
op: 'delete',
|
|
1009
|
+
seqs: [entry.targetSeq],
|
|
1010
|
+
tombstoneSeqs: [],
|
|
1011
|
+
estimatedFreedTokens: 0,
|
|
1012
|
+
result: 'skipped',
|
|
1013
|
+
reason: `target #${entry.targetSeq} ${plan.reason}`,
|
|
1014
|
+
})
|
|
659
1015
|
continue
|
|
660
1016
|
}
|
|
661
|
-
appendTombstones(session, plan.runs, turn, step)
|
|
1017
|
+
const tombstoneSeqs = appendTombstones(session, plan.runs, turn, step, entry.batchId)
|
|
662
1018
|
appendAck(session, entry.recordSeq, 'applied')
|
|
1019
|
+
appendBatchLedger(session, {
|
|
1020
|
+
batchId: entry.batchId ?? `pending-${entry.recordSeq}`,
|
|
1021
|
+
op: 'delete',
|
|
1022
|
+
seqs: [entry.targetSeq],
|
|
1023
|
+
tombstoneSeqs,
|
|
1024
|
+
count: plan.count,
|
|
1025
|
+
estimatedFreedTokens: freedOfPlan(plan),
|
|
1026
|
+
result: 'applied',
|
|
1027
|
+
})
|
|
663
1028
|
} else if (entry.op === 'delete-turn') {
|
|
664
|
-
const done = deleteTurnNow(session, entry.targetSeq, turn, step)
|
|
1029
|
+
const done = deleteTurnNow(session, entry.targetSeq, turn, step, entry.batchId)
|
|
665
1030
|
if (done === null) {
|
|
666
1031
|
appendAck(session, entry.recordSeq, 'skipped', `turn #${entry.targetSeq} has no remaining content`)
|
|
1032
|
+
appendBatchLedger(session, {
|
|
1033
|
+
batchId: entry.batchId ?? `pending-${entry.recordSeq}`,
|
|
1034
|
+
op: 'delete-turn',
|
|
1035
|
+
seqs: [entry.targetSeq],
|
|
1036
|
+
tombstoneSeqs: [],
|
|
1037
|
+
estimatedFreedTokens: 0,
|
|
1038
|
+
result: 'skipped',
|
|
1039
|
+
reason: `turn #${entry.targetSeq} has no remaining content`,
|
|
1040
|
+
})
|
|
667
1041
|
} else {
|
|
668
1042
|
appendAck(session, entry.recordSeq, 'applied')
|
|
1043
|
+
appendBatchLedger(session, {
|
|
1044
|
+
batchId: entry.batchId ?? `pending-${entry.recordSeq}`,
|
|
1045
|
+
op: 'delete-turn',
|
|
1046
|
+
seqs: [entry.targetSeq],
|
|
1047
|
+
tombstoneSeqs: done.tombstoneSeqs,
|
|
1048
|
+
count: done.count,
|
|
1049
|
+
estimatedFreedTokens: tokensByTurn.get(entry.targetSeq) ?? 0,
|
|
1050
|
+
result: 'applied',
|
|
1051
|
+
})
|
|
669
1052
|
}
|
|
670
1053
|
} else {
|
|
671
1054
|
restoreOne(session, entry.targetSeq, turn, step)
|
|
672
1055
|
appendAck(session, entry.recordSeq, 'applied')
|
|
1056
|
+
// Close the undo ledger entry once the restore actually landed, so the
|
|
1057
|
+
// audit trail does not stay stuck at "queued".
|
|
1058
|
+
if (typeof entry.batchId === 'string') {
|
|
1059
|
+
appendBatchLedger(session, {
|
|
1060
|
+
batchId: entry.batchId,
|
|
1061
|
+
op: 'undo',
|
|
1062
|
+
seqs: [entry.targetSeq],
|
|
1063
|
+
tombstoneSeqs: [],
|
|
1064
|
+
count: 1,
|
|
1065
|
+
estimatedFreedTokens: 0,
|
|
1066
|
+
result: 'applied',
|
|
1067
|
+
})
|
|
1068
|
+
}
|
|
673
1069
|
}
|
|
674
1070
|
} catch (error) {
|
|
675
1071
|
const message = error instanceof Error ? error.message : String(error)
|
|
@@ -723,6 +1119,24 @@ function parseCommand(rawInput) {
|
|
|
723
1119
|
const head = parts[0].toLowerCase()
|
|
724
1120
|
if (head === 'list' || head === 'ls') return { op: 'list' }
|
|
725
1121
|
if (head === 'turns' || head === 'list-turns' || head === 'ls-turns') return { op: 'list-turns' }
|
|
1122
|
+
if (head === 'clean') {
|
|
1123
|
+
const rest = text.slice(head.length).trim()
|
|
1124
|
+
if (rest.length === 0) return { op: 'invalid', reason: '缺少要释放的 token 预算。' }
|
|
1125
|
+
if (!/^\d+$/.test(rest)) return { op: 'invalid', reason: '目标 token 数必须是正整数。' }
|
|
1126
|
+
return { op: 'clean', targetTokens: Number(rest) }
|
|
1127
|
+
}
|
|
1128
|
+
if (head === 'compact') {
|
|
1129
|
+
const rest = text.slice(head.length).trim()
|
|
1130
|
+
const values = rest.length === 0 ? [] : rest.split(/[,\s]+/).filter(Boolean)
|
|
1131
|
+
if (values.length !== 2) return { op: 'invalid', reason: 'compact 需要两个序号:起始与结束(按表面位置)。' }
|
|
1132
|
+
if (values.some((value) => !/^\d+$/.test(value))) return { op: 'invalid', reason: 'compact 的两个序号必须是数字。' }
|
|
1133
|
+
return { op: 'compact', start: Number(values[0]), end: Number(values[1]) }
|
|
1134
|
+
}
|
|
1135
|
+
if (head === 'batches' || head === 'ledger' || head === 'audit') return { op: 'batches' }
|
|
1136
|
+
if (head === 'undo-batch' || head === 'undobatch' || head === 'undo-last' || head === 'undolast') {
|
|
1137
|
+
const rest = text.slice(head.length).trim()
|
|
1138
|
+
return rest.length === 0 ? { op: 'undo-batch' } : { op: 'undo-batch', batchId: rest }
|
|
1139
|
+
}
|
|
726
1140
|
const deleteTurn = head === 'deleteturn' || head === 'delturn' || head === 'dt'
|
|
727
1141
|
if (head === 'delete' || head === 'rm' || head === 'restore' || head === 'undo' || deleteTurn) {
|
|
728
1142
|
const rest = text.slice(head.length).trim()
|
|
@@ -745,8 +1159,8 @@ export function apply(ctx) {
|
|
|
745
1159
|
|
|
746
1160
|
const command = ctx.commands.register({
|
|
747
1161
|
name: 'ctxmgr',
|
|
748
|
-
description: '
|
|
749
|
-
input: { hint: 'list | turns | delete <序号,...> | deleteturn <轮号,...> | restore <删除记录序号,...>' },
|
|
1162
|
+
description: '列出、批量删除或恢复当前会话中的单条消息,并按轮删除整轮对话,支持按 token 预算自动清理(仅移出/恢复模型上下文,保留原始日志)。',
|
|
1163
|
+
input: { hint: 'list | turns | delete <序号,...> | deleteturn <轮号,...> | clean <目标tokens> | compact <起序号> <止序号> | batches | undo-batch [batchId] | restore <删除记录序号,...>' },
|
|
750
1164
|
recordInput: false,
|
|
751
1165
|
async handler(invocation) {
|
|
752
1166
|
try {
|
|
@@ -767,11 +1181,27 @@ export function apply(ctx) {
|
|
|
767
1181
|
const result = await deleteTurns(ctx, invocation.agent, parsed.seqs)
|
|
768
1182
|
return { kind: 'success', text: result.text }
|
|
769
1183
|
}
|
|
1184
|
+
if (parsed.op === 'clean') {
|
|
1185
|
+
const result = await cleanMessages(ctx, invocation.agent, parsed.targetTokens, {})
|
|
1186
|
+
return { kind: 'success', text: result.text }
|
|
1187
|
+
}
|
|
1188
|
+
if (parsed.op === 'compact') {
|
|
1189
|
+
const result = await compactSelection(ctx, invocation.agent, parsed.start, parsed.end)
|
|
1190
|
+
return { kind: 'success', text: result.text }
|
|
1191
|
+
}
|
|
1192
|
+
if (parsed.op === 'batches') {
|
|
1193
|
+
const result = await listBatches(ctx, invocation.agent)
|
|
1194
|
+
return { kind: 'success', text: result.text }
|
|
1195
|
+
}
|
|
1196
|
+
if (parsed.op === 'undo-batch') {
|
|
1197
|
+
const result = await undoBatch(ctx, invocation.agent, parsed.batchId)
|
|
1198
|
+
return { kind: 'success', text: result.text }
|
|
1199
|
+
}
|
|
770
1200
|
if (parsed.op === 'restore') {
|
|
771
1201
|
const result = await restoreMessages(ctx, invocation.agent, parsed.seqs)
|
|
772
1202
|
return { kind: 'success', text: result.text }
|
|
773
1203
|
}
|
|
774
|
-
return { kind: 'error', text: `${parsed.reason} 用法:/ctxmgr list | /ctxmgr turns | /ctxmgr delete <序号,...> | /ctxmgr deleteturn <轮号,...> | /ctxmgr restore <删除记录序号,...>` }
|
|
1204
|
+
return { kind: 'error', text: `${parsed.reason} 用法:/ctxmgr list | /ctxmgr turns | /ctxmgr delete <序号,...> | /ctxmgr deleteturn <轮号,...> | /ctxmgr clean <目标tokens> | /ctxmgr compact <起序号> <止序号> | /ctxmgr batches | /ctxmgr undo-batch [batchId] | /ctxmgr restore <删除记录序号,...>` }
|
|
775
1205
|
} catch (error) {
|
|
776
1206
|
return { kind: 'error', text: error instanceof Error ? error.message : String(error) }
|
|
777
1207
|
}
|
|
@@ -780,14 +1210,14 @@ export function apply(ctx) {
|
|
|
780
1210
|
|
|
781
1211
|
const tool = ctx.tools.register({
|
|
782
1212
|
name: 'context_manager',
|
|
783
|
-
description: 'Manage the model context of the current session. Actions: list (current messages plus deleted records and queued operations), list-turns (conversation turns with turn numbers), delete (message seqs; any tool results tied to an assistant message that calls tools go with it), delete-turns (whole turns: the user prompt, the assistant work and reply, and that turn\'s injected context), restore (tombstone seqs from list; user/context restores at its original position, assistant content is appended at the tail). Typical uses: roll back to the start of a turn by deleting that turn and the ones after it, or drop noisy messages that no longer matter. Deletion only affects later model requests; the raw session log and chat transcript are retained. Operations that cannot run safely yet are recorded durably in the session log and applied when the next step starts, surviving restarts. Use only when the user explicitly asks. Requires a live session.',
|
|
1213
|
+
description: 'Manage the model context of the current session. Actions: list (current messages with estimated tokens plus deleted records and queued operations), list-turns (conversation turns with turn numbers), delete (message seqs; any tool results tied to an assistant message that calls tools go with it), delete-turns (whole turns: the user prompt, the assistant work and reply, and that turn\'s injected context), compact (summarize exactly one user-selected surface span via the official ctx.compaction.compactRegion; only the named range, never a global threshold), clean (token-budget cleanup: automatically picks large tool/assistant messages ranked by estimated tokens descending, until target tokens are freed; user messages and the most recent messages are protected, and the planner reuses the same delete pipeline), restore (tombstone seqs from list; user/context restores at its original position, assistant content is appended at the tail). Typical uses: roll back to the start of a turn by deleting that turn and the ones after it, or drop noisy messages that no longer matter. All token figures are estimates from a 4-chars-per-token heuristic and can notably underprice CJK text and JSON. Deletion only affects later model requests; the raw session log and chat transcript are retained. Operations that cannot run safely yet are recorded durably in the session log and applied when the next step starts, surviving restarts. Use only when the user explicitly asks. Requires a live session.',
|
|
784
1214
|
parameters: {
|
|
785
1215
|
type: 'object',
|
|
786
1216
|
properties: {
|
|
787
1217
|
action: {
|
|
788
1218
|
type: 'string',
|
|
789
|
-
enum: ['list', 'list-turns', 'delete', 'delete-turns', 'restore'],
|
|
790
|
-
description: 'list messages, list conversation turns, delete message seqs, delete whole turns by turn number, or restore tombstone seqs.',
|
|
1219
|
+
enum: ['list', 'list-turns', 'delete', 'delete-turns', 'clean', 'compact', 'batches', 'undo-batch', 'restore'],
|
|
1220
|
+
description: 'list messages, list conversation turns, delete message seqs, delete whole turns by turn number, clean by token budget, list the batch audit ledger, undo a batch, or restore tombstone seqs.',
|
|
791
1221
|
},
|
|
792
1222
|
seq: {
|
|
793
1223
|
type: 'integer',
|
|
@@ -798,6 +1228,30 @@ export function apply(ctx) {
|
|
|
798
1228
|
items: { type: 'integer' },
|
|
799
1229
|
description: 'Message seqs for delete, turn numbers for delete-turns, or tombstone seqs for restore (from list/turns output).',
|
|
800
1230
|
},
|
|
1231
|
+
targetTokens: {
|
|
1232
|
+
type: 'integer',
|
|
1233
|
+
description: 'For clean: the token budget (target number of tokens to free).',
|
|
1234
|
+
},
|
|
1235
|
+
minCandidateTokens: {
|
|
1236
|
+
type: 'integer',
|
|
1237
|
+
description: 'For clean: optional minimum estimated tokens for a message to be considered a candidate (default 100).',
|
|
1238
|
+
},
|
|
1239
|
+
protectRecent: {
|
|
1240
|
+
type: 'integer',
|
|
1241
|
+
description: 'For clean: optional number of most recent messages to protect (default 3).',
|
|
1242
|
+
},
|
|
1243
|
+
batchId: {
|
|
1244
|
+
type: 'string',
|
|
1245
|
+
description: 'For undo-batch: optional batch id (or unambiguous prefix) from the ledger; omit to undo the most recent applied batch.',
|
|
1246
|
+
},
|
|
1247
|
+
start: {
|
|
1248
|
+
type: 'integer',
|
|
1249
|
+
description: 'For compact: first surface seq of the span to compact (inclusive, from list).',
|
|
1250
|
+
},
|
|
1251
|
+
end: {
|
|
1252
|
+
type: 'integer',
|
|
1253
|
+
description: 'For compact: last surface seq of the span to compact (inclusive, from list); both edges must be tool-pairing balanced.',
|
|
1254
|
+
},
|
|
801
1255
|
},
|
|
802
1256
|
required: ['action'],
|
|
803
1257
|
additionalProperties: false,
|
|
@@ -839,12 +1293,38 @@ export function apply(ctx) {
|
|
|
839
1293
|
const result = await deleteTurns(ctx, exec.agent, list)
|
|
840
1294
|
return { ok: true, text: result.text }
|
|
841
1295
|
}
|
|
1296
|
+
if (action === 'clean') {
|
|
1297
|
+
if (!Number.isSafeInteger(args?.targetTokens) || args.targetTokens <= 0) {
|
|
1298
|
+
throw new Error('clean 需要正整数 targetTokens(要释放的 token 预算)。')
|
|
1299
|
+
}
|
|
1300
|
+
const result = await cleanMessages(ctx, exec.agent, args.targetTokens, {
|
|
1301
|
+
minCandidateTokens: args?.minCandidateTokens,
|
|
1302
|
+
protectRecent: args?.protectRecent,
|
|
1303
|
+
})
|
|
1304
|
+
return { ok: true, text: result.text }
|
|
1305
|
+
}
|
|
1306
|
+
if (action === 'compact') {
|
|
1307
|
+
if (!Number.isSafeInteger(args?.start) || !Number.isSafeInteger(args?.end)) {
|
|
1308
|
+
throw new Error('compact 需要整数 start 与 end(list 返回的表面序号)。')
|
|
1309
|
+
}
|
|
1310
|
+
const result = await compactSelection(ctx, exec.agent, args.start, args.end)
|
|
1311
|
+
return { ok: true, text: result.text }
|
|
1312
|
+
}
|
|
1313
|
+
if (action === 'batches') {
|
|
1314
|
+
const result = await listBatches(ctx, exec.agent)
|
|
1315
|
+
return { ok: true, text: result.text }
|
|
1316
|
+
}
|
|
1317
|
+
if (action === 'undo-batch') {
|
|
1318
|
+
const result = await undoBatch(ctx, exec.agent,
|
|
1319
|
+
typeof args?.batchId === 'string' ? args.batchId : undefined)
|
|
1320
|
+
return { ok: true, text: result.text }
|
|
1321
|
+
}
|
|
842
1322
|
if (action === 'restore') {
|
|
843
1323
|
if (list.length === 0) throw new Error('restore 需要已删除记录返回的整数 tombstone seq。')
|
|
844
1324
|
const result = await restoreMessages(ctx, exec.agent, list)
|
|
845
1325
|
return { ok: true, text: result.text }
|
|
846
1326
|
}
|
|
847
|
-
throw new Error('action 必须是 list、list-turns、delete、delete-turns 或 restore。')
|
|
1327
|
+
throw new Error('action 必须是 list、list-turns、delete、delete-turns、clean、compact、batches、undo-batch 或 restore。')
|
|
848
1328
|
},
|
|
849
1329
|
})
|
|
850
1330
|
|