@digilogiclabs/platform-core 1.27.1 → 1.28.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/dist/index.js CHANGED
@@ -7273,11 +7273,14 @@ __export(src_exports, {
7273
7273
  CommonRateLimits: () => CommonRateLimits,
7274
7274
  ConsoleEmail: () => ConsoleEmail,
7275
7275
  ConsoleLogger: () => ConsoleLogger,
7276
+ CreditIdempotencyConflictError: () => CreditIdempotencyConflictError,
7277
+ CreditReservationStateError: () => CreditReservationStateError,
7276
7278
  CronPresets: () => CronPresets,
7277
7279
  CryptoConfigSchema: () => CryptoConfigSchema,
7278
7280
  DEFAULT_AGENT_LOOP_OPTIONS: () => DEFAULT_AGENT_LOOP_OPTIONS,
7279
7281
  DEFAULT_BULKHEAD_OPTIONS: () => DEFAULT_BULKHEAD_OPTIONS,
7280
7282
  DEFAULT_CIRCUIT_BREAKER_OPTIONS: () => DEFAULT_CIRCUIT_BREAKER_OPTIONS,
7283
+ DEFAULT_RESERVATION_SECONDS: () => DEFAULT_RESERVATION_SECONDS,
7281
7284
  DEFAULT_RETRY_OPTIONS: () => DEFAULT_RETRY_OPTIONS,
7282
7285
  DatabaseAIUsage: () => DatabaseAIUsage,
7283
7286
  DatabaseAuditLog: () => DatabaseAuditLog,
@@ -7299,10 +7302,12 @@ __export(src_exports, {
7299
7302
  GoogleAIAdapter: () => GoogleAIAdapter,
7300
7303
  HTML_TAG_PATTERN: () => HTML_TAG_PATTERN,
7301
7304
  HttpWebhook: () => HttpWebhook,
7305
+ InsufficientCreditsError: () => InsufficientCreditsError,
7302
7306
  KEYCLOAK_DEFAULT_ROLES: () => KEYCLOAK_DEFAULT_ROLES,
7303
7307
  LogLevelSchema: () => LogLevelSchema,
7304
7308
  LoggingConfigSchema: () => LoggingConfigSchema,
7305
7309
  LoginSchema: () => LoginSchema,
7310
+ MAX_LIST_ENTRIES: () => MAX_LIST_ENTRIES,
7306
7311
  MemoryAI: () => MemoryAI,
7307
7312
  MemoryAIUsage: () => MemoryAIUsage,
7308
7313
  MemoryAuditLog: () => MemoryAuditLog,
@@ -7312,6 +7317,7 @@ __export(src_exports, {
7312
7317
  MemoryBilling: () => MemoryBilling,
7313
7318
  MemoryCache: () => MemoryCache,
7314
7319
  MemoryCompliance: () => MemoryCompliance,
7320
+ MemoryCreditLedger: () => MemoryCreditLedger,
7315
7321
  MemoryCrypto: () => MemoryCrypto,
7316
7322
  MemoryDatabase: () => MemoryDatabase,
7317
7323
  MemoryDevPortal: () => MemoryDevPortal,
@@ -7351,6 +7357,7 @@ __export(src_exports, {
7351
7357
  PineconeRAG: () => PineconeRAG,
7352
7358
  PlatformConfigSchema: () => PlatformConfigSchema,
7353
7359
  PostgresBeta: () => PostgresBeta,
7360
+ PostgresCreditLedger: () => PostgresCreditLedger,
7354
7361
  PostgresDatabase: () => PostgresDatabase,
7355
7362
  PostgresTenant: () => PostgresTenant,
7356
7363
  QueueConfigSchema: () => QueueConfigSchema,
@@ -7392,6 +7399,8 @@ __export(src_exports, {
7392
7399
  WeaviateRAG: () => WeaviateRAG,
7393
7400
  WebhookEventTypes: () => WebhookEventTypes,
7394
7401
  WrapperPresets: () => WrapperPresets,
7402
+ assertIdempotencyKey: () => assertIdempotencyKey,
7403
+ assertWholeCredits: () => assertWholeCredits,
7395
7404
  buildAllowlist: () => buildAllowlist,
7396
7405
  buildAuthCookies: () => buildAuthCookies,
7397
7406
  buildErrorBody: () => buildErrorBody,
@@ -7405,6 +7414,7 @@ __export(src_exports, {
7405
7414
  calculateRetryDelay: () => calculateRetryDelay,
7406
7415
  checkEnvVars: () => checkEnvVars,
7407
7416
  checkRateLimit: () => checkRateLimit,
7417
+ clampEntryLimit: () => clampEntryLimit,
7408
7418
  classifyError: () => classifyError,
7409
7419
  clearStoredBetaCode: () => clearStoredBetaCode,
7410
7420
  closeSharedRedis: () => closeSharedRedis,
@@ -7491,6 +7501,7 @@ __export(src_exports, {
7491
7501
  generateBetaCode: () => generateBetaCode,
7492
7502
  generateBetaId: () => generateBetaId,
7493
7503
  generateChecksum: () => generateChecksum,
7504
+ generateCreditId: () => generateCreditId,
7494
7505
  generateDeliveryId: () => generateDeliveryId,
7495
7506
  generateErrorId: () => generateErrorId,
7496
7507
  generateEventId: () => generateEventId,
@@ -7543,6 +7554,7 @@ __export(src_exports, {
7543
7554
  parseKeycloakRoles: () => parseKeycloakRoles,
7544
7555
  raceTimeout: () => raceTimeout,
7545
7556
  refreshKeycloakToken: () => refreshKeycloakToken,
7557
+ reservationSeconds: () => reservationSeconds,
7546
7558
  resetRateLimitForKey: () => resetRateLimitForKey,
7547
7559
  resolveIdentifier: () => resolveIdentifier,
7548
7560
  resolveRateLimitIdentifier: () => resolveRateLimitIdentifier,
@@ -14599,6 +14611,272 @@ var MemoryBeta = class {
14599
14611
  }
14600
14612
  };
14601
14613
 
14614
+ // src/interfaces/ICreditLedger.ts
14615
+ var InsufficientCreditsError = class extends Error {
14616
+ constructor(accountId, requested, available) {
14617
+ super(
14618
+ `Account ${accountId} has ${available} credits available; ${requested} requested`
14619
+ );
14620
+ this.accountId = accountId;
14621
+ this.requested = requested;
14622
+ this.available = available;
14623
+ this.name = "InsufficientCreditsError";
14624
+ }
14625
+ code = "INSUFFICIENT_CREDITS";
14626
+ };
14627
+ var CreditIdempotencyConflictError = class extends Error {
14628
+ constructor(idempotencyKey) {
14629
+ super(`Idempotency key ${idempotencyKey} was used for a different request`);
14630
+ this.idempotencyKey = idempotencyKey;
14631
+ this.name = "CreditIdempotencyConflictError";
14632
+ }
14633
+ code = "IDEMPOTENCY_CONFLICT";
14634
+ };
14635
+ var CreditReservationStateError = class extends Error {
14636
+ code = "RESERVATION_STATE";
14637
+ constructor(message) {
14638
+ super(message);
14639
+ this.name = "CreditReservationStateError";
14640
+ }
14641
+ };
14642
+ var DEFAULT_RESERVATION_SECONDS = 600;
14643
+ function assertWholeCredits(value, field) {
14644
+ if (!Number.isSafeInteger(value) || value <= 0) {
14645
+ throw new RangeError(`${field} must be a positive whole number of credits`);
14646
+ }
14647
+ }
14648
+ var RESERVED_KEY_PREFIXES = ["reserve:", "settle:", "release:"];
14649
+ function assertIdempotencyKey(key) {
14650
+ if (typeof key !== "string" || key.length === 0 || key.length > 200) {
14651
+ throw new RangeError("idempotencyKey must be 1-200 characters");
14652
+ }
14653
+ if (RESERVED_KEY_PREFIXES.some((prefix) => key.startsWith(prefix))) {
14654
+ throw new RangeError(
14655
+ `idempotencyKey cannot start with ${RESERVED_KEY_PREFIXES.join(", ")}`
14656
+ );
14657
+ }
14658
+ }
14659
+ function reservationSeconds(value) {
14660
+ const seconds = value ?? DEFAULT_RESERVATION_SECONDS;
14661
+ if (!Number.isSafeInteger(seconds) || seconds <= 0) {
14662
+ throw new RangeError("expiresInSeconds must be a positive whole number");
14663
+ }
14664
+ return seconds;
14665
+ }
14666
+ var MAX_LIST_ENTRIES = 500;
14667
+ function clampEntryLimit(limit) {
14668
+ return Math.min(Math.max(Math.trunc(limit ?? 50), 1), MAX_LIST_ENTRIES);
14669
+ }
14670
+ function generateCreditId(prefix) {
14671
+ const random = globalThis.crypto.randomUUID().replace(/-/g, "");
14672
+ return `${prefix}_${random}`;
14673
+ }
14674
+ var MemoryCreditLedger = class {
14675
+ accounts = /* @__PURE__ */ new Map();
14676
+ entries = [];
14677
+ entriesByKey = /* @__PURE__ */ new Map();
14678
+ reservations = /* @__PURE__ */ new Map();
14679
+ reservationsByKey = /* @__PURE__ */ new Map();
14680
+ async getBalance(accountId) {
14681
+ const account = this.accounts.get(accountId);
14682
+ return {
14683
+ accountId,
14684
+ available: account?.available ?? 0,
14685
+ reserved: account?.reserved ?? 0
14686
+ };
14687
+ }
14688
+ async grant(input) {
14689
+ assertWholeCredits(input.credits, "credits");
14690
+ assertIdempotencyKey(input.idempotencyKey);
14691
+ const existing = this.entriesByKey.get(input.idempotencyKey);
14692
+ if (existing) {
14693
+ if (existing.accountId !== input.accountId || existing.kind !== input.kind || existing.delta !== input.credits) {
14694
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
14695
+ }
14696
+ return { ...existing };
14697
+ }
14698
+ const account = this.account(input.accountId);
14699
+ account.available += input.credits;
14700
+ return this.record({
14701
+ accountId: input.accountId,
14702
+ kind: input.kind,
14703
+ delta: input.credits,
14704
+ consumed: 0,
14705
+ availableAfter: account.available,
14706
+ reservationId: null,
14707
+ reference: input.reference ?? null,
14708
+ idempotencyKey: input.idempotencyKey
14709
+ });
14710
+ }
14711
+ async reserve(input) {
14712
+ assertWholeCredits(input.credits, "credits");
14713
+ assertIdempotencyKey(input.idempotencyKey);
14714
+ const seconds = reservationSeconds(input.expiresInSeconds);
14715
+ const existing = this.reservationsByKey.get(input.idempotencyKey);
14716
+ if (existing) {
14717
+ if (existing.accountId !== input.accountId || existing.credits !== input.credits) {
14718
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
14719
+ }
14720
+ return { ...existing };
14721
+ }
14722
+ const account = this.accounts.get(input.accountId);
14723
+ const available = account?.available ?? 0;
14724
+ if (!account || available < input.credits) {
14725
+ throw new InsufficientCreditsError(
14726
+ input.accountId,
14727
+ input.credits,
14728
+ available
14729
+ );
14730
+ }
14731
+ account.available -= input.credits;
14732
+ account.reserved += input.credits;
14733
+ const now = /* @__PURE__ */ new Date();
14734
+ const reservation = {
14735
+ id: generateCreditId("cr"),
14736
+ accountId: input.accountId,
14737
+ credits: input.credits,
14738
+ status: "held",
14739
+ consumed: null,
14740
+ reference: input.reference ?? null,
14741
+ idempotencyKey: input.idempotencyKey,
14742
+ expiresAt: new Date(now.getTime() + seconds * 1e3),
14743
+ createdAt: now
14744
+ };
14745
+ this.reservations.set(reservation.id, reservation);
14746
+ this.reservationsByKey.set(reservation.idempotencyKey, reservation);
14747
+ this.record({
14748
+ accountId: input.accountId,
14749
+ kind: "reserve",
14750
+ delta: -input.credits,
14751
+ consumed: 0,
14752
+ availableAfter: account.available,
14753
+ reservationId: reservation.id,
14754
+ reference: reservation.reference,
14755
+ idempotencyKey: `reserve:${reservation.id}`
14756
+ });
14757
+ return { ...reservation };
14758
+ }
14759
+ async settle(reservationId, consumed) {
14760
+ if (!Number.isSafeInteger(consumed) || consumed < 0) {
14761
+ throw new RangeError("consumed must be a whole number of credits >= 0");
14762
+ }
14763
+ const reservation = this.reservations.get(reservationId);
14764
+ if (!reservation) {
14765
+ throw new CreditReservationStateError(
14766
+ `Reservation ${reservationId} not found`
14767
+ );
14768
+ }
14769
+ const key = `settle:${reservationId}`;
14770
+ if (reservation.status === "settled") {
14771
+ const entry = this.entriesByKey.get(key);
14772
+ if (!entry || entry.consumed !== consumed) {
14773
+ throw new CreditIdempotencyConflictError(key);
14774
+ }
14775
+ return { ...entry };
14776
+ }
14777
+ if (reservation.status === "released") {
14778
+ throw new CreditReservationStateError(
14779
+ `Reservation ${reservationId} was released`
14780
+ );
14781
+ }
14782
+ if (consumed > reservation.credits) {
14783
+ throw new CreditReservationStateError(
14784
+ `Cannot consume ${consumed}; reservation holds ${reservation.credits}`
14785
+ );
14786
+ }
14787
+ return this.close(reservation, "settled", consumed, key);
14788
+ }
14789
+ async release(reservationId) {
14790
+ const reservation = this.reservations.get(reservationId);
14791
+ if (!reservation) {
14792
+ throw new CreditReservationStateError(
14793
+ `Reservation ${reservationId} not found`
14794
+ );
14795
+ }
14796
+ if (reservation.status !== "held") return;
14797
+ this.close(reservation, "released", 0, `release:${reservationId}`);
14798
+ }
14799
+ async clawback(input) {
14800
+ assertWholeCredits(input.credits, "credits");
14801
+ assertIdempotencyKey(input.idempotencyKey);
14802
+ const existing = this.entriesByKey.get(input.idempotencyKey);
14803
+ if (existing) {
14804
+ if (existing.accountId !== input.accountId || existing.kind !== "clawback") {
14805
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
14806
+ }
14807
+ return { entry: { ...existing }, clawedBack: -existing.delta };
14808
+ }
14809
+ const account = this.account(input.accountId);
14810
+ const taken = Math.min(input.credits, account.available);
14811
+ account.available -= taken;
14812
+ const entry = this.record({
14813
+ accountId: input.accountId,
14814
+ kind: "clawback",
14815
+ delta: -taken,
14816
+ consumed: 0,
14817
+ availableAfter: account.available,
14818
+ reservationId: null,
14819
+ reference: input.reference ?? null,
14820
+ idempotencyKey: input.idempotencyKey
14821
+ });
14822
+ return { entry, clawedBack: taken };
14823
+ }
14824
+ async expireReservations(now = /* @__PURE__ */ new Date()) {
14825
+ let released = 0;
14826
+ for (const reservation of this.reservations.values()) {
14827
+ if (reservation.status === "held" && reservation.expiresAt <= now) {
14828
+ this.close(reservation, "released", 0, `release:${reservation.id}`);
14829
+ released++;
14830
+ }
14831
+ }
14832
+ return released;
14833
+ }
14834
+ async getReservation(reservationId) {
14835
+ const reservation = this.reservations.get(reservationId);
14836
+ return reservation ? { ...reservation } : null;
14837
+ }
14838
+ async listEntries(accountId, options = {}) {
14839
+ const limit = clampEntryLimit(options.limit);
14840
+ return this.entries.filter((entry) => entry.accountId === accountId).reverse().slice(0, limit).map((entry) => ({ ...entry }));
14841
+ }
14842
+ account(accountId) {
14843
+ let account = this.accounts.get(accountId);
14844
+ if (!account) {
14845
+ account = { available: 0, reserved: 0 };
14846
+ this.accounts.set(accountId, account);
14847
+ }
14848
+ return account;
14849
+ }
14850
+ close(reservation, status, consumed, key) {
14851
+ const account = this.account(reservation.accountId);
14852
+ const returned = reservation.credits - consumed;
14853
+ account.reserved -= reservation.credits;
14854
+ account.available += returned;
14855
+ reservation.status = status;
14856
+ reservation.consumed = status === "settled" ? consumed : null;
14857
+ return this.record({
14858
+ accountId: reservation.accountId,
14859
+ kind: status === "settled" ? "settle" : "release",
14860
+ delta: returned,
14861
+ consumed,
14862
+ availableAfter: account.available,
14863
+ reservationId: reservation.id,
14864
+ reference: reservation.reference,
14865
+ idempotencyKey: key
14866
+ });
14867
+ }
14868
+ record(entry) {
14869
+ const full = {
14870
+ ...entry,
14871
+ id: generateCreditId("ce"),
14872
+ createdAt: /* @__PURE__ */ new Date()
14873
+ };
14874
+ this.entries.push(full);
14875
+ this.entriesByKey.set(full.idempotencyKey, full);
14876
+ return { ...full };
14877
+ }
14878
+ };
14879
+
14602
14880
  // src/index.ts
14603
14881
  init_IAI();
14604
14882
  init_IRAG();
@@ -19594,11 +19872,24 @@ async function checkRateLimit(operation, identifier, rule, options = {}) {
19594
19872
  retryAfterSeconds: 0
19595
19873
  };
19596
19874
  } catch (error) {
19597
- options.logger?.error("Rate limit check failed, allowing request", {
19598
- error: error instanceof Error ? error.message : String(error),
19599
- operation,
19600
- identifier
19601
- });
19875
+ options.logger?.error(
19876
+ rule.failClosed ? "Rate limit check failed, denying request (fail-closed rule)" : "Rate limit check failed, allowing request",
19877
+ {
19878
+ error: error instanceof Error ? error.message : String(error),
19879
+ operation,
19880
+ identifier
19881
+ }
19882
+ );
19883
+ if (rule.failClosed) {
19884
+ return {
19885
+ allowed: false,
19886
+ remaining: 0,
19887
+ resetAt,
19888
+ current: 0,
19889
+ limit,
19890
+ retryAfterSeconds: 30
19891
+ };
19892
+ }
19602
19893
  return {
19603
19894
  allowed: true,
19604
19895
  remaining: limit,
@@ -32780,6 +33071,444 @@ var PostgresBeta = class {
32780
33071
  }
32781
33072
  };
32782
33073
 
33074
+ // src/adapters/postgres-credits/PostgresCreditLedger.ts
33075
+ var SCHEMA_NAME = /^[a-z_][a-z0-9_]{0,62}$/;
33076
+ var TABLE_PREFIX = /^[a-z_][a-z0-9_]{0,19}$/;
33077
+ var UNIQUE_VIOLATION = "23505";
33078
+ function isUniqueViolation(error) {
33079
+ return error?.code === UNIQUE_VIOLATION;
33080
+ }
33081
+ function toEntry(row) {
33082
+ return {
33083
+ id: row.id,
33084
+ accountId: row.account_id,
33085
+ kind: row.kind,
33086
+ delta: Number(row.delta),
33087
+ consumed: Number(row.consumed),
33088
+ availableAfter: Number(row.available_after),
33089
+ reservationId: row.reservation_id ?? null,
33090
+ reference: row.reference ?? null,
33091
+ idempotencyKey: row.idempotency_key,
33092
+ createdAt: new Date(row.created_at)
33093
+ };
33094
+ }
33095
+ function toReservation(row) {
33096
+ return {
33097
+ id: row.id,
33098
+ accountId: row.account_id,
33099
+ credits: Number(row.credits),
33100
+ status: row.status,
33101
+ consumed: row.consumed === null ? null : Number(row.consumed),
33102
+ reference: row.reference ?? null,
33103
+ idempotencyKey: row.idempotency_key,
33104
+ expiresAt: new Date(row.expires_at),
33105
+ createdAt: new Date(row.created_at)
33106
+ };
33107
+ }
33108
+ var PostgresCreditLedger = class {
33109
+ pool;
33110
+ prefix;
33111
+ accounts;
33112
+ entries;
33113
+ reservations;
33114
+ constructor(config) {
33115
+ const schema = config.schema ?? "public";
33116
+ const prefix = config.tablePrefix ?? "credit_";
33117
+ if (!SCHEMA_NAME.test(schema) || !TABLE_PREFIX.test(prefix)) {
33118
+ throw new RangeError(
33119
+ "schema (max 63) and tablePrefix (max 20) must be lowercase SQL identifiers"
33120
+ );
33121
+ }
33122
+ this.pool = config.pool;
33123
+ this.prefix = prefix;
33124
+ this.accounts = `"${schema}"."${prefix}accounts"`;
33125
+ this.entries = `"${schema}"."${prefix}entries"`;
33126
+ this.reservations = `"${schema}"."${prefix}reservations"`;
33127
+ }
33128
+ /**
33129
+ * DDL for the ledger. Exposed so apps that hand-apply migrations can ship
33130
+ * it as a reviewed file instead of calling initialize() at runtime.
33131
+ */
33132
+ schemaSql() {
33133
+ return `
33134
+ CREATE TABLE IF NOT EXISTS ${this.accounts} (
33135
+ account_id text PRIMARY KEY,
33136
+ available bigint NOT NULL DEFAULT 0 CHECK (available >= 0),
33137
+ reserved bigint NOT NULL DEFAULT 0 CHECK (reserved >= 0),
33138
+ updated_at timestamptz NOT NULL DEFAULT now()
33139
+ );
33140
+ CREATE TABLE IF NOT EXISTS ${this.reservations} (
33141
+ id text PRIMARY KEY,
33142
+ account_id text NOT NULL REFERENCES ${this.accounts}(account_id),
33143
+ credits bigint NOT NULL CHECK (credits > 0),
33144
+ status text NOT NULL CHECK (status IN ('held','settled','released')),
33145
+ consumed bigint CHECK (consumed IS NULL OR (consumed >= 0 AND consumed <= credits)),
33146
+ reference text,
33147
+ idempotency_key text NOT NULL UNIQUE,
33148
+ expires_at timestamptz NOT NULL,
33149
+ created_at timestamptz NOT NULL DEFAULT now(),
33150
+ updated_at timestamptz NOT NULL DEFAULT now()
33151
+ );
33152
+ CREATE INDEX IF NOT EXISTS "${this.prefix}reservations_held_expiry"
33153
+ ON ${this.reservations} (expires_at) WHERE status = 'held';
33154
+ CREATE TABLE IF NOT EXISTS ${this.entries} (
33155
+ id text PRIMARY KEY,
33156
+ account_id text NOT NULL REFERENCES ${this.accounts}(account_id),
33157
+ kind text NOT NULL CHECK (kind IN ('purchase','grant','reserve','settle','release','clawback')),
33158
+ delta bigint NOT NULL,
33159
+ consumed bigint NOT NULL DEFAULT 0 CHECK (consumed >= 0),
33160
+ available_after bigint NOT NULL CHECK (available_after >= 0),
33161
+ reservation_id text REFERENCES ${this.reservations}(id),
33162
+ reference text,
33163
+ idempotency_key text NOT NULL UNIQUE,
33164
+ created_at timestamptz NOT NULL DEFAULT now()
33165
+ );
33166
+ CREATE INDEX IF NOT EXISTS "${this.prefix}entries_account_created"
33167
+ ON ${this.entries} (account_id, created_at DESC);
33168
+ `;
33169
+ }
33170
+ async initialize() {
33171
+ await this.pool.query(this.schemaSql());
33172
+ }
33173
+ async getBalance(accountId) {
33174
+ const { rows } = await this.pool.query(
33175
+ `SELECT available, reserved FROM ${this.accounts} WHERE account_id = $1`,
33176
+ [accountId]
33177
+ );
33178
+ const row = rows[0];
33179
+ return {
33180
+ accountId,
33181
+ available: row ? Number(row.available) : 0,
33182
+ reserved: row ? Number(row.reserved) : 0
33183
+ };
33184
+ }
33185
+ async grant(input) {
33186
+ assertWholeCredits(input.credits, "credits");
33187
+ assertIdempotencyKey(input.idempotencyKey);
33188
+ const replay = (entry) => {
33189
+ if (entry.accountId !== input.accountId || entry.kind !== input.kind || entry.delta !== input.credits) {
33190
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
33191
+ }
33192
+ return entry;
33193
+ };
33194
+ return this.idempotent(input.idempotencyKey, replay, async (client) => {
33195
+ await client.query(
33196
+ `INSERT INTO ${this.accounts} (account_id) VALUES ($1) ON CONFLICT DO NOTHING`,
33197
+ [input.accountId]
33198
+ );
33199
+ const { rows } = await client.query(
33200
+ `UPDATE ${this.accounts} SET available = available + $2, updated_at = now()
33201
+ WHERE account_id = $1 RETURNING available`,
33202
+ [input.accountId, input.credits]
33203
+ );
33204
+ return this.insertEntry(client, {
33205
+ accountId: input.accountId,
33206
+ kind: input.kind,
33207
+ delta: input.credits,
33208
+ consumed: 0,
33209
+ availableAfter: Number(rows[0].available),
33210
+ reservationId: null,
33211
+ reference: input.reference ?? null,
33212
+ idempotencyKey: input.idempotencyKey
33213
+ });
33214
+ });
33215
+ }
33216
+ async reserve(input) {
33217
+ assertWholeCredits(input.credits, "credits");
33218
+ assertIdempotencyKey(input.idempotencyKey);
33219
+ const seconds = reservationSeconds(input.expiresInSeconds);
33220
+ const existing = await this.reservationByKey(
33221
+ this.pool,
33222
+ input.idempotencyKey
33223
+ );
33224
+ if (existing) return this.replayReservation(existing, input);
33225
+ const client = await this.pool.connect();
33226
+ try {
33227
+ await client.query("BEGIN");
33228
+ const { rows } = await client.query(
33229
+ `UPDATE ${this.accounts}
33230
+ SET available = available - $2, reserved = reserved + $2, updated_at = now()
33231
+ WHERE account_id = $1 AND available >= $2
33232
+ RETURNING available`,
33233
+ [input.accountId, input.credits]
33234
+ );
33235
+ if (rows.length === 0) {
33236
+ await client.query("ROLLBACK");
33237
+ const current = await client.query(
33238
+ `SELECT available FROM ${this.accounts} WHERE account_id = $1`,
33239
+ [input.accountId]
33240
+ );
33241
+ throw new InsufficientCreditsError(
33242
+ input.accountId,
33243
+ input.credits,
33244
+ current.rows[0] ? Number(current.rows[0].available) : 0
33245
+ );
33246
+ }
33247
+ const id = generateCreditId("cr");
33248
+ const inserted = await client.query(
33249
+ `INSERT INTO ${this.reservations}
33250
+ (id, account_id, credits, status, reference, idempotency_key, expires_at)
33251
+ VALUES ($1, $2, $3, 'held', $4, $5, now() + make_interval(secs => $6))
33252
+ RETURNING *`,
33253
+ [
33254
+ id,
33255
+ input.accountId,
33256
+ input.credits,
33257
+ input.reference ?? null,
33258
+ input.idempotencyKey,
33259
+ seconds
33260
+ ]
33261
+ );
33262
+ await this.insertEntry(client, {
33263
+ accountId: input.accountId,
33264
+ kind: "reserve",
33265
+ delta: -input.credits,
33266
+ consumed: 0,
33267
+ availableAfter: Number(rows[0].available),
33268
+ reservationId: id,
33269
+ reference: input.reference ?? null,
33270
+ idempotencyKey: `reserve:${id}`
33271
+ });
33272
+ await client.query("COMMIT");
33273
+ return toReservation(inserted.rows[0]);
33274
+ } catch (error) {
33275
+ await client.query("ROLLBACK").catch(() => void 0);
33276
+ if (isUniqueViolation(error)) {
33277
+ const winner = await this.reservationByKey(
33278
+ client,
33279
+ input.idempotencyKey
33280
+ );
33281
+ if (winner) return this.replayReservation(winner, input);
33282
+ }
33283
+ throw error;
33284
+ } finally {
33285
+ client.release();
33286
+ }
33287
+ }
33288
+ async settle(reservationId, consumed) {
33289
+ if (!Number.isSafeInteger(consumed) || consumed < 0) {
33290
+ throw new RangeError("consumed must be a whole number of credits >= 0");
33291
+ }
33292
+ return (await this.closeReservation(reservationId, "settled", consumed)).entry;
33293
+ }
33294
+ async release(reservationId) {
33295
+ await this.closeReservation(reservationId, "released", 0);
33296
+ }
33297
+ async clawback(input) {
33298
+ assertWholeCredits(input.credits, "credits");
33299
+ assertIdempotencyKey(input.idempotencyKey);
33300
+ const replay = (entry2) => {
33301
+ if (entry2.accountId !== input.accountId || entry2.kind !== "clawback") {
33302
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
33303
+ }
33304
+ return entry2;
33305
+ };
33306
+ const entry = await this.idempotent(
33307
+ input.idempotencyKey,
33308
+ replay,
33309
+ async (client) => {
33310
+ await client.query(
33311
+ `INSERT INTO ${this.accounts} (account_id) VALUES ($1) ON CONFLICT DO NOTHING`,
33312
+ [input.accountId]
33313
+ );
33314
+ const { rows } = await client.query(
33315
+ `SELECT available FROM ${this.accounts} WHERE account_id = $1 FOR UPDATE`,
33316
+ [input.accountId]
33317
+ );
33318
+ const taken = Math.min(input.credits, Number(rows[0].available));
33319
+ const updated = await client.query(
33320
+ `UPDATE ${this.accounts} SET available = available - $2, updated_at = now()
33321
+ WHERE account_id = $1 RETURNING available`,
33322
+ [input.accountId, taken]
33323
+ );
33324
+ return this.insertEntry(client, {
33325
+ accountId: input.accountId,
33326
+ kind: "clawback",
33327
+ delta: -taken,
33328
+ consumed: 0,
33329
+ availableAfter: Number(updated.rows[0].available),
33330
+ reservationId: null,
33331
+ reference: input.reference ?? null,
33332
+ idempotencyKey: input.idempotencyKey
33333
+ });
33334
+ }
33335
+ );
33336
+ return { entry, clawedBack: -entry.delta };
33337
+ }
33338
+ async expireReservations(now) {
33339
+ const { rows } = await this.pool.query(
33340
+ `SELECT id FROM ${this.reservations}
33341
+ WHERE status = 'held' AND expires_at <= COALESCE($1::timestamptz, now())
33342
+ ORDER BY expires_at LIMIT 500`,
33343
+ [now ? now.toISOString() : null]
33344
+ );
33345
+ let released = 0;
33346
+ for (const row of rows) {
33347
+ const { closedHere } = await this.closeReservation(
33348
+ row.id,
33349
+ "released",
33350
+ 0
33351
+ );
33352
+ if (closedHere) released++;
33353
+ }
33354
+ return released;
33355
+ }
33356
+ async getReservation(reservationId) {
33357
+ const { rows } = await this.pool.query(
33358
+ `SELECT * FROM ${this.reservations} WHERE id = $1`,
33359
+ [reservationId]
33360
+ );
33361
+ return rows[0] ? toReservation(rows[0]) : null;
33362
+ }
33363
+ async listEntries(accountId, options = {}) {
33364
+ const limit = clampEntryLimit(options.limit);
33365
+ const { rows } = await this.pool.query(
33366
+ `SELECT * FROM ${this.entries} WHERE account_id = $1
33367
+ ORDER BY created_at DESC, id DESC LIMIT $2`,
33368
+ [accountId, limit]
33369
+ );
33370
+ return rows.map(toEntry);
33371
+ }
33372
+ // ─────────────────────────────────────────────────────────────
33373
+ // Internals
33374
+ // ─────────────────────────────────────────────────────────────
33375
+ /**
33376
+ * Runs `write` in a transaction keyed by `idempotencyKey`. An existing
33377
+ * entry with that key is replayed instead; a concurrent duplicate that
33378
+ * loses the unique insert rolls back and replays the winner.
33379
+ */
33380
+ async idempotent(idempotencyKey, replay, write) {
33381
+ const prior = await this.entryByKey(this.pool, idempotencyKey);
33382
+ if (prior) return replay(prior);
33383
+ const client = await this.pool.connect();
33384
+ try {
33385
+ await client.query("BEGIN");
33386
+ const entry = await write(client);
33387
+ await client.query("COMMIT");
33388
+ return entry;
33389
+ } catch (error) {
33390
+ await client.query("ROLLBACK").catch(() => void 0);
33391
+ if (isUniqueViolation(error)) {
33392
+ const winner = await this.entryByKey(client, idempotencyKey);
33393
+ if (winner) return replay(winner);
33394
+ }
33395
+ throw error;
33396
+ } finally {
33397
+ client.release();
33398
+ }
33399
+ }
33400
+ async closeReservation(reservationId, status, consumed) {
33401
+ const key = `${status === "settled" ? "settle" : "release"}:${reservationId}`;
33402
+ const client = await this.pool.connect();
33403
+ try {
33404
+ await client.query("BEGIN");
33405
+ const { rows } = await client.query(
33406
+ `SELECT * FROM ${this.reservations} WHERE id = $1 FOR UPDATE`,
33407
+ [reservationId]
33408
+ );
33409
+ if (!rows[0]) {
33410
+ throw new CreditReservationStateError(
33411
+ `Reservation ${reservationId} not found`
33412
+ );
33413
+ }
33414
+ const reservation = toReservation(rows[0]);
33415
+ if (reservation.status !== "held") {
33416
+ await client.query("ROLLBACK");
33417
+ const settledEntry = await this.entryByKey(
33418
+ client,
33419
+ `settle:${reservationId}`
33420
+ );
33421
+ if (status === "released") {
33422
+ const entry2 = settledEntry ?? await this.entryByKey(client, `release:${reservationId}`);
33423
+ return { entry: entry2, closedHere: false };
33424
+ }
33425
+ if (reservation.status === "released") {
33426
+ throw new CreditReservationStateError(
33427
+ `Reservation ${reservationId} was released`
33428
+ );
33429
+ }
33430
+ if (!settledEntry || settledEntry.consumed !== consumed) {
33431
+ throw new CreditIdempotencyConflictError(key);
33432
+ }
33433
+ return { entry: settledEntry, closedHere: false };
33434
+ }
33435
+ if (consumed > reservation.credits) {
33436
+ throw new CreditReservationStateError(
33437
+ `Cannot consume ${consumed}; reservation holds ${reservation.credits}`
33438
+ );
33439
+ }
33440
+ const returned = reservation.credits - consumed;
33441
+ const account = await client.query(
33442
+ `UPDATE ${this.accounts}
33443
+ SET reserved = reserved - $2, available = available + $3, updated_at = now()
33444
+ WHERE account_id = $1 RETURNING available`,
33445
+ [reservation.accountId, reservation.credits, returned]
33446
+ );
33447
+ await client.query(
33448
+ `UPDATE ${this.reservations} SET status = $2, consumed = $3, updated_at = now() WHERE id = $1`,
33449
+ [reservationId, status, status === "settled" ? consumed : null]
33450
+ );
33451
+ const entry = await this.insertEntry(client, {
33452
+ accountId: reservation.accountId,
33453
+ kind: status === "settled" ? "settle" : "release",
33454
+ delta: returned,
33455
+ consumed,
33456
+ availableAfter: Number(account.rows[0].available),
33457
+ reservationId,
33458
+ reference: reservation.reference,
33459
+ idempotencyKey: key
33460
+ });
33461
+ await client.query("COMMIT");
33462
+ return { entry, closedHere: true };
33463
+ } catch (error) {
33464
+ await client.query("ROLLBACK").catch(() => void 0);
33465
+ throw error;
33466
+ } finally {
33467
+ client.release();
33468
+ }
33469
+ }
33470
+ async insertEntry(client, entry) {
33471
+ const { rows } = await client.query(
33472
+ `INSERT INTO ${this.entries}
33473
+ (id, account_id, kind, delta, consumed, available_after, reservation_id, reference, idempotency_key)
33474
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
33475
+ RETURNING *`,
33476
+ [
33477
+ generateCreditId("ce"),
33478
+ entry.accountId,
33479
+ entry.kind,
33480
+ entry.delta,
33481
+ entry.consumed,
33482
+ entry.availableAfter,
33483
+ entry.reservationId,
33484
+ entry.reference,
33485
+ entry.idempotencyKey
33486
+ ]
33487
+ );
33488
+ return toEntry(rows[0]);
33489
+ }
33490
+ async entryByKey(db, idempotencyKey) {
33491
+ const { rows } = await db.query(
33492
+ `SELECT * FROM ${this.entries} WHERE idempotency_key = $1`,
33493
+ [idempotencyKey]
33494
+ );
33495
+ return rows[0] ? toEntry(rows[0]) : null;
33496
+ }
33497
+ async reservationByKey(db, idempotencyKey) {
33498
+ const { rows } = await db.query(
33499
+ `SELECT * FROM ${this.reservations} WHERE idempotency_key = $1`,
33500
+ [idempotencyKey]
33501
+ );
33502
+ return rows[0] ? toReservation(rows[0]) : null;
33503
+ }
33504
+ replayReservation(existing, input) {
33505
+ if (existing.accountId !== input.accountId || existing.credits !== input.credits) {
33506
+ throw new CreditIdempotencyConflictError(input.idempotencyKey);
33507
+ }
33508
+ return existing;
33509
+ }
33510
+ };
33511
+
32783
33512
  // src/app-logger.ts
32784
33513
  var LEVEL_PRIORITY2 = {
32785
33514
  debug: 0,
@@ -32913,9 +33642,12 @@ function createRedisClient(options) {
32913
33642
  const client = new import_ioredis.default(url, {
32914
33643
  keyPrefix,
32915
33644
  maxRetriesPerRequest: maxRetries,
33645
+ // Never give up reconnecting. Returning null here ends the connection
33646
+ // for good, and a long-lived singleton (rate limiting, caching) would
33647
+ // then stay broken until the process restarts. maxRetriesPerRequest
33648
+ // still makes individual commands fail fast while disconnected.
32916
33649
  retryStrategy(times) {
32917
- if (times > maxRetries) return null;
32918
- return Math.min(times * 200, 2e3);
33650
+ return Math.min(times * 200, 5e3);
32919
33651
  },
32920
33652
  lazyConnect
32921
33653
  });
@@ -33806,11 +34538,14 @@ function getEnterpriseMigrations(features) {
33806
34538
  CommonRateLimits,
33807
34539
  ConsoleEmail,
33808
34540
  ConsoleLogger,
34541
+ CreditIdempotencyConflictError,
34542
+ CreditReservationStateError,
33809
34543
  CronPresets,
33810
34544
  CryptoConfigSchema,
33811
34545
  DEFAULT_AGENT_LOOP_OPTIONS,
33812
34546
  DEFAULT_BULKHEAD_OPTIONS,
33813
34547
  DEFAULT_CIRCUIT_BREAKER_OPTIONS,
34548
+ DEFAULT_RESERVATION_SECONDS,
33814
34549
  DEFAULT_RETRY_OPTIONS,
33815
34550
  DatabaseAIUsage,
33816
34551
  DatabaseAuditLog,
@@ -33832,10 +34567,12 @@ function getEnterpriseMigrations(features) {
33832
34567
  GoogleAIAdapter,
33833
34568
  HTML_TAG_PATTERN,
33834
34569
  HttpWebhook,
34570
+ InsufficientCreditsError,
33835
34571
  KEYCLOAK_DEFAULT_ROLES,
33836
34572
  LogLevelSchema,
33837
34573
  LoggingConfigSchema,
33838
34574
  LoginSchema,
34575
+ MAX_LIST_ENTRIES,
33839
34576
  MemoryAI,
33840
34577
  MemoryAIUsage,
33841
34578
  MemoryAuditLog,
@@ -33845,6 +34582,7 @@ function getEnterpriseMigrations(features) {
33845
34582
  MemoryBilling,
33846
34583
  MemoryCache,
33847
34584
  MemoryCompliance,
34585
+ MemoryCreditLedger,
33848
34586
  MemoryCrypto,
33849
34587
  MemoryDatabase,
33850
34588
  MemoryDevPortal,
@@ -33884,6 +34622,7 @@ function getEnterpriseMigrations(features) {
33884
34622
  PineconeRAG,
33885
34623
  PlatformConfigSchema,
33886
34624
  PostgresBeta,
34625
+ PostgresCreditLedger,
33887
34626
  PostgresDatabase,
33888
34627
  PostgresTenant,
33889
34628
  QueueConfigSchema,
@@ -33925,6 +34664,8 @@ function getEnterpriseMigrations(features) {
33925
34664
  WeaviateRAG,
33926
34665
  WebhookEventTypes,
33927
34666
  WrapperPresets,
34667
+ assertIdempotencyKey,
34668
+ assertWholeCredits,
33928
34669
  buildAllowlist,
33929
34670
  buildAuthCookies,
33930
34671
  buildErrorBody,
@@ -33938,6 +34679,7 @@ function getEnterpriseMigrations(features) {
33938
34679
  calculateRetryDelay,
33939
34680
  checkEnvVars,
33940
34681
  checkRateLimit,
34682
+ clampEntryLimit,
33941
34683
  classifyError,
33942
34684
  clearStoredBetaCode,
33943
34685
  closeSharedRedis,
@@ -34024,6 +34766,7 @@ function getEnterpriseMigrations(features) {
34024
34766
  generateBetaCode,
34025
34767
  generateBetaId,
34026
34768
  generateChecksum,
34769
+ generateCreditId,
34027
34770
  generateDeliveryId,
34028
34771
  generateErrorId,
34029
34772
  generateEventId,
@@ -34076,6 +34819,7 @@ function getEnterpriseMigrations(features) {
34076
34819
  parseKeycloakRoles,
34077
34820
  raceTimeout,
34078
34821
  refreshKeycloakToken,
34822
+ reservationSeconds,
34079
34823
  resetRateLimitForKey,
34080
34824
  resolveIdentifier,
34081
34825
  resolveRateLimitIdentifier,