@lingda-ai/dsh-plugin-ledger 0.1.3 → 0.1.4
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/LICENSE +17 -0
- package/cordis.patch.yml +3 -2
- package/docs/business-plan.md +237 -0
- package/docs/spikes.md +373 -0
- package/docs/technical.md +364 -0
- package/docs/wire-format.md +95 -0
- package/lib/attribution.js +73 -0
- package/lib/audit-tool.js +184 -0
- package/lib/budget-message.js +28 -0
- package/lib/client.js +217 -0
- package/lib/config.js +74 -0
- package/lib/guard.js +102 -0
- package/lib/identity.js +119 -0
- package/lib/index.js +217 -0
- package/lib/ledger.js +260 -0
- package/lib/panel-path.js +39 -0
- package/lib/panel-view.js +717 -0
- package/lib/pricing-file.js +169 -0
- package/lib/pricing-table.js +55 -0
- package/lib/pricing.js +84 -0
- package/lib/ring.js +54 -0
- package/lib/snapshot-file.js +293 -0
- package/lib/store.js +330 -0
- package/lib/tool-size.js +25 -0
- package/lib/trace-file.js +139 -0
- package/lib/trace.js +82 -0
- package/lib/usage.js +67 -0
- package/lib/wire.js +87 -0
- package/package.json +25 -5
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 费率覆盖文件 —— 让"官方调价"不必改代码,也让改错不至于算错钱。
|
|
3
|
+
*
|
|
4
|
+
* 为什么需要它:
|
|
5
|
+
* 内置价表(pricing-table.js)写死了 2026-11-19 的价格。官方一调价,
|
|
6
|
+
* 所有用户看到的金额就**静默地**错了。对成本类产品,算错钱是信任级事故,
|
|
7
|
+
* 比少一个功能严重得多。
|
|
8
|
+
*
|
|
9
|
+
* 为什么是"整条生效或整条拒绝",而不是逐档合并:
|
|
10
|
+
* 四档费率共同定义一个模型的价格语义。缺一档就合并,等于拿旧价补新价,
|
|
11
|
+
* 算出来的数字既不是旧价也不是新价。宁可不认这个模型(costOf 返回 no-rate,
|
|
12
|
+
* 面板显示"—"),也不给一个看起来像真的假数。
|
|
13
|
+
*
|
|
14
|
+
* 为什么在 boot 读一次、不监听文件变化:
|
|
15
|
+
* 计价发生在每条 assistant/message 的热路径上。热路径不做 IO 是硬约束。
|
|
16
|
+
* 改费率后重启会话即可生效——这个代价换的是"每笔计价都稳定",
|
|
17
|
+
* 而计价不稳定比多等一次重启危险得多。
|
|
18
|
+
*
|
|
19
|
+
* 单位:文件里写的是**元 / 百万 tokens**(和官方页面、和价格公告一致),
|
|
20
|
+
* 内部转成元 / token。让人手写 1.2 而不是 0.0000012。
|
|
21
|
+
*/
|
|
22
|
+
import { readFileSync } from 'node:fs'
|
|
23
|
+
import { homedir } from 'node:os'
|
|
24
|
+
import { join } from 'node:path'
|
|
25
|
+
|
|
26
|
+
/** 覆盖文件默认位置:与 device-id 同目录,都在 ~/.dsh/ledger 下 */
|
|
27
|
+
export const PRICING_FILE_NAME = 'pricing.json'
|
|
28
|
+
|
|
29
|
+
const M = 1e-6
|
|
30
|
+
const REQUIRED_FIELDS = ['input', 'output', 'cacheRead', 'cacheWrite']
|
|
31
|
+
|
|
32
|
+
export function defaultPricingPath() {
|
|
33
|
+
return join(homedir(), '.dsh', 'ledger', PRICING_FILE_NAME)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* 解析文件文本。纯函数,异常不外抛——文件是用户手写的,必须能给出可读原因。
|
|
38
|
+
*
|
|
39
|
+
* @param {string} text
|
|
40
|
+
* @returns {{kind:'ok', rates:Record<string,object>, rejected:Array<object>, asOf:string|null, source:string|null, currency:string|null}
|
|
41
|
+
* |{kind:'invalid', reason:string, rejected:Array<object>}}
|
|
42
|
+
*/
|
|
43
|
+
export function parsePricingFile(text) {
|
|
44
|
+
let doc
|
|
45
|
+
try {
|
|
46
|
+
doc = JSON.parse(text)
|
|
47
|
+
} catch {
|
|
48
|
+
return { kind: 'invalid', reason: 'bad-json', rejected: [] }
|
|
49
|
+
}
|
|
50
|
+
if (!doc || typeof doc !== 'object' || Array.isArray(doc)) {
|
|
51
|
+
return { kind: 'invalid', reason: 'not-an-object', rejected: [] }
|
|
52
|
+
}
|
|
53
|
+
const raw = doc.rates
|
|
54
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
|
|
55
|
+
return { kind: 'invalid', reason: 'no-rates', rejected: [] }
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
const rates = {}
|
|
59
|
+
const rejected = []
|
|
60
|
+
for (const [model, value] of Object.entries(raw)) {
|
|
61
|
+
if (typeof model !== 'string' || model.trim() === '') {
|
|
62
|
+
rejected.push({ model: String(model), reason: 'empty-model' })
|
|
63
|
+
continue
|
|
64
|
+
}
|
|
65
|
+
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
|
66
|
+
rejected.push({ model, reason: 'not-an-object' })
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
const missing = REQUIRED_FIELDS.filter((f) => !Number.isFinite(value[f]))
|
|
70
|
+
if (missing.length > 0) {
|
|
71
|
+
// 缺档给缺档;写了非数字/负数给 field-invalid。两种 reject 原因分开,
|
|
72
|
+
// 用户才知道是"漏写"还是"写错"
|
|
73
|
+
const invalidField = REQUIRED_FIELDS.find(
|
|
74
|
+
(f) => value[f] !== undefined && !Number.isFinite(value[f]),
|
|
75
|
+
)
|
|
76
|
+
if (invalidField !== undefined) rejected.push({ model, reason: 'field-invalid', field: invalidField })
|
|
77
|
+
else rejected.push({ model, reason: 'fields-missing', missing })
|
|
78
|
+
continue
|
|
79
|
+
}
|
|
80
|
+
const negative = REQUIRED_FIELDS.find((f) => value[f] < 0)
|
|
81
|
+
if (negative !== undefined) {
|
|
82
|
+
rejected.push({ model, reason: 'negative', field: negative })
|
|
83
|
+
continue
|
|
84
|
+
}
|
|
85
|
+
// 元/百万 → 元/token。显式保留四档,不吞掉任何一档
|
|
86
|
+
rates[model] = Object.freeze({
|
|
87
|
+
input: value.input * M,
|
|
88
|
+
output: value.output * M,
|
|
89
|
+
cacheRead: value.cacheRead * M,
|
|
90
|
+
cacheWrite: value.cacheWrite * M,
|
|
91
|
+
currency: typeof value.currency === 'string' ? value.currency : undefined,
|
|
92
|
+
})
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (Object.keys(rates).length === 0) {
|
|
96
|
+
// 有内容但一条都不合法:这比"文件不存在"更值得报警,原因要带出去
|
|
97
|
+
return { kind: 'invalid', reason: rejected.length > 0 ? 'all-rejected' : 'no-rates', rejected }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
return {
|
|
101
|
+
kind: 'ok',
|
|
102
|
+
rates,
|
|
103
|
+
rejected,
|
|
104
|
+
asOf: typeof doc.asOf === 'string' ? doc.asOf : null,
|
|
105
|
+
source: typeof doc.source === 'string' ? doc.source : null,
|
|
106
|
+
currency: typeof doc.currency === 'string' ? doc.currency : null,
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/**
|
|
111
|
+
* 读覆盖文件并解析。文件不存在是正常情况(返回 absent),不是错误。
|
|
112
|
+
*
|
|
113
|
+
* @param {{path?: string, readFile?: (p:string)=>string}} [options]
|
|
114
|
+
* @returns {{kind:'absent'}|{kind:'ok',rates,rejected,asOf,source,currency}|{kind:'invalid',reason,rejected,detail?}}
|
|
115
|
+
*/
|
|
116
|
+
export function loadPricingOverride(options = {}) {
|
|
117
|
+
const path = options.path || defaultPricingPath()
|
|
118
|
+
const read = options.readFile ?? ((p) => readFileSync(p, 'utf8'))
|
|
119
|
+
let text
|
|
120
|
+
try {
|
|
121
|
+
text = read(path)
|
|
122
|
+
} catch (error) {
|
|
123
|
+
if (error && error.code === 'ENOENT') return { kind: 'absent' }
|
|
124
|
+
// 读不了和写错了要分开:一种是权限/路径问题,一种是内容问题
|
|
125
|
+
return { kind: 'invalid', reason: 'read-failed', rejected: [], detail: error?.code ?? 'unknown' }
|
|
126
|
+
}
|
|
127
|
+
return parsePricingFile(text)
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 把覆盖结果折算成面板/工具要展示的元信息。
|
|
132
|
+
*
|
|
133
|
+
* 关键:**失败也必须有 meta**。静默回退内置价、面板照常显示金额,
|
|
134
|
+
* 等于让用户以为自己的费率生效了——那正是这个文件机制要防的事。
|
|
135
|
+
*
|
|
136
|
+
* @param {ReturnType<typeof loadPricingOverride>} result
|
|
137
|
+
* @param {{asOf?: string, source?: string}} builtin
|
|
138
|
+
*/
|
|
139
|
+
export function pricingMetaOf(result, builtin = {}) {
|
|
140
|
+
if (result.kind === 'ok') {
|
|
141
|
+
return {
|
|
142
|
+
kind: 'file',
|
|
143
|
+
asOf: result.asOf,
|
|
144
|
+
source: result.source,
|
|
145
|
+
models: Object.keys(result.rates),
|
|
146
|
+
rejected: result.rejected,
|
|
147
|
+
error: null,
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
if (result.kind === 'invalid') {
|
|
151
|
+
return {
|
|
152
|
+
kind: 'builtin',
|
|
153
|
+
asOf: builtin.asOf ?? null,
|
|
154
|
+
source: builtin.source ?? null,
|
|
155
|
+
models: [],
|
|
156
|
+
rejected: result.rejected ?? [],
|
|
157
|
+
// 原因码要原样带出去,面板据此给一句人话
|
|
158
|
+
error: result.reason,
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
return {
|
|
162
|
+
kind: 'builtin',
|
|
163
|
+
asOf: builtin.asOf ?? null,
|
|
164
|
+
source: builtin.source ?? null,
|
|
165
|
+
models: [],
|
|
166
|
+
rejected: [],
|
|
167
|
+
error: null,
|
|
168
|
+
}
|
|
169
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 内置费率表 —— 只放**有官方页面可查**的价格,不猜、不估。
|
|
3
|
+
*
|
|
4
|
+
* 来源:https://api-docs.deepseek.com/zh-cn/quick_start/pricing
|
|
5
|
+
* 抓取日期:2026-11-19(官方页面原文:"产品价格可能发生变动,DeepSeek 保留修改价格的权利")
|
|
6
|
+
*
|
|
7
|
+
* 官方口径(元 / 百万 tokens):
|
|
8
|
+
* deepseek-v4-flash 缓存命中 0.02 缓存未命中 1 输出 2
|
|
9
|
+
* deepseek-v4-pro 缓存命中 0.025 缓存未命中 3 输出 6
|
|
10
|
+
*
|
|
11
|
+
* 换算:本表单位是"元 / token",即官方价 × 1e-6。
|
|
12
|
+
*
|
|
13
|
+
* 三个刻意的选择:
|
|
14
|
+
* 1. cacheWrite 记 0:DeepSeek 官方只有"命中/未命中"两档,**没有独立的缓存写单价**。
|
|
15
|
+
* 其缓存写入的 token 本来就计入"未命中输入"。若这里再给一个价,会和 input 重复计费
|
|
16
|
+
* (同一批 token 收两次钱,正是本插件最不该犯的错)。其它 provider 若单独收缓存写,
|
|
17
|
+
* 请在配置里覆盖。
|
|
18
|
+
* 2. cacheRead 用官方命中价(0.02 / 0.025),不是"未命中价打折估算"。
|
|
19
|
+
* 3. deepseek-chat / deepseek-reasoner 是官方明示的兼容别名
|
|
20
|
+
* (分别对应 v4-flash 的非思考 / 思考模式),因此与 v4-flash 同价;
|
|
21
|
+
* 官方声明这两个模型名将于北京时间 2026/07/24 23:59 弃用。
|
|
22
|
+
*
|
|
23
|
+
* 表里没有的模型,`costOf()` 返回 unknown(no-rate),面板显示"— no-rate",
|
|
24
|
+
* 绝不用 0 或平均值冒充。
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
const M = 1e-6 // 元 / 百万 tokens → 元 / token
|
|
28
|
+
|
|
29
|
+
const FLASH = Object.freeze({ input: 1 * M, output: 2 * M, cacheRead: 0.02 * M, cacheWrite: 0 })
|
|
30
|
+
const PRO = Object.freeze({ input: 3 * M, output: 6 * M, cacheRead: 0.025 * M, cacheWrite: 0 })
|
|
31
|
+
|
|
32
|
+
export const BUILTIN_RATES = Object.freeze({
|
|
33
|
+
'deepseek-v4-flash': FLASH,
|
|
34
|
+
'deepseek-v4-pro': PRO,
|
|
35
|
+
// 兼容别名(官方页面脚注 (1))
|
|
36
|
+
'deepseek-chat': FLASH,
|
|
37
|
+
'deepseek-reasoner': FLASH,
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
export const BUILTIN_SOURCE = 'https://api-docs.deepseek.com/zh-cn/quick_start/pricing'
|
|
41
|
+
export const BUILTIN_AS_OF = '2026-11-19'
|
|
42
|
+
|
|
43
|
+
/** 给面板/README 用的可读表,避免各处重复抄数字。 */
|
|
44
|
+
export function builtinRateTable() {
|
|
45
|
+
return Object.entries(BUILTIN_RATES).map(([model, rate]) => ({
|
|
46
|
+
model,
|
|
47
|
+
currency: 'CNY',
|
|
48
|
+
perMillion: {
|
|
49
|
+
cacheRead: rate.cacheRead / M,
|
|
50
|
+
input: rate.input / M,
|
|
51
|
+
output: rate.output / M,
|
|
52
|
+
cacheWrite: rate.cacheWrite / M,
|
|
53
|
+
},
|
|
54
|
+
}))
|
|
55
|
+
}
|
package/lib/pricing.js
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 四级计价。
|
|
3
|
+
*
|
|
4
|
+
* 为什么必须四级:TokenUsage 的计数 disjoint,缓存读写与未缓存输入单价不同。
|
|
5
|
+
* 用一个平均价乘总数会系统性偏高(缓存命中率越高错得越多)。
|
|
6
|
+
*
|
|
7
|
+
* 费率未知时返回 { kind: 'unknown' },**绝不退化成 0 或猜一个数**。
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Cost 是联合类型:
|
|
12
|
+
* { kind:'known', amount, currency, tier }
|
|
13
|
+
* { kind:'unknown', reason }
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
const REQUIRED_RATE_FIELDS = ['input', 'output', 'cacheRead', 'cacheWrite']
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* @param {{currency?: string, rates?: Record<string, object>}} [options]
|
|
20
|
+
*/
|
|
21
|
+
export function createPricing(options = {}) {
|
|
22
|
+
const currency = options.currency ?? 'CNY'
|
|
23
|
+
const rates = new Map(Object.entries(options.rates ?? {}))
|
|
24
|
+
|
|
25
|
+
/** 查找费率:优先 provider/model,其次裸 model,最后 provider/* */
|
|
26
|
+
function rateFor(provider, model) {
|
|
27
|
+
if (!model) return null
|
|
28
|
+
const exact = provider ? rates.get(`${provider}/${model}`) : null
|
|
29
|
+
return exact ?? rates.get(model) ?? (provider ? rates.get(`${provider}/*`) : null) ?? null
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* @param {ReturnType<import('./usage.js').normalizeUsage>} usage
|
|
34
|
+
* @param {{provider?: string, model?: string}|null} route
|
|
35
|
+
* @returns {{kind:'known',amount:number,currency:string,tier:'exact'}|{kind:'unknown',reason:string}}
|
|
36
|
+
*/
|
|
37
|
+
function costOf(usage, route) {
|
|
38
|
+
if (!usage) return { kind: 'unknown', reason: 'no-usage' }
|
|
39
|
+
if (!usage.complete) return { kind: 'unknown', reason: 'usage-incomplete' }
|
|
40
|
+
|
|
41
|
+
const rate = rateFor(route?.provider, route?.model)
|
|
42
|
+
if (!rate) return { kind: 'unknown', reason: 'no-rate' }
|
|
43
|
+
for (const field of REQUIRED_RATE_FIELDS) {
|
|
44
|
+
if (!Number.isFinite(rate[field])) return { kind: 'unknown', reason: 'no-rate' }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// reasoningTokens 已计入 outputTokens(适配器口径),不重复计价。
|
|
48
|
+
// 四档分开保留:面板要按"未缓存输入 / 缓存命中 / 缓存写 / 输出"分行显示,
|
|
49
|
+
// 前端不能自己乘(费率只在 Host 手里)。
|
|
50
|
+
const parts = {
|
|
51
|
+
input: usage.inputTokens * rate.input,
|
|
52
|
+
output: usage.outputTokens * rate.output,
|
|
53
|
+
cacheRead: usage.cacheReadTokens * rate.cacheRead,
|
|
54
|
+
cacheWrite: usage.cacheWriteTokens * rate.cacheWrite,
|
|
55
|
+
}
|
|
56
|
+
const amount = parts.input + parts.output + parts.cacheRead + parts.cacheWrite
|
|
57
|
+
|
|
58
|
+
return { kind: 'known', amount, parts, currency: rate.currency ?? currency, tier: 'exact' }
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* 缓存命中省下的钱 = cacheReadTokens × (未命中单价 − 命中单价)。
|
|
63
|
+
*
|
|
64
|
+
* 为什么这个数**可以报**而压缩省下的不能:两个单价都在同一张价表里,
|
|
65
|
+
* 差额是确定的,不需要假设「省下的 token 属哪一档」。这是账本里唯一
|
|
66
|
+
* 一个能严格算出来的"省了多少钱"。
|
|
67
|
+
*/
|
|
68
|
+
function savingsOf(usage, route) {
|
|
69
|
+
if (!usage || !usage.complete) return { kind: 'unknown', reason: 'no-usage' }
|
|
70
|
+
const rate = rateFor(route?.provider, route?.model)
|
|
71
|
+
if (!rate) return { kind: 'unknown', reason: 'no-rate' }
|
|
72
|
+
if (!Number.isFinite(rate.input) || !Number.isFinite(rate.cacheRead)) {
|
|
73
|
+
return { kind: 'unknown', reason: 'no-rate' }
|
|
74
|
+
}
|
|
75
|
+
const hit = usage.cacheReadTokens ?? 0
|
|
76
|
+
if (hit <= 0) return { kind: 'known', amount: 0, currency: rate.currency ?? currency }
|
|
77
|
+
const spread = rate.input - rate.cacheRead
|
|
78
|
+
// 命中价高于未命中价(配置写反了)时不报负数:那不是"省了"
|
|
79
|
+
if (!(spread > 0)) return { kind: 'known', amount: 0, currency: rate.currency ?? currency }
|
|
80
|
+
return { kind: 'known', amount: hit * spread, currency: rate.currency ?? currency }
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
return { costOf, savingsOf, rateFor, currency }
|
|
84
|
+
}
|
package/lib/ring.js
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 有界环形缓冲。
|
|
3
|
+
*
|
|
4
|
+
* 性能约束:单次写入 O(1)、无 shift、无中间数组分配。
|
|
5
|
+
* 事件流是热路径,每个 session/event 都会走到这里。
|
|
6
|
+
*/
|
|
7
|
+
export class RingBuffer {
|
|
8
|
+
#items
|
|
9
|
+
#start = 0
|
|
10
|
+
#size = 0
|
|
11
|
+
|
|
12
|
+
constructor(capacity) {
|
|
13
|
+
if (!Number.isInteger(capacity) || capacity <= 0) {
|
|
14
|
+
throw new TypeError('RingBuffer capacity must be a positive integer')
|
|
15
|
+
}
|
|
16
|
+
this.capacity = capacity
|
|
17
|
+
this.#items = new Array(capacity)
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
get size() {
|
|
21
|
+
return this.#size
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
push(item) {
|
|
25
|
+
if (this.#size < this.capacity) {
|
|
26
|
+
this.#items[(this.#start + this.#size) % this.capacity] = item
|
|
27
|
+
this.#size += 1
|
|
28
|
+
return
|
|
29
|
+
}
|
|
30
|
+
// 已满:覆盖最旧,头指针前移
|
|
31
|
+
this.#items[this.#start] = item
|
|
32
|
+
this.#start = (this.#start + 1) % this.capacity
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** 按时间顺序返回副本(调用方拿去序列化/渲染,不共享内部数组) */
|
|
36
|
+
toArray() {
|
|
37
|
+
const out = new Array(this.#size)
|
|
38
|
+
for (let i = 0; i < this.#size; i += 1) {
|
|
39
|
+
out[i] = this.#items[(this.#start + i) % this.capacity]
|
|
40
|
+
}
|
|
41
|
+
return out
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
last(n) {
|
|
45
|
+
if (!Number.isInteger(n) || n <= 0) return []
|
|
46
|
+
return this.toArray().slice(-n)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
clear() {
|
|
50
|
+
this.#items.fill(undefined)
|
|
51
|
+
this.#start = 0
|
|
52
|
+
this.#size = 0
|
|
53
|
+
}
|
|
54
|
+
}
|
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 面板快照落盘。
|
|
3
|
+
*
|
|
4
|
+
* 为什么是文件而不是自定义 Remote:
|
|
5
|
+
* 面板跑在浏览器,Host 的 ctx.ledger 它够不到。自定义 Typert remote 需要
|
|
6
|
+
* 代码生成产物(见 docs/spikes.md C-3),而宿主**已经**给了一条现成通道:
|
|
7
|
+
* 浏览器侧 `ctx.remote.workspaceFiles.read(absolutePath)` 可直接读工作区文本
|
|
8
|
+
* 文件。于是 Host 只负责把只读快照写成 JSON,面板读回即可——零新增协议。
|
|
9
|
+
*
|
|
10
|
+
* 设计约束:
|
|
11
|
+
* - 只读快照,不写流水(流水是 trace 的事,隐私优先);
|
|
12
|
+
* - 写盘失败绝不影响采集与预算:所有异常在内部吞掉,只记计数;
|
|
13
|
+
* - 节流:同一会话 intervalMs 内最多落盘一次,避免每个 token 都写盘;
|
|
14
|
+
* - 原子写:先写 `.tmp` 再 rename,面板永远读不到半截 JSON。
|
|
15
|
+
*/
|
|
16
|
+
import { mkdirSync, renameSync, rmSync, writeFileSync, readFileSync } from 'node:fs'
|
|
17
|
+
import { join, isAbsolute, resolve } from 'node:path'
|
|
18
|
+
import { PANEL_DIR, safeFileName } from './panel-path.js'
|
|
19
|
+
|
|
20
|
+
/** 快照文件的格式版本:字段变了就加,面板据此决定要不要重渲染。 */
|
|
21
|
+
export const SNAPSHOT_VERSION = 1
|
|
22
|
+
|
|
23
|
+
export { safeFileName }
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* 组装落盘内容。超过 maxBytes 时降级为"只有合计 + Top 来源",
|
|
27
|
+
* 面板据此显示"明细已截断",而不是显示一份不完整的明细。
|
|
28
|
+
*/
|
|
29
|
+
/**
|
|
30
|
+
* 生成时间统一成 ISO 字符串。
|
|
31
|
+
*
|
|
32
|
+
* store 给的是 Date.now() 数字,而面板按字符串截取显示("T" 换空格取前 19 位)。
|
|
33
|
+
* 类型不一致的后果是真机上显示"快照生成于 —"——数据明明有,却像坏了。
|
|
34
|
+
*/
|
|
35
|
+
function isoOf(at) {
|
|
36
|
+
if (typeof at === 'string' && at.length > 0) return at
|
|
37
|
+
if (typeof at === 'number' && Number.isFinite(at)) return new Date(at).toISOString()
|
|
38
|
+
return null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function buildPanelPayload(snapshot, sources, { maxBytes = 262144, budget = null, overview = null, pricing = null } = {}) {
|
|
42
|
+
const base = {
|
|
43
|
+
version: SNAPSHOT_VERSION,
|
|
44
|
+
generatedAt: isoOf(snapshot?.generatedAt),
|
|
45
|
+
sessionId: snapshot?.sessionId ?? null,
|
|
46
|
+
// 面板口径的派生字段集中在这里算一次,避免浏览器半各算一套
|
|
47
|
+
totals: withPanelTotals(snapshot?.totals ?? null),
|
|
48
|
+
topSources: snapshot?.topSources ?? [],
|
|
49
|
+
// 最近明细:面板的"表格视图"直接用它,不再另拉一次
|
|
50
|
+
recent: (snapshot?.recent ?? []).map(compactEntry),
|
|
51
|
+
// 最贵一步:只从"最近这段"里挑,面板会明说是"最近最贵",不冒充全程最贵
|
|
52
|
+
peak: peakOf((snapshot?.recent ?? []).map(compactEntry)),
|
|
53
|
+
// 跨会话对比:只给数字,不给别的内容(面板按 lastAt 排序取前几条)
|
|
54
|
+
overview: Array.isArray(overview) ? overview.slice(0, 8).map(compactSession) : null,
|
|
55
|
+
// 预算只给面板读数用:limit 为 null 表示未启用,面板不画进度条
|
|
56
|
+
budget: normalizeBudget(budget, snapshot?.totals),
|
|
57
|
+
// 费率来源:面板必须能说出"这些钱是按哪套价算的"。
|
|
58
|
+
// null 表示未传(老调用方),面板退化成只显示内置基准日。
|
|
59
|
+
pricing: pricing ?? null,
|
|
60
|
+
}
|
|
61
|
+
const full = { ...base, sources: sources?.sources ?? [], sourceCount: sources?.sourceCount ?? null }
|
|
62
|
+
const bytes = Buffer.byteLength(JSON.stringify(full))
|
|
63
|
+
return bytes <= maxBytes ? { payload: full, truncated: false } : { payload: base, truncated: true }
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 最近明细里金额最高的一条。没有已知金额时返回 null(未知不能用 0 参与比较)。
|
|
68
|
+
* @param {Array<ReturnType<typeof compactEntry>>} recent
|
|
69
|
+
*/
|
|
70
|
+
export function peakOf(recent) {
|
|
71
|
+
let best = null
|
|
72
|
+
for (const item of recent ?? []) {
|
|
73
|
+
if (item === null || typeof item.amount !== 'number' || !Number.isFinite(item.amount)) continue
|
|
74
|
+
if (best === null || item.amount > best.amount) best = item
|
|
75
|
+
}
|
|
76
|
+
if (best === null) return null
|
|
77
|
+
return {
|
|
78
|
+
amount: best.amount,
|
|
79
|
+
turn: best.turn,
|
|
80
|
+
step: best.step,
|
|
81
|
+
kind: best.kind,
|
|
82
|
+
model: best.route?.model ?? null,
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* 一条明细压成面板够用的形状:去掉 callId、usage 明细与 trace 引用。
|
|
88
|
+
* 金额与 token 都由 Host 算,面板只做显示。
|
|
89
|
+
*/
|
|
90
|
+
export function compactEntry(entry) {
|
|
91
|
+
if (entry === null || typeof entry !== 'object') return null
|
|
92
|
+
const cost = entry.cost
|
|
93
|
+
return {
|
|
94
|
+
at: entry.at ?? null,
|
|
95
|
+
turn: entry.turn ?? null,
|
|
96
|
+
step: entry.step ?? null,
|
|
97
|
+
// 上一步工具结果的文本字符数:解释"为什么这一步贵"的唯一线索
|
|
98
|
+
contextChars: typeof entry.contextChars === 'number' ? entry.contextChars : null,
|
|
99
|
+
// 压缩:前值 + 后一条省下的差值,两者都只在能算出来时给
|
|
100
|
+
contextBeforeTokens: typeof entry.contextBeforeTokens === 'number' ? entry.contextBeforeTokens : null,
|
|
101
|
+
contextSavedTokens: typeof entry.contextSavedTokens === 'number' ? entry.contextSavedTokens : null,
|
|
102
|
+
kind: entry.kind ?? null,
|
|
103
|
+
// 已知金额给数字,未知给原因码——面板据此显示"—"而不是 0
|
|
104
|
+
amount: cost?.kind === 'known' ? cost.amount : null,
|
|
105
|
+
unknownReason: cost?.kind === 'unknown' ? cost.reason : null,
|
|
106
|
+
route: entry.route === null || entry.route === undefined ? null : { provider: entry.route.provider ?? null, model: entry.route.model ?? null },
|
|
107
|
+
tokens: entry.usage === null || entry.usage === undefined
|
|
108
|
+
? null
|
|
109
|
+
: { input: entry.usage.inputTokens ?? 0, output: entry.usage.outputTokens ?? 0, cacheRead: entry.usage.cacheReadTokens ?? 0, cacheWrite: entry.usage.cacheWriteTokens ?? 0 },
|
|
110
|
+
plugin: entry.attribution?.primary?.plugin ?? null,
|
|
111
|
+
system: entry.attribution?.system ?? null,
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* 一个会话对比项:只有 id、金额、条目数、最后时间。
|
|
117
|
+
* 共享上下文拆不开时 amount 仍然是该会话的合计(面板不重算)。
|
|
118
|
+
*/
|
|
119
|
+
export function compactSession(row) {
|
|
120
|
+
const cost = row?.cost
|
|
121
|
+
return {
|
|
122
|
+
sessionId: row?.sessionId ?? null,
|
|
123
|
+
amount: typeof cost?.amount === 'number' ? cost.amount : null,
|
|
124
|
+
currency: cost?.currency ?? null,
|
|
125
|
+
entries: row?.entries ?? 0,
|
|
126
|
+
lastAt: row?.lastAt ?? null,
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* 预算读数:限额由配置给,已用取 snapshot 的合计金额。
|
|
132
|
+
* 金额缺失时不编 0 —— 面板显示"未计价",而不是假装花了 0。
|
|
133
|
+
*/
|
|
134
|
+
export function normalizeBudget(budget, totals) {
|
|
135
|
+
const limit = typeof budget?.limit === 'number' && budget.limit > 0 ? budget.limit : null
|
|
136
|
+
if (limit === null) return null
|
|
137
|
+
const amount = totals?.cost?.amount
|
|
138
|
+
const currency = budget?.currency ?? totals?.cost?.currency ?? 'CNY'
|
|
139
|
+
const used = typeof amount === 'number' && Number.isFinite(amount) ? amount : null
|
|
140
|
+
const known = totals?.cost?.knownEntries
|
|
141
|
+
|
|
142
|
+
// "还能问几次"比"已用 92%"更可行动:按已算出钱的条目均价反推。
|
|
143
|
+
// 只认已知条目——把未知金额的条目算进均价就是拿假数做预测。
|
|
144
|
+
const perCall = used !== null && typeof known === 'number' && known > 0 ? used / known : null
|
|
145
|
+
const remaining = used !== null ? limit - used : null
|
|
146
|
+
const callsLeft =
|
|
147
|
+
perCall !== null && perCall > 0 && remaining !== null ? Math.max(0, Math.floor(remaining / perCall)) : null
|
|
148
|
+
|
|
149
|
+
return {
|
|
150
|
+
limit,
|
|
151
|
+
currency,
|
|
152
|
+
used,
|
|
153
|
+
ratio: used === null ? null : Math.min(1, used / limit),
|
|
154
|
+
remaining,
|
|
155
|
+
perCall,
|
|
156
|
+
// 语义是"约":均价随缓存命中率波动,面板必须按约数展示
|
|
157
|
+
callsLeft,
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* 面板要的两个派生读数,口径只能有一处(否则前后端各算一套,迟早对不上)。
|
|
163
|
+
*
|
|
164
|
+
* cacheHitRate:输入里有多少走了缓存 = cacheRead / (未命中输入 + 命中输入)。
|
|
165
|
+
* 分母不含 cacheWrite —— DeepSeek 没有缓存写这一档,算进去会把命中率稀释。
|
|
166
|
+
*/
|
|
167
|
+
export function withPanelTotals(totals) {
|
|
168
|
+
if (totals === null || typeof totals !== 'object') return null
|
|
169
|
+
const t = totals.tokens ?? {}
|
|
170
|
+
const miss = typeof t.input === 'number' ? t.input : null
|
|
171
|
+
const hit = typeof t.cacheRead === 'number' ? t.cacheRead : null
|
|
172
|
+
const denom = miss === null || hit === null ? null : miss + hit
|
|
173
|
+
const cacheHitRate = denom !== null && denom > 0 ? hit / denom : null
|
|
174
|
+
|
|
175
|
+
// 缓存节省的占比:分母是"假如没有缓存本来要花的钱"(实花 + 省下),
|
|
176
|
+
// 这个比例才是客户能感知的价值("省了三分之一"比"省了 3 分钱"有力)
|
|
177
|
+
const savedAmount = totals.saved?.amount ?? null
|
|
178
|
+
const spent = totals.cost?.amount ?? null
|
|
179
|
+
const grossAmount = savedAmount !== null && spent !== null ? spent + savedAmount : null
|
|
180
|
+
const savedShare = grossAmount !== null && grossAmount > 0 ? savedAmount / grossAmount : null
|
|
181
|
+
|
|
182
|
+
return { ...totals, cacheHitRate, savedShare }
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* @param {object} options
|
|
187
|
+
* @param {string} options.dir - 输出目录(相对路径按 process.cwd() 解析)
|
|
188
|
+
* @param {number} [options.intervalMs]
|
|
189
|
+
* @param {number} [options.maxBytes]
|
|
190
|
+
* @param {(sessionId: string, opts?: object) => object} options.snapshot
|
|
191
|
+
* @param {(sessionId: string, opts?: object) => object} options.sources
|
|
192
|
+
* @param {() => number} [options.now]
|
|
193
|
+
*/
|
|
194
|
+
export function createSnapshotPublisher(options) {
|
|
195
|
+
const relativeDir = options.dir ?? PANEL_DIR
|
|
196
|
+
// 绝对路径=固定目录;相对路径=每个会话各自的工作区根 + 该相对目录
|
|
197
|
+
const fixedDir = isAbsolute(relativeDir) ? relativeDir : null
|
|
198
|
+
const rootOf = typeof options.rootOf === 'function' ? options.rootOf : () => process.cwd()
|
|
199
|
+
const dirOf = (sessionId) =>
|
|
200
|
+
fixedDir !== null ? fixedDir : resolve(rootOf(sessionId), relativeDir)
|
|
201
|
+
/** 诊断用:默认目录(固定目录时为它本身) */
|
|
202
|
+
const dir = fixedDir ?? relativeDir
|
|
203
|
+
|
|
204
|
+
const intervalMs = Math.max(0, Number(options.intervalMs ?? 0))
|
|
205
|
+
const maxBytes = Math.max(1024, Number(options.maxBytes ?? 262144))
|
|
206
|
+
const budget = options.budget ?? null // {limit, currency} 由调用方给(配置侧)
|
|
207
|
+
const overview = typeof options.overview === 'function' ? options.overview : null
|
|
208
|
+
const now = options.now ?? Date.now
|
|
209
|
+
|
|
210
|
+
/** sessionId → 上次落盘时间戳 */
|
|
211
|
+
const lastAt = new Map()
|
|
212
|
+
const stats = { writes: 0, truncated: 0, errors: 0, sessions: () => lastAt.size }
|
|
213
|
+
|
|
214
|
+
function filePathOf(sessionId) {
|
|
215
|
+
return join(dirOf(sessionId), `${safeFileName(sessionId)}.json`)
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** 立刻落盘一次;返回是否真的写了。 */
|
|
219
|
+
function publishNow(sessionId) {
|
|
220
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return false
|
|
221
|
+
try {
|
|
222
|
+
const snapshot = options.snapshot(sessionId)
|
|
223
|
+
if (snapshot === null || snapshot === undefined) return false // 该会话已淘汰
|
|
224
|
+
const sources = typeof options.sources === 'function' ? options.sources(sessionId) : null
|
|
225
|
+
const ov = overview === null ? null : overview()
|
|
226
|
+
const { payload, truncated } = buildPanelPayload(snapshot, sources, {
|
|
227
|
+
maxBytes,
|
|
228
|
+
budget,
|
|
229
|
+
overview: ov?.sessions ?? ov,
|
|
230
|
+
pricing: options.pricing ?? null,
|
|
231
|
+
})
|
|
232
|
+
// 多行写:浏览器侧 read 是按行取页的,单行超长 JSON 会被页宽截断
|
|
233
|
+
const body = JSON.stringify(payload, null, 2)
|
|
234
|
+
mkdirSync(dirOf(sessionId), { recursive: true })
|
|
235
|
+
const target = filePathOf(sessionId)
|
|
236
|
+
const tmp = `${target}.${process.pid}.tmp`
|
|
237
|
+
writeFileSync(tmp, body, 'utf8')
|
|
238
|
+
renameSync(tmp, target)
|
|
239
|
+
lastAt.set(sessionId, now())
|
|
240
|
+
stats.writes += 1
|
|
241
|
+
if (truncated) stats.truncated += 1
|
|
242
|
+
return true
|
|
243
|
+
} catch (error) {
|
|
244
|
+
stats.errors += 1
|
|
245
|
+
// 临时文件可能残留:尽力清理,失败就算了
|
|
246
|
+
try {
|
|
247
|
+
rmSync(`${filePathOf(sessionId)}.${process.pid}.tmp`, { force: true })
|
|
248
|
+
} catch {}
|
|
249
|
+
void error
|
|
250
|
+
return false
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/** 节流入口:由 session/event 高频调用,内部按 intervalMs 合并。 */
|
|
255
|
+
function schedule(sessionId) {
|
|
256
|
+
if (typeof sessionId !== 'string' || sessionId.length === 0) return false
|
|
257
|
+
const previous = lastAt.get(sessionId)
|
|
258
|
+
if (previous !== undefined && intervalMs > 0 && now() - previous < intervalMs) return false
|
|
259
|
+
return publishNow(sessionId)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** 会话结束:删掉快照并忘记节流状态(面板读到"会话已结束")。 */
|
|
263
|
+
function remove(sessionId) {
|
|
264
|
+
lastAt.delete(sessionId)
|
|
265
|
+
try {
|
|
266
|
+
rmSync(filePathOf(sessionId), { force: true })
|
|
267
|
+
return true
|
|
268
|
+
} catch {
|
|
269
|
+
stats.errors += 1
|
|
270
|
+
return false
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function dispose() {
|
|
275
|
+
lastAt.clear()
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
return { dir, publishNow, schedule, remove, dispose, stats, filePathOf }
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* 读回一份快照(测试与 Host 侧诊断用;浏览器侧走 workspace 文件 remote)。
|
|
283
|
+
* @param {string} filePath
|
|
284
|
+
* @returns {object|null}
|
|
285
|
+
*/
|
|
286
|
+
export function readPanelFile(filePath) {
|
|
287
|
+
try {
|
|
288
|
+
const parsed = JSON.parse(readFileSync(filePath, 'utf8'))
|
|
289
|
+
return parsed && typeof parsed === 'object' ? parsed : null
|
|
290
|
+
} catch {
|
|
291
|
+
return null
|
|
292
|
+
}
|
|
293
|
+
}
|