dsh-compaction-weave 0.0.0-stage → 0.3.4

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.
Files changed (92) hide show
  1. package/CHANGELOG.md +103 -0
  2. package/LICENSE +21 -0
  3. package/README.en.md +145 -0
  4. package/README.md +148 -2
  5. package/cordis.patch.yml +19 -0
  6. package/docs/architecture.md +84 -0
  7. package/docs/benchmarks/published-0.3.2-rc.1-tests.json +576 -0
  8. package/docs/benchmarks/rc2-documentation.json +41 -0
  9. package/docs/benchmarks/rc2-linux-tests.json +590 -0
  10. package/docs/benchmarks/rc2-live-and-cost.json +746 -0
  11. package/docs/benchmarks/rc3-host-compatibility.json +2314 -0
  12. package/docs/benchmarks/rc4-tests.json +617 -0
  13. package/docs/benchmarks/review35-compression.json +117 -0
  14. package/docs/benchmarks/v0.3.2-live-four-way.json +3495 -0
  15. package/docs/benchmarks/v0.3.2-tests.json +590 -0
  16. package/docs/configuration.md +131 -0
  17. package/docs/development.md +95 -0
  18. package/docs/en/architecture.md +75 -0
  19. package/docs/en/configuration.md +131 -0
  20. package/docs/en/development.md +92 -0
  21. package/docs/en/feedback.md +47 -0
  22. package/docs/en/principles.md +235 -0
  23. package/docs/en/testing.md +368 -0
  24. package/docs/en/troubleshooting.md +60 -0
  25. package/docs/feedback.md +47 -0
  26. package/docs/images/principles-context.en.svg +77 -0
  27. package/docs/images/principles-context.zh.svg +77 -0
  28. package/docs/images/principles-pipeline.en.svg +93 -0
  29. package/docs/images/principles-pipeline.zh.svg +93 -0
  30. package/docs/images/principles-recovery.en.svg +46 -0
  31. package/docs/images/principles-recovery.zh.svg +46 -0
  32. package/docs/principles.md +235 -0
  33. package/docs/test-results.json +634 -0
  34. package/docs/testing.md +358 -0
  35. package/docs/troubleshooting.md +60 -0
  36. package/lib/abort.js +13 -0
  37. package/lib/action-state.js +60 -0
  38. package/lib/atomic-replace.js +18 -0
  39. package/lib/attachments.js +76 -0
  40. package/lib/audit-reject.js +161 -0
  41. package/lib/audit.js +939 -0
  42. package/lib/cache-policy.js +71 -0
  43. package/lib/client.js +696 -0
  44. package/lib/command-compact.js +38 -0
  45. package/lib/command-heartbeat.js +61 -0
  46. package/lib/config.js +596 -0
  47. package/lib/constraint-scope.js +37 -0
  48. package/lib/continuation-budget.js +69 -0
  49. package/lib/continuation-pending.js +57 -0
  50. package/lib/continuation-progress.js +46 -0
  51. package/lib/continuation.js +287 -0
  52. package/lib/engine-entry.js +103 -0
  53. package/lib/engine.js +2485 -0
  54. package/lib/failure-diagnostics.js +220 -0
  55. package/lib/history-source.js +74 -0
  56. package/lib/history.js +712 -0
  57. package/lib/idle-compaction.js +64 -0
  58. package/lib/index.js +611 -0
  59. package/lib/instruction-source.js +163 -0
  60. package/lib/journal.js +164 -0
  61. package/lib/manual-error.js +179 -0
  62. package/lib/memory-policy.js +383 -0
  63. package/lib/meter.js +387 -0
  64. package/lib/observation-mask.js +390 -0
  65. package/lib/proactive.js +108 -0
  66. package/lib/progress-facts.js +347 -0
  67. package/lib/progress-state.js +30 -0
  68. package/lib/prompt.js +194 -0
  69. package/lib/reconstruct.js +72 -0
  70. package/lib/reference-input.js +107 -0
  71. package/lib/region.js +972 -0
  72. package/lib/source-provenance.js +58 -0
  73. package/lib/source-recovery.js +22 -0
  74. package/lib/source-refs.js +137 -0
  75. package/lib/state.js +46 -0
  76. package/lib/storage-path.js +42 -0
  77. package/lib/summary-budget.js +187 -0
  78. package/lib/summary-config.js +308 -0
  79. package/lib/summary-progress.js +56 -0
  80. package/lib/summary-retry.js +27 -0
  81. package/lib/summary-timeout.js +68 -0
  82. package/lib/summary.js +476 -0
  83. package/lib/tools.js +341 -0
  84. package/lib/transaction-host.js +252 -0
  85. package/lib/transaction.js +285 -0
  86. package/lib/validate.js +503 -0
  87. package/lib/version.js +3 -0
  88. package/lib/window.js +120 -0
  89. package/lib/work-report.js +55 -0
  90. package/locale/en.json +6 -0
  91. package/locale/zh.json +6 -0
  92. package/package.json +71 -4
