dsh-context-compression-improved 0.5.6 → 0.5.7

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 (162) 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.ja.md +169 -169
  5. package/CHANGELOG.ko.md +167 -167
  6. package/CHANGELOG.md +314 -304
  7. package/CHANGELOG.zh.md +152 -152
  8. package/CONTRIBUTING.md +22 -22
  9. package/LICENSE +21 -21
  10. package/README.ja.md +85 -85
  11. package/README.ko.md +85 -85
  12. package/README.md +94 -94
  13. package/README.zh.md +85 -85
  14. package/SECURITY.md +18 -18
  15. package/THIRD_PARTY_NOTICES.md +14 -14
  16. package/docs/compat-0.1.5-report.md +77 -77
  17. package/docs/installation.ja.md +78 -78
  18. package/docs/installation.ko.md +78 -78
  19. package/docs/installation.md +103 -103
  20. package/docs/installation.zh.md +100 -100
  21. package/docs/repair-log.md +657 -657
  22. package/eslint.config.js +30 -30
  23. package/package.json +164 -164
  24. package/packages/selector/LICENSE +21 -21
  25. package/packages/selector/README.md +26 -26
  26. package/packages/selector/README.zh.md +24 -24
  27. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -32
  28. package/packages/selector/cordis.patch.yml +27 -27
  29. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -112
  30. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -34
  31. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -46
  32. package/packages/selector/dsh.plugin.json +16 -16
  33. package/packages/selector/lib/client.js +733 -0
  34. package/packages/selector/lib/style.css +46 -46
  35. package/packages/selector/package.json +114 -114
  36. package/packages/selector/screenshots.json +3 -3
  37. package/packages/selector/src/client/CompressionProfileControls.tsx +226 -226
  38. package/packages/selector/src/client/CompressionProfileSelector.module.css +170 -170
  39. package/packages/selector/src/client/CompressionProfileSelector.tsx +83 -83
  40. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -216
  41. package/packages/selector/src/client/EstimatorControls.tsx +277 -277
  42. package/packages/selector/src/client/decode.ts +49 -49
  43. package/packages/selector/src/client/index.ts +178 -149
  44. package/packages/selector/src/client/locales/de.ts +98 -0
  45. package/packages/selector/src/client/locales/es.ts +98 -0
  46. package/packages/selector/src/client/locales/fr.ts +98 -0
  47. package/packages/selector/src/client/locales/it.ts +98 -0
  48. package/packages/selector/src/client/locales/ja.ts +98 -0
  49. package/packages/selector/src/client/locales/ko.ts +98 -0
  50. package/packages/selector/src/client/locales/ru.ts +98 -0
  51. package/packages/selector/src/client/locales.ts +196 -196
  52. package/packages/selector/src/client/preset-options.ts +88 -88
  53. package/packages/selector/src/client/settings-section.tsx +124 -124
  54. package/packages/selector/src/css-modules.d.ts +6 -6
  55. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -205
  56. package/packages/selector/src/estimator-catalog.ts +104 -104
  57. package/packages/selector/src/index.ts +463 -463
  58. package/packages/selector/src/invariant.ts +113 -113
  59. package/packages/selector/src/preset-overlay.ts +626 -626
  60. package/packages/selector/src/profiles.ts +394 -394
  61. package/packages/selector/src/pruner/content.ts +201 -201
  62. package/packages/selector/src/pruner/session.ts +94 -94
  63. package/packages/selector/src/pruner/state.ts +50 -50
  64. package/packages/selector/src/pruner/tuning.ts +23 -23
  65. package/packages/selector/src/pruner/types.ts +78 -78
  66. package/packages/selector/src/pruner.ts +2402 -2402
  67. package/packages/selector/src/runtime/adaptive-cost.ts +205 -205
  68. package/packages/selector/src/runtime/audit.ts +286 -286
  69. package/packages/selector/src/runtime/config.ts +706 -706
  70. package/packages/selector/src/runtime/custom-policy.ts +278 -278
  71. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -298
  72. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -254
  73. package/packages/selector/src/runtime/measurement.ts +436 -436
  74. package/packages/selector/src/runtime/reducers.ts +1674 -1674
  75. package/packages/selector/src/runtime/retrieve.ts +457 -457
  76. package/packages/selector/src/runtime/session-events.ts +30 -30
  77. package/packages/selector/src/runtime/tail-trim.ts +166 -166
  78. package/packages/selector/src/runtime/token-count.ts +72 -72
  79. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +188 -188
  80. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +149 -149
  81. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -419
  82. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -200
  83. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -81
  84. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -151
  85. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -128
  86. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -98
  87. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -303
  88. package/packages/selector/src/runtime/toolclass.ts +103 -103
  89. package/packages/selector/src/runtime/types.ts +346 -346
  90. package/packages/selector/src/runtime/value.ts +48 -48
  91. package/packages/selector/tests/advisor-report.host.spec.ts +223 -223
  92. package/packages/selector/tests/auto-compact.client.spec.tsx +213 -213
  93. package/packages/selector/tests/built/client-artifact.spec.ts +59 -59
  94. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -123
  95. package/packages/selector/tests/code-skeleton.client.spec.ts +90 -90
  96. package/packages/selector/tests/custom-contract.client.spec.ts +204 -204
  97. package/packages/selector/tests/estimator-catalog.spec.ts +70 -70
  98. package/packages/selector/tests/estimator-channel.client.spec.tsx +252 -252
  99. package/packages/selector/tests/estimator-route-registration.host.spec.ts +188 -188
  100. package/packages/selector/tests/host-preset-overlay.host.spec.ts +206 -206
  101. package/packages/selector/tests/preset-options-write.client.spec.ts +206 -206
  102. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +201 -201
  103. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -246
  104. package/packages/selector/tests/profiles.client.spec.tsx +434 -434
  105. package/packages/selector/tests/public/package-contract.client.spec.ts +78 -78
  106. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -167
  107. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +232 -232
  108. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -272
  109. package/packages/selector/tests/runtime/advisor.spec.ts +226 -226
  110. package/packages/selector/tests/runtime/audit.spec.ts +274 -274
  111. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -523
  112. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -30
  113. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -152
  114. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -186
  115. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -122
  116. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -122
  117. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -96
  118. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -273
  119. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -106
  120. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -459
  121. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -74
  122. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -212
  123. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -153
  124. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -133
  125. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2724 -2724
  126. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -33
  127. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -110
  128. package/packages/selector/tests/runtime/session-events.spec.ts +27 -27
  129. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -241
  130. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -159
  131. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -53
  132. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -217
  133. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -52
  134. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -79
  135. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -76
  136. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +116 -116
  137. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -82
  138. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -156
  139. package/packages/selector/tests/runtime/value.spec.ts +23 -23
  140. package/packages/selector/tests/settings-seat.client.spec.ts +118 -118
  141. package/packages/selector/tests/standing-generation.host.spec.ts +697 -697
  142. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +253 -253
  143. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -105
  144. package/packages/selector/tests/support/mock-adapter.ts +37 -37
  145. package/packages/selector/tests/support/ui-primitives.tsx +34 -34
  146. package/packages/selector/tsconfig.json +11 -11
  147. package/packages/selector/tsdown.client.config.ts +102 -102
  148. package/packages/selector/tsdown.config.ts +20 -20
  149. package/pnpm-workspace.yaml +66 -66
  150. package/scripts/capture-profile-baseline.mjs +42 -42
  151. package/scripts/generate-tokenizer-fixtures.py +81 -81
  152. package/scripts/generate-vision-fixtures.py +208 -208
  153. package/scripts/packed-components-smoke.mjs +732 -732
  154. package/scripts/packed-install-e2e.mjs +1273 -1273
  155. package/scripts/toolclass-corpus-replay.mjs +281 -281
  156. package/scripts/verify-release.mjs +317 -317
  157. package/tests/TEST_INVENTORY.md +41 -41
  158. package/tsconfig.base.json +18 -18
  159. package/tsconfig.json +7 -7
  160. package/tsconfig.tests.json +15 -15
  161. package/vitest.built.config.ts +9 -9
  162. package/vitest.config.ts +43 -43
