dsh-context-compression-improved 0.8.0 → 0.9.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.
Files changed (172) hide show
  1. package/.gitattributes +2 -2
  2. package/.githooks/pre-push +37 -37
  3. package/.github/workflows/ci.yml +39 -39
  4. package/CHANGELOG.de.md +41 -0
  5. package/CHANGELOG.es.md +41 -0
  6. package/CHANGELOG.fr.md +42 -0
  7. package/CHANGELOG.it.md +41 -0
  8. package/CHANGELOG.ja.md +35 -0
  9. package/CHANGELOG.ko.md +34 -0
  10. package/CHANGELOG.md +96 -0
  11. package/CHANGELOG.ru.md +37 -0
  12. package/CHANGELOG.zh.md +32 -0
  13. package/CONTRIBUTING.md +22 -22
  14. package/LICENSE +21 -21
  15. package/README.de.md +7 -9
  16. package/README.es.md +7 -9
  17. package/README.fr.md +7 -9
  18. package/README.it.md +7 -9
  19. package/README.ja.md +6 -2
  20. package/README.ko.md +6 -2
  21. package/README.md +96 -98
  22. package/README.ru.md +7 -9
  23. package/README.zh.md +89 -85
  24. package/SECURITY.md +18 -18
  25. package/THIRD_PARTY_NOTICES.md +14 -14
  26. package/docs/compat-0.1.5-report.md +77 -77
  27. package/docs/installation.de.md +5 -5
  28. package/docs/installation.es.md +5 -5
  29. package/docs/installation.fr.md +5 -5
  30. package/docs/installation.it.md +5 -5
  31. package/docs/installation.ja.md +5 -5
  32. package/docs/installation.ko.md +5 -5
  33. package/docs/installation.md +5 -5
  34. package/docs/installation.ru.md +5 -5
  35. package/docs/installation.zh.md +5 -5
  36. package/docs/repair-log.md +657 -657
  37. package/package.json +24 -22
  38. package/packages/selector/LICENSE +21 -21
  39. package/packages/selector/README.md +26 -26
  40. package/packages/selector/README.zh.md +24 -24
  41. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  42. package/packages/selector/cordis.patch.yml +27 -27
  43. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  44. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  45. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  46. package/packages/selector/dsh.plugin.json +16 -16
  47. package/packages/selector/lib/client.js +180 -22
  48. package/packages/selector/lib/host-generation.js +62 -0
  49. package/packages/selector/lib/index.js +208 -1
  50. package/packages/selector/lib/invariant.js +1 -1
  51. package/packages/selector/lib/pruner.js +46 -44
  52. package/packages/selector/lib/style.css +53 -53
  53. package/packages/selector/lib/tail-trim.js +73 -4
  54. package/packages/selector/package.json +80 -21
  55. package/packages/selector/screenshots.json +3 -3
  56. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  57. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  58. package/packages/selector/src/client/bridge-scope.ts +125 -0
  59. package/packages/selector/src/client/index.ts +122 -36
  60. package/packages/selector/src/client/monitor-fab.ts +0 -2
  61. package/packages/selector/src/client/preset-options.ts +88 -88
  62. package/packages/selector/src/client/scope-face.ts +24 -24
  63. package/packages/selector/src/compat/host-generation.ts +96 -0
  64. package/packages/selector/src/compat/settings-lease.ts +108 -0
  65. package/packages/selector/src/compat/tool-result.ts +91 -0
  66. package/packages/selector/src/css-modules.d.ts +6 -6
  67. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  68. package/packages/selector/src/estimator-catalog.ts +104 -104
  69. package/packages/selector/src/index.ts +8 -0
  70. package/packages/selector/src/invariant.ts +113 -113
  71. package/packages/selector/src/preset-overlay.ts +626 -626
  72. package/packages/selector/src/pruner/content.ts +198 -198
  73. package/packages/selector/src/pruner/session.ts +97 -96
  74. package/packages/selector/src/pruner/tuning.ts +23 -23
  75. package/packages/selector/src/pruner/types.ts +78 -78
  76. package/packages/selector/src/pruner.ts +61 -41
  77. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  78. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  79. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  80. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  81. package/packages/selector/src/runtime/measurement.ts +444 -431
  82. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  83. package/packages/selector/src/runtime/retrieve.ts +7 -3
  84. package/packages/selector/src/runtime/session-events.ts +30 -30
  85. package/packages/selector/src/runtime/tail-trim.ts +175 -165
  86. package/packages/selector/src/runtime/token-count.ts +72 -72
  87. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  88. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  89. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  90. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  91. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  92. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  93. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  94. package/packages/selector/src/runtime/toolclass.ts +103 -103
  95. package/packages/selector/src/runtime/value.ts +48 -48
  96. package/packages/selector/src/settings-bridge.ts +175 -0
  97. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  98. package/packages/selector/tests/built/client-artifact.spec.ts +6 -9
  99. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  100. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -94
  101. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  102. package/packages/selector/tests/custom-contract.client.spec.ts +226 -223
  103. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  104. package/packages/selector/tests/estimator-route-registration.host.spec.ts +199 -194
  105. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -35
  106. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -15
  107. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -41
  108. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -647
  109. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -78
  110. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -234
  111. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -204
  112. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -188
  113. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -200
  114. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  115. package/packages/selector/tests/public/package-contract.client.spec.ts +11 -3
  116. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  117. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -230
  118. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  119. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  120. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  121. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  122. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  123. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  124. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  125. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  126. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  127. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  128. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  129. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  130. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  131. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  132. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  133. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  134. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +3 -3
  135. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  136. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  137. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  138. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  139. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  140. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  141. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  142. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  143. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  144. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  145. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  146. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  147. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  148. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  149. package/packages/selector/tests/settings-seat.client.spec.ts +45 -7
  150. package/packages/selector/tests/standing-generation.host.spec.ts +724 -724
  151. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -269
  152. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  153. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  154. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  155. package/packages/selector/tsconfig.json +11 -11
  156. package/packages/selector/tsdown.client.config.ts +102 -102
  157. package/packages/selector/tsdown.config.ts +20 -20
  158. package/scripts/capture-profile-baseline.mjs +42 -42
  159. package/scripts/cell-browser-e2e.mjs +354 -0
  160. package/scripts/generate-tokenizer-fixtures.py +81 -81
  161. package/scripts/generate-vision-fixtures.py +208 -208
  162. package/scripts/hosts.mjs +74 -0
  163. package/scripts/packed-components-smoke.mjs +763 -732
  164. package/scripts/packed-install-e2e.mjs +1330 -1273
  165. package/scripts/sync-hosts.mjs +174 -0
  166. package/scripts/toolclass-corpus-replay.mjs +281 -281
  167. package/scripts/verify-release.mjs +335 -318
  168. package/tsconfig.base.json +18 -18
  169. package/tsconfig.json +7 -7
  170. package/tsconfig.tests.json +15 -15
  171. package/vitest.built.config.ts +9 -9
  172. package/vitest.config.ts +46 -43
