@logictan/dsh-verbatim-compaction 0.13.1 → 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,17 +30,15 @@
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
- import Schema from '@deepseek-ai/schemastery';
39
+ import { getLiveConfig } from './purpose.js';
36
40
  /** Cordis companion plugin name. Must equal this plugin's `cordis.patch.yml` row id. */
37
41
  export const name = 'verbatim-compaction';
38
- /** Three editable scalars; empty strings mean "follow the chat model". */
39
- export const OVERRIDE_FIELDS = {
40
- provider: Schema.string().default('').volatile(),
41
- model: Schema.string().default('').volatile(),
42
- reasoningEffort: Schema.string().default('').volatile(),
43
- };
44
42
  /** A provider/model override takes effect only as a complete pair. */
45
43
  export function pairedRouteOf(config) {
46
44
  const provider = config?.provider?.get().trim();
@@ -83,8 +81,11 @@ export function applyPurposeOverride(options, config, cheapest) {
83
81
  * per turn, and leaves the checkpoint far below any measured threshold.
84
82
  */
85
83
  export const DIGEST_TOKEN_CEILING = 20000;
86
- /** Framing overhead `frameSummary` adds: preamble plus both tags, 341 chars = 86 tokens. */
87
- 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;
88
89
  /** Safety margin below the shrink guard, in tokens. */
89
90
  const SHRINK_MARGIN_TOKENS = 512;
90
91
  /**
@@ -101,6 +102,37 @@ const SHRINK_MARGIN_TOKENS = 512;
101
102
  const USER_BUDGET_SHARE = 0.9;
102
103
  /** Tool names whose call arguments name a written path. */
103
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
+ }
104
136
  /** The message an event derives to, or null when it derives to none. */
105
137
  function messageOf(event) {
106
138
  switch (event.type) {
@@ -155,15 +187,28 @@ function isInjection(event) {
155
187
  * @param event - any event; non-goal events yield undefined.
156
188
  * @returns the objective text, or undefined.
157
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;
158
192
  function goalObjective(event) {
159
193
  if (sourceKind(event) !== 'goal')
160
194
  return undefined;
161
195
  const text = textOf(event);
162
- const match = /Objective:\s*"([\s\S]*?)"/.exec(text);
163
- // The objective arrives with its newlines already escaped inside the JSON
164
- // string, so a seven-item list reaches the digest as one unreadable line.
165
- const objective = (match?.[1] ?? '').replace(/\\n/g, '\n').trim();
166
- 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;
167
212
  }
168
213
  /** Whether this user message is a compaction checkpoint written by a backend. */
169
214
  function isCheckpoint(event) {
@@ -314,10 +359,81 @@ const EXTRACT_INSTRUCTION = [
314
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.',
315
360
  // The reply is the next turn's `## user` line, already verbatim in the digest.
316
361
  // Asking for it here printed the same sentence twice.
317
- "- 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.",
318
363
  '',
319
364
  'Write strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
320
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
+ }
321
437
  /**
322
438
  * Parse the model's JSON reply into per-slot extractions.
323
439
  *
@@ -331,34 +447,29 @@ const EXTRACT_INSTRUCTION = [
331
447
  */
332
448
  export function parseExtraction(answer) {
333
449
  const out = new Map();
334
- // Models wrap JSON in a fence often enough that stripping it is not defensive
335
- // programming but the common case.
336
- const body = answer.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '');
337
- const start = body.indexOf('{');
338
- const end = body.lastIndexOf('}');
339
- if (start < 0 || end <= start)
340
- return out;
341
- let parsed;
342
- try {
343
- parsed = JSON.parse(body.slice(start, end + 1));
344
- }
345
- catch {
346
- return out;
347
- }
450
+ const parsed = extractJsonPayload(answer);
348
451
  if (typeof parsed !== 'object' || parsed === null)
349
452
  return out;
350
- const slots = parsed['slots'];
453
+ const slots = Array.isArray(parsed)
454
+ ? parsed
455
+ : parsed['slots'];
351
456
  if (!Array.isArray(slots))
352
457
  return out;
353
- const strings = (value) => (Array.isArray(value)
354
- ? 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')
355
466
  .map((item) => item.replace(/\s+/g, ' ').trim())
356
467
  .filter((item) => item.length > 0)
357
468
  // A field is a list, so "nothing here" is an empty list. Models still write a
358
469
  // placeholder often enough that dropping it is worth one test.
359
- .filter((item) => !/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有)$/i.test(item))
360
- .filter((item) => !/^(?:未提问|无提问|没有提问|no questions? (?:were |was )?asked|none asked)[。.!!]*$/i.test(item))
361
- : []);
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
+ };
362
473
  // Asked is a list of objects, not of strings: a question without its options
363
474
  // turns the user's `1` into a number that selects nothing.
364
475
  const pairs = (value) => (Array.isArray(value)
@@ -376,9 +487,11 @@ export function parseExtraction(answer) {
376
487
  ? record['options']
377
488
  .filter((option) => typeof option === 'string')
378
489
  // The renderer supplies the numbering, so a model that echoes the source
379
- // list's own `1.` would print `1. 1. …`. Stripped here rather than asked
380
- // for in the prompt alone: three of five real runs kept it.
381
- .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())
382
495
  .filter((option) => option.length > 0)
383
496
  : [];
384
497
  return [{ question, options }];
@@ -388,8 +501,8 @@ export function parseExtraction(answer) {
388
501
  if (typeof slot !== 'object' || slot === null)
389
502
  continue;
390
503
  const record = slot;
391
- const key = record['key'];
392
- if (typeof key !== 'string' || key.length === 0)
504
+ const key = normalizeSlotKey(record['key']);
505
+ if (key.length === 0)
393
506
  continue;
394
507
  out.set(key, {
395
508
  did: strings(record['did']),
@@ -404,10 +517,12 @@ export function parseExtraction(answer) {
404
517
  * Render one extraction as the digest block, headings included.
405
518
  *
406
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).
407
522
  * @returns markdown with a heading per non-empty field; empty string when every
408
523
  * field is empty.
409
524
  */
410
- export function renderExtractionBlock(extraction, level = 3) {
525
+ export function renderExtractionBlock(extraction, level = 3, includeAsked = true) {
411
526
  if (extraction === undefined)
412
527
  return '';
413
528
  const lines = [];
@@ -416,11 +531,6 @@ export function renderExtractionBlock(extraction, level = 3) {
416
531
  return;
417
532
  lines.push(`## ${heading}`, ...items.map((item) => `- ${item}`));
418
533
  };
419
- // `level` is how many of the graded sections survive: 3 keeps all, 2 drops
420
- // Overturned, 1 keeps only Did, 0 keeps only Asked. Asked is never dropped by
421
- // the level because it is the one section nothing later can rebuild — the
422
- // reply arrives in the next turn, but the question and its options exist only
423
- // here. See `renderDigest` for why the ladder exists at all.
424
534
  if (level >= 1)
425
535
  section('Did', extraction.did);
426
536
  if (level >= 2)
@@ -429,13 +539,10 @@ export function renderExtractionBlock(extraction, level = 3) {
429
539
  section('Overturned', extraction.overturned);
430
540
  // Asked goes last and its options are listed under it, so the user's reply — the
431
541
  // next `## user` line — lands directly under the list it chose from.
432
- if (extraction.asked.length > 0) {
542
+ if (includeAsked && extraction.asked.length > 0) {
433
543
  lines.push('## Asked');
434
544
  for (const pair of extraction.asked) {
435
545
  lines.push(`- ${pair.question}`);
436
- // Indented under the question so a reader cannot mistake an option for a
437
- // separate question, and numbered so the reply's digit has something to
438
- // point at.
439
546
  for (const [index, option] of pair.options.entries()) {
440
547
  lines.push(` ${index + 1}. ${option}`);
441
548
  }
@@ -465,18 +572,10 @@ const TURNS_PER_CALL = 8;
465
572
  /**
466
573
  * Sections folded into one condensed block when the digest overflows.
467
574
  *
468
- * Each fold is a model call, so the group size trades calls against compression.
469
- * Simulated on a 700- and a 1200-turn digest at the measured 8.2% fold ratio:
470
- *
471
- * group 20 → 19 and 52 calls
472
- * group 50 → 8 and 21 calls
473
- * group 100 → 4 and 11 calls
474
- *
475
- * Larger groups fold more text per call, which is also where the ratio holds
476
- * best: a 20-section group is small enough that the model's own paragraph is a
477
- * 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.
478
577
  */
479
- const CONDENSE_GROUP = 100;
578
+ export const CONDENSE_GROUP = 30;
480
579
  /**
481
580
  * Output tokens allowed for one condensation call.
482
581
  *
@@ -593,18 +692,38 @@ export function collectHints(events) {
593
692
  }
594
693
  return lines.join('\n');
595
694
  }
596
- /** The `path` argument of one tool call, when the call carries one. */
597
- 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
+ };
598
705
  try {
599
706
  const parsed = JSON.parse(argumentsJson);
600
707
  if (typeof parsed !== 'object' || parsed === null)
601
- return undefined;
602
- const path = parsed.path;
603
- 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
+ }
604
722
  }
605
723
  catch {
606
- return undefined;
724
+ return paths;
607
725
  }
726
+ return paths;
608
727
  }
609
728
  /** The turn number an event belongs to, when the log records one. */
610
729
  function turnOf(event) {
@@ -613,89 +732,70 @@ function turnOf(event) {
613
732
  }
614
733
  /** A fresh, empty turn accumulator. */
615
734
  function emptyTurn(turn, fromRequest = false) {
616
- return { turn, fromRequest, user: [], assistant: [], tools: new Map(), writes: [], answered: [] };
735
+ return { turn, fromRequest, user: [], assistant: [], writes: [], answered: [] };
617
736
  }
618
737
  /**
619
- * Group append-origin surface events into per-turn digest material.
620
- *
621
- * A section starts at each non-injected user message; assistant-only runs
622
- * before the first user message join the first section. Turn numbers come from
623
- * the log: `turn/start` carries `{turn}` and `assistant/message` carries
624
- * `data.turn`. A user message carries no turn of its own, so it inherits the
625
- * last one seen.
626
- *
627
- * @param events - the digest source in log order.
628
- * @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.
629
741
  */
630
- export function buildSections(events) {
742
+ function buildSectionsWithEvents(events) {
631
743
  const sections = [];
744
+ const sectionEvents = [];
632
745
  let current;
746
+ let currentEvents;
633
747
  let currentTurn;
634
748
  let lastTurn;
749
+ const startSection = () => {
750
+ current = { turns: [] };
751
+ currentEvents = [];
752
+ sections.push(current);
753
+ sectionEvents.push(currentEvents);
754
+ };
635
755
  const openTurn = (turn, fromRequest = false) => {
636
- if (current === undefined) {
637
- current = { turns: [] };
638
- sections.push(current);
639
- }
756
+ if (current === undefined)
757
+ startSection();
640
758
  const next = emptyTurn(turn, fromRequest);
641
759
  current.turns.push(next);
642
760
  if (turn !== undefined)
643
761
  lastTurn = turn;
644
762
  return next;
645
763
  };
646
- // One objective per section, and never twice: the host re-injects the same
647
- // objective on every round, so recording each copy would repeat it dozens of
648
- // times across a long autonomous run.
649
764
  const recordedObjectives = new Set();
650
- // Question id to question text, for every `ask_user_question` call seen so far.
651
- // The answer batch names questions by id only, and an id like `quota` says
652
- // nothing on its own.
653
765
  const questionTexts = new Map();
654
- // Call ids of this turn's `ask_user_question` calls. A result is an answer only
655
- // when its own call asked something: without this every result in the log was
656
- // JSON-parsed (536 KB across 157 results in one measured session, the largest
657
- // 49.9 KB) and any output that happened to look like an answer batch — a file
658
- // dump, a test fixture — would be recorded as something the user chose.
659
766
  const questionCallIds = new Set();
660
767
  for (const event of events) {
661
768
  if (event.type === 'turn/start') {
662
769
  const turn = turnOf(event);
663
770
  if (turn !== undefined)
664
771
  lastTurn = turn;
772
+ currentEvents?.push(event);
665
773
  continue;
666
774
  }
667
- const objective = goalObjective(event);
668
- if (objective !== undefined) {
669
- if (current === undefined) {
670
- current = { turns: [] };
671
- sections.push(current);
672
- }
673
- 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.
674
780
  continue;
781
+ }
675
782
  recordedObjectives.add(objective);
676
- // A goal round opens a section like a user request does, and its objective
677
- // takes the user slot: it is the request this turn serves.
678
- current = { turns: [] };
679
- sections.push(current);
783
+ startSection();
680
784
  currentTurn = openTurn(turnOf(event) ?? lastTurn, false);
681
785
  currentTurn.user.push(objective);
786
+ currentEvents.push(event);
682
787
  continue;
683
788
  }
684
789
  if (event.type === 'tool/result') {
685
- // An answered question arrives as this call's own result. The call's
686
- // arguments named the questions; the result carries the choices.
790
+ currentEvents?.push(event);
687
791
  const callId = messageOf(event)?.toolCallId;
688
792
  if (callId === undefined || !questionCallIds.has(callId) || currentTurn === undefined)
689
793
  continue;
690
794
  currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
691
795
  continue;
692
796
  }
693
- // The host answers a question two ways. Inside the waiting window the answer
694
- // is the tool result above; after the call already returned its pending
695
- // notice, it is a `user/message` whose source kind is `user-question-reply`
696
- // and whose body is the same answer batch. That message is not a new request,
697
- // so it is read here rather than opening a section.
698
797
  if (sourceKind(event) === 'user-question-reply') {
798
+ currentEvents?.push(event);
699
799
  if (currentTurn !== undefined)
700
800
  currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
701
801
  continue;
@@ -706,35 +806,21 @@ export function buildSections(events) {
706
806
  continue;
707
807
  const eventTurn = turnOf(event) ?? lastTurn;
708
808
  if (event.type === 'user/message') {
709
- // A user message opens a new section, not merely a new turn: sections are
710
- // what the digest headings delimit, and one section per user request is
711
- // what makes the digest readable after a hundred turns.
712
- current = { turns: [] };
713
- sections.push(current);
809
+ startSection();
714
810
  currentTurn = openTurn(eventTurn, true);
715
811
  const text = textOf(event);
716
812
  if (text.length > 0)
717
813
  currentTurn.user.push(text);
814
+ currentEvents.push(event);
718
815
  continue;
719
816
  }
720
- // A user message carries no `turn` field while the reply carries one, so a
721
- // plain turn-number comparison opened a second turn for the same request: every
722
- // real section ended up with an empty request turn plus a reply turn holding no
723
- // user text, and the digest printed `## user` and `### assistant` twice.
724
- //
725
- // The turn number only separates work when the current turn already holds some,
726
- // i.e. when the log really moved on to a later turn.
727
- // A section is one request, so it is one turn. The log keeps advancing the turn
728
- // number inside a single request (7 assistant messages as turn 2, then 9 more as
729
- // turn 3), and splitting on the number gave every section a second turn whose
730
- // block was the tail of the same request's prose.
731
817
  if (currentTurn === undefined)
732
818
  currentTurn = openTurn(eventTurn ?? lastTurn);
819
+ currentEvents?.push(event);
733
820
  const text = textOf(event);
734
821
  if (text.length > 0)
735
822
  currentTurn.assistant.push(text);
736
823
  for (const call of toolCallsOf(event)) {
737
- currentTurn.tools.set(call.name, (currentTurn.tools.get(call.name) ?? 0) + 1);
738
824
  if (call.name === 'ask_user_question') {
739
825
  for (const [id, question] of questionTextsOf(call.arguments))
740
826
  questionTexts.set(id, question);
@@ -743,12 +829,22 @@ export function buildSections(events) {
743
829
  }
744
830
  if (!WRITE_TOOLS.has(call.name))
745
831
  continue;
746
- const path = pathArgumentOf(call.arguments);
747
- if (path !== undefined && !currentTurn.writes.includes(path))
748
- 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
+ }
749
836
  }
750
837
  }
751
- 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;
752
848
  }
753
849
  /**
754
850
  * Attach extracted blocks to the turns they belong to.
@@ -815,13 +911,13 @@ function hashText(input) {
815
911
  * @param events - one slot's events, in log order.
816
912
  * @returns a stable hex key.
817
913
  */
818
- function materialKey(events) {
914
+ function materialKey(events, options) {
819
915
  const prose = events
820
916
  .filter((event) => event.type === 'assistant/message')
821
917
  .map((event) => textOf(event))
822
918
  .filter((text) => text.length > 0)
823
919
  .join('\n');
824
- return hashText(buildExtractionMaterial(events, prose));
920
+ return hashText(buildExtractionMaterial(events, prose, options));
825
921
  }
826
922
  /**
827
923
  * Render one section to digest text, truncating assistant prose to `capChars`.
@@ -834,12 +930,65 @@ function materialKey(events) {
834
930
  * The tool pointer line stays either way: it is one line, and it is the only
835
931
  * record of what was actually run when the prose and extraction both say little.
836
932
  */
837
- 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) {
838
986
  const lines = [];
839
- // The block that covers this section, if any. Looked up by scanning the keys
840
- // rather than by probing one key per turn: a fold spans whole sections, so the
841
- // covering key belongs to an earlier section, not to this turn's own key.
842
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);
843
992
  let covering;
844
993
  if (condensed !== undefined) {
845
994
  for (const [key, block] of condensed) {
@@ -851,13 +1000,10 @@ function renderSection(section, level, condensed, sectionIndex) {
851
1000
  }
852
1001
  }
853
1002
  if (covering !== undefined) {
854
- // The user line stays: a request is a standing constraint. Only the first
855
- // covered section prints the folded text — the rest contribute their user
856
- // lines alone, which is the room the condensation buys.
857
1003
  const start = Number(covering.key.split(':')[0]);
858
1004
  for (const turn of section.turns) {
859
1005
  if (turn.user.length > 0)
860
- lines.push(`\n## user\n${turn.user.join('\n')}`);
1006
+ lines.push(`\n## user\n${formatUserText(turn.user, keepFullUser)}`);
861
1007
  }
862
1008
  if (index === start) {
863
1009
  const range = covering.block.covers <= 1
@@ -867,29 +1013,41 @@ function renderSection(section, level, condensed, sectionIndex) {
867
1013
  }
868
1014
  return lines.join('\n');
869
1015
  }
870
- for (const [turnIndex, turn] of section.turns.entries()) {
1016
+ for (const [, turn] of section.turns.entries()) {
871
1017
  if (turn.user.length > 0)
872
- lines.push(`\n## user\n${turn.user.join('\n')}`);
873
- // An extraction whose every field is empty renders nothing: a heading followed by
874
- // no body reads as a turn that did something but says nothing.
875
- if (turn.extracted !== undefined && renderExtractionBlock(turn.extracted, level).length > 0) {
876
- const block = renderExtractionBlock(turn.extracted, level);
877
- // The trailer goes *above* the block, not below it. `## Asked` is the block's
878
- // last section and the user's reply is the very next line, so a trailer line
879
- // 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) {
880
1024
  const trailer = [];
881
1025
  if (turn.writes.length > 0)
882
1026
  trailer.push(` wrote: ${turn.writes.join(', ')}`);
883
- const withAnswers = insertAnswers(block, renderAnswers(turn));
1027
+ const withAnswers = insertAnswers(renderedBlock, renderAnswers(turn, compactAnswerStem));
884
1028
  const body = trailer.length > 0 ? `${trailer.join('\n')}\n${withAnswers}` : withAnswers;
885
1029
  lines.push(`### assistant\n${body}`);
886
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
+ }
887
1047
  else {
888
- const body = turn.assistant.join('\n');
889
- const answers = renderAnswers(turn);
890
- // The heading goes on whenever there is anything to put under it. Emitting
891
- // the answers bare put `## Answers` directly below `## user`, at the user's
892
- // 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);
893
1051
  if (body.length > 0 || answers.length > 0)
894
1052
  lines.push(`### assistant\n${[body, answers].filter((part) => part.length > 0).join('\n')}`);
895
1053
  if (turn.writes.length > 0)
@@ -898,26 +1056,18 @@ function renderSection(section, level, condensed, sectionIndex) {
898
1056
  }
899
1057
  return lines.join('\n');
900
1058
  }
901
- /**
902
- * Render a turn's tool questions and their answers, or an empty string.
903
- *
904
- * This section exists because `## Asked` cannot cover these. `asked` is written by
905
- * the model from prose, and its contract says the reply is the next `## user` line
906
- * — true for a question asked in prose, false for one asked through
907
- * `ask_user_question`: the user answers inside the picker, the answer becomes the
908
- * tool result, and no user message is ever written. Two consecutive checkpoints of
909
- * a real session carried neither the question nor the answer.
910
- *
911
- * Rendered from the log, so it cannot be paraphrased away, and placed after the
912
- * assistant block because it belongs to that turn's work.
913
- *
914
- * @param turn - one turn's digest material.
915
- * @returns the `## Answers` section, or an empty string when nothing was asked.
916
- */
917
- function renderAnswers(turn) {
1059
+ function renderAnswers(turn, compactStem = false) {
918
1060
  if (turn.answered.length === 0)
919
1061
  return '';
920
- 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')}`;
921
1071
  }
922
1072
  /**
923
1073
  * Place the `## Answers` section just above `## Asked`, or at the end when the
@@ -978,11 +1128,25 @@ function insertAnswers(block, answers) {
978
1128
  * bodies, leaving only `## Asked`, before condensation ever got a chance.
979
1129
  */
980
1130
  export function renderDigest(events, budgetTokens, extracted, condensed) {
981
- 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
+ }));
982
1143
  const budgetChars = Math.max(0, budgetTokens * 4);
983
- const render = (trimmed, level = 3) => (trimmed ?? sections)
984
- .map((section, index) => renderSection(section, level, condensed, index))
985
- .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
+ };
986
1150
  // User prose is reserved before anything else is placed.
987
1151
  //
988
1152
  // Measured on a 122-turn session: every human message in the span totalled 469
@@ -1172,9 +1336,25 @@ export function renderDigest(events, budgetTokens, extracted, condensed) {
1172
1336
  */
1173
1337
  export function shadowedSeqs(session, input) {
1174
1338
  const nodes = session.surface.nodes;
1175
- const head = nodes[0] !== undefined && session.eventAt(nodes[0])?.type === 'system/message' ? 1 : 0;
1176
- const take = Math.max(0, input.messages.length - head);
1177
- 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);
1178
1358
  }
1179
1359
  /**
1180
1360
  * Pick the log events the digest is built from: every append-origin surface
@@ -1222,204 +1402,336 @@ export function digestSource(session, retainedSeqs) {
1222
1402
  * @param prose - that turn's assistant prose, already extracted by the caller.
1223
1403
  * @returns the joined material, or an empty string when the turn has nothing.
1224
1404
  */
1225
- 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) {
1226
1442
  const userRequest = turn
1227
- .filter((event) => event.type === 'user/message' && !isInjection(event) && !isCheckpoint(event))
1228
- .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)))
1229
1451
  .filter((text) => text.length > 0)
1230
1452
  .join('\n');
1231
1453
  const hints = collectHints(turn);
1232
- 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)
1233
1456
  return '';
1234
- return [
1235
- `USER INSTRUCTION (already in the digest verbatim; never copy it into Asked):\n${userRequest.slice(0, 4000) || '(none)'}`,
1236
- `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)'}`,
1237
1462
  `TOOL TRACE:\n${hints || '(none)'}`,
1238
- ].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');
1239
1468
  }
1240
- /**
1241
- * Per-turn extraction through the host's own LLM service.
1242
- *
1243
- * This is the part the verbatim digest cannot do on its own. Measured on a real
1244
- * 13878-event session: 1973 assistant messages, of which only 317 carried any
1245
- * prose, and one turn ran 342 tool calls while emitting zero characters of text.
1246
- * A digest that only copies prose therefore reduced that whole turn to a `tools:`
1247
- * count line — the work happened, the record did not.
1248
- *
1249
- * The call reuses the session's routed model exactly as the host's own
1250
- * compaction does (`ctx.llm.stream` with the session's provider/model), so no
1251
- * separate credential or configuration is involved.
1252
- *
1253
- * Every failure path yields no blocks and the caller falls back to the plain
1254
- * digest: a compaction that cannot reach the model must still compact, or the
1255
- * session dies of context overflow instead of losing detail. The degradation is
1256
- * per turn, but it is never silent — a batch that comes back unusable is
1257
- * reported, because the whole point of that fallback is invisible otherwise.
1258
- *
1259
- * @param ctx - plugin context carrying the `llm` service and a logger.
1260
- * @param agent - owner of the session being compacted; supplies the routed model.
1261
- * @param batch - slots to extract, in one call unless the answer is truncated.
1262
- * @param signal - cancellation forwarded to the adapter.
1263
- * @returns the extracted blocks by slot key; empty when extraction is unavailable.
1264
- */
1265
- /**
1266
- * One condensation request: fold a run of already-finished turns into a paragraph.
1267
- *
1268
- * Module-level and shaped like `extractOnce` rather than a method, so both calls
1269
- * derive their route and reasoning effort the same way.
1270
- *
1271
- * @param ctx - plugin context carrying the `llm` service and a logger.
1272
- * @param agent - owner of the session being compacted.
1273
- * @param material - the rendered blocks being folded.
1274
- * @param signal - cancellation forwarded to the adapter.
1275
- * @returns the folded paragraph, or undefined when the call produced nothing.
1276
- */
1277
- 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) {
1278
1625
  const llm = ctx.llm;
1279
1626
  if (llm === undefined) {
1280
1627
  ctx.logger?.warn('verbatim-compaction: no llm service, condensation skipped');
1281
1628
  return undefined;
1282
1629
  }
1283
- const route = agent.session.requestHeader()?.config;
1284
- const provider = route?.provider ?? agent.options.provider;
1285
- const model = route?.model ?? agent.options.model;
1286
- if (provider === undefined || model === undefined) {
1630
+ const effective = resolveEffectiveRoute(agent, override);
1631
+ if (effective === undefined) {
1287
1632
  ctx.logger?.warn('verbatim-compaction: no route for condensation, skipped');
1288
1633
  return undefined;
1289
1634
  }
1290
- const info = await Promise.resolve()
1291
- .then(() => llm.resolveModelInfo?.(provider, model, signal))
1292
- .catch(() => undefined);
1293
- const cheapest = cheapestEffort(info?.reasoning?.efforts);
1635
+ const call = withCallTimeout(signal, resolveCallTimeoutMs());
1294
1636
  const chunks = [];
1295
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);
1296
1642
  const stream = llm.stream(applyPurposeOverride({
1297
- provider,
1298
- model,
1643
+ provider: effective.provider,
1644
+ model: effective.model,
1299
1645
  messages: [{ role: 'user', content: [{ type: 'text', text: `${material}\n\n${CONDENSE_INSTRUCTION}` }] }],
1300
1646
  maxTokens: CONDENSE_TOKENS,
1301
1647
  sessionId: agent.session.id,
1302
1648
  purpose: 'compaction',
1303
- ...(signal === undefined ? {} : { signal }),
1649
+ signal: call.signal,
1304
1650
  }, override, cheapest));
1305
1651
  for await (const chunk of stream) {
1306
1652
  const delta = chunk;
1307
1653
  if (delta.type === 'text-delta' && typeof delta.text === 'string')
1308
1654
  chunks.push(delta.text);
1655
+ else if (delta.type === 'finish')
1656
+ addUsage(usageAcc, delta.usage);
1309
1657
  }
1310
1658
  }
1311
1659
  catch (error) {
1312
1660
  ctx.logger?.warn(`verbatim-compaction: condensation call failed: ${String(error)}`);
1313
1661
  return undefined;
1314
1662
  }
1315
- const text = chunks.join('').trim();
1663
+ finally {
1664
+ call.dispose();
1665
+ }
1666
+ const text = sanitizeCondensedText(chunks.join(''));
1316
1667
  if (text.length === 0) {
1317
- // Silence here is what makes "the digest stopped folding" invisible at runtime:
1318
- // the summary still renders, just without the room the fold would have bought.
1319
1668
  ctx.logger?.warn(`verbatim-compaction: condensation returned no text for ${material.length} chars of material`);
1320
1669
  return undefined;
1321
1670
  }
1322
1671
  return text;
1323
1672
  }
1324
- async function extractBatch(ctx, agent, batch, signal, override) {
1673
+ async function extractBatch(ctx, agent, batch, signal, override, usageAcc) {
1325
1674
  const out = new Map();
1326
- if (batch.length === 0)
1675
+ const isAborted = () => signal?.aborted === true;
1676
+ if (batch.length === 0 || isAborted())
1327
1677
  return out;
1328
- const attempt = await extractOnce(ctx, agent, batch, signal, override);
1329
- 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) {
1330
1683
  if (attempt.blocks.size === 0) {
1331
1684
  ctx.logger?.warn(`verbatim-compaction: extraction returned no usable JSON for ${batch.length} slot(s) `
1332
1685
  + `(${batch.map((slot) => slot.key).join(', ')}); those turns keep their verbatim prose`);
1333
1686
  }
1334
1687
  return attempt.blocks;
1335
1688
  }
1336
- // A truncated answer parses to nothing, so one over-budget turn would cost
1337
- // every turn in its batch. Measured on 191 real compactions, failures arrived
1338
- // in runs of exactly `TURNS_PER_CALL`, which is this batching, not the model
1339
- // failing per turn. Halving bounds the loss to the half that still does not
1340
- // fit, and a single slot cannot be split further.
1341
1689
  if (batch.length === 1) {
1342
- ctx.logger?.warn(`verbatim-compaction: extraction truncated at the token cap for slot ${batch[0]?.key ?? '?'}; `
1343
- + '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
+ }
1344
1694
  return attempt.blocks;
1345
1695
  }
1346
1696
  for (const [key, block] of attempt.blocks)
1347
1697
  out.set(key, block);
1348
- const middle = Math.ceil(batch.length / 2);
1349
- for (const half of [batch.slice(0, middle), batch.slice(middle)]) {
1350
- 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))
1351
1713
  out.set(key, block);
1352
1714
  }
1353
1715
  return out;
1354
1716
  }
1355
- /**
1356
- * The cheapest effort a route advertises, or undefined when it advertises none.
1357
- *
1358
- * The route's own default is not used: it is typically the highest level, and
1359
- * thinking is paid out of the answer's token budget. The list is ordered from
1360
- * least to greatest effort by the host's own contract, so the first entry is the
1361
- * cheapest. `off` is skipped even when present — pi-ai maps it to a wire value
1362
- * the route may reject, and a level that cannot be sent is worse than a cheap
1363
- * one that can.
1364
- *
1365
- * @param efforts - the route's advertised efforts, in escalation order.
1366
- * @returns the cheapest usable effort id, or undefined to leave the choice alone.
1367
- */
1368
1717
  function cheapestEffort(efforts) {
1369
- 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;
1370
1726
  }
1371
- /**
1372
- * One extraction request, no retry.
1373
- *
1374
- * The cap must carry a fixed thinking reserve on top of the per-slot output
1375
- * budget. `maxTokens` covers thinking and the answer together, and thinking is
1376
- * a per-call cost that does not shrink when the batch does. Measured against the
1377
- * live route (deepseek-flash, `reasoning_effort` unset, real-length material):
1378
- * a single slot at the old `220 x 1` cap returned zero parseable slots in 4 of 4
1379
- * runs, the thinking block having consumed the entire cap; the same single slot
1380
- * at `220 x 1 + 1000` parsed in 4 of 4. The reserve is what makes the cap work
1381
- * for a batch of any size, including the batches the caller splits down to.
1382
- *
1383
- * The effort is pinned to the route's cheapest advertised level rather than left
1384
- * to the route default. Thinking is paid out of the same `maxTokens` as the
1385
- * answer, so a default that thinks hard shrinks the answer budget even with the
1386
- * reserve in place. Measured on the live route at a 2-slot cap with the reserve:
1387
- * `low` spent 375 thinking tokens and parsed 3 of 3; `high` spent 931 and parsed
1388
- * 2 of 3.
1389
- *
1390
- * Two things that look like fixes and are not:
1391
- *
1392
- * - `off` cannot be reached through pi-ai. Its `deepseek` thinking format maps
1393
- * the `off` level to `reasoning_effort: "minimal"`, which the route rejects
1394
- * outright (`valid levels: low, medium, high`), and its `thinking` field is
1395
- * pinned to `{type: "enabled"}` for every level. Captured from pi-ai 1.3.0
1396
- * against a local echo server, not inferred.
1397
- * - Only the provider's own `thinking: {type: "disabled"}` actually stops
1398
- * thinking (0 thinking tokens, measured), but `GenerateOptions` has no field
1399
- * that carries it, so no plugin on this seam can send it.
1400
- *
1401
- * An effort is requested only when the route advertises it, because the host
1402
- * rejects one it does not.
1403
- *
1404
- * @param ctx - plugin context carrying the `llm` service and a logger.
1405
- * @param agent - owner of the session being compacted.
1406
- * @param batch - slots to ask about in this one call.
1407
- * @param signal - cancellation forwarded to the adapter.
1408
- * @returns the parsed blocks and whether the model stopped at the token cap.
1409
- */
1410
- async function extractOnce(ctx, agent, batch, signal, override) {
1727
+ async function extractOnce(ctx, agent, batch, signal, override, usageAcc) {
1411
1728
  const out = new Map();
1412
1729
  const llm = ctx.llm;
1413
1730
  if (llm === undefined)
1414
1731
  return { blocks: out, truncated: false };
1415
- const route = agent.session.requestHeader()?.config;
1416
- const provider = route?.provider ?? agent.options.provider;
1417
- const model = route?.model ?? agent.options.model;
1418
- if (provider === undefined || model === undefined)
1732
+ const effective = resolveEffectiveRoute(agent, override);
1733
+ if (effective === undefined)
1419
1734
  return { blocks: out, truncated: false };
1420
- // The label the model echoes back is the slot key, not the turn number: two
1421
- // requests can share a number, and a duplicate label would collapse two blocks
1422
- // into one entry.
1423
1735
  const parts = [];
1424
1736
  for (const slot of batch) {
1425
1737
  const prose = slot.events
@@ -1427,48 +1739,82 @@ async function extractOnce(ctx, agent, batch, signal, override) {
1427
1739
  .map((event) => textOf(event))
1428
1740
  .filter((text) => text.length > 0)
1429
1741
  .join('\n');
1430
- const material = buildExtractionMaterial(slot.events, prose);
1742
+ const material = buildExtractionMaterial(slot.events, prose, slot.includeToolResults === true ? { includeToolResults: true } : undefined);
1431
1743
  if (material.length === 0)
1432
1744
  continue;
1433
1745
  parts.push(`=== SLOT ${slot.key} (turn ${slot.turn ?? '?'}) ===\n${material}`);
1434
1746
  }
1435
1747
  if (parts.length === 0)
1436
1748
  return { blocks: out, truncated: false };
1437
- const info = await Promise.resolve()
1438
- .then(() => llm.resolveModelInfo?.(provider, model, signal))
1439
- .catch(() => undefined);
1440
- const cheapest = cheapestEffort(info?.reasoning?.efforts);
1749
+ const call = withCallTimeout(signal, resolveCallTimeoutMs());
1441
1750
  const chunks = [];
1442
1751
  let truncated = false;
1443
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);
1444
1757
  const stream = llm.stream(applyPurposeOverride({
1445
- provider,
1446
- model,
1758
+ provider: effective.provider,
1759
+ model: effective.model,
1447
1760
  messages: [
1448
1761
  { role: 'user', content: [{ type: 'text', text: `${parts.join('\n\n')}\n\n${EXTRACT_INSTRUCTION}` }] },
1449
1762
  ],
1450
1763
  maxTokens: EXTRACT_TOKENS_PER_TURN * parts.length + EXTRACT_THINKING_RESERVE_TOKENS,
1451
1764
  sessionId: agent.session.id,
1452
1765
  purpose: 'compaction',
1453
- ...(signal === undefined ? {} : { signal }),
1766
+ signal: call.signal,
1454
1767
  }, override, cheapest));
1455
1768
  for await (const chunk of stream) {
1456
1769
  const delta = chunk;
1457
1770
  if (delta.type === 'text-delta' && typeof delta.text === 'string')
1458
1771
  chunks.push(delta.text);
1459
- else if (delta.type === 'finish' && delta.reason?.kind === 'max-tokens')
1460
- truncated = true;
1772
+ else if (delta.type === 'finish') {
1773
+ if (delta.reason?.kind === 'max-tokens')
1774
+ truncated = true;
1775
+ addUsage(usageAcc, delta.usage);
1776
+ }
1461
1777
  }
1462
1778
  }
1463
1779
  catch (error) {
1464
1780
  ctx.logger?.warn(`verbatim-compaction: extraction call failed for ${parts.length} slot(s): ${String(error)}`);
1465
- 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();
1466
1786
  }
1467
1787
  const answer = chunks.join('').trim();
1468
1788
  if (answer.length === 0)
1469
1789
  return { blocks: out, truncated };
1470
1790
  return { blocks: parseExtraction(answer), truncated };
1471
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
+ }
1472
1818
  /**
1473
1819
  * Extractive compaction backend: verbatim user prose, one model call per batch,
1474
1820
  * call.
@@ -1479,22 +1825,6 @@ async function extractOnce(ctx, agent, batch, signal, override) {
1479
1825
  * subclass cannot diverge from the host's transaction semantics.
1480
1826
  */
1481
1827
  export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1482
- /**
1483
- * The Loader reads Config from the default-exported class, and the base
1484
- * constructor rejects unknown keys, so the base schema is merged instead of
1485
- * replaced. Only the three new fields are volatile: existing keys stay
1486
- * ordinary patch-level configuration.
1487
- */
1488
- static Config = Schema.object({
1489
- ...BasicCompactionEngine.Config.dict,
1490
- ...OVERRIDE_FIELDS,
1491
- });
1492
- purposeConfig;
1493
- constructor(ctx, config) {
1494
- const { provider, model, reasoningEffort, ...base } = config ?? {};
1495
- super(ctx, base);
1496
- this.purposeConfig = { provider, model, reasoningEffort };
1497
- }
1498
1828
  /**
1499
1829
  * Extraction results, keyed by a hash of the material they were derived from.
1500
1830
  *
@@ -1513,13 +1843,95 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1513
1843
  */
1514
1844
  extractionCache = new Map();
1515
1845
  /**
1516
- * Folded text, keyed by provider, model and a hash of the material folded.
1517
- *
1518
- * Same reasoning as `extractionCache`: the fold is a model call over material
1519
- * rebuilt from the raw log on every compaction, so the same run of old turns is
1520
- * 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.
1521
1847
  */
1522
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
+ }
1523
1935
  /**
1524
1936
  * Build the replacement checkpoint content from the session log.
1525
1937
  *
@@ -1533,10 +1945,11 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1533
1945
  * @param input - replayed conversation prefix the base class is shadowing.
1534
1946
  * @param agent - owner of the session being compacted.
1535
1947
  * @param signal - cancellation forwarded to the extraction and fold calls.
1536
- * @returns text summary blocks, unmarked by any LLM call.
1948
+ * @returns text summary blocks, route metadata, and aggregated LLM usage.
1537
1949
  */
1538
1950
  async summarize(input, agent, signal) {
1539
1951
  const session = agent.session;
1952
+ this.hydrateDiskCache(session.id);
1540
1953
  const shadowed = shadowedSeqs(session, input);
1541
1954
  const shadowedSet = new Set(shadowed);
1542
1955
  const retained = new Set(session.surface.nodes.filter((seq) => !shadowedSet.has(seq)));
@@ -1550,12 +1963,15 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1550
1963
  // size independent of history length; the guard bound only exists for the
1551
1964
  // degenerate case of a span smaller than the ceiling.
1552
1965
  const budget = Math.max(0, Math.min(DIGEST_TOKEN_CEILING, shadowedPrice - FRAME_TOKENS - SHRINK_MARGIN_TOKENS));
1553
- const extracted = await this.extractAll(source, agent, signal, this.purposeConfig);
1554
- // Fold the oldest turns up only when the plain digest overflows. The fold is an
1555
- // 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.
1556
1971
  let condensed;
1557
- if (renderDigest(source, budget, extracted).length > budget * 4) {
1558
- condensed = await this.condenseOldest(source, extracted, agent, budget, signal, this.purposeConfig);
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);
1559
1975
  }
1560
1976
  // The fold path returns its digest whole, so it can still overflow when every
1561
1977
  // group has been folded and the user lines alone are too long. The budget is a
@@ -1568,58 +1984,34 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1568
1984
  + `(${text.length} > ${budget * 4} chars), falling back to the graded ladder`);
1569
1985
  text = renderDigest(source, budget, extracted);
1570
1986
  }
1987
+ const effective = resolveEffectiveRoute(agent, override);
1571
1988
  const route = session.requestHeader()?.config;
1989
+ const usage = toTokenUsage(usageAcc);
1572
1990
  return {
1573
1991
  summary: [{ type: 'text', text }],
1574
- provider: route?.provider ?? agent.options.provider ?? 'verbatim',
1575
- 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 }),
1576
1995
  };
1577
1996
  }
