Skip to main content

Abstract Class: CreditStore

Defined in: javascript/src/stores/credit-store.ts:99

Abstract base for credit storage backends (WS8).

Split into two tiers:

  • Core (abstract, must be implemented): balance/credit ops, the atomic lease lifecycle, pricing-config versioning, plan management, spend caps, refunds, and expiry sweeping. Every backend needs these.
  • Optional capabilities (concrete, default-throwing): usage analytics, transaction listing, and shared team-balance pools. A custom store that doesn't need these can skip them entirely — the default implementation throws CapabilityNotSupportedError instead of forcing a stub.

Extended by

Constructors

Constructor

new CreditStore(): CreditStore

Returns

CreditStore

Methods

activatePricing()

abstract activatePricing(version): Promise<string>

Defined in: javascript/src/stores/credit-store.ts:200

Parameters

version

number

Returns

Promise<string>


addCredits()

abstract addCredits(userId, amount, type?, metadata?, expiresAt?, tier?, idempotencyKey?): Promise<AddCreditsResult>

Defined in: javascript/src/stores/credit-store.ts:102

Parameters

userId

string

amount

Decimal

type?

string

metadata?

CreditMetadata | null

expiresAt?

Date | null

tier?

string | null

Target credit tier (credit tiers); omitted/null resolves to the config's default tier.

idempotencyKey?

string | null

Replay-safe idempotency key (parity with the deduct/settle/refund idempotency idiom). When a prior grant for this userId carries the same key, the prior result is returned unchanged and no new credits are granted.

Returns

Promise<AddCreditsResult>


addTeamMember()

addTeamMember(_teamId, _userId, _role?, _spendCap?): Promise<AddTeamMemberResult>

Defined in: javascript/src/stores/credit-store.ts:302

Parameters

_teamId

string

_userId

string

_role?

string

_spendCap?

Decimal | null

Returns

Promise<AddTeamMemberResult>


aggregateStats()

aggregateStats(_start, _end): Promise<AggregateStats>

Defined in: javascript/src/stores/credit-store.ts:279

Parameters

_start

Date

_end

Date

Returns

Promise<AggregateStats>


checkAllowance()

abstract checkAllowance(userId, periodStart?): Promise<AllowanceResult>

Defined in: javascript/src/stores/credit-store.ts:209

Parameters

userId

string

periodStart?

Date | null

Returns

Promise<AllowanceResult>


checkFeature()

abstract checkFeature(userId, feature): Promise<CheckFeatureResult>

Defined in: javascript/src/stores/credit-store.ts:205

Parameters

userId

string

feature

string

Returns

Promise<CheckFeatureResult>


checkFeatureLimit()

abstract checkFeatureLimit(userId, feature, maxCalls, periodStart, periodEnd): Promise<FeatureLimitResult>

Defined in: javascript/src/stores/credit-store.ts:222

Advisory, non-locking read of invocation-count usage (UI only).

Mirrors checkSpendCap/checkAllowance: the caller (the manager) has already resolved the FeatureLimit from the user's plan and the calendar window via resolveCalendarWindow — this method only counts. Counting is ledger-derived (see deductWithAllowance): the number of committed usage transactions with metadata.feature === feature in [periodStart, periodEnd). Never used for admission control.

Parameters

userId

string

feature

string

maxCalls

number

periodStart

Date

periodEnd

Date

Returns

Promise<FeatureLimitResult>


checkSpendCap()

abstract checkSpendCap(userId, model?, amount?): Promise<CapCheckResult>

Defined in: javascript/src/stores/credit-store.ts:231

Parameters

userId

string

model?

string | null

amount?

Decimal

Returns

Promise<CapCheckResult>


createLease()

abstract createLease(userId, amount, operationType, options?): Promise<LeaseResult>

Defined in: javascript/src/stores/credit-store.ts:147

Atomically acquire a lease (hold) — the only admission control (D4).

Under one critical section the store: (1) ensures the balance row exists; (2) enforces maxConcurrent by counting active leases for (userId, operationType); (3) enforces deny spend caps for amount; (4) computes available = balance − Σ active holds and rejects with error="insufficient_credits" if available − amount < floor; (5) inserts an active lease expiring after ttlSeconds. Business failures are returned via LeaseResult.error; the store never raises domain exceptions.

