@logictan/dsh-verbatim-compaction 0.12.0 → 0.12.1
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/README.md +39 -3
- package/lib/index.js +458 -98
- package/lib/types/index.d.ts +108 -13
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -120,6 +120,41 @@
|
|
|
120
120
|
|
|
121
121
|
上限取**绝对值**而非「区间价的比例」。比例会让摘要随历史增长:同一会话实测早期区间 2642 字符、后期 51019 字符、触发事故那段 348539 字符——因为区间越大就允许摘要越大,而接近阈值的摘要立刻再触发压缩。固定上限让摘要大小与历史长度无关,宿主原生摘要也是这个形状(实测各区间稳定在 14009–22208 字符)。
|
|
122
122
|
|
|
123
|
+
## 超预算时折叠最旧的段,而不是删掉
|
|
124
|
+
|
|
125
|
+
摘要撞到 20000 token 上限后,把最旧的一批 section 交给模型压成一段,替换掉它们各自的提取块——不是删除:
|
|
126
|
+
|
|
127
|
+
```
|
|
128
|
+
## user
|
|
129
|
+
第1轮请求:…
|
|
130
|
+
|
|
131
|
+
### assistant
|
|
132
|
+
## Condensed (condensed from sections 1-20)
|
|
133
|
+
- <模型折叠出的段落>
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
覆盖范围内的 user 行全部保留(常驻约束不过期),只有各自的提取块被折掉,那才是腾出空间的地方。`covers` 按 **section** 计数而不是 turn:`buildSections` 每个用户请求开一节,所以一串连续请求就是一串连续 section;按 turn 计只会覆盖第一节,其余照旧渲染自己的块,折叠白做。
|
|
137
|
+
|
|
138
|
+
折叠只在普通渲染超预算时触发——它是一次模型调用,装得下就不该付费。
|
|
139
|
+
|
|
140
|
+
**折叠先于降级。** 折叠模式下 `renderDigest` 不走降级阶梯。此前 1200 轮时阶梯先丢掉 475 个 turn 的 body、只剩 `## Asked`,折叠根本没机会运行。
|
|
141
|
+
|
|
142
|
+
**折叠绝不截断。** 折叠路径返回完整文本,不做 `slice`:按字符切会把最后一块切成半句,而半句会被读成数据,比整节缺失更糟。折完全部分组仍超预算时(user 行本身过长),`summarize` 回退到降级阶梯并打 warn——预算上限是宿主 shrink guard 依赖的契约,降级后的摘要胜过超预算的摘要。
|
|
143
|
+
|
|
144
|
+
**折叠结果按内容缓存**(`provider:model:hashText(material)`,与提取缓存同一套 FNV-1a):历史每次压缩都从原始日志重建,不缓存就每次重新付费。
|
|
145
|
+
|
|
146
|
+
实测(真实模型、12000 字符摘要):折叠到 987 字符,压缩率 8.2%,保留了车控帧结构、签名覆盖范围与当前缺口。思考单独占 1873 token,`CONDENSE_TOKENS` 因此定为 6000——1200 时输出为空。
|
|
147
|
+
|
|
148
|
+
折叠组大小定为 100 个 section(按 8.2% 折叠率模拟):
|
|
149
|
+
|
|
150
|
+
| 组大小 | 700 轮 | 1200 轮 |
|
|
151
|
+
| --- | --- | --- |
|
|
152
|
+
| 20 | 19 次调用 | 52 次 |
|
|
153
|
+
| 50 | 8 次 | 21 次 |
|
|
154
|
+
| 100 | 4 次 | 11 次 |
|
|
155
|
+
|
|
156
|
+
**一个真实上限**:3000 轮时全折叠后仍超预算,因为 user 行本身合计 54786 字符。那不是折叠机制的问题——那么多请求的常驻约束本身就超过摘要容量。
|
|
157
|
+
|
|
123
158
|
## 为什么会收敛(一条真实事故)
|
|
124
159
|
|
|
125
160
|
只满足守卫**不等于**收敛。守卫只要求摘要比被替换的内容小,一个占到被替换量 99.3% 的摘要照样通过守卫,而 surface 几乎没变。
|
|
@@ -178,9 +213,10 @@ pnpm add @logictan/dsh-verbatim-compaction
|
|
|
178
213
|
|
|
179
214
|
## 已知边界
|
|
180
215
|
|
|
181
|
-
-
|
|
182
|
-
-
|
|
183
|
-
-
|
|
216
|
+
- **超预算时按节降级,不按字符截断。** 用户原话先占额度(`USER_BUDGET_SHARE` = 0.9);不够时整节丢弃(Overturned → Concluded → Did,`## Asked` 保留到最后);仍不够时从最旧端整轮丢弃 body,user 行留到最后。任何层级都不切半行。
|
|
217
|
+
- **折叠需要至少一个 section。** `foldGroupStarts` 按 `CONDENSE_GROUP`(100)分组;不足一组的会话仍会折叠那唯一一组,不会因「不够 100」而放弃。
|
|
218
|
+
- **折叠成本按组计。** 1200 轮约 11 次模型调用,但只在摘要真的撞到 20000 token 时才发生;本机最大摘要 8050 token。
|
|
219
|
+
- **user 行本身过长时无解。** 3000 轮会话的请求合计 54786 字符,超过 80000 字符预算,折叠再多也装不下——那是预算本身的上限,不是折叠机制的问题。
|
|
184
220
|
- **注入内容不进摘要。** 判据是 `source.kind !== 'user'`——注入上下文在一个真实会话里占 user 消息字符的 97%,放进摘要会把人的原话淹掉。
|
|
185
221
|
- **不改善首轮之外的工具参数细节。** `bash` 命令本身(占工具参数 84.2%)不保留;需要「当时跑了什么命令」的场景不在本插件的覆盖范围内。
|
|
186
222
|
|
package/lib/index.js
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* This backend keeps the base class's replay, range selection, durable
|
|
16
16
|
* transaction and shrink guard untouched and overrides only `summarize()`, the
|
|
17
17
|
* one hook the base class documents for exactly this purpose. The replacement
|
|
18
|
-
* summary is built
|
|
18
|
+
* summary is built from the log, with one model call per batch of turns:
|
|
19
19
|
*
|
|
20
20
|
* - user and assistant prose verbatim, per turn;
|
|
21
21
|
* - tool results reduced to one line (tool names, call counts, bytes);
|
|
@@ -55,8 +55,6 @@ export const DIGEST_TOKEN_CEILING = 20000;
|
|
|
55
55
|
const FRAME_TOKENS = 86;
|
|
56
56
|
/** Safety margin below the shrink guard, in tokens. */
|
|
57
57
|
const SHRINK_MARGIN_TOKENS = 512;
|
|
58
|
-
/** Per-turn floor when assistant prose has to be truncated, in characters. */
|
|
59
|
-
const MIN_TURN_CHARS = 800;
|
|
60
58
|
/**
|
|
61
59
|
* Share of the budget user prose may occupy before oldest-first truncation.
|
|
62
60
|
*
|
|
@@ -342,7 +340,7 @@ export function parseExtraction(answer) {
|
|
|
342
340
|
* @returns markdown with a heading per non-empty field; empty string when every
|
|
343
341
|
* field is empty.
|
|
344
342
|
*/
|
|
345
|
-
export function renderExtractionBlock(extraction) {
|
|
343
|
+
export function renderExtractionBlock(extraction, level = 3) {
|
|
346
344
|
if (extraction === undefined)
|
|
347
345
|
return '';
|
|
348
346
|
const lines = [];
|
|
@@ -351,9 +349,17 @@ export function renderExtractionBlock(extraction) {
|
|
|
351
349
|
return;
|
|
352
350
|
lines.push(`## ${heading}`, ...items.map((item) => `- ${item}`));
|
|
353
351
|
};
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
section
|
|
352
|
+
// `level` is how many of the graded sections survive: 3 keeps all, 2 drops
|
|
353
|
+
// Overturned, 1 keeps only Did, 0 keeps only Asked. Asked is never dropped by
|
|
354
|
+
// the level because it is the one section nothing later can rebuild — the
|
|
355
|
+
// reply arrives in the next turn, but the question and its options exist only
|
|
356
|
+
// here. See `renderDigest` for why the ladder exists at all.
|
|
357
|
+
if (level >= 1)
|
|
358
|
+
section('Did', extraction.did);
|
|
359
|
+
if (level >= 2)
|
|
360
|
+
section('Concluded', extraction.concluded);
|
|
361
|
+
if (level >= 3)
|
|
362
|
+
section('Overturned', extraction.overturned);
|
|
357
363
|
// Asked goes last and its options are listed under it, so the user's reply — the
|
|
358
364
|
// next `## user` line — lands directly under the list it chose from.
|
|
359
365
|
if (extraction.asked.length > 0) {
|
|
@@ -370,8 +376,62 @@ export function renderExtractionBlock(extraction) {
|
|
|
370
376
|
}
|
|
371
377
|
return lines.join('\n');
|
|
372
378
|
}
|
|
379
|
+
/**
|
|
380
|
+
* The group starts a fold walk visits, oldest first, one entry per group.
|
|
381
|
+
*
|
|
382
|
+
* Extracted so the walk's bounds are testable without a session, a logger and a
|
|
383
|
+
* model: the walk itself was where two defects lived — a bound that skipped the
|
|
384
|
+
* last group, and a start advanced from the success count, which retried a failed
|
|
385
|
+
* group on every pass.
|
|
386
|
+
*
|
|
387
|
+
* @param sectionCount - how many sections the digest has.
|
|
388
|
+
* @returns the start index of each group, in order.
|
|
389
|
+
*/
|
|
390
|
+
export function foldGroupStarts(sectionCount) {
|
|
391
|
+
const starts = [];
|
|
392
|
+
for (let start = 0; start < sectionCount; start += CONDENSE_GROUP)
|
|
393
|
+
starts.push(start);
|
|
394
|
+
return starts;
|
|
395
|
+
}
|
|
373
396
|
/** Turns handed to one extraction call. */
|
|
374
397
|
const TURNS_PER_CALL = 8;
|
|
398
|
+
/**
|
|
399
|
+
* Sections folded into one condensed block when the digest overflows.
|
|
400
|
+
*
|
|
401
|
+
* Each fold is a model call, so the group size trades calls against compression.
|
|
402
|
+
* Simulated on a 700- and a 1200-turn digest at the measured 8.2% fold ratio:
|
|
403
|
+
*
|
|
404
|
+
* group 20 → 19 and 52 calls
|
|
405
|
+
* group 50 → 8 and 21 calls
|
|
406
|
+
* group 100 → 4 and 11 calls
|
|
407
|
+
*
|
|
408
|
+
* Larger groups fold more text per call, which is also where the ratio holds
|
|
409
|
+
* best: a 20-section group is small enough that the model's own paragraph is a
|
|
410
|
+
* larger share of it. 100 keeps a long session to a handful of calls.
|
|
411
|
+
*/
|
|
412
|
+
const CONDENSE_GROUP = 100;
|
|
413
|
+
/**
|
|
414
|
+
* Output tokens allowed for one condensation call.
|
|
415
|
+
*
|
|
416
|
+
* A condensed block stands in for `CONDENSE_GROUP` sections, so it has to be far
|
|
417
|
+
* smaller than what it replaces to buy any room at all. Measured on 12000
|
|
418
|
+
* characters of real digest: the answer ran 565 tokens and produced 987
|
|
419
|
+
* characters, 8.2% of the input.
|
|
420
|
+
*
|
|
421
|
+
* The cap is far above that answer because thinking is charged to the same
|
|
422
|
+
* budget and is not small: the same call spent 1873 tokens thinking. At a 1200
|
|
423
|
+
* cap it returned an empty string in one run out of one — the thinking block
|
|
424
|
+
* took the whole allowance, the same failure the extraction call had.
|
|
425
|
+
*/
|
|
426
|
+
const CONDENSE_TOKENS = 6000;
|
|
427
|
+
const CONDENSE_INSTRUCTION = [
|
|
428
|
+
'The text above is the digest of a run of already-finished turns from a coding session.',
|
|
429
|
+
'Fold it into one short paragraph that a later turn can read to know what that stretch established.',
|
|
430
|
+
'Keep: decisions still in force, constraints that still apply, conclusions a later turn would otherwise redo, and anything later turns disproved.',
|
|
431
|
+
'Drop: per-turn narration, restatements, and detail already superseded by later turns in the same run.',
|
|
432
|
+
'Reply with the paragraph and nothing else. No heading, no bullets, no code fence, no preamble.',
|
|
433
|
+
'Write in the same language as the material.',
|
|
434
|
+
].join('\n');
|
|
375
435
|
/**
|
|
376
436
|
* Output tokens allowed per turn in an extraction call.
|
|
377
437
|
*
|
|
@@ -538,8 +598,8 @@ function turnOf(event) {
|
|
|
538
598
|
return typeof turn === 'number' && Number.isInteger(turn) ? turn : undefined;
|
|
539
599
|
}
|
|
540
600
|
/** A fresh, empty turn accumulator. */
|
|
541
|
-
function emptyTurn(turn) {
|
|
542
|
-
return { turn, user: [], assistant: [], tools: new Map(), resultBytes: 0, errors: [], writes: [] };
|
|
601
|
+
function emptyTurn(turn, fromRequest = false) {
|
|
602
|
+
return { turn, fromRequest, user: [], assistant: [], tools: new Map(), resultBytes: 0, errors: [], writes: [] };
|
|
543
603
|
}
|
|
544
604
|
/**
|
|
545
605
|
* Group append-origin surface events into per-turn digest material.
|
|
@@ -558,12 +618,12 @@ export function buildSections(events) {
|
|
|
558
618
|
let current;
|
|
559
619
|
let currentTurn;
|
|
560
620
|
let lastTurn;
|
|
561
|
-
const openTurn = (turn) => {
|
|
621
|
+
const openTurn = (turn, fromRequest = false) => {
|
|
562
622
|
if (current === undefined) {
|
|
563
623
|
current = { turns: [] };
|
|
564
624
|
sections.push(current);
|
|
565
625
|
}
|
|
566
|
-
const next = emptyTurn(turn);
|
|
626
|
+
const next = emptyTurn(turn, fromRequest);
|
|
567
627
|
current.turns.push(next);
|
|
568
628
|
if (turn !== undefined)
|
|
569
629
|
lastTurn = turn;
|
|
@@ -593,7 +653,7 @@ export function buildSections(events) {
|
|
|
593
653
|
// takes the user slot: it is the request this turn serves.
|
|
594
654
|
current = { turns: [] };
|
|
595
655
|
sections.push(current);
|
|
596
|
-
currentTurn = openTurn(turnOf(event) ?? lastTurn);
|
|
656
|
+
currentTurn = openTurn(turnOf(event) ?? lastTurn, false);
|
|
597
657
|
currentTurn.user.push(objective);
|
|
598
658
|
continue;
|
|
599
659
|
}
|
|
@@ -620,7 +680,7 @@ export function buildSections(events) {
|
|
|
620
680
|
// what makes the digest readable after a hundred turns.
|
|
621
681
|
current = { turns: [] };
|
|
622
682
|
sections.push(current);
|
|
623
|
-
currentTurn = openTurn(eventTurn);
|
|
683
|
+
currentTurn = openTurn(eventTurn, true);
|
|
624
684
|
const text = textOf(event);
|
|
625
685
|
if (text.length > 0)
|
|
626
686
|
currentTurn.user.push(text);
|
|
@@ -685,19 +745,35 @@ function withExtractions(sections, extracted) {
|
|
|
685
745
|
function turnKey(sectionIndex, turnIndex) {
|
|
686
746
|
return `${sectionIndex}:${turnIndex}`;
|
|
687
747
|
}
|
|
748
|
+
/**
|
|
749
|
+
* A stable hex digest of one string, used as a cache key.
|
|
750
|
+
*
|
|
751
|
+
* FNV-1a, 32-bit, two seeds. Not cryptographic: the risk here is an accidental
|
|
752
|
+
* collision between two inputs, and 64 bits over a few hundred entries makes that
|
|
753
|
+
* vanishingly unlikely.
|
|
754
|
+
*
|
|
755
|
+
* @param input - the text to hash.
|
|
756
|
+
* @returns a stable hex key.
|
|
757
|
+
*/
|
|
758
|
+
function hashText(input) {
|
|
759
|
+
let a = 0x811c9dc5;
|
|
760
|
+
let b = 0x01000193;
|
|
761
|
+
for (let index = 0; index < input.length; index += 1) {
|
|
762
|
+
const code = input.charCodeAt(index);
|
|
763
|
+
a = Math.imul(a ^ code, 0x01000193) >>> 0;
|
|
764
|
+
b = Math.imul(b ^ (code + index), 0x85ebca6b) >>> 0;
|
|
765
|
+
}
|
|
766
|
+
return `${a.toString(16)}${b.toString(16)}`;
|
|
767
|
+
}
|
|
688
768
|
/**
|
|
689
769
|
* Cache key for one slot's extraction material: a hash of everything the model
|
|
690
770
|
* would be shown.
|
|
691
771
|
*
|
|
692
772
|
* The material, not the slot's position or turn number: positions shift as
|
|
693
773
|
* history grows and numbers repeat, but identical material must produce an
|
|
694
|
-
* identical extraction. Hashing the exact string `buildExtractionMaterial`
|
|
695
|
-
*
|
|
696
|
-
*
|
|
697
|
-
*
|
|
698
|
-
* FNV-1a, 32-bit, two seeds. Not cryptographic: the risk here is an accidental
|
|
699
|
-
* collision between two turns, and 64 bits over a few hundred entries makes that
|
|
700
|
-
* vanishingly unlikely.
|
|
774
|
+
* identical extraction. Hashing the exact string `buildExtractionMaterial` returns
|
|
775
|
+
* means a change anywhere in the user request, the prose, or the tool trace
|
|
776
|
+
* invalidates the entry — nothing can silently go stale.
|
|
701
777
|
*
|
|
702
778
|
* @param events - one slot's events, in log order.
|
|
703
779
|
* @returns a stable hex key.
|
|
@@ -708,15 +784,7 @@ function materialKey(events) {
|
|
|
708
784
|
.map((event) => textOf(event))
|
|
709
785
|
.filter((text) => text.length > 0)
|
|
710
786
|
.join('\n');
|
|
711
|
-
|
|
712
|
-
let a = 0x811c9dc5;
|
|
713
|
-
let b = 0x01000193;
|
|
714
|
-
for (let index = 0; index < material.length; index += 1) {
|
|
715
|
-
const code = material.charCodeAt(index);
|
|
716
|
-
a = Math.imul(a ^ code, 0x01000193) >>> 0;
|
|
717
|
-
b = Math.imul(b ^ (code + index), 0x85ebca6b) >>> 0;
|
|
718
|
-
}
|
|
719
|
-
return `${a.toString(16)}${b.toString(16)}`;
|
|
787
|
+
return hashText(buildExtractionMaterial(events, prose));
|
|
720
788
|
}
|
|
721
789
|
/**
|
|
722
790
|
* Render one section to digest text, truncating assistant prose to `capChars`.
|
|
@@ -729,18 +797,46 @@ function materialKey(events) {
|
|
|
729
797
|
* The tool pointer line stays either way: it is one line, and it is the only
|
|
730
798
|
* record of what was actually run when the prose and extraction both say little.
|
|
731
799
|
*/
|
|
732
|
-
function renderSection(section,
|
|
800
|
+
function renderSection(section, level, condensed, sectionIndex) {
|
|
733
801
|
const lines = [];
|
|
734
|
-
|
|
802
|
+
// The block that covers this section, if any. Looked up by scanning the keys
|
|
803
|
+
// rather than by probing one key per turn: a fold spans whole sections, so the
|
|
804
|
+
// covering key belongs to an earlier section, not to this turn's own key.
|
|
805
|
+
const index = sectionIndex ?? 0;
|
|
806
|
+
let covering;
|
|
807
|
+
if (condensed !== undefined) {
|
|
808
|
+
for (const [key, block] of condensed) {
|
|
809
|
+
const start = Number(key.split(':')[0]);
|
|
810
|
+
if (index >= start && index < start + block.covers) {
|
|
811
|
+
covering = { key, block };
|
|
812
|
+
break;
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
if (covering !== undefined) {
|
|
817
|
+
// The user line stays: a request is a standing constraint. Only the first
|
|
818
|
+
// covered section prints the folded text — the rest contribute their user
|
|
819
|
+
// lines alone, which is the room the condensation buys.
|
|
820
|
+
const start = Number(covering.key.split(':')[0]);
|
|
821
|
+
for (const turn of section.turns) {
|
|
822
|
+
if (turn.user.length > 0)
|
|
823
|
+
lines.push(`\n## user\n${turn.user.join('\n')}`);
|
|
824
|
+
}
|
|
825
|
+
if (index === start) {
|
|
826
|
+
const range = covering.block.covers <= 1
|
|
827
|
+
? `section ${start + 1}`
|
|
828
|
+
: `sections ${start + 1}-${start + covering.block.covers}`;
|
|
829
|
+
lines.push(`\n### assistant\n## Condensed (condensed from ${range})\n- ${covering.block.text}`);
|
|
830
|
+
}
|
|
831
|
+
return lines.join('\n');
|
|
832
|
+
}
|
|
833
|
+
for (const [turnIndex, turn] of section.turns.entries()) {
|
|
735
834
|
if (turn.user.length > 0)
|
|
736
835
|
lines.push(`\n## user\n${turn.user.join('\n')}`);
|
|
737
836
|
// An extraction whose every field is empty renders nothing: a heading followed by
|
|
738
837
|
// no body reads as a turn that did something but says nothing.
|
|
739
|
-
if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted).length > 0) {
|
|
740
|
-
|
|
741
|
-
if (capChars !== undefined && block.length > capChars) {
|
|
742
|
-
block = `${block.slice(0, capChars)}\n…(+${block.length - capChars} chars)`;
|
|
743
|
-
}
|
|
838
|
+
if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted, level).length > 0) {
|
|
839
|
+
const block = renderExtractionBlock(turn.extracted, level);
|
|
744
840
|
// The trailer goes *above* the block, not below it. `## Asked` is the block's
|
|
745
841
|
// last section and the user's reply is the very next line, so an errors line
|
|
746
842
|
// in between would separate the reply from the question it answers.
|
|
@@ -754,10 +850,7 @@ function renderSection(section, capChars) {
|
|
|
754
850
|
lines.push(`### assistant\n${body}`);
|
|
755
851
|
}
|
|
756
852
|
else {
|
|
757
|
-
|
|
758
|
-
if (capChars !== undefined && body.length > capChars) {
|
|
759
|
-
body = `${body.slice(0, capChars)}\n…(+${body.length - capChars} chars)`;
|
|
760
|
-
}
|
|
853
|
+
const body = turn.assistant.join('\n');
|
|
761
854
|
if (body.length > 0)
|
|
762
855
|
lines.push(`### assistant\n${body}`);
|
|
763
856
|
if (turn.errors.length > 0) {
|
|
@@ -769,56 +862,45 @@ function renderSection(section, capChars) {
|
|
|
769
862
|
}
|
|
770
863
|
return lines.join('\n');
|
|
771
864
|
}
|
|
772
|
-
/**
|
|
773
|
-
* Total characters of turn bodies across every section: the extraction where a
|
|
774
|
-
* turn has one, its prose otherwise.
|
|
775
|
-
*
|
|
776
|
-
* Both must count, because the cap applies to whichever body is rendered. When
|
|
777
|
-
* only prose counted, a digest made almost entirely of extractions reported a
|
|
778
|
-
* bound of zero, the bisection had nothing to shrink, and the renderer fell
|
|
779
|
-
* through to dropping the oldest turns outright — which deleted the earliest
|
|
780
|
-
* human messages, the standing constraints the digest exists to keep.
|
|
781
|
-
*/
|
|
782
|
-
function assistantChars(sections) {
|
|
783
|
-
let total = 0;
|
|
784
|
-
for (const section of sections) {
|
|
785
|
-
for (const turn of section.turns) {
|
|
786
|
-
total += turn.extracted !== undefined
|
|
787
|
-
? renderExtractionBlock(turn.extracted).length
|
|
788
|
-
: turn.assistant.join('\n').length;
|
|
789
|
-
}
|
|
790
|
-
}
|
|
791
|
-
return total;
|
|
792
|
-
}
|
|
793
865
|
/**
|
|
794
866
|
* Render the digest under a hard character budget.
|
|
795
867
|
*
|
|
796
|
-
*
|
|
868
|
+
* Three tiers, in order:
|
|
797
869
|
*
|
|
798
870
|
* - **T1** user prose is verbatim unless it alone exceeds `USER_BUDGET_SHARE` of
|
|
799
871
|
* the budget, then the oldest turns are cut first. The share is 0.9 rather than
|
|
800
872
|
* 0.5 because real user prose is a few percent of the digest: at 0.5 the
|
|
801
873
|
* extracted blocks crowded out the oldest human messages, which are exactly the
|
|
802
874
|
* standing constraints (「请用pixi管理开发环境」) that must survive.
|
|
803
|
-
* - **T1'**
|
|
804
|
-
*
|
|
875
|
+
* - **T1'** the graded ladder: each block drops Overturned, then Concluded, then
|
|
876
|
+
* Did, while Asked survives every level.
|
|
877
|
+
* - **T2** whole turn bodies go, oldest first, when even the surviving sections
|
|
878
|
+
* overflow. The user lines stay; only what the assistant produced is dropped.
|
|
805
879
|
*
|
|
806
880
|
* T1' runs *after* T1 because a user's own words are the least reconstructible
|
|
807
|
-
* thing in the log: an assistant's reply can be inferred from its tool calls
|
|
808
|
-
*
|
|
809
|
-
* exists so a tight budget thins every turn instead of erasing the last few.
|
|
881
|
+
* thing in the log: an assistant's reply can be inferred from its tool calls and
|
|
882
|
+
* the surrounding turns, a user's request cannot.
|
|
810
883
|
*
|
|
811
|
-
*
|
|
884
|
+
* All three tiers run on a long session, and that is by design: the ceiling is
|
|
812
885
|
* absolute (`DIGEST_TOKEN_CEILING`), so a 122-turn history with 316k characters
|
|
813
886
|
* of assistant prose cannot fit verbatim. In the extractive design most turns
|
|
814
887
|
* carry an extraction instead of prose, which keeps the digest far below the
|
|
815
888
|
* ceiling; the tiers exist for the turns where extraction was unavailable and
|
|
816
889
|
* the prose is all that remains.
|
|
890
|
+
*
|
|
891
|
+
* When `condensed` is supplied the tiers are skipped and the digest is returned
|
|
892
|
+
* whole. That path is entered only by `condenseOldest`, which owns the overflow:
|
|
893
|
+
* degrading here would report "fits" at a level that has already dropped the
|
|
894
|
+
* sections the fold was meant to preserve, and the fold loop would stop early
|
|
895
|
+
* having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
|
|
896
|
+
* bodies, leaving only `## Asked`, before condensation ever got a chance.
|
|
817
897
|
*/
|
|
818
|
-
export function renderDigest(events, budgetTokens, extracted) {
|
|
898
|
+
export function renderDigest(events, budgetTokens, extracted, condensed) {
|
|
819
899
|
const sections = extracted === undefined ? buildSections(events) : withExtractions(buildSections(events), extracted);
|
|
820
900
|
const budgetChars = Math.max(0, budgetTokens * 4);
|
|
821
|
-
const render = (
|
|
901
|
+
const render = (trimmed, level = 3) => (trimmed ?? sections)
|
|
902
|
+
.map((section, index) => renderSection(section, level, condensed, index))
|
|
903
|
+
.join('\n');
|
|
822
904
|
// User prose is reserved before anything else is placed.
|
|
823
905
|
//
|
|
824
906
|
// Measured on a 122-turn session: every human message in the span totalled 469
|
|
@@ -828,7 +910,7 @@ export function renderDigest(events, budgetTokens, extracted) {
|
|
|
828
910
|
// standing constraints (「请用pixi管理开发环境」) that never expire, while the
|
|
829
911
|
// extraction describes work that is already finished.
|
|
830
912
|
const userReserve = Math.min(Math.floor(budgetChars * USER_BUDGET_SHARE), sections.reduce((total, section) => total + section.turns.reduce((sum, turn) => sum + turn.user.join('\n').length, 0), 0));
|
|
831
|
-
const verbatim = render(
|
|
913
|
+
const verbatim = render();
|
|
832
914
|
if (verbatim.length <= budgetChars)
|
|
833
915
|
return verbatim;
|
|
834
916
|
// T1: user prose over its share, oldest first. Only the user side changes, so
|
|
@@ -856,43 +938,139 @@ export function renderDigest(events, budgetTokens, extracted) {
|
|
|
856
938
|
}
|
|
857
939
|
}
|
|
858
940
|
}
|
|
859
|
-
const afterT1 = render(
|
|
941
|
+
const afterT1 = render(t1);
|
|
860
942
|
if (afterT1.length <= budgetChars)
|
|
861
943
|
return afterT1;
|
|
862
944
|
// The user side fits inside its reserve; what overflows is the turn bodies
|
|
863
945
|
// (extraction or prose plus pointers). Thin those, and only drop whole turns
|
|
864
946
|
// once every body is already at zero — dropping a turn also drops the user
|
|
865
947
|
// prose in it, which is what the reserve exists to prevent.
|
|
866
|
-
// T1':
|
|
867
|
-
//
|
|
868
|
-
//
|
|
869
|
-
//
|
|
948
|
+
// T1': the graded ladder. Each level drops one section from every block —
|
|
949
|
+
// Overturned first, then Concluded, then Did — and Asked survives all of them.
|
|
950
|
+
//
|
|
951
|
+
// This replaces a character cap applied to each block. That cap sliced every
|
|
952
|
+
// extraction at the same offset, and because Asked is the block's last section
|
|
953
|
+
// it was the first thing eaten: at 490 turns each question rendered as ` 1.`
|
|
954
|
+
// with its options gone, and by 520 both Asked and Overturned were absent from
|
|
955
|
+
// every block. A half-line reads as data, so slicing loses more than dropping:
|
|
956
|
+
// the reader cannot tell a truncated fact from a short one.
|
|
957
|
+
//
|
|
958
|
+
// Asked outranks everything because it is the only section nothing later can
|
|
959
|
+
// rebuild. Did and Concluded describe work whose results are still in the
|
|
960
|
+
// working tree; the question and the options the user chose between exist only
|
|
961
|
+
// in this line.
|
|
962
|
+
//
|
|
963
|
+
// No character cap at any level: a block either renders whole or loses a whole
|
|
964
|
+
// section. Slicing was the original mechanism and it cut Asked's options off
|
|
965
|
+
// mid-list, which reads as data rather than as truncation.
|
|
966
|
+
//
|
|
967
|
+
// The ladder only runs when no condensation was supplied. A condensed digest
|
|
968
|
+
// that still overflows is the caller's problem to fix by folding more turns:
|
|
969
|
+
// degrading it here would report "fits" at a level that has already dropped the
|
|
970
|
+
// sections the fold was meant to preserve, and the fold loop would stop early
|
|
971
|
+
// having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
|
|
972
|
+
// bodies, leaving only `## Asked`, before condensation ever got a chance.
|
|
973
|
+
if (condensed !== undefined && condensed.size > 0) {
|
|
974
|
+
// Returned whole even when it still overflows. The caller folds more turns and
|
|
975
|
+
// asks again; slicing here would cut the last block mid-line, which is the
|
|
976
|
+
// failure this whole path exists to remove.
|
|
977
|
+
return render(t1, 3);
|
|
978
|
+
}
|
|
979
|
+
for (let level = 3; level >= 0; level -= 1) {
|
|
980
|
+
const whole = render(t1, level);
|
|
981
|
+
if (whole.length <= budgetChars)
|
|
982
|
+
return whole;
|
|
983
|
+
}
|
|
984
|
+
// Every level overflowed with prose already at zero, so the user lines plus the
|
|
985
|
+
// surviving Asked sections alone exceed the budget. Drop the oldest turn
|
|
986
|
+
// *bodies* rather than the oldest sections: a dropped section takes the user's
|
|
987
|
+
// request with it, and those requests are standing constraints ("请用pixi管理
|
|
988
|
+
// 开发环境") that never expire, while a body describes work already superseded.
|
|
989
|
+
// The newest turns are the ones the next request depends on, so the cut runs
|
|
990
|
+
// from the oldest end.
|
|
991
|
+
const positions = [];
|
|
992
|
+
for (const [section, { turns }] of t1.entries()) {
|
|
993
|
+
for (let turn = 0; turn < turns.length; turn += 1)
|
|
994
|
+
positions.push({ section, turn });
|
|
995
|
+
}
|
|
996
|
+
const withoutBodies = (count) => {
|
|
997
|
+
const trimmed = t1.map((section) => ({ turns: section.turns.map((turn) => ({ ...turn })) }));
|
|
998
|
+
for (const { section, turn } of positions.slice(0, count)) {
|
|
999
|
+
const target = trimmed[section]?.turns[turn];
|
|
1000
|
+
if (target === undefined)
|
|
1001
|
+
continue;
|
|
1002
|
+
// The user line stays; only what the assistant produced goes. `delete`
|
|
1003
|
+
// rather than assigning undefined: `exactOptionalPropertyTypes` treats the
|
|
1004
|
+
// key's absence and its undefined value as different types.
|
|
1005
|
+
delete target.extracted;
|
|
1006
|
+
target.assistant = [];
|
|
1007
|
+
target.errors = [];
|
|
1008
|
+
target.writes = [];
|
|
1009
|
+
}
|
|
1010
|
+
return trimmed;
|
|
1011
|
+
};
|
|
1012
|
+
// Lower bound on the drop count: the smallest number that fits. `Math.floor`
|
|
1013
|
+
// rather than `ceil` is load-bearing — with `ceil`, `mid` equals `high` once the
|
|
1014
|
+
// range narrows to two entries, so a fitting `mid` left `high` unchanged and the
|
|
1015
|
+
// loop never terminated. A 2200-turn digest hung here; 2100 happened to converge.
|
|
870
1016
|
let low = 0;
|
|
871
|
-
let high =
|
|
1017
|
+
let high = positions.length;
|
|
872
1018
|
while (low < high) {
|
|
873
|
-
const mid = Math.
|
|
874
|
-
|
|
875
|
-
|
|
1019
|
+
const mid = Math.floor((low + high) / 2);
|
|
1020
|
+
const marker = mid === 0 ? '' : `…(${mid} oldest turn bodies dropped: over budget)\n`;
|
|
1021
|
+
if (marker.length + render(withoutBodies(mid), 0).length <= budgetChars)
|
|
1022
|
+
high = mid;
|
|
876
1023
|
else
|
|
877
|
-
|
|
1024
|
+
low = mid + 1;
|
|
878
1025
|
}
|
|
879
|
-
const
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
//
|
|
884
|
-
//
|
|
1026
|
+
const marker = low === 0 ? '' : `…(${low} oldest turn bodies dropped: over budget)\n`;
|
|
1027
|
+
const stripped = render(withoutBodies(low), 0);
|
|
1028
|
+
if (marker.length + stripped.length <= budgetChars)
|
|
1029
|
+
return `${marker}${stripped}`;
|
|
1030
|
+
// Even with every body gone the user lines alone overflow — a budget smaller
|
|
1031
|
+
// than the requests it must hold. Only here do whole sections go, oldest first:
|
|
1032
|
+
// slicing the tail instead would cut the newest turns, which are exactly the
|
|
1033
|
+
// ones the next request depends on.
|
|
1034
|
+
// Still over budget with every body gone. Drop whole turns from the oldest end
|
|
1035
|
+
// — a dropped turn takes its user line with it, which is the price of a budget
|
|
1036
|
+
// too small to hold the requests themselves. The newest turn is never dropped,
|
|
1037
|
+
// and the walk keeps every turn after the cut point rather than only the last
|
|
1038
|
+
// one: a `goal` round records its objective as a user message and can sit after
|
|
1039
|
+
// the newest request, so keeping just `slice(-1)` kept the goal and lost the
|
|
1040
|
+
// request.
|
|
1041
|
+
// The cut never passes the last turn carrying a user request. Without this the
|
|
1042
|
+
// walk reached the very end — the fixture's `goal` round is the last position,
|
|
1043
|
+
// so dropping up to it kept the goal and lost `USER-13`, the newest request.
|
|
1044
|
+
const turnAt = (position) => position === undefined ? undefined : t1[position.section]?.turns[position.turn];
|
|
1045
|
+
let lastRequest = positions.length - 1;
|
|
1046
|
+
while (lastRequest > 0 && turnAt(positions[lastRequest])?.fromRequest !== true)
|
|
1047
|
+
lastRequest -= 1;
|
|
885
1048
|
let first = 0;
|
|
886
|
-
|
|
887
|
-
while (first < t1.length - 1) {
|
|
888
|
-
dropped += 1;
|
|
1049
|
+
while (first < lastRequest) {
|
|
889
1050
|
first += 1;
|
|
890
|
-
const
|
|
891
|
-
|
|
1051
|
+
const cut = positions[first];
|
|
1052
|
+
if (cut === undefined)
|
|
1053
|
+
break;
|
|
1054
|
+
const kept = t1
|
|
1055
|
+
.map((section, sectionIndex) => ({
|
|
1056
|
+
turns: section.turns.filter((_, turnIndex) => sectionIndex > cut.section || (sectionIndex === cut.section && turnIndex >= cut.turn)),
|
|
1057
|
+
}))
|
|
1058
|
+
.filter((section) => section.turns.length > 0);
|
|
1059
|
+
const rest = render(kept, 0);
|
|
1060
|
+
const text = `…(${first} earlier turn(s) dropped: over budget)\n${rest}`;
|
|
892
1061
|
if (text.length <= budgetChars)
|
|
893
1062
|
return text;
|
|
894
1063
|
}
|
|
895
|
-
|
|
1064
|
+
// Nothing fit, so keep the one turn the next request depends on: the newest one
|
|
1065
|
+
// carrying a user request, not the last position in the log.
|
|
1066
|
+
// Only the user line: the budget cannot even hold one full turn, and the request
|
|
1067
|
+
// is the part the next turn is answering.
|
|
1068
|
+
const keeperTurn = turnAt(positions[lastRequest]);
|
|
1069
|
+
if (keeperTurn === undefined)
|
|
1070
|
+
return '';
|
|
1071
|
+
const bare = { ...keeperTurn, assistant: [], errors: [], writes: [] };
|
|
1072
|
+
delete bare.extracted;
|
|
1073
|
+
return render([{ turns: [bare] }], 0);
|
|
896
1074
|
}
|
|
897
1075
|
/**
|
|
898
1076
|
* The surface seqs this compaction shadows, recovered from the summarization
|
|
@@ -999,6 +1177,66 @@ export function buildExtractionMaterial(turn, prose) {
|
|
|
999
1177
|
* @param signal - cancellation forwarded to the adapter.
|
|
1000
1178
|
* @returns the extracted blocks by slot key; empty when extraction is unavailable.
|
|
1001
1179
|
*/
|
|
1180
|
+
/**
|
|
1181
|
+
* One condensation request: fold a run of already-finished turns into a paragraph.
|
|
1182
|
+
*
|
|
1183
|
+
* Module-level and shaped like `extractOnce` rather than a method, so both calls
|
|
1184
|
+
* derive their route and reasoning effort the same way.
|
|
1185
|
+
*
|
|
1186
|
+
* @param ctx - plugin context carrying the `llm` service and a logger.
|
|
1187
|
+
* @param agent - owner of the session being compacted.
|
|
1188
|
+
* @param material - the rendered blocks being folded.
|
|
1189
|
+
* @param signal - cancellation forwarded to the adapter.
|
|
1190
|
+
* @returns the folded paragraph, or undefined when the call produced nothing.
|
|
1191
|
+
*/
|
|
1192
|
+
async function condenseOnce(ctx, agent, material, signal) {
|
|
1193
|
+
const llm = ctx.llm;
|
|
1194
|
+
if (llm === undefined) {
|
|
1195
|
+
ctx.logger?.warn('verbatim-compaction: no llm service, condensation skipped');
|
|
1196
|
+
return undefined;
|
|
1197
|
+
}
|
|
1198
|
+
const route = agent.session.requestHeader()?.config;
|
|
1199
|
+
const provider = route?.provider ?? agent.options.provider;
|
|
1200
|
+
const model = route?.model ?? agent.options.model;
|
|
1201
|
+
if (provider === undefined || model === undefined) {
|
|
1202
|
+
ctx.logger?.warn('verbatim-compaction: no route for condensation, skipped');
|
|
1203
|
+
return undefined;
|
|
1204
|
+
}
|
|
1205
|
+
const info = await Promise.resolve()
|
|
1206
|
+
.then(() => llm.resolveModelInfo?.(provider, model, signal))
|
|
1207
|
+
.catch(() => undefined);
|
|
1208
|
+
const cheapest = cheapestEffort(info?.reasoning?.efforts);
|
|
1209
|
+
const chunks = [];
|
|
1210
|
+
try {
|
|
1211
|
+
const stream = llm.stream({
|
|
1212
|
+
provider,
|
|
1213
|
+
model,
|
|
1214
|
+
messages: [{ role: 'user', content: [{ type: 'text', text: `${material}\n\n${CONDENSE_INSTRUCTION}` }] }],
|
|
1215
|
+
maxTokens: CONDENSE_TOKENS,
|
|
1216
|
+
sessionId: agent.session.id,
|
|
1217
|
+
purpose: 'compaction',
|
|
1218
|
+
...(cheapest === undefined ? {} : { reasoningEffort: cheapest }),
|
|
1219
|
+
...(signal === undefined ? {} : { signal }),
|
|
1220
|
+
});
|
|
1221
|
+
for await (const chunk of stream) {
|
|
1222
|
+
const delta = chunk;
|
|
1223
|
+
if (delta.type === 'text-delta' && typeof delta.text === 'string')
|
|
1224
|
+
chunks.push(delta.text);
|
|
1225
|
+
}
|
|
1226
|
+
}
|
|
1227
|
+
catch (error) {
|
|
1228
|
+
ctx.logger?.warn(`verbatim-compaction: condensation call failed: ${String(error)}`);
|
|
1229
|
+
return undefined;
|
|
1230
|
+
}
|
|
1231
|
+
const text = chunks.join('').trim();
|
|
1232
|
+
if (text.length === 0) {
|
|
1233
|
+
// Silence here is what makes "the digest stopped folding" invisible at runtime:
|
|
1234
|
+
// the summary still renders, just without the room the fold would have bought.
|
|
1235
|
+
ctx.logger?.warn(`verbatim-compaction: condensation returned no text for ${material.length} chars of material`);
|
|
1236
|
+
return undefined;
|
|
1237
|
+
}
|
|
1238
|
+
return text;
|
|
1239
|
+
}
|
|
1002
1240
|
async function extractBatch(ctx, agent, batch, signal) {
|
|
1003
1241
|
const out = new Map();
|
|
1004
1242
|
if (batch.length === 0)
|
|
@@ -1149,7 +1387,7 @@ async function extractOnce(ctx, agent, batch, signal) {
|
|
|
1149
1387
|
return { blocks: parseExtraction(answer), truncated };
|
|
1150
1388
|
}
|
|
1151
1389
|
/**
|
|
1152
|
-
*
|
|
1390
|
+
* Extractive compaction backend: verbatim user prose, one model call per batch,
|
|
1153
1391
|
* call.
|
|
1154
1392
|
*
|
|
1155
1393
|
* Everything except `summarize()` is inherited. The base class prices pressure,
|
|
@@ -1175,6 +1413,14 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1175
1413
|
* the same behaviour as before this cache existed.
|
|
1176
1414
|
*/
|
|
1177
1415
|
extractionCache = new Map();
|
|
1416
|
+
/**
|
|
1417
|
+
* Folded text, keyed by provider, model and a hash of the material folded.
|
|
1418
|
+
*
|
|
1419
|
+
* Same reasoning as `extractionCache`: the fold is a model call over material
|
|
1420
|
+
* rebuilt from the raw log on every compaction, so the same run of old turns is
|
|
1421
|
+
* re-folded on every later compaction unless it is remembered.
|
|
1422
|
+
*/
|
|
1423
|
+
condensedCache = new Map();
|
|
1178
1424
|
/**
|
|
1179
1425
|
* Build the replacement checkpoint content from the session log.
|
|
1180
1426
|
*
|
|
@@ -1187,10 +1433,10 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1187
1433
|
*
|
|
1188
1434
|
* @param input - replayed conversation prefix the base class is shadowing.
|
|
1189
1435
|
* @param agent - owner of the session being compacted.
|
|
1190
|
-
* @param
|
|
1436
|
+
* @param signal - cancellation forwarded to the extraction and fold calls.
|
|
1191
1437
|
* @returns text summary blocks, unmarked by any LLM call.
|
|
1192
1438
|
*/
|
|
1193
|
-
async summarize(input, agent,
|
|
1439
|
+
async summarize(input, agent, signal) {
|
|
1194
1440
|
const session = agent.session;
|
|
1195
1441
|
const shadowed = shadowedSeqs(session, input);
|
|
1196
1442
|
const shadowedSet = new Set(shadowed);
|
|
@@ -1205,8 +1451,24 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1205
1451
|
// size independent of history length; the guard bound only exists for the
|
|
1206
1452
|
// degenerate case of a span smaller than the ceiling.
|
|
1207
1453
|
const budget = Math.max(0, Math.min(DIGEST_TOKEN_CEILING, shadowedPrice - FRAME_TOKENS - SHRINK_MARGIN_TOKENS));
|
|
1208
|
-
const extracted = await this.extractAll(source, agent,
|
|
1209
|
-
|
|
1454
|
+
const extracted = await this.extractAll(source, agent, signal);
|
|
1455
|
+
// Fold the oldest turns up only when the plain digest overflows. The fold is an
|
|
1456
|
+
// LLM call, so a digest that already fits must not pay for one.
|
|
1457
|
+
let condensed;
|
|
1458
|
+
if (renderDigest(source, budget, extracted).length > budget * 4) {
|
|
1459
|
+
condensed = await this.condenseOldest(source, extracted, agent, budget, signal);
|
|
1460
|
+
}
|
|
1461
|
+
// The fold path returns its digest whole, so it can still overflow when every
|
|
1462
|
+
// group has been folded and the user lines alone are too long. The budget is a
|
|
1463
|
+
// contract the host's shrink guard depends on, so that case falls back to the
|
|
1464
|
+
// ladder: a degraded digest beats an over-budget one. The fold is the better
|
|
1465
|
+
// outcome, not the only permitted one.
|
|
1466
|
+
let text = renderDigest(source, budget, extracted, condensed);
|
|
1467
|
+
if (text.length > budget * 4) {
|
|
1468
|
+
this.ctx.logger?.warn(`verbatim-compaction: digest still over budget after folding ${condensed?.size ?? 0} group(s) `
|
|
1469
|
+
+ `(${text.length} > ${budget * 4} chars), falling back to the graded ladder`);
|
|
1470
|
+
text = renderDigest(source, budget, extracted);
|
|
1471
|
+
}
|
|
1210
1472
|
const route = session.requestHeader()?.config;
|
|
1211
1473
|
return {
|
|
1212
1474
|
summary: [{ type: 'text', text }],
|
|
@@ -1214,6 +1476,104 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
1214
1476
|
model: route?.model ?? agent.options.model ?? 'digest',
|
|
1215
1477
|
};
|
|
1216
1478
|
}
|
|
1479
|
+
/**
|
|
1480
|
+
* Fold the oldest turns into condensed blocks until the digest fits.
|
|
1481
|
+
*
|
|
1482
|
+
* Only reached when the plain digest overflows `budget`. The oldest turns are
|
|
1483
|
+
* the right ones to fold: they describe work already superseded, while the
|
|
1484
|
+
* newest are what the next request depends on.
|
|
1485
|
+
*
|
|
1486
|
+
* Linear in groups, not bisected: a fold is not monotone in how much is folded —
|
|
1487
|
+
* a paragraph's length depends on what the model chose to keep — so there is no
|
|
1488
|
+
* boundary to bisect. The walk stops at the first size that fits, which is the
|
|
1489
|
+
* fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
|
|
1490
|
+
* consecutive sections, so the number of calls is proportional to the digest,
|
|
1491
|
+
* not to the number of turns.
|
|
1492
|
+
*
|
|
1493
|
+
* Cached by content, like the extraction: the same prefix of turns folds to the
|
|
1494
|
+
* same text, and a later compaction re-reads the same history.
|
|
1495
|
+
*
|
|
1496
|
+
* @param source - digest source events, in log order.
|
|
1497
|
+
* @param extracted - per-turn extractions already computed.
|
|
1498
|
+
* @param agent - owner of the session being compacted.
|
|
1499
|
+
* @param budget - token budget the digest must fit.
|
|
1500
|
+
* @param signal - cancellation forwarded to every call.
|
|
1501
|
+
* @returns condensed blocks keyed by the `turnKey` of the first covered section.
|
|
1502
|
+
*/
|
|
1503
|
+
async condenseOldest(source, extracted, agent, budget, signal) {
|
|
1504
|
+
const sections = withExtractions(buildSections(source), extracted);
|
|
1505
|
+
const budgetChars = budget * 4;
|
|
1506
|
+
const out = new Map();
|
|
1507
|
+
// One group per iteration, oldest first, checking after each whether the digest
|
|
1508
|
+
// fits. Single loop, `start` monotone: the earlier two-level form advanced its
|
|
1509
|
+
// inner start from `out.size`, so a group whose call failed was retried on every
|
|
1510
|
+
// outer pass (45 calls instead of 4 with the model down), and the outer bound
|
|
1511
|
+
// `covered < sections.length` stopped one group short of the end — at 700
|
|
1512
|
+
// sections the last 100 were never folded, and at 100 or fewer the loop body
|
|
1513
|
+
// never ran at all.
|
|
1514
|
+
for (const start of foldGroupStarts(sections.length)) {
|
|
1515
|
+
if (signal?.aborted === true)
|
|
1516
|
+
break;
|
|
1517
|
+
const group = sections.slice(start, start + CONDENSE_GROUP);
|
|
1518
|
+
if (group.length === 0)
|
|
1519
|
+
continue;
|
|
1520
|
+
const text = await this.condenseGroup(group, agent, signal);
|
|
1521
|
+
// A failed group is skipped rather than retried: the next group still buys
|
|
1522
|
+
// room, and retrying the same material against a failing model only spends
|
|
1523
|
+
// calls. The remaining turns keep their own blocks either way.
|
|
1524
|
+
if (text === undefined)
|
|
1525
|
+
continue;
|
|
1526
|
+
out.set(turnKey(start, 0), { text, covers: group.length });
|
|
1527
|
+
if (renderDigest(source, budget, extracted, out).length <= budgetChars)
|
|
1528
|
+
return out;
|
|
1529
|
+
}
|
|
1530
|
+
return out;
|
|
1531
|
+
}
|
|
1532
|
+
/**
|
|
1533
|
+
* Hand one group of turns to the model and return its folded text.
|
|
1534
|
+
*
|
|
1535
|
+
* @param group - consecutive sections to fold into one paragraph.
|
|
1536
|
+
* @param agent - owner of the session being compacted.
|
|
1537
|
+
* @param signal - cancellation forwarded to the call.
|
|
1538
|
+
* @returns the folded paragraph, or undefined when the call produced nothing.
|
|
1539
|
+
*/
|
|
1540
|
+
async condenseGroup(group, agent, signal) {
|
|
1541
|
+
// Both sources, because a turn has one or the other: extraction succeeds and
|
|
1542
|
+
// the block replaces the prose, or it fails and the verbatim prose is what the
|
|
1543
|
+
// digest shows. Reading only `extracted` meant a run of turns whose extraction
|
|
1544
|
+
// failed contributed nothing — and because the fold then still replaced them,
|
|
1545
|
+
// their content vanished from the digest entirely rather than merely being
|
|
1546
|
+
// summarised badly.
|
|
1547
|
+
const material = group
|
|
1548
|
+
.map((section) => section.turns
|
|
1549
|
+
.map((turn) => {
|
|
1550
|
+
const block = renderExtractionBlock(turn.extracted);
|
|
1551
|
+
return block.length > 0 ? block : turn.assistant.join('\n');
|
|
1552
|
+
})
|
|
1553
|
+
.filter((block) => block.length > 0)
|
|
1554
|
+
.join('\n'))
|
|
1555
|
+
.filter((block) => block.length > 0)
|
|
1556
|
+
.join('\n\n');
|
|
1557
|
+
if (material.length === 0)
|
|
1558
|
+
return undefined;
|
|
1559
|
+
const llm = this.ctx.llm;
|
|
1560
|
+
if (llm === undefined)
|
|
1561
|
+
return undefined;
|
|
1562
|
+
const route = agent.session.requestHeader()?.config;
|
|
1563
|
+
const provider = route?.provider ?? agent.options.provider;
|
|
1564
|
+
const model = route?.model ?? agent.options.model;
|
|
1565
|
+
if (provider === undefined || model === undefined)
|
|
1566
|
+
return undefined;
|
|
1567
|
+
const key = `${provider}:${model}:${hashText(material)}`;
|
|
1568
|
+
const cached = this.condensedCache.get(key);
|
|
1569
|
+
if (cached !== undefined)
|
|
1570
|
+
return cached;
|
|
1571
|
+
const text = await condenseOnce(this.ctx, agent, material, signal);
|
|
1572
|
+
if (text === undefined)
|
|
1573
|
+
return undefined;
|
|
1574
|
+
this.condensedCache.set(key, text);
|
|
1575
|
+
return text;
|
|
1576
|
+
}
|
|
1217
1577
|
/**
|
|
1218
1578
|
* Run the extraction for every turn in the digest source.
|
|
1219
1579
|
*
|
package/lib/types/index.d.ts
CHANGED
|
@@ -15,7 +15,7 @@
|
|
|
15
15
|
* This backend keeps the base class's replay, range selection, durable
|
|
16
16
|
* transaction and shrink guard untouched and overrides only `summarize()`, the
|
|
17
17
|
* one hook the base class documents for exactly this purpose. The replacement
|
|
18
|
-
* summary is built
|
|
18
|
+
* summary is built from the log, with one model call per batch of turns:
|
|
19
19
|
*
|
|
20
20
|
* - user and assistant prose verbatim, per turn;
|
|
21
21
|
* - tool results reduced to one line (tool names, call counts, bytes);
|
|
@@ -135,7 +135,43 @@ export declare function parseExtraction(answer: string): Map<string, Extraction>
|
|
|
135
135
|
* @returns markdown with a heading per non-empty field; empty string when every
|
|
136
136
|
* field is empty.
|
|
137
137
|
*/
|
|
138
|
-
export declare function renderExtractionBlock(extraction: Extraction | undefined): string;
|
|
138
|
+
export declare function renderExtractionBlock(extraction: Extraction | undefined, level?: number): string;
|
|
139
|
+
/**
|
|
140
|
+
* The group starts a fold walk visits, oldest first, one entry per group.
|
|
141
|
+
*
|
|
142
|
+
* Extracted so the walk's bounds are testable without a session, a logger and a
|
|
143
|
+
* model: the walk itself was where two defects lived — a bound that skipped the
|
|
144
|
+
* last group, and a start advanced from the success count, which retried a failed
|
|
145
|
+
* group on every pass.
|
|
146
|
+
*
|
|
147
|
+
* @param sectionCount - how many sections the digest has.
|
|
148
|
+
* @returns the start index of each group, in order.
|
|
149
|
+
*/
|
|
150
|
+
export declare function foldGroupStarts(sectionCount: number): number[];
|
|
151
|
+
/**
|
|
152
|
+
* A folded-up summary of a run of consecutive sections, keyed by the `turnKey` of
|
|
153
|
+
* the first section it covers. The key's second component is always 0: a fold
|
|
154
|
+
* starts at a section boundary, never mid-section.
|
|
155
|
+
*
|
|
156
|
+
* Produced when the plain digest overflows: the oldest turns are handed to the
|
|
157
|
+
* model together and replaced by one paragraph. Deleting those turns instead —
|
|
158
|
+
* what the budget walk used to do — loses what they established, while folding
|
|
159
|
+
* keeps a statement of it in a fraction of the room.
|
|
160
|
+
*/
|
|
161
|
+
export interface Condensed {
|
|
162
|
+
/** The folded text, already in the digest's own wording. */
|
|
163
|
+
text: string;
|
|
164
|
+
/**
|
|
165
|
+
* How many sections this block stands in for, counting from the key's own
|
|
166
|
+
* section.
|
|
167
|
+
*
|
|
168
|
+
* Sections, not turns: `buildSections` opens one section per user request, so a
|
|
169
|
+
* run of consecutive requests is a run of consecutive sections. Counting turns
|
|
170
|
+
* would cover only the first section and leave the rest rendering their own
|
|
171
|
+
* blocks — the fold bought nothing.
|
|
172
|
+
*/
|
|
173
|
+
covers: number;
|
|
174
|
+
}
|
|
139
175
|
/**
|
|
140
176
|
* Build the compact per-turn trace fed to the summarizer.
|
|
141
177
|
*
|
|
@@ -155,6 +191,15 @@ export declare function collectHints(events: readonly SessionEvent[]): string;
|
|
|
155
191
|
/** One turn's accumulated digest material. */
|
|
156
192
|
interface Turn {
|
|
157
193
|
turn: number | undefined;
|
|
194
|
+
/**
|
|
195
|
+
* True when a human request opened this turn, false when a `goal` objective did.
|
|
196
|
+
*
|
|
197
|
+
* Both fill the `user` slot, so `user.length > 0` cannot tell them apart — and
|
|
198
|
+
* the difference decides which turn is kept when the budget is too small to
|
|
199
|
+
* hold the digest: dropping the newest human request loses what the next turn
|
|
200
|
+
* is answering, while dropping a goal round only loses a restated objective.
|
|
201
|
+
*/
|
|
202
|
+
fromRequest: boolean;
|
|
158
203
|
user: string[];
|
|
159
204
|
assistant: string[];
|
|
160
205
|
tools: Map<string, number>;
|
|
@@ -190,29 +235,37 @@ export declare function buildSections(events: readonly SessionEvent[]): Section[
|
|
|
190
235
|
/**
|
|
191
236
|
* Render the digest under a hard character budget.
|
|
192
237
|
*
|
|
193
|
-
*
|
|
238
|
+
* Three tiers, in order:
|
|
194
239
|
*
|
|
195
240
|
* - **T1** user prose is verbatim unless it alone exceeds `USER_BUDGET_SHARE` of
|
|
196
241
|
* the budget, then the oldest turns are cut first. The share is 0.9 rather than
|
|
197
242
|
* 0.5 because real user prose is a few percent of the digest: at 0.5 the
|
|
198
243
|
* extracted blocks crowded out the oldest human messages, which are exactly the
|
|
199
244
|
* standing constraints (「请用pixi管理开发环境」) that must survive.
|
|
200
|
-
* - **T1'**
|
|
201
|
-
*
|
|
245
|
+
* - **T1'** the graded ladder: each block drops Overturned, then Concluded, then
|
|
246
|
+
* Did, while Asked survives every level.
|
|
247
|
+
* - **T2** whole turn bodies go, oldest first, when even the surviving sections
|
|
248
|
+
* overflow. The user lines stay; only what the assistant produced is dropped.
|
|
202
249
|
*
|
|
203
250
|
* T1' runs *after* T1 because a user's own words are the least reconstructible
|
|
204
|
-
* thing in the log: an assistant's reply can be inferred from its tool calls
|
|
205
|
-
*
|
|
206
|
-
* exists so a tight budget thins every turn instead of erasing the last few.
|
|
251
|
+
* thing in the log: an assistant's reply can be inferred from its tool calls and
|
|
252
|
+
* the surrounding turns, a user's request cannot.
|
|
207
253
|
*
|
|
208
|
-
*
|
|
254
|
+
* All three tiers run on a long session, and that is by design: the ceiling is
|
|
209
255
|
* absolute (`DIGEST_TOKEN_CEILING`), so a 122-turn history with 316k characters
|
|
210
256
|
* of assistant prose cannot fit verbatim. In the extractive design most turns
|
|
211
257
|
* carry an extraction instead of prose, which keeps the digest far below the
|
|
212
258
|
* ceiling; the tiers exist for the turns where extraction was unavailable and
|
|
213
259
|
* the prose is all that remains.
|
|
260
|
+
*
|
|
261
|
+
* When `condensed` is supplied the tiers are skipped and the digest is returned
|
|
262
|
+
* whole. That path is entered only by `condenseOldest`, which owns the overflow:
|
|
263
|
+
* degrading here would report "fits" at a level that has already dropped the
|
|
264
|
+
* sections the fold was meant to preserve, and the fold loop would stop early
|
|
265
|
+
* having bought nothing. Measured at 1200 turns: the ladder dropped 475 turn
|
|
266
|
+
* bodies, leaving only `## Asked`, before condensation ever got a chance.
|
|
214
267
|
*/
|
|
215
|
-
export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, Extraction>): string;
|
|
268
|
+
export declare function renderDigest(events: readonly SessionEvent[], budgetTokens: number, extracted?: ReadonlyMap<string, Extraction>, condensed?: ReadonlyMap<string, Condensed>): string;
|
|
216
269
|
/**
|
|
217
270
|
* The surface seqs this compaction shadows, recovered from the summarization
|
|
218
271
|
* input's message count.
|
|
@@ -261,7 +314,7 @@ export declare function digestSource(session: Session, retainedSeqs: ReadonlySet
|
|
|
261
314
|
*/
|
|
262
315
|
export declare function buildExtractionMaterial(turn: readonly SessionEvent[], prose: string): string;
|
|
263
316
|
/**
|
|
264
|
-
*
|
|
317
|
+
* Extractive compaction backend: verbatim user prose, one model call per batch,
|
|
265
318
|
* call.
|
|
266
319
|
*
|
|
267
320
|
* Everything except `summarize()` is inherited. The base class prices pressure,
|
|
@@ -287,6 +340,14 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
287
340
|
* the same behaviour as before this cache existed.
|
|
288
341
|
*/
|
|
289
342
|
private readonly extractionCache;
|
|
343
|
+
/**
|
|
344
|
+
* Folded text, keyed by provider, model and a hash of the material folded.
|
|
345
|
+
*
|
|
346
|
+
* Same reasoning as `extractionCache`: the fold is a model call over material
|
|
347
|
+
* rebuilt from the raw log on every compaction, so the same run of old turns is
|
|
348
|
+
* re-folded on every later compaction unless it is remembered.
|
|
349
|
+
*/
|
|
350
|
+
private readonly condensedCache;
|
|
290
351
|
/**
|
|
291
352
|
* Build the replacement checkpoint content from the session log.
|
|
292
353
|
*
|
|
@@ -299,10 +360,44 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
|
|
|
299
360
|
*
|
|
300
361
|
* @param input - replayed conversation prefix the base class is shadowing.
|
|
301
362
|
* @param agent - owner of the session being compacted.
|
|
302
|
-
* @param
|
|
363
|
+
* @param signal - cancellation forwarded to the extraction and fold calls.
|
|
303
364
|
* @returns text summary blocks, unmarked by any LLM call.
|
|
304
365
|
*/
|
|
305
|
-
protected summarize(input: SummarizationInput, agent: Agent,
|
|
366
|
+
protected summarize(input: SummarizationInput, agent: Agent, signal?: AbortSignal): Promise<SummaryResult>;
|
|
367
|
+
/**
|
|
368
|
+
* Fold the oldest turns into condensed blocks until the digest fits.
|
|
369
|
+
*
|
|
370
|
+
* Only reached when the plain digest overflows `budget`. The oldest turns are
|
|
371
|
+
* the right ones to fold: they describe work already superseded, while the
|
|
372
|
+
* newest are what the next request depends on.
|
|
373
|
+
*
|
|
374
|
+
* Linear in groups, not bisected: a fold is not monotone in how much is folded —
|
|
375
|
+
* a paragraph's length depends on what the model chose to keep — so there is no
|
|
376
|
+
* boundary to bisect. The walk stops at the first size that fits, which is the
|
|
377
|
+
* fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
|
|
378
|
+
* consecutive sections, so the number of calls is proportional to the digest,
|
|
379
|
+
* not to the number of turns.
|
|
380
|
+
*
|
|
381
|
+
* Cached by content, like the extraction: the same prefix of turns folds to the
|
|
382
|
+
* same text, and a later compaction re-reads the same history.
|
|
383
|
+
*
|
|
384
|
+
* @param source - digest source events, in log order.
|
|
385
|
+
* @param extracted - per-turn extractions already computed.
|
|
386
|
+
* @param agent - owner of the session being compacted.
|
|
387
|
+
* @param budget - token budget the digest must fit.
|
|
388
|
+
* @param signal - cancellation forwarded to every call.
|
|
389
|
+
* @returns condensed blocks keyed by the `turnKey` of the first covered section.
|
|
390
|
+
*/
|
|
391
|
+
private condenseOldest;
|
|
392
|
+
/**
|
|
393
|
+
* Hand one group of turns to the model and return its folded text.
|
|
394
|
+
*
|
|
395
|
+
* @param group - consecutive sections to fold into one paragraph.
|
|
396
|
+
* @param agent - owner of the session being compacted.
|
|
397
|
+
* @param signal - cancellation forwarded to the call.
|
|
398
|
+
* @returns the folded paragraph, or undefined when the call produced nothing.
|
|
399
|
+
*/
|
|
400
|
+
private condenseGroup;
|
|
306
401
|
/**
|
|
307
402
|
* Run the extraction for every turn in the digest source.
|
|
308
403
|
*
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@logictan/dsh-verbatim-compaction",
|
|
3
|
-
"version": "0.12.
|
|
3
|
+
"version": "0.12.1",
|
|
4
4
|
"description": "Deterministic compaction backend that keeps conversation prose verbatim in the checkpoint instead of re-summarizing it: user and assistant text survive word for word, tool results collapse to one-line pointers, reasoning is never read, and no model call is made.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "lib/index.js",
|