@asd2233996/dsh-auto-context 0.0.0-stage → 1.15.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/LICENSE +21 -0
- package/README.en.md +113 -0
- package/README.md +250 -2
- package/cordis.patch.yml +23 -0
- package/docs/product-introduction.md +282 -0
- package/docs/structured-kb-notes.md +179 -0
- package/lib/actions.js +2758 -0
- package/lib/extract.js +1647 -0
- package/lib/graph.js +1628 -0
- package/lib/groups.js +307 -0
- package/lib/impl.js +170 -0
- package/lib/index.js +43 -0
- package/lib/kb-tools.js +384 -0
- package/lib/kb.js +254 -0
- package/lib/kg-archive.js +1042 -0
- package/lib/kg-store.js +1427 -0
- package/lib/recall.js +62 -0
- package/lib/scan.js +2537 -0
- package/lib/segments.js +660 -0
- package/lib/store.js +365 -0
- package/lib/util.js +64 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +87 -4
package/lib/segments.js
ADDED
|
@@ -0,0 +1,660 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* context-manager — 会话 surface → 卡片模型(纯计算,不做任何写操作)。
|
|
3
|
+
*
|
|
4
|
+
* 设计口径(与 DSH 的 session surface 对齐):
|
|
5
|
+
* - 模型可见历史 = `session.surface.nodes` 顺序的 message-producing 事件。
|
|
6
|
+
* - 丢弃一张卡片 = 官方 `compaction/prune` 影子价格事件 + 一个极小的
|
|
7
|
+
* `user/message` 占位替换(surfaceOp.replace),原始 append-origin 事件仍完整
|
|
8
|
+
* 留在日志里(人类对话记录、导出、fork 都不受影响)。
|
|
9
|
+
* - 占位替换带 `<context-pruned card="..." title="..." tokens="..."/>` 标记,
|
|
10
|
+
* 因此「哪些卡片处于已丢弃状态」完全可以从会话日志重建(插件状态文件只是缓存)。
|
|
11
|
+
*
|
|
12
|
+
* 本模块只读 session,不调用 append;写事务在 lib/actions.js。
|
|
13
|
+
* @module context-manager/segments
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { deriveEventMessage, isReplacementSurfaceEvent } from '@deepseek-ai/dsh-session'
|
|
17
|
+
import { codePointLength, truncateChars } from './util.js'
|
|
18
|
+
|
|
19
|
+
/** 已丢弃卡片的占位标记(模型可见,语义=“这段被用户精简了”)。 */
|
|
20
|
+
export const STUB_TAG = 'context-pruned'
|
|
21
|
+
/** 恢复片段的标记(v1 仅用于让轨迹/详情可辨识,模型可见)。 */
|
|
22
|
+
export const RESTORED_TAG = 'context-restored'
|
|
23
|
+
/** 卡片预览默认截断(字符数)。 */
|
|
24
|
+
export const DEFAULT_PREVIEW_CHARS = 480
|
|
25
|
+
|
|
26
|
+
const STUB_PATTERN = new RegExp(`<${STUB_TAG}\\s+([^>]*?)\\/?>`)
|
|
27
|
+
const RESTORED_PATTERN = new RegExp(`<${RESTORED_TAG}\\s+([^>]*?)\\/?>`)
|
|
28
|
+
|
|
29
|
+
/** 解析 XML 风格属性串(card / title / tokens),只认我们写的这三个键。 */
|
|
30
|
+
function parseAttributes(raw) {
|
|
31
|
+
const attributes = {}
|
|
32
|
+
const pattern = /([a-zA-Z][a-zA-Z0-9_-]*)="([^"]*)"/g
|
|
33
|
+
let match
|
|
34
|
+
while ((match = pattern.exec(raw)) !== null) attributes[match[1]] = match[2]
|
|
35
|
+
return attributes
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** 取一条消息里全部 text block 拼成的纯文本(不含推理)。 */
|
|
39
|
+
function messageText(message) {
|
|
40
|
+
if (message === null || message === undefined || !Array.isArray(message.content)) return ''
|
|
41
|
+
const parts = []
|
|
42
|
+
for (const block of message.content) {
|
|
43
|
+
if (block === null || typeof block !== 'object') continue
|
|
44
|
+
if (block.type === 'text' && typeof block.text === 'string') parts.push(block.text)
|
|
45
|
+
}
|
|
46
|
+
return parts.join('\n')
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* 把一条消息压成“人类可读的一行/多行预览”(tool-call、图片、文件都有占位)。
|
|
51
|
+
* @param {object|null} message - 派生消息。
|
|
52
|
+
* @param {number} [maxChars] - 截断字符数。
|
|
53
|
+
* @returns {string} 预览文本。
|
|
54
|
+
*/
|
|
55
|
+
export function messagePreview(message, maxChars = DEFAULT_PREVIEW_CHARS) {
|
|
56
|
+
if (message === null || message === undefined || !Array.isArray(message.content)) return ''
|
|
57
|
+
const parts = []
|
|
58
|
+
for (const block of message.content) {
|
|
59
|
+
if (block === null || typeof block !== 'object') continue
|
|
60
|
+
switch (block.type) {
|
|
61
|
+
case 'text':
|
|
62
|
+
if (typeof block.text === 'string' && block.text.length > 0) parts.push(block.text)
|
|
63
|
+
break
|
|
64
|
+
case 'reasoning':
|
|
65
|
+
break
|
|
66
|
+
case 'tool-call':
|
|
67
|
+
parts.push(`[调用 ${block.name ?? 'tool'}]\n${typeof block.arguments === 'string' ? block.arguments : ''}`)
|
|
68
|
+
break
|
|
69
|
+
case 'tool-addition':
|
|
70
|
+
parts.push(`[新增工具 ${block.toolName ?? ''}]`)
|
|
71
|
+
break
|
|
72
|
+
case 'tool-removal':
|
|
73
|
+
parts.push(`[移除工具 ${block.toolName ?? ''}]`)
|
|
74
|
+
break
|
|
75
|
+
case 'image':
|
|
76
|
+
parts.push('[图片]')
|
|
77
|
+
break
|
|
78
|
+
case 'file':
|
|
79
|
+
parts.push(`[文件 ${block.attachment?.name ?? ''}]`)
|
|
80
|
+
break
|
|
81
|
+
default:
|
|
82
|
+
parts.push(`[${String(block.type)}]`)
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return truncateChars(parts.join('\n').trim(), maxChars)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** 汇总一条消息里出现的工具名(去重保序)。 */
|
|
89
|
+
export function messageToolNames(message) {
|
|
90
|
+
const names = []
|
|
91
|
+
if (message === null || message === undefined || !Array.isArray(message.content)) return names
|
|
92
|
+
for (const block of message.content) {
|
|
93
|
+
if (block === null || typeof block !== 'object') continue
|
|
94
|
+
if (block.type === 'tool-call' && typeof block.name === 'string') names.push(block.name)
|
|
95
|
+
else if ((block.type === 'tool-addition' || block.type === 'tool-removal') && typeof block.toolName === 'string') names.push(block.toolName)
|
|
96
|
+
}
|
|
97
|
+
return [...new Set(names)]
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** 一条消息是否含图片 / 文件。 */
|
|
101
|
+
export function messageMedia(message) {
|
|
102
|
+
let hasImage = false
|
|
103
|
+
let hasFile = false
|
|
104
|
+
if (message === null || message === undefined || !Array.isArray(message.content)) return { hasImage, hasFile }
|
|
105
|
+
for (const block of message.content) {
|
|
106
|
+
if (block === null || typeof block !== 'object') continue
|
|
107
|
+
if (block.type === 'image') hasImage = true
|
|
108
|
+
else if (block.type === 'file') hasFile = true
|
|
109
|
+
}
|
|
110
|
+
return { hasImage, hasFile }
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* 从事件里读出我们的占位/恢复标记;普通事件返回 null。
|
|
115
|
+
*
|
|
116
|
+
* 严格三重判定,避免把「正文里恰好引用了占位标签」的普通用户消息误判成占位:
|
|
117
|
+
* 1) 必须是 user/message;2) 必须是 surface **替换**(surfaceOp=replace),
|
|
118
|
+
* 真正的占位/恢复永远是被 append 成替换节点的;3) 第一个 text block 必须以
|
|
119
|
+
* 标记开头(我们生成的内容就是单块、以标记开头)。
|
|
120
|
+
*/
|
|
121
|
+
function markerOf(event, pattern) {
|
|
122
|
+
if (event === null || event === undefined || event.type !== 'user/message') return null
|
|
123
|
+
if (!isReplacementSurfaceEvent(event)) return null
|
|
124
|
+
const message = event.data
|
|
125
|
+
const blocks = Array.isArray(message?.content) ? message.content : []
|
|
126
|
+
const first = blocks[0]
|
|
127
|
+
if (first === null || typeof first !== 'object' || first.type !== 'text' || typeof first.text !== 'string') return null
|
|
128
|
+
if (!first.text.trimStart().startsWith(`<${pattern === STUB_PATTERN ? STUB_TAG : RESTORED_TAG}`)) return null
|
|
129
|
+
const match = pattern.exec(first.text)
|
|
130
|
+
if (match === null) return null
|
|
131
|
+
return parseAttributes(match[1])
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 一条事件是否是 context-manager 的丢弃占位替换。
|
|
136
|
+
* @param {object} event - 会话事件。
|
|
137
|
+
* @returns {{cardId:string,title:string,tokens:number}|null} 标记信息。
|
|
138
|
+
*/
|
|
139
|
+
export function parseStubEvent(event) {
|
|
140
|
+
const attributes = markerOf(event, STUB_PATTERN)
|
|
141
|
+
if (attributes === null) return null
|
|
142
|
+
const cardId = typeof attributes.card === 'string' ? attributes.card : ''
|
|
143
|
+
if (cardId.length === 0) return null
|
|
144
|
+
const tokens = Number(attributes.tokens)
|
|
145
|
+
return {
|
|
146
|
+
cardId,
|
|
147
|
+
title: typeof attributes.title === 'string' ? attributes.title : '',
|
|
148
|
+
tokens: Number.isFinite(tokens) && tokens > 0 ? Math.round(tokens) : 0,
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** 一条事件是否是 context-manager 的恢复片段(用于详情/轨迹辨识)。 */
|
|
153
|
+
export function parseRestoredEvent(event) {
|
|
154
|
+
const attributes = markerOf(event, RESTORED_PATTERN)
|
|
155
|
+
if (attributes === null) return null
|
|
156
|
+
const cardId = typeof attributes.card === 'string' ? attributes.card : ''
|
|
157
|
+
if (cardId.length === 0) return null
|
|
158
|
+
return { cardId, title: typeof attributes.title === 'string' ? attributes.title : '' }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 结构判定:一条替换事件是否是我们对“占位节点”做的恢复替换。
|
|
163
|
+
* 不依赖恢复文本里是否带标记,因此单节点 user/developer 的“原样恢复”也能识别。
|
|
164
|
+
* @param {object} session - 实时 Session。
|
|
165
|
+
* @param {object} event - 候选事件。
|
|
166
|
+
* @returns {{cardId:string,title:string}|null} 被恢复的卡片信息。
|
|
167
|
+
*/
|
|
168
|
+
export function restoreMarkerOf(session, event) {
|
|
169
|
+
if (event === null || event === undefined) return null
|
|
170
|
+
if (event.type !== 'user/message' && event.type !== 'developer/message') return null
|
|
171
|
+
const op = event.surfaceOp
|
|
172
|
+
if (op === null || typeof op !== 'object' || op.op !== 'replace') return null
|
|
173
|
+
const sources = Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []
|
|
174
|
+
if (sources.length !== 1) return null
|
|
175
|
+
const source = session.eventAt(sources[0])
|
|
176
|
+
if (source === undefined || source === null) return null
|
|
177
|
+
const stub = parseStubEvent(source)
|
|
178
|
+
if (stub === null) return null
|
|
179
|
+
return { cardId: stub.cardId, title: stub.title }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 用日志顺序建立 seq → turn 索引(turn/start 之后的表面事件归该轮)。
|
|
184
|
+
* @param {readonly object[]} events - 完整会话日志(snapshotEvents())。
|
|
185
|
+
* @returns {Map<number, number>} seq → turn(找不到时调用方回退 0)。
|
|
186
|
+
*/
|
|
187
|
+
export function buildTurnIndex(events) {
|
|
188
|
+
const index = new Map()
|
|
189
|
+
let turn = 0
|
|
190
|
+
for (const event of events) {
|
|
191
|
+
if (event !== null && typeof event === 'object' && event.type === 'turn/start') {
|
|
192
|
+
const value = Number(event.data?.turn)
|
|
193
|
+
if (Number.isFinite(value)) turn = Math.max(0, Math.trunc(value))
|
|
194
|
+
}
|
|
195
|
+
if (event !== null && typeof event === 'object' && Number.isSafeInteger(event.seq)) index.set(event.seq, turn)
|
|
196
|
+
}
|
|
197
|
+
return index
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** 把 `ctx.tokenMeter.measure().nodes` 转成 seq → 价格表(影子价格必须用同一口径)。 */
|
|
201
|
+
export function priceMapOf(measurement) {
|
|
202
|
+
const map = new Map()
|
|
203
|
+
if (measurement === null || measurement === undefined || !Array.isArray(measurement.nodes)) return map
|
|
204
|
+
for (const node of measurement.nodes) {
|
|
205
|
+
if (node === null || typeof node !== 'object') continue
|
|
206
|
+
map.set(node.seq, Number.isFinite(node.heuristicTokens) ? node.heuristicTokens : 0)
|
|
207
|
+
}
|
|
208
|
+
return map
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 一组 seq 的价格合计(缺价按 0)。 */
|
|
212
|
+
export function sumPrices(priceMap, seqs) {
|
|
213
|
+
let total = 0
|
|
214
|
+
for (const seq of seqs) total += priceMap.get(seq) ?? 0
|
|
215
|
+
return total
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 卡片 id 的前缀(用于从 id 判断类别)。 */
|
|
219
|
+
const CARD_ID_PREFIX = { user: 'u', assistant: 'a', developer: 'd', system: 's', context: 'x' }
|
|
220
|
+
|
|
221
|
+
/** 卡片 id:`<前缀>-<起始事件 seq>`,天然稳定且可从日志重建。 */
|
|
222
|
+
export function cardIdOf(kind, seq) {
|
|
223
|
+
return `${CARD_ID_PREFIX[kind] ?? 'x'}-${seq}`
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 构造一张普通(未丢弃)卡片。 */
|
|
227
|
+
function makeCard({ id, kind, role, seqs, events, messages, priceMap, turn, step, surfaceStart, surfaceEnd, droppable, previewChars }) {
|
|
228
|
+
const texts = []
|
|
229
|
+
const toolNames = []
|
|
230
|
+
let hasImage = false
|
|
231
|
+
let hasFile = false
|
|
232
|
+
let chars = 0
|
|
233
|
+
for (let i = 0; i < seqs.length; i += 1) {
|
|
234
|
+
const message = messages[i]
|
|
235
|
+
const preview = messagePreview(message, Number.MAX_SAFE_INTEGER)
|
|
236
|
+
if (preview.length > 0) texts.push(preview)
|
|
237
|
+
for (const name of messageToolNames(message)) if (!toolNames.includes(name)) toolNames.push(name)
|
|
238
|
+
const media = messageMedia(message)
|
|
239
|
+
hasImage = hasImage || media.hasImage
|
|
240
|
+
hasFile = hasFile || media.hasFile
|
|
241
|
+
chars += codePointLength(messageText(message))
|
|
242
|
+
}
|
|
243
|
+
const first = events[0]
|
|
244
|
+
return {
|
|
245
|
+
id,
|
|
246
|
+
lineage: id,
|
|
247
|
+
kind,
|
|
248
|
+
role,
|
|
249
|
+
turn: Number.isFinite(turn) ? turn : 0,
|
|
250
|
+
step: Number.isFinite(step) ? step : null,
|
|
251
|
+
startSeq: seqs[0],
|
|
252
|
+
endSeq: seqs[seqs.length - 1],
|
|
253
|
+
// 在 surface.nodes 里的位置区间(surface 顺序);分组/丢弃范围一律按它计算,
|
|
254
|
+
// 不能按 seq 数值排序(替换事件的 seq 在日志末尾,但 surface 位置可能在前面)。
|
|
255
|
+
surfaceStart: Number.isFinite(surfaceStart) ? surfaceStart : null,
|
|
256
|
+
surfaceEnd: Number.isFinite(surfaceEnd) ? surfaceEnd : null,
|
|
257
|
+
seqs: [...seqs],
|
|
258
|
+
tokens: sumPrices(priceMap, seqs),
|
|
259
|
+
chars,
|
|
260
|
+
toolNames,
|
|
261
|
+
hasImage,
|
|
262
|
+
hasFile,
|
|
263
|
+
time: Number.isFinite(first.time) ? first.time : Date.now(),
|
|
264
|
+
preview: truncateChars(texts.join('\n'), previewChars),
|
|
265
|
+
// 是否是“本轮的最终答复”(纯文本 assistant 单元):分组时单独成卡,方便用户保留/丢弃。
|
|
266
|
+
isFinalAnswer: kind === 'assistant' && toolNames.length === 0 && !hasImage && !hasFile
|
|
267
|
+
&& texts.length > 0,
|
|
268
|
+
droppable,
|
|
269
|
+
dropped: false,
|
|
270
|
+
restorable: false,
|
|
271
|
+
stubSeq: null,
|
|
272
|
+
originalSeqs: null,
|
|
273
|
+
restoredFrom: null,
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 构造一张“已丢弃”卡片(占位替换在 surface 上,或已被后续压缩收走)。 */
|
|
278
|
+
function makeDroppedCard({ marker, stubEvent, session, turn, onSurface, previewChars, surfaceIndex }) {
|
|
279
|
+
const originalSeqs = Array.isArray(stubEvent.sourceEventSeqs) ? stubEvent.sourceEventSeqs : []
|
|
280
|
+
const previews = []
|
|
281
|
+
let chars = 0
|
|
282
|
+
for (const seq of originalSeqs) {
|
|
283
|
+
const event = session.eventAt(seq)
|
|
284
|
+
if (event === undefined || event === null) continue
|
|
285
|
+
const message = deriveEventMessage(event)
|
|
286
|
+
const preview = messagePreview(message, DEFAULT_PREVIEW_CHARS)
|
|
287
|
+
if (preview.length > 0) previews.push(preview)
|
|
288
|
+
chars += codePointLength(messageText(message))
|
|
289
|
+
}
|
|
290
|
+
return {
|
|
291
|
+
id: marker.cardId,
|
|
292
|
+
lineage: marker.cardId,
|
|
293
|
+
kind: 'dropped',
|
|
294
|
+
role: 'user',
|
|
295
|
+
turn: Number.isFinite(turn) ? turn : 0,
|
|
296
|
+
step: null,
|
|
297
|
+
surfaceStart: Number.isFinite(surfaceIndex) ? surfaceIndex : null,
|
|
298
|
+
surfaceEnd: Number.isFinite(surfaceIndex) ? surfaceIndex : null,
|
|
299
|
+
startSeq: originalSeqs[0] ?? stubEvent.seq,
|
|
300
|
+
endSeq: originalSeqs[originalSeqs.length - 1] ?? stubEvent.seq,
|
|
301
|
+
seqs: [...originalSeqs],
|
|
302
|
+
tokens: marker.tokens,
|
|
303
|
+
chars,
|
|
304
|
+
toolNames: [],
|
|
305
|
+
hasImage: false,
|
|
306
|
+
hasFile: false,
|
|
307
|
+
time: Number.isFinite(stubEvent.time) ? stubEvent.time : Date.now(),
|
|
308
|
+
preview: truncateChars(previews.join('\n'), previewChars),
|
|
309
|
+
droppable: false,
|
|
310
|
+
dropped: true,
|
|
311
|
+
restorable: onSurface,
|
|
312
|
+
stubSeq: stubEvent.seq,
|
|
313
|
+
originalSeqs: [...originalSeqs],
|
|
314
|
+
restoredFrom: null,
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* 读取当前 surface 并切分卡片。
|
|
320
|
+
*
|
|
321
|
+
* 切分规则(步骤级):
|
|
322
|
+
* - `system/message` → 固定区(不可丢)。
|
|
323
|
+
* - `user/message` → 一张卡片(注入上下文同样是一张卡)。
|
|
324
|
+
* - `assistant/message` → 一张卡片,并把紧随其后的连续 `tool/result` 并入同一张卡
|
|
325
|
+
* (工具调用与结果永远同生共死,保证 provider 侧 tool pairing 合法)。
|
|
326
|
+
* - `developer/message` → 一张卡片(工具能力变更通知)。
|
|
327
|
+
* - 落单的 `tool/result`(异常历史)→ 不可丢的上下文卡片。
|
|
328
|
+
*
|
|
329
|
+
* @param {object} session - 实时 Session 对象(只读使用)。
|
|
330
|
+
* @param {{ priceMap: Map<number, number>, previewChars?: number }} options
|
|
331
|
+
* @returns {{
|
|
332
|
+
* active: object[], dropped: object[], fixed: object[],
|
|
333
|
+
* all: object[], byId: Map<string, object>,
|
|
334
|
+
* nodes: readonly number[], turns: Map<number, number>
|
|
335
|
+
* }}
|
|
336
|
+
*/
|
|
337
|
+
export function buildSurfaceModel(session, { priceMap, previewChars = DEFAULT_PREVIEW_CHARS }) {
|
|
338
|
+
const events = session.snapshotEvents()
|
|
339
|
+
const turns = buildTurnIndex(events)
|
|
340
|
+
const nodes = [...session.surface.nodes]
|
|
341
|
+
// 替换事件的 seq 在日志末尾,但 surface 位置在原处;它的 turn/step 必须从
|
|
342
|
+
// 被它 shadow 的原始事件继承,否则恢复出来的片段会被误归到最后一轮、
|
|
343
|
+
// 分组顺序也会错乱(用户丢弃→恢复→再丢会直接 500)。
|
|
344
|
+
const turnCache = new Map()
|
|
345
|
+
const turnOf = (event) => {
|
|
346
|
+
if (event === undefined || event === null) return 0
|
|
347
|
+
if (turnCache.has(event.seq)) return turnCache.get(event.seq)
|
|
348
|
+
turnCache.set(event.seq, 0) // 防环占位
|
|
349
|
+
let value = turns.get(event.seq) ?? 0
|
|
350
|
+
const op = event.surfaceOp
|
|
351
|
+
if (typeof op === 'object' && op !== null && op.op === 'replace') {
|
|
352
|
+
let best = null
|
|
353
|
+
for (const sourceSeq of Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []) {
|
|
354
|
+
const source = session.eventAt(sourceSeq)
|
|
355
|
+
if (source === undefined || source === null) continue
|
|
356
|
+
const candidate = turnOf(source)
|
|
357
|
+
if (best === null || candidate < best) best = candidate
|
|
358
|
+
}
|
|
359
|
+
if (best !== null) value = best
|
|
360
|
+
}
|
|
361
|
+
turnCache.set(event.seq, value)
|
|
362
|
+
return value
|
|
363
|
+
}
|
|
364
|
+
const stepOf = (event) => {
|
|
365
|
+
if (event === undefined || event === null) return null
|
|
366
|
+
if (Number.isFinite(event.data?.step)) return Math.trunc(event.data.step)
|
|
367
|
+
const op = event.surfaceOp
|
|
368
|
+
if (typeof op === 'object' && op !== null && op.op === 'replace') {
|
|
369
|
+
for (const sourceSeq of Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []) {
|
|
370
|
+
const source = session.eventAt(sourceSeq)
|
|
371
|
+
if (source !== undefined && source !== null && Number.isFinite(source.data?.step)) return Math.trunc(source.data.step)
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
return null
|
|
375
|
+
}
|
|
376
|
+
const nodeSet = new Set(nodes)
|
|
377
|
+
const active = []
|
|
378
|
+
const dropped = []
|
|
379
|
+
const fixed = []
|
|
380
|
+
const allStubs = []
|
|
381
|
+
let index = 0
|
|
382
|
+
while (index < nodes.length) {
|
|
383
|
+
const seq = nodes[index]
|
|
384
|
+
const event = session.eventAt(seq)
|
|
385
|
+
if (event === undefined || event === null) {
|
|
386
|
+
index += 1
|
|
387
|
+
continue
|
|
388
|
+
}
|
|
389
|
+
if (event.type === 'user/message') {
|
|
390
|
+
const stub = parseStubEvent(event)
|
|
391
|
+
if (stub !== null) {
|
|
392
|
+
allStubs.push({ marker: stub, event })
|
|
393
|
+
dropped.push(makeDroppedCard({
|
|
394
|
+
marker: stub, stubEvent: event, session, turn: turnOf(event), onSurface: true, previewChars, surfaceIndex: index,
|
|
395
|
+
}))
|
|
396
|
+
index += 1
|
|
397
|
+
continue
|
|
398
|
+
}
|
|
399
|
+
const message = session.deriveEventMessage(event)
|
|
400
|
+
const card = makeCard({
|
|
401
|
+
id: cardIdOf('user', seq),
|
|
402
|
+
kind: 'user',
|
|
403
|
+
role: 'user',
|
|
404
|
+
seqs: [seq],
|
|
405
|
+
events: [event],
|
|
406
|
+
messages: [message],
|
|
407
|
+
priceMap,
|
|
408
|
+
turn: turnOf(event),
|
|
409
|
+
step: stepOf(event),
|
|
410
|
+
surfaceStart: index,
|
|
411
|
+
surfaceEnd: index,
|
|
412
|
+
droppable: true,
|
|
413
|
+
previewChars,
|
|
414
|
+
})
|
|
415
|
+
const restored = restoreMarkerOf(session, event) ?? parseRestoredEvent(event)
|
|
416
|
+
if (restored !== null) {
|
|
417
|
+
card.restoredFrom = restored.cardId
|
|
418
|
+
// 恢复片段的稳定血统 = 最初被丢弃卡片的 id(重丢时占位仍写这个 id),
|
|
419
|
+
// 这样历史恢复片段不会因为 surface 节点换了新 seq 而丢失分组血统。
|
|
420
|
+
card.lineage = restored.cardId
|
|
421
|
+
}
|
|
422
|
+
active.push(card)
|
|
423
|
+
index += 1
|
|
424
|
+
continue
|
|
425
|
+
}
|
|
426
|
+
if (event.type === 'assistant/message') {
|
|
427
|
+
const seqs = [seq]
|
|
428
|
+
const eventsOfCard = [event]
|
|
429
|
+
const messages = [session.deriveEventMessage(event)]
|
|
430
|
+
let next = index + 1
|
|
431
|
+
while (next < nodes.length) {
|
|
432
|
+
const nextEvent = session.eventAt(nodes[next])
|
|
433
|
+
if (nextEvent === undefined || nextEvent === null || nextEvent.type !== 'tool/result') break
|
|
434
|
+
seqs.push(nodes[next])
|
|
435
|
+
eventsOfCard.push(nextEvent)
|
|
436
|
+
messages.push(session.deriveEventMessage(nextEvent))
|
|
437
|
+
next += 1
|
|
438
|
+
}
|
|
439
|
+
active.push(makeCard({
|
|
440
|
+
id: cardIdOf('assistant', seq),
|
|
441
|
+
kind: 'assistant',
|
|
442
|
+
role: 'assistant',
|
|
443
|
+
seqs,
|
|
444
|
+
events: eventsOfCard,
|
|
445
|
+
messages,
|
|
446
|
+
priceMap,
|
|
447
|
+
turn: turnOf(event),
|
|
448
|
+
step: stepOf(event),
|
|
449
|
+
surfaceStart: index,
|
|
450
|
+
surfaceEnd: next - 1,
|
|
451
|
+
droppable: true,
|
|
452
|
+
previewChars,
|
|
453
|
+
}))
|
|
454
|
+
index = next
|
|
455
|
+
continue
|
|
456
|
+
}
|
|
457
|
+
if (event.type === 'developer/message') {
|
|
458
|
+
const card = makeCard({
|
|
459
|
+
id: cardIdOf('developer', seq),
|
|
460
|
+
kind: 'developer',
|
|
461
|
+
role: 'developer',
|
|
462
|
+
seqs: [seq],
|
|
463
|
+
events: [event],
|
|
464
|
+
messages: [session.deriveEventMessage(event)],
|
|
465
|
+
priceMap,
|
|
466
|
+
turn: turnOf(event),
|
|
467
|
+
step: stepOf(event),
|
|
468
|
+
surfaceStart: index,
|
|
469
|
+
surfaceEnd: index,
|
|
470
|
+
droppable: true,
|
|
471
|
+
previewChars,
|
|
472
|
+
})
|
|
473
|
+
const restored = restoreMarkerOf(session, event) ?? parseRestoredEvent(event)
|
|
474
|
+
if (restored !== null) {
|
|
475
|
+
card.restoredFrom = restored.cardId
|
|
476
|
+
card.lineage = restored.cardId
|
|
477
|
+
}
|
|
478
|
+
active.push(card)
|
|
479
|
+
index += 1
|
|
480
|
+
continue
|
|
481
|
+
}
|
|
482
|
+
if (event.type === 'system/message') {
|
|
483
|
+
fixed.push(makeCard({
|
|
484
|
+
id: cardIdOf('system', seq),
|
|
485
|
+
kind: 'system',
|
|
486
|
+
role: 'system',
|
|
487
|
+
seqs: [seq],
|
|
488
|
+
events: [event],
|
|
489
|
+
messages: [session.deriveEventMessage(event)],
|
|
490
|
+
priceMap,
|
|
491
|
+
turn: turnOf(event),
|
|
492
|
+
step: stepOf(event),
|
|
493
|
+
surfaceStart: index,
|
|
494
|
+
surfaceEnd: index,
|
|
495
|
+
droppable: false,
|
|
496
|
+
previewChars,
|
|
497
|
+
}))
|
|
498
|
+
index += 1
|
|
499
|
+
continue
|
|
500
|
+
}
|
|
501
|
+
if (event.type === 'tool/result') {
|
|
502
|
+
fixed.push(makeCard({
|
|
503
|
+
id: cardIdOf('context', seq),
|
|
504
|
+
kind: 'context',
|
|
505
|
+
role: 'tool',
|
|
506
|
+
seqs: [seq],
|
|
507
|
+
events: [event],
|
|
508
|
+
messages: [session.deriveEventMessage(event)],
|
|
509
|
+
priceMap,
|
|
510
|
+
turn: turnOf(event),
|
|
511
|
+
step: stepOf(event),
|
|
512
|
+
surfaceStart: index,
|
|
513
|
+
surfaceEnd: index,
|
|
514
|
+
droppable: false,
|
|
515
|
+
previewChars,
|
|
516
|
+
}))
|
|
517
|
+
index += 1
|
|
518
|
+
continue
|
|
519
|
+
}
|
|
520
|
+
index += 1
|
|
521
|
+
}
|
|
522
|
+
|
|
523
|
+
// 日志里存在、但已不在当前 surface 上的占位:可能被我们自己的恢复替换收走,
|
|
524
|
+
// 也可能被内置自动压缩收走。前者不算“已丢弃”,后者展示为“已丢弃 · 无法恢复”。
|
|
525
|
+
const restoredStubSeqs = new Set()
|
|
526
|
+
for (const event of events) {
|
|
527
|
+
const op = event.surfaceOp
|
|
528
|
+
if (op === null || typeof op !== 'object' || op.op !== 'replace') continue
|
|
529
|
+
const shadowed = Array.isArray(event.sourceEventSeqs) ? event.sourceEventSeqs : []
|
|
530
|
+
let restoresStub = shadowed.length > 0
|
|
531
|
+
for (const seq of shadowed) {
|
|
532
|
+
const source = session.eventAt(seq)
|
|
533
|
+
if (source === undefined || source === null || parseStubEvent(source) === null) { restoresStub = false; break }
|
|
534
|
+
}
|
|
535
|
+
if (restoresStub) for (const seq of shadowed) restoredStubSeqs.add(seq)
|
|
536
|
+
}
|
|
537
|
+
const latestStubByCard = new Map()
|
|
538
|
+
for (const event of events) {
|
|
539
|
+
const marker = parseStubEvent(event)
|
|
540
|
+
if (marker === null) continue
|
|
541
|
+
const previous = latestStubByCard.get(marker.cardId)
|
|
542
|
+
if (previous === undefined || event.seq > previous.seq) latestStubByCard.set(marker.cardId, event)
|
|
543
|
+
}
|
|
544
|
+
for (const [cardId, stubEvent] of latestStubByCard) {
|
|
545
|
+
if (nodeSet.has(stubEvent.seq)) continue // 已在上面按 surface 占位加入
|
|
546
|
+
if (restoredStubSeqs.has(stubEvent.seq)) continue // 已被恢复
|
|
547
|
+
if (dropped.some(card => card.id === cardId)) continue
|
|
548
|
+
const marker = parseStubEvent(stubEvent)
|
|
549
|
+
if (marker === null) continue
|
|
550
|
+
dropped.push(makeDroppedCard({
|
|
551
|
+
marker, stubEvent, session, turn: turnOf(stubEvent), onSurface: false, previewChars,
|
|
552
|
+
}))
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
const byId = new Map()
|
|
556
|
+
for (const card of [...fixed, ...active, ...dropped]) byId.set(card.id, card)
|
|
557
|
+
return { active, dropped, fixed, all: [...fixed, ...active, ...dropped], byId, nodes, turns }
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
/**
|
|
561
|
+
* 内容 block → 展示文本(不截断)。
|
|
562
|
+
* @param {Array<object>} blocks - 消息内容块。
|
|
563
|
+
* @returns {string[]} 文本片段。
|
|
564
|
+
*/
|
|
565
|
+
function renderBlocks(blocks) {
|
|
566
|
+
const parts = []
|
|
567
|
+
if (!Array.isArray(blocks)) return parts
|
|
568
|
+
for (const block of blocks) {
|
|
569
|
+
if (block === null || typeof block !== 'object') continue
|
|
570
|
+
switch (block.type) {
|
|
571
|
+
case 'text':
|
|
572
|
+
if (typeof block.text === 'string' && block.text.length > 0) parts.push(block.text)
|
|
573
|
+
break
|
|
574
|
+
case 'reasoning':
|
|
575
|
+
if (typeof block.text === 'string' && block.text.length > 0) parts.push(`[思考]\n${block.text}`)
|
|
576
|
+
break
|
|
577
|
+
case 'tool-call':
|
|
578
|
+
parts.push(`[调用工具 ${block.name ?? ''}]\n${typeof block.arguments === 'string' ? block.arguments : JSON.stringify(block.arguments ?? {})}`)
|
|
579
|
+
break
|
|
580
|
+
case 'tool-addition':
|
|
581
|
+
parts.push(`[新增工具] ${block.toolName ?? ''}`)
|
|
582
|
+
break
|
|
583
|
+
case 'tool-removal':
|
|
584
|
+
parts.push(`[移除工具] ${block.toolName ?? ''}`)
|
|
585
|
+
break
|
|
586
|
+
case 'image':
|
|
587
|
+
parts.push('[图片]')
|
|
588
|
+
break
|
|
589
|
+
case 'file':
|
|
590
|
+
parts.push(`[文件] ${block.attachment?.name ?? ''}`)
|
|
591
|
+
break
|
|
592
|
+
default:
|
|
593
|
+
parts.push(`[${String(block.type)}]`)
|
|
594
|
+
}
|
|
595
|
+
}
|
|
596
|
+
return parts
|
|
597
|
+
}
|
|
598
|
+
|
|
599
|
+
/**
|
|
600
|
+
* 渲染一组事件为可读文本节点(供 context_recall / KG 抽取等内部逻辑使用)。
|
|
601
|
+
* @param {object} session - 实时 Session。
|
|
602
|
+
* @param {readonly number[]} seqs - 事件 seq。
|
|
603
|
+
* @returns {Array<{seq:number,type:string,role:string,text:string}>} 文本节点。
|
|
604
|
+
*/
|
|
605
|
+
export function renderEvents(session, seqs) {
|
|
606
|
+
const nodes = []
|
|
607
|
+
for (const seq of seqs) {
|
|
608
|
+
const event = session.eventAt(seq)
|
|
609
|
+
if (event === undefined || event === null) continue
|
|
610
|
+
const stub = parseStubEvent(event)
|
|
611
|
+
if (stub !== null) {
|
|
612
|
+
nodes.push({
|
|
613
|
+
seq,
|
|
614
|
+
type: 'stub',
|
|
615
|
+
role: 'system',
|
|
616
|
+
text: `⟪已精简卡片 ${stub.cardId}${stub.title.length > 0 ? ` · ${stub.title}` : ''}(原文仍保存在会话日志中,可恢复或由模型用 context_recall 取回)⟫`,
|
|
617
|
+
})
|
|
618
|
+
continue
|
|
619
|
+
}
|
|
620
|
+
const restored = parseRestoredEvent(event)
|
|
621
|
+
if (restored !== null) {
|
|
622
|
+
const message = session.deriveEventMessage(event)
|
|
623
|
+
nodes.push({
|
|
624
|
+
seq,
|
|
625
|
+
type: 'restored',
|
|
626
|
+
role: 'user',
|
|
627
|
+
text: renderBlocks(message?.content).join('\n\n'),
|
|
628
|
+
})
|
|
629
|
+
continue
|
|
630
|
+
}
|
|
631
|
+
const message = session.deriveEventMessage(event)
|
|
632
|
+
const role = message?.role ?? (event.type === 'tool/result' ? 'tool' : 'system')
|
|
633
|
+
nodes.push({
|
|
634
|
+
seq,
|
|
635
|
+
type: String(event.type),
|
|
636
|
+
role,
|
|
637
|
+
text: renderBlocks(message?.content).join('\n\n'),
|
|
638
|
+
})
|
|
639
|
+
}
|
|
640
|
+
return nodes
|
|
641
|
+
}
|
|
642
|
+
|
|
643
|
+
/**
|
|
644
|
+
* 生成“丢弃”占位替换的 content(模型可见,必须极简)。
|
|
645
|
+
* @param {{id:string,title:string,tokens:number}} card - 卡片。
|
|
646
|
+
* @returns {Array<{type:'text',text:string}>} 内容块。
|
|
647
|
+
*/
|
|
648
|
+
export function buildStubContent(card) {
|
|
649
|
+
const cardId = typeof card.lineage === 'string' && card.lineage.length > 0 ? card.lineage : card.id
|
|
650
|
+
const tokens = Number.isFinite(card.tokens) && card.tokens > 0 ? Math.round(card.tokens) : 0
|
|
651
|
+
const attributes = [`card="${cardId}"`]
|
|
652
|
+
// 占位内容会跟着每一次请求重发:只有足够大的卡片才值得附带标题提示,
|
|
653
|
+
// 小卡片保持极简(否则“精简一张 10 tokens 的小卡”反而会净增占用)。
|
|
654
|
+
if (tokens >= 150) {
|
|
655
|
+
const title = truncateChars(String(card.title ?? '').trim(), 24)
|
|
656
|
+
if (title.length > 0) attributes.push(`title="${title.replaceAll('&', '&').replaceAll('"', '"').replaceAll('<', '<').replaceAll('>', '>')}"`)
|
|
657
|
+
}
|
|
658
|
+
if (tokens > 0) attributes.push(`tokens="${tokens}"`)
|
|
659
|
+
return [{ type: 'text', text: `<${STUB_TAG} ${attributes.join(' ')}/>` }]
|
|
660
|
+
}
|