@zonastery/bursar 1.0.0 → 1.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.
- package/README.md +108 -64
- package/dist/billing/auto-recharge-port.js.map +1 -1
- package/dist/billing/auto-recharge-service.js.map +1 -1
- package/dist/billing/billing-service.js.map +1 -1
- package/dist/billing/billing-store.d.ts +2 -2
- package/dist/billing/billing-store.d.ts.map +1 -1
- package/dist/billing/billing-store.js.map +1 -1
- package/dist/billing/contracts.js.map +1 -1
- package/dist/billing/event-handlers.d.ts.map +1 -1
- package/dist/billing/event-handlers.js +21 -4
- package/dist/billing/event-handlers.js.map +1 -1
- package/dist/billing/event-processor.d.ts +1 -0
- package/dist/billing/event-processor.d.ts.map +1 -1
- package/dist/billing/event-processor.js +35 -9
- package/dist/billing/event-processor.js.map +1 -1
- package/dist/billing/financial-event-handlers.js.map +1 -1
- package/dist/billing/index.d.ts +1 -0
- package/dist/billing/index.d.ts.map +1 -1
- package/dist/billing/index.js.map +1 -1
- package/dist/billing/management.js.map +1 -1
- package/dist/billing/policy-window.js.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/auto-recharge.js +3 -1
- package/dist/billing/postgres/repositories/auto-recharge.js.map +1 -1
- package/dist/billing/postgres/repositories/customer.js.map +1 -1
- package/dist/billing/postgres/repositories/dispute.js.map +1 -1
- package/dist/billing/postgres/repositories/event.d.ts +2 -2
- package/dist/billing/postgres/repositories/event.d.ts.map +1 -1
- package/dist/billing/postgres/repositories/event.js +10 -12
- package/dist/billing/postgres/repositories/event.js.map +1 -1
- package/dist/billing/postgres/repositories/invoice.js.map +1 -1
- package/dist/billing/postgres/repositories/offer.js.map +1 -1
- package/dist/billing/postgres/repositories/payment.js.map +1 -1
- package/dist/billing/postgres/repositories/preferences.js.map +1 -1
- package/dist/billing/postgres/repositories/refund.js.map +1 -1
- package/dist/billing/postgres/repositories/subscription.js.map +1 -1
- package/dist/billing/postgres/repositories/topup.js.map +1 -1
- package/dist/billing/postgres/store.d.ts +7 -5
- package/dist/billing/postgres/store.d.ts.map +1 -1
- package/dist/billing/postgres/store.js +19 -4
- package/dist/billing/postgres/store.js.map +1 -1
- package/dist/billing/service-types.js.map +1 -1
- package/dist/billing/types/auto-recharge.js.map +1 -1
- package/dist/billing/types/catalog.js.map +1 -1
- package/dist/billing/types/common.js.map +1 -1
- package/dist/billing/types/documents.js.map +1 -1
- package/dist/billing/types/events.js.map +1 -1
- package/dist/billing/types/index.js.map +1 -1
- package/dist/billing/types/preferences.js.map +1 -1
- package/dist/billing/types/subscriptions.js.map +1 -1
- package/dist/breakdown.js.map +1 -1
- package/dist/browser.js.map +1 -1
- package/dist/bursar.d.ts +7 -3
- package/dist/bursar.d.ts.map +1 -1
- package/dist/bursar.js +12 -4
- package/dist/bursar.js.map +1 -1
- package/dist/catalog.d.ts +1 -0
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +1 -0
- package/dist/catalog.js.map +1 -1
- package/dist/commerce/errors.d.ts +3 -4
- package/dist/commerce/errors.d.ts.map +1 -1
- package/dist/commerce/errors.js +3 -5
- package/dist/commerce/errors.js.map +1 -1
- package/dist/commerce/index.js.map +1 -1
- package/dist/commerce/plan-change.js.map +1 -1
- package/dist/commerce/provider-registry.js.map +1 -1
- package/dist/commerce/service.d.ts.map +1 -1
- package/dist/commerce/service.js +47 -12
- package/dist/commerce/service.js.map +1 -1
- package/dist/commerce/types.d.ts +8 -0
- package/dist/commerce/types.d.ts.map +1 -1
- package/dist/commerce/types.js.map +1 -1
- package/dist/config/parse-access.js.map +1 -1
- package/dist/config/parse-commerce.js.map +1 -1
- package/dist/config/parse-credits.js.map +1 -1
- package/dist/config/parse-plans.d.ts.map +1 -1
- package/dist/config/parse-plans.js +23 -7
- package/dist/config/parse-plans.js.map +1 -1
- package/dist/config/parse-pricing.js.map +1 -1
- package/dist/config/parse-utils.js.map +1 -1
- package/dist/config/types.d.ts +14 -1
- package/dist/config/types.d.ts.map +1 -1
- package/dist/config/types.js.map +1 -1
- package/dist/config.d.ts +7 -1
- package/dist/config.d.ts.map +1 -1
- package/dist/config.js +64 -1
- package/dist/config.js.map +1 -1
- package/dist/credits/events.js.map +1 -1
- package/dist/credits/lease-workflow.js.map +1 -1
- package/dist/credits/low-balance-monitor.js.map +1 -1
- package/dist/credits/postgres/repositories/analytics.d.ts +5 -1
- package/dist/credits/postgres/repositories/analytics.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/analytics.js +3 -1
- package/dist/credits/postgres/repositories/analytics.js.map +1 -1
- package/dist/credits/postgres/repositories/balance.js.map +1 -1
- package/dist/credits/postgres/repositories/bucket.js.map +1 -1
- package/dist/credits/postgres/repositories/deduction.d.ts +9 -0
- package/dist/credits/postgres/repositories/deduction.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/deduction.js +24 -0
- package/dist/credits/postgres/repositories/deduction.js.map +1 -1
- package/dist/credits/postgres/repositories/lease.js.map +1 -1
- package/dist/credits/postgres/repositories/plan.d.ts +6 -1
- package/dist/credits/postgres/repositories/plan.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/plan.js +15 -3
- package/dist/credits/postgres/repositories/plan.js.map +1 -1
- package/dist/credits/postgres/repositories/pricing.d.ts +3 -3
- package/dist/credits/postgres/repositories/pricing.d.ts.map +1 -1
- package/dist/credits/postgres/repositories/pricing.js +12 -6
- package/dist/credits/postgres/repositories/pricing.js.map +1 -1
- package/dist/credits/postgres/repositories/team.js.map +1 -1
- package/dist/credits/postgres/store.d.ts +12 -7
- package/dist/credits/postgres/store.d.ts.map +1 -1
- package/dist/credits/postgres/store.js +86 -13
- package/dist/credits/postgres/store.js.map +1 -1
- package/dist/credits/postgres/value-mappers.d.ts.map +1 -1
- package/dist/credits/postgres/value-mappers.js +6 -2
- package/dist/credits/postgres/value-mappers.js.map +1 -1
- package/dist/credits/pricing-runtime.d.ts +3 -2
- package/dist/credits/pricing-runtime.d.ts.map +1 -1
- package/dist/credits/pricing-runtime.js +4 -4
- package/dist/credits/pricing-runtime.js.map +1 -1
- package/dist/credits/queries.js.map +1 -1
- package/dist/credits/service-errors.js.map +1 -1
- package/dist/credits/service-types.js.map +1 -1
- package/dist/credits/service.d.ts +16 -3
- package/dist/credits/service.d.ts.map +1 -1
- package/dist/credits/service.js +51 -5
- package/dist/credits/service.js.map +1 -1
- package/dist/credits/store.d.ts +8 -3
- package/dist/credits/store.d.ts.map +1 -1
- package/dist/credits/store.js +4 -0
- package/dist/credits/store.js.map +1 -1
- package/dist/credits/types/account.d.ts +1 -1
- package/dist/credits/types/account.d.ts.map +1 -1
- package/dist/credits/types/account.js.map +1 -1
- package/dist/credits/types/admission.js.map +1 -1
- package/dist/credits/types/analytics.js.map +1 -1
- package/dist/credits/types/catalog.d.ts +3 -1
- package/dist/credits/types/catalog.d.ts.map +1 -1
- package/dist/credits/types/catalog.js.map +1 -1
- package/dist/credits/types/grants.js.map +1 -1
- package/dist/credits/types/index.js.map +1 -1
- package/dist/credits/types/ledger.d.ts +10 -0
- package/dist/credits/types/ledger.d.ts.map +1 -1
- package/dist/credits/types/ledger.js.map +1 -1
- package/dist/credits/types/quotas.js.map +1 -1
- package/dist/credits/types/teams.js.map +1 -1
- package/dist/engine.js.map +1 -1
- package/dist/errors.d.ts +53 -4
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +61 -5
- package/dist/errors.js.map +1 -1
- package/dist/expr/ast.js.map +1 -1
- package/dist/expr/evaluator.js.map +1 -1
- package/dist/expr/language.js.map +1 -1
- package/dist/expr/parser.js.map +1 -1
- package/dist/expr/tokenizer.js.map +1 -1
- package/dist/expr.js +2 -2
- package/dist/expr.js.map +1 -1
- package/dist/generated/pricing-config.schema.json +37 -9
- package/dist/generated/pricing-config.types.d.ts +14 -3
- package/dist/generated/pricing-config.types.d.ts.map +1 -1
- package/dist/generated/pricing-config.types.js.map +1 -1
- package/dist/index.d.ts +8 -6
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/load-pricing-file.d.ts.map +1 -1
- package/dist/load-pricing-file.js +8 -4
- package/dist/load-pricing-file.js.map +1 -1
- package/dist/metrics.js.map +1 -1
- package/dist/node.js.map +1 -1
- package/dist/providers/_shared.d.ts.map +1 -1
- package/dist/providers/_shared.js +41 -14
- package/dist/providers/_shared.js.map +1 -1
- package/dist/providers/dodo/client-contract.js.map +1 -1
- package/dist/providers/dodo/event-mapper.js.map +1 -1
- package/dist/providers/dodo/index.js.map +1 -1
- package/dist/providers/dodo/provider.js.map +1 -1
- package/dist/providers/index.js.map +1 -1
- package/dist/providers/mock/index.js.map +1 -1
- package/dist/providers/mock/provider.js.map +1 -1
- package/dist/providers/stripe/event-mapper.js.map +1 -1
- package/dist/providers/stripe/index.js.map +1 -1
- package/dist/providers/stripe/provider.js.map +1 -1
- package/dist/providers/types.js.map +1 -1
- package/dist/retry.d.ts +26 -4
- package/dist/retry.d.ts.map +1 -1
- package/dist/retry.js +65 -23
- package/dist/retry.js.map +1 -1
- package/dist/shared/diagnostics.d.ts +7 -0
- package/dist/shared/diagnostics.d.ts.map +1 -0
- package/dist/shared/diagnostics.js +18 -0
- package/dist/shared/diagnostics.js.map +1 -0
- package/dist/shared/logger.js.map +1 -1
- package/dist/shared/postgres-client.d.ts +38 -5
- package/dist/shared/postgres-client.d.ts.map +1 -1
- package/dist/shared/postgres-client.js +261 -25
- package/dist/shared/postgres-client.js.map +1 -1
- package/dist/shared/postgres-errors.d.ts +11 -0
- package/dist/shared/postgres-errors.d.ts.map +1 -0
- package/dist/shared/postgres-errors.js +105 -0
- package/dist/shared/postgres-errors.js.map +1 -0
- package/dist/shared/postgres-types.js.map +1 -1
- package/dist/shared/postgres-validation.d.ts.map +1 -1
- package/dist/shared/postgres-validation.js +1 -1
- package/dist/shared/postgres-validation.js.map +1 -1
- package/dist/storage/adapters/clickhouse.d.ts.map +1 -1
- package/dist/storage/adapters/clickhouse.js +20 -2
- package/dist/storage/adapters/clickhouse.js.map +1 -1
- package/dist/storage/adapters/s3.js.map +1 -1
- package/dist/storage/outbox-worker.d.ts +2 -1
- package/dist/storage/outbox-worker.d.ts.map +1 -1
- package/dist/storage/outbox-worker.js +17 -3
- package/dist/storage/outbox-worker.js.map +1 -1
- package/dist/storage/ports.d.ts +1 -0
- package/dist/storage/ports.d.ts.map +1 -1
- package/dist/storage/ports.js.map +1 -1
- package/dist/storage/postgres-repository.d.ts.map +1 -1
- package/dist/storage/postgres-repository.js +11 -1
- package/dist/storage/postgres-repository.js.map +1 -1
- package/dist/storage/runtime.d.ts +11 -1
- package/dist/storage/runtime.d.ts.map +1 -1
- package/dist/storage/runtime.js +91 -35
- package/dist/storage/runtime.js.map +1 -1
- package/package.json +9 -3
package/dist/credits/service.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import Decimal from "decimal.js";
|
|
2
2
|
import { randomUUID } from "node:crypto";
|
|
3
|
-
import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError } from "../errors.js";
|
|
3
|
+
import { CapReachedError, ConfigError, InsufficientCreditsError, RefundError, StoreError, } from "../errors.js";
|
|
4
4
|
import { raiseDeductError } from "./service-errors.js";
|
|
5
5
|
import { LowBalanceMonitor } from "./low-balance-monitor.js";
|
|
6
6
|
import { CreditQueries } from "./queries.js";
|
|
@@ -199,16 +199,16 @@ export class CreditsService {
|
|
|
199
199
|
* a persistence failure surfaces to the caller instead of becoming an
|
|
200
200
|
* unhandled promise rejection.
|
|
201
201
|
*/
|
|
202
|
-
async publishPricing(config, label) {
|
|
203
|
-
await this.pricing.publish(config, label);
|
|
202
|
+
async publishPricing(config, label, rollout) {
|
|
203
|
+
await this.pricing.publish(config, label, rollout);
|
|
204
204
|
}
|
|
205
205
|
/** Publish a validated, inactive catalog draft. */
|
|
206
206
|
async publishPricingDraft(config, label) {
|
|
207
207
|
return this.pricing.publishDraft(config, label);
|
|
208
208
|
}
|
|
209
209
|
/** Activate an existing catalog version and reload the local engine. */
|
|
210
|
-
async activatePricing(version) {
|
|
211
|
-
return this.pricing.activate(version);
|
|
210
|
+
async activatePricing(version, rollout) {
|
|
211
|
+
return this.pricing.activate(version, rollout);
|
|
212
212
|
}
|
|
213
213
|
/** The current PricingEngine, or null if not loaded. */
|
|
214
214
|
get pricingEngine() {
|
|
@@ -239,6 +239,14 @@ export class CreditsService {
|
|
|
239
239
|
timestamp: new Date().toISOString(),
|
|
240
240
|
});
|
|
241
241
|
}
|
|
242
|
+
/** Pin or unpin the user's current assignment revision. */
|
|
243
|
+
async setPlanRevisionPin(userId, pinned) {
|
|
244
|
+
return this.store.setPlanRevisionPin(userId, pinned);
|
|
245
|
+
}
|
|
246
|
+
/** Apply one bounded batch of renewal-effective plan changes. */
|
|
247
|
+
async applyDuePlanChanges(limit = 100) {
|
|
248
|
+
return this.store.applyDuePlanChanges(limit);
|
|
249
|
+
}
|
|
242
250
|
/** Sweep this user's expired lots when lazy expiry is enabled. */
|
|
243
251
|
async maybeLazyExpire(userId) {
|
|
244
252
|
if (!this.lazyExpiry)
|
|
@@ -476,6 +484,44 @@ export class CreditsService {
|
|
|
476
484
|
}
|
|
477
485
|
return result;
|
|
478
486
|
}
|
|
487
|
+
/**
|
|
488
|
+
* Record priced usage for a workflow without debiting the account again.
|
|
489
|
+
*
|
|
490
|
+
* This is intended for child work inside a fixed-price operation. The
|
|
491
|
+
* parent operation remains the only customer debit; the returned usage row
|
|
492
|
+
* preserves the child cost and metadata in Bursar's usage journal.
|
|
493
|
+
*/
|
|
494
|
+
async recordUsage(userId, metrics, idempotencyKey, metadata) {
|
|
495
|
+
const engine = await this.pricing.engineForUser(userId);
|
|
496
|
+
const plan = await this.store.getUserPlan(userId);
|
|
497
|
+
const effectiveIdempotencyKey = idempotencyKey ?? `usage-record:${randomUUID()}`;
|
|
498
|
+
const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });
|
|
499
|
+
const meta = {};
|
|
500
|
+
if (metadata) {
|
|
501
|
+
for (const [key, value] of Object.entries(metadata)) {
|
|
502
|
+
if (value != null)
|
|
503
|
+
meta[key] = value;
|
|
504
|
+
}
|
|
505
|
+
}
|
|
506
|
+
meta.operation = metrics.operation;
|
|
507
|
+
meta.measures = { ...(metrics.measures ?? {}) };
|
|
508
|
+
meta.dimensions = { ...(metrics.dimensions ?? {}) };
|
|
509
|
+
meta.breakdownTotal = breakdown.total.toString();
|
|
510
|
+
meta.idempotencyKey = effectiveIdempotencyKey;
|
|
511
|
+
const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {
|
|
512
|
+
idempotencyKey: effectiveIdempotencyKey,
|
|
513
|
+
operation: metrics.operation,
|
|
514
|
+
model: typeof metrics.dimensions?.model === "string" ? metrics.dimensions.model : null,
|
|
515
|
+
region: typeof metrics.dimensions?.region === "string" ? metrics.dimensions.region : null,
|
|
516
|
+
measures: { ...(metrics.measures ?? {}) },
|
|
517
|
+
dimensions: { ...(metrics.dimensions ?? {}) },
|
|
518
|
+
metadata: meta,
|
|
519
|
+
});
|
|
520
|
+
if (result.error) {
|
|
521
|
+
throw new StoreError(`Usage record failed: ${result.error}`);
|
|
522
|
+
}
|
|
523
|
+
return result;
|
|
524
|
+
}
|
|
479
525
|
/**
|
|
480
526
|
* Refund a previous credit deduction.
|
|
481
527
|
*
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"service.js","sourceRoot":"","sources":["../../src/credits/service.ts"],"names":[],"mappings":"AAAA,OAAO,OAAO,MAAM,YAAY,CAAC;AACjC,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAC;AACzC,OAAO,EAAE,eAAe,EAAE,WAAW,EAAE,wBAAwB,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AA0CnG,OAAO,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AACvD,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAC7D,OAAO,EAAE,aAAa,EAAE,MAAM,cAA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M,IAAI,wBAAwB,CAChC,0BAA0B,MAAM,CAAC,KAAK,UAAU,MAAM,UAAU,MAAM,eAAe,IAAI,EAAE,CAC5F,CAAC;QACJ,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,kBAAkB,EAAE,MAAM,EAAE;YACpC,OAAO,EAAE,MAAM,CAAC,OAAO;YACvB,MAAM,EAAE,MAAM,CAAC,MAAM;YACrB,gBAAgB,EAAE,MAAM,CAAC,gBAAgB;YACzC,MAAM;YACN,UAAU,EAAE,MAAM;SACnB,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;IACO,KAAK,CAAC,QAAQ,CAAC,MAAe,EAAE,MAAe;QACrD,MAAM,MAAM,GAAG,MAAM,IAAI,CAAC,KAAK,CAAC,mBAAmB,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC;QACpE,IAAI,CAAC,MAAM,IAAI,MAAM,CAAC,YAAY,GAAG,CAAC,EAAE,CAAC;YACvC,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,MAAM,IAAI,QAAQ,EAAE;gBAC/C,YAAY,EAAE,MAAM,CAAC,YAAY;gBACjC,aAAa,EAAE,MAAM,CAAC,aAAa;gBACnC,eAAe,EAAE,MAAM,CAAC,eAAe,IAAI,IAAI;aAChD,CAAC,CAAC;QACL,CAAC;QACD,OAAO,MAAM,CAAC;IAChB,CAAC;IAED;;;;;OAKG;IACH,KAAK,CAAC,mBAAmB,CAAC,MAAM,GAAG,KAAK;QACtC,OAAO,MAAM,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;IACrC,CAAC;CACF","sourcesContent":["import Decimal from \"decimal.js\";\nimport { randomUUID } from \"node:crypto\";\nimport {\n CapReachedError,\n ConfigError,\n InsufficientCreditsError,\n RefundError,\n StoreError,\n} from \"../errors.js\";\nimport type { PricingEngine } from \"../engine.js\";\nimport type { CatalogRollout } from \"../config.js\";\nimport type {\n AddCreditsResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n BursarConfigResult,\n BucketBalancesResult,\n CanAffordResult,\n CheckFeatureResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GetUserPlanResult,\n GrantProgramAwardResult,\n LedgerEntry,\n LedgerPage,\n LeaseResult,\n ListLedgerEntriesOptions,\n ListQuotaEventsOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n RefundResult,\n ReleaseResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamDeductionResult,\n TopUserRow,\n UsageChargePage,\n UsageRecordResult,\n} from \"./types/index.js\";\nimport type { CreditStore } from \"./store.js\";\nimport type { CreditEventEmitter, CreditEventType } from \"./events.js\";\nimport type { UsageMetrics } from \"../metrics.js\";\nimport { raiseDeductError } from \"./service-errors.js\";\nimport { LowBalanceMonitor } from \"./low-balance-monitor.js\";\nimport { CreditQueries } from \"./queries.js\";\nimport { PricingRuntime, toDecimal } from \"./pricing-runtime.js\";\nimport { CreditLeaseWorkflow } from \"./lease-workflow.js\";\nimport type {\n CanAffordOptions,\n CreditsServiceOptions,\n GrantSubscriptionCycleOptions,\n MetricsOrAmount,\n PolicyPreset,\n PostDeductionContext,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n BeginBilledOperationOptions,\n BilledOperation,\n} from \"./service-types.js\";\nexport type {\n CanAffordOptions,\n CreditsServiceOptions,\n GrantSubscriptionCycleOptions,\n LowBalanceConfig,\n PolicyPreset,\n ReserveOptions,\n RunBilledOptions,\n SettleOptions,\n PostDeductionContext,\n BeginBilledOperationOptions,\n BilledOperation,\n} from \"./service-types.js\";\n/**\n * Default lease TTL (seconds) for ``reserve``/``runBilled`` (interface plan §3).\n * Long batch/agentic jobs call the configured lease TTL before this elapses.\n */\nconst DEFAULT_LEASE_TTL_SECONDS = 600;\n\nconst POLICY_PRESETS = new Set<PolicyPreset>([\"strict_prepaid\", \"overdraft\"]);\n\nimport { type NormalizedLogger, normalizeLogger } from \"../shared/logger.js\";\n\n/**\n * Orchestrates credit operations.\n *\n * The deduction path is a single atomic, idempotency-keyed store call\n * (``deductWithAllowance``) that consumes free allowance, enforces plan policy,\n * and debits the net amount in one transaction\n * (contract §2). The manager is a thin layer that calculates the cost, maps\n * the store's typed ``error`` codes to exceptions, and emits lifecycle events\n * **only after** the operation has succeeded (contract §6).\n *\n * Optionally accepts a ``CreditEventEmitter`` to emit lifecycle events\n * (deducted, deduct_failed, added, refunded, refund_failed, expired,\n * low_balance).\n */\nexport class CreditsService {\n private readonly store: CreditStore;\n private readonly queries: CreditQueries;\n private readonly pricing: PricingRuntime;\n private readonly leases: CreditLeaseWorkflow;\n private emitter: CreditEventEmitter | null = null;\n private balanceMonitor: LowBalanceMonitor;\n // Lazy-on-read credit expiry (closes the gap with allowance windows/lease\n // TTLs, which are already lazy-on-read). Default `false` — unchanged\n // behaviour; explicit `sweepExpiredCredits`/cron remains required.\n private lazyExpiry: boolean;\n private logger: NormalizedLogger;\n private readonly postDeductionHooks = new Set<\n (context: PostDeductionContext) => void | Promise<void>\n >();\n constructor(\n store: CreditStore,\n engine?: PricingEngine | null,\n emitter?: CreditEventEmitter | null,\n options?: CreditsServiceOptions | null,\n ) {\n this.store = store;\n this.queries = new CreditQueries(\n store,\n options?.analytics ?? store,\n options?.usageStore ?? store,\n );\n const policy = options?.policy ?? \"strict_prepaid\";\n if (!POLICY_PRESETS.has(policy)) {\n throw new ConfigError(\n `unknown policy preset '${policy}'; expected one of ${[...POLICY_PRESETS].sort().join(\", \")}`,\n );\n }\n if (emitter) this.emitter = emitter;\n this.logger = normalizeLogger(options?.logger);\n if (options?.postDeduction) this.postDeductionHooks.add(options.postDeduction);\n this.pricing = new PricingRuntime(\n store,\n engine ?? null,\n this.logger,\n options?.pricingTtl ?? 300_000,\n );\n this.balanceMonitor = new LowBalanceMonitor(\n options?.lowBalance,\n (type, userId, data) => this.emit(type, userId, data),\n this.logger,\n );\n this.lazyExpiry = options?.lazyExpiry ?? false;\n this.leases = new CreditLeaseWorkflow(\n store,\n this.pricing,\n this.logger,\n this.balanceMonitor,\n policy,\n options?.overdraftFloor != null ? toDecimal(options.overdraftFloor) : null,\n options?.maxConcurrent ?? null,\n options?.defaultTtlSeconds ?? DEFAULT_LEASE_TTL_SECONDS,\n (type, userId, data) => this.emit(type, userId, data),\n (userId, idempotencyKey) => this.emitQuotaEvents(userId, idempotencyKey),\n (userId) => this.maybeLazyExpire(userId),\n (userId, result) => this.afterDeduction(userId, \"settle\", result),\n );\n }\n\n /**\n * Register an awaited post-commit deduction hook. A failing hook is logged\n * and isolated so it can never roll back an already committed charge.\n */\n addPostDeductionHook(hook: (context: PostDeductionContext) => void | Promise<void>): () => void {\n this.postDeductionHooks.add(hook);\n return () => this.postDeductionHooks.delete(hook);\n }\n\n private async afterDeduction(\n userId: string,\n source: PostDeductionContext[\"source\"],\n deduction: PostDeductionContext[\"deduction\"],\n ): Promise<void> {\n for (const hook of this.postDeductionHooks) {\n try {\n await hook({ userId, source, deduction });\n } catch (error) {\n this.logger.warn(\"[CreditsService] post-deduction hook failed\", {\n userId,\n source,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n }\n }\n\n async getActivePricing(): Promise<BursarConfigResult | null> {\n return this.queries.getActivePricing();\n }\n\n async getUserPlan(userId: string): Promise<GetUserPlanResult> {\n return this.queries.getUserPlan(userId);\n }\n\n async checkFeature(userId: string, feature: string): Promise<CheckFeatureResult> {\n return this.queries.checkFeature(userId, feature);\n }\n\n async getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]> {\n return this.queries.getQuotaState(userId, quotaKey);\n }\n\n async listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]> {\n return this.queries.listQuotaEvents(userId, options);\n }\n\n async startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult> {\n return this.queries.startPlanMigration(fromPlanId, toPlanId);\n }\n\n async migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult> {\n return this.queries.migratePlanBatch(migrationId, batchSize);\n }\n\n async revokeCreditsByEntryType(\n userId: string,\n entryType: string,\n ): Promise<Record<string, unknown>> {\n return this.queries.revokeCreditsByEntryType(userId, entryType);\n }\n\n /** Execute an application-driven catalog grant program. */\n async executeGrantProgram(\n request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n return this.store.executeGrantProgram(request);\n }\n\n async getLedgerEntry(userId: string, entryId: string): Promise<LedgerEntry | null> {\n return this.queries.getLedgerEntry(userId, entryId);\n }\n\n async getAvailable(userId: string): Promise<AvailableResult> {\n return this.queries.getAvailable(userId);\n }\n\n async aggregateStats(start: Date, end: Date): Promise<AggregateStats> {\n return this.queries.aggregateStats(start, end);\n }\n\n async spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]> {\n return this.queries.spendByUser(start, end);\n }\n\n async spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]> {\n return this.queries.spendByModel(start, end);\n }\n\n async listLedgerEntries(userId: string, options?: ListLedgerEntriesOptions): Promise<LedgerPage> {\n return this.queries.listLedgerEntries(userId, options);\n }\n\n async listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage> {\n return this.queries.listUsageEntries(userId, options);\n }\n\n async listUsageCharges(\n userId: string,\n options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n return this.queries.listUsageCharges(userId, options);\n }\n\n async topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]> {\n return this.queries.topUsers(limit, start, end);\n }\n\n async dailySpend(start: Date, end: Date): Promise<DailySpendRow[]> {\n return this.queries.dailySpend(start, end);\n }\n\n /** Emit a credit lifecycle event. No-op if no emitter is configured. */\n private emit(type: CreditEventType, userId: string, data?: Record<string, unknown>): void {\n this.emitter?.emit({ type, timestamp: new Date(), userId, data });\n }\n\n private async emitQuotaEvents(userId: string, idempotencyKey: string): Promise<void> {\n const events = await this.store.listQuotaEvents(userId, {\n idempotencyKey,\n limit: 100,\n });\n for (const event of events) {\n const data = {\n quotaKey: event.quotaKey,\n operation: event.operation,\n measure: event.measure,\n thresholdPercent: event.thresholdPercent,\n usageChargeId: event.usageChargeId,\n idempotencyKey: event.idempotencyKey,\n };\n if (event.eventType === \"blocked\") {\n this.emit(\"credits.quota_blocked\", userId, data);\n } else {\n this.emit(\"credits.quota_threshold\", userId, data);\n }\n }\n }\n\n /** Load pricing from a raw dict and sync it. */\n async publishPricingFromDict(data: Record<string, unknown>): Promise<void> {\n await this.pricing.publishFromDict(data);\n }\n\n /** Load the active pricing config from the store. */\n async loadPricingFromStore(): Promise<void> {\n await this.pricing.loadFromStore();\n }\n\n /**\n * If the cached PricingEngine is stale (TTL expired), reload it from the\n * store. Concurrent callers are deduplicated via the underlying\n * ``lru-cache.fetch()`` — only one ``loadPricingFromStore`` runs and all\n * callers await the same result.\n *\n * When ``pricingTtl`` is ``0``, this is a no-op (the consumer must call\n * ``loadPricingFromStore`` manually).\n */\n async refreshIfStale(): Promise<void> {\n await this.pricing.refreshIfStale();\n }\n\n /**\n * Invalidate the pricing cache so the next ``refreshIfStale`` call\n * reloads from the store. Useful after a manual ``loadPricingFromStore``\n * that bypasses the cache, or when the consumer knows the remote config\n * has changed.\n */\n invalidatePricing(): void {\n this.pricing.invalidate();\n }\n\n /**\n * Publish new pricing and update the engine in one call.\n *\n * H10: the store write is now **awaited** (was a fire-and-forget `void`), so\n * a persistence failure surfaces to the caller instead of becoming an\n * unhandled promise rejection.\n */\n async publishPricing(\n config: Record<string, unknown>,\n label?: string | null,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<void> {\n await this.pricing.publish(config, label, rollout);\n }\n\n /** Publish a validated, inactive catalog draft. */\n async publishPricingDraft(\n config: Record<string, unknown>,\n label?: string | null,\n ): Promise<string> {\n return this.pricing.publishDraft(config, label);\n }\n\n /** Activate an existing catalog version and reload the local engine. */\n async activatePricing(\n version: number,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string> {\n return this.pricing.activate(version, rollout);\n }\n\n /** The current PricingEngine, or null if not loaded. */\n get pricingEngine(): PricingEngine | null {\n return this.pricing.currentEngine;\n }\n\n /**\n * Set a user's subscription plan and emit ``credits.plan_changed``.\n *\n * The store call is awaited so a persistence failure surfaces to the caller.\n * The event is emitted only after the store write succeeds (contract §6).\n */\n async setUserPlan(userId: string, planKey: string, planAssignedAt?: Date | null): Promise<void> {\n this.logger.info(\"[CreditsService] setUserPlan\", { planKey, planAssignedAt });\n const result = await this.store.setUserPlan(userId, planKey, planAssignedAt);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey,\n planAssignedAt: result.planAssignedAt ?? null,\n timestamp: new Date().toISOString(),\n });\n }\n\n /** Unset a user's subscription plan and emit the plan-change event. */\n async unsetUserPlan(userId: string): Promise<void> {\n await this.store.unsetUserPlan(userId);\n this.emit(\"credits.plan_changed\", userId, {\n userId,\n planKey: null,\n timestamp: new Date().toISOString(),\n });\n }\n\n /** Pin or unpin the user's current assignment revision. */\n async setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean> {\n return this.store.setPlanRevisionPin(userId, pinned);\n }\n\n /** Apply one bounded batch of renewal-effective plan changes. */\n async applyDuePlanChanges(limit = 100): Promise<number> {\n return this.store.applyDuePlanChanges(limit);\n }\n\n /** Sweep this user's expired lots when lazy expiry is enabled. */\n private async maybeLazyExpire(userId: string): Promise<void> {\n if (!this.lazyExpiry) return;\n await this.runSweep(false, userId);\n }\n\n async getBalance(userId: string): Promise<BalanceResult> {\n await this.maybeLazyExpire(userId);\n return await this.store.getBalance(userId);\n }\n\n /** Add credits to a user's account. */\n async addCredits(\n userId: string,\n amount: Decimal | number,\n options?: {\n type?: string;\n metadata?: CreditMetadata | null;\n expiresAt?: Date | null;\n /** Target credit bucket; omitted resolves to the config's default bucket. */\n bucket?: string | null;\n /** Replay-safe idempotency key (parity with `deduct`/`settle`/`refund`). */\n idempotencyKey?: string | null;\n },\n ): Promise<AddCreditsResult> {\n const type = options?.type ?? \"adjustment\";\n this.logger.info(\"[CreditsService] addCredits\", { amount, type, bucket: options?.bucket });\n const result = await this.store.addCredits(\n userId,\n toDecimal(amount),\n type,\n options?.metadata,\n options?.expiresAt,\n options?.bucket,\n options?.idempotencyKey,\n );\n this.emit(\"credits.added\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n type,\n idempotent: result.idempotent ?? false,\n });\n this.balanceMonitor.rearmAfterCredit(userId, result.newBalance);\n return result;\n }\n\n /**\n * Deduct a raw credit amount from a user's account.\n *\n * Uses the store's `addCredits` with `type='adjustment'` and a negated\n * amount — the existing validation path for negative/zero adjustments.\n * Use this for refund clawbacks and other administrative deductions that\n * bypass the usage-based `deduct()` flow.\n */\n async deductCredits(\n userId: string,\n amount: Decimal | number,\n options?: {\n entryType?: string;\n bucket?: string | null;\n metadata?: CreditMetadata | null;\n },\n ): Promise<AddCreditsResult> {\n const entryType = options?.entryType ?? \"adjustment\";\n this.logger.info(\"[CreditsService] deductCredits\", {\n amount,\n entryType,\n bucket: options?.bucket,\n });\n const result = await this.store.addCredits(\n userId,\n toDecimal(amount).neg(),\n entryType,\n options?.metadata ?? null,\n null,\n options?.bucket ?? undefined,\n undefined,\n );\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n newBalance: result.newBalance,\n entryType,\n });\n await this.afterDeduction(userId, \"raw\", {\n entryId: result.entryId,\n userId,\n amount: result.amount.abs(),\n allowanceConsumed: new Decimal(0),\n balanceAfter: result.newBalance,\n idempotent: result.idempotent ?? false,\n });\n return result;\n }\n\n /**\n * Grant one billing-cycle's worth of credits — idempotent-safe for a\n * payment-provider webhook handler (Stripe, etc. — bursar stays\n * provider-agnostic) to call even on webhook redelivery.\n *\n * 1. At most one of ``expiresAt``/``ttlDays`` may be given (throws\n * ``ConfigError`` otherwise).\n * 2. When ``ttlDays`` is given, ``expiresAt = now + ttlDays`` days.\n * 3. When ``replacePrior`` (default ``true``), any remaining balance in\n * ``bucket`` is expired immediately via a direct ``store.addCredits``\n * negative adjustment — naturally idempotent (a replay finds the bucket\n * already at zero and skips the call).\n * 4. The new cycle is granted via a direct ``store.addCredits`` call\n * (bypassing {@link addCredits} so only ``credits.cycle_renewed`` fires,\n * not a duplicate ``credits.added``), threading ``idempotencyKey`` so a\n * redelivered webhook replays the prior grant instead of double-crediting.\n * 5. When ``planKey`` is given, assigns it via {@link setUserPlan}.\n * 6. Emits ``credits.cycle_renewed`` and returns the grant result.\n */\n async grantSubscriptionCycle(\n userId: string,\n amount: Decimal | number,\n options?: GrantSubscriptionCycleOptions,\n ): Promise<AddCreditsResult> {\n this.logger.info(\"[CreditsService] grantSubscriptionCycle\", {\n amount,\n bucket: options?.bucket,\n planKey: options?.planKey,\n });\n if (options?.expiresAt != null && options?.ttlDays != null) {\n throw new ConfigError(\n \"grantSubscriptionCycle: specify at most one of 'expiresAt' or 'ttlDays', not both\",\n );\n }\n const bucket = options?.bucket ?? \"subscription\";\n const replacePrior = options?.replacePrior ?? true;\n const expiresAt: Date | undefined =\n options?.ttlDays != null\n ? new Date(Date.now() + options.ttlDays * 86_400_000)\n : options?.expiresAt;\n const amountDec = toDecimal(amount);\n\n // Snapshot the bucket's leftover balance before granting. A redelivered\n // webhook must skip the replace-prior wipe as well as the duplicate grant.\n let priorLeftover = new Decimal(0);\n if (replacePrior) {\n const bucketsBefore = await this.getBucketBalances(userId);\n const current = bucketsBefore.buckets.find((t) => t.bucketKey === bucket);\n if (current) priorLeftover = current.balance;\n }\n\n let result = await this.store.addCredits(\n userId,\n amountDec,\n \"purchase\",\n options?.metadata,\n expiresAt,\n bucket,\n options?.idempotencyKey,\n );\n\n // The store contract exposes the mutation's replay result directly, avoiding\n // a racy lifetime-balance comparison and an extra database round trip.\n const isFreshGrant = !result.idempotent;\n if (replacePrior && isFreshGrant && priorLeftover.gt(0)) {\n await this.store.addCredits(\n userId,\n priorLeftover.negated(),\n \"adjustment\",\n { reason: \"cycle_replaced\" },\n undefined,\n bucket,\n );\n // Reflect the post-replace balance so the returned result is accurate\n // (the grant call above only knows the pre-replace balance).\n result = { ...result, newBalance: (await this.getBalance(userId)).balance };\n }\n\n if (options?.planKey) {\n await this.setUserPlan(userId, options.planKey);\n }\n\n this.emit(\"credits.cycle_renewed\", userId, {\n entryId: result.entryId,\n amount: amountDec,\n newBalance: result.newBalance,\n bucket,\n planKey: options?.planKey ?? null,\n idempotencyKey: options?.idempotencyKey ?? null,\n });\n\n return result;\n }\n\n // ── Lease lifecycle: atomic admission (interface plan §3/§4) ────────\n\n async reserve(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: ReserveOptions,\n ): Promise<LeaseResult> {\n return this.leases.reserve(userId, metricsOrAmount, options);\n }\n\n async settle(\n userId: string,\n leaseId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: SettleOptions,\n ): Promise<DeductionResult> {\n return this.leases.settle(userId, leaseId, metricsOrAmount, options);\n }\n\n async release(userId: string, leaseId: string): Promise<ReleaseResult> {\n return this.leases.release(userId, leaseId);\n }\n\n async renew(userId: string, leaseId: string, ttl?: number | null): Promise<LeaseResult> {\n return this.leases.renew(userId, leaseId, ttl);\n }\n\n async canAfford(\n userId: string,\n metricsOrAmount: MetricsOrAmount,\n options?: CanAffordOptions,\n ): Promise<CanAffordResult> {\n return this.leases.canAfford(userId, metricsOrAmount, options);\n }\n\n async getBucketBalances(userId: string): Promise<BucketBalancesResult> {\n return this.leases.getBucketBalances(userId);\n }\n\n async checkAllowance(userId: string): Promise<AllowanceResult> {\n return this.leases.checkAllowance(userId);\n }\n\n async runBilled<T>(\n userId: string,\n options: RunBilledOptions<T>,\n ): Promise<{ result: T; deduction: DeductionResult }> {\n return this.leases.runBilled(userId, options);\n }\n\n async beginBilledOperation(\n userId: string,\n options: BeginBilledOperationOptions,\n ): Promise<BilledOperation> {\n return this.leases.beginBilledOperation(userId, options);\n }\n\n /**\n * Full deduction flow as one atomic store call (contract §2).\n *\n * 1. ``breakdown = engine.calculate(metrics)``; ``cost = breakdown.total``\n * (exact `Decimal`, **no truncation**).\n * 2. ``store.deductWithAllowance`` records the usage, enforces policy, consumes\n * allowance, and debits any remainder — idempotency-keyed end-to-end.\n *\n * On a store ``error`` a ``credits.deduct_failed`` event is emitted and a\n * typed exception is thrown. No success event is emitted on error.\n */\n async deduct(\n userId: string,\n metrics: UsageMetrics,\n idempotencyKey?: string | null,\n metadata?: CreditMetadata | null,\n /** Entitlement feature required for this operation. */\n feature?: string | null,\n ): Promise<DeductionResult> {\n await this.maybeLazyExpire(userId);\n this.logger.debug(\"[CreditsService] deduct\", { model: metrics.dimensions?.model, feature });\n const engine = await this.pricing.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = idempotencyKey ?? `usage:${randomUUID()}`;\n\n // 1) Calculate cost — exact Decimal, never truncated (H1).\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n // Build ledger metadata: caller fields FIRST, system fields LAST so the\n // system fields win (contract §5 / M7).\n const meta: Record<string, unknown> = {};\n if (metadata) {\n for (const [k, v] of Object.entries(metadata)) {\n if (v != null) meta[k] = v;\n }\n }\n meta[\"operation\"] = metrics.operation;\n meta[\"measures\"] = { ...(metrics.measures ?? {}) };\n meta[\"dimensions\"] = { ...(metrics.dimensions ?? {}) };\n meta[\"breakdownTotal\"] = breakdown.total.toString();\n meta[\"idempotencyKey\"] = effectiveIdempotencyKey;\n\n const options: DeductWithAllowanceOptions = {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n feature: feature ?? null,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n };\n\n // 2) Atomic charge. This records zero-cost usage too, so authorization,\n // quotas, and usage history cannot be bypassed by a free rate.\n const result = await this.store.deductWithAllowance(userId, cost, options);\n\n if (result.error) {\n if (result.error === \"quota_exceeded\") {\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n }\n this.logger.warn(\"[CreditsService] deduct failed\", {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model,\n feature,\n });\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n model: metrics.dimensions?.model ?? null,\n });\n raiseDeductError(result.error, userId, cost);\n }\n\n // Success — emit deducted, then any cap warning, then edge-triggered low-balance.\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n allowanceConsumed: result.allowanceConsumed,\n balanceAfter: result.balanceAfter,\n model: metrics.dimensions?.model ?? null,\n idempotent: result.idempotent,\n });\n\n // low_balance is EDGE-triggered (M18): only fire when THIS deduction crossed\n // the threshold. A replayed (idempotent) result did not move the balance, so\n // it never crosses. balanceBefore = balanceAfter + amount charged.\n if (!result.idempotent) {\n const balanceBefore = result.balanceAfter.plus(result.amount);\n await this.balanceMonitor.signalCrossing(userId, balanceBefore, result.balanceAfter);\n await this.emitQuotaEvents(userId, effectiveIdempotencyKey);\n await this.afterDeduction(userId, \"deduct\", result);\n }\n\n return result;\n }\n\n /**\n * Record priced usage for a workflow without debiting the account again.\n *\n * This is intended for child work inside a fixed-price operation. The\n * parent operation remains the only customer debit; the returned usage row\n * preserves the child cost and metadata in Bursar's usage journal.\n */\n async recordUsage(\n userId: string,\n metrics: UsageMetrics,\n idempotencyKey?: string | null,\n metadata?: CreditMetadata | null,\n ): Promise<UsageRecordResult> {\n const engine = await this.pricing.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n const effectiveIdempotencyKey = idempotencyKey ?? `usage-record:${randomUUID()}`;\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const meta: Record<string, unknown> = {};\n if (metadata) {\n for (const [key, value] of Object.entries(metadata)) {\n if (value != null) meta[key] = value;\n }\n }\n meta.operation = metrics.operation;\n meta.measures = { ...(metrics.measures ?? {}) };\n meta.dimensions = { ...(metrics.dimensions ?? {}) };\n meta.breakdownTotal = breakdown.total.toString();\n meta.idempotencyKey = effectiveIdempotencyKey;\n\n const result = await this.store.recordUsage(userId, metrics.operation, breakdown.total, {\n idempotencyKey: effectiveIdempotencyKey,\n operation: metrics.operation,\n model: typeof metrics.dimensions?.model === \"string\" ? metrics.dimensions.model : null,\n region: typeof metrics.dimensions?.region === \"string\" ? metrics.dimensions.region : null,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: { ...(metrics.dimensions ?? {}) },\n metadata: meta as CreditMetadata,\n });\n if (result.error) {\n throw new StoreError(`Usage record failed: ${result.error}`);\n }\n return result;\n }\n\n /**\n * Refund a previous credit deduction.\n *\n * Returns the RefundResult. A successful refund\n * emits ``credits.refunded``; a failed/duplicate/over-refund emits\n * ``credits.refund_failed`` (no success event is ever emitted for a failed\n * refund).\n */\n /** Deduct the configured fixed cost for one named job. */\n async deductFlatJob(\n userId: string,\n jobName: string,\n idempotencyKey?: string | null,\n metadata?: CreditMetadata | null,\n feature?: string | null,\n ): Promise<DeductionResult> {\n return this.deduct(\n userId,\n { operation: jobName, measures: { jobs: 1 } },\n idempotencyKey,\n metadata,\n feature,\n );\n }\n\n async refundCredits(\n entryId: string,\n amount?: Decimal | number,\n reason?: string,\n metadata?: CreditMetadata | null,\n idempotencyKey?: string | null,\n ): Promise<RefundResult> {\n const refundAmount = amount != null ? toDecimal(amount) : undefined;\n this.logger.info(\"[CreditsService] refundCredits\", { entryId, refundAmount, reason });\n const result = await this.store.refundCredits(\n entryId,\n refundAmount,\n reason,\n metadata,\n idempotencyKey,\n );\n\n if (result.error) {\n this.logger.warn(\"[CreditsService] refundCredits failed\", {\n entryId,\n error: result.error,\n });\n this.emit(\"credits.refund_failed\", result.userId, {\n entryId,\n error: result.error,\n reason: reason ?? null,\n });\n throw new RefundError(`Refund rejected: ${result.error}`);\n }\n\n this.emit(\"credits.refunded\", result.userId, {\n entryId,\n refundEntryId: result.refundEntryId,\n amount: result.amount,\n newBalance: result.newBalance,\n reason: reason ?? null,\n });\n return result;\n }\n\n /**\n * Deduct from a team's shared balance pool.\n *\n * Calculates the cost via the pricing engine (exact `Decimal`, no truncation),\n * then debits the team balance. Threads an optional ``idempotencyKey`` through\n * to the store so retried team charges are not double-counted (H12).\n */\n async deductTeam(\n teamId: string,\n userId: string,\n metrics: UsageMetrics,\n idempotencyKey?: string | null,\n metadata?: CreditMetadata | null,\n ): Promise<TeamDeductionResult> {\n await this.maybeLazyExpire(userId);\n // Lazy expiry is scoped to the individual member's credits, not the team's\n // shared pool — there's no per-team expiry concept.\n const engine = await this.pricing.engineForUser(userId);\n const plan = await this.store.getUserPlan(userId);\n\n const breakdown = engine.calculate(metrics, { rateCard: plan.rateCard ?? undefined });\n const cost = breakdown.total;\n\n if (cost.lte(0)) {\n const teamBal = await this.store.getTeamBalance(teamId);\n return {\n entryId: \"\",\n teamId,\n userId,\n amount: new Decimal(0),\n teamBalanceAfter: teamBal.balance,\n };\n }\n\n const teamMetadata: CreditMetadata = {\n ...(metadata ?? {}),\n operation: metrics.operation,\n measures: { ...(metrics.measures ?? {}) },\n dimensions: Object.fromEntries(\n Object.entries(metrics.dimensions ?? {}).map(([key, value]) => [key, String(value)]),\n ),\n breakdownTotal: breakdown.total.toString(),\n };\n const result = await this.store.deductTeam(teamId, userId, cost, teamMetadata, idempotencyKey);\n // H2 fix: surface store errors — emit credits.deduct_failed and throw,\n // mirroring the Python credit service implementation. Previously returned a silent\n // success-shaped object with an .error field, so failed charges looked OK.\n if (result.error) {\n this.emit(\"credits.deduct_failed\", userId, {\n error: result.error,\n amount: cost,\n teamId,\n deductType: \"team\",\n });\n if (result.error === \"member_spend_cap_exceeded\") {\n throw new CapReachedError(\n `Team member spend cap exceeded. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n throw new InsufficientCreditsError(\n `Team deduction failed: ${result.error}. Team=${teamId}, user=${userId}, requested=${cost}`,\n );\n }\n this.emit(\"credits.deducted\", userId, {\n entryId: result.entryId,\n amount: result.amount,\n teamBalanceAfter: result.teamBalanceAfter,\n teamId,\n deductType: \"team\",\n });\n return result;\n }\n private async runSweep(dryRun: boolean, userId?: string): Promise<SweepResult> {\n const result = await this.store.sweepExpiredCredits(dryRun, userId);\n if (!dryRun && result.expiredCount > 0) {\n this.emit(\"credits.expired\", userId ?? \"system\", {\n expiredCount: result.expiredCount,\n expiredAmount: result.expiredAmount,\n expiredByBucket: result.expiredByBucket ?? null,\n });\n }\n return result;\n }\n\n /**\n * Sweep expired credits from all users' balances.\n *\n * When ``dryRun`` is true, reports what would expire without mutating\n * balances. Automatic lazy sweeps remain scoped to one subject.\n */\n async sweepExpiredCredits(dryRun = false): Promise<SweepResult> {\n return await this.runSweep(dryRun);\n }\n}\n"]}
|
package/dist/credits/store.d.ts
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { Decimal } from "decimal.js";
|
|
2
|
-
import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, BillingMode, BucketBalancesResult, CheckFeatureResult, CreateTeamResult, CreditMetadata, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, ListQuotaEventsOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListUsageEntriesOptions, LedgerPage, UsageChargePage, BursarConfigHistoryItem, BursarConfigResult, RefundResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TopUserRow, LedgerEntry } from "./types/index.js";
|
|
2
|
+
import type { AddCreditsResult, AddTeamMemberResult, AggregateStats, AllowanceResult, AvailableResult, BalanceResult, BillingMode, BucketBalancesResult, CheckFeatureResult, CreateTeamResult, CreditMetadata, DailySpendRow, DeductionResult, DeductWithAllowanceOptions, ExecuteGrantProgramRequest, GrantProgramAwardResult, GetUserPlanResult, ListQuotaEventsOptions, PlanMigrationBatchResult, PlanMigrationStartResult, QuotaEvent, QuotaState, LeaseResult, LeasePricingContext, ListLedgerEntriesOptions, ListUsageChargesOptions, ListUsageEntriesOptions, LedgerPage, UsageChargePage, UsageRecordResult, BursarConfigHistoryItem, BursarConfigResult, RefundResult, ReleaseResult, SetUserPlanResult, SpendByModelRow, SpendByUserRow, SweepResult, TeamBalanceResult, TeamDeductionResult, TeamMember, TopUserRow, LedgerEntry } from "./types/index.js";
|
|
3
|
+
import type { CatalogRollout } from "../config.js";
|
|
3
4
|
export interface OperationUsageOptions {
|
|
4
5
|
/** Entitlement feature that must be enabled for the operation. */
|
|
5
6
|
feature?: string | null;
|
|
@@ -104,16 +105,18 @@ export declare abstract class CreditStore {
|
|
|
104
105
|
*/
|
|
105
106
|
abstract getAvailable(userId: string): Promise<AvailableResult>;
|
|
106
107
|
abstract getActivePricing(): Promise<BursarConfigResult | null>;
|
|
107
|
-
abstract setActivePricing(config: Record<string, unknown>, label?: string | null): Promise<string>;
|
|
108
|
+
abstract setActivePricing(config: Record<string, unknown>, label?: string | null, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
|
|
108
109
|
abstract publishPricing(config: Record<string, unknown>, label?: string | null): Promise<string>;
|
|
109
110
|
abstract getPricingHistory(): Promise<BursarConfigHistoryItem[]>;
|
|
110
111
|
abstract getBursarConfig(version: number): Promise<BursarConfigResult | null>;
|
|
111
|
-
abstract activatePricing(version: number): Promise<string>;
|
|
112
|
+
abstract activatePricing(version: number, rollout?: CatalogRollout | Record<string, unknown> | null): Promise<string>;
|
|
112
113
|
abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;
|
|
113
114
|
abstract setUserPlan(userId: string, planKey: string, planAssignedAt?: Date | null): Promise<SetUserPlanResult>;
|
|
114
115
|
abstract unsetUserPlan(userId: string): Promise<{
|
|
115
116
|
userId: string;
|
|
116
117
|
}>;
|
|
118
|
+
abstract setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean>;
|
|
119
|
+
abstract applyDuePlanChanges(limit?: number): Promise<number>;
|
|
117
120
|
abstract startPlanMigration(fromPlanId: string | null, toPlanId: string): Promise<PlanMigrationStartResult>;
|
|
118
121
|
abstract migratePlanBatch(migrationId: string, batchSize?: number): Promise<PlanMigrationBatchResult>;
|
|
119
122
|
abstract checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;
|
|
@@ -152,6 +155,8 @@ export declare abstract class CreditStore {
|
|
|
152
155
|
abstract listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;
|
|
153
156
|
/** Read metered usage charges, including allowance-covered events. */
|
|
154
157
|
listUsageCharges(_userId: string, _options?: ListUsageChargesOptions): Promise<UsageChargePage>;
|
|
158
|
+
/** Append priced usage telemetry without debiting the account again. */
|
|
159
|
+
recordUsage(_userId: string, _operation: string, _requested: Decimal, _options?: DeductWithAllowanceOptions): Promise<UsageRecordResult>;
|
|
155
160
|
/**
|
|
156
161
|
* Fetch a single transaction by ID. Returns `null` when the transaction
|
|
157
162
|
* does not exist or belongs to a different user.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,UAAU,EACV,eAAe,EACf,uBAAuB,EACvB,kBAAkB,EAClB,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,UAAU,EACV,UAAU,EACV,WAAW,EACZ,MAAM,kBAAkB,CAAC;
|
|
1
|
+
{"version":3,"file":"store.d.ts","sourceRoot":"","sources":["../../src/credits/store.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,OAAO,KAAK,EACV,gBAAgB,EAChB,mBAAmB,EACnB,cAAc,EACd,eAAe,EACf,eAAe,EACf,aAAa,EACb,WAAW,EACX,oBAAoB,EACpB,kBAAkB,EAClB,gBAAgB,EAChB,cAAc,EACd,aAAa,EACb,eAAe,EACf,0BAA0B,EAC1B,0BAA0B,EAC1B,uBAAuB,EACvB,iBAAiB,EACjB,sBAAsB,EACtB,wBAAwB,EACxB,wBAAwB,EACxB,UAAU,EACV,UAAU,EACV,WAAW,EACX,mBAAmB,EACnB,wBAAwB,EACxB,uBAAuB,EACvB,uBAAuB,EACvB,UAAU,EACV,eAAe,EACf,iBAAiB,EACjB,uBAAuB,EACvB,kBAAkB,EAClB,YAAY,EACZ,aAAa,EACb,iBAAiB,EACjB,eAAe,EACf,cAAc,EACd,WAAW,EACX,iBAAiB,EACjB,mBAAmB,EACnB,UAAU,EACV,UAAU,EACV,WAAW,EACZ,MAAM,kBAAkB,CAAC;AAC1B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AAEnD,MAAM,WAAW,qBAAqB;IACpC,kEAAkE;IAClE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACxB,KAAK,CAAC,EAAE,MAAM,G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AC,WAAW,GAAG,IAAI,CAAC;IAK9E,UAAU,CACd,eAAe,EAAE,MAAM,EACvB,KAAK,EAAE,MAAM,EACb,eAAe,CAAC,EAAE,OAAO,GACxB,OAAO,CAAC,gBAAgB,CAAC;IAGtB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,iBAAiB,CAAC;IAG3D,aAAa,CACjB,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,KAAK,CAAC,EAAE,MAAM,EACd,SAAS,CAAC,EAAE,OAAO,GAAG,IAAI,GACzB,OAAO,CAAC,mBAAmB,CAAC;IAGzB,cAAc,CAAC,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,EAAE,CAAC;IAGtD,gBAAgB,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC;IAGpE,UAAU,CACd,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,MAAM,EACf,OAAO,EAAE,OAAO,EAChB,SAAS,CAAC,EAAE,cAAc,GAAG,IAAI,EACjC,eAAe,CAAC,EAAE,MAAM,GAAG,IAAI,GAC9B,OAAO,CAAC,mBAAmB,CAAC;CAGhC"}
|
package/dist/credits/store.js
CHANGED
|
@@ -45,6 +45,10 @@ export class CreditStore {
|
|
|
45
45
|
async listUsageCharges(_userId, _options) {
|
|
46
46
|
throw new CapabilityNotSupportedError("listUsageCharges is not supported by this store");
|
|
47
47
|
}
|
|
48
|
+
/** Append priced usage telemetry without debiting the account again. */
|
|
49
|
+
async recordUsage(_userId, _operation, _requested, _options) {
|
|
50
|
+
throw new CapabilityNotSupportedError("recordUsage is not supported by this store");
|
|
51
|
+
}
|
|
48
52
|
// ── Single transaction lookup (optional capability — WS8) ────────────
|
|
49
53
|
/**
|
|
50
54
|
* Fetch a single transaction by ID. Returns `null` when the transaction
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"store.js","sourceRoot":"","sources":["../../src/cred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C;IAED,wEAAwE;IACxE,KAAK,CAAC,UAAU,CACd,eAAuB,EACvB,KAAa,EACb,eAAyB;QAEzB,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,aAAa,CACjB,OAAe,EACf,OAAe,EACf,KAAc,EACd,SAA0B;QAE1B,MAAM,IAAI,2BAA2B,CAAC,8CAA8C,CAAC,CAAC;IACxF,CAAC;IACD,KAAK,CAAC,cAAc,CAAC,OAAe;QAClC,MAAM,IAAI,2BAA2B,CAAC,+CAA+C,CAAC,CAAC;IACzF,CAAC;IACD,KAAK,CAAC,gBAAgB,CAAC,OAAe,EAAE,OAAe;QACrD,MAAM,IAAI,2BAA2B,CAAC,iDAAiD,CAAC,CAAC;IAC3F,CAAC;IACD,KAAK,CAAC,UAAU,CACd,OAAe,EACf,OAAe,EACf,OAAgB,EAChB,SAAiC,EACjC,eAA+B;QAE/B,MAAM,IAAI,2BAA2B,CAAC,2CAA2C,CAAC,CAAC;IACrF,CAAC;CACF","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport { CapabilityNotSupportedError } from \"../errors.js\";\nimport type {\n AddCreditsResult,\n AddTeamMemberResult,\n AggregateStats,\n AllowanceResult,\n AvailableResult,\n BalanceResult,\n BillingMode,\n BucketBalancesResult,\n CheckFeatureResult,\n CreateTeamResult,\n CreditMetadata,\n DailySpendRow,\n DeductionResult,\n DeductWithAllowanceOptions,\n ExecuteGrantProgramRequest,\n GrantProgramAwardResult,\n GetUserPlanResult,\n ListQuotaEventsOptions,\n PlanMigrationBatchResult,\n PlanMigrationStartResult,\n QuotaEvent,\n QuotaState,\n LeaseResult,\n LeasePricingContext,\n ListLedgerEntriesOptions,\n ListUsageChargesOptions,\n ListUsageEntriesOptions,\n LedgerPage,\n UsageChargePage,\n UsageRecordResult,\n BursarConfigHistoryItem,\n BursarConfigResult,\n RefundResult,\n ReleaseResult,\n SetUserPlanResult,\n SpendByModelRow,\n SpendByUserRow,\n SweepResult,\n TeamBalanceResult,\n TeamDeductionResult,\n TeamMember,\n TopUserRow,\n LedgerEntry,\n} from \"./types/index.js\";\nimport type { CatalogRollout } from \"../config.js\";\n\nexport interface OperationUsageOptions {\n /** Entitlement feature that must be enabled for the operation. */\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n}\n\n/** Options for atomically acquiring a lease (interface plan §3 / D4). */\nexport interface CreateLeaseOptions extends OperationUsageOptions {\n /**\n * Replay-safe acquisition key. Supplying the same key with the same request\n * returns the original lease; conflicting reuse is rejected.\n */\n idempotencyKey?: string | null;\n billingMode?: BillingMode;\n floor?: Decimal;\n maxConcurrent?: number | null;\n overdraftFloor?: Decimal | null;\n ttlSeconds?: number;\n metadata?: CreditMetadata | null;\n}\n\n/** Options for charging the actual cost against a lease (interface plan §3 / D5). */\nexport interface SettleLeaseOptions extends OperationUsageOptions {\n idempotencyKey?: string | null;\n metadata?: CreditMetadata | null;\n}\n\n/**\n * Abstract base for credit storage backends (WS8).\n *\n * Split into two tiers:\n * - **Core** (abstract, must be implemented): balance/credit ops, the atomic\n * lease lifecycle, bursar-config versioning, plan management,\n * refunds, and expiry sweeping. Every backend needs these.\n * - **Optional capabilities** (concrete, default-throwing): usage analytics,\n * ledger listing, and shared team-balance pools. A custom store that\n * doesn't need these can skip them entirely — the default implementation\n * throws {@link CapabilityNotSupportedError} instead of forcing a stub.\n */\nexport abstract class CreditStore {\n constructor() {}\n\n abstract getBalance(userId: string): Promise<BalanceResult>;\n abstract addCredits(\n userId: string,\n amount: Decimal,\n type?: string,\n metadata?: CreditMetadata | null,\n expiresAt?: Date | null,\n /** Target credit bucket; omitted/`null` resolves to the config's default bucket. */\n bucket?: string | null,\n /**\n * Replay-safe idempotency key (parity with the `deduct`/`settle`/`refund`\n * idempotency idiom). When a prior grant for this `userId` carries the same\n * key, the prior result is returned unchanged and no new credits are granted.\n */\n idempotencyKey?: string | null,\n ): Promise<AddCreditsResult>;\n /**\n * Atomically calculate-and-charge in one server-side transaction:\n * consume free allowance, enforce plan policy and quotas, and debit the net\n * amount — idempotency-keyed end-to-end. See contract §2.\n */\n abstract deductWithAllowance(\n userId: string,\n amount: Decimal,\n options?: DeductWithAllowanceOptions,\n ): Promise<DeductionResult>;\n\n // ── Lease lifecycle (atomic admission) ─────────────────────────────\n //\n // The lease is the canonical admission primitive (interface plan §3/D4).\n // ``reserve``/``settle``/``release`` on the manager map onto these.\n // Leases reuse the credit_reservations table/records extended with a status\n // (active → settled | released | expired), a billing mode, and an overdraft\n // floor. ``available = balance − Σ(amount WHERE status='active' AND unexpired)``.\n\n /**\n * Atomically acquire a lease (hold) — the only admission control (D4).\n *\n * Under one critical section the store: (1) ensures the balance row exists;\n * (2) enforces ``maxConcurrent`` by counting active leases for ``(userId,\n * operationType)``; (3) enforces plan entitlements and quotas; (4) computes\n * ``available = balance − Σ active holds`` and rejects with\n * ``error=\"insufficient_credits\"`` if ``available − amount < floor``; (5) inserts\n * an ``active`` lease expiring after ``ttlSeconds``. Business failures are\n * returned via ``LeaseResult.error``; the store never raises domain exceptions.\n */\n abstract createLease(\n userId: string,\n amount: Decimal,\n operationType: string,\n options?: CreateLeaseOptions,\n ): Promise<LeaseResult>;\n\n /**\n * Charge the actual cost against a lease, then mark it settled (D5).\n *\n * De-clamped: charges ``amount`` even if it exceeds the lease hold (overdraft)\n * and never clamps to the reserved ceiling. The balance may go negative in\n * overdraft. ``amount === 0`` releases the lease without charging.\n * Lease-state failures (``lease_not_found``/``lease_expired``) are returned via\n * ``DeductionResult.error``; a replay returns the original result idempotently.\n */\n abstract settleLease(\n userId: string,\n leaseId: string,\n amount: Decimal,\n options?: SettleLeaseOptions,\n ): Promise<DeductionResult>;\n\n /** Read the immutable catalog and rate card captured at lease admission. */\n abstract getLeasePricingContext(\n userId: string,\n leaseId: string,\n ): Promise<LeasePricingContext | null>;\n\n /**\n * Release a lease without charging (work failed/aborted) — idempotent (H1).\n *\n * Transitions an ``active``/``expired`` lease to ``released`` and reports\n * ``released=true``; otherwise reports ``released=false`` with a ``reason``.\n */\n abstract releaseLease(userId: string, leaseId: string): Promise<ReleaseResult>;\n\n /**\n * Extend an active lease's TTL (long batch/agentic jobs, resolves B4).\n *\n * Returns ``error=\"lease_expired\"`` if the TTL already elapsed and\n * ``error=\"lease_not_found\"`` if missing/other-user/finalized.\n */\n abstract renewLease(userId: string, leaseId: string, ttlSeconds: number): Promise<LeaseResult>;\n\n /** Expire a bounded batch of abandoned leases and release their reservations. */\n async expireLeases(_limit?: number): Promise<number> {\n throw new CapabilityNotSupportedError(\"expireLeases is not supported by this store\");\n }\n\n /**\n * Advisory, non-locking read of ``available = balance − Σ active holds``.\n *\n * For UI only — never an admission gate (D4/H3); may be stale the instant read.\n */\n\n abstract getAvailable(userId: string): Promise<AvailableResult>;\n\n abstract getActivePricing(): Promise<BursarConfigResult | null>;\n abstract setActivePricing(\n config: Record<string, unknown>,\n label?: string | null,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string>;\n abstract publishPricing(config: Record<string, unknown>, label?: string | null): Promise<string>;\n\n // H8: pricing history / activation — parity with Python base.py:293-312.\n abstract getPricingHistory(): Promise<BursarConfigHistoryItem[]>;\n abstract getBursarConfig(version: number): Promise<BursarConfigResult | null>;\n abstract activatePricing(\n version: number,\n rollout?: CatalogRollout | Record<string, unknown> | null,\n ): Promise<string>;\n\n abstract getUserPlan(userId: string): Promise<GetUserPlanResult>;\n abstract setUserPlan(\n userId: string,\n planKey: string,\n planAssignedAt?: Date | null,\n ): Promise<SetUserPlanResult>;\n abstract unsetUserPlan(userId: string): Promise<{ userId: string }>;\n abstract setPlanRevisionPin(userId: string, pinned: boolean): Promise<boolean>;\n abstract applyDuePlanChanges(limit?: number): Promise<number>;\n abstract startPlanMigration(\n fromPlanId: string | null,\n toPlanId: string,\n ): Promise<PlanMigrationStartResult>;\n abstract migratePlanBatch(\n migrationId: string,\n batchSize?: number,\n ): Promise<PlanMigrationBatchResult>;\n abstract checkFeature(userId: string, feature: string): Promise<CheckFeatureResult>;\n abstract getQuotaState(userId: string, quotaKey?: string | null): Promise<QuotaState[]>;\n abstract listQuotaEvents(userId: string, options?: ListQuotaEventsOptions): Promise<QuotaEvent[]>;\n abstract checkAllowance(userId: string): Promise<AllowanceResult>;\n\n abstract revokeCreditsByEntryType(\n userId: string,\n entryType: string,\n ): Promise<Record<string, unknown>>;\n\n // ── Refunds ────────────────────────────────────────────────────────\n abstract refundCredits(\n entryId: string,\n amount?: Decimal,\n reason?: string,\n metadata?: CreditMetadata | null,\n /** Replay-safe key; pass a unique key for multiple equal partial refunds. */\n idempotencyKey?: string | null,\n ): Promise<RefundResult>;\n\n // ── Credit expiry ────────────────────────────────────────────────────\n /**\n * Sweep expired credit grants and debit the aggregate/tier balances.\n *\n * When `userId` is omitted (default), sweeps globally across every user —\n * unchanged behaviour/output shape from before this parameter existed. When\n * given, restricts the scan/expiry to that user's transactions only (used by\n * bounded expiry sweep operation).\n */\n abstract sweepExpiredCredits(\n dryRun?: boolean,\n userId?: string,\n limit?: number,\n ): Promise<SweepResult>;\n\n // ── Credit buckets ─────────────────────────────────────────────────────\n /**\n * Per-bucket credit balances for a user (credit buckets).\n *\n * Sorted by `priority` ascending. When no buckets are configured, synthesizes\n * a single `\"default\"` entry from the aggregate balance so the shape is\n * uniform either way.\n */\n abstract getBucketBalances(userId: string): Promise<BucketBalancesResult>;\n\n /** Execute one configured grant-program event. */\n async executeGrantProgram(\n _request: ExecuteGrantProgramRequest,\n ): Promise<GrantProgramAwardResult[]> {\n throw new CapabilityNotSupportedError(\"executeGrantProgram is not supported by this store\");\n }\n\n // ── Usage analytics (optional capability — WS8) ──────────────────────\n async spendByUser(_start: Date, _end: Date): Promise<SpendByUserRow[]> {\n throw new CapabilityNotSupportedError(\"spendByUser is not supported by this store\");\n }\n async spendByModel(_start: Date, _end: Date): Promise<SpendByModelRow[]> {\n throw new CapabilityNotSupportedError(\"spendByModel is not supported by this store\");\n }\n async topUsers(_limit: number, _start: Date, _end: Date): Promise<TopUserRow[]> {\n throw new CapabilityNotSupportedError(\"topUsers is not supported by this store\");\n }\n async dailySpend(_start: Date, _end: Date): Promise<DailySpendRow[]> {\n throw new CapabilityNotSupportedError(\"dailySpend is not supported by this store\");\n }\n async aggregateStats(_start: Date, _end: Date): Promise<AggregateStats> {\n throw new CapabilityNotSupportedError(\"aggregateStats is not supported by this store\");\n }\n\n // ── Transaction listing (optional capability — WS8) ──────────────────\n async listLedgerEntries(\n _userId: string,\n _options?: ListLedgerEntriesOptions,\n ): Promise<LedgerPage> {\n throw new CapabilityNotSupportedError(\"listLedgerEntries is not supported by this store\");\n }\n abstract listUsageEntries(userId: string, options?: ListUsageEntriesOptions): Promise<LedgerPage>;\n\n /** Read metered usage charges, including allowance-covered events. */\n async listUsageCharges(\n _userId: string,\n _options?: ListUsageChargesOptions,\n ): Promise<UsageChargePage> {\n throw new CapabilityNotSupportedError(\"listUsageCharges is not supported by this store\");\n }\n\n /** Append priced usage telemetry without debiting the account again. */\n async recordUsage(\n _userId: string,\n _operation: string,\n _requested: Decimal,\n _options?: DeductWithAllowanceOptions,\n ): Promise<UsageRecordResult> {\n throw new CapabilityNotSupportedError(\"recordUsage is not supported by this store\");\n }\n\n // ── Single transaction lookup (optional capability — WS8) ────────────\n /**\n * Fetch a single transaction by ID. Returns `null` when the transaction\n * does not exist or belongs to a different user.\n */\n async getLedgerEntry(_userId: string, _entryId: string): Promise<LedgerEntry | null> {\n throw new CapabilityNotSupportedError(\"getLedgerEntry is not supported by this store\");\n }\n\n // ── Team/shared balance pools (optional capability — WS8) ────────────\n async createTeam(\n _ownerSubjectId: string,\n _name: string,\n _initialBalance?: Decimal,\n ): Promise<CreateTeamResult> {\n throw new CapabilityNotSupportedError(\"createTeam is not supported by this store\");\n }\n async getTeamBalance(_teamId: string): Promise<TeamBalanceResult> {\n throw new CapabilityNotSupportedError(\"getTeamBalance is not supported by this store\");\n }\n async addTeamMember(\n _teamId: string,\n _userId: string,\n _role?: string,\n _spendCap?: Decimal | null,\n ): Promise<AddTeamMemberResult> {\n throw new CapabilityNotSupportedError(\"addTeamMember is not supported by this store\");\n }\n async getTeamMembers(_teamId: string): Promise<TeamMember[]> {\n throw new CapabilityNotSupportedError(\"getTeamMembers is not supported by this store\");\n }\n async removeTeamMember(_teamId: string, _userId: string): Promise<boolean> {\n throw new CapabilityNotSupportedError(\"removeTeamMember is not supported by this store\");\n }\n async deductTeam(\n _teamId: string,\n _userId: string,\n _amount: Decimal,\n _metadata?: CreditMetadata | null,\n _idempotencyKey?: string | null,\n ): Promise<TeamDeductionResult> {\n throw new CapabilityNotSupportedError(\"deductTeam is not supported by this store\");\n }\n}\n"]}
|
|
@@ -3,7 +3,7 @@ export type BillingMode = "strict" | "overdraft";
|
|
|
3
3
|
export interface CreditMetadata {
|
|
4
4
|
operation?: string | null;
|
|
5
5
|
measures?: Record<string, unknown> | null;
|
|
6
|
-
dimensions?: Record<string, string> | null;
|
|
6
|
+
dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;
|
|
7
7
|
breakdownTotal?: string | null;
|
|
8
8
|
referenceType?: string | null;
|
|
9
9
|
referenceId?: string | null;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account.d.ts","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,MAAM,MAAM,WAAW,GAAG,QAAQ,GAAG,WAAW,CAAC;AAEjD,MAAM,WAAW,cAAc;IAC7B,SAAS,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IAC1B,QAAQ,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IAC1C,UAAU,C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IAAI,CAAC;IAC5C,QAAQ,CAAC,EAAE,cAAc,GAAG,IAAI,CAAC;CAClC;AAED,MAAM,WAAW,YAAY;IAC3B,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,OAAO,CAAC;IAChB,UAAU,EAAE,OAAO,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAClD;AAED,MAAM,WAAW,WAAW;IAC1B,YAAY,EAAE,MAAM,CAAC;IACrB,aAAa,EAAE,OAAO,CAAC;IACvB,MAAM,EAAE,OAAO,CAAC;IAChB,eAAe,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;CAClD"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"account.js","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"account.js","sourceRoot":"","sources":["../../../src/credits/types/account.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport type BillingMode = \"strict\" | \"overdraft\";\n\nexport interface CreditMetadata {\n operation?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, string | number | boolean | Decimal.Value> | null;\n breakdownTotal?: string | null;\n referenceType?: string | null;\n referenceId?: string | null;\n idempotencyKey?: string | null;\n [key: string]: unknown;\n}\n\nexport interface BucketDefinition {\n label: string;\n priority: number;\n expires: boolean;\n ttlDays?: number | null;\n allowOverdraft?: boolean;\n default?: boolean;\n}\n\nexport interface BucketBalance {\n bucketKey: string;\n label: string;\n priority: number;\n expires: boolean;\n balance: Decimal;\n}\n\nexport interface BucketBalancesResult {\n userId: string;\n buckets: BucketBalance[];\n totalBalance: Decimal;\n}\n\nexport interface BalanceResult {\n userId: string;\n balance: Decimal;\n lifetimePurchased: Decimal;\n}\n\nexport interface AddCreditsResult {\n entryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n lifetimePurchased: Decimal;\n bucket: string;\n idempotent: boolean;\n}\n\nexport interface DeductionResult {\n entryId: string;\n userId: string;\n amount: Decimal;\n allowanceConsumed: Decimal;\n balanceAfter: Decimal;\n idempotent: boolean;\n error?: string | null;\n bucketBreakdown?: Record<string, Decimal> | null;\n}\n\nexport interface DeductWithAllowanceOptions {\n idempotencyKey?: string | null;\n operation?: string | null;\n feature?: string | null;\n model?: string | null;\n region?: string | null;\n measures?: Record<string, unknown> | null;\n dimensions?: Record<string, unknown> | null;\n metadata?: CreditMetadata | null;\n}\n\nexport interface RefundResult {\n refundEntryId: string;\n originalEntryId: string;\n userId: string;\n amount: Decimal;\n newBalance: Decimal;\n error?: string | null;\n bucketBreakdown?: Record<string, Decimal> | null;\n}\n\nexport interface SweepResult {\n expiredCount: number;\n expiredAmount: Decimal;\n dryRun: boolean;\n expiredByBucket?: Record<string, Decimal> | null;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"admission.js","sourceRoot":"","sources":["../../../src/credits/types/admission.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"admission.js","sourceRoot":"","sources":["../../../src/credits/types/admission.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { BillingMode } from \"./account.js\";\n\nexport interface LeaseResult {\n leaseId: string;\n userId: string;\n amount: Decimal;\n available: Decimal;\n reservedTotal: Decimal;\n minimumBalance: Decimal;\n billingMode: BillingMode;\n expiresAt: string;\n error?: string | null;\n}\n\n/** Immutable pricing references captured when an operation lease is admitted. */\nexport interface LeasePricingContext {\n catalogVersion: number;\n planId: string | null;\n planKey: string | null;\n rateCard: string | null;\n}\n\nexport interface ReleaseResult {\n leaseId: string;\n userId: string;\n released: boolean;\n reason?: string | null;\n}\n\nexport interface CanAffordResult {\n affordable: boolean;\n spendable: Decimal;\n worstCase: Decimal;\n reason?: string | null;\n}\n\nexport interface AvailableResult {\n userId: string;\n balance: Decimal;\n reserved: Decimal;\n available: Decimal;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../src/credits/types/analytics.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"analytics.js","sourceRoot":"","sources":["../../../src/credits/types/analytics.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { ListUsageChargesOptions, UsageChargePage } from \"./ledger.js\";\n\n// ── Usage analytics ─────────────────────────────────────────────────\n/** Aggregated spend for a single user in a time window. */\nexport interface SpendByUserRow {\n userId: string;\n totalSpend: Decimal;\n entryCount: number;\n}\n\n/** Aggregated spend for a single model in a time window. */\nexport interface SpendByModelRow {\n model: string;\n totalSpend: Decimal;\n entryCount: number;\n}\n\n/** Top-spending user in a time window. */\nexport interface TopUserRow {\n userId: string;\n totalSpend: Decimal;\n}\n\n/** Daily spend aggregation in a time window. */\nexport interface DailySpendRow {\n date: string;\n totalSpend: Decimal;\n entryCount: number;\n}\n\n/** Aggregate statistics across all users in a time window. */\nexport interface AggregateStats {\n totalCreditsConsumed: Decimal;\n activeUsers: number;\n avgDailySpend: Decimal;\n topModel: string;\n topUser: string;\n}\n\n/**\n * Read-only usage analytics backend.\n *\n * PostgreSQL implements this contract by default. High-volume deployments can\n * provide a ClickHouse implementation without moving balances or compact\n * accounting receipts out of PostgreSQL.\n */\nexport interface UsageAnalyticsStore {\n spendByUser(start: Date, end: Date): Promise<SpendByUserRow[]>;\n spendByModel(start: Date, end: Date): Promise<SpendByModelRow[]>;\n topUsers(limit: number, start: Date, end: Date): Promise<TopUserRow[]>;\n dailySpend(start: Date, end: Date): Promise<DailySpendRow[]>;\n aggregateStats(start: Date, end: Date): Promise<AggregateStats>;\n}\n\n/** Read-only usage history backend selected with the analytics backend. */\nexport interface UsageChargeStore {\n listUsageCharges(userId: string, options?: ListUsageChargesOptions): Promise<UsageChargePage>;\n}\n"]}
|
|
@@ -13,6 +13,8 @@ export interface BursarConfigHistoryItem {
|
|
|
13
13
|
}
|
|
14
14
|
export interface PlanAllowancePolicy {
|
|
15
15
|
amount: Decimal | null;
|
|
16
|
+
/** Shared with bucket priorities; null means legacy allowance-first ordering. */
|
|
17
|
+
priority?: number | null;
|
|
16
18
|
resetUnit: string | null;
|
|
17
19
|
resetCount: number | null;
|
|
18
20
|
resetAnchor: string | null;
|
|
@@ -50,7 +52,7 @@ export interface GetUserPlanResult {
|
|
|
50
52
|
planAssignedAt?: Date | null;
|
|
51
53
|
assignmentSourceType?: string | null;
|
|
52
54
|
assignmentSourceId?: string | null;
|
|
53
|
-
|
|
55
|
+
catalogRevisionPinned: boolean;
|
|
54
56
|
catalogVersion?: number | null;
|
|
55
57
|
}
|
|
56
58
|
export interface SetUserPlanResult {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.d.ts","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAE1C,MAAM,WAAW,kBAAkB;IACjC,EAAE,EAAE,MAAM,CAAC;IACX,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,uBAAuB;IACtC,EAAE,EAAE,MAAM,CAAC;IACX,OAAO,EAAE,MAAM,CAAC;IAChB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,mBAAmB;IAClC,MAAM,EAAE,OAAO,GAAG,IAAI,CAAC;IACvB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,UA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CACnB;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,SAAS,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,SAAS,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACtC,YAAY,EAAE,MAAM,CAAC,MAAM,EAAE;QAAE,KAAK,EAAE,OAAO,CAAA;KAAE,CAAC,CAAC;IACjD,QAAQ,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACzB,YAAY,EAAE,gBAAgB,GAAG,IAAI,CAAC;IACtC,SAAS,EAAE,mBAAmB,GAAG,IAAI,CAAC;IACtC,iBAAiB,EAAE,MAAM,EAAE,CAAC;IAC5B,cAAc,CAAC,EAAE,IAAI,GAAG,IAAI,CAAC;IAC7B,oBAAoB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrC,kBAAkB,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACnC,qBAAqB,EAAE,OAAO,CAAC;IAC/B,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,MAAM,WAAW,iBAAiB;IAChC,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,cAAc,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAChC;AAED,MAAM,WAAW,wBAAwB;IACvC,WAAW,EAAE,MAAM,CAAC;CACrB;AAED,MAAM,WAAW,wBAAwB;IACvC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,OAAO,CAAC;IACd,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"catalog.js","sourceRoot":"","sources":["../../../src/credits/types/catalog.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport interface BursarConfigResult {\n id: string;\n config: Record<string, unknown>;\n version: number;\n}\n\nexport interface BursarConfigHistoryItem {\n id: string;\n version: number;\n label: string | null;\n active: boolean;\n createdAt: string;\n}\n\nexport interface PlanAllowancePolicy {\n amount: Decimal | null;\n /** Shared with bucket priorities; null means legacy allowance-first ordering. */\n priority?: number | null;\n resetUnit: string | null;\n resetCount: number | null;\n resetAnchor: string | null;\n resetTimezone: string | null;\n}\n\nexport interface PlanCreditPolicy {\n type: \"prepaid\" | \"credit_line\";\n creditLimit: Decimal | null;\n}\n\nexport interface PlanAdmissionPolicy {\n maxInFlight: number | null;\n operations: Record<string, { maxInFlight: number | null }>;\n}\n\nexport interface AllowanceResult {\n planId: string;\n allowanceRemaining: Decimal;\n periodStart: string;\n periodEnd: string;\n}\n\nexport interface GetUserPlanResult {\n userId: string;\n planId: string | null;\n planKey: string | null;\n planLabel: string | null;\n allowance: PlanAllowancePolicy | null;\n entitlements: Record<string, { value: unknown }>;\n rateCard?: string | null;\n creditPolicy: PlanCreditPolicy | null;\n admission: PlanAdmissionPolicy | null;\n allowedOperations: string[];\n planAssignedAt?: Date | null;\n assignmentSourceType?: string | null;\n assignmentSourceId?: string | null;\n catalogRevisionPinned: boolean;\n catalogVersion?: number | null;\n}\n\nexport interface SetUserPlanResult {\n userId: string;\n planId: string;\n planAssignedAt?: string | null;\n}\n\nexport interface PlanMigrationStartResult {\n migrationId: string;\n}\n\nexport interface PlanMigrationBatchResult {\n migrated: number;\n done: boolean;\n nextCursor: string | null;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"grants.js","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"grants.js","sourceRoot":"","sources":["../../../src/credits/types/grants.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\nimport type { CreditMetadata } from \"./account.js\";\n\nexport type GrantProgramTrigger =\n \"account_created\" | \"referral_completed\" | \"promo_code_redeemed\" | \"manual\";\n\n/** One application event that may award one or more catalog grants. */\nexport interface ExecuteGrantProgramRequest {\n trigger: GrantProgramTrigger;\n programKey: string;\n subjectId: string;\n eventKey: string;\n referrerSubjectId?: string | null;\n region?: string | null;\n metadata?: CreditMetadata | null;\n}\n\n/** One award row produced by a grant-program execution. */\nexport interface GrantProgramAwardResult {\n grantEventId: string | null;\n grantAwardId: string | null;\n recipientSubjectId: string | null;\n ledgerEntryId: string | null;\n amount: Decimal;\n replayed: boolean;\n error?: string | null;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/credits/types/index.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../src/credits/types/index.ts"],"names":[],"mappings":"","sourcesContent":["export type * from \"./account.js\";\nexport type * from \"./catalog.js\";\nexport type * from \"./admission.js\";\nexport type * from \"./quotas.js\";\nexport type * from \"./ledger.js\";\nexport type * from \"./analytics.js\";\nexport type * from \"./teams.js\";\nexport type * from \"./grants.js\";\n"]}
|
|
@@ -45,6 +45,7 @@ export interface UsageCharge {
|
|
|
45
45
|
charged: Decimal;
|
|
46
46
|
allowanceRequested: Decimal;
|
|
47
47
|
allowanceCovered: Decimal;
|
|
48
|
+
billingDisposition: "billable" | "record_only";
|
|
48
49
|
feature: string | null;
|
|
49
50
|
model: string | null;
|
|
50
51
|
region: string | null;
|
|
@@ -62,11 +63,20 @@ export interface ListUsageChargesOptions {
|
|
|
62
63
|
toDate?: Date;
|
|
63
64
|
limit?: number;
|
|
64
65
|
cursor?: UsageChargeCursor | null;
|
|
66
|
+
includeRecordOnly?: boolean;
|
|
65
67
|
}
|
|
66
68
|
export interface UsageChargePage {
|
|
67
69
|
items: UsageCharge[];
|
|
68
70
|
nextCursor: UsageChargeCursor | null;
|
|
69
71
|
}
|
|
72
|
+
/** Result of appending a usage event without creating another balance debit. */
|
|
73
|
+
export interface UsageRecordResult {
|
|
74
|
+
usageId: string;
|
|
75
|
+
userId: string;
|
|
76
|
+
requested: Decimal;
|
|
77
|
+
idempotent: boolean;
|
|
78
|
+
error?: string | null;
|
|
79
|
+
}
|
|
70
80
|
/** Cursor-only options for the usage-only ledger view. */
|
|
71
81
|
export interface ListUsageEntriesOptions {
|
|
72
82
|
fromDate?: Date;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger.d.ts","sourceRoot":"","sources":["../../../src/credits/types/ledger.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAE,MAAM,YAAY,CAAC;AAI1C,kEAAkE;AAClE,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,WAAW,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3B,MAAM,EAAE,OAAO,CAAC;IAChB,SAAS,EAAE,MAAM,CAAC;IAClB,SAAS,EAAE,MAAM,CAAC;IAClB,gBAAgB,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACzC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,4CAA4C;AAC5C,MAAM,WAAW,YAAY;IAC3B,SAAS,EAAE,MAAM,CAAC;IAClB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,8DAA8D;AAC9D,MAAM,WAAW,wBAAwB;IACvC,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;IACtB,QAAQ,CAAC,EAAE,IAAI,CAAC;IAChB,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI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AM,CAAC;IAChB,cAAc,EAAE,MAAM,CAAC;IACvB,QAAQ,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAAC;IACzC,SAAS,EAAE,MAAM,CAAC;CACnB;AAED,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,OAAO,EAAE,MAAM,CAAC;CACjB;AAED,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,EAAE,IAAI,CAAC;IAChB,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,iBAAiB,GAAG,IAAI,CAAC;IAClC,iBAAiB,CAAC,EAAE,OAAO,CAAC;CAC7B;AAED,MAAM,WAAW,eAAe;IAC9B,KAAK,EAAE,WAAW,EAAE,CAAC;IACrB,UAAU,EAAE,iBAAiB,GAAG,IAAI,CAAC;CACtC;AAED,gFAAgF;AAChF,MAAM,WAAW,iBAAiB;IAChC,OAAO,EAAE,MAAM,CAAC;IAChB,MAAM,EAAE,MAAM,CAAC;IACf,SAAS,EAAE,OAAO,CAAC;IACnB,UAAU,EAAE,OAAO,CAAC;IACpB,KAAK,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACvB;AAED,0DAA0D;AAC1D,MAAM,WAAW,uBAAuB;IACtC,QAAQ,CAAC,EAAE,IAAI,CAAC;IAChB,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,MAAM,CAAC,EAAE,YAAY,GAAG,IAAI,CAAC;CAC9B"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ledger.js","sourceRoot":"","sources":["../../../src/credits/types/ledger.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"ledger.js","sourceRoot":"","sources":["../../../src/credits/types/ledger.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\n// ── Canonical ledger history ─────────────────────────────────────────\n\n/** One immutable monetary entry on a canonical credit account. */\nexport interface LedgerEntry {\n entryId: string;\n accountId: string;\n actorUserId: string | null;\n amount: Decimal;\n entryType: string;\n operation: string;\n referenceEntryId: string | null;\n idempotencyKey: string | null;\n metadata: Record<string, unknown> | null;\n createdAt: string;\n}\n\n/** Stable position in an account ledger. */\nexport interface LedgerCursor {\n createdAt: string;\n entryId: string;\n}\n\n/** Cursor-only options for listing account ledger entries. */\nexport interface ListLedgerEntriesOptions {\n entryTypes?: string[];\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: LedgerCursor | null;\n}\n\n/** One stable cursor page. */\nexport interface LedgerPage {\n items: LedgerEntry[];\n nextCursor: LedgerCursor | null;\n}\n\n/**\n * A metered usage charge from the usage charge journal.\n *\n * Usage charges are deliberately separate from ledger entries: included\n * allowance consumption does not create a monetary ledger debit, but it is\n * still a billable usage event that belongs in the usage history.\n */\nexport interface UsageCharge {\n usageId: string;\n accountId: string;\n operation: string;\n requested: Decimal;\n charged: Decimal;\n allowanceRequested: Decimal;\n allowanceCovered: Decimal;\n billingDisposition: \"billable\" | \"record_only\";\n feature: string | null;\n model: string | null;\n region: string | null;\n eventAt: string;\n idempotencyKey: string;\n metadata: Record<string, unknown> | null;\n createdAt: string;\n}\n\nexport interface UsageChargeCursor {\n eventAt: string;\n usageId: string;\n}\n\nexport interface ListUsageChargesOptions {\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: UsageChargeCursor | null;\n includeRecordOnly?: boolean;\n}\n\nexport interface UsageChargePage {\n items: UsageCharge[];\n nextCursor: UsageChargeCursor | null;\n}\n\n/** Result of appending a usage event without creating another balance debit. */\nexport interface UsageRecordResult {\n usageId: string;\n userId: string;\n requested: Decimal;\n idempotent: boolean;\n error?: string | null;\n}\n\n/** Cursor-only options for the usage-only ledger view. */\nexport interface ListUsageEntriesOptions {\n fromDate?: Date;\n toDate?: Date;\n limit?: number;\n cursor?: LedgerCursor | null;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"quotas.js","sourceRoot":"","sources":["../../../src/credits/types/quotas.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"quotas.js","sourceRoot":"","sources":["../../../src/credits/types/quotas.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\nexport interface CheckFeatureResult {\n userId: string;\n feature: string;\n value: unknown;\n hasFeature: boolean;\n}\n\nexport interface QuotaState {\n userId: string;\n quotaKey: string;\n operation: string;\n measure: string;\n limit: Decimal;\n consumed: Decimal;\n reserved: Decimal;\n remaining: Decimal;\n overage: Decimal;\n enforcement: \"block\" | \"allow\";\n windowStart: string;\n windowEnd: string;\n emitAtPercent: number[];\n}\n\nexport interface QuotaEvent {\n eventId: string;\n quotaKey: string;\n operation: string;\n measure: string;\n eventType: \"threshold\" | \"blocked\";\n thresholdPercent: number | null;\n idempotencyKey: string;\n usageChargeId: string | null;\n createdAt: string;\n}\n\nexport interface ListQuotaEventsOptions {\n after?: Date | null;\n afterId?: string | null;\n limit?: number;\n idempotencyKey?: string | null;\n}\n"]}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"teams.js","sourceRoot":"","sources":["../../../src/credits/types/teams.ts"],"names":[],"mappings":""}
|
|
1
|
+
{"version":3,"file":"teams.js","sourceRoot":"","sources":["../../../src/credits/types/teams.ts"],"names":[],"mappings":"","sourcesContent":["import type { Decimal } from \"decimal.js\";\n\n// ── Team/shared balance pools ─────────────────────────────────────────\n/** A team with a shared credit balance pool. */\nexport interface Team {\n id: string;\n name: string;\n balance: Decimal;\n memberCount: number;\n createdAt: string;\n}\n\n/** A member of a team, with optional spend cap. */\nexport interface TeamMember {\n userId: string;\n role: string;\n spendCap?: Decimal | null;\n totalSpent: Decimal;\n}\n\n/** Result of fetching team balance. */\nexport interface TeamBalanceResult {\n teamId: string;\n name: string;\n balance: Decimal;\n memberCount: number;\n}\n\n/** Result of creating a team. */\nexport interface CreateTeamResult {\n teamId: string;\n name: string;\n}\n\n/** Result of adding a team member. */\nexport interface AddTeamMemberResult {\n teamId: string;\n userId: string;\n role: string;\n}\n\n/** Result of deducting credits from a team pool. */\nexport interface TeamDeductionResult {\n entryId: string;\n teamId: string;\n userId: string;\n amount: Decimal;\n teamBalanceAfter: Decimal;\n error?: string | null;\n}\n"]}
|