Parameters

userId

string

amount

Decimal

operationType

string

options?

CreateLeaseOptions

Returns

Promise<LeaseResult>


createTeam()

createTeam(_name, _initialBalance?): Promise<CreateTeamResult>

Defined in: javascript/src/stores/credit-store.ts:296

Parameters

_name

string

_initialBalance?

Decimal

Returns

Promise<CreateTeamResult>


dailySpend()

dailySpend(_start, _end): Promise<DailySpendRow[]>

Defined in: javascript/src/stores/credit-store.ts:276

Parameters

_start

Date

_end

Date

Returns

Promise<DailySpendRow[]>


deductTeam()

deductTeam(_teamId, _userId, _amount, _metadata?, _idempotencyKey?): Promise<TeamDeductionResult>

Defined in: javascript/src/stores/credit-store.ts:313

Parameters

_teamId

string

_userId

string

_amount

Decimal

_metadata?

CreditMetadata | null

_idempotencyKey?

string | null

Returns

Promise<TeamDeductionResult>


deductWithAllowance()

abstract deductWithAllowance(userId, amount, options?): Promise<DeductionResult>

Defined in: javascript/src/stores/credit-store.ts:122

Atomically calculate-and-charge in one server-side transaction: consume free allowance, enforce spend caps, apply the balance floor, and debit the net amount — idempotency-keyed end-to-end. See contract §2.

Parameters

userId

string

amount

Decimal

options?

DeductWithAllowanceOptions

Returns

Promise<DeductionResult>


getActivePricing()

abstract getActivePricing(): Promise<PricingConfigResult | null>

Defined in: javascript/src/stores/credit-store.ts:194

Returns

Promise<PricingConfigResult | null>


getAvailable()

abstract getAvailable(userId): Promise<AvailableResult>

Defined in: javascript/src/stores/credit-store.ts:192

Advisory, non-locking read of available = balance − Σ active holds.

For UI only — never an admission gate (D4/H3); may be stale the instant read.

Parameters

userId

string

Returns

Promise<AvailableResult>


getBalance()

abstract getBalance(userId): Promise<BalanceResult>

Defined in: javascript/src/stores/credit-store.ts:101

Parameters

userId

string

Returns

Promise<BalanceResult>


getCreditTiers()

abstract getCreditTiers(userId): Promise<TierBalancesResult>

Defined in: javascript/src/stores/credit-store.ts:264

Per-tier credit balances for a user (credit tiers).

Sorted by priority ascending. When no tiers are configured, synthesizes a single "default" entry from the aggregate balance so the shape is uniform either way.

Parameters

userId

string

Returns

Promise<TierBalancesResult>


getPricingConfig()

abstract getPricingConfig(version): Promise<PricingConfigResult | null>

Defined in: javascript/src/stores/credit-store.ts:199

Parameters

version

number

Returns

Promise<PricingConfigResult | null>


getPricingHistory()

abstract getPricingHistory(): Promise<PricingConfigHistoryItem[]>

Defined in: javascript/src/stores/credit-store.ts:198

Returns

Promise<PricingConfigHistoryItem[]>


getTeamBalance()

getTeamBalance(_teamId): Promise<TeamBalanceResult>

Defined in: javascript/src/stores/credit-store.ts:299

Parameters

_teamId

string

Returns

Promise<TeamBalanceResult>


getTeamMembers()

getTeamMembers(_teamId): Promise<TeamMember[]>

Defined in: javascript/src/stores/credit-store.ts:310

Parameters

_teamId

string

Returns

Promise<TeamMember[]>


getUserPlan()

abstract getUserPlan(userId): Promise<GetUserPlanResult>

Defined in: javascript/src/stores/credit-store.ts:203

Parameters

userId

string

Returns

Promise<GetUserPlanResult>


incrementUsageWindow()

abstract incrementUsageWindow(userId, planId, amount): Promise<void>

Defined in: javascript/src/stores/credit-store.ts:210

Parameters

userId

string

planId

string

amount

Decimal

Returns

Promise<void>


listUsageEvents()

abstract listUsageEvents(userId, options?): Promise<PaginatedTransactions>

Defined in: javascript/src/stores/credit-store.ts:290

Parameters

userId

string

options?

