@zonastery/bursar 0.0.1

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.
Files changed (70) hide show
  1. package/README.md +375 -0
  2. package/dist/allowance.d.ts +48 -0
  3. package/dist/allowance.d.ts.map +1 -0
  4. package/dist/allowance.js +140 -0
  5. package/dist/allowance.js.map +1 -0
  6. package/dist/breakdown.d.ts +27 -0
  7. package/dist/breakdown.d.ts.map +1 -0
  8. package/dist/breakdown.js +27 -0
  9. package/dist/breakdown.js.map +1 -0
  10. package/dist/config.d.ts +23 -0
  11. package/dist/config.d.ts.map +1 -0
  12. package/dist/config.js +278 -0
  13. package/dist/config.js.map +1 -0
  14. package/dist/engine.d.ts +44 -0
  15. package/dist/engine.d.ts.map +1 -0
  16. package/dist/engine.js +172 -0
  17. package/dist/engine.js.map +1 -0
  18. package/dist/errors.d.ts +55 -0
  19. package/dist/errors.d.ts.map +1 -0
  20. package/dist/errors.js +55 -0
  21. package/dist/errors.js.map +1 -0
  22. package/dist/expr.d.ts +65 -0
  23. package/dist/expr.d.ts.map +1 -0
  24. package/dist/expr.js +681 -0
  25. package/dist/expr.js.map +1 -0
  26. package/dist/index.d.ts +20 -0
  27. package/dist/index.d.ts.map +1 -0
  28. package/dist/index.js +14 -0
  29. package/dist/index.js.map +1 -0
  30. package/dist/load-pricing-file.d.ts +12 -0
  31. package/dist/load-pricing-file.d.ts.map +1 -0
  32. package/dist/load-pricing-file.js +45 -0
  33. package/dist/load-pricing-file.js.map +1 -0
  34. package/dist/manager.d.ts +421 -0
  35. package/dist/manager.d.ts.map +1 -0
  36. package/dist/manager.js +1112 -0
  37. package/dist/manager.js.map +1 -0
  38. package/dist/metrics.d.ts +19 -0
  39. package/dist/metrics.d.ts.map +1 -0
  40. package/dist/metrics.js +2 -0
  41. package/dist/metrics.js.map +1 -0
  42. package/dist/node.d.ts +15 -0
  43. package/dist/node.d.ts.map +1 -0
  44. package/dist/node.js +15 -0
  45. package/dist/node.js.map +1 -0
  46. package/dist/stores/credit-store.d.ts +171 -0
  47. package/dist/stores/credit-store.d.ts.map +1 -0
  48. package/dist/stores/credit-store.js +52 -0
  49. package/dist/stores/credit-store.js.map +1 -0
  50. package/dist/stores/events.d.ts +63 -0
  51. package/dist/stores/events.d.ts.map +1 -0
  52. package/dist/stores/events.js +68 -0
  53. package/dist/stores/events.js.map +1 -0
  54. package/dist/stores/memory-store.d.ts +178 -0
  55. package/dist/stores/memory-store.d.ts.map +1 -0
  56. package/dist/stores/memory-store.js +1833 -0
  57. package/dist/stores/memory-store.js.map +1 -0
  58. package/dist/stores/postgres-store.d.ts +95 -0
  59. package/dist/stores/postgres-store.d.ts.map +1 -0
  60. package/dist/stores/postgres-store.js +872 -0
  61. package/dist/stores/postgres-store.js.map +1 -0
  62. package/dist/stores/supabase-store.d.ts +76 -0
  63. package/dist/stores/supabase-store.d.ts.map +1 -0
  64. package/dist/stores/supabase-store.js +865 -0
  65. package/dist/stores/supabase-store.js.map +1 -0
  66. package/dist/types.d.ts +462 -0
  67. package/dist/types.d.ts.map +1 -0
  68. package/dist/types.js +2 -0
  69. package/dist/types.js.map +1 -0
  70. package/package.json +82 -0
