Open History to see the last commit
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;
25}
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 );
43}
44
45export function tokenCount(value: unknown): number {
46 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
47}
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;
53}
54
55export type SelectedFields = { readonly [key: string]: true | SelectedFields };
56
57export interface TranscriptUsageFormat<State> {
58 readonly selectFields: SelectedFields;
59 /**
60 * ASCII substrings, at least one of which every line that matters contains.
61 * Lines that only update `State` must match too.
62 */
63 readonly usageMarkers: readonly [string, ...string[]];
64 parseLine(line: string, state: State): readonly UsageRecord[];
65 parseProjected(projected: unknown, state: State): readonly UsageRecord[];
66 /** Cumulative malformed or inconsistent usage records, including skipped records. */
67 readMalformedRecords?(state: State): number;
68 /**
69 * Present for formats whose records depend on earlier lines. The state at a
70 * resume point is persisted in the scan cache through `schema`, so a grown
71 * file resumes with it. Absent means every line stands alone.
72 */
73 readonly state?: {
74 readonly initial: () => State;
75 readonly schema: Schema.Codec<State, unknown>;
76 };
77 /**
78 * Whether one session's records may appear in several files, such as a
79 * rollout copied when it moves. The server then keys those sessions'
80 * records for cross-file de-duplication.
81 */
82 readonly sharedSessionsAcrossFiles?: true;
83}
84
85export interface ProviderUsageInstance<Config> {
86 readonly instanceId: ProviderInstanceId;
87 /**
88 * `undefined` when the stored config does not decode. The instance still has
89 * history on disk, so readers that need no config read it anyway.
90 */
91 readonly config: Config | undefined;
92 readonly environment: NodeJS.ProcessEnv;
93 readonly configured: boolean;
94}
95
96export interface ProviderUsageScan {
97 readonly dir: string;
98 readonly volumeId?: string;
99 readonly hostId?: string;
100 readonly status?: UsageSource["status"];
101 readonly message?: string;
102 readonly action?: UsageSource["action"];
103 readonly files:
104 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
105 | null;
106 readonly refreshing?: true;
107}
108
109export interface ProviderUsageScanInput<Config> {
110 readonly instances: ReadonlyArray<ProviderUsageInstance<Config>>;
111 readonly settings: ServerSettings;
112 readonly windowStartMs: number;
113 readonly retentionCutoffMs: number;
114 readonly awaitRefresh: boolean;
115}
116
117export type ProviderUsageReader<Config, R> =
118 | {
119 readonly kind: "transcripts";
120 readonly provider: UsageProviderKind;
121 readonly format: TranscriptUsageFormat<unknown>;
122 readonly resolveServiceTiers?: (
123 records: readonly UsageRecord[],
124 ) => Effect.Effect<ReadonlyMap<UsageRecord, UsageSpeed>, never, R>;
125 readonly directories: (
126 instance: ProviderUsageInstance<Config>,
127 ) => Effect.Effect<
128 ReadonlyArray<{ readonly dir: string; readonly fileName?: string }>,
129 never,
130 R
131 >;
132 }
133 | {
134 readonly kind: "scan";
135 readonly provider: UsageProviderKind;
136 /** Fails only when the whole usage read cannot go on; an unreadable source is a status. */
137 readonly scan: (
138 input: ProviderUsageScanInput<Config>,
139 ) => Effect.Effect<ReadonlyArray<ProviderUsageScan>, UsageReadError, R>;
140 };