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

ProviderUsageAnalytics.ts

430 lines15.8 KB

1/**
2 * Provider token reporting: one `provider.turn.completed` per provider turn and one
3 * `provider.request.completed` per run, built from the same turns so each counts once.
4 *
5 * @module ProviderUsageAnalytics
6 */
7import type {
8 ModelSelection,
9 OrchestrationV2Actor,
10 OrchestrationV2CreationSource,
11 OrchestrationV2ProviderTurn,
12 OrchestrationV2RunAttempt,
13 ProviderInteractionMode,
14 RunId,
15 RuntimeMode,
16 TurnTokenUsage,
17} from "@t3tools/contracts";
18import * as Context from "effect/Context";
19import * as DateTime from "effect/DateTime";
20import * as Effect from "effect/Effect";
21import * as Layer from "effect/Layer";
22​
23import {
24 getModelSelectionBooleanOptionValue,
25 getModelSelectionStringOptionValue,
26} from "@t3tools/shared/model";
27import * as ProviderRegistry from "../provider/ProviderRegistry.ts";
28import * as AnalyticsService from "./AnalyticsService.ts";
29import { modelLabel } from "./ProviderDimensions.ts";
30​
31// Bump when a field changes meaning, so reports can split old and new rows.
32const REPORT_VERSION = 2;
33​
34/**
35 * Where the run's starting message came from. Most turns start without a
36 * person (provider continuations, agent sends, delegated subagents), so
37 * reports need this to tell user turns apart.
38 */
39export interface ProviderTurnOrigin {
40 readonly createdBy: OrchestrationV2Actor;
41 readonly creationSource: OrchestrationV2CreationSource;
42 readonly scheduled: boolean;
43 readonly subagent: boolean;
45​
46/** What started this provider turn inside its run. */
47export type ProviderTurnSegment =
48 | OrchestrationV2RunAttempt["reason"]
49 | "continuation"
50 | "native_child";
51​
52export interface ProviderTurnAnalyticsContext {
53 readonly runId?: RunId;
54 readonly modelSelection: ModelSelection;
55 readonly runtimeMode?: RuntimeMode;
56 readonly interactionMode?: ProviderInteractionMode;
57 readonly origin?: ProviderTurnOrigin;
58 readonly segment?: ProviderTurnSegment;
59 readonly restartContinuation?: boolean;
61​
62export interface ProviderTurnReport {
63 readonly driver: string;
64 readonly providerTurn: OrchestrationV2ProviderTurn;
65 readonly context?: ProviderTurnAnalyticsContext;
67​
68export interface RunSettledReport {
69 readonly runId: RunId;
70 readonly status: OrchestrationV2ProviderTurn["status"];
71 readonly completedAt: DateTime.Utc;
72 // Run-owned children were still open when the run settled; their later turns are not added.
73 readonly childrenRunning: boolean;
75​
76type Properties = Readonly<Record<string, unknown>>;
77/** Maps a driver's native model id to the name analytics reports. */
78export type ModelLabeler = (driver: string, model: string) => string;
79​
80const TERMINAL_STATUSES: ReadonlySet<OrchestrationV2ProviderTurn["status"]> = new Set([
81 "completed",
82 "failed",
83 "interrupted",
84 "cancelled",
85]);
86​
87const REPORTED_EFFORTS: ReadonlySet<string> = new Set([
88 "none",
89 "minimal",
90 "low",
91 "medium",
92 "high",
93 "xhigh",
94 "max",
95 "ultrathink",
96 "ultracode",
97 "brutal",
98]);
99​
100const defined = (entries: Properties): Properties =>
101 Object.fromEntries(Object.entries(entries).filter(([, value]) => value !== undefined));
102​
103// OpenCode names its effort option `variant`, and variants can be user-defined.
104function selectedEffort(selection: ModelSelection): string | undefined {
105 const effort =
106 getModelSelectionStringOptionValue(selection, "reasoningEffort") ??
107 getModelSelectionStringOptionValue(selection, "effort") ??
108 getModelSelectionStringOptionValue(selection, "variant");
109 return effort !== undefined && REPORTED_EFFORTS.has(effort) ? effort : undefined;
111​
112// Codex sends a tier id (its "fast" config shows up as "priority"); Claude has a fastMode toggle.
113const REPORTED_SERVICE_TIERS: ReadonlyMap<string, string> = new Map([
114 ["default", "standard"],
115 ["flex", "flex"],
116 ["fast", "fast"],
117 ["priority", "fast"],
118 ["ultrafast", "ultrafast"],
119]);
120​
121function selectedServiceTier(selection: ModelSelection): string | undefined {
122 const tier = getModelSelectionStringOptionValue(selection, "serviceTier");
123 if (tier !== undefined) return REPORTED_SERVICE_TIERS.get(tier);
124 const fastMode = getModelSelectionBooleanOptionValue(selection, "fastMode");
125 return fastMode === undefined ? undefined : fastMode ? "fast" : "standard";
127​
128/**
129 * Confirmed models across counted work. Unknown when any piece of work has no
130 * reported model, unless two distinct models were already seen.
131 */
132function modelObservation(
133 models: ReadonlyArray<ReadonlyArray<string> | undefined>,
134 label: (model: string) => string,
135): Properties {
136 const distinct = new Set(models.flatMap((entry) => entry ?? []));
137 if (distinct.size > 1) return { mixedModels: true };
138 if (distinct.size === 0 || models.some((entry) => entry === undefined || entry.length === 0)) {
139 return {};
140 }
141 return defined({ mixedModels: false, observedModel: label([...distinct][0]!) });
143​
144function selectionProperties(
145 context: ProviderTurnAnalyticsContext | undefined,
146 label: (model: string) => string,
147) {
148 const selection = context?.modelSelection;
149 return defined({
150 model: selection === undefined ? undefined : label(selection.model),
151 effort: selection === undefined ? undefined : selectedEffort(selection),
152 serviceTier: selection === undefined ? undefined : selectedServiceTier(selection),
153 runtimeMode: context?.runtimeMode,
154 interactionMode: context?.interactionMode,
155 ...context?.origin,
156 });
158​
159function childKind(context: ProviderTurnAnalyticsContext | undefined) {
160 if (context?.segment === "native_child") return "native";
161 return context?.origin?.subagent === true ? "t3" : undefined;
163​
164function counters(usage: TurnTokenUsage | undefined): Properties {
165 return defined({
166 inputTokens: usage?.inputTokens,
167 cachedInputTokens: usage?.cachedInputTokens,
168 cacheCreationTokens: usage?.cacheCreationTokens,
169 outputTokens: usage?.outputTokens,
170 reasoningTokens: usage?.reasoningTokens,
171 });
173​
174export function providerTurnProperties(
175 report: ProviderTurnReport,
176 labeler: ModelLabeler,
177): Properties {
178 const { providerTurn, context } = report;
179 const usage = providerTurn.turnTokenUsage;
180 const label = (model: string) => labeler(report.driver, model);
181 return defined({
182 reportVersion: REPORT_VERSION,
183 provider: report.driver,
184 terminalStatus: providerTurn.status,
185 usageStatus: usage?.usageStatus ?? "unavailable",
186 usageScope: usage?.usageScope ?? "main_agent",
187 usageReported: usage !== undefined,
188 hasSubagents: usage?.hasSubagents,
189 ...counters(usage),
190 localCommand: usage?.localCommand === true ? true : undefined,
191 otherInputTokens: usage?.otherUsage?.inputTokens,
192 otherOutputTokens: usage?.otherUsage?.outputTokens,
193 ...selectionProperties(context, label),
194 ...modelObservation([usage?.models], label),
195 segment: context?.segment,
196 childKind: childKind(context),
197 durationMs:
198 providerTurn.startedAt && providerTurn.completedAt
199 ? Math.max(
200 0,
201 DateTime.toEpochMillis(providerTurn.completedAt) -
202 DateTime.toEpochMillis(providerTurn.startedAt),
203 )
204 : undefined,
205 });
207​
208/** How the request reached the provider; only `user` counts as a person asking. */
209function requestKind(origin: ProviderTurnOrigin | undefined) {
210 if (origin === undefined) return "unknown";
211 if (origin.scheduled) return "scheduled";
212 if (origin.subagent) return "t3_child";
213 if (origin.createdBy === "user") return "user";
214 if (origin.creationSource === "provider") return "provider_continuation";
215 return origin.createdBy;
217​
218function sumOf(
219 usages: ReadonlyArray<TurnTokenUsage>,
220 field:
221 | "inputTokens"
222 | "cachedInputTokens"
223 | "cacheCreationTokens"
224 | "outputTokens"
225 | "reasoningTokens",
226 requireAll: boolean,
227): number | undefined {
228 const values = usages.map((usage) => usage[field]);
229 const known = values.filter((value) => value !== undefined);
230 if (known.length === 0 || (requireAll && known.length < values.length)) return undefined;
231 return known.reduce((sum, value) => sum + value, 0);
233​
234/** complete only when every turn is complete; partial when any turn has counts. */
235function combinedStatus(usages: ReadonlyArray<TurnTokenUsage | undefined>) {
236 if (usages.length > 0 && usages.every((usage) => usage?.usageStatus === "complete")) {
237 return "complete";
238 }
239 return usages.some(
240 (usage) => usage?.inputTokens !== undefined || usage?.outputTokens !== undefined,
241 )
242 ? "partial"
243 : "unavailable";
245​
246interface RequestTurn {
247 readonly child: boolean;
248 readonly segment: ProviderTurnSegment | undefined;
249 readonly providerTurn: OrchestrationV2ProviderTurn;
251​
252interface RequestEntry {
253 driver: string | undefined;
254 context: ProviderTurnAnalyticsContext | undefined;
255 readonly lifecycleObserved: boolean;
256 readonly turns: Map<string, RequestTurn>;
258​
259const MAX_TRACKED_RUNS = 2048;
260​
261/**
262 * Collects terminal provider turns per run in this process. A replayed turn
263 * replaces its earlier copy, a settled run ignores late turns, and a run whose
264 * initial attempt started before this process reports `lifecycleObserved: false`.
265 */
266export class RequestUsageLedger {
267 private readonly open = new Map<RunId, RequestEntry>();
268 private readonly settled = new Set<RunId>();
269​
270 start(runId: RunId, driver: string, context: ProviderTurnAnalyticsContext): void {
271 if (this.settled.has(runId) || this.open.has(runId)) return;
272 // A restart continuation carries on a run whose earlier turns this process never saw.
273 const lifecycleObserved = context.restartContinuation !== true;
274 this.open.set(runId, { driver, context, lifecycleObserved, turns: new Map() });
275 evictOldest(this.open);
276 }
277​
278 add(report: ProviderTurnReport): void {
279 const runId = report.context?.runId;
280 if (runId === undefined || this.settled.has(runId)) return;
281 if (!TERMINAL_STATUSES.has(report.providerTurn.status)) return;
282 let entry = this.open.get(runId);
283 if (entry === undefined) {
284 entry = { driver: undefined, context: undefined, lifecycleObserved: false, turns: new Map() };
285 this.open.set(runId, entry);
286 evictOldest(this.open);
287 }
288 const child = report.context?.segment === "native_child";
289 if (!child) {
290 entry.driver ??= report.driver;
291 entry.context ??= report.context;
292 }
293 entry.turns.set(String(report.providerTurn.id), {
294 child,
295 segment: report.context?.segment,
296 providerTurn: report.providerTurn,
297 });
298 }
299​
300 settle(report: RunSettledReport, labeler: ModelLabeler): Properties | undefined {
301 if (this.settled.has(report.runId)) return undefined;
302 this.settled.add(report.runId);
303 evictOldest(this.settled);
304 const entry = this.open.get(report.runId);
305 this.open.delete(report.runId);
306 if (entry === undefined) return undefined;
307 const provider = entry.driver ?? "unknown";
308 const label = (model: string) => labeler(provider, model);
309​
310 const turns = [...entry.turns.values()];
311 const root = turns.filter((turn) => !turn.child);
312 const children = turns.filter((turn) => turn.child);
313 const rootUsage = root.map((turn) => turn.providerTurn.turnTokenUsage);
314 const childUsage = children.map((turn) => turn.providerTurn.turnTokenUsage);
315 const { lifecycleObserved } = entry;
316 const measuredRoot = rootUsage.filter((usage) => usage !== undefined);
317 const status = combinedStatus(rootUsage);
318 const rootComplete = status === "complete";
319 const otherUsage = measuredRoot.map((usage) => usage.otherUsage);
320 const allOtherKnown = otherUsage.length > 0 && otherUsage.every((usage) => usage !== undefined);
321 const anyRootSubagents = measuredRoot.some((usage) => usage.hasSubagents);
322 const measuredChildren = childUsage.filter((usage) => usage !== undefined);
323 const childStatus =
324 children.length === 0 && !anyRootSubagents && !report.childrenRunning
325 ? "none"
326 : children.length === 0
327 ? "unavailable"
328 : report.childrenRunning && combinedStatus(childUsage) === "complete"
329 ? "partial"
330 : combinedStatus(childUsage);
331 const startedAt = turns
332 .map((turn) => turn.providerTurn.startedAt)
333 .filter((value) => value !== null)
334 .map(DateTime.toEpochMillis);
335​
336 return defined({
337 reportVersion: REPORT_VERSION,
338 provider,
339 requestKind: requestKind(entry.context?.origin),
340 restartContinuation: entry.context?.restartContinuation === true ? true : undefined,
341 terminalStatus: report.status,
342 lifecycleObserved,
343 ...selectionProperties(entry.context, label),
344 providerTurns: root.length,
345 continuations: root.filter((turn) => turn.segment === "continuation").length,
346 steeringRestarts: root.filter((turn) => turn.segment === "steering_restart").length,
347 usageStatus: lifecycleObserved || status === "unavailable" ? status : "partial",
348 inputTokens: sumOf(measuredRoot, "inputTokens", rootComplete),
349 cachedInputTokens: sumOf(measuredRoot, "cachedInputTokens", true),
350 cacheCreationTokens: sumOf(measuredRoot, "cacheCreationTokens", true),
351 outputTokens: sumOf(measuredRoot, "outputTokens", rootComplete),
352 reasoningTokens: sumOf(measuredRoot, "reasoningTokens", true),
353 localCommand: measuredRoot.some((usage) => usage.localCommand === true) ? true : undefined,
354 otherInputTokens: allOtherKnown
355 ? otherUsage.reduce((sum, usage) => sum + (usage?.inputTokens ?? 0), 0)
356 : undefined,
357 otherOutputTokens: allOtherKnown
358 ? otherUsage.reduce((sum, usage) => sum + (usage?.outputTokens ?? 0), 0)
359 : undefined,
360 nativeChildTurns: children.length,
361 childUsageStatus: childStatus,
362 childInputTokens: sumOf(measuredChildren, "inputTokens", false),
363 childOutputTokens: sumOf(measuredChildren, "outputTokens", false),
364 childrenRunning: report.childrenRunning ? true : undefined,
365 ...modelObservation(
366 [...rootUsage, ...childUsage].map((usage) => usage?.models),
367 label,
368 ),
369 durationMs:
370 startedAt.length === 0
371 ? undefined
372 : Math.max(0, DateTime.toEpochMillis(report.completedAt) - Math.min(...startedAt)),
373 });
374 }
376​
377function evictOldest(collection: Map<RunId, unknown> | Set<RunId>) {
378 if (collection.size <= MAX_TRACKED_RUNS) return;
379 const oldest = collection.keys().next().value;
380 if (oldest !== undefined) collection.delete(oldest);
382​
383export class ProviderTurnAnalytics extends Context.Reference<{
384 readonly runStarted: (input: {
385 readonly runId: RunId;
386 readonly driver: string;
387 readonly context: ProviderTurnAnalyticsContext;
388 }) => Effect.Effect<void>;
389 readonly turnCompleted: (report: ProviderTurnReport) => Effect.Effect<void>;
390 readonly runSettled: (report: RunSettledReport) => Effect.Effect<void>;
391}>("t3/telemetry/ProviderTurnAnalytics", {
392 defaultValue: () => ({
393 runStarted: () => Effect.void,
394 turnCompleted: () => Effect.void,
395 runSettled: () => Effect.void,
396 }),
397}) {}
398​
399export const layer = Layer.effect(
400 ProviderTurnAnalytics,
401 Effect.gen(function* () {
402 const analytics = yield* AnalyticsService.AnalyticsService;
403 const registry = yield* ProviderRegistry.ProviderRegistry;
404 const ledger = new RequestUsageLedger();
405 const labeler = Effect.map(
406 registry.getProviders,
407 (providers): ModelLabeler =>
408 (driver, model) =>
409 modelLabel(providers, driver, model),
410 );
411 return {
412 runStarted: Effect.fn("ProviderTurnAnalytics.runStarted")((input) =>
413 Effect.sync(() => ledger.start(input.runId, input.driver, input.context)),
414 ),
415 turnCompleted: Effect.fn("ProviderTurnAnalytics.turnCompleted")(function* (report) {
416 ledger.add(report);
417 yield* analytics.record(
418 "provider.turn.completed",
419 providerTurnProperties(report, yield* labeler),
420 );
421 }),
422 runSettled: Effect.fn("ProviderTurnAnalytics.runSettled")(function* (report) {
423 const properties = ledger.settle(report, yield* labeler);
424 if (properties !== undefined) {
425 yield* analytics.record("provider.request.completed", properties);
426 }
427 }),
428 };
429 }),
430);