dsh-context-compression-improved 0.9.8 → 0.9.9
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/.agents/plans/improve/checklist.md +32 -0
- package/.agents/plans/improve/findings.md +102 -0
- package/.agents/plans/improve/spec.md +53 -0
- package/.agents/plans/improve/tasks.md +70 -0
- package/CHANGELOG.md +4 -0
- package/README.md +14 -2
- package/README.zh.md +14 -2
- package/package.json +1 -1
- package/packages/selector/dsh.plugin.json +1 -1
- package/packages/selector/lib/client.d.ts +16 -0
- package/packages/selector/lib/client.js +396 -117
- package/packages/selector/lib/index.js +829 -10
- package/packages/selector/lib/invariant.js +2 -1
- package/packages/selector/lib/pruner.d.ts +1 -1
- package/packages/selector/lib/pruner.js +77 -983
- package/packages/selector/lib/savings-integral.js +4515 -0
- package/packages/selector/lib/tail-trim.js +2 -90
- package/packages/selector/lib/tool-result.js +150 -0
- package/packages/selector/package.json +8 -4
- package/packages/selector/src/client/index.ts +15 -12
- package/packages/selector/src/client/locales/de.ts +20 -4
- package/packages/selector/src/client/locales/es.ts +20 -4
- package/packages/selector/src/client/locales/fr.ts +20 -4
- package/packages/selector/src/client/locales/it.ts +20 -4
- package/packages/selector/src/client/locales/ja.ts +20 -4
- package/packages/selector/src/client/locales/ko.ts +20 -4
- package/packages/selector/src/client/locales/ru.ts +20 -4
- package/packages/selector/src/client/locales.ts +40 -8
- package/packages/selector/src/client/monitor-fab.ts +80 -10
- package/packages/selector/src/client/savings-card.tsx +159 -40
- package/packages/selector/src/index.ts +236 -1
- package/packages/selector/src/pruner.ts +54 -8
- package/packages/selector/src/runtime/audit.ts +17 -0
- package/packages/selector/src/runtime/display-prefs.ts +98 -0
- package/packages/selector/src/runtime/monitor.ts +75 -0
- package/packages/selector/src/runtime/panel-command.ts +213 -0
- package/packages/selector/src/runtime/retrieve.ts +31 -12
- package/packages/selector/src/runtime/savings-integral.ts +117 -0
- package/packages/selector/src/runtime/savings-projection.ts +3 -0
- package/packages/selector/src/runtime/savings-verify.ts +446 -0
- package/packages/selector/src/runtime/savings.ts +122 -13
- package/packages/selector/src/runtime/session-file-decode.ts +523 -0
- package/packages/selector/src/runtime/stats-backfill.ts +541 -0
- package/packages/selector/src/runtime/stats-db.ts +492 -0
- package/packages/selector/src/runtime/stats-schema.ts +123 -0
- package/packages/selector/src/runtime/stats-sync.ts +302 -0
- package/packages/selector/tests/estimator-route-registration.host.spec.ts +7 -4
- package/packages/selector/tests/monitor-fab.client.spec.ts +83 -1
- package/packages/selector/tests/runtime/fixtures/session-v4-dump.jsonl +46 -0
- package/packages/selector/tests/runtime/monitor.spec.ts +53 -0
- package/packages/selector/tests/runtime/panel-command.spec.ts +101 -0
- package/packages/selector/tests/runtime/public/public-runtime.spec.ts +0 -1
- package/packages/selector/tests/runtime/savings-accounting.spec.ts +291 -0
- package/packages/selector/tests/runtime/savings-integral.spec.ts +169 -0
- package/packages/selector/tests/runtime/savings-verify.spec.ts +226 -0
- package/packages/selector/tests/runtime/session-file-decode.spec.ts +281 -0
- package/packages/selector/tests/runtime/stats-backfill-scheduler.spec.ts +167 -0
- package/packages/selector/tests/runtime/stats-backfill.spec.ts +327 -0
- package/packages/selector/tests/runtime/stats-db.spec.ts +361 -0
- package/packages/selector/tests/runtime/stats-privacy.spec.ts +55 -0
- package/packages/selector/tests/runtime/stats-sync.spec.ts +278 -0
- package/packages/selector/tests/savings-sessions.client.spec.tsx +140 -0
- package/packages/selector/tests/settings-seat.client.spec.ts +15 -15
- package/pnpm-workspace.yaml +4 -0
- package/scripts/verify-release.mjs +5 -2
- package/vitest.config.ts +8 -0
- package/packages/selector/lib/config.js +0 -1777
- package/packages/selector/lib/host-generation.js +0 -62
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `/ccip` — context-compression-improved panel 实时控制命令(spec T29/T30/T31)。
|
|
3
|
+
*
|
|
4
|
+
* 子命令(`parsePanelCommandArgs` 为纯函数,单测钉死):
|
|
5
|
+
* - `status` —— 面板状态总览(行开关/模式/聚焦、持久化状态、回填进度)
|
|
6
|
+
* - `rows stock|total|money on|off` —— 三行显示开关
|
|
7
|
+
* - `mode compact|full`
|
|
8
|
+
* - `session <id|latest|off>` —— 面板聚焦会话(latest = stats sessions 表
|
|
9
|
+
* updated_at 最新,usage 水位每秒 upsert 使活跃会话自然浮前)
|
|
10
|
+
* - `flush` —— 立即冲刷在途 usage debounce
|
|
11
|
+
* - `backfill pause|resume|status`
|
|
12
|
+
*
|
|
13
|
+
* 实时语义:命令改 server 端 displayPrefs(meta 表持久)→ 客户端下一轮询周期
|
|
14
|
+
* (忙 2s/闲 5s)经 /savings/sessions 载荷拾取。不开推送通道(决策记录)。
|
|
15
|
+
*
|
|
16
|
+
* 注册形态与 `/ctx-summary` 完全同款:optional `commands` 服务注入 + 动态
|
|
17
|
+
* `CommandDefinitionId` brand import 降级——无注册表宿主静默不挂载,插件加载
|
|
18
|
+
* 零报错;registry 拒收也只吞掉命令面本身。
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-context-compression-improved/runtime/panel-command
|
|
21
|
+
*/
|
|
22
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
23
|
+
import {
|
|
24
|
+
getDisplayPrefs,
|
|
25
|
+
setDisplayPrefs,
|
|
26
|
+
} from './display-prefs.ts'
|
|
27
|
+
import {
|
|
28
|
+
getStatsBackfillStatus,
|
|
29
|
+
pauseStatsBackfill,
|
|
30
|
+
resumeStatsBackfill,
|
|
31
|
+
} from './stats-backfill.ts'
|
|
32
|
+
import { statsPersistenceState } from './stats-db.ts'
|
|
33
|
+
import { flushPendingUsageNow } from './stats-sync.ts'
|
|
34
|
+
import { verifySessionSavingsLines } from './savings-verify.ts'
|
|
35
|
+
import { getStatsStore } from './stats-db.ts'
|
|
36
|
+
|
|
37
|
+
export const PANEL_COMMAND_NAME = 'ccip'
|
|
38
|
+
|
|
39
|
+
const USAGE = [
|
|
40
|
+
'Usage: /ccip <subcommand>',
|
|
41
|
+
' status',
|
|
42
|
+
' rows stock|total|money on|off',
|
|
43
|
+
' mode compact|full',
|
|
44
|
+
' session <id|latest|off>',
|
|
45
|
+
' flush',
|
|
46
|
+
' backfill pause|resume|status',
|
|
47
|
+
].join('\n')
|
|
48
|
+
|
|
49
|
+
/** 一条已解析的 /ccip 子命令(纯数据,测试直接断言)。 */
|
|
50
|
+
export type PanelCommandArgs =
|
|
51
|
+
| { op: 'status' }
|
|
52
|
+
| { op: 'rows'; row: 'stock' | 'total' | 'money'; on: boolean }
|
|
53
|
+
| { op: 'mode'; mode: 'full' | 'compact' }
|
|
54
|
+
| { op: 'session'; target: { kind: 'id'; id: string } | { kind: 'latest' } | { kind: 'off' } }
|
|
55
|
+
| { op: 'flush' }
|
|
56
|
+
| { op: 'backfill'; action: 'pause' | 'resume' | 'status' }
|
|
57
|
+
| { op: 'verify'; sessionId?: string }
|
|
58
|
+
|
|
59
|
+
/** 解析原始参数串;undefined = 无法识别(回 usage)。 */
|
|
60
|
+
export function parsePanelCommandArgs(rawInput: string): PanelCommandArgs | undefined {
|
|
61
|
+
const tokens = rawInput.trim().toLowerCase().split(/\s+/u).filter(token => token !== '')
|
|
62
|
+
if (tokens.length === 0) return undefined
|
|
63
|
+
const [head, ...rest] = tokens
|
|
64
|
+
if (head === 'status' && rest.length === 0) return { op: 'status' }
|
|
65
|
+
if (head === 'flush' && rest.length === 0) return { op: 'flush' }
|
|
66
|
+
if (head === 'rows' && rest.length === 2) {
|
|
67
|
+
const row = rest[0]
|
|
68
|
+
const on = rest[1]
|
|
69
|
+
if ((row === 'stock' || row === 'total' || row === 'money') && (on === 'on' || on === 'off')) {
|
|
70
|
+
return { op: 'rows', row, on: on === 'on' }
|
|
71
|
+
}
|
|
72
|
+
return undefined
|
|
73
|
+
}
|
|
74
|
+
if (head === 'mode' && rest.length === 1 && (rest[0] === 'compact' || rest[0] === 'full')) {
|
|
75
|
+
return { op: 'mode', mode: rest[0] }
|
|
76
|
+
}
|
|
77
|
+
if (head === 'session' && rest.length === 1) {
|
|
78
|
+
const target = rest[0]
|
|
79
|
+
if (target === undefined) return undefined
|
|
80
|
+
if (target === 'off') return { op: 'session', target: { kind: 'off' } }
|
|
81
|
+
if (target === 'latest') return { op: 'session', target: { kind: 'latest' } }
|
|
82
|
+
if (target.length <= 512) return { op: 'session', target: { kind: 'id', id: target } }
|
|
83
|
+
return undefined
|
|
84
|
+
}
|
|
85
|
+
if (head === 'backfill' && rest.length === 1 && (rest[0] === 'pause' || rest[0] === 'resume' || rest[0] === 'status')) {
|
|
86
|
+
return { op: 'backfill', action: rest[0] }
|
|
87
|
+
}
|
|
88
|
+
// verify [latest|<sessionId>]:无参 = 当前活跃会话;'latest' 视同无参
|
|
89
|
+
if (head === 'verify' && rest.length <= 1) {
|
|
90
|
+
const target = rest[0]
|
|
91
|
+
if (target === undefined || target === 'latest') return { op: 'verify' }
|
|
92
|
+
if (target.length <= 512) return { op: 'verify', sessionId: target }
|
|
93
|
+
return undefined
|
|
94
|
+
}
|
|
95
|
+
return undefined
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
function persistedLine(): string {
|
|
99
|
+
const state = statsPersistenceState()
|
|
100
|
+
return state.persisted ? `persisted: yes (${state.driver})` : `persisted: no (${state.reason})`
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function backfillLine(): string {
|
|
104
|
+
const status = getStatsBackfillStatus()
|
|
105
|
+
const summary = status.lastSummary === undefined
|
|
106
|
+
? 'no pass yet'
|
|
107
|
+
: `${status.lastSummary.backend}: sessions=${String(status.lastSummary.sessions)} claims+${String(status.lastSummary.claimsAdded)}`
|
|
108
|
+
return `backfill: ${status.paused ? 'paused' : status.running ? 'running' : 'idle'}, runs=${String(status.runs)}, last ${summary}`
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function formatStatus(): string {
|
|
112
|
+
const prefs = getDisplayPrefs()
|
|
113
|
+
return [
|
|
114
|
+
'ccip status:',
|
|
115
|
+
` rows: stock=${prefs.rows.stock ? 'on' : 'off'} total=${prefs.rows.total ? 'on' : 'off'} money=${prefs.rows.money ? 'on' : 'off'}`,
|
|
116
|
+
` mode: ${prefs.mode}`,
|
|
117
|
+
` focus session: ${prefs.focusSessionId ?? 'off'}`,
|
|
118
|
+
` ${persistedLine()}`,
|
|
119
|
+
` ${backfillLine()}`,
|
|
120
|
+
].join('\n')
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** `/ccip` 无会话依赖(与 /ctx-summary 不同:面板偏好是进程级而非会话级)。 */
|
|
124
|
+
export function executePanelCommand(args: PanelCommandArgs): { kind: 'success' | 'error'; text: string } {
|
|
125
|
+
switch (args.op) {
|
|
126
|
+
case 'status':
|
|
127
|
+
return { kind: 'success', text: formatStatus() }
|
|
128
|
+
case 'rows': {
|
|
129
|
+
const prefs = setDisplayPrefs({ rows: { [args.row]: args.on } })
|
|
130
|
+
return { kind: 'success', text: `ccip: ${args.row} row ${args.on ? 'on' : 'off'} (stock=${String(prefs.rows.stock)} total=${String(prefs.rows.total)} money=${String(prefs.rows.money)})` }
|
|
131
|
+
}
|
|
132
|
+
case 'mode': {
|
|
133
|
+
setDisplayPrefs({ mode: args.mode })
|
|
134
|
+
return { kind: 'success', text: `ccip: panel mode ${args.mode}` }
|
|
135
|
+
}
|
|
136
|
+
case 'session': {
|
|
137
|
+
if (args.target.kind === 'off') {
|
|
138
|
+
setDisplayPrefs({ focusSessionId: null })
|
|
139
|
+
return { kind: 'success', text: 'ccip: panel focus off' }
|
|
140
|
+
}
|
|
141
|
+
if (args.target.kind === 'id') {
|
|
142
|
+
setDisplayPrefs({ focusSessionId: args.target.id })
|
|
143
|
+
return { kind: 'success', text: `ccip: panel focus ${args.target.id}` }
|
|
144
|
+
}
|
|
145
|
+
const latest = getStatsStore()?.recentSessionIds(1)[0]
|
|
146
|
+
if (latest === undefined) return { kind: 'error', text: 'ccip: no known session yet (stats store empty)' }
|
|
147
|
+
setDisplayPrefs({ focusSessionId: latest.sessionId })
|
|
148
|
+
return { kind: 'success', text: `ccip: panel focus ${latest.sessionId} (latest)` }
|
|
149
|
+
}
|
|
150
|
+
case 'flush': {
|
|
151
|
+
flushPendingUsageNow()
|
|
152
|
+
return { kind: 'success', text: 'ccip: pending usage flushed to stats store' }
|
|
153
|
+
}
|
|
154
|
+
case 'backfill': {
|
|
155
|
+
if (args.action === 'pause') { pauseStatsBackfill(); return { kind: 'success', text: 'ccip: backfill paused' } }
|
|
156
|
+
if (args.action === 'resume') { resumeStatsBackfill(); return { kind: 'success', text: 'ccip: backfill resumed' } }
|
|
157
|
+
return { kind: 'success', text: `ccip: ${backfillLine()}` }
|
|
158
|
+
}
|
|
159
|
+
case 'verify': {
|
|
160
|
+
// 验算:jsonl 原文 × DS token 口径独立重算六值,与持久 claims 对账;
|
|
161
|
+
// 缺省目标 = 当前活跃会话(运行时指针)。
|
|
162
|
+
const text = args.sessionId === undefined
|
|
163
|
+
? verifySessionSavingsLines().join('\n')
|
|
164
|
+
: verifySessionSavingsLines({ sessionId: args.sessionId }).join('\n')
|
|
165
|
+
return { kind: 'success', text }
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
type CommandsServiceLike = {
|
|
171
|
+
register: (definition: {
|
|
172
|
+
definitionId?: unknown
|
|
173
|
+
name: string
|
|
174
|
+
description: string
|
|
175
|
+
handler: (invocation: { agent?: unknown, rawInput?: unknown }) => Promise<{ kind: 'success' | 'error', text: string }>
|
|
176
|
+
}) => unknown
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Best-effort `CommandDefinitionId` brand;stripped 宿主返回 undefined(不带 definitionId 注册)。 */
|
|
180
|
+
async function loadCommandDefinitionId(): Promise<((id: string) => unknown) | undefined> {
|
|
181
|
+
try {
|
|
182
|
+
const mod = (await import('@deepseek-ai/dsh-commands')) as { CommandDefinitionId?: (id: string) => unknown }
|
|
183
|
+
return mod.CommandDefinitionId
|
|
184
|
+
} catch {
|
|
185
|
+
return undefined
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 挂载 `/ccip`;永不抛错(无 commands 服务的宿主静默不挂载)。 */
|
|
190
|
+
export function registerPanelCommand(ctx: Context): void {
|
|
191
|
+
ctx.inject(['commands'], (injected) => {
|
|
192
|
+
const commands = (injected as { commands?: unknown }).commands as CommandsServiceLike | undefined
|
|
193
|
+
if (commands === undefined || typeof commands.register !== 'function') return
|
|
194
|
+
void (async () => {
|
|
195
|
+
try {
|
|
196
|
+
const definitionId = await loadCommandDefinitionId()
|
|
197
|
+
await commands.register({
|
|
198
|
+
name: PANEL_COMMAND_NAME,
|
|
199
|
+
description: 'Context-compression panel: toggle rows/mode, focus a session, flush stats, pause backfill',
|
|
200
|
+
...(definitionId === undefined ? {} : { definitionId: definitionId('dsh-context-compression-improved/ccip') }),
|
|
201
|
+
handler: async (invocation) => {
|
|
202
|
+
const rawInput = typeof invocation.rawInput === 'string' ? invocation.rawInput : ''
|
|
203
|
+
const args = parsePanelCommandArgs(rawInput)
|
|
204
|
+
if (args === undefined) return { kind: 'error' as const, text: USAGE }
|
|
205
|
+
return executePanelCommand(args)
|
|
206
|
+
},
|
|
207
|
+
})
|
|
208
|
+
} catch {
|
|
209
|
+
// Registry 拒收(形状漂移等):插件照常工作,只缺席命令面。
|
|
210
|
+
}
|
|
211
|
+
})()
|
|
212
|
+
})
|
|
213
|
+
}
|
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
} from './tail-trim.ts'
|
|
21
21
|
import { sessionEvents } from './session-events.ts'
|
|
22
22
|
import { getSavingsLedger } from './savings.ts'
|
|
23
|
+
import { claimOffset } from './stats-sync.ts'
|
|
23
24
|
import { viewToolResult } from '../compat/tool-result.ts'
|
|
24
25
|
|
|
25
26
|
export const name = 'context-compression-retrieve'
|
|
@@ -93,11 +94,13 @@ export function installContextCompressionRetrieve(ctx: Context, config: Config =
|
|
|
93
94
|
throw new Error('context_compression_retrieve: ref must be session://<session-id>/(event|tailtrim)/<seq>')
|
|
94
95
|
}
|
|
95
96
|
const sessionId = match?.[1] ?? tailTrimRef?.sessionId
|
|
96
|
-
|
|
97
|
+
// 身份键一律用 session.id(与 pruner 落账/占位符 sourceRef 同键);旧版这里
|
|
98
|
+
// 用 exec.agent.id,两键不一致时抵消会记到另一本账上。
|
|
99
|
+
if (sessionId !== String(exec.agent.session.id)) {
|
|
97
100
|
throw new Error('context_compression_retrieve: a compression reference may only read the caller\'s current session')
|
|
98
101
|
}
|
|
99
102
|
if (tailTrimRef !== null) {
|
|
100
|
-
const sessionId = String(exec.agent.id)
|
|
103
|
+
const sessionId = String(exec.agent.session.id)
|
|
101
104
|
return Promise.resolve(recoverTailTrim(
|
|
102
105
|
exec.agent.session,
|
|
103
106
|
args.ref,
|
|
@@ -107,14 +110,22 @@ export function installContextCompressionRetrieve(ctx: Context, config: Config =
|
|
|
107
110
|
args.max_lines,
|
|
108
111
|
{ maxChars, maxScanChars, maxQueryChars },
|
|
109
112
|
)).then((text: string) => {
|
|
110
|
-
// 节省统计:回读内容重新进入上下文 =
|
|
111
|
-
// (chars/4 估算口径;retrieve 不持有精确 counter
|
|
112
|
-
|
|
113
|
+
// 节省统计:回读内容重新进入上下文 = 对该组原声称节省的抵消。
|
|
114
|
+
// 同 basis(chars/4 估算口径;retrieve 不持有精确 counter 身份,
|
|
115
|
+
// 分列不混算)经 foldRecall 折进源条目翻负;跨基退化带 sourceSeq 的收敛 offset。
|
|
116
|
+
const offsetTokens = Math.ceil(codePointLength(text) / 4)
|
|
117
|
+
getSavingsLedger().foldRecall(sessionId, tailTrimRef.manifestSeq, offsetTokens, 'characters', {
|
|
118
|
+
component: 'tailtrim-retrieve',
|
|
119
|
+
note: `tailtrim/${tailTrimRef.manifestSeq} 回读`,
|
|
120
|
+
})
|
|
121
|
+
// T6 接线:持久 offset claim(流水审计层);幂等键含 manifestSeq,
|
|
122
|
+
// 同源反复召回首次入账、重放去重(定键口径见 stats-sync 头注)。
|
|
123
|
+
claimOffset({
|
|
113
124
|
sessionId,
|
|
114
125
|
component: 'tailtrim-retrieve',
|
|
115
|
-
tokens:
|
|
126
|
+
tokens: offsetTokens,
|
|
116
127
|
basis: 'characters',
|
|
117
|
-
|
|
128
|
+
sourceSeq: tailTrimRef.manifestSeq,
|
|
118
129
|
})
|
|
119
130
|
return text
|
|
120
131
|
})
|
|
@@ -159,14 +170,22 @@ export function installContextCompressionRetrieve(ctx: Context, config: Config =
|
|
|
159
170
|
].filter(Boolean).join('\n')
|
|
160
171
|
const output = `${header}\n${selected.text}`
|
|
161
172
|
const bounded = boundCodePoints(output, maxChars)
|
|
162
|
-
// 节省统计:retrieve 产物重新进入上下文 = 抵消(chars/4 估算口径)
|
|
163
|
-
|
|
164
|
-
|
|
173
|
+
// 节省统计:retrieve 产物重新进入上下文 = 抵消(chars/4 估算口径);
|
|
174
|
+
// 同 basis 折进源条目翻负,R = boundCodePoints 后的实测值,跨基退化为
|
|
175
|
+
// 带 sourceSeq(event/N)的收敛 offset。落账键用 session.id 与 pruner 统一。
|
|
176
|
+
const offsetTokens = Math.ceil(codePointLength(bounded) / 4)
|
|
177
|
+
getSavingsLedger().foldRecall(String(exec.agent.session.id), seq, offsetTokens, 'characters', {
|
|
165
178
|
component: 'retrieve',
|
|
166
|
-
tokens: Math.ceil(codePointLength(bounded) / 4),
|
|
167
|
-
basis: 'characters',
|
|
168
179
|
note: `event/${String(seq)} 回读`,
|
|
169
180
|
})
|
|
181
|
+
// T6 接线:持久 offset claim;幂等键 (session_id, 源事件绝对 seq, …)。
|
|
182
|
+
claimOffset({
|
|
183
|
+
sessionId: String(exec.agent.session.id),
|
|
184
|
+
component: 'retrieve',
|
|
185
|
+
tokens: offsetTokens,
|
|
186
|
+
basis: 'characters',
|
|
187
|
+
sourceSeq: seq,
|
|
188
|
+
})
|
|
170
189
|
return Promise.resolve(bounded)
|
|
171
190
|
},
|
|
172
191
|
}))
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 按 call 积分器(spec T15/T16)——"真节省"口径。
|
|
3
|
+
*
|
|
4
|
+
* 定义:真节省 = Σ_每次call(该次基线输入 − 实际输入)。存量(delta, observeActive
|
|
5
|
+
* 收敛)回答"现在省多少";积分把每个 fresh 边界的存量净快照累加成跨重启的
|
|
6
|
+
* "累计(按 N 次 call)"。召回不追溯翻账:召回前的 call 真省过钱,样本保留;
|
|
7
|
+
* 召回后存量转负,后续采样自然把积分往下拉——前向口径,历史样本永不改写。
|
|
8
|
+
*
|
|
9
|
+
* 采样点:pruneSession stage='fresh' 的 recordUsage 同点(pruner 接线行,本
|
|
10
|
+
* 模块不重做任何测量)。boundarySeq = 采样时刻事件日志的最大绝对 seq——每完成
|
|
11
|
+
* 一次请求日志必追加(assistant/message 等),相邻两次 fresh 采样之间 maxSeq
|
|
12
|
+
* 单调递增,天然构成 per-call 幂等键;同 seq 重放被 claims 主键吸收。
|
|
13
|
+
*
|
|
14
|
+
* 省钱口径(T16):cached/uncached 分权——cachedInput×inputCacheHit +
|
|
15
|
+
* uncachedInput×inputCacheMiss(官方定价目录,定点 bigint,零浮点)。无定价
|
|
16
|
+
* 路由(非 deepseek-official 官方公网/未知模型)返回 null,面板仅 token 口径。
|
|
17
|
+
* 拆分规则:cacheReadTokens = 命中数;uncached = inputTokens − cacheRead
|
|
18
|
+
* (负值截 0)。首 call 无 usage 报告时照常采样存量(calls 照计,拆分记 0)。
|
|
19
|
+
*
|
|
20
|
+
* @module dsh-context-compression-improved/runtime/savings-integral
|
|
21
|
+
*/
|
|
22
|
+
import type { Session } from '@deepseek-ai/dsh-session'
|
|
23
|
+
import {
|
|
24
|
+
decimalRateNanoUnits,
|
|
25
|
+
type OfficialDeepSeekPriceRecord,
|
|
26
|
+
} from './deepseek-official-pricing.ts'
|
|
27
|
+
import { sessionEvents } from './session-events.ts'
|
|
28
|
+
import { recordIntegralSample } from './stats-sync.ts'
|
|
29
|
+
|
|
30
|
+
/** 一次 fresh 边界采样的输入(测量由调用方完成,本模块只定键、拆分、落库)。 */
|
|
31
|
+
export interface IntegralSampleInput {
|
|
32
|
+
sessionId: string
|
|
33
|
+
session: Session
|
|
34
|
+
/** 内存账本当前存量净额(snapshot(sessionId).net,双 basis 分列)。 */
|
|
35
|
+
net: { exact: number; estimated: number }
|
|
36
|
+
/** 该边界读到的上一已完成请求官方 usage;首 call 缺报时 undefined。 */
|
|
37
|
+
usage?: { inputTokens?: number; cacheReadTokens?: number } | undefined
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** 采样时刻事件日志的最大绝对 seq;空日志(无从定键)返回 undefined。 */
|
|
41
|
+
export function latestEventSeq(session: Session): number | undefined {
|
|
42
|
+
let max: number | undefined
|
|
43
|
+
for (const event of sessionEvents(session)) {
|
|
44
|
+
const seq = Number(event.seq)
|
|
45
|
+
if (Number.isFinite(seq)) max = max === undefined ? seq : Math.max(max, seq)
|
|
46
|
+
}
|
|
47
|
+
return max
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** usage 拆分:cacheRead = 命中;uncached = input − cacheRead(负截 0);非法值记 0。 */
|
|
51
|
+
export function splitCachedUncached(usage: IntegralSampleInput['usage']): { cachedInput: number; uncachedInput: number } {
|
|
52
|
+
const cached = typeof usage?.cacheReadTokens === 'number' && Number.isFinite(usage.cacheReadTokens) && usage.cacheReadTokens > 0
|
|
53
|
+
? Math.trunc(usage.cacheReadTokens)
|
|
54
|
+
: 0
|
|
55
|
+
const input = typeof usage?.inputTokens === 'number' && Number.isFinite(usage.inputTokens) && usage.inputTokens > 0
|
|
56
|
+
? Math.trunc(usage.inputTokens)
|
|
57
|
+
: 0
|
|
58
|
+
return { cachedInput: cached, uncachedInput: Math.max(0, input - cached) }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** fresh 边界采样入口:定键 → 拆分 → 经 stats-sync 幂等落库;空日志静默跳过。 */
|
|
62
|
+
export function sampleIntegralBoundary(input: IntegralSampleInput): void {
|
|
63
|
+
const boundarySeq = latestEventSeq(input.session)
|
|
64
|
+
if (boundarySeq === undefined) return
|
|
65
|
+
const { cachedInput, uncachedInput } = splitCachedUncached(input.usage)
|
|
66
|
+
recordIntegralSample({
|
|
67
|
+
sessionId: input.sessionId,
|
|
68
|
+
boundarySeq,
|
|
69
|
+
netExact: input.net.exact,
|
|
70
|
+
netEstimated: input.net.estimated,
|
|
71
|
+
cachedInput,
|
|
72
|
+
uncachedInput,
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 定价目录单位(每 1M tokens)下的双科目省钱估计;记录缺有效费率 = null。 */
|
|
77
|
+
export interface IntegralMoneyEstimate {
|
|
78
|
+
/** 定点十进制(主币种单位),格式同定价模块 femto 渲染。 */
|
|
79
|
+
decimal: string
|
|
80
|
+
/** 原始定点整数(femto 主币种单位),供聚合而不丢精度。 */
|
|
81
|
+
femtoUnits: string
|
|
82
|
+
currency: 'USD' | 'CNY'
|
|
83
|
+
band: 'peak' | 'off-peak'
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 省钱估计(T16):cached 走 inputCacheHit、uncached 走 inputCacheMiss,
|
|
88
|
+
* femto = tokens × nanoRate(与定价模块 amountFor 同构,输出侧不计——
|
|
89
|
+
* 积分口径只对输入省钱)。费率不可解析(理论上目录内不会)返回 null。
|
|
90
|
+
*/
|
|
91
|
+
export function estimateIntegralMoney(input: {
|
|
92
|
+
cachedInput: number
|
|
93
|
+
uncachedInput: number
|
|
94
|
+
record: OfficialDeepSeekPriceRecord
|
|
95
|
+
}): IntegralMoneyEstimate | null {
|
|
96
|
+
const hit = decimalRateNanoUnits(input.record.inputCacheHit)
|
|
97
|
+
const miss = decimalRateNanoUnits(input.record.inputCacheMiss)
|
|
98
|
+
if (hit === undefined || miss === undefined) return null
|
|
99
|
+
const cached = Number.isFinite(input.cachedInput) && input.cachedInput > 0 ? BigInt(Math.trunc(input.cachedInput)) : 0n
|
|
100
|
+
const uncached = Number.isFinite(input.uncachedInput) && input.uncachedInput > 0 ? BigInt(Math.trunc(input.uncachedInput)) : 0n
|
|
101
|
+
if (cached === 0n && uncached === 0n) return null
|
|
102
|
+
const femtoUnits = cached * hit + uncached * miss
|
|
103
|
+
return {
|
|
104
|
+
decimal: formatFemtoUnits(femtoUnits),
|
|
105
|
+
femtoUnits: femtoUnits.toString(),
|
|
106
|
+
currency: input.record.currency,
|
|
107
|
+
band: input.record.band,
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** femto(1e-15)整数 → 十进制串;与定价模块的 femto 渲染同构(模块内私有,此处独立实现)。 */
|
|
112
|
+
function formatFemtoUnits(value: bigint): string {
|
|
113
|
+
const digits = value.toString().padStart(16, '0')
|
|
114
|
+
const whole = digits.slice(0, -15)
|
|
115
|
+
const fraction = digits.slice(-15).replace(/0+$/u, '')
|
|
116
|
+
return fraction.length === 0 ? whole : `${whole}.${fraction}`
|
|
117
|
+
}
|
|
@@ -42,6 +42,8 @@ export interface ProjectedOffset {
|
|
|
42
42
|
tokens: number
|
|
43
43
|
basis: SavingsBasis
|
|
44
44
|
at: number
|
|
45
|
+
/** 重读事件的绝对 seq(持久 claims 主键需要;投影条目靠它定位到日志行)。 */
|
|
46
|
+
seq: number
|
|
45
47
|
note: string
|
|
46
48
|
}
|
|
47
49
|
export interface ProjectedRegistryItem {
|
|
@@ -205,6 +207,7 @@ export function projectSavingsCore(input: {
|
|
|
205
207
|
tokens: priced.tokens,
|
|
206
208
|
basis: priced.basis,
|
|
207
209
|
at: Number(event.time) || 0,
|
|
210
|
+
seq: Number(event.seq),
|
|
208
211
|
note: `#${hit.sourceSeq} 的原文被全文重读(投影重建)`,
|
|
209
212
|
})
|
|
210
213
|
}
|