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/CHANGELOG.md +75 -0
- package/LICENSE +21 -0
- package/README.md +368 -3
- package/client.js +1371 -0
- package/cordis.patch.yml +3 -0
- package/core.js +730 -0
- package/docs/DETAIL.md +23 -0
- package/docs/DETAIL.zh.md +23 -0
- package/docs/preview.svg +56 -0
- package/icon.svg +19 -0
- package/index.js +1330 -0
- package/locale/en.json +7 -0
- package/locale/zh.json +7 -0
- package/package.json +70 -6
package/index.js
ADDED
|
@@ -0,0 +1,1330 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Host half of the Session Context Manager.
|
|
3
|
+
*
|
|
4
|
+
* A surface replacement whose replacement event derives no model message is the
|
|
5
|
+
* supported way to remove one conversation entry from later model requests: the
|
|
6
|
+
* append-only Session log, its Chat transcript, and every audit surface keep the
|
|
7
|
+
* original record.
|
|
8
|
+
*
|
|
9
|
+
* Session format validation requires every `developer/message` to match an open
|
|
10
|
+
* turn and step, and a Session cannot append from inside its own `session/event`
|
|
11
|
+
* dispatch. A deletion or restore that cannot run safely right now is therefore
|
|
12
|
+
* recorded as a durable `plugin:context-manager/pending` record — plugin records
|
|
13
|
+
* append without an open turn/step and travel with the log across restarts —
|
|
14
|
+
* and replayed on the owning Agent's `agent/request` waterfall. That hook runs
|
|
15
|
+
* after `step/start` (so the step is open and appending is allowed) and before
|
|
16
|
+
* the request messages are derived, so the next request already reflects it.
|
|
17
|
+
* Every replay is idempotent: an applied record is acknowledged with a
|
|
18
|
+
* `plugin:context-manager/ack` record, and a replayed operation whose target
|
|
19
|
+
* vanished is acknowledged as skipped instead of being retried forever.
|
|
20
|
+
*
|
|
21
|
+
* Restore reverses a tombstone:
|
|
22
|
+
* - user/context: the tombstone is replaced by a copy of the original message,
|
|
23
|
+
* preserving its surface position;
|
|
24
|
+
* - assistant text: a copy is appended at the tail, because assistant messages
|
|
25
|
+
* cannot carry the source references a surface replacement requires;
|
|
26
|
+
* - assistant tool groups: the assistant message, its tool calls, and its tool
|
|
27
|
+
* results are appended as one valid lifecycle at the tail.
|
|
28
|
+
*/
|
|
29
|
+
import { randomUUID } from 'node:crypto'
|
|
30
|
+
import { join } from 'node:path'
|
|
31
|
+
import { pathToFileURL } from 'node:url'
|
|
32
|
+
import {
|
|
33
|
+
addTurnTokens,
|
|
34
|
+
buildRecall,
|
|
35
|
+
deletedFromSurface,
|
|
36
|
+
formatBatches,
|
|
37
|
+
matchUndoBatches,
|
|
38
|
+
pickUndoBatch,
|
|
39
|
+
foldSurface,
|
|
40
|
+
formatList,
|
|
41
|
+
formatTurns,
|
|
42
|
+
hasToolChange,
|
|
43
|
+
isTombstoneKind,
|
|
44
|
+
itemsFromSurface,
|
|
45
|
+
planClean,
|
|
46
|
+
planDeletion,
|
|
47
|
+
tombstoneData,
|
|
48
|
+
turnsFromSurface,
|
|
49
|
+
} from './core.js'
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Load the Session core the Host itself runs on.
|
|
53
|
+
*
|
|
54
|
+
* A profile-linked plugin cannot resolve `@deepseek-ai/*` by bare name: its
|
|
55
|
+
* realpath sits outside the profile, and the packaged desktop carries the core
|
|
56
|
+
* packages only inside the application asar. Try the bare specifier first (dev
|
|
57
|
+
* checkouts with a real node_modules), then anchor on the Host process's
|
|
58
|
+
* runtime directory — the packaged desktop Host starts with that directory as
|
|
59
|
+
* `process.argv[2]`, and importing the same file URL yields the same module
|
|
60
|
+
* instance the Host itself uses, so Session private-field brand checks pass.
|
|
61
|
+
*/
|
|
62
|
+
let sessionCore
|
|
63
|
+
try {
|
|
64
|
+
sessionCore = await import('@deepseek-ai/dsh-session')
|
|
65
|
+
} catch {
|
|
66
|
+
const runtimeDir = process.argv[2]
|
|
67
|
+
if (typeof runtimeDir !== 'string' || runtimeDir.length === 0) {
|
|
68
|
+
throw new Error('context-manager 无法加载 @deepseek-ai/dsh-session:裸导入失败,且当前进程不是携带运行时目录的桌面 Host。')
|
|
69
|
+
}
|
|
70
|
+
sessionCore = await import(pathToFileURL(join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh-session', 'lib', 'index.js')).href)
|
|
71
|
+
}
|
|
72
|
+
const { appendPluginRecord, pluginRecordOf } = sessionCore
|
|
73
|
+
|
|
74
|
+
export const name = 'context-manager'
|
|
75
|
+
|
|
76
|
+
export const inject = ['sessions', 'agents', 'commands', 'tools']
|
|
77
|
+
|
|
78
|
+
const RESTORED_PREFIX = 'restored-assistant-'
|
|
79
|
+
const PENDING_TYPE = 'plugin:context-manager/pending'
|
|
80
|
+
const ACK_TYPE = 'plugin:context-manager/ack'
|
|
81
|
+
/** Audit ledger: one record per user-visible batch operation. */
|
|
82
|
+
const BATCH_TYPE = 'plugin:context-manager/batch'
|
|
83
|
+
/** Queue record types older releases wrote; still applied after an upgrade. */
|
|
84
|
+
const LEGACY_PENDING_TYPES = ['plugin:message-manager/pending']
|
|
85
|
+
const LEGACY_ACK_TYPES = ['plugin:message-manager/ack']
|
|
86
|
+
/** Messages that mean a replayed operation already happened; ack as skipped. */
|
|
87
|
+
const IDEMPOTENT_MARKERS = ['已不在当前表面', '已经恢复', '已不在会话日志']
|
|
88
|
+
|
|
89
|
+
/** Resolve the live Session behind one command/tool agent. */
|
|
90
|
+
function liveSession(ctx, agent) {
|
|
91
|
+
if (agent === undefined || agent === null || typeof agent.id !== 'string') {
|
|
92
|
+
throw new Error('上下文管理需要一个会话作用域。')
|
|
93
|
+
}
|
|
94
|
+
const session = ctx.sessions.get(agent.id)
|
|
95
|
+
if (session === undefined) throw new Error('当前会话未处于运行状态,无法读取或修改消息上下文。')
|
|
96
|
+
return session
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Read the complete current model surface for one live Session. */
|
|
100
|
+
async function readSurfaceEvents(ctx, session) {
|
|
101
|
+
const query = ctx.get('sessionQuery')
|
|
102
|
+
if (query !== undefined && typeof query.readSurface === 'function') {
|
|
103
|
+
const snapshot = await query.readSurface(session.id)
|
|
104
|
+
return snapshot.events
|
|
105
|
+
}
|
|
106
|
+
const folded = foldSurface(session.snapshotEvents())
|
|
107
|
+
return folded.nodes.map((seq) => session.eventAt(seq)).filter((event) => event !== undefined)
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** Read the current surface synchronously (used inside the request hook). */
|
|
111
|
+
function surfaceEventsSync(session) {
|
|
112
|
+
return session.surface.nodes
|
|
113
|
+
.map((seq) => session.eventAt(seq))
|
|
114
|
+
.filter((event) => event !== undefined)
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/** Build an optional seq→tokens map from the token-meter service (when available). */
|
|
118
|
+
function buildTokensBySeq(ctx, session) {
|
|
119
|
+
try {
|
|
120
|
+
const meter = ctx.tokenMeter
|
|
121
|
+
if (meter === undefined || meter === null || typeof meter.measure !== 'function') return undefined
|
|
122
|
+
const measurement = meter.measure(session)
|
|
123
|
+
if (measurement === undefined || measurement === null || !Array.isArray(measurement.nodes)) return undefined
|
|
124
|
+
const map = new Map()
|
|
125
|
+
for (const node of measurement.nodes) {
|
|
126
|
+
if (node !== null && typeof node === 'object' && Number.isSafeInteger(node.seq)) {
|
|
127
|
+
map.set(node.seq, node.tokens)
|
|
128
|
+
}
|
|
129
|
+
}
|
|
130
|
+
return map
|
|
131
|
+
} catch (_error) {
|
|
132
|
+
return undefined
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Read the turn/step that is open at the very end of the live log.
|
|
138
|
+
* Scans backward: the last boundary marker decides the state, so an open step
|
|
139
|
+
* deep in a long session is found without walking the whole log.
|
|
140
|
+
* @returns the open coordinates plus the opening step seq, or undefined.
|
|
141
|
+
*/
|
|
142
|
+
function openStepOf(session) {
|
|
143
|
+
const events = session.snapshotEvents()
|
|
144
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
145
|
+
const event = events[index]
|
|
146
|
+
if (event.type === 'turn/end' || event.type === 'step/end' || event.type === 'turn/start') return undefined
|
|
147
|
+
if (event.type === 'step/start') {
|
|
148
|
+
const { turn, step } = event.data ?? {}
|
|
149
|
+
if (Number.isSafeInteger(turn) && Number.isSafeInteger(step) && turn >= 0 && step >= 0) {
|
|
150
|
+
return { turn, step, startSeq: event.seq }
|
|
151
|
+
}
|
|
152
|
+
break // unusual payload; fall back to the full forward scan
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
let turn = null
|
|
156
|
+
let step = null
|
|
157
|
+
let startSeq
|
|
158
|
+
for (const event of events) {
|
|
159
|
+
switch (event.type) {
|
|
160
|
+
case 'turn/start':
|
|
161
|
+
turn = event.data.turn
|
|
162
|
+
step = null
|
|
163
|
+
startSeq = undefined
|
|
164
|
+
break
|
|
165
|
+
case 'turn/end':
|
|
166
|
+
turn = null
|
|
167
|
+
step = null
|
|
168
|
+
startSeq = undefined
|
|
169
|
+
break
|
|
170
|
+
case 'step/start':
|
|
171
|
+
step = event.data.step
|
|
172
|
+
startSeq = event.seq
|
|
173
|
+
break
|
|
174
|
+
case 'step/end':
|
|
175
|
+
step = null
|
|
176
|
+
startSeq = undefined
|
|
177
|
+
break
|
|
178
|
+
default:
|
|
179
|
+
break
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
return turn !== null && step !== null && startSeq !== undefined
|
|
183
|
+
? { turn, step, startSeq }
|
|
184
|
+
: undefined
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/** Append tombstone replacements for one plan inside an open turn/step. */
|
|
188
|
+
function appendTombstones(session, runs, turn, step, batchId = undefined) {
|
|
189
|
+
const tombstoneSeqs = []
|
|
190
|
+
try {
|
|
191
|
+
for (const run of runs) {
|
|
192
|
+
const event = session.append(
|
|
193
|
+
'developer/message',
|
|
194
|
+
tombstoneData(turn, step, randomUUID(), batchId,
|
|
195
|
+
buildRecall(run.seqs.map((seq) => session.eventAt(seq)).filter((event) => event !== undefined))),
|
|
196
|
+
{
|
|
197
|
+
surfaceOp: { op: 'replace', startSeq: run.startSeq, endSeq: run.endSeq },
|
|
198
|
+
sourceEventSeqs: run.seqs,
|
|
199
|
+
},
|
|
200
|
+
)
|
|
201
|
+
tombstoneSeqs.push(event.seq)
|
|
202
|
+
}
|
|
203
|
+
} catch (error) {
|
|
204
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
205
|
+
if (tombstoneSeqs.length > 0) {
|
|
206
|
+
throw new Error(`已删除部分内容,后续替换失败:${reason}。请刷新后重试。`)
|
|
207
|
+
}
|
|
208
|
+
throw new Error(`删除失败:${reason}`)
|
|
209
|
+
}
|
|
210
|
+
return tombstoneSeqs
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
/** Whether one event is an empty context-manager tombstone, current or legacy kind. */
|
|
214
|
+
function isTombstone(event) {
|
|
215
|
+
return event !== undefined
|
|
216
|
+
&& event !== null
|
|
217
|
+
&& event.type === 'developer/message'
|
|
218
|
+
&& Array.isArray(event.data?.message?.content)
|
|
219
|
+
&& event.data.message.content.length === 0
|
|
220
|
+
&& isTombstoneKind(event.data?.message?.source?.kind)
|
|
221
|
+
&& event.surfaceOp !== null
|
|
222
|
+
&& typeof event.surfaceOp === 'object'
|
|
223
|
+
&& event.surfaceOp.op === 'replace'
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** Tool-call blocks carried by one assistant message. */
|
|
227
|
+
function assistantToolCalls(event) {
|
|
228
|
+
if (event === undefined || event.type !== 'assistant/message') return []
|
|
229
|
+
const content = event.data?.message?.content
|
|
230
|
+
return Array.isArray(content)
|
|
231
|
+
? content.filter((block) => block !== null && typeof block === 'object' && block.type === 'tool-call')
|
|
232
|
+
: []
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Per-plugin-instance incremental scan state, keyed by plugin ctx then session id. */
|
|
236
|
+
const queueCaches = new WeakMap()
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* Unacknowledged pending operations in log order, incrementally.
|
|
240
|
+
*
|
|
241
|
+
* The queue lives in the session log as plugin records, so a restart replays it
|
|
242
|
+
* for free; within one process each event is examined exactly once.
|
|
243
|
+
* @returns durable queue entries: { recordSeq, op, targetSeq }.
|
|
244
|
+
*/
|
|
245
|
+
function durableQueue(ctx, session) {
|
|
246
|
+
let cache = queueCaches.get(ctx)
|
|
247
|
+
if (cache === undefined) {
|
|
248
|
+
cache = new Map()
|
|
249
|
+
queueCaches.set(ctx, cache)
|
|
250
|
+
}
|
|
251
|
+
const state = cache.get(session.id) ?? { checkedTo: -1, pending: new Map() }
|
|
252
|
+
const events = session.snapshotEvents(Math.max(0, state.checkedTo + 1))
|
|
253
|
+
for (const event of events) {
|
|
254
|
+
const record = pluginRecordOf(event)
|
|
255
|
+
if (record === undefined) continue
|
|
256
|
+
if (record.type === ACK_TYPE || LEGACY_ACK_TYPES.includes(record.type)) {
|
|
257
|
+
const pendingSeq = record.data?.pendingSeq
|
|
258
|
+
if (Number.isSafeInteger(pendingSeq)) state.pending.delete(pendingSeq)
|
|
259
|
+
} else if (record.type === PENDING_TYPE || LEGACY_PENDING_TYPES.includes(record.type)) {
|
|
260
|
+
const op = record.data?.op
|
|
261
|
+
const targetSeq = record.data?.targetSeq
|
|
262
|
+
const batchId = record.data?.batchId
|
|
263
|
+
if ((op === 'delete' || op === 'restore' || op === 'delete-turn') && Number.isSafeInteger(targetSeq)) {
|
|
264
|
+
state.pending.set(record.seq, {
|
|
265
|
+
recordSeq: record.seq,
|
|
266
|
+
op,
|
|
267
|
+
targetSeq,
|
|
268
|
+
batchId: typeof batchId === 'string' ? batchId : undefined,
|
|
269
|
+
})
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
if (events.length > 0) state.checkedTo = events[events.length - 1].seq
|
|
274
|
+
cache.set(session.id, state)
|
|
275
|
+
return [...state.pending.values()]
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/** Durably enqueue one operation; plugin records need no open turn/step. */
|
|
279
|
+
function appendPending(session, op, targetSeq, batchId = undefined) {
|
|
280
|
+
return appendPluginRecord(session, PENDING_TYPE, {
|
|
281
|
+
op,
|
|
282
|
+
targetSeq,
|
|
283
|
+
...typeof batchId === 'string' && batchId.length > 0 ? { batchId } : {},
|
|
284
|
+
})
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
/** Acknowledge one pending record so restarts and replays leave it alone. */
|
|
288
|
+
function appendAck(session, pendingSeq, result, detail) {
|
|
289
|
+
appendPluginRecord(session, ACK_TYPE, {
|
|
290
|
+
pendingSeq,
|
|
291
|
+
result,
|
|
292
|
+
...typeof detail === 'string' && detail.length > 0 ? { detail: detail.slice(0, 300) } : {},
|
|
293
|
+
})
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Append one audit ledger record; plugin records need no open turn/step. */
|
|
297
|
+
function appendBatchLedger(session, entry) {
|
|
298
|
+
return appendPluginRecord(session, BATCH_TYPE, {
|
|
299
|
+
batchId: entry.batchId,
|
|
300
|
+
op: entry.op,
|
|
301
|
+
seqs: Array.isArray(entry.seqs) ? entry.seqs.slice(0, 200) : [],
|
|
302
|
+
tombstoneSeqs: Array.isArray(entry.tombstoneSeqs) ? entry.tombstoneSeqs.slice(0, 200) : [],
|
|
303
|
+
...Number.isSafeInteger(entry.count) && entry.count > 0 ? { count: entry.count } : {},
|
|
304
|
+
estimatedFreedTokens: Number.isSafeInteger(entry.estimatedFreedTokens) ? entry.estimatedFreedTokens : 0,
|
|
305
|
+
result: entry.result,
|
|
306
|
+
...typeof entry.reason === 'string' && entry.reason.length > 0 ? { reason: entry.reason.slice(0, 300) } : {},
|
|
307
|
+
})
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/** Per-plugin-instance batch ledger scan state, keyed by ctx then session id. */
|
|
311
|
+
const batchCaches = new WeakMap()
|
|
312
|
+
|
|
313
|
+
/**
|
|
314
|
+
* Batch ledger entries in log order, incrementally.
|
|
315
|
+
*
|
|
316
|
+
* The ledger is a plugin record inside the append-only session log, so the
|
|
317
|
+
* audit trail travels with the session, survives restarts, and never rewrites
|
|
318
|
+
* a past record. Each record carries the batch id, the target seqs, the
|
|
319
|
+
* tombstones it wrote, the estimated relief, and the outcome.
|
|
320
|
+
*/
|
|
321
|
+
function batchesFromLog(ctx, session) {
|
|
322
|
+
let cache = batchCaches.get(ctx)
|
|
323
|
+
if (cache === undefined) {
|
|
324
|
+
cache = new Map()
|
|
325
|
+
batchCaches.set(ctx, cache)
|
|
326
|
+
}
|
|
327
|
+
const state = cache.get(session.id) ?? { checkedTo: -1, entries: [] }
|
|
328
|
+
const events = session.snapshotEvents(Math.max(0, state.checkedTo + 1))
|
|
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
|
+
state.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
|
+
if (events.length > 0) state.checkedTo = events[events.length - 1].seq
|
|
348
|
+
cache.set(session.id, state)
|
|
349
|
+
return state.entries
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/** List the audit ledger for one live session. */
|
|
353
|
+
async function listBatches(ctx, agent) {
|
|
354
|
+
const session = liveSession(ctx, agent)
|
|
355
|
+
const batches = batchesFromLog(ctx, session)
|
|
356
|
+
return { text: formatBatches(batches), batches }
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/**
|
|
360
|
+
* Compact exactly one user-selected surface span into a summary node.
|
|
361
|
+
*
|
|
362
|
+
* This is the only place this plugin borrows the official compaction engine,
|
|
363
|
+
* and it stays deliberately narrow: the span is whatever the user named by
|
|
364
|
+
* surface position, never a global pressure threshold (that is the compaction
|
|
365
|
+
* backend's own policy). Both edges must already be tool-pairing balanced; the
|
|
366
|
+
* engine rejects an unbalanced range, and we surface that reason verbatim.
|
|
367
|
+
*/
|
|
368
|
+
async function compactSelection(ctx, agent, start, end) {
|
|
369
|
+
const session = liveSession(ctx, agent)
|
|
370
|
+
const controller = new AbortController()
|
|
371
|
+
try {
|
|
372
|
+
// Resolve the optional service through ctx.get: compaction is not a hard
|
|
373
|
+
// dependency of this plugin, and reading ctx.compaction would make Cordis
|
|
374
|
+
// throw "cannot get property" for users who never loaded a backend.
|
|
375
|
+
const engine = ctx.get('compaction')
|
|
376
|
+
if (engine === undefined || engine === null || typeof engine.compactRegion !== 'function') {
|
|
377
|
+
throw new Error('当前环境没有加载 compaction 服务(ctx.compaction);请先启用 dsh-compaction-basic 之类的压缩后端。')
|
|
378
|
+
}
|
|
379
|
+
const nodes = session.surface.nodes
|
|
380
|
+
if (!nodes.includes(start)) throw new Error(`起始序号 #${start} 不在当前表面上(/ctxmgr list 查看)。`)
|
|
381
|
+
if (!nodes.includes(end)) throw new Error(`结束序号 #${end} 不在当前表面上(/ctxmgr list 查看)。`)
|
|
382
|
+
if (nodes.indexOf(start) > nodes.indexOf(end)) {
|
|
383
|
+
throw new Error('起始序号必须位于结束序号之前(按表面位置,不是数值大小)。')
|
|
384
|
+
}
|
|
385
|
+
const options = agent !== null && typeof agent === 'object'
|
|
386
|
+
&& agent.options !== null && typeof agent.options === 'object'
|
|
387
|
+
? agent.options
|
|
388
|
+
: {}
|
|
389
|
+
const agentCtx = { session, options }
|
|
390
|
+
const result = await engine.compactRegion(start, end, agentCtx, controller.signal)
|
|
391
|
+
const shadowedSeqs = Array.isArray(result?.shadowedSeqs) ? result.shadowedSeqs : []
|
|
392
|
+
const tokens = Number.isSafeInteger(result?.shadowedTokenCount) ? result.shadowedTokenCount : 0
|
|
393
|
+
// Node count and token count use different scopes: our tombstones are real
|
|
394
|
+
// surface nodes (so they are counted) but derive no message (so they cost 0).
|
|
395
|
+
// Reporting only the live message count keeps the number meaningful.
|
|
396
|
+
let liveCount = 0
|
|
397
|
+
let tombstoneCount = 0
|
|
398
|
+
for (const seq of shadowedSeqs) {
|
|
399
|
+
if (isTombstone(session.eventAt(seq))) tombstoneCount += 1
|
|
400
|
+
else liveCount += 1
|
|
401
|
+
}
|
|
402
|
+
appendBatchLedger(session, {
|
|
403
|
+
batchId: randomUUID(),
|
|
404
|
+
op: 'compact',
|
|
405
|
+
seqs: [start, end],
|
|
406
|
+
tombstoneSeqs: [],
|
|
407
|
+
count: liveCount,
|
|
408
|
+
estimatedFreedTokens: 0,
|
|
409
|
+
result: 'applied',
|
|
410
|
+
reason: `shadowed ${liveCount} messages + ${tombstoneCount} tombstones / ${tokens} tokens`,
|
|
411
|
+
})
|
|
412
|
+
const tombNote = tombstoneCount > 0 ? `(另有 ${tombstoneCount} 个墓碑节点一并折叠,它们本就不占上下文)` : ''
|
|
413
|
+
return {
|
|
414
|
+
text: `已把表面区间 #${start}…#${end}(${liveCount} 条消息,估算 ${tokens.toLocaleString('en-US')} tokens${tombNote})压缩成一条摘要消息。原始会话日志与聊天记录仍保留;这只作用于你选中的区间,不做全局阈值压缩。`,
|
|
415
|
+
count: liveCount,
|
|
416
|
+
tokens,
|
|
417
|
+
}
|
|
418
|
+
} catch (error) {
|
|
419
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
420
|
+
// The backend prices the shrink check against model-visible content only, so
|
|
421
|
+
// a span whose live content is mostly already deleted cannot be summarized.
|
|
422
|
+
// Say that plainly, and keep the ledger in the same language as the reply.
|
|
423
|
+
const shrink = /summary is not smaller than the shadowed content \((\d+) estimated framed tokens >= (\d+)\)/.exec(message)
|
|
424
|
+
const explanation = shrink !== null
|
|
425
|
+
? `选区内模型可见内容只剩约 ${shrink[2]} tokens(墓碑不算内容),而摘要本身就约 ${shrink[1]} tokens,官方压缩会拒绝「摘要不比原文小」的情况。`
|
|
426
|
+
: message
|
|
427
|
+
appendBatchLedger(session, {
|
|
428
|
+
batchId: randomUUID(),
|
|
429
|
+
op: 'compact',
|
|
430
|
+
seqs: [start, end],
|
|
431
|
+
tombstoneSeqs: [],
|
|
432
|
+
estimatedFreedTokens: 0,
|
|
433
|
+
result: 'failed',
|
|
434
|
+
reason: explanation,
|
|
435
|
+
})
|
|
436
|
+
if (shrink !== null) {
|
|
437
|
+
throw new Error(`局部压缩失败:${explanation}建议改用 /ctxmgr delete 或 /ctxmgr clean 直接移出这段,而不是压缩它。`)
|
|
438
|
+
}
|
|
439
|
+
throw new Error(`局部压缩失败:${message}`)
|
|
440
|
+
}
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
/**
|
|
444
|
+
* Undo one batch by restoring the tombstones it wrote.
|
|
445
|
+
*
|
|
446
|
+
* Undo never invents a new restore mechanism: it reuses the queued restore
|
|
447
|
+
* path, so the raw log stays append-only and the restore keeps its usual
|
|
448
|
+
* semantics (user/context at position, assistant content at the tail).
|
|
449
|
+
*/
|
|
450
|
+
async function undoBatch(ctx, agent, batchId) {
|
|
451
|
+
const session = liveSession(ctx, agent)
|
|
452
|
+
const batches = batchesFromLog(ctx, session)
|
|
453
|
+
const matches = matchUndoBatches(batches, batchId)
|
|
454
|
+
const isNamed = typeof batchId === 'string' && batchId.length > 0
|
|
455
|
+
if (isNamed && matches.length > 1 && !matches.some((entry) => entry.batchId === batchId)) {
|
|
456
|
+
throw new Error(`批次前缀有歧义(匹配 ${matches.length} 条),请给更长的前缀或完整 batchId(/ctxmgr batches 查看台账)。`)
|
|
457
|
+
}
|
|
458
|
+
const target = pickUndoBatch(batches, batchId)
|
|
459
|
+
if (target === undefined) {
|
|
460
|
+
throw new Error(typeof batchId === 'string' && batchId.length > 0
|
|
461
|
+
? '找不到该批次记录(/ctxmgr batches 查看台账)。'
|
|
462
|
+
: '还没有可撤销的批次记录(台账为空,或只有恢复类操作)。')
|
|
463
|
+
}
|
|
464
|
+
const restoreSeqs = target.tombstoneSeqs.filter((seq) => session.surface.nodes.includes(seq))
|
|
465
|
+
if (restoreSeqs.length === 0) throw new Error('该批次已没有仍在表面的删除记录(可能已恢复过)。')
|
|
466
|
+
const undoBatchId = randomUUID()
|
|
467
|
+
const result = await restoreMessages(ctx, agent, restoreSeqs, { batchId: undoBatchId })
|
|
468
|
+
appendBatchLedger(session, {
|
|
469
|
+
batchId: undoBatchId,
|
|
470
|
+
op: 'undo',
|
|
471
|
+
seqs: restoreSeqs,
|
|
472
|
+
tombstoneSeqs: [],
|
|
473
|
+
count: restoreSeqs.length,
|
|
474
|
+
estimatedFreedTokens: 0,
|
|
475
|
+
result: 'queued',
|
|
476
|
+
reason: target.batchId,
|
|
477
|
+
})
|
|
478
|
+
const short = target.batchId.slice(0, 8)
|
|
479
|
+
return {
|
|
480
|
+
text: `撤销批次 ${short}(${target.op}):${result.text}`,
|
|
481
|
+
note: '用户与上下文消息回到原位;助手内容与工具结果会追加到末尾(序号会变)。',
|
|
482
|
+
batchId: target.batchId,
|
|
483
|
+
count: restoreSeqs.length,
|
|
484
|
+
}
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* Classify one tombstone into a restore plan without mutating the Session.
|
|
489
|
+
* @throws when the tombstone or its original group cannot be restored safely.
|
|
490
|
+
*/
|
|
491
|
+
function planRestore(session, tombstoneSeq) {
|
|
492
|
+
if (!session.surface.nodes.includes(tombstoneSeq)) throw new Error('该删除记录已不在当前表面,可能已被恢复。')
|
|
493
|
+
const tombstone = session.eventAt(tombstoneSeq)
|
|
494
|
+
if (!isTombstone(tombstone)) throw new Error('该序号不是本插件的删除记录。')
|
|
495
|
+
const targets = tombstone.sourceEventSeqs
|
|
496
|
+
if (!Array.isArray(targets) || targets.length === 0) throw new Error('删除记录缺少原始消息引用。')
|
|
497
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
498
|
+
const originals = targets.map((seq) => bySeq.get(seq))
|
|
499
|
+
if (originals.some((event) => event === undefined)) throw new Error('原始消息已不在会话日志中,无法恢复。')
|
|
500
|
+
|
|
501
|
+
if (originals.length === 1) {
|
|
502
|
+
const original = originals[0]
|
|
503
|
+
if (original.type === 'user/message') return { kind: 'user', original }
|
|
504
|
+
if (original.type === 'developer/message') {
|
|
505
|
+
if (hasToolChange(original)) throw new Error('该上下文消息携带工具变更,不能恢复。')
|
|
506
|
+
return { kind: 'developer', original }
|
|
507
|
+
}
|
|
508
|
+
if (original.type === 'assistant/message') {
|
|
509
|
+
if (assistantToolCalls(original).length > 0) throw new Error('该助手消息属于工具调用组,无法单独恢复。')
|
|
510
|
+
if (!Array.isArray(original.data?.message?.content) || original.data.message.content.length === 0) {
|
|
511
|
+
throw new Error('该助手消息没有可恢复的内容。')
|
|
512
|
+
}
|
|
513
|
+
return { kind: 'assistant', original }
|
|
514
|
+
}
|
|
515
|
+
throw new Error('该类型的消息暂不支持恢复。')
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
const assistant = originals[0]
|
|
519
|
+
if (assistant.type !== 'assistant/message') throw new Error('删除组不是可恢复的助手消息组。')
|
|
520
|
+
const calls = assistantToolCalls(assistant)
|
|
521
|
+
if (calls.length === 0) throw new Error('删除组不是可恢复的助手消息组。')
|
|
522
|
+
const results = originals.slice(1)
|
|
523
|
+
if (results.some((event) => event.type !== 'tool/result')) throw new Error('删除组包含不支持恢复的消息类型。')
|
|
524
|
+
const callIds = new Set(calls.map((block) => block.id))
|
|
525
|
+
const resultIds = new Set()
|
|
526
|
+
for (const result of results) {
|
|
527
|
+
const callId = result.data?.message?.toolCallId
|
|
528
|
+
if (!callIds.has(callId)) throw new Error('删除组的工具调用与结果不匹配,无法恢复。')
|
|
529
|
+
resultIds.add(callId)
|
|
530
|
+
}
|
|
531
|
+
if (resultIds.size !== callIds.size) throw new Error('删除组的工具调用不完整,无法恢复。')
|
|
532
|
+
return { kind: 'group', assistant, calls, results }
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** Append an assistant copy at the tail and return its marker message id. */
|
|
536
|
+
function appendAssistantCopy(session, original, tombstoneSeq, turn, step) {
|
|
537
|
+
const messageId = `${RESTORED_PREFIX}${tombstoneSeq}-${randomUUID()}`
|
|
538
|
+
session.append('assistant/message', {
|
|
539
|
+
turn,
|
|
540
|
+
step,
|
|
541
|
+
message: {
|
|
542
|
+
id: messageId,
|
|
543
|
+
role: 'assistant',
|
|
544
|
+
content: original.data.message.content,
|
|
545
|
+
source: original.data.message.source,
|
|
546
|
+
},
|
|
547
|
+
stream: [],
|
|
548
|
+
}, { surfaceOp: 'append' })
|
|
549
|
+
return messageId
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
/** Restore one tombstone inside the request's open step. */
|
|
553
|
+
function restoreOne(session, tombstoneSeq, turn, step) {
|
|
554
|
+
const plan = planRestore(session, tombstoneSeq)
|
|
555
|
+
if (plan.kind === 'user') {
|
|
556
|
+
session.append(
|
|
557
|
+
'user/message',
|
|
558
|
+
{ ...plan.original.data, id: randomUUID() },
|
|
559
|
+
{
|
|
560
|
+
surfaceOp: { op: 'replace', startSeq: tombstoneSeq, endSeq: tombstoneSeq },
|
|
561
|
+
sourceEventSeqs: [tombstoneSeq],
|
|
562
|
+
},
|
|
563
|
+
)
|
|
564
|
+
return
|
|
565
|
+
}
|
|
566
|
+
if (plan.kind === 'developer') {
|
|
567
|
+
const data = {
|
|
568
|
+
...plan.original.data,
|
|
569
|
+
turn,
|
|
570
|
+
step,
|
|
571
|
+
message: { ...plan.original.data.message, id: randomUUID() },
|
|
572
|
+
}
|
|
573
|
+
delete data.headerSeq
|
|
574
|
+
session.append(
|
|
575
|
+
'developer/message',
|
|
576
|
+
data,
|
|
577
|
+
{
|
|
578
|
+
surfaceOp: { op: 'replace', startSeq: tombstoneSeq, endSeq: tombstoneSeq },
|
|
579
|
+
sourceEventSeqs: [tombstoneSeq],
|
|
580
|
+
},
|
|
581
|
+
)
|
|
582
|
+
return
|
|
583
|
+
}
|
|
584
|
+
if (plan.kind === 'assistant') {
|
|
585
|
+
const marker = `${RESTORED_PREFIX}${tombstoneSeq}-`
|
|
586
|
+
if (surfaceEventsSync(session).some((event) => event.type === 'assistant/message'
|
|
587
|
+
&& typeof event.data?.message?.id === 'string'
|
|
588
|
+
&& event.data.message.id.startsWith(marker))) {
|
|
589
|
+
throw new Error('该消息已经恢复。')
|
|
590
|
+
}
|
|
591
|
+
appendAssistantCopy(session, plan.original, tombstoneSeq, turn, step)
|
|
592
|
+
return
|
|
593
|
+
}
|
|
594
|
+
if (plan.kind === 'group') {
|
|
595
|
+
const marker = `${RESTORED_PREFIX}${tombstoneSeq}-`
|
|
596
|
+
if (surfaceEventsSync(session).some((event) => event.type === 'assistant/message'
|
|
597
|
+
&& typeof event.data?.message?.id === 'string'
|
|
598
|
+
&& event.data.message.id.startsWith(marker))) {
|
|
599
|
+
throw new Error('该消息组已经恢复。')
|
|
600
|
+
}
|
|
601
|
+
appendAssistantCopy(session, plan.assistant, tombstoneSeq, turn, step)
|
|
602
|
+
for (const call of plan.calls) {
|
|
603
|
+
session.append('tool/call', {
|
|
604
|
+
turn,
|
|
605
|
+
step,
|
|
606
|
+
callId: call.id,
|
|
607
|
+
name: call.name,
|
|
608
|
+
arguments: call.arguments,
|
|
609
|
+
})
|
|
610
|
+
}
|
|
611
|
+
for (const result of plan.results) {
|
|
612
|
+
const message = result.data.message
|
|
613
|
+
const data = {
|
|
614
|
+
turn,
|
|
615
|
+
step,
|
|
616
|
+
message: {
|
|
617
|
+
id: randomUUID(),
|
|
618
|
+
role: 'tool',
|
|
619
|
+
content: message.content,
|
|
620
|
+
source: message.source,
|
|
621
|
+
toolCallId: message.toolCallId,
|
|
622
|
+
...message.isError === true ? { isError: true } : {},
|
|
623
|
+
},
|
|
624
|
+
...result.data.error === undefined ? {} : { error: result.data.error },
|
|
625
|
+
}
|
|
626
|
+
session.append('tool/result', data, { surfaceOp: 'append' })
|
|
627
|
+
}
|
|
628
|
+
return
|
|
629
|
+
}
|
|
630
|
+
throw new Error('不支持恢复该删除记录。')
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
/** List current surface messages plus deleted records and durable queue. */
|
|
634
|
+
async function listMessages(ctx, agent) {
|
|
635
|
+
const session = liveSession(ctx, agent)
|
|
636
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
637
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
638
|
+
const items = itemsFromSurface(events, tokensBySeq)
|
|
639
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
640
|
+
const deleted = deletedFromSurface(events, bySeq)
|
|
641
|
+
const pending = durableQueue(ctx, session)
|
|
642
|
+
return { text: formatList(items, deleted, pending), items, deleted, pending }
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
/** Delete one or more messages now when safe, otherwise queue them durably. */
|
|
646
|
+
async function deleteMessages(ctx, agent, seqs, options = {}) {
|
|
647
|
+
const unique = [...new Set(seqs)]
|
|
648
|
+
if (unique.length === 0 || unique.some((seq) => !Number.isSafeInteger(seq) || seq < 0)) {
|
|
649
|
+
throw new Error('序号必须是非负整数。')
|
|
650
|
+
}
|
|
651
|
+
const batchId = typeof options.batchId === 'string' && options.batchId.length > 0
|
|
652
|
+
? options.batchId
|
|
653
|
+
: randomUUID()
|
|
654
|
+
const opName = typeof options.op === 'string' && options.op.length > 0 ? options.op : 'delete'
|
|
655
|
+
const session = liveSession(ctx, agent)
|
|
656
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
657
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
658
|
+
const targets = []
|
|
659
|
+
for (const seq of unique) {
|
|
660
|
+
const plan = planDeletion(events, seq)
|
|
661
|
+
if (!plan.ok) {
|
|
662
|
+
if (plan.reason === 'system') throw new Error('系统提示词不是可删除的对话消息。')
|
|
663
|
+
if (plan.reason === 'tombstone') {
|
|
664
|
+
throw new Error('该序号是一条删除记录(墓碑),不是消息;要回到上下文请用 /ctxmgr restore。')
|
|
665
|
+
}
|
|
666
|
+
if (plan.reason === 'not-found') {
|
|
667
|
+
if (unique.length === 1) throw new Error('该消息已不在当前模型上下文中,可能已被删除;请刷新后重试。')
|
|
668
|
+
continue
|
|
669
|
+
}
|
|
670
|
+
throw new Error('这条消息不支持单独删除。')
|
|
671
|
+
}
|
|
672
|
+
targets.push({ seq, plan })
|
|
673
|
+
}
|
|
674
|
+
if (targets.length === 0) throw new Error('选中的消息都已不在当前模型上下文中。')
|
|
675
|
+
|
|
676
|
+
// Items are always priced (meter when available, else the local heuristic),
|
|
677
|
+
// so the reported relief never collapses to 0 when the meter is absent.
|
|
678
|
+
const tokensOfSeq = new Map(itemsFromSurface(events, tokensBySeq).map((item) => [item.seq, item.tokens ?? 0]))
|
|
679
|
+
let estimatedFreedTokens = 0
|
|
680
|
+
for (const target of targets) {
|
|
681
|
+
for (const run of target.plan.runs) {
|
|
682
|
+
for (const seq of run.seqs) estimatedFreedTokens += tokensOfSeq.get(seq) ?? 0
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
|
|
686
|
+
const open = openStepOf(session)
|
|
687
|
+
const touchesOpenStep = open !== undefined
|
|
688
|
+
&& targets.some((target) => target.plan.indices.some((index) => events[index].seq >= open.startSeq))
|
|
689
|
+
if (open !== undefined && !touchesOpenStep) {
|
|
690
|
+
let count = 0
|
|
691
|
+
const tombstoneSeqs = []
|
|
692
|
+
for (const target of targets) {
|
|
693
|
+
// Re-plan against the live surface because an earlier target may have
|
|
694
|
+
// already removed this target as part of the same tool group.
|
|
695
|
+
const current = surfaceEventsSync(session)
|
|
696
|
+
const plan = planDeletion(current, target.seq)
|
|
697
|
+
if (!plan.ok) continue
|
|
698
|
+
tombstoneSeqs.push(...appendTombstones(session, plan.runs, open.turn, open.step, batchId))
|
|
699
|
+
count += plan.count
|
|
700
|
+
}
|
|
701
|
+
appendBatchLedger(session, {
|
|
702
|
+
batchId,
|
|
703
|
+
op: opName,
|
|
704
|
+
seqs: targets.map((target) => target.seq),
|
|
705
|
+
tombstoneSeqs,
|
|
706
|
+
count,
|
|
707
|
+
estimatedFreedTokens,
|
|
708
|
+
result: 'applied',
|
|
709
|
+
})
|
|
710
|
+
return {
|
|
711
|
+
text: `已从模型上下文删除 ${count} 条消息,估算释放约 ${estimatedFreedTokens.toLocaleString('en-US')} tokens(会话日志与聊天记录仍保留)。批次 ${batchId.slice(0, 8)},可用 /ctxmgr undo-batch 撤销。`,
|
|
712
|
+
count,
|
|
713
|
+
estimatedFreedTokens,
|
|
714
|
+
batchId,
|
|
715
|
+
queued: false,
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
|
|
719
|
+
const queuedTargets = new Set(durableQueue(ctx, session)
|
|
720
|
+
.filter((entry) => entry.op === 'delete')
|
|
721
|
+
.map((entry) => entry.targetSeq))
|
|
722
|
+
let added = 0
|
|
723
|
+
for (const target of targets) {
|
|
724
|
+
if (queuedTargets.has(target.seq)) continue
|
|
725
|
+
appendPending(session, 'delete', target.seq, batchId)
|
|
726
|
+
queuedTargets.add(target.seq)
|
|
727
|
+
added += 1
|
|
728
|
+
}
|
|
729
|
+
if (!ensureAgentListener(ctx, agent)) {
|
|
730
|
+
throw new Error('当前会话没有可用的 Agent 请求作用域,无法排队删除;请重试。')
|
|
731
|
+
}
|
|
732
|
+
return {
|
|
733
|
+
text: added === 0
|
|
734
|
+
? '选中的消息已在删除队列中,将在下一次请求开始时生效。'
|
|
735
|
+
: `已加入删除队列:${added} 条消息将在下一次请求开始时从模型上下文移除,估算释放约 ${estimatedFreedTokens.toLocaleString('en-US')} tokens(会话日志与聊天记录仍保留)。批次 ${batchId.slice(0, 8)},下一次请求生效后可用 /ctxmgr undo-batch 撤销。`,
|
|
736
|
+
count: added,
|
|
737
|
+
estimatedFreedTokens,
|
|
738
|
+
batchId,
|
|
739
|
+
queued: true,
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
|
|
743
|
+
/** Token-budget cleanup: plan candidates then delete them via the normal pipeline. */
|
|
744
|
+
async function cleanMessages(ctx, agent, targetTokens, options) {
|
|
745
|
+
const session = liveSession(ctx, agent)
|
|
746
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
747
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
748
|
+
const items = itemsFromSurface(events, tokensBySeq)
|
|
749
|
+
const cleanPlan = planClean(items, targetTokens, options)
|
|
750
|
+
if (cleanPlan.chosen.length === 0) {
|
|
751
|
+
return {
|
|
752
|
+
text: '没有可清理的消息(只有用户/上下文消息,或剩余消息都太小、太新被保护)。token 数为启发式估算,实际可能略少。',
|
|
753
|
+
count: 0,
|
|
754
|
+
estimatedFreedTokens: 0,
|
|
755
|
+
queued: false,
|
|
756
|
+
}
|
|
757
|
+
}
|
|
758
|
+
const result = await deleteMessages(ctx, agent, cleanPlan.chosen, { op: 'clean' })
|
|
759
|
+
return {
|
|
760
|
+
text: `clean:目标 ${targetTokens.toLocaleString('en-US')} tokens,实际估算释放约 ${result.estimatedFreedTokens.toLocaleString('en-US')} tokens(token 数为启发式估算)。${result.text}`,
|
|
761
|
+
count: result.count,
|
|
762
|
+
estimatedFreedTokens: result.estimatedFreedTokens,
|
|
763
|
+
queued: result.queued,
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
/** Queue one or more tombstones for restore at the next request. */
|
|
768
|
+
async function restoreMessages(ctx, agent, tombstoneSeqs, options = {}) {
|
|
769
|
+
const batchId = typeof options.batchId === 'string' && options.batchId.length > 0
|
|
770
|
+
? options.batchId
|
|
771
|
+
: undefined
|
|
772
|
+
const unique = [...new Set(tombstoneSeqs)]
|
|
773
|
+
if (unique.length === 0 || unique.some((seq) => !Number.isSafeInteger(seq) || seq < 0)) {
|
|
774
|
+
throw new Error('删除记录序号必须是非负整数。')
|
|
775
|
+
}
|
|
776
|
+
const session = liveSession(ctx, agent)
|
|
777
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
778
|
+
const accepted = []
|
|
779
|
+
for (const seq of unique) {
|
|
780
|
+
const tombstone = bySeq.get(seq)
|
|
781
|
+
if (tombstone === undefined) {
|
|
782
|
+
if (unique.length === 1) throw new Error('找不到该删除记录。')
|
|
783
|
+
continue
|
|
784
|
+
}
|
|
785
|
+
if (!session.surface.nodes.includes(seq)) continue
|
|
786
|
+
// Validate now so unsupported groups fail before queueing.
|
|
787
|
+
planRestore(session, seq)
|
|
788
|
+
accepted.push(seq)
|
|
789
|
+
}
|
|
790
|
+
if (accepted.length === 0) throw new Error('没有可恢复的删除记录(可能已经恢复)。')
|
|
791
|
+
const queuedTargets = new Set(durableQueue(ctx, session)
|
|
792
|
+
.filter((entry) => entry.op === 'restore')
|
|
793
|
+
.map((entry) => entry.targetSeq))
|
|
794
|
+
let added = 0
|
|
795
|
+
for (const seq of accepted) {
|
|
796
|
+
if (queuedTargets.has(seq)) continue
|
|
797
|
+
appendPending(session, 'restore', seq, batchId)
|
|
798
|
+
queuedTargets.add(seq)
|
|
799
|
+
added += 1
|
|
800
|
+
}
|
|
801
|
+
if (!ensureAgentListener(ctx, agent)) {
|
|
802
|
+
throw new Error('当前会话没有可用的 Agent 请求作用域,无法排队恢复;请重试。')
|
|
803
|
+
}
|
|
804
|
+
return {
|
|
805
|
+
text: added === 0
|
|
806
|
+
? '选中的删除记录已在恢复队列中,将在下一次请求开始时恢复。'
|
|
807
|
+
: `已加入恢复队列:${added} 条删除记录将在下一次请求开始时恢复到模型上下文。`,
|
|
808
|
+
count: added,
|
|
809
|
+
queued: true,
|
|
810
|
+
}
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
/** List current conversation turns as text. */
|
|
814
|
+
async function listTurns(ctx, agent) {
|
|
815
|
+
const session = liveSession(ctx, agent)
|
|
816
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
817
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
818
|
+
const open = openStepOf(session)
|
|
819
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
820
|
+
const items = itemsFromSurface(events, tokensBySeq)
|
|
821
|
+
const turns = addTurnTokens(
|
|
822
|
+
turnsFromSurface(events, bySeq).map((turn) => ({
|
|
823
|
+
...turn,
|
|
824
|
+
inProgress: open !== undefined && turn.seqs.some((seq) => seq >= open.startSeq),
|
|
825
|
+
})),
|
|
826
|
+
items,
|
|
827
|
+
)
|
|
828
|
+
return { text: formatTurns(turns), turns }
|
|
829
|
+
}
|
|
830
|
+
|
|
831
|
+
/** Delete whole conversation turns now when safe, otherwise queue them durably. */
|
|
832
|
+
async function deleteTurns(ctx, agent, turnNums, options = {}) {
|
|
833
|
+
const unique = [...new Set(turnNums)]
|
|
834
|
+
if (unique.length === 0 || unique.some((num) => !Number.isSafeInteger(num) || num < 0)) {
|
|
835
|
+
throw new Error('轮号必须是非负整数(list-turns 查看)。')
|
|
836
|
+
}
|
|
837
|
+
const session = liveSession(ctx, agent)
|
|
838
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
839
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
840
|
+
const open = openStepOf(session)
|
|
841
|
+
const tokensBySeq = buildTokensBySeq(ctx, session)
|
|
842
|
+
const batchId = typeof options.batchId === 'string' && options.batchId.length > 0
|
|
843
|
+
? options.batchId
|
|
844
|
+
: randomUUID()
|
|
845
|
+
const items = itemsFromSurface(events, tokensBySeq)
|
|
846
|
+
// Attribute each item's tokens to its turn (same rule as turn grouping).
|
|
847
|
+
const tokensByTurn = new Map()
|
|
848
|
+
for (const item of items) {
|
|
849
|
+
tokensByTurn.set(item.turn, (tokensByTurn.get(item.turn) ?? 0) + (item.tokens ?? 0))
|
|
850
|
+
}
|
|
851
|
+
const all = turnsFromSurface(events, bySeq).map((turn) => ({
|
|
852
|
+
...turn,
|
|
853
|
+
tokens: tokensByTurn.get(turn.turn) ?? 0,
|
|
854
|
+
}))
|
|
855
|
+
const targets = []
|
|
856
|
+
for (const num of unique) {
|
|
857
|
+
const turn = all.find((entry) => entry.turn === num)
|
|
858
|
+
if (turn === undefined) {
|
|
859
|
+
if (unique.length === 1) throw new Error('该轮已不在当前上下文中(可能已删除);list-turns 查看现有轮。')
|
|
860
|
+
continue
|
|
861
|
+
}
|
|
862
|
+
targets.push(turn)
|
|
863
|
+
}
|
|
864
|
+
if (targets.length === 0) throw new Error('选中的轮都已不在当前上下文中。')
|
|
865
|
+
|
|
866
|
+
const estimatedFreedTokens = targets.reduce((total, turn) => total + (turn.tokens ?? 0), 0)
|
|
867
|
+
|
|
868
|
+
const touchesOpen = open !== undefined
|
|
869
|
+
&& targets.some((turn) => turn.seqs.some((seq) => seq >= open.startSeq))
|
|
870
|
+
if (open !== undefined && !touchesOpen) {
|
|
871
|
+
let turns = 0
|
|
872
|
+
let messages = 0
|
|
873
|
+
const tombstoneSeqs = []
|
|
874
|
+
for (const turn of targets) {
|
|
875
|
+
const done = deleteTurnNow(session, turn.turn, open.turn, open.step, batchId)
|
|
876
|
+
if (done !== null) {
|
|
877
|
+
turns += 1
|
|
878
|
+
messages += done.count
|
|
879
|
+
tombstoneSeqs.push(...done.tombstoneSeqs)
|
|
880
|
+
}
|
|
881
|
+
}
|
|
882
|
+
appendBatchLedger(session, {
|
|
883
|
+
batchId,
|
|
884
|
+
op: 'delete-turn',
|
|
885
|
+
seqs: targets.map((turn) => turn.turn),
|
|
886
|
+
tombstoneSeqs,
|
|
887
|
+
count: messages,
|
|
888
|
+
estimatedFreedTokens,
|
|
889
|
+
result: 'applied',
|
|
890
|
+
})
|
|
891
|
+
return {
|
|
892
|
+
text: `已从模型上下文删除 ${turns} 轮对话(共 ${messages} 条消息,估算释放约 ${estimatedFreedTokens.toLocaleString('en-US')} tokens;会话日志与聊天记录仍保留)。批次 ${batchId.slice(0, 8)},可用 /ctxmgr undo-batch 撤销。`,
|
|
893
|
+
turns,
|
|
894
|
+
messages,
|
|
895
|
+
estimatedFreedTokens,
|
|
896
|
+
batchId,
|
|
897
|
+
queued: false,
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
|
|
901
|
+
const queued = new Set(durableQueue(ctx, session)
|
|
902
|
+
.filter((entry) => entry.op === 'delete-turn')
|
|
903
|
+
.map((entry) => entry.targetSeq))
|
|
904
|
+
let added = 0
|
|
905
|
+
for (const turn of targets) {
|
|
906
|
+
if (queued.has(turn.turn)) continue
|
|
907
|
+
appendPending(session, 'delete-turn', turn.turn, batchId)
|
|
908
|
+
queued.add(turn.turn)
|
|
909
|
+
added += 1
|
|
910
|
+
}
|
|
911
|
+
if (!ensureAgentListener(ctx, agent)) {
|
|
912
|
+
throw new Error('当前会话没有可用的 Agent 请求作用域,无法排队删除;请重试。')
|
|
913
|
+
}
|
|
914
|
+
return {
|
|
915
|
+
text: added === 0
|
|
916
|
+
? '选中的轮已在删除队列中,将在下一次请求开始时生效。'
|
|
917
|
+
: `已加入删除队列:${added} 轮对话将在下一次请求开始时从模型上下文移除,估算释放约 ${estimatedFreedTokens.toLocaleString('en-US')} tokens(会话日志与聊天记录仍保留)。`,
|
|
918
|
+
turns: added,
|
|
919
|
+
estimatedFreedTokens,
|
|
920
|
+
batchId,
|
|
921
|
+
queued: true,
|
|
922
|
+
}
|
|
923
|
+
}
|
|
924
|
+
|
|
925
|
+
/**
|
|
926
|
+
* Delete every remaining content node of one conversation turn, grouping the
|
|
927
|
+
* nodes through the same planner used for single-message deletion so each
|
|
928
|
+
* tombstone keeps its own restore semantics (user in place, assistant groups
|
|
929
|
+
* and text at the tail). Tombstones already on the surface stay untouched.
|
|
930
|
+
* @returns the number of messages removed, or null when none remain.
|
|
931
|
+
*/
|
|
932
|
+
function deleteTurnNow(session, turnNum, curTurn, curStep, batchId = undefined) {
|
|
933
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
934
|
+
const turn = turnsFromSurface(surfaceEventsSync(session), bySeq)
|
|
935
|
+
.find((entry) => entry.turn === turnNum)
|
|
936
|
+
if (turn === undefined || turn.seqs.length === 0) return null
|
|
937
|
+
const planned = new Set()
|
|
938
|
+
const tombstoneSeqs = []
|
|
939
|
+
let count = 0
|
|
940
|
+
for (const seq of turn.seqs) {
|
|
941
|
+
if (planned.has(seq)) continue
|
|
942
|
+
// Re-plan against the live surface: an earlier group may already have
|
|
943
|
+
// absorbed this target, and each append invalidates stale ranges.
|
|
944
|
+
const current = surfaceEventsSync(session)
|
|
945
|
+
const plan = planDeletion(current, seq)
|
|
946
|
+
if (!plan.ok) continue
|
|
947
|
+
tombstoneSeqs.push(...appendTombstones(session, plan.runs, curTurn, curStep, batchId))
|
|
948
|
+
for (const index of plan.indices) planned.add(current[index].seq)
|
|
949
|
+
count += plan.count
|
|
950
|
+
}
|
|
951
|
+
return { count, tombstoneSeqs }
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
/** Per-plugin-instance agent listener registries, keyed by plugin ctx. */
|
|
955
|
+
const listenerRegistries = new WeakMap()
|
|
956
|
+
|
|
957
|
+
/** The listener registry owned by one plugin ctx. */
|
|
958
|
+
function listenerRegistry(ctx) {
|
|
959
|
+
let registry = listenerRegistries.get(ctx)
|
|
960
|
+
if (registry === undefined) {
|
|
961
|
+
registry = new Map()
|
|
962
|
+
listenerRegistries.set(ctx, registry)
|
|
963
|
+
}
|
|
964
|
+
return registry
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
/**
|
|
968
|
+
* Replay every durable pending delete/restore for one Agent's Session inside
|
|
969
|
+
* the request's open step, then acknowledge each record so it never replays
|
|
970
|
+
* again. Replayed operations whose target already vanished are acked as
|
|
971
|
+
* skipped; genuine failures are acked with the reason.
|
|
972
|
+
*/
|
|
973
|
+
function applyQueuedOperations(ctx, agent, turn, step) {
|
|
974
|
+
const session = ctx.sessions.get(agent.id)
|
|
975
|
+
if (session === undefined) return
|
|
976
|
+
const queue = durableQueue(ctx, session)
|
|
977
|
+
if (queue.length === 0) return
|
|
978
|
+
// Price the current surface once, so a replayed entry records the relief it
|
|
979
|
+
// actually produced instead of a zero placeholder.
|
|
980
|
+
const pricedItems = itemsFromSurface(surfaceEventsSync(session), buildTokensBySeq(ctx, session))
|
|
981
|
+
const tokensOfSeq = new Map(pricedItems.map((item) => [item.seq, item.tokens ?? 0]))
|
|
982
|
+
const tokensByTurn = new Map()
|
|
983
|
+
for (const item of pricedItems) {
|
|
984
|
+
tokensByTurn.set(item.turn, (tokensByTurn.get(item.turn) ?? 0) + (item.tokens ?? 0))
|
|
985
|
+
}
|
|
986
|
+
const freedOfPlan = (plan) => plan.runs.reduce((sum, run) => sum
|
|
987
|
+
+ run.seqs.reduce((inner, seq) => inner + (tokensOfSeq.get(seq) ?? 0), 0), 0)
|
|
988
|
+
for (const entry of queue) {
|
|
989
|
+
try {
|
|
990
|
+
if (entry.op === 'delete') {
|
|
991
|
+
const plan = planDeletion(surfaceEventsSync(session), entry.targetSeq)
|
|
992
|
+
if (!plan.ok) {
|
|
993
|
+
appendAck(session, entry.recordSeq, 'skipped', `target #${entry.targetSeq} ${plan.reason}`)
|
|
994
|
+
appendBatchLedger(session, {
|
|
995
|
+
batchId: entry.batchId ?? `pending-${entry.recordSeq}`,
|
|
996
|
+
op: 'delete',
|
|
997
|
+
seqs: [entry.targetSeq],
|
|
998
|
+
tombstoneSeqs: [],
|
|
999
|
+
estimatedFreedTokens: 0,
|
|
1000
|
+
result: 'skipped',
|
|
1001
|
+
reason: `target #${entry.targetSeq} ${plan.reason}`,
|
|
1002
|
+
})
|
|
1003
|
+
continue
|
|
1004
|
+
}
|
|
1005
|
+
const tombstoneSeqs = appendTombstones(session, plan.runs, turn, step, entry.batchId)
|
|
1006
|
+
appendAck(session, entry.recordSeq, 'applied')
|
|
1007
|
+
appendBatchLedger(session, {
|
|
1008
|
+
batchId: entry.batchId ?? `pending-${entry.recordSeq}`,
|
|
1009
|
+
op: 'delete',
|
|
1010
|
+
seqs: [entry.targetSeq],
|
|
1011
|
+
tombstoneSeqs,
|
|
1012
|
+
count: plan.count,
|
|
1013
|
+
estimatedFreedTokens: freedOfPlan(plan),
|
|
1014
|
+
result: 'applied',
|
|
1015
|
+
})
|
|
1016
|
+
} else if (entry.op === 'delete-turn') {
|
|
1017
|
+
const done = deleteTurnNow(session, entry.targetSeq, turn, step, entry.batchId)
|
|
1018
|
+
if (done === null) {
|
|
1019
|
+
appendAck(session, entry.recordSeq, 'skipped', `turn #${entry.targetSeq} has no remaining content`)
|
|
1020
|
+
appendBatchLedger(session, {
|
|
1021
|
+
batchId: entry.batchId ?? `pending-${entry.recordSeq}`,
|
|
1022
|
+
op: 'delete-turn',
|
|
1023
|
+
seqs: [entry.targetSeq],
|
|
1024
|
+
tombstoneSeqs: [],
|
|
1025
|
+
estimatedFreedTokens: 0,
|
|
1026
|
+
result: 'skipped',
|
|
1027
|
+
reason: `turn #${entry.targetSeq} has no remaining content`,
|
|
1028
|
+
})
|
|
1029
|
+
} else {
|
|
1030
|
+
appendAck(session, entry.recordSeq, 'applied')
|
|
1031
|
+
appendBatchLedger(session, {
|
|
1032
|
+
batchId: entry.batchId ?? `pending-${entry.recordSeq}`,
|
|
1033
|
+
op: 'delete-turn',
|
|
1034
|
+
seqs: [entry.targetSeq],
|
|
1035
|
+
tombstoneSeqs: done.tombstoneSeqs,
|
|
1036
|
+
count: done.count,
|
|
1037
|
+
estimatedFreedTokens: tokensByTurn.get(entry.targetSeq) ?? 0,
|
|
1038
|
+
result: 'applied',
|
|
1039
|
+
})
|
|
1040
|
+
}
|
|
1041
|
+
} else {
|
|
1042
|
+
restoreOne(session, entry.targetSeq, turn, step)
|
|
1043
|
+
appendAck(session, entry.recordSeq, 'applied')
|
|
1044
|
+
// Close the undo ledger entry once the restore actually landed, so the
|
|
1045
|
+
// audit trail does not stay stuck at "queued".
|
|
1046
|
+
if (typeof entry.batchId === 'string') {
|
|
1047
|
+
appendBatchLedger(session, {
|
|
1048
|
+
batchId: entry.batchId,
|
|
1049
|
+
op: 'undo',
|
|
1050
|
+
seqs: [entry.targetSeq],
|
|
1051
|
+
tombstoneSeqs: [],
|
|
1052
|
+
count: 1,
|
|
1053
|
+
estimatedFreedTokens: 0,
|
|
1054
|
+
result: 'applied',
|
|
1055
|
+
})
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
} catch (error) {
|
|
1059
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
1060
|
+
const result = IDEMPOTENT_MARKERS.some((marker) => message.includes(marker)) ? 'skipped' : 'failed'
|
|
1061
|
+
appendAck(session, entry.recordSeq, result, message)
|
|
1062
|
+
if (result === 'failed') {
|
|
1063
|
+
ctx.logger?.warn?.(`context-manager: queued ${entry.op} ${entry.targetSeq} failed: ${message}`)
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
}
|
|
1067
|
+
// Refresh the incremental cache with the acks just appended.
|
|
1068
|
+
durableQueue(ctx, session)
|
|
1069
|
+
}
|
|
1070
|
+
|
|
1071
|
+
/**
|
|
1072
|
+
* Register one Agent-scoped `agent/request` listener for queued operations.
|
|
1073
|
+
* The request hook runs after `step/start` and before request derivation.
|
|
1074
|
+
* @returns whether the listener is available.
|
|
1075
|
+
*/
|
|
1076
|
+
function ensureAgentListener(ctx, agent) {
|
|
1077
|
+
if (agent === undefined || agent === null || typeof agent.id !== 'string') return false
|
|
1078
|
+
const agentListeners = listenerRegistry(ctx)
|
|
1079
|
+
const id = agent.id
|
|
1080
|
+
if (agentListeners.has(id)) return true
|
|
1081
|
+
const liveAgent = ctx.agents.get(id) ?? agent
|
|
1082
|
+
const owner = liveAgent.ctx ?? agent.ctx
|
|
1083
|
+
if (owner === undefined || owner === null || typeof owner.on !== 'function') return false
|
|
1084
|
+
const stop = owner.on('agent/request', (payload, next) => {
|
|
1085
|
+
if (payload === undefined || payload.agent === undefined || payload.agent.id !== id) return next()
|
|
1086
|
+
applyQueuedOperations(ctx, liveAgent, payload.turn, payload.step)
|
|
1087
|
+
return next()
|
|
1088
|
+
})
|
|
1089
|
+
const disposeOwnerEffect = typeof owner.effect === 'function'
|
|
1090
|
+
? owner.effect(() => () => {
|
|
1091
|
+
stop()
|
|
1092
|
+
agentListeners.delete(id)
|
|
1093
|
+
}, 'context-manager: queued operations')
|
|
1094
|
+
: () => {
|
|
1095
|
+
stop()
|
|
1096
|
+
agentListeners.delete(id)
|
|
1097
|
+
}
|
|
1098
|
+
agentListeners.set(id, { stop, disposeOwnerEffect })
|
|
1099
|
+
return true
|
|
1100
|
+
}
|
|
1101
|
+
|
|
1102
|
+
/** Parse `/ctxmgr` input into an operation. */
|
|
1103
|
+
function parseCommand(rawInput) {
|
|
1104
|
+
const text = typeof rawInput === 'string' ? rawInput.trim() : ''
|
|
1105
|
+
if (text.length === 0) return { op: 'list' }
|
|
1106
|
+
const parts = text.split(/\s+/)
|
|
1107
|
+
const head = parts[0].toLowerCase()
|
|
1108
|
+
if (head === 'list' || head === 'ls') return { op: 'list' }
|
|
1109
|
+
if (head === 'turns' || head === 'list-turns' || head === 'ls-turns') return { op: 'list-turns' }
|
|
1110
|
+
if (head === 'clean') {
|
|
1111
|
+
const rest = text.slice(head.length).trim()
|
|
1112
|
+
if (rest.length === 0) return { op: 'invalid', reason: '缺少要释放的 token 预算。' }
|
|
1113
|
+
if (!/^\d+$/.test(rest)) return { op: 'invalid', reason: '目标 token 数必须是正整数。' }
|
|
1114
|
+
return { op: 'clean', targetTokens: Number(rest) }
|
|
1115
|
+
}
|
|
1116
|
+
if (head === 'compact') {
|
|
1117
|
+
const rest = text.slice(head.length).trim()
|
|
1118
|
+
const values = rest.length === 0 ? [] : rest.split(/[,\s]+/).filter(Boolean)
|
|
1119
|
+
if (values.length !== 2) return { op: 'invalid', reason: 'compact 需要两个序号:起始与结束(按表面位置)。' }
|
|
1120
|
+
if (values.some((value) => !/^\d+$/.test(value))) return { op: 'invalid', reason: 'compact 的两个序号必须是数字。' }
|
|
1121
|
+
return { op: 'compact', start: Number(values[0]), end: Number(values[1]) }
|
|
1122
|
+
}
|
|
1123
|
+
if (head === 'batches' || head === 'ledger' || head === 'audit') return { op: 'batches' }
|
|
1124
|
+
if (head === 'undo-batch' || head === 'undobatch' || head === 'undo-last' || head === 'undolast') {
|
|
1125
|
+
const rest = text.slice(head.length).trim()
|
|
1126
|
+
return rest.length === 0 ? { op: 'undo-batch' } : { op: 'undo-batch', batchId: rest }
|
|
1127
|
+
}
|
|
1128
|
+
const deleteTurn = head === 'deleteturn' || head === 'delturn' || head === 'dt'
|
|
1129
|
+
if (head === 'delete' || head === 'rm' || head === 'restore' || head === 'undo' || deleteTurn) {
|
|
1130
|
+
const rest = text.slice(head.length).trim()
|
|
1131
|
+
const values = rest.length === 0 ? [] : rest.split(/[,\s]+/).filter(Boolean)
|
|
1132
|
+
if (values.length === 0) return { op: 'invalid', reason: deleteTurn ? '缺少要删除的轮号。' : '缺少要处理的序号。' }
|
|
1133
|
+
if (values.some((value) => !/^\d+$/.test(value))) return { op: 'invalid', reason: '轮号/序号必须是数字,多个用逗号分隔。' }
|
|
1134
|
+
return {
|
|
1135
|
+
op: deleteTurn ? 'delete-turns' : head === 'restore' || head === 'undo' ? 'restore' : 'delete',
|
|
1136
|
+
seqs: values.map(Number),
|
|
1137
|
+
}
|
|
1138
|
+
}
|
|
1139
|
+
return { op: 'invalid', reason: `未知子命令 “${parts[0]}”。` }
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
export function apply(ctx) {
|
|
1143
|
+
for (const liveAgent of ctx.agents.list()) ensureAgentListener(ctx, liveAgent)
|
|
1144
|
+
const stopCreated = ctx.on('agent/created', (payload) => {
|
|
1145
|
+
if (payload !== undefined) ensureAgentListener(ctx, payload.agent)
|
|
1146
|
+
})
|
|
1147
|
+
|
|
1148
|
+
const command = ctx.commands.register({
|
|
1149
|
+
name: 'ctxmgr',
|
|
1150
|
+
description: '列出、批量删除或恢复当前会话中的单条消息,并按轮删除整轮对话,支持按 token 预算自动清理(仅移出/恢复模型上下文,保留原始日志)。',
|
|
1151
|
+
input: { hint: 'list | turns | delete <序号,...> | deleteturn <轮号,...> | clean <目标tokens> | compact <起序号> <止序号> | batches | undo-batch [batchId] | restore <删除记录序号,...>' },
|
|
1152
|
+
recordInput: false,
|
|
1153
|
+
async handler(invocation) {
|
|
1154
|
+
try {
|
|
1155
|
+
const parsed = parseCommand(invocation.rawInput)
|
|
1156
|
+
if (parsed.op === 'list') {
|
|
1157
|
+
const result = await listMessages(ctx, invocation.agent)
|
|
1158
|
+
return { kind: 'success', text: result.text }
|
|
1159
|
+
}
|
|
1160
|
+
if (parsed.op === 'list-turns') {
|
|
1161
|
+
const result = await listTurns(ctx, invocation.agent)
|
|
1162
|
+
return { kind: 'success', text: result.text }
|
|
1163
|
+
}
|
|
1164
|
+
if (parsed.op === 'delete') {
|
|
1165
|
+
const result = await deleteMessages(ctx, invocation.agent, parsed.seqs)
|
|
1166
|
+
return { kind: 'success', text: result.text }
|
|
1167
|
+
}
|
|
1168
|
+
if (parsed.op === 'delete-turns') {
|
|
1169
|
+
const result = await deleteTurns(ctx, invocation.agent, parsed.seqs)
|
|
1170
|
+
return { kind: 'success', text: result.text }
|
|
1171
|
+
}
|
|
1172
|
+
if (parsed.op === 'clean') {
|
|
1173
|
+
const result = await cleanMessages(ctx, invocation.agent, parsed.targetTokens, {})
|
|
1174
|
+
return { kind: 'success', text: result.text }
|
|
1175
|
+
}
|
|
1176
|
+
if (parsed.op === 'compact') {
|
|
1177
|
+
const result = await compactSelection(ctx, invocation.agent, parsed.start, parsed.end)
|
|
1178
|
+
return { kind: 'success', text: result.text }
|
|
1179
|
+
}
|
|
1180
|
+
if (parsed.op === 'batches') {
|
|
1181
|
+
const result = await listBatches(ctx, invocation.agent)
|
|
1182
|
+
return { kind: 'success', text: result.text }
|
|
1183
|
+
}
|
|
1184
|
+
if (parsed.op === 'undo-batch') {
|
|
1185
|
+
const result = await undoBatch(ctx, invocation.agent, parsed.batchId)
|
|
1186
|
+
return { kind: 'success', text: result.text }
|
|
1187
|
+
}
|
|
1188
|
+
if (parsed.op === 'restore') {
|
|
1189
|
+
const result = await restoreMessages(ctx, invocation.agent, parsed.seqs)
|
|
1190
|
+
return { kind: 'success', text: result.text }
|
|
1191
|
+
}
|
|
1192
|
+
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 <删除记录序号,...>` }
|
|
1193
|
+
} catch (error) {
|
|
1194
|
+
return { kind: 'error', text: error instanceof Error ? error.message : String(error) }
|
|
1195
|
+
}
|
|
1196
|
+
},
|
|
1197
|
+
})
|
|
1198
|
+
|
|
1199
|
+
const tool = ctx.tools.register({
|
|
1200
|
+
name: 'context_manager',
|
|
1201
|
+
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.',
|
|
1202
|
+
parameters: {
|
|
1203
|
+
type: 'object',
|
|
1204
|
+
properties: {
|
|
1205
|
+
action: {
|
|
1206
|
+
type: 'string',
|
|
1207
|
+
enum: ['list', 'list-turns', 'delete', 'delete-turns', 'clean', 'compact', 'batches', 'undo-batch', 'restore'],
|
|
1208
|
+
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.',
|
|
1209
|
+
},
|
|
1210
|
+
seq: {
|
|
1211
|
+
type: 'integer',
|
|
1212
|
+
description: 'One message seq for delete (legacy single-target form).',
|
|
1213
|
+
},
|
|
1214
|
+
seqs: {
|
|
1215
|
+
type: 'array',
|
|
1216
|
+
items: { type: 'integer' },
|
|
1217
|
+
description: 'Message seqs for delete, turn numbers for delete-turns, or tombstone seqs for restore (from list/turns output).',
|
|
1218
|
+
},
|
|
1219
|
+
targetTokens: {
|
|
1220
|
+
type: 'integer',
|
|
1221
|
+
description: 'For clean: the token budget (target number of tokens to free).',
|
|
1222
|
+
},
|
|
1223
|
+
minCandidateTokens: {
|
|
1224
|
+
type: 'integer',
|
|
1225
|
+
description: 'For clean: optional minimum estimated tokens for a message to be considered a candidate (default 100).',
|
|
1226
|
+
},
|
|
1227
|
+
protectRecent: {
|
|
1228
|
+
type: 'integer',
|
|
1229
|
+
description: 'For clean: optional number of most recent messages to protect (default 3).',
|
|
1230
|
+
},
|
|
1231
|
+
batchId: {
|
|
1232
|
+
type: 'string',
|
|
1233
|
+
description: 'For undo-batch: optional batch id (or unambiguous prefix) from the ledger; omit to undo the most recent applied batch.',
|
|
1234
|
+
},
|
|
1235
|
+
start: {
|
|
1236
|
+
type: 'integer',
|
|
1237
|
+
description: 'For compact: first surface seq of the span to compact (inclusive, from list).',
|
|
1238
|
+
},
|
|
1239
|
+
end: {
|
|
1240
|
+
type: 'integer',
|
|
1241
|
+
description: 'For compact: last surface seq of the span to compact (inclusive, from list); both edges must be tool-pairing balanced.',
|
|
1242
|
+
},
|
|
1243
|
+
},
|
|
1244
|
+
required: ['action'],
|
|
1245
|
+
additionalProperties: false,
|
|
1246
|
+
},
|
|
1247
|
+
output: {
|
|
1248
|
+
schema: {
|
|
1249
|
+
type: 'object',
|
|
1250
|
+
properties: {
|
|
1251
|
+
ok: { type: 'boolean', description: 'Whether the operation succeeded.' },
|
|
1252
|
+
text: { type: 'string', description: 'Human-readable result or message list.' },
|
|
1253
|
+
},
|
|
1254
|
+
required: ['ok', 'text'],
|
|
1255
|
+
additionalProperties: false,
|
|
1256
|
+
},
|
|
1257
|
+
render(_args, value) {
|
|
1258
|
+
return [{ type: 'text', text: typeof value?.text === 'string' ? value.text : '' }]
|
|
1259
|
+
},
|
|
1260
|
+
},
|
|
1261
|
+
async execute(args, exec) {
|
|
1262
|
+
const action = args?.action
|
|
1263
|
+
const list = Array.isArray(args?.seqs)
|
|
1264
|
+
? args.seqs
|
|
1265
|
+
: Number.isSafeInteger(args?.seq) ? [args.seq] : []
|
|
1266
|
+
if (action === 'list') {
|
|
1267
|
+
const result = await listMessages(ctx, exec.agent)
|
|
1268
|
+
return { ok: true, text: result.text }
|
|
1269
|
+
}
|
|
1270
|
+
if (action === 'list-turns') {
|
|
1271
|
+
const result = await listTurns(ctx, exec.agent)
|
|
1272
|
+
return { ok: true, text: result.text }
|
|
1273
|
+
}
|
|
1274
|
+
if (action === 'delete') {
|
|
1275
|
+
if (list.length === 0) throw new Error('delete 需要 list 返回的整数 seq 或 seqs。')
|
|
1276
|
+
const result = await deleteMessages(ctx, exec.agent, list)
|
|
1277
|
+
return { ok: true, text: result.text }
|
|
1278
|
+
}
|
|
1279
|
+
if (action === 'delete-turns') {
|
|
1280
|
+
if (list.length === 0) throw new Error('delete-turns 需要 list-turns 返回的整数轮号。')
|
|
1281
|
+
const result = await deleteTurns(ctx, exec.agent, list)
|
|
1282
|
+
return { ok: true, text: result.text }
|
|
1283
|
+
}
|
|
1284
|
+
if (action === 'clean') {
|
|
1285
|
+
if (!Number.isSafeInteger(args?.targetTokens) || args.targetTokens <= 0) {
|
|
1286
|
+
throw new Error('clean 需要正整数 targetTokens(要释放的 token 预算)。')
|
|
1287
|
+
}
|
|
1288
|
+
const result = await cleanMessages(ctx, exec.agent, args.targetTokens, {
|
|
1289
|
+
minCandidateTokens: args?.minCandidateTokens,
|
|
1290
|
+
protectRecent: args?.protectRecent,
|
|
1291
|
+
})
|
|
1292
|
+
return { ok: true, text: result.text }
|
|
1293
|
+
}
|
|
1294
|
+
if (action === 'compact') {
|
|
1295
|
+
if (!Number.isSafeInteger(args?.start) || !Number.isSafeInteger(args?.end)) {
|
|
1296
|
+
throw new Error('compact 需要整数 start 与 end(list 返回的表面序号)。')
|
|
1297
|
+
}
|
|
1298
|
+
const result = await compactSelection(ctx, exec.agent, args.start, args.end)
|
|
1299
|
+
return { ok: true, text: result.text }
|
|
1300
|
+
}
|
|
1301
|
+
if (action === 'batches') {
|
|
1302
|
+
const result = await listBatches(ctx, exec.agent)
|
|
1303
|
+
return { ok: true, text: result.text }
|
|
1304
|
+
}
|
|
1305
|
+
if (action === 'undo-batch') {
|
|
1306
|
+
const result = await undoBatch(ctx, exec.agent,
|
|
1307
|
+
typeof args?.batchId === 'string' ? args.batchId : undefined)
|
|
1308
|
+
return { ok: true, text: result.text }
|
|
1309
|
+
}
|
|
1310
|
+
if (action === 'restore') {
|
|
1311
|
+
if (list.length === 0) throw new Error('restore 需要已删除记录返回的整数 tombstone seq。')
|
|
1312
|
+
const result = await restoreMessages(ctx, exec.agent, list)
|
|
1313
|
+
return { ok: true, text: result.text }
|
|
1314
|
+
}
|
|
1315
|
+
throw new Error('action 必须是 list、list-turns、delete、delete-turns、clean、compact、batches、undo-batch 或 restore。')
|
|
1316
|
+
},
|
|
1317
|
+
})
|
|
1318
|
+
|
|
1319
|
+
ctx.effect(() => () => {
|
|
1320
|
+
tool()
|
|
1321
|
+
command()
|
|
1322
|
+
stopCreated()
|
|
1323
|
+
const agentListeners = listenerRegistry(ctx)
|
|
1324
|
+
for (const entry of [...agentListeners.values()]) {
|
|
1325
|
+
entry.stop()
|
|
1326
|
+
entry.disposeOwnerEffect()
|
|
1327
|
+
}
|
|
1328
|
+
agentListeners.clear()
|
|
1329
|
+
}, 'context-manager: command, tool, and queued operations')
|
|
1330
|
+
}
|