dsh-context-compression-improved 0.10.1 → 0.10.2

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 (262) hide show
  1. package/README.md +15 -110
  2. package/README.zh.md +14 -104
  3. package/THIRD_PARTY_NOTICES.md +25 -7
  4. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +1 -1
  5. package/{packages/selector/lib → lib}/client.js +73 -12
  6. package/package.json +125 -112
  7. package/screenshots.json +3 -6
  8. package/.agents/plans/improve/checklist.md +0 -32
  9. package/.agents/plans/improve/findings.md +0 -102
  10. package/.agents/plans/improve/spec.md +0 -53
  11. package/.agents/plans/improve/tasks.md +0 -70
  12. package/.gitattributes +0 -2
  13. package/.githooks/pre-push +0 -37
  14. package/.github/workflows/ci.yml +0 -39
  15. package/CHANGELOG.de.md +0 -580
  16. package/CHANGELOG.es.md +0 -588
  17. package/CHANGELOG.fr.md +0 -576
  18. package/CHANGELOG.it.md +0 -577
  19. package/CHANGELOG.ja.md +0 -261
  20. package/CHANGELOG.ko.md +0 -254
  21. package/CHANGELOG.md +0 -544
  22. package/CHANGELOG.ru.md +0 -554
  23. package/CHANGELOG.zh.md +0 -238
  24. package/CONTRIBUTING.md +0 -22
  25. package/README.de.md +0 -96
  26. package/README.es.md +0 -96
  27. package/README.fr.md +0 -96
  28. package/README.it.md +0 -96
  29. package/README.ja.md +0 -102
  30. package/README.ko.md +0 -102
  31. package/README.ru.md +0 -96
  32. package/SECURITY.md +0 -18
  33. package/assets/board.png +0 -0
  34. package/assets/context.png +0 -0
  35. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  36. package/docs/assets/context-compression-selector-settings.png +0 -0
  37. package/docs/compat-0.1.5-report.md +0 -77
  38. package/docs/installation.de.md +0 -104
  39. package/docs/installation.es.md +0 -104
  40. package/docs/installation.fr.md +0 -104
  41. package/docs/installation.it.md +0 -104
  42. package/docs/installation.ja.md +0 -78
  43. package/docs/installation.ko.md +0 -78
  44. package/docs/installation.md +0 -103
  45. package/docs/installation.ru.md +0 -104
  46. package/docs/installation.zh.md +0 -100
  47. package/docs/repair-log.md +0 -657
  48. package/eslint.config.js +0 -30
  49. package/packages/selector/LICENSE +0 -21
  50. package/packages/selector/README.md +0 -26
  51. package/packages/selector/README.zh.md +0 -24
  52. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  53. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  54. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  55. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  56. package/packages/selector/lib/style.css +0 -350
  57. package/packages/selector/package.json +0 -178
  58. package/packages/selector/screenshots.json +0 -3
  59. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
  60. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  61. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
  62. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  63. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  64. package/packages/selector/src/client/bridge-scope.ts +0 -125
  65. package/packages/selector/src/client/decode.ts +0 -57
  66. package/packages/selector/src/client/index.ts +0 -424
  67. package/packages/selector/src/client/locales/de.ts +0 -158
  68. package/packages/selector/src/client/locales/es.ts +0 -158
  69. package/packages/selector/src/client/locales/fr.ts +0 -158
  70. package/packages/selector/src/client/locales/it.ts +0 -158
  71. package/packages/selector/src/client/locales/ja.ts +0 -158
  72. package/packages/selector/src/client/locales/ko.ts +0 -158
  73. package/packages/selector/src/client/locales/ru.ts +0 -158
  74. package/packages/selector/src/client/locales.ts +0 -316
  75. package/packages/selector/src/client/monitor-fab.ts +0 -419
  76. package/packages/selector/src/client/preset-options.ts +0 -88
  77. package/packages/selector/src/client/savings-card.tsx +0 -269
  78. package/packages/selector/src/client/scope-face.ts +0 -24
  79. package/packages/selector/src/client/settings-section.tsx +0 -140
  80. package/packages/selector/src/compat/host-generation.ts +0 -96
  81. package/packages/selector/src/compat/llm-messages.ts +0 -50
  82. package/packages/selector/src/compat/settings-lease.ts +0 -108
  83. package/packages/selector/src/compat/tool-result.ts +0 -91
  84. package/packages/selector/src/css-modules.d.ts +0 -6
  85. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  86. package/packages/selector/src/estimator-catalog.ts +0 -104
  87. package/packages/selector/src/index.ts +0 -890
  88. package/packages/selector/src/invariant.ts +0 -113
  89. package/packages/selector/src/preset-overlay.ts +0 -749
  90. package/packages/selector/src/profiles.ts +0 -431
  91. package/packages/selector/src/pruner/content.ts +0 -198
  92. package/packages/selector/src/pruner/session.ts +0 -97
  93. package/packages/selector/src/pruner/state.ts +0 -61
  94. package/packages/selector/src/pruner/tuning.ts +0 -23
  95. package/packages/selector/src/pruner/types.ts +0 -78
  96. package/packages/selector/src/pruner.ts +0 -2914
  97. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  98. package/packages/selector/src/runtime/audit.ts +0 -320
  99. package/packages/selector/src/runtime/config.ts +0 -756
  100. package/packages/selector/src/runtime/custom-policy.ts +0 -278
  101. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  102. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  103. package/packages/selector/src/runtime/display-prefs.ts +0 -98
  104. package/packages/selector/src/runtime/measurement.ts +0 -444
  105. package/packages/selector/src/runtime/monitor.ts +0 -310
  106. package/packages/selector/src/runtime/panel-command.ts +0 -213
  107. package/packages/selector/src/runtime/reducers.ts +0 -1754
  108. package/packages/selector/src/runtime/retrieve.ts +0 -503
  109. package/packages/selector/src/runtime/savings-integral.ts +0 -117
  110. package/packages/selector/src/runtime/savings-projection.ts +0 -229
  111. package/packages/selector/src/runtime/savings-verify.ts +0 -446
  112. package/packages/selector/src/runtime/savings.ts +0 -526
  113. package/packages/selector/src/runtime/session-events.ts +0 -30
  114. package/packages/selector/src/runtime/session-file-decode.ts +0 -523
  115. package/packages/selector/src/runtime/stats-backfill.ts +0 -541
  116. package/packages/selector/src/runtime/stats-db.ts +0 -492
  117. package/packages/selector/src/runtime/stats-schema.ts +0 -123
  118. package/packages/selector/src/runtime/stats-sync.ts +0 -307
  119. package/packages/selector/src/runtime/summary-command.ts +0 -127
  120. package/packages/selector/src/runtime/tail-trim.ts +0 -176
  121. package/packages/selector/src/runtime/token-count.ts +0 -72
  122. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  123. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  124. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  125. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  126. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
  127. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  128. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  129. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  130. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  131. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  132. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
  133. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  134. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  135. package/packages/selector/src/runtime/toolclass.ts +0 -103
  136. package/packages/selector/src/runtime/types.ts +0 -365
  137. package/packages/selector/src/runtime/value.ts +0 -48
  138. package/packages/selector/src/settings-bridge.ts +0 -175
  139. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  140. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  141. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  142. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  143. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  144. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  145. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  146. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  147. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  148. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -202
  149. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  150. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  154. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  155. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  156. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -220
  157. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  158. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  159. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  160. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  161. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
  162. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  163. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  164. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  165. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  166. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  167. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  168. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  169. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  170. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  171. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  172. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  173. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  174. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  175. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +0 -46
  176. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  177. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  178. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  179. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  180. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  181. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  182. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  183. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  184. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  185. package/packages/selector/tests/runtime/monitor.spec.ts +0 -354
  186. package/packages/selector/tests/runtime/panel-command.spec.ts +0 -101
  187. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  188. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2781
  189. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  190. package/packages/selector/tests/runtime/savings-accounting.spec.ts +0 -291
  191. package/packages/selector/tests/runtime/savings-integral.spec.ts +0 -169
  192. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  193. package/packages/selector/tests/runtime/savings-verify.spec.ts +0 -226
  194. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  195. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  196. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  197. package/packages/selector/tests/runtime/session-file-decode.spec.ts +0 -281
  198. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  199. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  200. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +0 -167
  201. package/packages/selector/tests/runtime/stats-backfill.spec.ts +0 -348
  202. package/packages/selector/tests/runtime/stats-db.spec.ts +0 -361
  203. package/packages/selector/tests/runtime/stats-privacy.spec.ts +0 -55
  204. package/packages/selector/tests/runtime/stats-sync.spec.ts +0 -278
  205. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  206. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  207. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  208. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  209. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  210. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  211. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  212. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
  213. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  214. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  215. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  216. package/packages/selector/tests/savings-sessions.client.spec.tsx +0 -140
  217. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  218. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  219. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  220. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  221. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  222. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  223. package/packages/selector/tsconfig.json +0 -11
  224. package/packages/selector/tsdown.client.config.ts +0 -102
  225. package/packages/selector/tsdown.config.ts +0 -20
  226. package/pnpm-workspace.yaml +0 -76
  227. package/scripts/capture-profile-baseline.mjs +0 -42
  228. package/scripts/cell-browser-e2e.mjs +0 -354
  229. package/scripts/generate-tokenizer-fixtures.py +0 -81
  230. package/scripts/generate-vision-fixtures.py +0 -208
  231. package/scripts/hosts.mjs +0 -78
  232. package/scripts/packed-components-smoke.mjs +0 -763
  233. package/scripts/packed-install-e2e.mjs +0 -1346
  234. package/scripts/sync-hosts.mjs +0 -174
  235. package/scripts/toolclass-corpus-replay.mjs +0 -281
  236. package/scripts/verify-release.mjs +0 -338
  237. package/tests/TEST_INVENTORY.md +0 -41
  238. package/tsconfig.base.json +0 -18
  239. package/tsconfig.json +0 -7
  240. package/tsconfig.tests.json +0 -15
  241. package/vitest.built.config.ts +0 -9
  242. package/vitest.config.ts +0 -54
  243. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  244. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  245. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  246. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  247. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  248. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  249. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  250. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  251. /package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +0 -0
  252. /package/{packages/selector/lib → lib}/client.d.ts +0 -0
  253. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  254. /package/{packages/selector/lib → lib}/index.js +0 -0
  255. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  256. /package/{packages/selector/lib → lib}/invariant.js +0 -0
  257. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
  258. /package/{packages/selector/lib → lib}/pruner.d.ts +0 -0
  259. /package/{packages/selector/lib → lib}/pruner.js +0 -0
  260. /package/{packages/selector/lib → lib}/savings-integral.js +0 -0
  261. /package/{packages/selector/lib → lib}/tail-trim.js +0 -0
  262. /package/{packages/selector/lib → lib}/tool-result.js +0 -0
