@logictan/dsh-verbatim-compaction 0.13.2 → 0.13.3

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/lib/index.js CHANGED
@@ -30,6 +30,10 @@
30
30
  *
31
31
  * @module @logictan/dsh-verbatim-compaction
32
32
  */
33
+ import { randomBytes } from 'node:crypto';
34
+ import { mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
35
+ import { homedir } from 'node:os';
36
+ import { join } from 'node:path';
33
37
  import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
34
38
  import { ReasoningEffortId } from '@deepseek-ai/dsh-llm';
35
39
  import { getLiveConfig } from './purpose.js';
@@ -77,8 +81,11 @@ export function applyPurposeOverride(options, config, cheapest) {
77
81
  * per turn, and leaves the checkpoint far below any measured threshold.
78
82
  */
79
83
  export const DIGEST_TOKEN_CEILING = 20000;
80
- /** Framing overhead `frameSummary` adds: preamble plus both tags, 341 chars = 86 tokens. */
81
- const FRAME_TOKENS = 86;
84
+ /**
85
+ * Framing overhead `frameSummary` adds under `TokenMeter.estimateMessage`:
86
+ * 3 text blocks (`BLOCK_OVERHEAD = 4` each) + `ROLE_OVERHEAD = 4` + preamble/tags = 102 tokens.
87
+ */
88
+ const FRAME_TOKENS = 102;
82
89
  /** Safety margin below the shrink guard, in tokens. */
83
90
  const SHRINK_MARGIN_TOKENS = 512;
84
91
  /**
@@ -95,6 +102,37 @@ const SHRINK_MARGIN_TOKENS = 512;
95
102
  const USER_BUDGET_SHARE = 0.9;
96
103
  /** Tool names whose call arguments name a written path. */
97
104
  const WRITE_TOOLS = new Set(['write', 'edit', 'multiedit', 'apply_patch']);
105
+ /** Max parallel batch extraction calls in flight per compaction. */
106
+ const EXTRACT_CONCURRENCY = 4;
107
+ /** Default per-call timeout (ms) for extraction and condensation LLM streams. */
108
+ const DEFAULT_LLM_CALL_TIMEOUT_MS = 90_000;
109
+ /** In-memory cache bounds (FIFO/LRU eviction). */
110
+ const EXTRACTION_CACHE_MAX = 2000;
111
+ const CONDENSED_CACHE_MAX = 200;
112
+ /** Max characters kept per turn when extraction fails and prose falls back verbatim. */
113
+ const FALLBACK_PROSE_MAX_CHARS = 3000;
114
+ /** Old (non-latest) user messages longer than this are head+tail clipped to prevent paste bloat. */
115
+ const OLD_USER_PASTE_MAX_CHARS = 2400;
116
+ /** Recent trailing section count whose `## Answers` keep full verbose question stems. */
117
+ const FULL_ANSWER_STEM_RECENT_SECTIONS = 3;
118
+ /** Max characters for historical `## Answers` question stems (user answers always stay verbatim). */
119
+ const OLD_ANSWER_STEM_MAX_CHARS = 180;
120
+ /** Max length of a following user turn that counts as a short reply depending on prior `## Asked`. */
121
+ const SHORT_REPLY_MAX_CHARS = 80;
122
+ /** Thresholds for supplementing single-turn tool-heavy (subagent/research) extraction with sampled tool results. */
123
+ const SINGLE_TURN_TOOL_HEAVY_CALLS = 10;
124
+ const SINGLE_TURN_TOOL_HEAVY_PROSE_MAX = 1500;
125
+ const SAMPLED_TOOL_RESULT_TOTAL_CHARS = 6000;
126
+ const SAMPLED_TOOL_RESULT_PER_CALL_CHARS = 600;
127
+ /** Keep head and tail of overlong text so both opening context and final conclusions survive. */
128
+ function clipHeadTail(text, maxChars, headChars, tailChars) {
129
+ if (text.length <= maxChars)
130
+ return text;
131
+ const omitted = text.length - headChars - tailChars;
132
+ if (omitted <= 0)
133
+ return text;
134
+ return `${text.slice(0, headChars).trimEnd()}\n…(+${omitted} chars omitted)\n${text.slice(text.length - tailChars).trimStart()}`;
135
+ }
98
136
  /** The message an event derives to, or null when it derives to none. */
99
137
  function messageOf(event) {
100
138
  switch (event.type) {
@@ -149,15 +187,28 @@ function isInjection(event) {
149
187
  * @param event - any event; non-goal events yield undefined.
150
188
  * @returns the objective text, or undefined.
151
189
  */
190
+ /** Auto-generated host continuation goals that restate the todo list rather than a user goal. */
191
+ const AUTO_CONTINUATION_GOAL = /^(?:Continue the \d+ open tasks? this session recorded:|Continue working on the current goal\b)/i;
152
192
  function goalObjective(event) {
153
193
  if (sourceKind(event) !== 'goal')
154
194
  return undefined;
155
195
  const text = textOf(event);
156
- const match = /Objective:\s*"([\s\S]*?)"/.exec(text);
157
- // The objective arrives with its newlines already escaped inside the JSON
158
- // string, so a seven-item list reaches the digest as one unreadable line.
159
- const objective = (match?.[1] ?? '').replace(/\\n/g, '\n').trim();
160
- return objective.length > 0 ? objective : undefined;
196
+ const match = /Objective:\s*"((?:[^"\\]|\\.)*)"/.exec(text);
197
+ if (match === null)
198
+ return undefined;
199
+ const raw = match[1] ?? '';
200
+ let objective;
201
+ try {
202
+ objective = String(JSON.parse(`"${raw}"`)).trim();
203
+ }
204
+ catch {
205
+ objective = raw.replace(/\\([n"\\])/g, (_, ch) => (ch === 'n' ? '\n' : ch)).trim();
206
+ }
207
+ if (objective.length === 0)
208
+ return undefined;
209
+ if (AUTO_CONTINUATION_GOAL.test(objective))
210
+ return undefined;
211
+ return objective;
161
212
  }
162
213
  /** Whether this user message is a compaction checkpoint written by a backend. */
163
214
  function isCheckpoint(event) {
@@ -308,10 +359,81 @@ const EXTRACT_INSTRUCTION = [
308
359
  '- `options`: what the user could pick from, in order, one short line each, with their own numbering stripped. The list is often a paragraph or two above the question. Use [] when the question offered none.',
309
360
  // The reply is the next turn's `## user` line, already verbatim in the digest.
310
361
  // Asking for it here printed the same sentence twice.
311
- "- Use [] for `asked` when the turn asked nothing. Do not report the user's reply.",
362
+ "- Use [] for `asked` when the turn asked nothing or when questions were already answered via `ask_user_question`. Do not report the user's reply.",
312
363
  '',
313
364
  'Write strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
314
365
  ].join('\n');
366
+ /** Whether a parsed JSON value looks like an extraction slot payload (object with `slots[]` or array of keyed slots). */
367
+ function isSlotPayload(value) {
368
+ if (Array.isArray(value)) {
369
+ return value.some((item) => typeof item === 'object' && item !== null && 'key' in item);
370
+ }
371
+ return typeof value === 'object' && value !== null && Array.isArray(value.slots);
372
+ }
373
+ /** Extract the first balanced JSON object or array payload from a model reply that may carry prose or stray braces. */
374
+ function extractJsonPayload(raw) {
375
+ const body = raw.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '').trim();
376
+ try {
377
+ return JSON.parse(body);
378
+ }
379
+ catch {
380
+ // Fall through to balanced scan.
381
+ }
382
+ const candidates = [];
383
+ for (let start = 0; start < body.length; start += 1) {
384
+ const opener = body[start];
385
+ if (opener !== '{' && opener !== '[')
386
+ continue;
387
+ const closer = opener === '{' ? '}' : ']';
388
+ let depth = 0;
389
+ let inString = false;
390
+ let escaped = false;
391
+ for (let end = start; end < body.length; end += 1) {
392
+ const ch = body[end];
393
+ if (inString) {
394
+ if (escaped)
395
+ escaped = false;
396
+ else if (ch === '\\')
397
+ escaped = true;
398
+ else if (ch === '"')
399
+ inString = false;
400
+ continue;
401
+ }
402
+ if (ch === '"') {
403
+ inString = true;
404
+ continue;
405
+ }
406
+ if (ch === opener)
407
+ depth += 1;
408
+ else if (ch === closer) {
409
+ depth -= 1;
410
+ if (depth === 0) {
411
+ try {
412
+ const parsed = JSON.parse(body.slice(start, end + 1));
413
+ if (isSlotPayload(parsed))
414
+ return parsed;
415
+ candidates.push(parsed);
416
+ start = end;
417
+ }
418
+ catch {
419
+ // Do not skip past `end`: valid JSON may be nested inside invalid outer braces.
420
+ }
421
+ break;
422
+ }
423
+ }
424
+ }
425
+ }
426
+ return candidates[0];
427
+ }
428
+ /** Normalize model-drifted slot keys like `SLOT 0:0 (turn 1)` back to `0:0`. */
429
+ function normalizeSlotKey(raw) {
430
+ const str = typeof raw === 'string' ? raw : typeof raw === 'number' ? String(raw) : '';
431
+ return str
432
+ .trim()
433
+ .replace(/^SLOT\s+/i, '')
434
+ .replace(/\s*\(turn\s+[^)]*\)\s*$/i, '')
435
+ .trim();
436
+ }
315
437
  /**
316
438
  * Parse the model's JSON reply into per-slot extractions.
317
439
  *
@@ -325,34 +447,29 @@ const EXTRACT_INSTRUCTION = [
325
447
  */
326
448
  export function parseExtraction(answer) {
327
449
  const out = new Map();
328
- // Models wrap JSON in a fence often enough that stripping it is not defensive
329
- // programming but the common case.
330
- const body = answer.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
331
- const start = body.indexOf('{');
332
- const end = body.lastIndexOf('}');
333
- if (start < 0 || end <= start)
334
- return out;
335
- let parsed;
336
- try {
337
- parsed = JSON.parse(body.slice(start, end + 1));
338
- }
339
- catch {
340
- return out;
341
- }
450
+ const parsed = extractJsonPayload(answer);
342
451
  if (typeof parsed !== 'object' || parsed === null)
343
452
  return out;
344
- const slots = parsed['slots'];
453
+ const slots = Array.isArray(parsed)
454
+ ? parsed
455
+ : parsed['slots'];
345
456
  if (!Array.isArray(slots))
346
457
  return out;
347
- const strings = (value) => (Array.isArray(value)
348
- ? value.filter((item) => typeof item === 'string')
458
+ const strings = (value) => {
459
+ const rawList = Array.isArray(value)
460
+ ? value
461
+ : typeof value === 'string'
462
+ ? [value]
463
+ : [];
464
+ return rawList
465
+ .filter((item) => typeof item === 'string')
349
466
  .map((item) => item.replace(/\s+/g, ' ').trim())
350
467
  .filter((item) => item.length > 0)
351
468
  // A field is a list, so "nothing here" is an empty list. Models still write a
352
469
  // placeholder often enough that dropping it is worth one test.
353
- .filter((item) => !/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有)$/i.test(item))
354
- .filter((item) => !/^(?:未提问|无提问|没有提问|no questions? (?:were |was )?asked|none asked)[。.!!]*$/i.test(item))
355
- : []);
470
+ .filter((item) => !/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有|暂无|无变更|无推翻|未发现)[。.!!]*$/i.test(item))
471
+ .filter((item) => !/^(?:未提问|无提问|没有提问|no questions? (?:were |was )?asked|none asked)[。.!!]*$/i.test(item));
472
+ };
356
473
  // Asked is a list of objects, not of strings: a question without its options
357
474
  // turns the user's `1` into a number that selects nothing.
358
475
  const pairs = (value) => (Array.isArray(value)
@@ -370,9 +487,11 @@ export function parseExtraction(answer) {
370
487
  ? record['options']
371
488
  .filter((option) => typeof option === 'string')
372
489
  // The renderer supplies the numbering, so a model that echoes the source
373
- // list's own `1.` would print `1. 1. …`. Stripped here rather than asked
374
- // for in the prompt alone: three of five real runs kept it.
375
- .map((option) => option.replace(/\s+/g, ' ').replace(/^\s*\d{1,2}\s*[.、)]\s*/, '').trim())
490
+ // list's own `1.` / `(1)` / `A.` would print double prefixes.
491
+ .map((option) => option
492
+ .replace(/\s+/g, ' ')
493
+ .replace(/^\s*(?:(?:\d{1,2}|[A-Za-z])\s*[.、::)]\s*|[((]\s*(?:\d{1,2}|[A-Za-z])\s*[))]\s*)/, '')
494
+ .trim())
376
495
  .filter((option) => option.length > 0)
377
496
  : [];
378
497
  return [{ question, options }];
@@ -382,8 +501,8 @@ export function parseExtraction(answer) {
382
501
  if (typeof slot !== 'object' || slot === null)
383
502
  continue;
384
503
  const record = slot;
385
- const key = record['key'];
386
- if (typeof key !== 'string' || key.length === 0)
504
+ const key = normalizeSlotKey(record['key']);
505
+ if (key.length === 0)
387
506
  continue;
388
507
  out.set(key, {
389
508
  did: strings(record['did']),
@@ -398,10 +517,12 @@ export function parseExtraction(answer) {
398
517
  * Render one extraction as the digest block, headings included.
399
518
  *
400
519
  * @param extraction - the fields for one slot.
520
+ * @param level - graded retention level (3..0).
521
+ * @param includeAsked - whether to render the `## Asked` section (false for stale historical turns).
401
522
  * @returns markdown with a heading per non-empty field; empty string when every
402
523
  * field is empty.
403
524
  */
404
- export function renderExtractionBlock(extraction, level = 3) {
525
+ export function renderExtractionBlock(extraction, level = 3, includeAsked = true) {
405
526
  if (extraction === undefined)
406
527
  return '';
407
528
  const lines = [];
@@ -410,11 +531,6 @@ export function renderExtractionBlock(extraction, level = 3) {
410
531
  return;
411
532
  lines.push(`## ${heading}`, ...items.map((item) => `- ${item}`));
412
533
  };
413
- // `level` is how many of the graded sections survive: 3 keeps all, 2 drops
414
- // Overturned, 1 keeps only Did, 0 keeps only Asked. Asked is never dropped by
415
- // the level because it is the one section nothing later can rebuild — the
416
- // reply arrives in the next turn, but the question and its options exist only
417
- // here. See `renderDigest` for why the ladder exists at all.
418
534
  if (level >= 1)
419
535
  section('Did', extraction.did);
420
536
  if (level >= 2)
@@ -423,13 +539,10 @@ export function renderExtractionBlock(extraction, level = 3) {
423
539
  section('Overturned', extraction.overturned);
424
540
  // Asked goes last and its options are listed under it, so the user's reply — the
425
541
  // next `## user` line — lands directly under the list it chose from.
426
- if (extraction.asked.length > 0) {
542
+ if (includeAsked && extraction.asked.length > 0) {
427
543
  lines.push('## Asked');
428
544
  for (const pair of extraction.asked) {
429
545
  lines.push(`- ${pair.question}`);
430
- // Indented under the question so a reader cannot mistake an option for a
431
- // separate question, and numbered so the reply's digit has something to
432
- // point at.
433
546
  for (const [index, option] of pair.options.entries()) {
434
547
  lines.push(` ${index + 1}. ${option}`);
435
548
  }
@@ -459,18 +572,10 @@ const TURNS_PER_CALL = 8;
459
572
  /**
460
573
  * Sections folded into one condensed block when the digest overflows.
461
574
  *
462
- * Each fold is a model call, so the group size trades calls against compression.
463
- * Simulated on a 700- and a 1200-turn digest at the measured 8.2% fold ratio:
464
- *
465
- * group 20 → 19 and 52 calls
466
- * group 50 → 8 and 21 calls
467
- * group 100 → 4 and 11 calls
468
- *
469
- * Larger groups fold more text per call, which is also where the ratio holds
470
- * best: a 20-section group is small enough that the model's own paragraph is a
471
- * larger share of it. 100 keeps a long session to a handful of calls.
575
+ * Lowered from 100 to 30 so real long sessions (30–80 turns) fold oldest runs
576
+ * instead of falling straight into destructive body eviction.
472
577
  */
473
- const CONDENSE_GROUP = 100;
578
+ export const CONDENSE_GROUP = 30;
474
579
  /**
475
580
  * Output tokens allowed for one condensation call.
476
581
  *
@@ -587,18 +692,38 @@ export function collectHints(events) {
587
692
  }
588
693
  return lines.join('\n');
589
694
  }
590
- /** The `path` argument of one tool call, when the call carries one. */
591
- function pathArgumentOf(argumentsJson) {
695
+ /** Extract target file paths from write/edit/multiedit/apply_patch tool calls. */
696
+ function writePathsOf(toolName, argumentsJson) {
697
+ const paths = [];
698
+ const add = (candidate) => {
699
+ if (typeof candidate !== 'string')
700
+ return;
701
+ const trimmed = candidate.trim();
702
+ if (trimmed.length > 0 && !paths.includes(trimmed))
703
+ paths.push(trimmed);
704
+ };
592
705
  try {
593
706
  const parsed = JSON.parse(argumentsJson);
594
707
  if (typeof parsed !== 'object' || parsed === null)
595
- return undefined;
596
- const path = parsed.path;
597
- return typeof path === 'string' ? path : undefined;
708
+ return paths;
709
+ const record = parsed;
710
+ add(record['file_path']);
711
+ add(record['path']);
712
+ if (toolName === 'apply_patch') {
713
+ const patchText = typeof record['input'] === 'string'
714
+ ? record['input']
715
+ : typeof record['patch'] === 'string'
716
+ ? record['patch']
717
+ : '';
718
+ for (const match of patchText.matchAll(/^\*\*\*\s+(?:Add|Update|Delete)\s+File:\s*(.+)$|^\*\*\*\s+Move to:\s*(.+)$/gm)) {
719
+ add(match[1] ?? match[2]);
720
+ }
721
+ }
598
722
  }
599
723
  catch {
600
- return undefined;
724
+ return paths;
601
725
  }
726
+ return paths;
602
727
  }
603
728
  /** The turn number an event belongs to, when the log records one. */
604
729
  function turnOf(event) {
@@ -607,89 +732,70 @@ function turnOf(event) {
607
732
  }
608
733
  /** A fresh, empty turn accumulator. */
609
734
  function emptyTurn(turn, fromRequest = false) {
610
- return { turn, fromRequest, user: [], assistant: [], tools: new Map(), writes: [], answered: [] };
735
+ return { turn, fromRequest, user: [], assistant: [], writes: [], answered: [] };
611
736
  }
612
737
  /**
613
- * Group append-origin surface events into per-turn digest material.
614
- *
615
- * A section starts at each non-injected user message; assistant-only runs
616
- * before the first user message join the first section. Turn numbers come from
617
- * the log: `turn/start` carries `{turn}` and `assistant/message` carries
618
- * `data.turn`. A user message carries no turn of its own, so it inherits the
619
- * last one seen.
620
- *
621
- * @param events - the digest source in log order.
622
- * @returns one section per non-injected user message.
738
+ * Single source of truth for partitioning log events into sections alongside each
739
+ * section's exact slice of raw events, so rendering and extraction can never drift
740
+ * off by one section.
623
741
  */
624
- export function buildSections(events) {
742
+ function buildSectionsWithEvents(events) {
625
743
  const sections = [];
744
+ const sectionEvents = [];
626
745
  let current;
746
+ let currentEvents;
627
747
  let currentTurn;
628
748
  let lastTurn;
749
+ const startSection = () => {
750
+ current = { turns: [] };
751
+ currentEvents = [];
752
+ sections.push(current);
753
+ sectionEvents.push(currentEvents);
754
+ };
629
755
  const openTurn = (turn, fromRequest = false) => {
630
- if (current === undefined) {
631
- current = { turns: [] };
632
- sections.push(current);
633
- }
756
+ if (current === undefined)
757
+ startSection();
634
758
  const next = emptyTurn(turn, fromRequest);
635
759
  current.turns.push(next);
636
760
  if (turn !== undefined)
637
761
  lastTurn = turn;
638
762
  return next;
639
763
  };
640
- // One objective per section, and never twice: the host re-injects the same
641
- // objective on every round, so recording each copy would repeat it dozens of
642
- // times across a long autonomous run.
643
764
  const recordedObjectives = new Set();
644
- // Question id to question text, for every `ask_user_question` call seen so far.
645
- // The answer batch names questions by id only, and an id like `quota` says
646
- // nothing on its own.
647
765
  const questionTexts = new Map();
648
- // Call ids of this turn's `ask_user_question` calls. A result is an answer only
649
- // when its own call asked something: without this every result in the log was
650
- // JSON-parsed (536 KB across 157 results in one measured session, the largest
651
- // 49.9 KB) and any output that happened to look like an answer batch — a file
652
- // dump, a test fixture — would be recorded as something the user chose.
653
766
  const questionCallIds = new Set();
654
767
  for (const event of events) {
655
768
  if (event.type === 'turn/start') {
656
769
  const turn = turnOf(event);
657
770
  if (turn !== undefined)
658
771
  lastTurn = turn;
772
+ currentEvents?.push(event);
659
773
  continue;
660
774
  }
661
- const objective = goalObjective(event);
662
- if (objective !== undefined) {
663
- if (current === undefined) {
664
- current = { turns: [] };
665
- sections.push(current);
666
- }
667
- if (recordedObjectives.has(objective))
775
+ if (sourceKind(event) === 'goal') {
776
+ const objective = goalObjective(event);
777
+ if (objective === undefined || recordedObjectives.has(objective)) {
778
+ // Auto todo-continuation goals, malformed goals, and repeated rounds never
779
+ // penetrate into human `## user` sections.
668
780
  continue;
781
+ }
669
782
  recordedObjectives.add(objective);
670
- // A goal round opens a section like a user request does, and its objective
671
- // takes the user slot: it is the request this turn serves.
672
- current = { turns: [] };
673
- sections.push(current);
783
+ startSection();
674
784
  currentTurn = openTurn(turnOf(event) ?? lastTurn, false);
675
785
  currentTurn.user.push(objective);
786
+ currentEvents.push(event);
676
787
  continue;
677
788
  }
678
789
  if (event.type === 'tool/result') {
679
- // An answered question arrives as this call's own result. The call's
680
- // arguments named the questions; the result carries the choices.
790
+ currentEvents?.push(event);
681
791
  const callId = messageOf(event)?.toolCallId;
682
792
  if (callId === undefined || !questionCallIds.has(callId) || currentTurn === undefined)
683
793
  continue;
684
794
  currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
685
795
  continue;
686
796
  }
687
- // The host answers a question two ways. Inside the waiting window the answer
688
- // is the tool result above; after the call already returned its pending
689
- // notice, it is a `user/message` whose source kind is `user-question-reply`
690
- // and whose body is the same answer batch. That message is not a new request,
691
- // so it is read here rather than opening a section.
692
797
  if (sourceKind(event) === 'user-question-reply') {
798
+ currentEvents?.push(event);
693
799
  if (currentTurn !== undefined)
694
800
  currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
695
801
  continue;
@@ -700,35 +806,21 @@ export function buildSections(events) {
700
806
  continue;
701
807
  const eventTurn = turnOf(event) ?? lastTurn;
702
808
  if (event.type === 'user/message') {
703
- // A user message opens a new section, not merely a new turn: sections are
704
- // what the digest headings delimit, and one section per user request is
705
- // what makes the digest readable after a hundred turns.
706
- current = { turns: [] };
707
- sections.push(current);
809
+ startSection();
708
810
  currentTurn = openTurn(eventTurn, true);
709
811
  const text = textOf(event);
710
812
  if (text.length > 0)
711
813
  currentTurn.user.push(text);
814
+ currentEvents.push(event);
712
815
  continue;
713
816
  }
714
- // A user message carries no `turn` field while the reply carries one, so a
715
- // plain turn-number comparison opened a second turn for the same request: every
716
- // real section ended up with an empty request turn plus a reply turn holding no
717
- // user text, and the digest printed `## user` and `### assistant` twice.
718
- //
719
- // The turn number only separates work when the current turn already holds some,
720
- // i.e. when the log really moved on to a later turn.
721
- // A section is one request, so it is one turn. The log keeps advancing the turn
722
- // number inside a single request (7 assistant messages as turn 2, then 9 more as
723
- // turn 3), and splitting on the number gave every section a second turn whose
724
- // block was the tail of the same request's prose.
725
817
  if (currentTurn === undefined)
726
818
  currentTurn = openTurn(eventTurn ?? lastTurn);
819
+ currentEvents?.push(event);
727
820
  const text = textOf(event);
728
821
  if (text.length > 0)
729
822
  currentTurn.assistant.push(text);
730
823
  for (const call of toolCallsOf(event)) {
731
- currentTurn.tools.set(call.name, (currentTurn.tools.get(call.name) ?? 0) + 1);
732
824
  if (call.name === 'ask_user_question') {
733
825
  for (const [id, question] of questionTextsOf(call.arguments))
734
826
  questionTexts.set(id, question);
@@ -737,12 +829,22 @@ export function buildSections(events) {
737
829
  }
738
830
  if (!WRITE_TOOLS.has(call.name))
739
831
  continue;
740
- const path = pathArgumentOf(call.arguments);
741
- if (path !== undefined && !currentTurn.writes.includes(path))
742
- currentTurn.writes.push(path);
832
+ for (const path of writePathsOf(call.name, call.arguments)) {
833
+ if (!currentTurn.writes.includes(path))
834
+ currentTurn.writes.push(path);
835
+ }
743
836
  }
744
837
  }
745
- return sections;
838
+ return { sections, sectionEvents };
839
+ }
840
+ /**
841
+ * Group append-origin surface events into per-turn digest material.
842
+ *
843
+ * @param events - the digest source in log order.
844
+ * @returns one section per non-injected user message.
845
+ */
846
+ export function buildSections(events) {
847
+ return buildSectionsWithEvents(events).sections;
746
848
  }
747
849
  /**
748
850
  * Attach extracted blocks to the turns they belong to.
@@ -809,13 +911,13 @@ function hashText(input) {
809
911
  * @param events - one slot's events, in log order.
810
912
  * @returns a stable hex key.
811
913
  */
812
- function materialKey(events) {
914
+ function materialKey(events, options) {
813
915
  const prose = events
814
916
  .filter((event) => event.type === 'assistant/message')
815
917
  .map((event) => textOf(event))
816
918
  .filter((text) => text.length > 0)
817
919
  .join('\n');
818
- return hashText(buildExtractionMaterial(events, prose));
920
+ return hashText(buildExtractionMaterial(events, prose, options));
819
921
  }
820
922
  /**
821
923
  * Render one section to digest text, truncating assistant prose to `capChars`.
@@ -828,12 +930,65 @@ function materialKey(events) {
828
930
  * The tool pointer line stays either way: it is one line, and it is the only
829
931
  * record of what was actually run when the prose and extraction both say little.
830
932
  */
831
- function renderSection(section, level, condensed, sectionIndex) {
933
+ /** Normalize a question string for fuzzy duplicate comparison between Answers and Asked. */
934
+ function normalizeQuestionText(text) {
935
+ return text.toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '');
936
+ }
937
+ /** Drop `asked` entries that duplicate questions already answered via `ask_user_question` in the same turn. */
938
+ function dedupeAskedAgainstAnswers(extraction, answered) {
939
+ if (answered.length === 0 || extraction.asked.length === 0)
940
+ return extraction;
941
+ const answeredNorms = answered.map((item) => normalizeQuestionText(item.question)).filter((q) => q.length > 0);
942
+ if (answeredNorms.length === 0)
943
+ return extraction;
944
+ const filtered = extraction.asked.filter((pair) => {
945
+ const q = normalizeQuestionText(pair.question);
946
+ if (q.length === 0)
947
+ return true;
948
+ return !answeredNorms.some((ans) => (ans === q
949
+ || (q.length >= 4 && ans.length >= 4 && (ans.includes(q) || q.includes(ans)))));
950
+ });
951
+ return filtered.length === extraction.asked.length ? extraction : { ...extraction, asked: filtered };
952
+ }
953
+ /** Whether a section's `## Asked` should survive into the digest. */
954
+ function shouldKeepAsked(sections, sectionIndex) {
955
+ const isLast = sectionIndex === sections.length - 1;
956
+ if (isLast)
957
+ return true;
958
+ const nextUser = sections[sectionIndex + 1]?.turns[0]?.user.join('\n').trim() ?? '';
959
+ return nextUser.length > 0 && nextUser.length <= SHORT_REPLY_MAX_CHARS;
960
+ }
961
+ /** Index of the latest section carrying a real user request, falling back to the final section. */
962
+ function lastRealUserSectionIndex(sections) {
963
+ for (let i = sections.length - 1; i >= 0; i -= 1) {
964
+ if (sections[i]?.turns.some((turn) => turn.fromRequest && turn.user.length > 0))
965
+ return i;
966
+ }
967
+ return sections.length - 1;
968
+ }
969
+ /** Keep the latest section and the latest real user request unclipped; clip oversized pastes in older sections. */
970
+ function shouldKeepFullUser(sections, sectionIndex) {
971
+ if (sections === undefined)
972
+ return true;
973
+ if (sectionIndex === sections.length - 1)
974
+ return true;
975
+ return sectionIndex === lastRealUserSectionIndex(sections);
976
+ }
977
+ /** Format a turn's user prose, clipping oversized pastes in older (non-latest) sections. */
978
+ function formatUserText(texts, keepFullUser) {
979
+ if (keepFullUser)
980
+ return texts.join('\n');
981
+ return texts
982
+ .map((text) => clipHeadTail(text, OLD_USER_PASTE_MAX_CHARS, 1400, 800))
983
+ .join('\n');
984
+ }
985
+ function renderSection(section, level, condensed, sectionIndex, allSections) {
832
986
  const lines = [];
833
- // The block that covers this section, if any. Looked up by scanning the keys
834
- // rather than by probing one key per turn: a fold spans whole sections, so the
835
- // covering key belongs to an earlier section, not to this turn's own key.
836
987
  const index = sectionIndex ?? 0;
988
+ const totalSections = allSections?.length ?? (index + 1);
989
+ const keepFullUser = shouldKeepFullUser(allSections, index);
990
+ const compactAnswerStem = index < totalSections - FULL_ANSWER_STEM_RECENT_SECTIONS;
991
+ const keepAsked = allSections === undefined ? true : shouldKeepAsked(allSections, index);
837
992
  let covering;
838
993
  if (condensed !== undefined) {
839
994
  for (const [key, block] of condensed) {
@@ -845,13 +1000,10 @@ function renderSection(section, level, condensed, sectionIndex) {
845
1000
  }
846
1001
  }
847
1002
  if (covering !== undefined) {
848
- // The user line stays: a request is a standing constraint. Only the first
849
- // covered section prints the folded text — the rest contribute their user
850
- // lines alone, which is the room the condensation buys.
851
1003
  const start = Number(covering.key.split(':')[0]);
852
1004
  for (const turn of section.turns) {
853
1005
  if (turn.user.length > 0)
854
- lines.push(`\n## user\n${turn.user.join('\n')}`);
1006
+ lines.push(`\n## user\n${formatUserText(turn.user, keepFullUser)}`);
855
1007
  }
856
1008
  if (index === start) {
857
1009
  const range = covering.block.covers <= 1
@@ -861,29 +1013,41 @@ function renderSection(section, level, condensed, sectionIndex) {
861
1013
  }
862
1014
  return lines.join('\n');
863
1015
  }
864
- for (const [turnIndex, turn] of section.turns.entries()) {
1016
+ for (const [, turn] of section.turns.entries()) {
865
1017
  if (turn.user.length > 0)
866
- lines.push(`\n## user\n${turn.user.join('\n')}`);
867
- // An extraction whose every field is empty renders nothing: a heading followed by
868
- // no body reads as a turn that did something but says nothing.
869
- if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted, level).length > 0) {
870
- const block = renderExtractionBlock(turn.extracted, level);
871
- // The trailer goes *above* the block, not below it. `## Asked` is the block's
872
- // last section and the user's reply is the very next line, so a trailer line
873
- // in between would separate the reply from the question it answers.
1018
+ lines.push(`\n## user\n${formatUserText(turn.user, keepFullUser)}`);
1019
+ const effectiveExtraction = turn.extracted === undefined
1020
+ ? undefined
1021
+ : dedupeAskedAgainstAnswers(turn.extracted, turn.answered);
1022
+ const renderedBlock = renderExtractionBlock(effectiveExtraction, level, keepAsked);
1023
+ if (effectiveExtraction !== undefined && renderedBlock.length > 0) {
874
1024
  const trailer = [];
875
1025
  if (turn.writes.length > 0)
876
1026
  trailer.push(` wrote: ${turn.writes.join(', ')}`);
877
- const withAnswers = insertAnswers(block, renderAnswers(turn));
1027
+ const withAnswers = insertAnswers(renderedBlock, renderAnswers(turn, compactAnswerStem));
878
1028
  const body = trailer.length > 0 ? `${trailer.join('\n')}\n${withAnswers}` : withAnswers;
879
1029
  lines.push(`### assistant\n${body}`);
880
1030
  }
1031
+ else if (turn.extracted !== undefined
1032
+ && (turn.extracted.did.length > 0
1033
+ || turn.extracted.concluded.length > 0
1034
+ || turn.extracted.overturned.length > 0
1035
+ || turn.extracted.asked.length > 0)) {
1036
+ // Extraction succeeded with non-empty fields, and everything was filtered at this
1037
+ // level or dropped as stale Asked. Emit answers/writes if present without falling
1038
+ // back to raw prose.
1039
+ const trailer = [];
1040
+ if (turn.writes.length > 0)
1041
+ trailer.push(` wrote: ${turn.writes.join(', ')}`);
1042
+ const answers = renderAnswers(turn, compactAnswerStem);
1043
+ const parts = [...trailer, answers].filter((part) => part.length > 0);
1044
+ if (parts.length > 0)
1045
+ lines.push(`### assistant\n${parts.join('\n')}`);
1046
+ }
881
1047
  else {
882
- const body = turn.assistant.join('\n');
883
- const answers = renderAnswers(turn);
884
- // The heading goes on whenever there is anything to put under it. Emitting
885
- // the answers bare put `## Answers` directly below `## user`, at the user's
886
- // own heading level, where it reads as something the user said.
1048
+ const rawBody = turn.assistant.join('\n');
1049
+ const body = clipHeadTail(rawBody, FALLBACK_PROSE_MAX_CHARS, 1000, 1800);
1050
+ const answers = renderAnswers(turn, compactAnswerStem);
887
1051
  if (body.length > 0 || answers.length > 0)
888
1052
  lines.push(`### assistant\n${[body, answers].filter((part) => part.length > 0).join('\n')}`);
889
1053
  if (turn.writes.length > 0)
@@ -892,26 +1056,18 @@ function renderSection(section, level, condensed, sectionIndex) {
892
1056
  }
893
1057
  return lines.join('\n');
894
1058
  }
895
- /**
896
- * Render a turn's tool questions and their answers, or an empty string.
897
- *
898
- * This section exists because `## Asked` cannot cover these. `asked` is written by
899
- * the model from prose, and its contract says the reply is the next `## user` line
900
- * — true for a question asked in prose, false for one asked through
901
- * `ask_user_question`: the user answers inside the picker, the answer becomes the
902
- * tool result, and no user message is ever written. Two consecutive checkpoints of
903
- * a real session carried neither the question nor the answer.
904
- *
905
- * Rendered from the log, so it cannot be paraphrased away, and placed after the
906
- * assistant block because it belongs to that turn's work.
907
- *
908
- * @param turn - one turn's digest material.
909
- * @returns the `## Answers` section, or an empty string when nothing was asked.
910
- */
911
- function renderAnswers(turn) {
1059
+ function renderAnswers(turn, compactStem = false) {
912
1060
  if (turn.answered.length === 0)
913
1061
  return '';
914
- return `## Answers\n${turn.answered.flatMap(renderAnswered).join('\n')}`;
1062
+ const items = compactStem
1063
+ ? turn.answered.map((item) => {
1064
+ const collapsed = item.question.replace(/\s+/g, ' ').trim();
1065
+ return collapsed.length > OLD_ANSWER_STEM_MAX_CHARS
1066
+ ? { ...item, question: `${collapsed.slice(0, OLD_ANSWER_STEM_MAX_CHARS).trimEnd()}…` }
1067
+ : { ...item, question: collapsed };
1068
+ })
1069
+ : turn.answered;
1070
+ return `## Answers\n${items.flatMap(renderAnswered).join('\n')}`;
915
1071
  }
916
1072
  /**
917
1073
  * Place the `## Answers` section just above `## Asked`, or at the end when the
@@ -972,11 +1128,25 @@ function insertAnswers(block, answers) {
972
1128
  * bodies, leaving only `## Asked`, before condensation ever got a chance.
973
1129
  */
974
1130
  export function renderDigest(events, budgetTokens, extracted, condensed) {
975
- const sections = extracted === undefined ? buildSections(events) : withExtractions(buildSections(events), extracted);
1131
+ const rawSections = extracted === undefined ? buildSections(events) : withExtractions(buildSections(events), extracted);
1132
+ // Normalize oversized pastes in older sections before budgeting and T1 so a
1133
+ // single 50k historical paste is billed at its ~2.2k clipped size instead of
1134
+ // starving earlier standing constraints or being truncated twice.
1135
+ const sections = rawSections.map((section, sectionIndex) => (shouldKeepFullUser(rawSections, sectionIndex)
1136
+ ? section
1137
+ : {
1138
+ turns: section.turns.map((turn) => ({
1139
+ ...turn,
1140
+ user: turn.user.map((text) => clipHeadTail(text, OLD_USER_PASTE_MAX_CHARS, 1400, 800)),
1141
+ })),
1142
+ }));
976
1143
  const budgetChars = Math.max(0, budgetTokens * 4);
977
- const render = (trimmed, level = 3) => (trimmed ?? sections)
978
- .map((section, index) => renderSection(section, level, condensed, index))
979
- .join('\n');
1144
+ const render = (trimmed, level = 3) => {
1145
+ const list = trimmed ?? sections;
1146
+ return list
1147
+ .map((section, index) => renderSection(section, level, condensed, index, list))
1148
+ .join('\n');
1149
+ };
980
1150
  // User prose is reserved before anything else is placed.
981
1151
  //
982
1152
  // Measured on a 122-turn session: every human message in the span totalled 469
@@ -1166,9 +1336,25 @@ export function renderDigest(events, budgetTokens, extracted, condensed) {
1166
1336
  */
1167
1337
  export function shadowedSeqs(session, input) {
1168
1338
  const nodes = session.surface.nodes;
1169
- const head = nodes[0] !== undefined && session.eventAt(nodes[0])?.type === 'system/message' ? 1 : 0;
1170
- const take = Math.max(0, input.messages.length - head);
1171
- return nodes.slice(head, head + take);
1339
+ const firstEvent = nodes[0] !== undefined ? session.eventAt(nodes[0]) : undefined;
1340
+ const head = firstEvent?.type === 'system/message' ? 1 : 0;
1341
+ const messageCount = Math.max(0, input.messages.length - head);
1342
+ if (messageCount === 0)
1343
+ return [];
1344
+ // Match surface nodes that actually derive to a message: the host's
1345
+ // `buildSummarizationInput` skips nodes whose `deriveEventMessage` is null,
1346
+ // while the replaced span still covers every surface node through the last
1347
+ // shadowed message.
1348
+ let seenMessages = 0;
1349
+ let endIndex = head;
1350
+ for (let i = head; i < nodes.length && seenMessages < messageCount; i += 1) {
1351
+ const seq = nodes[i];
1352
+ const ev = seq === undefined ? undefined : session.eventAt(seq);
1353
+ if (ev !== undefined && messageOf(ev) !== null)
1354
+ seenMessages += 1;
1355
+ endIndex = i + 1;
1356
+ }
1357
+ return nodes.slice(head, endIndex);
1172
1358
  }
1173
1359
  /**
1174
1360
  * Pick the log events the digest is built from: every append-origin surface
@@ -1216,204 +1402,336 @@ export function digestSource(session, retainedSeqs) {
1216
1402
  * @param prose - that turn's assistant prose, already extracted by the caller.
1217
1403
  * @returns the joined material, or an empty string when the turn has nothing.
1218
1404
  */
1219
- export function buildExtractionMaterial(turn, prose) {
1405
+ /** Sample non-error, non-question tool results for single-turn tool-heavy (subagent) runs. */
1406
+ function sampleToolResults(turn) {
1407
+ const questionCallIds = new Set();
1408
+ const callNames = new Map();
1409
+ for (const event of turn) {
1410
+ if (event.type !== 'assistant/message')
1411
+ continue;
1412
+ for (const call of toolCallsOf(event)) {
1413
+ callNames.set(call.id, call.name);
1414
+ if (call.name === 'ask_user_question')
1415
+ questionCallIds.add(call.id);
1416
+ }
1417
+ }
1418
+ const collected = [];
1419
+ let budget = SAMPLED_TOOL_RESULT_TOTAL_CHARS;
1420
+ for (let i = turn.length - 1; i >= 0 && budget > 0; i -= 1) {
1421
+ const event = turn[i];
1422
+ if (event === undefined || event.type !== 'tool/result')
1423
+ continue;
1424
+ const msg = messageOf(event);
1425
+ if (msg === null || msg.isError === true)
1426
+ continue;
1427
+ const callId = msg.toolCallId;
1428
+ if (callId !== undefined && questionCallIds.has(callId))
1429
+ continue;
1430
+ const raw = textOf(event).replace(/\s+/g, ' ').trim();
1431
+ if (raw.length === 0)
1432
+ continue;
1433
+ const snippet = raw.slice(0, Math.min(SAMPLED_TOOL_RESULT_PER_CALL_CHARS, budget));
1434
+ const toolLabel = callId !== undefined ? (callNames.get(callId) ?? 'tool') : 'tool';
1435
+ const entry = `[${toolLabel}] ${snippet}`;
1436
+ collected.push(entry);
1437
+ budget -= entry.length + 1;
1438
+ }
1439
+ return collected.reverse().join('\n');
1440
+ }
1441
+ export function buildExtractionMaterial(turn, prose, options) {
1220
1442
  const userRequest = turn
1221
- .filter((event) => event.type === 'user/message' && !isInjection(event) && !isCheckpoint(event))
1222
- .map((event) => textOf(event))
1443
+ .filter((event) => {
1444
+ if (event.type !== 'user/message' || isCheckpoint(event))
1445
+ return false;
1446
+ if (sourceKind(event) === 'goal')
1447
+ return goalObjective(event) !== undefined;
1448
+ return !isInjection(event);
1449
+ })
1450
+ .map((event) => (sourceKind(event) === 'goal' ? (goalObjective(event) ?? '') : textOf(event)))
1223
1451
  .filter((text) => text.length > 0)
1224
1452
  .join('\n');
1225
1453
  const hints = collectHints(turn);
1226
- if (userRequest.length === 0 && prose.length === 0 && hints.length === 0)
1454
+ const toolResults = options?.includeToolResults === true ? sampleToolResults(turn) : '';
1455
+ if (userRequest.length === 0 && prose.length === 0 && hints.length === 0 && toolResults.length === 0)
1227
1456
  return '';
1228
- return [
1229
- `USER INSTRUCTION (already in the digest verbatim; never copy it into Asked):\n${userRequest.slice(0, 4000) || '(none)'}`,
1230
- `ASSISTANT PROSE:\n${prose.slice(0, 6000) || '(none)'}`,
1457
+ const clippedUser = clipHeadTail(userRequest, 4000, 2500, 1400);
1458
+ const clippedProse = clipHeadTail(prose, 6000, 2000, 3900);
1459
+ const sections = [
1460
+ `USER INSTRUCTION (already in the digest verbatim; never copy it into Asked):\n${clippedUser || '(none)'}`,
1461
+ `ASSISTANT PROSE:\n${clippedProse || '(none)'}`,
1231
1462
  `TOOL TRACE:\n${hints || '(none)'}`,
1232
- ].join('\n\n');
1463
+ ];
1464
+ if (toolResults.length > 0) {
1465
+ sections.push(`KEY TOOL RESULTS (sampled from tool-heavy single-turn run):\n${toolResults}`);
1466
+ }
1467
+ return sections.join('\n\n');
1233
1468
  }
1234
- /**
1235
- * Per-turn extraction through the host's own LLM service.
1236
- *
1237
- * This is the part the verbatim digest cannot do on its own. Measured on a real
1238
- * 13878-event session: 1973 assistant messages, of which only 317 carried any
1239
- * prose, and one turn ran 342 tool calls while emitting zero characters of text.
1240
- * A digest that only copies prose therefore reduced that whole turn to a `tools:`
1241
- * count line — the work happened, the record did not.
1242
- *
1243
- * The call reuses the session's routed model exactly as the host's own
1244
- * compaction does (`ctx.llm.stream` with the session's provider/model), so no
1245
- * separate credential or configuration is involved.
1246
- *
1247
- * Every failure path yields no blocks and the caller falls back to the plain
1248
- * digest: a compaction that cannot reach the model must still compact, or the
1249
- * session dies of context overflow instead of losing detail. The degradation is
1250
- * per turn, but it is never silent — a batch that comes back unusable is
1251
- * reported, because the whole point of that fallback is invisible otherwise.
1252
- *
1253
- * @param ctx - plugin context carrying the `llm` service and a logger.
1254
- * @param agent - owner of the session being compacted; supplies the routed model.
1255
- * @param batch - slots to extract, in one call unless the answer is truncated.
1256
- * @param signal - cancellation forwarded to the adapter.
1257
- * @returns the extracted blocks by slot key; empty when extraction is unavailable.
1258
- */
1259
- /**
1260
- * One condensation request: fold a run of already-finished turns into a paragraph.
1261
- *
1262
- * Module-level and shaped like `extractOnce` rather than a method, so both calls
1263
- * derive their route and reasoning effort the same way.
1264
- *
1265
- * @param ctx - plugin context carrying the `llm` service and a logger.
1266
- * @param agent - owner of the session being compacted.
1267
- * @param material - the rendered blocks being folded.
1268
- * @param signal - cancellation forwarded to the adapter.
1269
- * @returns the folded paragraph, or undefined when the call produced nothing.
1270
- */
1271
- async function condenseOnce(ctx, agent, material, signal, override) {
1469
+ function createUsageAccumulator() {
1470
+ return {
1471
+ seen: false,
1472
+ inputTokens: 0,
1473
+ outputTokens: 0,
1474
+ totalTokens: 0,
1475
+ hasTotalTokens: false,
1476
+ cacheReadTokens: 0,
1477
+ hasCacheRead: false,
1478
+ cacheWriteTokens: 0,
1479
+ hasCacheWrite: false,
1480
+ reasoningTokens: 0,
1481
+ hasReasoning: false,
1482
+ };
1483
+ }
1484
+ function addUsage(acc, usage) {
1485
+ if (acc === undefined || typeof usage !== 'object' || usage === null)
1486
+ return;
1487
+ const u = usage;
1488
+ const input = typeof u['inputTokens'] === 'number' ? u['inputTokens'] : 0;
1489
+ const output = typeof u['outputTokens'] === 'number' ? u['outputTokens'] : 0;
1490
+ if (input === 0 && output === 0 && typeof u['totalTokens'] !== 'number')
1491
+ return;
1492
+ acc.seen = true;
1493
+ acc.inputTokens += input;
1494
+ acc.outputTokens += output;
1495
+ if (typeof u['totalTokens'] === 'number') {
1496
+ acc.hasTotalTokens = true;
1497
+ acc.totalTokens += u['totalTokens'];
1498
+ }
1499
+ if (typeof u['cacheReadTokens'] === 'number') {
1500
+ acc.hasCacheRead = true;
1501
+ acc.cacheReadTokens += u['cacheReadTokens'];
1502
+ }
1503
+ if (typeof u['cacheWriteTokens'] === 'number') {
1504
+ acc.hasCacheWrite = true;
1505
+ acc.cacheWriteTokens += u['cacheWriteTokens'];
1506
+ }
1507
+ if (typeof u['reasoningTokens'] === 'number') {
1508
+ acc.hasReasoning = true;
1509
+ acc.reasoningTokens += u['reasoningTokens'];
1510
+ }
1511
+ }
1512
+ function toTokenUsage(acc) {
1513
+ if (!acc.seen)
1514
+ return undefined;
1515
+ return {
1516
+ inputTokens: acc.inputTokens,
1517
+ outputTokens: acc.outputTokens,
1518
+ ...(acc.hasTotalTokens ? { totalTokens: acc.totalTokens } : {}),
1519
+ ...(acc.hasCacheRead ? { cacheReadTokens: acc.cacheReadTokens } : {}),
1520
+ ...(acc.hasCacheWrite ? { cacheWriteTokens: acc.cacheWriteTokens } : {}),
1521
+ ...(acc.hasReasoning ? { reasoningTokens: acc.reasoningTokens } : {}),
1522
+ };
1523
+ }
1524
+ /** Resolve the effective provider and model after applying any configured purpose override. */
1525
+ function resolveEffectiveRoute(agent, override) {
1526
+ const sessionRoute = agent.session.requestHeader()?.config;
1527
+ const baseProvider = sessionRoute?.provider ?? agent.options.provider;
1528
+ const baseModel = sessionRoute?.model ?? agent.options.model;
1529
+ const paired = pairedRouteOf(override);
1530
+ const provider = paired?.provider ?? baseProvider;
1531
+ const model = paired?.model ?? baseModel;
1532
+ if (provider === undefined || model === undefined)
1533
+ return undefined;
1534
+ return { provider, model };
1535
+ }
1536
+ /** Read the per-call LLM timeout in ms, honoring an optional environment override. */
1537
+ function resolveCallTimeoutMs() {
1538
+ const raw = process.env['DSH_VERBATIM_CALL_TIMEOUT_MS'];
1539
+ if (raw !== undefined) {
1540
+ const parsed = Number(raw);
1541
+ if (Number.isFinite(parsed) && parsed > 0)
1542
+ return parsed;
1543
+ }
1544
+ return DEFAULT_LLM_CALL_TIMEOUT_MS;
1545
+ }
1546
+ /** Combine an optional outer AbortSignal with a per-call timeout. */
1547
+ function withCallTimeout(signal, timeoutMs) {
1548
+ const controller = new AbortController();
1549
+ const onAbort = () => {
1550
+ controller.abort(signal?.reason);
1551
+ };
1552
+ if (signal !== undefined) {
1553
+ if (signal.aborted) {
1554
+ controller.abort(signal.reason);
1555
+ return { signal: controller.signal, dispose: () => { } };
1556
+ }
1557
+ signal.addEventListener('abort', onAbort, { once: true });
1558
+ }
1559
+ const timer = setTimeout(() => {
1560
+ controller.abort(new Error(`verbatim-compaction call timed out after ${timeoutMs}ms`));
1561
+ }, timeoutMs);
1562
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer && typeof timer.unref === 'function') {
1563
+ timer.unref();
1564
+ }
1565
+ return {
1566
+ signal: controller.signal,
1567
+ dispose: () => {
1568
+ clearTimeout(timer);
1569
+ signal?.removeEventListener('abort', onAbort);
1570
+ },
1571
+ };
1572
+ }
1573
+ /** Flatten folded model output into one clean bullet-safe paragraph (no code fences, headings, or multiline breaks). */
1574
+ function sanitizeCondensedText(raw) {
1575
+ const unfenced = raw.trim().replace(/^```[a-zA-Z0-9_-]*\s*/i, '').replace(/\s*```$/, '').trim();
1576
+ const cleanedLines = unfenced
1577
+ .split(/\r?\n/)
1578
+ .map((line) => line
1579
+ .trim()
1580
+ .replace(/^#{1,6}\s+/, '')
1581
+ .replace(/^[-*•]\s+/, '')
1582
+ .trim())
1583
+ .filter((line) => line.length > 0 && !/^```/.test(line));
1584
+ return cleanedLines.join(' ').replace(/\s+/g, ' ').trim();
1585
+ }
1586
+ /** Bounded LRU-like Map read/write helpers. */
1587
+ function boundedCacheGet(map, key) {
1588
+ const value = map.get(key);
1589
+ if (value !== undefined) {
1590
+ map.delete(key);
1591
+ map.set(key, value);
1592
+ }
1593
+ return value;
1594
+ }
1595
+ function boundedCacheSet(map, key, value, maxSize) {
1596
+ if (map.has(key))
1597
+ map.delete(key);
1598
+ map.set(key, value);
1599
+ while (map.size > maxSize) {
1600
+ const oldest = map.keys().next().value;
1601
+ if (oldest === undefined)
1602
+ break;
1603
+ map.delete(oldest);
1604
+ }
1605
+ }
1606
+ /** Directory for persistent per-session caches, or undefined when disabled (e.g. under node --test). */
1607
+ function resolveCacheDir() {
1608
+ const explicit = process.env['DSH_VERBATIM_CACHE_DIR'];
1609
+ if (explicit !== undefined) {
1610
+ const trimmed = explicit.trim();
1611
+ if (trimmed === '' || /^(?:off|none|false|0)$/i.test(trimmed))
1612
+ return undefined;
1613
+ return trimmed;
1614
+ }
1615
+ if (process.env['NODE_TEST_CONTEXT'] !== undefined)
1616
+ return undefined;
1617
+ const base = process.env['DSH_HOME']?.trim() || join(homedir(), '.dsh');
1618
+ return join(base, 'cache', 'verbatim-compaction');
1619
+ }
1620
+ function cacheFilePath(dir, sessionId) {
1621
+ const safeId = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_') || 'default';
1622
+ return join(dir, `${safeId}.json`);
1623
+ }
1624
+ async function condenseOnce(ctx, agent, material, signal, override, usageAcc) {
1272
1625
  const llm = ctx.llm;
1273
1626
  if (llm === undefined) {
1274
1627
  ctx.logger?.warn('verbatim-compaction: no llm service, condensation skipped');
1275
1628
  return undefined;
1276
1629
  }
1277
- const route = agent.session.requestHeader()?.config;
1278
- const provider = route?.provider ?? agent.options.provider;
1279
- const model = route?.model ?? agent.options.model;
1280
- if (provider === undefined || model === undefined) {
1630
+ const effective = resolveEffectiveRoute(agent, override);
1631
+ if (effective === undefined) {
1281
1632
  ctx.logger?.warn('verbatim-compaction: no route for condensation, skipped');
1282
1633
  return undefined;
1283
1634
  }
1284
- const info = await Promise.resolve()
1285
- .then(() => llm.resolveModelInfo?.(provider, model, signal))
1286
- .catch(() => undefined);
1287
- const cheapest = cheapestEffort(info?.reasoning?.efforts);
1635
+ const call = withCallTimeout(signal, resolveCallTimeoutMs());
1288
1636
  const chunks = [];
1289
1637
  try {
1638
+ const info = await Promise.resolve()
1639
+ .then(() => llm.resolveModelInfo?.(effective.provider, effective.model, call.signal))
1640
+ .catch(() => undefined);
1641
+ const cheapest = cheapestEffort(info?.reasoning?.efforts);
1290
1642
  const stream = llm.stream(applyPurposeOverride({
1291
- provider,
1292
- model,
1643
+ provider: effective.provider,
1644
+ model: effective.model,
1293
1645
  messages: [{ role: 'user', content: [{ type: 'text', text: `${material}\n\n${CONDENSE_INSTRUCTION}` }] }],
1294
1646
  maxTokens: CONDENSE_TOKENS,
1295
1647
  sessionId: agent.session.id,
1296
1648
  purpose: 'compaction',
1297
- ...(signal === undefined ? {} : { signal }),
1649
+ signal: call.signal,
1298
1650
  }, override, cheapest));
1299
1651
  for await (const chunk of stream) {
1300
1652
  const delta = chunk;
1301
1653
  if (delta.type === 'text-delta' && typeof delta.text === 'string')
1302
1654
  chunks.push(delta.text);
1655
+ else if (delta.type === 'finish')
1656
+ addUsage(usageAcc, delta.usage);
1303
1657
  }
1304
1658
  }
1305
1659
  catch (error) {
1306
1660
  ctx.logger?.warn(`verbatim-compaction: condensation call failed: ${String(error)}`);
1307
1661
  return undefined;
1308
1662
  }
1309
- const text = chunks.join('').trim();
1663
+ finally {
1664
+ call.dispose();
1665
+ }
1666
+ const text = sanitizeCondensedText(chunks.join(''));
1310
1667
  if (text.length === 0) {
1311
- // Silence here is what makes "the digest stopped folding" invisible at runtime:
1312
- // the summary still renders, just without the room the fold would have bought.
1313
1668
  ctx.logger?.warn(`verbatim-compaction: condensation returned no text for ${material.length} chars of material`);
1314
1669
  return undefined;
1315
1670
  }
1316
1671
  return text;
1317
1672
  }
1318
- async function extractBatch(ctx, agent, batch, signal, override) {
1673
+ async function extractBatch(ctx, agent, batch, signal, override, usageAcc) {
1319
1674
  const out = new Map();
1320
- if (batch.length === 0)
1675
+ const isAborted = () => signal?.aborted === true;
1676
+ if (batch.length === 0 || isAborted())
1321
1677
  return out;
1322
- const attempt = await extractOnce(ctx, agent, batch, signal, override);
1323
- if (!attempt.truncated) {
1678
+ const attempt = await extractOnce(ctx, agent, batch, signal, override, usageAcc);
1679
+ if (attempt.transportError)
1680
+ return attempt.blocks;
1681
+ const needsSplit = attempt.truncated || (attempt.blocks.size === 0 && batch.length > 1 && !isAborted());
1682
+ if (!needsSplit) {
1324
1683
  if (attempt.blocks.size === 0) {
1325
1684
  ctx.logger?.warn(`verbatim-compaction: extraction returned no usable JSON for ${batch.length} slot(s) `
1326
1685
  + `(${batch.map((slot) => slot.key).join(', ')}); those turns keep their verbatim prose`);
1327
1686
  }
1328
1687
  return attempt.blocks;
1329
1688
  }
1330
- // A truncated answer parses to nothing, so one over-budget turn would cost
1331
- // every turn in its batch. Measured on 191 real compactions, failures arrived
1332
- // in runs of exactly `TURNS_PER_CALL`, which is this batching, not the model
1333
- // failing per turn. Halving bounds the loss to the half that still does not
1334
- // fit, and a single slot cannot be split further.
1335
1689
  if (batch.length === 1) {
1336
- ctx.logger?.warn(`verbatim-compaction: extraction truncated at the token cap for slot ${batch[0]?.key ?? '?'}; `
1337
- + 'that turn keeps its verbatim prose');
1690
+ if (attempt.blocks.size === 0) {
1691
+ ctx.logger?.warn(`verbatim-compaction: extraction truncated at the token cap for slot ${batch[0]?.key ?? '?'}; `
1692
+ + 'that turn keeps its verbatim prose');
1693
+ }
1338
1694
  return attempt.blocks;
1339
1695
  }
1340
1696
  for (const [key, block] of attempt.blocks)
1341
1697
  out.set(key, block);
1342
- const middle = Math.ceil(batch.length / 2);
1343
- for (const half of [batch.slice(0, middle), batch.slice(middle)]) {
1344
- for (const [key, block] of await extractBatch(ctx, agent, half, signal, override))
1698
+ const remaining = batch.filter((slot) => !out.has(slot.key));
1699
+ if (remaining.length === 0)
1700
+ return out;
1701
+ if (remaining.length === 1) {
1702
+ if (!isAborted()) {
1703
+ for (const [key, block] of await extractBatch(ctx, agent, remaining, signal, override, usageAcc))
1704
+ out.set(key, block);
1705
+ }
1706
+ return out;
1707
+ }
1708
+ const middle = Math.ceil(remaining.length / 2);
1709
+ for (const half of [remaining.slice(0, middle), remaining.slice(middle)]) {
1710
+ if (half.length === 0 || isAborted())
1711
+ continue;
1712
+ for (const [key, block] of await extractBatch(ctx, agent, half, signal, override, usageAcc))
1345
1713
  out.set(key, block);
1346
1714
  }
1347
1715
  return out;
1348
1716
  }
1349
- /**
1350
- * The cheapest effort a route advertises, or undefined when it advertises none.
1351
- *
1352
- * The route's own default is not used: it is typically the highest level, and
1353
- * thinking is paid out of the answer's token budget. The list is ordered from
1354
- * least to greatest effort by the host's own contract, so the first entry is the
1355
- * cheapest. `off` is skipped even when present — pi-ai maps it to a wire value
1356
- * the route may reject, and a level that cannot be sent is worse than a cheap
1357
- * one that can.
1358
- *
1359
- * @param efforts - the route's advertised efforts, in escalation order.
1360
- * @returns the cheapest usable effort id, or undefined to leave the choice alone.
1361
- */
1362
1717
  function cheapestEffort(efforts) {
1363
- return efforts?.find((entry) => entry.id !== 'off')?.id;
1718
+ if (efforts === undefined)
1719
+ return undefined;
1720
+ for (const entry of efforts) {
1721
+ const id = typeof entry === 'string' ? entry : entry.id;
1722
+ if (id !== 'off')
1723
+ return id;
1724
+ }
1725
+ return undefined;
1364
1726
  }
1365
- /**
1366
- * One extraction request, no retry.
1367
- *
1368
- * The cap must carry a fixed thinking reserve on top of the per-slot output
1369
- * budget. `maxTokens` covers thinking and the answer together, and thinking is
1370
- * a per-call cost that does not shrink when the batch does. Measured against the
1371
- * live route (deepseek-flash, `reasoning_effort` unset, real-length material):
1372
- * a single slot at the old `220 x 1` cap returned zero parseable slots in 4 of 4
1373
- * runs, the thinking block having consumed the entire cap; the same single slot
1374
- * at `220 x 1 + 1000` parsed in 4 of 4. The reserve is what makes the cap work
1375
- * for a batch of any size, including the batches the caller splits down to.
1376
- *
1377
- * The effort is pinned to the route's cheapest advertised level rather than left
1378
- * to the route default. Thinking is paid out of the same `maxTokens` as the
1379
- * answer, so a default that thinks hard shrinks the answer budget even with the
1380
- * reserve in place. Measured on the live route at a 2-slot cap with the reserve:
1381
- * `low` spent 375 thinking tokens and parsed 3 of 3; `high` spent 931 and parsed
1382
- * 2 of 3.
1383
- *
1384
- * Two things that look like fixes and are not:
1385
- *
1386
- * - `off` cannot be reached through pi-ai. Its `deepseek` thinking format maps
1387
- * the `off` level to `reasoning_effort: "minimal"`, which the route rejects
1388
- * outright (`valid levels: low, medium, high`), and its `thinking` field is
1389
- * pinned to `{type: "enabled"}` for every level. Captured from pi-ai 1.3.0
1390
- * against a local echo server, not inferred.
1391
- * - Only the provider's own `thinking: {type: "disabled"}` actually stops
1392
- * thinking (0 thinking tokens, measured), but `GenerateOptions` has no field
1393
- * that carries it, so no plugin on this seam can send it.
1394
- *
1395
- * An effort is requested only when the route advertises it, because the host
1396
- * rejects one it does not.
1397
- *
1398
- * @param ctx - plugin context carrying the `llm` service and a logger.
1399
- * @param agent - owner of the session being compacted.
1400
- * @param batch - slots to ask about in this one call.
1401
- * @param signal - cancellation forwarded to the adapter.
1402
- * @returns the parsed blocks and whether the model stopped at the token cap.
1403
- */
1404
- async function extractOnce(ctx, agent, batch, signal, override) {
1727
+ async function extractOnce(ctx, agent, batch, signal, override, usageAcc) {
1405
1728
  const out = new Map();
1406
1729
  const llm = ctx.llm;
1407
1730
  if (llm === undefined)
1408
1731
  return { blocks: out, truncated: false };
1409
- const route = agent.session.requestHeader()?.config;
1410
- const provider = route?.provider ?? agent.options.provider;
1411
- const model = route?.model ?? agent.options.model;
1412
- if (provider === undefined || model === undefined)
1732
+ const effective = resolveEffectiveRoute(agent, override);
1733
+ if (effective === undefined)
1413
1734
  return { blocks: out, truncated: false };
1414
- // The label the model echoes back is the slot key, not the turn number: two
1415
- // requests can share a number, and a duplicate label would collapse two blocks
1416
- // into one entry.
1417
1735
  const parts = [];
1418
1736
  for (const slot of batch) {
1419
1737
  const prose = slot.events
@@ -1421,48 +1739,82 @@ async function extractOnce(ctx, agent, batch, signal, override) {
1421
1739
  .map((event) => textOf(event))
1422
1740
  .filter((text) => text.length > 0)
1423
1741
  .join('\n');
1424
- const material = buildExtractionMaterial(slot.events, prose);
1742
+ const material = buildExtractionMaterial(slot.events, prose, slot.includeToolResults === true ? { includeToolResults: true } : undefined);
1425
1743
  if (material.length === 0)
1426
1744
  continue;
1427
1745
  parts.push(`=== SLOT ${slot.key} (turn ${slot.turn ?? '?'}) ===\n${material}`);
1428
1746
  }
1429
1747
  if (parts.length === 0)
1430
1748
  return { blocks: out, truncated: false };
1431
- const info = await Promise.resolve()
1432
- .then(() => llm.resolveModelInfo?.(provider, model, signal))
1433
- .catch(() => undefined);
1434
- const cheapest = cheapestEffort(info?.reasoning?.efforts);
1749
+ const call = withCallTimeout(signal, resolveCallTimeoutMs());
1435
1750
  const chunks = [];
1436
1751
  let truncated = false;
1437
1752
  try {
1753
+ const info = await Promise.resolve()
1754
+ .then(() => llm.resolveModelInfo?.(effective.provider, effective.model, call.signal))
1755
+ .catch(() => undefined);
1756
+ const cheapest = cheapestEffort(info?.reasoning?.efforts);
1438
1757
  const stream = llm.stream(applyPurposeOverride({
1439
- provider,
1440
- model,
1758
+ provider: effective.provider,
1759
+ model: effective.model,
1441
1760
  messages: [
1442
1761
  { role: 'user', content: [{ type: 'text', text: `${parts.join('\n\n')}\n\n${EXTRACT_INSTRUCTION}` }] },
1443
1762
  ],
1444
1763
  maxTokens: EXTRACT_TOKENS_PER_TURN * parts.length + EXTRACT_THINKING_RESERVE_TOKENS,
1445
1764
  sessionId: agent.session.id,
1446
1765
  purpose: 'compaction',
1447
- ...(signal === undefined ? {} : { signal }),
1766
+ signal: call.signal,
1448
1767
  }, override, cheapest));
1449
1768
  for await (const chunk of stream) {
1450
1769
  const delta = chunk;
1451
1770
  if (delta.type === 'text-delta' && typeof delta.text === 'string')
1452
1771
  chunks.push(delta.text);
1453
- else if (delta.type === 'finish' && delta.reason?.kind === 'max-tokens')
1454
- truncated = true;
1772
+ else if (delta.type === 'finish') {
1773
+ if (delta.reason?.kind === 'max-tokens')
1774
+ truncated = true;
1775
+ addUsage(usageAcc, delta.usage);
1776
+ }
1455
1777
  }
1456
1778
  }
1457
1779
  catch (error) {
1458
1780
  ctx.logger?.warn(`verbatim-compaction: extraction call failed for ${parts.length} slot(s): ${String(error)}`);
1459
- return { blocks: out, truncated: false };
1781
+ const abortedOrTimedOut = call.signal.aborted || signal?.aborted === true;
1782
+ return { blocks: out, truncated: false, transportError: abortedOrTimedOut };
1783
+ }
1784
+ finally {
1785
+ call.dispose();
1460
1786
  }
1461
1787
  const answer = chunks.join('').trim();
1462
1788
  if (answer.length === 0)
1463
1789
  return { blocks: out, truncated };
1464
1790
  return { blocks: parseExtraction(answer), truncated };
1465
1791
  }
1792
+ /** Validate a deserialized extraction object before hydrating from disk cache. */
1793
+ function isValidExtraction(value) {
1794
+ if (value === null || typeof value !== 'object')
1795
+ return false;
1796
+ const rec = value;
1797
+ const isStringArray = (v) => Array.isArray(v) && v.every((item) => typeof item === 'string');
1798
+ if (!isStringArray(rec['did']) || !isStringArray(rec['concluded']) || !isStringArray(rec['overturned'])) {
1799
+ return false;
1800
+ }
1801
+ const asked = rec['asked'];
1802
+ if (!Array.isArray(asked))
1803
+ return false;
1804
+ return asked.every((entry) => {
1805
+ if (entry === null || typeof entry !== 'object')
1806
+ return false;
1807
+ const pair = entry;
1808
+ return typeof pair['question'] === 'string' && isStringArray(pair['options']);
1809
+ });
1810
+ }
1811
+ /** Trim a plain record to its newest `max` entries in insertion order. */
1812
+ function trimRecord(record, max) {
1813
+ const entries = Object.entries(record);
1814
+ if (entries.length <= max)
1815
+ return record;
1816
+ return Object.fromEntries(entries.slice(-max));
1817
+ }
1466
1818
  /**
1467
1819
  * Extractive compaction backend: verbatim user prose, one model call per batch,
1468
1820
  * call.
@@ -1491,13 +1843,95 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1491
1843
  */
1492
1844
  extractionCache = new Map();
1493
1845
  /**
1494
- * Folded text, keyed by provider, model and a hash of the material folded.
1495
- *
1496
- * Same reasoning as `extractionCache`: the fold is a model call over material
1497
- * rebuilt from the raw log on every compaction, so the same run of old turns is
1498
- * re-folded on every later compaction unless it is remembered.
1846
+ * Folded text, keyed by effective provider, model and a hash of the material folded.
1499
1847
  */
1500
1848
  condensedCache = new Map();
1849
+ /** Session ids whose on-disk cache has already been hydrated into memory. */
1850
+ hydratedSessions = new Set();
1851
+ hydrateDiskCache(sessionId) {
1852
+ if (this.hydratedSessions.has(sessionId))
1853
+ return;
1854
+ this.hydratedSessions.add(sessionId);
1855
+ const dir = resolveCacheDir();
1856
+ if (dir === undefined)
1857
+ return;
1858
+ try {
1859
+ const raw = readFileSync(cacheFilePath(dir, sessionId), 'utf8');
1860
+ const parsed = JSON.parse(raw);
1861
+ if (parsed.v !== 1)
1862
+ return;
1863
+ if (parsed.extraction !== undefined && typeof parsed.extraction === 'object' && parsed.extraction !== null) {
1864
+ for (const [key, value] of Object.entries(parsed.extraction)) {
1865
+ if (isValidExtraction(value)) {
1866
+ boundedCacheSet(this.extractionCache, key, value, EXTRACTION_CACHE_MAX);
1867
+ }
1868
+ }
1869
+ }
1870
+ if (parsed.condensed !== undefined && typeof parsed.condensed === 'object' && parsed.condensed !== null) {
1871
+ for (const [key, value] of Object.entries(parsed.condensed)) {
1872
+ if (typeof value === 'string' && value.length > 0) {
1873
+ boundedCacheSet(this.condensedCache, key, value, CONDENSED_CACHE_MAX);
1874
+ }
1875
+ }
1876
+ }
1877
+ }
1878
+ catch {
1879
+ // Cache miss or corrupt file — start cold without failing compaction.
1880
+ }
1881
+ }
1882
+ persistDiskCache(sessionId, newExtractions, newCondensed) {
1883
+ if (newExtractions.size === 0 && newCondensed.size === 0)
1884
+ return;
1885
+ const dir = resolveCacheDir();
1886
+ if (dir === undefined)
1887
+ return;
1888
+ try {
1889
+ mkdirSync(dir, { recursive: true });
1890
+ const target = cacheFilePath(dir, sessionId);
1891
+ let payload = { v: 1, extraction: {}, condensed: {} };
1892
+ try {
1893
+ const existing = JSON.parse(readFileSync(target, 'utf8'));
1894
+ if (existing.v === 1) {
1895
+ const validExtraction = {};
1896
+ if (existing.extraction !== undefined && typeof existing.extraction === 'object' && existing.extraction !== null) {
1897
+ for (const [key, value] of Object.entries(existing.extraction)) {
1898
+ if (isValidExtraction(value))
1899
+ validExtraction[key] = value;
1900
+ }
1901
+ }
1902
+ const validCondensed = {};
1903
+ if (existing.condensed !== undefined && typeof existing.condensed === 'object' && existing.condensed !== null) {
1904
+ for (const [key, value] of Object.entries(existing.condensed)) {
1905
+ if (typeof value === 'string' && value.length > 0)
1906
+ validCondensed[key] = value;
1907
+ }
1908
+ }
1909
+ payload = { v: 1, extraction: validExtraction, condensed: validCondensed };
1910
+ }
1911
+ }
1912
+ catch {
1913
+ // Fresh cache file.
1914
+ }
1915
+ payload.extraction ??= {};
1916
+ payload.condensed ??= {};
1917
+ for (const [key, value] of newExtractions) {
1918
+ delete payload.extraction[key];
1919
+ payload.extraction[key] = value;
1920
+ }
1921
+ for (const [key, value] of newCondensed) {
1922
+ delete payload.condensed[key];
1923
+ payload.condensed[key] = value;
1924
+ }
1925
+ payload.extraction = trimRecord(payload.extraction, EXTRACTION_CACHE_MAX);
1926
+ payload.condensed = trimRecord(payload.condensed, CONDENSED_CACHE_MAX);
1927
+ const tmp = `${target}.${process.pid}.${Date.now()}.${randomBytes(6).toString('hex')}.tmp`;
1928
+ writeFileSync(tmp, JSON.stringify(payload), 'utf8');
1929
+ renameSync(tmp, target);
1930
+ }
1931
+ catch (error) {
1932
+ this.ctx.logger?.warn(`verbatim-compaction: failed to persist cache for ${sessionId}: ${String(error)}`);
1933
+ }
1934
+ }
1501
1935
  /**
1502
1936
  * Build the replacement checkpoint content from the session log.
1503
1937
  *
@@ -1511,10 +1945,11 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1511
1945
  * @param input - replayed conversation prefix the base class is shadowing.
1512
1946
  * @param agent - owner of the session being compacted.
1513
1947
  * @param signal - cancellation forwarded to the extraction and fold calls.
1514
- * @returns text summary blocks, unmarked by any LLM call.
1948
+ * @returns text summary blocks, route metadata, and aggregated LLM usage.
1515
1949
  */
1516
1950
  async summarize(input, agent, signal) {
1517
1951
  const session = agent.session;
1952
+ this.hydrateDiskCache(session.id);
1518
1953
  const shadowed = shadowedSeqs(session, input);
1519
1954
  const shadowedSet = new Set(shadowed);
1520
1955
  const retained = new Set(session.surface.nodes.filter((seq) => !shadowedSet.has(seq)));
@@ -1528,12 +1963,15 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1528
1963
  // size independent of history length; the guard bound only exists for the
1529
1964
  // degenerate case of a span smaller than the ceiling.
1530
1965
  const budget = Math.max(0, Math.min(DIGEST_TOKEN_CEILING, shadowedPrice - FRAME_TOKENS - SHRINK_MARGIN_TOKENS));
1531
- const extracted = await this.extractAll(source, agent, signal, getLiveConfig());
1532
- // Fold the oldest turns up only when the plain digest overflows. The fold is an
1533
- // LLM call, so a digest that already fits must not pay for one.
1966
+ const override = getLiveConfig();
1967
+ const usageAcc = createUsageAccumulator();
1968
+ const extracted = await this.extractAll(source, agent, signal, override, usageAcc);
1969
+ // Check overflow against the *unclipped* digest. Measuring `renderDigest(source, budget, extracted)`
1970
+ // was always <= `budget * 4` because `renderDigest` clips to budget, making `condenseOldest` dead code.
1534
1971
  let condensed;
1535
- if (renderDigest(source, budget, extracted).length > budget * 4) {
1536
- condensed = await this.condenseOldest(source, extracted, agent, budget, signal, getLiveConfig());
1972
+ const unclippedLength = renderDigest(source, Math.floor(Number.MAX_SAFE_INTEGER / 4), extracted).length;
1973
+ if (unclippedLength > budget * 4) {
1974
+ condensed = await this.condenseOldest(source, extracted, agent, budget, signal, override, usageAcc);
1537
1975
  }
1538
1976
  // The fold path returns its digest whole, so it can still overflow when every
1539
1977
  // group has been folded and the user lines alone are too long. The budget is a
@@ -1546,58 +1984,34 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1546
1984
  + `(${text.length} > ${budget * 4} chars), falling back to the graded ladder`);
1547
1985
  text = renderDigest(source, budget, extracted);
1548
1986
  }
1987
+ const effective = resolveEffectiveRoute(agent, override);
1549
1988
  const route = session.requestHeader()?.config;
1989
+ const usage = toTokenUsage(usageAcc);
1550
1990
  return {
1551
1991
  summary: [{ type: 'text', text }],
1552
- provider: route?.provider ?? agent.options.provider ?? 'verbatim',
1553
- model: route?.model ?? agent.options.model ?? 'digest',
1992
+ provider: effective?.provider ?? route?.provider ?? agent.options.provider ?? 'verbatim',
1993
+ model: effective?.model ?? route?.model ?? agent.options.model ?? 'digest',
1994
+ ...(usage === undefined ? {} : { usage }),
1554
1995
  };
1555
1996
  }
1556
1997
  /**
1557
1998
  * Fold the oldest turns into condensed blocks until the digest fits.
1558
1999
  *
1559
- * Only reached when the plain digest overflows `budget`. The oldest turns are
1560
- * the right ones to fold: they describe work already superseded, while the
1561
- * newest are what the next request depends on.
1562
- *
1563
- * Linear in groups, not bisected: a fold is not monotone in how much is folded —
1564
- * a paragraph's length depends on what the model chose to keep — so there is no
1565
- * boundary to bisect. The walk stops at the first size that fits, which is the
1566
- * fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
1567
- * consecutive sections, so the number of calls is proportional to the digest,
1568
- * not to the number of turns.
1569
- *
1570
- * Cached by content, like the extraction: the same prefix of turns folds to the
1571
- * same text, and a later compaction re-reads the same history.
1572
- *
1573
- * @param source - digest source events, in log order.
1574
- * @param extracted - per-turn extractions already computed.
1575
- * @param agent - owner of the session being compacted.
1576
- * @param budget - token budget the digest must fit.
1577
- * @param signal - cancellation forwarded to every call.
1578
- * @returns condensed blocks keyed by the `turnKey` of the first covered section.
2000
+ * Only reached when the unclipped plain digest overflows `budget`. The oldest
2001
+ * turns are the right ones to fold: they describe work already superseded, while
2002
+ * the newest are what the next request depends on.
1579
2003
  */
1580
- async condenseOldest(source, extracted, agent, budget, signal, override) {
2004
+ async condenseOldest(source, extracted, agent, budget, signal, override, usageAcc) {
1581
2005
  const sections = withExtractions(buildSections(source), extracted);
1582
2006
  const budgetChars = budget * 4;
1583
2007
  const out = new Map();
1584
- // One group per iteration, oldest first, checking after each whether the digest
1585
- // fits. Single loop, `start` monotone: the earlier two-level form advanced its
1586
- // inner start from `out.size`, so a group whose call failed was retried on every
1587
- // outer pass (45 calls instead of 4 with the model down), and the outer bound
1588
- // `covered < sections.length` stopped one group short of the end — at 700
1589
- // sections the last 100 were never folded, and at 100 or fewer the loop body
1590
- // never ran at all.
1591
2008
  for (const start of foldGroupStarts(sections.length)) {
1592
2009
  if (signal?.aborted === true)
1593
2010
  break;
1594
2011
  const group = sections.slice(start, start + CONDENSE_GROUP);
1595
2012
  if (group.length === 0)
1596
2013
  continue;
1597
- const text = await this.condenseGroup(group, agent, signal, override);
1598
- // A failed group is skipped rather than retried: the next group still buys
1599
- // room, and retrying the same material against a failing model only spends
1600
- // calls. The remaining turns keep their own blocks either way.
2014
+ const text = await this.condenseGroup(group, agent, signal, override, usageAcc);
1601
2015
  if (text === undefined)
1602
2016
  continue;
1603
2017
  out.set(turnKey(start, 0), { text, covers: group.length });
@@ -1608,19 +2022,8 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1608
2022
  }
1609
2023
  /**
1610
2024
  * Hand one group of turns to the model and return its folded text.
1611
- *
1612
- * @param group - consecutive sections to fold into one paragraph.
1613
- * @param agent - owner of the session being compacted.
1614
- * @param signal - cancellation forwarded to the call.
1615
- * @returns the folded paragraph, or undefined when the call produced nothing.
1616
2025
  */
1617
- async condenseGroup(group, agent, signal, override) {
1618
- // Both sources, because a turn has one or the other: extraction succeeds and
1619
- // the block replaces the prose, or it fails and the verbatim prose is what the
1620
- // digest shows. Reading only `extracted` meant a run of turns whose extraction
1621
- // failed contributed nothing — and because the fold then still replaced them,
1622
- // their content vanished from the digest entirely rather than merely being
1623
- // summarised badly.
2026
+ async condenseGroup(group, agent, signal, override, usageAcc) {
1624
2027
  const material = group
1625
2028
  .map((section) => section.turns
1626
2029
  .map((turn) => {
@@ -1636,115 +2039,99 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1636
2039
  const llm = this.ctx.llm;
1637
2040
  if (llm === undefined)
1638
2041
  return undefined;
1639
- const route = agent.session.requestHeader()?.config;
1640
- const provider = route?.provider ?? agent.options.provider;
1641
- const model = route?.model ?? agent.options.model;
1642
- if (provider === undefined || model === undefined)
2042
+ const effective = resolveEffectiveRoute(agent, override);
2043
+ if (effective === undefined)
1643
2044
  return undefined;
1644
- const key = `${provider}:${model}:${hashText(material)}`;
1645
- const cached = this.condensedCache.get(key);
2045
+ const key = `${effective.provider}:${effective.model}:${hashText(material)}`;
2046
+ const cached = boundedCacheGet(this.condensedCache, key);
1646
2047
  if (cached !== undefined)
1647
2048
  return cached;
1648
- const text = await condenseOnce(this.ctx, agent, material, signal, override);
2049
+ const text = await condenseOnce(this.ctx, agent, material, signal, override, usageAcc);
1649
2050
  if (text === undefined)
1650
2051
  return undefined;
1651
- this.condensedCache.set(key, text);
2052
+ boundedCacheSet(this.condensedCache, key, text, CONDENSED_CACHE_MAX);
2053
+ this.persistDiskCache(agent.session.id, new Map(), new Map([[key, text]]));
1652
2054
  return text;
1653
2055
  }
1654
2056
  /**
1655
- * Run the extraction for every turn in the digest source.
1656
- *
1657
- * Sequential rather than parallel: these calls share the session's routed
1658
- * model and the provider's KV cache, and firing a dozen at once would both
1659
- * multiply the cost and defeat the cache the host's own summarizer relies on.
1660
- *
1661
- * A turn that fails is simply absent from the output; one bad turn must not
1662
- * drop the extraction for the rest.
1663
- *
1664
- * Batched rather than one call per turn. One call per turn meant 131 calls on a
1665
- * 122-turn session, each with its own round trip: a measured extraction budget
1666
- * of 131 x 400 tokens could on its own exceed the whole digest ceiling. A
1667
- * batch of `TURNS_PER_CALL` turns costs one round trip and shares the prompt
1668
- * prefix, so the provider's KV cache is reused rather than rebuilt.
2057
+ * Run the extraction for every section in the digest source.
1669
2058
  *
1670
- * @param source - digest source events, in log order.
1671
- * @param agent - owner of the session being compacted.
1672
- * @param signal - cancellation forwarded to every call.
1673
- * @returns turn number to extracted block, omitting turns that yielded none.
2059
+ * Uses `buildSectionsWithEvents` as the single source of truth so slot keys can
2060
+ * never drift out of alignment with rendered sections. Uncached batches execute
2061
+ * with bounded concurrency (`EXTRACT_CONCURRENCY`), and newly extracted entries
2062
+ * are persisted to the per-session disk cache.
1674
2063
  */
1675
- async extractAll(source, agent, signal, override) {
1676
- // Walk the same sections the renderer will use, so a key addresses the exact
1677
- // slot the block will be written into. Grouping by turn number instead lost
1678
- // blocks whenever the log reused a number.
1679
- // Partition the source into the same sections `buildSections` produced, then
1680
- // hand each section to its slot. A slot is a section, not a single message:
1681
- // the earlier version stopped at the first message, so a turn with 69
1682
- // assistant messages and 112 tool calls contributed 2 events out of 164 and
1683
- // the extractor reported "no work observed" for a turn that did plenty.
1684
- const sections = buildSections(source);
1685
- // Attribute events to sections by replaying the same walk `buildSections`
1686
- // does, so the two can never disagree about where a section starts. An
1687
- // independent scan drifted by one section on the fixture: `buildSections`
1688
- // opens a new section for an unclosed turn without consuming a user message.
1689
- const grouped = [];
1690
- let sectionIndex = -1;
1691
- const openedObjectives = new Set();
1692
- for (const event of source) {
1693
- const objective = goalObjective(event);
1694
- let startsSection = false;
1695
- if (objective !== undefined) {
1696
- if (!openedObjectives.has(objective)) {
1697
- openedObjectives.add(objective);
1698
- startsSection = true;
1699
- }
1700
- }
1701
- else if (event.type === 'user/message' && !isInjection(event) && !isCheckpoint(event)) {
1702
- startsSection = true;
1703
- }
1704
- if (startsSection) {
1705
- sectionIndex += 1;
1706
- grouped[sectionIndex] = [];
1707
- }
1708
- if (sectionIndex >= 0)
1709
- grouped[sectionIndex]?.push(event);
1710
- }
1711
- // One slot per section, addressed to the section's first turn.
1712
- //
1713
- // The material is about what the section did as a whole, so handing it to
1714
- // every turn in the section made the model answer twice with the same block:
1715
- // a real section holding two turns produced two identical `## Concluded`
1716
- // bodies plus `(duplicate of SLOT 4:0)` placeholders in the digest. The extra
1717
- // turns keep their prose and their own headings; only the first carries the
1718
- // section's extraction.
2064
+ async extractAll(source, agent, signal, override, usageAcc) {
2065
+ const { sections, sectionEvents } = buildSectionsWithEvents(source);
2066
+ const singleSection = sections.length === 1;
1719
2067
  const slots = [];
1720
2068
  for (const [sectionIndex, section] of sections.entries()) {
1721
2069
  const first = section.turns[0];
1722
2070
  if (first === undefined)
1723
2071
  continue;
1724
- slots.push({ key: turnKey(sectionIndex, 0), turn: first.turn, events: grouped[sectionIndex] ?? [] });
2072
+ const events = sectionEvents[sectionIndex] ?? [];
2073
+ let includeToolResults = false;
2074
+ if (singleSection) {
2075
+ let toolCallCount = 0;
2076
+ let proseChars = 0;
2077
+ for (const ev of events) {
2078
+ if (ev.type !== 'assistant/message')
2079
+ continue;
2080
+ toolCallCount += toolCallsOf(ev).length;
2081
+ proseChars += textOf(ev).length;
2082
+ }
2083
+ if (toolCallCount >= SINGLE_TURN_TOOL_HEAVY_CALLS && proseChars <= SINGLE_TURN_TOOL_HEAVY_PROSE_MAX) {
2084
+ includeToolResults = true;
2085
+ }
2086
+ }
2087
+ slots.push({
2088
+ key: turnKey(sectionIndex, 0),
2089
+ turn: first.turn,
2090
+ events,
2091
+ ...(includeToolResults ? { includeToolResults: true } : {}),
2092
+ });
1725
2093
  }
2094
+ const effective = resolveEffectiveRoute(agent, override);
2095
+ const routePrefix = effective === undefined ? '' : `${effective.provider}:${effective.model}:`;
2096
+ const cacheKeyFor = (slot) => `${routePrefix}${slot.includeToolResults === true ? 'tr:' : ''}${materialKey(slot.events, slot.includeToolResults === true ? { includeToolResults: true } : undefined)}`;
1726
2097
  const extracted = new Map();
1727
2098
  const missing = [];
1728
2099
  for (const slot of slots) {
1729
- const cached = this.extractionCache.get(materialKey(slot.events));
2100
+ const cached = boundedCacheGet(this.extractionCache, cacheKeyFor(slot));
1730
2101
  if (cached === undefined)
1731
2102
  missing.push(slot);
1732
2103
  else
1733
2104
  extracted.set(slot.key, cached);
1734
2105
  }
2106
+ const batches = [];
1735
2107
  for (let index = 0; index < missing.length; index += TURNS_PER_CALL) {
1736
- if (signal?.aborted === true)
1737
- break;
1738
- const batch = missing.slice(index, index + TURNS_PER_CALL);
1739
- const blocks = await extractBatch(this.ctx, agent, batch, signal, override);
1740
- for (const slot of batch) {
1741
- const block = blocks.get(slot.key);
1742
- if (block === undefined)
1743
- continue;
1744
- extracted.set(slot.key, block);
1745
- this.extractionCache.set(materialKey(slot.events), block);
1746
- }
2108
+ batches.push(missing.slice(index, index + TURNS_PER_CALL));
1747
2109
  }
2110
+ const newlyExtracted = new Map();
2111
+ let nextBatch = 0;
2112
+ const workerCount = Math.min(EXTRACT_CONCURRENCY, batches.length);
2113
+ const worker = async () => {
2114
+ while (nextBatch < batches.length) {
2115
+ if (signal?.aborted === true)
2116
+ break;
2117
+ const batch = batches[nextBatch];
2118
+ nextBatch += 1;
2119
+ if (batch === undefined)
2120
+ break;
2121
+ const blocks = await extractBatch(this.ctx, agent, batch, signal, override, usageAcc);
2122
+ for (const slot of batch) {
2123
+ const block = blocks.get(slot.key);
2124
+ if (block === undefined)
2125
+ continue;
2126
+ extracted.set(slot.key, block);
2127
+ const ckey = cacheKeyFor(slot);
2128
+ boundedCacheSet(this.extractionCache, ckey, block, EXTRACTION_CACHE_MAX);
2129
+ newlyExtracted.set(ckey, block);
2130
+ }
2131
+ }
2132
+ };
2133
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
2134
+ this.persistDiskCache(agent.session.id, newlyExtracted, new Map());
1748
2135
  return extracted;
1749
2136
  }
1750
2137
  }