@natgurlain/dsh-token-usage 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.
- package/LICENSE +21 -0
- package/README.md +196 -2
- package/cordis.patch.yml +16 -0
- package/icon.svg +17 -0
- package/lib/cli.js +102 -0
- package/lib/client.js +502 -0
- package/lib/index.js +318 -0
- package/lib/openrouter-Ygu9q4uX.js +855 -0
- package/lib/query-BYb2mk4u.js +700 -0
- package/lib/types/cli.d.ts +17 -0
- package/lib/types/index.d.ts +39 -0
- package/lib/types/ledger.d.ts +28 -0
- package/lib/types/openrouter.d.ts +72 -0
- package/lib/types/query.d.ts +41 -0
- package/lib/types/report.d.ts +82 -0
- package/lib/types/scan.d.ts +77 -0
- package/lib/types/snapshot.d.ts +77 -0
- package/package.json +88 -4
- package/src/cli.ts +94 -0
- package/src/client.js +502 -0
- package/src/index.ts +195 -0
- package/src/ledger.ts +98 -0
- package/src/openrouter.ts +165 -0
- package/src/query.ts +97 -0
- package/src/report.ts +244 -0
- package/src/scan.ts +289 -0
- package/src/snapshot.ts +151 -0
package/src/index.ts
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@natgurlain/dsh-token-usage`: token usage for DeepSeek Harness.
|
|
3
|
+
*
|
|
4
|
+
* Counts the tokens of every model call in every session (conversations,
|
|
5
|
+
* subagents, failed attempts and compaction) from DSH's own session logs,
|
|
6
|
+
* and reports them by day, model, workspace or session. The user types
|
|
7
|
+
* `/usage`; the agent has a read-only `token_usage` tool; `dsh-token-usage`
|
|
8
|
+
* prints the same report in a terminal.
|
|
9
|
+
*
|
|
10
|
+
* @module @natgurlain/dsh-token-usage
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import type { Context } from '@deepseek-ai/cordis'
|
|
14
|
+
import z from '@deepseek-ai/schemastery'
|
|
15
|
+
import { defineTool, type ToolDefinition } from '@deepseek-ai/dsh-tools'
|
|
16
|
+
import { dshHomePath } from '@deepseek-ai/dsh-home-paths'
|
|
17
|
+
import { join } from 'node:path'
|
|
18
|
+
import { UsageLedger } from './ledger.ts'
|
|
19
|
+
import { answer, parseQuery, USAGE_HINT, type Query, type QueryContext } from './query.ts'
|
|
20
|
+
import { GROUPS, priceFor, type GroupBy, type Prices } from './report.ts'
|
|
21
|
+
import type { UsageRecord } from './scan.ts'
|
|
22
|
+
import { handleReportRequest, REPORT_API_PATH, type FetchRegistry, type LoadedUsage } from './snapshot.ts'
|
|
23
|
+
import { mergePrices, OpenRouterPrices } from './openrouter.ts'
|
|
24
|
+
|
|
25
|
+
export { UsageLedger } from './ledger.ts'
|
|
26
|
+
export { readSessionLog, recordsFromEvents, findSessionLogs, normalizeUsage, type UsageRecord, type UsageKind } from './scan.ts'
|
|
27
|
+
export { buildReport, renderReport, parsePeriod, dayOf, type Report, type Row, type Totals, type Price, type Prices, type GroupBy, type Period } from './report.ts'
|
|
28
|
+
export { answer, parseQuery, type Query } from './query.ts'
|
|
29
|
+
export { buildSnapshot, REPORT_API_PATH, type UsageSnapshot } from './snapshot.ts'
|
|
30
|
+
export { OpenRouterPrices, matchModel, parseModels, mergePrices } from './openrouter.ts'
|
|
31
|
+
|
|
32
|
+
export const name = 'token-usage'
|
|
33
|
+
export const inject = ['tools']
|
|
34
|
+
|
|
35
|
+
export interface Config {
|
|
36
|
+
prices?: Prices
|
|
37
|
+
timeZone?: string
|
|
38
|
+
root?: string
|
|
39
|
+
sessionsDir?: string
|
|
40
|
+
openRouter?: { enabled?: boolean; refreshHours?: number; models?: Record<string, string> }
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export type ResolvedConfig = Required<Pick<Config, 'prices'>> & Omit<Config, 'prices' | 'openRouter'> & {
|
|
44
|
+
openRouter: Required<NonNullable<Config['openRouter']>>
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const Price = z.object({
|
|
48
|
+
input: z.number().min(0).required().description('USD per million uncached input tokens.'),
|
|
49
|
+
output: z.number().min(0).required().description('USD per million output tokens.'),
|
|
50
|
+
cacheRead: z.number().min(0).description('USD per million cache-read tokens; defaults to the input price.'),
|
|
51
|
+
cacheWrite: z.number().min(0).description('USD per million cache-write tokens; defaults to the input price.'),
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
export const Config: z<Config, ResolvedConfig> = z.object({
|
|
55
|
+
prices: z.dict(Price).default({}).description('Prices by "provider/model" or model name, to show costs next to tokens.'),
|
|
56
|
+
timeZone: z.string().description('IANA time zone for days, like Europe/Warsaw; defaults to this machine\'s.'),
|
|
57
|
+
root: z.string().description('Where the usage index is kept; defaults to ~/.dsh/token-usage.'),
|
|
58
|
+
sessionsDir: z.string().description('Session logs to read; defaults to ~/.dsh/sessions.'),
|
|
59
|
+
openRouter: z.object({
|
|
60
|
+
enabled: z.boolean().default(true).description('Price models without a configured price at their OpenRouter list price (fetched from openrouter.ai once a day; nothing about you is sent).'),
|
|
61
|
+
refreshHours: z.number().min(1).default(24).description('Hours before the OpenRouter price list is fetched again.'),
|
|
62
|
+
models: z.dict(z.string()).default({}).description('Manual matches: "provider/model" (or model) → OpenRouter model id, like qwen/qwen4-35b-a3b.'),
|
|
63
|
+
}).default({ enabled: true, refreshHours: 24, models: {} }),
|
|
64
|
+
}) as unknown as z<Config, ResolvedConfig>
|
|
65
|
+
|
|
66
|
+
type Result = { kind: 'success' | 'error'; text: string }
|
|
67
|
+
|
|
68
|
+
interface CommandRegistryLike {
|
|
69
|
+
register(definition: {
|
|
70
|
+
name: string
|
|
71
|
+
description: string
|
|
72
|
+
input?: { hint: string }
|
|
73
|
+
handler: (invocation: { rawInput: string; agent?: AgentLike }) => Promise<Result>
|
|
74
|
+
}): () => void
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
interface AgentLike { id?: unknown; session?: { header?: { cwd?: string } } }
|
|
78
|
+
|
|
79
|
+
const TEXT_OUTPUT = {
|
|
80
|
+
schema: { type: 'object', additionalProperties: false, properties: { text: { type: 'string', required: true } } },
|
|
81
|
+
render: (_args: unknown, value: unknown) => [{ type: 'text' as const, text: (value as { text: string }).text }],
|
|
82
|
+
} as const
|
|
83
|
+
|
|
84
|
+
/** The caller's working directory: from the agent, else from its own logged calls. */
|
|
85
|
+
function cwdOf(agent: AgentLike | undefined, records: readonly UsageRecord[]): string | undefined {
|
|
86
|
+
const direct = agent?.session?.header?.cwd
|
|
87
|
+
if (typeof direct === 'string' && direct !== '') return direct
|
|
88
|
+
if (agent?.id === undefined) return undefined
|
|
89
|
+
const id = String(agent.id)
|
|
90
|
+
return records.findLast((record) => record.sessionId === id)?.cwd
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export function apply(ctx: Context, config: ResolvedConfig): void {
|
|
94
|
+
const ledger = new UsageLedger({
|
|
95
|
+
sessionsDir: config.sessionsDir ?? dshHomePath('sessions'),
|
|
96
|
+
indexFile: join(config.root ?? dshHomePath('token-usage'), 'index.json'),
|
|
97
|
+
})
|
|
98
|
+
|
|
99
|
+
const root = config.root ?? dshHomePath('token-usage')
|
|
100
|
+
const openRouter = config.openRouter.enabled
|
|
101
|
+
? new OpenRouterPrices({ cacheFile: join(root, 'openrouter-prices.json'), refreshHours: config.openRouter.refreshHours, models: config.openRouter.models })
|
|
102
|
+
: undefined
|
|
103
|
+
/** Records plus the prices that apply: configured ones, then OpenRouter's for the rest. */
|
|
104
|
+
const load = async (): Promise<LoadedUsage> => {
|
|
105
|
+
const records = await ledger.records()
|
|
106
|
+
if (openRouter === undefined) return { records, prices: config.prices }
|
|
107
|
+
await openRouter.ready()
|
|
108
|
+
const routes = new Map(records.map((record) => [`${record.provider}/${record.model}`, record]))
|
|
109
|
+
const unpriced = [...routes.values()].filter((record) => priceFor(config.prices, record.provider, record.model) === undefined)
|
|
110
|
+
const found = openRouter.pricesFor(unpriced)
|
|
111
|
+
const fetchedAt = openRouter.fetchedAt
|
|
112
|
+
return {
|
|
113
|
+
records,
|
|
114
|
+
prices: mergePrices(config.prices, found.prices),
|
|
115
|
+
priceSources: Object.fromEntries(Object.entries(found.sources).map(([key, source]) => [key, source.openRouterId])),
|
|
116
|
+
...(fetchedAt === undefined ? {} : { pricesAsOf: fetchedAt }),
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
const run = async (query: Query, agent: AgentLike | undefined): Promise<string> => {
|
|
120
|
+
const { records, prices, priceSources } = await load()
|
|
121
|
+
const cwd = cwdOf(agent, records)
|
|
122
|
+
const estimated = Object.keys(priceSources ?? {})
|
|
123
|
+
const context: QueryContext = {
|
|
124
|
+
prices,
|
|
125
|
+
...(estimated.length === 0 ? {} : { priceNote: `Costs for ${estimated.length} model${estimated.length === 1 ? '' : 's'} without a configured price use OpenRouter list prices (${estimated.map((key) => `${key} as ${priceSources?.[key] ?? '?'}`).join(', ')}).` }),
|
|
126
|
+
...(config.timeZone === undefined ? {} : { timeZone: config.timeZone }),
|
|
127
|
+
...(cwd === undefined ? {} : { cwd }),
|
|
128
|
+
}
|
|
129
|
+
return answer(records, query, context)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// The Usage page (lib/client.js) reads its data here, on dsh's authenticated `/api`
|
|
133
|
+
// channel. Hosts without a web connection (headless, TUI) simply never mount it.
|
|
134
|
+
const mountRoute = (connection: { fetch?: FetchRegistry } | undefined): (() => void) => {
|
|
135
|
+
const fetch = connection?.fetch
|
|
136
|
+
if (typeof fetch?.register !== 'function') return () => undefined
|
|
137
|
+
const dispose = fetch.register({
|
|
138
|
+
path: REPORT_API_PATH,
|
|
139
|
+
methods: ['POST'],
|
|
140
|
+
requestBody: 'buffered',
|
|
141
|
+
fetch: (request) => handleReportRequest(request, load, config.timeZone === undefined ? {} : { timeZone: config.timeZone }),
|
|
142
|
+
})
|
|
143
|
+
return () => { dispose() }
|
|
144
|
+
}
|
|
145
|
+
const withInject = ctx as unknown as { inject?: (deps: string[], callback: (ctx: Context) => void) => unknown }
|
|
146
|
+
if (typeof withInject.inject === 'function') {
|
|
147
|
+
withInject.inject(['connection'], (inner) => {
|
|
148
|
+
inner.effect(() => mountRoute(inner.get('connection' as never) as { fetch?: FetchRegistry } | undefined), 'token-usage: /api/token-usage.report')
|
|
149
|
+
})
|
|
150
|
+
} else {
|
|
151
|
+
ctx.effect(() => mountRoute(ctx.get('connection' as never) as { fetch?: FetchRegistry } | undefined), 'token-usage: /api/token-usage.report')
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const commands = ctx.get('commands' as never) as CommandRegistryLike | undefined
|
|
155
|
+
if (typeof commands?.register === 'function') {
|
|
156
|
+
ctx.effect(() => commands.register({
|
|
157
|
+
name: 'usage',
|
|
158
|
+
description: 'Tokens used across all sessions, by day, model, workspace or session',
|
|
159
|
+
input: { hint: USAGE_HINT },
|
|
160
|
+
handler: async (invocation) => {
|
|
161
|
+
const query = parseQuery(invocation.rawInput.trim().split(/\s+/).filter((word) => word !== ''))
|
|
162
|
+
if (typeof query === 'string') return { kind: 'error', text: `${query} Usage: /usage ${USAGE_HINT}` }
|
|
163
|
+
try {
|
|
164
|
+
return { kind: 'success', text: await run(query, invocation.agent) }
|
|
165
|
+
} catch (error) {
|
|
166
|
+
return { kind: 'error', text: error instanceof Error ? error.message : String(error) }
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
}), 'token-usage: /usage command')
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
const tool: ToolDefinition = defineTool({
|
|
173
|
+
name: 'token_usage',
|
|
174
|
+
description: 'Report how many tokens the user has used in DeepSeek Harness, across all sessions (including subagents, retries and compaction), from the session logs. Read-only. Use when the user asks about token usage, spend or which model or project used the most.',
|
|
175
|
+
parameters: {
|
|
176
|
+
period: { type: 'string', description: 'today, yesterday, week (last 7 days), month (last 30 days), all, a number of days like 14, a day 2026-12-01, a month 2026-12, or a range 2026-11-01..2026-11-30. Omit for an overview.' },
|
|
177
|
+
group_by: { type: 'string', enum: [...GROUPS], description: 'How to break the period down; default day.' },
|
|
178
|
+
this_workspace: { type: 'boolean', description: 'Only sessions in this conversation\'s working directory.' },
|
|
179
|
+
limit: { type: 'number', description: 'Most rows to show; default 30.' },
|
|
180
|
+
},
|
|
181
|
+
timeoutMs: 60_000,
|
|
182
|
+
output: TEXT_OUTPUT,
|
|
183
|
+
execute: async (args, exec) => {
|
|
184
|
+
const a = args as { period?: string; group_by?: GroupBy; this_workspace?: boolean; limit?: number }
|
|
185
|
+
const query: Query = {
|
|
186
|
+
...(a.period === undefined || a.period === '' ? {} : { period: a.period }),
|
|
187
|
+
...(a.group_by === undefined ? {} : { by: a.group_by }),
|
|
188
|
+
...(a.this_workspace === true ? { here: true } : {}),
|
|
189
|
+
...(typeof a.limit === 'number' && a.limit >= 1 ? { limit: Math.floor(a.limit) } : {}),
|
|
190
|
+
}
|
|
191
|
+
return { text: await run(query, (exec as { agent?: AgentLike }).agent) }
|
|
192
|
+
},
|
|
193
|
+
})
|
|
194
|
+
ctx.effect(() => ctx.tools.register(tool), 'token-usage: token_usage tool')
|
|
195
|
+
}
|
package/src/ledger.ts
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The usage ledger: every billed model call across all session logs, kept
|
|
3
|
+
* current incrementally. A log is read again only when its size or
|
|
4
|
+
* modification time changed; the per-log results are saved to an index file
|
|
5
|
+
* (`<root>/index.json`, 0600) so a restart does not re-read old logs.
|
|
6
|
+
*
|
|
7
|
+
* @module @natgurlain/dsh-token-usage/ledger
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
11
|
+
import { dirname, join } from 'node:path'
|
|
12
|
+
import { findSessionLogs, readSessionLog, type UsageRecord } from './scan.ts'
|
|
13
|
+
|
|
14
|
+
const INDEX_VERSION = 2
|
|
15
|
+
|
|
16
|
+
interface IndexEntry {
|
|
17
|
+
size: number
|
|
18
|
+
mtimeMs: number
|
|
19
|
+
records: UsageRecord[]
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
interface IndexFile {
|
|
23
|
+
version: number
|
|
24
|
+
logs: Record<string, IndexEntry>
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface LedgerOptions {
|
|
28
|
+
/** `<dsh home>/sessions`. */
|
|
29
|
+
sessionsDir: string
|
|
30
|
+
/** Where the index is kept; omit to keep it in memory only. */
|
|
31
|
+
indexFile?: string
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export class UsageLedger {
|
|
35
|
+
private logs = new Map<string, IndexEntry>()
|
|
36
|
+
private loaded = false
|
|
37
|
+
private pending: Promise<UsageRecord[]> | undefined
|
|
38
|
+
|
|
39
|
+
constructor(private readonly options: LedgerOptions) {}
|
|
40
|
+
|
|
41
|
+
/** All records, after reading any log that changed. Concurrent calls share one refresh. */
|
|
42
|
+
records(): Promise<UsageRecord[]> {
|
|
43
|
+
this.pending ??= this.refresh().finally(() => { this.pending = undefined })
|
|
44
|
+
return this.pending
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private async load(): Promise<void> {
|
|
48
|
+
if (this.loaded) return
|
|
49
|
+
this.loaded = true
|
|
50
|
+
if (this.options.indexFile === undefined) return
|
|
51
|
+
try {
|
|
52
|
+
const parsed = JSON.parse(await readFile(this.options.indexFile, 'utf8')) as IndexFile
|
|
53
|
+
if (parsed.version === INDEX_VERSION && parsed.logs !== null && typeof parsed.logs === 'object') {
|
|
54
|
+
this.logs = new Map(Object.entries(parsed.logs))
|
|
55
|
+
}
|
|
56
|
+
} catch {
|
|
57
|
+
// No index yet, or an unreadable one: rebuild it.
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
private async save(): Promise<void> {
|
|
62
|
+
const file = this.options.indexFile
|
|
63
|
+
if (file === undefined) return
|
|
64
|
+
await mkdir(dirname(file), { recursive: true, mode: 0o700 })
|
|
65
|
+
const temp = join(dirname(file), `.index.${process.pid}.${Date.now()}.tmp`)
|
|
66
|
+
const body: IndexFile = { version: INDEX_VERSION, logs: Object.fromEntries(this.logs) }
|
|
67
|
+
await writeFile(temp, JSON.stringify(body), { mode: 0o600 })
|
|
68
|
+
await rename(temp, file)
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
private async refresh(): Promise<UsageRecord[]> {
|
|
72
|
+
await this.load()
|
|
73
|
+
const files = await findSessionLogs(this.options.sessionsDir)
|
|
74
|
+
let changed = false
|
|
75
|
+
for (const file of files) {
|
|
76
|
+
const known = this.logs.get(file.path)
|
|
77
|
+
if (known !== undefined && known.size === file.size && known.mtimeMs === file.mtimeMs) continue
|
|
78
|
+
const records = await readSessionLog(file.path).catch(() => undefined)
|
|
79
|
+
if (records === undefined) continue
|
|
80
|
+
this.logs.set(file.path, { size: file.size, mtimeMs: file.mtimeMs, records })
|
|
81
|
+
changed = true
|
|
82
|
+
}
|
|
83
|
+
// A deleted session's tokens were still spent: keep its records.
|
|
84
|
+
if (changed) await this.save().catch(() => undefined)
|
|
85
|
+
|
|
86
|
+
const seen = new Set<string>()
|
|
87
|
+
const all: UsageRecord[] = []
|
|
88
|
+
for (const entry of this.logs.values()) {
|
|
89
|
+
for (const record of entry.records) {
|
|
90
|
+
if (seen.has(record.key)) continue
|
|
91
|
+
seen.add(record.key)
|
|
92
|
+
all.push(record)
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
all.sort((a, b) => a.time - b.time)
|
|
96
|
+
return all
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenRouter list prices, to estimate what a model would cost there: useful
|
|
3
|
+
* for models you run yourself (a local GPU server), which have no bill.
|
|
4
|
+
*
|
|
5
|
+
* The public `GET https://openrouter.ai/api/v1/models` list is fetched at most
|
|
6
|
+
* once per `refreshHours` and only when a report needs prices; nothing about
|
|
7
|
+
* the user or their sessions is sent. A failed fetch falls back to the last
|
|
8
|
+
* saved copy. A DSH route matches an OpenRouter model by its bare model name
|
|
9
|
+
* (`inkling-local/qwen4-35b-a3b` → `qwen/qwen4-35b-a3b`), case-insensitively,
|
|
10
|
+
* ignoring variants like `:batch`; `models` in the config maps routes by hand.
|
|
11
|
+
*
|
|
12
|
+
* @module @natgurlain/dsh-token-usage/openrouter
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
16
|
+
import { dirname, join } from 'node:path'
|
|
17
|
+
import type { Price, Prices } from './report.ts'
|
|
18
|
+
|
|
19
|
+
export const OPENROUTER_MODELS_URL = 'https://openrouter.ai/api/v1/models'
|
|
20
|
+
|
|
21
|
+
export interface OpenRouterModel {
|
|
22
|
+
id: string
|
|
23
|
+
pricing?: { prompt?: string; completion?: string; input_cache_read?: string; input_cache_write?: string }
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
interface PriceCache {
|
|
27
|
+
fetchedAt: number
|
|
28
|
+
models: Array<{ id: string; price: Price }>
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** USD per token as a string → USD per million tokens; undefined when unusable. */
|
|
32
|
+
function perMillion(value: string | undefined): number | undefined {
|
|
33
|
+
if (value === undefined) return undefined
|
|
34
|
+
const n = Number(value)
|
|
35
|
+
return Number.isFinite(n) && n >= 0 ? Math.round(n * 1e6 * 1e6) / 1e6 : undefined
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Turn OpenRouter's list into prices; models without prompt and completion prices (or priced below zero, like the router) are left out. */
|
|
39
|
+
export function parseModels(models: readonly OpenRouterModel[]): Array<{ id: string; price: Price }> {
|
|
40
|
+
const out: Array<{ id: string; price: Price }> = []
|
|
41
|
+
for (const model of models) {
|
|
42
|
+
if (typeof model?.id !== 'string') continue
|
|
43
|
+
const input = perMillion(model.pricing?.prompt)
|
|
44
|
+
const output = perMillion(model.pricing?.completion)
|
|
45
|
+
if (input === undefined || output === undefined) continue
|
|
46
|
+
const cacheRead = perMillion(model.pricing?.input_cache_read)
|
|
47
|
+
const cacheWrite = perMillion(model.pricing?.input_cache_write)
|
|
48
|
+
out.push({ id: model.id, price: { input, output, ...(cacheRead === undefined ? {} : { cacheRead }), ...(cacheWrite === undefined ? {} : { cacheWrite }) } })
|
|
49
|
+
}
|
|
50
|
+
return out
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
const bare = (id: string): string => (id.split(':')[0] ?? id).split('/').at(-1)?.toLowerCase() ?? ''
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The OpenRouter model a DSH route corresponds to: an explicit mapping, the
|
|
57
|
+
* same id (an `openrouter` provider), or the one base model (no `:variant`,
|
|
58
|
+
* no `~` alias) with the same bare name. Two candidates are ambiguous: none.
|
|
59
|
+
*/
|
|
60
|
+
export function matchModel(provider: string, model: string, ids: ReadonlySet<string>, mapping: Record<string, string> = {}): string | undefined {
|
|
61
|
+
const mapped = mapping[`${provider}/${model}`] ?? mapping[model]
|
|
62
|
+
if (mapped !== undefined) return ids.has(mapped) ? mapped : undefined
|
|
63
|
+
const lower = model.toLowerCase()
|
|
64
|
+
if (ids.has(lower)) return lower
|
|
65
|
+
if (ids.has(model)) return model
|
|
66
|
+
const name = bare(model)
|
|
67
|
+
if (name === '') return undefined
|
|
68
|
+
const candidates = [...ids].filter((id) => !id.includes(':') && !id.startsWith('~') && bare(id) === name)
|
|
69
|
+
return candidates.length === 1 ? candidates[0] : undefined
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export interface OpenRouterOptions {
|
|
73
|
+
/** Where the last list is saved. */
|
|
74
|
+
cacheFile: string
|
|
75
|
+
refreshHours?: number
|
|
76
|
+
/** Manual matches: `provider/model` (or model) → OpenRouter id. */
|
|
77
|
+
models?: Record<string, string>
|
|
78
|
+
fetch?: typeof fetch
|
|
79
|
+
now?: () => number
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface PriceSource {
|
|
83
|
+
/** The OpenRouter model whose list price was used. */
|
|
84
|
+
openRouterId: string
|
|
85
|
+
price: Price
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export class OpenRouterPrices {
|
|
89
|
+
private cache: PriceCache | undefined
|
|
90
|
+
private loading: Promise<void> | undefined
|
|
91
|
+
|
|
92
|
+
constructor(private readonly options: OpenRouterOptions) {}
|
|
93
|
+
|
|
94
|
+
/** When the list in use was fetched; undefined before any list is known. */
|
|
95
|
+
get fetchedAt(): number | undefined {
|
|
96
|
+
return this.cache?.fetchedAt
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
private async read(): Promise<PriceCache | undefined> {
|
|
100
|
+
try {
|
|
101
|
+
const parsed = JSON.parse(await readFile(this.options.cacheFile, 'utf8')) as PriceCache
|
|
102
|
+
return typeof parsed.fetchedAt === 'number' && Array.isArray(parsed.models) ? parsed : undefined
|
|
103
|
+
} catch {
|
|
104
|
+
return undefined
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
private async refresh(): Promise<void> {
|
|
109
|
+
const now = this.options.now?.() ?? Date.now()
|
|
110
|
+
const maxAge = (this.options.refreshHours ?? 24) * 3_600_000
|
|
111
|
+
this.cache ??= await this.read()
|
|
112
|
+
if (this.cache !== undefined && now - this.cache.fetchedAt < maxAge) return
|
|
113
|
+
try {
|
|
114
|
+
const response = await (this.options.fetch ?? fetch)(OPENROUTER_MODELS_URL, { signal: AbortSignal.timeout(15_000), headers: { accept: 'application/json' } })
|
|
115
|
+
if (!response.ok) throw new Error(`HTTP ${response.status}`)
|
|
116
|
+
const body = await response.json() as { data?: OpenRouterModel[] }
|
|
117
|
+
const models = parseModels(Array.isArray(body.data) ? body.data : [])
|
|
118
|
+
if (models.length === 0) throw new Error('empty model list')
|
|
119
|
+
this.cache = { fetchedAt: now, models }
|
|
120
|
+
await mkdir(dirname(this.options.cacheFile), { recursive: true, mode: 0o700 })
|
|
121
|
+
const temp = join(dirname(this.options.cacheFile), `.openrouter.${process.pid}.${now}.tmp`)
|
|
122
|
+
await writeFile(temp, JSON.stringify(this.cache), { mode: 0o600 })
|
|
123
|
+
await rename(temp, this.options.cacheFile)
|
|
124
|
+
} catch {
|
|
125
|
+
// Offline or refused: keep the saved list (even a stale one), or price nothing.
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
/** Make sure a list is loaded (fetching it when stale); concurrent calls share one fetch. */
|
|
130
|
+
async ready(): Promise<void> {
|
|
131
|
+
this.loading ??= this.refresh().finally(() => { this.loading = undefined })
|
|
132
|
+
await this.loading
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** OpenRouter prices for the given routes, keyed `provider/model`. Call {@link ready} first. */
|
|
136
|
+
pricesFor(routes: Iterable<{ provider: string; model: string }>): { prices: Prices; sources: Record<string, PriceSource> } {
|
|
137
|
+
const prices: Prices = {}
|
|
138
|
+
const sources: Record<string, PriceSource> = {}
|
|
139
|
+
if (this.cache === undefined) return { prices, sources }
|
|
140
|
+
const byId = new Map(this.cache.models.map((entry) => [entry.id, entry.price]))
|
|
141
|
+
const ids = new Set(byId.keys())
|
|
142
|
+
for (const { provider, model } of routes) {
|
|
143
|
+
const key = `${provider}/${model}`
|
|
144
|
+
if (key in prices) continue
|
|
145
|
+
const id = matchModel(provider, model, ids, this.options.models)
|
|
146
|
+
const price = id === undefined ? undefined : byId.get(id)
|
|
147
|
+
if (id === undefined || price === undefined) continue
|
|
148
|
+
prices[key] = price
|
|
149
|
+
sources[key] = { openRouterId: id, price }
|
|
150
|
+
}
|
|
151
|
+
return { prices, sources }
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** Configured prices win; OpenRouter fills in the routes they leave unpriced. */
|
|
156
|
+
export function mergePrices(configured: Prices, fromOpenRouter: Prices): Prices {
|
|
157
|
+
const merged: Prices = { ...fromOpenRouter }
|
|
158
|
+
for (const [key, price] of Object.entries(configured)) merged[key] = price
|
|
159
|
+
// A bare-model configured price also outranks OpenRouter's provider/model entry.
|
|
160
|
+
for (const key of Object.keys(fromOpenRouter)) {
|
|
161
|
+
const model = key.slice(key.indexOf('/') + 1)
|
|
162
|
+
if (configured[model] !== undefined) delete merged[key]
|
|
163
|
+
}
|
|
164
|
+
return merged
|
|
165
|
+
}
|
package/src/query.ts
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One query language for the `/usage` command, the `token_usage` tool and
|
|
3
|
+
* the CLI: a period word, a grouping, and `here` for this workspace only.
|
|
4
|
+
*
|
|
5
|
+
* ```
|
|
6
|
+
* /usage overview, then the last 14 days by day
|
|
7
|
+
* /usage today | week | month one period, by day
|
|
8
|
+
* /usage 30 by model the last 30 days, by model
|
|
9
|
+
* /usage 2026-11 workspaces November, by workspace
|
|
10
|
+
* /usage week sessions here this workspace's sessions this week
|
|
11
|
+
* ```
|
|
12
|
+
*
|
|
13
|
+
* @module @natgurlain/dsh-token-usage/query
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
import { buildReport, compact, dayOf, GROUPS, parsePeriod, renderReport, usd, type GroupBy, type Prices } from './report.ts'
|
|
17
|
+
import type { UsageRecord } from './scan.ts'
|
|
18
|
+
|
|
19
|
+
export interface Query {
|
|
20
|
+
/** A period word for {@link parsePeriod}; undefined for the overview. */
|
|
21
|
+
period?: string
|
|
22
|
+
by?: GroupBy
|
|
23
|
+
/** Only the caller's workspace. */
|
|
24
|
+
here?: boolean
|
|
25
|
+
noSubagents?: boolean
|
|
26
|
+
limit?: number
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
const ALIASES: Record<string, GroupBy> = {
|
|
30
|
+
day: 'day', days: 'day', daily: 'day',
|
|
31
|
+
model: 'model', models: 'model',
|
|
32
|
+
workspace: 'workspace', workspaces: 'workspace', folder: 'workspace', folders: 'workspace', project: 'workspace', projects: 'workspace',
|
|
33
|
+
session: 'session', sessions: 'session', conversation: 'session', conversations: 'session',
|
|
34
|
+
kind: 'kind', kinds: 'kind', type: 'kind',
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Parse command words; returns an error message for words it does not know. */
|
|
38
|
+
export function parseQuery(words: readonly string[]): Query | string {
|
|
39
|
+
const query: Query = {}
|
|
40
|
+
for (const raw of words) {
|
|
41
|
+
const word = raw.toLowerCase()
|
|
42
|
+
if (word === 'by' || word === 'per') continue
|
|
43
|
+
if (word === 'here') query.here = true
|
|
44
|
+
else if (word === 'nosub' || word === 'no-subagents') query.noSubagents = true
|
|
45
|
+
else if (ALIASES[word] !== undefined) query.by = ALIASES[word]
|
|
46
|
+
else if (query.period === undefined) query.period = word
|
|
47
|
+
else return `Unknown word "${raw}".`
|
|
48
|
+
}
|
|
49
|
+
return query
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export const USAGE_HINT = '[today | yesterday | week | month | all | <days> | <YYYY-MM[-DD]> | <from>..<to>] [by day | model | workspace | session | kind] [here]'
|
|
53
|
+
|
|
54
|
+
export interface QueryContext {
|
|
55
|
+
prices?: Prices
|
|
56
|
+
timeZone?: string
|
|
57
|
+
/** The caller's working directory, for `here`. */
|
|
58
|
+
cwd?: string
|
|
59
|
+
/** A line saying where estimated prices came from. */
|
|
60
|
+
priceNote?: string
|
|
61
|
+
now?: number
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Answer a query as plain text. */
|
|
65
|
+
export function answer(records: readonly UsageRecord[], query: Query, context: QueryContext = {}): string {
|
|
66
|
+
const today = dayOf(context.now ?? Date.now(), context.timeZone)
|
|
67
|
+
if (query.here === true && context.cwd === undefined) return 'This conversation has no working directory, so "here" has nothing to filter by.'
|
|
68
|
+
const scope = {
|
|
69
|
+
...(context.prices === undefined ? {} : { prices: context.prices }),
|
|
70
|
+
...(context.timeZone === undefined ? {} : { timeZone: context.timeZone }),
|
|
71
|
+
...(query.here === true && context.cwd !== undefined ? { cwd: context.cwd } : {}),
|
|
72
|
+
...(query.noSubagents === true ? { excludeSubagents: true } : {}),
|
|
73
|
+
}
|
|
74
|
+
const where = scope.cwd === undefined ? '' : ` in ${scope.cwd}`
|
|
75
|
+
|
|
76
|
+
if (query.period === undefined && query.by === undefined) {
|
|
77
|
+
const sum = (word: string): string => {
|
|
78
|
+
const period = parsePeriod(word, today)
|
|
79
|
+
const report = buildReport(records, { ...scope, period: period ?? { label: word }, by: 'kind' })
|
|
80
|
+
return `${compact(report.totals.total)}${report.priced ? ` (${usd(report.totals.cost ?? 0)})` : ''}`
|
|
81
|
+
}
|
|
82
|
+
const overview = `Today ${sum('today')} · 7 days ${sum('week')} · 30 days ${sum('month')} · all time ${sum('all')} tokens${where}`
|
|
83
|
+
const recent = buildReport(records, { ...scope, period: parsePeriod('14', today) ?? { label: 'the last 14 days' }, by: 'day' })
|
|
84
|
+
return withNote(`${overview}\n\n${renderReport(recent, query.limit === undefined ? {} : { limit: query.limit })}`, recent.priced, context.priceNote)
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const period = parsePeriod(query.period ?? (query.by === undefined || query.by === 'day' ? '30' : 'all'), today)
|
|
88
|
+
if (period === undefined) return `Unknown period "${query.period ?? ''}". Usage: /usage ${USAGE_HINT}`
|
|
89
|
+
const report = buildReport(records, { ...scope, period: { ...period, label: `${period.label}${where}` }, by: query.by ?? 'day' })
|
|
90
|
+
return withNote(renderReport(report, query.limit === undefined ? {} : { limit: query.limit }), report.priced, context.priceNote)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
function withNote(text: string, priced: boolean, note: string | undefined): string {
|
|
94
|
+
return priced && note !== undefined ? `${text}\n${note}` : text
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export { GROUPS }
|