@qlairoslabs/acp-client 0.5.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,991 @@
1
+ // Per-operation metering. See §7 (rating units), §8, §9, §11, §12.
2
+ //
3
+ // The engine owns one rating unit per ACP operation: resolve and freeze a pricing policy
4
+ // BEFORE dispatch, then after the operation subtract the baseline, select one schedule
5
+ // from the frozen policy, and rate. Resolving before dispatch is what makes a strict mode
6
+ // able to fail preflight instead of after the provider has already been paid, and what
7
+ // stops a mid-flight configuration change from repricing work already sent.
8
+
9
+ import type { TokenUsage } from "../types.ts";
10
+ import {
11
+ TOKEN_CATEGORY_KEYS,
12
+ disjointTokenUsage,
13
+ type TokenCategoryKey,
14
+ } from "./categories.ts";
15
+ import type { ContextWindowStatus, ProviderCostSnapshot } from "./context.ts";
16
+ import { baselineMatches, calculateDelta } from "./delta.ts";
17
+ import {
18
+ MeteringPreflightError,
19
+ type MeteredOperationKind,
20
+ type MeteringEnforcement,
21
+ type MeteringPricingStatus,
22
+ type MeteringProvenance,
23
+ type MeteringUsageResult,
24
+ type OperationMeteringRecord,
25
+ type OperationOutcome,
26
+ type CostReconciliation,
27
+ acpProvenance,
28
+ UNAVAILABLE_PROVENANCE,
29
+ } from "./record.ts";
30
+ import type {
31
+ CategoryApplicability,
32
+ PricingConfiguration,
33
+ PricingContext,
34
+ PricingPolicy,
35
+ PricingResolver,
36
+ TokenCategory,
37
+ } from "./pricing.ts";
38
+ import { validatePricingPolicy } from "./pricing.ts";
39
+ import { counterInterpretationForAdapter, type CounterInterpretation } from "./provider.ts";
40
+ import { billingRefusalReason, certificationFor } from "./certification.ts";
41
+ import type { ProviderInference } from "./opencode/channel.ts";
42
+
43
+ /**
44
+ * A source of per-inference records from inside the harness.
45
+ *
46
+ * The ACP-derived backend sees one inference per prompt; a certified source sees them all,
47
+ * which is the whole difference between observability and billing.
48
+ */
49
+ export interface InferenceSource {
50
+ /** Certification this source claims, engraved into every record it produces. */
51
+ readonly certificationId: string;
52
+ /** False when the channel never handshook or has since failed. */
53
+ isHealthy(): boolean;
54
+ /** Records completed since the last drain, for the named provider thread. */
55
+ drain(internalSessionId: string | null): readonly ProviderInference[];
56
+ /**
57
+ * Records for OTHER provider threads, swept so they are accounted rather than stranded.
58
+ *
59
+ * Work the harness did outside the active thread — a replaced thread after a handoff,
60
+ * or background activity — belongs in unallocated usage, not charged to whichever
61
+ * operation happens to drain next and not silently dropped.
62
+ */
63
+ drainForeign?(internalSessionId: string | null): readonly ProviderInference[];
64
+ /**
65
+ * Reports known skipped and not yet filled, for this provider thread.
66
+ *
67
+ * RETRACTABLE — a late arrival discharges its own gap, so this can fall. The engine asks
68
+ * it as a STATE question at close rather than comparing a counter across the operation,
69
+ * because a delta over a retractable value is meaningless.
70
+ */
71
+ outstandingReports?(internalSessionId: string | null): number;
72
+ /**
73
+ * Reports the source refused and can never receive.
74
+ *
75
+ * Permanent, and therefore the only loss that justifies stopping a billing session: that
76
+ * usage is unaccounted anywhere, whereas a late report still lands in unallocated usage.
77
+ */
78
+ permanentlyLostCount?(): number;
79
+ /** Highest sequence recorded for a thread, used to recognise a late arrival at close. */
80
+ sequenceHighWater?(internalSessionId: string | null): number;
81
+ }
82
+ import {
83
+ rateDelta,
84
+ selectSchedule,
85
+ unpricedUsage,
86
+ type AttributableUsage,
87
+ type BillingFacts,
88
+ type PricedTokenAmount,
89
+ } from "./rating.ts";
90
+ import {
91
+ EMPTY_MONEY_TOTAL,
92
+ decimalFromNumber,
93
+ isTotalComplete,
94
+ mergeTotals,
95
+ ratioOf,
96
+ soleAmount,
97
+ subtractMoney,
98
+ type Money,
99
+ } from "./money.ts";
100
+ import {
101
+ accrueOperation,
102
+ emptyMeteringState,
103
+ restoreMeteringState,
104
+ type AgentSessionMeteringState,
105
+ type MeteringBaseline,
106
+ type StateRestoration,
107
+ type UnallocatedUsageAccrual,
108
+ } from "./state.ts";
109
+
110
+ export interface MeteringEngineOptions {
111
+ readonly agentSessionId: string;
112
+ readonly adapterId: string;
113
+ readonly enforcement: MeteringEnforcement;
114
+ readonly pricing: PricingConfiguration;
115
+ readonly initialState?: AgentSessionMeteringState;
116
+ /** True when the library created the active provider thread, so counters began at zero. */
117
+ readonly createdActiveThread: boolean;
118
+ /**
119
+ * How to read this harness's counters. Defaults to the adapter's measured evidence.
120
+ * A consumer may override when it knows its harness version; it is never guessed at
121
+ * runtime, because §4 forbids switching interpretations mid-session.
122
+ */
123
+ readonly counterInterpretation?: CounterInterpretation;
124
+ /** When present and healthy, replaces ACP usage as the measurement. */
125
+ readonly inferenceSource?: InferenceSource;
126
+ }
127
+
128
+ /** A rating unit opened before dispatch and closed after the operation finishes. */
129
+ export interface OpenOperation {
130
+ readonly operationId: string;
131
+ readonly operationKind: MeteredOperationKind;
132
+ readonly startedAt: number;
133
+ readonly internalSessionId: string | null;
134
+ readonly providerId: string | null;
135
+ readonly model: string | null;
136
+ readonly policy: PricingPolicy | null;
137
+ readonly pricingFailureReason: string | null;
138
+ /** Permanently-lost count at open, to spot a refusal during this operation. */
139
+ readonly permanentlyLostAtOpen: number;
140
+ /**
141
+ * Sequence high-water when the operation opened.
142
+ *
143
+ * A record drained at close whose sequence is at or below this was expected before the
144
+ * operation began — it is LATE, and belongs to unallocated usage rather than being
145
+ * charged to whichever operation happens to be draining.
146
+ */
147
+ readonly sequenceHighWaterAtOpen: number;
148
+ }
149
+
150
+ export interface CloseOperationInput {
151
+ readonly outcome: OperationOutcome;
152
+ /** Normalized cumulative report, or null when the harness supplied none. */
153
+ readonly reportedCumulative: TokenUsage | null;
154
+ readonly usageFailureReason?: string;
155
+ readonly contextAfter: ContextWindowStatus | null;
156
+ readonly providerCostAfter: ProviderCostSnapshot | null;
157
+ readonly billingFacts?: BillingFacts;
158
+ }
159
+
160
+ const UNKNOWN_APPLICABILITY: Readonly<Record<TokenCategory, CategoryApplicability>> = Object.freeze({
161
+ input: "unknown",
162
+ output: "unknown",
163
+ cached_read: "unknown",
164
+ cached_write: "unknown",
165
+ thought: "unknown",
166
+ });
167
+
168
+ export class MeteringEngine {
169
+ private state: AgentSessionMeteringState;
170
+ private readonly _restoration: StateRestoration;
171
+ private _blocked = false;
172
+ private _blockedReason: string | null = null;
173
+ private _lastOperation: OperationMeteringRecord | null = null;
174
+ /** Whether the active thread's counters are known to have started at zero. */
175
+ private trustedZeroBaseline: boolean;
176
+ private baseline: MeteringBaseline | null;
177
+ private readonly interpretation: CounterInterpretation;
178
+ /** Provider cumulative cost as of the previous close, for per-operation deltas. */
179
+ private lastProviderCost: Money | null = null;
180
+ /** Records drained this close that belong to an operation already finished. */
181
+ private lateArrivals: readonly ProviderInference[] = [];
182
+
183
+ constructor(private readonly options: MeteringEngineOptions) {
184
+ const restoration = restoreMeteringState(options.initialState, options.agentSessionId);
185
+ this._restoration = restoration;
186
+ this.state =
187
+ restoration.status === "restored"
188
+ ? restoration.state
189
+ : emptyMeteringState(options.agentSessionId);
190
+ this.baseline = restoration.status === "restored" ? this.state.activeBaseline : null;
191
+ this.trustedZeroBaseline = options.createdActiveThread;
192
+ this.interpretation =
193
+ options.counterInterpretation ?? counterInterpretationForAdapter(options.adapterId);
194
+
195
+ if (restoration.status === "ignored" && options.enforcement !== "best_effort") {
196
+ throw new MeteringPreflightError(
197
+ `metering initialState rejected: ${restoration.reason}`,
198
+ );
199
+ }
200
+ const certification = certificationFor(options.adapterId);
201
+ if (
202
+ options.enforcement === "billing_required" &&
203
+ (!certification || options.inferenceSource?.certificationId !== certification.certificationId)
204
+ ) {
205
+ // Refused at construction rather than at the first prompt: a consumer asking for
206
+ // billing-grade metering should learn it is unavailable before any work is queued,
207
+ // not after a turn has already been paid for.
208
+ throw new MeteringPreflightError(billingRefusalReason(options.adapterId));
209
+ }
210
+ }
211
+
212
+ get enforcement(): MeteringEnforcement {
213
+ return this.options.enforcement;
214
+ }
215
+ get restoration(): StateRestoration {
216
+ return this._restoration;
217
+ }
218
+ get currentState(): AgentSessionMeteringState {
219
+ return this.state;
220
+ }
221
+ get blocked(): boolean {
222
+ return this._blocked;
223
+ }
224
+ get blockedReason(): string | null {
225
+ return this._blockedReason;
226
+ }
227
+ get lastOperation(): OperationMeteringRecord | null {
228
+ return this._lastOperation;
229
+ }
230
+ /** Reports the certified source is still missing for a thread; retractable. */
231
+ outstandingReports(internalSessionId: string | null): number {
232
+ return this.options.inferenceSource?.outstandingReports?.(internalSessionId) ?? 0;
233
+ }
234
+ get counterInterpretation(): CounterInterpretation {
235
+ return this.interpretation;
236
+ }
237
+
238
+ /**
239
+ * Called when the active provider thread is replaced.
240
+ *
241
+ * The new thread's counters restart, so the old baseline is meaningless. A thread the
242
+ * library created has a trusted zero baseline; one it merely loaded does not.
243
+ */
244
+ onThreadReplaced(internalSessionId: string | null, created: boolean): void {
245
+ // A restored baseline that names the thread we just activated is still valid — that
246
+ // is the whole point of restoring it. Only a baseline for some OTHER thread is stale.
247
+ const keep =
248
+ this.baseline &&
249
+ internalSessionId &&
250
+ baselineMatches(this.baseline, {
251
+ adapterId: this.options.adapterId,
252
+ internalSessionId,
253
+ });
254
+ if (!keep) this.baseline = null;
255
+ // A thread we created has counters starting at zero; one we merely loaded does not.
256
+ this.trustedZeroBaseline = created && !keep;
257
+ }
258
+
259
+ /**
260
+ * Open a rating unit. Throws in a strict mode when a known preflight condition fails —
261
+ * before any provider work is dispatched, so nothing has been paid for.
262
+ */
263
+ async open(input: {
264
+ operationId: string;
265
+ operationKind: MeteredOperationKind;
266
+ internalSessionId: string | null;
267
+ providerId: string | null;
268
+ model: string | null;
269
+ degraded: boolean;
270
+ }): Promise<OpenOperation> {
271
+ const strict = this.options.enforcement !== "best_effort";
272
+
273
+ if (this._blocked && strict) {
274
+ throw new MeteringPreflightError(
275
+ `metering is blocked: ${this._blockedReason ?? "unknown reason"}`,
276
+ );
277
+ }
278
+ if (input.degraded && strict) {
279
+ throw new MeteringPreflightError(
280
+ "degraded (pty) mode cannot supply structured metering",
281
+ );
282
+ }
283
+ // A certified source that is already unhealthy must fail BEFORE the provider is paid.
284
+ // Checking only afterwards let the first operation through, which defeats the point of
285
+ // a preflight in the one mode that exists to guarantee measurement.
286
+ if (strict && this.options.inferenceSource && !this.options.inferenceSource.isHealthy()) {
287
+ throw new MeteringPreflightError(
288
+ "certified metering channel is not healthy; refusing to dispatch billable work",
289
+ );
290
+ }
291
+ // A per-turn harness needs no baseline: each report already describes one operation.
292
+ if (
293
+ strict &&
294
+ this.interpretation === "cumulative" &&
295
+ !this.trustedZeroBaseline &&
296
+ !this.baseline
297
+ ) {
298
+ throw new MeteringPreflightError(
299
+ "no trusted baseline for the active provider thread; restore prior metering state",
300
+ );
301
+ }
302
+
303
+ const startedAt = Date.now();
304
+ let policy: PricingPolicy | null = null;
305
+ let pricingFailureReason: string | null = null;
306
+
307
+ if (this.options.pricing === false) {
308
+ if (strict) {
309
+ throw new MeteringPreflightError("pricing is disabled but this mode requires rating");
310
+ }
311
+ pricingFailureReason = "pricing disabled by configuration";
312
+ } else {
313
+ const context: PricingContext = {
314
+ scope: "operation",
315
+ agentSessionId: this.options.agentSessionId,
316
+ internalSessionId: input.internalSessionId,
317
+ operationId: input.operationId,
318
+ adapterId: this.options.adapterId,
319
+ providerId: input.providerId,
320
+ model: input.model,
321
+ operationKind: input.operationKind,
322
+ at: startedAt,
323
+ };
324
+ const resolved = await this.resolvePolicy(this.options.pricing, context);
325
+ if (resolved.ok) policy = resolved.policy;
326
+ else pricingFailureReason = resolved.reason;
327
+
328
+ if (!policy && strict) {
329
+ throw new MeteringPreflightError(`pricing unavailable: ${pricingFailureReason}`);
330
+ }
331
+ }
332
+
333
+ return Object.freeze({
334
+ operationId: input.operationId,
335
+ operationKind: input.operationKind,
336
+ startedAt,
337
+ internalSessionId: input.internalSessionId,
338
+ providerId: input.providerId,
339
+ model: input.model,
340
+ policy,
341
+ pricingFailureReason,
342
+ permanentlyLostAtOpen: this.options.inferenceSource?.permanentlyLostCount?.() ?? 0,
343
+ sequenceHighWaterAtOpen:
344
+ this.options.inferenceSource?.sequenceHighWater?.(input.internalSessionId) ?? 0,
345
+ });
346
+ }
347
+
348
+ private async resolvePolicy(
349
+ resolver: PricingResolver,
350
+ context: PricingContext,
351
+ ): Promise<{ ok: true; policy: PricingPolicy } | { ok: false; reason: string }> {
352
+ let policy: PricingPolicy | null;
353
+ try {
354
+ policy = await resolver(context);
355
+ } catch (err) {
356
+ // A resolver that throws follows the same path as one returning null; the original
357
+ // error is preserved as the preflight cause by the caller.
358
+ return { ok: false, reason: `pricing resolver failed: ${String(err)}` };
359
+ }
360
+ if (!policy) return { ok: false, reason: "no pricing policy for this provider/model" };
361
+ const validation = validatePricingPolicy(policy);
362
+ if (!validation.ok) return { ok: false, reason: `invalid pricing policy: ${validation.reason}` };
363
+ return { ok: true, policy };
364
+ }
365
+
366
+ /**
367
+ * Close a rating unit and produce its immutable record.
368
+ *
369
+ * Never throws for missing or malformed post-operation usage: the provider has already
370
+ * done the work, and rejecting would risk a retry that duplicates cost. A strict mode
371
+ * records the failure and blocks FUTURE operations instead.
372
+ */
373
+ async close(open: OpenOperation, input: CloseOperationInput): Promise<OperationMeteringRecord> {
374
+ const strict = this.options.enforcement !== "best_effort";
375
+ const source = this.options.inferenceSource;
376
+ const certified = source ? await this.measureCertified(source, open, input) : null;
377
+ const { usage, attributable, applicability, nextBaseline, ratingFailureReason, ratingComplete } =
378
+ certified ?? this.measure(open, input);
379
+
380
+ let pricingStatus: MeteringPricingStatus;
381
+ // A post-operation rating failure is more specific than a preflight one, so it wins.
382
+ let pricingFailureReason = ratingFailureReason ?? open.pricingFailureReason ?? undefined;
383
+
384
+ // `pricingSource` describes PROVENANCE and is legitimately null on a multi-model
385
+ // operation, where each model's source is engraved in its line item instead. Using it
386
+ // as the "was this priced" signal marked fully-rated multi-model operations
387
+ // pricing_unavailable and blocked strict mode on correctly priced work.
388
+ if (usage.status !== "metered") {
389
+ pricingStatus = "not_attributable";
390
+ } else if (this.options.pricing === false) {
391
+ pricingStatus = "not_configured";
392
+ } else if (ratingComplete && attributable && isTotalComplete(attributable.ratedTotal)) {
393
+ // Completeness is read off the DATA, not from a flag travelling beside it. The two
394
+ // could drift, and did: a fully rated multi-model operation was once reported
395
+ // pricing_unavailable because a separate signal disagreed with the total.
396
+ pricingStatus = "priced";
397
+ } else {
398
+ pricingStatus = "pricing_unavailable";
399
+ }
400
+
401
+ // Swept before provenance so the attribution claim and the blocking decision are made
402
+ // from the same facts, not from two separate reads of a moving source.
403
+ const foreign = source?.drainForeign?.(open.internalSessionId) ?? [];
404
+ // A STATE question, not a delta: gaps are retractable, so "did a counter rise" is not
405
+ // answerable. What matters is whether anything is still missing now, at close.
406
+ const outstanding = source?.outstandingReports?.(open.internalSessionId) ?? 0;
407
+ const permanentlyLost =
408
+ (source?.permanentlyLostCount?.() ?? 0) > open.permanentlyLostAtOpen;
409
+
410
+ const provenance: MeteringProvenance =
411
+ usage.status !== "metered"
412
+ ? UNAVAILABLE_PROVENANCE
413
+ : certified
414
+ ? Object.freeze({
415
+ source: "certified" as const,
416
+ measurement: "provider_normalized" as const,
417
+ // Still "observed", never "enforced": the plugin reports what the harness
418
+ // ran, but a library cannot prove no model call bypassed it.
419
+ routing: "observed" as const,
420
+ // "complete" has to be EARNED. If the source lost a report while this
421
+ // operation ran, some inference happened that we never saw, and claiming
422
+ // complete attribution would be exactly the overstatement this design
423
+ // refuses everywhere else.
424
+ attribution:
425
+ outstanding > 0 || permanentlyLost || foreign.length > 0
426
+ ? ("partial" as const)
427
+ : ("complete" as const),
428
+ certificationId: source!.certificationId,
429
+ })
430
+ : acpProvenance(this.interpretation);
431
+
432
+ this.state = accrueOperation(this.state, {
433
+ attributable,
434
+ applicability,
435
+ baseline: nextBaseline,
436
+ ...(foreign.length > 0 || this.lateArrivals.length > 0
437
+ ? {
438
+ unallocated: [
439
+ ...foreign.map((inference) => toUnallocated(inference, "foreign")),
440
+ ...this.lateArrivals.map((inference) => toUnallocated(inference, "late")),
441
+ ],
442
+ }
443
+ : {}),
444
+ });
445
+ this.baseline = nextBaseline;
446
+ if (nextBaseline) this.trustedZeroBaseline = false;
447
+
448
+ const record: OperationMeteringRecord = Object.freeze({
449
+ operationId: open.operationId,
450
+ operationKind: open.operationKind,
451
+ outcome: input.outcome,
452
+ startedAt: open.startedAt,
453
+ completedAt: Date.now(),
454
+ agentSessionId: this.options.agentSessionId,
455
+ internalSessionId: open.internalSessionId,
456
+ provider: Object.freeze({
457
+ adapterId: this.options.adapterId,
458
+ providerId: open.providerId,
459
+ model: open.model,
460
+ }),
461
+ provenance,
462
+ usage,
463
+ pricingStatus,
464
+ ...(pricingFailureReason ? { pricingFailureReason } : {}),
465
+ contextAfter: input.contextAfter,
466
+ providerCostAfter: input.providerCostAfter,
467
+ costReconciliation: this.reconcileCost(attributable, input.providerCostAfter),
468
+ nextState: this.state,
469
+ });
470
+ this.lastProviderCost = input.providerCostAfter?.cumulative ?? this.lastProviderCost;
471
+ this.lateArrivals = [];
472
+
473
+ this._lastOperation = record;
474
+
475
+ // Strict modes block on any post-operation metering failure. The response is kept —
476
+ // it was paid for — but continued silent under-accounting is prevented.
477
+ if (strict && !this._blocked) {
478
+ if (usage.status !== "metered") {
479
+ this.block(`operation ${open.operationId}: ${usage.reason}`);
480
+ } else if (pricingStatus !== "priced") {
481
+ this.block(
482
+ `operation ${open.operationId}: ${pricingFailureReason ?? "rated cost unavailable"}`,
483
+ );
484
+ }
485
+ }
486
+
487
+ // Attribution gaps block billing_required only. telemetry_required is strict handling
488
+ // of ACP telemetry and never claimed to account for every hidden inference, so holding
489
+ // it to that standard would be a promise it was explicitly not making.
490
+ if (this.options.enforcement === "billing_required" && !this._blocked) {
491
+ // Only PERMANENT loss blocks. An outstanding gap usually resolves moments later and
492
+ // its usage then lands in unallocated — visible, costed, reconcilable — so the
493
+ // promise "never silently under-account" still holds, and the record already says
494
+ // `attribution: partial`. Blocking a production session on a loopback reorder costs
495
+ // more than it prevents. A refused record is different: that usage is accounted
496
+ // nowhere and never will be.
497
+ if (permanentlyLost) {
498
+ this.block(
499
+ `operation ${open.operationId}: certified source refused inference reports for ` +
500
+ `capacity, so some billable work can never be measured`,
501
+ );
502
+ } else if (foreign.length > 0) {
503
+ this.block(
504
+ `operation ${open.operationId}: observed ${foreign.length} inference(s) from ` +
505
+ `another provider thread; usage was preserved as unallocated but cannot be ` +
506
+ `attributed`,
507
+ );
508
+ }
509
+ }
510
+
511
+ return record;
512
+ }
513
+
514
+ /**
515
+ * Measure an operation from per-inference records instead of ACP usage.
516
+ *
517
+ * Returns null when there is no certified measurement to make, so the caller falls back
518
+ * to the ACP path — except in a strict mode, where an unhealthy source is a failure
519
+ * rather than a silent downgrade to a backend known to undercount.
520
+ */
521
+ private async measureCertified(
522
+ source: InferenceSource,
523
+ open: OpenOperation,
524
+ input: CloseOperationInput,
525
+ ): Promise<ReturnType<MeteringEngine["measure"]> | null> {
526
+ if (!source.isHealthy()) {
527
+ return {
528
+ usage: {
529
+ status: "usage_unavailable",
530
+ reason: "certified metering channel is not healthy",
531
+ },
532
+ attributable: null,
533
+ applicability: open.policy?.categoryApplicability ?? null,
534
+ nextBaseline: this.baseline,
535
+ };
536
+ }
537
+
538
+ const drained = source.drain(open.internalSessionId);
539
+ // A record whose sequence predates this operation's start was expected earlier: it is
540
+ // a LATE arrival belonging to an operation already closed. Charging it here would
541
+ // misattribute it, so it goes to unallocated usage instead — which is what makes it
542
+ // defensible not to block on an outstanding gap.
543
+ // `typeof`, not `=== null`: a source that omits `sequence` yields undefined, and
544
+ // comparing that against the high-water mark is false — which silently classified
545
+ // EVERY record as late and reported the operation unmeasured. An absent sequence means
546
+ // "no ordering information", which must default to keeping the record.
547
+ const isLate = (inference: ProviderInference): boolean =>
548
+ typeof inference.sequence === "number" &&
549
+ inference.sequence <= open.sequenceHighWaterAtOpen;
550
+ const inferences = drained.filter((inference) => !isLate(inference));
551
+ this.lateArrivals = drained.filter(isLate);
552
+ if (inferences.length === 0) {
553
+ // A prompt that reached the provider ran at least one inference. None means the
554
+ // channel missed them, which is exactly the silent undercount this path exists to
555
+ // prevent — so it is reported unavailable rather than as a free operation.
556
+ return {
557
+ usage: {
558
+ status: "usage_unavailable",
559
+ reason: "certified channel reported no inferences for this operation",
560
+ },
561
+ attributable: null,
562
+ applicability: open.policy?.categoryApplicability ?? null,
563
+ nextBaseline: this.baseline,
564
+ };
565
+ }
566
+
567
+ const summed = sumInferenceTokens(inferences);
568
+ const rated = await this.ratePerInference(open, inferences, input.billingFacts ?? {});
569
+ return {
570
+ usage: {
571
+ status: "metered",
572
+ reportedCumulative: summed,
573
+ attributable: rated.usage,
574
+ },
575
+ attributable: rated.usage,
576
+ applicability: open.policy?.categoryApplicability ?? UNKNOWN_APPLICABILITY,
577
+ nextBaseline: this.baseline,
578
+ ratingComplete: rated.complete,
579
+ ...(rated.reason ? { ratingFailureReason: rated.reason } : {}),
580
+ };
581
+ }
582
+
583
+ private measure(
584
+ open: OpenOperation,
585
+ input: CloseOperationInput,
586
+ ): {
587
+ usage: MeteringUsageResult;
588
+ attributable: AttributableUsage | null;
589
+ applicability: Readonly<Record<TokenCategory, CategoryApplicability>> | null;
590
+ nextBaseline: MeteringBaseline | null;
591
+ ratingFailureReason?: string;
592
+ /** Whether every reported category was actually rated. */
593
+ ratingComplete?: boolean;
594
+ } {
595
+ const applicability = open.policy?.categoryApplicability ?? null;
596
+ const keepBaseline = this.baseline;
597
+
598
+ if (!input.reportedCumulative) {
599
+ return {
600
+ usage: {
601
+ status: "usage_unavailable",
602
+ reason: input.usageFailureReason ?? "harness reported no usage",
603
+ },
604
+ attributable: null,
605
+ applicability,
606
+ nextBaseline: keepBaseline,
607
+ };
608
+ }
609
+
610
+ const reported = input.reportedCumulative;
611
+ const usableBaseline =
612
+ keepBaseline && open.internalSessionId
613
+ ? baselineMatches(keepBaseline, {
614
+ adapterId: this.options.adapterId,
615
+ internalSessionId: open.internalSessionId,
616
+ })
617
+ ? keepBaseline.reportedUsage
618
+ : null
619
+ : null;
620
+
621
+ const delta = calculateDelta(usableBaseline, reported, {
622
+ trustedZeroBaseline: this.trustedZeroBaseline && !usableBaseline,
623
+ interpretation: this.interpretation,
624
+ });
625
+
626
+ const nextBaseline: MeteringBaseline | null = open.internalSessionId
627
+ ? Object.freeze({
628
+ adapterId: this.options.adapterId,
629
+ internalSessionId: open.internalSessionId,
630
+ reportedUsage: reported,
631
+ })
632
+ : keepBaseline;
633
+
634
+ if (delta.kind !== "attributable") {
635
+ return {
636
+ usage: {
637
+ status: delta.kind === "counter_reset" ? "counter_reset" : "baseline_required",
638
+ reportedCumulative: reported,
639
+ reason: delta.reason,
640
+ },
641
+ attributable: null,
642
+ applicability,
643
+ // A reset report becomes the next baseline so best-effort metering can continue.
644
+ nextBaseline,
645
+ };
646
+ }
647
+
648
+ const attributable = this.rate(open, delta.delta, input.billingFacts ?? {});
649
+ return {
650
+ usage: {
651
+ status: "metered",
652
+ reportedCumulative: reported,
653
+ attributable: attributable.usage,
654
+ },
655
+ attributable: attributable.usage,
656
+ applicability: applicability ?? UNKNOWN_APPLICABILITY,
657
+ nextBaseline,
658
+ ratingComplete: attributable.complete,
659
+ // Why rating fell back to unpriced. Without this the record says
660
+ // "pricing_unavailable" with no way to find out why.
661
+ ...(attributable.reason ? { ratingFailureReason: attributable.reason } : {}),
662
+ };
663
+ }
664
+
665
+ /**
666
+ * Rate a certified operation one MODEL GROUP at a time.
667
+ *
668
+ * §7 makes a certified backend's rating unit the physical inference, and it matters:
669
+ * a harness may run compaction or title generation on a different, cheaper model than
670
+ * the one answering the prompt. Summing every inference and applying the operation's
671
+ * model would price that work at the wrong rate, silently.
672
+ *
673
+ * The policy resolved at open() is reused for its own provider/model so the frozen price
674
+ * still governs the work the caller asked for; any other model is resolved here, because
675
+ * which models a turn would use cannot be known before it runs.
676
+ */
677
+ private async ratePerInference(
678
+ open: OpenOperation,
679
+ inferences: readonly ProviderInference[],
680
+ facts: BillingFacts,
681
+ ): Promise<{ usage: AttributableUsage; complete: boolean; reason?: string }> {
682
+ const groups = new Map<string, ProviderInference[]>();
683
+ for (const inference of inferences) {
684
+ const key = `${inference.providerID}\u0000${inference.modelID}`;
685
+ const group = groups.get(key);
686
+ if (group) group.push(inference);
687
+ else groups.set(key, [inference]);
688
+ }
689
+
690
+ // One model: the operation's own policy applies, unchanged.
691
+ if (groups.size === 1) {
692
+ const [only] = [...groups.values()];
693
+ const first = only![0]!;
694
+ if (first.providerID === open.providerId && first.modelID === open.model) {
695
+ return this.rate(open, sumInferenceTokens(only!), facts);
696
+ }
697
+ }
698
+
699
+ const parts: { usage: AttributableUsage; sample: ProviderInference }[] = [];
700
+ let reason: string | undefined;
701
+ // `pricing: false` is a choice everywhere, including here. The single-model fast path
702
+ // already honoured it; a multi-model operation was still recording each group as a
703
+ // failed rating, so a deliberately unrated session accumulated phantom losses.
704
+ const unpricedReason = this.options.pricing === false ? "not_attempted" : "failed";
705
+ for (const group of groups.values()) {
706
+ const sample = group[0]!;
707
+ const tokens = sumInferenceTokens(group);
708
+ const matchesOperation =
709
+ sample.providerID === open.providerId && sample.modelID === open.model;
710
+ const policy = matchesOperation
711
+ ? open.policy
712
+ : await this.resolveForInference(open, sample);
713
+ if (!policy) {
714
+ if (unpricedReason === "failed") {
715
+ reason ??= `no pricing policy for ${sample.providerID}/${sample.modelID}`;
716
+ }
717
+ parts.push({ usage: unpricedUsage(tokens, unpricedReason), sample });
718
+ continue;
719
+ }
720
+ const selected = selectSchedule(policy, facts);
721
+ if (!selected.ok) {
722
+ reason ??= selected.reason;
723
+ parts.push({ usage: unpricedUsage(tokens, "failed"), sample });
724
+ continue;
725
+ }
726
+ const rated = rateDelta(tokens, policy, selected.schedule);
727
+ if (!rated.ok) {
728
+ reason ??= rated.reason;
729
+ parts.push({ usage: unpricedUsage(tokens, "failed"), sample });
730
+ continue;
731
+ }
732
+ parts.push({ usage: rated.usage, sample });
733
+ }
734
+
735
+ const combined = combineAttributable(parts);
736
+ // Complete only when EVERY model group rated. One unpriceable model makes the
737
+ // operation's total an understatement, whatever the others managed.
738
+ // With pricing off, "complete" means nothing was lost — not that everything was rated.
739
+ const complete = parts.every((part) => isTotalComplete(part.usage.ratedTotal));
740
+ return reason ? { usage: combined, complete, reason } : { usage: combined, complete };
741
+ }
742
+
743
+ /** Resolve a policy for a model the operation did not anticipate. */
744
+ private async resolveForInference(
745
+ open: OpenOperation,
746
+ inference: ProviderInference,
747
+ ): Promise<PricingPolicy | null> {
748
+ if (this.options.pricing === false) return null;
749
+ const resolved = await this.resolvePolicy(this.options.pricing, {
750
+ scope: "inference",
751
+ agentSessionId: this.options.agentSessionId,
752
+ internalSessionId: open.internalSessionId,
753
+ operationId: open.operationId,
754
+ inferenceId: inference.messageID,
755
+ adapterId: this.options.adapterId,
756
+ providerId: inference.providerID,
757
+ model: inference.modelID,
758
+ operationKind: open.operationKind,
759
+ at: inference.completedAt,
760
+ });
761
+ return resolved.ok ? resolved.policy : null;
762
+ }
763
+
764
+ private rate(
765
+ open: OpenOperation,
766
+ delta: TokenUsage,
767
+ facts: BillingFacts,
768
+ ): { usage: AttributableUsage; complete: boolean; reason?: string } {
769
+ if (!open.policy) {
770
+ // `pricing: false` is a choice, not a failure. Marking it unaccounted would make a
771
+ // deliberately unrated session report lost costs.
772
+ const reason = this.options.pricing === false ? "not_attempted" : "failed";
773
+ return { usage: unpricedUsage(delta, reason), complete: this.options.pricing === false };
774
+ }
775
+
776
+ const selected = selectSchedule(open.policy, facts);
777
+ if (!selected.ok) {
778
+ return { usage: unpricedUsage(delta), complete: false, reason: selected.reason };
779
+ }
780
+
781
+ const rated = rateDelta(delta, open.policy, selected.schedule);
782
+ if (!rated.ok) return { usage: unpricedUsage(delta), complete: false, reason: rated.reason };
783
+ return { usage: rated.usage, complete: true };
784
+ }
785
+
786
+ /**
787
+ * Compare our rated cost with the provider's own for this operation.
788
+ *
789
+ * The provider's cumulative cost is the only visibility the ACP-derived backend has into
790
+ * inferences it never saw — retries, compaction, and above all tool-call round trips. A
791
+ * divergence here is not a rounding question; it means real spend went unaccounted.
792
+ */
793
+ private reconcileCost(
794
+ attributable: AttributableUsage | null,
795
+ providerCostAfter: ProviderCostSnapshot | null,
796
+ ): CostReconciliation {
797
+ // Only an unambiguous single amount can be compared with the provider's single figure.
798
+ // A multi-currency or incomplete total has no one number to reconcile.
799
+ const rated = attributable ? soleAmount(attributable.ratedTotal) : null;
800
+ if (!rated) {
801
+ return {
802
+ status: "unavailable",
803
+ reason: attributable
804
+ ? "operation has no single rated amount to compare"
805
+ : "operation was not rated",
806
+ };
807
+ }
808
+ if (!providerCostAfter) {
809
+ return { status: "unavailable", reason: "harness reported no provider cost" };
810
+ }
811
+ const previous = this.lastProviderCost;
812
+ const current = providerCostAfter.cumulative;
813
+ if (previous && previous.currency !== current.currency) {
814
+ return { status: "unavailable", reason: "provider cost changed currency" };
815
+ }
816
+
817
+ // Provider cost is cumulative, so this operation's share is the rise since the last
818
+ // close. Operations are serialized, which is what makes that difference attributable.
819
+ const delta = previous ? subtractMoney(current, previous) : current;
820
+ if (!delta) {
821
+ return { status: "unavailable", reason: "provider cost decreased" };
822
+ }
823
+ if (delta.currency !== rated.currency) {
824
+ return { status: "unavailable", reason: "provider and rated currencies differ" };
825
+ }
826
+ // Agreement is judged on the ratio, not on string equality. Provider cost arrives as
827
+ // a JSON float, so subtracting two cumulative values yields artifacts like
828
+ // 0.002577469999999998 against an exact 0.00257747 — the same number, and an exact
829
+ // comparison would report a discrepancy on every operation. The ratio rounds at scale
830
+ // 6, which is far tighter than any real undercount (the measured ones were 2x-3.4x).
831
+ const ratio = ratioOf(delta, rated);
832
+ return {
833
+ status: "checked",
834
+ providerDelta: delta,
835
+ ratedTotal: rated,
836
+ ratio,
837
+ matches: ratio === "1",
838
+ };
839
+ }
840
+
841
+ private block(reason: string): void {
842
+ this._blocked = true;
843
+ this._blockedReason = reason;
844
+ }
845
+
846
+ /**
847
+ * Replace state after an out-of-band reconciliation.
848
+ *
849
+ * Deliberately does not mint a record: the adjustment is an accounting correction, not
850
+ * provider usage, and pretending otherwise would put a fabricated operation in the
851
+ * consumer's ledger.
852
+ */
853
+ reconcile(state: AgentSessionMeteringState): { before: AgentSessionMeteringState } {
854
+ const before = this.state;
855
+ this.state = state;
856
+ this.baseline = state.activeBaseline;
857
+ if (state.activeBaseline) this.trustedZeroBaseline = false;
858
+ this._blocked = false;
859
+ this._blockedReason = null;
860
+ return { before };
861
+ }
862
+ }
863
+
864
+ /**
865
+ * Sum the token counts of every inference in an operation.
866
+ *
867
+ * OpenCode's categories are disjoint — measured across five providers, input + output +
868
+ * reasoning + cache equals its reported total exactly — so summing them per category and
869
+ * recomputing the total is faithful rather than an approximation.
870
+ *
871
+ * A category absent from EVERY inference stays absent: a model that never reported cache
872
+ * has told us nothing, and zero-filling would claim it cached nothing.
873
+ */
874
+ export function sumInferenceTokens(inferences: readonly ProviderInference[]): TokenUsage {
875
+ let input = 0;
876
+ let output = 0;
877
+ let cachedRead: number | null = null;
878
+ let cachedWrite: number | null = null;
879
+ let thought: number | null = null;
880
+
881
+ for (const inference of inferences) {
882
+ const tokens = inference.tokens;
883
+ input += tokens.inputTokens;
884
+ output += tokens.outputTokens;
885
+ if (tokens.cachedReadTokens !== undefined) cachedRead = (cachedRead ?? 0) + tokens.cachedReadTokens;
886
+ if (tokens.cachedWriteTokens !== undefined) cachedWrite = (cachedWrite ?? 0) + tokens.cachedWriteTokens;
887
+ if (tokens.thoughtTokens !== undefined) thought = (thought ?? 0) + tokens.thoughtTokens;
888
+ }
889
+
890
+ return disjointTokenUsage({ input, output, cachedRead, cachedWrite, thought });
891
+ }
892
+
893
+ /**
894
+ * Merge per-model ratings into one operation-level view WITHOUT inventing a blended rate.
895
+ *
896
+ * An earlier version kept the first group's unit price beside a cost summed across groups
897
+ * priced differently, so `tokens x unitPrice` did not reproduce `ratedCost` and the record
898
+ * could not be recomputed — the one property §6 and §8 exist to protect.
899
+ *
900
+ * Now the top level carries tokens and the exact total, per-category `pricing` is null
901
+ * because no single rate applies, and `lineItems` carries each model's own rated detail.
902
+ */
903
+ function combineAttributable(
904
+ parts: readonly { usage: AttributableUsage; sample: ProviderInference }[],
905
+ ): AttributableUsage {
906
+ if (parts.length === 1) return parts[0]!.usage;
907
+
908
+ const merged: Partial<Record<TokenCategoryKey, PricedTokenAmount>> = {};
909
+ for (const category of TOKEN_CATEGORY_KEYS) {
910
+ const present = parts
911
+ .map((part) => part.usage[category])
912
+ .filter((amount): amount is PricedTokenAmount => amount !== undefined);
913
+ if (present.length === 0) continue;
914
+ merged[category] = Object.freeze({
915
+ reportedTokens: present.reduce((total, amount) => total + amount.reportedTokens, 0),
916
+ pricedTokens: present.every((amount) => amount.pricedTokens !== null)
917
+ ? present.reduce((total, amount) => total + (amount.pricedTokens ?? 0), 0)
918
+ : null,
919
+ // Deliberately null: several rates priced these tokens, and naming one would make
920
+ // the record look recomputable when it is not. See lineItems.
921
+ pricing: null,
922
+ });
923
+ }
924
+
925
+ // Merged, never dropped. The previous version discarded a line item whose currency could
926
+ // not be added — producing a total of 10 beside line items summing to 20, reported as
927
+ // fully priced.
928
+ let ratedTotal = EMPTY_MONEY_TOTAL;
929
+ for (const part of parts) ratedTotal = mergeTotals(ratedTotal, part.usage.ratedTotal);
930
+
931
+ const lineItems = parts.map((part) =>
932
+ Object.freeze({
933
+ providerId: part.sample.providerID,
934
+ modelId: part.sample.modelID,
935
+ tier: part.usage.pricingKey?.tier ?? "unrated",
936
+ pricingSource: part.usage.pricingSource,
937
+ cacheInputConvention: part.usage.cacheInputConvention,
938
+ totalTokens: part.usage.totalTokens,
939
+ input: part.usage.input,
940
+ output: part.usage.output,
941
+ ...(part.usage.cachedRead ? { cachedRead: part.usage.cachedRead } : {}),
942
+ ...(part.usage.cachedWrite ? { cachedWrite: part.usage.cachedWrite } : {}),
943
+ ...(part.usage.thought ? { thought: part.usage.thought } : {}),
944
+ ratedTotal: part.usage.ratedTotal,
945
+ }),
946
+ );
947
+
948
+ return Object.freeze({
949
+ reportedDelta: sumInferenceTokens(
950
+ parts.map((part) => ({ tokens: part.usage.reportedDelta }) as ProviderInference),
951
+ ),
952
+ // Source and key describe ONE model; with several there is no single answer, and the
953
+ // line items carry the per-model identities instead.
954
+ pricingSource: null,
955
+ pricingKey: null,
956
+ cacheInputConvention: null,
957
+ totalTokens: parts.reduce((total, part) => total + part.usage.totalTokens, 0),
958
+ input: merged.input!,
959
+ output: merged.output!,
960
+ ...(merged.cachedRead ? { cachedRead: merged.cachedRead } : {}),
961
+ ...(merged.cachedWrite ? { cachedWrite: merged.cachedWrite } : {}),
962
+ ...(merged.thought ? { thought: merged.thought } : {}),
963
+ ratedTotal,
964
+ lineItems: Object.freeze(lineItems),
965
+ });
966
+ }
967
+
968
+ /**
969
+ * Describe an inference no operation can claim.
970
+ *
971
+ * Uses the harness's own cost rather than rating it here: pricing would need a policy for
972
+ * a model no operation selected, and the provider has already priced the work. A cost that
973
+ * cannot be represented becomes null — never zero, which would understate a reconciliation
974
+ * against an invoice.
975
+ */
976
+ function toUnallocated(
977
+ inference: ProviderInference,
978
+ kind: "foreign" | "late",
979
+ ): UnallocatedUsageAccrual {
980
+ const decimal = inference.cost === null ? null : decimalFromNumber(inference.cost);
981
+ return {
982
+ usage: inference.tokens,
983
+ // OpenCode reports cost in USD; the currency travels with the figure so a consumer
984
+ // never has to infer it.
985
+ ratedCost: decimal?.ok ? { amount: decimal.value, currency: "USD" } : null,
986
+ reason:
987
+ kind === "foreign"
988
+ ? `inference from provider thread ${inference.sessionID}`
989
+ : `report arrived after the operation it belonged to had closed`,
990
+ };
991
+ }