@lingda-ai/dsh-plugin-replay 0.0.0-stage → 0.1.1
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 +202 -0
- package/README.md +102 -2
- package/cordis.patch.yml +7 -0
- package/docs/replay-contract.md +81 -0
- package/index.js +146 -0
- package/lib/client.js +682 -0
- package/lib/projector.js +253 -0
- package/lib/rates.js +172 -0
- package/lib/redact.js +58 -0
- package/lib/route.js +196 -0
- package/lib/store.js +439 -0
- package/package.json +72 -4
package/lib/projector.js
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 事件投影:session/event → 回放行(span)。
|
|
3
|
+
*
|
|
4
|
+
* 三条硬约束:
|
|
5
|
+
* 1. **只投影结构**。工具名(白名单内)与模型名留下,参数/返回值/文本一律丢弃;
|
|
6
|
+
* 2. **幂等**。同一个 (会话, 轮, 步, 动作) 只可能产出一条,重复到达直接丢;
|
|
7
|
+
* 3. **失败即未知**。算不出的金额写 null + reason,绝不填 0。
|
|
8
|
+
*
|
|
9
|
+
* 真实事件形状是 {type, seq, time, data, surfaceOp},载荷在 data 里;
|
|
10
|
+
* 但类型声明写的是扁平形状。两种都认——账本曾因只认扁平形状而线上全空,
|
|
11
|
+
* 这条教训在这里直接复用。
|
|
12
|
+
*/
|
|
13
|
+
import { createHash } from 'node:crypto'
|
|
14
|
+
import { baseName, redactText, safeCode, shortHash } from './redact.js'
|
|
15
|
+
import { normalizeUsage } from './rates.js'
|
|
16
|
+
|
|
17
|
+
/** DSH 内置工具名:留下真名,热点才有意义。自定义插件的工具名会被哈希。 */
|
|
18
|
+
export const DEFAULT_TOOL_WHITELIST = Object.freeze([
|
|
19
|
+
'read_file', 'write_file', 'edit_file', 'list_files', 'glob', 'grep',
|
|
20
|
+
'run_tests', 'run_command', 'bash', 'task', 'web_fetch', 'web_search',
|
|
21
|
+
'ledger_query', 'ask_user_question', 'todo_write', 'think',
|
|
22
|
+
])
|
|
23
|
+
|
|
24
|
+
const MODEL_EVENTS = new Set(['assistant/message'])
|
|
25
|
+
const ATTEMPT_EVENTS = new Set(['assistant/attempt'])
|
|
26
|
+
const TOOL_CALL = 'tool/call'
|
|
27
|
+
const TOOL_RESULT = 'tool/result'
|
|
28
|
+
const COMPACTION_PREFIX = 'compaction/'
|
|
29
|
+
|
|
30
|
+
function payloadOf(event) {
|
|
31
|
+
const data = event?.data
|
|
32
|
+
if (data !== null && typeof data === 'object' && !Array.isArray(data)) return data
|
|
33
|
+
return event
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function toInt(value) {
|
|
37
|
+
const n = Number(value)
|
|
38
|
+
return Number.isFinite(n) && n >= 0 ? Math.floor(n) : null
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 幂等键:与会话内唯一坐标绑定,重复上报自动折叠。 */
|
|
42
|
+
export function eventIdOf({ sid, turn, step, op, sub }) {
|
|
43
|
+
const key = [sid ?? '', turn ?? '', step ?? '', op ?? '', sub ?? ''].join('|')
|
|
44
|
+
return createHash('sha1').update(key).digest('hex').slice(0, 16)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* @param {{rates: ReturnType<import('./rates.js').loadRates>, toolWhitelist?: string[],
|
|
49
|
+
* now?: () => number, maxSeen?: number}} deps
|
|
50
|
+
*/
|
|
51
|
+
export function createProjector({ rates, toolWhitelist, now = () => Date.now(), maxSeen = 20000 }) {
|
|
52
|
+
const whitelist = new Set(toolWhitelist ?? DEFAULT_TOOL_WHITELIST)
|
|
53
|
+
/** sessionId → 会话级状态 */
|
|
54
|
+
const state = new Map()
|
|
55
|
+
|
|
56
|
+
function stateOf(sid) {
|
|
57
|
+
let value = state.get(sid)
|
|
58
|
+
if (value === undefined) {
|
|
59
|
+
value = {
|
|
60
|
+
title: null,
|
|
61
|
+
cwdName: null,
|
|
62
|
+
pending: new Map(), // callId → { turn, step, name, at }
|
|
63
|
+
driverByStep: new Map(), // `${turn}:${step}` → 工具名
|
|
64
|
+
seen: new Set(),
|
|
65
|
+
firstAt: null,
|
|
66
|
+
lastAt: null,
|
|
67
|
+
deduped: 0,
|
|
68
|
+
emitted: 0,
|
|
69
|
+
}
|
|
70
|
+
state.set(sid, value)
|
|
71
|
+
}
|
|
72
|
+
return value
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** 工具名:白名单内保留真名,否则哈希——私有工具名不该被外部看到。 */
|
|
76
|
+
function toolLabel(name) {
|
|
77
|
+
if (typeof name !== 'string' || name.length === 0) return null
|
|
78
|
+
if (whitelist.has(name)) return name
|
|
79
|
+
return `tool#${shortHash(name)}`
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function makeRow(sid, op, fields) {
|
|
83
|
+
const s = stateOf(sid)
|
|
84
|
+
const at = Number.isFinite(fields.at) ? fields.at : now()
|
|
85
|
+
const row = { v: 1, t: 'span', sid, at, op }
|
|
86
|
+
if (fields.turn !== null && fields.turn !== undefined) row.turn = fields.turn
|
|
87
|
+
if (fields.step !== null && fields.step !== undefined) row.step = fields.step
|
|
88
|
+
for (const key of ['tool', 'model', 'driver', 'conf', 'meas', 'cost', 'costReason', 'saved', 'durMs', 'ok', 'errCode', 'aggr']) {
|
|
89
|
+
if (fields[key] !== undefined) row[key] = fields[key]
|
|
90
|
+
}
|
|
91
|
+
row.eid = eventIdOf({ sid, turn: row.turn, step: row.step, op, sub: fields.sub ?? fields.tool ?? null })
|
|
92
|
+
if (s.seen.has(row.eid)) {
|
|
93
|
+
s.deduped += 1
|
|
94
|
+
return null
|
|
95
|
+
}
|
|
96
|
+
if (s.seen.size > maxSeen) s.seen.clear() // 长会话:清空重来,宁可重复一条也不无限涨
|
|
97
|
+
s.seen.add(row.eid)
|
|
98
|
+
s.emitted += 1
|
|
99
|
+
s.lastAt = at
|
|
100
|
+
if (s.firstAt === null) s.firstAt = at
|
|
101
|
+
return row
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* 处理一条事件,返回本次新增的行(可能 0 条)。
|
|
106
|
+
* 任何异常都由调用方兜住——这里不做 try/catch,避免掩盖逻辑错误(由测试暴露)。
|
|
107
|
+
*/
|
|
108
|
+
function onEvent(sid, event, session) {
|
|
109
|
+
if (typeof sid !== 'string' || sid.length === 0) return []
|
|
110
|
+
const s = stateOf(sid)
|
|
111
|
+
const type = event?.type
|
|
112
|
+
if (typeof type !== 'string') return []
|
|
113
|
+
|
|
114
|
+
// 标题与工作区名:先到先得,标题后来会被改写
|
|
115
|
+
if (type === 'session/title') {
|
|
116
|
+
const payload = payloadOf(event)
|
|
117
|
+
const title = payload?.title
|
|
118
|
+
if (typeof title === 'string' && title.length > 0) s.title = redactText(title, 80)
|
|
119
|
+
return []
|
|
120
|
+
}
|
|
121
|
+
if (s.cwdName === null && typeof session?.header?.cwd === 'string') {
|
|
122
|
+
s.cwdName = baseName(session.header.cwd)
|
|
123
|
+
}
|
|
124
|
+
if (s.title === null && typeof session?.title === 'string' && session.title.length > 0) {
|
|
125
|
+
s.title = redactText(session.title, 80)
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const payload = payloadOf(event)
|
|
129
|
+
const turn = toInt(payload?.turn ?? event?.turn)
|
|
130
|
+
const step = toInt(payload?.step ?? event?.step)
|
|
131
|
+
const at = Number.isFinite(event?.time) ? Number(event.time) : now()
|
|
132
|
+
|
|
133
|
+
if (MODEL_EVENTS.has(type)) return onModel(sid, s, payload, { turn, step, at })
|
|
134
|
+
if (ATTEMPT_EVENTS.has(type)) return [] // 无 usage 的尝试不是计费调用,也不该占时间轴
|
|
135
|
+
if (type === TOOL_CALL) return onToolCall(s, payload, { turn, step, at })
|
|
136
|
+
if (type === TOOL_RESULT) return onToolResult(sid, s, payload, { turn, step, at })
|
|
137
|
+
if (type.startsWith(COMPACTION_PREFIX)) {
|
|
138
|
+
const row = makeRow(sid, 'compaction', { turn, step, at, cost: null })
|
|
139
|
+
return row ? [row] : []
|
|
140
|
+
}
|
|
141
|
+
return []
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function onModel(sid, s, payload, { turn, step, at }) {
|
|
145
|
+
const normalized = normalizeUsage(payload?.usage ?? payload?.message?.usage)
|
|
146
|
+
if (normalized === null || normalized.complete !== true) return []
|
|
147
|
+
|
|
148
|
+
const source = payload?.message?.source
|
|
149
|
+
const route = {
|
|
150
|
+
provider: source?.provider ?? payload?.provider ?? null,
|
|
151
|
+
model: source?.model ?? payload?.model ?? null,
|
|
152
|
+
}
|
|
153
|
+
const cost = rates.costOf(normalized, route)
|
|
154
|
+
// 因果归因:本步请求由 **上一步** 的工具结果推动(与账本同一算法)
|
|
155
|
+
const driver = turn !== null && step !== null && step > 0 ? s.driverByStep.get(`${turn}:${step - 1}`) ?? null : null
|
|
156
|
+
|
|
157
|
+
const meas = []
|
|
158
|
+
if (normalized.inputTokens > 0) meas.push({ unit: 'token.input', value: normalized.inputTokens })
|
|
159
|
+
if (normalized.cacheReadTokens > 0) meas.push({ unit: 'token.cache_read', value: normalized.cacheReadTokens })
|
|
160
|
+
if (normalized.cacheWriteTokens > 0) meas.push({ unit: 'token.cache_write', value: normalized.cacheWriteTokens })
|
|
161
|
+
if (normalized.outputTokens > 0) meas.push({ unit: 'token.output', value: normalized.outputTokens })
|
|
162
|
+
|
|
163
|
+
const row = makeRow(sid, 'model.call', {
|
|
164
|
+
turn, step, at,
|
|
165
|
+
model: route.model,
|
|
166
|
+
driver,
|
|
167
|
+
meas,
|
|
168
|
+
cost: cost.kind === 'known' ? { amount: round6(cost.amount), currency: cost.currency } : null,
|
|
169
|
+
costReason: cost.kind === 'known' ? null : cost.reason,
|
|
170
|
+
saved: cost.kind === 'known' ? round6(rates.savedOf(normalized, route) ?? 0) : null,
|
|
171
|
+
})
|
|
172
|
+
return row ? [row] : []
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function onToolCall(s, payload, { turn, step, at }) {
|
|
176
|
+
const callId = payload?.callId ?? payload?.id ?? null
|
|
177
|
+
if (callId === null) return []
|
|
178
|
+
s.pending.set(String(callId), {
|
|
179
|
+
turn, step, at,
|
|
180
|
+
name: toolLabel(payload?.name ?? payload?.tool ?? null),
|
|
181
|
+
})
|
|
182
|
+
return []
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function onToolResult(sid, s, payload, { turn, step, at }) {
|
|
186
|
+
const callId = payload?.callId ?? payload?.id ?? null
|
|
187
|
+
if (callId === null) return []
|
|
188
|
+
const pending = s.pending.get(String(callId)) ?? null
|
|
189
|
+
s.pending.delete(String(callId))
|
|
190
|
+
|
|
191
|
+
const name = pending?.name ?? toolLabel(payload?.name ?? null)
|
|
192
|
+
const startedAt = pending?.at ?? null
|
|
193
|
+
const isError = payload?.isError === true || payload?.error !== undefined && payload?.error !== null
|
|
194
|
+
const errCode = isError
|
|
195
|
+
? safeCode(payload?.error?.code ?? payload?.error?.type ?? payload?.code) ?? 'error'
|
|
196
|
+
: null
|
|
197
|
+
|
|
198
|
+
const rowTurn = pending?.turn ?? turn
|
|
199
|
+
const rowStep = pending?.step ?? step
|
|
200
|
+
if (name !== null && rowTurn !== null && rowStep !== null) {
|
|
201
|
+
s.driverByStep.set(`${rowTurn}:${rowStep}`, name)
|
|
202
|
+
if (s.driverByStep.size > 4000) s.driverByStep.clear()
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
const row = makeRow(sid, 'tool.call', {
|
|
206
|
+
turn: rowTurn, step: rowStep, at: startedAt ?? at,
|
|
207
|
+
tool: name,
|
|
208
|
+
durMs: startedAt === null ? null : Math.max(0, at - startedAt),
|
|
209
|
+
ok: isError ? false : true,
|
|
210
|
+
errCode,
|
|
211
|
+
cost: null,
|
|
212
|
+
})
|
|
213
|
+
return row ? [row] : []
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function flushPending(sid) {
|
|
217
|
+
const s = state.get(sid)
|
|
218
|
+
if (!s || s.pending.size === 0) return []
|
|
219
|
+
const rows = []
|
|
220
|
+
for (const [callId, pending] of s.pending) {
|
|
221
|
+
const row = makeRow(sid, 'tool.call', {
|
|
222
|
+
turn: pending.turn, step: pending.step, at: pending.at,
|
|
223
|
+
tool: pending.name, durMs: null, ok: null, cost: null,
|
|
224
|
+
})
|
|
225
|
+
if (row) rows.push(row)
|
|
226
|
+
}
|
|
227
|
+
s.pending.clear()
|
|
228
|
+
return rows
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function metaOf(sid) {
|
|
232
|
+
const s = state.get(sid)
|
|
233
|
+
if (!s) return null
|
|
234
|
+
return {
|
|
235
|
+
title: s.title,
|
|
236
|
+
cwdName: s.cwdName,
|
|
237
|
+
firstAt: s.firstAt,
|
|
238
|
+
lastAt: s.lastAt,
|
|
239
|
+
emitted: s.emitted,
|
|
240
|
+
deduped: s.deduped,
|
|
241
|
+
}
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
function forget(sid) {
|
|
245
|
+
state.delete(sid)
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
return { onEvent, flushPending, metaOf, forget, toolLabel }
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function round6(value) {
|
|
252
|
+
return Math.round(Number(value) * 1e6) / 1e6
|
|
253
|
+
}
|
package/lib/rates.js
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 费率:与账本同源,四档计价,未知即未知。
|
|
3
|
+
*
|
|
4
|
+
* 为什么把价表抄一份而不是依赖 @lingda-ai/dsh-plugin-ledger:
|
|
5
|
+
* 1. 市场收录要求"自包含单包、可安装",跨包强依赖会让"只装黑匣子"失败;
|
|
6
|
+
* 2. 但口径必须一致——两个插件对同一会话报出两个数,是信任级事故。
|
|
7
|
+
* 所以:**数字抄自账本内置价表(同一官方页面、同一抓取日)**,并优先读账本写的
|
|
8
|
+
* `~/.dsh/ledger/pricing.json`(文件契约,不是代码依赖)。用户改价只有一处。
|
|
9
|
+
*
|
|
10
|
+
* 单位:本文件内部一律"元 / token"。用户写的 pricing.json 是"元 / 百万 tokens"。
|
|
11
|
+
* 表里没有的模型 → unknown(no-rate),显示"—",绝不用 0 或均值冒充。
|
|
12
|
+
*/
|
|
13
|
+
import { readFileSync } from 'node:fs'
|
|
14
|
+
import { homedir } from 'node:os'
|
|
15
|
+
import { join } from 'node:path'
|
|
16
|
+
|
|
17
|
+
const M = 1e-6
|
|
18
|
+
|
|
19
|
+
/** 与账本 lib/pricing-table.js 同源同值(官方页面 2026-11-19)。 */
|
|
20
|
+
const FLASH = Object.freeze({ input: 1 * M, output: 2 * M, cacheRead: 0.02 * M, cacheWrite: 0 })
|
|
21
|
+
const PRO = Object.freeze({ input: 3 * M, output: 6 * M, cacheRead: 0.025 * M, cacheWrite: 0 })
|
|
22
|
+
|
|
23
|
+
export const BUILTIN_RATES = Object.freeze({
|
|
24
|
+
'deepseek-v4-flash': FLASH,
|
|
25
|
+
'deepseek-v4-pro': PRO,
|
|
26
|
+
'deepseek-chat': FLASH,
|
|
27
|
+
'deepseek-reasoner': FLASH,
|
|
28
|
+
'deepseek-flash': FLASH,
|
|
29
|
+
'deepseek-pro': PRO,
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
export const BUILTIN_AS_OF = '2026-11-19'
|
|
33
|
+
export const BUILTIN_SOURCE = 'https://api-docs.deepseek.com/zh-cn/quick_start/pricing'
|
|
34
|
+
|
|
35
|
+
const REQUIRED = ['input', 'output', 'cacheRead', 'cacheWrite']
|
|
36
|
+
|
|
37
|
+
export function defaultPricingPath() {
|
|
38
|
+
return join(homedir(), '.dsh', 'ledger', 'pricing.json')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** 归一化 usage:缺字段与 0 是两件事,用 complete 表达。 */
|
|
42
|
+
export function normalizeUsage(raw) {
|
|
43
|
+
if (raw === null || typeof raw !== 'object') return null
|
|
44
|
+
const num = (value) => (Number.isFinite(value) ? Number(value) : null)
|
|
45
|
+
const usage = {
|
|
46
|
+
inputTokens: num(raw.inputTokens) ?? 0,
|
|
47
|
+
outputTokens: num(raw.outputTokens) ?? 0,
|
|
48
|
+
cacheReadTokens: num(raw.cacheReadTokens) ?? 0,
|
|
49
|
+
cacheWriteTokens: num(raw.cacheWriteTokens) ?? 0,
|
|
50
|
+
}
|
|
51
|
+
// 至少有一个真实数字,且没有脏值(字符串、NaN):两种情况才算完整。
|
|
52
|
+
// 注意这里用的是 **usage 字段名**,不是费率字段名——两套名字混用会让 complete 永远 false。
|
|
53
|
+
const FIELDS = ['inputTokens', 'outputTokens', 'cacheReadTokens', 'cacheWriteTokens']
|
|
54
|
+
const present = FIELDS.some((field) => Number.isFinite(raw[field]))
|
|
55
|
+
const clean = FIELDS.every(
|
|
56
|
+
(field) => raw[field] === undefined || raw[field] === null || Number.isFinite(raw[field]),
|
|
57
|
+
)
|
|
58
|
+
usage.complete = present && clean
|
|
59
|
+
return usage
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/**
|
|
63
|
+
* 读账本写的费率覆盖文件。整条生效或整条拒绝:缺一档就不认这个模型,
|
|
64
|
+
* 因为"旧价补新价"算出来的数既不是旧价也不是新价。
|
|
65
|
+
*/
|
|
66
|
+
export function parsePricingFile(text) {
|
|
67
|
+
let doc
|
|
68
|
+
try {
|
|
69
|
+
doc = JSON.parse(text)
|
|
70
|
+
} catch {
|
|
71
|
+
return { kind: 'invalid', reason: 'json-error', rates: {}, rejected: [] }
|
|
72
|
+
}
|
|
73
|
+
if (doc === null || typeof doc !== 'object' || Array.isArray(doc)) {
|
|
74
|
+
return { kind: 'invalid', reason: 'not-object', rates: {}, rejected: [] }
|
|
75
|
+
}
|
|
76
|
+
const table = doc.models !== null && typeof doc.models === 'object' && !Array.isArray(doc.models) ? doc.models : doc
|
|
77
|
+
const rates = {}
|
|
78
|
+
const rejected = []
|
|
79
|
+
for (const [model, value] of Object.entries(table)) {
|
|
80
|
+
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
|
|
81
|
+
rejected.push({ model, reason: 'not-object' })
|
|
82
|
+
continue
|
|
83
|
+
}
|
|
84
|
+
const missing = REQUIRED.filter((field) => !Number.isFinite(value[field]))
|
|
85
|
+
if (missing.length > 0) {
|
|
86
|
+
rejected.push({ model, reason: 'fields-missing', missing })
|
|
87
|
+
continue
|
|
88
|
+
}
|
|
89
|
+
rates[model] = {
|
|
90
|
+
input: value.input * M,
|
|
91
|
+
output: value.output * M,
|
|
92
|
+
cacheRead: value.cacheRead * M,
|
|
93
|
+
cacheWrite: value.cacheWrite * M,
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
return {
|
|
97
|
+
kind: 'ok',
|
|
98
|
+
rates,
|
|
99
|
+
rejected,
|
|
100
|
+
asOf: typeof doc.asOf === 'string' ? doc.asOf : null,
|
|
101
|
+
source: typeof doc.source === 'string' ? doc.source : null,
|
|
102
|
+
currency: typeof doc.currency === 'string' ? doc.currency : null,
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* @param {{pricingPath?: string|null, readFile?: (p:string)=>string}} [options]
|
|
108
|
+
*/
|
|
109
|
+
export function loadRates(options = {}) {
|
|
110
|
+
const path = options.pricingPath === undefined ? defaultPricingPath() : options.pricingPath
|
|
111
|
+
const readFile = options.readFile ?? ((p) => readFileSync(p, 'utf8'))
|
|
112
|
+
|
|
113
|
+
let rates = { ...BUILTIN_RATES }
|
|
114
|
+
let meta = { kind: 'builtin', asOf: BUILTIN_AS_OF, source: BUILTIN_SOURCE, currency: 'CNY', rejected: [], error: null }
|
|
115
|
+
|
|
116
|
+
if (typeof path === 'string' && path.length > 0) {
|
|
117
|
+
try {
|
|
118
|
+
const parsed = parsePricingFile(readFile(path))
|
|
119
|
+
if (parsed.kind === 'ok' && Object.keys(parsed.rates).length > 0) {
|
|
120
|
+
rates = { ...rates, ...parsed.rates }
|
|
121
|
+
meta = {
|
|
122
|
+
kind: 'file',
|
|
123
|
+
asOf: parsed.asOf,
|
|
124
|
+
source: parsed.source ?? `file:${path}`,
|
|
125
|
+
currency: parsed.currency ?? 'CNY',
|
|
126
|
+
rejected: parsed.rejected,
|
|
127
|
+
error: null,
|
|
128
|
+
}
|
|
129
|
+
} else if (parsed.kind === 'invalid') {
|
|
130
|
+
meta = { ...meta, error: parsed.reason, rejected: parsed.rejected ?? [] }
|
|
131
|
+
}
|
|
132
|
+
} catch (error) {
|
|
133
|
+
const code = error && error.code ? String(error.code) : 'read-failed'
|
|
134
|
+
// 文件不存在是常态(用户没改过价),不算错误
|
|
135
|
+
if (code !== 'ENOENT') meta = { ...meta, error: code }
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function rateFor(provider, model) {
|
|
140
|
+
if (typeof model !== 'string' || model.length === 0) return null
|
|
141
|
+
if (provider && rates[`${provider}/${model}`]) return rates[`${provider}/${model}`]
|
|
142
|
+
return rates[model] ?? (provider ? rates[`${provider}/*`] ?? null : null)
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** @returns {{kind:'known',amount:number,currency:string,parts:object}|{kind:'unknown',reason:string}} */
|
|
146
|
+
function costOf(usage, route) {
|
|
147
|
+
if (!usage) return { kind: 'unknown', reason: 'no-usage' }
|
|
148
|
+
if (!usage.complete) return { kind: 'unknown', reason: 'usage-incomplete' }
|
|
149
|
+
const rate = rateFor(route?.provider ?? null, route?.model ?? null)
|
|
150
|
+
if (!rate) return { kind: 'unknown', reason: 'no-rate' }
|
|
151
|
+
const parts = {
|
|
152
|
+
input: usage.inputTokens * rate.input,
|
|
153
|
+
output: usage.outputTokens * rate.output,
|
|
154
|
+
cacheRead: usage.cacheReadTokens * rate.cacheRead,
|
|
155
|
+
cacheWrite: usage.cacheWriteTokens * rate.cacheWrite,
|
|
156
|
+
}
|
|
157
|
+
const amount = parts.input + parts.output + parts.cacheRead + parts.cacheWrite
|
|
158
|
+
return { kind: 'known', amount, parts, currency: meta.currency ?? 'CNY' }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/** 缓存省下的钱:命中部分若按未缓存输入价计,会多花多少。费率未知时为 null。 */
|
|
162
|
+
function savedOf(usage, route) {
|
|
163
|
+
if (!usage || !usage.complete) return null
|
|
164
|
+
const rate = rateFor(route?.provider ?? null, route?.model ?? null)
|
|
165
|
+
if (!rate) return null
|
|
166
|
+
const delta = rate.input - rate.cacheRead
|
|
167
|
+
if (!Number.isFinite(delta) || delta <= 0) return null
|
|
168
|
+
return usage.cacheReadTokens * delta
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
return { costOf, savedOf, meta, rateFor }
|
|
172
|
+
}
|
package/lib/redact.js
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 脱敏与文件名规范化。
|
|
3
|
+
*
|
|
4
|
+
* 黑匣子的隐私底线比流水更硬:**内容零拷贝**。
|
|
5
|
+
* - 不存 prompt / completion / 工具参数 / 工具返回;
|
|
6
|
+
* - 错误只留错误码,不留 message(message 里常带路径与代码片段);
|
|
7
|
+
* - 绝对路径不入账,只留最后一级目录名;
|
|
8
|
+
* - 会话标题会落盘(它本来就是用户可见的元数据),但要截断并擦掉密钥。
|
|
9
|
+
*
|
|
10
|
+
* 这些函数是纯函数,便于单测直接断言"脏东西进不去"。
|
|
11
|
+
*/
|
|
12
|
+
import { createHash } from 'node:crypto'
|
|
13
|
+
|
|
14
|
+
const SECRET_PATTERNS = [
|
|
15
|
+
/\bsk-[A-Za-z0-9_-]{8,}\b/g,
|
|
16
|
+
/\bBearer\s+[A-Za-z0-9._-]{8,}\b/gi,
|
|
17
|
+
/\b(api[_-]?key|token|secret|password)\s*[:=]\s*[^\s,;]{6,}/gi,
|
|
18
|
+
/\bnpm_[A-Za-z0-9]{10,}\b/g,
|
|
19
|
+
/\bgh[pousr]_[A-Za-z0-9]{10,}\b/g,
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
/** 绝对路径(POSIX 与 Windows 两种),整体替换成 [path]。 */
|
|
23
|
+
const ABS_PATH = /(?:^|[\s"'(])((?:[A-Za-z]:)?(?:[\\/](?:[^\\/\s"']+)){2,})/g
|
|
24
|
+
|
|
25
|
+
export function redactText(value, maxLength = 120) {
|
|
26
|
+
if (typeof value !== 'string') return ''
|
|
27
|
+
let text = value
|
|
28
|
+
for (const pattern of SECRET_PATTERNS) text = text.replace(pattern, '[redacted]')
|
|
29
|
+
text = text.replace(ABS_PATH, ' [path]')
|
|
30
|
+
text = text.replace(/\s+/g, ' ').trim()
|
|
31
|
+
return text.length > maxLength ? `${text.slice(0, maxLength)}…` : text
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** 错误码白名单化:只放行短标识符,其余一律归为 error。 */
|
|
35
|
+
export function safeCode(value) {
|
|
36
|
+
if (typeof value !== 'string') return null
|
|
37
|
+
const code = value.trim()
|
|
38
|
+
if (code.length === 0 || code.length > 40) return null
|
|
39
|
+
return /^[A-Za-z0-9_.:-]+$/.test(code) ? code : null
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 目录名(不含绝对路径),用于区分工作区而不泄露路径。 */
|
|
43
|
+
export function baseName(path) {
|
|
44
|
+
if (typeof path !== 'string' || path.length === 0) return null
|
|
45
|
+
const parts = path.split(/[\\/]+/).filter(Boolean)
|
|
46
|
+
const last = parts.length > 0 ? parts[parts.length - 1] : null
|
|
47
|
+
return last === null ? null : redactText(last, 48)
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function shortHash(value) {
|
|
51
|
+
return createHash('sha1').update(String(value)).digest('hex').slice(0, 6)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** 文件名安全化:只允许 [A-Za-z0-9._-],其余替换成 _,并限制长度。 */
|
|
55
|
+
export function safeFileName(id) {
|
|
56
|
+
const raw = typeof id === 'string' ? id : String(id ?? '')
|
|
57
|
+
return raw.replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 120) || 'unknown'
|
|
58
|
+
}
|
package/lib/route.js
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 只读 HTTP API。
|
|
3
|
+
*
|
|
4
|
+
* 形态与塔台一致:`GET /dsh-ops/api?...`,同源、no-store、业务失败一律
|
|
5
|
+
* `200 + {ok:false, error}`(HTTP 状态只表达传输层),错误文案中文可读。
|
|
6
|
+
*
|
|
7
|
+
* 这里**没有任何写操作**:回放是"看历史",不是"改历史"。
|
|
8
|
+
*/
|
|
9
|
+
export const API_PREFIX = '/dsh-ops/api'
|
|
10
|
+
|
|
11
|
+
function jsonOf(value) {
|
|
12
|
+
return JSON.stringify(value)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function moneyOf(cost) {
|
|
16
|
+
if (!cost || !Number.isFinite(cost.amount)) return null
|
|
17
|
+
return { amount: cost.amount, currency: cost.currency ?? 'CNY' }
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* @param {{store: ReturnType<import('./store.js').createReplayStore>}} deps
|
|
22
|
+
*/
|
|
23
|
+
export function createApi({ store }) {
|
|
24
|
+
function sessions({ limit = 20 } = {}) {
|
|
25
|
+
const list = store.listSessions({ limit })
|
|
26
|
+
return { ok: true, sessions: list, dir: store.dir }
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function replay({ sid, limit = 200, offset = 0, order = 'desc' }) {
|
|
30
|
+
if (typeof sid !== 'string' || sid.length === 0) return { ok: false, error: '缺少 sid' }
|
|
31
|
+
const result = store.read(sid, { limit, offset, order })
|
|
32
|
+
if (!result.ok) return { ok: false, error: result.error }
|
|
33
|
+
return {
|
|
34
|
+
ok: true,
|
|
35
|
+
sid,
|
|
36
|
+
rows: result.rows,
|
|
37
|
+
total: result.total,
|
|
38
|
+
offset: Number(offset) || 0,
|
|
39
|
+
truncated: result.truncated,
|
|
40
|
+
skipped: result.skipped,
|
|
41
|
+
sum: result.sum,
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function hotspot({ sid }) {
|
|
46
|
+
if (typeof sid !== 'string' || sid.length === 0) return { ok: false, error: '缺少 sid' }
|
|
47
|
+
const summary = store.summarize(sid)
|
|
48
|
+
if (summary === null) return { ok: false, error: '没有找到这个会话的回放' }
|
|
49
|
+
const total = summary.totals.cost.amount ?? 0
|
|
50
|
+
const withShare = (list) => list.map((item) => ({
|
|
51
|
+
...item,
|
|
52
|
+
share: total > 0 ? Math.round((item.amount / total) * 1000) / 10 : null,
|
|
53
|
+
}))
|
|
54
|
+
return {
|
|
55
|
+
ok: true,
|
|
56
|
+
sid,
|
|
57
|
+
totals: summary.totals,
|
|
58
|
+
byTool: withShare(summary.byTool),
|
|
59
|
+
byModel: withShare(summary.byModel),
|
|
60
|
+
truncated: summary.truncated,
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** 结论由规则产生,不让模型自由发挥;每个数字都能回溯到 span。 */
|
|
65
|
+
function notesOf(a, b, diff) {
|
|
66
|
+
const notes = []
|
|
67
|
+
const ratio = (from, to) => (from > 0 ? (to - from) / from : null)
|
|
68
|
+
|
|
69
|
+
const stepRatio = ratio(a.steps ?? 0, b.steps ?? 0)
|
|
70
|
+
if (stepRatio !== null && Math.abs(stepRatio) >= 0.2) {
|
|
71
|
+
notes.push({
|
|
72
|
+
kind: 'steps',
|
|
73
|
+
text: `步数${stepRatio > 0 ? '多' : '少'} ${Math.abs(a.steps - b.steps)} 步(${Math.round(Math.abs(stepRatio) * 100)}%),差异集中在耗时最长的那几步。`,
|
|
74
|
+
})
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const costA = a.cost?.amount ?? null
|
|
78
|
+
const costB = b.cost?.amount ?? null
|
|
79
|
+
if (costA !== null && costB !== null && costA > 0) {
|
|
80
|
+
const costRatio = (costB - costA) / costA
|
|
81
|
+
const topB = b.topModel
|
|
82
|
+
const topA = a.topModel
|
|
83
|
+
const driver = costRatio < 0 ? topA : topB
|
|
84
|
+
if (driver && driver.share !== null && driver.share >= 40) {
|
|
85
|
+
notes.push({
|
|
86
|
+
kind: 'model',
|
|
87
|
+
text: `成本${costRatio > 0 ? '上升' : '下降'} ${Math.round(Math.abs(costRatio) * 100)}%,主因是 ${driver.key} 占该项目 ${driver.share}% 的成本。`,
|
|
88
|
+
})
|
|
89
|
+
} else {
|
|
90
|
+
notes.push({
|
|
91
|
+
kind: 'cost',
|
|
92
|
+
text: `成本${costRatio > 0 ? '上升' : '下降'} ${Math.round(Math.abs(costRatio) * 100)}%,没有单一模型占比超过 40%。`,
|
|
93
|
+
})
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
if (diff.failures !== 0) {
|
|
98
|
+
notes.push({
|
|
99
|
+
kind: 'failures',
|
|
100
|
+
text: `失败次数${diff.failures > 0 ? '多' : '少'} ${Math.abs(diff.failures)} 次(${a.failures} → ${b.failures})。`,
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return notes.slice(0, 3)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function compare({ a, b }) {
|
|
108
|
+
if (!a || !b) return { ok: false, error: '需要两个会话 id' }
|
|
109
|
+
const left = store.summarize(a)
|
|
110
|
+
const right = store.summarize(b)
|
|
111
|
+
if (left === null) return { ok: false, error: `会话 ${a} 没有回放` }
|
|
112
|
+
if (right === null) return { ok: false, error: `会话 ${b} 没有回放` }
|
|
113
|
+
|
|
114
|
+
const pack = (sid, summary) => ({
|
|
115
|
+
sid,
|
|
116
|
+
title: summary.sum?.title ?? null,
|
|
117
|
+
cwdName: summary.sum?.cwdName ?? null,
|
|
118
|
+
steps: summary.totals.steps,
|
|
119
|
+
turns: summary.totals.turns,
|
|
120
|
+
calls: summary.totals.calls,
|
|
121
|
+
failures: summary.totals.failures,
|
|
122
|
+
cost: moneyOf(summary.totals.cost),
|
|
123
|
+
saved: moneyOf(summary.totals.saved),
|
|
124
|
+
tokens: summary.totals.tokens,
|
|
125
|
+
topModel: summary.byModel[0] ?? null,
|
|
126
|
+
topTool: summary.byTool[0] ?? null,
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
const packA = pack(a, left)
|
|
130
|
+
const packB = pack(b, right)
|
|
131
|
+
const diff = {
|
|
132
|
+
steps: packB.steps - packA.steps,
|
|
133
|
+
cost: packA.cost && packB.cost ? Math.round((packB.cost.amount - packA.cost.amount) * 1e6) / 1e6 : null,
|
|
134
|
+
failures: packB.failures - packA.failures,
|
|
135
|
+
}
|
|
136
|
+
// 同源校验:不同工作区也能比,但必须提示,避免读者误以为是同条件对照
|
|
137
|
+
const sameWorkspace = packA.cwdName !== null && packA.cwdName === packB.cwdName
|
|
138
|
+
return {
|
|
139
|
+
ok: true,
|
|
140
|
+
a: packA,
|
|
141
|
+
b: packB,
|
|
142
|
+
diff,
|
|
143
|
+
sameWorkspace,
|
|
144
|
+
notes: notesOf(packA, packB, diff),
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 纯函数入口:参数对象 → 数据对象(便于单测,不起 HTTP)。 */
|
|
149
|
+
function answer(params) {
|
|
150
|
+
const has = (key) => Object.prototype.hasOwnProperty.call(params, key)
|
|
151
|
+
if (has('sessions')) return sessions({ limit: params.limit })
|
|
152
|
+
if (has('replay')) return replay({ sid: params.replay, limit: params.limit, offset: params.offset, order: params.order })
|
|
153
|
+
if (has('hotspot')) return hotspot({ sid: params.hotspot })
|
|
154
|
+
if (has('compare')) {
|
|
155
|
+
const parts = String(params.compare).split(',')
|
|
156
|
+
return compare({ a: parts[0], b: parts[1] })
|
|
157
|
+
}
|
|
158
|
+
return { ok: false, error: '未指定查询:sessions / replay / hotspot / compare' }
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
return { answer, sessions, replay, hotspot, compare }
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* @param {ReturnType<typeof createApi>} api
|
|
166
|
+
*/
|
|
167
|
+
export function handleRequest(api, req, res) {
|
|
168
|
+
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
169
|
+
res.setHeader('cache-control', 'no-store')
|
|
170
|
+
|
|
171
|
+
if (req.method !== 'GET') {
|
|
172
|
+
res.statusCode = 405
|
|
173
|
+
res.end(jsonOf({ ok: false, error: '只支持 GET' }))
|
|
174
|
+
return
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let params
|
|
178
|
+
try {
|
|
179
|
+
const url = new URL(req.url ?? '/', 'http://localhost')
|
|
180
|
+
params = Object.fromEntries(url.searchParams.entries())
|
|
181
|
+
if (url.searchParams.has('sessions')) params.sessions = url.searchParams.get('sessions') ?? '1'
|
|
182
|
+
} catch {
|
|
183
|
+
res.statusCode = 400
|
|
184
|
+
res.end(jsonOf({ ok: false, error: '查询串无法解析' }))
|
|
185
|
+
return
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
let data
|
|
189
|
+
try {
|
|
190
|
+
data = api.answer(params)
|
|
191
|
+
} catch (error) {
|
|
192
|
+
data = { ok: false, error: '回放查询失败' }
|
|
193
|
+
}
|
|
194
|
+
res.statusCode = 200
|
|
195
|
+
res.end(jsonOf(data))
|
|
196
|
+
}
|