dsh-context-compression-improved 0.2.3 → 0.2.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.
Files changed (52) hide show
  1. package/.github/workflows/ci.yml +39 -39
  2. package/CHANGELOG.md +137 -135
  3. package/README.md +112 -112
  4. package/package.json +142 -142
  5. package/packages/selector/README.md +31 -31
  6. package/packages/selector/README.zh.md +31 -31
  7. package/packages/selector/dsh.plugin.json +16 -16
  8. package/packages/selector/lib/client.d.ts +228 -228
  9. package/packages/selector/lib/client.js +1462 -1462
  10. package/packages/selector/lib/config.js +856 -842
  11. package/packages/selector/lib/index.d.ts +37 -37
  12. package/packages/selector/lib/index.js +693 -645
  13. package/packages/selector/lib/invariant.js +70 -70
  14. package/packages/selector/lib/pruner.d.ts +728 -683
  15. package/packages/selector/lib/pruner.js +4765 -3807
  16. package/packages/selector/lib/style.css +46 -46
  17. package/packages/selector/lib/tail-trim.js +136 -136
  18. package/packages/selector/package.json +9 -1
  19. package/packages/selector/src/client/index.ts +111 -111
  20. package/packages/selector/src/preset-overlay.ts +60 -1
  21. package/packages/selector/src/pruner/content.ts +18 -5
  22. package/packages/selector/src/pruner/types.ts +23 -5
  23. package/packages/selector/src/pruner.ts +164 -154
  24. package/packages/selector/src/runtime/adaptive-cost.ts +23 -12
  25. package/packages/selector/src/runtime/audit.ts +18 -2
  26. package/packages/selector/src/runtime/config.ts +30 -1
  27. package/packages/selector/src/runtime/measurement.ts +31 -2
  28. package/packages/selector/src/runtime/reducers.ts +1115 -97
  29. package/packages/selector/src/runtime/tokenpilot/dedup.ts +1 -1
  30. package/packages/selector/src/runtime/tokenpilot/locator.ts +1 -1
  31. package/packages/selector/src/runtime/tokenpilot/read-state.ts +23 -2
  32. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +275 -0
  33. package/packages/selector/src/runtime/toolclass.ts +103 -0
  34. package/packages/selector/src/runtime/types.ts +16 -0
  35. package/packages/selector/tests/preset-overlay.host.spec.ts +256 -243
  36. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +7 -7
  37. package/packages/selector/tests/runtime/audit.spec.ts +44 -1
  38. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  39. package/packages/selector/tests/runtime/code-skeleton.spec.ts +14 -3
  40. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  41. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  42. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  43. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  44. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +198 -27
  45. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  46. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  47. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  48. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  49. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +24 -0
  50. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  51. package/packages/selector/tests/standing-generation.host.spec.ts +642 -631
  52. package/scripts/toolclass-corpus-replay.mjs +273 -0
@@ -5,6 +5,7 @@ import type {
5
5
  TokenCount,
6
6
  } from './measurement.ts'
7
7
  import { decimalRateNanoUnits } from './deepseek-official-pricing.ts'
8
+ import { charsToTokens } from './config.ts'
8
9
 
9
10
  /** Inputs that conservatively bound one already-planned Adaptive History batch. */
