dsh-context-compression-improved 0.10.2 → 0.10.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (264) hide show
  1. package/.agents/plans/improve/checklist.md +32 -0
  2. package/.agents/plans/improve/findings.md +102 -0
  3. package/.agents/plans/improve/spec.md +53 -0
  4. package/.agents/plans/improve/tasks.md +70 -0
  5. package/.gitattributes +2 -0
  6. package/.githooks/pre-push +37 -0
  7. package/.github/workflows/ci.yml +39 -0
  8. package/CHANGELOG.de.md +580 -0
  9. package/CHANGELOG.es.md +588 -0
  10. package/CHANGELOG.fr.md +576 -0
  11. package/CHANGELOG.it.md +577 -0
  12. package/CHANGELOG.ja.md +261 -0
  13. package/CHANGELOG.ko.md +254 -0
  14. package/CHANGELOG.md +549 -0
  15. package/CHANGELOG.ru.md +554 -0
  16. package/CHANGELOG.zh.md +238 -0
  17. package/CONTRIBUTING.md +22 -0
  18. package/README.de.md +96 -0
  19. package/README.es.md +96 -0
  20. package/README.fr.md +96 -0
  21. package/README.it.md +96 -0
  22. package/README.ja.md +102 -0
  23. package/README.ko.md +102 -0
  24. package/README.md +110 -15
  25. package/README.ru.md +96 -0
  26. package/README.zh.md +104 -14
  27. package/SECURITY.md +18 -0
  28. package/THIRD_PARTY_NOTICES.md +7 -25
  29. package/assets/board.png +0 -0
  30. package/assets/context.png +0 -0
  31. package/docs/assets/context-compression-selector-profiles.jpg +0 -0
  32. package/docs/assets/context-compression-selector-settings.png +0 -0
  33. package/docs/compat-0.1.5-report.md +77 -0
  34. package/docs/installation.de.md +104 -0
  35. package/docs/installation.es.md +104 -0
  36. package/docs/installation.fr.md +104 -0
  37. package/docs/installation.it.md +104 -0
  38. package/docs/installation.ja.md +78 -0
  39. package/docs/installation.ko.md +78 -0
  40. package/docs/installation.md +103 -0
  41. package/docs/installation.ru.md +104 -0
  42. package/docs/installation.zh.md +100 -0
  43. package/docs/repair-log.md +657 -0
  44. package/eslint.config.js +30 -0
  45. package/package.json +116 -129
  46. package/packages/selector/LICENSE +21 -0
  47. package/packages/selector/README.md +26 -0
  48. package/packages/selector/README.zh.md +24 -0
  49. package/packages/selector/THIRD_PARTY_NOTICES.md +32 -0
  50. package/packages/selector/docs/history-tool-call-working-set-spec.md +112 -0
  51. package/packages/selector/docs/native-tool-result-selector-spec.md +34 -0
  52. package/packages/selector/docs/subagent-cache-reuse-spec.md +46 -0
  53. package/{dsh.plugin.json → packages/selector/dsh.plugin.json} +2 -2
  54. package/packages/selector/lib/style.css +350 -0
  55. package/packages/selector/package.json +178 -0
  56. package/packages/selector/screenshots.json +3 -0
  57. package/packages/selector/src/client/CompressionProfileControls.tsx +293 -0
  58. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -0
  59. package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -0
  60. package/packages/selector/src/client/CustomPolicyEditor.tsx +216 -0
  61. package/packages/selector/src/client/EstimatorControls.tsx +277 -0
  62. package/packages/selector/src/client/bridge-scope.ts +125 -0
  63. package/packages/selector/src/client/decode.ts +57 -0
  64. package/packages/selector/src/client/fab-pos.ts +71 -0
  65. package/packages/selector/src/client/index.ts +424 -0
  66. package/packages/selector/src/client/locales/de.ts +158 -0
  67. package/packages/selector/src/client/locales/es.ts +158 -0
  68. package/packages/selector/src/client/locales/fr.ts +158 -0
  69. package/packages/selector/src/client/locales/it.ts +158 -0
  70. package/packages/selector/src/client/locales/ja.ts +158 -0
  71. package/packages/selector/src/client/locales/ko.ts +158 -0
  72. package/packages/selector/src/client/locales/ru.ts +158 -0
  73. package/packages/selector/src/client/locales.ts +316 -0
  74. package/packages/selector/src/client/monitor-fab.ts +431 -0
  75. package/packages/selector/src/client/preset-options.ts +88 -0
  76. package/packages/selector/src/client/savings-card.tsx +269 -0
  77. package/packages/selector/src/client/scope-face.ts +24 -0
  78. package/packages/selector/src/client/settings-section.tsx +140 -0
  79. package/packages/selector/src/compat/host-generation.ts +96 -0
  80. package/packages/selector/src/compat/llm-messages.ts +50 -0
  81. package/packages/selector/src/compat/settings-lease.ts +108 -0
  82. package/packages/selector/src/compat/tool-result.ts +91 -0
  83. package/packages/selector/src/css-modules.d.ts +6 -0
  84. package/packages/selector/src/deepseek-v4-tokenizer.ts +205 -0
  85. package/packages/selector/src/estimator-catalog.ts +104 -0
  86. package/packages/selector/src/index.ts +890 -0
  87. package/packages/selector/src/invariant.ts +113 -0
  88. package/packages/selector/src/preset-overlay.ts +749 -0
  89. package/packages/selector/src/profiles.ts +431 -0
  90. package/packages/selector/src/pruner/content.ts +198 -0
  91. package/packages/selector/src/pruner/session.ts +97 -0
  92. package/packages/selector/src/pruner/state.ts +61 -0
  93. package/packages/selector/src/pruner/tuning.ts +23 -0
  94. package/packages/selector/src/pruner/types.ts +78 -0
  95. package/packages/selector/src/pruner.ts +2914 -0
  96. package/packages/selector/src/runtime/adaptive-cost.ts +205 -0
  97. package/packages/selector/src/runtime/audit.ts +320 -0
  98. package/packages/selector/src/runtime/config.ts +756 -0
  99. package/packages/selector/src/runtime/custom-policy.ts +278 -0
  100. package/packages/selector/src/runtime/deepseek-official-pricing.ts +298 -0
  101. package/packages/selector/src/runtime/deepseek-v4-vision-tokens.ts +254 -0
  102. package/packages/selector/src/runtime/display-prefs.ts +98 -0
  103. package/packages/selector/src/runtime/measurement.ts +444 -0
  104. package/packages/selector/src/runtime/monitor.ts +310 -0
  105. package/packages/selector/src/runtime/panel-command.ts +213 -0
  106. package/packages/selector/src/runtime/reducers.ts +1754 -0
  107. package/packages/selector/src/runtime/retrieve.ts +503 -0
  108. package/packages/selector/src/runtime/savings-integral.ts +117 -0
  109. package/packages/selector/src/runtime/savings-projection.ts +229 -0
  110. package/packages/selector/src/runtime/savings-verify.ts +446 -0
  111. package/packages/selector/src/runtime/savings.ts +526 -0
  112. package/packages/selector/src/runtime/session-events.ts +30 -0
  113. package/packages/selector/src/runtime/session-file-decode.ts +523 -0
  114. package/packages/selector/src/runtime/stats-backfill.ts +541 -0
  115. package/packages/selector/src/runtime/stats-db.ts +492 -0
  116. package/packages/selector/src/runtime/stats-schema.ts +123 -0
  117. package/packages/selector/src/runtime/stats-sync.ts +307 -0
  118. package/packages/selector/src/runtime/summary-command.ts +127 -0
  119. package/packages/selector/src/runtime/tail-trim.ts +176 -0
  120. package/packages/selector/src/runtime/token-count.ts +72 -0
  121. package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +233 -0
  122. package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +204 -0
  123. package/packages/selector/src/runtime/tokenpilot/advisor.ts +419 -0
  124. package/packages/selector/src/runtime/tokenpilot/benefit.ts +200 -0
  125. package/packages/selector/src/runtime/tokenpilot/dedup.ts +81 -0
  126. package/packages/selector/src/runtime/tokenpilot/estimator.ts +151 -0
  127. package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
  128. package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
  129. package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
  130. package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
  131. package/packages/selector/src/runtime/tokenpilot/locator.ts +128 -0
  132. package/packages/selector/src/runtime/tokenpilot/read-state.ts +98 -0
  133. package/packages/selector/src/runtime/tokenpilot/sidechannel.ts +303 -0
  134. package/packages/selector/src/runtime/toolclass.ts +103 -0
  135. package/packages/selector/src/runtime/types.ts +365 -0
  136. package/packages/selector/src/runtime/value.ts +48 -0
  137. package/packages/selector/src/settings-bridge.ts +175 -0
  138. package/packages/selector/tests/advisor-report.host.spec.ts +223 -0
  139. package/packages/selector/tests/auto-compact.client.spec.tsx +214 -0
  140. package/packages/selector/tests/built/client-artifact.spec.ts +56 -0
  141. package/packages/selector/tests/cache-prefix-audit.spec.ts +123 -0
  142. package/packages/selector/tests/code-skeleton.client.spec.ts +98 -0
  143. package/packages/selector/tests/compat/compat-narrow-waist.spec.ts +150 -0
  144. package/packages/selector/tests/custom-contract.client.spec.ts +226 -0
  145. package/packages/selector/tests/estimator-catalog.spec.ts +70 -0
  146. package/packages/selector/tests/estimator-channel.client.spec.tsx +253 -0
  147. package/packages/selector/tests/estimator-route-registration.host.spec.ts +202 -0
  148. package/packages/selector/tests/fab-pos.client.spec.ts +47 -0
  149. package/packages/selector/tests/helpers/legacy-namespace.ts +35 -0
  150. package/packages/selector/tests/helpers/legacy-settings/index.ts +15 -0
  151. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.d.ts +41 -0
  152. package/packages/selector/tests/helpers/legacy-settings/legacy/provider.js +647 -0
  153. package/packages/selector/tests/helpers/legacy-settings/legacy/redact.js +78 -0
  154. package/packages/selector/tests/helpers/legacy-settings/legacy/util-values.js +234 -0
  155. package/packages/selector/tests/host-preset-overlay.host.spec.ts +204 -0
  156. package/packages/selector/tests/monitor-fab.client.spec.ts +240 -0
  157. package/packages/selector/tests/preset-options-write.client.spec.ts +192 -0
  158. package/packages/selector/tests/preset-overlay-loader.e2e.host.spec.ts +200 -0
  159. package/packages/selector/tests/preset-overlay.host.spec.ts +246 -0
  160. package/packages/selector/tests/profiles.client.spec.tsx +436 -0
  161. package/packages/selector/tests/public/package-contract.client.spec.ts +86 -0
  162. package/packages/selector/tests/runtime/adaptive-cost.spec.ts +167 -0
  163. package/packages/selector/tests/runtime/advice-never-withholds.host.spec.ts +230 -0
  164. package/packages/selector/tests/runtime/advisor-invariant.spec.ts +272 -0
  165. package/packages/selector/tests/runtime/advisor.spec.ts +226 -0
  166. package/packages/selector/tests/runtime/audit.spec.ts +275 -0
  167. package/packages/selector/tests/runtime/auto-compact-config.spec.ts +523 -0
  168. package/packages/selector/tests/runtime/char-basis.spec.ts +30 -0
  169. package/packages/selector/tests/runtime/code-skeleton.spec.ts +152 -0
  170. package/packages/selector/tests/runtime/deepseek-official-pricing.spec.ts +186 -0
  171. package/packages/selector/tests/runtime/deepseek-v4-tokenizer.spec.ts +122 -0
  172. package/packages/selector/tests/runtime/deepseek-v4-vision-tokens.spec.ts +122 -0
  173. package/packages/selector/tests/runtime/deprecated-preset-options.spec.ts +96 -0
  174. package/packages/selector/tests/runtime/fixtures/profile-baseline.json +273 -0
  175. package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
  176. package/packages/selector/tests/runtime/fixtures/tokenizer-golden.json +106 -0
  177. package/packages/selector/tests/runtime/fixtures/vision-golden.json +459 -0
  178. package/packages/selector/tests/runtime/frequency-longstrings.spec.ts +74 -0
  179. package/packages/selector/tests/runtime/fresh-gate.spec.ts +43 -0
  180. package/packages/selector/tests/runtime/html-reducer.spec.ts +212 -0
  181. package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
  182. package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
  183. package/packages/selector/tests/runtime/jsonl-reducer.spec.ts +79 -0
  184. package/packages/selector/tests/runtime/line-mapping.spec.ts +153 -0
  185. package/packages/selector/tests/runtime/monitor.spec.ts +354 -0
  186. package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
  187. package/packages/selector/tests/runtime/prose-reducers.spec.ts +133 -0
  188. package/packages/selector/tests/runtime/public/public-runtime.spec.ts +2781 -0
  189. package/packages/selector/tests/runtime/read-input-cap.spec.ts +33 -0
  190. package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
  191. package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
  192. package/packages/selector/tests/runtime/savings-projection.spec.ts +89 -0
  193. package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
  194. package/packages/selector/tests/runtime/savings.spec.ts +139 -0
  195. package/packages/selector/tests/runtime/search-reducer.spec.ts +110 -0
  196. package/packages/selector/tests/runtime/session-events.spec.ts +27 -0
  197. package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
  198. package/packages/selector/tests/runtime/settings-unwrap.spec.ts +58 -0
  199. package/packages/selector/tests/runtime/sidechannel.spec.ts +241 -0
  200. package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
  201. package/packages/selector/tests/runtime/stats-backfill.spec.ts +348 -0
  202. package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
  203. package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
  204. package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
  205. package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
  206. package/packages/selector/tests/runtime/toc-and-bundled.spec.ts +159 -0
  207. package/packages/selector/tests/runtime/tokenizer-golden.spec.ts +53 -0
  208. package/packages/selector/tests/runtime/tokenpilot/benefit.spec.ts +217 -0
  209. package/packages/selector/tests/runtime/tokenpilot/dedup.spec.ts +52 -0
  210. package/packages/selector/tests/runtime/tokenpilot/estimator.spec.ts +79 -0
  211. package/packages/selector/tests/runtime/tokenpilot/locator.spec.ts +76 -0
  212. package/packages/selector/tests/runtime/tokenpilot/profile-baseline.spec.ts +119 -0
  213. package/packages/selector/tests/runtime/tokenpilot/read-state.spec.ts +82 -0
  214. package/packages/selector/tests/runtime/toolclass.spec.ts +156 -0
  215. package/packages/selector/tests/runtime/value.spec.ts +23 -0
  216. package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
  217. package/packages/selector/tests/settings-seat.client.spec.ts +215 -0
  218. package/packages/selector/tests/standing-generation.host.spec.ts +724 -0
  219. package/packages/selector/tests/subagent-cache-reuse.host.spec.ts +269 -0
  220. package/packages/selector/tests/support/cache-prefix-audit.ts +105 -0
  221. package/packages/selector/tests/support/mock-adapter.ts +37 -0
  222. package/packages/selector/tests/support/ui-primitives.tsx +34 -0
  223. package/packages/selector/tsconfig.json +11 -0
  224. package/packages/selector/tsdown.client.config.ts +102 -0
  225. package/packages/selector/tsdown.config.ts +20 -0
  226. package/pnpm-workspace.yaml +76 -0
  227. package/screenshots.json +6 -3
  228. package/scripts/capture-profile-baseline.mjs +42 -0
  229. package/scripts/cell-browser-e2e.mjs +354 -0
  230. package/scripts/generate-tokenizer-fixtures.py +81 -0
  231. package/scripts/generate-vision-fixtures.py +208 -0
  232. package/scripts/hosts.mjs +78 -0
  233. package/scripts/packed-components-smoke.mjs +763 -0
  234. package/scripts/packed-install-e2e.mjs +1346 -0
  235. package/scripts/sync-hosts.mjs +174 -0
  236. package/scripts/toolclass-corpus-replay.mjs +281 -0
  237. package/scripts/verify-release.mjs +338 -0
  238. package/tests/TEST_INVENTORY.md +41 -0
  239. package/tsconfig.base.json +18 -0
  240. package/tsconfig.json +7 -0
  241. package/tsconfig.tests.json +15 -0
  242. package/vitest.built.config.ts +9 -0
  243. package/vitest.config.ts +54 -0
  244. /package/{assets → packages/selector/assets}/deepseek-v4/LICENSE.DeepSeek-V4-Pro.txt +0 -0
  245. /package/{assets → packages/selector/assets}/deepseek-v4/manifest.json +0 -0
  246. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer.json +0 -0
  247. /package/{assets → packages/selector/assets}/deepseek-v4/tokenizer_config.json +0 -0
  248. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/LICENSE.DeepSeek-V4-Flash-Vision-Exp.txt +0 -0
  249. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/manifest.json +0 -0
  250. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer.json +0 -0
  251. /package/{assets → packages/selector/assets}/deepseek-v4-vision-exp/tokenizer_config.json +0 -0
  252. /package/{cordis.patch.yml → packages/selector/cordis.patch.yml} +0 -0
  253. /package/{lib → packages/selector/lib}/client.d.ts +0 -0
  254. /package/{lib → packages/selector/lib}/client.js +0 -0
  255. /package/{lib → packages/selector/lib}/index.d.ts +0 -0
  256. /package/{lib → packages/selector/lib}/index.js +0 -0
  257. /package/{lib → packages/selector/lib}/invariant.d.ts +0 -0
  258. /package/{lib → packages/selector/lib}/invariant.js +0 -0
  259. /package/{lib → packages/selector/lib}/profiles.d.ts +0 -0
  260. /package/{lib → packages/selector/lib}/pruner.d.ts +0 -0
  261. /package/{lib → packages/selector/lib}/pruner.js +0 -0
  262. /package/{lib → packages/selector/lib}/savings-integral.js +0 -0
  263. /package/{lib → packages/selector/lib}/tail-trim.js +0 -0
  264. /package/{lib → packages/selector/lib}/tool-result.js +0 -0
