dsh-context-compression-improved 0.7.0-beta.2 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/package.json +17 -18
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +44 -0
- package/packages/selector/lib/client.js +1007 -13
- package/packages/selector/lib/{intent-gate.js → config.js} +799 -136
- package/packages/selector/lib/index.d.ts +13 -1
- package/packages/selector/lib/index.js +204 -3
- package/packages/selector/lib/profiles.d.ts +6 -0
- package/packages/selector/lib/pruner.d.ts +6 -0
- package/packages/selector/lib/pruner.js +90 -258
- package/packages/selector/lib/style.css +42 -0
- package/packages/selector/src/client/CompressionProfileControls.tsx +293 -226
- package/packages/selector/src/client/CompressionProfileSelector.module.css +199 -170
- package/packages/selector/src/client/CompressionProfileSelector.tsx +85 -83
- package/packages/selector/src/client/decode.ts +5 -1
- package/packages/selector/src/client/index.ts +307 -243
- 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 +282 -196
- 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 +140 -124
- package/packages/selector/src/index.ts +207 -5
- package/packages/selector/src/profiles.ts +17 -0
- package/packages/selector/src/pruner.ts +96 -2
- package/packages/selector/src/runtime/config.ts +26 -1
- package/packages/selector/src/runtime/monitor.ts +235 -0
- package/packages/selector/src/runtime/retrieve.ts +479 -457
- package/packages/selector/src/runtime/savings.ts +337 -0
- package/packages/selector/src/runtime/types.ts +7 -0
- package/packages/selector/tests/code-skeleton.client.spec.ts +2 -2
- package/packages/selector/tests/custom-contract.client.spec.ts +2 -2
- package/packages/selector/tests/estimator-channel.client.spec.tsx +2 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +194 -188
- package/packages/selector/tests/monitor-fab.client.spec.ts +138 -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/settings-seat.client.spec.ts +177 -165
- package/scripts/packed-install-e2e.mjs +1 -1
- package/scripts/verify-release.mjs +1 -1
|
@@ -31,7 +31,7 @@ import type {
|
|
|
31
31
|
CompactionTokenView,
|
|
32
32
|
ObservedPromptUsage,
|
|
33
33
|
} from './runtime/measurement.ts'
|
|
34
|
-
import { measureForCompaction } from './runtime/measurement.ts'
|
|
34
|
+
import { measureForCompaction, officialRequestUsage } from './runtime/measurement.ts'
|
|
35
35
|
import { eventBySeq, sessionEvents } from './runtime/session-events.ts'
|
|
36
36
|
import { countExactCanonicalTextFields } from './runtime/token-count.ts'
|
|
37
37
|
import type {} from '@deepseek-ai/dsh-tools'
|
|
@@ -97,6 +97,7 @@ import { computeIntentRange, INTENT_RANGE_MAX_CANDIDATES } from './runtime/token
|
|
|
97
97
|
import { INTENT_FOLD_MARKER, renderIntentFoldBlock } from './runtime/tokenpilot/intent-fold.ts'
|
|
98
98
|
import { buildIntentSummarySystemPrompt, buildIntentSummaryUserPrompt, parseIntentSummaryAnswer } from './runtime/tokenpilot/advisor-prompt.ts'
|
|
99
99
|
import { getSummaryOverride, observeIntentEnabled, recordIntentFold } from './runtime/tokenpilot/advisor-state.ts'
|
|
100
|
+
import { observeContextUsage } from './runtime/monitor.ts'
|
|
100
101
|
|
|
101
102
|
import {
|
|
102
103
|
DedupeTable,
|
|
@@ -104,6 +105,12 @@ import {
|
|
|
104
105
|
dedupePlaceholder,
|
|
105
106
|
flattenPlainText,
|
|
106
107
|
} from './runtime/tokenpilot/dedup.ts'
|
|
108
|
+
import { getSavingsLedger } from './runtime/savings.ts'
|
|
109
|
+
|
|
110
|
+
/** 节省统计配对键用原文(纯文本块才可配对;富内容返回 undefined)。 */
|
|
111
|
+
function originalTextForSavings(candidate: SnapshotCandidate): string | undefined {
|
|
112
|
+
return flattenPlainText(candidate.event.data.message.content)
|
|
113
|
+
}
|
|
107
114
|
import {
|
|
108
115
|
charsForTokens,
|
|
109
116
|
charsToTokens,
|
|
@@ -258,6 +265,27 @@ export class ToolResultPruner extends Service {
|
|
|
258
265
|
intentBaselines: new WeakMap(),
|
|
259
266
|
}
|
|
260
267
|
|
|
268
|
+
// 会话结束汇总(dsh-token-optimizer monitor 模式的同款体验):输出该会话的
|
|
269
|
+
// 净节省/缓存命中率一行账。事件名探测式注册——老代际不发 session/disposed
|
|
270
|
+
// 时监听器静默闲置,不构成任何行为差异。
|
|
271
|
+
try {
|
|
272
|
+
;(ctx as unknown as { on: (name: string, handler: (session: Session) => void) => unknown }).on(
|
|
273
|
+
'session/disposed',
|
|
274
|
+
(session) => {
|
|
275
|
+
try {
|
|
276
|
+
const line = getSavingsLedger().sessionSummaryLine(String(session.id))
|
|
277
|
+
if (line.includes('requests=0') === false || line.includes('net=0(exact)/0(est)') === false) {
|
|
278
|
+
ctx.logger.info('context-compression session savings (%s): %s', String(session.id), line)
|
|
279
|
+
}
|
|
280
|
+
} catch {
|
|
281
|
+
/* 汇总失败不影响 dispose */
|
|
282
|
+
}
|
|
283
|
+
},
|
|
284
|
+
)
|
|
285
|
+
} catch {
|
|
286
|
+
/* 宿主不支持该事件名:静默 */
|
|
287
|
+
}
|
|
288
|
+
|
|
261
289
|
ctx.on('session/event', (session, event) => {
|
|
262
290
|
this.scanForSeededNativeSummary(session)
|
|
263
291
|
if (event.type === 'compaction/summary') {
|
|
@@ -318,6 +346,15 @@ export class ToolResultPruner extends Service {
|
|
|
318
346
|
this.auditFailure(agent.session, 'fresh', 'terminal-pass', error)
|
|
319
347
|
ctx.logger.warn('context-compression terminal pass failed open: %o', error)
|
|
320
348
|
}
|
|
349
|
+
// 压缩监控观测:每回合无条件记录上下文占用——面板占用条与
|
|
350
|
+
// 灾难性遗忘区建议的数据源,与 intentSummary 门控解耦(门关也可观测)。
|
|
351
|
+
try {
|
|
352
|
+
observeContextUsage(
|
|
353
|
+
String(agent.session.id),
|
|
354
|
+
measureForCompaction(this.ctx, agent.session).totalTokens,
|
|
355
|
+
this.contextWindowForRequest(agent.session),
|
|
356
|
+
)
|
|
357
|
+
} catch { /* 观测失败静默:面板显示陈旧/空态 */ }
|
|
321
358
|
// TokenPilot-inspired E1: advisory estimator pass, strictly off the
|
|
322
359
|
// synchronous chain. Verdicts only feed the next pressure pass.
|
|
323
360
|
void this.postflightEstimatorPass(agent.session, signal).catch(() => undefined)
|
|
@@ -369,7 +406,15 @@ export class ToolResultPruner extends Service {
|
|
|
369
406
|
if (policy === undefined) return emptyResult()
|
|
370
407
|
const profile = policy.profile
|
|
371
408
|
const view = measureForCompaction(this.ctx, session)
|
|
372
|
-
if (stage === 'fresh')
|
|
409
|
+
if (stage === 'fresh') {
|
|
410
|
+
// 真实 usage 聚合(monitor 口径):官方 TokenMeter 的上一已完成请求,
|
|
411
|
+
// 每 fresh 边界入账一次;pressure pass 读到同一 baseline,不重复计。
|
|
412
|
+
const usage = officialRequestUsage(view)
|
|
413
|
+
if (usage !== undefined) {
|
|
414
|
+
getSavingsLedger().recordUsage(String(session.id), usage)
|
|
415
|
+
}
|
|
416
|
+
return this.decideFreshStep(session, options, policy, view)
|
|
417
|
+
}
|
|
373
418
|
if (profile === 'off') return emptyResult()
|
|
374
419
|
|
|
375
420
|
const landed: PrunedEntry[] = []
|
|
@@ -1424,6 +1469,24 @@ export class ToolResultPruner extends Service {
|
|
|
1424
1469
|
policy.aggregateEnabled ? 'no-new-tool-result-candidates' : 'profile-policy')
|
|
1425
1470
|
return emptyResult()
|
|
1426
1471
|
}
|
|
1472
|
+
// 节省统计(负节省配对):新全文工具结果按 (session,seq) 一次性过账——
|
|
1473
|
+
// 命中"此前压缩过的原文哈希"即记抵消。挂在压力门控之前:全文重读无论
|
|
1474
|
+
// 本轮是否再次压缩,都使原声称的节省不再成立(先骨架后全文 = 负节省)。
|
|
1475
|
+
const ledger = getSavingsLedger()
|
|
1476
|
+
const sid = String(session.id)
|
|
1477
|
+
for (const candidate of candidates) {
|
|
1478
|
+
const text = flattenPlainText(candidate.event.data.message.content)
|
|
1479
|
+
if (text === undefined) continue
|
|
1480
|
+
ledger.noteFullText({
|
|
1481
|
+
sessionId: sid,
|
|
1482
|
+
seq: candidate.seq,
|
|
1483
|
+
text,
|
|
1484
|
+
measure: () =>
|
|
1485
|
+
candidate.count.kind === 'exact-tokenizer' && typeof candidate.count.tokens === 'number'
|
|
1486
|
+
? { tokens: candidate.count.tokens, basis: 'exact-tokenizer' }
|
|
1487
|
+
: { tokens: Math.ceil(candidate.characterPressure / 4), basis: 'characters' },
|
|
1488
|
+
})
|
|
1489
|
+
}
|
|
1427
1490
|
|
|
1428
1491
|
const plans = new Map<number, PlannedReplacement>()
|
|
1429
1492
|
let freshPlanned = 0
|
|
@@ -2226,6 +2289,25 @@ export class ToolResultPruner extends Service {
|
|
|
2226
2289
|
? exactSurface.tokenizerRevision
|
|
2227
2290
|
: 'chars-per-token-4.0',
|
|
2228
2291
|
})
|
|
2292
|
+
// 节省统计:tail-trim 组的原文配对键(纯文本结果才登记,富内容跳过——
|
|
2293
|
+
// 与 land() 同口径:只记已落盘、可配对者)。
|
|
2294
|
+
const groupText = shadowedSeqs
|
|
2295
|
+
.map(seq => sessionEvents(session)[seq])
|
|
2296
|
+
.filter((event): event is SessionEvent<'tool/result'> => event?.type === 'tool/result')
|
|
2297
|
+
.map(event => flattenPlainText(event.data.message.content))
|
|
2298
|
+
.filter((text): text is string => text !== undefined)
|
|
2299
|
+
.join('\n')
|
|
2300
|
+
if (groupText.length > 0) {
|
|
2301
|
+
getSavingsLedger().recordSaving({
|
|
2302
|
+
sessionId: String(session.id),
|
|
2303
|
+
component: 'tail-trim',
|
|
2304
|
+
tokensBefore,
|
|
2305
|
+
tokensAfter,
|
|
2306
|
+
basis: exact ? 'exact-tokenizer' : 'characters',
|
|
2307
|
+
sourceSeq: manifestSeq,
|
|
2308
|
+
originalText: groupText,
|
|
2309
|
+
})
|
|
2310
|
+
}
|
|
2229
2311
|
return
|
|
2230
2312
|
}
|
|
2231
2313
|
this.auditComponent(session, policy, 'tail-trim', 'pressure', 'skipped',
|
|
@@ -2380,6 +2462,18 @@ export class ToolResultPruner extends Service {
|
|
|
2380
2462
|
// record ONLY — the replacement content is untouched by this field.
|
|
2381
2463
|
...plan.elidedLines === undefined ? {} : { elidedLines: plan.elidedLines },
|
|
2382
2464
|
})
|
|
2465
|
+
// 节省统计:已实现的削减才入账(tokensBefore−tokensAfter,审计同源同口径);
|
|
2466
|
+
// 原文哈希登记,供后续全文重读/retrieve 抵消配对。
|
|
2467
|
+
const pairedOriginal = originalTextForSavings(candidate)
|
|
2468
|
+
getSavingsLedger().recordSaving({
|
|
2469
|
+
sessionId: String(session.id),
|
|
2470
|
+
component: plan.component,
|
|
2471
|
+
tokensBefore: plan.tokensBefore,
|
|
2472
|
+
tokensAfter: plan.tokensAfter,
|
|
2473
|
+
basis: plan.measurementBasis,
|
|
2474
|
+
sourceSeq: plan.sourceSeq,
|
|
2475
|
+
...(pairedOriginal === undefined ? {} : { originalText: pairedOriginal }),
|
|
2476
|
+
})
|
|
2383
2477
|
return {
|
|
2384
2478
|
originalSeq: candidate.seq,
|
|
2385
2479
|
sourceSeq: plan.sourceSeq,
|
|
@@ -6,6 +6,7 @@ import type {
|
|
|
6
6
|
CodeSkeletonSettings,
|
|
7
7
|
CompressionPolicy,
|
|
8
8
|
IntentSummarySettings,
|
|
9
|
+
MonitorPanelSettings,
|
|
9
10
|
CompressionProfile,
|
|
10
11
|
CustomCompressionPolicy,
|
|
11
12
|
PresetOptions,
|
|
@@ -136,6 +137,27 @@ function parseIntentSummarySettings(value: unknown): IntentSummarySettings {
|
|
|
136
137
|
return { enabled }
|
|
137
138
|
}
|
|
138
139
|
|
|
140
|
+
/**
|
|
141
|
+
* Strictly parse the persisted monitorPanel section. Mirrors the intentSummary
|
|
142
|
+
* section semantics: absent inherits the hidden default, while a
|
|
143
|
+
* present-but-invalid section is an explicitly invalid document.
|
|
144
|
+
*/
|
|
145
|
+
function parseMonitorPanelSettings(value: unknown): MonitorPanelSettings {
|
|
146
|
+
if (value === undefined) return { enabled: false }
|
|
147
|
+
if (!isPlainRecord(value)) {
|
|
148
|
+
throw new TypeError('Context-compression monitorPanel must be a plain object')
|
|
149
|
+
}
|
|
150
|
+
const keys = Object.keys(value)
|
|
151
|
+
if (keys.length !== 1 || keys[0] !== 'enabled') {
|
|
152
|
+
throw new TypeError(`Context-compression monitorPanel: expected exactly "enabled", got "${keys.join('", "')}"`)
|
|
153
|
+
}
|
|
154
|
+
const enabled = (value as Record<string, unknown>).enabled
|
|
155
|
+
if (typeof enabled !== 'boolean') {
|
|
156
|
+
throw new TypeError('Context-compression monitorPanel.enabled must be a boolean')
|
|
157
|
+
}
|
|
158
|
+
return { enabled }
|
|
159
|
+
}
|
|
160
|
+
|
|
139
161
|
/**
|
|
140
162
|
* Parse the optional tokenpilot-inspired preset sub-capability section. Absent
|
|
141
163
|
* inherits the preset defaults; present-but-invalid is rejected, mirroring the
|
|
@@ -276,6 +298,7 @@ export const DEFAULT_CONTEXT_COMPRESSION_SETTINGS: ContextCompressionSettings =
|
|
|
276
298
|
autoCompact: { thresholdPercent: AUTO_COMPACT_THRESHOLD_LIMITS.default },
|
|
277
299
|
codeSkeleton: { enabled: false },
|
|
278
300
|
intentSummary: { enabled: false },
|
|
301
|
+
monitorPanel: { enabled: false },
|
|
279
302
|
}
|
|
280
303
|
|
|
281
304
|
/**
|
|
@@ -313,7 +336,7 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
|
|
|
313
336
|
// remain valid and inherit their defaults; the sections themselves stay
|
|
314
337
|
// strictly shaped.
|
|
315
338
|
const unknown = Object.keys(candidate).find(key =>
|
|
316
|
-
key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'presetOptions')
|
|
339
|
+
key !== 'profile' && key !== 'custom' && key !== 'autoCompact' && key !== 'codeSkeleton' && key !== 'intentSummary' && key !== 'monitorPanel' && key !== 'presetOptions')
|
|
317
340
|
if (unknown !== undefined) {
|
|
318
341
|
throw new TypeError(`Context-compression settings: unknown key "${unknown}"`)
|
|
319
342
|
}
|
|
@@ -326,12 +349,14 @@ export const ContextCompressionSettingsSchema: z<ContextCompressionSettings> = z
|
|
|
326
349
|
const autoCompact = parseAutoCompactSettings(candidate.autoCompact)
|
|
327
350
|
const codeSkeleton = parseCodeSkeletonSettings(candidate.codeSkeleton)
|
|
328
351
|
const intentSummary = parseIntentSummarySettings(candidate.intentSummary)
|
|
352
|
+
const monitorPanel = parseMonitorPanelSettings(candidate.monitorPanel)
|
|
329
353
|
const presetOptions = parsePresetOptionsSettings(candidate.presetOptions)
|
|
330
354
|
return {
|
|
331
355
|
...contextCompressionSettingsInputSchema(candidate),
|
|
332
356
|
autoCompact,
|
|
333
357
|
codeSkeleton,
|
|
334
358
|
intentSummary,
|
|
359
|
+
monitorPanel,
|
|
335
360
|
...presetOptions === undefined ? {} : { presetOptions },
|
|
336
361
|
}
|
|
337
362
|
},
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Compression monitor surface for the floating panel (FAB, task: cci-monitor-fab).
|
|
3
|
+
*
|
|
4
|
+
* Three pieces, one module:
|
|
5
|
+
* - `buildMonitorSnapshot`: the savings snapshot (reused verbatim from the
|
|
6
|
+
* ledger — no second accounting) plus the turn-tail intent-summary block
|
|
7
|
+
* (override / observed flag / gate constants / last fold);
|
|
8
|
+
* - `applySessionOverride`: the `/ctx-summary` override state machine,
|
|
9
|
+
* addressed by session id — the panel buttons drive the same state the
|
|
10
|
+
* command drives, never a second one;
|
|
11
|
+
* - `estimateSavingsPricing`: moved here from the entry (the savings route
|
|
12
|
+
* and the monitor route share it; keeping it next to the monitor payload
|
|
13
|
+
* avoids a runtime → entry import cycle).
|
|
14
|
+
*
|
|
15
|
+
* The monitor route itself stays in the entry (`registerMonitorRoute`),
|
|
16
|
+
* mirroring the savings/estimator registrars: all webServer wiring lives in
|
|
17
|
+
* one place, the data plane lives here.
|
|
18
|
+
*
|
|
19
|
+
* Contract discipline: the published `/savings` route contract is frozen
|
|
20
|
+
* (estimator-route spec encodes it) — the monitor aggregates but never
|
|
21
|
+
* reshapes it; new fields attach under `intent` / `sessionScope`.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
/** Current host model-group selection, when the service exposes one. */
|
|
25
|
+
export interface AgentDefaultModelLike {
|
|
26
|
+
currentSelection?: () => { provider?: unknown, model?: unknown } | undefined
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
import { priceOfficialDeepSeekUsage } from './deepseek-official-pricing.ts'
|
|
30
|
+
import { getSavingsLedger, type SavingsLedger, type SavingsSnapshot } from './savings.ts'
|
|
31
|
+
import {
|
|
32
|
+
getLastIntentFold,
|
|
33
|
+
getObservedIntentEnabled,
|
|
34
|
+
getSummaryOverride,
|
|
35
|
+
setSummaryOverride,
|
|
36
|
+
type IntentFoldRecord,
|
|
37
|
+
} from './tokenpilot/advisor-state.ts'
|
|
38
|
+
import { INTENT_GATE_FLOOR_FRACTION, INTENT_GATE_GROWTH_TOKENS } from './tokenpilot/intent-gate.ts'
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 灾难性遗忘区建议阈值:占用达到该比例即建议压缩/裁剪(DeepSeek 等长上下文
|
|
42
|
+
* 模型在高占用段对早期内容的召回显著退化)。有意低于宿主 Auto Compact 阈值
|
|
43
|
+
* (默认 80%)——提前一档给出人工干预窗口。
|
|
44
|
+
*/
|
|
45
|
+
export const MONITOR_SUGGEST_PCT = 0.7
|
|
46
|
+
|
|
47
|
+
export interface MonitorIntentBlock {
|
|
48
|
+
/** Session-scoped override; absent = settings-driven. */
|
|
49
|
+
override: 'on' | 'off' | undefined
|
|
50
|
+
/** Settings flag as last observed by the gate; absent = gate not evaluated yet. */
|
|
51
|
+
observedEnabled: boolean | undefined
|
|
52
|
+
gate: { floorFraction: number, growthTokens: number }
|
|
53
|
+
lastFold: IntentFoldRecord | undefined
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export interface MonitorContextBlock {
|
|
57
|
+
liveTokens: number
|
|
58
|
+
contextWindow: number | undefined
|
|
59
|
+
/** liveTokens / contextWindow, rounded to 3 decimals; null when the window is unknown. */
|
|
60
|
+
pct: number | null
|
|
61
|
+
sessionId: string
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface MonitorSuggestionBlock {
|
|
65
|
+
/** 占用达到建议阈值——客户端点亮悬浮球并展示提示行。 */
|
|
66
|
+
suggest: boolean
|
|
67
|
+
thresholdPct: number
|
|
68
|
+
occupancyPct: number | null
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export type MonitorSnapshot = SavingsSnapshot & {
|
|
72
|
+
intent: MonitorIntentBlock
|
|
73
|
+
/** Latest observed context occupancy; undefined until the pruner observes a turn. */
|
|
74
|
+
context?: MonitorContextBlock
|
|
75
|
+
/** 灾难性遗忘区建议;未观测前 absent。 */
|
|
76
|
+
suggestion?: MonitorSuggestionBlock
|
|
77
|
+
/** The session the snapshot was filtered to; `null` = all-sessions aggregate. */
|
|
78
|
+
sessionScope: string | null
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* Savings snapshot plus the intent-summary control block. Ledger is
|
|
83
|
+
* injectable so tests seed a private instance instead of the process
|
|
84
|
+
* singleton.
|
|
85
|
+
*/
|
|
86
|
+
export function buildMonitorSnapshot(
|
|
87
|
+
sessionId?: string,
|
|
88
|
+
ledger: SavingsLedger = getSavingsLedger(),
|
|
89
|
+
): MonitorSnapshot {
|
|
90
|
+
const scopeKey = sessionId ?? ''
|
|
91
|
+
const override = getSummaryOverride(scopeKey)
|
|
92
|
+
const observedContext = scopeKey.length > 0
|
|
93
|
+
? getContextUsage(scopeKey)
|
|
94
|
+
: latestObservedContextUsage()
|
|
95
|
+
const contextBlock = observedContext === undefined
|
|
96
|
+
? undefined
|
|
97
|
+
: {
|
|
98
|
+
liveTokens: observedContext.liveTokens,
|
|
99
|
+
contextWindow: observedContext.contextWindow,
|
|
100
|
+
pct: observedContext.contextWindow !== undefined && observedContext.contextWindow > 0
|
|
101
|
+
? Math.round((observedContext.liveTokens / observedContext.contextWindow) * 1000) / 1000
|
|
102
|
+
: null,
|
|
103
|
+
sessionId: observedContext.sessionId,
|
|
104
|
+
}
|
|
105
|
+
const suggestion = contextBlock === undefined || contextBlock.pct === null
|
|
106
|
+
? undefined
|
|
107
|
+
: {
|
|
108
|
+
suggest: contextBlock.pct >= MONITOR_SUGGEST_PCT,
|
|
109
|
+
thresholdPct: MONITOR_SUGGEST_PCT,
|
|
110
|
+
occupancyPct: contextBlock.pct,
|
|
111
|
+
}
|
|
112
|
+
return {
|
|
113
|
+
...ledger.snapshot(sessionId),
|
|
114
|
+
...(contextBlock === undefined ? {} : { context: contextBlock }),
|
|
115
|
+
...(suggestion === undefined ? {} : { suggestion }),
|
|
116
|
+
intent: {
|
|
117
|
+
override,
|
|
118
|
+
observedEnabled: getObservedIntentEnabled(scopeKey),
|
|
119
|
+
gate: { floorFraction: INTENT_GATE_FLOOR_FRACTION, growthTokens: INTENT_GATE_GROWTH_TOKENS },
|
|
120
|
+
lastFold: getLastIntentFold(scopeKey),
|
|
121
|
+
},
|
|
122
|
+
sessionScope: sessionId ?? null,
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export interface ContextUsageObservation {
|
|
127
|
+
liveTokens: number
|
|
128
|
+
contextWindow: number | undefined
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** 每会话最近一次上下文占用观测;上限 64 会话,超出淘汰最旧。 */
|
|
132
|
+
const contextUsageBySession = new Map<string, ContextUsageObservation & { at: number; seq: number }>()
|
|
133
|
+
const CONTEXT_USAGE_CAP = 64
|
|
134
|
+
|
|
135
|
+
/**
|
|
136
|
+
* 由 pruner 的 turn-tail postflight 调用:记录该会话最近的 liveTokens/
|
|
137
|
+
* contextWindow,供 monitor 快照的占用条消费。空会话 id 忽略。
|
|
138
|
+
*/
|
|
139
|
+
export function observeContextUsage(sessionId: string, liveTokens: number, contextWindow: number | undefined): void {
|
|
140
|
+
if (sessionId.length === 0 || !Number.isFinite(liveTokens)) return
|
|
141
|
+
if (contextUsageBySession.size >= CONTEXT_USAGE_CAP) {
|
|
142
|
+
const oldest = contextUsageBySession.keys().next().value
|
|
143
|
+
if (oldest !== undefined) contextUsageBySession.delete(oldest)
|
|
144
|
+
}
|
|
145
|
+
contextUsageBySession.set(sessionId, { liveTokens, contextWindow, at: Date.now(), seq: ++observeSeq })
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export function getContextUsage(sessionId: string): (ContextUsageObservation & { sessionId: string }) | undefined {
|
|
149
|
+
const entry = contextUsageBySession.get(sessionId)
|
|
150
|
+
return entry === undefined ? undefined : { liveTokens: entry.liveTokens, contextWindow: entry.contextWindow, sessionId }
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
let observeSeq = 0
|
|
154
|
+
|
|
155
|
+
function latestObservedContextUsage(): (ContextUsageObservation & { sessionId: string }) | undefined {
|
|
156
|
+
let latest: (ContextUsageObservation & { sessionId: string; seq: number }) | undefined
|
|
157
|
+
for (const [sessionId, entry] of contextUsageBySession) {
|
|
158
|
+
if (latest === undefined || entry.seq > latest.seq) latest = { sessionId, liveTokens: entry.liveTokens, contextWindow: entry.contextWindow, seq: entry.seq }
|
|
159
|
+
}
|
|
160
|
+
return latest
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
export type SessionOverrideAction = 'on' | 'off' | 'clear'
|
|
164
|
+
|
|
165
|
+
export function isSessionOverrideAction(value: unknown): value is SessionOverrideAction {
|
|
166
|
+
return value === 'on' || value === 'off' || value === 'clear'
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/**
|
|
170
|
+
* Drive the `/ctx-summary` override state machine: `on`/`off` pin the
|
|
171
|
+
* session, `clear` returns it to settings-driven. The resulting override is
|
|
172
|
+
* handed back so the route can echo the post-action truth.
|
|
173
|
+
*/
|
|
174
|
+
export function applySessionOverride(
|
|
175
|
+
sessionId: string,
|
|
176
|
+
action: SessionOverrideAction,
|
|
177
|
+
): { override: 'on' | 'off' | undefined } {
|
|
178
|
+
setSummaryOverride(sessionId, action === 'clear' ? undefined : action)
|
|
179
|
+
return { override: getSummaryOverride(sessionId) }
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
/**
|
|
183
|
+
* 金额估算(monitor 口径的 token/金额估算,结合官方牌价):
|
|
184
|
+
* - actualCost:本进程累计真实 usage 的官方牌价(exact/range);
|
|
185
|
+
* - estimatedSavedCost:净节省(精确口径)按 cache-miss 输入价折算——
|
|
186
|
+
* 基线假设"这些 token 不压缩就要全价进上下文",标注估算。
|
|
187
|
+
* 仅官方 deepseek-official 路由可解;第三方/未知模型 fail-closed 为 undefined。
|
|
188
|
+
* (自入口迁入: savings 路由与 monitor 路由共享,避免 runtime → entry 回环。)
|
|
189
|
+
*/
|
|
190
|
+
export function estimateSavingsPricing(readService: (name: string) => unknown, snapshot: {
|
|
191
|
+
startedAt: string
|
|
192
|
+
net: { exact: number; estimated: number }
|
|
193
|
+
usage: { requests: number; inputTokens: number; outputTokens: number; cacheReadTokens: number; cacheWriteTokens: number }
|
|
194
|
+
}): { currency: string; actualCost?: string | undefined; estimatedSavedCost?: string | undefined } | undefined {
|
|
195
|
+
if (snapshot.usage.requests === 0 && snapshot.net.exact === 0) return undefined
|
|
196
|
+
const defaults = readService('agentDefaultModel') as AgentDefaultModelLike | undefined
|
|
197
|
+
const selection = defaults?.currentSelection?.()
|
|
198
|
+
const provider = typeof selection?.provider === 'string' ? selection.provider : ''
|
|
199
|
+
const modelId = typeof selection?.model === 'string' ? selection.model : ''
|
|
200
|
+
if (provider !== 'deepseek-official') return undefined
|
|
201
|
+
const now = new Date()
|
|
202
|
+
const startedAt = new Date(snapshot.startedAt)
|
|
203
|
+
const completedAt = now.getTime() > startedAt.getTime() ? now : new Date(startedAt.getTime() + 1)
|
|
204
|
+
const base = {
|
|
205
|
+
provider,
|
|
206
|
+
baseUrlClass: 'official-public',
|
|
207
|
+
apiRoute: 'chat-completions',
|
|
208
|
+
modelId,
|
|
209
|
+
currency: 'USD',
|
|
210
|
+
startedAt,
|
|
211
|
+
completedAt,
|
|
212
|
+
} as const
|
|
213
|
+
const actual = priceOfficialDeepSeekUsage({
|
|
214
|
+
...base,
|
|
215
|
+
usage: {
|
|
216
|
+
cacheReadTokens: Math.max(0, Math.round(snapshot.usage.cacheReadTokens)),
|
|
217
|
+
cacheMissTokens: Math.max(0, Math.round(snapshot.usage.inputTokens)),
|
|
218
|
+
outputTokens: Math.max(0, Math.round(snapshot.usage.outputTokens)),
|
|
219
|
+
},
|
|
220
|
+
})
|
|
221
|
+
const saved = snapshot.net.exact > 0
|
|
222
|
+
? priceOfficialDeepSeekUsage({
|
|
223
|
+
...base,
|
|
224
|
+
usage: { cacheReadTokens: 0, cacheMissTokens: Math.round(snapshot.net.exact), outputTokens: 0 },
|
|
225
|
+
})
|
|
226
|
+
: undefined
|
|
227
|
+
const decimalOf = (cost: typeof actual): string | undefined =>
|
|
228
|
+
cost.kind === 'exact' ? cost.decimal : cost.kind === 'range' ? cost.minimum.decimal : undefined
|
|
229
|
+
if (actual.kind === 'unpriced' && (saved === undefined || saved.kind === 'unpriced')) return undefined
|
|
230
|
+
return {
|
|
231
|
+
currency: 'USD',
|
|
232
|
+
...(actual.kind === 'unpriced' ? {} : { actualCost: decimalOf(actual) }),
|
|
233
|
+
...(saved === undefined || saved.kind === 'unpriced' ? {} : { estimatedSavedCost: decimalOf(saved) }),
|
|
234
|
+
}
|
|
235
|
+
}
|