10
11
  export interface AdaptiveTokenBoundsInput {
@@ -25,7 +26,7 @@ export interface AdaptiveTokenBoundsInput {
25
26
  /** Available lower-benefit and upper-risk bounds for one History batch. */
26
27
  export interface AvailableAdaptiveTokenBounds {
27
28
  readonly kind: 'available'
28
- readonly measurementKind: 'exact-tokenizer' | 'tokenizer-estimate'
29
+ readonly measurementKind: 'exact-tokenizer' | 'tokenizer-estimate' | 'characters'
29
30
  /** D: conservative lower bound of input tokens removed by the plan. */
30
31
  readonly reclaimedLowerBoundTokens: number
31
32
  /** A: conservative upper bound of retained suffix tokens that may lose a hit. */
@@ -89,24 +90,34 @@ export function deriveAdaptiveTokenBounds(input: AdaptiveTokenBoundsInput): Adap
89
90
 
90
91
  let identity: { readonly tokenizerId: string; readonly tokenizerRevision: string } | undefined
91
92
  let exactPrefixLowerBoundTokens = 0
93
+ let characterDerivedPrefix = false
92
94
  const seen = new Set<number>()
93
95
  for (const node of input.measuredNodes) {
94
96
  if (!isCount(node.seq) || seen.has(node.seq)) return unknown('invalid-measured-node-sequence')
95
97
  seen.add(node.seq)
96
- if (node.seq >= input.earliestChangedSeq || node.count.kind !== 'exact-tokenizer') continue
97
- if (!isCount(node.count.tokens)) return unknown('invalid-exact-prefix-count')
98
- if (node.count.tokenizerRevision !== input.expectedTokenizerRevision) {
99
- return unknown('exact-prefix-tokenizer-revision-mismatch')
98
+ if (node.seq >= input.earliestChangedSeq) continue
99
+ if (node.count.kind === 'exact-tokenizer') {
100
+ if (!isCount(node.count.tokens)) return unknown('invalid-exact-prefix-count')
101
+ if (node.count.tokenizerRevision !== input.expectedTokenizerRevision) {
102
+ return unknown('exact-prefix-tokenizer-revision-mismatch')
103
+ }
104
+ if (identity !== undefined
105
+ && (identity.tokenizerId !== node.count.tokenizerId
106
+ || identity.tokenizerRevision !== node.count.tokenizerRevision)) {
107
+ return unknown('exact-prefix-tokenizer-identity-mismatch')
108
+ }
109
+ identity ??= node.count
110
+ exactPrefixLowerBoundTokens += node.count.tokens
111
+ } else {
112
+ // Character-basis degrade: a prefix node without an exact count still
113
+ // occupies retained-request space, so charge its conservative
114
+ // character→token derivation instead of skipping it silently.
115
+ exactPrefixLowerBoundTokens += charsToTokens(node.characterPressure)
116
+ characterDerivedPrefix = true
100
117
  }
101
- if (identity !== undefined
102
- && (identity.tokenizerId !== node.count.tokenizerId
103
- || identity.tokenizerRevision !== node.count.tokenizerRevision)) {
104
- return unknown('exact-prefix-tokenizer-identity-mismatch')
105
- }
106
- identity ??= node.count
107
- exactPrefixLowerBoundTokens += node.count.tokens
108
118
  if (!isCount(exactPrefixLowerBoundTokens)) return unknown('exact-prefix-overflow')
109
119
  }
120
+ if (characterDerivedPrefix) measurementKind = 'characters'
110
121
 
111
122
  const accounted = exactPrefixLowerBoundTokens + reclaimedLowerBoundTokens
112
123
  if (!isCount(accounted) || accounted > input.previousPromptTokens) {
@@ -79,7 +79,7 @@ export interface CompressionPolicyResolvedAuditRecord extends CompressionAuditBa
79
79
  readonly tokenizer?: CompressionTokenizerAuditFact
80
80
  }
81
81
 
82
- /** One committed model-free surface rewrite and its exact token accounting. */
82
+ /** One committed model-free surface rewrite and its accounting. */
83
83
  export interface CompressionRewriteAuditRecord extends CompressionAuditBase {
84
84
  readonly kind: 'rewrite'
85
85
  readonly profile: CompressionProfile
@@ -94,8 +94,24 @@ export interface CompressionRewriteAuditRecord extends CompressionAuditBase {
94
94
  readonly tokensBefore: number
95
95
  readonly tokensAfter: number
96
96
  readonly tokensRemoved: number
97
+ /**
98
+ * Which measurement backed this record's decision and token figures:
99
+ * 'exact-tokenizer' when both sides of the reduction carry one bundled
100
+ * tokenizer identity, 'characters' when the proof ran on Unicode code
101
+ * points and `tokensBefore/After` were derived at 4.0 chars per token
102
+ * (`tokenizerId: 'characters'`, `tokenizerRevision: 'chars-per-token-4.0'`).
103
+ */
104
+ readonly measurementBasis: 'exact-tokenizer' | 'characters'
97
105
  readonly tokenizerId: string
98
106
  readonly tokenizerRevision: string
107
+ /**
108
+ * Original-event lines the reducer elided (task_4c/G7, from
109
+ * `ReducerOutput.elidedLines` via the plan). Present when the landing
110
+ * reducer reports it; absent for placeholder/trim rewrites. Exists so the
111
+ * compress→retrieve M/N ratio is computable from session logs alone —
112
+ * never printed into replacement content.
113
+ */
114
+ readonly elidedLines?: number
99
115
  }
100
116
 
101
117
  /** Why an enabled component did not rewrite, or why it was disabled. */
@@ -107,7 +123,7 @@ export interface CompressionComponentEvaluationAuditRecord extends CompressionAu
107
123
  readonly status: CompressionAuditEvaluationStatus
108
124
  readonly reason: string
109
125
  readonly historyMode?: HistoryMode
110
- readonly measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'unavailable'
126
+ readonly measurementKind?: 'exact-tokenizer' | 'tokenizer-estimate' | 'characters' | 'unavailable'
111
127
  readonly currentTokens?: number
112
128
  readonly triggerTokens?: number
113
129
  readonly targetTokens?: number
@@ -286,6 +286,7 @@ const CONFIG_KEYS: ReadonlySet<string> = new Set([
286
286
  'historyKeepRecentToolCalls',
287
287
  'historyKeepRecentTokens',
288
288
  'historyMinReclaimTokens',
289
+ 'readInputCapChars',
289
290
  'autoCompactThresholdPercent',
290
291
  'presetOptions',
291
292
  ])
@@ -313,6 +314,24 @@ export function codePointLength(text: string): number {
313
314
  return length
314
315
  }
315
316
 
317
+ /**
318
+ * Conservative upper bound on characters per token. Same convention the
319
+ * readInputCapChars invariant already uses (see resolvePolicy): English
320
+ * code runs approximately four characters per token at the upper bound.
321
+ */
322
+ export const CHARS_PER_TOKEN = 4.0
323
+
324
+ /** Express one token-named policy gate on the character basis. */
325
+ export function charsForTokens(tokens: number): number {
326
+ return tokens * CHARS_PER_TOKEN
327
+ }
328
+
329
+ /** Derive the telemetry-only token figure from a character measurement. */
330
+ export function charsToTokens(chars: number): number {
331
+ if (!Number.isFinite(chars) || chars <= 0) return 0
332
+ return Math.max(1, Math.round(chars / CHARS_PER_TOKEN))
333
+ }
334
+
316
335
  /**
317
336
  * Test whether a settings value names a supported compression profile.
318
337
  * @param value - untrusted settings value.
@@ -354,6 +373,7 @@ export function resolveConfig(config: ToolResultPruneConfig = {}): ResolvedConfi
354
373
  ...config.historyKeepRecentToolCalls === undefined ? {} : { historyKeepRecentToolCalls: config.historyKeepRecentToolCalls },
355
374
  ...config.historyKeepRecentTokens === undefined ? {} : { historyKeepRecentTokens: config.historyKeepRecentTokens },
356
375
  ...config.historyMinReclaimTokens === undefined ? {} : { historyMinReclaimTokens: config.historyMinReclaimTokens },
376
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
357
377
  ...config.autoCompactThresholdPercent === undefined ? {} : { autoCompactThresholdPercent: config.autoCompactThresholdPercent },
358
378
  ...config.presetOptions === undefined ? {} : { presetOptions: config.presetOptions },
359
379
  }
@@ -365,7 +385,7 @@ export function resolveConfig(config: ToolResultPruneConfig = {}): ResolvedConfi
365
385
  for (const key of [
366
386
  'nativeTriggerTokens', 'nativeTargetTokens', 'freshTriggerTokens', 'freshTargetTokens',
367
387
  'aggregateTriggerTokens', 'aggregateTargetTokens', 'historyTriggerTokens',
368
- 'historyMinReclaimTokens',
388
+ 'historyMinReclaimTokens', 'readInputCapChars',
369
389
  ] as const) {
370
390
  const value = resolved[key]
371
391
  if (value !== undefined) assertPositiveInteger(key, value)
@@ -567,6 +587,7 @@ export function resolvePolicy(
567
587
  ?? linkage?.historyKeepRecentTokens ?? preset.historyKeepRecentTokens,
568
588
  historyMinReclaimTokens: config.historyMinReclaimTokens
569
589
  ?? linkage?.historyMinReclaimTokens ?? preset.historyMinReclaimTokens,
590
+ ...config.readInputCapChars === undefined ? {} : { readInputCapChars: config.readInputCapChars },
570
591
  ...linkage === undefined ? {} : {
571
592
  autoCompactTokens: linkage.autoCompactTokens,
572
593
  microDeadlineTokens: linkage.microDeadlineTokens,
@@ -584,6 +605,14 @@ export function resolvePolicy(
584
605
  if (policy.aggregateTargetTokens >= policy.aggregateTriggerTokens && policy.freshEnabled) {
585
606
  throw new Error('context compression policy: aggregate target must be below trigger')
586
607
  }
608
+ // G2 invariant: the fresh trigger is in TOKENS while a read input cap is in
609
+ // CHARACTERS. English code runs ≈4.0 chars/token at the conservative upper
610
+ // bound, so a cap at or below `freshTriggerTokens × 4.0` would truncate every
611
+ // read result below the trigger and silently silence the fresh path.
612
+ if (policy.readInputCapChars !== undefined
613
+ && policy.readInputCapChars <= policy.freshTriggerTokens * 4.0) {
614
+ throw new Error('context compression policy: read input cap would silence the fresh path')
615
+ }
587
616
  return deepFreeze(policy)
588
617
  }
589
618
 
@@ -16,6 +16,7 @@ import {
16
16
  } from './deepseek-v4-vision-tokens.ts'
17
17
  import { unavailableTokenCount } from './token-count.ts'
18
18
  import { sessionEvents } from './session-events.ts'
19
+ import { pressureCost } from '../pruner/content.ts'
19
20
  import type {
20
21
  CanonicalTextTokenCounter,
21
22
  ExactTokenizerTokenCount,
@@ -25,6 +26,19 @@ import type {
25
26
 
26
27
  export type { TokenCount } from './token-count.ts'
27
28
 
29
+ /**
30
+ * Character pressure of one model-visible content array, measured on the same
31
+ * level `SnapshotCandidate.characterPressure` uses: a tool/result message is
32
+ * measured by its inner tool-result content, never by the wrapper block, so the
33
+ * node-level and candidate-level figures stay directly comparable.
34
+ * @param content - the node's model-visible content blocks.
35
+ * @returns character pressure in Unicode code points, plus rich-block costs.
36
+ */
37
+ function nodeCharacterPressure(content: readonly ContentBlock[]): number {
38
+ const only = content.length === 1 ? content[0] : undefined
39
+ return pressureCost(only?.type === 'tool-result' ? only.content : content)
40
+ }
41
+
28
42
  /** Request identity retained only when every dimension is publicly known. */
29
43
  export interface ProviderMeasurementKey {
30
44
  readonly provider: string
@@ -77,6 +91,11 @@ export interface IntrinsicImageBlockDiagnostic {
77
91
  export interface MeasuredTokenSurfaceNode {
78
92
  readonly seq: number
79
93
  readonly count: TokenCount
94
+ /**
95
+ * Authoritative decision metric for this node: character pressure in
96
+ * Unicode code points (same convention as SnapshotCandidate.characterPressure).
97
+ */
98
+ readonly characterPressure: number
80
99
  /** Intrinsic-grid diagnostic when usable image dimensions were available. */
81
100
  readonly intrinsicImageBlockEstimate?: IntrinsicImageBlockDiagnostic
82
101
  }
@@ -87,6 +106,11 @@ export interface CompactionTokenView extends TokenMeasurement {
87
106
  readonly modelId?: string
88
107
  readonly measuredNodes: readonly MeasuredTokenSurfaceNode[]
89
108
  readonly currentSurface: TokenCount
109
+ /**
110
+ * Exact character analogue of `currentSurface`: sum of per-node
111
+ * `characterPressure` over the same nodes `currentSurface` covers.
112
+ */
113
+ readonly currentSurfaceChars: number
90
114
  /** Sum of per-node intrinsic padding minima; a diagnostic, not a token bound. */
91
115
  readonly intrinsicImageBlockEstimateTokens: number
92
116
  readonly latestEnvelopeKey?: ProviderMeasurementKey
@@ -116,11 +140,13 @@ export function measureForCompaction(ctx: Context, session: Session): Compaction
116
140
  const measuredNodes = measurement.nodes.map((node): MeasuredTokenSurfaceNode => {
117
141
  const event = events[node.seq]
118
142
  if (event === undefined) {
119
- return { seq: node.seq, count: unavailableTokenCount(`surface node ${String(node.seq)} is missing`) }
143
+ // The node's content is not model-visible, so it carries no character
144
+ // pressure on the decision surface.
145
+ return { seq: node.seq, count: unavailableTokenCount(`surface node ${String(node.seq)} is missing`), characterPressure: 0 }
120
146
  }
121
147
  const message = deriveEventMessage(event)
122
148
  if (message === null) {
123
- return { seq: node.seq, count: unavailableTokenCount(`surface node ${String(node.seq)} is not model-visible`) }
149
+ return { seq: node.seq, count: unavailableTokenCount(`surface node ${String(node.seq)} is not model-visible`), characterPressure: 0 }
124
150
  }
125
151
  const count = countCanonicalContent(message.content, counter, `surface node ${String(node.seq)}`)
126
152
  const intrinsicImageBlockEstimate = count.kind === 'tokenizer-estimate'
@@ -129,6 +155,7 @@ export function measureForCompaction(ctx: Context, session: Session): Compaction
129
155
  return {
130
156
  seq: node.seq,
131
157
  count,
158
+ characterPressure: nodeCharacterPressure(message.content),
132
159
  ...intrinsicImageBlockEstimate === undefined ? {} : { intrinsicImageBlockEstimate },
133
160
  }
134
161
  })
@@ -136,6 +163,7 @@ export function measureForCompaction(ctx: Context, session: Session): Compaction
136
163
  measuredNodes.map(node => node.count),
137
164
  'current surface',
138
165
  )
166
+ const currentSurfaceChars = measuredNodes.reduce((sum, node) => sum + node.characterPressure, 0)
139
167
  const intrinsicImageBlockEstimateTokens = measuredNodes.reduce(
140
168
  (sum, node) => sum + (node.intrinsicImageBlockEstimate?.paddingMinimumTokens ?? 0),
141
169
  0,
@@ -145,6 +173,7 @@ export function measureForCompaction(ctx: Context, session: Session): Compaction
145
173
  ...(target === undefined ? {} : { providerRoute: target.provider, modelId: target.model }),
146
174
  measuredNodes: Object.freeze(measuredNodes),
147
175
  currentSurface,
176
+ currentSurfaceChars,
148
177
  intrinsicImageBlockEstimateTokens,
149
178
  countCanonicalText: counter.countText,
150
179
  })