@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,349 @@
1
+ // Turning an attributable delta into a priced, engraved record. See §6, §7, §8.
2
+ //
3
+ // The subtle part is the cache-input convention. Providers disagree about whether
4
+ // `inputTokens` already contains cached reads/writes. Pricing ordinary input at the full
5
+ // reported figure when the provider folds cache into it charges the cached tokens twice —
6
+ // once at the input rate, once at the cache rate. So the schedule declares the convention,
7
+ // the adjustment is applied before rating, and BOTH the raw delta and the adjusted
8
+ // quantity are engraved, so a later reader can see which interpretation produced the
9
+ // number.
10
+
11
+ import type { TokenUsage } from "../types.ts";
12
+ import { CATEGORY_FIELD, TOKEN_CATEGORIES } from "./categories.ts";
13
+ import {
14
+ EMPTY_MONEY_TOTAL,
15
+ addToTotal,
16
+ rateTokens,
17
+ soleAmount,
18
+ type Money,
19
+ type MoneyTotal,
20
+ type TokenUnitPrice,
21
+ } from "./money.ts";
22
+ import {
23
+ unitPriceFor,
24
+ type PricingPolicy,
25
+ type PricingSchedule,
26
+ type PricingSource,
27
+ type TokenCategory,
28
+ } from "./pricing.ts";
29
+
30
+ export interface PricedTokenAmount {
31
+ /** Attributable counter delta reported for this category. */
32
+ readonly reportedTokens: number;
33
+ /** Tokens to which this category's unit price was applied. */
34
+ readonly pricedTokens: number | null;
35
+ readonly pricing:
36
+ | {
37
+ readonly unitPrice: TokenUnitPrice;
38
+ readonly ratedCost: Money;
39
+ }
40
+ | null;
41
+ }
42
+
43
+ /**
44
+ * One model's share of an operation, rated under its own policy.
45
+ *
46
+ * A turn can run several models — compaction and title generation often use a cheaper one
47
+ * than the prompt. Flattening those into a single set of category amounts destroys
48
+ * auditability: the engraved unit price belongs to one model while the cost is a sum
49
+ * across several, so `tokens x unitPrice` no longer reproduces `ratedCost`. Line items
50
+ * keep each rate with the tokens it actually priced.
51
+ */
52
+ export interface RatedLineItem {
53
+ readonly providerId: string;
54
+ readonly modelId: string;
55
+ readonly tier: string;
56
+ readonly pricingSource: PricingSource | null;
57
+ readonly cacheInputConvention: PricingSchedule["cacheInputConvention"] | null;
58
+ readonly totalTokens: number;
59
+ readonly input: PricedTokenAmount;
60
+ readonly output: PricedTokenAmount;
61
+ readonly cachedRead?: PricedTokenAmount;
62
+ readonly cachedWrite?: PricedTokenAmount;
63
+ readonly thought?: PricedTokenAmount;
64
+ /** This model's cost. Carries its own completeness — see MoneyTotal. */
65
+ readonly ratedTotal: MoneyTotal;
66
+ }
67
+
68
+ export interface AttributableUsage {
69
+ /** Unpriced attributable usage before cache-convention adjustment. */
70
+ readonly reportedDelta: TokenUsage;
71
+ readonly pricingSource: PricingSource | null;
72
+ readonly pricingKey:
73
+ | {
74
+ readonly providerId: string;
75
+ readonly modelId: string;
76
+ readonly tier: string;
77
+ /**
78
+ * ISO date this model's catalog entry was last changed upstream, when known.
79
+ *
80
+ * Answers "how old is this price", which the source timestamp cannot: a catalog
81
+ * fetched a minute ago can still carry a year-old rate.
82
+ */
83
+ readonly modelLastUpdated?: string;
84
+ }
85
+ | null;
86
+ readonly cacheInputConvention: PricingSchedule["cacheInputConvention"] | null;
87
+ readonly totalTokens: number;
88
+ readonly input: PricedTokenAmount;
89
+ readonly output: PricedTokenAmount;
90
+ readonly cachedRead?: PricedTokenAmount;
91
+ readonly cachedWrite?: PricedTokenAmount;
92
+ readonly thought?: PricedTokenAmount;
93
+ /**
94
+ * The operation's cost, carrying what it could not include.
95
+ *
96
+ * `soleAmount()` returns a single figure only when exactly one currency was involved and
97
+ * nothing was unaccounted; otherwise the caller must decide what to show.
98
+ */
99
+ readonly ratedTotal: MoneyTotal;
100
+ /**
101
+ * Per-model breakdown, present only when an operation spanned more than one model.
102
+ *
103
+ * When present, the top-level per-category `pricing` is null: there is no single rate to
104
+ * engrave, and showing one model's would misrepresent the total. The line items are then
105
+ * the auditable record, and their rated totals sum to `ratedTotal`.
106
+ */
107
+ readonly lineItems?: readonly RatedLineItem[];
108
+ }
109
+
110
+ export type RatingResult =
111
+ | { readonly ok: true; readonly usage: AttributableUsage }
112
+ | { readonly ok: false; readonly reason: string };
113
+
114
+ /** Facts observed about an operation, used to select one schedule from the frozen policy. */
115
+ export interface BillingFacts {
116
+ /** Context size in tokens, when the backend can supply it as a trusted fact. */
117
+ readonly contextTokens?: number;
118
+ readonly serviceTier?: string;
119
+ readonly batch?: boolean;
120
+ readonly consumer?: Readonly<Record<string, string>>;
121
+ }
122
+
123
+ export type ScheduleSelection =
124
+ | { readonly ok: true; readonly schedule: PricingSchedule }
125
+ | { readonly ok: false; readonly reason: string };
126
+
127
+ /**
128
+ * Select exactly one schedule from the frozen policy.
129
+ *
130
+ * A condition may only be evaluated from a fact the backend actually supplies. When a
131
+ * schedule needs a fact we do not have, the whole selection is unavailable rather than
132
+ * being resolved against a proxy measurement — §7 is explicit that the ACP-derived
133
+ * backend cannot substitute a cumulative delta or `contextAfter` for real context size.
134
+ *
135
+ * Ambiguity is also unavailable: two equally applicable non-default schedules is a
136
+ * catalog problem, and picking one arbitrarily would engrave an arbitrary price.
137
+ */
138
+ export function selectSchedule(policy: PricingPolicy, facts: BillingFacts): ScheduleSelection {
139
+ const matched: PricingSchedule[] = [];
140
+ let fallback: PricingSchedule | null = null;
141
+
142
+ for (const schedule of policy.schedules) {
143
+ let applies = true;
144
+ let isDefault = false;
145
+ for (const condition of schedule.conditions) {
146
+ switch (condition.kind) {
147
+ case "default":
148
+ isDefault = true;
149
+ break;
150
+ case "context_tokens_at_least":
151
+ if (facts.contextTokens === undefined) {
152
+ return {
153
+ ok: false,
154
+ reason:
155
+ `schedule ${schedule.tier} needs a context size this metering backend ` +
156
+ `cannot supply; core will not substitute a proxy measurement`,
157
+ };
158
+ }
159
+ if (facts.contextTokens < condition.tokens) applies = false;
160
+ break;
161
+ case "service_tier":
162
+ if (facts.serviceTier === undefined) {
163
+ return { ok: false, reason: `schedule ${schedule.tier} needs a service tier fact` };
164
+ }
165
+ if (facts.serviceTier !== condition.value) applies = false;
166
+ break;
167
+ case "batch":
168
+ if (facts.batch === undefined) {
169
+ return { ok: false, reason: `schedule ${schedule.tier} needs a batch fact` };
170
+ }
171
+ if (facts.batch !== condition.value) applies = false;
172
+ break;
173
+ case "consumer": {
174
+ const value = facts.consumer?.[condition.name];
175
+ if (value === undefined) {
176
+ return {
177
+ ok: false,
178
+ reason: `schedule ${schedule.tier} needs consumer fact ${condition.name}`,
179
+ };
180
+ }
181
+ if (value !== condition.value) applies = false;
182
+ break;
183
+ }
184
+ }
185
+ if (!applies) break;
186
+ }
187
+ if (!applies) continue;
188
+ if (isDefault) fallback = schedule;
189
+ else matched.push(schedule);
190
+ }
191
+
192
+ if (matched.length > 1) {
193
+ return {
194
+ ok: false,
195
+ reason: `schedules ${matched.map((s) => s.tier).sort().join(", ")} are equally applicable`,
196
+ };
197
+ }
198
+ const selected = matched[0] ?? fallback;
199
+ if (!selected) return { ok: false, reason: "no applicable schedule" };
200
+ return { ok: true, schedule: selected };
201
+ }
202
+
203
+ /**
204
+ * Rate an attributable delta under one schedule.
205
+ *
206
+ * Every category the delta reports is either priced or makes the whole rating
207
+ * unavailable: silently omitting a reported category would understate cost while looking
208
+ * complete. A category the policy declares `not_applicable` but the harness reported is
209
+ * contradictory evidence and invalidates the record (§7) rather than being ignored.
210
+ */
211
+ export function rateDelta(
212
+ delta: TokenUsage,
213
+ policy: PricingPolicy,
214
+ schedule: PricingSchedule,
215
+ ): RatingResult {
216
+ const convention = schedule.cacheInputConvention;
217
+ const amounts: Partial<Record<TokenCategory, PricedTokenAmount>> = {};
218
+ const subtotals: Money[] = [];
219
+
220
+ // Cached tokens folded into the input counter must come out before input is rated.
221
+ let adjustedInput = delta.inputTokens;
222
+ if (convention.cachedRead === "included_in_input") adjustedInput -= delta.cachedReadTokens ?? 0;
223
+ if (convention.cachedWrite === "included_in_input") adjustedInput -= delta.cachedWriteTokens ?? 0;
224
+ if (adjustedInput < 0) {
225
+ return {
226
+ ok: false,
227
+ reason:
228
+ `cached tokens (${delta.cachedReadTokens ?? 0} read, ${delta.cachedWriteTokens ?? 0} write) ` +
229
+ `exceed the ${delta.inputTokens} input tokens they are declared to be included in`,
230
+ };
231
+ }
232
+
233
+ for (const category of TOKEN_CATEGORIES) {
234
+ const reportedTokens = delta[CATEGORY_FIELD[category]];
235
+ if (reportedTokens === undefined) continue; // not reported → not rated, not zeroed
236
+
237
+ if (policy.categoryApplicability[category] === "not_applicable") {
238
+ return {
239
+ ok: false,
240
+ reason: `harness reported ${category} tokens for a model where it is not applicable`,
241
+ };
242
+ }
243
+ const unitPrice = unitPriceFor(schedule, category);
244
+ if (!unitPrice) {
245
+ // An explicit zero needs no price: zero tokens cost zero at any rate, so refusing
246
+ // here would block a whole operation over a category that contributed nothing.
247
+ // OpenCode reports cache.write on every inference, usually as 0, and most catalog
248
+ // entries carry no cache-write price.
249
+ if (reportedTokens === 0) {
250
+ amounts[category] = Object.freeze({
251
+ reportedTokens: 0,
252
+ pricedTokens: null,
253
+ pricing: null,
254
+ });
255
+ continue;
256
+ }
257
+ return { ok: false, reason: `schedule ${schedule.tier} has no ${category} unit price` };
258
+ }
259
+ const pricedTokens = category === "input" ? adjustedInput : reportedTokens;
260
+ const rated = rateTokens(pricedTokens, unitPrice);
261
+ if (!rated.ok) return { ok: false, reason: `rating ${category}: ${rated.reason}` };
262
+
263
+ amounts[category] = Object.freeze({
264
+ reportedTokens,
265
+ pricedTokens,
266
+ pricing: Object.freeze({ unitPrice, ratedCost: rated.value }),
267
+ });
268
+ subtotals.push(rated.value);
269
+ }
270
+
271
+ // The total is the exact sum of the already-rounded engraved subtotals, so a reader can
272
+ // add up what the record shows and land on what the record says.
273
+ let ratedTotal = EMPTY_MONEY_TOTAL;
274
+ for (const subtotal of subtotals) ratedTotal = addToTotal(ratedTotal, subtotal);
275
+ if (ratedTotal.unaccounted > 0) {
276
+ return { ok: false, reason: `${ratedTotal.unaccounted} category subtotal(s) could not be totalled` };
277
+ }
278
+ // One schedule is single-currency by validation, so more than one here means the
279
+ // categories disagree — a catalog fault, not something to average over.
280
+ if (ratedTotal.amounts.length > 1) {
281
+ return {
282
+ ok: false,
283
+ reason: `schedule ${schedule.tier} produced ${ratedTotal.amounts.length} currencies`,
284
+ };
285
+ }
286
+
287
+ return {
288
+ ok: true,
289
+ usage: Object.freeze({
290
+ reportedDelta: delta,
291
+ pricingSource: policy.source,
292
+ pricingKey: Object.freeze({
293
+ providerId: policy.providerId,
294
+ modelId: policy.modelId,
295
+ tier: schedule.tier,
296
+ ...(policy.modelLastUpdated ? { modelLastUpdated: policy.modelLastUpdated } : {}),
297
+ }),
298
+ cacheInputConvention: convention,
299
+ totalTokens: delta.totalTokens,
300
+ input: amounts.input!,
301
+ output: amounts.output!,
302
+ ...(amounts.cached_read ? { cachedRead: amounts.cached_read } : {}),
303
+ ...(amounts.cached_write ? { cachedWrite: amounts.cached_write } : {}),
304
+ ...(amounts.thought ? { thought: amounts.thought } : {}),
305
+ ratedTotal,
306
+ }),
307
+ };
308
+ }
309
+
310
+ /**
311
+ * Why an attributable delta carries no price.
312
+ *
313
+ * `not_attempted` is a consumer choice (`pricing: false`); `failed` is a rating that was
314
+ * tried and could not finish. Collapsing them makes a deliberately unrated session look
315
+ * like one that lost costs — the same conflation `not_applicable` versus `unavailable`
316
+ * avoids for token categories.
317
+ */
318
+ export type UnpricedReason = "not_attempted" | "failed";
319
+
320
+ /**
321
+ * Represent an attributable delta with no pricing applied.
322
+ *
323
+ * Best-effort metering reports real token counts even when no price is available; the
324
+ * null pricing says so explicitly rather than implying the operation was free.
325
+ */
326
+ export function unpricedUsage(
327
+ delta: TokenUsage,
328
+ reason: UnpricedReason = "failed",
329
+ ): AttributableUsage {
330
+ const amount = (reportedTokens: number): PricedTokenAmount =>
331
+ Object.freeze({ reportedTokens, pricedTokens: null, pricing: null });
332
+ return Object.freeze({
333
+ reportedDelta: delta,
334
+ pricingSource: null,
335
+ pricingKey: null,
336
+ cacheInputConvention: null,
337
+ totalTokens: delta.totalTokens,
338
+ input: amount(delta.inputTokens),
339
+ output: amount(delta.outputTokens),
340
+ ...(delta.cachedReadTokens !== undefined ? { cachedRead: amount(delta.cachedReadTokens) } : {}),
341
+ ...(delta.cachedWriteTokens !== undefined
342
+ ? { cachedWrite: amount(delta.cachedWriteTokens) }
343
+ : {}),
344
+ ...(delta.thoughtTokens !== undefined ? { thought: amount(delta.thoughtTokens) } : {}),
345
+ // A rating that failed leaves an unaccounted contribution; one never attempted leaves
346
+ // an empty total, because nothing was lost.
347
+ ratedTotal: reason === "failed" ? addToTotal(EMPTY_MONEY_TOTAL, null) : EMPTY_MONEY_TOTAL,
348
+ });
349
+ }
@@ -0,0 +1,274 @@
1
+ // The operation metering record and its enforcement policy. See §9, §12.
2
+ //
3
+ // One record per ACP operation the library can observe — not one per hidden model
4
+ // inference. An ACP prompt may conceal retries, compaction, or several model calls, and
5
+ // the ACP-derived backend cannot see them; a certified backend can, and says so through
6
+ // provenance.
7
+ //
8
+ // An unavailable record is still a record. It proves an operation happened while refusing
9
+ // to assert it cost zero, which is the difference between "we don't know" and a false
10
+ // accounting entry.
11
+
12
+ import type { TokenUsage } from "../types.ts";
13
+ import type { ContextWindowStatus, ProviderCostSnapshot } from "./context.ts";
14
+ import type { Money } from "./money.ts";
15
+ import type { AttributableUsage } from "./rating.ts";
16
+ import type { AgentSessionMeteringState, StateRestoration } from "./state.ts";
17
+ import type { PricingConfiguration } from "./pricing.ts";
18
+ import type { InferenceSource } from "./engine.ts";
19
+
20
+ export type MeteredOperationKind =
21
+ | "prompt"
22
+ | "internal_command"
23
+ | "handoff_summary"
24
+ | "handoff_seed";
25
+
26
+ export type OperationOutcome = "completed" | "cancelled" | "error";
27
+
28
+ export type MeteringUsageResult =
29
+ | {
30
+ readonly status: "metered";
31
+ readonly reportedCumulative: TokenUsage;
32
+ readonly attributable: AttributableUsage;
33
+ }
34
+ | {
35
+ readonly status: "usage_unavailable" | "baseline_required" | "counter_reset";
36
+ readonly reportedCumulative?: TokenUsage;
37
+ readonly reason: string;
38
+ };
39
+
40
+ export type MeteringPricingStatus =
41
+ | "priced"
42
+ | "not_configured"
43
+ | "not_attributable"
44
+ | "pricing_unavailable";
45
+
46
+ export interface ProviderIdentitySnapshot {
47
+ readonly adapterId: string;
48
+ /** Provider catalog key when established by structured evidence, else null. */
49
+ readonly providerId: string | null;
50
+ readonly model: string | null;
51
+ }
52
+
53
+ /**
54
+ * Where a record's numbers came from and how far they can be trusted.
55
+ *
56
+ * These describe EVIDENCE, not configuration. A consumer cannot promote a record by
57
+ * asserting a stronger provenance: `routing` in particular is only ever "observed" or
58
+ * "unknown" here, because a library spawning a subprocess cannot verify that no model
59
+ * traffic bypassed it. Network isolation is a deployment property, not a library claim.
60
+ */
61
+ export interface MeteringProvenance {
62
+ readonly source: "certified" | "acp_usage" | "none";
63
+ readonly measurement: "provider_normalized" | "acp_derived" | "unavailable";
64
+ readonly routing: "observed" | "unknown";
65
+ readonly attribution: "complete" | "partial" | "unavailable";
66
+ /** Present for ACP-derived cumulative delta records. */
67
+ readonly counterInterpretation?: "cumulative" | "per_turn";
68
+ /** Present only when a recognized certified integration produced the record. */
69
+ readonly certificationId?: string;
70
+ }
71
+
72
+ /**
73
+ * Our rated cost checked against the provider's own reported cost for the same operation.
74
+ *
75
+ * The ACP-derived backend sees one record per ACP operation, but a harness may run SEVERAL
76
+ * model inferences inside one — measured on OpenCode, a turn with N tool calls bills for
77
+ * roughly N+1 inferences while `PromptResponse.usage` reports one. Token math alone cannot
78
+ * detect that; the provider's own cumulative cost can.
79
+ *
80
+ * `ratio` is providerDelta / ratedTotal. 1 means we accounted for everything; 3.43 means
81
+ * the provider charged 3.43x what we saw. Consumers choose their own tolerance — a
82
+ * scale-12 rounding difference is not the same as a missing inference.
83
+ */
84
+ export type CostReconciliation =
85
+ | {
86
+ readonly status: "checked";
87
+ /** Provider cumulative cost consumed by this operation. */
88
+ readonly providerDelta: Money;
89
+ readonly ratedTotal: Money;
90
+ /** providerDelta / ratedTotal at scale 6, or null when it cannot be formed. */
91
+ readonly ratio: string | null;
92
+ /** True only when the two agree exactly. */
93
+ readonly matches: boolean;
94
+ }
95
+ | {
96
+ readonly status: "unavailable";
97
+ readonly reason: string;
98
+ };
99
+
100
+ export interface OperationMeteringRecord {
101
+ readonly operationId: string;
102
+ readonly operationKind: MeteredOperationKind;
103
+ readonly outcome: OperationOutcome;
104
+ readonly startedAt: number;
105
+ readonly completedAt: number;
106
+
107
+ readonly agentSessionId: string;
108
+ readonly internalSessionId: string | null;
109
+ readonly provider: ProviderIdentitySnapshot;
110
+ readonly provenance: MeteringProvenance;
111
+
112
+ readonly usage: MeteringUsageResult;
113
+ readonly pricingStatus: MeteringPricingStatus;
114
+ readonly pricingFailureReason?: string;
115
+ /** Latest observation received by completion; not guaranteed to include this operation. */
116
+ readonly contextAfter: ContextWindowStatus | null;
117
+ /** Latest cumulative provider observation; not asserted to be an invoice. */
118
+ readonly providerCostAfter: ProviderCostSnapshot | null;
119
+ /**
120
+ * Our rated cost against the provider's own, when both are available.
121
+ *
122
+ * The only signal the ACP-derived backend has for inferences it could not see.
123
+ */
124
+ readonly costReconciliation: CostReconciliation;
125
+
126
+ /** State the consumer can persist and pass to a reopened AgentSession. */
127
+ readonly nextState: AgentSessionMeteringState;
128
+ }
129
+
130
+ /**
131
+ * Evidence policy, not authentication type. There is no subscription mode and no
132
+ * subscription inference.
133
+ *
134
+ * `telemetry_required` is strict handling of ACP-derived telemetry — useful for tests and
135
+ * for consumers that prefer to stop rather than accumulate gaps. It is explicitly NOT a
136
+ * billing guarantee: ACP advertises no usage capability, so the library can fail fast on
137
+ * known preflight conditions but cannot prove a harness will return usage until it does.
138
+ *
139
+ * `billing_required` needs a registered certified integration and is rejected until one
140
+ * exists. Plain ACP usage can never activate it.
141
+ */
142
+ export type MeteringEnforcement = "best_effort" | "telemetry_required" | "billing_required";
143
+
144
+ export interface MeteringConfig {
145
+ readonly enforcement?: MeteringEnforcement;
146
+ readonly pricing?: PricingConfiguration;
147
+ readonly initialState?: AgentSessionMeteringState;
148
+ /**
149
+ * Override how this harness's ACP counters are read.
150
+ *
151
+ * Defaults to the adapter's measured evidence. Supply it when you know your harness
152
+ * version reports differently than the library has recorded — it is evidence you are
153
+ * asserting, and it is stamped into every record's provenance. The library never infers
154
+ * it at runtime (§4).
155
+ */
156
+ readonly counterInterpretation?: "cumulative" | "per_turn";
157
+ /**
158
+ * A certified per-inference source, replacing ACP usage as the measurement.
159
+ *
160
+ * Required by `billing_required`: ACP reports one inference per prompt while a
161
+ * tool-using turn bills several. See `createOpencodeMetering()`.
162
+ */
163
+ readonly inferenceSource?: InferenceSource;
164
+ }
165
+
166
+ export interface AgentSessionMeteringSnapshot extends AgentSessionMeteringState {
167
+ readonly enforcement: MeteringEnforcement;
168
+ /**
169
+ * Outcome of restoring `MeteringConfig.initialState`.
170
+ *
171
+ * The restored version is DERIVED from `AgentSessionMeteringState["version"]` rather
172
+ * than written literally. Hardcoding it left the snapshot reporting a restore of
173
+ * version 2 beside version-3 state after the last bump — a hand-maintained copy of a
174
+ * fact that already exists elsewhere will eventually disagree with it.
175
+ */
176
+ readonly restoration:
177
+ | Exclude<StateRestoration, { status: "restored" }>
178
+ | { status: "restored"; version: AgentSessionMeteringState["version"] };
179
+ readonly blocked: boolean;
180
+ readonly blockedReason: string | null;
181
+ /**
182
+ * Reports the certified source is still missing.
183
+ *
184
+ * Retractable — a late arrival discharges its gap — and deliberately NOT a blocking
185
+ * condition, because the usage lands in unallocated when it appears. A count that stops
186
+ * falling is the signal worth alerting on, which is why it is surfaced here.
187
+ */
188
+ readonly outstandingReports: number;
189
+ readonly lastOperation: OperationMeteringRecord | null;
190
+ }
191
+
192
+ /**
193
+ * Provenance for an ACP-derived record.
194
+ *
195
+ * The interpretation is stamped in rather than assumed, so a stored record says how its
196
+ * counters were read — the one thing ACP itself does not settle.
197
+ */
198
+ export function acpProvenance(
199
+ counterInterpretation: "cumulative" | "per_turn",
200
+ ): MeteringProvenance {
201
+ return Object.freeze({
202
+ source: "acp_usage",
203
+ measurement: "acp_derived",
204
+ routing: "unknown",
205
+ attribution: "partial",
206
+ counterInterpretation,
207
+ });
208
+ }
209
+
210
+ /** Provenance for an ordinary cumulative ACP-derived record. */
211
+ export const ACP_PROVENANCE: MeteringProvenance = acpProvenance("cumulative");
212
+
213
+ /** Provenance for an operation whose usage could not be established at all. */
214
+ export const UNAVAILABLE_PROVENANCE: MeteringProvenance = Object.freeze({
215
+ source: "none",
216
+ measurement: "unavailable",
217
+ routing: "unknown",
218
+ attribution: "unavailable",
219
+ });
220
+
221
+ export interface MeteringReconciliation {
222
+ readonly state: AgentSessionMeteringState;
223
+ readonly reason: string;
224
+ /** Consumer/provider incident, invoice, or audit identifier. */
225
+ readonly reference?: string;
226
+ }
227
+
228
+ /** Thrown when a strict mode refuses to start or continue a token-consuming operation. */
229
+ export class MeteringPreflightError extends Error {
230
+ constructor(message: string) {
231
+ super(message);
232
+ this.name = "MeteringPreflightError";
233
+ }
234
+ }
235
+
236
+ /**
237
+ * Thrown when an AgentSession operation fails, carrying the metering record.
238
+ *
239
+ * A failed operation can still have consumed tokens, so the record has to survive the
240
+ * rejection rather than only reaching event subscribers.
241
+ */
242
+ export class AgentSessionOperationError extends Error {
243
+ readonly operationId: string;
244
+ readonly metering: OperationMeteringRecord;
245
+
246
+ constructor(operationId: string, metering: OperationMeteringRecord, cause: unknown) {
247
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
248
+ this.name = "AgentSessionOperationError";
249
+ this.operationId = operationId;
250
+ this.metering = metering;
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Thrown when a handoff fails, carrying the records it produced before and during failure.
256
+ *
257
+ * A rejected handoff cannot return a HandoffResult, but the summary and seed prompts it
258
+ * already ran consumed real tokens, so their records must still reach the caller.
259
+ */
260
+ export class AgentSessionHandoffError extends Error {
261
+ readonly handoffId: string;
262
+ readonly meteringRecords: readonly OperationMeteringRecord[];
263
+
264
+ constructor(
265
+ handoffId: string,
266
+ meteringRecords: readonly OperationMeteringRecord[],
267
+ cause: unknown,
268
+ ) {
269
+ super(cause instanceof Error ? cause.message : String(cause), { cause });
270
+ this.name = "AgentSessionHandoffError";
271
+ this.handoffId = handoffId;
272
+ this.meteringRecords = Object.freeze([...meteringRecords]);
273
+ }
274
+ }