@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.
- package/CHANGELOG-metering.md +288 -0
- package/package.json +6 -3
- package/src/agent-session.ts +416 -15
- package/src/client.ts +57 -1
- package/src/controller.ts +30 -0
- package/src/index.ts +151 -0
- package/src/metering/catalog/build.ts +285 -0
- package/src/metering/catalog/index.ts +243 -0
- package/src/metering/catalog/live.ts +171 -0
- package/src/metering/catalog/models-dev.catalog.json +8797 -0
- package/src/metering/catalog/models-dev.meta.json +6 -0
- package/src/metering/categories.ts +129 -0
- package/src/metering/certification.ts +86 -0
- package/src/metering/context.ts +134 -0
- package/src/metering/delta.ts +108 -0
- package/src/metering/engine.ts +991 -0
- package/src/metering/money.ts +356 -0
- package/src/metering/opencode/channel.ts +389 -0
- package/src/metering/opencode/index.ts +159 -0
- package/src/metering/opencode/plugin.js +90 -0
- package/src/metering/opencode/profile.ts +159 -0
- package/src/metering/pricing.ts +285 -0
- package/src/metering/provider.ts +121 -0
- package/src/metering/rating.ts +349 -0
- package/src/metering/record.ts +274 -0
- package/src/metering/state.ts +421 -0
- package/src/metering/usage.ts +72 -0
- package/src/types.ts +28 -5
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
// Money and token unit prices. See 9-6-SPEC-metering.md §6.
|
|
2
|
+
//
|
|
3
|
+
// Every amount is a canonical, non-negative plain decimal STRING, and all arithmetic
|
|
4
|
+
// runs on BigInt. Binary floating point never touches a rated cost: `0.1 + 0.2` must not
|
|
5
|
+
// be able to make a historical record irreproducible, and records are engraved once and
|
|
6
|
+
// read back years later.
|
|
7
|
+
//
|
|
8
|
+
// Rating is `tokens * unitPrice.amount / unitPrice.perTokens`, evaluated exactly and then
|
|
9
|
+
// rounded ONCE to scale 12 using round-half-even. Category subtotals round independently;
|
|
10
|
+
// sums of already-rounded subtotals are exact and are never re-rounded.
|
|
11
|
+
|
|
12
|
+
/** Maximum fractional decimal places of a rated result. */
|
|
13
|
+
export const MAX_SCALE = 12;
|
|
14
|
+
|
|
15
|
+
/** Canonical decimal input: no sign, exponent, grouping separator, or leading zero. */
|
|
16
|
+
const DECIMAL_PATTERN = /^(?:0|[1-9][0-9]*)(?:\.[0-9]+)?$/;
|
|
17
|
+
|
|
18
|
+
export interface Money {
|
|
19
|
+
readonly amount: string;
|
|
20
|
+
readonly currency: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface TokenUnitPrice {
|
|
24
|
+
readonly amount: string;
|
|
25
|
+
readonly currency: string;
|
|
26
|
+
/** Tokens the amount buys, normally 1_000_000. Explicit rather than encoded in a name. */
|
|
27
|
+
readonly perTokens: number;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export type MoneyResult<T> =
|
|
31
|
+
| { readonly ok: true; readonly value: T }
|
|
32
|
+
| { readonly ok: false; readonly reason: string };
|
|
33
|
+
|
|
34
|
+
/** An exact non-negative decimal: `units / 10^scale`. Internal representation only. */
|
|
35
|
+
interface Decimal {
|
|
36
|
+
readonly units: bigint;
|
|
37
|
+
readonly scale: number;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const TEN = 10n;
|
|
41
|
+
|
|
42
|
+
function pow10(n: number): bigint {
|
|
43
|
+
return TEN ** BigInt(n);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Parse a canonical decimal string. Rejects anything DECIMAL_PATTERN does not accept. */
|
|
47
|
+
export function parseDecimal(text: string): Decimal | null {
|
|
48
|
+
if (typeof text !== "string" || !DECIMAL_PATTERN.test(text)) return null;
|
|
49
|
+
const dot = text.indexOf(".");
|
|
50
|
+
if (dot === -1) return { units: BigInt(text), scale: 0 };
|
|
51
|
+
const fraction = text.slice(dot + 1);
|
|
52
|
+
return { units: BigInt(text.slice(0, dot) + fraction), scale: fraction.length };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Render a decimal canonically: trailing fractional zeroes trimmed, zero as "0". */
|
|
56
|
+
export function formatDecimal(value: Decimal): string {
|
|
57
|
+
if (value.scale === 0) return value.units.toString();
|
|
58
|
+
const digits = value.units.toString().padStart(value.scale + 1, "0");
|
|
59
|
+
const whole = digits.slice(0, digits.length - value.scale);
|
|
60
|
+
const fraction = digits.slice(digits.length - value.scale).replace(/0+$/, "");
|
|
61
|
+
return fraction.length === 0 ? whole : `${whole}.${fraction}`;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/** Rescale to a common scale so two decimals can be compared or added exactly. */
|
|
65
|
+
function align(a: Decimal, b: Decimal): { a: bigint; b: bigint; scale: number } {
|
|
66
|
+
const scale = Math.max(a.scale, b.scale);
|
|
67
|
+
return {
|
|
68
|
+
a: a.units * pow10(scale - a.scale),
|
|
69
|
+
b: b.units * pow10(scale - b.scale),
|
|
70
|
+
scale,
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Divide non-negative bigints, rounding half-even (banker's rounding).
|
|
76
|
+
*
|
|
77
|
+
* Half-even rather than half-up because subtotals are summed: half-up biases every tie
|
|
78
|
+
* in the same direction, so a long session accumulates a systematic overcharge.
|
|
79
|
+
*/
|
|
80
|
+
function divideRoundHalfEven(numerator: bigint, denominator: bigint): bigint {
|
|
81
|
+
const quotient = numerator / denominator;
|
|
82
|
+
const remainder = numerator % denominator;
|
|
83
|
+
if (remainder === 0n) return quotient;
|
|
84
|
+
const doubled = remainder * 2n;
|
|
85
|
+
if (doubled > denominator) return quotient + 1n;
|
|
86
|
+
if (doubled < denominator) return quotient;
|
|
87
|
+
return quotient % 2n === 0n ? quotient : quotient + 1n;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
/** Validate a canonical money value without interpreting it. */
|
|
91
|
+
export function isValidMoney(value: Money): boolean {
|
|
92
|
+
return (
|
|
93
|
+
typeof value?.currency === "string" &&
|
|
94
|
+
value.currency.length > 0 &&
|
|
95
|
+
parseDecimal(value.amount) !== null
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Canonicalize a money amount, e.g. "0.50" → "0.5", "0.0" → "0". */
|
|
100
|
+
export function canonicalizeMoney(value: Money): MoneyResult<Money> {
|
|
101
|
+
if (typeof value?.currency !== "string" || value.currency.length === 0) {
|
|
102
|
+
return { ok: false, reason: "currency must be a non-empty string" };
|
|
103
|
+
}
|
|
104
|
+
const parsed = parseDecimal(value.amount);
|
|
105
|
+
if (!parsed) return { ok: false, reason: `amount ${JSON.stringify(value.amount)} is not a canonical decimal` };
|
|
106
|
+
return { ok: true, value: Object.freeze({ amount: formatDecimal(parsed), currency: value.currency }) };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function validateUnitPrice(price: TokenUnitPrice): MoneyResult<{ amount: Decimal; scale: bigint }> {
|
|
110
|
+
if (typeof price?.currency !== "string" || price.currency.length === 0) {
|
|
111
|
+
return { ok: false, reason: "unit price currency must be a non-empty string" };
|
|
112
|
+
}
|
|
113
|
+
if (!Number.isSafeInteger(price.perTokens) || price.perTokens <= 0) {
|
|
114
|
+
return { ok: false, reason: `perTokens ${String(price.perTokens)} must be a positive safe integer` };
|
|
115
|
+
}
|
|
116
|
+
const amount = parseDecimal(price.amount);
|
|
117
|
+
if (!amount) {
|
|
118
|
+
return { ok: false, reason: `unit price ${JSON.stringify(price.amount)} is not a canonical decimal` };
|
|
119
|
+
}
|
|
120
|
+
return { ok: true, value: { amount, scale: BigInt(price.perTokens) } };
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/**
|
|
124
|
+
* Rate a token count at a unit price.
|
|
125
|
+
*
|
|
126
|
+
* Exact value is `tokens * amount / perTokens`; it is evaluated in full precision and
|
|
127
|
+
* rounded exactly once, to MAX_SCALE, half-even.
|
|
128
|
+
*/
|
|
129
|
+
export function rateTokens(tokens: number, price: TokenUnitPrice): MoneyResult<Money> {
|
|
130
|
+
if (!Number.isSafeInteger(tokens) || tokens < 0) {
|
|
131
|
+
return { ok: false, reason: `token count ${String(tokens)} must be a non-negative safe integer` };
|
|
132
|
+
}
|
|
133
|
+
const validated = validateUnitPrice(price);
|
|
134
|
+
if (!validated.ok) return validated;
|
|
135
|
+
const { amount, scale: perTokens } = validated.value;
|
|
136
|
+
|
|
137
|
+
// tokens * (units / 10^scale) / perTokens, expressed at MAX_SCALE:
|
|
138
|
+
// numerator = tokens * units * 10^MAX_SCALE
|
|
139
|
+
// denominator = perTokens * 10^scale
|
|
140
|
+
const numerator = BigInt(tokens) * amount.units * pow10(MAX_SCALE);
|
|
141
|
+
const denominator = perTokens * pow10(amount.scale);
|
|
142
|
+
const units = divideRoundHalfEven(numerator, denominator);
|
|
143
|
+
return {
|
|
144
|
+
ok: true,
|
|
145
|
+
value: Object.freeze({
|
|
146
|
+
amount: formatDecimal({ units, scale: MAX_SCALE }),
|
|
147
|
+
currency: price.currency,
|
|
148
|
+
}),
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/**
|
|
153
|
+
* Add money values exactly. Same-currency only — core never converts or compares across
|
|
154
|
+
* currencies, so a mixed-currency sum is an error rather than a silent coercion.
|
|
155
|
+
*
|
|
156
|
+
* Inputs are already-engraved subtotals at scale <= MAX_SCALE, so the sum is exact and is
|
|
157
|
+
* never re-rounded. This is also the cross-operation accumulation rule for
|
|
158
|
+
* `AgentSessionMeteringState.ratedCosts`.
|
|
159
|
+
*/
|
|
160
|
+
export function addMoney(a: Money, b: Money): MoneyResult<Money> {
|
|
161
|
+
if (a.currency !== b.currency) {
|
|
162
|
+
return { ok: false, reason: `cannot add ${a.currency} to ${b.currency}` };
|
|
163
|
+
}
|
|
164
|
+
const left = parseDecimal(a.amount);
|
|
165
|
+
const right = parseDecimal(b.amount);
|
|
166
|
+
if (!left || !right) return { ok: false, reason: "operand is not a canonical decimal" };
|
|
167
|
+
const aligned = align(left, right);
|
|
168
|
+
return {
|
|
169
|
+
ok: true,
|
|
170
|
+
value: Object.freeze({
|
|
171
|
+
amount: formatDecimal({ units: aligned.a + aligned.b, scale: aligned.scale }),
|
|
172
|
+
currency: a.currency,
|
|
173
|
+
}),
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/**
|
|
178
|
+
* Sum money values, keeping one accumulated amount per currency and never merging two.
|
|
179
|
+
* Used for operation totals and for `ratedCosts` accumulation.
|
|
180
|
+
*/
|
|
181
|
+
export function sumMoneyByCurrency(values: readonly Money[]): MoneyResult<readonly Money[]> {
|
|
182
|
+
const totals = new Map<string, Money>();
|
|
183
|
+
for (const value of values) {
|
|
184
|
+
const existing = totals.get(value.currency);
|
|
185
|
+
if (!existing) {
|
|
186
|
+
const canonical = canonicalizeMoney(value);
|
|
187
|
+
if (!canonical.ok) return canonical;
|
|
188
|
+
totals.set(value.currency, canonical.value);
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const sum = addMoney(existing, value);
|
|
192
|
+
if (!sum.ok) return sum;
|
|
193
|
+
totals.set(value.currency, sum.value);
|
|
194
|
+
}
|
|
195
|
+
return { ok: true, value: Object.freeze([...totals.values()]) };
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Subtract `b` from `a`, or null when the result would be negative or currencies differ.
|
|
200
|
+
*
|
|
201
|
+
* Null rather than a negative: a cumulative provider figure that went DOWN is not a
|
|
202
|
+
* refund, it is a counter that restarted, and treating it as arithmetic would hide that.
|
|
203
|
+
*/
|
|
204
|
+
export function subtractMoney(a: Money, b: Money): Money | null {
|
|
205
|
+
if (a.currency !== b.currency) return null;
|
|
206
|
+
const left = parseDecimal(a.amount);
|
|
207
|
+
const right = parseDecimal(b.amount);
|
|
208
|
+
if (!left || !right) return null;
|
|
209
|
+
const aligned = align(left, right);
|
|
210
|
+
if (aligned.a < aligned.b) return null;
|
|
211
|
+
return Object.freeze({
|
|
212
|
+
amount: formatDecimal({ units: aligned.a - aligned.b, scale: aligned.scale }),
|
|
213
|
+
currency: a.currency,
|
|
214
|
+
});
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
/**
|
|
218
|
+
* Ratio of two same-currency amounts, as a decimal string at scale 6.
|
|
219
|
+
*
|
|
220
|
+
* Used to express how far a rated cost is from the provider's own figure: "3.43" means
|
|
221
|
+
* the provider charged 3.43x what we accounted for. Returns null when the denominator is
|
|
222
|
+
* zero or the currencies differ — a ratio against nothing is not a number.
|
|
223
|
+
*/
|
|
224
|
+
export function ratioOf(numerator: Money, denominator: Money): string | null {
|
|
225
|
+
if (numerator.currency !== denominator.currency) return null;
|
|
226
|
+
const top = parseDecimal(numerator.amount);
|
|
227
|
+
const bottom = parseDecimal(denominator.amount);
|
|
228
|
+
if (!top || !bottom || bottom.units === 0n) return null;
|
|
229
|
+
const RATIO_SCALE = 6;
|
|
230
|
+
// (top.units / 10^top.scale) / (bottom.units / 10^bottom.scale), at RATIO_SCALE
|
|
231
|
+
const scaled = top.units * pow10(bottom.scale) * pow10(RATIO_SCALE);
|
|
232
|
+
const units = divideRoundHalfEven(scaled, bottom.units * pow10(top.scale));
|
|
233
|
+
return formatDecimal({ units, scale: RATIO_SCALE });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* A running money total that cannot hide what it failed to include.
|
|
238
|
+
*
|
|
239
|
+
* `Money[]` had no way to say "one contribution did not make it", so every accumulation
|
|
240
|
+
* site wrote `if (sum.ok) total = sum.value` and a failure silently became a no-op. That
|
|
241
|
+
* single missing concept produced six separate under-reporting bugs, including an
|
|
242
|
+
* operation that dropped half its cost while reporting itself fully priced.
|
|
243
|
+
*
|
|
244
|
+
* Tokens never had this problem: `UsageCategoryTotal` forces a coverage answer. This is the
|
|
245
|
+
* same idea for money.
|
|
246
|
+
*/
|
|
247
|
+
export interface MoneyTotal {
|
|
248
|
+
/** One accumulated amount per currency. Empty when nothing was added. */
|
|
249
|
+
readonly amounts: readonly Money[];
|
|
250
|
+
/**
|
|
251
|
+
* Contributions that could not be included — absent, malformed, or uncombinable.
|
|
252
|
+
*
|
|
253
|
+
* Non-zero means `amounts` is a LOWER BOUND.
|
|
254
|
+
*/
|
|
255
|
+
readonly unaccounted: number;
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
export const EMPTY_MONEY_TOTAL: MoneyTotal = Object.freeze({
|
|
259
|
+
amounts: Object.freeze([]),
|
|
260
|
+
unaccounted: 0,
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
/**
|
|
264
|
+
* Add a contribution to a total.
|
|
265
|
+
*
|
|
266
|
+
* Deliberately returns a total rather than a Result: there is no `.ok` to forget, so a
|
|
267
|
+
* failure cannot silently become a no-op. A null or unusable contribution is COUNTED.
|
|
268
|
+
*/
|
|
269
|
+
export function addToTotal(total: MoneyTotal, addition: Money | null): MoneyTotal {
|
|
270
|
+
if (!addition) {
|
|
271
|
+
return Object.freeze({ amounts: total.amounts, unaccounted: total.unaccounted + 1 });
|
|
272
|
+
}
|
|
273
|
+
const canonical = canonicalizeMoney(addition);
|
|
274
|
+
if (!canonical.ok) {
|
|
275
|
+
return Object.freeze({ amounts: total.amounts, unaccounted: total.unaccounted + 1 });
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const amounts: Money[] = [];
|
|
279
|
+
let merged = false;
|
|
280
|
+
for (const existing of total.amounts) {
|
|
281
|
+
if (existing.currency !== canonical.value.currency) {
|
|
282
|
+
amounts.push(existing);
|
|
283
|
+
continue;
|
|
284
|
+
}
|
|
285
|
+
const sum = addMoney(existing, canonical.value);
|
|
286
|
+
if (!sum.ok) {
|
|
287
|
+
// Cannot happen for two canonical same-currency amounts, but counting beats
|
|
288
|
+
// assuming: an uncounted drop is the bug this type exists to prevent.
|
|
289
|
+
return Object.freeze({ amounts: total.amounts, unaccounted: total.unaccounted + 1 });
|
|
290
|
+
}
|
|
291
|
+
amounts.push(sum.value);
|
|
292
|
+
merged = true;
|
|
293
|
+
}
|
|
294
|
+
if (!merged) amounts.push(canonical.value);
|
|
295
|
+
return Object.freeze({ amounts: Object.freeze(amounts), unaccounted: total.unaccounted });
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/** Merge one total into another, preserving both unaccounted counts. */
|
|
299
|
+
export function mergeTotals(a: MoneyTotal, b: MoneyTotal): MoneyTotal {
|
|
300
|
+
let merged = a;
|
|
301
|
+
for (const amount of b.amounts) merged = addToTotal(merged, amount);
|
|
302
|
+
return Object.freeze({ amounts: merged.amounts, unaccounted: merged.unaccounted + b.unaccounted });
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
/** True when every contribution was accounted for. */
|
|
306
|
+
export function isTotalComplete(total: MoneyTotal): boolean {
|
|
307
|
+
return total.unaccounted === 0;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
/**
|
|
311
|
+
* The single amount a total represents, or null.
|
|
312
|
+
*
|
|
313
|
+
* Null whenever there is not exactly one — several currencies, none, or something
|
|
314
|
+
* unaccounted. Callers that want one number must therefore handle the ambiguous case
|
|
315
|
+
* rather than reading `amounts[0]` and hoping.
|
|
316
|
+
*/
|
|
317
|
+
export function soleAmount(total: MoneyTotal): Money | null {
|
|
318
|
+
return total.unaccounted === 0 && total.amounts.length === 1 ? total.amounts[0]! : null;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** Build a total from a single known amount. */
|
|
322
|
+
export function totalOf(amount: Money | null): MoneyTotal {
|
|
323
|
+
return addToTotal(EMPTY_MONEY_TOTAL, amount);
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Convert an ACP-reported JSON number cost into a canonical decimal string.
|
|
328
|
+
*
|
|
329
|
+
* `String(n)` is already the shortest round-trippable representation; this only expands
|
|
330
|
+
* exponent notation into plain decimal form. It preserves the number the SDK delivered
|
|
331
|
+
* and cannot recover precision JSON parsing already lost — the result stays explicitly
|
|
332
|
+
* provider-reported, never billing-grade.
|
|
333
|
+
*/
|
|
334
|
+
export function decimalFromNumber(value: number): MoneyResult<string> {
|
|
335
|
+
if (typeof value !== "number" || !Number.isFinite(value)) {
|
|
336
|
+
return { ok: false, reason: `cost ${String(value)} is not a finite number` };
|
|
337
|
+
}
|
|
338
|
+
if (value < 0) return { ok: false, reason: `cost ${String(value)} is negative` };
|
|
339
|
+
|
|
340
|
+
const text = String(value);
|
|
341
|
+
const exponentIndex = text.search(/[eE]/);
|
|
342
|
+
if (exponentIndex === -1) {
|
|
343
|
+
const parsed = parseDecimal(text);
|
|
344
|
+
return parsed ? { ok: true, value: formatDecimal(parsed) } : { ok: false, reason: `cost ${text} is not representable` };
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const exponent = Number(text.slice(exponentIndex + 1));
|
|
348
|
+
const mantissa = text.slice(0, exponentIndex);
|
|
349
|
+
const dot = mantissa.indexOf(".");
|
|
350
|
+
const digits = dot === -1 ? mantissa : mantissa.slice(0, dot) + mantissa.slice(dot + 1);
|
|
351
|
+
const mantissaScale = dot === -1 ? 0 : mantissa.length - dot - 1;
|
|
352
|
+
// value = digits / 10^mantissaScale * 10^exponent = digits / 10^(mantissaScale - exponent)
|
|
353
|
+
const scale = mantissaScale - exponent;
|
|
354
|
+
const units = scale < 0 ? BigInt(digits) * pow10(-scale) : BigInt(digits);
|
|
355
|
+
return { ok: true, value: formatDecimal({ units, scale: Math.max(scale, 0) }) };
|
|
356
|
+
}
|