dsh-context-compression-improved 0.8.0-beta.1 → 0.8.0-beta.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 (51) hide show
  1. package/CHANGELOG.de.md +539 -0
  2. package/CHANGELOG.es.md +547 -0
  3. package/CHANGELOG.fr.md +534 -0
  4. package/CHANGELOG.it.md +536 -0
  5. package/CHANGELOG.md +15 -0
  6. package/CHANGELOG.ru.md +517 -0
  7. package/README.de.md +98 -0
  8. package/README.es.md +98 -0
  9. package/README.fr.md +98 -0
  10. package/README.it.md +98 -0
  11. package/README.ja.md +1 -1
  12. package/README.ko.md +1 -1
  13. package/README.md +1 -1
  14. package/README.ru.md +98 -0
  15. package/README.zh.md +1 -1
  16. package/docs/installation.de.md +104 -0
  17. package/docs/installation.es.md +104 -0
  18. package/docs/installation.fr.md +104 -0
  19. package/docs/installation.it.md +104 -0
  20. package/docs/installation.ja.md +78 -78
  21. package/docs/installation.ko.md +78 -78
  22. package/docs/installation.md +103 -103
  23. package/docs/installation.ru.md +104 -0
  24. package/docs/installation.zh.md +100 -100
  25. package/package.json +17 -16
  26. package/packages/selector/dsh.plugin.json +1 -1
  27. package/packages/selector/lib/advisor-state.js +503 -1
  28. package/packages/selector/lib/client.d.ts +14 -0
  29. package/packages/selector/lib/client.js +1053 -3
  30. package/packages/selector/lib/index.js +122 -2
  31. package/packages/selector/lib/pruner.js +87 -258
  32. package/packages/selector/lib/style.css +42 -0
  33. package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
  34. package/packages/selector/src/client/index.ts +244 -213
  35. package/packages/selector/src/client/locales/de.ts +113 -0
  36. package/packages/selector/src/client/locales/es.ts +113 -0
  37. package/packages/selector/src/client/locales/fr.ts +113 -0
  38. package/packages/selector/src/client/locales/it.ts +113 -0
  39. package/packages/selector/src/client/locales/ja.ts +113 -0
  40. package/packages/selector/src/client/locales/ko.ts +113 -0
  41. package/packages/selector/src/client/locales/ru.ts +113 -0
  42. package/packages/selector/src/client/locales.ts +226 -196
  43. package/packages/selector/src/client/savings-card.tsx +150 -0
  44. package/packages/selector/src/client/settings-section.tsx +126 -124
  45. package/packages/selector/src/index.ts +547 -411
  46. package/packages/selector/src/pruner.ts +2505 -2421
  47. package/packages/selector/src/runtime/retrieve.ts +479 -457
  48. package/packages/selector/src/runtime/savings.ts +337 -0
  49. package/packages/selector/tests/estimator-route-registration.host.spec.ts +192 -188
  50. package/packages/selector/tests/runtime/savings.spec.ts +120 -0
  51. package/tests/TEST_INVENTORY.md +41 -41
