@lingda-ai/dsh-plugin-ledger 0.1.3 → 0.1.5
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 +382 -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 +1044 -0
- package/lib/client.src.js +248 -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 +26 -6
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ledger_query:让 Agent 查自己的运行时账本。
|
|
3
|
+
*
|
|
4
|
+
* 契约对齐(@deepseek-ai/dsh-llm ToolSchema / dsh-tools ToolDefinition):
|
|
5
|
+
* { name, description, parameters } + output: { schema, render } + execute
|
|
6
|
+
* execute 返回唯一 canonical 值(这里是字符串),render 把它变成 ContentBlock[]。
|
|
7
|
+
*
|
|
8
|
+
* 返回摘要而不是原始 JSONL:消费者是 Agent,不是人。
|
|
9
|
+
*
|
|
10
|
+
* 三个 op:
|
|
11
|
+
* snapshot(默认):单会话总览 + 最近 N 条
|
|
12
|
+
* sources:单会话全部成本来源(不截断到 Top3),可按金额/条目数排序
|
|
13
|
+
* overview:跨会话概览(LRU 顺序),用于"这周哪个会话最贵"
|
|
14
|
+
*
|
|
15
|
+
* 未知成本一律带原因返回,不做估算、不补 0。
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
function formatAmount(cost) {
|
|
19
|
+
if (!cost) return 'n/a'
|
|
20
|
+
if (cost.kind === 'unknown') return `未知(${cost.reason})`
|
|
21
|
+
return `${cost.amount.toFixed(6)} ${cost.currency}`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function formatPct(share) {
|
|
25
|
+
return typeof share === 'number' ? ` (${(share * 100).toFixed(1)}%)` : ''
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const M = 1e6
|
|
29
|
+
|
|
30
|
+
/** 元/token → 元/百万,和官方公告同一单位,人读才不费劲 */
|
|
31
|
+
function perMillion(v) {
|
|
32
|
+
if (!Number.isFinite(v)) return '—'
|
|
33
|
+
return String(Number((v * M).toFixed(6)))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
const REJECT_TEXT = {
|
|
37
|
+
'fields-missing': (r) => `缺字段 ${(r.missing ?? []).join('/')}`,
|
|
38
|
+
'field-invalid': (r) => `${r.field} 不是数字`,
|
|
39
|
+
negative: (r) => `${r.field} 为负数`,
|
|
40
|
+
'not-an-object': () => '值不是对象',
|
|
41
|
+
'empty-model': () => '模型名为空',
|
|
42
|
+
'bad-json': () => '文件不是合法 JSON',
|
|
43
|
+
'no-rates': () => '缺少 rates',
|
|
44
|
+
'all-rejected': () => '没有一条完整费率',
|
|
45
|
+
'read-failed': () => '文件读取失败',
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function createLedgerQueryTool({ store, pricingMeta = null, rates = null }) {
|
|
49
|
+
return {
|
|
50
|
+
name: 'ledger_query',
|
|
51
|
+
description:
|
|
52
|
+
'查询运行时账本:模型调用与工具调用流水、token 用量、成本归因。'
|
|
53
|
+
+ 'op=snapshot 看单会话总览与最近 N 条;op=sources 看该会话全部成本来源(含条目数与占比);'
|
|
54
|
+
+ 'op=overview 看跨会话概览;op=rates 看当前生效的费率表与来源'
|
|
55
|
+
+ '(含被忽略的模型及原因,用来排查"我的 pricing.json 为什么没生效")。'
|
|
56
|
+
+ '成本未知时明确返回 unknown 及原因,不给出估算值。',
|
|
57
|
+
parameters: {
|
|
58
|
+
type: 'object',
|
|
59
|
+
additionalProperties: false,
|
|
60
|
+
required: [],
|
|
61
|
+
properties: {
|
|
62
|
+
op: {
|
|
63
|
+
type: 'string',
|
|
64
|
+
enum: ['snapshot', 'sources', 'overview', 'rates'],
|
|
65
|
+
description: '查询类型,默认 snapshot',
|
|
66
|
+
},
|
|
67
|
+
sessionId: {
|
|
68
|
+
type: 'string',
|
|
69
|
+
description: '目标会话 id;op=overview 时可省略',
|
|
70
|
+
},
|
|
71
|
+
lastN: { type: 'number', description: 'snapshot 最近 N 条条目,默认 10,上限 100' },
|
|
72
|
+
limit: { type: 'number', description: 'sources/overview 返回条数上限,默认 20,上限 64' },
|
|
73
|
+
sort: {
|
|
74
|
+
type: 'string',
|
|
75
|
+
enum: ['amount', 'entries', 'name'],
|
|
76
|
+
description: 'sources 排序,默认 amount(金额降序)',
|
|
77
|
+
},
|
|
78
|
+
},
|
|
79
|
+
},
|
|
80
|
+
output: {
|
|
81
|
+
schema: { type: 'string' },
|
|
82
|
+
render(_args, value) {
|
|
83
|
+
return [{ type: 'text', text: String(value) }]
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
async execute(args) {
|
|
87
|
+
const op = args?.op ?? 'snapshot'
|
|
88
|
+
|
|
89
|
+
// 费率自查:用户写了 pricing.json 却没生效时,先看这里。
|
|
90
|
+
// 这是"不静默回退"的另一半——回退要留痕,痕要能被查到。
|
|
91
|
+
if (op === 'rates') {
|
|
92
|
+
if (rates === null) return '费率表未注入(当前运行时没有共享费率)。'
|
|
93
|
+
const meta = pricingMeta ?? {}
|
|
94
|
+
const kind = meta.kind === 'file' ? '自定义文件' : '内置官方价'
|
|
95
|
+
const lines = [`费率来源:${kind}${meta.asOf ? ` · ${meta.asOf}` : ''}`]
|
|
96
|
+
if (meta.source) lines.push(`来源:${meta.source}`)
|
|
97
|
+
lines.push('', '模型费率(元 / 百万 tokens):')
|
|
98
|
+
for (const [model, rate] of Object.entries(rates)) {
|
|
99
|
+
lines.push(
|
|
100
|
+
` - ${model} 命中 ${perMillion(rate.cacheRead)} / 未命中 ${perMillion(rate.input)}`
|
|
101
|
+
+ ` / 输出 ${perMillion(rate.output)} / 缓存写 ${perMillion(rate.cacheWrite)}`,
|
|
102
|
+
)
|
|
103
|
+
}
|
|
104
|
+
if (typeof meta.error === 'string') {
|
|
105
|
+
const text = (REJECT_TEXT[meta.error] ?? (() => meta.error))(meta)
|
|
106
|
+
lines.push('', `注意:pricing.json 未生效(${text})${meta.detail ? ` (${meta.detail})` : ''},以上为内置价。`)
|
|
107
|
+
}
|
|
108
|
+
const rejected = Array.isArray(meta.rejected) ? meta.rejected : []
|
|
109
|
+
if (rejected.length > 0) {
|
|
110
|
+
lines.push('', `被忽略的模型 ${rejected.length} 条(整条不生效,不会半套合并):`)
|
|
111
|
+
for (const r of rejected) {
|
|
112
|
+
const text = (REJECT_TEXT[r.reason] ?? (() => r.reason))(r)
|
|
113
|
+
lines.push(` - ${r.model ?? '—'}:${text}`)
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return lines.join('\n')
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (op === 'overview') {
|
|
120
|
+
const limit = Math.min(Math.max(Number(args?.limit) || 20, 1), 64)
|
|
121
|
+
const ov = store.overview({ limit })
|
|
122
|
+
if (!ov.sessions.length) return '暂无任何会话账本记录(可能未被采集或已全部淘汰)。'
|
|
123
|
+
const lines = [`会话数 ${ov.sessionCount}${ov.truncated ? `(仅显示最近 ${ov.sessions.length} 个)` : ''}`, '按最近使用排序:']
|
|
124
|
+
for (const s of ov.sessions) {
|
|
125
|
+
const amount = s.cost.amount === null ? '未知' : `${s.cost.amount.toFixed(6)} ${s.cost.currency}`
|
|
126
|
+
lines.push(` - ${s.sessionId} | ${amount} | 已知 ${s.cost.knownEntries} / 未知 ${s.cost.unknownEntries} | ${s.entries} 条`)
|
|
127
|
+
}
|
|
128
|
+
return lines.join('\n')
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
const sessionId = args?.sessionId
|
|
132
|
+
if (!sessionId) return '缺少 sessionId(op=overview 之外必须提供)。'
|
|
133
|
+
|
|
134
|
+
if (op === 'sources') {
|
|
135
|
+
const limit = Math.min(Math.max(Number(args?.limit) || 20, 1), 64)
|
|
136
|
+
const sort = args?.sort ?? 'amount'
|
|
137
|
+
const res = store.sources(sessionId, { limit, sort })
|
|
138
|
+
if (!res) return `会话 ${sessionId} 无账本记录(可能未被采集或已淘汰)。`
|
|
139
|
+
const total = res.total === null ? '未知' : res.total.toFixed(6)
|
|
140
|
+
const lines = [
|
|
141
|
+
`会话 ${sessionId} 成本来源(排序 ${sort},共 ${res.sourceCount} 个${res.truncated ? `,显示前 ${res.sources.length}` : ''})`,
|
|
142
|
+
`已知合计 ${total} / 条目 已知 ${res.knownEntries} 未知 ${res.unknownEntries}`,
|
|
143
|
+
]
|
|
144
|
+
if (!res.sources.length) lines.push(' 暂无可归因来源。')
|
|
145
|
+
for (const s of res.sources) {
|
|
146
|
+
lines.push(` - ${s.plugin}: ${s.amount.toFixed(6)}${formatPct(s.share)} | ${s.entries} 条`)
|
|
147
|
+
}
|
|
148
|
+
if (res.unknownEntries > 0) lines.push(`注意:${res.unknownEntries} 条成本未知,未计入上述合计与占比。`)
|
|
149
|
+
return lines.join('\n')
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const n = Math.min(Math.max(Number(args?.lastN) || 10, 1), 100)
|
|
153
|
+
const snap = store.snapshot(sessionId, { lastN: n })
|
|
154
|
+
if (!snap) return `会话 ${sessionId} 无账本记录(可能未被采集或已淘汰)。`
|
|
155
|
+
|
|
156
|
+
const t = snap.totals
|
|
157
|
+
const lines = []
|
|
158
|
+
lines.push(`会话 ${sessionId}`)
|
|
159
|
+
lines.push(`累计成本:${t.cost.amount === null ? '未知(无已知费率条目)' : `${t.cost.amount.toFixed(6)} ${t.cost.currency}`}`)
|
|
160
|
+
lines.push(`计费条目:已知 ${t.cost.knownEntries} / 未知 ${t.cost.unknownEntries}`)
|
|
161
|
+
if (t.tokens) {
|
|
162
|
+
lines.push(
|
|
163
|
+
`Token:input ${t.tokens.input} / output ${t.tokens.output} / cacheRead ${t.tokens.cacheRead} / cacheWrite ${t.tokens.cacheWrite}`
|
|
164
|
+
+ (t.tokens.missing > 0 ? `(${t.tokens.missing} 条 usage 不完整)` : ''),
|
|
165
|
+
)
|
|
166
|
+
}
|
|
167
|
+
if (snap.topSources.length) {
|
|
168
|
+
lines.push('成本来源 Top:')
|
|
169
|
+
for (const item of snap.topSources) lines.push(` - ${item.plugin}: ${item.amount.toFixed(6)}`)
|
|
170
|
+
} else {
|
|
171
|
+
lines.push('成本来源:暂无。')
|
|
172
|
+
}
|
|
173
|
+
lines.push(`最近 ${snap.recent.length} 条:`)
|
|
174
|
+
for (const e of snap.recent) {
|
|
175
|
+
const who = e.attribution?.system === 'compaction'
|
|
176
|
+
? 'system:compaction'
|
|
177
|
+
: e.attribution?.primary?.plugin
|
|
178
|
+
?? (e.attribution?.unresolvedReason ? `unattributed(${e.attribution.unresolvedReason})` : 'unattributed')
|
|
179
|
+
lines.push(` #${e.turn}.${e.step} ${e.kind} ${e.callId ?? ''} → ${who} | ${formatAmount(e.cost)}`.replace(/\s+/g, ' '))
|
|
180
|
+
}
|
|
181
|
+
return lines.join('\n')
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 预算事实 → 合法 model-facing UserMessage。
|
|
3
|
+
*
|
|
4
|
+
* 纯函数:构造函数由调用方注入。
|
|
5
|
+
* - 真实运行时传 `createUserMessage`(已核实导出,见 docs/spikes.md);
|
|
6
|
+
* - 测试传替身,不需要装整个 dsh-llm。
|
|
7
|
+
* 这样既不把 dsh-llm 绑成硬依赖,也不靠"猜消息结构"。
|
|
8
|
+
*
|
|
9
|
+
* 已核实契约:
|
|
10
|
+
* createUserMessage({ content: ContentBlock[], source: { kind: 'user' } })
|
|
11
|
+
* → { id, role: 'user', content, source }
|
|
12
|
+
*/
|
|
13
|
+
export function makeBudgetMessage(fact, createUserMessage) {
|
|
14
|
+
if (typeof createUserMessage !== 'function') return null
|
|
15
|
+
if (!fact || typeof fact !== 'object') return null
|
|
16
|
+
|
|
17
|
+
const money = (v) => (typeof v === 'number' ? v.toFixed(4) : String(v))
|
|
18
|
+
const cur = fact.currency ?? ''
|
|
19
|
+
const pct = Math.round((fact.remainingRatio ?? 0) * 100)
|
|
20
|
+
const text =
|
|
21
|
+
`[账本] 本会话已花费 ${cur}${money(fact.spent)} / 预算 ${cur}${money(fact.limit)}` +
|
|
22
|
+
`(剩余 ${pct}%)。建议:压缩上下文,或改用更低档的模型继续。`
|
|
23
|
+
|
|
24
|
+
return createUserMessage({
|
|
25
|
+
content: [{ type: 'text', text }],
|
|
26
|
+
source: { kind: 'user' },
|
|
27
|
+
})
|
|
28
|
+
}
|