@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
package/lib/index.js
ADDED
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @lingda-ai/ledger —— DSH 运行时账本插件(Host 半)
|
|
3
|
+
*
|
|
4
|
+
* 三条铁律(改动前先读):
|
|
5
|
+
* 1. 采集只订阅,不 emit、不修改 session/event;
|
|
6
|
+
* 2. 决策只经 agent/request 改 LlmCallConfig,不在工具执行中途中断;
|
|
7
|
+
* 3. 面板只读快照,计量只发生在 Host 半。
|
|
8
|
+
*
|
|
9
|
+
* 性能约定:
|
|
10
|
+
* - 事件热路径无 async、无 JSON 序列化、无定时器;
|
|
11
|
+
* - 所有缓存容量固定;
|
|
12
|
+
* - 任何异常都被吞掉并计数,绝不污染 post-commit 广播。
|
|
13
|
+
*/
|
|
14
|
+
import { resolveConfig } from './config.js'
|
|
15
|
+
import { createPricing } from './pricing.js'
|
|
16
|
+
import { loadPricingOverride, pricingMetaOf } from './pricing-file.js'
|
|
17
|
+
import { BUILTIN_AS_OF, BUILTIN_SOURCE } from './pricing-table.js'
|
|
18
|
+
import { LedgerStore } from './store.js'
|
|
19
|
+
import { createAttribution } from './attribution.js'
|
|
20
|
+
import { createTrace } from './trace.js'
|
|
21
|
+
import { createLedger } from './ledger.js'
|
|
22
|
+
import { createIdentity } from './identity.js'
|
|
23
|
+
import { createBudgetGuard } from './guard.js'
|
|
24
|
+
import { createLedgerQueryTool } from './audit-tool.js'
|
|
25
|
+
import { makeBudgetMessage } from './budget-message.js'
|
|
26
|
+
import { createSnapshotPublisher } from './snapshot-file.js'
|
|
27
|
+
import { createTraceSink } from './trace-file.js'
|
|
28
|
+
|
|
29
|
+
export const name = 'ledger'
|
|
30
|
+
export const inject = ['sessions', 'tools', 'llm']
|
|
31
|
+
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
// 预算事实通道 A 的消息构造
|
|
34
|
+
//
|
|
35
|
+
// 已核实的契约(dsh-llm/lib/types/message.d.ts):
|
|
36
|
+
// MessageBase = { id, content: ContentBlock[], source: MessageSource }
|
|
37
|
+
// MessageSourceMap.user = { kind: 'user' }
|
|
38
|
+
// createUserMessage({ content, source }) → 带稳定 id 的冻结消息
|
|
39
|
+
//
|
|
40
|
+
// 构造函数惰性加载到 userMessageCtor,随后交给纯函数 makeBudgetMessage 使用。
|
|
41
|
+
// 拿不到构造函数(老运行时/裁剪安装)时 A 通道自动不可用,
|
|
42
|
+
// 事实退化为只经 ledger_query 拉取——少一个能力,不伪造契约。
|
|
43
|
+
// ---------------------------------------------------------------------------
|
|
44
|
+
let userMessageCtor = null
|
|
45
|
+
void import('@deepseek-ai/dsh-llm')
|
|
46
|
+
.then((mod) => {
|
|
47
|
+
if (typeof mod.createUserMessage === 'function') userMessageCtor = mod.createUserMessage
|
|
48
|
+
})
|
|
49
|
+
.catch(() => {})
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* @param {import('@deepseek-ai/cordis').Context} ctx
|
|
53
|
+
* @param {object} [rawConfig]
|
|
54
|
+
*/
|
|
55
|
+
export function apply(ctx, rawConfig) {
|
|
56
|
+
const config = resolveConfig(rawConfig)
|
|
57
|
+
|
|
58
|
+
// 每个会话的工作区根:面板与流水都写进各自的工作区,而不是进程 cwd
|
|
59
|
+
// (session.header.cwd 已核实为会话创建时的绝对工作目录)
|
|
60
|
+
const sessionRoots = new Map()
|
|
61
|
+
|
|
62
|
+
// 流水落盘:trace.enabled 且 trace.file.enabled 才开(两层开关,隐私优先)
|
|
63
|
+
// rootOf 在 store 构造时还拿不到会话 cwd,所以先给默认;append 时按会话解析。
|
|
64
|
+
const traceSink =
|
|
65
|
+
config.trace.enabled === true && config.trace.file?.enabled === true
|
|
66
|
+
? createTraceSink({
|
|
67
|
+
dir: config.panel?.dir ?? '.dsh/ledger',
|
|
68
|
+
maxBytes: config.trace.file.maxBytes,
|
|
69
|
+
rootOf: (sessionId) => sessionRoots?.get(sessionId) ?? process.cwd(),
|
|
70
|
+
})
|
|
71
|
+
: null
|
|
72
|
+
|
|
73
|
+
const store = new LedgerStore({
|
|
74
|
+
capacity: config.ledger.capacity,
|
|
75
|
+
traceCapacity: config.trace.capacity,
|
|
76
|
+
traceEnabled: config.trace.enabled,
|
|
77
|
+
maxSessions: config.ledger.maxSessions,
|
|
78
|
+
onTrace: traceSink === null ? null : (sessionId, record) => traceSink.append(sessionId, record),
|
|
79
|
+
})
|
|
80
|
+
|
|
81
|
+
// 费率覆盖:boot 时读一次(热路径不做 IO)。文件不存在不算错误;
|
|
82
|
+
// 写坏了必须留痕——静默回退内置价会让人以为自己的费率生效了。
|
|
83
|
+
const pricingOverride = loadPricingOverride({ path: config.pricing?.file ?? undefined })
|
|
84
|
+
const pricingMeta = pricingMetaOf(pricingOverride, { asOf: BUILTIN_AS_OF, source: BUILTIN_SOURCE })
|
|
85
|
+
const effectivePricing =
|
|
86
|
+
pricingOverride.kind === 'ok'
|
|
87
|
+
? {
|
|
88
|
+
...config.pricing,
|
|
89
|
+
// 只覆盖同名模型,内置其余模型继续可用(不是"全量替换")
|
|
90
|
+
rates: { ...config.pricing.rates, ...pricingOverride.rates },
|
|
91
|
+
currency: pricingOverride.currency ?? config.pricing.currency,
|
|
92
|
+
}
|
|
93
|
+
: config.pricing
|
|
94
|
+
|
|
95
|
+
const pricing = createPricing(effectivePricing)
|
|
96
|
+
const attribution = createAttribution(config.attribution)
|
|
97
|
+
const trace = createTrace(config.trace)
|
|
98
|
+
|
|
99
|
+
// sessionId → agent:预算事实需要 agent 才能投递到 logged channel
|
|
100
|
+
// agent/created 载荷已核实为 { agent, source, signal? }
|
|
101
|
+
const agents = new Map()
|
|
102
|
+
|
|
103
|
+
const guard = createBudgetGuard({
|
|
104
|
+
store,
|
|
105
|
+
config,
|
|
106
|
+
deliver(sessionId, fact) {
|
|
107
|
+
const agent = agents.get(sessionId)
|
|
108
|
+
if (!agent || typeof agent.inject !== 'function') return
|
|
109
|
+
const factory = config.budget?.messageFactory
|
|
110
|
+
const message =
|
|
111
|
+
typeof factory === 'function'
|
|
112
|
+
? factory(fact)
|
|
113
|
+
: makeBudgetMessage(fact, userMessageCtor)
|
|
114
|
+
// 工厂返回 falsy 表示"这次不推送",不是错误
|
|
115
|
+
if (!message) return
|
|
116
|
+
agent.inject(message)
|
|
117
|
+
},
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
// 右侧栏面板的数据通道:Host 落快照 JSON,浏览器半用 workspace 文件 remote 读回。
|
|
121
|
+
// 默认关闭(config.panel.enabled),打开才有写盘副作用。
|
|
122
|
+
const publisher =
|
|
123
|
+
config.panel?.enabled === true
|
|
124
|
+
? createSnapshotPublisher({
|
|
125
|
+
dir: config.panel.dir,
|
|
126
|
+
intervalMs: config.panel.intervalMs,
|
|
127
|
+
maxBytes: config.panel.maxBytes,
|
|
128
|
+
rootOf: (sessionId) => sessionRoots.get(sessionId) ?? process.cwd(),
|
|
129
|
+
// 预算读数:面板画进度条用,口径来自配置,不由前端推算
|
|
130
|
+
budget: { limit: config.budget?.limit ?? null, currency: config.pricing?.currency ?? 'CNY' },
|
|
131
|
+
// 会话对比:只读 overview,不 touch LRU(store 已保证)
|
|
132
|
+
overview: () => store.overview({ limit: 8 }),
|
|
133
|
+
snapshot: (sessionId, opts) => store.snapshot(sessionId, opts),
|
|
134
|
+
sources: (sessionId, opts) => store.sources(sessionId, opts),
|
|
135
|
+
// 面板必须知道"这些金额是拿哪套价算的",否则数字不可信
|
|
136
|
+
pricing: pricingMeta,
|
|
137
|
+
})
|
|
138
|
+
: null
|
|
139
|
+
|
|
140
|
+
// 身份线索(actor/project/deviceId):解析只发生在会话第一条事件上,热路径零成本。
|
|
141
|
+
// 读的是 .git/config 与 ~/.gitconfig 两个小文件,**不起 git 子进程**。
|
|
142
|
+
const identity = createIdentity()
|
|
143
|
+
|
|
144
|
+
const ledger = createLedger({
|
|
145
|
+
store,
|
|
146
|
+
pricing,
|
|
147
|
+
attribution,
|
|
148
|
+
trace,
|
|
149
|
+
cwdOf: (sessionId) => sessionRoots?.get(sessionId) ?? null,
|
|
150
|
+
identity,
|
|
151
|
+
onEntry: (sessionId, entry) => guard.onEntry(sessionId, entry),
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
ctx.on('session/event', (session, event) => {
|
|
155
|
+
const sid = session?.id
|
|
156
|
+
if (typeof sid === 'string' && !sessionRoots.has(sid) && typeof session?.header?.cwd === 'string') {
|
|
157
|
+
sessionRoots.set(sid, session.header.cwd)
|
|
158
|
+
}
|
|
159
|
+
ledger.onSessionEvent(session, event)
|
|
160
|
+
// 节流落盘在 publisher 内部完成:热路径只多一次 Map 读 + 比较
|
|
161
|
+
if (publisher !== null) publisher.schedule(session?.id)
|
|
162
|
+
})
|
|
163
|
+
|
|
164
|
+
ctx.on('agent/created', ({ agent }) => {
|
|
165
|
+
if (agent?.session?.id) agents.set(agent.session.id, agent)
|
|
166
|
+
})
|
|
167
|
+
ctx.on('agent/disposed', ({ agent }) => {
|
|
168
|
+
if (agent?.session?.id) agents.delete(agent.session.id)
|
|
169
|
+
})
|
|
170
|
+
// session/disposed 载荷就是 session 本身(不是 {session})
|
|
171
|
+
ctx.on('session/disposed', (session) => {
|
|
172
|
+
const id = session?.id
|
|
173
|
+
if (!id) return
|
|
174
|
+
agents.delete(id)
|
|
175
|
+
// 会话消失即释放内存:账本不跨会话累积,避免长期运行的内存增长
|
|
176
|
+
publisher?.remove(id)
|
|
177
|
+
// 按会话索引的状态必须一起释放,否则长跑进程里这几张 Map 只增不减
|
|
178
|
+
guard.forget(id)
|
|
179
|
+
ledger.forget(id)
|
|
180
|
+
traceSink?.remove(id)
|
|
181
|
+
sessionRoots.delete(id)
|
|
182
|
+
store.drop(id)
|
|
183
|
+
})
|
|
184
|
+
|
|
185
|
+
ctx.on('agent/request', (payload, next) => guard.onRequest(payload, next))
|
|
186
|
+
|
|
187
|
+
ctx.tools.register(
|
|
188
|
+
createLedgerQueryTool({ store, pricingMeta, rates: effectivePricing.rates }),
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
const api = {
|
|
192
|
+
snapshot: (sessionId, opts) => store.snapshot(sessionId, opts),
|
|
193
|
+
totals: (sessionId) => store.totals(sessionId),
|
|
194
|
+
// 面板需要"看全部来源"和"跨会话对比":这两个只能由存储层给,前端不拼
|
|
195
|
+
sources: (sessionId, opts) => store.sources(sessionId, opts),
|
|
196
|
+
overview: (opts) => store.overview(opts),
|
|
197
|
+
stats: () => ({ ...ledger.stats(), sessions: store.sessionCount }),
|
|
198
|
+
// 面板诊断:面板读不到数据时,先看这里是 enabled 还是 dir 不对
|
|
199
|
+
panel: publisher === null ? { enabled: false } : { enabled: true, dir: publisher.dir, stats: publisher.stats },
|
|
200
|
+
// 费率来源与拒收明细:对外可查,避免"我改了价但数字没变"变成悬案
|
|
201
|
+
pricing: pricingMeta,
|
|
202
|
+
config,
|
|
203
|
+
}
|
|
204
|
+
// 仓库既有插件统一用 ctx.provide 暴露服务(见 lingzhi-core / lingzhi-workbench)
|
|
205
|
+
ctx.provide('ledger', api)
|
|
206
|
+
|
|
207
|
+
const cleanup = () => {
|
|
208
|
+
publisher?.dispose()
|
|
209
|
+
traceSink?.dispose()
|
|
210
|
+
}
|
|
211
|
+
if (publisher !== null || traceSink !== null) {
|
|
212
|
+
if (typeof ctx.effect === 'function') ctx.effect(() => cleanup)
|
|
213
|
+
else ctx.on('dispose', cleanup)
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
return api
|
|
217
|
+
}
|
package/lib/ledger.js
ADDED
|
@@ -0,0 +1,260 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 采集层:session/event 旁路 → 账本条目。
|
|
3
|
+
*
|
|
4
|
+
* 为什么只订阅 session/event:
|
|
5
|
+
* 源码注释写明它是 "Post-commit, fire-and-forget append feed",
|
|
6
|
+
* 监听器失败会被记录并吞掉,不会让已提交的 append 失败。
|
|
7
|
+
* 这正是治理插件需要的:可观测,且不进入关键路径。
|
|
8
|
+
*
|
|
9
|
+
* 为什么不会阻塞:单事件处理只做常量级工作(复用对象、O(1) 环形写、增量累计)。
|
|
10
|
+
*/
|
|
11
|
+
import { toolResultChars } from './tool-size.js'
|
|
12
|
+
import { normalizeUsage } from './usage.js'
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* 宿主派发的 session/event 实际形状是 {type, seq, time, data, surfaceOp},
|
|
16
|
+
* 载荷在 data 里;而类型声明(dsh-session types.d.ts)写的是扁平的 {turn,step,message}。
|
|
17
|
+
*
|
|
18
|
+
* 两种都认:data 是普通对象就用它,否则退回事件本身。
|
|
19
|
+
*
|
|
20
|
+
* 这条是 2026-11-20 真机跑出来的:单测当时用的是扁平形状,所以 158 例全绿,
|
|
21
|
+
* 但线上真实事件读不到 turn/usage → 每条都记成 unknown(no-usage)、金额全是 null。
|
|
22
|
+
* 教训:**只测自己假设的契约,等于没测宿主。**
|
|
23
|
+
*/
|
|
24
|
+
function payloadOf(event) {
|
|
25
|
+
const data = event?.data
|
|
26
|
+
if (data !== null && typeof data === 'object' && !Array.isArray(data)) return data
|
|
27
|
+
return event
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const MODEL_EVENTS = new Set(['assistant/message', 'assistant/attempt'])
|
|
31
|
+
const TOOL_RESULT = 'tool/result'
|
|
32
|
+
const COMPACTION_PREFIX = 'compaction/'
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* @param {{
|
|
36
|
+
* store: import('./store.js').LedgerStore,
|
|
37
|
+
* pricing: ReturnType<import('./pricing.js').createPricing>,
|
|
38
|
+
* attribution: ReturnType<import('./attribution.js').createAttribution>,
|
|
39
|
+
* trace: ReturnType<import('./trace.js').createTrace>,
|
|
40
|
+
* onEntry?: (sessionId: string, entry: object) => void,
|
|
41
|
+
* now?: () => number,
|
|
42
|
+
* }} deps
|
|
43
|
+
*/
|
|
44
|
+
export function createLedger({ store, pricing, attribution, trace, onEntry, cwdOf, identity, now = () => Date.now() }) {
|
|
45
|
+
let failures = 0
|
|
46
|
+
let handled = 0
|
|
47
|
+
|
|
48
|
+
/**
|
|
49
|
+
* 唯一入账出口。`onEntry` 是给 Budget Guard 的正式钩子,
|
|
50
|
+
* 不再用替换 store.recordEntry 的方式挂副作用(那会污染 store 的职责边界)。
|
|
51
|
+
*/
|
|
52
|
+
/** sessionId → {actor, project, deviceId}。解析只发生一次,热路径上只有一次 Map 读。 */
|
|
53
|
+
const identityBySession = new Map()
|
|
54
|
+
|
|
55
|
+
function identityFor(sessionId) {
|
|
56
|
+
const hit = identityBySession.get(sessionId)
|
|
57
|
+
if (hit !== undefined) return hit
|
|
58
|
+
if (!identity || typeof identity.resolve !== 'function') return null
|
|
59
|
+
const cwd = typeof cwdOf === 'function' ? cwdOf(sessionId) : null
|
|
60
|
+
const value = identity.resolve(cwd)
|
|
61
|
+
identityBySession.set(sessionId, value)
|
|
62
|
+
return value
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function commit(sessionId, entry) {
|
|
66
|
+
store.recordEntry(sessionId, entry)
|
|
67
|
+
if (typeof onEntry !== 'function') return
|
|
68
|
+
try {
|
|
69
|
+
onEntry(sessionId, entry)
|
|
70
|
+
} catch {
|
|
71
|
+
failures += 1
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
function routeOf(event) {
|
|
76
|
+
const source = event?.message?.source
|
|
77
|
+
const provider = source?.provider ?? event?.provider ?? null
|
|
78
|
+
const model = source?.model ?? event?.model ?? null
|
|
79
|
+
return provider || model ? { provider, model } : null
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function sessionIdOf(session) {
|
|
83
|
+
return session?.id ?? session?.sessionId ?? null
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** assistant/message:模型调用成本 */
|
|
87
|
+
function onModelEvent(session, event) {
|
|
88
|
+
const sessionId = sessionIdOf(session)
|
|
89
|
+
if (!sessionId) return
|
|
90
|
+
const turn = event.turn ?? 0
|
|
91
|
+
const step = event.step ?? 0
|
|
92
|
+
|
|
93
|
+
const usage = normalizeUsage(event.usage ?? event.message?.usage)
|
|
94
|
+
const route = routeOf(event)
|
|
95
|
+
const cost = pricing.costOf(usage, route)
|
|
96
|
+
|
|
97
|
+
// 因果映射:本步请求由 **上一轮** 的工具结果推动,因此归因取 step-1 的工具集
|
|
98
|
+
const drivingTools = store.toolsForStep(sessionId, turn, step - 1)
|
|
99
|
+
// 上一步工具结果有多大:成本高的真实原因往往不是模型单价,而是塞进上下文的体量
|
|
100
|
+
const contextChars = store.resultCharsForStep(sessionId, turn, step - 1)
|
|
101
|
+
// 压缩后的第一条调用:与压缩前的规模对照。只报 token 差,不折算金额——
|
|
102
|
+
// 省下的 token 属于"命中"还是"未命中"无法可靠推断,硬乘单价就是编数字。
|
|
103
|
+
const afterContext = usage === null ? null : (usage.inputTokens ?? 0) + (usage.cacheReadTokens ?? 0)
|
|
104
|
+
// 绝大多数会话没有待对照的压缩:size 为 0 时直接跳过 Map 访问(热路径少一次哈希)
|
|
105
|
+
const beforeContext = pendingCompaction.size === 0 ? undefined : pendingCompaction.get(sessionId)
|
|
106
|
+
const contextSaved = beforeContext !== null && beforeContext !== undefined && afterContext !== null && beforeContext > afterContext
|
|
107
|
+
? beforeContext - afterContext
|
|
108
|
+
: null
|
|
109
|
+
if (beforeContext !== null && beforeContext !== undefined) pendingCompaction.delete(sessionId)
|
|
110
|
+
const attr = attribution.forModel({ toolNames: drivingTools })
|
|
111
|
+
|
|
112
|
+
commit(sessionId, {
|
|
113
|
+
at: now(),
|
|
114
|
+
sessionId,
|
|
115
|
+
turn,
|
|
116
|
+
step,
|
|
117
|
+
kind: 'model',
|
|
118
|
+
callId: event.callId ?? null,
|
|
119
|
+
usage,
|
|
120
|
+
cost,
|
|
121
|
+
attribution: attr,
|
|
122
|
+
route,
|
|
123
|
+
contextChars: contextChars > 0 ? contextChars : null,
|
|
124
|
+
contextSavedTokens: contextSaved,
|
|
125
|
+
// 缓存命中省下的钱:两个单价都在价表里,差额确定,不需要任何假设
|
|
126
|
+
savedAmount: pricing.savingsOf(usage, route).amount ?? null,
|
|
127
|
+
})
|
|
128
|
+
|
|
129
|
+
const record = trace.enabled
|
|
130
|
+
? trace.project({
|
|
131
|
+
identity: identityFor(sessionId),
|
|
132
|
+
sessionId, turn, step,
|
|
133
|
+
eventType: 'chat',
|
|
134
|
+
pluginSource: attr.primary?.plugin ?? null,
|
|
135
|
+
usage,
|
|
136
|
+
cost,
|
|
137
|
+
summary: route ? `${route.provider ?? '?'}/${route.model ?? '?'}` : 'model call',
|
|
138
|
+
at: now(),
|
|
139
|
+
})
|
|
140
|
+
: null
|
|
141
|
+
if (record) store.recordTrace(sessionId, record)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** tool/call:记录工具名,供下一步归因 */
|
|
145
|
+
/** tool/result:只记体积,不记内容(内容可能含用户文件全文,不落账本) */
|
|
146
|
+
function onToolResult(session, event) {
|
|
147
|
+
const sessionId = sessionIdOf(session)
|
|
148
|
+
if (!sessionId) return
|
|
149
|
+
const chars = toolResultChars(event.message)
|
|
150
|
+
store.noteToolResult(sessionId, event.turn ?? 0, event.step ?? 0, chars)
|
|
151
|
+
|
|
152
|
+
const record = trace.enabled
|
|
153
|
+
? trace.project({
|
|
154
|
+
identity: identityFor(sessionId),
|
|
155
|
+
sessionId,
|
|
156
|
+
turn: event.turn ?? 0,
|
|
157
|
+
step: event.step ?? 0,
|
|
158
|
+
eventType: 'tool_result',
|
|
159
|
+
pluginSource: null,
|
|
160
|
+
usage: null,
|
|
161
|
+
cost: null,
|
|
162
|
+
summary: `${chars} chars`,
|
|
163
|
+
})
|
|
164
|
+
: null
|
|
165
|
+
if (record) store.recordTrace(sessionId, record)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function onToolCall(session, event) {
|
|
169
|
+
const sessionId = sessionIdOf(session)
|
|
170
|
+
if (!sessionId || typeof event.name !== 'string') return
|
|
171
|
+
store.noteToolCall(sessionId, event.turn ?? 0, event.step ?? 0, event.name)
|
|
172
|
+
|
|
173
|
+
const attr = attribution.forTool(event.name)
|
|
174
|
+
const record = trace.enabled
|
|
175
|
+
? trace.project({
|
|
176
|
+
identity: identityFor(sessionId),
|
|
177
|
+
sessionId,
|
|
178
|
+
turn: event.turn ?? 0,
|
|
179
|
+
step: event.step ?? 0,
|
|
180
|
+
eventType: 'execute_tool',
|
|
181
|
+
pluginSource: attr.primary?.plugin ?? null,
|
|
182
|
+
usage: null,
|
|
183
|
+
cost: null,
|
|
184
|
+
summary: `${event.name} ${event.callId ?? ''}`,
|
|
185
|
+
})
|
|
186
|
+
: null
|
|
187
|
+
if (record) store.recordTrace(sessionId, record)
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** compaction/*:压缩成本必须单列,不能算到业务插件头上 */
|
|
191
|
+
/** 压缩前上下文规模,等压缩后的第一条模型调用来对照。按会话存,会话销毁必须清。 */
|
|
192
|
+
const pendingCompaction = new Map()
|
|
193
|
+
|
|
194
|
+
function onCompaction(session, event, type) {
|
|
195
|
+
const sessionId = sessionIdOf(session)
|
|
196
|
+
if (!sessionId) return
|
|
197
|
+
const usage = normalizeUsage(event.usage ?? event.message?.usage)
|
|
198
|
+
const cost = pricing.costOf(usage, routeOf(event))
|
|
199
|
+
|
|
200
|
+
// 压缩前的上下文规模:压缩本身是一笔支出,要和"省下来多少"一起看才有意义
|
|
201
|
+
const before = store.lastModelContextTokens(sessionId)
|
|
202
|
+
if (before !== null) pendingCompaction.set(sessionId, before)
|
|
203
|
+
|
|
204
|
+
commit(sessionId, {
|
|
205
|
+
at: now(),
|
|
206
|
+
sessionId,
|
|
207
|
+
turn: event.turn ?? 0,
|
|
208
|
+
step: event.step ?? 0,
|
|
209
|
+
kind: 'compaction',
|
|
210
|
+
callId: null,
|
|
211
|
+
usage,
|
|
212
|
+
cost,
|
|
213
|
+
attribution: attribution.forCompaction(),
|
|
214
|
+
route: routeOf(event),
|
|
215
|
+
contextBeforeTokens: before,
|
|
216
|
+
})
|
|
217
|
+
|
|
218
|
+
const record = trace.enabled
|
|
219
|
+
? trace.project({
|
|
220
|
+
identity: identityFor(sessionId),
|
|
221
|
+
sessionId,
|
|
222
|
+
turn: event.turn ?? 0,
|
|
223
|
+
step: event.step ?? 0,
|
|
224
|
+
eventType: 'compaction',
|
|
225
|
+
pluginSource: 'system:compaction',
|
|
226
|
+
usage,
|
|
227
|
+
cost,
|
|
228
|
+
summary: type,
|
|
229
|
+
})
|
|
230
|
+
: null
|
|
231
|
+
if (record) store.recordTrace(sessionId, record)
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function onSessionEvent(session, event) {
|
|
235
|
+
handled += 1
|
|
236
|
+
try {
|
|
237
|
+
const type = event?.type
|
|
238
|
+
if (!type) return
|
|
239
|
+
// 载荷在 data 里(见 payloadOf)。所有 handler 都按扁平形状读,这里统一摊平一次
|
|
240
|
+
const payload = payloadOf(event)
|
|
241
|
+
if (MODEL_EVENTS.has(type)) onModelEvent(session, payload)
|
|
242
|
+
else if (type === 'tool/call') onToolCall(session, payload)
|
|
243
|
+
else if (type === TOOL_RESULT) onToolResult(session, payload)
|
|
244
|
+
else if (type.startsWith(COMPACTION_PREFIX)) onCompaction(session, payload, type)
|
|
245
|
+
} catch {
|
|
246
|
+
// 采集失败只能计数:绝不让它冒泡到已提交的 append 路径
|
|
247
|
+
failures += 1
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
return {
|
|
252
|
+
onSessionEvent,
|
|
253
|
+
/** 会话销毁:pendingCompaction 是按会话索引的状态,必须一起释放 */
|
|
254
|
+
forget: (sessionId) => {
|
|
255
|
+
pendingCompaction.delete(sessionId)
|
|
256
|
+
identityBySession.delete(sessionId)
|
|
257
|
+
},
|
|
258
|
+
stats: () => ({ handled, failures }),
|
|
259
|
+
}
|
|
260
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 面板快照的路径约定(纯函数,两侧共用)。
|
|
3
|
+
*
|
|
4
|
+
* 为什么单独成文件:Host 半要写盘(用 node:fs),浏览器半要读回(用 workspace 文件 remote)。
|
|
5
|
+
* 两侧必须给出**同名同路径**,所以文件名规则和相对路径只在这里定义一次,
|
|
6
|
+
* 不能一边用 node:path 拼、一边又手写一遍。
|
|
7
|
+
*
|
|
8
|
+
* 路径形态:相对路径 `<root>/.dsh/ledger/<safeSessionId>.json`。
|
|
9
|
+
* `workspaceFiles.stat/list` 接受以 Session cwd 为基准的相对路径,
|
|
10
|
+
* `read` 则要绝对路径 —— 客户端先 stat 拿 `absolutePath` 再 read,无需配置。
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** 默认目录(相对会话工作区根)。 */
|
|
14
|
+
export const PANEL_DIR = '.dsh/ledger'
|
|
15
|
+
|
|
16
|
+
/** 快照文件名的固定后缀。 */
|
|
17
|
+
export const PANEL_SUFFIX = '.json'
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* sessionId 进文件名前必须清洗:只留 `[A-Za-z0-9_-]`。
|
|
21
|
+
* 换掉 `../` 这类字符是为了不让会话 id 变成路径穿越。
|
|
22
|
+
* @param {unknown} sessionId
|
|
23
|
+
* @returns {string}
|
|
24
|
+
*/
|
|
25
|
+
export function safeFileName(sessionId) {
|
|
26
|
+
const raw = typeof sessionId === 'string' ? sessionId : ''
|
|
27
|
+
const safe = raw.replace(/[^A-Za-z0-9_-]/g, '_')
|
|
28
|
+
return safe.length > 0 ? safe : 'unknown'
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* 一份快照在工作区里的相对路径。
|
|
33
|
+
* @param {unknown} sessionId
|
|
34
|
+
* @param {string} [dir] - 相对目录,默认 {@link PANEL_DIR}
|
|
35
|
+
* @returns {string}
|
|
36
|
+
*/
|
|
37
|
+
export function panelRelativePath(sessionId, dir = PANEL_DIR) {
|
|
38
|
+
return `${dir}/${safeFileName(sessionId)}${PANEL_SUFFIX}`
|
|
39
|
+
}
|