@@ -20,6 +20,7 @@ import {
20
20
  } from './tail-trim.ts'
21
21
  import { sessionEvents } from './session-events.ts'
22
22
  import { getSavingsLedger } from './savings.ts'
23
+ import { viewToolResult } from '../compat/tool-result.ts'
23
24
 
24
25
  export const name = 'context-compression-retrieve'
25
26
  export const inject = ['tools', 'systemPrompt']
@@ -123,7 +124,10 @@ export function installContextCompressionRetrieve(ctx: Context, config: Config =
123
124
  throw new Error(`context_compression_retrieve: event ${String(seq)} is not a tool/result in the current session`)
124
125
  }
125
126
  const maxLines = resolveMaxLines(args.max_lines)
126
- const scan = scanBlocks(event.data.message.content, maxScanChars)
127
+ // Generation-gated triple view: content blocks / error flag / call id
128
+ // move together across the 0.1.x envelope and the flat 0.2.0 message.
129
+ const resultView = viewToolResult(event.data.message)
130
+ const scan = scanBlocks(resultView.blocks as ContentBlock[], maxScanChars)
127
131
  const scannedLines = splitScannedLines(scan)
128
132
  const lines = scannedLines.lines
129
133
  const query = args.query
@@ -138,8 +142,8 @@ export function installContextCompressionRetrieve(ctx: Context, config: Config =
138
142
  const total = scan.complete ? String(lines.length) : `at least ${String(lines.length)}`
139
143
  const header = [
140
144
  `source: ${args.ref}`,
141
- `tool_call_id: ${event.data.message.toolCallId}`,
142
- `status: ${(event.data.message as { isError?: boolean }).isError === true ? 'error' : 'completed'}`,
145
+ `tool_call_id: ${resultView.callId}`,
146
+ `status: ${resultView.isError ? 'error' : 'completed'}`,
143
147
  `lines: ${String(selected.start)}-${String(selected.end)} of ${total}`,
144
148
  scan.complete ? '' : 'note: source scan limit reached; later lines were not inspected',
145
149
  selected.partialLine === undefined
@@ -1,30 +1,30 @@
1
- /** Public Session event-log compatibility across Harness 0.1.x releases. */
2
-
3
- import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
4
-
5
- /**
6
- * Read one immutable Session event snapshot.
7
- *
8
- * Harness rc.2 exposed `events`; Alpha 5 replaced it with the public
9
- * `snapshotEvents()` method. Prefer the new API when present and retain the
10
- * old accessor as the compatibility fallback for already-supported hosts.
11
- */
12
- export function sessionEvents(session: Session): readonly SessionEvent[] {
13
- const snapshot = (session as unknown as {
14
- snapshotEvents?: () => readonly SessionEvent[]
15
- }).snapshotEvents
16
- if (typeof snapshot === 'function') return snapshot.call(session)
17
- return (session as unknown as { events?: readonly SessionEvent[] }).events ?? []
18
- }
19
-
20
- /**
21
- * Resolve one surface-node seq to its event. 0.1.5 surface nodes are
22
- * positional and may replace earlier ranges, so a node's seq is not
23
- * guaranteed to equal the snapshot array index: always resolve by seq.
24
- */
25
- export function eventBySeq(
26
- events: readonly SessionEvent[],
27
- seq: number | bigint | { valueOf(): number },
28
- ): SessionEvent | undefined {
29
- return events[Number(seq)]
30
- }
1
+ /** Public Session event-log compatibility across Harness 0.1.x releases. */
2
+
3
+ import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
4
+
5
+ /**
6
+ * Read one immutable Session event snapshot.
7
+ *
8
+ * Harness rc.2 exposed `events`; Alpha 5 replaced it with the public
9
+ * `snapshotEvents()` method. Prefer the new API when present and retain the
10
+ * old accessor as the compatibility fallback for already-supported hosts.
11
+ */
12
+ export function sessionEvents(session: Session): readonly SessionEvent[] {
13
+ const snapshot = (session as unknown as {
14
+ snapshotEvents?: () => readonly SessionEvent[]
15
+ }).snapshotEvents
16
+ if (typeof snapshot === 'function') return snapshot.call(session)
17
+ return (session as unknown as { events?: readonly SessionEvent[] }).events ?? []
18
+ }
19
+
20
+ /**
21
+ * Resolve one surface-node seq to its event. 0.1.5 surface nodes are
22
+ * positional and may replace earlier ranges, so a node's seq is not
23
+ * guaranteed to equal the snapshot array index: always resolve by seq.
24
+ */
25
+ export function eventBySeq(
26
+ events: readonly SessionEvent[],
27
+ seq: number | bigint | { valueOf(): number },
28
+ ): SessionEvent | undefined {
29
+ return events[Number(seq)]
30
+ }
@@ -1,165 +1,175 @@
1
- /** Plugin-owned TailTrim publication protocol over official Session events. */
2
-
3
- import { createUserMessage } from '@deepseek-ai/dsh-llm'
4
- import type { ContentBlock, UserMessage } from '@deepseek-ai/dsh-llm'
5
- import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
6
- import { sessionEvents } from './session-events.ts'
7
-
8
- const TAIL_TRIM_REF_PATTERN = /^session:\/\/([^/]+)\/tailtrim\/(\d+)$/
9
- const MAX_ROOTS = 64
10
- const MAX_STUB_CODE_POINTS = 1_024
11
-
12
- /** A standard prune plus adjacent user-message replacement that validates. */
13
- export interface PublishedTailTrim {
14
- readonly manifest: SessionEvent<'compaction/prune'>
15
- readonly replacement: SessionEvent<'user/message'>
16
- readonly roots: readonly (
17
- SessionEvent<'assistant/message'> | SessionEvent<'tool/result'>
18
- )[]
19
- readonly toolNames: readonly string[]
20
- readonly ref: string
21
- readonly stub: string
22
- }
23
-
24
- /** Build a same-session reference keyed by the standard prune event. */
25
- export function tailTrimRef(sessionId: string, manifestSeq: number): string {
26
- return `session://${sessionId}/tailtrim/${String(manifestSeq)}`
27
- }
28
-
29
- /** Parse one exact TailTrim reference. */
30
- export function parseTailTrimRef(ref: string): { sessionId: string; manifestSeq: number } | null {
31
- const match = TAIL_TRIM_REF_PATTERN.exec(ref)
32
- if (match === null) return null
33
- const manifestSeq = Number(match[2])
34
- if (!Number.isSafeInteger(manifestSeq) || manifestSeq < 0) return null
35
- return { sessionId: match[1] ?? '', manifestSeq }
36
- }
37
-
38
- /** Build the fixed bounded model-visible TailTrim stub. */
39
- export function tailTrimStub(
40
- ref: string,
41
- toolNames: readonly string[],
42
- sourceEventSeqs: readonly number[],
43
- ): string | null {
44
- const stub = [
45
- '[TailTrim: completed tool-call group]',
46
- `ref: ${ref}`,
47
- `tools: ${toolNames.join(', ')}`,
48
- `source_event_seqs: ${sourceEventSeqs.join(', ')}`,
49
- 'use context_compression_retrieve with this TailTrim ref if needed',
50
- ].join('\n')
51
- return Array.from(stub).length <= MAX_STUB_CODE_POINTS ? stub : null
52
- }
53
-
54
- /** Wrap a TailTrim stub in the one user message used for range replacement. */
55
- export function tailTrimMessage(stub: string): UserMessage {
56
- return createUserMessage({
57
- content: [{ type: 'text', text: stub }],
58
- source: { kind: 'dsh-context-compression' },
59
- })
60
- }
61
-
62
- /** Validate the standard prune, adjacent replacement, append roots and stub. */
63
- export function validatePublishedTailTrim(
64
- session: Session,
65
- manifestSeq: number,
66
- ): PublishedTailTrim | null {
67
- const events = sessionEvents(session)
68
- const manifest = events[manifestSeq]
69
- if (manifest?.type !== 'compaction/prune'
70
- || manifest.data.shadowedSeqs.length < 2
71
- || manifest.data.shadowedSeqs.length > MAX_ROOTS
72
- || manifest.data.shadowedSeqs[0] !== Number(manifest.data.shadowedRange.start)
73
- || manifest.data.shadowedSeqs.at(-1) !== Number(manifest.data.shadowedRange.end)
74
- || new Set(manifest.data.shadowedSeqs).size !== manifest.data.shadowedSeqs.length) return null
75
- const replacement = events[manifestSeq + 1]
76
- if (replacement?.type !== 'user/message'
77
- || replacement.seq !== manifest.seq + 1
78
- || replacement.data.source.kind !== 'dsh-context-compression'
79
- || replacement.surfaceOp === undefined
80
- || replacement.surfaceOp === 'append'
81
- || replacement.surfaceOp.startSeq !== manifest.data.shadowedRange.start
82
- || replacement.surfaceOp.endSeq !== manifest.data.shadowedRange.end
83
- || !sameNumbers(
84
- replacement.sourceEventSeqs,
85
- [manifest.seq, ...manifest.data.shadowedSeqs],
86
- )
87
- || replacement.data.content.length !== 1
88
- || replacement.data.content[0]?.type !== 'text') return null
89
-
90
- const tracedRoots = manifest.data.shadowedSeqs.map(seq => uniqueAppendRoot(session, seq, manifestSeq))
91
- if (tracedRoots.some(root => root === null)) return null
92
- const sourceEventSeqs = tracedRoots as number[]
93
- if (new Set(sourceEventSeqs).size !== sourceEventSeqs.length) return null
94
- const roots = sourceEventSeqs.map(seq => events[seq])
95
- if (roots.some((event): event is undefined => event === undefined)) return null
96
- const typedRoots = roots as SessionEvent[]
97
- if (!validRootGroup(typedRoots, manifestSeq)) return null
98
- const assistant = typedRoots[0]
99
- if (assistant?.type !== 'assistant/message') return null
100
- const toolNames = assistant.data.message.content.map((block) => {
101
- if (block.type !== 'tool-call') throw new Error('unreachable')
102
- return block.name
103
- })
104
- const ref = tailTrimRef(String(session.id), manifestSeq)
105
- const stub = tailTrimStub(ref, toolNames, sourceEventSeqs)
106
- if (stub === null || replacement.data.content[0].text !== stub) return null
107
- return {
108
- manifest,
109
- replacement,
110
- roots: typedRoots as PublishedTailTrim['roots'],
111
- toolNames,
112
- ref,
113
- stub,
114
- }
115
- }
116
-
117
- function uniqueAppendRoot(session: Session, seq: number, beforeSeq: number): number | null {
118
- const events = sessionEvents(session)
119
- const pending: Array<{ readonly seq: number; readonly depth: number }> = [{ seq, depth: 0 }]
120
- const visited = new Set<number>()
121
- const roots = new Set<number>()
122
- while (pending.length > 0) {
123
- const next = pending.pop()
124
- if (next === undefined || next.depth > MAX_ROOTS || visited.has(next.seq)) continue
125
- if (!Number.isSafeInteger(next.seq) || next.seq < 0 || next.seq >= beforeSeq) return null
126
- visited.add(next.seq)
127
- if (visited.size > MAX_ROOTS) return null
128
- const event = events[next.seq]
129
- if (event === undefined || (event.type !== 'assistant/message' && event.type !== 'tool/result')) return null
130
- if (event.surfaceOp === 'append') roots.add(event.seq)
131
- else if (typeof event.surfaceOp === 'object') {
132
- const sources = event.sourceEventSeqs
133
- if (sources === undefined || sources.length === 0) return null
134
- for (const source of sources) pending.push({ seq: source, depth: next.depth + 1 })
135
- } else return null
136
- if (roots.size > 1) return null
137
- }
138
- return roots.size === 1 ? [...roots][0] ?? null : null
139
- }
140
-
141
- function validRootGroup(roots: readonly SessionEvent[], manifestSeq: number): boolean {
142
- const assistant = roots[0]
143
- if (assistant?.type !== 'assistant/message' || assistant.seq >= manifestSeq
144
- || assistant.surfaceOp !== 'append' || assistant.data.interrupted === true
145
- || assistant.data.message.content.length === 0
146
- || assistant.data.message.content.some(block => block.type !== 'tool-call')) return false
147
- const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
148
- const callIds = calls.map(call => call.id)
149
- if (new Set(callIds).size !== callIds.length || roots.length !== callIds.length + 1) return false
150
- for (const [index, root] of roots.slice(1).entries()) {
151
- if (root.type !== 'tool/result' || root.seq >= manifestSeq || root.surfaceOp !== 'append') return false
152
- const result = root.data.message as { isError?: boolean }
153
- if (result.isError === true
154
- || root.data.error !== undefined
155
- || root.data.turn !== assistant.data.turn
156
- || root.data.step !== assistant.data.step
157
- || String((root.data.message as { toolCallId?: unknown }).toolCallId) !== String(callIds[index])) return false
158
- }
159
- return true
160
- }
161
-
162
- function sameNumbers(left: readonly number[] | undefined, right: readonly number[]): boolean {
163
- return left !== undefined && left.length === right.length
164
- && left.every((value, index) => value === right[index])
165
- }
1
+ /** Plugin-owned TailTrim publication protocol over official Session events. */
2
+
3
+ import { createUserMessage } from '@deepseek-ai/dsh-llm'
4
+ import type { ContentBlock, UserMessage } from '@deepseek-ai/dsh-llm'
5
+ import type { Session, SessionEvent } from '@deepseek-ai/dsh-session'
6
+ import { sessionEvents } from './session-events.ts'
7
+ import { compressionMessageSource, viewToolResult } from '../compat/tool-result.ts'
8
+
9
+ const TAIL_TRIM_REF_PATTERN = /^session:\/\/([^/]+)\/tailtrim\/(\d+)$/
10
+ const MAX_ROOTS = 64
11
+ const MAX_STUB_CODE_POINTS = 1_024
12
+
13
+ /** A standard prune plus adjacent user-message replacement that validates. */
14
+ export interface PublishedTailTrim {
15
+ readonly manifest: SessionEvent<'compaction/prune'>
16
+ readonly replacement: SessionEvent<'user/message'>
17
+ readonly roots: readonly (
18
+ SessionEvent<'assistant/message'> | SessionEvent<'tool/result'>
19
+ )[]
20
+ readonly toolNames: readonly string[]
21
+ readonly ref: string
22
+ readonly stub: string
23
+ }
24
+
25
+ /** Build a same-session reference keyed by the standard prune event. */
26
+ export function tailTrimRef(sessionId: string, manifestSeq: number): string {
27
+ return `session://${sessionId}/tailtrim/${String(manifestSeq)}`
28
+ }
29
+
30
+ /** Parse one exact TailTrim reference. */
31
+ export function parseTailTrimRef(ref: string): { sessionId: string; manifestSeq: number } | null {
32
+ const match = TAIL_TRIM_REF_PATTERN.exec(ref)
33
+ if (match === null) return null
34
+ const manifestSeq = Number(match[2])
35
+ if (!Number.isSafeInteger(manifestSeq) || manifestSeq < 0) return null
36
+ return { sessionId: match[1] ?? '', manifestSeq }
37
+ }
38
+
39
+ /** Build the fixed bounded model-visible TailTrim stub. */
40
+ export function tailTrimStub(
41
+ ref: string,
42
+ toolNames: readonly string[],
43
+ sourceEventSeqs: readonly number[],
44
+ ): string | null {
45
+ const stub = [
46
+ '[TailTrim: completed tool-call group]',
47
+ `ref: ${ref}`,
48
+ `tools: ${toolNames.join(', ')}`,
49
+ `source_event_seqs: ${sourceEventSeqs.join(', ')}`,
50
+ 'use context_compression_retrieve with this TailTrim ref if needed',
51
+ ].join('\n')
52
+ return Array.from(stub).length <= MAX_STUB_CODE_POINTS ? stub : null
53
+ }
54
+
55
+ /** Wrap a TailTrim stub in the one user message used for range replacement. */
56
+ export function tailTrimMessage(stub: string): UserMessage {
57
+ return createUserMessage({
58
+ content: [{ type: 'text', text: stub }],
59
+ // Generation-gated: 0.1.x hosts only accept the shared plugin kind.
60
+ source: compressionMessageSource() as { kind: 'dsh-context-compression' },
61
+ })
62
+ }
63
+
64
+ /** Validate the standard prune, adjacent replacement, append roots and stub. */
65
+ export function validatePublishedTailTrim(
66
+ session: Session,
67
+ manifestSeq: number,
68
+ ): PublishedTailTrim | null {
69
+ const events = sessionEvents(session)
70
+ const manifest = events[manifestSeq]
71
+ if (manifest?.type !== 'compaction/prune'
72
+ || manifest.data.shadowedSeqs.length < 2
73
+ || manifest.data.shadowedSeqs.length > MAX_ROOTS
74
+ || manifest.data.shadowedSeqs[0] !== Number(manifest.data.shadowedRange.start)
75
+ || manifest.data.shadowedSeqs.at(-1) !== Number(manifest.data.shadowedRange.end)
76
+ || new Set(manifest.data.shadowedSeqs).size !== manifest.data.shadowedSeqs.length) return null
77
+ const replacement = events[manifestSeq + 1]
78
+ // The validator checks THIS runtime's own publication (same host, same
79
+ // generation), so the expected source kind is the generation-gated one the
80
+ // writer used — hardcoding the modern kind made the validator reject its
81
+ // own legacy output (measured: legacy testbed classified the host, writer
82
+ // emitted {kind:'plugin'}, validator demanded 'dsh-context-compression').
83
+ const expectedSource = compressionMessageSource()
84
+ if (replacement?.type !== 'user/message'
85
+ || replacement.seq !== manifest.seq + 1
86
+ || replacement.data.source.kind !== expectedSource.kind
87
+ || replacement.surfaceOp === undefined
88
+ || replacement.surfaceOp === 'append'
89
+ || replacement.surfaceOp.startSeq !== manifest.data.shadowedRange.start
90
+ || replacement.surfaceOp.endSeq !== manifest.data.shadowedRange.end
91
+ || !sameNumbers(
92
+ replacement.sourceEventSeqs,
93
+ [manifest.seq, ...manifest.data.shadowedSeqs],
94
+ )
95
+ || replacement.data.content.length !== 1
96
+ || replacement.data.content[0]?.type !== 'text') return null
97
+
98
+ const tracedRoots = manifest.data.shadowedSeqs.map(seq => uniqueAppendRoot(session, seq, manifestSeq))
99
+ if (tracedRoots.some(root => root === null)) return null
100
+ const sourceEventSeqs = tracedRoots as number[]
101
+ if (new Set(sourceEventSeqs).size !== sourceEventSeqs.length) return null
102
+ const roots = sourceEventSeqs.map(seq => events[seq])
103
+ if (roots.some((event): event is undefined => event === undefined)) return null
104
+ const typedRoots = roots as SessionEvent[]
105
+ if (!validRootGroup(typedRoots, manifestSeq)) return null
106
+ const assistant = typedRoots[0]
107
+ if (assistant?.type !== 'assistant/message') return null
108
+ const toolNames = assistant.data.message.content.map((block) => {
109
+ if (block.type !== 'tool-call') throw new Error('unreachable')
110
+ return block.name
111
+ })
112
+ const ref = tailTrimRef(String(session.id), manifestSeq)
113
+ const stub = tailTrimStub(ref, toolNames, sourceEventSeqs)
114
+ if (stub === null || replacement.data.content[0].text !== stub) return null
115
+ return {
116
+ manifest,
117
+ replacement,
118
+ roots: typedRoots as PublishedTailTrim['roots'],
119
+ toolNames,
120
+ ref,
121
+ stub,
122
+ }
123
+ }
124
+
125
+ function uniqueAppendRoot(session: Session, seq: number, beforeSeq: number): number | null {
126
+ const events = sessionEvents(session)
127
+ const pending: Array<{ readonly seq: number; readonly depth: number }> = [{ seq, depth: 0 }]
128
+ const visited = new Set<number>()
129
+ const roots = new Set<number>()
130
+ while (pending.length > 0) {
131
+ const next = pending.pop()
132
+ if (next === undefined || next.depth > MAX_ROOTS || visited.has(next.seq)) continue
133
+ if (!Number.isSafeInteger(next.seq) || next.seq < 0 || next.seq >= beforeSeq) return null
134
+ visited.add(next.seq)
135
+ if (visited.size > MAX_ROOTS) return null
136
+ const event = events[next.seq]
137
+ if (event === undefined || (event.type !== 'assistant/message' && event.type !== 'tool/result')) return null
138
+ if (event.surfaceOp === 'append') roots.add(event.seq)
139
+ else if (typeof event.surfaceOp === 'object') {
140
+ const sources = event.sourceEventSeqs
141
+ if (sources === undefined || sources.length === 0) return null
142
+ for (const source of sources) pending.push({ seq: source, depth: next.depth + 1 })
143
+ } else return null
144
+ if (roots.size > 1) return null
145
+ }
146
+ return roots.size === 1 ? [...roots][0] ?? null : null
147
+ }
148
+
149
+ function validRootGroup(roots: readonly SessionEvent[], manifestSeq: number): boolean {
150
+ const assistant = roots[0]
151
+ if (assistant?.type !== 'assistant/message' || assistant.seq >= manifestSeq
152
+ || assistant.surfaceOp !== 'append' || assistant.data.interrupted === true
153
+ || assistant.data.message.content.length === 0
154
+ || assistant.data.message.content.some(block => block.type !== 'tool-call')) return false
155
+ const calls = assistant.data.message.content as Extract<ContentBlock, { type: 'tool-call' }>[]
156
+ const callIds = calls.map(call => call.id)
157
+ if (new Set(callIds).size !== callIds.length || roots.length !== callIds.length + 1) return false
158
+ for (const [index, root] of roots.slice(1).entries()) {
159
+ if (root.type !== 'tool/result' || root.seq >= manifestSeq || root.surfaceOp !== 'append') return false
160
+ // Generation-gated triple view: error flag and call id axes relocate
161
+ // between the 0.1.x envelope and the flat 0.2.0 message.
162
+ const result = viewToolResult(root.data.message)
163
+ if (result.isError
164
+ || root.data.error !== undefined
165
+ || root.data.turn !== assistant.data.turn
166
+ || root.data.step !== assistant.data.step
167
+ || String(result.callId) !== String(callIds[index])) return false
168
+ }
169
+ return true
170
+ }
171
+
172
+ function sameNumbers(left: readonly number[] | undefined, right: readonly number[]): boolean {
173
+ return left !== undefined && left.length === right.length
174
+ && left.every((value, index) => value === right[index])
175
+ }
@@ -1,72 +1,72 @@
1
- /** Token counts owned by the standalone compression runtime. */
2
-
3
- /** Exact count of one canonical value under a pinned tokenizer artifact. */
4
- export interface ExactTokenizerTokenCount {
5
- readonly kind: 'exact-tokenizer'
6
- readonly tokens: number
7
- readonly tokenizerId: string
8
- readonly tokenizerRevision: string
9
- }
10
-
11
- /** A value that the bundled tokenizer cannot safely count. */
12
- export interface UnavailableTokenCount {
13
- readonly kind: 'unavailable'
14
- readonly reason: string
15
- }
16
-
17
- /** Best-effort estimate carrying a conservative upper value when available. */
18
- export interface TokenizerEstimateTokenCount {
19
- readonly kind: 'tokenizer-estimate'
20
- readonly tokens: number
21
- readonly upperBoundTokens: number
22
- readonly estimatorId: string
23
- readonly estimatorRevision: string
24
- readonly calibration?: Readonly<{
25
- readonly sampleCount: number
26
- readonly conservativeMarginTokens: number
27
- }>
28
- }
29
-
30
- /** Exact, conservative request estimate, or an explicit refusal. */
31
- export type TokenCount = ExactTokenizerTokenCount | TokenizerEstimateTokenCount | UnavailableTokenCount
32
-
33
- /** Bound exact text counter for one durable provider/model request target. */
34
- export type CanonicalTextTokenCounter = (text: string) => TokenCount
35
-
36
- /** Build an explicit unavailable result without inventing an estimate. */
37
- export function unavailableTokenCount(reason: string): UnavailableTokenCount {
38
- if (reason.length === 0) throw new TypeError('unavailable token count requires a reason')
39
- return Object.freeze({ kind: 'unavailable', reason })
40
- }
41
-
42
- /** Sum independent canonical fields only when every count has one identity. */
43
- export function countExactCanonicalTextFields(
44
- fields: readonly string[],
45
- counter: CanonicalTextTokenCounter,
46
- subject: string,
47
- ): TokenCount {
48
- if (subject.length === 0) throw new TypeError('canonical text field count requires a subject')
49
- const values = fields.length === 0 ? [''] : fields
50
- let identity: ExactTokenizerTokenCount | undefined
51
- let tokens = 0
52
- for (const value of values) {
53
- const count = counter(value)
54
- if (count.kind !== 'exact-tokenizer') {
55
- return unavailableTokenCount(`${subject}: ${count.kind === 'unavailable'
56
- ? count.reason
57
- : 'canonical content requires an exact tokenizer count'}`)
58
- }
59
- if (identity !== undefined
60
- && (identity.tokenizerId !== count.tokenizerId
61
- || identity.tokenizerRevision !== count.tokenizerRevision)) {
62
- return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`)
63
- }
64
- identity ??= count
65
- tokens += count.tokens
66
- if (!Number.isSafeInteger(tokens) || tokens < 0) {
67
- return unavailableTokenCount(`${subject}: token sum is outside the safe integer range`)
68
- }
69
- }
70
- if (identity === undefined) return unavailableTokenCount(`${subject}: no tokenizer identity`)
71
- return Object.freeze({ ...identity, tokens })
72
- }
1
+ /** Token counts owned by the standalone compression runtime. */
2
+
3
+ /** Exact count of one canonical value under a pinned tokenizer artifact. */
4
+ export interface ExactTokenizerTokenCount {
5
+ readonly kind: 'exact-tokenizer'
6
+ readonly tokens: number
7
+ readonly tokenizerId: string
8
+ readonly tokenizerRevision: string
9
+ }
10
+
11
+ /** A value that the bundled tokenizer cannot safely count. */
12
+ export interface UnavailableTokenCount {
13
+ readonly kind: 'unavailable'
14
+ readonly reason: string
15
+ }
16
+
17
+ /** Best-effort estimate carrying a conservative upper value when available. */
18
+ export interface TokenizerEstimateTokenCount {
19
+ readonly kind: 'tokenizer-estimate'
20
+ readonly tokens: number
21
+ readonly upperBoundTokens: number
22
+ readonly estimatorId: string
23
+ readonly estimatorRevision: string
24
+ readonly calibration?: Readonly<{
25
+ readonly sampleCount: number
26
+ readonly conservativeMarginTokens: number
27
+ }>
28
+ }
29
+
30
+ /** Exact, conservative request estimate, or an explicit refusal. */
31
+ export type TokenCount = ExactTokenizerTokenCount | TokenizerEstimateTokenCount | UnavailableTokenCount
32
+
33
+ /** Bound exact text counter for one durable provider/model request target. */
34
+ export type CanonicalTextTokenCounter = (text: string) => TokenCount
35
+
36
+ /** Build an explicit unavailable result without inventing an estimate. */
37
+ export function unavailableTokenCount(reason: string): UnavailableTokenCount {
38
+ if (reason.length === 0) throw new TypeError('unavailable token count requires a reason')
39
+ return Object.freeze({ kind: 'unavailable', reason })
40
+ }
41
+
42
+ /** Sum independent canonical fields only when every count has one identity. */
43
+ export function countExactCanonicalTextFields(
44
+ fields: readonly string[],
45
+ counter: CanonicalTextTokenCounter,
46
+ subject: string,
47
+ ): TokenCount {
48
+ if (subject.length === 0) throw new TypeError('canonical text field count requires a subject')
49
+ const values = fields.length === 0 ? [''] : fields
50
+ let identity: ExactTokenizerTokenCount | undefined
51
+ let tokens = 0
52
+ for (const value of values) {
53
+ const count = counter(value)
54
+ if (count.kind !== 'exact-tokenizer') {
55
+ return unavailableTokenCount(`${subject}: ${count.kind === 'unavailable'
56
+ ? count.reason
57
+ : 'canonical content requires an exact tokenizer count'}`)
58
+ }
59
+ if (identity !== undefined
60
+ && (identity.tokenizerId !== count.tokenizerId
61
+ || identity.tokenizerRevision !== count.tokenizerRevision)) {
62
+ return unavailableTokenCount(`${subject}: tokenizer identity changed within one measurement`)
63
+ }
64
+ identity ??= count
65
+ tokens += count.tokens
66
+ if (!Number.isSafeInteger(tokens) || tokens < 0) {
67
+ return unavailableTokenCount(`${subject}: token sum is outside the safe integer range`)
68
+ }
69
+ }
70
+ if (identity === undefined) return unavailableTokenCount(`${subject}: no tokenizer identity`)
71
+ return Object.freeze({ ...identity, tokens })
72
+ }