Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

usage.ts

130 lines4.3 KB

1import type {
2 ProviderInstanceId,
3 ServerSettings,
4 UsageProviderKind,
5 UsageReadError,
6 UsageSource,
7 UsageTokenTotals,
8} from "@t3tools/contracts";
9import type * as Effect from "effect/Effect";
10import type * as Schema from "effect/Schema";
11​
12export type UsageSpeed = "standard" | "fast" | "ultrafast";
13​
14export interface UsageRecord {
15 readonly provider: UsageProviderKind;
16 readonly timestampMs: number;
17 readonly model: string;
18 readonly rateModel?: string;
19 readonly sessionId: string;
20 readonly totals: UsageTokenTotals;
21 readonly reportedCostUsd: number | null;
22 readonly speed: UsageSpeed;
23 readonly unresolvedServiceTierTurnId?: string;
24 readonly dedupeKey: string | null;
26​
27export const EMPTY_TOTALS: UsageTokenTotals = {
28 uncachedInputTokens: 0,
29 cachedInputTokens: 0,
30 cacheCreationTokens: 0,
31 outputTokens: 0,
32 reasoningTokens: 0,
33};
34​
35export function totalTokens(totals: UsageTokenTotals): number {
36 // reasoningTokens is a subset of outputTokens and must not be added again.
37 return (
38 totals.uncachedInputTokens +
39 totals.cachedInputTokens +
40 totals.cacheCreationTokens +
41 totals.outputTokens
42 );
44​
45export function tokenCount(value: unknown): number {
46 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
48​
49export function parseTimestampMs(value: unknown): number | null {
50 if (typeof value !== "string") return null;
51 const parsed = Date.parse(value);
52 return Number.isNaN(parsed) ? null : parsed;
54​
55export type SelectedFields = { readonly [key: string]: true | SelectedFields };
56​
57export interface TranscriptUsageFormat<State> {
58 readonly selectFields: SelectedFields;
59 /** ASCII markers must match every relevant line, including state-only updates. */
60 readonly usageMarkers: readonly [string, ...string[]];
61 parseLine(line: string, state: State): readonly UsageRecord[];
62 parseProjected(projected: unknown, state: State): readonly UsageRecord[];
63 /** Cumulative malformed or inconsistent usage records, including skipped records. */
64 readMalformedRecords?(state: State): number;
65 /**
66 * Present for formats whose records depend on earlier lines. The state at a
67 * resume point is persisted in the scan cache through `schema`, so a grown
68 * file resumes with it. Absent means every line stands alone.
69 */
70 readonly state?: {
71 readonly initial: () => State;
72 readonly schema: Schema.Codec<State, unknown>;
73 };
74 /** Enable cross-file deduplication when session records can appear in multiple files. */
75 readonly sharedSessionsAcrossFiles?: true;
77​
78export interface ProviderUsageInstance<Config> {
79 readonly instanceId: ProviderInstanceId;
80 /** Undefined for invalid stored config; config-independent readers should still read history. */
81 readonly config: Config | undefined;
82 readonly environment: NodeJS.ProcessEnv;
83 readonly configured: boolean;
85​
86export interface ProviderUsageScan {
87 readonly dir: string;
88 readonly volumeId?: string;
89 readonly hostId?: string;
90 readonly status?: UsageSource["status"];
91 readonly message?: string;
92 readonly action?: UsageSource["action"];
93 readonly files:
94 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
95 | null;
96 readonly refreshing?: true;
98​
99export interface ProviderUsageScanInput<Config> {
100 readonly instances: ReadonlyArray<ProviderUsageInstance<Config>>;
101 readonly settings: ServerSettings;
102 readonly windowStartMs: number;
103 readonly retentionCutoffMs: number;
104 readonly awaitRefresh: boolean;
106​
107export type ProviderUsageReader<Config, R> =
108 | {
109 readonly kind: "transcripts";
110 readonly provider: UsageProviderKind;
111 readonly format: TranscriptUsageFormat<unknown>;
112 readonly resolveServiceTiers?: (
113 records: readonly UsageRecord[],
114 ) => Effect.Effect<ReadonlyMap<UsageRecord, UsageSpeed>, never, R>;
115 readonly directories: (
116 instance: ProviderUsageInstance<Config>,
117 ) => Effect.Effect<
118 ReadonlyArray<{ readonly dir: string; readonly fileName?: string }>,
119 never,
120 R
121 >;
122 }
123 | {
124 readonly kind: "scan";
125 readonly provider: UsageProviderKind;
126 /** Fails only when the whole usage read cannot go on; an unreadable source is a status. */
127 readonly scan: (
128 input: ProviderUsageScanInput<Config>,
129 ) => Effect.Effect<ReadonlyArray<ProviderUsageScan>, UsageReadError, R>;
130 };