dsh-context-compression-improved 0.9.7 → 0.9.9-beta.0

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 (240) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +15 -98
  3. package/README.zh.md +14 -92
  4. package/THIRD_PARTY_NOTICES.md +32 -14
  5. package/{packages/selector/cordis.patch.yml → cordis.patch.yml} +27 -27
  6. package/{packages/selector/dsh.plugin.json → dsh.plugin.json} +2 -2
  7. package/{packages/selector/lib → lib}/client.d.ts +16 -0
  8. package/{packages/selector/lib → lib}/client.js +393 -116
  9. package/{packages/selector/lib → lib}/index.js +829 -10
  10. package/{packages/selector/lib → lib}/invariant.js +2 -1
  11. package/{packages/selector/lib → lib}/pruner.d.ts +1 -1
  12. package/{packages/selector/lib → lib}/pruner.js +77 -983
  13. package/lib/savings-integral.js +4515 -0
  14. package/{packages/selector/lib → lib}/tail-trim.js +2 -90
  15. package/lib/tool-result.js +150 -0
  16. package/package.json +129 -116
  17. package/screenshots.json +3 -6
  18. package/.gitattributes +0 -2
  19. package/.githooks/pre-push +0 -37
  20. package/.github/workflows/ci.yml +0 -39
  21. package/CHANGELOG.de.md +0 -580
  22. package/CHANGELOG.es.md +0 -588
  23. package/CHANGELOG.fr.md +0 -576
  24. package/CHANGELOG.it.md +0 -577
  25. package/CHANGELOG.ja.md +0 -261
  26. package/CHANGELOG.ko.md +0 -254
  27. package/CHANGELOG.md +0 -532
  28. package/CHANGELOG.ru.md +0 -554
  29. package/CHANGELOG.zh.md +0 -236
  30. package/CONTRIBUTING.md +0 -22
  31. package/README.de.md +0 -96
  32. package/README.es.md +0 -96
  33. package/README.fr.md +0 -96
  34. package/README.it.md +0 -96
  35. package/README.ja.md +0 -102
  36. package/README.ko.md +0 -102
  37. package/README.ru.md +0 -96
  38. package/SECURITY.md +0 -18
  39. package/assets/board.png +0 -0
  40. package/assets/context.png +0 -0
  41. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  42. package/docs/assets/context-compression-selector-settings.png +0 -0
  43. package/docs/compat-0.1.5-report.md +0 -77
  44. package/docs/installation.de.md +0 -104
  45. package/docs/installation.es.md +0 -104
  46. package/docs/installation.fr.md +0 -104
  47. package/docs/installation.it.md +0 -104
  48. package/docs/installation.ja.md +0 -78
  49. package/docs/installation.ko.md +0 -78
  50. package/docs/installation.md +0 -103
  51. package/docs/installation.ru.md +0 -104
  52. package/docs/installation.zh.md +0 -100
  53. package/docs/repair-log.md +0 -657
  54. package/eslint.config.js +0 -30
  55. package/packages/selector/LICENSE +0 -21
  56. package/packages/selector/README.md +0 -26
  57. package/packages/selector/README.zh.md +0 -24
  58. package/packages/selector/THIRD_PARTY_NOTICES.md +0 -32
  59. package/packages/selector/docs/history-tool-call-working-set-spec.md +0 -112
  60. package/packages/selector/docs/native-tool-result-selector-spec.md +0 -34
  61. package/packages/selector/docs/subagent-cache-reuse-spec.md +0 -46
  62. package/packages/selector/lib/config.js +0 -1777
  63. package/packages/selector/lib/host-generation.js +0 -62
  64. package/packages/selector/lib/style.css +0 -350
  65. package/packages/selector/package.json +0 -174
  66. package/packages/selector/screenshots.json +0 -3
  67. package/packages/selector/src/client/CompressionProfileControls.tsx +0 -293
  68. package/packages/selector/src/client/CompressionProfileSelector.module.css +0 -199
  69. package/packages/selector/src/client/CompressionProfileSelector.tsx +0 -85
  70. package/packages/selector/src/client/CustomPolicyEditor.tsx +0 -216
  71. package/packages/selector/src/client/EstimatorControls.tsx +0 -277
  72. package/packages/selector/src/client/bridge-scope.ts +0 -125
  73. package/packages/selector/src/client/decode.ts +0 -57
  74. package/packages/selector/src/client/index.ts +0 -421
  75. package/packages/selector/src/client/locales/de.ts +0 -142
  76. package/packages/selector/src/client/locales/es.ts +0 -142
  77. package/packages/selector/src/client/locales/fr.ts +0 -142
  78. package/packages/selector/src/client/locales/it.ts +0 -142
  79. package/packages/selector/src/client/locales/ja.ts +0 -142
  80. package/packages/selector/src/client/locales/ko.ts +0 -142
  81. package/packages/selector/src/client/locales/ru.ts +0 -142
  82. package/packages/selector/src/client/locales.ts +0 -284
  83. package/packages/selector/src/client/monitor-fab.ts +0 -349
  84. package/packages/selector/src/client/preset-options.ts +0 -88
  85. package/packages/selector/src/client/savings-card.tsx +0 -150
  86. package/packages/selector/src/client/scope-face.ts +0 -24
  87. package/packages/selector/src/client/settings-section.tsx +0 -140
  88. package/packages/selector/src/compat/host-generation.ts +0 -96
  89. package/packages/selector/src/compat/llm-messages.ts +0 -50
  90. package/packages/selector/src/compat/settings-lease.ts +0 -108
  91. package/packages/selector/src/compat/tool-result.ts +0 -91
  92. package/packages/selector/src/css-modules.d.ts +0 -6
  93. package/packages/selector/src/deepseek-v4-tokenizer.ts +0 -205
  94. package/packages/selector/src/estimator-catalog.ts +0 -104
  95. package/packages/selector/src/index.ts +0 -655
  96. package/packages/selector/src/invariant.ts +0 -113
  97. package/packages/selector/src/preset-overlay.ts +0 -749
  98. package/packages/selector/src/profiles.ts +0 -431
  99. package/packages/selector/src/pruner/content.ts +0 -198
  100. package/packages/selector/src/pruner/session.ts +0 -97
  101. package/packages/selector/src/pruner/state.ts +0 -61
  102. package/packages/selector/src/pruner/tuning.ts +0 -23
  103. package/packages/selector/src/pruner/types.ts +0 -78
  104. package/packages/selector/src/pruner.ts +0 -2868
  105. package/packages/selector/src/runtime/adaptive-cost.ts +0 -205
  106. package/packages/selector/src/runtime/audit.ts +0 -303
  107. package/packages/selector/src/runtime/config.ts +0 -756
  108. package/packages/selector/src/runtime/custom-policy.ts +0 -278
  109. package/packages/selector/src/runtime/deepseek-official-pricing.ts +0 -298
  110. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +0 -254
  111. package/packages/selector/src/runtime/measurement.ts +0 -444
  112. package/packages/selector/src/runtime/monitor.ts +0 -235
  113. package/packages/selector/src/runtime/reducers.ts +0 -1754
  114. package/packages/selector/src/runtime/retrieve.ts +0 -484
  115. package/packages/selector/src/runtime/savings-projection.ts +0 -226
  116. package/packages/selector/src/runtime/savings.ts +0 -417
  117. package/packages/selector/src/runtime/session-events.ts +0 -30
  118. package/packages/selector/src/runtime/summary-command.ts +0 -127
  119. package/packages/selector/src/runtime/tail-trim.ts +0 -176
  120. package/packages/selector/src/runtime/token-count.ts +0 -72
  121. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +0 -233
  122. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +0 -204
  123. package/packages/selector/src/runtime/tokenpilot/advisor.ts +0 -419
  124. package/packages/selector/src/runtime/tokenpilot/benefit.ts +0 -200
  125. package/packages/selector/src/runtime/tokenpilot/dedup.ts +0 -81
  126. package/packages/selector/src/runtime/tokenpilot/estimator.ts +0 -151
  127. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +0 -53
  128. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +0 -65
  129. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +0 -125
  130. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +0 -37
  131. package/packages/selector/src/runtime/tokenpilot/locator.ts +0 -128
  132. package/packages/selector/src/runtime/tokenpilot/read-state.ts +0 -98
  133. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +0 -303
  134. package/packages/selector/src/runtime/toolclass.ts +0 -103
  135. package/packages/selector/src/runtime/types.ts +0 -365
  136. package/packages/selector/src/runtime/value.ts +0 -48
  137. package/packages/selector/src/settings-bridge.ts +0 -175
  138. package/packages/selector/tests/advisor-report.host.spec.ts +0 -223
  139. package/packages/selector/tests/auto-compact.client.spec.tsx +0 -214
  140. package/packages/selector/tests/built/client-artifact.spec.ts +0 -56
  141. package/packages/selector/tests/cache-prefix-audit.spec.ts +0 -123
  142. package/packages/selector/tests/code-skeleton.client.spec.ts +0 -98
  143. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +0 -150
  144. package/packages/selector/tests/custom-contract.client.spec.ts +0 -226
  145. package/packages/selector/tests/estimator-catalog.spec.ts +0 -70
  146. package/packages/selector/tests/estimator-channel.client.spec.tsx +0 -253
  147. package/packages/selector/tests/estimator-route-registration.host.spec.ts +0 -199
  148. package/packages/selector/tests/helpers/legacy-namespace.ts +0 -35
  149. package/packages/selector/tests/helpers/legacy-settings/index.ts +0 -15
  150. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +0 -41
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +0 -647
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +0 -78
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +0 -234
  154. package/packages/selector/tests/host-preset-overlay.host.spec.ts +0 -204
  155. package/packages/selector/tests/monitor-fab.client.spec.ts +0 -138
  156. package/packages/selector/tests/preset-options-write.client.spec.ts +0 -192
  157. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +0 -200
  158. package/packages/selector/tests/preset-overlay.host.spec.ts +0 -246
  159. package/packages/selector/tests/profiles.client.spec.tsx +0 -436
  160. package/packages/selector/tests/public/package-contract.client.spec.ts +0 -86
  161. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +0 -167
  162. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +0 -230
  163. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +0 -272
  164. package/packages/selector/tests/runtime/advisor.spec.ts +0 -226
  165. package/packages/selector/tests/runtime/audit.spec.ts +0 -275
  166. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +0 -523
  167. package/packages/selector/tests/runtime/char-basis.spec.ts +0 -30
  168. package/packages/selector/tests/runtime/code-skeleton.spec.ts +0 -152
  169. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +0 -186
  170. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +0 -122
  171. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +0 -122
  172. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +0 -96
  173. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +0 -273
  174. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +0 -106
  175. package/packages/selector/tests/runtime/fixtures/vision-golden.json +0 -459
  176. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +0 -74
  177. package/packages/selector/tests/runtime/fresh-gate.spec.ts +0 -43
  178. package/packages/selector/tests/runtime/html-reducer.spec.ts +0 -212
  179. package/packages/selector/tests/runtime/intent-gate.spec.ts +0 -62
  180. package/packages/selector/tests/runtime/intent-summary.spec.ts +0 -156
  181. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +0 -79
  182. package/packages/selector/tests/runtime/line-mapping.spec.ts +0 -153
  183. package/packages/selector/tests/runtime/monitor.spec.ts +0 -301
  184. package/packages/selector/tests/runtime/prose-reducers.spec.ts +0 -133
  185. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -2782
  186. package/packages/selector/tests/runtime/read-input-cap.spec.ts +0 -33
  187. package/packages/selector/tests/runtime/savings-projection.spec.ts +0 -89
  188. package/packages/selector/tests/runtime/savings.spec.ts +0 -139
  189. package/packages/selector/tests/runtime/search-reducer.spec.ts +0 -110
  190. package/packages/selector/tests/runtime/session-events.spec.ts +0 -27
  191. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +0 -58
  192. package/packages/selector/tests/runtime/sidechannel.spec.ts +0 -241
  193. package/packages/selector/tests/runtime/summary-command.spec.ts +0 -154
  194. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +0 -159
  195. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +0 -53
  196. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +0 -217
  197. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +0 -52
  198. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +0 -79
  199. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +0 -76
  200. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +0 -119
  201. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +0 -82
  202. package/packages/selector/tests/runtime/toolclass.spec.ts +0 -156
  203. package/packages/selector/tests/runtime/value.spec.ts +0 -23
  204. package/packages/selector/tests/settings-seat.client.spec.ts +0 -215
  205. package/packages/selector/tests/standing-generation.host.spec.ts +0 -724
  206. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +0 -269
  207. package/packages/selector/tests/support/cache-prefix-audit.ts +0 -105
  208. package/packages/selector/tests/support/mock-adapter.ts +0 -37
  209. package/packages/selector/tests/support/ui-primitives.tsx +0 -34
  210. package/packages/selector/tsconfig.json +0 -11
  211. package/packages/selector/tsdown.client.config.ts +0 -102
  212. package/packages/selector/tsdown.config.ts +0 -20
  213. package/pnpm-workspace.yaml +0 -72
  214. package/scripts/capture-profile-baseline.mjs +0 -42
  215. package/scripts/cell-browser-e2e.mjs +0 -354
  216. package/scripts/generate-tokenizer-fixtures.py +0 -81
  217. package/scripts/generate-vision-fixtures.py +0 -208
  218. package/scripts/hosts.mjs +0 -77
  219. package/scripts/packed-components-smoke.mjs +0 -763
  220. package/scripts/packed-install-e2e.mjs +0 -1346
  221. package/scripts/sync-hosts.mjs +0 -174
  222. package/scripts/toolclass-corpus-replay.mjs +0 -281
  223. package/scripts/verify-release.mjs +0 -335
  224. package/tests/TEST_INVENTORY.md +0 -41
  225. package/tsconfig.base.json +0 -18
  226. package/tsconfig.json +0 -7
  227. package/tsconfig.tests.json +0 -15
  228. package/vitest.built.config.ts +0 -9
  229. package/vitest.config.ts +0 -46
  230. /package/{packages/selector/assets → assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  231. /package/{packages/selector/assets → assets}/deepseek-v4/manifest.json +0 -0
  232. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer.json +0 -0
  233. /package/{packages/selector/assets → assets}/deepseek-v4/tokenizer_config.json +0 -0
  234. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  235. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  236. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  237. /package/{packages/selector/assets → assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  238. /package/{packages/selector/lib → lib}/index.d.ts +0 -0
  239. /package/{packages/selector/lib → lib}/invariant.d.ts +0 -0
  240. /package/{packages/selector/lib → lib}/profiles.d.ts +0 -0
@@ -1,655 +0,0 @@
1
- /** Host owner of the context-compression preference consumed by the browser selector. */
2
-
3
- import type { Context } from '@deepseek-ai/cordis'
4
- import z from '@deepseek-ai/schemastery'
5
- import { buildEstimatorCatalog, type EstimatorCatalogDeps } from './estimator-catalog.ts'
6
- import { getSavingsLedger } from './runtime/savings.ts'
7
- import {
8
- applySessionOverride,
9
- buildMonitorSnapshot,
10
- estimateSavingsPricing,
11
- isSessionOverrideAction,
12
- type AgentDefaultModelLike,
13
- } from './runtime/monitor.ts'
14
- import type { ContextCompressionSettings } from './profiles.ts'
15
- import {
16
- CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
17
- DEFAULT_CONTEXT_COMPRESSION_SETTINGS,
18
- } from './runtime/config.ts'
19
-
20
- import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
21
- import { registerSummaryCommand } from './runtime/summary-command.ts'
22
- import { wireSettingsBridge } from './settings-bridge.ts'
23
-
24
- // The settings namespace literal and the settings schema are owned by the
25
- // runtime config module. Both were once inlined/replaced here to dodge a
26
- // cross-package dependency (ab2175a: the namespace literal was duplicated and
27
- // the schema was downgraded to `z.any()`); the runtime is now part of this
28
- // package, so the real schema is back and the daily Custom defaults are
29
- // published again through settings.register(). The namespace value is
30
- // unchanged ('context-compression').
31
- import {
32
- decorateAgentPresets,
33
- resolveCompressionModulePaths,
34
- } from './preset-overlay.ts'
35
-
36
- // 0.1.1/0.1.2 clients ask for /endpoint; 0.1.5 and later ask for /api. Both
37
- // absolute paths are registered (each is its own (kind, path) table entry) and
38
- // one handler serves both prefixes. The bundled client only probes /api.
39
- const ESTIMATOR_CATALOG_ROUTES = [
40
- '/endpoint/dsh-context-compression-improved/estimator-catalog',
41
- '/api/dsh-context-compression-improved/estimator-catalog',
42
- ] as const
43
-
44
- // Advisory advisor: one read-only report route, dual prefixed like the others.
45
- const ADVISOR_REPORT_ROUTES = [
46
- '/endpoint/dsh-context-compression-improved/advisor-report',
47
- '/api/dsh-context-compression-improved/advisor-report',
48
- ] as const
49
-
50
- // Savings stats: one read-only snapshot route, dual prefixed like the others.
51
- const SAVINGS_ROUTES = [
52
- '/endpoint/dsh-context-compression-improved/savings',
53
- '/api/dsh-context-compression-improved/savings',
54
- ] as const
55
-
56
- const MONITOR_ROUTES = [
57
- '/endpoint/dsh-context-compression-improved/monitor',
58
- '/api/dsh-context-compression-improved/monitor',
59
- ] as const
60
-
61
- /** Minimal face of the agents service: session id → agent (carrying the session). */
62
- interface AgentsServiceLike {
63
- get?(id: unknown): { session?: unknown } | undefined
64
- }
65
-
66
- function sessionFor(readService: (name: string) => unknown, sessionId: string): unknown {
67
- const agents = readService('agents') as AgentsServiceLike | undefined
68
- return typeof agents?.get === 'function' ? agents.get(sessionId)?.session : undefined
69
- }
70
-
71
- function jsonResponse(res: unknown, status: number, body: unknown): void {
72
- const resTyped = res as {
73
- writeHead: (code: number, headers?: Record<string, string>) => void
74
- end: (body?: string) => void
75
- }
76
- resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
77
- resTyped.end(JSON.stringify(body))
78
- }
79
-
80
- /**
81
- * Serve the advisory advisor's read-only report route (same registration
82
- * skeleton as the estimator-catalog route):
83
- *
84
- * `GET .../advisor-report?sessionId=…` → the session's prefix-decay figure,
85
- * the todolist-bound task summary, and the score distribution. Content-free
86
- * by construction: task semantics are LLM-derived summaries, never message
87
- * text, and no score reason or candidate preview is ever returned.
88
- * Unknown session → 404; no agents service → 503. A session whose advisor
89
- * never ran reports nulls and empty arrays, not an error.
90
- */
91
- function registerAdvisorReportRoute(ctx: Context): void {
92
- const readService = (name: string): unknown => {
93
- try {
94
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
95
- } catch {
96
- return undefined
97
- }
98
- }
99
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
100
- console[level](message, ...args)
101
- }
102
-
103
- const getHandler = (req: unknown, res: unknown): void => {
104
- const agents = readService('agents') as AgentsServiceLike | undefined
105
- if (typeof agents?.get !== 'function') {
106
- jsonResponse(res, 503, { ok: false, error: 'advisor report unavailable' })
107
- return
108
- }
109
- let sessionId = ''
110
- try {
111
- const url = new URL(String((req as { url?: string }).url ?? ''), 'http://localhost')
112
- sessionId = url.searchParams.get('sessionId') ?? ''
113
- } catch {
114
- // Malformed URL: fall through with the empty sessionId already set.
115
- }
116
- if (sessionId === '') {
117
- jsonResponse(res, 400, { ok: false, error: 'sessionId is required' })
118
- return
119
- }
120
- const session = sessionFor(readService, sessionId)
121
- if (session === undefined) {
122
- jsonResponse(res, 404, { ok: false, error: 'unknown session' })
123
- return
124
- }
125
- const state = getAdvisorState(session as Parameters<typeof getAdvisorState>[0])
126
- jsonResponse(res, 200, {
127
- ok: true,
128
- sessionId,
129
- advisor: {
130
- summary: state.summary ?? null,
131
- decay: state.lastDecay?.decay ?? null,
132
- weightedChars: state.lastDecay?.weightedChars ?? null,
133
- decayTurn: state.lastDecay?.turn ?? null,
134
- scores: [...state.scores].map(([seq, entry]) => ({ seq, score: entry.score, turn: entry.turn })),
135
- lowRelevanceSeqs: [...state.recertified.keys()],
136
- // The benefit model's label of the last landed batch — advice, never a
137
- // gate: the batch it describes landed regardless of the band.
138
- lastAdvice: state.lastAdvice === undefined
139
- ? null
140
- : {
141
- band: state.lastAdvice.band,
142
- turn: state.lastAdvice.turn,
143
- itemSeqs: state.lastAdvice.itemSeqs,
144
- recoveredTokens: state.lastAdvice.recoveredTokens,
145
- penaltyTokens: state.lastAdvice.penaltyTokens,
146
- paybackTurns: state.lastAdvice.paybackTurns ?? null,
147
- },
148
- },
149
- })
150
- }
151
-
152
- const register = (webServer: WebServerLike): void => {
153
- const table = [...ADVISOR_REPORT_ROUTES].map(path => ({ path, handler: getHandler }))
154
- const disposers = table
155
- .map(entry => webServer.register({ kind: 'exact', path: entry.path, handler: entry.handler }))
156
- .filter((off): off is () => void => typeof off === 'function')
157
- ctx.effect(
158
- () => () => { for (const off of disposers) off() },
159
- 'contextCompressionSelector.advisor report route',
160
- )
161
- log('info', 'context-compression advisor report route registered: %s', ADVISOR_REPORT_ROUTES.join(', '))
162
- }
163
-
164
- const active = asWebServer(readService('webServer'))
165
- if (active !== undefined) {
166
- register(active)
167
- return
168
- }
169
-
170
- ctx.inject(['webServer'], (injected) => {
171
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
172
- if (webServer === undefined) {
173
- log('warn', 'context-compression webServer exposes no register() — advisor report route not registered')
174
- return
175
- }
176
- register(webServer)
177
- })
178
-
179
- log('warn', 'context-compression webServer not active yet — advisor report route pending: %s', ADVISOR_REPORT_ROUTES.join(', '))
180
- }
181
-
182
- /**
183
- * The one service the catalog route actually needs. `llm` and
184
- * `agentDefaultModel` are payload enrichment the handler resolves per request,
185
- * never reasons to withhold the route.
186
- */
187
- const ESTIMATOR_CATALOG_ROUTE_DEPS: readonly ['webServer'] = ['webServer']
188
-
189
- /** The minimal face of the DSH `webServer` service this plugin uses. */
190
- interface WebServerLike {
191
- register(route: {
192
- kind: 'exact'
193
- path: string
194
- handler: (req: unknown, res: unknown) => unknown
195
- }): () => void
196
- }
197
-
198
- /** The estimator-side service the catalog handler enriches its response with. */
199
- function asWebServer(value: unknown): WebServerLike | undefined {
200
- if (typeof value !== 'object' || value === null) return undefined
201
- const candidate = value as { register?: unknown }
202
- // Hand back the service itself -- never a wrapper re-exporting `register`.
203
- // The host reads its route tables off `this` (`this.exact` / `this.prefixes`),
204
- // so a detached call makes `this` the wrapper and throws "Cannot read
205
- // properties of undefined (reading 'has')" inside the host, after which the
206
- // route is simply absent and the client sees a bare 404. The 0.1.5 branch
207
- // never had that defect; take this implementation, not the 0.1.2 history's.
208
- return typeof candidate.register === 'function' ? (value as WebServerLike) : undefined
209
- }
210
-
211
- /**
212
- * `webServer.register` throws `duplicate exact route` when the same lib is
213
- * mounted twice by the host (two plugin ids resolving to one module: the
214
- * package-root manifest and the nested selector manifest). The other mount
215
- * already owns every path in the batch, so the collision is a success from
216
- * the plugin's point of view — without this, the losing arm logs a stack-
217
- * heavy warn pair on every boot (observed 0.9.5 on 0.2.0-rc.2, savings and
218
- * monitor).
219
- */
220
- const isDuplicateRouteError = (error: unknown): boolean =>
221
- String((error as Error)?.message ?? error).includes('duplicate exact route')
222
-
223
- /**
224
- * Serve `GET /api/dsh-context-compression-improved/estimator-catalog` — the
225
- * settings card's host-route dropdowns (live provider/model groups from the DSH
226
- * `llm` service plus the effective selection). Best effort: without the
227
- * `webServer` service the plugin keeps working, only the HTTP API is missing.
228
- *
229
- * The route gates on `webServer` **alone**. `llm` and `agentDefaultModel` only
230
- * enrich the response and are resolved per request, so listing them here would
231
- * let an estimator-side service the handler never needs keep the route
232
- * unregistered. That failure is silent by construction — an unsatisfied
233
- * `ctx.inject` callback never runs, so the plugin simply has no HTTP API and
234
- * every request falls through to the host 404.
235
- *
236
- * Two channels cover the two arrival orders: a direct lookup catches a
237
- * `webServer` that is already active when the plugin loads, and `ctx.inject`
238
- * catches one that activates later. Both funnel into a single guarded
239
- * registration, because a late-arriving service must not re-register a
240
- * `(kind, path)` the host treats as a composition-contract violation.
241
- */
242
- function registerEstimatorCatalogRoute(ctx: Context): void {
243
- const readService = (name: string): unknown => {
244
- try {
245
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
246
- } catch {
247
- return undefined
248
- }
249
- }
250
- // `console`, not `ctx.logger`: measured on the 0.1.2 host, the cordis logger
251
- // surfaces no plugin output in the `dsh web` terminal at all — a full boot
252
- // produced zero plugin log lines while the process itself stayed chatty — so
253
- // a lifecycle diagnostic published there is unobservable. `dsh-perm-gate`
254
- // uses `console.warn` for the same message class on the same host.
255
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
256
- console[level](message, ...args)
257
- }
258
-
259
- let registered = false
260
- const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
261
- if (registered) return
262
- const handler = (_req: unknown, res: unknown): void => {
263
- const resTyped = res as {
264
- writeHead: (code: number, headers?: Record<string, string>) => void
265
- end: (body?: string) => void
266
- }
267
- if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
268
- const llm = readService('llm')
269
- const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
270
- const deps: EstimatorCatalogDeps = {
271
- ...(llm === undefined
272
- ? {}
273
- : { llm: llm as NonNullable<EstimatorCatalogDeps['llm']> }),
274
- ...(typeof defaults?.currentSelection === 'function'
275
- ? { currentSelection: () => defaults.currentSelection?.() }
276
- : {}),
277
- }
278
- buildEstimatorCatalog(deps).then(
279
- catalog => {
280
- resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
281
- resTyped.end(JSON.stringify({ ok: true, ...catalog }))
282
- },
283
- (error: unknown) => {
284
- resTyped.writeHead(500, { 'content-type': 'application/json; charset=utf-8' })
285
- resTyped.end(JSON.stringify({ ok: false, error: String((error as Error)?.message ?? error) }))
286
- },
287
- )
288
- }
289
- try {
290
- const disposers = ESTIMATOR_CATALOG_ROUTES
291
- .map(path => webServer.register({ kind: 'exact', path, handler }))
292
- .filter((off): off is () => void => typeof off === 'function')
293
- registered = true
294
- ctx.effect(
295
- () => () => { for (const off of disposers) off() },
296
- 'contextCompressionSelector.estimator-catalog route',
297
- )
298
- log('info', 'context-compression estimator catalog route registered (%s): %s', channel, ESTIMATOR_CATALOG_ROUTES.join(', '))
299
- } catch (error) {
300
- if (isDuplicateRouteError(error)) {
301
- registered = true
302
- log('info', 'context-compression estimator catalog route already registered by another mount (%s)', channel)
303
- return
304
- }
305
- log('warn', 'context-compression estimator catalog route registration failed (%s): %o', channel, error)
306
- }
307
- }
308
-
309
- const active = asWebServer(readService('webServer'))
310
- if (active !== undefined) {
311
- register(active, 'direct')
312
- if (registered) return
313
- }
314
-
315
- ctx.inject([...ESTIMATOR_CATALOG_ROUTE_DEPS], (injected) => {
316
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
317
- if (webServer === undefined) {
318
- log('warn', 'context-compression webServer exposes no register() — estimator catalog route not registered')
319
- return
320
- }
321
- register(webServer, 'inject')
322
- })
323
-
324
- log('warn', 'context-compression webServer not active yet — estimator catalog route pending: %s', ESTIMATOR_CATALOG_ROUTES.join(', '))
325
- }
326
-
327
- /**
328
- * Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
329
- * offsets (negative savings — compressed content later re-read in full), and net,
330
- * with exact-tokenizer and chars/4 bases reported separately and never merged.
331
- * Registration mirrors the estimator-catalog route (webServer gate alone, dual
332
- * channels for both service arrival orders, single guarded registration).
333
- */
334
- function registerSavingsRoute(ctx: Context): void {
335
- const readService = (name: string): unknown => {
336
- try {
337
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
338
- } catch {
339
- return undefined
340
- }
341
- }
342
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
343
- console[level](message, ...args)
344
- }
345
-
346
- let registered = false
347
- const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
348
- if (registered) return
349
- const handler = (req: unknown, res: unknown): void => {
350
- const resTyped = res as {
351
- writeHead: (code: number, headers?: Record<string, string>) => void
352
- end: (body?: string) => void
353
- }
354
- if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
355
- let sessionId: string | undefined
356
- try {
357
- const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
358
- const raw = url.searchParams.get('sessionId')
359
- if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
360
- } catch {
361
- /* 无法解析的查询串 = 全会话聚合 */
362
- }
363
- const snapshot = getSavingsLedger().snapshot(sessionId)
364
- const pricing = estimateSavingsPricing(readService, snapshot)
365
- resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
366
- resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
367
- }
368
- try {
369
- const disposers = SAVINGS_ROUTES
370
- .map(path => webServer.register({ kind: 'exact', path, handler }))
371
- .filter((off): off is () => void => typeof off === 'function')
372
- registered = true
373
- ctx.effect(
374
- () => () => { for (const off of disposers) off() },
375
- 'contextCompressionSelector.savings route',
376
- )
377
- log('info', 'context-compression savings route registered (%s): %s', channel, SAVINGS_ROUTES.join(', '))
378
- } catch (error) {
379
- if (isDuplicateRouteError(error)) {
380
- registered = true
381
- log('info', 'context-compression savings route already registered by another mount (%s)', channel)
382
- return
383
- }
384
- log('warn', 'context-compression savings route registration failed (%s): %o', channel, error)
385
- }
386
- }
387
-
388
- const active = asWebServer(readService('webServer'))
389
- if (active !== undefined) {
390
- register(active, 'direct')
391
- if (registered) return
392
- }
393
-
394
- ctx.inject(['webServer'], (injected) => {
395
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
396
- if (webServer === undefined) {
397
- log('warn', 'context-compression webServer exposes no register() — savings route not registered')
398
- return
399
- }
400
- register(webServer, 'inject')
401
- })
402
- }
403
-
404
- /**
405
- * Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
406
- * - GET → the monitor snapshot (savings aggregate + intent control block +
407
- * pricing) — the payload shape the panel polls;
408
- * - POST → session override action (`{"action":"on"|"off"|"clear"}`),
409
- * driving the exact state machine `/ctx-summary` drives.
410
- * Registration mirrors the savings route (webServer gate alone, dual channels,
411
- * single guarded registration); the handler branches on `req.method` because
412
- * the registration surface is method-agnostic.
413
- */
414
- /** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
415
- export function registerMonitorRoute(ctx: Context): void {
416
- const readService = (name: string): unknown => {
417
- try {
418
- return (ctx as unknown as { get: (service: string) => unknown }).get(name)
419
- } catch {
420
- return undefined
421
- }
422
- }
423
- const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
424
- console[level](message, ...args)
425
- }
426
-
427
- let registered = false
428
- const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
429
- if (registered) return
430
- const handler = (req: unknown, res: unknown): void => {
431
- const resTyped = res as {
432
- writeHead: (code: number, headers?: Record<string, string>) => void
433
- end: (body?: string) => void
434
- }
435
- if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
436
- let sessionId: string | undefined
437
- try {
438
- const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
439
- const raw = url.searchParams.get('sessionId')
440
- if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
441
- } catch {
442
- /* 无法解析的查询串 = 全会话聚合 */
443
- }
444
- const method = String((req as { method?: string })?.method ?? 'GET').toUpperCase()
445
- if (method === 'POST') {
446
- const chunks: Buffer[] = []
447
- let size = 0
448
- let done = false
449
- const respond = (status: number, body: Record<string, unknown>): void => {
450
- if (done) return
451
- done = true
452
- resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
453
- resTyped.end(JSON.stringify(body))
454
- }
455
- const reqTyped = req as { on?: (event: string, cb: (chunk?: Buffer) => void) => void }
456
- if (typeof reqTyped?.on !== 'function') {
457
- respond(400, { ok: false, error: 'unreadable request body' })
458
- return
459
- }
460
- reqTyped.on('data', (chunk?: Buffer) => {
461
- size += chunk?.length ?? 0
462
- if (size <= 4096) chunks.push(Buffer.from(chunk ?? new Uint8Array()))
463
- })
464
- reqTyped.on('end', () => {
465
- let action: unknown
466
- try {
467
- action = (JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') as { action?: unknown }).action
468
- } catch {
469
- respond(400, { ok: false, error: 'monitor override action must be JSON' })
470
- return
471
- }
472
- if (!isSessionOverrideAction(action)) {
473
- respond(400, { ok: false, error: 'monitor override action must be "on" | "off" | "clear"' })
474
- return
475
- }
476
- const { override } = applySessionOverride(sessionId ?? '', action)
477
- respond(200, { ok: true, override: override ?? null, sessionScope: sessionId ?? null })
478
- })
479
- return
480
- }
481
- const snapshot = buildMonitorSnapshot(sessionId)
482
- const pricing = estimateSavingsPricing(readService, snapshot)
483
- resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
484
- resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
485
- }
486
- try {
487
- const disposers = MONITOR_ROUTES
488
- .map(path => webServer.register({ kind: 'exact', path, handler }))
489
- .filter((off): off is () => void => typeof off === 'function')
490
- registered = true
491
- ctx.effect(
492
- () => () => { for (const off of disposers) off() },
493
- 'contextCompressionSelector.monitor route',
494
- )
495
- log('info', 'context-compression monitor route registered (%s): %s', channel, MONITOR_ROUTES.join(', '))
496
- } catch (error) {
497
- if (isDuplicateRouteError(error)) {
498
- registered = true
499
- log('info', 'context-compression monitor route already registered by another mount (%s)', channel)
500
- return
501
- }
502
- log('warn', 'context-compression monitor route registration failed (%s): %o', channel, error)
503
- }
504
- }
505
-
506
- const active = asWebServer(readService('webServer'))
507
- if (active !== undefined) {
508
- register(active, 'direct')
509
- if (registered) return
510
- }
511
-
512
- ctx.inject(['webServer'], (injected) => {
513
- const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
514
- if (webServer === undefined) {
515
- log('warn', 'context-compression webServer exposes no register() — monitor route not registered')
516
- return
517
- }
518
- register(webServer, 'inject')
519
- })
520
- }
521
-
522
- /**
523
- * Resolve one possibly-volatile field: a live ref on 0.1.7+, a plain value
524
- * otherwise (0.1.7 hands `.volatile()` fields to `apply()` as live refs).
525
- */
526
- function readVolatileValue<T>(value: T | { get(): T } | undefined): T | undefined {
527
- if (value !== null && typeof value === 'object' && typeof (value as { get?: unknown }).get === 'function') {
528
- return (value as { get(): T }).get()
529
- }
530
- return value as T | undefined
531
- }
532
-
533
- /** The compression settings document carried by this row's composition entry. */
534
- function readCompressionDoc(config: Config | undefined): ContextCompressionSettings | undefined {
535
- return readVolatileValue(config?.settings)
536
- }
537
-
538
- /** Standalone Bundle behavior; the settings/UI owner remains safe when false. */
539
- export interface Config {
540
- /** Add the canonical compression stack to every non-Minimal preset. */
541
- presetOverlay?: boolean
542
- /**
543
- * Register the estimator-catalog HTTP route on this row.
544
- *
545
- * The standalone Bundle patch sets this on its own row (which declares
546
- * `inject: [webServer]`), so profiles without a host web server never mount a
547
- * row that could only announce a pending route. The row-level `inject` is
548
- * belt-and-braces: `dsh-host-webserver.register` performs no authorization
549
- * check and `ctx.get(name)` only asks whether the providing fiber is active,
550
- * so the two-channel registration inside this function is what actually
551
- * covers both arrival orders.
552
- */
553
- estimatorCatalogRoute?: boolean
554
- /**
555
- * Register the advisory advisor's read-only HTTP report route (decay
556
- * figure, task summary, score distribution, last benefit-model advice).
557
- * Same Bundle opt-in semantics as `estimatorCatalogRoute`; the advisor
558
- * itself stays off until the user turns it on through the
559
- * `presetOptions.advisor*` settings keys.
560
- */
561
- advisorReportRoute?: boolean
562
- /**
563
- * 0.1.7: the compression settings document as ONE `.volatile()` whole-object
564
- * field (the old dedicated namespace has no declarative equivalent). The
565
- * browser selector writes it through `configForms`; the runtime reads the
566
- * dereferenced value. Loose section schemas keep unknown keys — the strict
567
- * validation stays in `decodeSettings` (client) and the runtime resolver.
568
- */
569
- settings?: ContextCompressionSettings
570
- }
571
-
572
- /** Loader validation for the standalone Bundle opt-in. */
573
- export const Config = z.object({
574
- presetOverlay: z.boolean().default(false),
575
- estimatorCatalogRoute: z.boolean().default(false),
576
- advisorReportRoute: z.boolean().default(false),
577
- // The daily Custom defaults ride the field's schema default so every
578
- // composition resolves a complete document without a stored user layer.
579
- settings: z.any().default(DEFAULT_CONTEXT_COMPRESSION_SETTINGS).volatile(),
580
- }) as unknown as z<Config>
581
-
582
- /** Register the persisted default read by the currently mounted root pruner. */
583
- export function apply(ctx: Context, config: Config = {}): void {
584
- // Measured on the 0.1.2 host: a plugin-load failure surfaces only through the
585
- // cordis logger, which prints nothing in the `dsh web` terminal — so a throw
586
- // here is completely invisible and looks exactly like a plugin that loaded
587
- // and quietly did nothing. Report it to a sink the host shows, then re-throw
588
- // unchanged: behaviour is untouched, only observability is restored.
589
- try {
590
- // The settings card's host-route dropdowns read this route; it lives on the
591
- // top-level plugin fiber, not inside the isolated `toolResultPruner`
592
- // service, because the route is host-wide rather than per-pruner-instance.
593
- if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
594
- // 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
595
- registerSavingsRoute(ctx)
596
- registerMonitorRoute(ctx)
597
-
598
- // compat-legacy 单版本:legacy 宿主(0.1.0–0.1.5,settings.register 仍在)
599
- // 上租约注册压缩命名空间 + 全线挂 settings 桥路由(旧线 client 的唯一数据面;
600
- // modern 线 client 走 configForms,桥 GET 只是补充读)。零 opt-in 门槛,与
601
- // savings/monitor 同级;Gate 0 实证路由行必须带行级 inject:[webServer],
602
- // bundle patch 已含该行(findings B2.1 工程契约)。
603
- wireSettingsBridge(ctx)
604
-
605
- // Advisory advisor: read-only decay/score/advice report (opt-in).
606
- if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
607
-
608
- // Turn-tail intent summary: `/ctx-summary off|on|status`. The command is
609
- // free to register and stays quiet on hosts without the commands
610
- // registry; the capability itself is gated by the frozen `intentSummary`
611
- // setting plus the session-scoped override this command controls.
612
- registerSummaryCommand(ctx)
613
-
614
- if (config.presetOverlay !== true) return
615
-
616
- ctx.inject(['agentPresets'], (presetsCtx) => {
617
- const installation = decorateAgentPresets(
618
- presetsCtx.agentPresets,
619
- {
620
- modules: resolveCompressionModulePaths(),
621
- excludedPresetIds: ['minimal'],
622
- autoCompactThresholdPercent: () => resolveAutoCompactThresholdPercent(config, presetsCtx),
623
- },
624
- )
625
- presetsCtx.effect(() => () => installation.dispose(), 'contextCompressionSelector.agentPresets()')
626
- })
627
- } catch (error) {
628
- console.error('context-compression selector apply failed: %o', error)
629
- throw error
630
- }
631
- }
632
-
633
- /**
634
- * Read the current Auto Compact threshold ratio at composition time. Settings
635
- * values are revalidated here, and any unreadable value falls back to the 80%
636
- * default rather than blocking preset composition.
637
- */
638
- function resolveAutoCompactThresholdPercent(config: Config | undefined, presetsCtx?: Context): number {
639
- // 0.1.7: the volatile entry field is authoritative; the legacy per-namespace
640
- // read stays as a fallback so a host that still serves the old service shape
641
- // keeps working (test hosts do exactly that).
642
- const raw = readCompressionDoc(config)
643
- ?? (presetsCtx?.get('settings') as { get?: (ns: never) => unknown } | undefined)
644
- ?.get?.(CONTEXT_COMPRESSION_SETTINGS_NAMESPACE as never)
645
- try {
646
- const record = structuredClone(raw) as Record<string, unknown> | undefined
647
- const threshold = record?.autoCompact as { thresholdPercent?: number } | undefined
648
- const value = typeof threshold?.thresholdPercent === 'number' ? threshold.thresholdPercent : 80
649
- return Number.isFinite(value) && value >= 50 && value <= 90 ? value : 80
650
- } catch {
651
- return 80
652
- }
653
- }
654
-
655
-