@logictan/dsh-verbatim-compaction 0.13.2 → 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,38 +1,6 @@
1
- /**
2
- * Deterministic, verbatim-history compaction backend.
3
- *
4
- * `@deepseek-ai/dsh-compaction-basic` condenses a shadowed span through one
5
- * `ctx.llm.stream()` call whose instruction asks for a nine-section template
6
- * ("Primary Request / Key Technical Concepts / Errors and Fixes ..."). Measured
7
- * over eight real sessions (403 MiB, 145 compactions, 24.5M discarded tokens)
8
- * that template retains 2.38% of what it discards, and of everything discarded
9
- * only 0.67% is prose a human wrote -- the rest is reasoning (63.8%), tool
10
- * results (25.2%) and tool-call arguments (10.4%). The prose that does survive
11
- * is then summarized again on the next compaction, because
12
- * `selectCompactableRange` always starts at `surfaceNodes[firstIdx]` and the
13
- * previous checkpoint sits at index 1.
14
- *
15
- * This backend keeps the base class's replay, range selection, durable
16
- * transaction and shrink guard untouched and overrides only `summarize()`, the
17
- * one hook the base class documents for exactly this purpose. The replacement
18
- * summary is built from the log, with one model call per batch of turns:
19
- *
20
- * - user and assistant prose verbatim, per turn;
21
- * - tool results reduced to one line (tool names, call counts, bytes);
22
- * - reasoning never read;
23
- * - repeated injections recorded once.
24
- *
25
- * The digest source is the session log, not the shadowed span: the previous
26
- * checkpoint is itself shadowed on every compaction, so a span-only digest
27
- * would drop everything the previous digest carried. Reading the log's
28
- * append-origin surface events minus the retained tail reconstructs the whole
29
- * history without any accumulated state.
30
- *
31
- * @module @logictan/dsh-verbatim-compaction
32
- */
33
1
  import { BasicCompactionEngine } from '@deepseek-ai/dsh-compaction-basic';
34
2
  import type { Agent } from '@deepseek-ai/dsh-agent';
35
- import { type ContentBlock, type Message } from '@deepseek-ai/dsh-llm';
3
+ import { type ContentBlock, type Message, type TokenUsage } from '@deepseek-ai/dsh-llm';
36
4
  import type { Session, SessionEvent, SessionSeq } from '@deepseek-ai/dsh-session';
37
5
  import { type PurposeConfig } from './purpose.js';
38
6
  /** Cordis companion plugin name. Must equal this plugin's `cordis.patch.yml` row id. */
@@ -77,6 +45,7 @@ export interface SummaryResult {
77
45
  summary: ContentBlock[];
78
46
  provider: string;
79
47
  model: string;
48
+ usage?: TokenUsage;
80
49
  }
81
50
  /** One question the user answered through the question tool, with its answer. */
82
51
  interface AnsweredQuestion {
@@ -138,10 +107,12 @@ export declare function parseExtraction(answer: string): Map<string, Extraction>
138
107
  * Render one extraction as the digest block, headings included.
139
108
  *
140
109
  * @param extraction - the fields for one slot.
110
+ * @param level - graded retention level (3..0).
111
+ * @param includeAsked - whether to render the `## Asked` section (false for stale historical turns).
141
112
  * @returns markdown with a heading per non-empty field; empty string when every
142
113
  * field is empty.
143
114
  */
144
- export declare function renderExtractionBlock(extraction: Extraction | undefined, level?: number): string;
115
+ export declare function renderExtractionBlock(extraction: Extraction | undefined, level?: number, includeAsked?: boolean): string;
145
116
  /**
146
117
  * The group starts a fold walk visits, oldest first, one entry per group.
147
118
  *
@@ -178,6 +149,13 @@ export interface Condensed {
178
149
  */
179
150
  covers: number;
180
151
  }
152
+ /**
153
+ * Sections folded into one condensed block when the digest overflows.
154
+ *
155
+ * Lowered from 100 to 30 so real long sessions (30–80 turns) fold oldest runs
156
+ * instead of falling straight into destructive body eviction.
157
+ */
158
+ export declare const CONDENSE_GROUP = 30;
181
159
  /**
182
160
  * Build the compact per-turn trace fed to the summarizer.
183
161
  *
@@ -210,7 +188,6 @@ interface Turn {
210
188
  fromRequest: boolean;
211
189
  user: string[];
212
190
  assistant: string[];
213
- tools: Map<string, number>;
214
191
  writes: string[];
215
192
  /**
216
193
  * Questions this turn put to the user through `ask_user_question`, with the
@@ -241,12 +218,6 @@ interface Section {
241
218
  /**
242
219
  * Group append-origin surface events into per-turn digest material.
243
220
  *
244
- * A section starts at each non-injected user message; assistant-only runs
245
- * before the first user message join the first section. Turn numbers come from
246
- * the log: `turn/start` carries `{turn}` and `assistant/message` carries
247
- * `data.turn`. A user message carries no turn of its own, so it inherits the
248
- * last one seen.
249
- *
250
221
  * @param events - the digest source in log order.
251
222
  * @returns one section per non-injected user message.
252
223
  */
