@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.
@@ -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
+ }
package/lib/client.js ADDED
@@ -0,0 +1,217 @@
1
+ /**
2
+ * @lingda-ai/ledger —— 浏览器半(右侧栏 tab)
3
+ *
4
+ * 已核实的契约(源码逐条对过,勿凭记忆改):
5
+ *
6
+ * 1) 类型登记 @ dsh-client-ui-sidebar-right
7
+ * ctx.sidebarRightTabs.register(definition) → disposer
8
+ * definition: { id, kind, title(address), priority?, patterns?, canOpen?, guide?, multiple?, keepMounted? }
9
+ * guide entry: { id, order, title(), description?(), icon?, commandId? }
10
+ *
11
+ * 2) 正文/标题 seat @ 同一包(keyed,session scope,key = type.id)
12
+ * - 'sidebar.right.pane.tab'
13
+ * - 'sidebar.right.pane.tab.title'
14
+ * 宿主自带的注册形态(sidebar-right 自己的 guide 就是这么写的):
15
+ * ctx.slots.inject('<seat>', () => ctx.slots.register({ name: '<seat>', key: ID }, Component))
16
+ *
17
+ * 3) React 由宿主模块表提供(sidebar-right 编译产物里是 require("react")),
18
+ * 故这里用动态 import 取,取不到就退回"只登记类型、不挂正文"的降级态。
19
+ *
20
+ * 取数通道(已接,细节见 docs/spikes.md C-3):
21
+ * 数据在 Host 的 ctx.ledger 上,浏览器进程拿不到;Host 把只读快照写成
22
+ * 工作区里的 JSON,这里用 `ctx.remote.workspaceFiles` 的 stat/read 读回。
23
+ * 接入点集中在 createFetchView() 一处。
24
+ *
25
+ * 约定(dsh-client-modules):客户端模块是 lazy factory,副作用只能发生在 apply() 内。
26
+ */
27
+
28
+ /** 本实现的身份,也是两个 keyed seat 的 key。 */
29
+ const LEDGER_ID = '@lingda-ai/ledger'
30
+ /** tab 类型判别串,`openTab('ledger.cost', …)` 用的就是它。 */
31
+ const LEDGER_KIND = 'ledger.cost'
32
+
33
+ /** 面板用到的 seat 名,抽出来避免字符串散落。 */
34
+ const SEAT_BODY = 'sidebar.right.pane.tab'
35
+ const SEAT_TITLE = 'sidebar.right.pane.tab.title'
36
+
37
+ import { panelRelativePath } from './panel-path.js'
38
+ import {
39
+ makeLedgerBody,
40
+ makeLedgerTitle,
41
+ renderPayload,
42
+ formatAmount,
43
+ formatTokens,
44
+ formatShare,
45
+ formatClock,
46
+ shortId,
47
+ sourceLabel,
48
+ } from './panel-view.js'
49
+
50
+
51
+ /** 会话 id 太长时截断成 chip 能放下的样子。 */
52
+
53
+ /**
54
+ * 面板取数的唯一注入点:读 Host 落在工作区里的只读快照。
55
+ *
56
+ * 通道已核实(@deepseek-ai/dsh-api-workspace-files 的生成 remote 声明):
57
+ * list(scopeId, path, signal?) → RemoteResult<WorkspaceDirectoryListing>
58
+ * stat(scopeId, path, signal?) → RemoteResult<WorkspaceFileStat>(带 absolutePath)
59
+ * read(scopeId, absolutePath, range, signal?) → RemoteResult<WorkspaceFileText>
60
+ * 相对路径以 Session 的 cwd 为基准,所以客户端**不需要知道**工作区绝对路径:
61
+ * 先用相对路径 stat 换出 absolutePath,再 read。
62
+ *
63
+ * 返回形状:
64
+ * null → 还没有快照(Host 未开启或尚未落盘)
65
+ * { error: '...' } → 通道/解析失败,面板显示原因
66
+ * payload → Host 写的 JSON(version / totals / topSources / sources)
67
+ *
68
+ * @param {any} ctx - 浏览器侧 cordis 上下文
69
+ * @returns {(sessionId: string, opts?: { signal?: AbortSignal }) => Promise<any>}
70
+ */
71
+ export function createFetchView(ctx) {
72
+ return async function fetchView(sessionId, opts = {}) {
73
+ if (typeof sessionId !== 'string' || sessionId.length === 0) return null
74
+ const files = ctx?.remote?.workspaceFiles
75
+ if (!files || typeof files.stat !== 'function' || typeof files.read !== 'function') {
76
+ return { error: '宿主未提供 workspaceFiles 通道' }
77
+ }
78
+ const relative = panelRelativePath(sessionId)
79
+
80
+ let stat
81
+ try {
82
+ stat = await files.stat(sessionId, relative, opts.signal)
83
+ } catch (error) {
84
+ return { error: stringifyError(error) }
85
+ }
86
+ if (!stat?.ok) return null // 文件不存在=尚未落盘,不是错误
87
+ const absolutePath = stat.value?.absolutePath
88
+ if (typeof absolutePath !== 'string') return null
89
+ // 快照可能被写坏/过大:超过上限直接拒绝,避免把整份文件拖进内存
90
+ const bytes = stat.value?.bytes
91
+ if (typeof bytes === 'number' && bytes > 1024 * 1024) return { error: '快照文件过大,已跳过' }
92
+
93
+ let page
94
+ try {
95
+ page = await files.read(sessionId, absolutePath, { offset: 0, limit: 400 }, opts.signal)
96
+ } catch (error) {
97
+ return { error: stringifyError(error) }
98
+ }
99
+ if (!page?.ok) return { error: '读取快照失败' }
100
+ const text = page.value?.text
101
+ if (typeof text !== 'string') return { error: '快照内容为空' }
102
+ if (page.value?.eof === false) return { error: '快照过长,未能一次读完' }
103
+
104
+ try {
105
+ const parsed = JSON.parse(text)
106
+ return parsed && typeof parsed === 'object' ? parsed : { error: '快照格式无法识别' }
107
+ } catch {
108
+ return { error: '快照不是合法 JSON(可能正写到一半)' }
109
+ }
110
+ }
111
+ }
112
+
113
+ /** 把任意抛出物变成一句话。 */
114
+ function stringifyError(error) {
115
+ if (error instanceof Error) return error.message
116
+ if (typeof error === 'string') return error
117
+ return '未知错误'
118
+ }
119
+
120
+ /** CNY 用 ¥,其它币种保留原符号 + 代码。 */
121
+
122
+ /**
123
+ * 正文组件。用 createElement 而不引 JSX,避免给独立仓库引入构建链。
124
+ * @param {any} React - 宿主的 React
125
+ * @param {(sid: string, opts?: object) => Promise<any>} fetchView
126
+ */
127
+
128
+ /**
129
+ * 渲染已取到的快照。
130
+ *
131
+ * 从组件里抽出来是为了可测:SSR 不跑 effect,组件首帧永远是"读取中",
132
+ * 只有把渲染当纯函数,才能在测试里断言四档金额、明细、预算条真的画出来了。
133
+ * @param {any} React
134
+ * @param {any} view - 快照 payload
135
+ * @param {string|null} sessionId
136
+ * @param {any} head - 已在组件侧建好的头部(含刷新按钮)
137
+ */
138
+
139
+ /** 一行 label / value,两个渲染入口共用。 */
140
+
141
+ /** 标题组件:chip 上的实时文案(不做金额,避免每次事件都改布局)。 */
142
+
143
+ /** @param {import('@deepseek-ai/cordis').Context} ctx */
144
+ export async function apply(ctx) {
145
+ const tabs = ctx.sidebarRightTabs
146
+ if (!tabs || typeof tabs.register !== 'function') return
147
+
148
+ const definition = {
149
+ id: LEDGER_ID,
150
+ kind: LEDGER_KIND,
151
+ title: () => '账本',
152
+ priority: 'extension',
153
+ guide: [
154
+ {
155
+ id: 'ledger.cost',
156
+ order: 10,
157
+ title: () => '账本',
158
+ description: () => '本会话的 token 用量与成本归因',
159
+ },
160
+ ],
161
+ // 切会话不重建面板体:成本是常驻读数,重建会丢滚动位置
162
+ keepMounted: true,
163
+ }
164
+
165
+ const disposeTab = tabs.register(definition)
166
+ const disposeClose =
167
+ typeof ctx.sidebarRight?.registerCloseHandler === 'function'
168
+ ? ctx.sidebarRight.registerCloseHandler(LEDGER_KIND, () => {})
169
+ : null
170
+
171
+ // 正文与标题:宿主把 seat 声明在 sidebar-right 里,先 inject 再 register
172
+ let disposeBody = null
173
+ let disposeTitle = null
174
+ const slots = ctx.slots
175
+ if (typeof slots?.inject === 'function' && typeof slots.register === 'function') {
176
+ let React = null
177
+ try {
178
+ React = (await import('react')).default ?? null
179
+ } catch {
180
+ React = null // 宿主没给 React:保持无正文的降级态
181
+ }
182
+ if (React !== null) {
183
+ const fetchView = createFetchView(ctx)
184
+ disposeBody = slots.inject(SEAT_BODY, () =>
185
+ slots.register({ name: SEAT_BODY, key: LEDGER_ID }, makeLedgerBody(React, fetchView)),
186
+ )
187
+ disposeTitle = slots.inject(SEAT_TITLE, () =>
188
+ slots.register({ name: SEAT_TITLE, key: LEDGER_ID }, makeLedgerTitle(React)),
189
+ )
190
+ }
191
+ }
192
+
193
+ const cleanup = () => {
194
+ disposeTitle?.()
195
+ disposeBody?.()
196
+ disposeClose?.()
197
+ disposeTab()
198
+ }
199
+ if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
200
+ else ctx.on('dispose', cleanup)
201
+ }
202
+
203
+ /**
204
+ * 测试可见的内部件。实现都在 panel-view.js(纯展示),
205
+ * 这里重导出,是为了让断言只认 `client.js` 一个入口。
206
+ */
207
+ export const __internal = {
208
+ makeLedgerBody,
209
+ makeLedgerTitle,
210
+ renderPayload,
211
+ formatAmount,
212
+ formatTokens,
213
+ formatShare,
214
+ formatClock,
215
+ shortId,
216
+ sourceLabel,
217
+ }
package/lib/config.js ADDED
@@ -0,0 +1,74 @@
1
+ import { BUILTIN_RATES } from './pricing-table.js'
2
+
3
+ /**
4
+ * 配置默认值。
5
+ *
6
+ * 取舍原则:
7
+ * - 会改变 Agent 行为质量的开关(预算降级、事实推送)默认 **关闭**;
8
+ * - 只读观测(账本)默认开启,但容量有界;
9
+ * - 任何"猜"的字段都不给默认值,宁可为 null。
10
+ */
11
+ export const DEFAULT_CONFIG = Object.freeze({
12
+ ledger: {
13
+ capacity: 2000, // 每个会话保留的账本条目数
14
+ maxSessions: 64, // 同时保留状态的会话上限(LRU 淘汰)
15
+ },
16
+ pricing: {
17
+ currency: 'CNY',
18
+ // 内置官方价(来源与日期见 pricing-table.js),用户配置按单模型深合并覆盖。
19
+ // "provider/model" 或 "model" → {input,output,cacheRead,cacheWrite},单位 元/token
20
+ rates: BUILTIN_RATES,
21
+ // 费率覆盖文件:null = 用默认 ~/.dsh/ledger/pricing.json(不存在就纯用内置价)。
22
+ // 文件里写 元/百万,整条生效或整条拒绝,见 pricing-file.js 的取舍说明。
23
+ file: null,
24
+ },
25
+ budget: {
26
+ limit: null, // null = 不启用预算
27
+ threshold: 0.8, // 触发投递的比例
28
+ downgrade: null, // {provider, model, maxTokens} | null,默认关闭
29
+ },
30
+ trace: {
31
+ enabled: false, // 行为流水默认关闭(隐私优先)
32
+ capacity: 5000,
33
+ maxTextLength: 200, // 摘要截断长度
34
+ // 落盘是二次副作用,必须显式再开一层;开启后写 <cwd>/.dsh/ledger/<sid>.trace.jsonl
35
+ file: {
36
+ enabled: false,
37
+ maxBytes: 4194304, // 单文件 4MB 封顶
38
+ },
39
+ },
40
+ attribution: {
41
+ toolOwners: {}, // 工具名 → 所属插件(唯一可得的归因依据,见 docs/spikes.md)
42
+ },
43
+ // 右侧栏面板的数据通道:Host 把只读快照落成 JSON,浏览器半用 workspace 文件 remote 读回。
44
+ // 默认关闭——写盘是外部副作用,不该由观测默认产生。
45
+ panel: {
46
+ enabled: false,
47
+ dir: '.dsh/ledger', // 相对 process.cwd();也可给绝对路径
48
+ intervalMs: 3000, // 同一会话两次落盘的最小间隔
49
+ maxBytes: 262144, // 超过则只写 totals + topSources
50
+ },
51
+ })
52
+
53
+ function merge(base, patch) {
54
+ if (!patch || typeof patch !== 'object') return base
55
+ const out = { ...base }
56
+ for (const [key, value] of Object.entries(patch)) {
57
+ const current = base[key]
58
+ if (value && typeof value === 'object' && !Array.isArray(value) && current && typeof current === 'object' && !Array.isArray(current)) {
59
+ out[key] = merge(current, value)
60
+ } else if (value !== undefined) {
61
+ out[key] = value
62
+ }
63
+ }
64
+ return out
65
+ }
66
+
67
+ export function resolveConfig(raw) {
68
+ return merge(DEFAULT_CONFIG, raw)
69
+ }
70
+
71
+ /** 预算是否真的可用:有 limit 才算,避免 limit=0 被当成"启用" */
72
+ export function budgetEnabled(config) {
73
+ return typeof config?.budget?.limit === 'number' && config.budget.limit > 0
74
+ }
package/lib/guard.js ADDED
@@ -0,0 +1,102 @@
1
+ /**
2
+ * Budget Guard。
3
+ *
4
+ * P-3 探针修正(源码证据见 docs/spikes.md):
5
+ * 原设计想在 agent/request 里把 budget_pressure 塞进"请求参数"让模型读到。
6
+ * 源码事实是:该 waterfall 的返回类型是 LlmCallConfig
7
+ * { provider, model, reasoningEffort?, temperature?, maxTokens?, stop? }
8
+ * 且注释明确 "this waterfall cannot mutate messages"。
9
+ * → 因此 **prompt 事实注入不能走 agent/request**,只能走可持久化的日志通道。
10
+ *
11
+ * 拆分后的两条通道:
12
+ * 通道 A(事实/推送):agent 可读的 budget 事实 → 由宿主注入一个 UserMessage
13
+ * (经 agent.inject,属于 logged channel),**默认关闭**,
14
+ * 需要宿主提供 messageFactory,插件自身不猜消息结构。
15
+ * 通道 B(决策/降级):agent/request 返回替换的 LlmCallConfig(只改路由与预算),
16
+ * 这是真·原生能力,默认关闭。
17
+ *
18
+ * 两条通道都遵守:绝不 throwing、绝不短路 next()。
19
+ */
20
+ import { budgetEnabled } from './config.js'
21
+
22
+ export function createBudgetGuard({ store, config, deliver }) {
23
+ const threshold = config?.budget?.threshold ?? 0.8
24
+ const limit = config?.budget?.limit ?? null
25
+ const downgrade = config?.budget?.downgrade ?? null
26
+ const armed = new Map() // sessionId → 是否已在本轮超限中投递过
27
+
28
+ function spentOf(sessionId) {
29
+ const totals = store.totals(sessionId)
30
+ // 只按已知金额判断;有未知条目时该会话不可判预算
31
+ if (totals.cost.amount === null || totals.cost.unknownEntries > 0) return null
32
+ return totals.cost.amount
33
+ }
34
+
35
+ function evaluate(sessionId, turn, step) {
36
+ if (!budgetEnabled(config)) return null
37
+ const spent = spentOf(sessionId)
38
+ if (spent === null) return null
39
+ const ratio = spent / limit
40
+ if (ratio < threshold) {
41
+ // 回滞:低于 90% 阈值才重新武装,避免在阈值附近反复投递
42
+ if (ratio < threshold * 0.9) armed.delete(sessionId)
43
+ return null
44
+ }
45
+ if (armed.get(sessionId) === true) return null
46
+ armed.set(sessionId, true)
47
+ return {
48
+ spent,
49
+ limit,
50
+ // 币种来自计价层,不在展示层假设
51
+ currency: store.totals(sessionId).cost.currency ?? null,
52
+ remainingRatio: Math.max(0, 1 - ratio),
53
+ suggestion: 'consider_compaction_or_model_downgrade',
54
+ asOfStep: { turn, step },
55
+ }
56
+ }
57
+
58
+ /** 每条账本条目后调用;仅在跨越阈值那一次投递 */
59
+ function onEntry(sessionId, entry) {
60
+ try {
61
+ const fact = evaluate(sessionId, entry.turn, entry.step)
62
+ if (!fact) return
63
+ deliver?.(sessionId, fact)
64
+ } catch {
65
+ // 投递失败不影响采集
66
+ }
67
+ }
68
+
69
+ /** agent/request waterfall:只做降级,不做事实注入 */
70
+ async function onRequest(payload, next) {
71
+ const config0 = await next()
72
+ try {
73
+ if (!downgrade || !budgetEnabled(config)) return config0
74
+ if (!downgrade.provider && !downgrade.model) return config0
75
+ const sessionId = payload?.agent?.session?.id
76
+ if (!sessionId) return config0
77
+ const spent = spentOf(sessionId)
78
+ if (spent === null || spent / limit < threshold) return config0
79
+
80
+ // 已超阈值且用户显式启用降级:替换路由。字段来自 LlmCallConfig,逐项覆盖即可。
81
+ return {
82
+ ...config0,
83
+ provider: downgrade.provider ?? config0.provider,
84
+ model: downgrade.model ?? config0.model,
85
+ maxTokens: downgrade.maxTokens ?? config0.maxTokens,
86
+ }
87
+ } catch {
88
+ // 降级失败必须回退到原配置,宁可超预算也不能让请求崩掉
89
+ return config0
90
+ }
91
+ }
92
+
93
+ /**
94
+ * 会话结束要释放按会话索引的状态。
95
+ * armed 只存 boolean,但它按会话无界增长——长跑进程里就是一条缓慢的内存泄漏。
96
+ */
97
+ function forget(sessionId) {
98
+ armed.delete(sessionId)
99
+ }
100
+
101
+ return { onEntry, onRequest, evaluate, forget }
102
+ }