@qlairoslabs/acp-client 0.4.3 → 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,6 @@
1
+ {
2
+ "kind": "models.dev",
3
+ "commit": "c12e91757aa9a652a506c3ed73d4462a810b5b67",
4
+ "artifactSha256": "44e0e1910b91603951975c12d281b2261e2e0818b0ecadec3567bfb80910fe02",
5
+ "generatedAt": 1788784501527
6
+ }
@@ -0,0 +1,129 @@
1
+ // The token category set, stated once.
2
+ //
3
+ // Every part of the metering pipeline has to agree on what the categories ARE: pricing
4
+ // enumerates them to build schedules, rating maps them onto reported counters, state maps
5
+ // them onto persisted totals, the engine merges them across models, and normalization
6
+ // decides which are required versus optional. Each of those used to carry its own copy of
7
+ // the list — seven copies in three different spellings, two of them untyped inline arrays.
8
+ //
9
+ // That is the same defect `unitPriceFor` was created to remove: a mapping duplicated
10
+ // between validation and rating drifted the moment `billed_as_output` arrived. The copies
11
+ // here would fail more quietly still. An untyped `["total", "input", ...]` used to
12
+ // validate restored state accepts a sixth category silently, so a counter the library
13
+ // knows how to normalize would restore unvalidated and never be rated.
14
+ //
15
+ // So the list lives here, typed against TokenCategory, and every consumer imports it.
16
+ // Adding a category becomes a compile error at each site that must handle it rather than
17
+ // a silent undercount.
18
+
19
+ import type { TokenUsage } from "../types.ts";
20
+
21
+ /** The billable token categories, in canonical (pricing-facing) spelling. */
22
+ export type TokenCategory = "input" | "output" | "cached_read" | "cached_write" | "thought";
23
+
24
+
25
+ /**
26
+ * The same categories in the camelCase spelling used for aggregates.
27
+ *
28
+ * `AttributableUsage` and `UsageTotals` both key their per-category members this way, so
29
+ * one list serves merging and validation alike.
30
+ */
31
+ export type TokenCategoryKey = "input" | "output" | "cachedRead" | "cachedWrite" | "thought";
32
+
33
+
34
+ /** Category → the TokenUsage counter carrying it. */
35
+ export const CATEGORY_FIELD: Readonly<Record<TokenCategory, keyof TokenUsage>> = Object.freeze({
36
+ input: "inputTokens",
37
+ output: "outputTokens",
38
+ cached_read: "cachedReadTokens",
39
+ cached_write: "cachedWriteTokens",
40
+ thought: "thoughtTokens",
41
+ });
42
+
43
+ /** Category → the camelCase aggregate key carrying it. */
44
+ export const CATEGORY_TOTAL: Readonly<Record<TokenCategory, TokenCategoryKey>> = Object.freeze({
45
+ input: "input",
46
+ output: "output",
47
+ cached_read: "cachedRead",
48
+ cached_write: "cachedWrite",
49
+ thought: "thought",
50
+ });
51
+
52
+ // Derived from the maps, not written out again. Both maps are `Record<TokenCategory, …>`,
53
+ // so the compiler already refuses an incomplete one; taking the lists from their keys
54
+ // makes an incomplete LIST unrepresentable too, which a second array literal typed
55
+ // `readonly TokenCategory[]` would not have caught.
56
+ export const TOKEN_CATEGORIES: readonly TokenCategory[] = Object.freeze(
57
+ Object.keys(CATEGORY_FIELD) as TokenCategory[],
58
+ );
59
+
60
+ export const TOKEN_CATEGORY_KEYS: readonly TokenCategoryKey[] = Object.freeze(
61
+ Object.values(CATEGORY_TOTAL),
62
+ );
63
+
64
+ /**
65
+ * Required counters. A malformed one makes the whole report unavailable, because the
66
+ * remaining ones cannot be checked against a total that is itself untrustworthy.
67
+ */
68
+ export const REQUIRED_USAGE_KEYS = ["totalTokens", "inputTokens", "outputTokens"] as const;
69
+
70
+ /**
71
+ * Optional counters, which may legitimately be absent — and, between two cumulative
72
+ * reports, may legitimately appear and disappear.
73
+ */
74
+ export const OPTIONAL_USAGE_KEYS = [
75
+ "cachedReadTokens",
76
+ "cachedWriteTokens",
77
+ "thoughtTokens",
78
+ ] as const;
79
+
80
+ /** Every TokenUsage counter, required first. */
81
+ export const USAGE_KEYS = [...REQUIRED_USAGE_KEYS, ...OPTIONAL_USAGE_KEYS] as const;
82
+
83
+ // The required/optional split cannot be derived from the type, so it is asserted instead:
84
+ // adding a field to TokenUsage without classifying it here is a compile error rather than
85
+ // a counter that normalizes and is then silently dropped from every delta.
86
+ type Assert<T extends true> = T;
87
+ type UsageKeysAreComplete = Assert<
88
+ Exclude<keyof TokenUsage, (typeof USAGE_KEYS)[number]> extends never ? true : false
89
+ >;
90
+ export type { UsageKeysAreComplete };
91
+
92
+ /** A counter must be a finite, non-negative safe integer. Nothing else is a token count. */
93
+ export function isTokenCount(value: unknown): value is number {
94
+ return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
95
+ }
96
+
97
+ /** Per-category counts with absence preserved, as `disjointTokenUsage` accepts them. */
98
+ export interface DisjointTokenCounts {
99
+ readonly input: number;
100
+ readonly output: number;
101
+ readonly cachedRead: number | null;
102
+ readonly cachedWrite: number | null;
103
+ readonly thought: number | null;
104
+ }
105
+
106
+ /**
107
+ * Build a TokenUsage from disjoint per-category counts.
108
+ *
109
+ * The categories do not overlap — measured across five providers, `input + output +
110
+ * thought + cachedRead + cachedWrite` equals the provider's reported total exactly — so
111
+ * `totalTokens` is DERIVED here rather than trusted from a separate field. That identity
112
+ * is what lets the certified path check a provider's arithmetic instead of restating it,
113
+ * and it was previously written out at each site that needed it, under two different
114
+ * absence conventions.
115
+ *
116
+ * A null category is omitted, never zero-filled: "the provider did not report cache
117
+ * writes" and "the provider wrote no cache" are different facts.
118
+ */
119
+ export function disjointTokenUsage(counts: DisjointTokenCounts): TokenUsage {
120
+ const { input, output, cachedRead, cachedWrite, thought } = counts;
121
+ return Object.freeze({
122
+ totalTokens: input + output + (cachedRead ?? 0) + (cachedWrite ?? 0) + (thought ?? 0),
123
+ inputTokens: input,
124
+ outputTokens: output,
125
+ ...(cachedRead !== null ? { cachedReadTokens: cachedRead } : {}),
126
+ ...(cachedWrite !== null ? { cachedWriteTokens: cachedWrite } : {}),
127
+ ...(thought !== null ? { thoughtTokens: thought } : {}),
128
+ });
129
+ }
@@ -0,0 +1,86 @@
1
+ // Which integrations may satisfy `billing_required`. See §12.
2
+ //
3
+ // This registry is LIBRARY-OWNED and deliberately not reachable from consumer
4
+ // configuration. §9 requires provenance to describe evidence rather than configuration: a
5
+ // consumer that could set a `billingApproved` flag on its own adapter object would be
6
+ // asserting the very thing the mode exists to verify.
7
+ //
8
+ // Certification is also not a property of an adapter. "OpenCode" is not approvable;
9
+ // "OpenCode 1.18.x, with the metering plugin handshake succeeding, on this provider route"
10
+ // is. A boolean cannot express a version range or a runtime check, and a stale `true`
11
+ // after a harness upgrade is worse than no gate at all.
12
+
13
+ /** What a certified integration must establish before billing-grade metering is allowed. */
14
+ export interface CertificationRequirements {
15
+ /** Stable id engraved into every record the integration produces. */
16
+ readonly certificationId: string;
17
+ /** The adapter this certification applies to. */
18
+ readonly adapterId: string;
19
+ /** Harness versions the integration has actually been tested against. */
20
+ readonly supportedHarnessVersions: readonly string[];
21
+ /** What the integration observes that ACP alone cannot. */
22
+ readonly description: string;
23
+ }
24
+
25
+ /** The OpenCode plugin integration. See src/metering/opencode/. */
26
+ export const OPENCODE_PLUGIN_CERTIFICATION: CertificationRequirements = Object.freeze({
27
+ certificationId: "opencode-plugin@1",
28
+ adapterId: "opencode",
29
+ // Verified against 1.18.29. The plugin API is not stable across majors — 1.18's hooks
30
+ // differ from those the v2 docs describe — so the range is what was actually exercised.
31
+ supportedHarnessVersions: Object.freeze(["1.18"]),
32
+ description:
33
+ "An OpenCode plugin on the `event` hook observes one assistant message per model " +
34
+ "inference, each carrying its own cost and normalized token counts. This recovers " +
35
+ "the inferences ACP hides: a tool-using turn runs several while PromptResponse.usage " +
36
+ "reports one.",
37
+ });
38
+
39
+ /**
40
+ * Certified integrations, in registration order.
41
+ *
42
+ * An entry here means the mechanism has been measured end to end, not that it is
43
+ * configured. `billing_required` additionally requires a live `InferenceSource` presenting
44
+ * the matching certificationId, so a registry entry alone opens nothing.
45
+ *
46
+ * The ACP-derived backend can never appear here: measured on OpenCode, a turn with three
47
+ * tool calls billed 3.43x what `PromptResponse.usage` reported.
48
+ */
49
+ export const CERTIFIED_INTEGRATIONS: readonly CertificationRequirements[] = Object.freeze([
50
+ OPENCODE_PLUGIN_CERTIFICATION,
51
+ ]);
52
+
53
+ /** The certification for an adapter, or null when none is registered. */
54
+ export function certificationFor(adapterId: string): CertificationRequirements | null {
55
+ return CERTIFIED_INTEGRATIONS.find((entry) => entry.adapterId === adapterId) ?? null;
56
+ }
57
+
58
+ /**
59
+ * Why `billing_required` is refused for an adapter.
60
+ *
61
+ * Names the adapter and what is registered, so the failure is actionable rather than a
62
+ * flat "unsupported".
63
+ */
64
+ export function billingRefusalReason(adapterId: string): string {
65
+ const registered = CERTIFIED_INTEGRATIONS.map((entry) => entry.adapterId);
66
+ const available =
67
+ registered.length === 0
68
+ ? "no integrations are certified yet"
69
+ : `certified adapters: ${registered.join(", ")}`;
70
+ const known = certificationFor(adapterId);
71
+ if (known) {
72
+ // The adapter CAN be certified; what is missing is the live channel.
73
+ return (
74
+ `billing_required for adapter "${adapterId}" needs a live ${known.certificationId} ` +
75
+ `metering channel. Start one with createOpencodeMetering() and pass its ` +
76
+ `inferenceSource, so measurement comes from observed inferences rather than from ` +
77
+ `ACP usage, which reports one inference per prompt while a tool-using turn bills ` +
78
+ `several.`
79
+ );
80
+ }
81
+ return (
82
+ `billing_required needs a certified metering integration for adapter ` +
83
+ `"${adapterId}" — ${available}. ACP usage alone cannot satisfy it: a prompt reports ` +
84
+ `one inference while a tool-using turn bills several.`
85
+ );
86
+ }
@@ -0,0 +1,134 @@
1
+ // Context-window and provider-cost observations from ACP `usage_update`.
2
+ // See 9-6-SPEC-metering.md §5 and §13.
3
+ //
4
+ // These are the two quantities most easily confused with token usage, and with each
5
+ // other:
6
+ //
7
+ // - Context window is what currently OCCUPIES the model's context. It does not
8
+ // aggregate across provider threads and is not a prediction of the next request's
9
+ // input. A handoff resets it to null.
10
+ // - Provider cost is the harness's own cumulative figure for the provider session. It
11
+ // is not an invoice — a subscription harness may report an API-equivalent number —
12
+ // and it is never merged with locally rated cost.
13
+ //
14
+ // ACP delivers both in one `usage_update`, but they have different lifecycles, so they
15
+ // are parsed and stored separately: a cost-only change must not make a context value look
16
+ // newly observed.
17
+
18
+ import { isTokenCount } from "./categories.ts";
19
+ import { decimalFromNumber, type Money } from "./money.ts";
20
+
21
+ export interface ContextWindowStatus {
22
+ readonly internalSessionId: string;
23
+ /** Tokens currently in context per the harness — not billed usage, not the last message. */
24
+ readonly usedTokens: number;
25
+ readonly sizeTokens: number;
26
+ readonly remainingTokens: number;
27
+ /** A ratio in [0, 1], not a percentage in [0, 100]. */
28
+ readonly utilization: number;
29
+ readonly observedAt: number;
30
+ }
31
+
32
+ export interface ProviderCostSnapshot {
33
+ readonly internalSessionId: string;
34
+ readonly cumulative: Money;
35
+ readonly observedAt: number;
36
+ }
37
+
38
+ /**
39
+ * How a `usage_update` changes provider cost.
40
+ *
41
+ * ACP's absent-versus-null distinction is meaningful and must survive parsing: an update
42
+ * that simply does not mention cost says nothing about it, while an explicit null clears
43
+ * it. Collapsing the two — as a `!= null` check does — would silently drop a value on
44
+ * every context-only update.
45
+ */
46
+ export type ProviderCostUpdate =
47
+ | { readonly kind: "unchanged" }
48
+ | { readonly kind: "cleared" }
49
+ | { readonly kind: "observed"; readonly cumulative: Money }
50
+ | { readonly kind: "invalid"; readonly reason: string };
51
+
52
+ /**
53
+ * Parse the context-window half of a `usage_update`.
54
+ *
55
+ * Returns null when the update cannot describe a context window. A zero `size` produces
56
+ * no snapshot rather than an `Infinity` utilization, and malformed counters are never
57
+ * coerced to zero.
58
+ */
59
+ export function parseContextWindow(
60
+ update: unknown,
61
+ internalSessionId: string,
62
+ observedAt: number,
63
+ ): ContextWindowStatus | null {
64
+ if (typeof update !== "object" || update === null) return null;
65
+ const raw = update as Record<string, unknown>;
66
+ const usedTokens = raw.used;
67
+ const sizeTokens = raw.size;
68
+ if (!isTokenCount(usedTokens) || !isTokenCount(sizeTokens)) return null;
69
+ if (sizeTokens === 0) return null;
70
+
71
+ return Object.freeze({
72
+ internalSessionId,
73
+ usedTokens,
74
+ sizeTokens,
75
+ // A harness may report more used than the window holds; remaining is clamped, but the
76
+ // reported `used` is preserved verbatim rather than being clamped to match.
77
+ remainingTokens: Math.max(0, sizeTokens - usedTokens),
78
+ utilization: usedTokens / sizeTokens,
79
+ observedAt,
80
+ });
81
+ }
82
+
83
+ /** Parse the cost half of a `usage_update`, preserving absent-versus-null. */
84
+ export function parseProviderCost(update: unknown): ProviderCostUpdate {
85
+ if (typeof update !== "object" || update === null) return { kind: "unchanged" };
86
+ const raw = update as Record<string, unknown>;
87
+ if (!("cost" in raw) || raw.cost === undefined) return { kind: "unchanged" };
88
+ if (raw.cost === null) return { kind: "cleared" };
89
+
90
+ const cost = raw.cost;
91
+ if (typeof cost !== "object") return { kind: "invalid", reason: `cost is ${typeof cost}` };
92
+ const { amount, currency } = cost as Record<string, unknown>;
93
+ if (typeof currency !== "string" || currency.length === 0) {
94
+ return { kind: "invalid", reason: "cost.currency is missing or empty" };
95
+ }
96
+ if (typeof amount !== "number") {
97
+ return { kind: "invalid", reason: `cost.amount is ${typeof amount}, not a number` };
98
+ }
99
+ const decimal = decimalFromNumber(amount);
100
+ if (!decimal.ok) return { kind: "invalid", reason: `cost.amount ${decimal.reason}` };
101
+
102
+ return {
103
+ kind: "observed",
104
+ cumulative: Object.freeze({ amount: decimal.value, currency }),
105
+ };
106
+ }
107
+
108
+ /** True when two context snapshots differ in anything a consumer would render. */
109
+ export function contextWindowChanged(
110
+ previous: ContextWindowStatus | null,
111
+ next: ContextWindowStatus | null,
112
+ ): boolean {
113
+ if (previous === next) return false;
114
+ if (!previous || !next) return true;
115
+ return (
116
+ previous.internalSessionId !== next.internalSessionId ||
117
+ previous.usedTokens !== next.usedTokens ||
118
+ previous.sizeTokens !== next.sizeTokens
119
+ );
120
+ }
121
+
122
+ /** True when two cost snapshots differ in anything a consumer would render. */
123
+ export function providerCostChanged(
124
+ previous: ProviderCostSnapshot | null,
125
+ next: ProviderCostSnapshot | null,
126
+ ): boolean {
127
+ if (previous === next) return false;
128
+ if (!previous || !next) return true;
129
+ return (
130
+ previous.internalSessionId !== next.internalSessionId ||
131
+ previous.cumulative.amount !== next.cumulative.amount ||
132
+ previous.cumulative.currency !== next.cumulative.currency
133
+ );
134
+ }
@@ -0,0 +1,108 @@
1
+ // Attributable delta calculation. See 9-6-SPEC-metering.md §8.
2
+ //
3
+ // ACP reports cumulative internal-session counters, so "what did THIS operation use" is a
4
+ // subtraction — and a subtraction is only meaningful against a baseline we can justify.
5
+ // The three trusted baselines are: we created the thread (counters began at zero), the
6
+ // consumer restored matching state, or we observed a prior report in this same live
7
+ // session. Anything else is unattributable, and says so, rather than reporting the whole
8
+ // cumulative figure as if one operation had incurred it.
9
+
10
+ import type { TokenUsage } from "../types.ts";
11
+ import { OPTIONAL_USAGE_KEYS, REQUIRED_USAGE_KEYS } from "./categories.ts";
12
+ import type { CounterInterpretation } from "./provider.ts";
13
+
14
+ export type DeltaResult =
15
+ | { readonly kind: "attributable"; readonly delta: TokenUsage }
16
+ /** A counter went backwards: the provider thread's counters restarted. */
17
+ | { readonly kind: "counter_reset"; readonly reason: string }
18
+ /** No trusted baseline, so no subtraction is defensible. */
19
+ | { readonly kind: "baseline_required"; readonly reason: string };
20
+
21
+ /**
22
+ * Subtract a baseline cumulative report from the latest one.
23
+ *
24
+ * `baseline` is null only for a thread the library created, whose counters are known to
25
+ * have started at zero — the one case where absence genuinely means zero.
26
+ */
27
+ export function calculateDelta(
28
+ baseline: TokenUsage | null,
29
+ current: TokenUsage,
30
+ options: {
31
+ readonly trustedZeroBaseline: boolean;
32
+ /** Defaults to cumulative — see counterInterpretationForAdapter. */
33
+ readonly interpretation?: CounterInterpretation;
34
+ },
35
+ ): DeltaResult {
36
+ // A per-turn harness already reports exactly this operation's usage. There is nothing
37
+ // to subtract, no baseline to trust, and no such thing as a counter reset: a counter
38
+ // that "decreased" just means this turn was smaller than the last one.
39
+ if (options.interpretation === "per_turn") {
40
+ return { kind: "attributable", delta: Object.freeze({ ...current }) };
41
+ }
42
+
43
+ if (!baseline && !options.trustedZeroBaseline) {
44
+ return {
45
+ kind: "baseline_required",
46
+ reason: "no trusted baseline for this provider thread; restore prior metering state",
47
+ };
48
+ }
49
+
50
+ // A decreasing counter is a reset, never a negative operation. Reporting a negative
51
+ // delta — or clamping it to zero — would both be inventions.
52
+ for (const key of REQUIRED_USAGE_KEYS) {
53
+ const previous = baseline?.[key] ?? 0;
54
+ if (current[key] < previous) {
55
+ return {
56
+ kind: "counter_reset",
57
+ reason: `${key} decreased from ${previous} to ${current[key]}`,
58
+ };
59
+ }
60
+ }
61
+ for (const key of OPTIONAL_USAGE_KEYS) {
62
+ const previous = baseline?.[key];
63
+ const now = current[key];
64
+ if (previous !== undefined && now !== undefined && now < previous) {
65
+ return { kind: "counter_reset", reason: `${key} decreased from ${previous} to ${now}` };
66
+ }
67
+ }
68
+
69
+ const delta: TokenUsage = {
70
+ totalTokens: current.totalTokens - (baseline?.totalTokens ?? 0),
71
+ inputTokens: current.inputTokens - (baseline?.inputTokens ?? 0),
72
+ outputTokens: current.outputTokens - (baseline?.outputTokens ?? 0),
73
+ };
74
+
75
+ for (const key of OPTIONAL_USAGE_KEYS) {
76
+ const now = current[key];
77
+ if (now === undefined) continue; // not reported now → nothing attributable
78
+ const previous = baseline?.[key];
79
+ if (previous === undefined) {
80
+ // The category appeared with no prior value. From a known-zero baseline the whole
81
+ // amount is this operation's; otherwise the prior value is unknown and no exact
82
+ // delta exists, so the category is omitted rather than guessed.
83
+ if (baseline === null && options.trustedZeroBaseline) delta[key] = now;
84
+ continue;
85
+ }
86
+ delta[key] = now - previous;
87
+ }
88
+
89
+ return { kind: "attributable", delta: Object.freeze(delta) };
90
+ }
91
+
92
+ /**
93
+ * Whether a restored baseline may be used for the thread being opened.
94
+ *
95
+ * All three identifiers must match: a baseline from another logical session, another
96
+ * adapter, or another provider thread describes counters that have nothing to do with
97
+ * this one, and subtracting it would produce a confident wrong number.
98
+ */
99
+ export function baselineMatches(
100
+ baseline: { readonly adapterId: string; readonly internalSessionId: string },
101
+ target: { readonly adapterId: string; readonly internalSessionId: string | null },
102
+ ): boolean {
103
+ return (
104
+ target.internalSessionId !== null &&
105
+ baseline.adapterId === target.adapterId &&
106
+ baseline.internalSessionId === target.internalSessionId
107
+ );
108
+ }