package/lib/region.js ADDED
@@ -0,0 +1,972 @@
1
+ import {collectProgressFacts, renderProgressFacts, renderSummaryScope} from './progress-facts.js';
2
+ import {collectWorkReport, renderWorkReport, scopeWorkReport} from './work-report.js';
3
+ // 选区、边界校验、工具配对平衡、提交。
4
+ //
5
+ // 这些逻辑照抄官方 `dsh-compaction-basic` 的对应函数语义(已逐行读过
6
+ // `@deepseek-ai/dsh-compaction-basic@0.2.1-rc.5/lib/index.js:396-675`),
7
+ // 因为宿主对 surface 的约束是硬的:
8
+ // - 压缩区间的两端必须落在「工具调用/结果配对平衡」的位置,否则会把一次
9
+ // 工具调用切成两半,模型看到孤立的 tool_result 就会崩。
10
+ // - 区间必须在 surface 上找得到,且 start 的位置不能晚于 end。
11
+ // - 提交方式是:先 append 一条 `compaction/summary`,再 append 一条
12
+ // `user/message`,后者带 `surfaceOp: {op:'replace', startSeq, endSeq}`。
13
+ //
14
+ // 与官方的差异(本插件的 L5):提交时把「最近 N 条用户消息原文」拼在摘要
15
+ // 之后一起写进那条 user/message,这样用户原话永远不会被摘要改写。
16
+
17
+ import {isReferenceContextKind, renderChannelProvenance, sourceKindOf} from './source-provenance.js';
18
+ import {projectSummaryMessage} from './reference-input.js';
19
+ import {hasPreviousCancellation, restoreRetiredDecisions, selectMemoryMessages, boundMemoryQuotes, removeConsumedCancellations, restoreMemorySource} from './memory-policy.js';
20
+ import {sourceLayout} from './source-refs.js';
21
+ import {copyInstructionBoundaries,projectInstructionBoundaries} from './instruction-source.js';
22
+ const balanceCacheBySession = new WeakMap();
23
+
24
+ /**
25
+ * 本地估算,避免为了一个 4 行的工具函数去 import 另一个模块(region.js 被
26
+ * engine.js 引用,保持零内部依赖能减少循环引用风险)。
27
+ * 与 lib/meter.js 的 approxTokens 保持同一口径:CJK 1 字≈1 token,其余 4 字符≈1 token。
28
+ */
29
+ function approxTokensLocal(text) {
30
+ if (typeof text !== 'string' || text.length === 0) return 0;
31
+ let cjk = 0;
32
+ for (let i = 0; i < text.length; i += 1) {
33
+ const code = text.charCodeAt(i);
34
+ if (code >= 0x2e80 && code <= 0x9fff) cjk += 1;
35
+ else if (code >= 0xac00 && code <= 0xd7af) cjk += 1;
36
+ else if (code >= 0xf900 && code <= 0xfaff) cjk += 1;
37
+ }
38
+ const rest = text.length - cjk;
39
+ return cjk + Math.ceil(rest / 4);
40
+ }
41
+
42
+ function eventDelta(event) {
43
+ if (!event || typeof event !== 'object') return 0;
44
+ if (event.type === 'assistant/message') {
45
+ const content = event.data?.message?.content;
46
+ if (!Array.isArray(content)) return 0;
47
+ let count = 0;
48
+ for (const block of content) {
49
+ if (block && block.type === 'tool-call') count += 1;
50
+ }
51
+ return count;
52
+ }
53
+ if (event.type === 'tool/result') return -1;
54
+ return 0;
55
+ }
56
+
57
+ function surfaceNodes(session) {
58
+ const nodes = session?.surface?.nodes;
59
+ return Array.isArray(nodes) ? nodes : [];
60
+ }
61
+
62
+ function buildBalanceCache(session) {
63
+ const nodes = surfaceNodes(session);
64
+ const indexBySeq = new Map();
65
+ /** @type {number[]} */
66
+ const inProgress = [0];
67
+ let running = 0;
68
+ for (let i = 0; i < nodes.length; i += 1) {
69
+ const seq = nodes[i];
70
+ indexBySeq.set(seq, i);
71
+ const event = typeof session.eventAt === 'function' ? session.eventAt(seq) : undefined;
72
+ running += eventDelta(event);
73
+ if (running < 0) {
74
+ throw new Error(
75
+ `tool-pairing balance: tool/result at surface seq ${seq} has no matching tool-call (corrupt surface)`,
76
+ );
77
+ }
78
+ inProgress.push(running);
79
+ }
80
+ return {
81
+ generation: session?.surface?.replaceGeneration ?? 0,
82
+ length: nodes.length,
83
+ indexBySeq,
84
+ // cutBalanced[i] = 在 nodes[i] 之前切开是否平衡(i 从 0 到 length)
85
+ cutBalanced: inProgress.map((n) => n === 0),
86
+ };
87
+ }
88
+
89
+ function balanceCache(session) {
90
+ const generation = session?.surface?.replaceGeneration ?? 0;
91
+ const cached = balanceCacheBySession.get(session);
92
+ if (cached !== undefined && cached.generation === generation && cached.length === surfaceNodes(session).length) {
93
+ return cached;
94
+ }
95
+ const fresh = buildBalanceCache(session);
96
+ balanceCacheBySession.set(session, fresh);
97
+ return fresh;
98
+ }
99
+
100
+ /** 在 `seq` 之前切开是否平衡(即 seq 是某个 cut 的起点)。 */
101
+ export function toolPairingBalancedBefore(session, seq) {
102
+ const cache = balanceCache(session);
103
+ const index = cache.indexBySeq.get(seq);
104
+ if (index === undefined) throw new Error(`tool-pairing balance: surface seq ${seq} not found`);
105
+ return cache.cutBalanced[index] === true;
106
+ }
107
+
108
+ /** 在 `seq` 之后切开是否平衡(即 seq 是某个 cut 的终点)。 */
109
+ export function toolPairingBalancedAfter(session, seq) {
110
+ const cache = balanceCache(session);
111
+ const index = cache.indexBySeq.get(seq);
112
+ if (index === undefined) throw new Error(`tool-pairing balance: surface seq ${seq} not found`);
113
+ return cache.cutBalanced[index + 1] === true;
114
+ }
115
+
116
+ /** 会话首条是不是 system/message;是则压缩区间要从第二条开始。 */
117
+ export function systemHead(session, headSeq) {
118
+ if (typeof session.eventAt !== 'function') return undefined;
119
+ const event = session.eventAt(headSeq);
120
+ if (!event || event.type !== 'system/message') return undefined;
121
+ return event;
122
+ }
123
+
124
+ /**
125
+ * 官方 `selectCompactableRange` 的等价实现。
126
+ *
127
+ * @param {object} session
128
+ * @param {{ nodes: readonly number[], pricedNodes?: readonly {seq:number, tokens:number}[] }} measurement
129
+ * @param {number} retainTokens
130
+ * @returns {{ start: number, end: number }|null}
131
+ */
132
+ export function selectCompactableRange(session, measurement, retainTokens) {
133
+ const nodes = surfaceNodes(session);
134
+ const measured = measurement?.nodes;
135
+ if (!Array.isArray(measured) || measured.length !== nodes.length) {
136
+ throw new Error('compaction: token-meter surface does not match the current session surface');
137
+ }
138
+
139
+ // `ctx.tokenMeter.measure()` 返回的 `nodes[]` 元素是
140
+ // `{ seq, tokens, heuristicTokens }`(不是裸 seq 数字)。这里同时接受两种形态:
141
+ // 数字与对象,避免宿主口径不同时在这一行抛错。
142
+ const seqAt = (index) => {
143
+ const node = measured[index];
144
+ if (typeof node === 'number') return node;
145
+ if (node && typeof node === 'object' && typeof node.seq === 'number') return node.seq;
146
+ return undefined;
147
+ };
148
+ for (let i = 0; i < nodes.length; i += 1) {
149
+ if (seqAt(i) !== nodes[i]) {
150
+ throw new Error('compaction: token-meter surface does not match the current session surface');
151
+ }
152
+ }
153
+ if (nodes.length === 0) return null;
154
+
155
+ const firstIdx = systemHead(session, nodes[0]) === undefined ? 0 : 1;
156
+ if (firstIdx >= nodes.length) return null;
157
+
158
+ // 先把带价节点建成 Map:`find()` 在长会话里是 O(n²),
159
+ // 上万条消息时会把事件循环卡住(bili 的 slow-session 就是这么来的)。
160
+ const pricedBySeq = new Map();
161
+ if (measurement.pricedBySeq instanceof Map) {
162
+ for (const [seq, tokens] of measurement.pricedBySeq) {
163
+ if (typeof seq === 'number' && typeof tokens === 'number') pricedBySeq.set(seq, tokens);
164
+ }
165
+ }
166
+ for (const node of measured) {
167
+ if (!node || typeof node !== 'object' || typeof node.seq !== 'number') continue;
168
+ if (typeof node.tokens === 'number' && Number.isFinite(node.tokens)) {
169
+ pricedBySeq.set(node.seq, node.tokens);
170
+ }
171
+ }
172
+ if (Array.isArray(measurement.pricedNodes)) {
173
+ for (const node of measurement.pricedNodes) {
174
+ if (node && typeof node.seq === 'number' && typeof node.tokens === 'number') {
175
+ pricedBySeq.set(node.seq, node.tokens);
176
+ }
177
+ }
178
+ }
179
+
180
+ // pricedNodes 缺失或不完整时退化成按文本长度估算,否则 `kept` 永远是 0,
181
+ // 保留区会被算成"没有",结果一路压到只留第一条。
182
+ const tokensOf = (seq) => {
183
+ const priced = pricedBySeq.get(seq);
184
+ if (typeof priced === 'number' && priced > 0) return priced;
185
+ const event = typeof session.eventAt === 'function' ? session.eventAt(seq) : undefined;
186
+ const message =
187
+ typeof session.deriveEventMessage === 'function' ? session.deriveEventMessage(event) : undefined;
188
+ const text = textOfMessage(message);
189
+ return text === null ? 0 : approxTokensLocal(text);
190
+ };
191
+
192
+ // 从尾部往前累加,直到攒够保留额度;keepFromIdx 之前的部分可以压。
193
+ //
194
+ // 注意 `retainTokens === 0` 的语义:官方实现里循环体至少跑一次
195
+ // (`accumulated >= retainTokens` 在 retainTokens=0 时立刻为真),所以
196
+ // **最后一条 surface 节点永远被保留**。手动 `/compact` 传的就是 0,如果这里
197
+ // 也按 0 处理成"一条都不留",checkpoint 会把整段历史(含最后一轮)全换掉,
198
+ // 模型下一轮就完全看不到刚才发生了什么。这里逐字对齐官方。
199
+ let keepFromIdx = nodes.length;
200
+ let kept = 0;
201
+ for (let index = nodes.length - 1; index >= firstIdx; index -= 1) {
202
+ kept += tokensOf(nodes[index]);
203
+ keepFromIdx = index;
204
+ if (kept >= retainTokens) break;
205
+ }
206
+
207
+ // 边界必须落在工具配对平衡处,否则往前退。
208
+ while (keepFromIdx > firstIdx && !toolPairingBalancedBefore(session, nodes[keepFromIdx])) {
209
+ keepFromIdx -= 1;
210
+ }
211
+ if (keepFromIdx <= firstIdx) return null;
212
+
213
+ return { start: nodes[firstIdx], end: nodes[keepFromIdx - 1] };
214
+ }
215
+
216
+ /**
217
+ * 官方 `validateSurfaceRegion` 的等价实现,报错原文保持一致,便于对照日志。
218
+ */
219
+ export function validateSurfaceRegion(session, start, end) {
220
+ const nodes = surfaceNodes(session);
221
+ const startIdx = nodes.indexOf(start);
222
+ const endIdx = nodes.indexOf(end);
223
+ if (startIdx < 0) throw new Error(`compactRegion: start seq ${start} not found in surface`);
224
+ if (endIdx < 0) throw new Error(`compactRegion: end seq ${end} not found in surface`);
225
+ if (startIdx > endIdx) {
226
+ throw new Error(
227
+ `compactRegion: start seq ${start} (position ${startIdx}) is after end seq ${end} (position ${endIdx}) on the surface`,
228
+ );
229
+ }
230
+ if (!toolPairingBalancedBefore(session, start)) {
231
+ throw new Error(
232
+ `compactRegion: start seq ${start} is not a balanced boundary (would split a step's tool-call/result pair)`,
233
+ );
234
+ }
235
+ if (!toolPairingBalancedAfter(session, end)) {
236
+ throw new Error(
237
+ `compactRegion: end seq ${end} is not a balanced boundary (would split a step, or the step is still open)`,
238
+ );
239
+ }
240
+ }
241
+
242
+ /**
243
+ * 扫描会话尾部,判断当前是否已经有一轮压缩在进行、是否有未闭合的 turn。
244
+ * 官方 `inspectCompactionEntryState` 的等价实现。
245
+ * @param {object} session
246
+ */
247
+ export function inspectCompactionEntryState(session) {
248
+ const seq = typeof session?.seq === 'number' ? session.seq : 0;
249
+ let openTurnSeq = null;
250
+ let openTurn = null;
251
+ let unmatchedCompactionStart = null;
252
+ let latestEndSeedSeq = null;
253
+
254
+ for (let cursor = seq - 1; cursor >= 0; cursor -= 1) {
255
+ const event = typeof session.eventAt === 'function' ? session.eventAt(cursor) : undefined;
256
+ if (!event) continue;
257
+ if (latestEndSeedSeq === null && event.type === 'session/end-seed') latestEndSeedSeq = cursor;
258
+ if (unmatchedCompactionStart === null) {
259
+ if (event.type === 'compaction/end') {
260
+ unmatchedCompactionStart = false;
261
+ } else if (event.type === 'compaction/start') {
262
+ unmatchedCompactionStart = cursor;
263
+ }
264
+ }
265
+ if (openTurn === null) {
266
+ if (event.type === 'turn/end') {
267
+ openTurn = false;
268
+ } else if (event.type === 'turn/start') {
269
+ // ⚠️ turn 身份是 `event.data.turn`(一个从 1 递增的小整数),
270
+ // **不是**事件序号。把 cursor 当成 turn 写进 compaction/start 会让
271
+ // 宿主的 turn 归属错位(seq=42 的 turn 可能实际是第 3 轮)。
272
+ openTurnSeq = cursor;
273
+ const raw = event.data?.turn;
274
+ openTurn = typeof raw === 'number' && Number.isFinite(raw) ? raw : null;
275
+ }
276
+ }
277
+ if (openTurn !== null && unmatchedCompactionStart !== null && latestEndSeedSeq !== null) break;
278
+ }
279
+
280
+ return {
281
+ openTurn: openTurn === false ? null : openTurn,
282
+ openTurnSeq,
283
+ unmatchedCompactionStart: unmatchedCompactionStart === false ? null : unmatchedCompactionStart,
284
+ latestEndSeedSeq,
285
+ };
286
+ }
287
+
288
+ /**
289
+ * 会话上是否已经挂着一把压缩锁。
290
+ *
291
+ * 官方语义(`assertCompactionInactive(unmatchedCompactionStart, latestEndSeedSeq, stage)`):
292
+ * 只有当「未闭合的 compaction/start」比「最近一次 session/end-seed」更**新**时,
293
+ * 才算锁还活着。否则说明那是上一个会话生命周期里崩掉留下的孤儿锁 —— 这时候
294
+ * 必须放行,否则一次崩溃会让这个会话永远压不动(用户感知就是"再也不压缩了,
295
+ * 一路涨到 413")。
296
+ *
297
+ * @param {number|null} unmatchedCompactionStart
298
+ * @param {number|null} [latestEndSeedSeq]
299
+ * @param {string} [stage]
300
+ */
301
+ export function assertCompactionInactive(unmatchedCompactionStart, latestEndSeedSeq, stage = 'compaction') {
302
+ if (unmatchedCompactionStart === null || unmatchedCompactionStart === undefined) return;
303
+ if (latestEndSeedSeq !== null && latestEndSeedSeq !== undefined && latestEndSeedSeq > unmatchedCompactionStart) {
304
+ // 孤儿锁:属于更早的会话生命周期,不再阻塞本次压缩。
305
+ return;
306
+ }
307
+ const error = new Error(
308
+ `${stage}: compaction already in progress; the session compaction lock is already active`,
309
+ );
310
+ error.code = 'busy';
311
+ throw error;
312
+ }
313
+
314
+ /**
315
+ * 把被压缩区间里的消息抽出来,作为摘要调用的输入。
316
+ * 官方 `buildSummarizationInput` 的等价实现。
317
+ *
318
+ * @param {object} session
319
+ * @param {readonly number[]} shadowedSeqs
320
+ */
321
+ export function buildSummarizationInput(session, shadowedSeqs, options = {}) {
322
+ const nodes = surfaceNodes(session);
323
+ const head = nodes.length > 0 ? systemHead(session, nodes[0]) : undefined;
324
+ const system =
325
+ head !== undefined && typeof session.deriveEventMessage === 'function'
326
+ ? session.deriveEventMessage(head)
327
+ : null;
328
+
329
+ const firstBodyIdx = head !== undefined ? 1 : 0;
330
+ const startIdx = Array.isArray(shadowedSeqs) && shadowedSeqs.length > 0 ? nodes.indexOf(shadowedSeqs[0]) : -1;
331
+ const endIdx = Array.isArray(shadowedSeqs) && shadowedSeqs.length > 0 ? nodes.indexOf(shadowedSeqs.at(-1)) : -1;
332
+ const useVerbatimPrefix =
333
+ options.preservePrefixCache === true &&
334
+ typeof session.deriveEventMessage === 'function' &&
335
+ startIdx >= firstBodyIdx &&
336
+ endIdx >= startIdx &&
337
+ endIdx - startIdx + 1 === shadowedSeqs.length &&
338
+ shadowedSeqs.every((seq, offset) => nodes[startIdx + offset] === seq);
339
+
340
+ const messages = [];
341
+ let verbatimSeqs;
342
+ let prefixBoundary;
343
+ if (useVerbatimPrefix) {
344
+ verbatimSeqs = nodes.slice(firstBodyIdx, endIdx + 1);
345
+ let actualPrefixCount = 0;
346
+ for (let i = 0; i < verbatimSeqs.length; i += 1) {
347
+ const seq = verbatimSeqs[i];
348
+ const event = typeof session.eventAt === 'function' ? session.eventAt(seq) : undefined;
349
+ if (!event) continue;
350
+ const message = session.deriveEventMessage(event);
351
+ if (message !== null && message !== undefined) {
352
+ messages.push(message);
353
+ if (firstBodyIdx + i < startIdx) actualPrefixCount += 1;
354
+ }
355
+ }
356
+ if (actualPrefixCount > 0) {
357
+ prefixBoundary = {
358
+ prefixCount: actualPrefixCount,
359
+ startSeq: shadowedSeqs[0],
360
+ endSeq: shadowedSeqs.at(-1),
361
+ };
362
+ }
363
+ } else {
364
+ for (const seq of shadowedSeqs) {
365
+ if (typeof session.deriveEventMessage !== 'function') break;
366
+ const event = typeof session.eventAt === 'function' ? session.eventAt(seq) : undefined;
367
+ if (!event) continue;
368
+ const message = projectSummaryMessage(session, event, session.deriveEventMessage(event));
369
+ if (message !== null && message !== undefined) messages.push(message);
370
+ }
371
+ }
372
+
373
+ const header = typeof session.requestHeader === 'function' ? session.requestHeader() : undefined;
374
+ const tools = header?.tools;
375
+ const progress=shadowedSeqs.length?(options.selectProgress??(seqs=>collectProgressFacts(session,seqs)))(shadowedSeqs):null;
376
+ const channelProvenance = renderChannelProvenance(session, shadowedSeqs);
377
+ const input = {
378
+ messages: system === null ? messages : [system, ...messages],
379
+ workReport: scopeWorkReport(collectWorkReport(session,shadowedSeqs),progress),
380
+ progress,
381
+ ...(channelProvenance ? { channelProvenance } : {}),
382
+ ...(verbatimSeqs ? { verbatimSeqs } : {}),
383
+ ...(prefixBoundary ? { prefixBoundary } : {}),
384
+ };
385
+ if (Array.isArray(tools) && tools.length > 0) input.tools = [...tools];
386
+ return input;
387
+ }
388
+
389
+ /**
390
+ * Collect exact original source messages from a span, including checkpoint
391
+ * references. This raw-source helper is unbounded unless limits are supplied;
392
+ * production selection/deduplication uses selectSessionMemory afterwards.
393
+ * Source fragments are recovered from durable events, not generated summaries.
394
+ * Text blocks retain their original whitespace and code fences.
395
+ *
396
+ * @param {object} session
397
+ * @param {readonly number[]} spanSeqs 即将被摘要覆盖的 seq(按 surface 顺序)
398
+ * @param {{ maxMessages?: number|null, maxTokens?: number|null, approxTokens?: (text:string)=>number, instructionsOnly?: boolean }} [options]
399
+ * @returns {{ seq: number, blocks: {type:'text', text:string}[], text: string }[]}
400
+ */
401
+ function restoreCheckpointMemory(session, checkpoint, original, ref) {
402
+ try { return restoreMemorySource(original,ref); }
403
+ catch(error) {
404
+ if(ref.layout||error.code!=='MEMORY_SOURCE_UNAVAILABLE')throw error;
405
+ // Older continuation checkpoints stored a constraint-only projection under
406
+ // the original seq. Match its recorded hash AND prove its source substrings.
407
+ const restoreFrom=event=>{
408
+ if(event?.type!=='user/message'||!isCompactCheckpointEvent(event))return null;
409
+ for(const field of ['preserved','memoryRequirements'])for(const candidate of event.data.source[field]??[]){
410
+ if(candidate?.seq!==ref.seq)continue;
411
+ try {
412
+ const blocks=Array.isArray(candidate.blocks)?candidate.blocks:typeof candidate.text==='string'?[{type:'text',text:candidate.text}]:[];
413
+ if(!blocks.length||blocks.some(b=>b.type!=='text'||typeof b.text!=='string'))continue;
414
+ const restored=restoreMemorySource({...candidate,blocks,text:blocks.map(b=>b.text).join('\n')},ref);
415
+ if(!restored)continue;
416
+ const layout=sourceLayout(restored,original); // Reject invented, reordered or edited prose.
417
+ return projectInstructionBoundaries(restored,original,layout);
418
+ }catch{/* Try an earlier authoritative projection; never fabricate text. */}
419
+ }
420
+ return null;
421
+ };
422
+ // Usually this checkpoint itself has the matching projection. Avoid scanning
423
+ // the entire event log again on every planning and audit pass in that case.
424
+ const current=restoreFrom(checkpoint);if(current)return current;
425
+ for(let seq=checkpoint.seq-1;seq>ref.seq;seq--){
426
+ const restored=restoreFrom(session.eventAt(seq));if(restored)return restored;
427
+ }
428
+ throw error;
429
+ }
430
+ }
431
+
432
+ export function collectRecentUserMessages(session, spanSeqs, options = {}) {
433
+ const out = [];
434
+ if (!Array.isArray(spanSeqs) || spanSeqs.length === 0) return out;
435
+ if (typeof session.eventAt !== 'function') return out;
436
+
437
+ const maxMessages =
438
+ typeof options.maxMessages === 'number' && Number.isFinite(options.maxMessages)
439
+ ? Math.max(0, Math.trunc(options.maxMessages))
440
+ : null;
441
+ const maxTokens =
442
+ typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens)
443
+ ? Math.max(0, options.maxTokens)
444
+ : null;
445
+ if (maxMessages === 0 || maxTokens === 0) return out;
446
+
447
+ const collected = [];
448
+ for (const seq of spanSeqs) {
449
+ const event = session.eventAt(seq);
450
+ if (!event || event.type !== 'user/message') continue;
451
+ if (isCompactCheckpointEvent(event)) {
452
+ if (Array.isArray(event.data.source.memorySources)) {
453
+ for (const ref of event.data.source.memorySources) {
454
+ const original = session.eventAt(ref?.seq);
455
+ if (!Number.isSafeInteger(ref?.seq) || ref.seq >= event.seq || original?.type !== 'user/message' || isCompactCheckpointEvent(original)) {
456
+ throw Object.assign(new Error('Cannot resolve checkpoint memory source.'), {code:'CHECKPOINT_PRESERVED_UNREADABLE'});
457
+ }
458
+ const blocks = blocksOfMessage(session.deriveEventMessage(original));
459
+ if (!blocks) throw Object.assign(new Error('Missing original memory source blocks.'), {code:'CHECKPOINT_PRESERVED_UNREADABLE'});
460
+ const restored = restoreCheckpointMemory(session,event,{seq:ref.seq,blocks,text:blocks.map(b=>b.text).join('\n')},ref);
461
+ if (restored) collected.push(restored);
462
+ }
463
+ continue;
464
+ }
465
+ // 上一代检查点:正文是摘要,不能当原话抄;但它携带的原始原话要续传。
466
+ //
467
+ // ⚠️ 解析不出可信结构时必须**中止**,不能当成"这一代没有原话"。
468
+ // 旧格式没有 `source.preserved`,只能反解析渲染文本;一旦原文里
469
+ // 恰好有一行和容器标记同形,任何猜测都可能吞掉后半段用户原话。
470
+ // 而覆盖校验核对的是同一份(被截短的)列表,会一路绿灯提交。
471
+ // 宁可这次不压,也不能用"看起来成功"换掉用户原话。
472
+ const inspected = inspectCheckpointPreserved(event);
473
+ if (!inspected.ok || !inspected.structured) {
474
+ // V8-07:旧格式用 `--- seq N ---` 分隔每条原话,而用户原文里也完全可能
475
+ // 有一行长得一模一样。按文本切就是在猜 —— 猜错了会把一行原文当分隔符
476
+ // 吞掉,而覆盖校验核对的是同一份被吞过的列表,照样一路绿灯。
477
+ //
478
+ // 这里**不再猜**:改从会话日志里恢复。那次压缩留下的 `compaction/summary`
479
+ // 事件带着 `shadowedSeqs`,顺着它把原始 `user/message` 读回来,得到的是
480
+ // 完整清单,不是猜测结果。恢复不了就安全拒绝。
481
+ const recovered = recoverLegacyCheckpointPreserved(session, event);
482
+ if (recovered !== null) {
483
+ for (const carried of recovered) collected.push(carried);
484
+ continue;
485
+ }
486
+ const error = new Error(
487
+ `compaction: cannot recover the original user messages from the previous checkpoint (${inspected.reason ?? 'legacy checkpoint has no authoritative structured originals'}); ` +
488
+ 'refusing to compact rather than guessing and dropping part of them',
489
+ );
490
+ error.code = 'CHECKPOINT_PRESERVED_UNREADABLE';
491
+ throw error;
492
+ }
493
+ for (const carried of inspected.preserved) {
494
+ const original=session.eventAt(carried.seq);
495
+ if(original?.type!=='user/message'||isCompactCheckpointEvent(original)){collected.push(carried);continue;}
496
+ const blocks=blocksOfMessage(session.deriveEventMessage(original));
497
+ if(!blocks)throw Object.assign(new Error('Missing original memory source blocks.'),{code:'CHECKPOINT_PRESERVED_UNREADABLE'});
498
+ const source={seq:carried.seq,blocks,text:blocks.map(b=>b.text).join('\n')};
499
+ const layout=sourceLayout(carried,source);
500
+ collected.push(projectInstructionBoundaries(carried,source,layout));
501
+ }
502
+ continue;
503
+ }
504
+ const message = typeof session.deriveEventMessage === 'function' ? session.deriveEventMessage(event) : undefined;
505
+ const blocks = blocksOfMessage(message);
506
+ if (blocks === null) continue;
507
+ collected.push({ seq, blocks, text: blocks.map((block) => block.text).join('\n') });
508
+ }
509
+
510
+ // 上限只在用户显式设定时生效,且从最新往前累加(新的原话优先级更高)。
511
+ let used = 0;
512
+ for (let i = collected.length - 1; i >= 0; i -= 1) {
513
+ const item = collected[i];
514
+ const sourceKind = sourceKindOf(session, item.seq);
515
+ // Filter before applying user-preservation limits: a host reference must
516
+ // neither consume a user slot nor crowd an actual requirement out of it.
517
+ if (options.instructionsOnly && isReferenceContextKind(sourceKind)) continue;
518
+ if (maxMessages !== null && out.length >= maxMessages) break;
519
+ if (maxTokens !== null) {
520
+ const cost = approxTokensFor(item.text, options.approxTokens);
521
+ if (used + cost > maxTokens) break;
522
+ used += cost;
523
+ }
524
+ // Provenance comes from the durable original event, never from text which
525
+ // merely claims to be memory. Re-resolve carried checkpoint entries too:
526
+ // older checkpoints did not serialize the kind of each original message.
527
+ const { sourceKind: ignoredSourceKind, ...original } = item;
528
+ out.push(copyInstructionBoundaries(item,typeof sourceKind === 'string' ? { ...original, sourceKind } : original));
529
+ }
530
+
531
+ out.reverse();
532
+ return out;
533
+ }
534
+
535
+ // One selection contract for planning, exact preservation, audit and continuation.
536
+ // Full reference content remains in durable events and the source archive.
537
+ function carriedDecisions(session, seqs) {
538
+ return seqs.flatMap(seq=>{
539
+ const event=session.eventAt(seq);
540
+ return event?.data?.source?.kind==='compact-checkpoint' ? event.data.source.memoryDecisions??[] : [];
541
+ });
542
+ }
543
+ export function collectInstructionMessages(session, spanSeqs, options = {}) {
544
+ const decisions=carriedDecisions(session,session.surface?.nodes??spanSeqs);
545
+ return removeConsumedCancellations(collectRecentUserMessages(session,spanSeqs,{...options,instructionsOnly:true}),decisions);
546
+ }
547
+
548
+ // Newer tail messages govern revisions of an older prefix. Keep only fragment
549
+ // hashes for consumed cancellations while their original tail event remains live.
550
+ // Resolve relative cancellation against the durable user sequence, including
551
+ // no-op nudges already omitted from old checkpoints. Otherwise "cancel previous"
552
+ // can jump backwards to an unrelated surviving requirement after compaction.
553
+ function withPreviousUserContext(session,messages) {
554
+ return messages.map(message=>{
555
+ if(!hasPreviousCancellation(message))return message;
556
+ for(let seq=message.seq-1;seq>=0;seq--){
557
+ const event=session.eventAt(seq);
558
+ if(event?.type!=='user/message')continue;
559
+ const kind=sourceKindOf(session,seq);
560
+ if(kind===undefined||kind==='user')return copyInstructionBoundaries(message,{...message,previousUserSeq:seq});
561
+ }
562
+ return message;
563
+ });
564
+ }
565
+ // Reuse the expensive global lifecycle resolution within one synchronous
566
+ // planning operation. The selector cannot be reused after the surface changes.
567
+ export function createSessionMemorySelector(session, nodes = session.surface?.nodes??[]) {
568
+ const generation=session.surface?.replaceGeneration??0,snapshot=[...nodes],length=nodes.length;
569
+ const all=withPreviousUserContext(session,collectInstructionMessages(session,nodes));
570
+ const global=selectMemoryMessages(all,{maxMessages:Infinity,maxTokens:Infinity});
571
+ const retired=nodes.flatMap(seq=>{const event=session.eventAt(seq);return event?.data?.source?.kind==='compact-checkpoint'?restoreRetiredDecisions(event.data.source.memoryDecisions??[],session,seq):[];});
572
+ return (spanSeqs,options={})=>{
573
+ const current=session.surface?.nodes??nodes;
574
+ if(current.length!==length||(session.surface?.replaceGeneration??0)!==generation||current.some((seq,index)=>seq!==snapshot[index]))throw Object.assign(new Error('Session surface changed during memory planning; create a fresh selector.'),{code:'MEMORY_SELECTION_STALE'});
575
+ const local=collectInstructionMessages(session,spanSeqs),localSeqs=new Set(local.map(m=>m.seq));
576
+ const selected=boundMemoryQuotes(global.active.filter(m=>localSeqs.has(m.seq)),options);
577
+ const applied=new Set(global.decisions.filter(d=>localSeqs.has(d.seq)&&d.reason==='cancelled').map(d=>d.by));
578
+ const inherited=carriedDecisions(session,spanSeqs).filter(d=>d.reason==='cancellation-applied'&&nodes.includes(d.seq));
579
+ const decisions=[...retired,...inherited,...global.decisions.filter(d=>localSeqs.has(d.seq)||d.reason==='cancellation-applied'&&applied.has(d.seq)),...selected.decisions];
580
+ const governingSeqs=new Set(decisions.filter(d=>d.by!==undefined&&!localSeqs.has(d.by)).map(d=>d.by));
581
+ return {...selected,retained:global.active.filter(m=>!localSeqs.has(m.seq)),governing:global.active.filter(m=>governingSeqs.has(m.seq)),decisions:[...new Map(decisions.map(d=>[JSON.stringify(d),d])).values()]};
582
+ };
583
+ }
584
+ export function selectSessionMemory(session, spanSeqs, options = {}) {
585
+ return createSessionMemorySelector(session,session.surface?.nodes??spanSeqs)(spanSeqs,options);
586
+ }
587
+
588
+ /**
589
+ * 从一代检查点消息里取回它当年携带的**原始用户原话**,用于跨代续传。
590
+ *
591
+ * 结构化来源优先(本插件写入时带 `source.preserved`),文本解析只作兜底
592
+ * (兼容没有该字段的旧检查点)。
593
+ *
594
+ * @param {object} event
595
+ * @returns {{ seq: number, blocks: {type:'text', text:string}[], text: string }[]}
596
+ */
597
+ export function preservedFromCheckpoint(event) {
598
+ const inspected = inspectCheckpointPreserved(event);
599
+ return inspected.ok ? inspected.preserved : [];
600
+ }
601
+
602
+ /** 保留段容器的起止标记。 */
603
+ const PRESERVED_OPEN = '<preserved-user-messages>';
604
+ const PRESERVED_CLOSE = '</preserved-user-messages>';
605
+
606
+ /**
607
+ * 解析检查点里的保留段,并**报告结构是否可信**。
608
+ *
609
+ * ⚠️ 旧格式只有渲染后的文本,没有 `source.preserved` 可以对照。这时候
610
+ * "容器标记"和"用户恰好写下的同一行"在字节上完全一样:原文里有一行
611
+ * `</preserved-user-messages>`,按行扫描就会把它当成段的结束,后面的
612
+ * 内容被整段丢弃 —— 而且丢掉之后覆盖校验拿的还是这份被截短的列表,
613
+ * 自己跟自己对得上,一路绿灯。
614
+ *
615
+ * 因此这里不按"第一个结束标记"切,而是按**已知的渲染结构**切:
616
+ * 保留段永远是检查点的最后一段(`buildCheckpointBlocks` 就是这么拼的),
617
+ * 所以真正的结束标记是**最后一个**、且其后只剩空行。
618
+ * 段内出现的同名标记一律当作用户原文保留。
619
+ *
620
+ * 无法无歧义判断时返回 `ok:false`,由调用方**安全拒绝压缩**,
621
+ * 而不是猜一个可能吞掉原话的切法。
622
+ *
623
+ * @param {object} event
624
+ * @returns {{ ok: true, preserved: {seq:number, blocks:{type:'text',text:string}[], text:string}[], structured: boolean }
625
+ * | { ok: false, reason: string }}
626
+ */
627
+ export function inspectCheckpointPreserved(event) {
628
+ const source = event?.data?.source;
629
+ const structured = source && typeof source === 'object' ? source.preserved : undefined;
630
+ if (Array.isArray(structured)) {
631
+ const out = [];
632
+ const extras = Array.isArray(source.memoryRequirements) ? source.memoryRequirements : [];
633
+ const identities = new Set(structured.map(item => item?.seq));
634
+ for (const item of [...structured, ...extras.filter(item => !identities.has(item?.seq))]) {
635
+ if (!item || typeof item !== 'object' || !Number.isSafeInteger(item.seq) || item.seq < 0) {
636
+ return { ok: false, reason: 'invalid structured original identity' };
637
+ }
638
+ const rawBlocks = Array.isArray(item.blocks) ? item.blocks : typeof item.text === 'string' ? [{ type: 'text', text: item.text }] : null;
639
+ if (!rawBlocks || rawBlocks.length === 0 || rawBlocks.some(block => !block || block.type !== 'text' || typeof block.text !== 'string')) {
640
+ return { ok: false, reason: 'invalid structured original blocks' };
641
+ }
642
+ const blocks = rawBlocks.map(block => ({ type: 'text', text: block.text }));
643
+ out.push({ seq: item.seq, blocks, text: blocks.map(block => block.text).join('\n') });
644
+ }
645
+ return { ok: true, preserved: out, structured: true };
646
+ }
647
+
648
+ const content = event?.data?.content;
649
+ if (!Array.isArray(content)) return { ok: true, preserved: [], structured: false };
650
+
651
+ const lines = [];
652
+ for (const block of content) {
653
+ if (!block || typeof block !== 'object' || block.type !== 'text' || typeof block.text !== 'string') continue;
654
+ for (const line of block.text.split('\n')) lines.push(line);
655
+ }
656
+
657
+ const open = lines.findIndex((line) => line.trim() === PRESERVED_OPEN);
658
+ if (open < 0) return { ok: true, preserved: [], structured: false };
659
+
660
+ const closes = [];
661
+ for (let index = open + 1; index < lines.length; index += 1) {
662
+ if (lines[index].trim() === PRESERVED_CLOSE) closes.push(index);
663
+ }
664
+ if (closes.length === 0) {
665
+ return { ok: false, reason: 'the preserved section has no closing marker' };
666
+ }
667
+
668
+ // 真正的结束标记是最后一个,并且其后只能是空行 —— 保留段永远排在检查点末尾。
669
+ const close = closes[closes.length - 1];
670
+ for (let index = close + 1; index < lines.length; index += 1) {
671
+ if (lines[index].trim().length > 0) {
672
+ return { ok: false, reason: 'unexpected content after the preserved section' };
673
+ }
674
+ }
675
+ // ⚠️ 段内出现**任何**容器标记行都算无法无歧义恢复。
676
+ // 旧格式(v6 之前)没有结构化的 `source.preserved`,原话只能从渲染文本里
677
+ // 反解析。用户消息里若恰好有一行 `</preserved-user-messages>`,它和真正的
678
+ // 结束标记长得一模一样 —— 取第一个会截掉后半段原话,取最后一个会把
679
+ // 中间那段"容器外的内容"吞进保留段。两种都错,而且错得看不出来:
680
+ // 后面那道覆盖校验核对的是**已经被截短/污染的列表**,会自己跟自己对上。
681
+ // 宁可这次不压,也不能用"看起来成功"换掉用户原话。
682
+ for (let index = open + 1; index < close; index += 1) {
683
+ const line = lines[index].trim();
684
+ if (line === PRESERVED_OPEN || line === PRESERVED_CLOSE) {
685
+ return { ok: false, reason: 'the preserved section contains another container marker' };
686
+ }
687
+ }
688
+
689
+ // ⚠️ V8-07:保留段里出现 `--- seq N ---` 这类分隔行时,**一律不当结构切**。
690
+ //
691
+ // 这条分隔行是旧格式(v6 及更早)每条原话之间的分隔符,也是本插件多块消息
692
+ // 用来标块边界的东西。问题在于:用户自己写的一句话,如果恰好就是
693
+ // `--- seq 99 ---`,它和结构分隔符在字节上完全一样。按行切就是在赌 ——
694
+ // 赌错了会把用户原文里的一行当分隔符吃掉,把一条消息劈成两条,而且
695
+ // `ok` 仍然是 true。后面那道覆盖校验核对的是同一份被污染的列表,
696
+ // 自己跟自己对得上,于是"看起来压缩成功",实际少了一行用户要求。
697
+ //
698
+ // 这里不再猜:报告 `legacyLayout`,让调用方从会话日志里那次压缩留下的
699
+ // `shadowedSeqs` 把**原始事件**读回来(那是完整清单,不是猜测结果)。
700
+ for (let index = open + 1; index < close; index += 1) {
701
+ if (/^--- seq -?\d+(?: block \d+)? ---$/.test(lines[index])) {
702
+ return {
703
+ ok: false,
704
+ legacyLayout: true,
705
+ reason:
706
+ 'the preserved section is written in the legacy "--- seq N ---" layout, where the separator ' +
707
+ 'cannot be told apart from a line the user actually typed',
708
+ };
709
+ }
710
+ }
711
+
712
+ // 走到这里说明保留段里没有任何分隔行。旧格式每条消息都带分隔符,所以
713
+ // 这段要么是单条无分隔的旧内容,要么是手工写的;整段按一条原话处理。
714
+ const text = lines.slice(open + 1, close).join('\n');
715
+ // 只跳过**整段空白**的条目,不做 trim —— 前导空格与缩进是原文的一部分。
716
+ if (text.trim().length === 0) return { ok: true, preserved: [], structured: false };
717
+ return {
718
+ ok: true,
719
+ preserved: [{ seq: -1, blocks: [{ type: 'text', text }], text }],
720
+ structured: false,
721
+ };
722
+ }
723
+
724
+ /**
725
+ * V8-07 的确定性恢复:从**会话日志**里把上一代检查点携带的用户原话读回来。
726
+ *
727
+ * 为什么这条路可信,而文本反解析不可信:
728
+ * - 文本里分隔符与用户原文同形,任何切法都是在猜;
729
+ * - 而会话日志里留着那次压缩写下的 `compaction/summary` 事件,它带
730
+ * `compactionId` 和 `shadowedSeqs`。顺着这些 seq 取原始 `user/message`
731
+ * 事件,拿到的是**当时真实存在的消息**,不需要猜任何边界。
732
+ *
733
+ * 压缩只改 surface(`state.nodes.splice`),不改事件日志,所以被折叠的那些
734
+ * 事件在 `session.eventAt(seq)` 上仍然读得到。
735
+ *
736
+ * 恢复不了(找不到对应 summary 事件、seq 越界或来源存在歧义)
737
+ * 一律返回 `null`,由调用方安全拒绝压缩 —— 宁可这次不压,也不能拿一份
738
+ * 猜出来的清单去替换用户原话。
739
+ *
740
+ * @param {object} session
741
+ * @param {object} checkpointEvent 上一代检查点事件
742
+ * @returns {{ seq:number, blocks:{type:'text',text:string}[], text:string }[] | null}
743
+ */
744
+ function recoverLegacyCheckpointPreserved(session, checkpointEvent) {
745
+ if (!session || typeof session.eventAt !== 'function') return null;
746
+ const compactionId = checkpointEvent?.data?.source?.compactionId;
747
+ if (typeof compactionId !== 'string' || compactionId.length === 0) return null;
748
+
749
+ const total = typeof session.seq === 'number' ? session.seq : null;
750
+ if (total === null || total <= 0) return null;
751
+
752
+ for (let seq = 0; seq < total; seq += 1) {
753
+ const event = session.eventAt(seq);
754
+ if (!event || event.type !== 'compaction/summary') continue;
755
+ if (event.data?.compactionId !== compactionId) continue;
756
+ const shadowed = event.data?.shadowedSeqs;
757
+ if (!Array.isArray(shadowed) || shadowed.length === 0) return null;
758
+ // 只认「整段都在日志里」的情况:越界说明日志被裁过,清单不完整。
759
+ for (const item of shadowed) {
760
+ if (!Number.isInteger(item) || item < 0 || item >= seq || !session.eventAt(item)) return null;
761
+ }
762
+ const checkpointSeq = Number.isSafeInteger(checkpointEvent.seq) ? checkpointEvent.seq : total;
763
+ if (seq >= checkpointSeq || new Set(shadowed).size !== shadowed.length) return null;
764
+ const recovered = collectRecentUserMessages(session, shadowed, {});
765
+ return recovered; // An empty set is valid only after every source event was checked.
766
+ }
767
+ return null;
768
+ }
769
+
770
+ function approxTokensFor(text, approx) {
771
+ return typeof approx === 'function' ? approx(text) : Math.ceil(text.length / 4);
772
+ }
773
+
774
+ /**
775
+ * 把一条消息的 content 摊平成 text 块数组,**不做任何裁剪或空白处理**。
776
+ * 每个 text 块单独保留,渲染时按块分段,多块消息的块边界也不会丢。
777
+ */
778
+ function blocksOfMessage(message) {
779
+ if (!message || typeof message !== 'object') return null;
780
+ const content = message.content;
781
+ if (typeof content === 'string') {
782
+ return content.length === 0 ? null : [{ type: 'text', text: content }];
783
+ }
784
+ if (!Array.isArray(content)) return null;
785
+ const blocks = [];
786
+ for (const block of content) {
787
+ if (!block || typeof block !== 'object') continue;
788
+ if (block.type === 'text' && typeof block.text === 'string') blocks.push({ type: 'text', text: block.text });
789
+ }
790
+ return blocks.length === 0 ? null : blocks;
791
+ }
792
+
793
+ /** 事件是不是本插件/官方写下的检查点消息(而不是真正的用户发言)。 */
794
+ function isCompactCheckpointEvent(event) {
795
+ const source = event?.data?.source;
796
+ if (!source || typeof source !== 'object') return false;
797
+ return source.kind === 'compact-checkpoint';
798
+ }
799
+
800
+ function textOfMessage(message) {
801
+ if (!message || typeof message !== 'object') return null;
802
+ const content = message.content;
803
+ if (typeof content === 'string') return content;
804
+ if (!Array.isArray(content)) return null;
805
+ const parts = [];
806
+ for (const block of content) {
807
+ if (block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string') {
808
+ parts.push(block.text);
809
+ }
810
+ }
811
+ return parts.length === 0 ? null : parts.join('\n');
812
+ }
813
+
814
+ /**
815
+ * 生成要写进 surface 的那条替换消息的内容:
816
+ * 检查点前言 + <compacted-summary>摘要</compacted-summary>
817
+ * + (可选)<preserved-user-messages>被压区间里的用户原话</preserved-user-messages>
818
+ *
819
+ * ⚠️ 保留段里**一个字都不能改**:不 trim、不合并多块、不换行规范化。
820
+ * "逐字保留"如果连空格和缩进都改了,那就不叫逐字 —— 代码缩进、命令行参数、
821
+ * 空白敏感的内容都会变味。分块渲染是为了让多块消息的块边界也留下来。
822
+ *
823
+ * @param {readonly any[]} summaryBlocks
824
+ * @param {readonly {seq:number, blocks?:{type:'text',text:string}[], text?:string}[]} preservedUserMessages
825
+ * @param {string} preamble
826
+ */
827
+ function normalizeArchivePath(value) {
828
+ if (typeof value !== 'string') return null;
829
+ const cleaned = value.trim().replace(/\s+/g, ' ');
830
+ if (!cleaned || cleaned.length > 120 || /[\r\n]/.test(cleaned)) return null;
831
+ return cleaned;
832
+ }
833
+
834
+ function extractCallPaths(args, out) {
835
+ let parsed = args;
836
+ if (typeof parsed === 'string') {
837
+ try { parsed = JSON.parse(parsed); } catch { return; }
838
+ }
839
+ if (!parsed || typeof parsed !== 'object') return;
840
+ for (const key of ['path', 'file_path']) {
841
+ const normalized = normalizeArchivePath(parsed[key]);
842
+ if (normalized) out.add(normalized);
843
+ }
844
+ if (Array.isArray(parsed.files)) {
845
+ for (const item of parsed.files) {
846
+ const candidate = typeof item === 'string' ? item : item?.path ?? item?.file_path;
847
+ const normalized = normalizeArchivePath(candidate);
848
+ if (normalized) out.add(normalized);
849
+ }
850
+ }
851
+ }
852
+
853
+ export function collectArchivedFiles(session, shadowedSeqs, maxFiles = 8) {
854
+ if (typeof session?.eventAt !== 'function' || !Array.isArray(shadowedSeqs) || maxFiles <= 0) return [];
855
+ const seen = new Set();
856
+ const inspectEvent = (event) => {
857
+ if (!event || typeof event !== 'object') return;
858
+ if (event.type === 'tool/call') {
859
+ extractCallPaths(event.data?.arguments, seen);
860
+ return;
861
+ }
862
+ if (event.type === 'assistant/message') {
863
+ const content = event.data?.message?.content;
864
+ if (!Array.isArray(content)) return;
865
+ for (const block of content) {
866
+ if (block && block.type === 'tool-call') {
867
+ extractCallPaths(block.args ?? block.arguments, seen);
868
+ if (seen.size >= maxFiles) break;
869
+ }
870
+ }
871
+ }
872
+ };
873
+ for (const seq of shadowedSeqs) {
874
+ const event = session.eventAt(seq);
875
+ if (!event) continue;
876
+ inspectEvent(event);
877
+ if (seen.size < maxFiles && Array.isArray(event.sourceEventSeqs)) {
878
+ for (const sourceSeq of event.sourceEventSeqs) {
879
+ const sourceEvent = session.eventAt(sourceSeq);
880
+ if (sourceEvent?.type === 'tool/call') inspectEvent(sourceEvent);
881
+ if (seen.size >= maxFiles) break;
882
+ }
883
+ }
884
+ if (seen.size >= maxFiles) break;
885
+ }
886
+ return [...seen].slice(0, maxFiles);
887
+ }
888
+
889
+ export function renderArchivePointer(archive) {
890
+ if (!archive || typeof archive.compactionId !== 'string' || !archive.compactionId) return '';
891
+ const span = Number.isInteger(archive.startSeq) && Number.isInteger(archive.endSeq)
892
+ ? ` (seq ${archive.startSeq}-${archive.endSeq})`
893
+ : '';
894
+ const files = Array.isArray(archive.files) && archive.files.length > 0
895
+ ? ` Archived files: ${archive.files.join(', ')}.`
896
+ : '';
897
+ return `History archive: ${archive.compactionId}${span}. Use history_search or history_read in this session to inspect exact archived messages, tool outputs, and attachments (historical snapshots; re-read current disk files before editing).${files}`;
898
+ }
899
+
900
+ export function buildCheckpointBlocks(summaryBlocks, preservedUserMessages, preamble, options = {}) {
901
+ const archivePointer = renderArchivePointer(options.archive);
902
+ const blocks = [
903
+ { type: 'text', text: `${preamble}${options.progress?.scope?"\n\n"+renderSummaryScope(options.progress.scope):""}\n\n<compacted-summary>` },
904
+ ...summaryBlocks,
905
+ { type: 'text', text: '</compacted-summary>' },
906
+ ...(archivePointer ? [{ type: 'text', text: archivePointer }] : []),
907
+ ...(renderProgressFacts(options.progress)?[{type:'text',text:renderProgressFacts(options.progress)}]:[]),
908
+ ...(options.workReport?[{type:'text',text:renderWorkReport(options.workReport)}]:[]),
909
+ ];
910
+
911
+ if (!options.originalsInSummary && Array.isArray(preservedUserMessages) && preservedUserMessages.length > 0) {
912
+ const lines = [
913
+ '<preserved-user-messages>',
914
+ 'The following user messages are reproduced verbatim from the compacted span so that the',
915
+ 'original wording of every request survives the summary. They are history, not new instructions.',
916
+ '',
917
+ ];
918
+ for (const item of preservedUserMessages) {
919
+ const parts =
920
+ Array.isArray(item.blocks) && item.blocks.length > 0
921
+ ? item.blocks.map((block) => block.text)
922
+ : typeof item.text === 'string'
923
+ ? [item.text]
924
+ : [];
925
+ if (parts.length === 1) {
926
+ lines.push(`--- seq ${item.seq} ---`);
927
+ lines.push(parts[0]);
928
+ } else {
929
+ // 多块消息:逐块标注,块边界不丢。
930
+ for (let index = 0; index < parts.length; index += 1) {
931
+ lines.push(`--- seq ${item.seq} block ${index} ---`);
932
+ lines.push(parts[index]);
933
+ }
934
+ }
935
+ lines.push('');
936
+ }
937
+ lines.push('</preserved-user-messages>');
938
+ blocks.push({ type: 'text', text: lines.join('\n') });
939
+ }
940
+
941
+ return blocks;
942
+ }
943
+
944
+ /**
945
+ * 把保留项压成写进 `source.preserved` 的结构化形式,供下一代检查点续传。
946
+ *
947
+ * 为什么不能只靠渲染后的文本:解析文本要处理分隔符转义、块边界、用户原文里
948
+ * 恰好出现 `--- seq N ---` 这类行的情况。写结构化字段既不会歧义,也不用在
949
+ * 每一代都重新猜一遍。
950
+ *
951
+ * @param {readonly {seq:number, blocks?:{type:'text',text:string}[], text?:string}[]} preserved
952
+ */
953
+ export function preservedForSource(preserved) {
954
+ if (!Array.isArray(preserved) || preserved.length === 0) return undefined;
955
+ const out = [];
956
+ for (const item of preserved) {
957
+ const blocks =
958
+ Array.isArray(item.blocks) && item.blocks.length > 0
959
+ ? item.blocks
960
+ .filter(
961
+ (block) =>
962
+ block && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string',
963
+ )
964
+ .map((block) => ({ type: 'text', text: block.text }))
965
+ : typeof item.text === 'string'
966
+ ? [{ type: 'text', text: item.text }]
967
+ : [];
968
+ if (blocks.length === 0) continue;
969
+ out.push({ seq: typeof item.seq === 'number' ? item.seq : -1, blocks });
970
+ }
971
+ return out.length === 0 ? undefined : out;
972
+ }