@logictan/dsh-verbatim-compaction 0.13.1 → 0.13.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/purpose.js ADDED
@@ -0,0 +1,25 @@
1
+ import Schema from '@deepseek-ai/schemastery';
2
+ /** Settings namespace for the optional model override used by compaction. */
3
+ export const name = 'verbatim-compaction-purpose';
4
+ /** The three editable scalars; empty strings mean "follow the chat model". */
5
+ export const Config = Schema.object({
6
+ provider: Schema.string().default('').volatile(),
7
+ model: Schema.string().default('').volatile(),
8
+ reasoningEffort: Schema.string().default('').volatile(),
9
+ });
10
+ /**
11
+ * The compaction engine runs inside isolated preset groups, while this
12
+ * settings row lives in the root realm. A module-level live reference is the
13
+ * one channel both halves can see without registering a second service.
14
+ */
15
+ let liveConfig;
16
+ export function setLiveConfig(config) {
17
+ liveConfig = config;
18
+ }
19
+ export function getLiveConfig() {
20
+ return liveConfig;
21
+ }
22
+ /** Root-realm settings row. It registers no service. */
23
+ export function apply(_ctx, config) {
24
+ setLiveConfig(config);
25
+ }
@@ -1,58 +1,10 @@
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';
36
- import Schema from '@deepseek-ai/schemastery';
3
+ import { type ContentBlock, type Message, type TokenUsage } from '@deepseek-ai/dsh-llm';
37
4
  import type { Session, SessionEvent, SessionSeq } from '@deepseek-ai/dsh-session';
5
+ import { type PurposeConfig } from './purpose.js';
38
6
  /** Cordis companion plugin name. Must equal this plugin's `cordis.patch.yml` row id. */
39
7
  export declare const name = "verbatim-compaction";
40
- /** Live reference Cordis hands over for a volatile Config field. */
41
- interface ConfigRef<T> {
42
- get(): T;
43
- }
44
- /** Optional model/effort override for compaction's two LLM calls. */
45
- export interface PurposeConfig {
46
- provider?: ConfigRef<string>;
47
- model?: ConfigRef<string>;
48
- reasoningEffort?: ConfigRef<string>;
49
- }
50
- /** Three editable scalars; empty strings mean "follow the chat model". */
51
- export declare const OVERRIDE_FIELDS: {
52
- provider: Schema<string, string, "volatile-defined">;
53
- model: Schema<string, string, "volatile-defined">;
54
- reasoningEffort: Schema<string, string, "volatile-defined">;
55
- };
56
8
  /** A provider/model override takes effect only as a complete pair. */