ListUsageEventsOptions

Returns

Promise<PaginatedTransactions>


listUserTransactions()

listUserTransactions(_userId, _options?): Promise<PaginatedTransactions>

Defined in: javascript/src/stores/credit-store.ts:284

Parameters

_userId

string

_options?

ListTransactionsOptions

Returns

Promise<PaginatedTransactions>


refundCredits()

abstract refundCredits(transactionId, amount?, reason?, metadata?): Promise<RefundResult>

Defined in: javascript/src/stores/credit-store.ts:238

Parameters

transactionId

string

amount?

Decimal

reason?

string

metadata?

CreditMetadata | null

Returns

Promise<RefundResult>


releaseLease()

abstract releaseLease(userId, leaseId): Promise<ReleaseResult>

Defined in: javascript/src/stores/credit-store.ts:177

Release a lease without charging (work failed/aborted) — idempotent (H1).

Transitions an active/expired lease to released and reports released=true; otherwise reports released=false with a reason.

Parameters

userId

string

leaseId

string

Returns

Promise<ReleaseResult>


renewLease()

abstract renewLease(userId, leaseId, ttlSeconds): Promise<LeaseResult>

Defined in: javascript/src/stores/credit-store.ts:185

Extend an active lease's TTL (long batch/agentic jobs, resolves B4).

Returns error="lease_expired" if the TTL already elapsed and error="lease_not_found" if missing/other-user/finalized.

Parameters

userId

string

leaseId

string

ttlSeconds

number

Returns

Promise<LeaseResult>


setActivePricing()

abstract setActivePricing(config, label?): Promise<string>

Defined in: javascript/src/stores/credit-store.ts:195

Parameters

config

PricingConfigData

label?

string | null

Returns

Promise<string>


settleLease()

abstract settleLease(userId, leaseId, amount, options?): Promise<DeductionResult>

Defined in: javascript/src/stores/credit-store.ts:164

Charge the actual cost against a lease, then mark it settled (D5).

De-clamped: charges amount even if it exceeds the lease hold (overdraft), and never clamps to the reserved ceiling. Spend caps are advisory at settle (a breach sets capWarning but never blocks); no floor block, so the balance may go negative in overdraft. amount === 0 releases the lease without charging. Lease-state failures (lease_not_found/lease_expired) are returned via DeductionResult.error; a replay returns the original result idempotently.

Parameters

userId

string

leaseId

string

amount

Decimal

options?

SettleLeaseOptions

Returns

Promise<DeductionResult>


setup()

abstract setup(databaseUrl?): Promise<SetupResult>

Defined in: javascript/src/stores/credit-store.ts:100

Parameters

databaseUrl?

string | null

Returns

Promise<SetupResult>


setUserPlan()

abstract setUserPlan(userId, planId): Promise<SetUserPlanResult>

Defined in: javascript/src/stores/credit-store.ts:204

Parameters

userId

string

planId

string

Returns

Promise<SetUserPlanResult>


spendByModel()

spendByModel(_start, _end): Promise<SpendByModelRow[]>

Defined in: javascript/src/stores/credit-store.ts:270

Parameters

_start

Date

_end

Date

Returns

Promise<SpendByModelRow[]>


spendByUser()

spendByUser(_start, _end): Promise<SpendByUserRow[]>

Defined in: javascript/src/stores/credit-store.ts:267

Parameters

_start

Date

_end

Date

Returns

Promise<SpendByUserRow[]>


sweepExpiredCredits()

abstract sweepExpiredCredits(dryRun?, userId?): Promise<SweepResult>

Defined in: javascript/src/stores/credit-store.ts:254

Sweep expired credit grants and debit the aggregate/tier balances.

When userId is omitted (default), sweeps globally across every user — unchanged behaviour/output shape from before this parameter existed. When given, restricts the scan/expiry to that user's transactions only (used by CreditManager's lazy-on-read expiry, options.lazyExpiry).

Parameters

dryRun?

boolean

userId?

string

Returns

Promise<SweepResult>


topUsers()

topUsers(_limit, _start, _end): Promise<TopUserRow[]>

Defined in: javascript/src/stores/credit-store.ts:273

Parameters

_limit

number

_start

Date

_end

Date

Returns

Promise<TopUserRow[]>