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 dedupeKey: string | null;
24}
25
26export const EMPTY_TOTALS: UsageTokenTotals = {
27 uncachedInputTokens: 0,
28 cachedInputTokens: 0,
29 cacheCreationTokens: 0,
30 outputTokens: 0,
31 reasoningTokens: 0,
32};
33
34export function totalTokens(totals: UsageTokenTotals): number {
35 // reasoningTokens is a subset of outputTokens and must not be added again.
36 return (
37 totals.uncachedInputTokens +
38 totals.cachedInputTokens +
39 totals.cacheCreationTokens +
40 totals.outputTokens
41 );
42}
43
44export function tokenCount(value: unknown): number {
45 return typeof value === "number" && Number.isFinite(value) && value > 0 ? Math.trunc(value) : 0;
46}
47
48export function parseTimestampMs(value: unknown): number | null {
49 if (typeof value !== "string") return null;
50 const parsed = Date.parse(value);
51 return Number.isNaN(parsed) ? null : parsed;
52}
53
54export type SelectedFields = { readonly [key: string]: true | SelectedFields };
55
56export interface TranscriptUsageFormat<State> {
57 readonly selectFields: SelectedFields;
58 /**
59 * ASCII substrings, at least one of which every line that matters contains.
60 * Lines that only update `State` must match too.
61 */
62 readonly usageMarkers: readonly [string, ...string[]];
63 parseLine(line: string, state: State): readonly UsageRecord[];
64 parseProjected(projected: unknown, state: State): readonly UsageRecord[];
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 /**
75 * Whether one session's records may appear in several files, such as a
76 * rollout copied when it moves. The server then keys those sessions'
77 * records for cross-file de-duplication.
78 */
79 readonly sharedSessionsAcrossFiles?: true;
80}
81
82export interface ProviderUsageInstance<Config> {
83 readonly instanceId: ProviderInstanceId;
84 /**
85 * `undefined` when the stored config does not decode. The instance still has
86 * history on disk, so readers that need no config read it anyway.
87 */
88 readonly config: Config | undefined;
89 readonly environment: NodeJS.ProcessEnv;
90 readonly configured: boolean;
91}
92
93export interface ProviderUsageScan {
94 readonly dir: string;
95 readonly volumeId?: string;
96 readonly hostId?: string;
97 readonly status?: UsageSource["status"];
98 readonly message?: string;
99 readonly action?: UsageSource["action"];
100 readonly files:
101 | readonly { readonly path: string; readonly records: readonly UsageRecord[] }[]
102 | null;
103 readonly refreshing?: true;
104}
105
106export interface ProviderUsageScanInput<Config> {
107 readonly instances: ReadonlyArray<ProviderUsageInstance<Config>>;
108 readonly settings: ServerSettings;
109 readonly windowStartMs: number;
110 readonly retentionCutoffMs: number;
111 readonly awaitRefresh: boolean;
112}
113
114export type ProviderUsageReader<Config, R> =
115 | {
116 readonly kind: "transcripts";
117 readonly provider: UsageProviderKind;
118 readonly format: TranscriptUsageFormat<unknown>;
119 readonly directories: (
120 instance: ProviderUsageInstance<Config>,
121 ) => Effect.Effect<
122 ReadonlyArray<{ readonly dir: string; readonly fileName?: string }>,
123 never,
124 R
125 >;
126 }
127 | {
128 readonly kind: "scan";
129 readonly provider: UsageProviderKind;
130 /** Fails only when the whole usage read cannot go on; an unreadable source is a status. */
131 readonly scan: (
132 input: ProviderUsageScanInput<Config>,
133 ) => Effect.Effect<ReadonlyArray<ProviderUsageScan>, UsageReadError, R>;
134 };