@@ -0,0 +1,150 @@
1
+ /**
2
+ * 节省统计卡片(设置分节内,只读):净/毛/抵消 + 分项条。
3
+ * 数据源 = `/api/.../savings` 只读快照路由(忙 2s / 闲 5s 自调度轮询,
4
+ * 失败静默——统计卡片永不打扰设置页主功能)。
5
+ *
6
+ * @module dsh-context-compression-improved/client/savings-card
7
+ */
8
+ import { useEffect, useRef, useState } from 'react'
9
+ import css from './CompressionProfileSelector.module.css'
10
+ import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
11
+
12
+ const SAVINGS_ROUTE = '/api/dsh-context-compression-improved/savings'
13
+
14
+ interface SavingsSnapshot {
15
+ ok?: boolean
16
+ startedAt: string
17
+ sessions: number
18
+ gross: { exact: number; estimated: number }
19
+ offsets: { exact: number; estimated: number }
20
+ net: { exact: number; estimated: number }
21
+ perComponent: Array<{ component: string; tokens: number; basis: string; kind: string }>
22
+ recentOffsets: Array<{ component: string; tokens: number; basis: string; at: string; note?: string }>
23
+ usage?: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number; cacheHitRate: number | null }
24
+ perSession?: Array<{ sessionId: string; net: { exact: number; estimated: number }; requests: number; cacheHitRate: number | null }>
25
+ pricing?: { currency: string; actualCost?: string; estimatedSavedCost?: string }
26
+ }
27
+
28
+ export interface SavingsCardProps {
29
+ /** locale 文案函数(与设置分节同一 translator,键受字典类型约束)。 */
30
+ t: CompressionProfileSelectorProps['t']
31
+ }
32
+
33
+ function fmt(n: number): string {
34
+ return n.toLocaleString('en-US')
35
+ }
36
+
37
+ /** 节省统计卡片:口径分列(精确 tokenizer vs chars/4 估算),永不混算。 */
38
+ export function SavingsCard({ t }: SavingsCardProps) {
39
+ const [snap, setSnap] = useState<SavingsSnapshot | null>(null)
40
+ const stopped = useRef(false)
41
+ useEffect(() => {
42
+ stopped.current = false
43
+ const tick = async (): Promise<void> => {
44
+ try {
45
+ const response = await fetch(SAVINGS_ROUTE, { headers: { 'cache-control': 'no-cache' } })
46
+ if (response.ok) {
47
+ const data = (await response.json()) as SavingsSnapshot
48
+ if (data?.startedAt !== undefined && !stopped.current) setSnap(data)
49
+ }
50
+ } catch {
51
+ /* 路由未注册/网络不可用:静默 */
52
+ }
53
+ if (!stopped.current) setTimeout(tick, 5000)
54
+ }
55
+ void tick()
56
+ return () => {
57
+ stopped.current = true
58
+ }
59
+ }, [])
60
+
61
+ if (snap === null || (snap.gross.exact + snap.gross.estimated === 0)) {
62
+ return <div className={css.pricing}>{t('savings.empty')}</div>
63
+ }
64
+ const hasExact = snap.gross.exact > 0 || snap.offsets.exact > 0
65
+ const hasEstimated = snap.gross.estimated > 0 || snap.offsets.estimated > 0
66
+ const netTone = (snap.net.exact + snap.net.estimated) >= 0 ? css.savingsNetPositive : css.savingsNetNegative
67
+ return (
68
+ <div className={`${css.savingsCard}`} data-testid="savings-card">
69
+ <div className={css.savingsRow}>
70
+ <span>{t('savings.title')}</span>
71
+ </div>
72
+ {hasExact ? (
73
+ <div className={`${css.savingsRow} ${netTone}`}>
74
+ <span>{t('savings.netExact')}</span>
75
+ <strong>{fmt(snap.net.exact)}</strong>
76
+ </div>
77
+ ) : null}
78
+ {hasEstimated ? (
79
+ <div className={css.savingsRow}>
80
+ <span>{t('savings.netEstimated')}</span>
81
+ <strong>{fmt(snap.net.estimated)}</strong>
82
+ </div>
83
+ ) : null}
84
+ <div className={css.savingsRow}>
85
+ <span className={css.savingsMuted}>{t('savings.gross')}</span>
86
+ <span className={css.savingsMuted}>
87
+ {hasExact ? `✓ ${fmt(snap.gross.exact)}` : ''}{hasExact && hasEstimated ? ' · ' : ''}{hasEstimated ? `≈ ${fmt(snap.gross.estimated)}` : ''}
88
+ </span>
89
+ </div>
90
+ <div className={css.savingsRow}>
91
+ <span className={css.savingsMuted}>{t('savings.offsets')}</span>
92
+ <span className={css.savingsMuted}>
93
+ {hasExact ? `−${fmt(snap.offsets.exact)}` : ''}{hasExact && hasEstimated ? ' · ' : ''}{hasEstimated ? `−${fmt(snap.offsets.estimated)}` : ''}
94
+ </span>
95
+ </div>
96
+ {snap.usage !== undefined && snap.usage.requests > 0 ? (
97
+ <>
98
+ <div className={css.savingsRow}>
99
+ <span className={css.savingsMuted}>{t('savings.requests')}</span>
100
+ <span className={css.savingsMuted}>{fmt(snap.usage.requests)}</span>
101
+ </div>
102
+ <div className={css.savingsRow}>
103
+ <span className={css.savingsMuted}>{t('savings.cacheHit')}</span>
104
+ <span className={css.savingsMuted}>
105
+ {snap.usage.cacheHitRate === null ? '–' : `${Math.round(snap.usage.cacheHitRate * 100)}%`}
106
+ </span>
107
+ </div>
108
+ {snap.pricing?.actualCost !== undefined ? (
109
+ <div className={css.savingsRow}>
110
+ <span className={css.savingsMuted}>{t('savings.actualCost')}</span>
111
+ <span className={css.savingsMuted}>{snap.pricing.currency} {snap.pricing.actualCost}</span>
112
+ </div>
113
+ ) : null}
114
+ {snap.pricing?.estimatedSavedCost !== undefined ? (
115
+ <div className={css.savingsRow}>
116
+ <span className={css.savingsMuted}>{t('savings.savedMoney')}</span>
117
+ <span className={css.savingsMuted}>{snap.pricing.currency} {snap.pricing.estimatedSavedCost}</span>
118
+ </div>
119
+ ) : null}
120
+ </>
121
+ ) : null}
122
+ {snap.perSession !== undefined && snap.perSession.length > 1 ? (
123
+ <div className={css.savingsBreakdown}>
124
+ {snap.perSession.slice(0, 5).map(row => (
125
+ <div key={row.sessionId} className={css.savingsRow}>
126
+ <span className={css.savingsMuted}>
127
+ {t('savings.perSession')} · {row.sessionId.slice(0, 8)}…{row.requests > 0 ? ` · ${t('savings.cacheHit')} ${row.cacheHitRate === null ? '–' : `${Math.round(row.cacheHitRate * 100)}%`}` : ''}
128
+ </span>
129
+ <span className={css.savingsMuted}>{fmt(row.net.exact)}</span>
130
+ </div>
131
+ ))}
132
+ </div>
133
+ ) : null}
134
+ {snap.perComponent.length > 0 ? (
135
+ <div className={css.savingsBreakdown}>
136
+ {snap.perComponent.slice(0, 6).map((row) => (
137
+ <div key={`${row.kind}:${row.component}:${row.basis}`} className={css.savingsRow}>
138
+ <span className={css.savingsMuted}>
139
+ {row.kind === 'offset' ? '−' : '+'} {row.component}
140
+ <small> ({row.basis === 'exact-tokenizer' ? t('savings.basisExact') : t('savings.basisEstimated')})</small>
141
+ </span>
142
+ <span className={css.savingsMuted}>{fmt(row.tokens)}</span>
143
+ </div>
144
+ ))}
145
+ </div>
146
+ ) : null}
147
+ <div className={css.savingsNote}>{t('savings.basisNote')}</div>
148
+ </div>
149
+ )
150
+ }
@@ -1,124 +1,126 @@
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 } from './CompressionProfileControls.tsx'
19
- import { EstimatorControls, EstimatorInactiveNotice } from './EstimatorControls.tsx'
20
- import { CustomPolicyEditor, editableCustom } from './CustomPolicyEditor.tsx'
21
-
22
- /** Full-page Settings surface backed by the same durable selector state. */
23
- export function ContextCompressionSettingsSection(props: CompressionProfileSelectorProps) {
24
- return <SettingsCompressionProfileControls {...props} />
25
- }
26
-
27
- export function SettingsCompressionProfileControls({
28
- useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton,
29
- savePresetOptions, t,
30
- }: CompressionProfileSelectorProps) {
31
- const state = useCompression(snapshot => snapshot)
32
- // Harness 0.1.5 dropped browser-side agentPreset from session summaries, so
33
- // the old Minimal-preset gate has no data source; the selector stays enabled.
34
- const selectorAvailable = true
35
- const [saving, setSaving] = useState(false)
36
- const [saveError, setSaveError] = useState<string | null>(null)
37
- const [draft, setDraft] = useState<CustomCompressionPolicyV3 | null>(null)
38
- const current = state.value?.profile ?? 'balanced'
39
- useEffect(() => {
40
- const custom = state.value?.custom
41
- setDraft(current === 'custom' && custom !== undefined ? editableCustom(custom) : null)
42
- }, [current, state.value?.custom])
43
- if (state.status === 'unavailable') return null
44
-
45
- const busy = state.status === 'loading' || saving
46
- const selectProfile = (profile: CompressionProfile): void => {
47
- if (!selectorAvailable || !state.writable || profile === current) return
48
- setSaveError(null)
49
- setSaving(true)
50
- void select(profile).then(
51
- () => { setSaving(false) },
52
- (error: unknown) => {
53
- setSaving(false)
54
- setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
55
- },
56
- )
57
- }
58
- const settle = (operation: () => Promise<void>): void => {
59
- setSaveError(null)
60
- setSaving(true)
61
- void operation().then(
62
- () => { setSaving(false) },
63
- (error: unknown) => {
64
- setSaving(false)
65
- setSaveError(error instanceof Error && error.message !== '' ? error.message : t('status.saveFailed'))
66
- },
67
- )
68
- }
69
-
70
- return (
71
- <section className={css.settingsSection}>
72
- <h2 className={css.settingsTitle}>{t('settings.title')}</h2>
73
- <p className={css.settingsDescription}>{t('settings.description')}</p>
74
- {selectorAvailable ? (
75
- <div className={css.profileGrid} aria-label={t('label')}>
76
- {COMPRESSION_PROFILES.map((profile) => {
77
- const selected = profile === current
78
- return (
79
- <button key={profile} type="button" className={css.profileCard} aria-pressed={selected}
80
- disabled={busy || !state.writable} onClick={() => { selectProfile(profile) }}>
81
- <span className={css.profileCardTop}>
82
- <span className={css.profileCardTitle}>{t(`profile.${profile}`)}</span>
83
- {selected ? <span className={css.profileCurrent}>{t('profile.current')}</span> : null}
84
- </span>
85
- <span className={css.profileCardDetail}>{t(`detail.${profile}`)}</span>
86
- </button>
87
- )
88
- })}
89
- </div>
90
- ) : <div className={css.unavailable} role="status">{t('status.minimalUnavailable')}</div>}
91
- <AutoCompactThresholdControls
92
- value={state.value?.autoCompact?.thresholdPercent ?? AUTO_COMPACT_THRESHOLD_LIMITS.default}
93
- disabled={busy || !state.writable || !selectorAvailable}
94
- save={saveAutoCompact}
95
- settle={settle}
96
- t={t}
97
- />
98
- <CodeSkeletonControls
99
- value={state.value?.codeSkeleton?.enabled ?? false}
100
- disabled={busy || !state.writable || !selectorAvailable}
101
- save={saveCodeSkeleton}
102
- settle={settle}
103
- t={t}
104
- />
105
- {current !== 'tokenpilot-inspired' ? (
106
- <EstimatorInactiveNotice profile={t(`profile.${current}`)} t={t} />
107
- ) : (
108
- <EstimatorControls
109
- options={state.value?.presetOptions ?? {}}
110
- disabled={busy || !state.writable || !selectorAvailable}
111
- save={savePresetOptions}
112
- settle={settle}
113
- t={t}
114
- />
115
- )}
116
- <div className={css.pricing}>{t('pricing.disclosure')}</div>
117
- {current !== 'custom' || draft === null || !selectorAvailable ? null : (
118
- <CustomPolicyEditor value={draft} disabled={busy || !state.writable} setValue={setDraft}
119
- save={() => saveCustom(structuredClone(draft))} reset={resetCustom} settle={settle} t={t} />
120
- )}
121
- {saveError === null ? null : <div className={css.error} role="alert">{saveError}</div>}
122
- </section>
123
- )
124
- }
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 } 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,
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
+ {current !== 'tokenpilot-inspired' ? (
107
+ <EstimatorInactiveNotice profile={t(`profile.${current}`)} t={t} />
108
+ ) : (
109
+ <EstimatorControls
110
+ options={state.value?.presetOptions ?? {}}
111
+ disabled={busy || !state.writable || !selectorAvailable}
112
+ save={savePresetOptions}
113
+ settle={settle}
114
+ t={t}
115
+ />
116
+ )}
117
+ <SavingsCard t={t} />
118
+ <div className={css.pricing}>{t('pricing.disclosure')}</div>
119
+ {current !== 'custom' || draft === null || !selectorAvailable ? null : (
120
+ <CustomPolicyEditor value={draft} disabled={busy || !state.writable} setValue={setDraft}
121
+ save={() => saveCustom(structuredClone(draft))} reset={resetCustom} settle={settle} t={t} />
122
+ )}
123
+ {saveError === null ? null : <div className={css.error} role="alert">{saveError}</div>}
124
+ </section>
125
+ )
126
+ }