1578
1997
  /**
1579
1998
  * Fold the oldest turns into condensed blocks until the digest fits.
1580
1999
  *
1581
- * Only reached when the plain digest overflows `budget`. The oldest turns are
1582
- * the right ones to fold: they describe work already superseded, while the
1583
- * newest are what the next request depends on.
1584
- *
1585
- * Linear in groups, not bisected: a fold is not monotone in how much is folded —
1586
- * a paragraph's length depends on what the model chose to keep — so there is no
1587
- * boundary to bisect. The walk stops at the first size that fits, which is the
1588
- * fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
1589
- * consecutive sections, so the number of calls is proportional to the digest,
1590
- * not to the number of turns.
1591
- *
1592
- * Cached by content, like the extraction: the same prefix of turns folds to the
1593
- * same text, and a later compaction re-reads the same history.
1594
- *
1595
- * @param source - digest source events, in log order.
1596
- * @param extracted - per-turn extractions already computed.
1597
- * @param agent - owner of the session being compacted.
1598
- * @param budget - token budget the digest must fit.
1599
- * @param signal - cancellation forwarded to every call.
1600
- * @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.
1601
2003
  */
1602
- async condenseOldest(source, extracted, agent, budget, signal, override) {
2004
+ async condenseOldest(source, extracted, agent, budget, signal, override, usageAcc) {
1603
2005
  const sections = withExtractions(buildSections(source), extracted);
1604
2006
  const budgetChars = budget * 4;
1605
2007
  const out = new Map();
1606
- // One group per iteration, oldest first, checking after each whether the digest
1607
- // fits. Single loop, `start` monotone: the earlier two-level form advanced its
1608
- // inner start from `out.size`, so a group whose call failed was retried on every
1609
- // outer pass (45 calls instead of 4 with the model down), and the outer bound
1610
- // `covered < sections.length` stopped one group short of the end — at 700
1611
- // sections the last 100 were never folded, and at 100 or fewer the loop body
1612
- // never ran at all.
1613
2008
  for (const start of foldGroupStarts(sections.length)) {
1614
2009
  if (signal?.aborted === true)
1615
2010
  break;
1616
2011
  const group = sections.slice(start, start + CONDENSE_GROUP);
1617
2012
  if (group.length === 0)
1618
2013
  continue;
1619
- const text = await this.condenseGroup(group, agent, signal, override);
1620
- // A failed group is skipped rather than retried: the next group still buys
1621
- // room, and retrying the same material against a failing model only spends
1622
- // calls. The remaining turns keep their own blocks either way.
2014
+ const text = await this.condenseGroup(group, agent, signal, override, usageAcc);
1623
2015
  if (text === undefined)
1624
2016
  continue;
1625
2017
  out.set(turnKey(start, 0), { text, covers: group.length });
@@ -1630,19 +2022,8 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1630
2022
  }
1631
2023
  /**
1632
2024
  * Hand one group of turns to the model and return its folded text.
1633
- *
1634
- * @param group - consecutive sections to fold into one paragraph.
1635
- * @param agent - owner of the session being compacted.
1636
- * @param signal - cancellation forwarded to the call.
1637
- * @returns the folded paragraph, or undefined when the call produced nothing.
1638
2025
  */
1639
- async condenseGroup(group, agent, signal, override) {
1640
- // Both sources, because a turn has one or the other: extraction succeeds and
1641
- // the block replaces the prose, or it fails and the verbatim prose is what the
1642
- // digest shows. Reading only `extracted` meant a run of turns whose extraction
1643
- // failed contributed nothing — and because the fold then still replaced them,
1644
- // their content vanished from the digest entirely rather than merely being
1645
- // summarised badly.
2026
+ async condenseGroup(group, agent, signal, override, usageAcc) {
1646
2027
  const material = group
1647
2028
  .map((section) => section.turns
1648
2029
  .map((turn) => {
@@ -1658,115 +2039,99 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1658
2039
  const llm = this.ctx.llm;
1659
2040
  if (llm === undefined)
1660
2041
  return undefined;
1661
- const route = agent.session.requestHeader()?.config;
1662
- const provider = route?.provider ?? agent.options.provider;
1663
- const model = route?.model ?? agent.options.model;
1664
- if (provider === undefined || model === undefined)
2042
+ const effective = resolveEffectiveRoute(agent, override);
2043
+ if (effective === undefined)
1665
2044
  return undefined;
1666
- const key = `${provider}:${model}:${hashText(material)}`;
1667
- const cached = this.condensedCache.get(key);
2045
+ const key = `${effective.provider}:${effective.model}:${hashText(material)}`;
2046
+ const cached = boundedCacheGet(this.condensedCache, key);
1668
2047
  if (cached !== undefined)
1669
2048
  return cached;
1670
- const text = await condenseOnce(this.ctx, agent, material, signal, override);
2049
+ const text = await condenseOnce(this.ctx, agent, material, signal, override, usageAcc);
1671
2050
  if (text === undefined)
1672
2051
  return undefined;
1673
- 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]]));
1674
2054
  return text;
1675
2055
  }
1676
2056
  /**
1677
- * Run the extraction for every turn in the digest source.
1678
- *
1679
- * Sequential rather than parallel: these calls share the session's routed
1680
- * model and the provider's KV cache, and firing a dozen at once would both
1681
- * multiply the cost and defeat the cache the host's own summarizer relies on.
1682
- *
1683
- * A turn that fails is simply absent from the output; one bad turn must not
1684
- * drop the extraction for the rest.
2057
+ * Run the extraction for every section in the digest source.
1685
2058
  *
1686
- * Batched rather than one call per turn. One call per turn meant 131 calls on a
1687
- * 122-turn session, each with its own round trip: a measured extraction budget
1688
- * of 131 x 400 tokens could on its own exceed the whole digest ceiling. A
1689
- * batch of `TURNS_PER_CALL` turns costs one round trip and shares the prompt
1690
- * prefix, so the provider's KV cache is reused rather than rebuilt.
1691
- *
1692
- * @param source - digest source events, in log order.
1693
- * @param agent - owner of the session being compacted.
1694
- * @param signal - cancellation forwarded to every call.
1695
- * @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.
1696
2063
  */
1697
- async extractAll(source, agent, signal, override) {
1698
- // Walk the same sections the renderer will use, so a key addresses the exact
1699
- // slot the block will be written into. Grouping by turn number instead lost
1700
- // blocks whenever the log reused a number.
1701
- // Partition the source into the same sections `buildSections` produced, then
1702
- // hand each section to its slot. A slot is a section, not a single message:
1703
- // the earlier version stopped at the first message, so a turn with 69
1704
- // assistant messages and 112 tool calls contributed 2 events out of 164 and
1705
- // the extractor reported "no work observed" for a turn that did plenty.
1706
- const sections = buildSections(source);
1707
- // Attribute events to sections by replaying the same walk `buildSections`
1708
- // does, so the two can never disagree about where a section starts. An
1709
- // independent scan drifted by one section on the fixture: `buildSections`
1710
- // opens a new section for an unclosed turn without consuming a user message.
1711
- const grouped = [];
1712
- let sectionIndex = -1;
1713
- const openedObjectives = new Set();
1714
- for (const event of source) {
1715
- const objective = goalObjective(event);
1716
- let startsSection = false;
1717
- if (objective !== undefined) {
1718
- if (!openedObjectives.has(objective)) {
1719
- openedObjectives.add(objective);
1720
- startsSection = true;
1721
- }
1722
- }
1723
- else if (event.type === 'user/message' && !isInjection(event) && !isCheckpoint(event)) {
1724
- startsSection = true;
1725
- }
1726
- if (startsSection) {
1727
- sectionIndex += 1;
1728
- grouped[sectionIndex] = [];
1729
- }
1730
- if (sectionIndex >= 0)
1731
- grouped[sectionIndex]?.push(event);
1732
- }
1733
- // One slot per section, addressed to the section's first turn.
1734
- //
1735
- // The material is about what the section did as a whole, so handing it to
1736
- // every turn in the section made the model answer twice with the same block:
1737
- // a real section holding two turns produced two identical `## Concluded`
1738
- // bodies plus `(duplicate of SLOT 4:0)` placeholders in the digest. The extra
1739
- // turns keep their prose and their own headings; only the first carries the
1740
- // section's extraction.
2064
+ async extractAll(source, agent, signal, override, usageAcc) {
2065
+ const { sections, sectionEvents } = buildSectionsWithEvents(source);
2066
+ const singleSection = sections.length === 1;
1741
2067
  const slots = [];
1742
2068
  for (const [sectionIndex, section] of sections.entries()) {
1743
2069
  const first = section.turns[0];
1744
2070
  if (first === undefined)
1745
2071
  continue;
1746
- 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
+ });
1747
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)}`;
1748
2097
  const extracted = new Map();
1749
2098
  const missing = [];
1750
2099
  for (const slot of slots) {
1751
- const cached = this.extractionCache.get(materialKey(slot.events));
2100
+ const cached = boundedCacheGet(this.extractionCache, cacheKeyFor(slot));
1752
2101
  if (cached === undefined)
1753
2102
  missing.push(slot);
1754
2103
  else
1755
2104
  extracted.set(slot.key, cached);
1756
2105
  }
2106
+ const batches = [];
1757
2107
  for (let index = 0; index < missing.length; index += TURNS_PER_CALL) {
1758
- if (signal?.aborted === true)
1759
- break;
1760
- const batch = missing.slice(index, index + TURNS_PER_CALL);
1761
- const blocks = await extractBatch(this.ctx, agent, batch, signal, override);
1762
- for (const slot of batch) {
1763
- const block = blocks.get(slot.key);
1764
- if (block === undefined)
1765
- continue;
1766
- extracted.set(slot.key, block);
1767
- this.extractionCache.set(materialKey(slot.events), block);
1768
- }
2108
+ batches.push(missing.slice(index, index + TURNS_PER_CALL));
1769
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());
1770
2135
  return extracted;
1771
2136
  }
1772
2137
  }