dsh-context-compression-improved 0.5.7 → 0.5.8
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.
- package/CHANGELOG.md +9 -0
- package/package.json +16 -17
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +59 -0
- package/packages/selector/lib/client.js +1012 -17
- package/packages/selector/lib/{advisor-state.js → config.js} +816 -65
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +295 -3
- package/packages/selector/lib/pruner.d.ts +65 -0
- package/packages/selector/lib/pruner.js +497 -262
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/src/client/CompressionProfileControls.tsx +67 -0
- package/packages/selector/src/client/CompressionProfileSelector.module.css +29 -0
- package/packages/selector/src/client/CompressionProfileSelector.tsx +2 -0
- package/packages/selector/src/client/decode.ts +10 -2
- package/packages/selector/src/client/index.ts +62 -0
- package/packages/selector/src/client/locales/de.ts +43 -0
- package/packages/selector/src/client/locales/es.ts +43 -0
- package/packages/selector/src/client/locales/fr.ts +43 -0
- package/packages/selector/src/client/locales/it.ts +43 -0
- package/packages/selector/src/client/locales/ja.ts +43 -0
- package/packages/selector/src/client/locales/ko.ts +43 -0
- package/packages/selector/src/client/locales/ru.ts +43 -0
- package/packages/selector/src/client/locales.ts +86 -0
- package/packages/selector/src/client/monitor-fab.ts +336 -0
- package/packages/selector/src/client/savings-card.tsx +150 -0
- package/packages/selector/src/client/settings-section.tsx +18 -2
- package/packages/selector/src/index.ts +215 -5
- package/packages/selector/src/profiles.ts +37 -0
- package/packages/selector/src/pruner/state.ts +7 -0
- package/packages/selector/src/pruner.ts +337 -3
- package/packages/selector/src/runtime/audit.ts +17 -0
- package/packages/selector/src/runtime/config.ts +52 -2
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/retrieve.ts +24 -2
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/summary-command.ts +127 -0
- package/packages/selector/src/runtime/tokenpilot/advisor-prompt.ts +46 -1
- package/packages/selector/src/runtime/tokenpilot/advisor-state.ts +55 -0
- package/packages/selector/src/runtime/tokenpilot/intent-fold.ts +53 -0
- package/packages/selector/src/runtime/tokenpilot/intent-gate.ts +65 -0
- package/packages/selector/src/runtime/tokenpilot/intent-input-mask.ts +125 -0
- package/packages/selector/src/runtime/tokenpilot/intent-range.ts +37 -0
- package/packages/selector/src/runtime/types.ts +19 -0
- package/packages/selector/tests/auto-compact.client.spec.tsx +2 -1
- package/packages/selector/tests/code-skeleton.client.spec.ts +3 -2
- package/packages/selector/tests/custom-contract.client.spec.ts +3 -2
- package/packages/selector/tests/estimator-channel.client.spec.tsx +1 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +10 -4
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -0
- package/packages/selector/tests/preset-options-write.client.spec.ts +1 -0
- package/packages/selector/tests/profiles.client.spec.tsx +4 -2
- package/packages/selector/tests/runtime/audit.spec.ts +1 -0
- package/packages/selector/tests/runtime/intent-gate.spec.ts +62 -0
- package/packages/selector/tests/runtime/intent-summary.spec.ts +156 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +301 -0
- package/packages/selector/tests/runtime/savings.spec.ts +120 -0
- package/packages/selector/tests/runtime/summary-command.spec.ts +154 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +19 -7
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +2 -1
|
@@ -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
|
+
}
|
|
@@ -15,9 +15,10 @@ import {
|
|
|
15
15
|
type CustomCompressionPolicyV3,
|
|
16
16
|
} from '../profiles.ts'
|
|
17
17
|
import type { CompressionProfileSelectorProps } from './CompressionProfileSelector.tsx'
|
|
18
|
-
import { AutoCompactThresholdControls, CodeSkeletonControls } from './CompressionProfileControls.tsx'
|
|
18
|
+
import { AutoCompactThresholdControls, CodeSkeletonControls, IntentSummaryControls, MonitorPanelControls } from './CompressionProfileControls.tsx'
|
|
19
19
|
import { EstimatorControls, EstimatorInactiveNotice } from './EstimatorControls.tsx'
|
|
20
20
|
import { CustomPolicyEditor, editableCustom } from './CustomPolicyEditor.tsx'
|
|
21
|
+
import { SavingsCard } from './savings-card'
|
|
21
22
|
|
|
22
23
|
/** Full-page Settings surface backed by the same durable selector state. */
|
|
23
24
|
export function ContextCompressionSettingsSection(props: CompressionProfileSelectorProps) {
|
|
@@ -25,7 +26,7 @@ export function ContextCompressionSettingsSection(props: CompressionProfileSelec
|
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
export function SettingsCompressionProfileControls({
|
|
28
|
-
useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton,
|
|
29
|
+
useCompression, select, saveCustom, resetCustom, saveAutoCompact, saveCodeSkeleton, saveIntentSummary, saveMonitorPanel,
|
|
29
30
|
savePresetOptions, t,
|
|
30
31
|
}: CompressionProfileSelectorProps) {
|
|
31
32
|
const state = useCompression(snapshot => snapshot)
|
|
@@ -102,6 +103,20 @@ export function SettingsCompressionProfileControls({
|
|
|
102
103
|
settle={settle}
|
|
103
104
|
t={t}
|
|
104
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
|
+
/>
|
|
105
120
|
{current !== 'tokenpilot-inspired' ? (
|
|
106
121
|
<EstimatorInactiveNotice profile={t(`profile.${current}`)} t={t} />
|
|
107
122
|
) : (
|
|
@@ -113,6 +128,7 @@ export function SettingsCompressionProfileControls({
|
|
|
113
128
|
t={t}
|
|
114
129
|
/>
|
|
115
130
|
)}
|
|
131
|
+
<SavingsCard t={t} />
|
|
116
132
|
<div className={css.pricing}>{t('pricing.disclosure')}</div>
|
|
117
133
|
{current !== 'custom' || draft === null || !selectorAvailable ? null : (
|
|
118
134
|
<CustomPolicyEditor value={draft} disabled={busy || !state.writable} setValue={setDraft}
|
|
@@ -7,12 +7,22 @@ import {
|
|
|
7
7
|
type default as SettingsService,
|
|
8
8
|
} from '@deepseek-ai/dsh-settings'
|
|
9
9
|
import { buildEstimatorCatalog, type EstimatorCatalogDeps } from './estimator-catalog.ts'
|
|
10
|
+
import { getSavingsLedger } from './runtime/savings.ts'
|
|
11
|
+
import { priceOfficialDeepSeekUsage } from './runtime/deepseek-official-pricing.ts'
|
|
12
|
+
import {
|
|
13
|
+
applySessionOverride,
|
|
14
|
+
buildMonitorSnapshot,
|
|
15
|
+
estimateSavingsPricing,
|
|
16
|
+
isSessionOverrideAction,
|
|
17
|
+
type AgentDefaultModelLike,
|
|
18
|
+
} from './runtime/monitor.ts'
|
|
10
19
|
import {
|
|
11
20
|
CONTEXT_COMPRESSION_SETTINGS_NAMESPACE,
|
|
12
21
|
ContextCompressionSettingsSchema,
|
|
13
22
|
} from './runtime/config.ts'
|
|
14
23
|
|
|
15
24
|
import { getAdvisorState } from './runtime/tokenpilot/advisor-state.ts'
|
|
25
|
+
import { registerSummaryCommand } from './runtime/summary-command.ts'
|
|
16
26
|
|
|
17
27
|
// The settings namespace literal and the settings schema are owned by the
|
|
18
28
|
// runtime config module. Both were once inlined/replaced here to dodge a
|
|
@@ -41,6 +51,17 @@ const ADVISOR_REPORT_ROUTES = [
|
|
|
41
51
|
'/api/dsh-context-compression-improved/advisor-report',
|
|
42
52
|
] as const
|
|
43
53
|
|
|
54
|
+
// Savings stats: one read-only snapshot route, dual prefixed like the others.
|
|
55
|
+
const SAVINGS_ROUTES = [
|
|
56
|
+
'/endpoint/dsh-context-compression-improved/savings',
|
|
57
|
+
'/api/dsh-context-compression-improved/savings',
|
|
58
|
+
] as const
|
|
59
|
+
|
|
60
|
+
const MONITOR_ROUTES = [
|
|
61
|
+
'/endpoint/dsh-context-compression-improved/monitor',
|
|
62
|
+
'/api/dsh-context-compression-improved/monitor',
|
|
63
|
+
] as const
|
|
64
|
+
|
|
44
65
|
/** Minimal face of the agents service: session id → agent (carrying the session). */
|
|
45
66
|
interface AgentsServiceLike {
|
|
46
67
|
get?(id: unknown): { session?: unknown } | undefined
|
|
@@ -179,11 +200,6 @@ interface WebServerLike {
|
|
|
179
200
|
}
|
|
180
201
|
|
|
181
202
|
/** The estimator-side service the catalog handler enriches its response with. */
|
|
182
|
-
interface AgentDefaultModelLike {
|
|
183
|
-
/** Current host model-group selection, when the service exposes one. */
|
|
184
|
-
currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
|
|
185
|
-
}
|
|
186
|
-
|
|
187
203
|
function asWebServer(value: unknown): WebServerLike | undefined {
|
|
188
204
|
if (typeof value !== 'object' || value === null) return undefined
|
|
189
205
|
const candidate = value as { register?: unknown }
|
|
@@ -307,6 +323,191 @@ interface SharedSettingsRegistration {
|
|
|
307
323
|
scope: SettingsScope<unknown>
|
|
308
324
|
}
|
|
309
325
|
|
|
326
|
+
/**
|
|
327
|
+
* Read-only savings snapshot route (`GET .../savings?sessionId=…`): gross saved,
|
|
328
|
+
* offsets (negative savings — compressed content later re-read in full), and net,
|
|
329
|
+
* with exact-tokenizer and chars/4 bases reported separately and never merged.
|
|
330
|
+
* Registration mirrors the estimator-catalog route (webServer gate alone, dual
|
|
331
|
+
* channels for both service arrival orders, single guarded registration).
|
|
332
|
+
*/
|
|
333
|
+
function registerSavingsRoute(ctx: Context): void {
|
|
334
|
+
const readService = (name: string): unknown => {
|
|
335
|
+
try {
|
|
336
|
+
return (ctx as unknown as { get: (service: string) => unknown }).get(name)
|
|
337
|
+
} catch {
|
|
338
|
+
return undefined
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
|
|
342
|
+
console[level](message, ...args)
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
let registered = false
|
|
346
|
+
const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
|
|
347
|
+
if (registered) return
|
|
348
|
+
const handler = (req: unknown, res: unknown): void => {
|
|
349
|
+
const resTyped = res as {
|
|
350
|
+
writeHead: (code: number, headers?: Record<string, string>) => void
|
|
351
|
+
end: (body?: string) => void
|
|
352
|
+
}
|
|
353
|
+
if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
|
|
354
|
+
let sessionId: string | undefined
|
|
355
|
+
try {
|
|
356
|
+
const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
|
|
357
|
+
const raw = url.searchParams.get('sessionId')
|
|
358
|
+
if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
|
|
359
|
+
} catch {
|
|
360
|
+
/* 无法解析的查询串 = 全会话聚合 */
|
|
361
|
+
}
|
|
362
|
+
const snapshot = getSavingsLedger().snapshot(sessionId)
|
|
363
|
+
const pricing = estimateSavingsPricing(readService, snapshot)
|
|
364
|
+
resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
|
|
365
|
+
resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
|
|
366
|
+
}
|
|
367
|
+
try {
|
|
368
|
+
const disposers = SAVINGS_ROUTES
|
|
369
|
+
.map(path => webServer.register({ kind: 'exact', path, handler }))
|
|
370
|
+
.filter((off): off is () => void => typeof off === 'function')
|
|
371
|
+
registered = true
|
|
372
|
+
ctx.effect(
|
|
373
|
+
() => () => { for (const off of disposers) off() },
|
|
374
|
+
'contextCompressionSelector.savings route',
|
|
375
|
+
)
|
|
376
|
+
log('info', 'context-compression savings route registered (%s): %s', channel, SAVINGS_ROUTES.join(', '))
|
|
377
|
+
} catch (error) {
|
|
378
|
+
log('warn', 'context-compression savings route registration failed (%s): %o', channel, error)
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
const active = asWebServer(readService('webServer'))
|
|
383
|
+
if (active !== undefined) {
|
|
384
|
+
register(active, 'direct')
|
|
385
|
+
if (registered) return
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
ctx.inject(['webServer'], (injected) => {
|
|
389
|
+
const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
|
|
390
|
+
if (webServer === undefined) {
|
|
391
|
+
log('warn', 'context-compression webServer exposes no register() — savings route not registered')
|
|
392
|
+
return
|
|
393
|
+
}
|
|
394
|
+
register(webServer, 'inject')
|
|
395
|
+
})
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/**
|
|
399
|
+
* Floating-panel monitor route (`GET|POST .../monitor?sessionId=…`):
|
|
400
|
+
* - GET → the monitor snapshot (savings aggregate + intent control block +
|
|
401
|
+
* pricing) — the payload shape the panel polls;
|
|
402
|
+
* - POST → session override action (`{"action":"on"|"off"|"clear"}`),
|
|
403
|
+
* driving the exact state machine `/ctx-summary` drives.
|
|
404
|
+
* Registration mirrors the savings route (webServer gate alone, dual channels,
|
|
405
|
+
* single guarded registration); the handler branches on `req.method` because
|
|
406
|
+
* the registration surface is method-agnostic.
|
|
407
|
+
*/
|
|
408
|
+
/** Exported for the runtime monitor spec; the entry owns all webServer wiring. */
|
|
409
|
+
export function registerMonitorRoute(ctx: Context): void {
|
|
410
|
+
const readService = (name: string): unknown => {
|
|
411
|
+
try {
|
|
412
|
+
return (ctx as unknown as { get: (service: string) => unknown }).get(name)
|
|
413
|
+
} catch {
|
|
414
|
+
return undefined
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const log = (level: 'info' | 'warn', message: string, ...args: unknown[]): void => {
|
|
418
|
+
console[level](message, ...args)
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
let registered = false
|
|
422
|
+
const register = (webServer: WebServerLike, channel: 'direct' | 'inject'): void => {
|
|
423
|
+
if (registered) return
|
|
424
|
+
const handler = (req: unknown, res: unknown): void => {
|
|
425
|
+
const resTyped = res as {
|
|
426
|
+
writeHead: (code: number, headers?: Record<string, string>) => void
|
|
427
|
+
end: (body?: string) => void
|
|
428
|
+
}
|
|
429
|
+
if (typeof resTyped?.writeHead !== 'function' || typeof resTyped?.end !== 'function') return
|
|
430
|
+
let sessionId: string | undefined
|
|
431
|
+
try {
|
|
432
|
+
const url = new URL(String((req as { url?: string })?.url ?? '/'), 'http://localhost')
|
|
433
|
+
const raw = url.searchParams.get('sessionId')
|
|
434
|
+
if (typeof raw === 'string' && raw.length > 0 && raw.length <= 512) sessionId = raw
|
|
435
|
+
} catch {
|
|
436
|
+
/* 无法解析的查询串 = 全会话聚合 */
|
|
437
|
+
}
|
|
438
|
+
const method = String((req as { method?: string })?.method ?? 'GET').toUpperCase()
|
|
439
|
+
if (method === 'POST') {
|
|
440
|
+
const chunks: Buffer[] = []
|
|
441
|
+
let size = 0
|
|
442
|
+
let done = false
|
|
443
|
+
const respond = (status: number, body: Record<string, unknown>): void => {
|
|
444
|
+
if (done) return
|
|
445
|
+
done = true
|
|
446
|
+
resTyped.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
|
|
447
|
+
resTyped.end(JSON.stringify(body))
|
|
448
|
+
}
|
|
449
|
+
const reqTyped = req as { on?: (event: string, cb: (chunk?: Buffer) => void) => void }
|
|
450
|
+
if (typeof reqTyped?.on !== 'function') {
|
|
451
|
+
respond(400, { ok: false, error: 'unreadable request body' })
|
|
452
|
+
return
|
|
453
|
+
}
|
|
454
|
+
reqTyped.on('data', (chunk?: Buffer) => {
|
|
455
|
+
size += chunk?.length ?? 0
|
|
456
|
+
if (size <= 4096) chunks.push(Buffer.from(chunk ?? new Uint8Array()))
|
|
457
|
+
})
|
|
458
|
+
reqTyped.on('end', () => {
|
|
459
|
+
let action: unknown
|
|
460
|
+
try {
|
|
461
|
+
action = (JSON.parse(Buffer.concat(chunks).toString('utf8') || '{}') as { action?: unknown }).action
|
|
462
|
+
} catch {
|
|
463
|
+
respond(400, { ok: false, error: 'monitor override action must be JSON' })
|
|
464
|
+
return
|
|
465
|
+
}
|
|
466
|
+
if (!isSessionOverrideAction(action)) {
|
|
467
|
+
respond(400, { ok: false, error: 'monitor override action must be "on" | "off" | "clear"' })
|
|
468
|
+
return
|
|
469
|
+
}
|
|
470
|
+
const { override } = applySessionOverride(sessionId ?? '', action)
|
|
471
|
+
respond(200, { ok: true, override: override ?? null, sessionScope: sessionId ?? null })
|
|
472
|
+
})
|
|
473
|
+
return
|
|
474
|
+
}
|
|
475
|
+
const snapshot = buildMonitorSnapshot(sessionId)
|
|
476
|
+
const pricing = estimateSavingsPricing(readService, snapshot)
|
|
477
|
+
resTyped.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-cache' })
|
|
478
|
+
resTyped.end(JSON.stringify({ ok: true, ...snapshot, ...(pricing === undefined ? {} : { pricing }) }))
|
|
479
|
+
}
|
|
480
|
+
try {
|
|
481
|
+
const disposers = MONITOR_ROUTES
|
|
482
|
+
.map(path => webServer.register({ kind: 'exact', path, handler }))
|
|
483
|
+
.filter((off): off is () => void => typeof off === 'function')
|
|
484
|
+
registered = true
|
|
485
|
+
ctx.effect(
|
|
486
|
+
() => () => { for (const off of disposers) off() },
|
|
487
|
+
'contextCompressionSelector.monitor route',
|
|
488
|
+
)
|
|
489
|
+
log('info', 'context-compression monitor route registered (%s): %s', channel, MONITOR_ROUTES.join(', '))
|
|
490
|
+
} catch (error) {
|
|
491
|
+
log('warn', 'context-compression monitor route registration failed (%s): %o', channel, error)
|
|
492
|
+
}
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
const active = asWebServer(readService('webServer'))
|
|
496
|
+
if (active !== undefined) {
|
|
497
|
+
register(active, 'direct')
|
|
498
|
+
if (registered) return
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
ctx.inject(['webServer'], (injected) => {
|
|
502
|
+
const webServer = asWebServer((injected as { webServer?: unknown }).webServer)
|
|
503
|
+
if (webServer === undefined) {
|
|
504
|
+
log('warn', 'context-compression webServer exposes no register() — monitor route not registered')
|
|
505
|
+
return
|
|
506
|
+
}
|
|
507
|
+
register(webServer, 'inject')
|
|
508
|
+
})
|
|
509
|
+
}
|
|
510
|
+
|
|
310
511
|
/** One selector Host row able to own the registration effect. */
|
|
311
512
|
interface SettingsOwner {
|
|
312
513
|
/** Traceable service proxy binding register() to this row's fiber. */
|
|
@@ -371,10 +572,19 @@ export function apply(ctx: Context, config: Config = {}): void {
|
|
|
371
572
|
// top-level plugin fiber, not inside the isolated `toolResultPruner`
|
|
372
573
|
// service, because the route is host-wide rather than per-pruner-instance.
|
|
373
574
|
if (config.estimatorCatalogRoute === true) registerEstimatorCatalogRoute(ctx)
|
|
575
|
+
// 节省统计路由:只读快照,无 opt-in 门槛(无敏感数据,纯 token 计数)。
|
|
576
|
+
registerSavingsRoute(ctx)
|
|
577
|
+
registerMonitorRoute(ctx)
|
|
374
578
|
|
|
375
579
|
// Advisory advisor: read-only decay/score/advice report (opt-in).
|
|
376
580
|
if (config.advisorReportRoute === true) registerAdvisorReportRoute(ctx)
|
|
377
581
|
|
|
582
|
+
// Turn-tail intent summary: `/ctx-summary off|on|status`. The command is
|
|
583
|
+
// free to register and stays quiet on hosts without the commands
|
|
584
|
+
// registry; the capability itself is gated by the frozen `intentSummary`
|
|
585
|
+
// setting plus the session-scoped override this command controls.
|
|
586
|
+
registerSummaryCommand(ctx)
|
|
587
|
+
|
|
378
588
|
if (config.presetOverlay !== true) return
|
|
379
589
|
|
|
380
590
|
ctx.inject(['agentPresets'], (presetsCtx) => {
|
|
@@ -108,6 +108,19 @@ export interface CodeSkeletonSettings {
|
|
|
108
108
|
enabled: boolean
|
|
109
109
|
}
|
|
110
110
|
|
|
111
|
+
/**
|
|
112
|
+
* Orthogonal turn-tail intent-summary gate, mirrored browser-safe from the
|
|
113
|
+
* runtime: independent of every profile, default off.
|
|
114
|
+
*/
|
|
115
|
+
export interface IntentSummarySettings {
|
|
116
|
+
enabled: boolean
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Floating compression-monitor panel (FAB); visibility switch. */
|
|
120
|
+
export interface MonitorPanelSettings {
|
|
121
|
+
enabled: boolean
|
|
122
|
+
}
|
|
123
|
+
|
|
111
124
|
/**
|
|
112
125
|
* Decode the persisted codeSkeleton section with exactly the runtime schema's
|
|
113
126
|
* strictness: absent means the lossless off default; present values must be a
|
|
@@ -123,6 +136,26 @@ export function decodeCodeSkeletonSettings(value: unknown): CodeSkeletonSettings
|
|
|
123
136
|
return typeof enabled === 'boolean' ? { enabled } : undefined
|
|
124
137
|
}
|
|
125
138
|
|
|
139
|
+
/** Browser-safe mirror of the runtime intentSummary section (absent inherits off). */
|
|
140
|
+
export function decodeIntentSummarySettings(value: unknown): IntentSummarySettings | undefined {
|
|
141
|
+
if (value === undefined) return { enabled: false }
|
|
142
|
+
if (!isPlainRecord(value)) return undefined
|
|
143
|
+
const keys = Object.keys(value)
|
|
144
|
+
if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
|
|
145
|
+
const enabled = (value as Record<string, unknown>).enabled
|
|
146
|
+
return typeof enabled === 'boolean' ? { enabled } : undefined
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/** Browser-safe mirror of the runtime monitorPanel section (absent inherits hidden). */
|
|
150
|
+
export function decodeMonitorPanelSettings(value: unknown): MonitorPanelSettings | undefined {
|
|
151
|
+
if (value === undefined) return { enabled: false }
|
|
152
|
+
if (!isPlainRecord(value)) return undefined
|
|
153
|
+
const keys = Object.keys(value)
|
|
154
|
+
if (keys.length !== 1 || keys[0] !== 'enabled') return undefined
|
|
155
|
+
const enabled = (value as Record<string, unknown>).enabled
|
|
156
|
+
return typeof enabled === 'boolean' ? { enabled } : undefined
|
|
157
|
+
}
|
|
158
|
+
|
|
126
159
|
/** Browser-safe mirror of the runtime presetOptions section. */
|
|
127
160
|
export interface PresetOptionsSettings {
|
|
128
161
|
readonly dedupeToolResults?: boolean
|
|
@@ -289,6 +322,10 @@ export interface ContextCompressionSettings {
|
|
|
289
322
|
autoCompact: AutoCompactSettings
|
|
290
323
|
/** Code-skeleton reducer gate captured independently of `profile`. */
|
|
291
324
|
codeSkeleton: CodeSkeletonSettings
|
|
325
|
+
/** Turn-tail intent-summary gate captured independently of `profile`. */
|
|
326
|
+
intentSummary: IntentSummarySettings
|
|
327
|
+
/** Floating compression-monitor panel (FAB); absent inherits hidden. */
|
|
328
|
+
monitorPanel?: MonitorPanelSettings
|
|
292
329
|
/** Optional tokenpilot-inspired sub-capability overrides (presence-validated only). */
|
|
293
330
|
presetOptions?: PresetOptionsSettings
|
|
294
331
|
}
|
|
@@ -9,6 +9,7 @@ import type { Session } from '@deepseek-ai/dsh-session'
|
|
|
9
9
|
import type { DedupeTable } from '../runtime/tokenpilot/dedup.ts'
|
|
10
10
|
import type { EstimatorFailures } from '../runtime/tokenpilot/estimator.ts'
|
|
11
11
|
import type { SideChannel } from '../runtime/tokenpilot/sidechannel.ts'
|
|
12
|
+
import type { PendingIntentFold } from '../runtime/tokenpilot/intent-fold.ts'
|
|
12
13
|
import type {
|
|
13
14
|
ContextCompressionSettings,
|
|
14
15
|
ResolvedConfig,
|
|
@@ -47,4 +48,10 @@ export interface PrunerState {
|
|
|
47
48
|
readonly estimatorRemainingTurns: WeakMap<Session, number>
|
|
48
49
|
/** Per-session advisor side channel, constructed once with the advisor overrides. */
|
|
49
50
|
readonly advisorChannels: WeakMap<Session, SideChannel>
|
|
51
|
+
/** Staged intent fold awaiting the next pressure round (at most one per session). */
|
|
52
|
+
readonly pendingIntentFolds: WeakMap<Session, PendingIntentFold>
|
|
53
|
+
/** Landed intent-fold seqs: fold-once, never reconsidered by any later stage. */
|
|
54
|
+
readonly intentFoldedSeqs: WeakMap<Session, Set<number>>
|
|
55
|
+
/** Live-surface tokens when the last intent fold landed (growth-gate baseline). */
|
|
56
|
+
readonly intentBaselines: WeakMap<Session, number>
|
|
50
57
|
}
|