@@ -1,457 +1,457 @@
1
- /**
2
- * Current-session recovery tool for context-compression placeholders.
3
- *
4
- * It reads the immutable append-only event cited by a `session://.../event/N`
5
- * reference. The tool never reads the replacement surface as the source of
6
- * truth and never crosses into another Session.
7
- *
8
- * @module dsh-context-compression-improved-runtime/retrieve
9
- */
10
-
11
- import type { Context } from '@deepseek-ai/cordis'
12
- import z from '@deepseek-ai/schemastery'
13
- import { defineTool } from '@deepseek-ai/dsh-tools'
14
- import type { ContentBlock } from '@deepseek-ai/dsh-llm'
15
- import type {} from '@deepseek-ai/dsh-system-prompt'
16
- import {
17
- parseTailTrimRef,
18
- validatePublishedTailTrim,
19
- type PublishedTailTrim,
20
- } from './tail-trim.ts'
21
- import { sessionEvents } from './session-events.ts'
22
-
23
- export const name = 'context-compression-retrieve'
24
- export const inject = ['tools', 'systemPrompt']
25
-
26
- /** Maximum text returned by one recovery call. */
27
- export interface Config {
28
- /** Hard response bound in Unicode code points. Defaults to 50000. */
29
- maxChars?: number
30
- /** Maximum source text inspected by one call. Defaults to 250000. */
31
- maxScanChars?: number
32
- /** Maximum query length in Unicode code points. Defaults to 256. */
33
- maxQueryChars?: number
34
- }
35
-
36
- /** Loader schema for the recovery tool's bounded runtime configuration. */
37
- export const Config: z<Config> = z.object({
38
- maxChars: z.number().step(1).min(1).default(50_000),
39
- maxScanChars: z.number().step(1).min(1).default(250_000),
40
- maxQueryChars: z.number().step(1).min(1).default(256),
41
- })
42
-
43
- const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/
44
- const MAX_LINES = 1_000
45
- const DEFAULT_MAX_CHARS = 50_000
46
- const DEFAULT_MAX_SCAN_CHARS = 250_000
47
- const DEFAULT_MAX_QUERY_CHARS = 256
48
- const TRUNCATION_MARKER = '\n[context_compression_retrieve output truncated; reported lines describe the selected source range]\n'
49
- const PROMPT = 'When a compacted tool result contains a session://<session-id>/event/<seq> reference, '
50
- + 'or TailTrim contains a session://<session-id>/tailtrim/<seq> reference, use context_compression_retrieve with that exact ref '
51
- + 'and a narrow line range or query if the omitted evidence is necessary. '
52
- + 'The returned event content comes from the append-only session log, which is the source of truth.'
53
-
54
- const OUTPUT = {
55
- schema: { type: 'string' as const },
56
- render: (_args: unknown, value: string) => [{ type: 'text' as const, text: value }],
57
- }
58
-
59
- /**
60
- * Register the current-session recovery tool and its stable guidance.
61
- *
62
- * @param ctx Plugin context providing the tool registry and system prompt.
63
- * @param config Optional response, scan, and query bounds.
64
- */
65
- export function installContextCompressionRetrieve(ctx: Context, config: Config = {}): void {
66
- const maxChars = resolvePositiveInteger('maxChars', config.maxChars, DEFAULT_MAX_CHARS)
67
- const maxScanChars = resolvePositiveInteger(
68
- 'maxScanChars', config.maxScanChars, DEFAULT_MAX_SCAN_CHARS,
69
- )
70
- const maxQueryChars = resolvePositiveInteger(
71
- 'maxQueryChars', config.maxQueryChars, DEFAULT_MAX_QUERY_CHARS,
72
- )
73
- ctx.systemPrompt.section({ name: 'tool:context-compression-retrieve', order: 114, text: PROMPT })
74
- ctx.tools.register(defineTool({
75
- name: 'context_compression_retrieve',
76
- description: 'Recover exact content from one compacted tool result or TailTrim group using its current-session session:// reference.',
77
- parameters: {
78
- ref: { type: 'string', required: true, description: 'Exact session://<current-session-id>/event/<seq> or /tailtrim/<seq> reference from a placeholder.' },
79
- query: { type: 'string', description: 'Optional case-insensitive text to search for inside the original result.' },
80
- start_line: { type: 'integer', description: 'Optional 1-based first line for a direct slice. Defaults to 1.' },
81
- max_lines: { type: 'integer', description: 'Maximum lines to return. Defaults to 200; maximum 1000.' },
82
- },
83
- output: OUTPUT,
84
- isConcurrencySafe: () => true,
85
- execute(args, exec) {
86
- if (exec.agent === undefined) throw new Error('context_compression_retrieve requires an agent session')
87
- const match = REF_PATTERN.exec(args.ref)
88
- const tailTrimRef = parseTailTrimRef(args.ref)
89
- if (match === null && tailTrimRef === null) {
90
- throw new Error('context_compression_retrieve: ref must be session://<session-id>/(event|tailtrim)/<seq>')
91
- }
92
- const sessionId = match?.[1] ?? tailTrimRef?.sessionId
93
- if (sessionId !== String(exec.agent.id)) {
94
- throw new Error('context_compression_retrieve: a compression reference may only read the caller\'s current session')
95
- }
96
- if (tailTrimRef !== null) {
97
- return Promise.resolve(recoverTailTrim(
98
- exec.agent.session,
99
- args.ref,
100
- tailTrimRef.manifestSeq,
101
- args.query,
102
- args.start_line,
103
- args.max_lines,
104
- { maxChars, maxScanChars, maxQueryChars },
105
- ))
106
- }
107
- const seq = Number(match?.[2])
108
- const event = sessionEvents(exec.agent.session)[seq]
109
- if (event?.type !== 'tool/result') {
110
- throw new Error(`context_compression_retrieve: event ${String(seq)} is not a tool/result in the current session`)
111
- }
112
- const maxLines = resolveMaxLines(args.max_lines)
113
- const scan = scanBlocks(event.data.message.content[0].content, maxScanChars)
114
- const scannedLines = splitScannedLines(scan)
115
- const lines = scannedLines.lines
116
- const query = args.query
117
- if (query !== undefined && exceedsCodePointLimit(query, maxQueryChars)) {
118
- throw new Error(
119
- `context_compression_retrieve: query must be at most ${String(maxQueryChars)} Unicode code points`,
120
- )
121
- }
122
- const selected = query === undefined || query === ''
123
- ? directSlice(lines, args.start_line ?? 1, maxLines, scan.complete, scannedLines.partialTail)
124
- : querySlice(lines, query, maxLines, scan.complete, scannedLines.partialTail)
125
- const total = scan.complete ? String(lines.length) : `at least ${String(lines.length)}`
126
- const header = [
127
- `source: ${args.ref}`,
128
- `tool_call_id: ${event.data.message.source.callId}`,
129
- `status: ${event.data.message.content[0].isError === true ? 'error' : 'completed'}`,
130
- `lines: ${String(selected.start)}-${String(selected.end)} of ${total}`,
131
- scan.complete ? '' : 'note: source scan limit reached; later lines were not inspected',
132
- selected.partialLine === undefined
133
- ? ''
134
- : `note: line ${String(selected.partialLine)} is a partial prefix ending at the source scan limit`,
135
- selected.omitted
136
- ? query === undefined || query === ''
137
- ? 'note: additional source lines were omitted'
138
- : 'note: additional matching or neighboring lines were omitted'
139
- : '',
140
- '--- original tool result ---',
141
- ].filter(Boolean).join('\n')
142
- const output = `${header}\n${selected.text}`
143
- return Promise.resolve(boundCodePoints(output, maxChars))
144
- },
145
- }))
146
- }
147
-
148
- function recoverTailTrim(
149
- session: Parameters<typeof validatePublishedTailTrim>[0],
150
- ref: string,
151
- manifestSeq: number,
152
- query: string | undefined,
153
- startLine: number | undefined,
154
- requestedMaxLines: number | undefined,
155
- bounds: { readonly maxChars: number; readonly maxScanChars: number; readonly maxQueryChars: number },
156
- ): string {
157
- const published = validatePublishedTailTrim(session, manifestSeq)
158
- if (published === null || published.ref !== ref) {
159
- throw new Error('context_compression_retrieve: ref is not a valid published TailTrim group')
160
- }
161
- if (query !== undefined && exceedsCodePointLimit(query, bounds.maxQueryChars)) {
162
- throw new Error(
163
- `context_compression_retrieve: query must be at most ${String(bounds.maxQueryChars)} Unicode code points`,
164
- )
165
- }
166
- const fixedHeader = [
167
- `source: ${ref}`,
168
- 'kind: tailtrim-group',
169
- `records: ${String(published.roots.length)}`,
170
- '--- original tool group (jsonl) ---',
171
- ].join('\n')
172
- const scanBudget = Math.max(0, bounds.maxScanChars - codePointLength(`${fixedHeader}\n`))
173
- const scan = consumeChunks(renderGroupRecordChunks(published.roots), scanBudget)
174
- const scannedLines = splitScannedLines(scan)
175
- const maxLines = resolveMaxLines(requestedMaxLines)
176
- const selected = query === undefined || query === ''
177
- ? directSlice(
178
- scannedLines.lines,
179
- startLine ?? 1,
180
- maxLines,
181
- scan.complete,
182
- scannedLines.partialTail,
183
- )
184
- : querySlice(
185
- scannedLines.lines,
186
- query,
187
- maxLines,
188
- scan.complete,
189
- scannedLines.partialTail,
190
- )
191
- const header = [
192
- fixedHeader.split('\n').slice(0, 3).join('\n'),
193
- scan.complete ? '' : 'note: source scan limit reached; later records were not inspected',
194
- selected.omitted ? 'note: additional group records were omitted' : '',
195
- '--- original tool group (jsonl) ---',
196
- ].filter(Boolean).join('\n')
197
- return boundCodePoints(`${header}\n${selected.text}`, bounds.maxChars)
198
- }
199
-
200
- interface ScanResult {
201
- readonly text: string
202
- readonly complete: boolean
203
- }
204
-
205
- interface ScannedLines {
206
- readonly lines: readonly string[]
207
- readonly partialTail: boolean
208
- }
209
-
210
- interface Selection {
211
- readonly text: string
212
- readonly start: number
213
- readonly end: number
214
- readonly omitted: boolean
215
- readonly partialLine?: number
216
- }
217
-
218
- function resolvePositiveInteger(name: string, value: number | undefined, fallback: number): number {
219
- const resolved = value ?? fallback
220
- if (!Number.isSafeInteger(resolved) || resolved <= 0) {
221
- throw new TypeError(`tool-context-retrieve: ${name} must be a positive safe integer`)
222
- }
223
- return resolved
224
- }
225
-
226
- function resolveMaxLines(value: number | undefined): number {
227
- const resolved = value ?? 200
228
- if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > MAX_LINES) {
229
- throw new Error(`context_compression_retrieve: max_lines must be an integer from 1 to ${String(MAX_LINES)}`)
230
- }
231
- return resolved
232
- }
233
-
234
- function scanBlocks(blocks: readonly ContentBlock[], maxChars: number): ScanResult {
235
- return consumeChunks(renderBlockChunks(blocks), maxChars)
236
- }
237
-
238
- function* renderBlockChunks(blocks: readonly ContentBlock[]): Generator<string> {
239
- let first = true
240
- for (const block of blocks) {
241
- if (!first) yield '\n'
242
- first = false
243
- if (block.type === 'text') yield block.text
244
- else yield* jsonTokens(block)
245
- }
246
- }
247
-
248
- function* renderGroupRecordChunks(roots: PublishedTailTrim['roots']): Generator<string> {
249
- let first = true
250
- for (const root of roots) {
251
- if (!first) yield '\n'
252
- first = false
253
- const message = root.data.message
254
- yield* jsonTokens({
255
- seq: root.seq,
256
- type: root.type,
257
- message: {
258
- id: message.id,
259
- role: message.role,
260
- content: message.content,
261
- source: message.source,
262
- },
263
- })
264
- }
265
- }
266
-
267
- function* jsonTokens(value: unknown): Generator<string> {
268
- if (value === null) {
269
- yield 'null'
270
- return
271
- }
272
- switch (typeof value) {
273
- case 'string':
274
- yield '"'
275
- for (const point of value) {
276
- const quoted = jsonScalar(point)
277
- yield quoted.slice(1, -1)
278
- }
279
- yield '"'
280
- return
281
- case 'number':
282
- case 'boolean':
283
- yield jsonScalar(value)
284
- return
285
- case 'object': {
286
- if (Array.isArray(value)) {
287
- yield '['
288
- for (let index = 0; index < value.length; index++) {
289
- if (index > 0) yield ','
290
- yield* jsonTokens(value[index])
291
- }
292
- yield ']'
293
- return
294
- }
295
- yield '{'
296
- let first = true
297
- for (const key in value) {
298
- if (!Object.hasOwn(value, key)) continue
299
- if (!first) yield ','
300
- first = false
301
- yield* jsonTokens(key)
302
- yield ':'
303
- yield* jsonTokens((value as Record<string, unknown>)[key])
304
- }
305
- yield '}'
306
- return
307
- }
308
- default:
309
- throw new TypeError('context_compression_retrieve: source content is not JSON-serializable')
310
- }
311
- }
312
-
313
- function jsonScalar(value: string | number | boolean): string {
314
- return JSON.stringify(value)
315
- }
316
-
317
- function consumeChunks(chunks: Iterable<string>, maxChars: number): ScanResult {
318
- const output: string[] = []
319
- let remaining = maxChars
320
- for (const chunk of chunks) {
321
- const prefix = codePointPrefix(chunk, remaining)
322
- output.push(prefix.text)
323
- remaining -= prefix.count
324
- if (!prefix.complete) return { text: output.join(''), complete: false }
325
- }
326
- return { text: output.join(''), complete: true }
327
- }
328
-
329
- function splitScannedLines(scan: ScanResult): ScannedLines {
330
- const lines = scan.text.split('\n')
331
- const partialTail = !scan.complete && !scan.text.endsWith('\n')
332
- if (scan.text.endsWith('\n')) lines.pop()
333
- return { lines, partialTail }
334
- }
335
-
336
- function directSlice(
337
- lines: readonly string[],
338
- startLine: number,
339
- maxLines: number,
340
- scanComplete: boolean,
341
- partialTail: boolean,
342
- ): Selection {
343
- if (!Number.isSafeInteger(startLine) || startLine < 1) {
344
- throw new Error('context_compression_retrieve: start_line must be a positive safe integer')
345
- }
346
- if (startLine > lines.length) {
347
- const reason = scanComplete ? 'outside the source line range' : 'beyond the source scan limit'
348
- throw new Error(`context_compression_retrieve: start_line ${String(startLine)} is ${reason}`)
349
- }
350
- const startIndex = startLine - 1
351
- const selected = lines.slice(startIndex, startIndex + maxLines)
352
- return {
353
- text: selected.join('\n'),
354
- start: startIndex + 1,
355
- end: startIndex + selected.length,
356
- omitted: startIndex > 0 || startIndex + selected.length < lines.length || !scanComplete,
357
- ...partialTail && startIndex + selected.length === lines.length
358
- ? { partialLine: lines.length }
359
- : {},
360
- }
361
- }
362
-
363
- function querySlice(
364
- lines: readonly string[],
365
- query: string,
366
- maxLines: number,
367
- scanComplete: boolean,
368
- partialTail: boolean,
369
- ): Selection {
370
- const needle = query.toLowerCase()
371
- const chosen = new Set<number>()
372
- let matched = false
373
- let omitted = !scanComplete
374
- for (let index = 0; index < lines.length; index++) {
375
- const line = lines[index]
376
- if (line === undefined || !line.toLowerCase().includes(needle)) continue
377
- matched = true
378
- for (let row = Math.max(0, index - 2); row <= Math.min(lines.length - 1, index + 2); row++) {
379
- if (chosen.has(row)) continue
380
- if (chosen.size >= maxLines) {
381
- omitted = true
382
- continue
383
- }
384
- chosen.add(row)
385
- }
386
- }
387
- if (!matched) {
388
- return {
389
- text: scanComplete ? '[no matches]' : '[no matches within source scan limit]',
390
- start: 0,
391
- end: 0,
392
- omitted,
393
- }
394
- }
395
- const ordered = [...chosen].sort((a, b) => a - b)
396
- const rendered: string[] = []
397
- let previous = -2
398
- let start = 0
399
- let end = 0
400
- for (const index of ordered) {
401
- const line = lines[index]
402
- if (line === undefined) continue
403
- if (index > previous + 1) rendered.push('...')
404
- rendered.push(`${String(index + 1)}: ${line}`)
405
- if (start === 0) start = index + 1
406
- end = index + 1
407
- previous = index
408
- }
409
- return {
410
- text: rendered.join('\n'),
411
- start,
412
- end,
413
- omitted,
414
- ...partialTail && ordered.includes(lines.length - 1)
415
- ? { partialLine: lines.length }
416
- : {},
417
- }
418
- }
419
-
420
- function boundCodePoints(text: string, maxChars: number): string {
421
- const bounded = codePointPrefix(text, maxChars)
422
- if (bounded.complete) return text
423
- const marker = codePointPrefix(TRUNCATION_MARKER, maxChars)
424
- if (!marker.complete) return marker.text
425
- const body = codePointPrefix(text, maxChars - marker.count)
426
- return body.text + marker.text
427
- }
428
-
429
- function codePointPrefix(text: string, maxChars: number): {
430
- readonly text: string
431
- readonly count: number
432
- readonly complete: boolean
433
- } {
434
- const output: string[] = []
435
- let count = 0
436
- for (const point of text) {
437
- if (count >= maxChars) return { text: output.join(''), count, complete: false }
438
- output.push(point)
439
- count++
440
- }
441
- return { text: output.join(''), count, complete: true }
442
- }
443
-
444
- function exceedsCodePointLimit(text: string, limit: number): boolean {
445
- let count = 0
446
- for (const _point of text) {
447
- count++
448
- if (count > limit) return true
449
- }
450
- return false
451
- }
452
-
453
- function codePointLength(text: string): number {
454
- let count = 0
455
- for (const _point of text) count++
456
- return count
457
- }
1
+ /**
2
+ * Current-session recovery tool for context-compression placeholders.
3
+ *
4
+ * It reads the immutable append-only event cited by a `session://.../event/N`
5
+ * reference. The tool never reads the replacement surface as the source of
6
+ * truth and never crosses into another Session.
7
+ *
8
+ * @module dsh-context-compression-improved-runtime/retrieve
9
+ */
10
+
11
+ import type { Context } from '@deepseek-ai/cordis'
12
+ import z from '@deepseek-ai/schemastery'
13
+ import { defineTool } from '@deepseek-ai/dsh-tools'
14
+ import type { ContentBlock } from '@deepseek-ai/dsh-llm'
15
+ import type {} from '@deepseek-ai/dsh-system-prompt'
16
+ import {
17
+ parseTailTrimRef,
18
+ validatePublishedTailTrim,
19
+ type PublishedTailTrim,
20
+ } from './tail-trim.ts'
21
+ import { sessionEvents } from './session-events.ts'
22
+
23
+ export const name = 'context-compression-retrieve'
24
+ export const inject = ['tools', 'systemPrompt']
25
+
26
+ /** Maximum text returned by one recovery call. */
27
+ export interface Config {
28
+ /** Hard response bound in Unicode code points. Defaults to 50000. */
29
+ maxChars?: number
30
+ /** Maximum source text inspected by one call. Defaults to 250000. */
31
+ maxScanChars?: number
32
+ /** Maximum query length in Unicode code points. Defaults to 256. */
33
+ maxQueryChars?: number
34
+ }
35
+
36
+ /** Loader schema for the recovery tool's bounded runtime configuration. */
37
+ export const Config: z<Config> = z.object({
38
+ maxChars: z.number().step(1).min(1).default(50_000),
39
+ maxScanChars: z.number().step(1).min(1).default(250_000),
40
+ maxQueryChars: z.number().step(1).min(1).default(256),
41
+ })
42
+
43
+ const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/
44
+ const MAX_LINES = 1_000
45
+ const DEFAULT_MAX_CHARS = 50_000
46
+ const DEFAULT_MAX_SCAN_CHARS = 250_000
47
+ const DEFAULT_MAX_QUERY_CHARS = 256
48
+ const TRUNCATION_MARKER = '\n[context_compression_retrieve output truncated; reported lines describe the selected source range]\n'
49
+ const PROMPT = 'When a compacted tool result contains a session://<session-id>/event/<seq> reference, '
50
+ + 'or TailTrim contains a session://<session-id>/tailtrim/<seq> reference, use context_compression_retrieve with that exact ref '
51
+ + 'and a narrow line range or query if the omitted evidence is necessary. '
52
+ + 'The returned event content comes from the append-only session log, which is the source of truth.'
53
+
54
+ const OUTPUT = {
55
+ schema: { type: 'string' as const },
56
+ render: (_args: unknown, value: string) => [{ type: 'text' as const, text: value }],
57
+ }
58
+
59
+ /**
60
+ * Register the current-session recovery tool and its stable guidance.
61
+ *
62
+ * @param ctx Plugin context providing the tool registry and system prompt.
63
+ * @param config Optional response, scan, and query bounds.
64
+ */
65
+ export function installContextCompressionRetrieve(ctx: Context, config: Config = {}): void {
66
+ const maxChars = resolvePositiveInteger('maxChars', config.maxChars, DEFAULT_MAX_CHARS)
67
+ const maxScanChars = resolvePositiveInteger(
68
+ 'maxScanChars', config.maxScanChars, DEFAULT_MAX_SCAN_CHARS,
69
+ )
70
+ const maxQueryChars = resolvePositiveInteger(
71
+ 'maxQueryChars', config.maxQueryChars, DEFAULT_MAX_QUERY_CHARS,
72
+ )
73
+ ctx.systemPrompt.section({ name: 'tool:context-compression-retrieve', order: 114, text: PROMPT })
74
+ ctx.tools.register(defineTool({
75
+ name: 'context_compression_retrieve',
76
+ description: 'Recover exact content from one compacted tool result or TailTrim group using its current-session session:// reference.',
77
+ parameters: {
78
+ ref: { type: 'string', required: true, description: 'Exact session://<current-session-id>/event/<seq> or /tailtrim/<seq> reference from a placeholder.' },
79
+ query: { type: 'string', description: 'Optional case-insensitive text to search for inside the original result.' },
80
+ start_line: { type: 'integer', description: 'Optional 1-based first line for a direct slice. Defaults to 1.' },
81
+ max_lines: { type: 'integer', description: 'Maximum lines to return. Defaults to 200; maximum 1000.' },
82
+ },
83
+ output: OUTPUT,
84
+ isConcurrencySafe: () => true,
85
+ execute(args, exec) {
86
+ if (exec.agent === undefined) throw new Error('context_compression_retrieve requires an agent session')
87
+ const match = REF_PATTERN.exec(args.ref)
88
+ const tailTrimRef = parseTailTrimRef(args.ref)
89
+ if (match === null && tailTrimRef === null) {
90
+ throw new Error('context_compression_retrieve: ref must be session://<session-id>/(event|tailtrim)/<seq>')
91
+ }
92
+ const sessionId = match?.[1] ?? tailTrimRef?.sessionId
93
+ if (sessionId !== String(exec.agent.id)) {
94
+ throw new Error('context_compression_retrieve: a compression reference may only read the caller\'s current session')
95
+ }
96
+ if (tailTrimRef !== null) {
97
+ return Promise.resolve(recoverTailTrim(
98
+ exec.agent.session,
99
+ args.ref,
100
+ tailTrimRef.manifestSeq,
101
+ args.query,
102
+ args.start_line,
103
+ args.max_lines,
104
+ { maxChars, maxScanChars, maxQueryChars },
105
+ ))
106
+ }
107
+ const seq = Number(match?.[2])
108
+ const event = sessionEvents(exec.agent.session)[seq]
109
+ if (event?.type !== 'tool/result') {
110
+ throw new Error(`context_compression_retrieve: event ${String(seq)} is not a tool/result in the current session`)
111
+ }
112
+ const maxLines = resolveMaxLines(args.max_lines)
113
+ const scan = scanBlocks(event.data.message.content[0].content, maxScanChars)
114
+ const scannedLines = splitScannedLines(scan)
115
+ const lines = scannedLines.lines
116
+ const query = args.query
117
+ if (query !== undefined && exceedsCodePointLimit(query, maxQueryChars)) {
118
+ throw new Error(
119
+ `context_compression_retrieve: query must be at most ${String(maxQueryChars)} Unicode code points`,
120
+ )
121
+ }
122
+ const selected = query === undefined || query === ''
123
+ ? directSlice(lines, args.start_line ?? 1, maxLines, scan.complete, scannedLines.partialTail)
124
+ : querySlice(lines, query, maxLines, scan.complete, scannedLines.partialTail)
125
+ const total = scan.complete ? String(lines.length) : `at least ${String(lines.length)}`
126
+ const header = [
127
+ `source: ${args.ref}`,
128
+ `tool_call_id: ${event.data.message.source.callId}`,
129
+ `status: ${event.data.message.content[0].isError === true ? 'error' : 'completed'}`,
130
+ `lines: ${String(selected.start)}-${String(selected.end)} of ${total}`,
131
+ scan.complete ? '' : 'note: source scan limit reached; later lines were not inspected',
132
+ selected.partialLine === undefined
133
+ ? ''
134
+ : `note: line ${String(selected.partialLine)} is a partial prefix ending at the source scan limit`,
135
+ selected.omitted
136
+ ? query === undefined || query === ''
137
+ ? 'note: additional source lines were omitted'
138
+ : 'note: additional matching or neighboring lines were omitted'
139
+ : '',
140
+ '--- original tool result ---',
141
+ ].filter(Boolean).join('\n')
142
+ const output = `${header}\n${selected.text}`
143
+ return Promise.resolve(boundCodePoints(output, maxChars))
144
+ },
145
+ }))
146
+ }
147
+
148
+ function recoverTailTrim(
149
+ session: Parameters<typeof validatePublishedTailTrim>[0],
150
+ ref: string,
151
+ manifestSeq: number,
152
+ query: string | undefined,
153
+ startLine: number | undefined,
154
+ requestedMaxLines: number | undefined,
155
+ bounds: { readonly maxChars: number; readonly maxScanChars: number; readonly maxQueryChars: number },
156
+ ): string {
157
+ const published = validatePublishedTailTrim(session, manifestSeq)
158
+ if (published === null || published.ref !== ref) {
159
+ throw new Error('context_compression_retrieve: ref is not a valid published TailTrim group')
160
+ }
161
+ if (query !== undefined && exceedsCodePointLimit(query, bounds.maxQueryChars)) {
162
+ throw new Error(
163
+ `context_compression_retrieve: query must be at most ${String(bounds.maxQueryChars)} Unicode code points`,
164
+ )
165
+ }
166
+ const fixedHeader = [
167
+ `source: ${ref}`,
168
+ 'kind: tailtrim-group',
169
+ `records: ${String(published.roots.length)}`,
170
+ '--- original tool group (jsonl) ---',
171
+ ].join('\n')
172
+ const scanBudget = Math.max(0, bounds.maxScanChars - codePointLength(`${fixedHeader}\n`))
173
+ const scan = consumeChunks(renderGroupRecordChunks(published.roots), scanBudget)
174
+ const scannedLines = splitScannedLines(scan)
175
+ const maxLines = resolveMaxLines(requestedMaxLines)
176
+ const selected = query === undefined || query === ''
177
+ ? directSlice(
178
+ scannedLines.lines,
179
+ startLine ?? 1,
180
+ maxLines,
181
+ scan.complete,
182
+ scannedLines.partialTail,
183
+ )
184
+ : querySlice(
185
+ scannedLines.lines,
186
+ query,
187
+ maxLines,
188
+ scan.complete,
189
+ scannedLines.partialTail,
190
+ )
191
+ const header = [
192
+ fixedHeader.split('\n').slice(0, 3).join('\n'),
193
+ scan.complete ? '' : 'note: source scan limit reached; later records were not inspected',
194
+ selected.omitted ? 'note: additional group records were omitted' : '',
195
+ '--- original tool group (jsonl) ---',
196
+ ].filter(Boolean).join('\n')
197
+ return boundCodePoints(`${header}\n${selected.text}`, bounds.maxChars)
198
+ }
199
+
200
+ interface ScanResult {
201
+ readonly text: string
202
+ readonly complete: boolean
203
+ }
204
+
205
+ interface ScannedLines {
206
+ readonly lines: readonly string[]
207
+ readonly partialTail: boolean
208
+ }
209
+
210
+ interface Selection {
211
+ readonly text: string
212
+ readonly start: number
213
+ readonly end: number
214
+ readonly omitted: boolean
215
+ readonly partialLine?: number
216
+ }
217
+
218
+ function resolvePositiveInteger(name: string, value: number | undefined, fallback: number): number {
219
+ const resolved = value ?? fallback
220
+ if (!Number.isSafeInteger(resolved) || resolved <= 0) {
221
+ throw new TypeError(`tool-context-retrieve: ${name} must be a positive safe integer`)
222
+ }
223
+ return resolved
224
+ }
225
+
226
+ function resolveMaxLines(value: number | undefined): number {
227
+ const resolved = value ?? 200
228
+ if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > MAX_LINES) {
229
+ throw new Error(`context_compression_retrieve: max_lines must be an integer from 1 to ${String(MAX_LINES)}`)
230
+ }
231
+ return resolved
232
+ }
233
+
234
+ function scanBlocks(blocks: readonly ContentBlock[], maxChars: number): ScanResult {
235
+ return consumeChunks(renderBlockChunks(blocks), maxChars)
236
+ }
237
+
238
+ function* renderBlockChunks(blocks: readonly ContentBlock[]): Generator<string> {
239
+ let first = true
240
+ for (const block of blocks) {
241
+ if (!first) yield '\n'
242
+ first = false
243
+ if (block.type === 'text') yield block.text
244
+ else yield* jsonTokens(block)
245
+ }
246
+ }
247
+
248
+ function* renderGroupRecordChunks(roots: PublishedTailTrim['roots']): Generator<string> {
249
+ let first = true
250
+ for (const root of roots) {
251
+ if (!first) yield '\n'
252
+ first = false
253
+ const message = root.data.message
254
+ yield* jsonTokens({
255
+ seq: root.seq,
256
+ type: root.type,
257
+ message: {
258
+ id: message.id,
259
+ role: message.role,
260
+ content: message.content,
261
+ source: message.source,
262
+ },
263
+ })
264
+ }
265
+ }
266
+
267
+ function* jsonTokens(value: unknown): Generator<string> {
268
+ if (value === null) {
269
+ yield 'null'
270
+ return
271
+ }
272
+ switch (typeof value) {
273
+ case 'string':
274
+ yield '"'
275
+ for (const point of value) {
276
+ const quoted = jsonScalar(point)
277
+ yield quoted.slice(1, -1)
278
+ }
279
+ yield '"'
280
+ return
281
+ case 'number':
282
+ case 'boolean':
283
+ yield jsonScalar(value)
284
+ return
285
+ case 'object': {
286
+ if (Array.isArray(value)) {
287
+ yield '['
288
+ for (let index = 0; index < value.length; index++) {
289
+ if (index > 0) yield ','
290
+ yield* jsonTokens(value[index])
291
+ }
292
+ yield ']'
293
+ return
294
+ }
295
+ yield '{'
296
+ let first = true
297
+ for (const key in value) {
298
+ if (!Object.hasOwn(value, key)) continue
299
+ if (!first) yield ','
300
+ first = false
301
+ yield* jsonTokens(key)
302
+ yield ':'
303
+ yield* jsonTokens((value as Record<string, unknown>)[key])
304
+ }
305
+ yield '}'
306
+ return
307
+ }
308
+ default:
309
+ throw new TypeError('context_compression_retrieve: source content is not JSON-serializable')
310
+ }
311
+ }
312
+
313
+ function jsonScalar(value: string | number | boolean): string {
314
+ return JSON.stringify(value)
315
+ }
316
+
317
+ function consumeChunks(chunks: Iterable<string>, maxChars: number): ScanResult {
318
+ const output: string[] = []
319
+ let remaining = maxChars
320
+ for (const chunk of chunks) {
321
+ const prefix = codePointPrefix(chunk, remaining)
322
+ output.push(prefix.text)
323
+ remaining -= prefix.count
324
+ if (!prefix.complete) return { text: output.join(''), complete: false }
325
+ }
326
+ return { text: output.join(''), complete: true }
327
+ }
328
+
329
+ function splitScannedLines(scan: ScanResult): ScannedLines {
330
+ const lines = scan.text.split('\n')
331
+ const partialTail = !scan.complete && !scan.text.endsWith('\n')
332
+ if (scan.text.endsWith('\n')) lines.pop()
333
+ return { lines, partialTail }
334
+ }
335
+
336
+ function directSlice(
337
+ lines: readonly string[],
338
+ startLine: number,
339
+ maxLines: number,
340
+ scanComplete: boolean,
341
+ partialTail: boolean,
342
+ ): Selection {
343
+ if (!Number.isSafeInteger(startLine) || startLine < 1) {
344
+ throw new Error('context_compression_retrieve: start_line must be a positive safe integer')
345
+ }
346
+ if (startLine > lines.length) {
347
+ const reason = scanComplete ? 'outside the source line range' : 'beyond the source scan limit'
348
+ throw new Error(`context_compression_retrieve: start_line ${String(startLine)} is ${reason}`)
349
+ }
350
+ const startIndex = startLine - 1
351
+ const selected = lines.slice(startIndex, startIndex + maxLines)
352
+ return {
353
+ text: selected.join('\n'),
354
+ start: startIndex + 1,
355
+ end: startIndex + selected.length,
356
+ omitted: startIndex > 0 || startIndex + selected.length < lines.length || !scanComplete,
357
+ ...partialTail && startIndex + selected.length === lines.length
358
+ ? { partialLine: lines.length }
359
+ : {},
360
+ }
361
+ }
362
+
363
+ function querySlice(
364
+ lines: readonly string[],
365
+ query: string,
366
+ maxLines: number,
367
+ scanComplete: boolean,
368
+ partialTail: boolean,
369
+ ): Selection {
370
+ const needle = query.toLowerCase()
371
+ const chosen = new Set<number>()
372
+ let matched = false
373
+ let omitted = !scanComplete
374
+ for (let index = 0; index < lines.length; index++) {
375
+ const line = lines[index]
376
+ if (line === undefined || !line.toLowerCase().includes(needle)) continue
377
+ matched = true
378
+ for (let row = Math.max(0, index - 2); row <= Math.min(lines.length - 1, index + 2); row++) {
379
+ if (chosen.has(row)) continue
380
+ if (chosen.size >= maxLines) {
381
+ omitted = true
382
+ continue
383
+ }
384
+ chosen.add(row)
385
+ }
386
+ }
387
+ if (!matched) {
388
+ return {
389
+ text: scanComplete ? '[no matches]' : '[no matches within source scan limit]',
390
+ start: 0,
391
+ end: 0,
392
+ omitted,
393
+ }
394
+ }
395
+ const ordered = [...chosen].sort((a, b) => a - b)
396
+ const rendered: string[] = []
397
+ let previous = -2
398
+ let start = 0
399
+ let end = 0
400
+ for (const index of ordered) {
401
+ const line = lines[index]
402
+ if (line === undefined) continue
403
+ if (index > previous + 1) rendered.push('...')
404
+ rendered.push(`${String(index + 1)}: ${line}`)
405
+ if (start === 0) start = index + 1
406
+ end = index + 1
407
+ previous = index
408
+ }
409
+ return {
410
+ text: rendered.join('\n'),
411
+ start,
412
+ end,
413
+ omitted,
414
+ ...partialTail && ordered.includes(lines.length - 1)
415
+ ? { partialLine: lines.length }
416
+ : {},
417
+ }
418
+ }
419
+
420
+ function boundCodePoints(text: string, maxChars: number): string {
421
+ const bounded = codePointPrefix(text, maxChars)
422
+ if (bounded.complete) return text
423
+ const marker = codePointPrefix(TRUNCATION_MARKER, maxChars)
424
+ if (!marker.complete) return marker.text
425
+ const body = codePointPrefix(text, maxChars - marker.count)
426
+ return body.text + marker.text
427
+ }
428
+
429
+ function codePointPrefix(text: string, maxChars: number): {
430
+ readonly text: string
431
+ readonly count: number
432
+ readonly complete: boolean
433
+ } {
434
+ const output: string[] = []
435
+ let count = 0
436
+ for (const point of text) {
437
+ if (count >= maxChars) return { text: output.join(''), count, complete: false }
438
+ output.push(point)
439
+ count++
440
+ }
441
+ return { text: output.join(''), count, complete: true }
442
+ }
443
+
444
+ function exceedsCodePointLimit(text: string, limit: number): boolean {
445
+ let count = 0
446
+ for (const _point of text) {
447
+ count++
448
+ if (count > limit) return true
449
+ }
450
+ return false
451
+ }
452
+
453
+ function codePointLength(text: string): number {
454
+ let count = 0
455
+ for (const _point of text) count++
456
+ return count
457
+ }