@logictan/dsh-verbatim-compaction 0.13.2 → 0.13.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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) {
@@ -187,8 +238,27 @@ function toolCallsOf(event) {
187
238
  }
188
239
  return calls;
189
240
  }
190
- /** The `questions[]` payload of an `ask_user_question` call, as `{id → text}`. */
191
- function questionTextsOf(argumentsJson) {
241
+ function optionLabelsOf(raw) {
242
+ if (!Array.isArray(raw))
243
+ return [];
244
+ const labels = [];
245
+ for (const entry of raw) {
246
+ if (typeof entry === 'string') {
247
+ const trimmed = entry.trim();
248
+ if (trimmed.length > 0)
249
+ labels.push(trimmed);
250
+ continue;
251
+ }
252
+ if (typeof entry !== 'object' || entry === null)
253
+ continue;
254
+ const label = entry['label'];
255
+ if (typeof label === 'string' && label.trim().length > 0)
256
+ labels.push(label.trim());
257
+ }
258
+ return labels;
259
+ }
260
+ /** The `questions[]` payload of an `ask_user_question` call, as `{id → {question, options}}`. */
261
+ function questionSpecsOf(argumentsJson) {
192
262
  const out = new Map();
193
263
  let parsed;
194
264
  try {
@@ -208,8 +278,9 @@ function questionTextsOf(argumentsJson) {
208
278
  const record = question;
209
279
  const id = record['id'];
210
280
  const text = typeof record['question'] === 'string' ? record['question'] : undefined;
211
- if (typeof id === 'string' && text !== undefined)
212
- out.set(id, text);
281
+ if (typeof id === 'string' && text !== undefined) {
282
+ out.set(id, { question: text, options: optionLabelsOf(record['options']) });
283
+ }
213
284
  }
214
285
  return out;
215
286
  }
@@ -226,10 +297,10 @@ function questionTextsOf(argumentsJson) {
226
297
  * user's actual observations rather than a menu label.
227
298
  *
228
299
  * @param text - the JSON body.
229
- * @param texts - question id to question text, from the call's arguments.
300
+ * @param specs - question id to question text and option labels, from the call's arguments.
230
301
  * @returns one entry per answered question; empty when the body is not a batch.
231
302
  */
232
- function answersOf(text, texts) {
303
+ function answersOf(text, specs) {
233
304
  let parsed;
234
305
  try {
235
306
  parsed = JSON.parse(text);
@@ -243,15 +314,18 @@ function answersOf(text, texts) {
243
314
  // not depend on the call still being in the same turn's events.
244
315
  const body = parsed;
245
316
  const own = Array.isArray(body['questions']) ? body['questions'] : [];
246
- const merged = new Map(texts);
317
+ const merged = new Map(specs);
247
318
  for (const question of own) {
248
319
  if (typeof question !== 'object' || question === null)
249
320
  continue;
250
321
  const record = question;
251
322
  const id = record['id'];
252
323
  const text = record['question'];
253
- if (typeof id === 'string' && typeof text === 'string')
254
- merged.set(id, text);
324
+ if (typeof id === 'string' && typeof text === 'string') {
325
+ const existing = merged.get(id);
326
+ const options = optionLabelsOf(record['options']);
327
+ merged.set(id, { question: text, options: options.length > 0 ? options : (existing?.options ?? []) });
328
+ }
255
329
  }
256
330
  const answers = body['answers'];
257
331
  if (!Array.isArray(answers))
@@ -262,8 +336,8 @@ function answersOf(text, texts) {
262
336
  continue;
263
337
  const record = answer;
264
338
  const id = typeof record['id'] === 'string' ? record['id'] : '';
265
- const question = merged.get(id);
266
- if (question === undefined)
339
+ const spec = merged.get(id);
340
+ if (spec === undefined)
267
341
  continue;
268
342
  const selected = Array.isArray(record['selected'])
269
343
  ? record['selected'].map((value) => String(value)).filter((value) => value.length > 0)
@@ -271,7 +345,7 @@ function answersOf(text, texts) {
271
345
  const typed = typeof record['custom'] === 'string' ? record['custom'].trim() : '';
272
346
  if (selected.length === 0 && typed.length === 0)
273
347
  continue;
274
- out.push({ question, selected, typed });
348
+ out.push({ question: spec.question, options: spec.options, selected, typed });
275
349
  }
276
350
  return out;
277
351
  }
@@ -308,10 +382,81 @@ const EXTRACT_INSTRUCTION = [
308
382
  '- `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
383
  // The reply is the next turn's `## user` line, already verbatim in the digest.
310
384
  // 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.",
385
+ "- Use [] for `asked` when the turn asked nothing, when questions were already answered via `ask_user_question`, or when questions raised earlier were already resolved later in the same turn's prose. Do not report the user's reply.",
312
386
  '',
313
387
  'Write strings in the same language as the material. A session whose requests are Chinese gets Chinese text; do not switch to English.',
314
388
  ].join('\n');
389
+ /** Whether a parsed JSON value looks like an extraction slot payload (object with `slots[]` or array of keyed slots). */
390
+ function isSlotPayload(value) {
391
+ if (Array.isArray(value)) {
392
+ return value.some((item) => typeof item === 'object' && item !== null && 'key' in item);
393
+ }
394
+ return typeof value === 'object' && value !== null && Array.isArray(value.slots);
395
+ }
396
+ /** Extract the first balanced JSON object or array payload from a model reply that may carry prose or stray braces. */
397
+ function extractJsonPayload(raw) {
398
+ const body = raw.trim().replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/, '').trim();
399
+ try {
400
+ return JSON.parse(body);
401
+ }
402
+ catch {
403
+ // Fall through to balanced scan.
404
+ }
405
+ const candidates = [];
406
+ for (let start = 0; start < body.length; start += 1) {
407
+ const opener = body[start];
408
+ if (opener !== '{' && opener !== '[')
409
+ continue;
410
+ const closer = opener === '{' ? '}' : ']';
411
+ let depth = 0;
412
+ let inString = false;
413
+ let escaped = false;
414
+ for (let end = start; end < body.length; end += 1) {
415
+ const ch = body[end];
416
+ if (inString) {
417
+ if (escaped)
418
+ escaped = false;
419
+ else if (ch === '\\')
420
+ escaped = true;
421
+ else if (ch === '"')
422
+ inString = false;
423
+ continue;
424
+ }
425
+ if (ch === '"') {
426
+ inString = true;
427
+ continue;
428
+ }
429
+ if (ch === opener)
430
+ depth += 1;
431
+ else if (ch === closer) {
432
+ depth -= 1;
433
+ if (depth === 0) {
434
+ try {
435
+ const parsed = JSON.parse(body.slice(start, end + 1));
436
+ if (isSlotPayload(parsed))
437
+ return parsed;
438
+ candidates.push(parsed);
439
+ start = end;
440
+ }
441
+ catch {
442
+ // Do not skip past `end`: valid JSON may be nested inside invalid outer braces.
443
+ }
444
+ break;
445
+ }
446
+ }
447
+ }
448
+ }
449
+ return candidates[0];
450
+ }
451
+ /** Normalize model-drifted slot keys like `SLOT 0:0 (turn 1)` back to `0:0`. */
452
+ function normalizeSlotKey(raw) {
453
+ const str = typeof raw === 'string' ? raw : typeof raw === 'number' ? String(raw) : '';
454
+ return str
455
+ .trim()
456
+ .replace(/^SLOT\s+/i, '')
457
+ .replace(/\s*\(turn\s+[^)]*\)\s*$/i, '')
458
+ .trim();
459
+ }
315
460
  /**
316
461
  * Parse the model's JSON reply into per-slot extractions.
317
462
  *
@@ -325,34 +470,29 @@ const EXTRACT_INSTRUCTION = [
325
470
  */
326
471
  export function parseExtraction(answer) {
327
472
  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
- }
473
+ const parsed = extractJsonPayload(answer);
342
474
  if (typeof parsed !== 'object' || parsed === null)
343
475
  return out;
344
- const slots = parsed['slots'];
476
+ const slots = Array.isArray(parsed)
477
+ ? parsed
478
+ : parsed['slots'];
345
479
  if (!Array.isArray(slots))
346
480
  return out;
347
- const strings = (value) => (Array.isArray(value)
348
- ? value.filter((item) => typeof item === 'string')
481
+ const strings = (value) => {
482
+ const rawList = Array.isArray(value)
483
+ ? value
484
+ : typeof value === 'string'
485
+ ? [value]
486
+ : [];
487
+ return rawList
488
+ .filter((item) => typeof item === 'string')
349
489
  .map((item) => item.replace(/\s+/g, ' ').trim())
350
490
  .filter((item) => item.length > 0)
351
491
  // A field is a list, so "nothing here" is an empty list. Models still write a
352
492
  // 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
- : []);
493
+ .filter((item) => !/^(?:\(?none\)?|n\/a|na|-{1,2}|无|沒有|没有|暂无|无变更|无推翻|未发现)[。.!!]*$/i.test(item))
494
+ .filter((item) => !/^(?:未提问|无提问|没有提问|no questions? (?:were |was )?asked|none asked)[。.!!]*$/i.test(item));
495
+ };
356
496
  // Asked is a list of objects, not of strings: a question without its options
357
497
  // turns the user's `1` into a number that selects nothing.
358
498
  const pairs = (value) => (Array.isArray(value)
@@ -370,9 +510,11 @@ export function parseExtraction(answer) {
370
510
  ? record['options']
371
511
  .filter((option) => typeof option === 'string')
372
512
  // 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())
513
+ // list's own `1.` / `(1)` / `A.` would print double prefixes.
514
+ .map((option) => option
515
+ .replace(/\s+/g, ' ')
516
+ .replace(/^\s*(?:(?:\d{1,2}|[A-Za-z])\s*[.、::)]\s*|[((]\s*(?:\d{1,2}|[A-Za-z])\s*[))]\s*)/, '')
517
+ .trim())
376
518
  .filter((option) => option.length > 0)
377
519
  : [];
378
520
  return [{ question, options }];
@@ -382,8 +524,8 @@ export function parseExtraction(answer) {
382
524
  if (typeof slot !== 'object' || slot === null)
383
525
  continue;
384
526
  const record = slot;
385
- const key = record['key'];
386
- if (typeof key !== 'string' || key.length === 0)
527
+ const key = normalizeSlotKey(record['key']);
528
+ if (key.length === 0)
387
529
  continue;
388
530
  out.set(key, {
389
531
  did: strings(record['did']),
@@ -398,10 +540,12 @@ export function parseExtraction(answer) {
398
540
  * Render one extraction as the digest block, headings included.
399
541
  *
400
542
  * @param extraction - the fields for one slot.
543
+ * @param level - graded retention level (3..0).
544
+ * @param includeAsked - whether to render the `## Asked` section (false for stale historical turns).
401
545
  * @returns markdown with a heading per non-empty field; empty string when every
402
546
  * field is empty.
403
547
  */
404
- export function renderExtractionBlock(extraction, level = 3) {
548
+ export function renderExtractionBlock(extraction, level = 3, includeAsked = true) {
405
549
  if (extraction === undefined)
406
550
  return '';
407
551
  const lines = [];
@@ -410,11 +554,6 @@ export function renderExtractionBlock(extraction, level = 3) {
410
554
  return;
411
555
  lines.push(`## ${heading}`, ...items.map((item) => `- ${item}`));
412
556
  };
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
557
  if (level >= 1)
419
558
  section('Did', extraction.did);
420
559
  if (level >= 2)
@@ -423,13 +562,10 @@ export function renderExtractionBlock(extraction, level = 3) {
423
562
  section('Overturned', extraction.overturned);
424
563
  // Asked goes last and its options are listed under it, so the user's reply — the
425
564
  // next `## user` line — lands directly under the list it chose from.
426
- if (extraction.asked.length > 0) {
565
+ if (includeAsked && extraction.asked.length > 0) {
427
566
  lines.push('## Asked');
428
567
  for (const pair of extraction.asked) {
429
568
  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
569
  for (const [index, option] of pair.options.entries()) {
434
570
  lines.push(` ${index + 1}. ${option}`);
435
571
  }
@@ -459,18 +595,10 @@ const TURNS_PER_CALL = 8;
459
595
  /**
460
596
  * Sections folded into one condensed block when the digest overflows.
461
597
  *
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.
598
+ * Lowered from 100 to 30 so real long sessions (30–80 turns) fold oldest runs
599
+ * instead of falling straight into destructive body eviction.
472
600
  */
473
- const CONDENSE_GROUP = 100;
601
+ export const CONDENSE_GROUP = 30;
474
602
  /**
475
603
  * Output tokens allowed for one condensation call.
476
604
  *
@@ -587,18 +715,38 @@ export function collectHints(events) {
587
715
  }
588
716
  return lines.join('\n');
589
717
  }
590
- /** The `path` argument of one tool call, when the call carries one. */
591
- function pathArgumentOf(argumentsJson) {
718
+ /** Extract target file paths from write/edit/multiedit/apply_patch tool calls. */
719
+ function writePathsOf(toolName, argumentsJson) {
720
+ const paths = [];
721
+ const add = (candidate) => {
722
+ if (typeof candidate !== 'string')
723
+ return;
724
+ const trimmed = candidate.trim();
725
+ if (trimmed.length > 0 && !paths.includes(trimmed))
726
+ paths.push(trimmed);
727
+ };
592
728
  try {
593
729
  const parsed = JSON.parse(argumentsJson);
594
730
  if (typeof parsed !== 'object' || parsed === null)
595
- return undefined;
596
- const path = parsed.path;
597
- return typeof path === 'string' ? path : undefined;
731
+ return paths;
732
+ const record = parsed;
733
+ add(record['file_path']);
734
+ add(record['path']);
735
+ if (toolName === 'apply_patch') {
736
+ const patchText = typeof record['input'] === 'string'
737
+ ? record['input']
738
+ : typeof record['patch'] === 'string'
739
+ ? record['patch']
740
+ : '';
741
+ for (const match of patchText.matchAll(/^\*\*\*\s+(?:Add|Update|Delete)\s+File:\s*(.+)$|^\*\*\*\s+Move to:\s*(.+)$/gm)) {
742
+ add(match[1] ?? match[2]);
743
+ }
744
+ }
598
745
  }
599
746
  catch {
600
- return undefined;
747
+ return paths;
601
748
  }
749
+ return paths;
602
750
  }
603
751
  /** The turn number an event belongs to, when the log records one. */
604
752
  function turnOf(event) {
@@ -607,91 +755,72 @@ function turnOf(event) {
607
755
  }
608
756
  /** A fresh, empty turn accumulator. */
609
757
  function emptyTurn(turn, fromRequest = false) {
610
- return { turn, fromRequest, user: [], assistant: [], tools: new Map(), writes: [], answered: [] };
758
+ return { turn, fromRequest, user: [], assistant: [], writes: [], answered: [] };
611
759
  }
612
760
  /**
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.
761
+ * Single source of truth for partitioning log events into sections alongside each
762
+ * section's exact slice of raw events, so rendering and extraction can never drift
763
+ * off by one section.
623
764
  */
624
- export function buildSections(events) {
765
+ function buildSectionsWithEvents(events) {
625
766
  const sections = [];
767
+ const sectionEvents = [];
626
768
  let current;
769
+ let currentEvents;
627
770
  let currentTurn;
628
771
  let lastTurn;
772
+ const startSection = () => {
773
+ current = { turns: [] };
774
+ currentEvents = [];
775
+ sections.push(current);
776
+ sectionEvents.push(currentEvents);
777
+ };
629
778
  const openTurn = (turn, fromRequest = false) => {
630
- if (current === undefined) {
631
- current = { turns: [] };
632
- sections.push(current);
633
- }
779
+ if (current === undefined)
780
+ startSection();
634
781
  const next = emptyTurn(turn, fromRequest);
635
782
  current.turns.push(next);
636
783
  if (turn !== undefined)
637
784
  lastTurn = turn;
638
785
  return next;
639
786
  };
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
787
  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
- 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.
788
+ const questionSpecs = new Map();
653
789
  const questionCallIds = new Set();
654
790
  for (const event of events) {
655
791
  if (event.type === 'turn/start') {
656
792
  const turn = turnOf(event);
657
793
  if (turn !== undefined)
658
794
  lastTurn = turn;
795
+ currentEvents?.push(event);
659
796
  continue;
660
797
  }
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))
798
+ if (sourceKind(event) === 'goal') {
799
+ const objective = goalObjective(event);
800
+ if (objective === undefined || recordedObjectives.has(objective)) {
801
+ // Auto todo-continuation goals, malformed goals, and repeated rounds never
802
+ // penetrate into human `## user` sections.
668
803
  continue;
804
+ }
669
805
  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);
806
+ startSection();
674
807
  currentTurn = openTurn(turnOf(event) ?? lastTurn, false);
675
808
  currentTurn.user.push(objective);
809
+ currentEvents.push(event);
676
810
  continue;
677
811
  }
678
812
  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.
813
+ currentEvents?.push(event);
681
814
  const callId = messageOf(event)?.toolCallId;
682
815
  if (callId === undefined || !questionCallIds.has(callId) || currentTurn === undefined)
683
816
  continue;
684
- currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
817
+ currentTurn.answered.push(...answersOf(textOf(event), questionSpecs));
685
818
  continue;
686
819
  }
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
820
  if (sourceKind(event) === 'user-question-reply') {
821
+ currentEvents?.push(event);
693
822
  if (currentTurn !== undefined)
694
- currentTurn.answered.push(...answersOf(textOf(event), questionTexts));
823
+ currentTurn.answered.push(...answersOf(textOf(event), questionSpecs));
695
824
  continue;
696
825
  }
697
826
  if (event.type !== 'user/message' && event.type !== 'assistant/message')
@@ -700,49 +829,45 @@ export function buildSections(events) {
700
829
  continue;
701
830
  const eventTurn = turnOf(event) ?? lastTurn;
702
831
  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);
832
+ startSection();
708
833
  currentTurn = openTurn(eventTurn, true);
709
834
  const text = textOf(event);
710
835
  if (text.length > 0)
711
836
  currentTurn.user.push(text);
837
+ currentEvents.push(event);
712
838
  continue;
713
839
  }
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
840
  if (currentTurn === undefined)
726
841
  currentTurn = openTurn(eventTurn ?? lastTurn);
842
+ currentEvents?.push(event);
727
843
  const text = textOf(event);
728
844
  if (text.length > 0)
729
845
  currentTurn.assistant.push(text);
730
846
  for (const call of toolCallsOf(event)) {
731
- currentTurn.tools.set(call.name, (currentTurn.tools.get(call.name) ?? 0) + 1);
732
847
  if (call.name === 'ask_user_question') {
733
- for (const [id, question] of questionTextsOf(call.arguments))
734
- questionTexts.set(id, question);
848
+ for (const [id, spec] of questionSpecsOf(call.arguments))
849
+ questionSpecs.set(id, spec);
735
850
  questionCallIds.add(call.id);
736
851
  continue;
737
852
  }
738
853
  if (!WRITE_TOOLS.has(call.name))
739
854
  continue;
740
- const path = pathArgumentOf(call.arguments);
741
- if (path !== undefined && !currentTurn.writes.includes(path))
742
- currentTurn.writes.push(path);
855
+ for (const path of writePathsOf(call.name, call.arguments)) {
856
+ if (!currentTurn.writes.includes(path))
857
+ currentTurn.writes.push(path);
858
+ }
743
859
  }
744
860
  }
745
- return sections;
861
+ return { sections, sectionEvents };
862
+ }
863
+ /**
864
+ * Group append-origin surface events into per-turn digest material.
865
+ *
866
+ * @param events - the digest source in log order.
867
+ * @returns one section per non-injected user message.
868
+ */
869
+ export function buildSections(events) {
870
+ return buildSectionsWithEvents(events).sections;
746
871
  }
747
872
  /**
748
873
  * Attach extracted blocks to the turns they belong to.
@@ -809,13 +934,13 @@ function hashText(input) {
809
934
  * @param events - one slot's events, in log order.
810
935
  * @returns a stable hex key.
811
936
  */
812
- function materialKey(events) {
937
+ function materialKey(events, options) {
813
938
  const prose = events
814
939
  .filter((event) => event.type === 'assistant/message')
815
940
  .map((event) => textOf(event))
816
941
  .filter((text) => text.length > 0)
817
942
  .join('\n');
818
- return hashText(buildExtractionMaterial(events, prose));
943
+ return hashText(buildExtractionMaterial(events, prose, options));
819
944
  }
820
945
  /**
821
946
  * Render one section to digest text, truncating assistant prose to `capChars`.
@@ -828,12 +953,178 @@ function materialKey(events) {
828
953
  * The tool pointer line stays either way: it is one line, and it is the only
829
954
  * record of what was actually run when the prose and extraction both say little.
830
955
  */
831
- function renderSection(section, level, condensed, sectionIndex) {
956
+ /** Generic Chinese/English question boilerplate excluded from token-overlap dedupe. */
957
+ const QUESTION_STOP_TOKENS = new Set([
958
+ '是否', '要不要', '怎么', '如何', '哪个', '哪种', '哪一', '哪些', '什么', '还是', '或者', '以及',
959
+ '一下', '一起', '一并', '继续', '现在', '需要', '可以', '应该', '确认', '决定', '选择', '处理',
960
+ '修改', '改动', '保留', '不动', '直接', '如果', '那么', '这个', '那个', '这两', '两项', '两处',
961
+ '三处', '四处', '用户', '拍板', '我们', '你们', '他们', '已经', '不要', '不行',
962
+ 'the', 'and', 'for', 'with', 'this', 'that', 'from', 'should', 'would', 'which', 'what', 'how',
963
+ 'are', 'you', 'can', 'not', 'use', 'into', 'about', 'want', 'keep', 'change', 'yes', 'no',
964
+ ]);
965
+ function stripRecommendationTag(text) {
966
+ return text.replace(/[((]\s*(?:推荐|recommended)\s*[))]/gi, '');
967
+ }
968
+ /** Normalize a question or option string for fuzzy duplicate comparison between Answers and Asked. */
969
+ function normalizeQuestionText(text) {
970
+ return stripRecommendationTag(text).toLowerCase().replace(/[\s\p{P}\p{S}]+/gu, '');
971
+ }
972
+ /** Extract substantive ASCII words and CJK bigrams for cross-question paraphrase matching. */
973
+ function extractQuestionTokens(text) {
974
+ const lower = stripRecommendationTag(text).toLowerCase();
975
+ const tokens = new Set();
976
+ for (const match of lower.matchAll(/[a-z0-9_]{2,}/g)) {
977
+ const token = match[0];
978
+ if (!QUESTION_STOP_TOKENS.has(token))
979
+ tokens.add(token);
980
+ }
981
+ for (const match of lower.matchAll(/[\p{Script=Han}]{2,}/gu)) {
982
+ const run = match[0];
983
+ for (let i = 0; i < run.length - 1; i += 1) {
984
+ const bigram = run.slice(i, i + 2);
985
+ if (!QUESTION_STOP_TOKENS.has(bigram))
986
+ tokens.add(bigram);
987
+ }
988
+ }
989
+ return tokens;
990
+ }
991
+ function tokenOverlapCount(source, target) {
992
+ let hits = 0;
993
+ for (const token of source) {
994
+ if (target.has(token))
995
+ hits += 1;
996
+ }
997
+ return hits;
998
+ }
999
+ function toOptionMatchTarget(text) {
1000
+ return {
1001
+ norm: normalizeQuestionText(text),
1002
+ tokens: extractQuestionTokens(text),
1003
+ };
1004
+ }
1005
+ function optionMatchesTarget(candidate, target) {
1006
+ if (candidate.norm.length >= 5
1007
+ && target.norm.length >= 5
1008
+ && (target.norm.includes(candidate.norm) || candidate.norm.includes(target.norm))) {
1009
+ return true;
1010
+ }
1011
+ if (candidate.tokens.size >= 3 && target.tokens.size >= 3) {
1012
+ const hits = tokenOverlapCount(candidate.tokens, target.tokens);
1013
+ if (hits >= 3 && hits / candidate.tokens.size >= 0.6)
1014
+ return true;
1015
+ }
1016
+ return false;
1017
+ }
1018
+ /** Drop `asked` entries that duplicate or paraphrase questions already answered via `ask_user_question` in the same turn. */
1019
+ function dedupeAskedAgainstAnswers(extraction, answered) {
1020
+ if (answered.length === 0 || extraction.asked.length === 0)
1021
+ return extraction;
1022
+ const answeredNorms = answered.map((item) => normalizeQuestionText(item.question)).filter((q) => q.length > 0);
1023
+ if (answeredNorms.length === 0)
1024
+ return extraction;
1025
+ // Combined question + answer token corpus catches merged paraphrases across multiple
1026
+ // answered questions; unselected options stay out of this corpus so a later follow-up
1027
+ // prose question sharing a domain noun does not cross-bleed.
1028
+ const corpusTokens = new Set();
1029
+ const answerTargets = [];
1030
+ const offeredTargets = [];
1031
+ for (const item of answered) {
1032
+ for (const token of extractQuestionTokens(item.question))
1033
+ corpusTokens.add(token);
1034
+ for (const selected of item.selected) {
1035
+ for (const token of extractQuestionTokens(selected))
1036
+ corpusTokens.add(token);
1037
+ const target = toOptionMatchTarget(selected);
1038
+ if (target.norm.length >= 5 || target.tokens.size >= 3)
1039
+ answerTargets.push(target);
1040
+ }
1041
+ if (item.typed.length > 0) {
1042
+ for (const token of extractQuestionTokens(item.typed))
1043
+ corpusTokens.add(token);
1044
+ const target = toOptionMatchTarget(item.typed);
1045
+ if (target.norm.length >= 5 || target.tokens.size >= 3)
1046
+ answerTargets.push(target);
1047
+ }
1048
+ for (const opt of item.options) {
1049
+ const target = toOptionMatchTarget(opt);
1050
+ if (target.norm.length >= 5 || target.tokens.size >= 3)
1051
+ offeredTargets.push(target);
1052
+ }
1053
+ }
1054
+ const filtered = extraction.asked.filter((pair) => {
1055
+ const q = normalizeQuestionText(pair.question);
1056
+ if (q.length === 0)
1057
+ return true;
1058
+ if (answeredNorms.some((ans) => (ans === q
1059
+ || (q.length >= 4 && ans.length >= 4 && (ans.includes(q) || q.includes(ans)))))) {
1060
+ return false;
1061
+ }
1062
+ const qTokens = extractQuestionTokens(pair.question);
1063
+ if (qTokens.size > 0 && corpusTokens.size > 0) {
1064
+ const hits = tokenOverlapCount(qTokens, corpusTokens);
1065
+ const ratio = hits / qTokens.size;
1066
+ if ((hits >= 3 && ratio >= 0.4) || (hits >= 5 && ratio >= 0.35))
1067
+ return false;
1068
+ }
1069
+ if (pair.options.length > 0 && (answerTargets.length > 0 || offeredTargets.length > 0)) {
1070
+ const matchedOfferedIndices = new Set();
1071
+ for (const opt of pair.options) {
1072
+ const candidate = toOptionMatchTarget(opt);
1073
+ if (answerTargets.some((target) => optionMatchesTarget(candidate, target)))
1074
+ return false;
1075
+ for (let i = 0; i < offeredTargets.length; i += 1) {
1076
+ if (optionMatchesTarget(candidate, offeredTargets[i])) {
1077
+ matchedOfferedIndices.add(i);
1078
+ break;
1079
+ }
1080
+ }
1081
+ }
1082
+ if (matchedOfferedIndices.size >= 2)
1083
+ return false;
1084
+ }
1085
+ return true;
1086
+ });
1087
+ return filtered.length === extraction.asked.length ? extraction : { ...extraction, asked: filtered };
1088
+ }
1089
+ /** Whether a section's `## Asked` should survive into the digest. */
1090
+ function shouldKeepAsked(sections, sectionIndex) {
1091
+ const isLast = sectionIndex === sections.length - 1;
1092
+ if (isLast)
1093
+ return true;
1094
+ const nextUser = sections[sectionIndex + 1]?.turns[0]?.user.join('\n').trim() ?? '';
1095
+ return nextUser.length > 0 && nextUser.length <= SHORT_REPLY_MAX_CHARS;
1096
+ }
1097
+ /** Index of the latest section carrying a real user request, falling back to the final section. */
1098
+ function lastRealUserSectionIndex(sections) {
1099
+ for (let i = sections.length - 1; i >= 0; i -= 1) {
1100
+ if (sections[i]?.turns.some((turn) => turn.fromRequest && turn.user.length > 0))
1101
+ return i;
1102
+ }
1103
+ return sections.length - 1;
1104
+ }
1105
+ /** Keep the latest section and the latest real user request unclipped; clip oversized pastes in older sections. */
1106
+ function shouldKeepFullUser(sections, sectionIndex) {
1107
+ if (sections === undefined)
1108
+ return true;
1109
+ if (sectionIndex === sections.length - 1)
1110
+ return true;
1111
+ return sectionIndex === lastRealUserSectionIndex(sections);
1112
+ }
1113
+ /** Format a turn's user prose, clipping oversized pastes in older (non-latest) sections. */
1114
+ function formatUserText(texts, keepFullUser) {
1115
+ if (keepFullUser)
1116
+ return texts.join('\n');
1117
+ return texts
1118
+ .map((text) => clipHeadTail(text, OLD_USER_PASTE_MAX_CHARS, 1400, 800))
1119
+ .join('\n');
1120
+ }
1121
+ function renderSection(section, level, condensed, sectionIndex, allSections) {
832
1122
  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
1123
  const index = sectionIndex ?? 0;
1124
+ const totalSections = allSections?.length ?? (index + 1);
1125
+ const keepFullUser = shouldKeepFullUser(allSections, index);
1126
+ const compactAnswerStem = index < totalSections - FULL_ANSWER_STEM_RECENT_SECTIONS;
1127
+ const keepAsked = allSections === undefined ? true : shouldKeepAsked(allSections, index);
837
1128
  let covering;
838
1129
  if (condensed !== undefined) {
839
1130
  for (const [key, block] of condensed) {
@@ -845,13 +1136,10 @@ function renderSection(section, level, condensed, sectionIndex) {
845
1136
  }
846
1137
  }
847
1138
  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
1139
  const start = Number(covering.key.split(':')[0]);
852
1140
  for (const turn of section.turns) {
853
1141
  if (turn.user.length > 0)
854
- lines.push(`\n## user\n${turn.user.join('\n')}`);
1142
+ lines.push(`\n## user\n${formatUserText(turn.user, keepFullUser)}`);
855
1143
  }
856
1144
  if (index === start) {
857
1145
  const range = covering.block.covers <= 1
@@ -861,29 +1149,41 @@ function renderSection(section, level, condensed, sectionIndex) {
861
1149
  }
862
1150
  return lines.join('\n');
863
1151
  }
864
- for (const [turnIndex, turn] of section.turns.entries()) {
1152
+ for (const [, turn] of section.turns.entries()) {
865
1153
  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.
1154
+ lines.push(`\n## user\n${formatUserText(turn.user, keepFullUser)}`);
1155
+ const effectiveExtraction = turn.extracted === undefined
1156
+ ? undefined
1157
+ : dedupeAskedAgainstAnswers(turn.extracted, turn.answered);
1158
+ const renderedBlock = renderExtractionBlock(effectiveExtraction, level, keepAsked);
1159
+ if (effectiveExtraction !== undefined && renderedBlock.length > 0) {
874
1160
  const trailer = [];
875
1161
  if (turn.writes.length > 0)
876
1162
  trailer.push(` wrote: ${turn.writes.join(', ')}`);
877
- const withAnswers = insertAnswers(block, renderAnswers(turn));
1163
+ const withAnswers = insertAnswers(renderedBlock, renderAnswers(turn, compactAnswerStem));
878
1164
  const body = trailer.length > 0 ? `${trailer.join('\n')}\n${withAnswers}` : withAnswers;
879
1165
  lines.push(`### assistant\n${body}`);
880
1166
  }
1167
+ else if (turn.extracted !== undefined
1168
+ && (turn.extracted.did.length > 0
1169
+ || turn.extracted.concluded.length > 0
1170
+ || turn.extracted.overturned.length > 0
1171
+ || turn.extracted.asked.length > 0)) {
1172
+ // Extraction succeeded with non-empty fields, and everything was filtered at this
1173
+ // level or dropped as stale Asked. Emit answers/writes if present without falling
1174
+ // back to raw prose.
1175
+ const trailer = [];
1176
+ if (turn.writes.length > 0)
1177
+ trailer.push(` wrote: ${turn.writes.join(', ')}`);
1178
+ const answers = renderAnswers(turn, compactAnswerStem);
1179
+ const parts = [...trailer, answers].filter((part) => part.length > 0);
1180
+ if (parts.length > 0)
1181
+ lines.push(`### assistant\n${parts.join('\n')}`);
1182
+ }
881
1183
  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.
1184
+ const rawBody = turn.assistant.join('\n');
1185
+ const body = clipHeadTail(rawBody, FALLBACK_PROSE_MAX_CHARS, 1000, 1800);
1186
+ const answers = renderAnswers(turn, compactAnswerStem);
887
1187
  if (body.length > 0 || answers.length > 0)
888
1188
  lines.push(`### assistant\n${[body, answers].filter((part) => part.length > 0).join('\n')}`);
889
1189
  if (turn.writes.length > 0)
@@ -892,26 +1192,18 @@ function renderSection(section, level, condensed, sectionIndex) {
892
1192
  }
893
1193
  return lines.join('\n');
894
1194
  }
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) {
1195
+ function renderAnswers(turn, compactStem = false) {
912
1196
  if (turn.answered.length === 0)
913
1197
  return '';
914
- return `## Answers\n${turn.answered.flatMap(renderAnswered).join('\n')}`;
1198
+ const items = compactStem
1199
+ ? turn.answered.map((item) => {
1200
+ const collapsed = item.question.replace(/\s+/g, ' ').trim();
1201
+ return collapsed.length > OLD_ANSWER_STEM_MAX_CHARS
1202
+ ? { ...item, question: `${collapsed.slice(0, OLD_ANSWER_STEM_MAX_CHARS).trimEnd()}…` }
1203
+ : { ...item, question: collapsed };
1204
+ })
1205
+ : turn.answered;
1206
+ return `## Answers\n${items.flatMap(renderAnswered).join('\n')}`;
915
1207
  }
916
1208
  /**
917
1209
  * Place the `## Answers` section just above `## Asked`, or at the end when the
@@ -972,11 +1264,25 @@ function insertAnswers(block, answers) {
972
1264
  * bodies, leaving only `## Asked`, before condensation ever got a chance.
973
1265
  */
974
1266
  export function renderDigest(events, budgetTokens, extracted, condensed) {
975
- const sections = extracted === undefined ? buildSections(events) : withExtractions(buildSections(events), extracted);
1267
+ const rawSections = extracted === undefined ? buildSections(events) : withExtractions(buildSections(events), extracted);
1268
+ // Normalize oversized pastes in older sections before budgeting and T1 so a
1269
+ // single 50k historical paste is billed at its ~2.2k clipped size instead of
1270
+ // starving earlier standing constraints or being truncated twice.
1271
+ const sections = rawSections.map((section, sectionIndex) => (shouldKeepFullUser(rawSections, sectionIndex)
1272
+ ? section
1273
+ : {
1274
+ turns: section.turns.map((turn) => ({
1275
+ ...turn,
1276
+ user: turn.user.map((text) => clipHeadTail(text, OLD_USER_PASTE_MAX_CHARS, 1400, 800)),
1277
+ })),
1278
+ }));
976
1279
  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');
1280
+ const render = (trimmed, level = 3) => {
1281
+ const list = trimmed ?? sections;
1282
+ return list
1283
+ .map((section, index) => renderSection(section, level, condensed, index, list))
1284
+ .join('\n');
1285
+ };
980
1286
  // User prose is reserved before anything else is placed.
981
1287
  //
982
1288
  // Measured on a 122-turn session: every human message in the span totalled 469
@@ -1166,9 +1472,25 @@ export function renderDigest(events, budgetTokens, extracted, condensed) {
1166
1472
  */
1167
1473
  export function shadowedSeqs(session, input) {
1168
1474
  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);
1475
+ const firstEvent = nodes[0] !== undefined ? session.eventAt(nodes[0]) : undefined;
1476
+ const head = firstEvent?.type === 'system/message' ? 1 : 0;
1477
+ const messageCount = Math.max(0, input.messages.length - head);
1478
+ if (messageCount === 0)
1479
+ return [];
1480
+ // Match surface nodes that actually derive to a message: the host's
1481
+ // `buildSummarizationInput` skips nodes whose `deriveEventMessage` is null,
1482
+ // while the replaced span still covers every surface node through the last
1483
+ // shadowed message.
1484
+ let seenMessages = 0;
1485
+ let endIndex = head;
1486
+ for (let i = head; i < nodes.length && seenMessages < messageCount; i += 1) {
1487
+ const seq = nodes[i];
1488
+ const ev = seq === undefined ? undefined : session.eventAt(seq);
1489
+ if (ev !== undefined && messageOf(ev) !== null)
1490
+ seenMessages += 1;
1491
+ endIndex = i + 1;
1492
+ }
1493
+ return nodes.slice(head, endIndex);
1172
1494
  }
1173
1495
  /**
1174
1496
  * Pick the log events the digest is built from: every append-origin surface
@@ -1216,204 +1538,336 @@ export function digestSource(session, retainedSeqs) {
1216
1538
  * @param prose - that turn's assistant prose, already extracted by the caller.
1217
1539
  * @returns the joined material, or an empty string when the turn has nothing.
1218
1540
  */
1219
- export function buildExtractionMaterial(turn, prose) {
1541
+ /** Sample non-error, non-question tool results for single-turn tool-heavy (subagent) runs. */
1542
+ function sampleToolResults(turn) {
1543
+ const questionCallIds = new Set();
1544
+ const callNames = new Map();
1545
+ for (const event of turn) {
1546
+ if (event.type !== 'assistant/message')
1547
+ continue;
1548
+ for (const call of toolCallsOf(event)) {
1549
+ callNames.set(call.id, call.name);
1550
+ if (call.name === 'ask_user_question')
1551
+ questionCallIds.add(call.id);
1552
+ }
1553
+ }
1554
+ const collected = [];
1555
+ let budget = SAMPLED_TOOL_RESULT_TOTAL_CHARS;
1556
+ for (let i = turn.length - 1; i >= 0 && budget > 0; i -= 1) {
1557
+ const event = turn[i];
1558
+ if (event === undefined || event.type !== 'tool/result')
1559
+ continue;
1560
+ const msg = messageOf(event);
1561
+ if (msg === null || msg.isError === true)
1562
+ continue;
1563
+ const callId = msg.toolCallId;
1564
+ if (callId !== undefined && questionCallIds.has(callId))
1565
+ continue;
1566
+ const raw = textOf(event).replace(/\s+/g, ' ').trim();
1567
+ if (raw.length === 0)
1568
+ continue;
1569
+ const snippet = raw.slice(0, Math.min(SAMPLED_TOOL_RESULT_PER_CALL_CHARS, budget));
1570
+ const toolLabel = callId !== undefined ? (callNames.get(callId) ?? 'tool') : 'tool';
1571
+ const entry = `[${toolLabel}] ${snippet}`;
1572
+ collected.push(entry);
1573
+ budget -= entry.length + 1;
1574
+ }
1575
+ return collected.reverse().join('\n');
1576
+ }
1577
+ export function buildExtractionMaterial(turn, prose, options) {
1220
1578
  const userRequest = turn
1221
- .filter((event) => event.type === 'user/message' && !isInjection(event) && !isCheckpoint(event))
1222
- .map((event) => textOf(event))
1579
+ .filter((event) => {
1580
+ if (event.type !== 'user/message' || isCheckpoint(event))
1581
+ return false;
1582
+ if (sourceKind(event) === 'goal')
1583
+ return goalObjective(event) !== undefined;
1584
+ return !isInjection(event);
1585
+ })
1586
+ .map((event) => (sourceKind(event) === 'goal' ? (goalObjective(event) ?? '') : textOf(event)))
1223
1587
  .filter((text) => text.length > 0)
1224
1588
  .join('\n');
1225
1589
  const hints = collectHints(turn);
1226
- if (userRequest.length === 0 && prose.length === 0 && hints.length === 0)
1590
+ const toolResults = options?.includeToolResults === true ? sampleToolResults(turn) : '';
1591
+ if (userRequest.length === 0 && prose.length === 0 && hints.length === 0 && toolResults.length === 0)
1227
1592
  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)'}`,
1593
+ const clippedUser = clipHeadTail(userRequest, 4000, 2500, 1400);
1594
+ const clippedProse = clipHeadTail(prose, 6000, 2000, 3900);
1595
+ const sections = [
1596
+ `USER INSTRUCTION (already in the digest verbatim; never copy it into Asked):\n${clippedUser || '(none)'}`,
1597
+ `ASSISTANT PROSE:\n${clippedProse || '(none)'}`,
1231
1598
  `TOOL TRACE:\n${hints || '(none)'}`,
1232
- ].join('\n\n');
1599
+ ];
1600
+ if (toolResults.length > 0) {
1601
+ sections.push(`KEY TOOL RESULTS (sampled from tool-heavy single-turn run):\n${toolResults}`);
1602
+ }
1603
+ return sections.join('\n\n');
1233
1604
  }
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) {
1605
+ function createUsageAccumulator() {
1606
+ return {
1607
+ seen: false,
1608
+ inputTokens: 0,
1609
+ outputTokens: 0,
1610
+ totalTokens: 0,
1611
+ hasTotalTokens: false,
1612
+ cacheReadTokens: 0,
1613
+ hasCacheRead: false,
1614
+ cacheWriteTokens: 0,
1615
+ hasCacheWrite: false,
1616
+ reasoningTokens: 0,
1617
+ hasReasoning: false,
1618
+ };
1619
+ }
1620
+ function addUsage(acc, usage) {
1621
+ if (acc === undefined || typeof usage !== 'object' || usage === null)
1622
+ return;
1623
+ const u = usage;
1624
+ const input = typeof u['inputTokens'] === 'number' ? u['inputTokens'] : 0;
1625
+ const output = typeof u['outputTokens'] === 'number' ? u['outputTokens'] : 0;
1626
+ if (input === 0 && output === 0 && typeof u['totalTokens'] !== 'number')
1627
+ return;
1628
+ acc.seen = true;
1629
+ acc.inputTokens += input;
1630
+ acc.outputTokens += output;
1631
+ if (typeof u['totalTokens'] === 'number') {
1632
+ acc.hasTotalTokens = true;
1633
+ acc.totalTokens += u['totalTokens'];
1634
+ }
1635
+ if (typeof u['cacheReadTokens'] === 'number') {
1636
+ acc.hasCacheRead = true;
1637
+ acc.cacheReadTokens += u['cacheReadTokens'];
1638
+ }
1639
+ if (typeof u['cacheWriteTokens'] === 'number') {
1640
+ acc.hasCacheWrite = true;
1641
+ acc.cacheWriteTokens += u['cacheWriteTokens'];
1642
+ }
1643
+ if (typeof u['reasoningTokens'] === 'number') {
1644
+ acc.hasReasoning = true;
1645
+ acc.reasoningTokens += u['reasoningTokens'];
1646
+ }
1647
+ }
1648
+ function toTokenUsage(acc) {
1649
+ if (!acc.seen)
1650
+ return undefined;
1651
+ return {
1652
+ inputTokens: acc.inputTokens,
1653
+ outputTokens: acc.outputTokens,
1654
+ ...(acc.hasTotalTokens ? { totalTokens: acc.totalTokens } : {}),
1655
+ ...(acc.hasCacheRead ? { cacheReadTokens: acc.cacheReadTokens } : {}),
1656
+ ...(acc.hasCacheWrite ? { cacheWriteTokens: acc.cacheWriteTokens } : {}),
1657
+ ...(acc.hasReasoning ? { reasoningTokens: acc.reasoningTokens } : {}),
1658
+ };
1659
+ }
1660
+ /** Resolve the effective provider and model after applying any configured purpose override. */
1661
+ function resolveEffectiveRoute(agent, override) {
1662
+ const sessionRoute = agent.session.requestHeader()?.config;
1663
+ const baseProvider = sessionRoute?.provider ?? agent.options.provider;
1664
+ const baseModel = sessionRoute?.model ?? agent.options.model;
1665
+ const paired = pairedRouteOf(override);
1666
+ const provider = paired?.provider ?? baseProvider;
1667
+ const model = paired?.model ?? baseModel;
1668
+ if (provider === undefined || model === undefined)
1669
+ return undefined;
1670
+ return { provider, model };
1671
+ }
1672
+ /** Read the per-call LLM timeout in ms, honoring an optional environment override. */
1673
+ function resolveCallTimeoutMs() {
1674
+ const raw = process.env['DSH_VERBATIM_CALL_TIMEOUT_MS'];
1675
+ if (raw !== undefined) {
1676
+ const parsed = Number(raw);
1677
+ if (Number.isFinite(parsed) && parsed > 0)
1678
+ return parsed;
1679
+ }
1680
+ return DEFAULT_LLM_CALL_TIMEOUT_MS;
1681
+ }
1682
+ /** Combine an optional outer AbortSignal with a per-call timeout. */
1683
+ function withCallTimeout(signal, timeoutMs) {
1684
+ const controller = new AbortController();
1685
+ const onAbort = () => {
1686
+ controller.abort(signal?.reason);
1687
+ };
1688
+ if (signal !== undefined) {
1689
+ if (signal.aborted) {
1690
+ controller.abort(signal.reason);
1691
+ return { signal: controller.signal, dispose: () => { } };
1692
+ }
1693
+ signal.addEventListener('abort', onAbort, { once: true });
1694
+ }
1695
+ const timer = setTimeout(() => {
1696
+ controller.abort(new Error(`verbatim-compaction call timed out after ${timeoutMs}ms`));
1697
+ }, timeoutMs);
1698
+ if (typeof timer === 'object' && timer !== null && 'unref' in timer && typeof timer.unref === 'function') {
1699
+ timer.unref();
1700
+ }
1701
+ return {
1702
+ signal: controller.signal,
1703
+ dispose: () => {
1704
+ clearTimeout(timer);
1705
+ signal?.removeEventListener('abort', onAbort);
1706
+ },
1707
+ };
1708
+ }
1709
+ /** Flatten folded model output into one clean bullet-safe paragraph (no code fences, headings, or multiline breaks). */
1710
+ function sanitizeCondensedText(raw) {
1711
+ const unfenced = raw.trim().replace(/^```[a-zA-Z0-9_-]*\s*/i, '').replace(/\s*```$/, '').trim();
1712
+ const cleanedLines = unfenced
1713
+ .split(/\r?\n/)
1714
+ .map((line) => line
1715
+ .trim()
1716
+ .replace(/^#{1,6}\s+/, '')
1717
+ .replace(/^[-*•]\s+/, '')
1718
+ .trim())
1719
+ .filter((line) => line.length > 0 && !/^```/.test(line));
1720
+ return cleanedLines.join(' ').replace(/\s+/g, ' ').trim();
1721
+ }
1722
+ /** Bounded LRU-like Map read/write helpers. */
1723
+ function boundedCacheGet(map, key) {
1724
+ const value = map.get(key);
1725
+ if (value !== undefined) {
1726
+ map.delete(key);
1727
+ map.set(key, value);
1728
+ }
1729
+ return value;
1730
+ }
1731
+ function boundedCacheSet(map, key, value, maxSize) {
1732
+ if (map.has(key))
1733
+ map.delete(key);
1734
+ map.set(key, value);
1735
+ while (map.size > maxSize) {
1736
+ const oldest = map.keys().next().value;
1737
+ if (oldest === undefined)
1738
+ break;
1739
+ map.delete(oldest);
1740
+ }
1741
+ }
1742
+ /** Directory for persistent per-session caches, or undefined when disabled (e.g. under node --test). */
1743
+ function resolveCacheDir() {
1744
+ const explicit = process.env['DSH_VERBATIM_CACHE_DIR'];
1745
+ if (explicit !== undefined) {
1746
+ const trimmed = explicit.trim();
1747
+ if (trimmed === '' || /^(?:off|none|false|0)$/i.test(trimmed))
1748
+ return undefined;
1749
+ return trimmed;
1750
+ }
1751
+ if (process.env['NODE_TEST_CONTEXT'] !== undefined)
1752
+ return undefined;
1753
+ const base = process.env['DSH_HOME']?.trim() || join(homedir(), '.dsh');
1754
+ return join(base, 'cache', 'verbatim-compaction');
1755
+ }
1756
+ function cacheFilePath(dir, sessionId) {
1757
+ const safeId = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_') || 'default';
1758
+ return join(dir, `${safeId}.json`);
1759
+ }
1760
+ async function condenseOnce(ctx, agent, material, signal, override, usageAcc) {
1272
1761
  const llm = ctx.llm;
1273
1762
  if (llm === undefined) {
1274
1763
  ctx.logger?.warn('verbatim-compaction: no llm service, condensation skipped');
1275
1764
  return undefined;
1276
1765
  }
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) {
1766
+ const effective = resolveEffectiveRoute(agent, override);
1767
+ if (effective === undefined) {
1281
1768
  ctx.logger?.warn('verbatim-compaction: no route for condensation, skipped');
1282
1769
  return undefined;
1283
1770
  }
1284
- const info = await Promise.resolve()
1285
- .then(() => llm.resolveModelInfo?.(provider, model, signal))
1286
- .catch(() => undefined);
1287
- const cheapest = cheapestEffort(info?.reasoning?.efforts);
1771
+ const call = withCallTimeout(signal, resolveCallTimeoutMs());
1288
1772
  const chunks = [];
1289
1773
  try {
1774
+ const info = await Promise.resolve()
1775
+ .then(() => llm.resolveModelInfo?.(effective.provider, effective.model, call.signal))
1776
+ .catch(() => undefined);
1777
+ const cheapest = cheapestEffort(info?.reasoning?.efforts);
1290
1778
  const stream = llm.stream(applyPurposeOverride({
1291
- provider,
1292
- model,
1779
+ provider: effective.provider,
1780
+ model: effective.model,
1293
1781
  messages: [{ role: 'user', content: [{ type: 'text', text: `${material}\n\n${CONDENSE_INSTRUCTION}` }] }],
1294
1782
  maxTokens: CONDENSE_TOKENS,
1295
1783
  sessionId: agent.session.id,
1296
1784
  purpose: 'compaction',
1297
- ...(signal === undefined ? {} : { signal }),
1785
+ signal: call.signal,
1298
1786
  }, override, cheapest));
1299
1787
  for await (const chunk of stream) {
1300
1788
  const delta = chunk;
1301
1789
  if (delta.type === 'text-delta' && typeof delta.text === 'string')
1302
1790
  chunks.push(delta.text);
1791
+ else if (delta.type === 'finish')
1792
+ addUsage(usageAcc, delta.usage);
1303
1793
  }
1304
1794
  }
1305
1795
  catch (error) {
1306
1796
  ctx.logger?.warn(`verbatim-compaction: condensation call failed: ${String(error)}`);
1307
1797
  return undefined;
1308
1798
  }
1309
- const text = chunks.join('').trim();
1799
+ finally {
1800
+ call.dispose();
1801
+ }
1802
+ const text = sanitizeCondensedText(chunks.join(''));
1310
1803
  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
1804
  ctx.logger?.warn(`verbatim-compaction: condensation returned no text for ${material.length} chars of material`);
1314
1805
  return undefined;
1315
1806
  }
1316
1807
  return text;
1317
1808
  }
1318
- async function extractBatch(ctx, agent, batch, signal, override) {
1809
+ async function extractBatch(ctx, agent, batch, signal, override, usageAcc) {
1319
1810
  const out = new Map();
1320
- if (batch.length === 0)
1811
+ const isAborted = () => signal?.aborted === true;
1812
+ if (batch.length === 0 || isAborted())
1321
1813
  return out;
1322
- const attempt = await extractOnce(ctx, agent, batch, signal, override);
1323
- if (!attempt.truncated) {
1814
+ const attempt = await extractOnce(ctx, agent, batch, signal, override, usageAcc);
1815
+ if (attempt.transportError)
1816
+ return attempt.blocks;
1817
+ const needsSplit = attempt.truncated || (attempt.blocks.size === 0 && batch.length > 1 && !isAborted());
1818
+ if (!needsSplit) {
1324
1819
  if (attempt.blocks.size === 0) {
1325
1820
  ctx.logger?.warn(`verbatim-compaction: extraction returned no usable JSON for ${batch.length} slot(s) `
1326
1821
  + `(${batch.map((slot) => slot.key).join(', ')}); those turns keep their verbatim prose`);
1327
1822
  }
1328
1823
  return attempt.blocks;
1329
1824
  }
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
1825
  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');
1826
+ if (attempt.blocks.size === 0) {
1827
+ ctx.logger?.warn(`verbatim-compaction: extraction truncated at the token cap for slot ${batch[0]?.key ?? '?'}; `
1828
+ + 'that turn keeps its verbatim prose');
1829
+ }
1338
1830
  return attempt.blocks;
1339
1831
  }
1340
1832
  for (const [key, block] of attempt.blocks)
1341
1833
  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))
1834
+ const remaining = batch.filter((slot) => !out.has(slot.key));
1835
+ if (remaining.length === 0)
1836
+ return out;
1837
+ if (remaining.length === 1) {
1838
+ if (!isAborted()) {
1839
+ for (const [key, block] of await extractBatch(ctx, agent, remaining, signal, override, usageAcc))
1840
+ out.set(key, block);
1841
+ }
1842
+ return out;
1843
+ }
1844
+ const middle = Math.ceil(remaining.length / 2);
1845
+ for (const half of [remaining.slice(0, middle), remaining.slice(middle)]) {
1846
+ if (half.length === 0 || isAborted())
1847
+ continue;
1848
+ for (const [key, block] of await extractBatch(ctx, agent, half, signal, override, usageAcc))
1345
1849
  out.set(key, block);
1346
1850
  }
1347
1851
  return out;
1348
1852
  }
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
1853
  function cheapestEffort(efforts) {
1363
- return efforts?.find((entry) => entry.id !== 'off')?.id;
1854
+ if (efforts === undefined)
1855
+ return undefined;
1856
+ for (const entry of efforts) {
1857
+ const id = typeof entry === 'string' ? entry : entry.id;
1858
+ if (id !== 'off')
1859
+ return id;
1860
+ }
1861
+ return undefined;
1364
1862
  }
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) {
1863
+ async function extractOnce(ctx, agent, batch, signal, override, usageAcc) {
1405
1864
  const out = new Map();
1406
1865
  const llm = ctx.llm;
1407
1866
  if (llm === undefined)
1408
1867
  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)
1868
+ const effective = resolveEffectiveRoute(agent, override);
1869
+ if (effective === undefined)
1413
1870
  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
1871
  const parts = [];
1418
1872
  for (const slot of batch) {
1419
1873
  const prose = slot.events
@@ -1421,48 +1875,82 @@ async function extractOnce(ctx, agent, batch, signal, override) {
1421
1875
  .map((event) => textOf(event))
1422
1876
  .filter((text) => text.length > 0)
1423
1877
  .join('\n');
1424
- const material = buildExtractionMaterial(slot.events, prose);
1878
+ const material = buildExtractionMaterial(slot.events, prose, slot.includeToolResults === true ? { includeToolResults: true } : undefined);
1425
1879
  if (material.length === 0)
1426
1880
  continue;
1427
1881
  parts.push(`=== SLOT ${slot.key} (turn ${slot.turn ?? '?'}) ===\n${material}`);
1428
1882
  }
1429
1883
  if (parts.length === 0)
1430
1884
  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);
1885
+ const call = withCallTimeout(signal, resolveCallTimeoutMs());
1435
1886
  const chunks = [];
1436
1887
  let truncated = false;
1437
1888
  try {
1889
+ const info = await Promise.resolve()
1890
+ .then(() => llm.resolveModelInfo?.(effective.provider, effective.model, call.signal))
1891
+ .catch(() => undefined);
1892
+ const cheapest = cheapestEffort(info?.reasoning?.efforts);
1438
1893
  const stream = llm.stream(applyPurposeOverride({
1439
- provider,
1440
- model,
1894
+ provider: effective.provider,
1895
+ model: effective.model,
1441
1896
  messages: [
1442
1897
  { role: 'user', content: [{ type: 'text', text: `${parts.join('\n\n')}\n\n${EXTRACT_INSTRUCTION}` }] },
1443
1898
  ],
1444
1899
  maxTokens: EXTRACT_TOKENS_PER_TURN * parts.length + EXTRACT_THINKING_RESERVE_TOKENS,
1445
1900
  sessionId: agent.session.id,
1446
1901
  purpose: 'compaction',
1447
- ...(signal === undefined ? {} : { signal }),
1902
+ signal: call.signal,
1448
1903
  }, override, cheapest));
1449
1904
  for await (const chunk of stream) {
1450
1905
  const delta = chunk;
1451
1906
  if (delta.type === 'text-delta' && typeof delta.text === 'string')
1452
1907
  chunks.push(delta.text);
1453
- else if (delta.type === 'finish' && delta.reason?.kind === 'max-tokens')
1454
- truncated = true;
1908
+ else if (delta.type === 'finish') {
1909
+ if (delta.reason?.kind === 'max-tokens')
1910
+ truncated = true;
1911
+ addUsage(usageAcc, delta.usage);
1912
+ }
1455
1913
  }
1456
1914
  }
1457
1915
  catch (error) {
1458
1916
  ctx.logger?.warn(`verbatim-compaction: extraction call failed for ${parts.length} slot(s): ${String(error)}`);
1459
- return { blocks: out, truncated: false };
1917
+ const abortedOrTimedOut = call.signal.aborted || signal?.aborted === true;
1918
+ return { blocks: out, truncated: false, transportError: abortedOrTimedOut };
1919
+ }
1920
+ finally {
1921
+ call.dispose();
1460
1922
  }
1461
1923
  const answer = chunks.join('').trim();
1462
1924
  if (answer.length === 0)
1463
1925
  return { blocks: out, truncated };
1464
1926
  return { blocks: parseExtraction(answer), truncated };
1465
1927
  }
1928
+ /** Validate a deserialized extraction object before hydrating from disk cache. */
1929
+ function isValidExtraction(value) {
1930
+ if (value === null || typeof value !== 'object')
1931
+ return false;
1932
+ const rec = value;
1933
+ const isStringArray = (v) => Array.isArray(v) && v.every((item) => typeof item === 'string');
1934
+ if (!isStringArray(rec['did']) || !isStringArray(rec['concluded']) || !isStringArray(rec['overturned'])) {
1935
+ return false;
1936
+ }
1937
+ const asked = rec['asked'];
1938
+ if (!Array.isArray(asked))
1939
+ return false;
1940
+ return asked.every((entry) => {
1941
+ if (entry === null || typeof entry !== 'object')
1942
+ return false;
1943
+ const pair = entry;
1944
+ return typeof pair['question'] === 'string' && isStringArray(pair['options']);
1945
+ });
1946
+ }
1947
+ /** Trim a plain record to its newest `max` entries in insertion order. */
1948
+ function trimRecord(record, max) {
1949
+ const entries = Object.entries(record);
1950
+ if (entries.length <= max)
1951
+ return record;
1952
+ return Object.fromEntries(entries.slice(-max));
1953
+ }
1466
1954
  /**
1467
1955
  * Extractive compaction backend: verbatim user prose, one model call per batch,
1468
1956
  * call.
@@ -1491,13 +1979,95 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1491
1979
  */
1492
1980
  extractionCache = new Map();
1493
1981
  /**
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.
1982
+ * Folded text, keyed by effective provider, model and a hash of the material folded.
1499
1983
  */
1500
1984
  condensedCache = new Map();
1985
+ /** Session ids whose on-disk cache has already been hydrated into memory. */
1986
+ hydratedSessions = new Set();
1987
+ hydrateDiskCache(sessionId) {
1988
+ if (this.hydratedSessions.has(sessionId))
1989
+ return;
1990
+ this.hydratedSessions.add(sessionId);
1991
+ const dir = resolveCacheDir();
1992
+ if (dir === undefined)
1993
+ return;
1994
+ try {
1995
+ const raw = readFileSync(cacheFilePath(dir, sessionId), 'utf8');
1996
+ const parsed = JSON.parse(raw);
1997
+ if (parsed.v !== 1)
1998
+ return;
1999
+ if (parsed.extraction !== undefined && typeof parsed.extraction === 'object' && parsed.extraction !== null) {
2000
+ for (const [key, value] of Object.entries(parsed.extraction)) {
2001
+ if (isValidExtraction(value)) {
2002
+ boundedCacheSet(this.extractionCache, key, value, EXTRACTION_CACHE_MAX);
2003
+ }
2004
+ }
2005
+ }
2006
+ if (parsed.condensed !== undefined && typeof parsed.condensed === 'object' && parsed.condensed !== null) {
2007
+ for (const [key, value] of Object.entries(parsed.condensed)) {
2008
+ if (typeof value === 'string' && value.length > 0) {
2009
+ boundedCacheSet(this.condensedCache, key, value, CONDENSED_CACHE_MAX);
2010
+ }
2011
+ }
2012
+ }
2013
+ }
2014
+ catch {
2015
+ // Cache miss or corrupt file — start cold without failing compaction.
2016
+ }
2017
+ }
2018
+ persistDiskCache(sessionId, newExtractions, newCondensed) {
2019
+ if (newExtractions.size === 0 && newCondensed.size === 0)
2020
+ return;
2021
+ const dir = resolveCacheDir();
2022
+ if (dir === undefined)
2023
+ return;
2024
+ try {
2025
+ mkdirSync(dir, { recursive: true });
2026
+ const target = cacheFilePath(dir, sessionId);
2027
+ let payload = { v: 1, extraction: {}, condensed: {} };
2028
+ try {
2029
+ const existing = JSON.parse(readFileSync(target, 'utf8'));
2030
+ if (existing.v === 1) {
2031
+ const validExtraction = {};
2032
+ if (existing.extraction !== undefined && typeof existing.extraction === 'object' && existing.extraction !== null) {
2033
+ for (const [key, value] of Object.entries(existing.extraction)) {
2034
+ if (isValidExtraction(value))
2035
+ validExtraction[key] = value;
2036
+ }
2037
+ }
2038
+ const validCondensed = {};
2039
+ if (existing.condensed !== undefined && typeof existing.condensed === 'object' && existing.condensed !== null) {
2040
+ for (const [key, value] of Object.entries(existing.condensed)) {
2041
+ if (typeof value === 'string' && value.length > 0)
2042
+ validCondensed[key] = value;
2043
+ }
2044
+ }
2045
+ payload = { v: 1, extraction: validExtraction, condensed: validCondensed };
2046
+ }
2047
+ }
2048
+ catch {
2049
+ // Fresh cache file.
2050
+ }
2051
+ payload.extraction ??= {};
2052
+ payload.condensed ??= {};
2053
+ for (const [key, value] of newExtractions) {
2054
+ delete payload.extraction[key];
2055
+ payload.extraction[key] = value;
2056
+ }
2057
+ for (const [key, value] of newCondensed) {
2058
+ delete payload.condensed[key];
2059
+ payload.condensed[key] = value;
2060
+ }
2061
+ payload.extraction = trimRecord(payload.extraction, EXTRACTION_CACHE_MAX);
2062
+ payload.condensed = trimRecord(payload.condensed, CONDENSED_CACHE_MAX);
2063
+ const tmp = `${target}.${process.pid}.${Date.now()}.${randomBytes(6).toString('hex')}.tmp`;
2064
+ writeFileSync(tmp, JSON.stringify(payload), 'utf8');
2065
+ renameSync(tmp, target);
2066
+ }
2067
+ catch (error) {
2068
+ this.ctx.logger?.warn(`verbatim-compaction: failed to persist cache for ${sessionId}: ${String(error)}`);
2069
+ }
2070
+ }
1501
2071
  /**
1502
2072
  * Build the replacement checkpoint content from the session log.
1503
2073
  *
@@ -1511,10 +2081,11 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1511
2081
  * @param input - replayed conversation prefix the base class is shadowing.
1512
2082
  * @param agent - owner of the session being compacted.
1513
2083
  * @param signal - cancellation forwarded to the extraction and fold calls.
1514
- * @returns text summary blocks, unmarked by any LLM call.
2084
+ * @returns text summary blocks, route metadata, and aggregated LLM usage.
1515
2085
  */
1516
2086
  async summarize(input, agent, signal) {
1517
2087
  const session = agent.session;
2088
+ this.hydrateDiskCache(session.id);
1518
2089
  const shadowed = shadowedSeqs(session, input);
1519
2090
  const shadowedSet = new Set(shadowed);
1520
2091
  const retained = new Set(session.surface.nodes.filter((seq) => !shadowedSet.has(seq)));
@@ -1528,12 +2099,15 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1528
2099
  // size independent of history length; the guard bound only exists for the
1529
2100
  // degenerate case of a span smaller than the ceiling.
1530
2101
  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.
2102
+ const override = getLiveConfig();
2103
+ const usageAcc = createUsageAccumulator();
2104
+ const extracted = await this.extractAll(source, agent, signal, override, usageAcc);
2105
+ // Check overflow against the *unclipped* digest. Measuring `renderDigest(source, budget, extracted)`
2106
+ // was always <= `budget * 4` because `renderDigest` clips to budget, making `condenseOldest` dead code.
1534
2107
  let condensed;
1535
- if (renderDigest(source, budget, extracted).length > budget * 4) {
1536
- condensed = await this.condenseOldest(source, extracted, agent, budget, signal, getLiveConfig());
2108
+ const unclippedLength = renderDigest(source, Math.floor(Number.MAX_SAFE_INTEGER / 4), extracted).length;
2109
+ if (unclippedLength > budget * 4) {
2110
+ condensed = await this.condenseOldest(source, extracted, agent, budget, signal, override, usageAcc);
1537
2111
  }
1538
2112
  // The fold path returns its digest whole, so it can still overflow when every
1539
2113
  // group has been folded and the user lines alone are too long. The budget is a
@@ -1546,58 +2120,34 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1546
2120
  + `(${text.length} > ${budget * 4} chars), falling back to the graded ladder`);
1547
2121
  text = renderDigest(source, budget, extracted);
1548
2122
  }
2123
+ const effective = resolveEffectiveRoute(agent, override);
1549
2124
  const route = session.requestHeader()?.config;
2125
+ const usage = toTokenUsage(usageAcc);
1550
2126
  return {
1551
2127
  summary: [{ type: 'text', text }],
1552
- provider: route?.provider ?? agent.options.provider ?? 'verbatim',
1553
- model: route?.model ?? agent.options.model ?? 'digest',
2128
+ provider: effective?.provider ?? route?.provider ?? agent.options.provider ?? 'verbatim',
2129
+ model: effective?.model ?? route?.model ?? agent.options.model ?? 'digest',
2130
+ ...(usage === undefined ? {} : { usage }),
1554
2131
  };
1555
2132
  }
1556
2133
  /**
1557
2134
  * Fold the oldest turns into condensed blocks until the digest fits.
1558
2135
  *
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.
2136
+ * Only reached when the unclipped plain digest overflows `budget`. The oldest
2137
+ * turns are the right ones to fold: they describe work already superseded, while
2138
+ * the newest are what the next request depends on.
1579
2139
  */
1580
- async condenseOldest(source, extracted, agent, budget, signal, override) {
2140
+ async condenseOldest(source, extracted, agent, budget, signal, override, usageAcc) {
1581
2141
  const sections = withExtractions(buildSections(source), extracted);
1582
2142
  const budgetChars = budget * 4;
1583
2143
  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
2144
  for (const start of foldGroupStarts(sections.length)) {
1592
2145
  if (signal?.aborted === true)
1593
2146
  break;
1594
2147
  const group = sections.slice(start, start + CONDENSE_GROUP);
1595
2148
  if (group.length === 0)
1596
2149
  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.
2150
+ const text = await this.condenseGroup(group, agent, signal, override, usageAcc);
1601
2151
  if (text === undefined)
1602
2152
  continue;
1603
2153
  out.set(turnKey(start, 0), { text, covers: group.length });
@@ -1608,19 +2158,8 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1608
2158
  }
1609
2159
  /**
1610
2160
  * 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
2161
  */
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.
2162
+ async condenseGroup(group, agent, signal, override, usageAcc) {
1624
2163
  const material = group
1625
2164
  .map((section) => section.turns
1626
2165
  .map((turn) => {
@@ -1636,115 +2175,99 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
1636
2175
  const llm = this.ctx.llm;
1637
2176
  if (llm === undefined)
1638
2177
  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)
2178
+ const effective = resolveEffectiveRoute(agent, override);
2179
+ if (effective === undefined)
1643
2180
  return undefined;
1644
- const key = `${provider}:${model}:${hashText(material)}`;
1645
- const cached = this.condensedCache.get(key);
2181
+ const key = `${effective.provider}:${effective.model}:${hashText(material)}`;
2182
+ const cached = boundedCacheGet(this.condensedCache, key);
1646
2183
  if (cached !== undefined)
1647
2184
  return cached;
1648
- const text = await condenseOnce(this.ctx, agent, material, signal, override);
2185
+ const text = await condenseOnce(this.ctx, agent, material, signal, override, usageAcc);
1649
2186
  if (text === undefined)
1650
2187
  return undefined;
1651
- this.condensedCache.set(key, text);
2188
+ boundedCacheSet(this.condensedCache, key, text, CONDENSED_CACHE_MAX);
2189
+ this.persistDiskCache(agent.session.id, new Map(), new Map([[key, text]]));
1652
2190
  return text;
1653
2191
  }
1654
2192
  /**
1655
- * Run the extraction for every turn in the digest source.
2193
+ * Run the extraction for every section in the digest source.
1656
2194
  *
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.
1669
- *
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.
2195
+ * Uses `buildSectionsWithEvents` as the single source of truth so slot keys can
2196
+ * never drift out of alignment with rendered sections. Uncached batches execute
2197
+ * with bounded concurrency (`EXTRACT_CONCURRENCY`), and newly extracted entries
2198
+ * are persisted to the per-session disk cache.
1674
2199
  */
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.
2200
+ async extractAll(source, agent, signal, override, usageAcc) {
2201
+ const { sections, sectionEvents } = buildSectionsWithEvents(source);
2202
+ const singleSection = sections.length === 1;
1719
2203
  const slots = [];
1720
2204
  for (const [sectionIndex, section] of sections.entries()) {
1721
2205
  const first = section.turns[0];
1722
2206
  if (first === undefined)
1723
2207
  continue;
1724
- slots.push({ key: turnKey(sectionIndex, 0), turn: first.turn, events: grouped[sectionIndex] ?? [] });
2208
+ const events = sectionEvents[sectionIndex] ?? [];
2209
+ let includeToolResults = false;
2210
+ if (singleSection) {
2211
+ let toolCallCount = 0;
2212
+ let proseChars = 0;
2213
+ for (const ev of events) {
2214
+ if (ev.type !== 'assistant/message')
2215
+ continue;
2216
+ toolCallCount += toolCallsOf(ev).length;
2217
+ proseChars += textOf(ev).length;
2218
+ }
2219
+ if (toolCallCount >= SINGLE_TURN_TOOL_HEAVY_CALLS && proseChars <= SINGLE_TURN_TOOL_HEAVY_PROSE_MAX) {
2220
+ includeToolResults = true;
2221
+ }
2222
+ }
2223
+ slots.push({
2224
+ key: turnKey(sectionIndex, 0),
2225
+ turn: first.turn,
2226
+ events,
2227
+ ...(includeToolResults ? { includeToolResults: true } : {}),
2228
+ });
1725
2229
  }
2230
+ const effective = resolveEffectiveRoute(agent, override);
2231
+ const routePrefix = effective === undefined ? '' : `${effective.provider}:${effective.model}:`;
2232
+ const cacheKeyFor = (slot) => `${routePrefix}${slot.includeToolResults === true ? 'tr:' : ''}${materialKey(slot.events, slot.includeToolResults === true ? { includeToolResults: true } : undefined)}`;
1726
2233
  const extracted = new Map();
1727
2234
  const missing = [];
1728
2235
  for (const slot of slots) {
1729
- const cached = this.extractionCache.get(materialKey(slot.events));
2236
+ const cached = boundedCacheGet(this.extractionCache, cacheKeyFor(slot));
1730
2237
  if (cached === undefined)
1731
2238
  missing.push(slot);
1732
2239
  else
1733
2240
  extracted.set(slot.key, cached);
1734
2241
  }
2242
+ const batches = [];
1735
2243
  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
- }
2244
+ batches.push(missing.slice(index, index + TURNS_PER_CALL));
1747
2245
  }
2246
+ const newlyExtracted = new Map();
2247
+ let nextBatch = 0;
2248
+ const workerCount = Math.min(EXTRACT_CONCURRENCY, batches.length);
2249
+ const worker = async () => {
2250
+ while (nextBatch < batches.length) {
2251
+ if (signal?.aborted === true)
2252
+ break;
2253
+ const batch = batches[nextBatch];
2254
+ nextBatch += 1;
2255
+ if (batch === undefined)
2256
+ break;
2257
+ const blocks = await extractBatch(this.ctx, agent, batch, signal, override, usageAcc);
2258
+ for (const slot of batch) {
2259
+ const block = blocks.get(slot.key);
2260
+ if (block === undefined)
2261
+ continue;
2262
+ extracted.set(slot.key, block);
2263
+ const ckey = cacheKeyFor(slot);
2264
+ boundedCacheSet(this.extractionCache, ckey, block, EXTRACTION_CACHE_MAX);
2265
+ newlyExtracted.set(ckey, block);
2266
+ }
2267
+ }
2268
+ };
2269
+ await Promise.all(Array.from({ length: workerCount }, () => worker()));
2270
+ this.persistDiskCache(agent.session.id, newlyExtracted, new Map());
1748
2271
  return extracted;
1749
2272
  }
1750
2273
  }