@@ -319,19 +290,9 @@ export declare function shadowedSeqs(session: Session, input: SummarizationInput
319
290
  * @returns the events the digest is built from, in log order.
320
291
  */
321
292
  export declare function digestSource(session: Session, retainedSeqs: ReadonlySet<SessionSeq>): readonly SessionEvent[];
322
- /**
323
- * Assemble the three-part material one extraction call is given.
324
- *
325
- * Split out from the call itself so it can be asserted: the first hand-built
326
- * version of this silently dropped the user request, because it selected user
327
- * messages by `data.turn` and user messages carry no turn of their own. The model
328
- * then summarized tool names with no idea what had been asked.
329
- *
330
- * @param turn - one turn's events, in log order.
331
- * @param prose - that turn's assistant prose, already extracted by the caller.
332
- * @returns the joined material, or an empty string when the turn has nothing.
333
- */
334
- export declare function buildExtractionMaterial(turn: readonly SessionEvent[], prose: string): string;
293
+ export declare function buildExtractionMaterial(turn: readonly SessionEvent[], prose: string, options?: {
294
+ includeToolResults?: boolean;
295
+ }): string;
335
296
  /**
336
297
  * Extractive compaction backend: verbatim user prose, one model call per batch,
337
298
  * call.
@@ -360,13 +321,13 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
360
321
  */
361
322
  private readonly extractionCache;
362
323
  /**
363
- * Folded text, keyed by provider, model and a hash of the material folded.
364
- *
365
- * Same reasoning as `extractionCache`: the fold is a model call over material
366
- * rebuilt from the raw log on every compaction, so the same run of old turns is
367
- * re-folded on every later compaction unless it is remembered.
324
+ * Folded text, keyed by effective provider, model and a hash of the material folded.
368
325
  */
369
326
  private readonly condensedCache;
327
+ /** Session ids whose on-disk cache has already been hydrated into memory. */
328
+ private readonly hydratedSessions;
329
+ private hydrateDiskCache;
330
+ private persistDiskCache;
370
331
  /**
371
332
  * Build the replacement checkpoint content from the session log.
372
333
  *
@@ -380,63 +341,28 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
380
341
  * @param input - replayed conversation prefix the base class is shadowing.
381
342
  * @param agent - owner of the session being compacted.
382
343
  * @param signal - cancellation forwarded to the extraction and fold calls.
383
- * @returns text summary blocks, unmarked by any LLM call.
344
+ * @returns text summary blocks, route metadata, and aggregated LLM usage.
384
345
  */
385
346
  protected summarize(input: SummarizationInput, agent: Agent, signal?: AbortSignal): Promise<SummaryResult>;
386
347
  /**
387
348
  * Fold the oldest turns into condensed blocks until the digest fits.
388
349
  *
389
- * Only reached when the plain digest overflows `budget`. The oldest turns are
390
- * the right ones to fold: they describe work already superseded, while the
391
- * newest are what the next request depends on.
392
- *
393
- * Linear in groups, not bisected: a fold is not monotone in how much is folded —
394
- * a paragraph's length depends on what the model chose to keep — so there is no
395
- * boundary to bisect. The walk stops at the first size that fits, which is the
396
- * fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
397
- * consecutive sections, so the number of calls is proportional to the digest,
398
- * not to the number of turns.
399
- *
400
- * Cached by content, like the extraction: the same prefix of turns folds to the
401
- * same text, and a later compaction re-reads the same history.
402
- *
403
- * @param source - digest source events, in log order.
404
- * @param extracted - per-turn extractions already computed.
405
- * @param agent - owner of the session being compacted.
406
- * @param budget - token budget the digest must fit.
407
- * @param signal - cancellation forwarded to every call.
408
- * @returns condensed blocks keyed by the `turnKey` of the first covered section.
350
+ * Only reached when the unclipped plain digest overflows `budget`. The oldest
351
+ * turns are the right ones to fold: they describe work already superseded, while
352
+ * the newest are what the next request depends on.
409
353
  */
410
354
  private condenseOldest;
411
355
  /**
412
356
  * Hand one group of turns to the model and return its folded text.
413
- *
414
- * @param group - consecutive sections to fold into one paragraph.
415
- * @param agent - owner of the session being compacted.
416
- * @param signal - cancellation forwarded to the call.
417
- * @returns the folded paragraph, or undefined when the call produced nothing.
418
357
  */
419
358
  private condenseGroup;
420
359
  /**
421
- * Run the extraction for every turn in the digest source.
422
- *
423
- * Sequential rather than parallel: these calls share the session's routed
424
- * model and the provider's KV cache, and firing a dozen at once would both
425
- * multiply the cost and defeat the cache the host's own summarizer relies on.
360
+ * Run the extraction for every section in the digest source.
426
361
  *
427
- * A turn that fails is simply absent from the output; one bad turn must not
428
- * drop the extraction for the rest.
429
- *
430
- * Batched rather than one call per turn. One call per turn meant 131 calls on a
431
- * 122-turn session, each with its own round trip: a measured extraction budget
432
- * of 131 x 400 tokens could on its own exceed the whole digest ceiling. A
433
- * batch of `TURNS_PER_CALL` turns costs one round trip and shares the prompt
434
- * prefix, so the provider's KV cache is reused rather than rebuilt.
435
- *
436
- * @param source - digest source events, in log order.
437
- * @param agent - owner of the session being compacted.
438
- * @param signal - cancellation forwarded to every call.
439
- * @returns turn number to extracted block, omitting turns that yielded none.
362
+ * Uses `buildSectionsWithEvents` as the single source of truth so slot keys can
363
+ * never drift out of alignment with rendered sections. Uncached batches execute
364
+ * with bounded concurrency (`EXTRACT_CONCURRENCY`), and newly extracted entries
365
+ * are persisted to the per-session disk cache.
440
366
  */
441
367
  private extractAll;
442
368
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.13.2",
3
+ "version": "0.13.3",
4
4
  "description": "Deterministic compaction backend that keeps conversation prose verbatim in the checkpoint instead of re-summarizing it: user and assistant text survive word for word, tool results collapse to one-line pointers, reasoning is never read, and no model call is made.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",