@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/lib/index.js ADDED
@@ -0,0 +1,318 @@
1
+ import { _ as findSessionLogs, a as USAGE_HINT, b as recordsFromEvents, c as GROUPS, d as emptyTotals, f as parsePeriod, g as UsageLedger, h as shiftDay, i as parseModels, l as buildReport, m as renderReport, n as matchModel, o as answer, p as priceFor, r as mergePrices, s as parseQuery, t as OpenRouterPrices, u as dayOf, v as normalizeUsage, y as readSessionLog } from "./openrouter-Ygu9q4uX.js";
2
+ import z from "@deepseek-ai/schemastery";
3
+ import { defineTool } from "@deepseek-ai/dsh-tools";
4
+ import { dshHomePath } from "@deepseek-ai/dsh-home-paths";
5
+ import { join } from "node:path";
6
+ //#region lib/types/snapshot.js
7
+ /**
8
+ * The Usage page's data: one JSON snapshot per period, served on dsh's
9
+ * authenticated `/api` channel as `POST /api/token-usage.report`.
10
+ *
11
+ * The page asks for a period (`today`, `week`, `month`, `90`, `all`, or any
12
+ * word `/usage` takes) and gets the totals, a zero-filled daily series for
13
+ * the chart, the overview sums, and the top models, workspaces and sessions.
14
+ *
15
+ * @module @natgurlain/dsh-token-usage/snapshot
16
+ */
17
+ const REPORT_API_PATH = "/api/token-usage.report";
18
+ function buildSnapshot(records, periodWord, options = {}) {
19
+ const now = options.now ?? Date.now();
20
+ const today = dayOf(now, options.timeZone);
21
+ const period = parsePeriod(periodWord, today);
22
+ if (period === void 0) return void 0;
23
+ const base = {
24
+ ...options.prices === void 0 ? {} : { prices: options.prices },
25
+ ...options.timeZone === void 0 ? {} : { timeZone: options.timeZone }
26
+ };
27
+ const limit = options.limit ?? 50;
28
+ const report = (by) => buildReport(records, {
29
+ ...base,
30
+ period,
31
+ by
32
+ });
33
+ const byDay = report("day");
34
+ const chartEnd = period.to ?? shiftDay(today, 1);
35
+ const contextFrom = shiftDay(chartEnd, -7);
36
+ const chartFrom = period.from === void 0 ? void 0 : contextFrom < period.from ? contextFrom : period.from;
37
+ const chartDays = buildReport(records, {
38
+ ...base,
39
+ period: {
40
+ label: "chart",
41
+ ...chartFrom === void 0 ? {} : { from: chartFrom },
42
+ to: chartEnd
43
+ },
44
+ by: "day"
45
+ });
46
+ const total = (word) => buildReport(records, {
47
+ ...base,
48
+ period: parsePeriod(word, today) ?? { label: word },
49
+ by: "kind"
50
+ }).totals.total;
51
+ const firstActive = chartDays.rows.at(-1)?.key ?? today;
52
+ const first = chartFrom ?? (contextFrom < firstActive ? contextFrom : firstActive);
53
+ const start = shiftDay(chartEnd, -180) > first ? shiftDay(chartEnd, -180) : first;
54
+ const known = new Map(chartDays.rows.map((row) => [row.key, row]));
55
+ const days = [];
56
+ for (let day = start; day < chartEnd; day = shiftDay(day, 1)) {
57
+ const { key: _key, label: _label, ...totals } = known.get(day) ?? {
58
+ key: day,
59
+ label: day,
60
+ ...emptyTotals()
61
+ };
62
+ days.push({
63
+ day,
64
+ inPeriod: (period.from === void 0 || day >= period.from) && (period.to === void 0 || day < period.to),
65
+ ...totals
66
+ });
67
+ }
68
+ return {
69
+ ok: true,
70
+ period,
71
+ today,
72
+ priced: byDay.priced,
73
+ totals: byDay.totals,
74
+ sessions: byDay.sessions,
75
+ overview: {
76
+ today: total("today"),
77
+ week: total("week"),
78
+ month: total("month"),
79
+ all: total("all")
80
+ },
81
+ days,
82
+ models: report("model").rows.slice(0, limit),
83
+ workspaces: report("workspace").rows.slice(0, limit),
84
+ sessionRows: report("session").rows.slice(0, limit),
85
+ generatedAt: now,
86
+ priceSources: {}
87
+ };
88
+ }
89
+ function json(body, status = 200) {
90
+ return new Response(JSON.stringify(body), {
91
+ status,
92
+ headers: {
93
+ "content-type": "application/json",
94
+ "cache-control": "no-store"
95
+ }
96
+ });
97
+ }
98
+ /**
99
+ * Handle `POST /api/token-usage.report` with `{ "period": "week" }`. dsh has
100
+ * already authenticated the caller as the host's owner; a JSON content type
101
+ * also keeps a cross-site page from sending it without a preflight.
102
+ */
103
+ async function handleReportRequest(request, load, options) {
104
+ if (!/^application\/json\b/iu.test(request.headers.get("content-type") ?? "")) return json({
105
+ ok: false,
106
+ error: "bad-request"
107
+ }, 415);
108
+ let body;
109
+ try {
110
+ body = await request.json();
111
+ } catch {
112
+ return json({
113
+ ok: false,
114
+ error: "bad-request"
115
+ }, 400);
116
+ }
117
+ const word = typeof body?.period === "string" && body.period.length <= 40 ? body.period : "month";
118
+ try {
119
+ const usage = await load();
120
+ const snapshot = buildSnapshot(usage.records, word, {
121
+ ...options,
122
+ prices: usage.prices
123
+ });
124
+ if (snapshot === void 0) return json({
125
+ ok: false,
126
+ error: "bad-period"
127
+ }, 400);
128
+ const used = new Set(snapshot.models.map((row) => row.key));
129
+ snapshot.priceSources = Object.fromEntries(Object.entries(usage.priceSources ?? {}).filter(([key]) => used.has(key)));
130
+ if (usage.pricesAsOf !== void 0 && Object.keys(snapshot.priceSources).length > 0) snapshot.pricesAsOf = usage.pricesAsOf;
131
+ return json(snapshot);
132
+ } catch (error) {
133
+ return json({
134
+ ok: false,
135
+ error: "failed",
136
+ message: error instanceof Error ? error.message : String(error)
137
+ }, 500);
138
+ }
139
+ }
140
+ //#endregion
141
+ //#region lib/types/index.js
142
+ /**
143
+ * `@natgurlain/dsh-token-usage`: token usage for DeepSeek Harness.
144
+ *
145
+ * Counts the tokens of every model call in every session (conversations,
146
+ * subagents, failed attempts and compaction) from DSH's own session logs,
147
+ * and reports them by day, model, workspace or session. The user types
148
+ * `/usage`; the agent has a read-only `token_usage` tool; `dsh-token-usage`
149
+ * prints the same report in a terminal.
150
+ *
151
+ * @module @natgurlain/dsh-token-usage
152
+ */
153
+ const name = "token-usage";
154
+ const inject = ["tools"];
155
+ const Price = z.object({
156
+ input: z.number().min(0).required().description("USD per million uncached input tokens."),
157
+ output: z.number().min(0).required().description("USD per million output tokens."),
158
+ cacheRead: z.number().min(0).description("USD per million cache-read tokens; defaults to the input price."),
159
+ cacheWrite: z.number().min(0).description("USD per million cache-write tokens; defaults to the input price.")
160
+ });
161
+ const Config = z.object({
162
+ prices: z.dict(Price).default({}).description("Prices by \"provider/model\" or model name, to show costs next to tokens."),
163
+ timeZone: z.string().description("IANA time zone for days, like Europe/Warsaw; defaults to this machine's."),
164
+ root: z.string().description("Where the usage index is kept; defaults to ~/.dsh/token-usage."),
165
+ sessionsDir: z.string().description("Session logs to read; defaults to ~/.dsh/sessions."),
166
+ openRouter: z.object({
167
+ 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)."),
168
+ refreshHours: z.number().min(1).default(24).description("Hours before the OpenRouter price list is fetched again."),
169
+ models: z.dict(z.string()).default({}).description("Manual matches: \"provider/model\" (or model) → OpenRouter model id, like qwen/qwen4-35b-a3b.")
170
+ }).default({
171
+ enabled: true,
172
+ refreshHours: 24,
173
+ models: {}
174
+ })
175
+ });
176
+ const TEXT_OUTPUT = {
177
+ schema: {
178
+ type: "object",
179
+ additionalProperties: false,
180
+ properties: { text: {
181
+ type: "string",
182
+ required: true
183
+ } }
184
+ },
185
+ render: (_args, value) => [{
186
+ type: "text",
187
+ text: value.text
188
+ }]
189
+ };
190
+ /** The caller's working directory: from the agent, else from its own logged calls. */
191
+ function cwdOf(agent, records) {
192
+ const direct = agent?.session?.header?.cwd;
193
+ if (typeof direct === "string" && direct !== "") return direct;
194
+ if (agent?.id === void 0) return void 0;
195
+ const id = String(agent.id);
196
+ return records.findLast((record) => record.sessionId === id)?.cwd;
197
+ }
198
+ function apply(ctx, config) {
199
+ const ledger = new UsageLedger({
200
+ sessionsDir: config.sessionsDir ?? dshHomePath("sessions"),
201
+ indexFile: join(config.root ?? dshHomePath("token-usage"), "index.json")
202
+ });
203
+ const root = config.root ?? dshHomePath("token-usage");
204
+ const openRouter = config.openRouter.enabled ? new OpenRouterPrices({
205
+ cacheFile: join(root, "openrouter-prices.json"),
206
+ refreshHours: config.openRouter.refreshHours,
207
+ models: config.openRouter.models
208
+ }) : void 0;
209
+ /** Records plus the prices that apply: configured ones, then OpenRouter's for the rest. */
210
+ const load = async () => {
211
+ const records = await ledger.records();
212
+ if (openRouter === void 0) return {
213
+ records,
214
+ prices: config.prices
215
+ };
216
+ await openRouter.ready();
217
+ const unpriced = [...new Map(records.map((record) => [`${record.provider}/${record.model}`, record])).values()].filter((record) => priceFor(config.prices, record.provider, record.model) === void 0);
218
+ const found = openRouter.pricesFor(unpriced);
219
+ const fetchedAt = openRouter.fetchedAt;
220
+ return {
221
+ records,
222
+ prices: mergePrices(config.prices, found.prices),
223
+ priceSources: Object.fromEntries(Object.entries(found.sources).map(([key, source]) => [key, source.openRouterId])),
224
+ ...fetchedAt === void 0 ? {} : { pricesAsOf: fetchedAt }
225
+ };
226
+ };
227
+ const run = async (query, agent) => {
228
+ const { records, prices, priceSources } = await load();
229
+ const cwd = cwdOf(agent, records);
230
+ const estimated = Object.keys(priceSources ?? {});
231
+ return answer(records, query, {
232
+ prices,
233
+ ...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(", ")}).` },
234
+ ...config.timeZone === void 0 ? {} : { timeZone: config.timeZone },
235
+ ...cwd === void 0 ? {} : { cwd }
236
+ });
237
+ };
238
+ const mountRoute = (connection) => {
239
+ const fetch = connection?.fetch;
240
+ if (typeof fetch?.register !== "function") return () => void 0;
241
+ const dispose = fetch.register({
242
+ path: REPORT_API_PATH,
243
+ methods: ["POST"],
244
+ requestBody: "buffered",
245
+ fetch: (request) => handleReportRequest(request, load, config.timeZone === void 0 ? {} : { timeZone: config.timeZone })
246
+ });
247
+ return () => {
248
+ dispose();
249
+ };
250
+ };
251
+ const withInject = ctx;
252
+ if (typeof withInject.inject === "function") withInject.inject(["connection"], (inner) => {
253
+ inner.effect(() => mountRoute(inner.get("connection")), "token-usage: /api/token-usage.report");
254
+ });
255
+ else ctx.effect(() => mountRoute(ctx.get("connection")), "token-usage: /api/token-usage.report");
256
+ const commands = ctx.get("commands");
257
+ if (typeof commands?.register === "function") ctx.effect(() => commands.register({
258
+ name: "usage",
259
+ description: "Tokens used across all sessions, by day, model, workspace or session",
260
+ input: { hint: USAGE_HINT },
261
+ handler: async (invocation) => {
262
+ const query = parseQuery(invocation.rawInput.trim().split(/\s+/).filter((word) => word !== ""));
263
+ if (typeof query === "string") return {
264
+ kind: "error",
265
+ text: `${query} Usage: /usage ${USAGE_HINT}`
266
+ };
267
+ try {
268
+ return {
269
+ kind: "success",
270
+ text: await run(query, invocation.agent)
271
+ };
272
+ } catch (error) {
273
+ return {
274
+ kind: "error",
275
+ text: error instanceof Error ? error.message : String(error)
276
+ };
277
+ }
278
+ }
279
+ }), "token-usage: /usage command");
280
+ const tool = defineTool({
281
+ name: "token_usage",
282
+ 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.",
283
+ parameters: {
284
+ period: {
285
+ type: "string",
286
+ 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."
287
+ },
288
+ group_by: {
289
+ type: "string",
290
+ enum: [...GROUPS],
291
+ description: "How to break the period down; default day."
292
+ },
293
+ this_workspace: {
294
+ type: "boolean",
295
+ description: "Only sessions in this conversation's working directory."
296
+ },
297
+ limit: {
298
+ type: "number",
299
+ description: "Most rows to show; default 30."
300
+ }
301
+ },
302
+ timeoutMs: 6e4,
303
+ output: TEXT_OUTPUT,
304
+ execute: async (args, exec) => {
305
+ const a = args;
306
+ const query = {
307
+ ...a.period === void 0 || a.period === "" ? {} : { period: a.period },
308
+ ...a.group_by === void 0 ? {} : { by: a.group_by },
309
+ ...a.this_workspace === true ? { here: true } : {},
310
+ ...typeof a.limit === "number" && a.limit >= 1 ? { limit: Math.floor(a.limit) } : {}
311
+ };
312
+ return { text: await run(query, exec.agent) };
313
+ }
314
+ });
315
+ ctx.effect(() => ctx.tools.register(tool), "token-usage: token_usage tool");
316
+ }
317
+ //#endregion
318
+ export { Config, OpenRouterPrices, REPORT_API_PATH, UsageLedger, answer, apply, buildReport, buildSnapshot, dayOf, findSessionLogs, inject, matchModel, mergePrices, name, normalizeUsage, parseModels, parsePeriod, parseQuery, readSessionLog, recordsFromEvents, renderReport };