dsh-ta 0.1.0 → 0.3.0

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,160 @@
1
+ /** Durable per-turn usage ledger for Ta sessions. */
2
+ import { appendFileSync, mkdirSync, readdirSync, readFileSync, unlinkSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+ import { isTaSession } from '../gates.js'
5
+ import { readInternalSessions, todayText } from '../storage.js'
6
+ import { calculateCost, loadPricing } from './pricing.js'
7
+
8
+ function number(value) {
9
+ return Number.isFinite(Number(value)) ? Number(value) : 0
10
+ }
11
+
12
+ function usageFromEvent(event) {
13
+ const data = event?.data ?? {}
14
+ return data.usage ?? data.message?.usage ?? null
15
+ }
16
+
17
+ function modelFromEvent(event) {
18
+ const data = event?.data ?? {}
19
+ return data.message?.source?.model ?? data.source?.model ?? data.model ?? 'unknown'
20
+ }
21
+
22
+ export class UsageLedger {
23
+ constructor({ ctx, config }) {
24
+ this.ctx = ctx
25
+ this.config = config
26
+ this.turns = new Map()
27
+ this.started = false
28
+ }
29
+
30
+ start() {
31
+ if (this.started) return
32
+ this.started = true
33
+ }
34
+
35
+ handle(session, event) {
36
+ if (!session || !event) return
37
+ try {
38
+ if (!isTaSession(this.ctx, session, this.config)) return
39
+ if (event.type === 'assistant/message') {
40
+ const usage = usageFromEvent(event)
41
+ if (!usage) return
42
+ const turn = event.data?.turn ?? event.data?.message?.turn ?? 'unknown'
43
+ const key = `${session.id}:${turn}`
44
+ const current = this.turns.get(key) ?? {
45
+ sessionId: String(session.id),
46
+ turn,
47
+ tokens: { uncachedInput: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
48
+ model: modelFromEvent(event),
49
+ category: this.category(session),
50
+ firstAt: event.time ?? Date.now(),
51
+ }
52
+ current.tokens.uncachedInput += number(usage.inputTokens)
53
+ current.tokens.cacheRead += number(usage.cacheReadTokens)
54
+ current.tokens.cacheWrite += number(usage.cacheWriteTokens)
55
+ current.tokens.output += number(usage.outputTokens)
56
+ current.model = modelFromEvent(event)
57
+ this.turns.set(key, current)
58
+ return
59
+ }
60
+ if (event.type !== 'turn/end') return
61
+ const turn = event.data?.turn ?? 'unknown'
62
+ const key = `${session.id}:${turn}`
63
+ const current = this.turns.get(key)
64
+ if (!current) return
65
+ this.turns.delete(key)
66
+ this.append(current)
67
+ } catch {
68
+ /* usage accounting must never stop a turn */
69
+ }
70
+ }
71
+
72
+ category(session) {
73
+ let preset
74
+ try {
75
+ preset = this.ctx.agentPresets?.presetForSession?.(session)
76
+ } catch {
77
+ preset = undefined
78
+ }
79
+ if (preset === 'ta-review') return 'review'
80
+ const id = String(session.id ?? '')
81
+ if (id.startsWith('dsh-im-session-')) return 'chat'
82
+ const internal = readInternalSessions(this.config)
83
+ const purpose = internal?.[id]
84
+ if (purpose === 'heartbeat' || purpose === 'outing') return purpose
85
+ return 'chat'
86
+ }
87
+
88
+ append(item) {
89
+ const total = item.tokens.uncachedInput + item.tokens.cacheRead + item.tokens.cacheWrite + item.tokens.output
90
+ if (total <= 0) return
91
+ const date = todayText(this.config)
92
+ const pricing = loadPricing(this.config)
93
+ const costCny = calculateCost(item.tokens, item.model, pricing)
94
+ const record = {
95
+ ts: new Date().toISOString(),
96
+ sessionId: item.sessionId,
97
+ turn: item.turn,
98
+ category: item.category,
99
+ model: item.model || 'unknown',
100
+ tokens: item.tokens,
101
+ currency: pricing.currency ?? 'CNY',
102
+ priceVersion: pricing.version,
103
+ costCny,
104
+ }
105
+ const directory = resolve(this.config.taHome, 'state/usage')
106
+ mkdirSync(directory, { recursive: true })
107
+ appendFileSync(resolve(directory, `${date}.jsonl`), JSON.stringify(record) + '\n')
108
+ }
109
+ }
110
+
111
+ export function readUsageRecords(config, date) {
112
+ const path = resolve(config.taHome, 'state/usage', `${date}.jsonl`)
113
+ try {
114
+ const lines = readFileSync(path, 'utf8').split(/\r?\n/).filter(Boolean)
115
+ return lines.flatMap(line => {
116
+ try {
117
+ const value = JSON.parse(line)
118
+ return value && typeof value === 'object' ? [value] : []
119
+ } catch {
120
+ return []
121
+ }
122
+ })
123
+ } catch {
124
+ return []
125
+ }
126
+ }
127
+
128
+
129
+ /**
130
+ * 清零本地花销账本:只删除 state/usage 下的日期 JSONL,不碰目录和其他文件。
131
+ * 返回删除的文件数、记录数和警告;TA 家未配置时什么都不做。
132
+ */
133
+ export function resetUsage(config) {
134
+ const home = config?.taHome
135
+ if (typeof home !== 'string' || home.length === 0) {
136
+ return { files: 0, records: 0, warnings: ['TA 的家尚未配置'] }
137
+ }
138
+ const directory = resolve(home, 'state/usage')
139
+ let entries
140
+ try {
141
+ entries = readdirSync(directory, { withFileTypes: true })
142
+ } catch {
143
+ return { files: 0, records: 0, warnings: [] }
144
+ }
145
+ let files = 0
146
+ let records = 0
147
+ const warnings = []
148
+ for (const entry of entries) {
149
+ if (!entry.isFile() || !/^\d{4}-\d{2}-\d{2}\.jsonl$/.test(entry.name)) continue
150
+ const path = resolve(directory, entry.name)
151
+ try {
152
+ records += readFileSync(path, 'utf8').split(/\r?\n/).filter(Boolean).length
153
+ unlinkSync(path)
154
+ files += 1
155
+ } catch (cause) {
156
+ warnings.push(`删除 ${entry.name} 失败:${cause instanceof Error ? cause.message : String(cause)}`)
157
+ }
158
+ }
159
+ return { files, records, warnings }
160
+ }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * Price table for DSH agent usage.
3
+ *
4
+ * Prices are CNY per one million tokens and are deliberately a local,
5
+ * versioned table, not an authoritative billing source. A user override at
6
+ * $TA_HOME/state/usage/pricing.json wins over these defaults.
7
+ *
8
+ * Defaults are based on DeepSeek's published Flash/Pro rates at the time of
9
+ * implementation. Treat costCny as an estimate; token counts are exact.
10
+ */
11
+ import { readFileSync } from 'node:fs'
12
+ import { resolve } from 'node:path'
13
+
14
+ export const DEFAULT_PRICING = {
15
+ currency: 'CNY',
16
+ version: '2026-12-flash-pro-flat',
17
+ models: {
18
+ 'deepseek-flash': { input: 1, cacheRead: 0.02, cacheWrite: 1, output: 4 },
19
+ 'deepseek-v4-pro': { input: 4.5, cacheRead: 0.15, cacheWrite: 4.5, output: 13.5 },
20
+ 'deepseek-chat': { input: 1, cacheRead: 0.02, cacheWrite: 1, output: 4 },
21
+ },
22
+ }
23
+
24
+ export function pricingPath(config) {
25
+ return resolve(config.taHome, 'state/usage/pricing.json')
26
+ }
27
+
28
+ export function loadPricing(config) {
29
+ try {
30
+ const value = JSON.parse(readFileSync(pricingPath(config), 'utf8'))
31
+ if (!value || typeof value !== 'object' || !value.models || typeof value.models !== 'object') {
32
+ return DEFAULT_PRICING
33
+ }
34
+ return { ...DEFAULT_PRICING, ...value, models: { ...DEFAULT_PRICING.models, ...value.models } }
35
+ } catch {
36
+ return DEFAULT_PRICING
37
+ }
38
+ }
39
+
40
+ export function calculateCost(tokens, model, pricing = DEFAULT_PRICING) {
41
+ if (!tokens || typeof tokens !== 'object') return null
42
+ const key = typeof model === 'string' ? model.toLowerCase() : ''
43
+ const prices = pricing.models[key]
44
+ ?? Object.entries(pricing.models).find(([id]) => key.includes(id.toLowerCase()))?.[1]
45
+ ?? null
46
+ if (!prices) return null
47
+ const perMillion = (value, price) => (Number(value) || 0) * (Number(price) || 0) / 1_000_000
48
+ return perMillion(tokens.uncachedInput, prices.input)
49
+ + perMillion(tokens.cacheRead, prices.cacheRead)
50
+ + perMillion(tokens.cacheWrite, prices.cacheWrite)
51
+ + perMillion(tokens.output, prices.output)
52
+ }
package/usage/serve.js ADDED
@@ -0,0 +1,116 @@
1
+ import { aggregateUsage, usageCsv } from './aggregate.js'
2
+ import { resetUsage } from './ledger.js'
3
+
4
+ const ROOT = '/api/dsh-ta/usage'
5
+ const BODY_LIMIT = 4096
6
+
7
+ function sendJson(response, status, payload) {
8
+ response.writeHead(status, {
9
+ 'content-type': 'application/json; charset=utf-8',
10
+ 'cache-control': 'no-store',
11
+ })
12
+ response.end(JSON.stringify(payload))
13
+ }
14
+
15
+ /** 读取很小的 JSON 确认体;超过上限或格式错误都走 4xx。 */
16
+ function readJsonBody(request) {
17
+ return new Promise((resolve, reject) => {
18
+ const chunks = []
19
+ let size = 0
20
+ let settled = false
21
+ const fail = (status, message) => {
22
+ if (settled) return
23
+ settled = true
24
+ reject(Object.assign(new Error(message), { status }))
25
+ }
26
+ request.on('data', chunk => {
27
+ if (settled) return
28
+ size += chunk.length
29
+ if (size > BODY_LIMIT) {
30
+ fail(413, '确认信息过大')
31
+ return
32
+ }
33
+ chunks.push(chunk)
34
+ })
35
+ request.on('end', () => {
36
+ if (settled) return
37
+ settled = true
38
+ const text = Buffer.concat(chunks).toString('utf8')
39
+ if (!text.trim()) {
40
+ resolve({})
41
+ return
42
+ }
43
+ try {
44
+ resolve(JSON.parse(text))
45
+ } catch {
46
+ fail(400, '确认信息不是合法 JSON')
47
+ }
48
+ })
49
+ request.on('error', () => fail(400, '读取请求失败'))
50
+ })
51
+ }
52
+
53
+ export function mountUsageRoute(ctx, config) {
54
+ if (typeof ctx.inject !== 'function') return
55
+ ctx.inject(['webServer'], scope => {
56
+ const server = scope.webServer ?? scope.get?.('webServer')
57
+ if (typeof server?.register !== 'function') return
58
+ try {
59
+ scope.effect(() => server.register({
60
+ kind: 'prefix',
61
+ path: ROOT,
62
+ auth: 'required',
63
+ handler: (request, response) => {
64
+ const url = new URL(request.url ?? '/', 'http://localhost')
65
+ const suffix = url.pathname.slice(ROOT.length)
66
+ if (suffix === '/reset' || suffix === '/reset/') {
67
+ if (String(request.method ?? 'GET').toUpperCase() !== 'POST') {
68
+ response.setHeader?.('allow', 'POST')
69
+ sendJson(response, 405, {
70
+ ok: false,
71
+ error: { code: 'METHOD_NOT_ALLOWED', message: '清零只支持 POST' },
72
+ })
73
+ return
74
+ }
75
+ void readJsonBody(request).then(body => {
76
+ if (body?.confirm !== '清零') {
77
+ sendJson(response, 400, {
78
+ ok: false,
79
+ error: { code: 'RESET_CONFIRM_REQUIRED', message: '请输入“清零”确认' },
80
+ })
81
+ return
82
+ }
83
+ const result = resetUsage(config)
84
+ sendJson(response, 200, { ok: true, data: { cleared: true, ...result } })
85
+ }).catch(error => {
86
+ sendJson(response, error?.status === 413 ? 413 : 400, {
87
+ ok: false,
88
+ error: {
89
+ code: error?.status === 413 ? 'PAYLOAD_TOO_LARGE' : 'INVALID_JSON',
90
+ message: error instanceof Error ? error.message : '确认失败',
91
+ },
92
+ })
93
+ })
94
+ return
95
+ }
96
+ const report = aggregateUsage(config, {
97
+ from: url.searchParams.get('from') ?? undefined,
98
+ to: url.searchParams.get('to') ?? undefined,
99
+ })
100
+ if (suffix === '/export.csv') {
101
+ response.writeHead(200, { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': 'attachment; filename="dsh-ta-usage.csv"' })
102
+ response.end(usageCsv(report))
103
+ return
104
+ }
105
+ if (suffix !== '' && suffix !== '/' && suffix !== '/export.json') {
106
+ response.writeHead(404); response.end(); return
107
+ }
108
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
109
+ response.end(JSON.stringify(report))
110
+ },
111
+ }), 'dsh-ta usage route')
112
+ } catch (error) {
113
+ try { ctx.logger?.warn?.(error) } catch { /* logger optional */ }
114
+ }
115
+ })
116
+ }