dsh-context-manager 0.0.0-stage → 1.6.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 +56 -0
- package/LICENSE +21 -0
- package/README.md +227 -3
- package/client.js +1150 -0
- package/cordis.patch.yml +3 -0
- package/core.js +470 -0
- package/docs/DETAIL.md +6 -0
- package/docs/DETAIL.zh.md +6 -0
- package/docs/preview.svg +56 -0
- package/icon.svg +19 -0
- package/index.js +862 -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,862 @@
|
|
|
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
|
+
deletedFromSurface,
|
|
34
|
+
foldSurface,
|
|
35
|
+
formatList,
|
|
36
|
+
formatTurns,
|
|
37
|
+
hasToolChange,
|
|
38
|
+
isTombstoneKind,
|
|
39
|
+
itemsFromSurface,
|
|
40
|
+
planDeletion,
|
|
41
|
+
tombstoneData,
|
|
42
|
+
turnsFromSurface,
|
|
43
|
+
} from './core.js'
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Load the Session core the Host itself runs on.
|
|
47
|
+
*
|
|
48
|
+
* A profile-linked plugin cannot resolve `@deepseek-ai/*` by bare name: its
|
|
49
|
+
* realpath sits outside the profile, and the packaged desktop carries the core
|
|
50
|
+
* packages only inside the application asar. Try the bare specifier first (dev
|
|
51
|
+
* checkouts with a real node_modules), then anchor on the Host process's
|
|
52
|
+
* runtime directory — the packaged desktop Host starts with that directory as
|
|
53
|
+
* `process.argv[2]`, and importing the same file URL yields the same module
|
|
54
|
+
* instance the Host itself uses, so Session private-field brand checks pass.
|
|
55
|
+
*/
|
|
56
|
+
let sessionCore
|
|
57
|
+
try {
|
|
58
|
+
sessionCore = await import('@deepseek-ai/dsh-session')
|
|
59
|
+
} catch {
|
|
60
|
+
const runtimeDir = process.argv[2]
|
|
61
|
+
if (typeof runtimeDir !== 'string' || runtimeDir.length === 0) {
|
|
62
|
+
throw new Error('context-manager 无法加载 @deepseek-ai/dsh-session:裸导入失败,且当前进程不是携带运行时目录的桌面 Host。')
|
|
63
|
+
}
|
|
64
|
+
sessionCore = await import(pathToFileURL(join(runtimeDir, 'node_modules', '@deepseek-ai', 'dsh-session', 'lib', 'index.js')).href)
|
|
65
|
+
}
|
|
66
|
+
const { appendPluginRecord, pluginRecordOf } = sessionCore
|
|
67
|
+
|
|
68
|
+
export const name = 'context-manager'
|
|
69
|
+
|
|
70
|
+
export const inject = ['sessions', 'agents', 'commands', 'tools']
|
|
71
|
+
|
|
72
|
+
const RESTORED_PREFIX = 'restored-assistant-'
|
|
73
|
+
const PENDING_TYPE = 'plugin:context-manager/pending'
|
|
74
|
+
const ACK_TYPE = 'plugin:context-manager/ack'
|
|
75
|
+
/** Queue record types older releases wrote; still applied after an upgrade. */
|
|
76
|
+
const LEGACY_PENDING_TYPES = ['plugin:message-manager/pending']
|
|
77
|
+
const LEGACY_ACK_TYPES = ['plugin:message-manager/ack']
|
|
78
|
+
/** Messages that mean a replayed operation already happened; ack as skipped. */
|
|
79
|
+
const IDEMPOTENT_MARKERS = ['已不在当前表面', '已经恢复', '已不在会话日志']
|
|
80
|
+
|
|
81
|
+
/** Resolve the live Session behind one command/tool agent. */
|
|
82
|
+
function liveSession(ctx, agent) {
|
|
83
|
+
if (agent === undefined || agent === null || typeof agent.id !== 'string') {
|
|
84
|
+
throw new Error('上下文管理需要一个会话作用域。')
|
|
85
|
+
}
|
|
86
|
+
const session = ctx.sessions.get(agent.id)
|
|
87
|
+
if (session === undefined) throw new Error('当前会话未处于运行状态,无法读取或修改消息上下文。')
|
|
88
|
+
return session
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Read the complete current model surface for one live Session. */
|
|
92
|
+
async function readSurfaceEvents(ctx, session) {
|
|
93
|
+
const query = ctx.get('sessionQuery')
|
|
94
|
+
if (query !== undefined && typeof query.readSurface === 'function') {
|
|
95
|
+
const snapshot = await query.readSurface(session.id)
|
|
96
|
+
return snapshot.events
|
|
97
|
+
}
|
|
98
|
+
const folded = foldSurface(session.snapshotEvents())
|
|
99
|
+
return folded.nodes.map((seq) => session.eventAt(seq)).filter((event) => event !== undefined)
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Read the current surface synchronously (used inside the request hook). */
|
|
103
|
+
function surfaceEventsSync(session) {
|
|
104
|
+
return session.surface.nodes
|
|
105
|
+
.map((seq) => session.eventAt(seq))
|
|
106
|
+
.filter((event) => event !== undefined)
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Read the turn/step that is open at the very end of the live log.
|
|
111
|
+
* Scans backward: the last boundary marker decides the state, so an open step
|
|
112
|
+
* deep in a long session is found without walking the whole log.
|
|
113
|
+
* @returns the open coordinates plus the opening step seq, or undefined.
|
|
114
|
+
*/
|
|
115
|
+
function openStepOf(session) {
|
|
116
|
+
const events = session.snapshotEvents()
|
|
117
|
+
for (let index = events.length - 1; index >= 0; index -= 1) {
|
|
118
|
+
const event = events[index]
|
|
119
|
+
if (event.type === 'turn/end' || event.type === 'step/end' || event.type === 'turn/start') return undefined
|
|
120
|
+
if (event.type === 'step/start') {
|
|
121
|
+
const { turn, step } = event.data ?? {}
|
|
122
|
+
if (Number.isSafeInteger(turn) && Number.isSafeInteger(step) && turn >= 0 && step >= 0) {
|
|
123
|
+
return { turn, step, startSeq: event.seq }
|
|
124
|
+
}
|
|
125
|
+
break // unusual payload; fall back to the full forward scan
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
let turn = null
|
|
129
|
+
let step = null
|
|
130
|
+
let startSeq
|
|
131
|
+
for (const event of events) {
|
|
132
|
+
switch (event.type) {
|
|
133
|
+
case 'turn/start':
|
|
134
|
+
turn = event.data.turn
|
|
135
|
+
step = null
|
|
136
|
+
startSeq = undefined
|
|
137
|
+
break
|
|
138
|
+
case 'turn/end':
|
|
139
|
+
turn = null
|
|
140
|
+
step = null
|
|
141
|
+
startSeq = undefined
|
|
142
|
+
break
|
|
143
|
+
case 'step/start':
|
|
144
|
+
step = event.data.step
|
|
145
|
+
startSeq = event.seq
|
|
146
|
+
break
|
|
147
|
+
case 'step/end':
|
|
148
|
+
step = null
|
|
149
|
+
startSeq = undefined
|
|
150
|
+
break
|
|
151
|
+
default:
|
|
152
|
+
break
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return turn !== null && step !== null && startSeq !== undefined
|
|
156
|
+
? { turn, step, startSeq }
|
|
157
|
+
: undefined
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Append tombstone replacements for one plan inside an open turn/step. */
|
|
161
|
+
function appendTombstones(session, runs, turn, step) {
|
|
162
|
+
const tombstoneSeqs = []
|
|
163
|
+
try {
|
|
164
|
+
for (const run of runs) {
|
|
165
|
+
const event = session.append(
|
|
166
|
+
'developer/message',
|
|
167
|
+
tombstoneData(turn, step, randomUUID()),
|
|
168
|
+
{
|
|
169
|
+
surfaceOp: { op: 'replace', startSeq: run.startSeq, endSeq: run.endSeq },
|
|
170
|
+
sourceEventSeqs: run.seqs,
|
|
171
|
+
},
|
|
172
|
+
)
|
|
173
|
+
tombstoneSeqs.push(event.seq)
|
|
174
|
+
}
|
|
175
|
+
} catch (error) {
|
|
176
|
+
const reason = error instanceof Error ? error.message : String(error)
|
|
177
|
+
if (tombstoneSeqs.length > 0) {
|
|
178
|
+
throw new Error(`已删除部分内容,后续替换失败:${reason}。请刷新后重试。`)
|
|
179
|
+
}
|
|
180
|
+
throw new Error(`删除失败:${reason}`)
|
|
181
|
+
}
|
|
182
|
+
return tombstoneSeqs
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/** Whether one event is an empty context-manager tombstone, current or legacy kind. */
|
|
186
|
+
function isTombstone(event) {
|
|
187
|
+
return event !== undefined
|
|
188
|
+
&& event !== null
|
|
189
|
+
&& event.type === 'developer/message'
|
|
190
|
+
&& Array.isArray(event.data?.message?.content)
|
|
191
|
+
&& event.data.message.content.length === 0
|
|
192
|
+
&& isTombstoneKind(event.data?.message?.source?.kind)
|
|
193
|
+
&& event.surfaceOp !== null
|
|
194
|
+
&& typeof event.surfaceOp === 'object'
|
|
195
|
+
&& event.surfaceOp.op === 'replace'
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Tool-call blocks carried by one assistant message. */
|
|
199
|
+
function assistantToolCalls(event) {
|
|
200
|
+
if (event === undefined || event.type !== 'assistant/message') return []
|
|
201
|
+
const content = event.data?.message?.content
|
|
202
|
+
return Array.isArray(content)
|
|
203
|
+
? content.filter((block) => block !== null && typeof block === 'object' && block.type === 'tool-call')
|
|
204
|
+
: []
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/** Per-plugin-instance incremental scan state, keyed by plugin ctx then session id. */
|
|
208
|
+
const queueCaches = new WeakMap()
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Unacknowledged pending operations in log order, incrementally.
|
|
212
|
+
*
|
|
213
|
+
* The queue lives in the session log as plugin records, so a restart replays it
|
|
214
|
+
* for free; within one process each event is examined exactly once.
|
|
215
|
+
* @returns durable queue entries: { recordSeq, op, targetSeq }.
|
|
216
|
+
*/
|
|
217
|
+
function durableQueue(ctx, session) {
|
|
218
|
+
let cache = queueCaches.get(ctx)
|
|
219
|
+
if (cache === undefined) {
|
|
220
|
+
cache = new Map()
|
|
221
|
+
queueCaches.set(ctx, cache)
|
|
222
|
+
}
|
|
223
|
+
const state = cache.get(session.id) ?? { checkedTo: -1, pending: new Map() }
|
|
224
|
+
const events = session.snapshotEvents(Math.max(0, state.checkedTo + 1))
|
|
225
|
+
for (const event of events) {
|
|
226
|
+
const record = pluginRecordOf(event)
|
|
227
|
+
if (record === undefined) continue
|
|
228
|
+
if (record.type === ACK_TYPE || LEGACY_ACK_TYPES.includes(record.type)) {
|
|
229
|
+
const pendingSeq = record.data?.pendingSeq
|
|
230
|
+
if (Number.isSafeInteger(pendingSeq)) state.pending.delete(pendingSeq)
|
|
231
|
+
} else if (record.type === PENDING_TYPE || LEGACY_PENDING_TYPES.includes(record.type)) {
|
|
232
|
+
const op = record.data?.op
|
|
233
|
+
const targetSeq = record.data?.targetSeq
|
|
234
|
+
if ((op === 'delete' || op === 'restore' || op === 'delete-turn') && Number.isSafeInteger(targetSeq)) {
|
|
235
|
+
state.pending.set(record.seq, { recordSeq: record.seq, op, targetSeq })
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
if (events.length > 0) state.checkedTo = events[events.length - 1].seq
|
|
240
|
+
cache.set(session.id, state)
|
|
241
|
+
return [...state.pending.values()]
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Durably enqueue one operation; plugin records need no open turn/step. */
|
|
245
|
+
function appendPending(session, op, targetSeq) {
|
|
246
|
+
return appendPluginRecord(session, PENDING_TYPE, { op, targetSeq })
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Acknowledge one pending record so restarts and replays leave it alone. */
|
|
250
|
+
function appendAck(session, pendingSeq, result, detail) {
|
|
251
|
+
appendPluginRecord(session, ACK_TYPE, {
|
|
252
|
+
pendingSeq,
|
|
253
|
+
result,
|
|
254
|
+
...typeof detail === 'string' && detail.length > 0 ? { detail: detail.slice(0, 300) } : {},
|
|
255
|
+
})
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/**
|
|
259
|
+
* Classify one tombstone into a restore plan without mutating the Session.
|
|
260
|
+
* @throws when the tombstone or its original group cannot be restored safely.
|
|
261
|
+
*/
|
|
262
|
+
function planRestore(session, tombstoneSeq) {
|
|
263
|
+
if (!session.surface.nodes.includes(tombstoneSeq)) throw new Error('该删除记录已不在当前表面,可能已被恢复。')
|
|
264
|
+
const tombstone = session.eventAt(tombstoneSeq)
|
|
265
|
+
if (!isTombstone(tombstone)) throw new Error('该序号不是本插件的删除记录。')
|
|
266
|
+
const targets = tombstone.sourceEventSeqs
|
|
267
|
+
if (!Array.isArray(targets) || targets.length === 0) throw new Error('删除记录缺少原始消息引用。')
|
|
268
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
269
|
+
const originals = targets.map((seq) => bySeq.get(seq))
|
|
270
|
+
if (originals.some((event) => event === undefined)) throw new Error('原始消息已不在会话日志中,无法恢复。')
|
|
271
|
+
|
|
272
|
+
if (originals.length === 1) {
|
|
273
|
+
const original = originals[0]
|
|
274
|
+
if (original.type === 'user/message') return { kind: 'user', original }
|
|
275
|
+
if (original.type === 'developer/message') {
|
|
276
|
+
if (hasToolChange(original)) throw new Error('该上下文消息携带工具变更,不能恢复。')
|
|
277
|
+
return { kind: 'developer', original }
|
|
278
|
+
}
|
|
279
|
+
if (original.type === 'assistant/message') {
|
|
280
|
+
if (assistantToolCalls(original).length > 0) throw new Error('该助手消息属于工具调用组,无法单独恢复。')
|
|
281
|
+
if (!Array.isArray(original.data?.message?.content) || original.data.message.content.length === 0) {
|
|
282
|
+
throw new Error('该助手消息没有可恢复的内容。')
|
|
283
|
+
}
|
|
284
|
+
return { kind: 'assistant', original }
|
|
285
|
+
}
|
|
286
|
+
throw new Error('该类型的消息暂不支持恢复。')
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
const assistant = originals[0]
|
|
290
|
+
if (assistant.type !== 'assistant/message') throw new Error('删除组不是可恢复的助手消息组。')
|
|
291
|
+
const calls = assistantToolCalls(assistant)
|
|
292
|
+
if (calls.length === 0) throw new Error('删除组不是可恢复的助手消息组。')
|
|
293
|
+
const results = originals.slice(1)
|
|
294
|
+
if (results.some((event) => event.type !== 'tool/result')) throw new Error('删除组包含不支持恢复的消息类型。')
|
|
295
|
+
const callIds = new Set(calls.map((block) => block.id))
|
|
296
|
+
const resultIds = new Set()
|
|
297
|
+
for (const result of results) {
|
|
298
|
+
const callId = result.data?.message?.toolCallId
|
|
299
|
+
if (!callIds.has(callId)) throw new Error('删除组的工具调用与结果不匹配,无法恢复。')
|
|
300
|
+
resultIds.add(callId)
|
|
301
|
+
}
|
|
302
|
+
if (resultIds.size !== callIds.size) throw new Error('删除组的工具调用不完整,无法恢复。')
|
|
303
|
+
return { kind: 'group', assistant, calls, results }
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Append an assistant copy at the tail and return its marker message id. */
|
|
307
|
+
function appendAssistantCopy(session, original, tombstoneSeq, turn, step) {
|
|
308
|
+
const messageId = `${RESTORED_PREFIX}${tombstoneSeq}-${randomUUID()}`
|
|
309
|
+
session.append('assistant/message', {
|
|
310
|
+
turn,
|
|
311
|
+
step,
|
|
312
|
+
message: {
|
|
313
|
+
id: messageId,
|
|
314
|
+
role: 'assistant',
|
|
315
|
+
content: original.data.message.content,
|
|
316
|
+
source: original.data.message.source,
|
|
317
|
+
},
|
|
318
|
+
stream: [],
|
|
319
|
+
}, { surfaceOp: 'append' })
|
|
320
|
+
return messageId
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/** Restore one tombstone inside the request's open step. */
|
|
324
|
+
function restoreOne(session, tombstoneSeq, turn, step) {
|
|
325
|
+
const plan = planRestore(session, tombstoneSeq)
|
|
326
|
+
if (plan.kind === 'user') {
|
|
327
|
+
session.append(
|
|
328
|
+
'user/message',
|
|
329
|
+
{ ...plan.original.data, id: randomUUID() },
|
|
330
|
+
{
|
|
331
|
+
surfaceOp: { op: 'replace', startSeq: tombstoneSeq, endSeq: tombstoneSeq },
|
|
332
|
+
sourceEventSeqs: [tombstoneSeq],
|
|
333
|
+
},
|
|
334
|
+
)
|
|
335
|
+
return
|
|
336
|
+
}
|
|
337
|
+
if (plan.kind === 'developer') {
|
|
338
|
+
const data = {
|
|
339
|
+
...plan.original.data,
|
|
340
|
+
turn,
|
|
341
|
+
step,
|
|
342
|
+
message: { ...plan.original.data.message, id: randomUUID() },
|
|
343
|
+
}
|
|
344
|
+
delete data.headerSeq
|
|
345
|
+
session.append(
|
|
346
|
+
'developer/message',
|
|
347
|
+
data,
|
|
348
|
+
{
|
|
349
|
+
surfaceOp: { op: 'replace', startSeq: tombstoneSeq, endSeq: tombstoneSeq },
|
|
350
|
+
sourceEventSeqs: [tombstoneSeq],
|
|
351
|
+
},
|
|
352
|
+
)
|
|
353
|
+
return
|
|
354
|
+
}
|
|
355
|
+
if (plan.kind === 'assistant') {
|
|
356
|
+
const marker = `${RESTORED_PREFIX}${tombstoneSeq}-`
|
|
357
|
+
if (surfaceEventsSync(session).some((event) => event.type === 'assistant/message'
|
|
358
|
+
&& typeof event.data?.message?.id === 'string'
|
|
359
|
+
&& event.data.message.id.startsWith(marker))) {
|
|
360
|
+
throw new Error('该消息已经恢复。')
|
|
361
|
+
}
|
|
362
|
+
appendAssistantCopy(session, plan.original, tombstoneSeq, turn, step)
|
|
363
|
+
return
|
|
364
|
+
}
|
|
365
|
+
if (plan.kind === 'group') {
|
|
366
|
+
const marker = `${RESTORED_PREFIX}${tombstoneSeq}-`
|
|
367
|
+
if (surfaceEventsSync(session).some((event) => event.type === 'assistant/message'
|
|
368
|
+
&& typeof event.data?.message?.id === 'string'
|
|
369
|
+
&& event.data.message.id.startsWith(marker))) {
|
|
370
|
+
throw new Error('该消息组已经恢复。')
|
|
371
|
+
}
|
|
372
|
+
appendAssistantCopy(session, plan.assistant, tombstoneSeq, turn, step)
|
|
373
|
+
for (const call of plan.calls) {
|
|
374
|
+
session.append('tool/call', {
|
|
375
|
+
turn,
|
|
376
|
+
step,
|
|
377
|
+
callId: call.id,
|
|
378
|
+
name: call.name,
|
|
379
|
+
arguments: call.arguments,
|
|
380
|
+
})
|
|
381
|
+
}
|
|
382
|
+
for (const result of plan.results) {
|
|
383
|
+
const message = result.data.message
|
|
384
|
+
const data = {
|
|
385
|
+
turn,
|
|
386
|
+
step,
|
|
387
|
+
message: {
|
|
388
|
+
id: randomUUID(),
|
|
389
|
+
role: 'tool',
|
|
390
|
+
content: message.content,
|
|
391
|
+
source: message.source,
|
|
392
|
+
toolCallId: message.toolCallId,
|
|
393
|
+
...message.isError === true ? { isError: true } : {},
|
|
394
|
+
},
|
|
395
|
+
...result.data.error === undefined ? {} : { error: result.data.error },
|
|
396
|
+
}
|
|
397
|
+
session.append('tool/result', data, { surfaceOp: 'append' })
|
|
398
|
+
}
|
|
399
|
+
return
|
|
400
|
+
}
|
|
401
|
+
throw new Error('不支持恢复该删除记录。')
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** List current surface messages plus deleted records and durable queue. */
|
|
405
|
+
async function listMessages(ctx, agent) {
|
|
406
|
+
const session = liveSession(ctx, agent)
|
|
407
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
408
|
+
const items = itemsFromSurface(events)
|
|
409
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
410
|
+
const deleted = deletedFromSurface(events, bySeq)
|
|
411
|
+
const pending = durableQueue(ctx, session)
|
|
412
|
+
return { text: formatList(items, deleted, pending), items, deleted, pending }
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
/** Delete one or more messages now when safe, otherwise queue them durably. */
|
|
416
|
+
async function deleteMessages(ctx, agent, seqs) {
|
|
417
|
+
const unique = [...new Set(seqs)]
|
|
418
|
+
if (unique.length === 0 || unique.some((seq) => !Number.isSafeInteger(seq) || seq < 0)) {
|
|
419
|
+
throw new Error('序号必须是非负整数。')
|
|
420
|
+
}
|
|
421
|
+
const session = liveSession(ctx, agent)
|
|
422
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
423
|
+
const targets = []
|
|
424
|
+
for (const seq of unique) {
|
|
425
|
+
const plan = planDeletion(events, seq)
|
|
426
|
+
if (!plan.ok) {
|
|
427
|
+
if (plan.reason === 'system') throw new Error('系统提示词不是可删除的对话消息。')
|
|
428
|
+
if (plan.reason === 'not-found') {
|
|
429
|
+
if (unique.length === 1) throw new Error('该消息已不在当前模型上下文中,可能已被删除;请刷新后重试。')
|
|
430
|
+
continue
|
|
431
|
+
}
|
|
432
|
+
throw new Error('这条消息不支持单独删除。')
|
|
433
|
+
}
|
|
434
|
+
targets.push({ seq, plan })
|
|
435
|
+
}
|
|
436
|
+
if (targets.length === 0) throw new Error('选中的消息都已不在当前模型上下文中。')
|
|
437
|
+
|
|
438
|
+
const open = openStepOf(session)
|
|
439
|
+
const touchesOpenStep = open !== undefined
|
|
440
|
+
&& targets.some((target) => target.plan.indices.some((index) => events[index].seq >= open.startSeq))
|
|
441
|
+
if (open !== undefined && !touchesOpenStep) {
|
|
442
|
+
let count = 0
|
|
443
|
+
for (const target of targets) {
|
|
444
|
+
// Re-plan against the live surface because an earlier target may have
|
|
445
|
+
// already removed this target as part of the same tool group.
|
|
446
|
+
const current = surfaceEventsSync(session)
|
|
447
|
+
const plan = planDeletion(current, target.seq)
|
|
448
|
+
if (!plan.ok) continue
|
|
449
|
+
appendTombstones(session, plan.runs, open.turn, open.step)
|
|
450
|
+
count += plan.count
|
|
451
|
+
}
|
|
452
|
+
return {
|
|
453
|
+
text: `已从模型上下文删除 ${count} 条消息(会话日志与聊天记录仍保留)。`,
|
|
454
|
+
count,
|
|
455
|
+
queued: false,
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
const queuedTargets = new Set(durableQueue(ctx, session)
|
|
460
|
+
.filter((entry) => entry.op === 'delete')
|
|
461
|
+
.map((entry) => entry.targetSeq))
|
|
462
|
+
let added = 0
|
|
463
|
+
for (const target of targets) {
|
|
464
|
+
if (queuedTargets.has(target.seq)) continue
|
|
465
|
+
appendPending(session, 'delete', target.seq)
|
|
466
|
+
queuedTargets.add(target.seq)
|
|
467
|
+
added += 1
|
|
468
|
+
}
|
|
469
|
+
if (!ensureAgentListener(ctx, agent)) {
|
|
470
|
+
throw new Error('当前会话没有可用的 Agent 请求作用域,无法排队删除;请重试。')
|
|
471
|
+
}
|
|
472
|
+
return {
|
|
473
|
+
text: added === 0
|
|
474
|
+
? '选中的消息已在删除队列中,将在下一回合开始时生效。'
|
|
475
|
+
: `已加入删除队列:${added} 条消息将在下一回合开始时从模型上下文移除(会话日志与聊天记录仍保留)。`,
|
|
476
|
+
count: added,
|
|
477
|
+
queued: true,
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/** Queue one or more tombstones for restore at the next request. */
|
|
482
|
+
async function restoreMessages(ctx, agent, tombstoneSeqs) {
|
|
483
|
+
const unique = [...new Set(tombstoneSeqs)]
|
|
484
|
+
if (unique.length === 0 || unique.some((seq) => !Number.isSafeInteger(seq) || seq < 0)) {
|
|
485
|
+
throw new Error('删除记录序号必须是非负整数。')
|
|
486
|
+
}
|
|
487
|
+
const session = liveSession(ctx, agent)
|
|
488
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
489
|
+
const accepted = []
|
|
490
|
+
for (const seq of unique) {
|
|
491
|
+
const tombstone = bySeq.get(seq)
|
|
492
|
+
if (tombstone === undefined) {
|
|
493
|
+
if (unique.length === 1) throw new Error('找不到该删除记录。')
|
|
494
|
+
continue
|
|
495
|
+
}
|
|
496
|
+
if (!session.surface.nodes.includes(seq)) continue
|
|
497
|
+
// Validate now so unsupported groups fail before queueing.
|
|
498
|
+
planRestore(session, seq)
|
|
499
|
+
accepted.push(seq)
|
|
500
|
+
}
|
|
501
|
+
if (accepted.length === 0) throw new Error('没有可恢复的删除记录(可能已经恢复)。')
|
|
502
|
+
const queuedTargets = new Set(durableQueue(ctx, session)
|
|
503
|
+
.filter((entry) => entry.op === 'restore')
|
|
504
|
+
.map((entry) => entry.targetSeq))
|
|
505
|
+
let added = 0
|
|
506
|
+
for (const seq of accepted) {
|
|
507
|
+
if (queuedTargets.has(seq)) continue
|
|
508
|
+
appendPending(session, 'restore', seq)
|
|
509
|
+
queuedTargets.add(seq)
|
|
510
|
+
added += 1
|
|
511
|
+
}
|
|
512
|
+
if (!ensureAgentListener(ctx, agent)) {
|
|
513
|
+
throw new Error('当前会话没有可用的 Agent 请求作用域,无法排队恢复;请重试。')
|
|
514
|
+
}
|
|
515
|
+
return {
|
|
516
|
+
text: added === 0
|
|
517
|
+
? '选中的删除记录已在恢复队列中,将在下一回合开始时恢复。'
|
|
518
|
+
: `已加入恢复队列:${added} 条删除记录将在下一回合开始时恢复到模型上下文。`,
|
|
519
|
+
count: added,
|
|
520
|
+
queued: true,
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/** List current conversation turns as text. */
|
|
525
|
+
async function listTurns(ctx, agent) {
|
|
526
|
+
const session = liveSession(ctx, agent)
|
|
527
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
528
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
529
|
+
const open = openStepOf(session)
|
|
530
|
+
const turns = turnsFromSurface(events, bySeq).map((turn) => ({
|
|
531
|
+
...turn,
|
|
532
|
+
inProgress: open !== undefined && turn.seqs.some((seq) => seq >= open.startSeq),
|
|
533
|
+
}))
|
|
534
|
+
return { text: formatTurns(turns), turns }
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
/** Delete whole conversation turns now when safe, otherwise queue them durably. */
|
|
538
|
+
async function deleteTurns(ctx, agent, turnNums) {
|
|
539
|
+
const unique = [...new Set(turnNums)]
|
|
540
|
+
if (unique.length === 0 || unique.some((num) => !Number.isSafeInteger(num) || num < 0)) {
|
|
541
|
+
throw new Error('轮号必须是非负整数(list-turns 查看)。')
|
|
542
|
+
}
|
|
543
|
+
const session = liveSession(ctx, agent)
|
|
544
|
+
const events = await readSurfaceEvents(ctx, session)
|
|
545
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
546
|
+
const open = openStepOf(session)
|
|
547
|
+
const all = turnsFromSurface(events, bySeq)
|
|
548
|
+
const targets = []
|
|
549
|
+
for (const num of unique) {
|
|
550
|
+
const turn = all.find((entry) => entry.turn === num)
|
|
551
|
+
if (turn === undefined) {
|
|
552
|
+
if (unique.length === 1) throw new Error('该轮已不在当前上下文中(可能已删除);list-turns 查看现有轮。')
|
|
553
|
+
continue
|
|
554
|
+
}
|
|
555
|
+
targets.push(turn)
|
|
556
|
+
}
|
|
557
|
+
if (targets.length === 0) throw new Error('选中的轮都已不在当前上下文中。')
|
|
558
|
+
|
|
559
|
+
const touchesOpen = open !== undefined
|
|
560
|
+
&& targets.some((turn) => turn.seqs.some((seq) => seq >= open.startSeq))
|
|
561
|
+
if (open !== undefined && !touchesOpen) {
|
|
562
|
+
let turns = 0
|
|
563
|
+
let messages = 0
|
|
564
|
+
for (const turn of targets) {
|
|
565
|
+
const done = deleteTurnNow(session, turn.turn, open.turn, open.step)
|
|
566
|
+
if (done !== null) {
|
|
567
|
+
turns += 1
|
|
568
|
+
messages += done
|
|
569
|
+
}
|
|
570
|
+
}
|
|
571
|
+
return {
|
|
572
|
+
text: `已从模型上下文删除 ${turns} 轮对话(共 ${messages} 条消息;会话日志与聊天记录仍保留)。`,
|
|
573
|
+
turns,
|
|
574
|
+
messages,
|
|
575
|
+
queued: false,
|
|
576
|
+
}
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const queued = new Set(durableQueue(ctx, session)
|
|
580
|
+
.filter((entry) => entry.op === 'delete-turn')
|
|
581
|
+
.map((entry) => entry.targetSeq))
|
|
582
|
+
let added = 0
|
|
583
|
+
for (const turn of targets) {
|
|
584
|
+
if (queued.has(turn.turn)) continue
|
|
585
|
+
appendPending(session, 'delete-turn', turn.turn)
|
|
586
|
+
queued.add(turn.turn)
|
|
587
|
+
added += 1
|
|
588
|
+
}
|
|
589
|
+
if (!ensureAgentListener(ctx, agent)) {
|
|
590
|
+
throw new Error('当前会话没有可用的 Agent 请求作用域,无法排队删除;请重试。')
|
|
591
|
+
}
|
|
592
|
+
return {
|
|
593
|
+
text: added === 0
|
|
594
|
+
? '选中的轮已在删除队列中,将在下一回合开始时生效。'
|
|
595
|
+
: `已加入删除队列:${added} 轮对话将在下一回合开始时从模型上下文移除(会话日志与聊天记录仍保留)。`,
|
|
596
|
+
turns: added,
|
|
597
|
+
queued: true,
|
|
598
|
+
}
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
/**
|
|
602
|
+
* Delete every remaining content node of one conversation turn, grouping the
|
|
603
|
+
* nodes through the same planner used for single-message deletion so each
|
|
604
|
+
* tombstone keeps its own restore semantics (user in place, assistant groups
|
|
605
|
+
* and text at the tail). Tombstones already on the surface stay untouched.
|
|
606
|
+
* @returns the number of messages removed, or null when none remain.
|
|
607
|
+
*/
|
|
608
|
+
function deleteTurnNow(session, turnNum, curTurn, curStep) {
|
|
609
|
+
const bySeq = new Map(session.snapshotEvents().map((event) => [event.seq, event]))
|
|
610
|
+
const turn = turnsFromSurface(surfaceEventsSync(session), bySeq)
|
|
611
|
+
.find((entry) => entry.turn === turnNum)
|
|
612
|
+
if (turn === undefined || turn.seqs.length === 0) return null
|
|
613
|
+
const planned = new Set()
|
|
614
|
+
let count = 0
|
|
615
|
+
for (const seq of turn.seqs) {
|
|
616
|
+
if (planned.has(seq)) continue
|
|
617
|
+
// Re-plan against the live surface: an earlier group may already have
|
|
618
|
+
// absorbed this target, and each append invalidates stale ranges.
|
|
619
|
+
const current = surfaceEventsSync(session)
|
|
620
|
+
const plan = planDeletion(current, seq)
|
|
621
|
+
if (!plan.ok) continue
|
|
622
|
+
appendTombstones(session, plan.runs, curTurn, curStep)
|
|
623
|
+
for (const index of plan.indices) planned.add(current[index].seq)
|
|
624
|
+
count += plan.count
|
|
625
|
+
}
|
|
626
|
+
return count
|
|
627
|
+
}
|
|
628
|
+
|
|
629
|
+
/** Per-plugin-instance agent listener registries, keyed by plugin ctx. */
|
|
630
|
+
const listenerRegistries = new WeakMap()
|
|
631
|
+
|
|
632
|
+
/** The listener registry owned by one plugin ctx. */
|
|
633
|
+
function listenerRegistry(ctx) {
|
|
634
|
+
let registry = listenerRegistries.get(ctx)
|
|
635
|
+
if (registry === undefined) {
|
|
636
|
+
registry = new Map()
|
|
637
|
+
listenerRegistries.set(ctx, registry)
|
|
638
|
+
}
|
|
639
|
+
return registry
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
/**
|
|
643
|
+
* Replay every durable pending delete/restore for one Agent's Session inside
|
|
644
|
+
* the request's open step, then acknowledge each record so it never replays
|
|
645
|
+
* again. Replayed operations whose target already vanished are acked as
|
|
646
|
+
* skipped; genuine failures are acked with the reason.
|
|
647
|
+
*/
|
|
648
|
+
function applyQueuedOperations(ctx, agent, turn, step) {
|
|
649
|
+
const session = ctx.sessions.get(agent.id)
|
|
650
|
+
if (session === undefined) return
|
|
651
|
+
const queue = durableQueue(ctx, session)
|
|
652
|
+
if (queue.length === 0) return
|
|
653
|
+
for (const entry of queue) {
|
|
654
|
+
try {
|
|
655
|
+
if (entry.op === 'delete') {
|
|
656
|
+
const plan = planDeletion(surfaceEventsSync(session), entry.targetSeq)
|
|
657
|
+
if (!plan.ok) {
|
|
658
|
+
appendAck(session, entry.recordSeq, 'skipped', `target #${entry.targetSeq} ${plan.reason}`)
|
|
659
|
+
continue
|
|
660
|
+
}
|
|
661
|
+
appendTombstones(session, plan.runs, turn, step)
|
|
662
|
+
appendAck(session, entry.recordSeq, 'applied')
|
|
663
|
+
} else if (entry.op === 'delete-turn') {
|
|
664
|
+
const done = deleteTurnNow(session, entry.targetSeq, turn, step)
|
|
665
|
+
if (done === null) {
|
|
666
|
+
appendAck(session, entry.recordSeq, 'skipped', `turn #${entry.targetSeq} has no remaining content`)
|
|
667
|
+
} else {
|
|
668
|
+
appendAck(session, entry.recordSeq, 'applied')
|
|
669
|
+
}
|
|
670
|
+
} else {
|
|
671
|
+
restoreOne(session, entry.targetSeq, turn, step)
|
|
672
|
+
appendAck(session, entry.recordSeq, 'applied')
|
|
673
|
+
}
|
|
674
|
+
} catch (error) {
|
|
675
|
+
const message = error instanceof Error ? error.message : String(error)
|
|
676
|
+
const result = IDEMPOTENT_MARKERS.some((marker) => message.includes(marker)) ? 'skipped' : 'failed'
|
|
677
|
+
appendAck(session, entry.recordSeq, result, message)
|
|
678
|
+
if (result === 'failed') {
|
|
679
|
+
ctx.logger?.warn?.(`context-manager: queued ${entry.op} ${entry.targetSeq} failed: ${message}`)
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
// Refresh the incremental cache with the acks just appended.
|
|
684
|
+
durableQueue(ctx, session)
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
/**
|
|
688
|
+
* Register one Agent-scoped `agent/request` listener for queued operations.
|
|
689
|
+
* The request hook runs after `step/start` and before request derivation.
|
|
690
|
+
* @returns whether the listener is available.
|
|
691
|
+
*/
|
|
692
|
+
function ensureAgentListener(ctx, agent) {
|
|
693
|
+
if (agent === undefined || agent === null || typeof agent.id !== 'string') return false
|
|
694
|
+
const agentListeners = listenerRegistry(ctx)
|
|
695
|
+
const id = agent.id
|
|
696
|
+
if (agentListeners.has(id)) return true
|
|
697
|
+
const liveAgent = ctx.agents.get(id) ?? agent
|
|
698
|
+
const owner = liveAgent.ctx ?? agent.ctx
|
|
699
|
+
if (owner === undefined || owner === null || typeof owner.on !== 'function') return false
|
|
700
|
+
const stop = owner.on('agent/request', (payload, next) => {
|
|
701
|
+
if (payload === undefined || payload.agent === undefined || payload.agent.id !== id) return next()
|
|
702
|
+
applyQueuedOperations(ctx, liveAgent, payload.turn, payload.step)
|
|
703
|
+
return next()
|
|
704
|
+
})
|
|
705
|
+
const disposeOwnerEffect = typeof owner.effect === 'function'
|
|
706
|
+
? owner.effect(() => () => {
|
|
707
|
+
stop()
|
|
708
|
+
agentListeners.delete(id)
|
|
709
|
+
}, 'context-manager: queued operations')
|
|
710
|
+
: () => {
|
|
711
|
+
stop()
|
|
712
|
+
agentListeners.delete(id)
|
|
713
|
+
}
|
|
714
|
+
agentListeners.set(id, { stop, disposeOwnerEffect })
|
|
715
|
+
return true
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/** Parse `/ctxmgr` input into an operation. */
|
|
719
|
+
function parseCommand(rawInput) {
|
|
720
|
+
const text = typeof rawInput === 'string' ? rawInput.trim() : ''
|
|
721
|
+
if (text.length === 0) return { op: 'list' }
|
|
722
|
+
const parts = text.split(/\s+/)
|
|
723
|
+
const head = parts[0].toLowerCase()
|
|
724
|
+
if (head === 'list' || head === 'ls') return { op: 'list' }
|
|
725
|
+
if (head === 'turns' || head === 'list-turns' || head === 'ls-turns') return { op: 'list-turns' }
|
|
726
|
+
const deleteTurn = head === 'deleteturn' || head === 'delturn' || head === 'dt'
|
|
727
|
+
if (head === 'delete' || head === 'rm' || head === 'restore' || head === 'undo' || deleteTurn) {
|
|
728
|
+
const rest = text.slice(head.length).trim()
|
|
729
|
+
const values = rest.length === 0 ? [] : rest.split(/[,\s]+/).filter(Boolean)
|
|
730
|
+
if (values.length === 0) return { op: 'invalid', reason: deleteTurn ? '缺少要删除的轮号。' : '缺少要处理的序号。' }
|
|
731
|
+
if (values.some((value) => !/^\d+$/.test(value))) return { op: 'invalid', reason: '轮号/序号必须是数字,多个用逗号分隔。' }
|
|
732
|
+
return {
|
|
733
|
+
op: deleteTurn ? 'delete-turns' : head === 'restore' || head === 'undo' ? 'restore' : 'delete',
|
|
734
|
+
seqs: values.map(Number),
|
|
735
|
+
}
|
|
736
|
+
}
|
|
737
|
+
return { op: 'invalid', reason: `未知子命令 “${parts[0]}”。` }
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
export function apply(ctx) {
|
|
741
|
+
for (const liveAgent of ctx.agents.list()) ensureAgentListener(ctx, liveAgent)
|
|
742
|
+
const stopCreated = ctx.on('agent/created', (payload) => {
|
|
743
|
+
if (payload !== undefined) ensureAgentListener(ctx, payload.agent)
|
|
744
|
+
})
|
|
745
|
+
|
|
746
|
+
const command = ctx.commands.register({
|
|
747
|
+
name: 'ctxmgr',
|
|
748
|
+
description: '列出、批量删除或恢复当前会话中的单条消息,并按轮删除整轮对话(仅移出/恢复模型上下文,保留原始日志)。',
|
|
749
|
+
input: { hint: 'list | turns | delete <序号,...> | deleteturn <轮号,...> | restore <删除记录序号,...>' },
|
|
750
|
+
recordInput: false,
|
|
751
|
+
async handler(invocation) {
|
|
752
|
+
try {
|
|
753
|
+
const parsed = parseCommand(invocation.rawInput)
|
|
754
|
+
if (parsed.op === 'list') {
|
|
755
|
+
const result = await listMessages(ctx, invocation.agent)
|
|
756
|
+
return { kind: 'success', text: result.text }
|
|
757
|
+
}
|
|
758
|
+
if (parsed.op === 'list-turns') {
|
|
759
|
+
const result = await listTurns(ctx, invocation.agent)
|
|
760
|
+
return { kind: 'success', text: result.text }
|
|
761
|
+
}
|
|
762
|
+
if (parsed.op === 'delete') {
|
|
763
|
+
const result = await deleteMessages(ctx, invocation.agent, parsed.seqs)
|
|
764
|
+
return { kind: 'success', text: result.text }
|
|
765
|
+
}
|
|
766
|
+
if (parsed.op === 'delete-turns') {
|
|
767
|
+
const result = await deleteTurns(ctx, invocation.agent, parsed.seqs)
|
|
768
|
+
return { kind: 'success', text: result.text }
|
|
769
|
+
}
|
|
770
|
+
if (parsed.op === 'restore') {
|
|
771
|
+
const result = await restoreMessages(ctx, invocation.agent, parsed.seqs)
|
|
772
|
+
return { kind: 'success', text: result.text }
|
|
773
|
+
}
|
|
774
|
+
return { kind: 'error', text: `${parsed.reason} 用法:/ctxmgr list | /ctxmgr turns | /ctxmgr delete <序号,...> | /ctxmgr deleteturn <轮号,...> | /ctxmgr restore <删除记录序号,...>` }
|
|
775
|
+
} catch (error) {
|
|
776
|
+
return { kind: 'error', text: error instanceof Error ? error.message : String(error) }
|
|
777
|
+
}
|
|
778
|
+
},
|
|
779
|
+
})
|
|
780
|
+
|
|
781
|
+
const tool = ctx.tools.register({
|
|
782
|
+
name: 'context_manager',
|
|
783
|
+
description: 'Manage the model context of the current session. Actions: list (current messages plus deleted records and queued operations), list-turns (conversation turns with turn numbers), delete (message seqs; any tool results tied to an assistant message that calls tools go with it), delete-turns (whole turns: the user prompt, the assistant work and reply, and that turn\'s injected context), restore (tombstone seqs from list; user/context restores at its original position, assistant content is appended at the tail). Typical uses: roll back to the start of a turn by deleting that turn and the ones after it, or drop noisy messages that no longer matter. Deletion only affects later model requests; the raw session log and chat transcript are retained. Operations that cannot run safely yet are recorded durably in the session log and applied when the next step starts, surviving restarts. Use only when the user explicitly asks. Requires a live session.',
|
|
784
|
+
parameters: {
|
|
785
|
+
type: 'object',
|
|
786
|
+
properties: {
|
|
787
|
+
action: {
|
|
788
|
+
type: 'string',
|
|
789
|
+
enum: ['list', 'list-turns', 'delete', 'delete-turns', 'restore'],
|
|
790
|
+
description: 'list messages, list conversation turns, delete message seqs, delete whole turns by turn number, or restore tombstone seqs.',
|
|
791
|
+
},
|
|
792
|
+
seq: {
|
|
793
|
+
type: 'integer',
|
|
794
|
+
description: 'One message seq for delete (legacy single-target form).',
|
|
795
|
+
},
|
|
796
|
+
seqs: {
|
|
797
|
+
type: 'array',
|
|
798
|
+
items: { type: 'integer' },
|
|
799
|
+
description: 'Message seqs for delete, turn numbers for delete-turns, or tombstone seqs for restore (from list/turns output).',
|
|
800
|
+
},
|
|
801
|
+
},
|
|
802
|
+
required: ['action'],
|
|
803
|
+
additionalProperties: false,
|
|
804
|
+
},
|
|
805
|
+
output: {
|
|
806
|
+
schema: {
|
|
807
|
+
type: 'object',
|
|
808
|
+
properties: {
|
|
809
|
+
ok: { type: 'boolean', description: 'Whether the operation succeeded.' },
|
|
810
|
+
text: { type: 'string', description: 'Human-readable result or message list.' },
|
|
811
|
+
},
|
|
812
|
+
required: ['ok', 'text'],
|
|
813
|
+
additionalProperties: false,
|
|
814
|
+
},
|
|
815
|
+
render(_args, value) {
|
|
816
|
+
return [{ type: 'text', text: typeof value?.text === 'string' ? value.text : '' }]
|
|
817
|
+
},
|
|
818
|
+
},
|
|
819
|
+
async execute(args, exec) {
|
|
820
|
+
const action = args?.action
|
|
821
|
+
const list = Array.isArray(args?.seqs)
|
|
822
|
+
? args.seqs
|
|
823
|
+
: Number.isSafeInteger(args?.seq) ? [args.seq] : []
|
|
824
|
+
if (action === 'list') {
|
|
825
|
+
const result = await listMessages(ctx, exec.agent)
|
|
826
|
+
return { ok: true, text: result.text }
|
|
827
|
+
}
|
|
828
|
+
if (action === 'list-turns') {
|
|
829
|
+
const result = await listTurns(ctx, exec.agent)
|
|
830
|
+
return { ok: true, text: result.text }
|
|
831
|
+
}
|
|
832
|
+
if (action === 'delete') {
|
|
833
|
+
if (list.length === 0) throw new Error('delete 需要 list 返回的整数 seq 或 seqs。')
|
|
834
|
+
const result = await deleteMessages(ctx, exec.agent, list)
|
|
835
|
+
return { ok: true, text: result.text }
|
|
836
|
+
}
|
|
837
|
+
if (action === 'delete-turns') {
|
|
838
|
+
if (list.length === 0) throw new Error('delete-turns 需要 list-turns 返回的整数轮号。')
|
|
839
|
+
const result = await deleteTurns(ctx, exec.agent, list)
|
|
840
|
+
return { ok: true, text: result.text }
|
|
841
|
+
}
|
|
842
|
+
if (action === 'restore') {
|
|
843
|
+
if (list.length === 0) throw new Error('restore 需要已删除记录返回的整数 tombstone seq。')
|
|
844
|
+
const result = await restoreMessages(ctx, exec.agent, list)
|
|
845
|
+
return { ok: true, text: result.text }
|
|
846
|
+
}
|
|
847
|
+
throw new Error('action 必须是 list、list-turns、delete、delete-turns 或 restore。')
|
|
848
|
+
},
|
|
849
|
+
})
|
|
850
|
+
|
|
851
|
+
ctx.effect(() => () => {
|
|
852
|
+
tool()
|
|
853
|
+
command()
|
|
854
|
+
stopCreated()
|
|
855
|
+
const agentListeners = listenerRegistry(ctx)
|
|
856
|
+
for (const entry of [...agentListeners.values()]) {
|
|
857
|
+
entry.stop()
|
|
858
|
+
entry.disposeOwnerEffect()
|
|
859
|
+
}
|
|
860
|
+
agentListeners.clear()
|
|
861
|
+
}, 'context-manager: command, tool, and queued operations')
|
|
862
|
+
}
|