@@ -1,503 +0,0 @@
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
- import { claimOffset } from './stats-sync.ts'
24
- import { viewToolResult } from '../compat/tool-result.ts'
25
-
26
- export const name = 'context-compression-retrieve'
27
- export const inject = ['tools', 'systemPrompt']
28
-
29
- /** Maximum text returned by one recovery call. */
30
- export interface Config {
31
- /** Hard response bound in Unicode code points. Defaults to 12000. */
32
- maxChars?: number
33
- /** Maximum source text inspected by one call. Defaults to 250000. */
34
- maxScanChars?: number
35
- /** Maximum query length in Unicode code points. Defaults to 256. */
36
- maxQueryChars?: number
37
- }
38
-
39
- /** Loader schema for the recovery tool's bounded runtime configuration. */
40
- export const Config: z<Config> = z.object({
41
- maxChars: z.number().step(1).min(1).default(12_000),
42
- maxScanChars: z.number().step(1).min(1).default(250_000),
43
- maxQueryChars: z.number().step(1).min(1).default(256),
44
- })
45
-
46
- const REF_PATTERN = /^session:\/\/([^/]+)\/event\/(\d+)$/
47
- const MAX_LINES = 1_000
48
- const DEFAULT_MAX_CHARS = 12_000
49
- const DEFAULT_MAX_SCAN_CHARS = 250_000
50
- const DEFAULT_MAX_QUERY_CHARS = 256
51
- const TRUNCATION_MARKER = '\n[context_compression_retrieve output truncated; reported lines describe the selected source range]\n'
52
- const PROMPT = 'When a compacted tool result contains a session://<session-id>/event/<seq> reference, '
53
- + 'or TailTrim contains a session://<session-id>/tailtrim/<seq> reference, use context_compression_retrieve with that exact ref '
54
- + 'and a narrow line range or query if the omitted evidence is necessary. '
55
- + 'Prefer a query or a tight start_line/max_lines over re-reading the whole result: every recovery re-enters the context and is charged against the savings, so a targeted slice keeps the rest of the reduction. '
56
- + 'The returned event content comes from the append-only session log, which is the source of truth.'
57
-
58
- const OUTPUT = {
59
- schema: { type: 'string' as const },
60
- render: (_args: unknown, value: string) => [{ type: 'text' as const, text: value }],
61
- }
62
-
63
- /**
64
- * Register the current-session recovery tool and its stable guidance.
65
- *
66
- * @param ctx Plugin context providing the tool registry and system prompt.
67
- * @param config Optional response, scan, and query bounds.
68
- */
69
- export function installContextCompressionRetrieve(ctx: Context, config: Config = {}): void {
70
- const maxChars = resolvePositiveInteger('maxChars', config.maxChars, DEFAULT_MAX_CHARS)
71
- const maxScanChars = resolvePositiveInteger(
72
- 'maxScanChars', config.maxScanChars, DEFAULT_MAX_SCAN_CHARS,
73
- )
74
- const maxQueryChars = resolvePositiveInteger(
75
- 'maxQueryChars', config.maxQueryChars, DEFAULT_MAX_QUERY_CHARS,
76
- )
77
- ctx.systemPrompt.section({ name: 'tool:context-compression-retrieve', order: 114, text: PROMPT })
78
- ctx.tools.register(defineTool({
79
- name: 'context_compression_retrieve',
80
- description: 'Recover exact content from one compacted tool result or TailTrim group using its current-session session:// reference.',
81
- parameters: {
82
- ref: { type: 'string', required: true, description: 'Exact session://<current-session-id>/event/<seq> or /tailtrim/<seq> reference from a placeholder.' },
83
- query: { type: 'string', description: 'Optional case-insensitive text to search for inside the original result.' },
84
- start_line: { type: 'integer', description: 'Optional 1-based first line for a direct slice. Defaults to 1.' },
85
- max_lines: { type: 'integer', description: 'Maximum lines to return. Defaults to 200; maximum 1000.' },
86
- },
87
- output: OUTPUT,
88
- isConcurrencySafe: () => true,
89
- execute(args, exec) {
90
- if (exec.agent === undefined) throw new Error('context_compression_retrieve requires an agent session')
91
- const match = REF_PATTERN.exec(args.ref)
92
- const tailTrimRef = parseTailTrimRef(args.ref)
93
- if (match === null && tailTrimRef === null) {
94
- throw new Error('context_compression_retrieve: ref must be session://<session-id>/(event|tailtrim)/<seq>')
95
- }
96
- const sessionId = match?.[1] ?? tailTrimRef?.sessionId
97
- // 身份键一律用 session.id(与 pruner 落账/占位符 sourceRef 同键);旧版这里
98
- // 用 exec.agent.id,两键不一致时抵消会记到另一本账上。
99
- if (sessionId !== String(exec.agent.session.id)) {
100
- throw new Error('context_compression_retrieve: a compression reference may only read the caller\'s current session')
101
- }
102
- if (tailTrimRef !== null) {
103
- const sessionId = String(exec.agent.session.id)
104
- return Promise.resolve(recoverTailTrim(
105
- exec.agent.session,
106
- args.ref,
107
- tailTrimRef.manifestSeq,
108
- args.query,
109
- args.start_line,
110
- args.max_lines,
111
- { maxChars, maxScanChars, maxQueryChars },
112
- )).then((text: string) => {
113
- // 节省统计:回读内容重新进入上下文 = 对该组原声称节省的抵消。
114
- // 同 basis(chars/4 估算口径;retrieve 不持有精确 counter 身份,
115
- // 分列不混算)经 foldRecall 折进源条目翻负;跨基退化带 sourceSeq 的收敛 offset。
116
- const offsetTokens = Math.ceil(codePointLength(text) / 4)
117
- getSavingsLedger().foldRecall(sessionId, tailTrimRef.manifestSeq, offsetTokens, 'characters', {
118
- component: 'tailtrim-retrieve',
119
- note: `tailtrim/${tailTrimRef.manifestSeq} 回读`,
120
- })
121
- // T6 接线:持久 offset claim(流水审计层);幂等键含 manifestSeq,
122
- // 同源反复召回首次入账、重放去重(定键口径见 stats-sync 头注)。
123
- claimOffset({
124
- sessionId,
125
- component: 'tailtrim-retrieve',
126
- tokens: offsetTokens,
127
- basis: 'characters',
128
- sourceSeq: tailTrimRef.manifestSeq,
129
- })
130
- return text
131
- })
132
- }
133
- const seq = Number(match?.[2])
134
- const event = sessionEvents(exec.agent.session)[seq]
135
- if (event?.type !== 'tool/result') {
136
- throw new Error(`context_compression_retrieve: event ${String(seq)} is not a tool/result in the current session`)
137
- }
138
- const maxLines = resolveMaxLines(args.max_lines)
139
- // Generation-gated triple view: content blocks / error flag / call id
140
- // move together across the 0.1.x envelope and the flat 0.2.0 message.
141
- const resultView = viewToolResult(event.data.message)
142
- const scan = scanBlocks(resultView.blocks as ContentBlock[], maxScanChars)
143
- const scannedLines = splitScannedLines(scan)
144
- const lines = scannedLines.lines
145
- const query = args.query
146
- if (query !== undefined && exceedsCodePointLimit(query, maxQueryChars)) {
147
- throw new Error(
148
- `context_compression_retrieve: query must be at most ${String(maxQueryChars)} Unicode code points`,
149
- )
150
- }
151
- const selected = query === undefined || query === ''
152
- ? directSlice(lines, args.start_line ?? 1, maxLines, scan.complete, scannedLines.partialTail)
153
- : querySlice(lines, query, maxLines, scan.complete, scannedLines.partialTail)
154
- const total = scan.complete ? String(lines.length) : `at least ${String(lines.length)}`
155
- const header = [
156
- `source: ${args.ref}`,
157
- `tool_call_id: ${resultView.callId}`,
158
- `status: ${resultView.isError ? 'error' : 'completed'}`,
159
- `lines: ${String(selected.start)}-${String(selected.end)} of ${total}`,
160
- scan.complete ? '' : 'note: source scan limit reached; later lines were not inspected',
161
- selected.partialLine === undefined
162
- ? ''
163
- : `note: line ${String(selected.partialLine)} is a partial prefix ending at the source scan limit`,
164
- selected.omitted
165
- ? query === undefined || query === ''
166
- ? 'note: additional source lines were omitted'
167
- : 'note: additional matching or neighboring lines were omitted'
168
- : '',
169
- '--- original tool result ---',
170
- ].filter(Boolean).join('\n')
171
- const output = `${header}\n${selected.text}`
172
- const bounded = boundCodePoints(output, maxChars)
173
- // 节省统计:retrieve 产物重新进入上下文 = 抵消(chars/4 估算口径);
174
- // 同 basis 折进源条目翻负,R = boundCodePoints 后的实测值,跨基退化为
175
- // 带 sourceSeq(event/N)的收敛 offset。落账键用 session.id 与 pruner 统一。
176
- const offsetTokens = Math.ceil(codePointLength(bounded) / 4)
177
- getSavingsLedger().foldRecall(String(exec.agent.session.id), seq, offsetTokens, 'characters', {
178
- component: 'retrieve',
179
- note: `event/${String(seq)} 回读`,
180
- })
181
- // T6 接线:持久 offset claim;幂等键 (session_id, 源事件绝对 seq, …)。
182
- claimOffset({
183
- sessionId: String(exec.agent.session.id),
184
- component: 'retrieve',
185
- tokens: offsetTokens,
186
- basis: 'characters',
187
- sourceSeq: seq,
188
- })
189
- return Promise.resolve(bounded)
190
- },
191
- }))
192
- }
193
-
194
- function recoverTailTrim(
195
- session: Parameters<typeof validatePublishedTailTrim>[0],
196
- ref: string,
197
- manifestSeq: number,
198
- query: string | undefined,
199
- startLine: number | undefined,
200
- requestedMaxLines: number | undefined,
201
- bounds: { readonly maxChars: number; readonly maxScanChars: number; readonly maxQueryChars: number },
202
- ): string {
203
- const published = validatePublishedTailTrim(session, manifestSeq)
204
- if (published === null || published.ref !== ref) {
205
- throw new Error('context_compression_retrieve: ref is not a valid published TailTrim group')
206
- }
207
- if (query !== undefined && exceedsCodePointLimit(query, bounds.maxQueryChars)) {
208
- throw new Error(
209
- `context_compression_retrieve: query must be at most ${String(bounds.maxQueryChars)} Unicode code points`,
210
- )
211
- }
212
- const fixedHeader = [
213
- `source: ${ref}`,
214
- 'kind: tailtrim-group',
215
- `records: ${String(published.roots.length)}`,
216
- '--- original tool group (jsonl) ---',
217
- ].join('\n')
218
- const scanBudget = Math.max(0, bounds.maxScanChars - codePointLength(`${fixedHeader}\n`))
219
- const scan = consumeChunks(renderGroupRecordChunks(published.roots), scanBudget)
220
- const scannedLines = splitScannedLines(scan)
221
- const maxLines = resolveMaxLines(requestedMaxLines)
222
- const selected = query === undefined || query === ''
223
- ? directSlice(
224
- scannedLines.lines,
225
- startLine ?? 1,
226
- maxLines,
227
- scan.complete,
228
- scannedLines.partialTail,
229
- )
230
- : querySlice(
231
- scannedLines.lines,
232
- query,
233
- maxLines,
234
- scan.complete,
235
- scannedLines.partialTail,
236
- )
237
- const header = [
238
- fixedHeader.split('\n').slice(0, 3).join('\n'),
239
- scan.complete ? '' : 'note: source scan limit reached; later records were not inspected',
240
- selected.omitted ? 'note: additional group records were omitted' : '',
241
- '--- original tool group (jsonl) ---',
242
- ].filter(Boolean).join('\n')
243
- return boundCodePoints(`${header}\n${selected.text}`, bounds.maxChars)
244
- }
245
-
246
- interface ScanResult {
247
- readonly text: string
248
- readonly complete: boolean
249
- }
250
-
251
- interface ScannedLines {
252
- readonly lines: readonly string[]
253
- readonly partialTail: boolean
254
- }
255
-
256
- interface Selection {
257
- readonly text: string
258
- readonly start: number
259
- readonly end: number
260
- readonly omitted: boolean
261
- readonly partialLine?: number
262
- }
263
-
264
- function resolvePositiveInteger(name: string, value: number | undefined, fallback: number): number {
265
- const resolved = value ?? fallback
266
- if (!Number.isSafeInteger(resolved) || resolved <= 0) {
267
- throw new TypeError(`tool-context-retrieve: ${name} must be a positive safe integer`)
268
- }
269
- return resolved
270
- }
271
-
272
- function resolveMaxLines(value: number | undefined): number {
273
- const resolved = value ?? 200
274
- if (!Number.isSafeInteger(resolved) || resolved < 1 || resolved > MAX_LINES) {
275
- throw new Error(`context_compression_retrieve: max_lines must be an integer from 1 to ${String(MAX_LINES)}`)
276
- }
277
- return resolved
278
- }
279
-
280
- function scanBlocks(blocks: readonly ContentBlock[], maxChars: number): ScanResult {
281
- return consumeChunks(renderBlockChunks(blocks), maxChars)
282
- }
283
-
284
- function* renderBlockChunks(blocks: readonly ContentBlock[]): Generator<string> {
285
- let first = true
286
- for (const block of blocks) {
287
- if (!first) yield '\n'
288
- first = false
289
- if (block.type === 'text') yield block.text
290
- else yield* jsonTokens(block)
291
- }
292
- }
293
-
294
- function* renderGroupRecordChunks(roots: PublishedTailTrim['roots']): Generator<string> {
295
- let first = true
296
- for (const root of roots) {
297
- if (!first) yield '\n'
298
- first = false
299
- const message = root.data.message
300
- yield* jsonTokens({
301
- seq: root.seq,
302
- type: root.type,
303
- message: {
304
- id: message.id,
305
- role: message.role,
306
- content: message.content,
307
- source: message.source,
308
- },
309
- })
310
- }
311
- }
312
-
313
- function* jsonTokens(value: unknown): Generator<string> {
314
- if (value === null) {
315
- yield 'null'
316
- return
317
- }
318
- switch (typeof value) {
319
- case 'string':
320
- yield '"'
321
- for (const point of value) {
322
- const quoted = jsonScalar(point)
323
- yield quoted.slice(1, -1)
324
- }
325
- yield '"'
326
- return
327
- case 'number':
328
- case 'boolean':
329
- yield jsonScalar(value)
330
- return
331
- case 'object': {
332
- if (Array.isArray(value)) {
333
- yield '['
334
- for (let index = 0; index < value.length; index++) {
335
- if (index > 0) yield ','
336
- yield* jsonTokens(value[index])
337
- }
338
- yield ']'
339
- return
340
- }
341
- yield '{'
342
- let first = true
343
- for (const key in value) {
344
- if (!Object.hasOwn(value, key)) continue
345
- if (!first) yield ','
346
- first = false
347
- yield* jsonTokens(key)
348
- yield ':'
349
- yield* jsonTokens((value as Record<string, unknown>)[key])
350
- }
351
- yield '}'
352
- return
353
- }
354
- default:
355
- throw new TypeError('context_compression_retrieve: source content is not JSON-serializable')
356
- }
357
- }
358
-
359
- function jsonScalar(value: string | number | boolean): string {
360
- return JSON.stringify(value)
361
- }
362
-
363
- function consumeChunks(chunks: Iterable<string>, maxChars: number): ScanResult {
364
- const output: string[] = []
365
- let remaining = maxChars
366
- for (const chunk of chunks) {
367
- const prefix = codePointPrefix(chunk, remaining)
368
- output.push(prefix.text)
369
- remaining -= prefix.count
370
- if (!prefix.complete) return { text: output.join(''), complete: false }
371
- }
372
- return { text: output.join(''), complete: true }
373
- }
374
-
375
- function splitScannedLines(scan: ScanResult): ScannedLines {
376
- const lines = scan.text.split('\n')
377
- const partialTail = !scan.complete && !scan.text.endsWith('\n')
378
- if (scan.text.endsWith('\n')) lines.pop()
379
- return { lines, partialTail }
380
- }
381
-
382
- function directSlice(
383
- lines: readonly string[],
384
- startLine: number,
385
- maxLines: number,
386
- scanComplete: boolean,
387
- partialTail: boolean,
388
- ): Selection {
389
- if (!Number.isSafeInteger(startLine) || startLine < 1) {
390
- throw new Error('context_compression_retrieve: start_line must be a positive safe integer')
391
- }
392
- if (startLine > lines.length) {
393
- const reason = scanComplete ? 'outside the source line range' : 'beyond the source scan limit'
394
- throw new Error(`context_compression_retrieve: start_line ${String(startLine)} is ${reason}`)
395
- }
396
- const startIndex = startLine - 1
397
- const selected = lines.slice(startIndex, startIndex + maxLines)
398
- return {
399
- text: selected.join('\n'),
400
- start: startIndex + 1,
401
- end: startIndex + selected.length,
402
- omitted: startIndex > 0 || startIndex + selected.length < lines.length || !scanComplete,
403
- ...partialTail && startIndex + selected.length === lines.length
404
- ? { partialLine: lines.length }
405
- : {},
406
- }
407
- }
408
-
409
- function querySlice(
410
- lines: readonly string[],
411
- query: string,
412
- maxLines: number,
413
- scanComplete: boolean,
414
- partialTail: boolean,
415
- ): Selection {
416
- const needle = query.toLowerCase()
417
- const chosen = new Set<number>()
418
- let matched = false
419
- let omitted = !scanComplete
420
- for (let index = 0; index < lines.length; index++) {
421
- const line = lines[index]
422
- if (line === undefined || !line.toLowerCase().includes(needle)) continue
423
- matched = true
424
- for (let row = Math.max(0, index - 2); row <= Math.min(lines.length - 1, index + 2); row++) {
425
- if (chosen.has(row)) continue
426
- if (chosen.size >= maxLines) {
427
- omitted = true
428
- continue
429
- }
430
- chosen.add(row)
431
- }
432
- }
433
- if (!matched) {
434
- return {
435
- text: scanComplete ? '[no matches]' : '[no matches within source scan limit]',
436
- start: 0,
437
- end: 0,
438
- omitted,
439
- }
440
- }
441
- const ordered = [...chosen].sort((a, b) => a - b)
442
- const rendered: string[] = []
443
- let previous = -2
444
- let start = 0
445
- let end = 0
446
- for (const index of ordered) {
447
- const line = lines[index]
448
- if (line === undefined) continue
449
- if (index > previous + 1) rendered.push('...')
450
- rendered.push(`${String(index + 1)}: ${line}`)
451
- if (start === 0) start = index + 1
452
- end = index + 1
453
- previous = index
454
- }
455
- return {
456
- text: rendered.join('\n'),
457
- start,
458
- end,
459
- omitted,
460
- ...partialTail && ordered.includes(lines.length - 1)
461
- ? { partialLine: lines.length }
462
- : {},
463
- }
464
- }
465
-
466
- function boundCodePoints(text: string, maxChars: number): string {
467
- const bounded = codePointPrefix(text, maxChars)
468
- if (bounded.complete) return text
469
- const marker = codePointPrefix(TRUNCATION_MARKER, maxChars)
470
- if (!marker.complete) return marker.text
471
- const body = codePointPrefix(text, maxChars - marker.count)
472
- return body.text + marker.text
473
- }
474
-
475
- function codePointPrefix(text: string, maxChars: number): {
476
- readonly text: string
477
- readonly count: number
478
- readonly complete: boolean
479
- } {
480
- const output: string[] = []
481
- let count = 0
482
- for (const point of text) {
483
- if (count >= maxChars) return { text: output.join(''), count, complete: false }
484
- output.push(point)
485
- count++
486
- }
487
- return { text: output.join(''), count, complete: true }
488
- }
489
-
490
- function exceedsCodePointLimit(text: string, limit: number): boolean {
491
- let count = 0
492
- for (const _point of text) {
493
- count++
494
- if (count > limit) return true
495
- }
496
- return false
497
- }
498
-
499
- function codePointLength(text: string): number {
500
- let count = 0
501
- for (const _point of text) count++
502
- return count
503
- }
@@ -1,117 +0,0 @@
1
- /**
2
- * 按 call 积分器(spec T15/T16)——"真节省"口径。
3
- *
4
- * 定义:真节省 = Σ_每次call(该次基线输入 − 实际输入)。存量(delta, observeActive
5
- * 收敛)回答"现在省多少";积分把每个 fresh 边界的存量净快照累加成跨重启的
6
- * "累计(按 N 次 call)"。召回不追溯翻账:召回前的 call 真省过钱,样本保留;
7
- * 召回后存量转负,后续采样自然把积分往下拉——前向口径,历史样本永不改写。
8
- *
9
- * 采样点:pruneSession stage='fresh' 的 recordUsage 同点(pruner 接线行,本
10
- * 模块不重做任何测量)。boundarySeq = 采样时刻事件日志的最大绝对 seq——每完成
11
- * 一次请求日志必追加(assistant/message 等),相邻两次 fresh 采样之间 maxSeq
12
- * 单调递增,天然构成 per-call 幂等键;同 seq 重放被 claims 主键吸收。
13
- *
14
- * 省钱口径(T16):cached/uncached 分权——cachedInput×inputCacheHit +
15
- * uncachedInput×inputCacheMiss(官方定价目录,定点 bigint,零浮点)。无定价
16
- * 路由(非 deepseek-official 官方公网/未知模型)返回 null,面板仅 token 口径。
17
- * 拆分规则:cacheReadTokens = 命中数;uncached = inputTokens − cacheRead
18
- * (负值截 0)。首 call 无 usage 报告时照常采样存量(calls 照计,拆分记 0)。
19
- *
20
- * @module dsh-context-compression-improved/runtime/savings-integral
21
- */
22
- import type { Session } from '@deepseek-ai/dsh-session'
23
- import {
24
- decimalRateNanoUnits,
25
- type OfficialDeepSeekPriceRecord,
26
- } from './deepseek-official-pricing.ts'
27
- import { sessionEvents } from './session-events.ts'
28
- import { recordIntegralSample } from './stats-sync.ts'
29
-
30
- /** 一次 fresh 边界采样的输入(测量由调用方完成,本模块只定键、拆分、落库)。 */
31
- export interface IntegralSampleInput {
32
- sessionId: string
33
- session: Session
34
- /** 内存账本当前存量净额(snapshot(sessionId).net,双 basis 分列)。 */
35
- net: { exact: number; estimated: number }
36
- /** 该边界读到的上一已完成请求官方 usage;首 call 缺报时 undefined。 */
37
- usage?: { inputTokens?: number; cacheReadTokens?: number } | undefined
38
- }
39
-
40
- /** 采样时刻事件日志的最大绝对 seq;空日志(无从定键)返回 undefined。 */
41
- export function latestEventSeq(session: Session): number | undefined {
42
- let max: number | undefined
43
- for (const event of sessionEvents(session)) {
44
- const seq = Number(event.seq)
45
- if (Number.isFinite(seq)) max = max === undefined ? seq : Math.max(max, seq)
46
- }
47
- return max
48
- }
49
-
50
- /** usage 拆分:cacheRead = 命中;uncached = input − cacheRead(负截 0);非法值记 0。 */
51
- export function splitCachedUncached(usage: IntegralSampleInput['usage']): { cachedInput: number; uncachedInput: number } {
52
- const cached = typeof usage?.cacheReadTokens === 'number' && Number.isFinite(usage.cacheReadTokens) && usage.cacheReadTokens > 0
53
- ? Math.trunc(usage.cacheReadTokens)
54
- : 0
55
- const input = typeof usage?.inputTokens === 'number' && Number.isFinite(usage.inputTokens) && usage.inputTokens > 0
56
- ? Math.trunc(usage.inputTokens)
57
- : 0
58
- return { cachedInput: cached, uncachedInput: Math.max(0, input - cached) }
59
- }
60
-
61
- /** fresh 边界采样入口:定键 → 拆分 → 经 stats-sync 幂等落库;空日志静默跳过。 */
62
- export function sampleIntegralBoundary(input: IntegralSampleInput): void {
63
- const boundarySeq = latestEventSeq(input.session)
64
- if (boundarySeq === undefined) return
65
- const { cachedInput, uncachedInput } = splitCachedUncached(input.usage)
66
- recordIntegralSample({
67
- sessionId: input.sessionId,
68
- boundarySeq,
69
- netExact: input.net.exact,
70
- netEstimated: input.net.estimated,
71
- cachedInput,
72
- uncachedInput,
73
- })
74
- }
75
-
76
- /** 定价目录单位(每 1M tokens)下的双科目省钱估计;记录缺有效费率 = null。 */
77
- export interface IntegralMoneyEstimate {
78
- /** 定点十进制(主币种单位),格式同定价模块 femto 渲染。 */
79
- decimal: string
80
- /** 原始定点整数(femto 主币种单位),供聚合而不丢精度。 */
81
- femtoUnits: string
82
- currency: 'USD' | 'CNY'
83
- band: 'peak' | 'off-peak'
84
- }
85
-
86
- /**
87
- * 省钱估计(T16):cached 走 inputCacheHit、uncached 走 inputCacheMiss,
88
- * femto = tokens × nanoRate(与定价模块 amountFor 同构,输出侧不计——
89
- * 积分口径只对输入省钱)。费率不可解析(理论上目录内不会)返回 null。
90
- */
91
- export function estimateIntegralMoney(input: {
92
- cachedInput: number
93
- uncachedInput: number
94
- record: OfficialDeepSeekPriceRecord
95
- }): IntegralMoneyEstimate | null {
96
- const hit = decimalRateNanoUnits(input.record.inputCacheHit)
97
- const miss = decimalRateNanoUnits(input.record.inputCacheMiss)
98
- if (hit === undefined || miss === undefined) return null
99
- const cached = Number.isFinite(input.cachedInput) && input.cachedInput > 0 ? BigInt(Math.trunc(input.cachedInput)) : 0n
100
- const uncached = Number.isFinite(input.uncachedInput) && input.uncachedInput > 0 ? BigInt(Math.trunc(input.uncachedInput)) : 0n
101
- if (cached === 0n && uncached === 0n) return null
102
- const femtoUnits = cached * hit + uncached * miss
103
- return {
104
- decimal: formatFemtoUnits(femtoUnits),
105
- femtoUnits: femtoUnits.toString(),
106
- currency: input.record.currency,
107
- band: input.record.band,
108
- }
109
- }
110
-
111
- /** femto(1e-15)整数 → 十进制串;与定价模块的 femto 渲染同构(模块内私有,此处独立实现)。 */
112
- function formatFemtoUnits(value: bigint): string {
113
- const digits = value.toString().padStart(16, '0')
114
- const whole = digits.slice(0, -15)
115
- const fraction = digits.slice(-15).replace(/0+$/u, '')
116
- return fraction.length === 0 ? whole : `${whole}.${fraction}`
117
- }