57
9
  export declare function pairedRouteOf(config: PurposeConfig | undefined): {
58
10
  provider: string;
@@ -93,6 +45,7 @@ export interface SummaryResult {
93
45
  summary: ContentBlock[];
94
46
  provider: string;
95
47
  model: string;
48
+ usage?: TokenUsage;
96
49
  }
97
50
  /** One question the user answered through the question tool, with its answer. */
98
51
  interface AnsweredQuestion {
@@ -154,10 +107,12 @@ export declare function parseExtraction(answer: string): Map<string, Extraction>
154
107
  * Render one extraction as the digest block, headings included.
155
108
  *
156
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).
157
112
  * @returns markdown with a heading per non-empty field; empty string when every
158
113
  * field is empty.
159
114
  */
160
- export declare function renderExtractionBlock(extraction: Extraction | undefined, level?: number): string;
115
+ export declare function renderExtractionBlock(extraction: Extraction | undefined, level?: number, includeAsked?: boolean): string;
161
116
  /**
162
117
  * The group starts a fold walk visits, oldest first, one entry per group.
163
118
  *
@@ -194,6 +149,13 @@ export interface Condensed {
194
149
  */
195
150
  covers: number;
196
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;
197
159
  /**
198
160
  * Build the compact per-turn trace fed to the summarizer.
199
161
  *
@@ -226,7 +188,6 @@ interface Turn {
226
188
  fromRequest: boolean;
227
189
  user: string[];
228
190
  assistant: string[];
229
- tools: Map<string, number>;
230
191
  writes: string[];
231
192
  /**
232
193
  * Questions this turn put to the user through `ask_user_question`, with the
@@ -257,12 +218,6 @@ interface Section {
257
218
  /**
258
219
  * Group append-origin surface events into per-turn digest material.
259
220
  *
260
- * A section starts at each non-injected user message; assistant-only runs
261
- * before the first user message join the first section. Turn numbers come from
262
- * the log: `turn/start` carries `{turn}` and `assistant/message` carries
263
- * `data.turn`. A user message carries no turn of its own, so it inherits the
264
- * last one seen.
265
- *
266
221
  * @param events - the digest source in log order.
267
222
  * @returns one section per non-injected user message.
268
223
  */
@@ -335,19 +290,9 @@ export declare function shadowedSeqs(session: Session, input: SummarizationInput
335
290
  * @returns the events the digest is built from, in log order.
336
291
  */
337
292
  export declare function digestSource(session: Session, retainedSeqs: ReadonlySet<SessionSeq>): readonly SessionEvent[];
338
- /**
339
- * Assemble the three-part material one extraction call is given.
340
- *
341
- * Split out from the call itself so it can be asserted: the first hand-built
342
- * version of this silently dropped the user request, because it selected user
343
- * messages by `data.turn` and user messages carry no turn of their own. The model
344
- * then summarized tool names with no idea what had been asked.
345
- *
346
- * @param turn - one turn's events, in log order.
347
- * @param prose - that turn's assistant prose, already extracted by the caller.
348
- * @returns the joined material, or an empty string when the turn has nothing.
349
- */
350
- 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;
351
296
  /**
352
297
  * Extractive compaction backend: verbatim user prose, one model call per batch,
353
298
  * call.
@@ -358,15 +303,6 @@ export declare function buildExtractionMaterial(turn: readonly SessionEvent[], p
358
303
  * subclass cannot diverge from the host's transaction semantics.
359
304
  */
360
305
  export default class VerbatimCompactionEngine extends BasicCompactionEngine {
361
- /**
362
- * The Loader reads Config from the default-exported class, and the base
363
- * constructor rejects unknown keys, so the base schema is merged instead of
364
- * replaced. Only the three new fields are volatile: existing keys stay
365
- * ordinary patch-level configuration.
366
- */
367
- static Config: typeof BasicCompactionEngine.Config;
368
- private readonly purposeConfig;
369
- constructor(ctx: ConstructorParameters<typeof BasicCompactionEngine>[0], config: any);
370
306
  /**
371
307
  * Extraction results, keyed by a hash of the material they were derived from.
372
308
  *
@@ -385,13 +321,13 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
385
321
  */
386
322
  private readonly extractionCache;
387
323
  /**
388
- * Folded text, keyed by provider, model and a hash of the material folded.
389
- *
390
- * Same reasoning as `extractionCache`: the fold is a model call over material
391
- * rebuilt from the raw log on every compaction, so the same run of old turns is
392
- * 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.
393
325
  */
394
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;
395
331
  /**
396
332
  * Build the replacement checkpoint content from the session log.
397
333
  *
@@ -405,63 +341,28 @@ export default class VerbatimCompactionEngine extends BasicCompactionEngine {
405
341
  * @param input - replayed conversation prefix the base class is shadowing.
406
342
  * @param agent - owner of the session being compacted.
407
343
  * @param signal - cancellation forwarded to the extraction and fold calls.
408
- * @returns text summary blocks, unmarked by any LLM call.
344
+ * @returns text summary blocks, route metadata, and aggregated LLM usage.
409
345
  */
410
346
  protected summarize(input: SummarizationInput, agent: Agent, signal?: AbortSignal): Promise<SummaryResult>;
411
347
  /**
412
348
  * Fold the oldest turns into condensed blocks until the digest fits.
413
349
  *
414
- * Only reached when the plain digest overflows `budget`. The oldest turns are
415
- * the right ones to fold: they describe work already superseded, while the
416
- * newest are what the next request depends on.
417
- *
418
- * Linear in groups, not bisected: a fold is not monotone in how much is folded —
419
- * a paragraph's length depends on what the model chose to keep — so there is no
420
- * boundary to bisect. The walk stops at the first size that fits, which is the
421
- * fewest calls that buy enough room. Each block covers `CONDENSE_GROUP`
422
- * consecutive sections, so the number of calls is proportional to the digest,
423
- * not to the number of turns.
424
- *
425
- * Cached by content, like the extraction: the same prefix of turns folds to the
426
- * same text, and a later compaction re-reads the same history.
427
- *
428
- * @param source - digest source events, in log order.
429
- * @param extracted - per-turn extractions already computed.
430
- * @param agent - owner of the session being compacted.
431
- * @param budget - token budget the digest must fit.
432
- * @param signal - cancellation forwarded to every call.
433
- * @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.
434
353
  */
435
354
  private condenseOldest;
436
355
  /**
437
356
  * Hand one group of turns to the model and return its folded text.
438
- *
439
- * @param group - consecutive sections to fold into one paragraph.
440
- * @param agent - owner of the session being compacted.
441
- * @param signal - cancellation forwarded to the call.
442
- * @returns the folded paragraph, or undefined when the call produced nothing.
443
357
  */
444
358
  private condenseGroup;
445
359
  /**
446
- * Run the extraction for every turn in the digest source.
447
- *
448
- * Sequential rather than parallel: these calls share the session's routed
449
- * model and the provider's KV cache, and firing a dozen at once would both
450
- * 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.
451
361
  *
452
- * A turn that fails is simply absent from the output; one bad turn must not
453
- * drop the extraction for the rest.
454
- *
455
- * Batched rather than one call per turn. One call per turn meant 131 calls on a
456
- * 122-turn session, each with its own round trip: a measured extraction budget
457
- * of 131 x 400 tokens could on its own exceed the whole digest ceiling. A
458
- * batch of `TURNS_PER_CALL` turns costs one round trip and shares the prompt
459
- * prefix, so the provider's KV cache is reused rather than rebuilt.
460
- *
461
- * @param source - digest source events, in log order.
462
- * @param agent - owner of the session being compacted.
463
- * @param signal - cancellation forwarded to every call.
464
- * @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.
465
366
  */
466
367
  private extractAll;
467
368
  }
@@ -0,0 +1,27 @@
1
+ import Schema from '@deepseek-ai/schemastery';
2
+ /** Settings namespace for the optional model override used by compaction. */
3
+ export declare const name = "verbatim-compaction-purpose";
4
+ /** A live reference Cordis hands over for a volatile Config field. */
5
+ export interface ConfigRef<T> {
6
+ get(): T;
7
+ }
8
+ /** The three editable scalars; empty strings mean "follow the chat model". */
9
+ export declare const Config: Schema<Schemastery.ObjectS<NoInfer<{
10
+ provider: Schema<string, string, "volatile-defined">;
11
+ model: Schema<string, string, "volatile-defined">;
12
+ reasoningEffort: Schema<string, string, "volatile-defined">;
13
+ }>>, Schemastery.ObjectT<NoInfer<{
14
+ provider: Schema<string, string, "volatile-defined">;
15
+ model: Schema<string, string, "volatile-defined">;
16
+ reasoningEffort: Schema<string, string, "volatile-defined">;
17
+ }>>, "plain">;
18
+ /** The shape of the live configuration Cordis passes to the plugin. */
19
+ export interface PurposeConfig {
20
+ provider?: ConfigRef<string>;
21
+ model?: ConfigRef<string>;
22
+ reasoningEffort?: ConfigRef<string>;
23
+ }
24
+ export declare function setLiveConfig(config: PurposeConfig): void;
25
+ export declare function getLiveConfig(): PurposeConfig | undefined;
26
+ /** Root-realm settings row. It registers no service. */
27
+ export declare function apply(_ctx: unknown, config: PurposeConfig): void;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@logictan/dsh-verbatim-compaction",
3
- "version": "0.13.1",
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",
@@ -10,7 +10,11 @@
10
10
  "types": "./lib/types/index.d.ts",
11
11
  "default": "./lib/index.js"
12
12
  },
13
- "./package.json": "./package.json"
13
+ "./package.json": "./package.json",
14
+ "./purpose": {
15
+ "types": "./lib/types/purpose.d.ts",
16
+ "default": "./lib/purpose.js"
17
+ }
14
18
  },
15
19
  "dsh": {
16
20
  "bundle": {