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