dsh-context-manager 0.0.0-stage → 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/core.js ADDED
@@ -0,0 +1,730 @@
1
+ /**
2
+ * Pure helpers shared by the Host half of the message manager.
3
+ *
4
+ * The session surface is the model-visible projection of the append-only log.
5
+ * Deleting one message means appending a surface replacement whose derived
6
+ * message is empty, so later model requests no longer see the shadowed node
7
+ * while the raw log and the Chat transcript stay intact.
8
+ */
9
+
10
+ /** Surface event types that participate in the model-visible surface. */
11
+ export const SURFACE_TYPES = new Set([
12
+ 'system/message',
13
+ 'developer/message',
14
+ 'user/message',
15
+ 'assistant/message',
16
+ 'tool/result',
17
+ ])
18
+
19
+ /** Message carried by one surface event, or undefined for non-surface events. */
20
+ export function messageOf(event) {
21
+ if (event === undefined || event === null) return undefined
22
+ if (event.type === 'user/message') return event.data
23
+ return event.data?.message
24
+ }
25
+
26
+ /** Stable role label used by the Host listing. */
27
+ export function roleOf(event) {
28
+ switch (event.type) {
29
+ case 'user/message':
30
+ return event.data?.source?.kind === 'user' ? 'user' : 'context'
31
+ case 'assistant/message':
32
+ return 'assistant'
33
+ case 'tool/result':
34
+ return 'tool'
35
+ case 'developer/message':
36
+ return 'context'
37
+ default:
38
+ return 'system'
39
+ }
40
+ }
41
+
42
+ /** Tool-call ids requested by one assistant message. */
43
+ export function toolCallIdsOf(event) {
44
+ if (event.type !== 'assistant/message') return []
45
+ const content = event.data?.message?.content
46
+ if (!Array.isArray(content)) return []
47
+ const ids = []
48
+ for (const block of content) {
49
+ if (block?.type === 'tool-call' && typeof block.id === 'string') ids.push(block.id)
50
+ }
51
+ return ids
52
+ }
53
+
54
+ /** Whether one message event carries a tool-addition/removal block. */
55
+ export function hasToolChange(event) {
56
+ const content = event?.data?.message?.content
57
+ return Array.isArray(content)
58
+ && content.some((block) => block?.type === 'tool-addition' || block?.type === 'tool-removal')
59
+ }
60
+
61
+ /** Collapse one message's content blocks into a one-line preview. */
62
+ export function previewOf(message, limit = 160) {
63
+ const content = Array.isArray(message?.content) ? message.content : []
64
+ const parts = []
65
+ for (const block of content) {
66
+ if (block === null || typeof block !== 'object') continue
67
+ switch (block.type) {
68
+ case 'text':
69
+ if (typeof block.text === 'string') parts.push(block.text)
70
+ break
71
+ case 'tool-call':
72
+ parts.push(`tool:${typeof block.name === 'string' ? block.name : '?'}`)
73
+ break
74
+ case 'image':
75
+ parts.push('[image]')
76
+ break
77
+ case 'file':
78
+ parts.push(`[file${block.attachment?.name ? `: ${block.attachment.name}` : ''}]`)
79
+ break
80
+ case 'tool-addition':
81
+ parts.push(`+${String(block.toolName)}`)
82
+ break
83
+ case 'tool-removal':
84
+ parts.push(`-${String(block.toolName)}`)
85
+ break
86
+ case 'reasoning':
87
+ break
88
+ default:
89
+ break
90
+ }
91
+ }
92
+ const text = parts.join(' ').replace(/\s+/g, ' ').trim()
93
+ if (text.length === 0) return ''
94
+ return text.length > limit ? `${text.slice(0, limit - 1)}…` : text
95
+ }
96
+
97
+ /** Fold raw log events into the current surface sequence list. */
98
+ export function foldSurface(events) {
99
+ const nodes = []
100
+ const bySeq = new Map()
101
+ let uncertain = false
102
+ for (const event of events) {
103
+ if (event === null || typeof event !== 'object') continue
104
+ if (!Number.isSafeInteger(event.seq)) continue // a log object without a seq cannot be indexed
105
+ bySeq.set(event.seq, event)
106
+ if (!SURFACE_TYPES.has(event.type)) continue
107
+ const op = event.surfaceOp
108
+ if (op === undefined) continue
109
+ if (op === 'append') {
110
+ nodes.push(event.seq)
111
+ continue
112
+ }
113
+ if (op !== null && typeof op === 'object' && op.op === 'replace') {
114
+ const start = nodes.indexOf(op.startSeq)
115
+ const end = nodes.indexOf(op.endSeq)
116
+ if (start >= 0 && end >= start) nodes.splice(start, end - start + 1, event.seq)
117
+ else uncertain = true
118
+ }
119
+ }
120
+ return { nodes, bySeq, uncertain }
121
+ }
122
+
123
+ /** Whether a surface event should appear in the management list. */
124
+ function visibleSurfaceEvent(event) {
125
+ if (event.type === 'system/message') return false
126
+ const message = messageOf(event)
127
+ if (message === undefined) return false
128
+ const content = message.content
129
+ if ((event.type === 'developer/message' || event.type === 'assistant/message')
130
+ && (!Array.isArray(content) || content.length === 0)) return false
131
+ return true
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
+
180
+ /**
181
+ * Project current surface events into display items, oldest first.
182
+ * `events` is either a complete surface snapshot or the folded output of
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.
186
+ */
187
+ export function itemsFromSurface(events, tokensBySeq = undefined) {
188
+ const items = []
189
+ let currentTurn = 0
190
+ let currentStep = 0
191
+ for (let index = 0; index < events.length; index += 1) {
192
+ const event = events[index]
193
+ if (typeof event?.data?.turn === 'number' && Number.isSafeInteger(event.data.turn)) currentTurn = event.data.turn
194
+ if (typeof event?.data?.step === 'number' && Number.isSafeInteger(event.data.step)) currentStep = event.data.step
195
+ if (!visibleSurfaceEvent(event)) continue
196
+ const message = messageOf(event)
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')
203
+ const callIds = toolCallIdsOf(event)
204
+ let turn = Number.isSafeInteger(event.data?.turn) ? event.data.turn : undefined
205
+ let step = Number.isSafeInteger(event.data?.step) ? event.data.step : undefined
206
+ if (turn === undefined || step === undefined) {
207
+ for (let next = index + 1; next < events.length; next += 1) {
208
+ const data = events[next]?.data
209
+ if (Number.isSafeInteger(data?.turn) && Number.isSafeInteger(data?.step)) {
210
+ turn = data.turn
211
+ step = data.step
212
+ break
213
+ }
214
+ }
215
+ }
216
+ items.push({
217
+ seq: event.seq,
218
+ time: event.time,
219
+ type: event.type,
220
+ role: roleOf(event),
221
+ turn: turn ?? currentTurn,
222
+ step: step ?? currentStep,
223
+ messageId: typeof message.id === 'string' ? message.id : undefined,
224
+ preview: previewOf(message),
225
+ callIds,
226
+ toolCallId: event.type === 'tool/result' && typeof message.toolCallId === 'string' ? message.toolCallId : undefined,
227
+ blocks: content.length,
228
+ tokens,
229
+ })
230
+ }
231
+ return items
232
+ }
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
+
275
+ /** Boundary turn/step for a tombstone: prefer the deleted nodes, then neighbors. */
276
+ export function boundaryFor(events, indices) {
277
+ const valid = (data) => Number.isSafeInteger(data?.turn) && Number.isSafeInteger(data?.step)
278
+ for (const index of indices) {
279
+ const data = events[index]?.data
280
+ if (valid(data)) return { turn: data.turn, step: data.step }
281
+ }
282
+ const first = Math.min(...indices)
283
+ for (let index = first + 1; index < events.length; index += 1) {
284
+ const data = events[index]?.data
285
+ if (valid(data)) return { turn: data.turn, step: data.step }
286
+ }
287
+ for (let index = first - 1; index >= 0; index -= 1) {
288
+ const data = events[index]?.data
289
+ if (valid(data)) return { turn: data.turn, step: data.step }
290
+ }
291
+ return { turn: 0, step: 0 }
292
+ }
293
+
294
+ /**
295
+ * Plan one message deletion over a complete current surface.
296
+ *
297
+ * Deleting a tool result also removes its owning assistant message and every
298
+ * sibling result of that message, and deleting an assistant message removes its
299
+ * tool results, so the derived history never keeps a tool call without an answer
300
+ * (or the reverse). The returned runs are contiguous surface ranges, in surface
301
+ * order, each replaceable by a single tombstone event.
302
+ */
303
+ export function planDeletion(events, targetSeq) {
304
+ const targetIndex = events.findIndex((event) => event.seq === targetSeq)
305
+ if (targetIndex < 0) return { ok: false, reason: 'not-found' }
306
+ const target = events[targetIndex]
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' }
311
+ if (target.type === 'tool/result' && typeof target.data?.message?.toolCallId !== 'string') {
312
+ return { ok: false, reason: 'unsupported' }
313
+ }
314
+
315
+ const chosen = new Set([targetIndex])
316
+ const addAssistantGroup = (index) => {
317
+ chosen.add(index)
318
+ const callIds = new Set(toolCallIdsOf(events[index]))
319
+ if (callIds.size === 0) return
320
+ for (let i = 0; i < events.length; i += 1) {
321
+ const event = events[i]
322
+ if (event.type !== 'tool/result') continue
323
+ if (callIds.has(event.data?.message?.toolCallId)) chosen.add(i)
324
+ }
325
+ }
326
+
327
+ if (target.type === 'assistant/message') {
328
+ addAssistantGroup(targetIndex)
329
+ } else if (target.type === 'tool/result') {
330
+ const callId = target.data.message.toolCallId
331
+ let ownerFound = false
332
+ for (let i = 0; i < events.length; i += 1) {
333
+ const event = events[i]
334
+ if (event.type !== 'assistant/message') continue
335
+ if (!toolCallIdsOf(event).includes(callId)) continue
336
+ ownerFound = true
337
+ addAssistantGroup(i)
338
+ }
339
+ if (!ownerFound) chosen.add(targetIndex)
340
+ }
341
+
342
+ const indices = [...chosen].sort((a, b) => a - b)
343
+ const runs = []
344
+ let run = null
345
+ for (const index of indices) {
346
+ if (run !== null && index === run.endIndex + 1) {
347
+ run.endIndex = index
348
+ run.seqs.push(events[index].seq)
349
+ continue
350
+ }
351
+ run = { startIndex: index, endIndex: index, seqs: [events[index].seq] }
352
+ runs.push(run)
353
+ }
354
+ return {
355
+ ok: true,
356
+ target,
357
+ indices,
358
+ runs: runs.map((entry) => ({
359
+ startSeq: entry.seqs[0],
360
+ endSeq: entry.seqs[entry.seqs.length - 1],
361
+ seqs: entry.seqs,
362
+ })),
363
+ count: indices.length,
364
+ targetSeq,
365
+ }
366
+ }
367
+
368
+ /** Source kind this plugin writes for its invisible tombstones. */
369
+ export const TOMBSTONE_KIND = 'context-manager'
370
+ /** Source kinds older releases wrote; their tombstones stay restorable. */
371
+ export const LEGACY_TOMBSTONE_KINDS = Object.freeze(['message-manager'])
372
+
373
+ /** Whether one message source kind belongs to this plugin, current or legacy. */
374
+ export function isTombstoneKind(kind) {
375
+ return kind === TOMBSTONE_KIND || LEGACY_TOMBSTONE_KINDS.includes(kind)
376
+ }
377
+
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
+ }
435
+ return {
436
+ turn,
437
+ step,
438
+ message: {
439
+ id,
440
+ role: 'developer',
441
+ content: [],
442
+ source,
443
+ },
444
+ }
445
+ }
446
+
447
+ /** Parse a `restored-assistant-<tombstoneSeq>-…` marker id back to its tombstone seq. */
448
+ export function parseRestoredTombstoneId(id) {
449
+ if (typeof id !== 'string' || !id.startsWith('restored-assistant-')) return undefined
450
+ const rest = id.slice('restored-assistant-'.length)
451
+ const dash = rest.indexOf('-')
452
+ if (dash <= 0) return undefined
453
+ const seq = Number(rest.slice(0, dash))
454
+ return Number.isSafeInteger(seq) ? seq : undefined
455
+ }
456
+
457
+ /**
458
+ * Classify the deleted records currently reachable from the surface.
459
+ *
460
+ * Mirrors the restore planner's capability boundaries without throwing: a
461
+ * record is restorable when the same content would pass {@code planRestore}.
462
+ * @param events - current surface events, oldest first (tombstones included).
463
+ * @param bySeq - full-log index used to recover replaced originals.
464
+ * @returns deleted-record descriptors in surface order.
465
+ */
466
+ export function deletedFromSurface(events, bySeq) {
467
+ const restored = new Set()
468
+ for (const event of events) {
469
+ if (event === undefined || event === null || event.type !== 'assistant/message') continue
470
+ const seq = parseRestoredTombstoneId(event.data?.message?.id)
471
+ if (seq !== undefined) restored.add(seq)
472
+ }
473
+ const records = []
474
+ for (const event of events) {
475
+ if (event === undefined || event === null || event.type !== 'developer/message') continue
476
+ if (!isTombstoneKind(event.data?.message?.source?.kind)) continue
477
+ const op = event.surfaceOp
478
+ if (op === null || typeof op !== 'object' || op.op !== 'replace') continue
479
+ if (restored.has(event.seq)) continue
480
+ const targets = Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []
481
+ const originals = targets.map((seq) => bySeq.get(seq))
482
+ const known = originals.filter((original) => original !== undefined)
483
+ const missing = targets.length - known.length
484
+ const assistant = known.find((original) => original.type === 'assistant/message')
485
+ const calls = assistant === undefined ? [] : toolCallIdsOf(assistant)
486
+ const results = known.filter((original) => original.type === 'tool/result')
487
+ let restorable = false
488
+ let reason = ''
489
+ if (targets.length === 1) {
490
+ const original = known[0]
491
+ if (original === undefined) restorable = true
492
+ else if (original.type === 'user/message') restorable = true
493
+ else if (original.type === 'developer/message' && !hasToolChange(original)) restorable = true
494
+ else if (original.type === 'assistant/message' && calls.length === 0) {
495
+ restorable = original.data?.message?.content?.length > 0
496
+ reason = 'appended'
497
+ } else if (original.type === 'tool/result') reason = 'tool'
498
+ else reason = 'group'
499
+ } else if (assistant !== undefined && calls.length > 0 && missing === 0
500
+ && results.length === targets.length - 1) {
501
+ const callIds = new Set(calls)
502
+ const resultIds = new Set(results.map((original) => original.data?.message?.toolCallId))
503
+ restorable = callIds.size === resultIds.size && [...callIds].every((id) => resultIds.has(id))
504
+ reason = restorable ? 'appended' : 'group'
505
+ } else {
506
+ reason = missing > 0 ? 'missing' : 'group'
507
+ }
508
+ records.push({
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
+ : [],
516
+ targetSeqs: [...targets],
517
+ count: targets.length,
518
+ items: known.map((original) => ({
519
+ seq: original.seq,
520
+ role: roleOf(original),
521
+ preview: previewOf(original.type === 'user/message' ? original.data : original.data?.message),
522
+ })),
523
+ restorable,
524
+ reason,
525
+ })
526
+ }
527
+ return records
528
+ }
529
+
530
+ /** Human-readable Host listing for a command or tool result. */
531
+ export function formatList(items, deleted = [], pending = [], limit = 30) {
532
+ const lines = []
533
+ const totalTokens = items.reduce((total, item) => total + (item.tokens ?? 0), 0)
534
+ if (items.length === 0) {
535
+ lines.push('当前模型上下文中没有可管理的消息。')
536
+ } else {
537
+ const shown = items.length > limit ? items.slice(-limit) : items
538
+ const omitted = items.length - shown.length
539
+ lines.push(`当前模型上下文中共 ${items.length} 条可管理消息,估算占用约 ${totalTokens.toLocaleString('en-US')} tokens${omitted > 0 ? `,仅显示最近 ${shown.length} 条` : ''}:`)
540
+ for (const item of shown) {
541
+ const tokensLabel = `≈${(item.tokens ?? 0).toLocaleString('en-US')} tok`
542
+ lines.push(`#${item.seq} [${item.role}] [${tokensLabel}] ${item.preview.length > 0 ? item.preview : '(空消息)'}`)
543
+ }
544
+ if (omitted > 0) lines.push(`(更早的 ${omitted} 条请在标题栏的“上下文管理”中查看。)`)
545
+ }
546
+ if (pending.length > 0) {
547
+ lines.push('', `排队中(下一回合生效,共 ${pending.length} 项):`)
548
+ for (const entry of pending) {
549
+ lines.push(`#${entry.recordSeq} ${entry.op} #${entry.targetSeq}`)
550
+ }
551
+ }
552
+ if (deleted.length > 0) {
553
+ lines.push('', `已删除 ${deleted.length} 条记录(restore 使用 #后的删除记录序号):`)
554
+ for (const record of deleted.slice(-20)) {
555
+ const first = record.items[0]
556
+ const recalled = Array.isArray(record.recall) ? record.recall : []
557
+ const summary = record.items.length === 1 && first !== undefined
558
+ ? `${first.role} · ${first.preview.length > 0 ? first.preview : '(空消息)'}`
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} 条`
562
+ const note = record.restorable
563
+ ? record.reason === 'appended' ? '恢复到末尾' : '恢复到原位置'
564
+ : '不可恢复'
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})`)
571
+ }
572
+ }
573
+ lines.push('', '删除:/ctxmgr delete <序号,...>')
574
+ lines.push('整轮:/ctxmgr deleteturn <轮号,...>(list-turns 查看轮号)')
575
+ lines.push('清理:/ctxmgr clean <目标tokens>(自动挑选大体积工具/助手消息,保护用户消息与最近消息)')
576
+ lines.push('恢复:/ctxmgr restore <删除记录序号,...>(也可在标题栏的上下文管理弹窗中操作)')
577
+ lines.push('删除只会从后续模型请求的上下文中移除该消息,原始会话日志与聊天记录仍会保留。token 数为启发式估算(4 字符/token),中文与 JSON 内容会明显低估。')
578
+ return lines.join('\n')
579
+ }
580
+
581
+ /** Whether one event is an empty context-manager tombstone, current or legacy kind. */
582
+ export function isTombstone(event) {
583
+ return event !== undefined
584
+ && event !== null
585
+ && event.type === 'developer/message'
586
+ && Array.isArray(event.data?.message?.content)
587
+ && event.data.message.content.length === 0
588
+ && isTombstoneKind(event.data?.message?.source?.kind)
589
+ && event.surfaceOp !== null
590
+ && typeof event.surfaceOp === 'object'
591
+ && event.surfaceOp.op === 'replace'
592
+ }
593
+
594
+ /**
595
+ * Group the surface's content nodes into conversation turns, oldest first.
596
+ *
597
+ * A node's turn comes from its own `data.turn`; a tombstone is invisible here
598
+ * (it derives no message), so a fully deleted turn disappears from the list.
599
+ * Injected context (runtime snapshots and reminders) carries the turn it was
600
+ * injected under and therefore joins that turn.
601
+ * @param events - current surface events, oldest first.
602
+ * @param bySeq - full-log index, kept for signature symmetry with the other
603
+ * surface projections.
604
+ * @returns turn descriptors: { turn, seqs, messages, tokens, preview }.
605
+ */
606
+ export function turnsFromSurface(events, bySeq = new Map()) {
607
+ const groups = new Map()
608
+ for (const event of events) {
609
+ if (event === undefined || event === null) continue
610
+ if (!visibleSurfaceEvent(event)) continue
611
+ const turn = Number.isSafeInteger(event.data?.turn) ? event.data.turn : undefined
612
+ if (!Number.isSafeInteger(turn)) continue
613
+ const message = messageOf(event)
614
+ const role = roleOf(event)
615
+ const preview = previewOf(message)
616
+ const group = groups.get(turn) ?? { turn, seqs: [], messages: [], tokens: 0 }
617
+ group.seqs.push(event.seq)
618
+ group.messages.push({ seq: event.seq, role, preview })
619
+ groups.set(turn, group)
620
+ }
621
+ for (const group of groups.values()) {
622
+ const own = group.messages.find((entry) => entry.role === 'user')
623
+ group.preview = (own ?? group.messages[0])?.preview ?? ''
624
+ }
625
+ return [...groups.values()].sort((a, b) => a.turn - b.turn)
626
+ }
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
+ }
716
+ /** Human-readable turn listing for a command or tool result. */
717
+ export function formatTurns(turns, limit = 50) {
718
+ if (turns.length === 0) return '当前上下文中没有可删除的对话轮。'
719
+ const shown = turns.length > limit ? turns.slice(-limit) : turns
720
+ const omitted = turns.length - shown.length
721
+ const lines = [`当前上下文中共 ${turns.length} 轮对话${omitted > 0 ? `,仅显示最近 ${shown.length} 轮` : ''}:`]
722
+ for (const turn of shown) {
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}`)
726
+ }
727
+ lines.push('', '删除整轮:/ctxmgr deleteturn <轮号,...>')
728
+ lines.push('整轮删除会一并移除该轮的上下文注入;恢复仍按单条删除记录粒度进行。')
729
+ return lines.join('\n')
730
+ }