dsh-ta 0.1.0 → 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.
- package/CHANGELOG.md +12 -0
- package/README.md +32 -0
- package/client.js +74 -1
- package/config.js +154 -0
- package/docs/PACKS.md +78 -0
- package/docs/USAGE.md +93 -0
- package/gates.js +18 -0
- package/identity.js +97 -0
- package/im/bindings.js +29 -0
- package/im/say.js +24 -0
- package/index.js +53 -1556
- package/jurisdiction.js +171 -0
- package/life.js +277 -0
- package/package.json +17 -2
- package/prompts.js +28 -0
- package/reme.js +23 -0
- package/runtime.js +209 -0
- package/stickers/load.js +107 -0
- package/stickers/select.js +39 -0
- package/stickers/serve.js +48 -0
- package/stickers/tool.js +150 -0
- package/storage.js +95 -0
- package/tools.js +540 -0
- package/usage/aggregate.js +78 -0
- package/usage/ledger.js +126 -0
- package/usage/pricing.js +52 -0
- package/usage/serve.js +38 -0
package/usage/ledger.js
ADDED
|
@@ -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
|
+
}
|
package/usage/pricing.js
ADDED
|
@@ -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
|
+
}
|