@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.
@@ -0,0 +1,17 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `dsh-token-usage`: the `/usage` report in a terminal, without DSH running.
4
+ *
5
+ * ```
6
+ * dsh-token-usage overview and the last 14 days
7
+ * dsh-token-usage month by model the last 30 days, by model
8
+ * dsh-token-usage 2026-11 --json November's records as JSON
9
+ * ```
10
+ *
11
+ * Reads `$DSH_HOME/sessions` (default `~/.dsh/sessions`); `--home <dir>`
12
+ * points elsewhere. The CLI keeps no index; it reads every log each time.
13
+ *
14
+ * @module @natgurlain/dsh-token-usage/cli
15
+ */
16
+ export {};
17
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1,39 @@
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
+ import type { Context } from '@deepseek-ai/cordis';
13
+ import z from '@deepseek-ai/schemastery';
14
+ import { type Prices } from './report.ts';
15
+ export { UsageLedger } from './ledger.ts';
16
+ export { readSessionLog, recordsFromEvents, findSessionLogs, normalizeUsage, type UsageRecord, type UsageKind } from './scan.ts';
17
+ export { buildReport, renderReport, parsePeriod, dayOf, type Report, type Row, type Totals, type Price, type Prices, type GroupBy, type Period } from './report.ts';
18
+ export { answer, parseQuery, type Query } from './query.ts';
19
+ export { buildSnapshot, REPORT_API_PATH, type UsageSnapshot } from './snapshot.ts';
20
+ export { OpenRouterPrices, matchModel, parseModels, mergePrices } from './openrouter.ts';
21
+ export declare const name = "token-usage";
22
+ export declare const inject: string[];
23
+ export interface Config {
24
+ prices?: Prices;
25
+ timeZone?: string;
26
+ root?: string;
27
+ sessionsDir?: string;
28
+ openRouter?: {
29
+ enabled?: boolean;
30
+ refreshHours?: number;
31
+ models?: Record<string, string>;
32
+ };
33
+ }
34
+ export type ResolvedConfig = Required<Pick<Config, 'prices'>> & Omit<Config, 'prices' | 'openRouter'> & {
35
+ openRouter: Required<NonNullable<Config['openRouter']>>;
36
+ };
37
+ export declare const Config: z<Config, ResolvedConfig>;
38
+ export declare function apply(ctx: Context, config: ResolvedConfig): void;
39
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,28 @@
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
+ import { type UsageRecord } from './scan.ts';
10
+ export interface LedgerOptions {
11
+ /** `<dsh home>/sessions`. */
12
+ sessionsDir: string;
13
+ /** Where the index is kept; omit to keep it in memory only. */
14
+ indexFile?: string;
15
+ }
16
+ export declare class UsageLedger {
17
+ private readonly options;
18
+ private logs;
19
+ private loaded;
20
+ private pending;
21
+ constructor(options: LedgerOptions);
22
+ /** All records, after reading any log that changed. Concurrent calls share one refresh. */
23
+ records(): Promise<UsageRecord[]>;
24
+ private load;
25
+ private save;
26
+ private refresh;
27
+ }
28
+ //# sourceMappingURL=ledger.d.ts.map
@@ -0,0 +1,72 @@
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
+ import type { Price, Prices } from './report.ts';
15
+ export declare const OPENROUTER_MODELS_URL = "https://openrouter.ai/api/v1/models";
16
+ export interface OpenRouterModel {
17
+ id: string;
18
+ pricing?: {
19
+ prompt?: string;
20
+ completion?: string;
21
+ input_cache_read?: string;
22
+ input_cache_write?: string;
23
+ };
24
+ }
25
+ /** Turn OpenRouter's list into prices; models without prompt and completion prices (or priced below zero, like the router) are left out. */
26
+ export declare function parseModels(models: readonly OpenRouterModel[]): Array<{
27
+ id: string;
28
+ price: Price;
29
+ }>;
30
+ /**
31
+ * The OpenRouter model a DSH route corresponds to: an explicit mapping, the
32
+ * same id (an `openrouter` provider), or the one base model (no `:variant`,
33
+ * no `~` alias) with the same bare name. Two candidates are ambiguous: none.
34
+ */
35
+ export declare function matchModel(provider: string, model: string, ids: ReadonlySet<string>, mapping?: Record<string, string>): string | undefined;
36
+ export interface OpenRouterOptions {
37
+ /** Where the last list is saved. */
38
+ cacheFile: string;
39
+ refreshHours?: number;
40
+ /** Manual matches: `provider/model` (or model) → OpenRouter id. */
41
+ models?: Record<string, string>;
42
+ fetch?: typeof fetch;
43
+ now?: () => number;
44
+ }
45
+ export interface PriceSource {
46
+ /** The OpenRouter model whose list price was used. */
47
+ openRouterId: string;
48
+ price: Price;
49
+ }
50
+ export declare class OpenRouterPrices {
51
+ private readonly options;
52
+ private cache;
53
+ private loading;
54
+ constructor(options: OpenRouterOptions);
55
+ /** When the list in use was fetched; undefined before any list is known. */
56
+ get fetchedAt(): number | undefined;
57
+ private read;
58
+ private refresh;
59
+ /** Make sure a list is loaded (fetching it when stale); concurrent calls share one fetch. */
60
+ ready(): Promise<void>;
61
+ /** OpenRouter prices for the given routes, keyed `provider/model`. Call {@link ready} first. */
62
+ pricesFor(routes: Iterable<{
63
+ provider: string;
64
+ model: string;
65
+ }>): {
66
+ prices: Prices;
67
+ sources: Record<string, PriceSource>;
68
+ };
69
+ }
70
+ /** Configured prices win; OpenRouter fills in the routes they leave unpriced. */
71
+ export declare function mergePrices(configured: Prices, fromOpenRouter: Prices): Prices;
72
+ //# sourceMappingURL=openrouter.d.ts.map
@@ -0,0 +1,41 @@
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
+ import { GROUPS, type GroupBy, type Prices } from './report.ts';
16
+ import type { UsageRecord } from './scan.ts';
17
+ export interface Query {
18
+ /** A period word for {@link parsePeriod}; undefined for the overview. */
19
+ period?: string;
20
+ by?: GroupBy;
21
+ /** Only the caller's workspace. */
22
+ here?: boolean;
23
+ noSubagents?: boolean;
24
+ limit?: number;
25
+ }
26
+ /** Parse command words; returns an error message for words it does not know. */
27
+ export declare function parseQuery(words: readonly string[]): Query | string;
28
+ export declare const USAGE_HINT = "[today | yesterday | week | month | all | <days> | <YYYY-MM[-DD]> | <from>..<to>] [by day | model | workspace | session | kind] [here]";
29
+ export interface QueryContext {
30
+ prices?: Prices;
31
+ timeZone?: string;
32
+ /** The caller's working directory, for `here`. */
33
+ cwd?: string;
34
+ /** A line saying where estimated prices came from. */
35
+ priceNote?: string;
36
+ now?: number;
37
+ }
38
+ /** Answer a query as plain text. */
39
+ export declare function answer(records: readonly UsageRecord[], query: Query, context?: QueryContext): string;
40
+ export { GROUPS };
41
+ //# sourceMappingURL=query.d.ts.map
@@ -0,0 +1,82 @@
1
+ /**
2
+ * Summing usage records into reports: periods, groupings, optional prices,
3
+ * and a plain-text rendering for the `/usage` command, the tool and the CLI.
4
+ *
5
+ * @module @natgurlain/dsh-token-usage/report
6
+ */
7
+ import type { UsageRecord } from './scan.ts';
8
+ export type GroupBy = 'day' | 'model' | 'workspace' | 'session' | 'kind';
9
+ export declare const GROUPS: readonly GroupBy[];
10
+ /** USD per million tokens. Cache prices default to the input price. */
11
+ export interface Price {
12
+ input: number;
13
+ output: number;
14
+ cacheRead?: number;
15
+ cacheWrite?: number;
16
+ }
17
+ export type Prices = Record<string, Price>;
18
+ export interface Totals {
19
+ calls: number;
20
+ input: number;
21
+ output: number;
22
+ cacheRead: number;
23
+ cacheWrite: number;
24
+ reasoning: number;
25
+ total: number;
26
+ /** USD; undefined when no call in the group has a price. */
27
+ cost?: number;
28
+ /** Calls without a price, when some have one. */
29
+ unpriced: number;
30
+ }
31
+ export interface Row extends Totals {
32
+ key: string;
33
+ label: string;
34
+ }
35
+ /** A half-open range of local days, `from` inclusive, `to` exclusive (YYYY-MM-DD). */
36
+ export interface Period {
37
+ label: string;
38
+ from?: string;
39
+ to?: string;
40
+ }
41
+ export declare function emptyTotals(): Totals;
42
+ /** The price of a route: `provider/model` first, then the bare model name. */
43
+ export declare function priceFor(prices: Prices, provider: string, model: string): Price | undefined;
44
+ export declare function costOf(record: Pick<UsageRecord, 'input' | 'output' | 'cacheRead' | 'cacheWrite'>, price: Price): number;
45
+ /** The local calendar day of a time, as YYYY-MM-DD. */
46
+ export declare function dayOf(time: number, timeZone?: string): string;
47
+ /** Add days to a YYYY-MM-DD date (calendar arithmetic, no time zone involved). */
48
+ export declare function shiftDay(day: string, days: number): string;
49
+ /**
50
+ * Parse a period: `today`, `yesterday`, `week` (last 7 days), `month` (last
51
+ * 30 days), `all`, a number of days (`14`, `14d`), a day (`2026-12-01`), a
52
+ * month (`2026-12`) or a range (`2026-11-01..2026-11-30`, inclusive).
53
+ */
54
+ export declare function parsePeriod(input: string | undefined, today: string): Period | undefined;
55
+ export interface ReportOptions {
56
+ period: Period;
57
+ by: GroupBy;
58
+ prices?: Prices;
59
+ timeZone?: string;
60
+ /** Only sessions in this working directory. */
61
+ cwd?: string;
62
+ /** Leave out subagent sessions. */
63
+ excludeSubagents?: boolean;
64
+ }
65
+ export interface Report {
66
+ period: Period;
67
+ by: GroupBy;
68
+ rows: Row[];
69
+ totals: Totals;
70
+ priced: boolean;
71
+ /** Distinct sessions in the period. */
72
+ sessions: number;
73
+ }
74
+ export declare function buildReport(records: readonly UsageRecord[], options: ReportOptions): Report;
75
+ /** 1234 → 1.2k, 1234567 → 1.23M. */
76
+ export declare function compact(n: number): string;
77
+ export declare function usd(n: number): string;
78
+ /** Render a report as aligned plain text. */
79
+ export declare function renderReport(report: Report, options?: {
80
+ limit?: number;
81
+ }): string;
82
+ //# sourceMappingURL=report.d.ts.map
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Reading token usage out of DSH's session logs.
3
+ *
4
+ * Every model call DSH makes for a conversation is logged with the usage the
5
+ * provider reported:
6
+ *
7
+ * - `assistant/message`: a completed step, `data.usage`, with the route in
8
+ * `data.message.source`.
9
+ * - `assistant/attempt`: a failed or retried call, its usage in the last
10
+ * `usage` chunk of `data.stream`. It has no route of its own, so it takes
11
+ * the route of the session's latest `request/header`.
12
+ * - `compaction/summary`: the summary call that compacts a long conversation,
13
+ * `data.usage` with `data.provider` and `data.model`.
14
+ *
15
+ * A seeded session (a fork or a resume) starts with a copy of another log
16
+ * up to `session/end-seed`; that copy is skipped so nothing counts twice.
17
+ * A session still being written (a trailing partial frame or line) yields
18
+ * what was complete.
19
+ *
20
+ * @module @natgurlain/dsh-token-usage/scan
21
+ */
22
+ export type UsageKind = 'message' | 'attempt' | 'compaction';
23
+ /** One billed model call. */
24
+ export interface UsageRecord {
25
+ /** Unique across logs: message id, or session id + seq. */
26
+ key: string;
27
+ /** Epoch milliseconds. */
28
+ time: number;
29
+ sessionId: string;
30
+ /** The session's working directory, when it has one. */
31
+ cwd?: string;
32
+ /** True for subagent sessions. */
33
+ subagent: boolean;
34
+ /** The session's latest title, when it has one. */
35
+ title?: string;
36
+ kind: UsageKind;
37
+ provider: string;
38
+ model: string;
39
+ /** Prompt tokens that were not read from or written to a cache. */
40
+ input: number;
41
+ output: number;
42
+ cacheRead: number;
43
+ cacheWrite: number;
44
+ /** Subset of output, when reported. */
45
+ reasoning: number;
46
+ /** Prompt plus output, as the provider reported it (or the sum of the buckets). */
47
+ total: number;
48
+ }
49
+ interface Event {
50
+ type?: unknown;
51
+ seq?: unknown;
52
+ time?: unknown;
53
+ data?: Record<string, unknown>;
54
+ [key: string]: unknown;
55
+ }
56
+ /** Normalize a provider usage object; undefined when it reports nothing. */
57
+ export declare function normalizeUsage(raw: unknown): Pick<UsageRecord, 'input' | 'output' | 'cacheRead' | 'cacheWrite' | 'reasoning' | 'total'> | undefined;
58
+ /** Fold one session's events (in log order) into usage records. */
59
+ export declare function recordsFromEvents(events: Iterable<Event>): UsageRecord[];
60
+ /**
61
+ * Split a buffer of concatenated zstd frames. DSH appends one frame per
62
+ * write, and Node's zstd decoder stops after the first frame of its input,
63
+ * so each frame is located here and decoded on its own. Skippable frames are
64
+ * skipped; a truncated last frame (a log still being written) ends the list.
65
+ */
66
+ export declare function zstdFrames(buffer: Buffer): Generator<Buffer>;
67
+ /** Read one session log (`session.v4.jsonl` or `.jsonl.zstd`). */
68
+ export declare function readSessionLog(file: string): Promise<UsageRecord[]>;
69
+ export interface LogFile {
70
+ path: string;
71
+ size: number;
72
+ mtimeMs: number;
73
+ }
74
+ /** Every session log under `<dsh home>/sessions/<workspace>/<session>/`. */
75
+ export declare function findSessionLogs(sessionsDir: string): Promise<LogFile[]>;
76
+ export {};
77
+ //# sourceMappingURL=scan.d.ts.map
@@ -0,0 +1,77 @@
1
+ /**
2
+ * The Usage page's data: one JSON snapshot per period, served on dsh's
3
+ * authenticated `/api` channel as `POST /api/token-usage.report`.
4
+ *
5
+ * The page asks for a period (`today`, `week`, `month`, `90`, `all`, or any
6
+ * word `/usage` takes) and gets the totals, a zero-filled daily series for
7
+ * the chart, the overview sums, and the top models, workspaces and sessions.
8
+ *
9
+ * @module @natgurlain/dsh-token-usage/snapshot
10
+ */
11
+ import { type Period, type Prices, type Row, type Totals } from './report.ts';
12
+ import type { UsageRecord } from './scan.ts';
13
+ export declare const REPORT_API_PATH = "/api/token-usage.report";
14
+ export interface DayPoint extends Totals {
15
+ day: string;
16
+ /** False for the context days a short period's chart shows before it. */
17
+ inPeriod: boolean;
18
+ }
19
+ export interface UsageSnapshot {
20
+ ok: true;
21
+ period: Period;
22
+ today: string;
23
+ priced: boolean;
24
+ totals: Totals;
25
+ sessions: number;
26
+ overview: {
27
+ today: number;
28
+ week: number;
29
+ month: number;
30
+ all: number;
31
+ };
32
+ days: DayPoint[];
33
+ models: Row[];
34
+ workspaces: Row[];
35
+ sessionRows: Row[];
36
+ /** When the logs were last read (epoch ms). */
37
+ generatedAt: number;
38
+ /** `provider/model` → the OpenRouter model whose list price was used. */
39
+ priceSources: Record<string, string>;
40
+ /** When the OpenRouter list was fetched, when it was used. */
41
+ pricesAsOf?: number;
42
+ }
43
+ /** What a report is built from. */
44
+ export interface LoadedUsage {
45
+ records: readonly UsageRecord[];
46
+ prices: Prices;
47
+ priceSources?: Record<string, string>;
48
+ pricesAsOf?: number;
49
+ }
50
+ export interface SnapshotOptions {
51
+ prices?: Prices;
52
+ timeZone?: string;
53
+ now?: number;
54
+ /** Most rows per breakdown table. */
55
+ limit?: number;
56
+ }
57
+ /** The longest daily series the chart draws; older days are left out of the chart only. */
58
+ export declare const MAX_CHART_DAYS = 180;
59
+ /** The shortest: a short period is drawn with the days before it for context. */
60
+ export declare const MIN_CHART_DAYS = 7;
61
+ export declare function buildSnapshot(records: readonly UsageRecord[], periodWord: string, options?: SnapshotOptions): UsageSnapshot | undefined;
62
+ /** The slice of `ctx.connection.fetch` used here (the same one dsh-browser-agent uses). */
63
+ export interface FetchRegistry {
64
+ register(route: {
65
+ readonly path: string;
66
+ readonly methods: readonly ('GET' | 'HEAD' | 'POST')[];
67
+ readonly requestBody: 'buffered' | 'streaming';
68
+ readonly fetch: (request: Request) => Promise<Response>;
69
+ }): () => unknown;
70
+ }
71
+ /**
72
+ * Handle `POST /api/token-usage.report` with `{ "period": "week" }`. dsh has
73
+ * already authenticated the caller as the host's owner; a JSON content type
74
+ * also keeps a cross-site page from sending it without a preflight.
75
+ */
76
+ export declare function handleReportRequest(request: Request, load: () => Promise<LoadedUsage>, options: Omit<SnapshotOptions, 'now' | 'prices'>): Promise<Response>;
77
+ //# sourceMappingURL=snapshot.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,90 @@
1
1
  {
2
2
  "name": "@natgurlain/dsh-token-usage",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "description": "Token usage for DeepSeek Harness: counts the tokens of every session, by day, model, workspace and session, from DSH's own session logs",
4
+ "version": "0.2.0",
5
+ "author": "Nat Gurlain",
6
+ "license": "MIT",
7
+ "homepage": "https://github.com/natgurlain/dsh-token-usage#readme",
8
+ "repository": {
9
+ "type": "git",
10
+ "url": "git+https://github.com/natgurlain/dsh-token-usage.git"
11
+ },
12
+ "bugs": {
13
+ "url": "https://github.com/natgurlain/dsh-token-usage/issues"
14
+ },
15
+ "type": "module",
16
+ "keywords": [
17
+ "dsh-plugin",
18
+ "deepseek-harness",
19
+ "dsh",
20
+ "tokens",
21
+ "usage",
22
+ "cost",
23
+ "ai-agent"
24
+ ],
25
+ "packageManager": "pnpm@11.7.0",
26
+ "engines": {
27
+ "node": ">=24.9.0",
28
+ "dsh": "^0.2.2-rc.1"
29
+ },
30
+ "dsh": {
31
+ "manifestVersion": 1,
32
+ "bundle": {
33
+ "patch": "./cordis.patch.yml"
34
+ },
35
+ "client": {
36
+ "inject": [
37
+ "@deepseek-ai/dsh-client-locale",
38
+ "@deepseek-ai/dsh-client-ui-slots",
39
+ "@deepseek-ai/dsh-client-ui-settings"
40
+ ],
41
+ "platform": "web"
42
+ }
43
+ },
44
+ "bin": {
45
+ "dsh-token-usage": "lib/cli.js"
46
+ },
47
+ "main": "lib/index.js",
48
+ "types": "lib/types/index.d.ts",
49
+ "exports": {
50
+ ".": {
51
+ "types": "./lib/types/index.d.ts",
52
+ "default": "./lib/index.js"
53
+ },
54
+ "./client": "./lib/client.js",
55
+ "./cordis.patch.yml": "./cordis.patch.yml",
56
+ "./package.json": "./package.json"
57
+ },
58
+ "files": [
59
+ "lib/*.js",
60
+ "lib/types/**/*.d.ts",
61
+ "cordis.patch.yml",
62
+ "icon.svg",
63
+ "src"
64
+ ],
65
+ "publishConfig": {
66
+ "access": "public"
67
+ },
68
+ "scripts": {
69
+ "build": "tsc -b --pretty false && tsdown && node -e \"require('node:fs').copyFileSync('src/client.js', 'lib/client.js')\"",
70
+ "typecheck": "tsc -b --pretty false",
71
+ "test": "vitest run"
72
+ },
73
+ "peerDependencies": {
74
+ "@deepseek-ai/cordis": "~4.1.0",
75
+ "@deepseek-ai/dsh-home-paths": "^0.2.2-rc.1",
76
+ "@deepseek-ai/dsh-tools": "^0.2.2-rc.1"
77
+ },
78
+ "dependencies": {
79
+ "@deepseek-ai/schemastery": "~3.19.0"
80
+ },
81
+ "devDependencies": {
82
+ "@deepseek-ai/cordis": "~4.1.0",
83
+ "@deepseek-ai/dsh-home-paths": "0.2.2-rc.2",
84
+ "@deepseek-ai/dsh-tools": "0.2.2-rc.2",
85
+ "@types/node": "^22.20.0",
86
+ "tsdown": "0.22.2",
87
+ "typescript": "^6.0.3",
88
+ "vitest": "^4.1.11"
89
+ }
90
+ }
package/src/cli.ts ADDED
@@ -0,0 +1,94 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `dsh-token-usage`: the `/usage` report in a terminal, without DSH running.
4
+ *
5
+ * ```
6
+ * dsh-token-usage overview and the last 14 days
7
+ * dsh-token-usage month by model the last 30 days, by model
8
+ * dsh-token-usage 2026-11 --json November's records as JSON
9
+ * ```
10
+ *
11
+ * Reads `$DSH_HOME/sessions` (default `~/.dsh/sessions`); `--home <dir>`
12
+ * points elsewhere. The CLI keeps no index; it reads every log each time.
13
+ *
14
+ * @module @natgurlain/dsh-token-usage/cli
15
+ */
16
+
17
+ import { homedir } from 'node:os'
18
+ import { join, resolve } from 'node:path'
19
+ import { UsageLedger } from './ledger.ts'
20
+ import { answer, parseQuery, USAGE_HINT } from './query.ts'
21
+ import { buildReport, dayOf, parsePeriod, type Prices } from './report.ts'
22
+ import { OpenRouterPrices } from './openrouter.ts'
23
+
24
+ const HELP = `Usage: dsh-token-usage ${USAGE_HINT} [--json] [--home <dsh home>] [--tz <zone>]
25
+
26
+ Counts the tokens of every DSH session from its logs.
27
+ --json print the report as JSON
28
+ --home <dir> DSH home (default $DSH_HOME or ~/.dsh)
29
+ --tz <zone> time zone for days (default this machine's)
30
+ --openrouter estimate costs at OpenRouter list prices (fetches openrouter.ai/api/v1/models)`
31
+
32
+ async function main(argv: readonly string[]): Promise<number> {
33
+ const words: string[] = []
34
+ let json = false
35
+ let home = process.env.DSH_HOME ?? join(homedir(), '.dsh')
36
+ let timeZone: string | undefined
37
+ let openRouter = false
38
+ for (let i = 0; i < argv.length; i++) {
39
+ const arg = argv[i] as string
40
+ if (arg === '-h' || arg === '--help') {
41
+ console.log(HELP)
42
+ return 0
43
+ }
44
+ if (arg === '--json') json = true
45
+ else if (arg === '--openrouter') openRouter = true
46
+ else if (arg === '--home' || arg === '--tz') {
47
+ const value = argv[++i]
48
+ if (value === undefined) {
49
+ console.error(`${arg} needs a value`)
50
+ return 2
51
+ }
52
+ if (arg === '--home') home = resolve(value)
53
+ else timeZone = value
54
+ } else words.push(arg)
55
+ }
56
+ const query = parseQuery(words)
57
+ if (typeof query === 'string') {
58
+ console.error(`${query}\n${HELP}`)
59
+ return 2
60
+ }
61
+ const records = await new UsageLedger({ sessionsDir: join(home, 'sessions') }).records()
62
+ let prices: Prices | undefined
63
+ let note: string | undefined
64
+ if (openRouter) {
65
+ const list = new OpenRouterPrices({ cacheFile: join(home, 'token-usage', 'openrouter-prices.json') })
66
+ await list.ready()
67
+ const found = list.pricesFor(new Map(records.map((r) => [`${r.provider}/${r.model}`, r])).values())
68
+ prices = found.prices
69
+ const keys = Object.keys(found.sources)
70
+ note = keys.length === 0 ? 'No model matched an OpenRouter price.' : `OpenRouter list prices: ${keys.map((key) => `${key} as ${found.sources[key]?.openRouterId ?? '?'}`).join(', ')}.`
71
+ }
72
+ if (json) {
73
+ const today = dayOf(Date.now(), timeZone)
74
+ const period = parsePeriod(query.period ?? 'all', today)
75
+ if (period === undefined) {
76
+ console.error(`Unknown period "${query.period ?? ''}"`)
77
+ return 2
78
+ }
79
+ const report = buildReport(records, { period, by: query.by ?? 'day', ...(prices === undefined ? {} : { prices }), ...(timeZone === undefined ? {} : { timeZone }), ...(query.noSubagents === true ? { excludeSubagents: true } : {}) })
80
+ console.log(JSON.stringify(report, null, 2))
81
+ return 0
82
+ }
83
+ if (query.here === true) {
84
+ console.error('"here" works inside a DSH conversation; in a terminal, use --home or filter with "by workspace".')
85
+ return 2
86
+ }
87
+ console.log(answer(records, query, { ...(timeZone === undefined ? {} : { timeZone }), ...(prices === undefined ? {} : { prices }), ...(note === undefined ? {} : { priceNote: note }) }))
88
+ return 0
89
+ }
90
+
91
+ main(process.argv.slice(2)).then((code) => { process.exitCode = code }, (error: unknown) => {
92
+ console.error(error instanceof Error ? error.message : String(error))
93
+ process.exitCode = 1
94
+ })