dsh-context-manager 1.6.0 → 1.7.0
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 +19 -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 +508 -40
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +1 -1
package/core.js
CHANGED
|
@@ -101,6 +101,7 @@ export function foldSurface(events) {
|
|
|
101
101
|
let uncertain = false
|
|
102
102
|
for (const event of events) {
|
|
103
103
|
if (event === null || typeof event !== 'object') continue
|
|
104
|
+
if (!Number.isSafeInteger(event.seq)) continue // a log object without a seq cannot be indexed
|
|
104
105
|
bySeq.set(event.seq, event)
|
|
105
106
|
if (!SURFACE_TYPES.has(event.type)) continue
|
|
106
107
|
const op = event.surfaceOp
|
|
@@ -130,12 +131,60 @@ function visibleSurfaceEvent(event) {
|
|
|
130
131
|
return true
|
|
131
132
|
}
|
|
132
133
|
|
|
134
|
+
/** Fixed text-density estimate: 4 characters per token (token-meter heuristic). */
|
|
135
|
+
export const ESTIMATE_CHARS_PER_TOKEN = 4
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Heuristically price one message in tokens, mirroring the dsh-token-meter
|
|
139
|
+
* fixed-density heuristic (4 characters per token, plus per-block and role
|
|
140
|
+
* framing overhead). This is an estimate only: CJK text and dense JSON
|
|
141
|
+
* underprice badly under this rule, so all token figures surfaced by this
|
|
142
|
+
* plugin must be labeled as estimates.
|
|
143
|
+
* @param message - message (event.data for user, event.data.message otherwise).
|
|
144
|
+
* @param isSystem - price as a rendered system prompt (no per-block overhead).
|
|
145
|
+
* @returns heuristic tokens; 0 for empty content (e.g. tombstones).
|
|
146
|
+
*/
|
|
147
|
+
export function estimateMessageTokens(message, isSystem = false) {
|
|
148
|
+
if (message === undefined || message === null) return 0
|
|
149
|
+
const content = Array.isArray(message.content) ? message.content : []
|
|
150
|
+
if (content.length === 0) return 0
|
|
151
|
+
if (isSystem) {
|
|
152
|
+
let characters = 0
|
|
153
|
+
for (const block of content) {
|
|
154
|
+
characters += block?.type === 'text' ? block.text.length : JSON.stringify(block).length
|
|
155
|
+
}
|
|
156
|
+
return Math.ceil(characters / ESTIMATE_CHARS_PER_TOKEN) + 4
|
|
157
|
+
}
|
|
158
|
+
let tokens = 0
|
|
159
|
+
for (const block of content) {
|
|
160
|
+
if (block === null || typeof block !== 'object') continue
|
|
161
|
+
switch (block.type) {
|
|
162
|
+
case 'text':
|
|
163
|
+
case 'reasoning':
|
|
164
|
+
tokens += Math.ceil((block.text?.length ?? 0) / ESTIMATE_CHARS_PER_TOKEN) + 4
|
|
165
|
+
break
|
|
166
|
+
case 'tool-call':
|
|
167
|
+
tokens += Math.ceil((block.name?.length ?? 0) / ESTIMATE_CHARS_PER_TOKEN)
|
|
168
|
+
+ Math.ceil((block.arguments?.length ?? 0) / ESTIMATE_CHARS_PER_TOKEN)
|
|
169
|
+
+ 4
|
|
170
|
+
break
|
|
171
|
+
default:
|
|
172
|
+
// Merge-extensible/unknown blocks (and image references, whose request
|
|
173
|
+
// price is route-owned) keep a conservative structural JSON price.
|
|
174
|
+
tokens += 4 + Math.ceil(JSON.stringify(block).length / ESTIMATE_CHARS_PER_TOKEN)
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return tokens + 4
|
|
178
|
+
}
|
|
179
|
+
|
|
133
180
|
/**
|
|
134
181
|
* Project current surface events into display items, oldest first.
|
|
135
182
|
* `events` is either a complete surface snapshot or the folded output of
|
|
136
183
|
* {@link foldSurface} resolved back to events.
|
|
184
|
+
* @param tokensBySeq - optional seq→tokens map (e.g. from ctx.tokenMeter
|
|
185
|
+
* measure nodes) overriding the local heuristic per surface node.
|
|
137
186
|
*/
|
|
138
|
-
export function itemsFromSurface(events) {
|
|
187
|
+
export function itemsFromSurface(events, tokensBySeq = undefined) {
|
|
139
188
|
const items = []
|
|
140
189
|
let currentTurn = 0
|
|
141
190
|
let currentStep = 0
|
|
@@ -146,6 +195,11 @@ export function itemsFromSurface(events) {
|
|
|
146
195
|
if (!visibleSurfaceEvent(event)) continue
|
|
147
196
|
const message = messageOf(event)
|
|
148
197
|
const content = Array.isArray(message.content) ? message.content : []
|
|
198
|
+
const tokens = content.length === 0
|
|
199
|
+
? 0 // empty/tombstone messages occupy nothing
|
|
200
|
+
: tokensBySeq !== undefined && tokensBySeq.has(event.seq)
|
|
201
|
+
? tokensBySeq.get(event.seq)
|
|
202
|
+
: estimateMessageTokens(message, event.type === 'system/message')
|
|
149
203
|
const callIds = toolCallIdsOf(event)
|
|
150
204
|
let turn = Number.isSafeInteger(event.data?.turn) ? event.data.turn : undefined
|
|
151
205
|
let step = Number.isSafeInteger(event.data?.step) ? event.data.step : undefined
|
|
@@ -171,11 +225,53 @@ export function itemsFromSurface(events) {
|
|
|
171
225
|
callIds,
|
|
172
226
|
toolCallId: event.type === 'tool/result' && typeof message.toolCallId === 'string' ? message.toolCallId : undefined,
|
|
173
227
|
blocks: content.length,
|
|
228
|
+
tokens,
|
|
174
229
|
})
|
|
175
230
|
}
|
|
176
231
|
return items
|
|
177
232
|
}
|
|
178
233
|
|
|
234
|
+
/**
|
|
235
|
+
* Plan a token-budget "clean": choose an ordered set of deletable messages
|
|
236
|
+
* whose estimated tokens roughly reach the budget.
|
|
237
|
+
*
|
|
238
|
+
* Candidates are only large tool / assistant messages; user and context
|
|
239
|
+
* messages are never cleaned, and the most recent items on the surface are
|
|
240
|
+
* protected so the live conversation stays intact. Candidates are ranked by
|
|
241
|
+
* estimated tokens, descending, and taken until the budget is (first) met.
|
|
242
|
+
* @param items - display items from {@link itemsFromSurface} (tokens required).
|
|
243
|
+
* @param targetTokens - the token budget to free.
|
|
244
|
+
* @param options - minCandidateTokens (default 100) and protectRecent
|
|
245
|
+
* (default 3) thresholds.
|
|
246
|
+
*/
|
|
247
|
+
export function planClean(items, targetTokens, options = {}) {
|
|
248
|
+
const minTokens = options.minCandidateTokens ?? 100
|
|
249
|
+
const protectRecent = Math.max(0, options.protectRecent ?? 3)
|
|
250
|
+
const protectedSeqs = new Set(
|
|
251
|
+
items.slice(Math.max(0, items.length - protectRecent)).map((item) => item.seq),
|
|
252
|
+
)
|
|
253
|
+
const candidates = items
|
|
254
|
+
.filter((item) => (item.role === 'tool' || item.role === 'assistant')
|
|
255
|
+
&& (item.tokens ?? 0) >= minTokens
|
|
256
|
+
&& !protectedSeqs.has(item.seq))
|
|
257
|
+
// Total order: tokens descending, then surface order, so equal-priced
|
|
258
|
+
// candidates are always chosen deterministically.
|
|
259
|
+
.sort((a, b) => (b.tokens ?? 0) - (a.tokens ?? 0) || a.seq - b.seq)
|
|
260
|
+
const chosen = []
|
|
261
|
+
let estimatedFreedTokens = 0
|
|
262
|
+
for (const candidate of candidates) {
|
|
263
|
+
if (estimatedFreedTokens >= targetTokens) break
|
|
264
|
+
chosen.push(candidate.seq)
|
|
265
|
+
estimatedFreedTokens = estimatedFreedTokens + (candidate.tokens ?? 0)
|
|
266
|
+
}
|
|
267
|
+
return {
|
|
268
|
+
chosen,
|
|
269
|
+
candidates: candidates.map((item) => ({ seq: item.seq, role: item.role, tokens: item.tokens ?? 0 })),
|
|
270
|
+
estimatedFreedTokens,
|
|
271
|
+
meetsTarget: estimatedFreedTokens >= targetTokens,
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
|
|
179
275
|
/** Boundary turn/step for a tombstone: prefer the deleted nodes, then neighbors. */
|
|
180
276
|
export function boundaryFor(events, indices) {
|
|
181
277
|
const valid = (data) => Number.isSafeInteger(data?.turn) && Number.isSafeInteger(data?.step)
|
|
@@ -209,6 +305,9 @@ export function planDeletion(events, targetSeq) {
|
|
|
209
305
|
if (targetIndex < 0) return { ok: false, reason: 'not-found' }
|
|
210
306
|
const target = events[targetIndex]
|
|
211
307
|
if (target.type === 'system/message') return { ok: false, reason: 'system' }
|
|
308
|
+
// A tombstone is already an invisible replacement; deleting it would nest
|
|
309
|
+
// replacements and produce an empty recall pointer. Restore is the way out.
|
|
310
|
+
if (isTombstone(target)) return { ok: false, reason: 'tombstone' }
|
|
212
311
|
if (target.type === 'tool/result' && typeof target.data?.message?.toolCallId !== 'string') {
|
|
213
312
|
return { ok: false, reason: 'unsupported' }
|
|
214
313
|
}
|
|
@@ -276,8 +375,63 @@ export function isTombstoneKind(kind) {
|
|
|
276
375
|
return kind === TOMBSTONE_KIND || LEGACY_TOMBSTONE_KINDS.includes(kind)
|
|
277
376
|
}
|
|
278
377
|
|
|
279
|
-
/**
|
|
280
|
-
export
|
|
378
|
+
/** Shortest useful recall pointer: how many removed messages one tombstone names. */
|
|
379
|
+
export const RECALL_MAX_ENTRIES = 8
|
|
380
|
+
/** Recall preview length; keeps the pointer tiny and avoids copying message text. */
|
|
381
|
+
export const RECALL_PREVIEW_LIMIT = 80
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Build the recall pointer stored inside one tombstone.
|
|
385
|
+
*
|
|
386
|
+
* Each entry names the original seq, its role, and a one-line gist. The gist is
|
|
387
|
+
* an excerpt, never the full message, so a tombstone cannot leak content that
|
|
388
|
+
* the surrounding context no longer carries.
|
|
389
|
+
* @param events - originals being removed, in surface order.
|
|
390
|
+
* @returns recall entries, capped at {@link RECALL_MAX_ENTRIES}.
|
|
391
|
+
*/
|
|
392
|
+
export function buildRecall(events) {
|
|
393
|
+
const recall = []
|
|
394
|
+
for (const event of events) {
|
|
395
|
+
if (recall.length >= RECALL_MAX_ENTRIES) break
|
|
396
|
+
if (event === undefined || event === null || typeof event.seq !== 'number') continue
|
|
397
|
+
const message = event.type === 'user/message' ? event.data : event.data?.message
|
|
398
|
+
recall.push({
|
|
399
|
+
seq: event.seq,
|
|
400
|
+
role: roleOf(event),
|
|
401
|
+
preview: previewOf(message, RECALL_PREVIEW_LIMIT),
|
|
402
|
+
})
|
|
403
|
+
}
|
|
404
|
+
return recall
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
/**
|
|
408
|
+
* Durable payload of an invisible replacement node.
|
|
409
|
+
*
|
|
410
|
+
* `batchId` ties the tombstone to one auditable batch operation: the ledger
|
|
411
|
+
* record for that batch lists every tombstone it wrote, so an undo can name
|
|
412
|
+
* exactly the nodes one user action produced while the tombstone kind stays
|
|
413
|
+
* the only marker the restore planner relies on.
|
|
414
|
+
* @param turn - open turn coordinate; the node must match an open step.
|
|
415
|
+
* @param step - open step coordinate.
|
|
416
|
+
* @param id - fresh message id for the invisible node.
|
|
417
|
+
* @param batchId - optional batch identifier written into the source.
|
|
418
|
+
* @param recall - optional short pointers to the removed messages.
|
|
419
|
+
*/
|
|
420
|
+
export function tombstoneData(turn, step, id, batchId = undefined, recall = undefined) {
|
|
421
|
+
const source = typeof batchId === 'string' && batchId.length > 0
|
|
422
|
+
? { kind: TOMBSTONE_KIND, batchId }
|
|
423
|
+
: { kind: TOMBSTONE_KIND }
|
|
424
|
+
// A recall pointer turns "deleted" into "unloaded": the original seq and a
|
|
425
|
+
// one-line gist stay addressable from inside the tombstone, while no full
|
|
426
|
+
// message text is duplicated into the tombstone.
|
|
427
|
+
if (Array.isArray(recall) && recall.length > 0) {
|
|
428
|
+
// Copy the entries: the tombstone must not alias caller-owned objects.
|
|
429
|
+
source.recall = recall.slice(0, RECALL_MAX_ENTRIES).map((entry) => ({
|
|
430
|
+
seq: entry?.seq,
|
|
431
|
+
role: entry?.role,
|
|
432
|
+
preview: entry?.preview,
|
|
433
|
+
}))
|
|
434
|
+
}
|
|
281
435
|
return {
|
|
282
436
|
turn,
|
|
283
437
|
step,
|
|
@@ -285,7 +439,7 @@ export function tombstoneData(turn, step, id) {
|
|
|
285
439
|
id,
|
|
286
440
|
role: 'developer',
|
|
287
441
|
content: [],
|
|
288
|
-
source
|
|
442
|
+
source,
|
|
289
443
|
},
|
|
290
444
|
}
|
|
291
445
|
}
|
|
@@ -353,6 +507,12 @@ export function deletedFromSurface(events, bySeq) {
|
|
|
353
507
|
}
|
|
354
508
|
records.push({
|
|
355
509
|
tombstoneSeq: event.seq,
|
|
510
|
+
batchId: typeof event.data?.message?.source?.batchId === 'string'
|
|
511
|
+
? event.data.message.source.batchId
|
|
512
|
+
: undefined,
|
|
513
|
+
recall: Array.isArray(event.data?.message?.source?.recall)
|
|
514
|
+
? event.data.message.source.recall
|
|
515
|
+
: [],
|
|
356
516
|
targetSeqs: [...targets],
|
|
357
517
|
count: targets.length,
|
|
358
518
|
items: known.map((original) => ({
|
|
@@ -370,14 +530,16 @@ export function deletedFromSurface(events, bySeq) {
|
|
|
370
530
|
/** Human-readable Host listing for a command or tool result. */
|
|
371
531
|
export function formatList(items, deleted = [], pending = [], limit = 30) {
|
|
372
532
|
const lines = []
|
|
533
|
+
const totalTokens = items.reduce((total, item) => total + (item.tokens ?? 0), 0)
|
|
373
534
|
if (items.length === 0) {
|
|
374
535
|
lines.push('当前模型上下文中没有可管理的消息。')
|
|
375
536
|
} else {
|
|
376
537
|
const shown = items.length > limit ? items.slice(-limit) : items
|
|
377
538
|
const omitted = items.length - shown.length
|
|
378
|
-
lines.push(`当前模型上下文中共 ${items.length}
|
|
539
|
+
lines.push(`当前模型上下文中共 ${items.length} 条可管理消息,估算占用约 ${totalTokens.toLocaleString('en-US')} tokens${omitted > 0 ? `,仅显示最近 ${shown.length} 条` : ''}:`)
|
|
379
540
|
for (const item of shown) {
|
|
380
|
-
|
|
541
|
+
const tokensLabel = `≈${(item.tokens ?? 0).toLocaleString('en-US')} tok`
|
|
542
|
+
lines.push(`#${item.seq} [${item.role}] [${tokensLabel}] ${item.preview.length > 0 ? item.preview : '(空消息)'}`)
|
|
381
543
|
}
|
|
382
544
|
if (omitted > 0) lines.push(`(更早的 ${omitted} 条请在标题栏的“上下文管理”中查看。)`)
|
|
383
545
|
}
|
|
@@ -391,19 +553,28 @@ export function formatList(items, deleted = [], pending = [], limit = 30) {
|
|
|
391
553
|
lines.push('', `已删除 ${deleted.length} 条记录(restore 使用 #后的删除记录序号):`)
|
|
392
554
|
for (const record of deleted.slice(-20)) {
|
|
393
555
|
const first = record.items[0]
|
|
556
|
+
const recalled = Array.isArray(record.recall) ? record.recall : []
|
|
394
557
|
const summary = record.items.length === 1 && first !== undefined
|
|
395
558
|
? `${first.role} · ${first.preview.length > 0 ? first.preview : '(空消息)'}`
|
|
396
|
-
:
|
|
559
|
+
: record.items.length === 0 && recalled.length > 0
|
|
560
|
+
? `召回指针 · #${recalled[0].seq} ${recalled[0].role} · ${recalled[0].preview.length > 0 ? recalled[0].preview : '(空消息)'}`
|
|
561
|
+
: `删除组 · ${record.count} 条`
|
|
397
562
|
const note = record.restorable
|
|
398
563
|
? record.reason === 'appended' ? '恢复到末尾' : '恢复到原位置'
|
|
399
564
|
: '不可恢复'
|
|
400
|
-
|
|
565
|
+
// Name the original seqs so a user can pull the exact events back with
|
|
566
|
+
// session_event_read instead of guessing from the tombstone seq.
|
|
567
|
+
const recallNote = recalled.length > 0
|
|
568
|
+
? ` · 可召回 ${recalled.map((entry) => `#${entry.seq}`).join(',')}`
|
|
569
|
+
: ''
|
|
570
|
+
lines.push(`#${record.tombstoneSeq} ← ${summary}(${note}${recallNote})`)
|
|
401
571
|
}
|
|
402
572
|
}
|
|
403
573
|
lines.push('', '删除:/ctxmgr delete <序号,...>')
|
|
404
574
|
lines.push('整轮:/ctxmgr deleteturn <轮号,...>(list-turns 查看轮号)')
|
|
575
|
+
lines.push('清理:/ctxmgr clean <目标tokens>(自动挑选大体积工具/助手消息,保护用户消息与最近消息)')
|
|
405
576
|
lines.push('恢复:/ctxmgr restore <删除记录序号,...>(也可在标题栏的上下文管理弹窗中操作)')
|
|
406
|
-
lines.push('删除只会从后续模型请求的上下文中移除该消息,原始会话日志与聊天记录仍会保留。')
|
|
577
|
+
lines.push('删除只会从后续模型请求的上下文中移除该消息,原始会话日志与聊天记录仍会保留。token 数为启发式估算(4 字符/token),中文与 JSON 内容会明显低估。')
|
|
407
578
|
return lines.join('\n')
|
|
408
579
|
}
|
|
409
580
|
|
|
@@ -430,7 +601,7 @@ export function isTombstone(event) {
|
|
|
430
601
|
* @param events - current surface events, oldest first.
|
|
431
602
|
* @param bySeq - full-log index, kept for signature symmetry with the other
|
|
432
603
|
* surface projections.
|
|
433
|
-
* @returns turn descriptors: { turn, seqs, messages, preview }.
|
|
604
|
+
* @returns turn descriptors: { turn, seqs, messages, tokens, preview }.
|
|
434
605
|
*/
|
|
435
606
|
export function turnsFromSurface(events, bySeq = new Map()) {
|
|
436
607
|
const groups = new Map()
|
|
@@ -442,7 +613,7 @@ export function turnsFromSurface(events, bySeq = new Map()) {
|
|
|
442
613
|
const message = messageOf(event)
|
|
443
614
|
const role = roleOf(event)
|
|
444
615
|
const preview = previewOf(message)
|
|
445
|
-
const group = groups.get(turn) ?? { turn, seqs: [], messages: [] }
|
|
616
|
+
const group = groups.get(turn) ?? { turn, seqs: [], messages: [], tokens: 0 }
|
|
446
617
|
group.seqs.push(event.seq)
|
|
447
618
|
group.messages.push({ seq: event.seq, role, preview })
|
|
448
619
|
groups.set(turn, group)
|
|
@@ -454,6 +625,94 @@ export function turnsFromSurface(events, bySeq = new Map()) {
|
|
|
454
625
|
return [...groups.values()].sort((a, b) => a.turn - b.turn)
|
|
455
626
|
}
|
|
456
627
|
|
|
628
|
+
/**
|
|
629
|
+
* Attach per-turn estimated token totals to turn descriptors.
|
|
630
|
+
* @param turns - descriptors from {@link turnsFromSurface}.
|
|
631
|
+
* @param items - display items from {@link itemsFromSurface} (tokens required);
|
|
632
|
+
* each message is attributed to exactly one turn.
|
|
633
|
+
*/
|
|
634
|
+
export function addTurnTokens(turns, items) {
|
|
635
|
+
const byTurn = new Map()
|
|
636
|
+
for (const item of items) byTurn.set(item.turn, (byTurn.get(item.turn) ?? 0) + (item.tokens ?? 0))
|
|
637
|
+
for (const turn of turns) turn.tokens = byTurn.get(turn.turn) ?? 0
|
|
638
|
+
return turns
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/**
|
|
642
|
+
* Ledger entries an undo request could mean, most specific match first.
|
|
643
|
+
*
|
|
644
|
+
* Undo reuses the restore path, so a batch qualifies whenever it recorded at
|
|
645
|
+
* least one tombstone and was either applied or durably queued. A full batch id
|
|
646
|
+
* wins outright; otherwise the id is treated as a prefix, and the caller must
|
|
647
|
+
* refuse an ambiguous prefix rather than silently undoing a guess.
|
|
648
|
+
* @param batches - ledger entries from the Host's batch scan, in log order.
|
|
649
|
+
* @param batchId - optional full id or prefix.
|
|
650
|
+
* @returns every qualifying entry matching the id (all of them when omitted).
|
|
651
|
+
*/
|
|
652
|
+
export function matchUndoBatches(batches, batchId = undefined) {
|
|
653
|
+
if (!Array.isArray(batches)) return []
|
|
654
|
+
const eligible = batches.filter((entry) => entry !== null && typeof entry === 'object'
|
|
655
|
+
&& entry.op !== 'undo'
|
|
656
|
+
&& Array.isArray(entry.tombstoneSeqs) && entry.tombstoneSeqs.length > 0
|
|
657
|
+
&& (entry.result === 'applied' || entry.result === 'queued'))
|
|
658
|
+
if (typeof batchId !== 'string' || batchId.length === 0) return eligible
|
|
659
|
+
const exact = eligible.filter((entry) => entry.batchId === batchId)
|
|
660
|
+
if (exact.length > 0) return exact
|
|
661
|
+
return eligible.filter((entry) => typeof entry.batchId === 'string'
|
|
662
|
+
&& entry.batchId.startsWith(batchId))
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Choose the batch an undo request targets: a named batch (id or unambiguous
|
|
667
|
+
* prefix), or the most recent batch that still has tombstones worth restoring.
|
|
668
|
+
* @param batches - ledger entries from the Host's batch scan, in log order.
|
|
669
|
+
* @param batchId - optional full id or unambiguous prefix.
|
|
670
|
+
* @returns the chosen ledger entry, or undefined when nothing qualifies.
|
|
671
|
+
*/
|
|
672
|
+
export function pickUndoBatch(batches, batchId = undefined) {
|
|
673
|
+
const matches = matchUndoBatches(batches, batchId)
|
|
674
|
+
if (matches.length === 0) return undefined
|
|
675
|
+
if (typeof batchId === 'string' && batchId.length > 0) {
|
|
676
|
+
return matches.length === 1 ? matches[0] : undefined
|
|
677
|
+
}
|
|
678
|
+
return matches[matches.length - 1]
|
|
679
|
+
}
|
|
680
|
+
|
|
681
|
+
/** Human-readable audit trail for the batch ledger. */
|
|
682
|
+
export function formatBatches(batches, limit = 20) {
|
|
683
|
+
if (!Array.isArray(batches) || batches.length === 0) {
|
|
684
|
+
return [
|
|
685
|
+
'还没有操作台账:每次删除、整轮删除或按预算清理都会记一条。',
|
|
686
|
+
'',
|
|
687
|
+
'撤销最近一次:/ctxmgr undo-batch(有台账后可用)',
|
|
688
|
+
].join('\n')
|
|
689
|
+
}
|
|
690
|
+
// Clamp so limit=0 cannot accidentally mean "show everything".
|
|
691
|
+
const safeLimit = Math.max(1, Number.isSafeInteger(limit) ? limit : 20)
|
|
692
|
+
const shown = batches.length > safeLimit ? batches.slice(-safeLimit) : batches
|
|
693
|
+
const lines = [`操作台账(共 ${batches.length} 条,显示最近 ${shown.length} 条):`]
|
|
694
|
+
for (const entry of shown) {
|
|
695
|
+
const short = typeof entry.batchId === 'string' ? entry.batchId.slice(0, 8) : '未知'
|
|
696
|
+
const tokens = (Number.isSafeInteger(entry.estimatedFreedTokens) ? entry.estimatedFreedTokens : 0)
|
|
697
|
+
.toLocaleString('en-US')
|
|
698
|
+
const result = entry.result === 'applied'
|
|
699
|
+
? '成功'
|
|
700
|
+
: entry.result === 'queued'
|
|
701
|
+
? '排队中'
|
|
702
|
+
: entry.result === 'failed' ? '失败' : '跳过'
|
|
703
|
+
// Prefer the message count when the Host recorded it: one batch can remove
|
|
704
|
+
// more messages than it names as targets (a tool group travels together).
|
|
705
|
+
const count = Number.isSafeInteger(entry.count) && entry.count > 0
|
|
706
|
+
? entry.count
|
|
707
|
+
: Array.isArray(entry.seqs) ? entry.seqs.length : 0
|
|
708
|
+
const reason = typeof entry.reason === 'string' && entry.reason.length > 0 ? `(${entry.reason})` : ''
|
|
709
|
+
lines.push(`#${entry.recordSeq} ${short} · ${entry.op} · ${count} 条消息 · ≈${tokens} tok · ${result}${reason}`)
|
|
710
|
+
}
|
|
711
|
+
lines.push('', '撤销最近一次:/ctxmgr undo-batch',
|
|
712
|
+
'撤销指定批次:/ctxmgr undo-batch <batchId 前几位>(台账里 “·” 前的 8 位)')
|
|
713
|
+
lines.push('台账与墓碑都写在会话日志里,只增不改,重启后仍可查。')
|
|
714
|
+
return lines.join('\n')
|
|
715
|
+
}
|
|
457
716
|
/** Human-readable turn listing for a command or tool result. */
|
|
458
717
|
export function formatTurns(turns, limit = 50) {
|
|
459
718
|
if (turns.length === 0) return '当前上下文中没有可删除的对话轮。'
|
|
@@ -461,8 +720,9 @@ export function formatTurns(turns, limit = 50) {
|
|
|
461
720
|
const omitted = turns.length - shown.length
|
|
462
721
|
const lines = [`当前上下文中共 ${turns.length} 轮对话${omitted > 0 ? `,仅显示最近 ${shown.length} 轮` : ''}:`]
|
|
463
722
|
for (const turn of shown) {
|
|
464
|
-
const mark = turn.inProgress ? '
|
|
465
|
-
|
|
723
|
+
const mark = turn.inProgress ? '(进行中,删除将在下一次请求生效)' : ''
|
|
724
|
+
const tokensLabel = ` · ≈${(turn.tokens ?? 0).toLocaleString('en-US')} tok`
|
|
725
|
+
lines.push(`T${turn.turn} · ${turn.preview.length > 0 ? turn.preview : '(无用户提问)'} · ${turn.messages.length} 条${tokensLabel}${mark}`)
|
|
466
726
|
}
|
|
467
727
|
lines.push('', '删除整轮:/ctxmgr deleteturn <轮号,...>')
|
|
468
728
|
lines.push('整轮删除会一并移除该轮的上下文注入;恢复仍按单条删除记录粒度进行。')
|
package/docs/DETAIL.md
CHANGED
|
@@ -4,3 +4,20 @@
|
|
|
4
4
|
- Drop noise: `/ctxmgr list` to find the indexes, `/ctxmgr delete 12,13,14` to clear error logs and trial-and-error instructions entry by entry.
|
|
5
5
|
- Forget superseded conclusions: delete the turns that hold plans which were later overturned, so the model stops citing them.
|
|
6
6
|
- Honest limit: this only removes content from the model context; the raw session log and chat transcript stay in the local session file, and this plugin is not an eraser.
|
|
7
|
+
|
|
8
|
+
- Token estimates: the `≈N tok` values and the total occupation come from `estimateMessageTokens` in `core.js`, a heuristic priced like DSH's `dsh-token-meter` (4 characters ≈ 1 token, +4 per content block, +4 role overhead per message). The Host prefers `ctx.tokenMeter.measure()` node pricing and falls back to the local heuristic when no token meter is injected.
|
|
9
|
+
- These are estimates, not exact usage: Chinese text and JSON are markedly underestimated, so the real saving is usually larger than the reported figure.
|
|
10
|
+
- Budget clean-up: `/ctxmgr clean 60000` (tool: `context_manager` action `clean`) sorts `tool` / `assistant` candidates by estimated tokens descending and deletes until the budget is met. User and context messages are never eligible, the most recent 3 messages are protected by default, candidates below 100 tokens are skipped, and deletion reuses the same tombstone + durable queue pipeline, so it stays restorable.
|
|
11
|
+
|
|
12
|
+
- Batch audit: every delete, whole-turn delete and clean mints a `batchId`, stored in the tombstone `source` as `{ kind: 'context-manager', batchId: '<uuid>' }`.
|
|
13
|
+
- `kind` stays the only marker, so tombstones written before batch ids are still recognized and restored.
|
|
14
|
+
- Ledger: each operation appends one `plugin:context-manager/batch` record to the session log — `batchId`, `op` (`delete` / `delete-turn` / `clean` / `undo`), `seqs`, `tombstoneSeqs`, `estimatedFreedTokens`, outcome (`applied` / `queued` / `skipped` / `failed`) and `reason`.
|
|
15
|
+
- The ledger is append-only, persists with the session log, survives restarts and writes no external files.
|
|
16
|
+
- Undo: `/ctxmgr batches` lists the ledger; `/ctxmgr undo-batch [batchId]` undoes the latest batch or a specific one by id prefix (tool: `action=batches` / `action=undo-batch`).
|
|
17
|
+
- Undo reuses the existing restore path (durable queue + idempotent ack) rather than a second mechanism, and leaves its own `op=undo` ledger entry.
|
|
18
|
+
|
|
19
|
+
- Recall pointers: each tombstone `source` is `{ kind: 'context-manager', batchId, recall }`, where `recall` holds at most 8 `{ seq, role, preview }` entries (`RECALL_MAX_ENTRIES = 8`) with previews truncated to 80 characters (`RECALL_PREVIEW_LIMIT = 80`). It stores seq, role and a one-line preview — never the full message text — and the tombstone content stays an empty array, because a tombstone must project as an empty message.
|
|
20
|
+
- Retrieving the original: the recalled `seq` is the session seq of the original event. The read-only tools of `@deepseek-ai/dsh-tool-session-query` (`session_search`, `session_event_search`, `session_trace`, `session_event_trace`, `session_event_read`) can search that session by keyword or read the complete unredacted event as JSON; searches exclude the caller's own session and are authorized by the workspace `cwd`. Deletion is therefore unloading from the main context into a searchable archive, not erasure — versus `dsh-context-redline` (migrates away) and compaction plugins (summarize away).
|
|
21
|
+
- Local compaction: `/ctxmgr compact <start> <end>` (tool: `context_manager` action `compact` with `start` / `end`) calls the official `ctx.compaction.compactRegion(start, end, agentCtx, signal)`. `start` / `end` are surface position seqs, not numeric order, and both edges must be tool-pair balanced or the engine reports an unbalanced region.
|
|
22
|
+
- It only compacts the user selection — no global threshold compaction — and requires a loaded compaction backend (e.g. `dsh-compaction-basic`); without one the plugin answers with a clear Chinese hint and records the failure in the ledger. The service is obtained optionally via `ctx.get('compaction')`, so the plugin does not hard-depend on it, and both success and failure append an `op: 'compact'` ledger entry with the shadowed node count and tokens. Unlike delete / clean, which unload restorably with no summary, compact replaces the range with one official summary that cannot be restored per message, while the raw session log is still append-only.
|
|
23
|
+
- Tombstones written before `batchId` / `recall` keep working unchanged, and the dialog's deleted rows fall back to 可召回 #seq · 摘要 when the original text is no longer on the surface.
|
package/docs/DETAIL.zh.md
CHANGED
|
@@ -4,3 +4,20 @@
|
|
|
4
4
|
- 清除废物信息:`/ctxmgr list` 找到序号,`/ctxmgr delete 12,13,14` 按条清掉报错日志与试错指令。
|
|
5
5
|
- 让模型忘掉过时的中间结论:删掉被推翻的方案所在的轮次,避免它反复引用旧结论。
|
|
6
6
|
- 止损边界:只移出模型上下文,原始会话日志与聊天记录仍留在本地会话文件里,本插件不是擦除工具。
|
|
7
|
+
|
|
8
|
+
- token 估算:列表里的 `≈N tok` 与总占用来自 `core.js` 的 `estimateMessageTokens`,定价与 DSH 官方 `dsh-token-meter` 同源——4 字符 ≈ 1 token、每个内容块 +4、每条消息角色开销 +4。Host 有 token-meter 时优先用 `ctx.tokenMeter.measure()` 的节点定价,否则回退本地启发式。
|
|
9
|
+
- 这只是估算:中文与 JSON 明显被低估,实际省下的 token 通常多于显示值。
|
|
10
|
+
- 按预算清理:`/ctxmgr clean 60000`(工具等价 `context_manager` + `clean`)把 `tool` / `assistant` 候选按估算 token 降序删除,达到预算即停止。用户消息与上下文消息永不入选,默认保护最近 3 条,候选默认 ≥100 tokens;删除复用同一套墓碑与持久队列,仍可恢复。
|
|
11
|
+
|
|
12
|
+
- 批次审计:每次删除、整轮删除与按预算清理都会生成 `batchId`,写进墓碑消息的 `source`:`{ kind: 'context-manager', batchId: '<uuid>' }`。
|
|
13
|
+
- `kind` 仍是唯一标记,因此旧墓碑没有 `batchId` 也照常识别与恢复。
|
|
14
|
+
- 台账:每次操作在会话日志追加一条 `plugin:context-manager/batch` 记录——`batchId`、`op`(`delete` / `delete-turn` / `clean` / `undo`)、`seqs`、`tombstoneSeqs`、`estimatedFreedTokens`、结果(`applied` / `queued` / `skipped` / `failed`)与 `reason`。
|
|
15
|
+
- 台账只增不改,随会话日志持久化,重启后仍可查,不写外部文件。
|
|
16
|
+
- 撤销:`/ctxmgr batches` 查看台账;`/ctxmgr undo-batch [batchId]` 撤销最近一次或按 batchId 前几位撤销指定批次(工具 `action=batches` / `action=undo-batch`)。
|
|
17
|
+
- 撤销复用既有 restore 路径(持久队列 + ack 幂等),不是新的恢复机制,并会留下自己的 `op=undo` 台账记录。
|
|
18
|
+
|
|
19
|
+
- 召回指针:每条墓碑的 `source` 是 `{ kind: 'context-manager', batchId, recall }`,其中 `recall` 最多 8 条 `{ seq, role, preview }`(`RECALL_MAX_ENTRIES = 8`),`preview` 截断到 80 字符(`RECALL_PREVIEW_LIMIT = 80`)。只存 seq、角色与一行摘要,不写消息全文;墓碑的 content 仍为空数组——墓碑必须投影成空消息。老墓碑没有这两个字段也照常工作。
|
|
20
|
+
- 取回原文:`recall` 里的 `seq` 就是原始事件的会话序号,可用 `@deepseek-ai/dsh-tool-session-query` 的只读工具 `session_search` / `session_event_search` / `session_trace` / `session_event_trace` / `session_event_read` 按关键字检索或读取完整未删节事件(JSON);搜索会排除调用方会话、按工作区 `cwd` 授权。所以「删除」是从主上下文卸载到可检索存档,不是擦除——与 `dsh-context-redline`(迁移走)和压缩插件(摘要掉)区分开。
|
|
21
|
+
- 局部压缩:`/ctxmgr compact <起序号> <止序号>`(工具 `context_manager` + `action=compact`,参数 `start` / `end`)调用官方 `ctx.compaction.compactRegion(start, end, agentCtx, signal)`。start / end 是表面位置序号,不是数值大小顺序,两端必须工具配对平衡,否则引擎报 unbalanced。
|
|
22
|
+
- 它只作用于用户选区,不做全局阈值压缩;需要环境加载压缩后端(如 `dsh-compaction-basic`),没加载时给明确中文提示并把失败写进台账。服务通过 `ctx.get('compaction')` 可选获取,插件不硬依赖;成功与失败都会在台账留一条 `op: 'compact'` 记录(含被遮蔽的节点数与 tokens)。与 delete / clean 的区别:delete / clean 是移出上下文、可恢复且无摘要,compact 是把一段换成一条官方摘要、不能按消息恢复,但原始会话日志仍只增不改。
|
|
23
|
+
- 旧墓碑没有 `batchId` / `recall` 也照常工作;弹窗「已删除」行在拿不到原文时,用召回指针显示「可召回 #seq · 摘要」。
|