@aldus-runtime/gate-engine 0.2.0-next.2 → 0.2.0-next.21

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/src/spend.ts CHANGED
@@ -11,13 +11,19 @@
11
11
  * `GateDecision` stores only digests. Carrying the limit in a record beside the decision would
12
12
  * let someone raise the ceiling without touching the approval.
13
13
  *
14
- * So a grant does both: it holds the values, and {@link grantLimitsDigest} is included among the
14
+ * So a grant does both: it holds the values, and {@link grantTermsDigest} is included among the
15
15
  * gate's bound subjects. Raising a limit changes that digest, which drifts from `subjectHashes`,
16
16
  * which voids the authorization exactly as §13.2 requires. The ceiling cannot move without an
17
17
  * operator re-approving it.
18
18
  */
19
19
 
20
- import type { CostRecord, Money } from "@aldus-runtime/core";
20
+ import {
21
+ reservationExposureIsBounded,
22
+ reservationIsActive,
23
+ type CostRecord,
24
+ type Money,
25
+ type SpendReservation,
26
+ } from "@aldus-runtime/core";
21
27
 
22
28
  import { digestSubjectValue } from "./binding.js";
23
29
  import {
@@ -25,6 +31,7 @@ import {
25
31
  compareMoney,
26
32
  formatMoney,
27
33
  isNegativeMoney,
34
+ isPositiveMoney,
28
35
  subtractMoney,
29
36
  zeroMoney,
30
37
  } from "./money.js";
@@ -53,6 +60,34 @@ export interface SpendGrant {
53
60
  * back to the approval that permitted it (§19.3 "explicit spend authorization").
54
61
  */
55
62
  decisionId: string;
63
+ /**
64
+ * What this grant authorizes spending **on** (§13.2, §4.2).
65
+ *
66
+ * Operation names are adopter-defined open strings — `"agent.execute"`, `"tts.synthesize"`.
67
+ * Core names none.
68
+ *
69
+ * Present so that handing the wrong grant to an execution gateway cannot authorize an unrelated
70
+ * operation. Without it, "a grant" is a pool of money with no statement about what it is for,
71
+ * and the only thing keeping agent spend out of a synthesis ledger is which `decisionId` each
72
+ * happened to carry.
73
+ */
74
+ scope: {
75
+ operations: readonly string[];
76
+ };
77
+ /**
78
+ * Whether an execution with no estimate may be dispatched (§13.2, §19.3; ADR-0044).
79
+ *
80
+ * Operator-approved policy, so it lives on the grant and is bound by
81
+ * {@link grantTermsDigest} — changing it invalidates the approval exactly as changing a ceiling
82
+ * or the scope does. It must never be supplied by an execution input or an adapter: a caller
83
+ * that could assert its own permission is the shape #107 exists to prevent.
84
+ *
85
+ * A closed pair rather than a boolean. `permitUnestimated: true` invites being flipped in a
86
+ * config file; naming the reservation it implies makes the consequence part of the decision.
87
+ *
88
+ * Absent reads as `"refuse"`.
89
+ */
90
+ unestimatedExecution?: "refuse" | "reserve_max_per_request";
56
91
  /** Maximum total spend authorized across the Run (§13.2 "maximum authorized cost"). */
57
92
  maxTotal: Money;
58
93
  /** Maximum spend authorized for any single request (§19.3 "per-request ... limits"). */
@@ -60,13 +95,21 @@ export interface SpendGrant {
60
95
  }
61
96
 
62
97
  /**
63
- * The digest a gate must bind for the grant's limits to be tamper-evident.
98
+ * The digest a gate must bind for the grant's **terms** to be tamper-evident (§13.2).
64
99
  *
65
- * Only the limits are digested, not the grant's identity: re-issuing an identical ceiling under a
66
- * new `grantId` should not read as the operator having approved something different.
100
+ * Was `grantTermsDigest`, covering the ceilings alone. Scope is now a term too: changing a grant
101
+ * from agent-only to TTS-capable widens what an approval permits exactly as raising its ceiling
102
+ * does, and an approval that survives that change did not bind what it appeared to bind.
103
+ *
104
+ * Only the terms are digested, not the grant's identity: re-issuing an identical grant under a new
105
+ * `grantId` should not read as the operator having approved something different.
67
106
  */
68
- export function grantLimitsDigest(grant: SpendGrant): string {
107
+ export function grantTermsDigest(grant: SpendGrant): string {
69
108
  return digestSubjectValue({
109
+ // Sorted, because the *set* of authorized operations is the term, not the order an adopter
110
+ // listed them in — the same reason ADR-0033 sorts release input hashes.
111
+ scope: { operations: [...grant.scope.operations].sort() },
112
+ unestimatedExecution: grant.unestimatedExecution ?? "refuse",
70
113
  maxTotal: grant.maxTotal,
71
114
  maxPerRequest: grant.maxPerRequest ?? null,
72
115
  });
@@ -109,6 +152,36 @@ export interface SpendLedger {
109
152
  counted: CostRecord[];
110
153
  /** Cost records excluded because they were voided. */
111
154
  excluded: CostRecord[];
155
+ /**
156
+ * Charges whose amount nobody knows yet (§19.3; #150).
157
+ *
158
+ * A provider may charge a request and withhold or delay the figure. While one of these stands
159
+ * against a grant, **Aldus cannot prove how much authorization remains** — the charge is real
160
+ * and its size is not yet a fact.
161
+ *
162
+ * A record here is never treated as free, voided, or a zero draw. Zero is a numerical assertion;
163
+ * this is an uncertainty state, and the two are not interchangeable.
164
+ */
165
+ unresolvedUnknown: CostRecord[];
166
+ /**
167
+ * Whether {@link SpendLedger.remaining} is a number anyone may spend against.
168
+ *
169
+ * `false` while any unresolved unknown charge stands. `remaining` still reports the arithmetic
170
+ * over what is known, because an operator wants the figure — but presenting it as headroom
171
+ * would state a safe amount that nothing establishes.
172
+ */
173
+ remainingIsDeterminate: boolean;
174
+ }
175
+
176
+ /**
177
+ * Whether a record is a charge of unknown size (§19.3; #150).
178
+ *
179
+ * An estimate does not resolve it. An estimate is evidence about what a request was expected to
180
+ * cost, and the ruling on #150 is explicit that it does not confirm the final charge — so a record
181
+ * carrying both an estimate and `billingStatus: "unknown"` is still unresolved.
182
+ */
183
+ export function isUnresolvedUnknownCharge(record: CostRecord): boolean {
184
+ return record.billingStatus === "unknown";
112
185
  }
113
186
 
114
187
  /**
@@ -136,12 +209,214 @@ export function computeLedger(grant: SpendGrant, costs: readonly CostRecord[]):
136
209
 
137
210
  const headroom = subtractMoney(grant.maxTotal, consumed);
138
211
  const overspent = isNegativeMoney(headroom);
212
+ const unresolvedUnknown = counted.filter(isUnresolvedUnknownCharge);
139
213
  return {
140
214
  consumed,
141
215
  remaining: overspent ? zeroMoney(currency) : headroom,
142
216
  overspent,
143
217
  counted,
144
218
  excluded,
219
+ unresolvedUnknown,
220
+ remainingIsDeterminate: unresolvedUnknown.length === 0,
221
+ };
222
+ }
223
+
224
+ /**
225
+ * Authorization available to commit, derived rather than maintained (ADR-0044; #155).
226
+ *
227
+ * ```text
228
+ * available = authorized maximum − settled charges − active reservations
229
+ * ```
230
+ *
231
+ * Derived on every read, never stored as a balance. A maintained counter is a second source of
232
+ * truth about money, reconciled by hand against the records it summarises — and every defect this
233
+ * repository has fixed in the cost path has been a value asserting more than what established it.
234
+ */
235
+ export interface SpendAvailability {
236
+ /** The ceiling the operator approved. */
237
+ authorized: Money;
238
+ /** Charges already recorded against it. */
239
+ settled: Money;
240
+ /** Authorization committed to effects that have not settled. */
241
+ reserved: Money;
242
+ /**
243
+ * What may still be committed. Never negative.
244
+ *
245
+ * **Read {@link SpendAvailability.determinate} before spending against this.** The figure is the
246
+ * arithmetic over what is known, and while an unresolved charge of unknown size stands, what is
247
+ * known is not all there is.
248
+ */
249
+ available: Money;
250
+ /** Whether {@link SpendAvailability.available} is an amount anyone may commit against. */
251
+ determinate: boolean;
252
+ /**
253
+ * Why it is not, where it is not.
254
+ *
255
+ * Two independent sources, kept apart because they carry different evidence:
256
+ *
257
+ * - reservations in `billing_unknown` whose exposure is not bounded by an enforced ceiling;
258
+ * - cost records of unknown size with no reservation at all, which is every such record written
259
+ * before this protocol existed (#150).
260
+ */
261
+ indeterminate: {
262
+ unboundedReservations: SpendReservation[];
263
+ unreservedUnknownCharges: CostRecord[];
264
+ };
265
+ /**
266
+ * Reserved-but-unsettled amounts, per **authorization** currency (ADR-0044).
267
+ *
268
+ * Not the provider's billing currency. This states what Aldus set aside; what a provider charged,
269
+ * and in what currency, is a separate fact that may not exist yet. A report may say "USD 2.00
270
+ * remains reserved because billing is unresolved"; it must never restate that as "the provider
271
+ * made an unknown USD charge".
272
+ */
273
+ reservedUnknownByCurrency: Record<string, string>;
274
+ }
275
+
276
+ /**
277
+ * Derive what a grant still authorizes (§19.3; ADR-0044).
278
+ *
279
+ * Composes with #150 rather than replacing it. A charge of unknown size still makes the grant
280
+ * indeterminate — what a reservation adds is the possibility of a *bound*, and only when the
281
+ * execution that produced the charge was actually dispatched under an enforced ceiling. A backend
282
+ * that declares enforcement today is not evidence about a request dispatched by an earlier version
283
+ * (ADR-0030).
284
+ */
285
+ export function availableAuthorization(
286
+ grant: SpendGrant,
287
+ costs: readonly CostRecord[],
288
+ reservations: readonly SpendReservation[] = [],
289
+ ): SpendAvailability {
290
+ const currency = grant.maxTotal.currency;
291
+ const ledger = computeLedger(grant, costs);
292
+
293
+ // Per grant, never per decision. The grant is the budget pool; the decision is who authorized
294
+ // its terms. One decision may establish several grants — an episode-level ceiling above an agent
295
+ // grant and a TTS grant — and deriving availability per decision would silently aggregate them.
296
+ const mine = reservations.filter((reservation) => reservation.grantId === grant.grantId);
297
+ const active = mine.filter(reservationIsActive);
298
+
299
+ // Settled reservations are already represented by the cost records that settled them. Counting
300
+ // both would double-count the same money against the ceiling.
301
+ let reserved = zeroMoney(currency);
302
+ const reservedUnknownByCurrency = new Map<string, Money>();
303
+ for (const reservation of active) {
304
+ if (reservation.reserved.currency === currency) {
305
+ reserved = addMoney(reserved, reservation.reserved);
306
+ }
307
+ if (reservation.status === "billing_unknown") {
308
+ const running =
309
+ reservedUnknownByCurrency.get(reservation.reserved.currency) ??
310
+ zeroMoney(reservation.reserved.currency);
311
+ reservedUnknownByCurrency.set(
312
+ reservation.reserved.currency,
313
+ addMoney(running, reservation.reserved),
314
+ );
315
+ }
316
+ }
317
+
318
+ const unboundedReservations = active.filter(
319
+ (reservation) =>
320
+ reservation.status === "billing_unknown" && !reservationExposureIsBounded(reservation),
321
+ );
322
+ // #150's rule, narrowed by what a reservation can now establish. A record of unknown size whose
323
+ // reservation is bounded is accounted for; one with no reservation is not, and that is every
324
+ // such record written before this protocol.
325
+ const boundedReservationIds = new Set(
326
+ active
327
+ .filter((reservation) => reservationExposureIsBounded(reservation))
328
+ .map((reservation) => reservation.reservationId),
329
+ );
330
+ // `computeLedger` filters cost records by `authorizationId`, which is the legacy link and stays
331
+ // correct: a record written before reservations existed has no `reservationId` to reach a grant
332
+ // through, and its decision is the only thing tying it to an authorization (#155).
333
+ const unreservedUnknownCharges = ledger.counted.filter(
334
+ (record) =>
335
+ isUnresolvedUnknownCharge(record) &&
336
+ (record.reservationId === undefined || !boundedReservationIds.has(record.reservationId)),
337
+ );
338
+
339
+ const headroom = subtractMoney(subtractMoney(grant.maxTotal, ledger.consumed), reserved);
340
+ return {
341
+ authorized: grant.maxTotal,
342
+ settled: ledger.consumed,
343
+ reserved,
344
+ available: isNegativeMoney(headroom) ? zeroMoney(currency) : headroom,
345
+ determinate: unboundedReservations.length === 0 && unreservedUnknownCharges.length === 0,
346
+ indeterminate: { unboundedReservations, unreservedUnknownCharges },
347
+ reservedUnknownByCurrency: Object.fromEntries(
348
+ [...reservedUnknownByCurrency.entries()]
349
+ .sort(([a], [b]) => a.localeCompare(b))
350
+ .map(([code, money]) => [code, money.amount]),
351
+ ),
352
+ };
353
+ }
354
+
355
+ /**
356
+ * Whether a grant can truthfully permit an unestimated execution (ADR-0044; #155).
357
+ *
358
+ * `reserve_max_per_request` promises to reserve the per-request ceiling. A grant that permits it
359
+ * and states no such ceiling promises an amount it does not have — and reserving zero instead
360
+ * would make unestimated executions invisible to concurrency control, which is the case most
361
+ * likely to be dispatched in a loop.
362
+ *
363
+ * Checked at decode **and** before dispatch: a grant assembled from configuration never passes
364
+ * through the constructor that would have caught it.
365
+ */
366
+ export function unestimatedPolicyIsSatisfiable(grant: SpendGrant): string | undefined {
367
+ if ((grant.unestimatedExecution ?? "refuse") !== "reserve_max_per_request") return undefined;
368
+ const ceiling = grant.maxPerRequest;
369
+ if (ceiling === undefined) {
370
+ return (
371
+ `Grant "${grant.grantId}" permits unestimated execution by reserving its per-request ` +
372
+ "ceiling, and states no ceiling. There is no truthful amount to reserve, so this cannot be " +
373
+ "dispatched (§13.2, §19.3)."
374
+ );
375
+ }
376
+ if (!isPositiveMoney(ceiling)) {
377
+ return (
378
+ `Grant "${grant.grantId}" permits unestimated execution by reserving its per-request ` +
379
+ `ceiling, and that ceiling is ${formatMoney(ceiling)}. Reserving zero would make an ` +
380
+ "unestimated execution invisible to concurrency control."
381
+ );
382
+ }
383
+ if (ceiling.currency !== grant.maxTotal.currency) {
384
+ return (
385
+ `Grant "${grant.grantId}" states a per-request ceiling in ${ceiling.currency} and a total ` +
386
+ `in ${grant.maxTotal.currency}. A reservation is denominated in the grant's currency, and ` +
387
+ "converting implicitly is not something this runtime does (ADR-0044)."
388
+ );
389
+ }
390
+ return undefined;
391
+ }
392
+
393
+ /** Why a grant does not authorize an operation. */
394
+ export interface SpendScopeRefusal {
395
+ operation: string;
396
+ authorized: readonly string[];
397
+ explanation: string;
398
+ }
399
+
400
+ /**
401
+ * Whether a grant authorizes an operation (§13.2, §4.2; #155).
402
+ *
403
+ * Checked before reserving, so handing the wrong grant to an execution gateway cannot authorize
404
+ * unrelated work. Without it a grant is a pool of money with no statement about what it is for,
405
+ * and the only thing separating agent spend from a synthesis ledger is which decision each
406
+ * happened to name.
407
+ */
408
+ export function checkSpendScope(
409
+ grant: SpendGrant,
410
+ operation: string,
411
+ ): SpendScopeRefusal | undefined {
412
+ if (grant.scope.operations.includes(operation)) return undefined;
413
+ return {
414
+ operation,
415
+ authorized: [...grant.scope.operations],
416
+ explanation:
417
+ `Grant "${grant.grantId}" authorizes ${grant.scope.operations.map((entry) => `"${entry}"`).join(", ") || "nothing"} ` +
418
+ `and this operation is "${operation}". A grant states what it may be spent on as well as ` +
419
+ "how much, so passing the wrong one to a gateway cannot authorize unrelated work (§13.2).",
145
420
  };
146
421
  }
147
422
 
@@ -155,7 +430,19 @@ export interface SpendRequest {
155
430
 
156
431
  /** Why a spend was refused. */
157
432
  export type SpendRefusalReason =
158
- "per-request-limit" | "total-limit" | "already-overspent" | "negative-amount";
433
+ | "per-request-limit"
434
+ | "total-limit"
435
+ | "already-overspent"
436
+ | "negative-amount"
437
+ /**
438
+ * A charge of unknown size stands against this grant (§19.3; #150).
439
+ *
440
+ * Refused rather than allowed-with-a-warning: while the size of a real charge is unknown, the
441
+ * remaining headroom is not a fact, and spending against a figure nobody can establish is how a
442
+ * ceiling is exceeded without any single decision being wrong. Resolution is a reconciled amount
443
+ * or a new authorization under an explicit policy — both human acts.
444
+ */
445
+ | "billing-unconfirmed";
159
446
 
160
447
  /** The outcome of a stop-on-budget check. */
161
448
  export type SpendCheck =
@@ -197,6 +484,25 @@ export function checkSpend(
197
484
  };
198
485
  }
199
486
 
487
+ // Before the arithmetic, because the arithmetic is what cannot be trusted. While a charge of
488
+ // unknown size stands against this grant, `remaining` is the total over what is *known* — and
489
+ // spending against it would treat an unresolved charge as a zero draw, which is the one thing
490
+ // the ruling on #150 forbids (§19.3).
491
+ if (!ledger.remainingIsDeterminate) {
492
+ return {
493
+ allowed: false,
494
+ reason: "billing-unconfirmed",
495
+ ledger,
496
+ explanation:
497
+ `${ledger.unresolvedUnknown.length} charge(s) against this authorization have an ` +
498
+ "unconfirmed amount, so the remaining budget is indeterminate rather than " +
499
+ `${formatMoney(ledger.remaining)}. Automatic spend is refused until the amount is ` +
500
+ "reconciled or an operator issues a new authorization: an unknown charge is neither free " +
501
+ "nor zero, and drawing against a figure nobody can establish is how a ceiling is exceeded " +
502
+ "without any single decision being wrong (§19.3).",
503
+ };
504
+ }
505
+
200
506
  if (ledger.overspent) {
201
507
  return {
202
508
  allowed: false,