dsh-ta 0.0.0-stage → 0.2.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,78 @@
1
+ /** Read-only aggregation over the local usage ledger. */
2
+ import { readdirSync } from 'node:fs'
3
+ import { resolve } from 'node:path'
4
+ import { readUsageRecords } from './ledger.js'
5
+ import { loadPricing } from './pricing.js'
6
+
7
+ function empty() {
8
+ return {
9
+ tokens: { uncachedInput: 0, cacheRead: 0, cacheWrite: 0, output: 0 },
10
+ costCny: null,
11
+ turns: 0,
12
+ pricedTurns: 0,
13
+ unpricedTurns: 0,
14
+ }
15
+ }
16
+
17
+ function add(target, record) {
18
+ target.turns += 1
19
+ for (const key of Object.keys(target.tokens)) target.tokens[key] += Number(record.tokens?.[key]) || 0
20
+ if (Number.isFinite(record.costCny)) {
21
+ target.pricedTurns += 1
22
+ target.costCny = (target.costCny ?? 0) + record.costCny
23
+ } else {
24
+ target.unpricedTurns += 1
25
+ }
26
+ }
27
+
28
+ export function aggregateUsage(config, { from, to } = {}) {
29
+ const directory = resolve(config.taHome, 'state/usage')
30
+ let files = []
31
+ try {
32
+ files = readdirSync(directory).filter(name => /^\d{4}-\d{2}-\d{2}\.jsonl$/.test(name)).sort()
33
+ } catch {
34
+ return { currency: loadPricing(config).currency ?? 'CNY', total: empty(), byDay: {}, byModel: {}, byCategory: {}, records: [] }
35
+ }
36
+ const records = []
37
+ const seen = new Set()
38
+ for (const file of files) {
39
+ const date = file.slice(0, 10)
40
+ if (from && date < from) continue
41
+ if (to && date > to) continue
42
+ for (const record of readUsageRecords(config, date)) {
43
+ if (!record || typeof record !== 'object' || typeof record.sessionId !== 'string') continue
44
+ const key = `${record.sessionId}:${record.turn}`
45
+ if (seen.has(key)) continue
46
+ seen.add(key)
47
+ records.push(record)
48
+ }
49
+ }
50
+ const total = empty()
51
+ const byDay = {}
52
+ const byModel = {}
53
+ const byCategory = {}
54
+ for (const record of records) {
55
+ add(total, record)
56
+ const day = String(record.ts).slice(0, 10)
57
+ for (const [bucket, key] of [[byDay, day], [byModel, record.model], [byCategory, record.category]]) {
58
+ bucket[key] ??= empty()
59
+ add(bucket[key], record)
60
+ }
61
+ }
62
+ const pricing = loadPricing(config)
63
+ const currency = records.find(record => typeof record.currency === 'string')?.currency ?? pricing.currency ?? 'CNY'
64
+ total.currency = currency
65
+ return { currency, total, byDay, byModel, byCategory, records }
66
+ }
67
+
68
+ export function usageCsv(aggregate) {
69
+ const rows = [['date', 'category', 'model', 'uncached_input', 'cache_read', 'cache_write', 'output', 'cost_cny']]
70
+ for (const record of aggregate.records) {
71
+ rows.push([
72
+ String(record.ts).slice(0, 10), record.category, record.model,
73
+ record.tokens.uncachedInput, record.tokens.cacheRead, record.tokens.cacheWrite,
74
+ record.tokens.output, record.costCny ?? '',
75
+ ])
76
+ }
77
+ return rows.map(row => row.map(value => `"${String(value).replaceAll('"', '""')}"`).join(',')).join('\n') + '\n'
78
+ }
@@ -0,0 +1,126 @@
1
+ /** Durable per-turn usage ledger for Ta sessions. */
2
+ import { appendFileSync, mkdirSync, readFileSync } 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
+ }
@@ -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,38 @@
1
+ import { aggregateUsage, usageCsv } from './aggregate.js'
2
+
3
+ const ROOT = '/api/dsh-ta/usage'
4
+
5
+ export function mountUsageRoute(ctx, config) {
6
+ if (typeof ctx.inject !== 'function') return
7
+ ctx.inject(['webServer'], scope => {
8
+ const server = scope.webServer ?? scope.get?.('webServer')
9
+ if (typeof server?.register !== 'function') return
10
+ try {
11
+ scope.effect(() => server.register({
12
+ kind: 'prefix',
13
+ path: ROOT,
14
+ auth: 'required',
15
+ handler: (request, response) => {
16
+ const url = new URL(request.url ?? '/', 'http://localhost')
17
+ const suffix = url.pathname.slice(ROOT.length)
18
+ const report = aggregateUsage(config, {
19
+ from: url.searchParams.get('from') ?? undefined,
20
+ to: url.searchParams.get('to') ?? undefined,
21
+ })
22
+ if (suffix === '/export.csv') {
23
+ response.writeHead(200, { 'content-type': 'text/csv; charset=utf-8', 'content-disposition': 'attachment; filename="dsh-ta-usage.csv"' })
24
+ response.end(usageCsv(report))
25
+ return
26
+ }
27
+ if (suffix !== '' && suffix !== '/' && suffix !== '/export.json') {
28
+ response.writeHead(404); response.end(); return
29
+ }
30
+ response.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
31
+ response.end(JSON.stringify(report))
32
+ },
33
+ }), 'dsh-ta usage route')
34
+ } catch (error) {
35
+ try { ctx.logger?.warn?.(error) } catch { /* logger optional */ }
36
+ }
37
+ })
38
+ }