@@ -0,0 +1,1112 @@
1
+ import Decimal from "decimal.js";
2
+ import { CapReachedError, ConcurrencyLimitError, ConfigError, FeatureLimitReachedError, FeatureNotEntitledError, InsufficientCreditsError, LeaseExpiredError, LeaseNotFoundError, PricingNotLoadedError, RefundError, } from "./errors.js";
3
+ import { PricingEngine as PricingEngineClass } from "./engine.js";
4
+ import { resolveAllowanceWindow, resolveCalendarWindow } from "./allowance.js";
5
+ /**
6
+ * Default `low_balance` threshold multiplier (contract §6 / M18). The event
7
+ * fires when a deduction crosses ``minBalance * LOW_BALANCE_MULTIPLIER`` from
8
+ * above. Override via the ``lowBalance.thresholds`` constructor option to set
9
+ * an absolute threshold (or multiple levels) instead.
10
+ */
11
+ const LOW_BALANCE_MULTIPLIER = 2;
12
+ /**
13
+ * Default lease TTL (seconds) for ``reserve``/``runBilled`` (interface plan §3).
14
+ * Long batch/agentic jobs call {@link CreditManager.renew} before this elapses.
15
+ */
16
+ const DEFAULT_LEASE_TTL_SECONDS = 600;
17
+ /**
18
+ * Built-in financial-safety presets (interface plan §2). ``strict_prepaid``
19
+ * keeps the floor ``>= 0`` (structural zero debt); ``overdraft`` permits a
20
+ * negative floor and bills the full actual cost at settle.
21
+ */
22
+ const POLICY_PRESETS = new Set(["strict_prepaid", "overdraft"]);
23
+ /** Coerce a `Decimal | number` money input into a `Decimal`. */
24
+ function toDecimal(value) {
25
+ return value instanceof Decimal ? value : new Decimal(value);
26
+ }
27
+ /** True when `value` is a raw money amount rather than a `UsageMetrics` object. */
28
+ function isAmount(value) {
29
+ return value instanceof Decimal || typeof value === "number";
30
+ }
31
+ /**
32
+ * Orchestrates credit operations.
33
+ *
34
+ * The deduction path is a single atomic, idempotency-keyed store call
35
+ * (``deductWithAllowance``) that consumes free allowance, enforces spend caps,
36
+ * applies the balance floor and debits the net amount in one transaction
37
+ * (contract §2). The manager is a thin layer that calculates the cost, maps
38
+ * the store's typed ``error`` codes to exceptions, and emits lifecycle events
39
+ * **only after** the operation has succeeded (contract §6).
40
+ *
41
+ * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events
42
+ * (deducted, deduct_failed, added, refunded, refund_failed, expired,
43
+ * cap_reached, cap_warning, low_balance).
44
+ */
45
+ export class CreditManager {
46
+ store;
47
+ engine = null;
48
+ emitter = null;
49
+ // Financial-safety policy (interface plan §1/§2): `policy` is the preset default
50
+ // used for planless users; per-plan / per-call policy layers on top.
51
+ policy;
52
+ overdraftFloor;
53
+ defaultMaxConcurrent;
54
+ defaultTtl;
55
+ // Multi-level low_balance thresholds (interface plan §6), sorted high→low.
56
+ // Populated from `options.lowBalance.thresholds` (WS7); `null` means
57
+ // "unconfigured" — falls back to `[minBalance * LOW_BALANCE_MULTIPLIER]` lazily.
58
+ lowBalanceThresholds;
59
+ onLowBalance;
60
+ // Lazy-on-read credit expiry (closes the gap with allowance windows/lease
61
+ // TTLs, which are already lazy-on-read). Default `false` — unchanged
62
+ // behaviour; explicit `sweepExpiredCredits`/cron remains required.
63
+ lazyExpiry;
64
+ // Edge-trigger state: per-user set of thresholds currently breached ("below"),
65
+ // keyed by `.toString()`. A level re-arms only after the balance climbs back
66
+ // above it (a top-up).
67
+ lbBelow = new Map();
68
+ constructor(store, engine, emitter, options) {
69
+ const policy = options?.policy ?? "strict_prepaid";
70
+ if (!POLICY_PRESETS.has(policy)) {
71
+ throw new ConfigError(`unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(", ")}`);
72
+ }
73
+ this.store = store;
74
+ if (engine)
75
+ this.engine = engine;
76
+ if (emitter)
77
+ this.emitter = emitter;
78
+ this.policy = policy;
79
+ this.overdraftFloor =
80
+ options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null;
81
+ this.defaultMaxConcurrent = options?.maxConcurrent ?? null;
82
+ this.defaultTtl = options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS;
83
+ this.lowBalanceThresholds = options?.lowBalance?.thresholds?.length
84
+ ? options.lowBalance.thresholds.map(toDecimal).sort((a, b) => b.comparedTo(a))
85
+ : null;
86
+ this.onLowBalance = options?.lowBalance?.onTrigger ?? null;
87
+ this.lazyExpiry = options?.lazyExpiry ?? false;
88
+ }
89
+ /** Emit a credit lifecycle event. No-op if no emitter is configured. */
90
+ emit(type, userId, data) {
91
+ this.emitter?.emit({ type, timestamp: new Date(), userId, data });
92
+ }
93
+ /** The configured min-balance floor as a `Decimal` (defaults to 0). */
94
+ minBalanceDecimal() {
95
+ return new Decimal(this.engine?.minBalance ?? 0);
96
+ }
97
+ /**
98
+ * Resolve the single `low_balance` threshold used by the ``deduct`` fast path:
99
+ * the lowest configured level when ``lowBalance.thresholds`` is set, otherwise
100
+ * ``minBalance * LOW_BALANCE_MULTIPLIER`` (documented default).
101
+ */
102
+ resolveLowBalanceThreshold() {
103
+ if (this.lowBalanceThresholds) {
104
+ // `lowBalanceThresholds` is sorted high→low; the last element is lowest.
105
+ return this.lowBalanceThresholds[this.lowBalanceThresholds.length - 1];
106
+ }
107
+ return this.minBalanceDecimal().times(LOW_BALANCE_MULTIPLIER);
108
+ }
109
+ /** Run bundled SQL migrations through the store. */
110
+ async setup() {
111
+ return await this.store.setup();
112
+ }
113
+ /** Load pricing from a PricingConfigData or raw dict and sync it. */
114
+ async publishPricingFromDict(data) {
115
+ const raw = data;
116
+ this.engine = PricingEngineClass.fromDict(raw);
117
+ await this.store.setActivePricing(data);
118
+ }
119
+ /** Load the active pricing config from the store. */
120
+ async loadPricingFromStore() {
121
+ const active = await this.store.getActivePricing();
122
+ if (!active)
123
+ throw new PricingNotLoadedError("no active pricing config in store");
124
+ const { models, tools, search, cache, fixed, minBalance, plans } = active.config;
125
+ const engineDict = {
126
+ models,
127
+ tools: tools ?? { _default: "tool_calls * 0" },
128
+ search: search ?? null,
129
+ cache: cache ?? null,
130
+ fixed: fixed ?? {},
131
+ minBalance: minBalance ?? 0,
132
+ ...(plans ? { plans } : {}),
133
+ };
134
+ this.engine = PricingEngineClass.fromDict(engineDict);
135
+ }
136
+ /**
137
+ * Publish new pricing and update the engine in one call.
138
+ *
139
+ * H10: the store write is now **awaited** (was a fire-and-forget `void`), so
140
+ * a persistence failure surfaces to the caller instead of becoming an
141
+ * unhandled promise rejection.
142
+ */
143
+ async publishPricing(config, label) {
144
+ const { models, tools, search, cache, fixed, minBalance, plans } = config;
145
+ const raw = {
146
+ models,
147
+ tools: tools ?? { _default: "tool_calls * 0" },
148
+ search: search ?? null,
149
+ cache: cache ?? null,
150
+ fixed: fixed ?? {},
151
+ minBalance: minBalance ?? 0,
152
+ ...(plans ? { plans } : {}),
153
+ };
154
+ this.engine = PricingEngineClass.fromDict(raw);
155
+ await this.store.setActivePricing(config, label);
156
+ }
157
+ /** The current PricingEngine, or null if not loaded. */
158
+ get pricingEngine() {
159
+ return this.engine;
160
+ }
161
+ /** Fetch a user's current plan (including feature entitlements). */
162
+ async getUserPlan(userId) {
163
+ return this.store.getUserPlan(userId);
164
+ }
165
+ /**
166
+ * Set a user's subscription plan and emit ``credits.plan_changed``.
167
+ *
168
+ * The store call is awaited so a persistence failure surfaces to the caller.
169
+ * The event is emitted only after the store write succeeds (contract §6).
170
+ */
171
+ async setUserPlan(userId, planKey) {
172
+ await this.store.setUserPlan(userId, planKey);
173
+ this.emit("credits.plan_changed", userId, {
174
+ userId,
175
+ planKey,
176
+ timestamp: new Date().toISOString(),
177
+ });
178
+ }
179
+ /**
180
+ * Check whether a user's plan has a specific feature entitlement.
181
+ *
182
+ * Passthrough to the store, which distinguishes *presence* from *truthiness*
183
+ * (numeric `0` / `""` count as present; only `null`/`undefined`/`false`/absent
184
+ * read as missing — contract §5 / M6).
185
+ */
186
+ async checkFeature(userId, feature) {
187
+ return this.store.checkFeature(userId, feature);
188
+ }
189
+ /**
190
+ * Advisory, non-locking read of a per-feature invocation-count limit (UI only).
191
+ *
192
+ * Resolves the `FeatureLimit` (if any) from the user's plan and the
193
+ * calendar-aligned window, then delegates counting to the store. Returns
194
+ * `limited: false` (zeroed fields, `action: null`) when no `FeatureLimit`
195
+ * is configured for `feature` on the user's plan — never used for
196
+ * admission control; that is exclusively the atomic check-and-increment
197
+ * inside `deduct`/`reserve`.
198
+ */
199
+ async checkFeatureLimit(userId, feature) {
200
+ const { limit, periodStart, periodEnd } = await this.resolveFeatureLimit(userId, feature);
201
+ if (limit == null || periodStart == null || periodEnd == null) {
202
+ return {
203
+ userId,
204
+ feature,
205
+ limited: false,
206
+ limit: 0,
207
+ used: 0,
208
+ remaining: 0,
209
+ periodStart: "",
210
+ periodEnd: "",
211
+ action: null,
212
+ };
213
+ }
214
+ const result = await this.store.checkFeatureLimit(userId, feature, limit.maxCalls, periodStart, periodEnd);
215
+ // The store only counts; the manager (which owns plan lookup) overrides
216
+ // `limited`/`action` from the resolved FeatureLimit (mirrors how
217
+ // checkAllowance overrides periodEnd after the store call).
218
+ return { ...result, limited: true, action: limit.action };
219
+ }
220
+ /**
221
+ * Sweep a single user's own expired credits when ``options.lazyExpiry`` is
222
+ * enabled — no-op otherwise. Mirrors the fact that allowance windows and
223
+ * lease TTLs are already lazy-on-read; this closes the same gap for the
224
+ * stored aggregate expiry balance without requiring a cron job.
225
+ */
226
+ async maybeLazyExpire(userId) {
227
+ if (!this.lazyExpiry)
228
+ return;
229
+ await this.runSweep(false, userId);
230
+ }
231
+ /** Get a user's current credit balance. */
232
+ async getBalance(userId) {
233
+ await this.maybeLazyExpire(userId);
234
+ return await this.store.getBalance(userId);
235
+ }
236
+ /** Add credits to a user's account. */
237
+ async addCredits(userId, amount, options) {
238
+ const type = options?.type ?? "adjustment";
239
+ const result = await this.store.addCredits(userId, toDecimal(amount), type, options?.metadata, options?.expiresAt, options?.tier, options?.idempotencyKey);
240
+ this.emit("credits.added", userId, {
241
+ transactionId: result.transactionId,
242
+ amount: result.amount,
243
+ newBalance: result.newBalance,
244
+ type,
245
+ idempotent: result.idempotent ?? false,
246
+ });
247
+ // Re-arm multi-level low_balance: any level the topped-up balance is now back
248
+ // above can fire again on the next descent (interface plan §6).
249
+ if (this.lowBalanceThresholds) {
250
+ const below = this.lbBelow.get(userId) ?? new Set();
251
+ this.lbBelow.set(userId, below);
252
+ for (const t of this.lowBalanceThresholds) {
253
+ if (result.newBalance.gt(t))
254
+ below.delete(t.toString());
255
+ }
256
+ }
257
+ return result;
258
+ }
259
+ /**
260
+ * Grant one billing-cycle's worth of credits — idempotent-safe for a
261
+ * payment-provider webhook handler (Stripe, etc. — bursar stays
262
+ * provider-agnostic) to call even on webhook redelivery.
263
+ *
264
+ * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws
265
+ * ``ConfigError`` otherwise).
266
+ * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.
267
+ * 3. When ``replacePrior`` (default ``true``), any remaining balance in
268
+ * ``tier`` is expired immediately via a direct ``store.addCredits``
269
+ * negative adjustment — naturally idempotent (a replay finds the tier
270
+ * already at zero and skips the call).
271
+ * 4. The new cycle is granted via a direct ``store.addCredits`` call
272
+ * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,
273
+ * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a
274
+ * redelivered webhook replays the prior grant instead of double-crediting.
275
+ * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.
276
+ * 6. Emits ``credits.cycle_renewed`` and returns the grant result.
277
+ */
278
+ async grantSubscriptionCycle(userId, amount, options) {
279
+ if (options?.expiresAt != null && options?.ttlDays != null) {
280
+ throw new ConfigError("grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both");
281
+ }
282
+ const tier = options?.tier ?? "subscription";
283
+ const replacePrior = options?.replacePrior ?? true;
284
+ const expiresAt = options?.ttlDays != null
285
+ ? new Date(Date.now() + options.ttlDays * 86_400_000)
286
+ : options?.expiresAt;
287
+ const amountDec = toDecimal(amount);
288
+ // Snapshot the tier's leftover balance and lifetimePurchased BEFORE granting.
289
+ // A redelivered webhook must be a full no-op -- including skipping the
290
+ // replace-prior wipe below -- not just avoiding a double-grant. AddCreditsResult
291
+ // carries no reliable cross-store "was this a replay" flag (Postgres/Supabase
292
+ // never populate `idempotent`), so a genuine new grant is detected after the
293
+ // fact by checking whether lifetimePurchased actually moved by `amountDec`; an
294
+ // idempotent replay leaves it unchanged.
295
+ let priorLeftover = new Decimal(0);
296
+ let preLifetimePurchased = new Decimal(0);
297
+ if (replacePrior) {
298
+ const tiersBefore = await this.getCreditTiers(userId);
299
+ const current = tiersBefore.tiers.find((t) => t.tierKey === tier);
300
+ if (current)
301
+ priorLeftover = current.balance;
302
+ preLifetimePurchased = (await this.getBalance(userId)).lifetimePurchased;
303
+ }
304
+ let result = await this.store.addCredits(userId, amountDec, "purchase", options?.metadata, expiresAt, tier, options?.idempotencyKey);
305
+ const isFreshGrant = result.lifetimePurchased.minus(preLifetimePurchased).eq(amountDec);
306
+ if (replacePrior && isFreshGrant && priorLeftover.gt(0)) {
307
+ await this.store.addCredits(userId, priorLeftover.negated(), "adjustment", { reason: "cycle_replaced" }, undefined, tier);
308
+ // Reflect the post-replace balance so the returned result is accurate
309
+ // (the grant call above only knows the pre-replace balance).
310
+ result = { ...result, newBalance: (await this.getBalance(userId)).balance };
311
+ }
312
+ if (options?.planKey) {
313
+ await this.setUserPlan(userId, options.planKey);
314
+ }
315
+ this.emit("credits.cycle_renewed", userId, {
316
+ transactionId: result.transactionId,
317
+ amount: amountDec,
318
+ newBalance: result.newBalance,
319
+ tier,
320
+ planKey: options?.planKey ?? null,
321
+ idempotencyKey: options?.idempotencyKey ?? null,
322
+ });
323
+ return result;
324
+ }
325
+ // ── Lease lifecycle: atomic admission (interface plan §3/§4) ────────
326
+ /** The default {@link OperationPolicy} from the constructor preset (§2). */
327
+ presetPolicy() {
328
+ if (this.policy === "overdraft") {
329
+ return {
330
+ billingMode: "overdraft",
331
+ maxConcurrent: this.defaultMaxConcurrent,
332
+ overdraftFloor: this.overdraftFloor ?? new Decimal(0),
333
+ };
334
+ }
335
+ return {
336
+ billingMode: "strict",
337
+ maxConcurrent: this.defaultMaxConcurrent,
338
+ overdraftFloor: null,
339
+ };
340
+ }
341
+ /**
342
+ * Resolve the effective policy: explicit arg → per-op → plan → preset (§1).
343
+ *
344
+ * A planless user (``planId`` is null) always gets the constructor preset, never
345
+ * silently unlimited (resolves M1). A user *with* a plan gets the plan default,
346
+ * then any ``perOperation`` override, then the explicit per-call ``billingMode``.
347
+ */
348
+ async resolvePolicy(userId, operationType, billingModeOverride) {
349
+ let policy = this.presetPolicy();
350
+ let plan;
351
+ try {
352
+ plan = await this.store.getUserPlan(userId);
353
+ }
354
+ catch {
355
+ // A store outage shouldn't crash admission — fall back to the preset.
356
+ plan = null;
357
+ }
358
+ if (plan && plan.planId) {
359
+ policy = {
360
+ billingMode: plan.defaultBillingMode ?? "strict",
361
+ maxConcurrent: plan.maxConcurrent != null ? plan.maxConcurrent : policy.maxConcurrent,
362
+ overdraftFloor: plan.overdraftFloor != null ? plan.overdraftFloor : policy.overdraftFloor,
363
+ };
364
+ const op = plan.perOperation?.[operationType];
365
+ if (op) {
366
+ policy = {
367
+ billingMode: op.billingMode,
368
+ maxConcurrent: op.maxConcurrent != null ? op.maxConcurrent : policy.maxConcurrent,
369
+ overdraftFloor: op.overdraftFloor != null ? op.overdraftFloor : policy.overdraftFloor,
370
+ };
371
+ }
372
+ }
373
+ if (billingModeOverride != null) {
374
+ policy = { ...policy, billingMode: billingModeOverride };
375
+ }
376
+ return policy;
377
+ }
378
+ /** Admission floor for a policy: ``overdraftFloor`` (≤0) or ``minBalance`` (≥0). */
379
+ resolveFloor(policy) {
380
+ if (policy.billingMode === "overdraft") {
381
+ return policy.overdraftFloor ?? new Decimal(0);
382
+ }
383
+ return this.minBalanceDecimal();
384
+ }
385
+ /**
386
+ * Resolve the free-allowance period start for a user (WS9c).
387
+ *
388
+ * Fast path: a ``calendar_month`` plan (the default, and the vast majority of
389
+ * users) needs no computation — returns ``null`` and the store falls back to
390
+ * its own calendar-month window, exactly matching pre-WS9 behaviour. Only
391
+ * ``rolling_30d``/``anniversary`` plans pay the cost of resolving a window,
392
+ * anchored at the plan's ``planAssignedAt``.
393
+ */
394
+ async resolveAllowancePeriodStart(userId) {
395
+ let plan;
396
+ try {
397
+ plan = await this.store.getUserPlan(userId);
398
+ }
399
+ catch {
400
+ return null;
401
+ }
402
+ if (!plan || !plan.allowancePeriod || plan.allowancePeriod === "calendar_month") {
403
+ return null;
404
+ }
405
+ const { start } = resolveAllowanceWindow(new Date(), plan.allowancePeriod, plan.planAssignedAt ?? null);
406
+ return start;
407
+ }
408
+ /**
409
+ * Resolve the `FeatureLimit` (if any) configured for `feature` on the
410
+ * user's plan, plus the calendar-aligned `[start, end)` window it applies
411
+ * to (via {@link resolveCalendarWindow}).
412
+ *
413
+ * Returns `{ limit: null, periodStart: null, periodEnd: null }` when
414
+ * `feature` is omitted or no limit is configured for it — the store then
415
+ * skips enforcement entirely (mirrors `resolveAllowancePeriodStart`).
416
+ */
417
+ async resolveFeatureLimit(userId, feature) {
418
+ if (feature == null)
419
+ return { limit: null, periodStart: null, periodEnd: null };
420
+ let plan;
421
+ try {
422
+ plan = await this.store.getUserPlan(userId);
423
+ }
424
+ catch {
425
+ return { limit: null, periodStart: null, periodEnd: null };
426
+ }
427
+ const limit = plan?.featureLimits?.[feature] ?? null;
428
+ if (limit == null)
429
+ return { limit: null, periodStart: null, periodEnd: null };
430
+ const { start, end } = resolveCalendarWindow(new Date(), limit.period);
431
+ return { limit, periodStart: start, periodEnd: end };
432
+ }
433
+ /**
434
+ * Compute the credit cost and model from metrics, or pass a raw amount through.
435
+ *
436
+ * For {@link UsageMetrics} the cost is ``engine.calculate(...).total`` (exact
437
+ * `Decimal`, no truncation); a raw amount is used as-is with no model.
438
+ */
439
+ costOf(metricsOrAmount) {
440
+ if (isAmount(metricsOrAmount)) {
441
+ return { amount: toDecimal(metricsOrAmount), model: null };
442
+ }
443
+ if (!this.engine) {
444
+ throw new PricingNotLoadedError("pricing not loaded: call loadPricingFromStore or publishPricing first");
445
+ }
446
+ const breakdown = this.engine.calculate(metricsOrAmount);
447
+ return { amount: breakdown.total, model: metricsOrAmount.model ?? null };
448
+ }
449
+ /** Map a store business code to the coherent typed exception (M2). */
450
+ raiseLeaseError(error, userId, amount) {
451
+ switch (error) {
452
+ case "concurrency_limit":
453
+ throw new ConcurrencyLimitError(`Concurrency limit reached. user=${userId}`);
454
+ case "cap_reached":
455
+ throw new CapReachedError(`Spend cap exceeded. user=${userId}, requested=${amount}`);
456
+ case "feature_limit_reached":
457
+ throw new FeatureLimitReachedError(`Feature limit reached. user=${userId}`);
458
+ case "feature_not_entitled":
459
+ throw new FeatureNotEntitledError(`Feature not entitled. user=${userId}`);
460
+ case "insufficient_credits":
461
+ throw new InsufficientCreditsError(`Insufficient credits. user=${userId}, requested=${amount}`);
462
+ case "lease_expired":
463
+ throw new LeaseExpiredError(`Lease expired. user=${userId}`);
464
+ case "lease_not_found":
465
+ case "not_found":
466
+ throw new LeaseNotFoundError(`Lease not found. user=${userId}`);
467
+ case "invalid_amount":
468
+ throw new RangeError(`Invalid amount: ${amount}`);
469
+ default:
470
+ throw new InsufficientCreditsError(`Operation failed: ${error}. user=${userId}`);
471
+ }
472
+ }
473
+ /**
474
+ * Atomically acquire a lease — the only admission control (D4).
475
+ *
476
+ * Resolves the effective policy, enforces ``requiredFeature``, sizes the hold
477
+ * from ``metricsOrAmount`` (worst-case in strict, estimate in overdraft — the
478
+ * caller chooses what to pass), and calls the store's atomic ``createLease``. On
479
+ * any business failure throws the coherent typed exception; on success emits
480
+ * ``credits.reserved`` and returns the {@link LeaseResult}.
481
+ */
482
+ async reserve(userId, metricsOrAmount, options) {
483
+ await this.maybeLazyExpire(userId);
484
+ const operationType = options?.operationType ?? "usage";
485
+ const requiredFeature = options?.requiredFeature ?? null;
486
+ if (requiredFeature != null) {
487
+ const check = await this.store.checkFeature(userId, requiredFeature);
488
+ if (!check.hasFeature) {
489
+ throw new FeatureNotEntitledError(`Feature '${requiredFeature}' not entitled. user=${userId}`);
490
+ }
491
+ }
492
+ const policy = await this.resolvePolicy(userId, operationType, options?.billingMode);
493
+ const floor = this.resolveFloor(policy);
494
+ const { amount, model } = this.costOf(metricsOrAmount);
495
+ const ttlSeconds = options?.ttl != null ? options.ttl : this.defaultTtl;
496
+ const periodStart = await this.resolveAllowancePeriodStart(userId);
497
+ const feature = options?.feature ?? null;
498
+ const { limit: featureLimit, periodStart: featurePeriodStart } = await this.resolveFeatureLimit(userId, feature);
499
+ const result = await this.store.createLease(userId, amount, operationType, {
500
+ billingMode: policy.billingMode,
501
+ floor,
502
+ maxConcurrent: policy.maxConcurrent,
503
+ ttlSeconds,
504
+ model,
505
+ overdraftFloor: policy.overdraftFloor,
506
+ metadata: options?.metadata,
507
+ periodStart,
508
+ feature,
509
+ featureLimit,
510
+ featurePeriodStart,
511
+ });
512
+ if (result.error) {
513
+ this.emit("credits.deduct_failed", userId, {
514
+ error: result.error,
515
+ amount,
516
+ stage: "reserve",
517
+ operationType,
518
+ });
519
+ this.raiseLeaseError(result.error, userId, amount);
520
+ }
521
+ this.emit("credits.reserved", userId, {
522
+ leaseId: result.leaseId,
523
+ amount: result.amount,
524
+ available: result.available,
525
+ billingMode: result.billingMode,
526
+ operationType,
527
+ expiresAt: result.expiresAt,
528
+ });
529
+ return result;
530
+ }
531
+ /**
532
+ * Charge the ACTUAL cost against a lease and finalize it (D5).
533
+ *
534
+ * De-clamped: bills the full actual cost even if it exceeds the lease hold
535
+ * (overdraft). Never blocks on floor/cap at settle — a cap breach surfaces as a
536
+ * non-blocking ``credits.cap_warning``/``credits.cap_reached`` signal. Emits
537
+ * ``credits.deducted``, then multi-level ``credits.low_balance`` and a
538
+ * ``credits.overdraft`` signal if the balance went negative.
539
+ */
540
+ async settle(userId, leaseId, metricsOrAmount, options) {
541
+ await this.maybeLazyExpire(userId);
542
+ const idempotencyKey = options?.idempotencyKey ?? null;
543
+ const { amount, model } = this.costOf(metricsOrAmount);
544
+ // Build transaction metadata: caller fields first, system fields last (M7).
545
+ const txMeta = {};
546
+ if (isAmount(metricsOrAmount)) {
547
+ if (options?.metadata) {
548
+ for (const [k, v] of Object.entries(options.metadata)) {
549
+ if (v != null)
550
+ txMeta[k] = v;
551
+ }
552
+ }
553
+ if (idempotencyKey)
554
+ txMeta["idempotencyKey"] = idempotencyKey;
555
+ }
556
+ else {
557
+ if (options?.metadata) {
558
+ for (const [k, v] of Object.entries(options.metadata)) {
559
+ if (v != null)
560
+ txMeta[k] = v;
561
+ }
562
+ }
563
+ txMeta["inputTokens"] = metricsOrAmount.inputTokens ?? 0;
564
+ txMeta["outputTokens"] = metricsOrAmount.outputTokens ?? 0;
565
+ txMeta["model"] = metricsOrAmount.model ?? "unknown";
566
+ txMeta["breakdownTotal"] = amount.toString();
567
+ if (metricsOrAmount.fixedJob)
568
+ txMeta["fixedJob"] = metricsOrAmount.fixedJob;
569
+ if (idempotencyKey)
570
+ txMeta["idempotencyKey"] = idempotencyKey;
571
+ }
572
+ const periodStart = await this.resolveAllowancePeriodStart(userId);
573
+ // The caller re-supplies the same `feature` at settle as at reserve time,
574
+ // exactly like `model` is re-supplied for per-model spend-cap accuracy.
575
+ const feature = options?.feature ?? null;
576
+ const { limit: featureLimit, periodStart: featurePeriodStart } = await this.resolveFeatureLimit(userId, feature);
577
+ const result = await this.store.settleLease(userId, leaseId, amount, {
578
+ idempotencyKey,
579
+ minBalance: this.engine ? new Decimal(this.engine.minBalance) : new Decimal(0),
580
+ model,
581
+ metadata: txMeta,
582
+ periodStart,
583
+ feature,
584
+ featureLimit,
585
+ featurePeriodStart,
586
+ });
587
+ if (result.error) {
588
+ this.emit("credits.deduct_failed", userId, {
589
+ error: result.error,
590
+ amount,
591
+ stage: "settle",
592
+ leaseId,
593
+ });
594
+ if (result.error === "lease_expired") {
595
+ this.emit("credits.lease_expired", userId, { leaseId });
596
+ }
597
+ this.raiseLeaseError(result.error, userId, amount);
598
+ }
599
+ this.emit("credits.deducted", userId, {
600
+ transactionId: result.transactionId,
601
+ amount: result.amount,
602
+ allowanceConsumed: result.allowanceConsumed,
603
+ balanceAfter: result.balanceAfter,
604
+ model,
605
+ leaseId,
606
+ idempotent: result.idempotent,
607
+ });
608
+ // Cap signal: 'deny' breaching at settle is non-blocking (work is done) and
609
+ // re-emitted as cap_reached; warn/notify as cap_warning (interface plan §7).
610
+ if (result.capWarning === "deny") {
611
+ this.emit("credits.cap_reached", userId, {
612
+ amount: result.amount,
613
+ model,
614
+ blocking: false,
615
+ });
616
+ }
617
+ else if (result.capWarning === "warn" || result.capWarning === "notify") {
618
+ this.emit("credits.cap_warning", userId, {
619
+ balanceAfter: result.balanceAfter,
620
+ amount: result.amount,
621
+ model,
622
+ action: result.capWarning,
623
+ });
624
+ }
625
+ // Feature-limit signal: mirrors the cap signal above ("prefer deny" was
626
+ // already applied by the store when choosing featureLimitWarning).
627
+ if (result.featureLimitWarning === "deny") {
628
+ this.emit("credits.feature_limit_reached", userId, {
629
+ feature,
630
+ amount: result.amount,
631
+ blocking: false,
632
+ });
633
+ }
634
+ else if (result.featureLimitWarning === "warn" || result.featureLimitWarning === "notify") {
635
+ this.emit("credits.feature_limit_warning", userId, {
636
+ feature,
637
+ action: result.featureLimitWarning,
638
+ amount: result.amount,
639
+ });
640
+ }
641
+ await this.postChargeSignals(userId, result);
642
+ return result;
643
+ }
644
+ /** Release a lease without charging (work failed/aborted) — idempotent (H1). */
645
+ async release(userId, leaseId) {
646
+ const result = await this.store.releaseLease(userId, leaseId);
647
+ if (result.released) {
648
+ this.emit("credits.reservation_released", userId, {
649
+ leaseId,
650
+ reason: result.reason,
651
+ });
652
+ }
653
+ return result;
654
+ }
655
+ /** Extend a lease's TTL for long batch/agentic jobs (B4). */
656
+ async renew(userId, leaseId, ttl) {
657
+ const ttlSeconds = ttl != null ? ttl : this.defaultTtl;
658
+ const result = await this.store.renewLease(userId, leaseId, ttlSeconds);
659
+ if (result.error) {
660
+ if (result.error === "lease_expired") {
661
+ this.emit("credits.lease_expired", userId, { leaseId });
662
+ }
663
+ this.raiseLeaseError(result.error, userId, new Decimal(0));
664
+ }
665
+ return result;
666
+ }
667
+ /**
668
+ * Advisory affordability check — UI only, non-locking, may be stale (D4/H3).
669
+ *
670
+ * Never use this as an admission gate; only ``reserve`` is authoritative.
671
+ */
672
+ async canAfford(userId, metricsOrAmount, options) {
673
+ await this.maybeLazyExpire(userId);
674
+ const operationType = options?.operationType ?? "usage";
675
+ const requiredFeature = options?.requiredFeature ?? null;
676
+ const { amount: worstCase } = this.costOf(metricsOrAmount);
677
+ const avail = await this.store.getAvailable(userId);
678
+ const policy = await this.resolvePolicy(userId, operationType, options?.billingMode);
679
+ const floor = this.resolveFloor(policy);
680
+ let affordable = true;
681
+ let reason = null;
682
+ if (requiredFeature != null) {
683
+ const check = await this.store.checkFeature(userId, requiredFeature);
684
+ if (!check.hasFeature) {
685
+ affordable = false;
686
+ reason = "feature_not_entitled";
687
+ }
688
+ }
689
+ if (affordable && avail.available.minus(worstCase).lt(floor)) {
690
+ affordable = false;
691
+ reason = "insufficient_credits";
692
+ }
693
+ return { affordable, spendable: avail.available, worstCase, reason };
694
+ }
695
+ /** Advisory ``available = balance − Σ active holds`` read (UI only, D4/H3). */
696
+ async getAvailable(userId) {
697
+ await this.maybeLazyExpire(userId);
698
+ return await this.store.getAvailable(userId);
699
+ }
700
+ /** Get a user's per-tier credit balances (credit tiers). Thin pass-through, no event emission. */
701
+ async getCreditTiers(userId) {
702
+ await this.maybeLazyExpire(userId);
703
+ return await this.store.getCreditTiers(userId);
704
+ }
705
+ /**
706
+ * Get remaining free allowance for the current billing period.
707
+ *
708
+ * Convenience wrapper that routes through the manager so callers never need
709
+ * to reach past it into the raw store. Returns a zero-allowance result for
710
+ * planless users (no exception).
711
+ *
712
+ * For ``rolling_30d``/``anniversary`` plans (WS9), resolves and threads
713
+ * ``periodStart`` so the reported window matches the one actually used by
714
+ * ``deduct``/``settle``/``reserve`` — a ``calendar_month`` plan (the default)
715
+ * takes the fast path unchanged.
716
+ */
717
+ async checkAllowance(userId) {
718
+ const plan = await this.store.getUserPlan(userId);
719
+ if (!plan.planId || !plan.allowancePeriod || plan.allowancePeriod === "calendar_month") {
720
+ return await this.store.checkAllowance(userId);
721
+ }
722
+ const { start, end } = resolveAllowanceWindow(new Date(), plan.allowancePeriod, plan.planAssignedAt ?? null);
723
+ const result = await this.store.checkAllowance(userId, start);
724
+ // The store/SQL layer only knows a generic calendar-month periodEnd (see
725
+ // 004_plans.sql / 009_deduct_and_leases.sql); override it here with the
726
+ // authoritative window this manager resolved.
727
+ const periodEnd = new Date(end.getTime() - 86_400_000);
728
+ return {
729
+ ...result,
730
+ periodStart: start.toISOString(),
731
+ periodEnd: periodEnd.toISOString(),
732
+ };
733
+ }
734
+ /**
735
+ * One-call shortcut wiring reserve → doWork → settle (interface plan §4).
736
+ *
737
+ * ``doWork`` runs the operation and returns ``{ result, actual }`` where
738
+ * ``actual`` is the real usage metrics (or amount) to settle. On any exception
739
+ * from ``doWork`` the lease is released and the error re-raised. For long jobs
740
+ * ``doWork`` may call {@link renew}. A crash between reserve and settle is
741
+ * covered by the lease TTL (and the store's reaper).
742
+ */
743
+ async runBilled(userId, options) {
744
+ const lease = await this.reserve(userId, options.estimate, {
745
+ operationType: options.operationType,
746
+ billingMode: options.billingMode,
747
+ requiredFeature: options.requiredFeature,
748
+ ttl: options.ttl,
749
+ feature: options.feature,
750
+ });
751
+ let workResult;
752
+ let actual;
753
+ try {
754
+ ({ result: workResult, actual } = await options.doWork());
755
+ }
756
+ catch (err) {
757
+ await this.release(userId, lease.leaseId);
758
+ throw err;
759
+ }
760
+ const deduction = await this.settle(userId, lease.leaseId, actual, {
761
+ idempotencyKey: options.idempotencyKey,
762
+ feature: options.feature,
763
+ });
764
+ return { result: workResult, deduction };
765
+ }
766
+ // ── Low-balance / overdraft signals (interface plan §6) ─────────────
767
+ /** Emit overdraft + multi-level low_balance after a balance-decreasing op. */
768
+ async postChargeSignals(userId, result) {
769
+ if (result.balanceAfter.lt(0)) {
770
+ this.emit("credits.overdraft", userId, {
771
+ balance: result.balanceAfter,
772
+ amount: result.amount,
773
+ });
774
+ }
775
+ if (result.idempotent)
776
+ return;
777
+ const balanceAfter = result.balanceAfter;
778
+ const balanceBefore = balanceAfter.plus(result.amount);
779
+ await this.emitLowBalance(userId, balanceBefore, balanceAfter);
780
+ }
781
+ /** Edge-triggered low_balance: multi-level if configured, else single (§6). */
782
+ async emitLowBalance(userId, balanceBefore, balanceAfter) {
783
+ if (this.lowBalanceThresholds) {
784
+ const below = this.lbBelow.get(userId) ?? new Set();
785
+ this.lbBelow.set(userId, below);
786
+ const newlyCrossed = [];
787
+ for (const t of this.lowBalanceThresholds) {
788
+ // high → low
789
+ if (balanceAfter.lte(t)) {
790
+ if (!below.has(t.toString())) {
791
+ below.add(t.toString());
792
+ newlyCrossed.push(t);
793
+ }
794
+ }
795
+ else {
796
+ below.delete(t.toString());
797
+ }
798
+ }
799
+ const fireLevel = newlyCrossed.length > 0 ? newlyCrossed.reduce((min, t) => (t.lt(min) ? t : min)) : null;
800
+ if (fireLevel !== null) {
801
+ await this.fireLowBalance(userId, balanceAfter, fireLevel);
802
+ }
803
+ return;
804
+ }
805
+ const threshold = this.resolveLowBalanceThreshold();
806
+ if (balanceBefore.gt(threshold) && balanceAfter.lte(threshold)) {
807
+ await this.fireLowBalance(userId, balanceAfter, threshold);
808
+ }
809
+ }
810
+ /** Emit ``credits.low_balance`` and invoke the non-blocking ``onLowBalance``. */
811
+ async fireLowBalance(userId, balance, threshold) {
812
+ const data = { balance, threshold };
813
+ this.emit("credits.low_balance", userId, data);
814
+ if (this.onLowBalance != null) {
815
+ const event = {
816
+ type: "credits.low_balance",
817
+ timestamp: new Date(),
818
+ userId,
819
+ data,
820
+ };
821
+ try {
822
+ // Never block/break the op on a handler failure (§6/H4).
823
+ await this.onLowBalance(event);
824
+ }
825
+ catch (err) {
826
+ console.error(`[CreditManager] onLowBalance handler failed for user ${userId}:`, err);
827
+ }
828
+ }
829
+ }
830
+ /**
831
+ * Full deduction flow as one atomic store call (contract §2).
832
+ *
833
+ * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``
834
+ * (exact `Decimal`, **no truncation**).
835
+ * 2. If ``cost <= 0`` short-circuit with a zero-amount result.
836
+ * 3. Otherwise ``store.deductWithAllowance`` consumes allowance, enforces caps,
837
+ * applies the balance floor and debits — idempotency-keyed end-to-end.
838
+ *
839
+ * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a
840
+ * typed exception is thrown (``insufficient_credits`` → InsufficientCreditsError,
841
+ * ``cap_reached`` → CapReachedError). No success event is emitted on error.
842
+ */
843
+ async deduct(userId, metrics, idempotencyKey, metadata,
844
+ /** Named feature to enforce/tag a per-feature invocation-count limit for. */
845
+ feature) {
846
+ await this.maybeLazyExpire(userId);
847
+ if (!this.engine)
848
+ throw new PricingNotLoadedError("pricing not loaded: call loadPricingFromStore or publishPricing first");
849
+ // 1) Calculate cost — exact Decimal, never truncated (H1).
850
+ const breakdown = this.engine.calculate(metrics);
851
+ const cost = breakdown.total;
852
+ // 2) Zero-amount short-circuit (no balance touch, no store round-trip).
853
+ if (cost.lte(0)) {
854
+ const balance = await this.store.getBalance(userId);
855
+ const result = {
856
+ transactionId: "",
857
+ userId,
858
+ amount: new Decimal(0),
859
+ allowanceConsumed: new Decimal(0),
860
+ balanceAfter: balance.balance,
861
+ idempotent: false,
862
+ capWarning: null,
863
+ featureLimitWarning: null,
864
+ };
865
+ this.emit("credits.deducted", userId, {
866
+ amount: new Decimal(0),
867
+ balanceAfter: balance.balance,
868
+ planCovered: false,
869
+ });
870
+ return result;
871
+ }
872
+ // Build transaction metadata: caller fields FIRST, system fields LAST so the
873
+ // system fields win (contract §5 / M7).
874
+ const meta = {};
875
+ if (metadata) {
876
+ for (const [k, v] of Object.entries(metadata)) {
877
+ if (v != null)
878
+ meta[k] = v;
879
+ }
880
+ }
881
+ meta["inputTokens"] = metrics.inputTokens ?? 0;
882
+ meta["outputTokens"] = metrics.outputTokens ?? 0;
883
+ meta["model"] = metrics.model ?? "unknown";
884
+ meta["breakdownTotal"] = breakdown.total.toString();
885
+ if (metrics.fixedJob)
886
+ meta["fixedJob"] = metrics.fixedJob;
887
+ if (idempotencyKey)
888
+ meta["idempotencyKey"] = idempotencyKey;
889
+ const periodStart = await this.resolveAllowancePeriodStart(userId);
890
+ const { limit: featureLimit, periodStart: featurePeriodStart } = await this.resolveFeatureLimit(userId, feature);
891
+ const options = {
892
+ idempotencyKey: idempotencyKey ?? null,
893
+ minBalance: this.minBalanceDecimal(),
894
+ model: metrics.model ?? null,
895
+ metadata: meta,
896
+ periodStart,
897
+ feature: feature ?? null,
898
+ featureLimit,
899
+ featurePeriodStart,
900
+ };
901
+ // 3) Atomic charge.
902
+ const result = await this.store.deductWithAllowance(userId, cost, options);
903
+ if (result.error) {
904
+ this.emit("credits.deduct_failed", userId, {
905
+ error: result.error,
906
+ amount: cost,
907
+ model: metrics.model ?? null,
908
+ });
909
+ if (result.error === "cap_reached") {
910
+ throw new CapReachedError(`Spend cap exceeded for user ${userId} (requested ${cost})`);
911
+ }
912
+ if (result.error === "feature_limit_reached") {
913
+ this.emit("credits.feature_limit_reached", userId, {
914
+ feature,
915
+ amount: cost,
916
+ model: metrics.model ?? null,
917
+ });
918
+ throw new FeatureLimitReachedError(`Feature limit exceeded for '${feature}'. user=${userId}`);
919
+ }
920
+ // insufficient_credits, invalid_amount, and any other business error.
921
+ throw new InsufficientCreditsError(`Credit deduction failed: ${result.error}. user=${userId}, requested=${cost}`);
922
+ }
923
+ // Success — emit deducted, then any cap warning, then edge-triggered low-balance.
924
+ this.emit("credits.deducted", userId, {
925
+ transactionId: result.transactionId,
926
+ amount: result.amount,
927
+ allowanceConsumed: result.allowanceConsumed,
928
+ balanceAfter: result.balanceAfter,
929
+ model: metrics.model ?? null,
930
+ idempotent: result.idempotent,
931
+ });
932
+ if (result.capWarning) {
933
+ this.emit("credits.cap_warning", userId, {
934
+ action: result.capWarning,
935
+ amount: result.amount,
936
+ model: metrics.model ?? null,
937
+ });
938
+ }
939
+ // Non-blocking feature-limit signal surfaced by the store (parallels
940
+ // capWarning above). A 'deny' feature limit never reaches here — it
941
+ // aborts in the error path — so only warn/notify can appear here.
942
+ if (result.featureLimitWarning === "warn" || result.featureLimitWarning === "notify") {
943
+ this.emit("credits.feature_limit_warning", userId, {
944
+ feature,
945
+ balanceAfter: result.balanceAfter,
946
+ amount: result.amount,
947
+ model: metrics.model ?? null,
948
+ action: result.featureLimitWarning,
949
+ });
950
+ }
951
+ // low_balance is EDGE-triggered (M18): only fire when THIS deduction crossed
952
+ // the threshold. A replayed (idempotent) result did not move the balance, so
953
+ // it never crosses. balanceBefore = balanceAfter + amount charged.
954
+ if (!result.idempotent) {
955
+ const threshold = this.resolveLowBalanceThreshold();
956
+ const balanceBefore = result.balanceAfter.plus(result.amount);
957
+ if (result.balanceAfter.lte(threshold) && balanceBefore.gt(threshold)) {
958
+ this.emit("credits.low_balance", userId, {
959
+ balance: result.balanceAfter,
960
+ threshold,
961
+ minBalance: this.minBalanceDecimal(),
962
+ });
963
+ }
964
+ }
965
+ return result;
966
+ }
967
+ /**
968
+ * Refund a previous credit deduction.
969
+ *
970
+ * H3: the store's ``error`` is checked **before** emitting. A successful refund
971
+ * emits ``credits.refunded``; a failed/duplicate/over-refund emits
972
+ * ``credits.refund_failed`` and throws a typed ``RefundError`` (no success
973
+ * event is ever emitted for a failed refund).
974
+ */
975
+ async refundCredits(transactionId, amount, reason, metadata) {
976
+ const refundAmount = amount != null ? toDecimal(amount) : undefined;
977
+ const result = await this.store.refundCredits(transactionId, refundAmount, reason, metadata);
978
+ if (result.error) {
979
+ this.emit("credits.refund_failed", result.userId, {
980
+ transactionId,
981
+ error: result.error,
982
+ reason: reason ?? null,
983
+ });
984
+ throw new RefundError(`Refund failed: ${result.error}. transaction=${transactionId}`);
985
+ }
986
+ this.emit("credits.refunded", result.userId, {
987
+ transactionId,
988
+ refundTransactionId: result.refundTransactionId,
989
+ amount: result.amount,
990
+ newBalance: result.newBalance,
991
+ reason: reason ?? null,
992
+ });
993
+ return result;
994
+ }
995
+ /**
996
+ * Deduct from a team's shared balance pool.
997
+ *
998
+ * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),
999
+ * then debits the team balance. Threads an optional ``idempotencyKey`` through
1000
+ * to the store so retried team charges are not double-counted (H12).
1001
+ */
1002
+ async deductTeam(teamId, userId, metrics, idempotencyKey, metadata) {
1003
+ // Lazy expiry is scoped to the individual member's credits, not the team's
1004
+ // shared pool — there's no per-team expiry concept.
1005
+ await this.maybeLazyExpire(userId);
1006
+ if (!this.engine)
1007
+ throw new PricingNotLoadedError("pricing not loaded: call loadPricingFromStore or publishPricing first");
1008
+ const breakdown = this.engine.calculate(metrics);
1009
+ const cost = breakdown.total;
1010
+ if (cost.lte(0)) {
1011
+ const teamBal = await this.store.getTeamBalance(teamId);
1012
+ return {
1013
+ transactionId: "",
1014
+ teamId,
1015
+ userId,
1016
+ amount: new Decimal(0),
1017
+ teamBalanceAfter: teamBal.balance,
1018
+ };
1019
+ }
1020
+ const result = await this.store.deductTeam(teamId, userId, cost, metadata, idempotencyKey);
1021
+ // H2 fix: surface store errors — emit credits.deduct_failed and throw,
1022
+ // mirroring Python manager.py:1069-1082. Previously returned a silent
1023
+ // success-shaped object with an .error field, so failed charges looked OK.
1024
+ if (result.error) {
1025
+ this.emit("credits.deduct_failed", userId, {
1026
+ error: result.error,
1027
+ amount: cost,
1028
+ teamId,
1029
+ deductType: "team",
1030
+ });
1031
+ throw new InsufficientCreditsError(`Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`);
1032
+ }
1033
+ this.emit("credits.deducted", userId, {
1034
+ transactionId: result.transactionId,
1035
+ amount: result.amount,
1036
+ teamBalanceAfter: result.teamBalanceAfter,
1037
+ teamId,
1038
+ deductType: "team",
1039
+ });
1040
+ return result;
1041
+ }
1042
+ /**
1043
+ * Shortcut for fixed-cost batch jobs.
1044
+ *
1045
+ * L1: an unknown/typo'd ``jobName`` is rejected (throws) instead of silently
1046
+ * charging 0 credits — ``engine.getFixedCost(jobName) === null`` means the job
1047
+ * is not configured.
1048
+ */
1049
+ async deductFixed(userId, jobName, idempotencyKey, metadata) {
1050
+ await this.maybeLazyExpire(userId);
1051
+ if (!this.engine)
1052
+ throw new PricingNotLoadedError("pricing not loaded: call loadPricingFromStore or publishPricing first");
1053
+ if (this.engine.getFixedCost(jobName) === null) {
1054
+ throw new ConfigError(`unknown fixed job '${jobName}': not configured in pricing 'fixed' section`);
1055
+ }
1056
+ return await this.deduct(userId, { fixedJob: jobName }, idempotencyKey, metadata);
1057
+ }
1058
+ /**
1059
+ * Sweep expired credits — global when ``userId`` is omitted, scoped to a
1060
+ * single user when given (used by ``maybeLazyExpire``). Shared by the public
1061
+ * ``sweepExpiredCredits`` (always global) and the lazy-on-read trigger.
1062
+ */
1063
+ async runSweep(dryRun, userId) {
1064
+ const result = await this.store.sweepExpiredCredits(dryRun, userId);
1065
+ if (!dryRun && result.expiredCount > 0) {
1066
+ this.emit("credits.expired", userId ?? "system", {
1067
+ expiredCount: result.expiredCount,
1068
+ expiredAmount: result.expiredAmount,
1069
+ });
1070
+ }
1071
+ return result;
1072
+ }
1073
+ /**
1074
+ * Sweep expired credits from all users' balances.
1075
+ *
1076
+ * When ``dryRun`` is true, reports what would be expired without modifying
1077
+ * any balances. Unaffected by ``options.lazyExpiry`` — this always runs a
1078
+ * global sweep; lazy expiry only scopes *automatic* per-user sweeps.
1079
+ */
1080
+ async sweepExpiredCredits(dryRun = false) {
1081
+ return await this.runSweep(dryRun, undefined);
1082
+ }
1083
+ // ── Usage analytics ──────────────────────────────────────────────────
1084
+ /** Aggregate statistics across all users in a time window. */
1085
+ async aggregateStats(start, end) {
1086
+ return await this.store.aggregateStats(start, end);
1087
+ }
1088
+ /** Aggregate spend by user in a time window. */
1089
+ async spendByUser(start, end) {
1090
+ return await this.store.spendByUser(start, end);
1091
+ }
1092
+ /** Aggregate spend by model in a time window. */
1093
+ async spendByModel(start, end) {
1094
+ return await this.store.spendByModel(start, end);
1095
+ }
1096
+ /** List all user credit transactions with pagination. */
1097
+ async listUserTransactions(userId, options) {
1098
+ return await this.store.listUserTransactions(userId, options);
1099
+ }
1100
+ async listUsageEvents(userId, options) {
1101
+ return await this.store.listUsageEvents(userId, options);
1102
+ }
1103
+ /** Top users by spend in a time window with limit. */
1104
+ async topUsers(limit, start, end) {
1105
+ return await this.store.topUsers(limit, start, end);
1106
+ }
1107
+ /** Daily spend aggregation in a time window. */
1108
+ async dailySpend(start, end) {
1109
+ return await this.store.dailySpend(start, end);
1110
+ }
1111
+ }
1112
+ //# sourceMappingURL=manager.js.map