/** * What the session has spent: cumulative tokens, and the money they cost. * * The numbers come from the adapter's own accounting, folded out of * `assistant/message` events rather than counted here, so what the status line * reports is what dshline prices those reports at: a billed route's own rates, * or a signed-in route's public API equivalent — see {@link PricingBasis}. * Folding happens in the runner's shared projection, which means a resumed * session recovers its totals by replaying its log — there is no second * restore path that could disagree with the live one. * * Nothing in this module knows about a terminal, a Context, or an agent, so all * of it is testable directly. * @module dshline/usage */ import type { TokenUsage } from '@deepseek-ai/dsh-llm'; import type { ProjectionSnapshot } from '@deepseek-ai/dsh-session-projection'; import type { SessionPerformance } from './performance.ts'; /** * Prices for one route, in dollars per million tokens. * * Cached reads are their own rate because providers charge them at a small * fraction of an uncached one — DeepSeek bills a cache hit at a thirtieth of a * miss — and a session that reuses a long prompt is mostly cache hits. Pricing * those as misses would overstate a working day by most of it. */ export interface RateSet { /** Uncached input, which DeepSeek's price list calls a cache MISS. */ input: number; /** Cache reads, its cache HIT; falls back to {@link RateSet.input}. */ cachedInput?: number; /** * Cache writes. * * Falls back to {@link RateSet.input} rather than to the cached rate, because * on DeepSeek a write IS a miss — the tokens are being read for the first time * and stored on the way past — so the miss rate is the right one, not a * cheaper one that happens to have `cache` in its name. */ cachedWrite?: number; /** Output, reasoning included; the adapter reports reasoning inside it. */ output: number; } /** One rate tier: a rate set that applies once a request's input passes a bound. */ export interface RateTier { /** A request whose input is strictly ABOVE this token count prices at {@link RateTier.rates}. */ inputTokensAbove: number; /** The rates for a request that crosses the bound, applied to the WHOLE request. */ rates: RateSet; } /** * One route's prices, and how they change with the clock or the request size. * * The bare fields are the rate that applies most of the day, and `peak` is the * exception. That is the way round it is because DeepSeek's peak is the narrow * window — a few hours of the morning — so the common case reads as the plain * one, and a table written without a `peak` block simply prices the same all day * rather than silently picking one column of a two-column price list. * * A `tier` is the same kind of exception for request size: OpenAI prices * requests whose input passes 272k tokens at a higher rate set, applied to the * whole request. No shipped model has both a peak and a tier; when a tier * applies it replaces whatever the window selected. */ export interface ModelRates extends RateSet { /** Prices during a peak window; the bare fields apply outside one. */ peak?: RateSet; /** Rate set for a request whose input crosses {@link RateTier.inputTokensAbove}. */ tier?: RateTier; } /** * What one entry's rates represent for its route. * * `billed` is an ordinary route whose rates are its own published billing. * `api-equivalent` is a signed-in/OAuth route valued at the corresponding * public API rates — what the provider's own pay-as-you-go API would have * charged for these exact tokens. It is never the user's subscription charge * or Codex credits, which dshline deliberately does not account. */ export type PricingBasis = 'billed' | 'api-equivalent'; /** One route's price, and the basis it is offered on. */ export interface PricingEntry { /** The rates in force for this entry. */ rates: ModelRates; /** Whether these rates are the route's billing or its API-equivalent. */ basis: PricingBasis; } /** Rates by route, as {@link pricingKey} builds the key. */ export type PricingTable = ReadonlyMap; /** Minutes past midnight UTC, as a half-open range. */ export interface PeakWindow { /** First minute of the window. */ from: number; /** First minute after it. */ to: number; } /** * The lookup key for one route. * @param provider - provider route key. * @param model - provider-owned model id. * @returns the key a {@link PricingTable} is indexed by. */ export declare function pricingKey(provider: string, model: string): string; /** * Read a pricing table out of plugin configuration. * * Deliberately total: an entry that does not describe a price is dropped rather * than thrown over. Prices are a convenience on a status line, and a typo in a * machine-local config file must not be the reason a terminal refuses to start. * * A configured entry carries the `billed` basis by default — the reading for a * route dshline does not ship, where writing rates is a reader stating what * that route charges. {@link pricingFrom} then keeps the shipped basis when a * configured entry REPLACES one this interface ships: correcting an * `openai-codex/...` rate does not turn the OAuth route into pay-as-you-go, so * its money still reads `API-equivalent cost`. * @param raw - the `pricing` value from the plugin's config, of any shape. * @returns the entries that were complete and usable. */ export declare function parsePricing(raw: unknown): PricingTable; /** * The published rates, with configuration layered over them. * * A configured entry REPLACES the shipped one for that key rather than merging * field by field. Half a correction is the dangerous shape: someone fixing an * output price would not expect the input price beside it to stay at whatever * this release was built with. * * Replacement is about the NUMBERS. What the entry represents — its * {@link PricingBasis} — belongs to the route, so a correction of a shipped * `api-equivalent` entry keeps that basis, and only a route dshline does not * ship reads as the default `billed`. * @param raw - the `pricing` value from the plugin's config, of any shape. * @returns every route this session can price. */ export declare function pricingFrom(raw: unknown): PricingTable; /** * Read peak windows out of plugin configuration. * * An unreadable list falls back to the published windows rather than to none. * Falling back to none would price a whole session off-peak, which is the * cheaper answer and therefore the one nobody notices is wrong. * @param raw - the `peakHoursUtc` value from the plugin's config, of any shape. * @returns the windows to charge the standard rate in. */ export declare function parsePeakWindows(raw: unknown): readonly PeakWindow[]; /** * Whether a moment falls in a peak window. * * Windows are read in UTC because that is the timezone a provider publishes its * schedule in; reading them in the machine's zone would move everyone's prices * by their offset. A window whose end is before its start wraps midnight. * @param at - unix epoch milliseconds. * @param windows - the peak windows. * @returns whether the standard rate applies. */ export declare function isPeak(at: number, windows: readonly PeakWindow[]): boolean; /** Cumulative session usage as the status line reports it. */ export interface UsageReading { /** Every prompt token sent: uncached, cache reads, and cache writes together. */ inputTokens: number; /** Every token generated, reasoning included. */ outputTokens: number; /** Dollars priced across every basis, or undefined when no observed message had a known rate. */ costUsd: number | undefined; /** * Whether some observed usage could not be priced, so the amounts in this * reading are a floor rather than the total. */ partial: boolean; /** Money at `billed` entries, or undefined when no message priced that way. */ billedUsd: number | undefined; /** Money at `api-equivalent` entries, or undefined when no message priced that way. */ apiEquivalentUsd: number | undefined; } /** * Running totals for one session. * * Cost is accrued per message, at the rate of the model that produced *that* * message and the rate in force at the moment it ran. Totalling the tokens first * and pricing them once at the end would bill the whole session at whichever * model happened to be selected last, on whichever side of the peak boundary the * reader happened to look. * * The money is kept in two subtotals, one per {@link PricingBasis}. A session * may switch routes, and a billed route's total must not be labelled * API-equivalent (or the other way round), so the fold remembers which basis * each message priced at; the inspector decides what labels truthfully apply. */ export declare class SessionUsage { private readonly pricing; private readonly peakWindows; private inputTokens; private outputTokens; private billedUsd; private apiEquivalentUsd; private billed; private apiEquivalent; private unpriced; /** * @param pricing - rates by route, usually from plugin configuration. * @param peakWindows - when the standard rate applies. */ constructor(pricing: PricingTable, peakWindows?: readonly PeakWindow[]); /** * The price and its basis for one route, if any are known. * * An exact route is preferred, then the model on its own. The fallback is what * lets one entry cover a model wherever it is served, and it is deliberately * only reachable from configuration: nothing shipped is keyed that way, so a * gateway never inherits the direct provider's price list by accident. * @param provider - the route. * @param model - the model id. * @returns the price entry, or undefined. */ private entryFor; /** * Fold one message's accounting into the totals. * * The buckets are disjoint: `inputTokens` counts uncached input ONLY, with cache * reads and writes reported beside it, and `reasoningTokens` is already inside * `outputTokens`. Adding reasoning again is the mistake this comment exists to * name — it would inflate output on exactly the models people run it for. * @param usage - the adapter's accounting for one assistant message. * @param provider - the route that produced it, when known. * @param model - the model that produced it, when known. * @param at - when the message was logged, in unix epoch milliseconds. */ observe(usage: TokenUsage, provider: string | undefined, model: string | undefined, at: number): void; /** The totals so far. */ get reading(): UsageReading; } /** * Provider-reported cumulative usage, in the four disjoint buckets Harness * publishes. * * These come from the `tokenUsage` session projection, whose scope is the * agent's own model requests: it folds the usage every durable Assistant * settlement reports — an `assistant/message`'s own record, or the last usage * sample embedded in an `assistant/message` or `assistant/attempt` stream — * across the complete durable log, replacing a repeated sample for one attempt * and re-counting after `llm/retry-started`. Compaction and surface replacement * do not erase earlier billing, so a request whose messages were later * summarized away is still counted. * * An AUXILIARY provider call is not. A compaction's summarizer reports its own * usage on the `compaction/summary` event, which this projection does not fold — * confirmed against upstream's own projection test, which appends that event and * asserts the buckets do not move. * * This scope is Harness's, and dshline does not restate it as its own: the * pricing fold in {@link SessionUsage} observes finalized `assistant/message` * usage only, because it also needs the route and the moment to price by. The * two folds can therefore differ — a failed attempt whose stream reported usage * settles as `assistant/attempt` and is counted here and nowhere else. See * {@link usageInspection}. */ export interface UsageBuckets { /** Prompt tokens the provider billed as a cache miss. */ readonly uncachedInput: number; /** Prompt tokens served from the provider's cache. */ readonly cacheRead: number; /** Prompt tokens written into it on the way past. */ readonly cacheWrite: number; /** The three prompt buckets together. */ readonly input: number; /** Generated tokens, reasoning included. */ readonly output: number; } /** Everything the `/usage` inspector can truthfully report. */ export interface UsageInspection { /** Whether this profile mounted the generic projection infrastructure. */ readonly projections: boolean; /** Harness's own cumulative buckets, when its usage unit is registered. */ readonly buckets: UsageBuckets | undefined; /** dshline's own pricing fold: the tokens it priced, and the money. */ readonly reading: UsageReading; /** Share of prompt tokens served from cache; see {@link cacheReadShare}. */ readonly cacheReadShare: number | undefined; /** * How the session ran, from Harness's `sessionStats` projection. * * Part of this reading rather than a separate one because it comes from the * SAME projection cut as {@link UsageInspection.buckets}: the two * projection-backed halves of the report cannot describe two different * moments. {@link UsageInspection.reading} is the exception and stays one — * it is dshline's own pricing fold, not a value in that snapshot. */ readonly performance: SessionPerformance; } /** * Read cumulative usage from Harness's projection and dshline's own fold. * * Both, on purpose, because their scopes differ and neither subsumes the other. * Harness's `tokenUsage` is the authority on what the provider reported for the * agent's requests across the whole durable log. dshline's {@link SessionUsage} * exists for the one thing that projection cannot retain: cost, which depends on * the route each message ran on and the price in force at the moment it ran. The * buckets are therefore reported from Harness and the money from dshline. * * The two are NOT claimed to share one scope, and on an ordinary session they * need not. Harness folds every durable Assistant settlement's usage — a failed * attempt's `assistant/attempt` included — replacing a repeated sample for one * attempt and re-counting after `llm/retry-started`; dshline's pricing fold sees * finalized `assistant/message` usage only, because pricing needs the route and * the moment beside the tokens. A retried request therefore counts an attempt in * the buckets that the money never priced. Each figure is reported as what its * own authority says, and neither is divided into the other. * * When the projection is absent, the inspector falls back to dshline's own * totals rather than leaving a hole — without the cache split, and without * claiming it is the same accounting. * * Performance comes from the same cut, and has no dshline fold behind it at all * — see {@link SessionPerformance}. A profile without the `sessionStats` unit * reports no performance figures rather than reconstructed ones. * @param snapshot - the authoritative projection cut, or undefined when the profile mounts no registry. * @param reading - dshline's current fold. * @returns the inspector's reading. */ export declare function usageInspection(snapshot: ProjectionSnapshot | undefined, reading: UsageReading): UsageInspection; /** * Harness's cumulative buckets for one projection cut, in dshline's shape. * * The single place the projection's four numbers are read, so the inspector and * the status line cannot end up disagreeing about what the same cut said. The * projection is the authority; nothing here counts a token. * @param snapshot - the authoritative projection cut, or undefined when the profile mounts no registry. * @returns the buckets, or undefined when the profile's usage unit is not registered. */ export declare function usageBuckets(snapshot: ProjectionSnapshot | undefined): UsageBuckets | undefined; /** * Share of prompt tokens the provider served from cache, 0 to 1. * * `cacheRead / (uncachedInput + cacheRead + cacheWrite)` over Harness's * cumulative model-request usage, derived from {@link usageBuckets} and nothing * else — so it is a share of THAT accounting, and not of the totals dshline * priced. Deliberately NOT a provider-reported hit rate either: Harness * publishes token buckets, and naming a ratio after a metric nobody reported * would invite it to be compared with one. * * A cut with no prompt tokens at all has NO share rather than `0%`: there is no * denominator, and reporting zero would claim a cold cache for a session that * has not asked anything yet. * @param buckets - one cut's buckets, or undefined. * @returns the ratio, or undefined when there is nothing to divide. */ export declare function cacheReadShare(buckets: UsageBuckets | undefined): number | undefined; /** * A cache-read share as a percentage, at one decimal. * * One decimal because the interesting range is the top of it: a long session * reusing one prompt sits at ninety-nine-point-something, and whole percents * report every one of those as `100%` — a figure that reads as "nothing was * missed" when a fifth of a percent was. A round value still prints without a * trailing `.0`, which says the same thing in fewer columns. * * `0%` and `100%` are reported only for a share that really is none or all of * the prompt. A share between an endpoint and the printable resolution is * reported as a bound — {@link SHARE_BELOW_RESOLUTION}, * {@link SHARE_ABOVE_RESOLUTION} — rather than moved to the nearest printable * number: the display's precision is allowed to run out, but the value is not * allowed to change on the way to the screen. * @param share - the ratio, 0 to 1, or undefined when there is no denominator. * @returns e.g. `99.8%`, `>99.9%`, `100%`, or undefined when there is nothing true to report. */ export declare function formatCacheShare(share: number | undefined): string | undefined; /** * The status line's cache-read segment. * * Labelled `CR` because the line is measured in columns and the figure is a * convenience reading; the inspector spells the same fact out in full. It * follows the reader's usage preference, since `off` asks for the status line to * be left to the context reading rather than for one usage figure of three. * * It reports Harness's own cumulative model-request usage, which is not the * accounting behind the `↑`/`↓` totals beside it — see {@link usageInspection} — * and it says how much of the prompt came from cache, not what that cost: how * much a cache read saves is a route's own pricing question. * @param share - the ratio, or undefined when there is no denominator. * @param mode - how much of the usage reading the reader wants. * @returns e.g. `CR 99.8%`, `CR >99.9%`, or undefined when there is nothing to report. */ export declare function formatCacheRead(share: number | undefined, mode: UsageMode): string | undefined; /** * A dollar amount for the inspector, at the same precision the status line uses. * @param value - dollars. * @returns e.g. `$0.0018`, `$1.24`. */ export declare function usageCost(value: number): string; /** How much of the usage reading the status line carries. */ export type UsageMode = 'cost' | 'tokens' | 'off'; /** The modes `/usage` offers, in the order the picker lists them. */ export declare const USAGE_MODES: readonly { id: UsageMode; name: string; description: string; }[]; /** * The mode an argument names, if any. * @param argument - the text after the command name. * @returns the matching mode, or undefined when nothing matched. */ export declare function resolveUsageMode(argument: string): UsageMode | undefined; /** * The status line's usage segment. * * The cost is omitted entirely when no rate is configured for the models that * ran, rather than shown as zero: the same rule the context bar follows, where * nothing is drawn before there is something true to draw. A `~` marks a total * that is a floor because part of the session had no rates. * @param reading - the current totals. * @param mode - how much of it to report. * @returns e.g. `↑8.8k ↓1.6k $0.018`, or undefined when the mode is `off`. */ export declare function formatUsage(reading: UsageReading, mode: UsageMode): string | undefined; //# sourceMappingURL=usage.d.ts.map