@@ -0,0 +1,269 @@
1
+ /**
2
+ * 节省统计卡片(设置分节内,只读):存量(本进程口径) + 累计(按 N 次 call) +
3
+ * 省钱估计三行并存(T26),会话账本服务端分页(T24 数据面),持久化徽标与降级
4
+ * 标注,显示偏好经载荷 displayPrefs 实时拾取(T32,/ccip 的落点)。
5
+ * 数据源 = `/api/.../savings`(存量)与 `/api/.../savings/sessions`(分页面板),
6
+ * 5s 自调度轮询,失败静默——统计卡片永不打扰设置页主功能。
7
+ *
8
+ * @module dsh-context-compression-improved/client/savings-card
9
+ */
10
+ import { useEffect, useRef, useState } from 'react'
11
+ import css from './CompressionProfileSelector.module.css'
12
+ import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
13
+
14
+ const SAVINGS_ROUTE = '/api/dsh-context-compression-improved/savings'
15
+ const SESSIONS_ROUTE = '/api/dsh-context-compression-improved/savings/sessions'
16
+ const PAGE_SIZE = 20
17
+
18
+ interface BasisPair { exact: number; estimated: number }
19
+ interface IntegralTotals { netExact: number; netEstimated: number; cachedInput: number; uncachedInput: number; calls: number }
20
+ interface DisplayPrefs {
21
+ rows: { stock: boolean; total: boolean; money: boolean }
22
+ mode: 'full' | 'compact'
23
+ focusSessionId: string | null
24
+ }
25
+
26
+ interface SavingsSnapshot {
27
+ ok?: boolean
28
+ startedAt: string
29
+ sessions: number
30
+ gross: BasisPair
31
+ offsets: BasisPair
32
+ net: BasisPair
33
+ perComponent: Array<{ component: string; tokens: number; basis: string; kind: string }>
34
+ recentOffsets: Array<{ component: string; tokens: number; basis: string; at: string; note?: string }>
35
+ usage?: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; cacheHitRate: number | null }
36
+ perSession?: Array<{ sessionId: string; net: BasisPair; requests: number; cacheHitRate: number | null }>
37
+ pricing?: { currency: string; actualCost?: string; estimatedSavedCost?: string }
38
+ }
39
+
40
+ interface SessionsPayload {
41
+ ok?: boolean
42
+ persisted: { persisted: true; driver: string } | { persisted: false; reason: string }
43
+ displayPrefs: DisplayPrefs
44
+ total: number
45
+ offset: number
46
+ limit: number
47
+ integralTotal: IntegralTotals
48
+ integralMoney?: { decimal: string; currency: string }
49
+ sessions: Array<{
50
+ sessionId: string
51
+ net: BasisPair
52
+ integral: IntegralTotals
53
+ money?: { decimal: string; currency: string }
54
+ source: string
55
+ liveStock?: BasisPair
56
+ }>
57
+ liveOnly: Array<{ sessionId: string; net: BasisPair; requests: number; cacheHitRate: number | null }>
58
+ }
59
+
60
+ export interface SavingsCardProps {
61
+ /** locale 文案函数(与设置分节同一 translator,键受字典类型约束)。 */
62
+ t: CompressionProfileSelectorProps['t']
63
+ }
64
+
65
+ function fmt(n: number): string {
66
+ return n.toLocaleString('en-US')
67
+ }
68
+
69
+ /** 节省统计卡片:存量/累计双口径 + 会话账本分页;口径分列永不混算。 */
70
+ export function SavingsCard({ t }: SavingsCardProps) {
71
+ const [snap, setSnap] = useState<SavingsSnapshot | null>(null)
72
+ const [panel, setPanel] = useState<SessionsPayload | null>(null)
73
+ const [offset, setOffset] = useState(0)
74
+ const offsetRef = useRef(0)
75
+ offsetRef.current = offset
76
+ const stopped = useRef(false)
77
+ useEffect(() => {
78
+ stopped.current = false
79
+ const tick = async (): Promise<void> => {
80
+ try {
81
+ const response = await fetch(SAVINGS_ROUTE, { headers: { 'cache-control': 'no-cache' } })
82
+ if (response.ok) {
83
+ const data = (await response.json()) as SavingsSnapshot
84
+ if (data?.startedAt !== undefined && !stopped.current) setSnap(data)
85
+ }
86
+ } catch {
87
+ /* 路由未注册/网络不可用:静默 */
88
+ }
89
+ try {
90
+ const response = await fetch(`${SESSIONS_ROUTE}?offset=${String(offsetRef.current)}&limit=${String(PAGE_SIZE)}`, { headers: { 'cache-control': 'no-cache' } })
91
+ if (response.ok) {
92
+ const data = (await response.json()) as SessionsPayload
93
+ if (data?.ok === true && !stopped.current) setPanel(data)
94
+ }
95
+ } catch {
96
+ /* 分页面板缺席(老版本宿主):静默,存量口径照常显示 */
97
+ }
98
+ if (!stopped.current) setTimeout(tick, 5000)
99
+ }
100
+ void tick()
101
+ return () => {
102
+ stopped.current = true
103
+ }
104
+ }, [offset])
105
+
106
+ const prefs = panel?.displayPrefs
107
+ const stockVisible = prefs?.rows.stock !== false
108
+ const totalVisible = prefs?.rows.total !== false
109
+ const moneyVisible = prefs?.rows.money !== false
110
+ const compact = prefs?.mode === 'compact'
111
+ const focus = prefs?.focusSessionId ?? null
112
+ const persisted = panel?.persisted?.persisted === true
113
+
114
+ const integral = panel?.integralTotal
115
+ const stockEmpty = snap === null || (snap.gross.exact + snap.gross.estimated === 0)
116
+ const integralEmpty = integral === undefined || integral.calls === 0
117
+ // 桩数据/部分载荷可能缺数组字段:统一兜底,账本判据与渲染共用同一视图。
118
+ const panelSessions = panel?.sessions ?? []
119
+ const panelLiveOnly = panel?.liveOnly ?? []
120
+ // 本会话存量/累计为零时若账本已有回填数据,仍要落全卡渲染——早退会把
121
+ // 会话账本一起吞掉(存量空 ≠ 无历史节省)。
122
+ const ledgerReady = panelSessions.length > 0 || panelLiveOnly.length > 1
123
+ if (stockEmpty && integralEmpty && !ledgerReady) {
124
+ return <div className={css.pricing}>{t('savings.empty')}</div>
125
+ }
126
+ const hasExact = snap !== null && (snap.gross.exact > 0 || snap.offsets.exact > 0)
127
+ const hasEstimated = snap !== null && (snap.gross.estimated > 0 || snap.offsets.estimated > 0)
128
+ const netTone = snap !== null && (snap.net.exact + snap.net.estimated) >= 0 ? css.savingsNetPositive : css.savingsNetNegative
129
+ return (
130
+ <div className={`${css.savingsCard}`} data-testid="savings-card">
131
+ <div className={css.savingsRow}>
132
+ <span>{t('savings.title')}</span>
133
+ {panel === null ? null : (
134
+ <span className={css.savingsMuted} data-testid="savings-persisted">
135
+ {persisted ? `✓ ${t('savings.persisted')}` : `⚠ ${t('savings.degraded')}`}
136
+ </span>
137
+ )}
138
+ </div>
139
+ {stockVisible && snap !== null ? (
140
+ <>
141
+ {hasExact ? (
142
+ <div className={`${css.savingsRow} ${netTone}`} data-testid="savings-stock-exact">
143
+ <span>{t('savings.netExact')}</span>
144
+ <strong>{fmt(snap.net.exact)}</strong>
145
+ </div>
146
+ ) : null}
147
+ {hasEstimated ? (
148
+ <div className={css.savingsRow} data-testid="savings-stock-estimated">
149
+ <span>{t('savings.netEstimated')}</span>
150
+ <strong>{fmt(snap.net.estimated)}</strong>
151
+ </div>
152
+ ) : null}
153
+ {!compact ? (
154
+ <>
155
+ <div className={css.savingsRow}>
156
+ <span className={css.savingsMuted}>{t('savings.gross')}</span>
157
+ <span className={css.savingsMuted}>
158
+ {hasExact ? `✓ ${fmt(snap.gross.exact)}` : ''}{hasExact && hasEstimated ? ' · ' : ''}{hasEstimated ? `≈ ${fmt(snap.gross.estimated)}` : ''}
159
+ </span>
160
+ </div>
161
+ <div className={css.savingsRow}>
162
+ <span className={css.savingsMuted}>{t('savings.offsets')}</span>
163
+ <span className={css.savingsMuted}>
164
+ {hasExact ? `−${fmt(snap.offsets.exact)}` : ''}{hasExact && hasEstimated ? ' · ' : ''}{hasEstimated ? `−${fmt(snap.offsets.estimated)}` : ''}
165
+ </span>
166
+ </div>
167
+ </>
168
+ ) : null}
169
+ </>
170
+ ) : null}
171
+ {totalVisible && integral !== undefined && integral.calls > 0 ? (
172
+ <div className={css.savingsRow} data-testid="savings-cumulative">
173
+ <span>{t('savings.cumulative').replace('N', fmt(integral.calls))}</span>
174
+ <strong>
175
+ {integral.netExact !== 0 ? fmt(integral.netExact) : ''}{integral.netExact !== 0 && integral.netEstimated !== 0 ? ' · ' : ''}{integral.netEstimated !== 0 ? `≈ ${fmt(integral.netEstimated)}` : ''}
176
+ </strong>
177
+ </div>
178
+ ) : null}
179
+ {moneyVisible && panel?.integralMoney !== undefined ? (
180
+ <div className={css.savingsRow} data-testid="savings-money">
181
+ <span className={css.savingsMuted}>{t('savings.money')}</span>
182
+ <span className={css.savingsMuted}>{panel.integralMoney.currency} {panel.integralMoney.decimal}</span>
183
+ </div>
184
+ ) : null}
185
+ {stockVisible && snap !== null && !compact && snap.usage !== undefined && snap.usage.requests > 0 ? (
186
+ <>
187
+ <div className={css.savingsRow}>
188
+ <span className={css.savingsMuted}>{t('savings.requests')}</span>
189
+ <span className={css.savingsMuted}>{fmt(snap.usage.requests)}</span>
190
+ </div>
191
+ <div className={css.savingsRow}>
192
+ <span className={css.savingsMuted}>{t('savings.cacheHit')}</span>
193
+ <span className={css.savingsMuted}>
194
+ {snap.usage.cacheHitRate === null ? '–' : `${Math.round(snap.usage.cacheHitRate * 100)}%`}
195
+ </span>
196
+ </div>
197
+ {snap.pricing?.actualCost !== undefined ? (
198
+ <div className={css.savingsRow}>
199
+ <span className={css.savingsMuted}>{t('savings.actualCost')}</span>
200
+ <span className={css.savingsMuted}>{snap.pricing.currency} {snap.pricing.actualCost}</span>
201
+ </div>
202
+ ) : null}
203
+ {snap.pricing?.estimatedSavedCost !== undefined ? (
204
+ <div className={css.savingsRow}>
205
+ <span className={css.savingsMuted}>{t('savings.savedMoney')}</span>
206
+ <span className={css.savingsMuted}>{snap.pricing.currency} {snap.pricing.estimatedSavedCost}</span>
207
+ </div>
208
+ ) : null}
209
+ </>
210
+ ) : null}
211
+ {ledgerReady ? (
212
+ <div className={css.savingsBreakdown} data-testid="savings-session-list">
213
+ <div className={css.savingsRow}>
214
+ <span className={css.savingsMuted}>{t('savings.sessions')}{panel !== null && panel.total > 0 ? ` (${fmt(panel.total)})` : ''}</span>
215
+ <span className={css.savingsMuted}>
216
+ {panel !== null && (panel.total > panelSessions.length || panel.offset > 0) ? (
217
+ <>
218
+ <a
219
+ href="#"
220
+ data-testid="savings-page-prev"
221
+ onClick={(event) => { event.preventDefault(); setOffset(value => Math.max(0, value - PAGE_SIZE)) }}
222
+ >{t('savings.pagePrev')}</a>
223
+ {' · '}
224
+ </>
225
+ ) : null}
226
+ {panel !== null && panel.offset + panelSessions.length < panel.total ? (
227
+ <a
228
+ href="#"
229
+ data-testid="savings-page-next"
230
+ onClick={(event) => { event.preventDefault(); setOffset(value => value + PAGE_SIZE) }}
231
+ >{t('savings.pageNext')}</a>
232
+ ) : null}
233
+ </span>
234
+ </div>
235
+ {panelSessions.slice(0, 8).map(row => (
236
+ <div key={row.sessionId} className={css.savingsRow}>
237
+ <span className={css.savingsMuted}>
238
+ {row.sessionId === focus ? `◎ ${t('savings.focus')} · ` : ''}{row.sessionId.slice(0, 8)}… · {fmt(row.integral.calls)} calls
239
+ </span>
240
+ <span className={css.savingsMuted}>
241
+ {fmt(row.net.exact)}{row.money !== undefined ? ` · ${row.money.currency} ${row.money.decimal}` : ''}
242
+ </span>
243
+ </div>
244
+ ))}
245
+ {panelLiveOnly.slice(0, 3).map(row => (
246
+ <div key={row.sessionId} className={css.savingsRow}>
247
+ <span className={css.savingsMuted}>{row.sessionId.slice(0, 8)}… · {t('savings.netEstimated')}</span>
248
+ <span className={css.savingsMuted}>{fmt(row.net.exact + row.net.estimated)}</span>
249
+ </div>
250
+ ))}
251
+ </div>
252
+ ) : null}
253
+ {stockVisible && snap !== null && !compact && snap.perComponent.length > 0 ? (
254
+ <div className={css.savingsBreakdown}>
255
+ {snap.perComponent.slice(0, 6).map((row) => (
256
+ <div key={`${row.kind}:${row.component}:${row.basis}`} className={css.savingsRow}>
257
+ <span className={css.savingsMuted}>
258
+ {row.kind === 'offset' ? '−' : '+'} {row.component}
259
+ <small> ({row.basis === 'exact-tokenizer' ? t('savings.basisExact') : t('savings.basisEstimated')})</small>
260
+ </span>
261
+ <span className={css.savingsMuted}>{fmt(row.tokens)}</span>
262
+ </div>
263
+ ))}
264
+ </div>
265
+ ) : null}
266
+ <div className={css.savingsNote}>{t('savings.basisNote')}</div>
267
+ </div>
268
+ )
269
+ }
@@ -0,0 +1,24 @@
1
+ /**
2
+ * 0.1.7-rc.2 stopped exporting `SettingsScope` from
3
+ * `@deepseek-ai/dsh-client-ui-settings/client`; the structural face the
4
+ * selector consumes lives here instead (getSnapshot shape mirrors the 0.1.7
5
+ * `ConfigFormSnapshot` minus the parts the components never read).
6
+ */
7
+ /** The projected snapshot shape (identity-stable between changes — React #185). */
8
+ export interface ScopeSnapshot<T> {
9
+ status: 'loading' | 'ready' | 'unavailable'
10
+ value: T | undefined
11
+ revision: number | undefined
12
+ writable: boolean
13
+ base: unknown
14
+ user: unknown
15
+ mode: 'host' | 'memory'
16
+ }
17
+
18
+ export interface SettingsScope<T> {
19
+ getSnapshot(): ScopeSnapshot<T>
20
+ subscribe(listener: () => void): () => void
21
+ set(field: string, value: unknown): Promise<boolean>
22
+ unset(field: string): Promise<boolean>
23
+ mutate?(ops: readonly { path: readonly string[]; op: string; value?: unknown }[]): Promise<boolean>
24
+ }
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Full-page Settings surface backed by the same durable selector state.
3
+ *
4
+ * Extracted from CompressionProfileSelector.tsx to reduce god-module size.
5
+ *
6
+ * @module dsh-context-compression-improved/client/settings-section
7
+ */
8
+
9
+ import { useEffect, useState } from 'react'
10
+ import css from './CompressionProfileSelector.module.css'
11
+ import {
12
+ AUTO_COMPACT_THRESHOLD_LIMITS,
13
+ COMPRESSION_PROFILES,
14
+ type CompressionProfile,
15
+ type CustomCompressionPolicyV3,
16
+ } from '../profiles.ts'
17
+ import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
18
+ import { AutoCompactThresholdControls, CodeSkeletonControls, IntentSummaryControls, MonitorPanelControls } from './CompressionProfileControls.tsx'
19
+ import { EstimatorControls, EstimatorInactiveNotice } from './EstimatorControls.tsx'
20
+ import { CustomPolicyEditor, editableCustom } from './CustomPolicyEditor.tsx'
21
+ import { SavingsCard } from './savings-card'
22
+
23
+ /** Full-page Settings surface backed by the same durable selector state. */
24
+ export function ContextCompressionSettingsSection(props: CompressionProfileSelectorProps) {
25
+ return <SettingsCompressionProfileControls {...props} />
26
+ }
27
+
28
+ export function SettingsCompressionProfileControls({
29
+ useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary, saveMonitorPanel,
30
+ savePresetOptions, t,
31
+ }: CompressionProfileSelectorProps) {
32
+ const state = useCompression(snapshot => snapshot)
33
+ // Harness 0.1.5 dropped browser-side agentPreset from session summaries, so
34
+ // the old Minimal-preset gate has no data source; the selector stays enabled.
35
+ const selectorAvailable = true
36
+ const [saving, setSaving] = useState(false)
37
+ const [saveError, setSaveError] = useState<string | null>(null)
38
+ const [draft, setDraft] = useState<CustomCompressionPolicyV3 | null>(null)
39
+ const current = state.value?.profile ?? 'balanced'
40
+ useEffect(() => {
41
+ const custom = state.value?.custom
42
+ setDraft(current === 'custom' && custom !== undefined ? editableCustom(custom) : null)
43
+ }, [current, state.value?.custom])
44
+ if (state.status === 'unavailable') return null
45
+
46
+ const busy = state.status === 'loading' || saving
47
+ const selectProfile = (profile: CompressionProfile): void => {
48
+ if (!selectorAvailable || !state.writable || profile === current) return
49
+ setSaveError(null)
50
+ setSaving(true)
51
+ void select(profile).then(
52
+ () => { setSaving(false) },
53
+ (error: unknown) => {
54
+ setSaving(false)
55
+ setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
56
+ },
57
+ )
58
+ }
59
+ const settle = (operation: () => Promise<void>): void => {
60
+ setSaveError(null)
61
+ setSaving(true)
62
+ void operation().then(
63
+ () => { setSaving(false) },
64
+ (error: unknown) => {
65
+ setSaving(false)
66
+ setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
67
+ },
68
+ )
69
+ }
70
+
71
+ return (
72
+ <section className={css.settingsSection}>
73
+ <h2 className={css.settingsTitle}>{t('settings.title')}</h2>
74
+ <p className={css.settingsDescription}>{t('settings.description')}</p>
75
+ {selectorAvailable ? (
76
+ <div className={css.profileGrid} aria-label={t('label')}>
77
+ {COMPRESSION_PROFILES.map((profile) => {
78
+ const selected = profile === current
79
+ return (
80
+ <button key={profile} type="button" className={css.profileCard} aria-pressed={selected}
81
+ disabled={busy || !state.writable} onClick={() => { selectProfile(profile) }}>
82
+ <span className={css.profileCardTop}>
83
+ <span className={css.profileCardTitle}>{t(`profile.${profile}`)}</span>
84
+ {selected ? <span className={css.profileCurrent}>{t('profile.current')}</span> : null}
85
+ </span>
86
+ <span className={css.profileCardDetail}>{t(`detail.${profile}`)}</span>
87
+ </button>
88
+ )
89
+ })}
90
+ </div>
91
+ ) : <div className={css.unavailable} role="status">{t('status.minimalUnavailable')}</div>}
92
+ <AutoCompactThresholdControls
93
+ value={state.value?.autoCompact?.thresholdPercent ?? AUTO_COMPACT_THRESHOLD_LIMITS.default}
94
+ disabled={busy || !state.writable || !selectorAvailable}
95
+ save={saveAutoCompact}
96
+ settle={settle}
97
+ t={t}
98
+ />
99
+ <CodeSkeletonControls
100
+ value={state.value?.codeSkeleton?.enabled ?? false}
101
+ disabled={busy || !state.writable || !selectorAvailable}
102
+ save={saveCodeSkeleton}
103
+ settle={settle}
104
+ t={t}
105
+ />
106
+ <IntentSummaryControls
107
+ value={state.value?.intentSummary?.enabled ?? false}
108
+ disabled={busy || !state.writable || !selectorAvailable}
109
+ save={saveIntentSummary}
110
+ settle={settle}
111
+ t={t}
112
+ />
113
+ <MonitorPanelControls
114
+ value={state.value?.monitorPanel?.enabled ?? false}
115
+ disabled={busy || !state.writable || !selectorAvailable}
116
+ save={saveMonitorPanel}
117
+ settle={settle}
118
+ t={t}
119
+ />
120
+ {current !== 'tokenpilot-inspired' ? (
121
+ <EstimatorInactiveNotice profile={t(`profile.${current}`)} t={t} />
122
+ ) : (
123
+ <EstimatorControls
124
+ options={state.value?.presetOptions ?? {}}
125
+ disabled={busy || !state.writable || !selectorAvailable}
126
+ save={savePresetOptions}
127
+ settle={settle}
128
+ t={t}
129
+ />
130
+ )}
131
+ <SavingsCard t={t} />
132
+ <div className={css.pricing}>{t('pricing.disclosure')}</div>
133
+ {current !== 'custom' || draft === null || !selectorAvailable ? null : (
134
+ <CustomPolicyEditor value={draft} disabled={busy || !state.writable} setValue={setDraft}
135
+ save={() => saveCustom(structuredClone(draft))} reset={resetCustom} settle={settle} t={t} />
136
+ )}
137
+ {saveError === null ? null : <div className={css.error} role="alert">{saveError}</div>}
138
+ </section>
139
+ )
140
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * Host generation probe — the ONE narrow-waist version read in the server
3
+ * plane. Capability-based, never reads plugin-local node_modules (family
4
+ * rule, enum-peer INDEX §C): a settings service that still exposes
5
+ * `register` is a pre-0.1.7 host (0.1.0–0.1.5 lines, dsh-settings pack
6
+ * evidence); from 0.1.7-rc.1 the service drops register entirely (probe
7
+ * roundtrip: methods all undefined) and settings live in the loader-managed
8
+ * entry config.
9
+ *
10
+ * Client-side code must NOT use this module: per audit P1-9 the client picks
11
+ * its data path by which scoped sub-inject resolves (configForms arm = Gen D
12
+ * upgrade; bridge transport is the default that works everywhere).
13
+ */
14
+
15
+ export type HostGeneration = 'legacy' | 'modern'
16
+
17
+ let cached: HostGeneration | undefined
18
+
19
+ /**
20
+ * Pure classifier from a RESOLVED settings service face. A service that still
21
+ * exposes `register` is a pre-0.1.7 host (0.1.0–0.1.5 lines, dsh-settings pack
22
+ * evidence — verified on the real 0.1.0-rc.2 host: `register(ns, schema,
23
+ * options)` at dsh-settings/lib/index.js:311); from 0.1.7-rc.1 the service
24
+ * drops register entirely and settings live in the loader-managed entry
25
+ * config.
26
+ */
27
+ export function classifySettingsFace(settings: unknown): HostGeneration {
28
+ return typeof (settings as { register?: unknown } | null)?.register === 'function' ? 'legacy' : 'modern'
29
+ }
30
+
31
+ /**
32
+ * Probe the host generation from the settings service face.
33
+ *
34
+ * A verdict is only CACHED from a resolved service object. Rows compose
35
+ * before host services on every line (measured: the wire-time probe on a real
36
+ * 0.1.0-rc.2 cell saw no settings service yet and the old code cached
37
+ * 'modern' forever — the legacy lease arm went dead on the exact line it was
38
+ * built for). While the service is absent the answer is a provisional
39
+ * 'modern' and deliberately uncached, so the definitive
40
+ * `noteResolvedSettingsService` evidence can still flip it.
41
+ */
42
+ export function detectHostGeneration(ctx: { get(name: string): unknown }): HostGeneration {
43
+ if (cached !== undefined) return cached
44
+ let settings: unknown
45
+ try {
46
+ settings = ctx.get('settings')
47
+ } catch {
48
+ return 'modern'
49
+ }
50
+ if (settings === null || typeof settings !== 'object') return 'modern'
51
+ cached = classifySettingsFace(settings)
52
+ return cached
53
+ }
54
+
55
+ /**
56
+ * Definitive verdict from the resolved service (evidence observed, not
57
+ * guessed): the settings inject callback calls this once the service has
58
+ * actually composed. Always (re)writes the cache — a provisional earlier
59
+ * verdict must not survive real evidence.
60
+ */
61
+ export function noteResolvedSettingsService(settings: unknown): HostGeneration {
62
+ cached = classifySettingsFace(settings)
63
+ return cached
64
+ }
65
+
66
+ /**
67
+ * Server-plane snapshot for code paths that hold no ctx (the tool-result
68
+ * adapters). The bridge's inject callback has already noted the resolved
69
+ * service by the time any session message flows, so this reads real evidence
70
+ * on every line; without it the only safe answer is the provisional default.
71
+ */
72
+ export function hostGenerationSnapshot(): HostGeneration {
73
+ return cached ?? 'modern'
74
+ }
75
+
76
+ /** Test seam: reset the cached probe (unit tests only). */
77
+ export function resetHostGenerationCache(): void {
78
+ cached = undefined
79
+ }
80
+
81
+ /**
82
+ * Diagnostics sink by generation: measured on the 0.1.2 host the cordis
83
+ * logger prints nothing in the `dsh web` terminal, so legacy lines report
84
+ * through console; modern hosts keep the service logger.
85
+ */
86
+ export interface CompatLog {
87
+ (message: string, ...rest: unknown[]): void
88
+ }
89
+
90
+ export function compatLog(ctx: { get(name: string): unknown; logger?: Record<'info' | 'warn', (...rest: unknown[]) => void> }, level: 'info' | 'warn' = 'info'): CompatLog {
91
+ if (detectHostGeneration(ctx) === 'legacy') {
92
+ return (message, ...rest) => console[level](`[dsh-context-compression-improved] ${message}`, ...rest)
93
+ }
94
+ const sink = ctx.logger?.[level]?.bind(ctx.logger) ?? ((...rest: unknown[]) => console[level](...rest))
95
+ return (message, ...rest) => sink(`[dsh-context-compression-improved] ${message}`, ...rest)
96
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Local stand-ins for the two `@deepseek-ai/dsh-llm` message factories the
3
+ * pruner and TailTrim hot paths need. The package is an OPTIONAL peer — the
4
+ * official-clone profile in the packed-install e2e (and any host line that
5
+ * stops shipping it into a plugin's module graph) does not resolve it, and a
6
+ * static value import then crashes the whole plugin at module-load time with
7
+ * ERR_MODULE_NOT_FOUND. This mirrors the 0.9.3 pruner soft-import decision:
8
+ * the semantics are deliberately tiny and stable (deep clone → brand a fresh
9
+ * id → deep freeze), so the plugin carries its own copy instead of importing
10
+ * the host's.
11
+ */
12
+ import type { UserMessage } from '@deepseek-ai/dsh-llm'
13
+
14
+ /** Recursive `Object.freeze` over own enumerable properties (arrays included). */
15
+ function deepFreeze<T>(value: T): T {
16
+ if (value !== null && typeof value === 'object' && !Object.isFrozen(value)) {
17
+ Object.freeze(value)
18
+ for (const nested of Object.values(value as Record<string, unknown>)) {
19
+ deepFreeze(nested)
20
+ }
21
+ }
22
+ return value
23
+ }
24
+
25
+ /**
26
+ * Detach and deep-freeze a message whose identity already exists — the host
27
+ * factory is `deepFreeze(structuredClone(message))`, byte-for-byte.
28
+ */
29
+ export function freezeMessage<T>(message: T): T {
30
+ return deepFreeze(structuredClone(message))
31
+ }
32
+
33
+ /**
34
+ * Create one identified user-role message and freeze it before publication —
35
+ * the host factory spreads the input, stamps `role: 'user'` and a fresh UUID
36
+ * id, clones and freezes. The signature mirrors the host's generic form so
37
+ * call sites keep their excess-property discipline; `id`/`role` stay
38
+ * unconstructible via the `never` guards, exactly like the host's d.ts.
39
+ */
40
+ type NewUserMessage = Omit<UserMessage, 'id' | 'role'>
41
+
42
+ export function createUserMessage<T extends NewUserMessage>(
43
+ input: T & { readonly id?: never, readonly role?: never },
44
+ ): UserMessage {
45
+ return deepFreeze(structuredClone({
46
+ ...input,
47
+ role: 'user' as const,
48
+ id: crypto.randomUUID(),
49
+ })) as unknown as UserMessage
50
+ }