@jerry_chzy/dsh-token-usage 0.0.0-stage → 0.1.1

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,891 @@
1
+ import z from "@deepseek-ai/schemastery";
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import { readFile, rename, rm, writeFile } from "node:fs/promises";
4
+ import { join } from "node:path";
5
+ import { z as z$1 } from "zod";
6
+ //#region lib/types/pricing.js
7
+ /**
8
+ * Cost estimation for one conversation's durable token usage.
9
+ *
10
+ * The estimate converts the `tokenUsage` projection's four disjoint billing
11
+ * buckets into money with a deployment-supplied price table. It is a
12
+ * reference figure, not a bill: prices change, peak/off-peak rates exist, and
13
+ * the provider's own statement is authoritative.
14
+ *
15
+ * The table reaches the browser as the `tokenPricing` session projection
16
+ * because browser plugin rows carry no `config`; the host half registers the
17
+ * configured table and every session projects the same deployment constant.
18
+ * The module also owns the `tokenCostBackfill` projection's value — the
19
+ * browser notice's view of which routes the backfill price table missed.
20
+ *
21
+ * @module @jerry_chzy/dsh-token-usage/pricing
22
+ */
23
+ /**
24
+ * Advisory DeepSeek official price table (CNY per million tokens, peak rate;
25
+ * off-peak official rates are half). Deployments override it through the
26
+ * plugin's `pricing` config; an unlisted model shows no cost figure rather
27
+ * than a guessed one.
28
+ */
29
+ const DEFAULT_PRICING = Object.freeze({
30
+ "deepseek-flash": Object.freeze({
31
+ inputMiss: 2,
32
+ inputHit: .04,
33
+ output: 8
34
+ }),
35
+ "deepseek-v4-flash": Object.freeze({
36
+ inputMiss: 3,
37
+ inputHit: .1,
38
+ output: 9
39
+ }),
40
+ "deepseek-v4-flash-vision-exp": Object.freeze({
41
+ inputMiss: 3,
42
+ inputHit: .1,
43
+ output: 9
44
+ }),
45
+ "deepseek-v4-pro": Object.freeze({
46
+ inputMiss: 9,
47
+ inputHit: .3,
48
+ output: 27
49
+ })
50
+ });
51
+ /**
52
+ * Resolve a model id against a price table by longest matching prefix.
53
+ *
54
+ * Prefixes, not exact ids, because adapters append route suffixes (vision,
55
+ * dated snapshots) that share the base model's price. The value type is open
56
+ * because the readout's per-token price and the backfill's peak/off-peak pairs
57
+ * both key off the same prefix rule.
58
+ * @param model - the session's last-used model id.
59
+ * @param table - prices keyed by model-id prefix.
60
+ * @returns the matched entry, or undefined when no prefix matches.
61
+ */
62
+ function priceForModel(model, table) {
63
+ let best;
64
+ let bestLength = 0;
65
+ for (const [prefix, price] of Object.entries(table)) if (prefix.length > bestLength && model.startsWith(prefix)) {
66
+ best = price;
67
+ bestLength = prefix.length;
68
+ }
69
+ return best;
70
+ }
71
+ /**
72
+ * Estimate one conversation's cost in CNY.
73
+ *
74
+ * Prompt tokens that missed the cache (uncached input plus cache writes) bill
75
+ * at the miss rate; cache-hit prompt tokens bill at the hit rate; completion
76
+ * tokens bill at the output rate. The result is exact arithmetic over the
77
+ * projected buckets — the estimate error is entirely the price table's.
78
+ * @param usage - the session's four disjoint billing buckets.
79
+ * @param price - the matched model price.
80
+ * @returns estimated cost in CNY.
81
+ */
82
+ function estimateCostCny(usage, price) {
83
+ return ((usage.uncachedInputTokens + usage.cacheWriteTokens) * price.inputMiss + usage.cacheReadTokens * price.inputHit + usage.outputTokens * price.output) / 1e6;
84
+ }
85
+ /**
86
+ * Total billed tokens across the projection's four disjoint buckets.
87
+ * @param usage - the session's four disjoint billing buckets.
88
+ * @returns prompt-side billed input plus output.
89
+ */
90
+ function billedTokens(usage) {
91
+ return usage.uncachedInputTokens + usage.cacheReadTokens + usage.cacheWriteTokens + usage.outputTokens;
92
+ }
93
+ //#endregion
94
+ //#region lib/types/backfill.js
95
+ /**
96
+ * First-install history backfill: fold every archived session's durable usage
97
+ * into peak/off-peak money and write one `TOKEN_COST.md` per session working
98
+ * directory.
99
+ *
100
+ * The pass is a side effect of the plugin's fiber, not of its activation: it
101
+ * runs once per process start against the archived corpus, is idempotent
102
+ * through a marker comment carrying the fold version, the config hash, and the
103
+ * folded session watermarks, and never writes outside a session header's own
104
+ * `cwd`. A deployment without `ctx.sessionQuery` mounted, or a session without
105
+ * a working directory, is skipped with a log line rather than a guess.
106
+ *
107
+ * @module @jerry_chzy/dsh-token-usage/backfill
108
+ */
109
+ /** Name of the report written into each session working directory. */
110
+ const BACKFILL_FILE_NAME = "TOKEN_COST.md";
111
+ /** Marker prefix the report's first line carries. */
112
+ const MARKER_PREFIX = "<!-- dsh-token-cost-backfill:";
113
+ /**
114
+ * Fold-semantics version carried in the report marker.
115
+ *
116
+ * Increment it whenever {@link foldSessionUsage} can fold one log differently —
117
+ * version 1 read only the `assistant/message` usage field and missed
118
+ * stream-embedded usage and retried attempts. Without the bump a report written
119
+ * under the old semantics keeps matching the marker, and its understated
120
+ * amounts stay on disk forever.
121
+ */
122
+ const FOLD_SEMANTICS_VERSION = 2;
123
+ /** China Standard Time offset; peak windows are stated in Beijing time. */
124
+ const BEIJING_OFFSET_MS = 480 * 60 * 1e3;
125
+ /** Advisory peak windows: Beijing-time weekdays 09:00–12:00 and 14:00–18:00. */
126
+ const DEFAULT_PEAK_HOURS = Object.freeze([{
127
+ days: [
128
+ 1,
129
+ 2,
130
+ 3,
131
+ 4,
132
+ 5
133
+ ],
134
+ start: "09:00",
135
+ end: "12:00"
136
+ }, {
137
+ days: [
138
+ 1,
139
+ 2,
140
+ 3,
141
+ 4,
142
+ 5
143
+ ],
144
+ start: "14:00",
145
+ end: "18:00"
146
+ }]);
147
+ /** Build one price entry from its peak rates; off-peak is half. */
148
+ function peakPrice(inputMiss, inputHit, output) {
149
+ const pair = (peak) => Object.freeze([peak / 2, peak]);
150
+ return Object.freeze({
151
+ inputMiss: pair(inputMiss),
152
+ inputHit: pair(inputHit),
153
+ output: pair(output)
154
+ });
155
+ }
156
+ /**
157
+ * Advisory DeepSeek price table for the backfill (CNY per million tokens,
158
+ * `[offPeak, peak]`). Deployments override it through `backfill.pricing`; a
159
+ * route absent from the resolved table is reported as needing a price instead
160
+ * of being guessed at.
161
+ */
162
+ const DEFAULT_BACKFILL_PRICING = Object.freeze({
163
+ "deepseek-flash": peakPrice(2, .04, 8),
164
+ "deepseek-v4-flash": peakPrice(3, .1, 9),
165
+ "deepseek-v4-flash-vision-exp": peakPrice(3, .1, 9),
166
+ "deepseek-v4-pro": peakPrice(9, .3, 27)
167
+ });
168
+ /** The zero value of the four disjoint billing buckets. */
169
+ function zeroUsage() {
170
+ return {
171
+ uncachedInputTokens: 0,
172
+ outputTokens: 0,
173
+ cacheReadTokens: 0,
174
+ cacheWriteTokens: 0
175
+ };
176
+ }
177
+ /** Add one sample into a bucket total, mutating it. */
178
+ function addUsage(total, usage) {
179
+ total.uncachedInputTokens += usage.uncachedInputTokens;
180
+ total.outputTokens += usage.outputTokens;
181
+ total.cacheReadTokens += usage.cacheReadTokens;
182
+ total.cacheWriteTokens += usage.cacheWriteTokens;
183
+ }
184
+ /** Remove one previously counted sample from a bucket total, mutating it. */
185
+ function removeUsage(total, usage) {
186
+ total.uncachedInputTokens -= usage.uncachedInputTokens;
187
+ total.outputTokens -= usage.outputTokens;
188
+ total.cacheReadTokens -= usage.cacheReadTokens;
189
+ total.cacheWriteTokens -= usage.cacheWriteTokens;
190
+ }
191
+ /** `HH:MM` as minutes since local midnight. */
192
+ function toMinutes(value) {
193
+ const [hours, minutes] = value.split(":");
194
+ return Number(hours) * 60 + Number(minutes);
195
+ }
196
+ /**
197
+ * Whether one instant falls inside a Beijing-time peak window.
198
+ * @param time - event timestamp in Unix epoch milliseconds.
199
+ * @param windows - peak windows stated in Beijing time.
200
+ * @returns true when some window covers the instant's weekday and clock time.
201
+ */
202
+ function isPeakInstant(time, windows) {
203
+ const local = new Date(time + BEIJING_OFFSET_MS);
204
+ const day = local.getUTCDay();
205
+ const minutes = local.getUTCHours() * 60 + local.getUTCMinutes();
206
+ return windows.some((window) => window.days.includes(day) && minutes >= toMinutes(window.start) && minutes < toMinutes(window.end));
207
+ }
208
+ /**
209
+ * The provider usage one durable settlement reports.
210
+ *
211
+ * An `assistant/message` may carry the usage verbatim. Every other settlement —
212
+ * a failed `assistant/attempt`, or a message whose usage survived only inside
213
+ * its stream — reports it as the last `usage` chunk of the embedded compact
214
+ * record list, matching how the `tokenUsage` projection reads the same log.
215
+ * @param event - the settlement event to read.
216
+ * @returns the reported usage, or undefined when the settlement carries none.
217
+ */
218
+ function reportedUsage(event) {
219
+ if (event.type === "assistant/message" && event.data.usage !== void 0) return event.data.usage;
220
+ let found;
221
+ for (const record of event.data.stream) if (record.type === "chunk" && record.chunk.type === "usage") found = record.chunk.usage;
222
+ return found;
223
+ }
224
+ /**
225
+ * Fold one session log's durable usage into peak/off-peak buckets and routes.
226
+ *
227
+ * A settlement is either an `assistant/message` or a failed `assistant/attempt`;
228
+ * both report usage, and a stream-embedded sample counts even when the event's
229
+ * own `usage` field is absent. A second sample for the same turn and step
230
+ * replaces the first instead of adding to it, matching the `tokenUsage`
231
+ * projection: the provider reports one attempt's usage, and a re-settled
232
+ * attempt must not bill twice. `llm/retry-started` closes that replacement slot,
233
+ * so the sample after a retry adds to the failed attempt it followed — those
234
+ * tokens were billed too. Each sample lands in the period its own event
235
+ * timestamp falls in, so a conversation spanning the peak boundary is priced at
236
+ * both rates.
237
+ * @param sessionId - session the log belongs to.
238
+ * @param events - the session's complete raw log, in seq order.
239
+ * @param windows - peak windows stated in Beijing time.
240
+ * @returns the folded routes, period buckets, and highest folded seq.
241
+ */
242
+ function foldSessionUsage(sessionId, events, windows) {
243
+ const peak = zeroUsage();
244
+ const offPeak = zeroUsage();
245
+ const routes = [];
246
+ const lastSeq = events.at(-1)?.seq ?? -1;
247
+ let route = null;
248
+ let slot;
249
+ for (const event of events) {
250
+ if (event.type === "request/header") {
251
+ const { provider, model } = event.data.header.config;
252
+ route = `${provider}/${model}`;
253
+ if (!routes.includes(route)) routes.push(route);
254
+ continue;
255
+ }
256
+ if (event.type === "llm/retry-started") {
257
+ if (slot !== void 0 && slot.turn === event.data.turn && slot.step === event.data.step) slot = void 0;
258
+ continue;
259
+ }
260
+ if (event.type !== "assistant/message" && event.type !== "assistant/attempt") continue;
261
+ const usage = reportedUsage(event);
262
+ if (usage === void 0) continue;
263
+ const buckets = {
264
+ uncachedInputTokens: usage.inputTokens,
265
+ outputTokens: usage.outputTokens,
266
+ cacheReadTokens: usage.cacheReadTokens ?? 0,
267
+ cacheWriteTokens: usage.cacheWriteTokens ?? 0
268
+ };
269
+ const inPeak = isPeakInstant(event.time, windows);
270
+ if (slot !== void 0 && slot.turn === event.data.turn && slot.step === event.data.step) removeUsage(slot.peak ? peak : offPeak, slot.usage);
271
+ addUsage(inPeak ? peak : offPeak, buckets);
272
+ slot = {
273
+ turn: event.data.turn,
274
+ step: event.data.step,
275
+ usage: buckets,
276
+ peak: inPeak
277
+ };
278
+ }
279
+ return {
280
+ sessionId,
281
+ routes,
282
+ route,
283
+ peak,
284
+ offPeak,
285
+ lastSeq
286
+ };
287
+ }
288
+ /**
289
+ * Price one period's four buckets with a route price.
290
+ * @param usage - the period's four disjoint billing buckets.
291
+ * @param price - the route's `[offPeak, peak]` price pairs.
292
+ * @param peak - which period prices the usage.
293
+ * @returns cost in CNY.
294
+ */
295
+ function periodCostCny(usage, price, peak) {
296
+ const index = peak ? 1 : 0;
297
+ return ((usage.uncachedInputTokens + usage.cacheWriteTokens) * price.inputMiss[index] + usage.cacheReadTokens * price.inputHit[index] + usage.outputTokens * price.output[index]) / 1e6;
298
+ }
299
+ /** Model id of a `provider/model` route; model ids never contain `/`. */
300
+ function modelOf(route) {
301
+ return route.slice(route.indexOf("/") + 1);
302
+ }
303
+ /** Resolve one session's price from its last recorded route. */
304
+ function priceOf(sample, table) {
305
+ return sample.route === null ? void 0 : priceForModel(modelOf(sample.route), table);
306
+ }
307
+ /** Currency rendering that never rounds a real cost to a bare zero. */
308
+ function formatCny(value) {
309
+ if (value === 0) return "0";
310
+ if (value < .01) return value.toFixed(6).replace(/0+$/u, "").replace(/\.$/u, "");
311
+ if (value < 1) return value.toFixed(3);
312
+ return value.toFixed(2);
313
+ }
314
+ /** Stable identity of one report: the fold semantics, the price table, and every folded watermark. */
315
+ function markerFor(samples, pricing) {
316
+ return `${MARKER_PREFIX} fold=${FOLD_SEMANTICS_VERSION} config=${createHash("sha256").update(JSON.stringify(pricing)).digest("hex").slice(0, 16)} sessions=${[...samples].sort((left, right) => String(left.sessionId).localeCompare(String(right.sessionId))).map((sample) => `${sample.sessionId}:${sample.lastSeq}`).join(",")} -->`;
317
+ }
318
+ /** The routes across one working directory that need a price, with session counts. */
319
+ function unpricedRoutes(samples, pricing) {
320
+ const counts = /* @__PURE__ */ new Map();
321
+ for (const sample of samples) for (const route of sample.routes) {
322
+ if (priceForModel(modelOf(route), pricing) !== void 0) continue;
323
+ counts.set(route, (counts.get(route) ?? 0) + 1);
324
+ }
325
+ return [...counts.entries()].sort(([left], [right]) => left.localeCompare(right));
326
+ }
327
+ /** Header paragraph shared by both report forms. */
328
+ function reportIntro(samples) {
329
+ return `# TOKEN_COST.md\n\nHistorical cost backfill over ${samples.length} archived session(s) recorded in this working directory.`;
330
+ }
331
+ /** Amounts table for a working directory that has at least one priced route. */
332
+ function renderAmounts(samples, pricing, generatedAt) {
333
+ const rows = samples.map((sample) => {
334
+ const price = priceOf(sample, pricing);
335
+ const peak = price === void 0 ? void 0 : periodCostCny(sample.peak, price, true);
336
+ const offPeak = price === void 0 ? void 0 : periodCostCny(sample.offPeak, price, false);
337
+ const model = sample.route === null ? "—" : `\`${sample.route}\``;
338
+ const money = (value) => value === void 0 ? "—" : `¥${formatCny(value)}`;
339
+ const total = peak === void 0 || offPeak === void 0 ? void 0 : peak + offPeak;
340
+ const buckets = zeroUsage();
341
+ addUsage(buckets, sample.peak);
342
+ addUsage(buckets, sample.offPeak);
343
+ return `| \`${sample.sessionId}\` | ${model} | ${buckets.uncachedInputTokens} | ${buckets.cacheReadTokens} | ${buckets.cacheWriteTokens} | ${buckets.outputTokens} | ${money(peak)} | ${money(offPeak)} | ${money(total)} |`;
344
+ });
345
+ return [
346
+ reportIntro(samples),
347
+ "Amounts are CNY per the configured rates and are split by each event's Beijing-time window; `—` marks a route with no configured price.",
348
+ "",
349
+ "| Session | Model | Input (miss) | Cache read | Cache write | Output | Peak cost | Off-peak cost | Total |",
350
+ "| --- | --- | ---: | ---: | ---: | ---: | ---: | ---: | ---: |",
351
+ ...rows,
352
+ "",
353
+ `Generated ${generatedAt} by @jerry_chzy/dsh-token-usage.`
354
+ ].join("\n");
355
+ }
356
+ /** Pricing instructions for a working directory whose routes are all unpriced. */
357
+ function renderInstructions(samples, pricing, generatedAt) {
358
+ const routes = unpricedRoutes(samples, pricing).map(([route, sessions]) => `- \`${route}\` — ${sessions} session(s)`);
359
+ return [
360
+ reportIntro(samples),
361
+ "No configured price matched the recorded model route(s), so no amount could be computed.",
362
+ "",
363
+ "Routes without a price:",
364
+ "",
365
+ ...routes,
366
+ "",
367
+ "Add one by pasting this row into `~/.dsh/profiles/web/cordis.patch.yml` and restarting Web.",
368
+ "Each pair is `[off-peak, peak]` in CNY per million tokens; the longest matching model-id prefix wins.",
369
+ "",
370
+ "```yaml",
371
+ "- id: ui-token-usage",
372
+ " name: '@jerry_chzy/dsh-token-usage'",
373
+ " config:",
374
+ " backfill:",
375
+ " pricing:",
376
+ " <model-id-prefix>:",
377
+ " inputMiss: [4.5, 9]",
378
+ " inputHit: [0.15, 0.3]",
379
+ " output: [13.5, 27]",
380
+ "```",
381
+ "",
382
+ "The next start rewrites this file with the amounts.",
383
+ "",
384
+ `Generated ${generatedAt} by @jerry_chzy/dsh-token-usage.`
385
+ ].join("\n");
386
+ }
387
+ /**
388
+ * Write one working directory's report, unless its marker already matches.
389
+ *
390
+ * The write is a temporary file plus a rename, so a reader never observes a
391
+ * half-written report and a crash leaves the previous one intact. The marker
392
+ * carries the fold version, the price-table hash, and every folded watermark,
393
+ * so a pass skips work only when the folding semantics, the configuration, and
394
+ * the archived usage all still match.
395
+ * @param cwd - the session working directory the report belongs to.
396
+ * @param samples - the directory's folded sessions.
397
+ * @param options - the resolved backfill configuration.
398
+ */
399
+ async function writeReport(cwd, samples, options) {
400
+ if (samples.every((sample) => sample.routes.length === 0)) return;
401
+ const marker = markerFor(samples, options.pricing);
402
+ const path = join(cwd, BACKFILL_FILE_NAME);
403
+ const existing = await readFile(path, "utf8").catch(() => void 0);
404
+ if (existing !== void 0 && existing.includes(marker)) return;
405
+ const priced = samples.some((sample) => priceOf(sample, options.pricing) !== void 0);
406
+ const generatedAt = (/* @__PURE__ */ new Date()).toISOString();
407
+ const body = priced ? renderAmounts(samples, options.pricing, generatedAt) : renderInstructions(samples, options.pricing, generatedAt);
408
+ const temporary = `${path}.${randomUUID()}.tmp`;
409
+ await writeFile(temporary, `${marker}\n\n${body}\n`, "utf8");
410
+ try {
411
+ await rename(temporary, path);
412
+ } catch (error) {
413
+ await rm(temporary, { force: true });
414
+ throw error;
415
+ }
416
+ }
417
+ /**
418
+ * Run one backfill pass over the archived session corpus.
419
+ *
420
+ * The session-query service is optional: an unmounted one logs and returns
421
+ * instead of failing the plugin. Each session is read and folded inside its
422
+ * own failure scope, so one unreadable or malformed log costs only that
423
+ * session's row. Nothing is written outside a session header's own `cwd`;
424
+ * a session without one is logged and skipped.
425
+ * @param ctx - the host context owning the logger and the optional service.
426
+ * @param options - the resolved backfill configuration.
427
+ * @param signal - aborts the pass when the plugin's fiber is disposed.
428
+ */
429
+ async function runCostBackfill(ctx, options, signal) {
430
+ const query = ctx.get("sessionQuery", false);
431
+ if (query === void 0) {
432
+ ctx.logger.warn("ui-token-usage: the sessionQuery service is not mounted; skipping the TOKEN_COST.md backfill");
433
+ return;
434
+ }
435
+ const byCwd = /* @__PURE__ */ new Map();
436
+ for (const record of await query.listSessions(signal)) {
437
+ if (signal.aborted) return;
438
+ const { cwd, id } = record.header;
439
+ if (cwd === void 0) {
440
+ ctx.logger.warn(`ui-token-usage: session "${id}" records no working directory; skipping it in the TOKEN_COST.md backfill`);
441
+ continue;
442
+ }
443
+ try {
444
+ const loaded = await query.readSession(id);
445
+ const bucket = byCwd.get(cwd) ?? [];
446
+ bucket.push(foldSessionUsage(id, loaded.events, options.peakHours));
447
+ byCwd.set(cwd, bucket);
448
+ } catch (error) {
449
+ ctx.logger.warn(`ui-token-usage: cannot read session "${id}" for the TOKEN_COST.md backfill: ${String(error)}`);
450
+ }
451
+ }
452
+ for (const [cwd, samples] of byCwd) {
453
+ if (signal.aborted) return;
454
+ try {
455
+ await writeReport(cwd, samples, options);
456
+ } catch (error) {
457
+ ctx.logger.warn(`ui-token-usage: cannot write ${join(cwd, BACKFILL_FILE_NAME)}: ${String(error)}`);
458
+ }
459
+ }
460
+ }
461
+ //#endregion
462
+ //#region lib/types/format.js
463
+ /**
464
+ * Compact numeric formatting shared by the browser readout and the host's local
465
+ * `/usage` reply, so both render the same figure from the same rule.
466
+ * @module @jerry_chzy/dsh-token-usage/format
467
+ */
468
+ /** Units for host-authored text, which has no locale seat to render through. */
469
+ const ASCII_UNITS = {
470
+ thousand: (scaled) => `${scaled}K`,
471
+ million: (scaled) => `${scaled}M`
472
+ };
473
+ /**
474
+ * Compact token count: 517 / 12.3K / 1.2M.
475
+ * @param value - non-negative token count.
476
+ * @param units - suffix renderers, owned by the caller's locale or fixed text.
477
+ * @returns compact display string.
478
+ */
479
+ function formatTokens(value, units) {
480
+ const scaled = (candidate) => candidate >= 100 ? String(Math.round(candidate)) : String(Math.round(candidate * 10) / 10);
481
+ if (value < 1e3) return String(value);
482
+ if (value < 1e6) return units.thousand(scaled(value / 1e3));
483
+ return units.million(scaled(value / 1e6));
484
+ }
485
+ /**
486
+ * Cost with enough precision to stay non-zero on cheap sessions: two decimals
487
+ * once the figure is a yuan, three below it, and trailing-zero-trimmed
488
+ * micro-precision for sub-fen amounts.
489
+ * @param value - non-negative cost amount.
490
+ * @returns display amount that never rounds a real cost to bare zero.
491
+ */
492
+ function formatAmount(value) {
493
+ if (value === 0) return "0";
494
+ if (value < .01) return value.toFixed(6).replace(/0+$/u, "").replace(/\.$/u, "");
495
+ if (value < 1) return value.toFixed(3);
496
+ return value.toFixed(2);
497
+ }
498
+ //#endregion
499
+ //#region lib/types/command.js
500
+ /**
501
+ * The `/usage` report on two surfaces: a registered slash command for clients
502
+ * that execute commands, and a model-boundary fallback for clients that can only
503
+ * send messages.
504
+ *
505
+ * Neither surface calls the provider. The fallback returns a stream with no usage
506
+ * sample, so the loop logs the answer without settling anything: the token
507
+ * meter's context occupancy reads the newest settlement, and a synthetic zero
508
+ * would read as an empty context.
509
+ * @module @jerry_chzy/dsh-token-usage/command
510
+ */
511
+ /** English defaults, matching the shipped dictionaries. */
512
+ const DEFAULT_REPORT_LABELS = {
513
+ total: "total",
514
+ input: "in",
515
+ cacheRead: "cache read",
516
+ cacheWrite: "cache write",
517
+ output: "out",
518
+ context: "context"
519
+ };
520
+ /**
521
+ * Read one registered projection's state. Its key belongs to another package,
522
+ * so the registry is addressed through its published `stateOf` surface and a
523
+ * registration this profile lacks reads as absent instead of failing the command.
524
+ * @param ctx - plugin context owning the projection registry.
525
+ * @param session - session whose folded state is read.
526
+ * @param key - projection key registered by the owning plugin.
527
+ * @returns the projected state, or undefined when the key is not registered.
528
+ */
529
+ function readProjection(ctx, session, key) {
530
+ const registry = ctx.sessionProjections;
531
+ try {
532
+ return registry.stateOf(session, key);
533
+ } catch {
534
+ return;
535
+ }
536
+ }
537
+ /**
538
+ * One-line report of the session's billed usage, cost estimate, and context occupancy.
539
+ * @param usage - the session's four billing buckets.
540
+ * @param labels - copy for each figure.
541
+ * @param figures - cost and context values the reply can add.
542
+ * @returns the reply text.
543
+ */
544
+ function renderUsageReport(usage, labels, figures) {
545
+ const parts = [`${labels.total} ${formatTokens(billedTokens(usage), ASCII_UNITS)}`];
546
+ parts.push(`${labels.input} ${formatTokens(usage.uncachedInputTokens, ASCII_UNITS)}`);
547
+ if (usage.cacheReadTokens !== 0) parts.push(`${labels.cacheRead} ${formatTokens(usage.cacheReadTokens, ASCII_UNITS)}`);
548
+ if (usage.cacheWriteTokens !== 0) parts.push(`${labels.cacheWrite} ${formatTokens(usage.cacheWriteTokens, ASCII_UNITS)}`);
549
+ parts.push(`${labels.output} ${formatTokens(usage.outputTokens, ASCII_UNITS)}`);
550
+ if (figures.cost !== void 0) parts.push(`≈${figures.currencySymbol}${formatAmount(figures.cost)}`);
551
+ if (figures.context !== void 0) {
552
+ const used = formatTokens(figures.context.used, ASCII_UNITS);
553
+ const occupancy = figures.context.window === void 0 ? used : `${used}/${formatTokens(figures.context.window, ASCII_UNITS)}`;
554
+ parts.push(`${labels.context} ${occupancy}`);
555
+ }
556
+ return parts.join(" · ");
557
+ }
558
+ /**
559
+ * Build the reply for one session, or nothing when its projections cannot supply it.
560
+ * @param ctx - plugin context owning the services the reply reads.
561
+ * @param session - session whose folded state is reported.
562
+ * @param labels - copy for each figure.
563
+ * @returns the reply text, or undefined when the token meter does not project usage.
564
+ */
565
+ function buildReport(ctx, session, labels) {
566
+ const usage = readProjection(ctx, session, "tokenUsage")?.totals;
567
+ if (usage === void 0) return void 0;
568
+ const selection = readProjection(ctx, session, "modelSelection");
569
+ const pricing = readProjection(ctx, session, "tokenPricing");
570
+ const pressure = readProjection(ctx, session, "contextPressure");
571
+ const model = selection?.lastUsed?.model ?? selection?.pending?.model;
572
+ const price = model === void 0 || pricing === void 0 ? void 0 : priceForModel(model, pricing.prices);
573
+ const cost = price === void 0 ? void 0 : estimateCostCny(usage, price);
574
+ const used = pressure?.pressureTokens;
575
+ return renderUsageReport(usage, labels, {
576
+ ...cost === void 0 ? {} : { cost },
577
+ currencySymbol: pricing?.currencySymbol ?? "",
578
+ ...used === void 0 ? {} : { context: {
579
+ used,
580
+ ...pressure?.contextWindow === void 0 ? {} : { window: pressure.contextWindow }
581
+ } }
582
+ });
583
+ }
584
+ /**
585
+ * Register the usage command on the interactive command surface.
586
+ *
587
+ * The registration waits for the commands service through its own fiber, so a
588
+ * profile without a command surface (headless, ACP) keeps the readout and the
589
+ * backfill without holding this plugin pending.
590
+ * @param ctx - plugin context owning the command registration.
591
+ * @param options - registered command name and reply copy.
592
+ */
593
+ function registerUsageCommand(ctx, options) {
594
+ ctx.inject(["commands"], (commandCtx) => {
595
+ commandCtx.commands.register({
596
+ name: options.name,
597
+ description: "Show this session's token usage, estimated cost, and context occupancy",
598
+ handler: ({ agent }) => {
599
+ const text = buildReport(commandCtx, agent.session, options.labels);
600
+ return text === void 0 ? {
601
+ kind: "error",
602
+ text: "Token usage is unavailable: this profile registers no usage projection for the session."
603
+ } : {
604
+ kind: "success",
605
+ text
606
+ };
607
+ }
608
+ });
609
+ });
610
+ }
611
+ /**
612
+ * Whether the request's own human input is the trigger line.
613
+ *
614
+ * The harness appends instruction, context, and skill-catalog messages after the
615
+ * typed prompt, all shaped as user-role messages; only the prompt carries
616
+ * `source.kind === 'user'`. Comparing that message's text blocks exactly keeps a
617
+ * prompt that merely mentions the trigger from matching.
618
+ * @param messages - the request's model-visible messages.
619
+ * @param trigger - exact trigger line.
620
+ * @returns true when the newest human input is the trigger.
621
+ */
622
+ function triggerRequested(messages, trigger) {
623
+ for (const message of messages.toReversed()) {
624
+ if (message.role !== "user" || message.source.kind !== "user") continue;
625
+ return message.content.filter((block) => block.type === "text").map((block) => block.text.trim()).some((text) => text === trigger);
626
+ }
627
+ return false;
628
+ }
629
+ /**
630
+ * Shape the report as one complete text answer for the loop's stream grammar.
631
+ *
632
+ * The stream deliberately carries no usage sample. A settlement would be the
633
+ * newest one the token meter sees, and its `contextPressure` fold takes the
634
+ * occupancy numerator from exactly that sample: a synthetic zero would read as
635
+ * an empty context even though the conversation is untouched.
636
+ * @param text - the report to answer with.
637
+ * @returns a stream the loop assembles into one assistant message.
638
+ */
639
+ function reportStream(text) {
640
+ const chunks = [
641
+ {
642
+ type: "block-start",
643
+ index: 0,
644
+ blockType: "text"
645
+ },
646
+ {
647
+ type: "text-delta",
648
+ index: 0,
649
+ text
650
+ },
651
+ {
652
+ type: "block-end",
653
+ index: 0,
654
+ block: {
655
+ type: "text",
656
+ text
657
+ }
658
+ },
659
+ {
660
+ type: "finish",
661
+ reason: { kind: "stop" }
662
+ }
663
+ ];
664
+ let index = 0;
665
+ return { [Symbol.asyncIterator]: () => ({ next: () => Promise.resolve(index < chunks.length ? {
666
+ done: false,
667
+ value: chunks[index++]
668
+ } : {
669
+ done: true,
670
+ value: void 0
671
+ }) }) };
672
+ }
673
+ /**
674
+ * Answer the trigger at the model boundary, for clients that can only send
675
+ * messages rather than execute commands.
676
+ * @param ctx - plugin context owning the request middleware and the projections.
677
+ * @param options - trigger line and reply copy.
678
+ */
679
+ function installUsageCommand(ctx, options) {
680
+ ctx.on("llm/stream", (request, next) => {
681
+ if (!triggerRequested(request.messages, options.trigger)) return next();
682
+ const session = request.sessionId === void 0 ? void 0 : ctx.sessions.get(request.sessionId);
683
+ if (session === void 0) return next();
684
+ const text = buildReport(ctx, session, options.labels);
685
+ return text === void 0 ? next() : reportStream(text);
686
+ });
687
+ }
688
+ //#endregion
689
+ //#region lib/types/projection.js
690
+ /**
691
+ * The `tokenPricing` and `tokenCostBackfill` session-projection units: the
692
+ * deployment's token price table plus the coverage its history backfill has
693
+ * over this session's routes, projected to the browser so the composer readout
694
+ * can price durable usage and point at the routes it cannot price.
695
+ *
696
+ * Browser plugin rows carry no `config`, so a host-side projection is the
697
+ * delivery path for a client-side readout's pricing. The pricing unit is a
698
+ * constant: it ignores every event, returns the same state reference, and
699
+ * therefore publishes one value per session. The backfill unit folds
700
+ * `request/header` events into the set of routes the backfill price table
701
+ * misses, and derives the report path from the session header's working
702
+ * directory.
703
+ *
704
+ * @module @jerry_chzy/dsh-token-usage/projection
705
+ */
706
+ const modelPriceSchema = z$1.object({
707
+ inputMiss: z$1.number().min(0),
708
+ inputHit: z$1.number().min(0),
709
+ output: z$1.number().min(0)
710
+ }).strict();
711
+ const pricingSchema = z$1.object({
712
+ prices: z$1.record(z$1.string(), modelPriceSchema),
713
+ currencySymbol: z$1.string()
714
+ }).strict();
715
+ const backfillSchema$1 = z$1.object({
716
+ hasPricedUsage: z$1.boolean(),
717
+ unpricedRoutes: z$1.array(z$1.string()),
718
+ filePath: z$1.string().nullable()
719
+ }).strict();
720
+ /**
721
+ * Build the pricing projection unit for one resolved deployment table.
722
+ * @param pricing - prices keyed by model-id prefix.
723
+ * @param currencySymbol - symbol prefixed to the readout's cost figure.
724
+ * @returns the unit definition the host registers on `ctx.sessionProjections`.
725
+ */
726
+ function createPricingProjectionDefinition(pricing, currencySymbol) {
727
+ const value = {
728
+ prices: pricing,
729
+ currencySymbol
730
+ };
731
+ return {
732
+ key: "tokenPricing",
733
+ stateVersion: 1,
734
+ stateSchema: pricingSchema,
735
+ init: () => value,
736
+ apply: (state) => state,
737
+ wire: {
738
+ viewSchema: pricingSchema,
739
+ view: (state) => state
740
+ }
741
+ };
742
+ }
743
+ /**
744
+ * Build the backfill-coverage projection unit for one resolved price table.
745
+ *
746
+ * Only `request/header` can introduce a route, so every other event returns the
747
+ * same state reference and publishes nothing. The report path comes from the
748
+ * session header rather than from the running process: a session created in
749
+ * another directory must point at that directory's file, and a header without
750
+ * a working directory points nowhere.
751
+ * @param pricing - backfill prices keyed by model-id prefix.
752
+ * @returns the unit definition the host registers on `ctx.sessionProjections`.
753
+ */
754
+ function createBackfillProjectionDefinition(pricing) {
755
+ return {
756
+ key: "tokenCostBackfill",
757
+ stateVersion: 1,
758
+ stateSchema: backfillSchema$1,
759
+ init: (header) => ({
760
+ hasPricedUsage: false,
761
+ unpricedRoutes: [],
762
+ filePath: header.cwd === void 0 ? null : join(header.cwd, BACKFILL_FILE_NAME)
763
+ }),
764
+ apply: (state, event) => {
765
+ if (event.type !== "request/header") return state;
766
+ const { provider, model } = event.data.header.config;
767
+ if (priceForModel(model, pricing) !== void 0) return state.hasPricedUsage ? state : {
768
+ ...state,
769
+ hasPricedUsage: true
770
+ };
771
+ const route = `${provider}/${model}`;
772
+ if (state.unpricedRoutes.includes(route)) return state;
773
+ return {
774
+ ...state,
775
+ unpricedRoutes: [...state.unpricedRoutes, route]
776
+ };
777
+ },
778
+ wire: {
779
+ viewSchema: backfillSchema$1,
780
+ view: (state) => state
781
+ }
782
+ };
783
+ }
784
+ //#endregion
785
+ //#region lib/types/index.js
786
+ /**
787
+ * Token-usage readout plugin, node half: registers the deployment's
788
+ * `tokenPricing` session projection so the browser readout can price durable
789
+ * usage, plus the `tokenCostBackfill` projection and the one-time history
790
+ * backfill that writes a `TOKEN_COST.md` per session working directory. It also
791
+ * registers the `/usage` command, which answers from session state without a
792
+ * provider request or a usage settlement. The plugin owns no session state.
793
+ *
794
+ * @module @jerry_chzy/dsh-token-usage
795
+ */
796
+ /** `HH:MM` in 24-hour clock time. */
797
+ const CLOCK = /^(?:[01]\d|2[0-3]):[0-5]\d$/;
798
+ /**
799
+ * Schema for one `[offPeak, peak]` price pair.
800
+ *
801
+ * Schemastery widens tuple elements to optional, so the validated two-element
802
+ * list is asserted back to the pair the config type declares; the runtime
803
+ * requirement lives on the two element schemas.
804
+ * @returns the pair schema.
805
+ */
806
+ const pricePair = () => z.tuple([z.number().min(0).required(), z.number().min(0).required()]).required();
807
+ const backfillSchema = z.object({
808
+ enabled: z.boolean().default(true),
809
+ pricing: z.dict(z.object({
810
+ inputMiss: pricePair(),
811
+ inputHit: pricePair(),
812
+ output: pricePair()
813
+ })).default({ ...DEFAULT_BACKFILL_PRICING }),
814
+ peakHours: z.array(z.object({
815
+ days: z.array(z.number().min(0).max(6).required()).required(),
816
+ start: z.string().pattern(CLOCK).required(),
817
+ end: z.string().pattern(CLOCK).required()
818
+ })).default([...DEFAULT_PEAK_HOURS])
819
+ });
820
+ const commandSchema = z.object({
821
+ enabled: z.boolean().default(true),
822
+ name: z.string().pattern(/^[a-z][a-z0-9_-]*$/u).default("usage"),
823
+ labels: z.object({
824
+ total: z.string().default(DEFAULT_REPORT_LABELS.total),
825
+ input: z.string().default(DEFAULT_REPORT_LABELS.input),
826
+ cacheRead: z.string().default(DEFAULT_REPORT_LABELS.cacheRead),
827
+ cacheWrite: z.string().default(DEFAULT_REPORT_LABELS.cacheWrite),
828
+ output: z.string().default(DEFAULT_REPORT_LABELS.output),
829
+ context: z.string().default(DEFAULT_REPORT_LABELS.context)
830
+ }).default({ ...DEFAULT_REPORT_LABELS })
831
+ });
832
+ /** Validated readout configuration. */
833
+ const Config = z.object({
834
+ pricing: z.dict(z.object({
835
+ inputMiss: z.number().min(0),
836
+ inputHit: z.number().min(0),
837
+ output: z.number().min(0)
838
+ })).default({ ...DEFAULT_PRICING }),
839
+ currencySymbol: z.string().default("¥"),
840
+ backfill: backfillSchema,
841
+ command: commandSchema
842
+ });
843
+ /** The projection registry is the plugin's whole purpose; without it the fiber stays pending. */
844
+ const inject = ["sessionProjections", "sessions"];
845
+ /**
846
+ * Register the deployment pricing table and, unless disabled, the backfill
847
+ * coverage projection plus the one-pass history backfill. Both registrations
848
+ * are effects on this plugin's fiber, so unloading removes the keys for every
849
+ * session; the backfill's own effect owns an abort controller that cancels the
850
+ * pass on unload, and a pass failure is logged rather than propagated.
851
+ * @param ctx - registrant context carrying the projection registry.
852
+ * @param config - validated plugin config (schema defaults applied).
853
+ */
854
+ function apply(ctx, config = Config({})) {
855
+ ctx.sessionProjections.register(createPricingProjectionDefinition(config.pricing ?? DEFAULT_PRICING, config.currencySymbol ?? "¥"));
856
+ const command = config.command ?? {};
857
+ if (command.enabled !== false) {
858
+ const name = command.name ?? "usage";
859
+ const labels = {
860
+ ...DEFAULT_REPORT_LABELS,
861
+ ...command.labels
862
+ };
863
+ registerUsageCommand(ctx, {
864
+ name,
865
+ labels
866
+ });
867
+ installUsageCommand(ctx, {
868
+ trigger: `/${name}`,
869
+ labels
870
+ });
871
+ }
872
+ const backfill = config.backfill ?? {};
873
+ if (backfill.enabled === false) return;
874
+ const pricing = backfill.pricing ?? DEFAULT_BACKFILL_PRICING;
875
+ ctx.sessionProjections.register(createBackfillProjectionDefinition(pricing));
876
+ const peakHours = backfill.peakHours ?? DEFAULT_PEAK_HOURS;
877
+ ctx.effect(() => {
878
+ const controller = new AbortController();
879
+ runCostBackfill(ctx, {
880
+ pricing,
881
+ peakHours
882
+ }, controller.signal).catch((error) => {
883
+ ctx.logger.warn(`ui-token-usage: the TOKEN_COST.md backfill failed: ${String(error)}`);
884
+ });
885
+ return () => {
886
+ controller.abort();
887
+ };
888
+ }, "ui-token-usage: TOKEN_COST.md backfill");
889
+ }
890
+ //#endregion
891
+ export { Config, apply, inject };