@burdenoff/be-sdk 2026.1202.2 → 2026.1202.3

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.
@@ -1,2 +1,2 @@
1
- import { C as AiCreditPricingTransport, D as WorkspaceQuotaUsage, E as AiTokenUsageReport, S as AiCreditLogger, T as AiCreditSkipReason, _ as AiCreditChargeInput, a as AiCreditInputErrorCode, b as AiCreditGate, c as AiTokenUsageValidationError, d as aiCreditQuotaName, f as defaultAiCreditHashPrefix, g as AiCreditChargeGuard, h as AiCreditAllowance, i as AiCreditInputError, l as AiTokenUsageViolation, m as validateAiTokenUsage, n as AiCreditMeter, o as isAiCreditInputError, p as encodeAiCreditHashComponent, r as AiCreditMeterOptions, s as AI_CREDIT_MAX_TOKENS_PER_REPORT, u as aiCreditIdempotencyHash, v as AiCreditChargeResult, w as AiCreditQuoteInput, x as AiCreditGuardVerdict, y as AiCreditFetch } from "../index-BJwHEzpN.js";
2
- export { AI_CREDIT_MAX_TOKENS_PER_REPORT, type AiCreditAllowance, type AiCreditChargeGuard, type AiCreditChargeInput, type AiCreditChargeResult, type AiCreditFetch, type AiCreditGate, type AiCreditGuardVerdict, AiCreditInputError, type AiCreditInputErrorCode, type AiCreditLogger, AiCreditMeter, type AiCreditMeterOptions, type AiCreditPricingTransport, type AiCreditQuoteInput, type AiCreditSkipReason, type AiTokenUsageReport, type AiTokenUsageValidationError, type AiTokenUsageViolation, type WorkspaceQuotaUsage, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage };
1
+ import { A as UsageSettlementStatus, C as AiCreditPricingTransport, D as ReadUsageSettlementInput, E as AiTokenUsageReport, O as UsageSettlementPayer, S as AiCreditLogger, T as AiCreditSkipReason, _ as AiCreditChargeInput, a as AiCreditInputErrorCode, b as AiCreditGate, c as AiTokenUsageValidationError, d as aiCreditQuotaName, f as defaultAiCreditHashPrefix, g as AiCreditChargeGuard, h as AiCreditAllowance, i as AiCreditInputError, j as WorkspaceQuotaUsage, k as UsageSettlementReceipt, l as AiTokenUsageViolation, m as validateAiTokenUsage, n as AiCreditMeter, o as isAiCreditInputError, p as encodeAiCreditHashComponent, r as AiCreditMeterOptions, s as AI_CREDIT_MAX_TOKENS_PER_REPORT, u as aiCreditIdempotencyHash, v as AiCreditChargeResult, w as AiCreditQuoteInput, x as AiCreditGuardVerdict, y as AiCreditFetch } from "../index-SAUnwdbo.js";
2
+ export { AI_CREDIT_MAX_TOKENS_PER_REPORT, type AiCreditAllowance, type AiCreditChargeGuard, type AiCreditChargeInput, type AiCreditChargeResult, type AiCreditFetch, type AiCreditGate, type AiCreditGuardVerdict, AiCreditInputError, type AiCreditInputErrorCode, type AiCreditLogger, AiCreditMeter, type AiCreditMeterOptions, type AiCreditPricingTransport, type AiCreditQuoteInput, type AiCreditSkipReason, type AiTokenUsageReport, type AiTokenUsageValidationError, type AiTokenUsageViolation, type ReadUsageSettlementInput, type UsageSettlementPayer, type UsageSettlementReceipt, type UsageSettlementStatus, type WorkspaceQuotaUsage, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage };
@@ -1,4 +1,4 @@
1
- import { a as AI_CREDIT_MAX_TOKENS_PER_REPORT, c as defaultAiCreditHashPrefix, i as isAiCreditInputError, l as encodeAiCreditHashComponent, n as AiCreditMeter, o as aiCreditIdempotencyHash, r as AiCreditInputError, s as aiCreditQuotaName, u as validateAiTokenUsage } from "../ai-credits-xxfwGpHS.js";
1
+ import { a as AI_CREDIT_MAX_TOKENS_PER_REPORT, c as defaultAiCreditHashPrefix, i as isAiCreditInputError, l as encodeAiCreditHashComponent, n as AiCreditMeter, o as aiCreditIdempotencyHash, r as AiCreditInputError, s as aiCreditQuotaName, u as validateAiTokenUsage } from "../ai-credits-B_IPVIu1.js";
2
2
 
3
3
  export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditInputError, AiCreditMeter, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage };
4
4
  //# sourceMappingURL=index.js.map
@@ -135,6 +135,15 @@ const GATE_PROBE_AMOUNT = 1;
135
135
  const WORKSPACE_QUOTA_ASSIGNMENTS_QUERY = `query AiCreditMeterQuotaAssignments($workspaceId: ID!) {
136
136
  workspaceQuotaAssignments(workspaceId: $workspaceId) { quotaName used limit noLimit isActive }
137
137
  }`;
138
+ const GET_USAGE_SETTLEMENT_QUERY = `query AiCreditMeterGetUsageSettlement($hash: String!, $quotaName: String!, $productId: String!, $payer: UsageSettlementPayerInput) {
139
+ getUsageSettlement(hash: $hash, quotaName: $quotaName, productId: $productId, payer: $payer) { id status amount }
140
+ }`;
141
+ const VALID_SETTLEMENT_STATUSES = /* @__PURE__ */ new Set([
142
+ "pending",
143
+ "done",
144
+ "failed"
145
+ ]);
146
+ const USAGE_HOLD_MARKER = "USAGE_RECORD_HELD_FOR_REVIEW";
138
147
  function errorMessage(error) {
139
148
  return error instanceof Error ? error.message : String(error);
140
149
  }
@@ -239,6 +248,7 @@ var AiCreditMeter = class {
239
248
  if (!workspaceId) throw new AiCreditInputError("WORKSPACE_ID_REQUIRED", "This request has no workspace context.");
240
249
  const invalid = validateAiTokenUsage(input, this.maxTokensPerReport);
241
250
  if (invalid) throw new AiCreditInputError(invalid.code, invalid.message);
251
+ if (input.frozenCredits != null && (typeof input.frozenCredits !== "number" || !Number.isFinite(input.frozenCredits) || input.frozenCredits < 0)) throw new AiCreditInputError("FROZEN_CREDITS_INVALID", "frozenCredits must be a finite non-negative number.");
242
252
  const hash = this.hashFor(input.sessionId, input.messageId);
243
253
  const logFields = {
244
254
  productId: this.productId,
@@ -277,15 +287,19 @@ var AiCreditMeter = class {
277
287
  error: errorMessage(error)
278
288
  });
279
289
  }
280
- const credits = await this.quote(input);
290
+ const credits = input.frozenCredits != null ? input.frozenCredits : await this.quote(input);
281
291
  if (credits === null) return skipped("NOT_PRICED", null);
282
292
  if (credits <= 0) return skipped("ZERO_COST", credits);
293
+ const billingAccountId = input.billingAccountId?.trim() || void 0;
294
+ const quotaAssignmentId = input.quotaAssignmentId?.trim() || void 0;
283
295
  try {
284
296
  await this.trackUsage({
285
297
  workspaceId,
286
298
  amount: credits,
287
299
  description: input.description?.trim() || `AI credits for session ${input.sessionId}`,
288
300
  userId: input.userId ?? void 0,
301
+ ...billingAccountId ? { billingAccountId } : {},
302
+ ...quotaAssignmentId ? { quotaAssignmentId } : {},
289
303
  hash,
290
304
  metadata: {
291
305
  model: input.model,
@@ -302,7 +316,9 @@ var AiCreditMeter = class {
302
316
  }
303
317
  });
304
318
  } catch (error) {
305
- return skipped("RECORD_FAILED", credits, errorMessage(error));
319
+ const detail = errorMessage(error);
320
+ if (detail.includes(USAGE_HOLD_MARKER)) return skipped("HELD_FOR_REVIEW", credits, detail);
321
+ return skipped("RECORD_FAILED", credits, detail);
306
322
  }
307
323
  this.log.info(`[AiCreditMeter] Charged ${credits} AI credits for session ${input.sessionId}`, {
308
324
  ...logFields,
@@ -426,6 +442,38 @@ var AiCreditMeter = class {
426
442
  entitled: false
427
443
  };
428
444
  }
445
+ /**
446
+ * Read the payer-bound usage settlement receipt directly from wspace-activity-svc
447
+ * (`getUsageSettlement`).
448
+ *
449
+ * Returns `null` ONLY when Activity explicitly confirms no matching record exists
450
+ * for the workspace, hash, quota, product and payer scope. Throws on transport,
451
+ * GraphQL, or malformed-response errors so a caller never mistakes an outage for
452
+ * a missing settlement record.
453
+ */
454
+ async readSettlement(input) {
455
+ const workspaceId = input.workspaceId?.trim() ?? "";
456
+ if (!workspaceId) throw new AiCreditInputError("WORKSPACE_ID_REQUIRED", "This request has no workspace context.");
457
+ const hash = input.hash?.trim() ?? "";
458
+ if (!hash) throw new Error("AiCreditMeter.readSettlement: hash is required");
459
+ const payer = input.payer ? {
460
+ billingAccountId: requireNonEmpty(input.payer.billingAccountId, "payer.billingAccountId"),
461
+ ...input.payer.quotaAssignmentId != null ? { quotaAssignmentId: requireNonEmpty(input.payer.quotaAssignmentId, "payer.quotaAssignmentId") } : {}
462
+ } : void 0;
463
+ const receipt = (await this.activityRequest(workspaceId, GET_USAGE_SETTLEMENT_QUERY, {
464
+ hash,
465
+ quotaName: this.quotaName,
466
+ productId: this.productId,
467
+ ...payer ? { payer } : {}
468
+ })).getUsageSettlement;
469
+ if (receipt == null) return null;
470
+ if (typeof receipt.id !== "string" || !receipt.id.trim() || typeof receipt.status !== "string" || !VALID_SETTLEMENT_STATUSES.has(receipt.status) || typeof receipt.amount !== "number" || !Number.isFinite(receipt.amount) || receipt.amount < 0) throw new Error("getUsageSettlement returned a malformed settlement receipt");
471
+ return {
472
+ id: receipt.id,
473
+ status: receipt.status,
474
+ amount: receipt.amount
475
+ };
476
+ }
429
477
  async trackUsage(record) {
430
478
  const data = await this.activityRequest(record.workspaceId, TRACK_USAGE_MUTATION, { input: {
431
479
  workspaceId: record.workspaceId,
@@ -434,6 +482,8 @@ var AiCreditMeter = class {
434
482
  amount: record.amount,
435
483
  description: record.description,
436
484
  userId: record.userId,
485
+ ...record.billingAccountId ? { billingAccountId: record.billingAccountId } : {},
486
+ ...record.quotaAssignmentId ? { quotaAssignmentId: record.quotaAssignmentId } : {},
437
487
  hash: record.hash,
438
488
  metadata: record.metadata
439
489
  } });
@@ -543,4 +593,4 @@ var ai_credits_exports = /* @__PURE__ */ __exportAll({
543
593
  });
544
594
 
545
595
  export { AI_CREDIT_MAX_TOKENS_PER_REPORT as a, defaultAiCreditHashPrefix as c, isAiCreditInputError as i, encodeAiCreditHashComponent as l, AiCreditMeter as n, aiCreditIdempotencyHash as o, AiCreditInputError as r, aiCreditQuotaName as s, ai_credits_exports as t, validateAiTokenUsage as u };
546
- //# sourceMappingURL=ai-credits-xxfwGpHS.js.map
596
+ //# sourceMappingURL=ai-credits-B_IPVIu1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ai-credits-B_IPVIu1.js","names":["sdkLogger"],"sources":["../src/ai-credits/validation.ts","../src/ai-credits/errors.ts","../src/ai-credits/meter.ts","../src/ai-credits/index.ts"],"sourcesContent":["/**\n * Pure rules for AI-credit metering: report validation, quota naming and the\n * idempotency hash. Dependency-free so products can unit-test against them.\n */\nimport type { AiTokenUsageReport } from './types.js';\n\n/**\n * Sanity ceiling for one turn's token counts. Real turns stay far below it even\n * with a large context window; credits price at roughly one credit per input\n * token, so an unbounded count would be an unbounded charge.\n */\nexport const AI_CREDIT_MAX_TOKENS_PER_REPORT = 2_000_000;\n\n/** Stable machine-readable reasons a report is rejected. */\nexport type AiTokenUsageViolation =\n | 'SESSION_ID_REQUIRED'\n | 'MESSAGE_ID_REQUIRED'\n | 'MODEL_REQUIRED'\n | 'TOKEN_COUNTS_NOT_INTEGERS'\n | 'TOKEN_COUNTS_NEGATIVE'\n | 'TOKEN_COUNTS_EXCEED_MAXIMUM';\n\nexport interface AiTokenUsageValidationError {\n code: AiTokenUsageViolation;\n /** Operator-readable reason. Products usually map it to their i18n key by `code`. */\n message: string;\n}\n\nfunction blank(value: string | null | undefined): boolean {\n return typeof value !== 'string' || value.trim().length === 0;\n}\n\n/**\n * Validate a reported turn. Returns null when it is acceptable, otherwise the\n * first violation. Does not throw, so callers choose the error type (VC raises\n * an i18n'd BAD_USER_INPUT, HB a client-facing error).\n *\n * `messageId` is required, not optional: without it the idempotency hash\n * collapses to the session and only the first turn of a conversation would ever\n * be charged. `model` is required because it selects the per-token price.\n */\nexport function validateAiTokenUsage(\n report: Partial<Pick<AiTokenUsageReport, 'sessionId' | 'messageId' | 'model'>> &\n Pick<AiTokenUsageReport, 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'>,\n maxTokensPerReport: number = AI_CREDIT_MAX_TOKENS_PER_REPORT\n): AiTokenUsageValidationError | null {\n const { sessionId, messageId, model, inputTokens, outputTokens } = report;\n // Cache counts are optional; an omitted/null count is zero. They are checked and\n // summed with the ordinary counts, because they are priced too.\n const counts = [inputTokens, outputTokens, report.cacheReadTokens ?? 0, report.cacheWriteTokens ?? 0];\n\n if (blank(sessionId)) return { code: 'SESSION_ID_REQUIRED', message: 'sessionId is required.' };\n if (blank(messageId)) return { code: 'MESSAGE_ID_REQUIRED', message: 'messageId is required.' };\n if (blank(model)) return { code: 'MODEL_REQUIRED', message: 'model is required.' };\n if (counts.some((count) => !Number.isSafeInteger(count))) {\n return { code: 'TOKEN_COUNTS_NOT_INTEGERS', message: 'Token counts must be integers.' };\n }\n if (counts.some((count) => count < 0)) {\n return { code: 'TOKEN_COUNTS_NEGATIVE', message: 'Token counts must be non-negative.' };\n }\n if (counts.reduce((sum, count) => sum + count, 0) > maxTokensPerReport) {\n return {\n code: 'TOKEN_COUNTS_EXCEED_MAXIMUM',\n message: `Reported tokens exceed the per-report maximum of ${maxTokensPerReport}.`,\n };\n }\n return null;\n}\n\n/**\n * The quota a product's AI credits draw from: `<productId>.ai.credits`\n * (`vibecontrols.ai.credits`, `healthybowl.ai.credits`, …). Must match what\n * billing seeds exactly — a name mismatch reads as \"not provisioned\".\n */\nexport function aiCreditQuotaName(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('aiCreditQuotaName requires a productId');\n return `${id}.ai.credits`;\n}\n\n/** Default hash prefix for a product: `<productId>:aicredit`. */\nexport function defaultAiCreditHashPrefix(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('defaultAiCreditHashPrefix requires a productId');\n return `${id}:aicredit`;\n}\n\n/**\n * Make a hash component unambiguous when joined with `:`. Ids are `ID!` and may\n * contain colons, so raw joining would let `(\"a:b\",\"c\")` and `(\"a\",\"b:c\")`\n * collide — and activity's unique `usage_records.hash` would then drop the second,\n * genuinely different turn as a replay. `%` is escaped first so the escape itself\n * cannot collide. A no-op for ids containing neither character (uuids, `msg_…`),\n * so existing hashes are reproduced byte-for-byte.\n */\nexport function encodeAiCreditHashComponent(value: string): string {\n return value.replaceAll('%', '%25').replaceAll(':', '%3A');\n}\n\n/**\n * Idempotency hash for one turn: `<prefix>:<sessionId>:<messageId>`.\n *\n * activity-svc's unique index is on `hash` ALONE, shared by every product, so\n * the prefix must be product-namespaced. Products that already write a different\n * prefix must keep passing it (`aicredit` for VibeControls, `hb-assistant` for\n * HealthyBowl) — changing a prefix re-hashes every in-flight turn, so a client\n * retry across the deploy would be charged twice.\n */\nexport function aiCreditIdempotencyHash(prefix: string, sessionId: string, messageId: string): string {\n const head = prefix.trim();\n if (!head) throw new Error('aiCreditIdempotencyHash requires a prefix');\n if (blank(sessionId) || blank(messageId)) {\n throw new Error('aiCreditIdempotencyHash requires a sessionId and a messageId');\n }\n return `${head}:${encodeAiCreditHashComponent(sessionId)}:${encodeAiCreditHashComponent(messageId)}`;\n}\n","/**\n * Errors raised by the AI-credit meter. Only caller mistakes throw; billing and\n * recording failures are returned as a skipped charge (see `AiCreditMeter.charge`).\n */\nimport type { AiTokenUsageViolation } from './validation.js';\n\nexport type AiCreditInputErrorCode = AiTokenUsageViolation | 'WORKSPACE_ID_REQUIRED' | 'FROZEN_CREDITS_INVALID';\n\n/** A malformed report or missing workspace context. Map it to BAD_USER_INPUT. */\nexport class AiCreditInputError extends Error {\n readonly code: AiCreditInputErrorCode;\n /** GraphQL error code products should surface. */\n readonly graphqlCode = 'BAD_USER_INPUT';\n\n constructor(code: AiCreditInputErrorCode, message: string) {\n super(message);\n this.name = 'AiCreditInputError';\n this.code = code;\n }\n}\n\nexport function isAiCreditInputError(error: unknown): error is AiCreditInputError {\n return error instanceof AiCreditInputError;\n}\n","/**\n * AiCreditMeter — cost-weighted, idempotent AI-credit charging for an assistant turn.\n *\n * VibeControls (`utils/usage-billing.ts` + `modules/aicredit`) and HealthyBowl\n * (`utils/ai-credit-usage.ts` + `HealthyBowlAiCreditProvider`) each carried their\n * own copy of this path. This is the shared version, built on the path that is\n * proven to record in prod:\n *\n * 1. **Price** — `quoteAiCredits(model, inputTokens, outputTokens[, cacheReadTokens,\n * cacheWriteTokens])` on global-billing-svc, cross-layer through the be-sdk `GatewayClient`\n * (`GLOBAL_PUBLIC_GATEWAY_URL`, which resolves to the peer VPC's internal ALB\n * over the Route53 private zone). The amount is always computed server-side\n * from billing's per-model prices; a client never supplies it.\n * 2. **Record** — wspace-activity-svc `trackUsage` on the workspace's\n * `WorkspaceQuotaAssignment`, same-layer through the wspace INTERNAL gateway\n * (`WSPACE_INT_GATEWAY_URL`) with `x-workspace-id`. Activity resolves the\n * assignment itself and dedupes on the unique `usage_records.hash`, so a\n * replayed report for the same session + message is a no-op charge.\n *\n * Contract:\n * - {@link AiCreditMeter.charge} validates first and THROWS\n * {@link AiCreditInputError} for a malformed report (a caller bug worth\n * surfacing). After that it never throws: the user already has the answer, so a\n * metering failure must not become a user-visible error. Every un-charged\n * outcome is returned as `status: 'skipped'` with a reason AND logged.\n * - A null quote skips the charge: under-charging during an outage is\n * recoverable, charging an invented amount is not.\n * - Recording only counts as success when activity answers `trackUsage: true`.\n *\n * The meter is a METER, not a gate. Products that need a pre-flight gate keep a\n * `@usage(checkQuota: true, trackUsage: false)` field (VC `checkAiCredits`), or\n * call {@link AiCreditMeter.readGate}, which defers the final refusal to the same\n * activity check that `@usage` runs. The charging field must carry NO\n * `@usage(trackUsage)` directive, or the turn is charged twice.\n *\n * Enforcement rules live in wspace-activity-svc only. In particular the\n * `TEST_ENTITLEMENT_WORKSPACE_IDS` doctor-workspace entitlement is applied by\n * activity's `checkWorkspaceQuota`; a gate built on the raw assignment rows\n * ({@link AiCreditMeter.readUsage}) would never see it. The entitlement waives\n * the refusal only: {@link AiCreditMeter.charge} still records every turn.\n *\n * @example\n * ```ts\n * import { AiCreditMeter } from '@burdenoff/be-sdk/ai-credits';\n *\n * const meter = new AiCreditMeter({\n * productId: 'vibecontrols',\n * serviceName: 'wspace-vibecontrols-svc',\n * hashPrefix: 'aicredit', // VC's existing prefix — never change a live prefix\n * });\n *\n * const result = await meter.charge({\n * workspaceId: requireWorkspaceId(ctx.workspace?.id),\n * userId: ctx.actor?.id,\n * sessionId: input.sessionId,\n * messageId: input.messageId,\n * model: input.model,\n * inputTokens: input.inputTokens,\n * outputTokens: input.outputTokens,\n * });\n * ```\n */\nimport type { GraphQLRequestOptions } from '../gateway/types.js';\nimport { logger as sdkLogger } from '../logger/index.js';\n\nimport { AiCreditInputError } from './errors.js';\nimport type {\n AiCreditAllowance,\n AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditGate,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditQuoteInput,\n AiCreditSkipReason,\n ReadUsageSettlementInput,\n UsageSettlementReceipt,\n UsageSettlementStatus,\n WorkspaceQuotaUsage,\n} from './types.js';\nimport {\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n aiCreditIdempotencyHash,\n aiCreditQuotaName,\n defaultAiCreditHashPrefix,\n validateAiTokenUsage,\n} from './validation.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\nconst QUOTE_AI_CREDITS_QUERY = `query AiCreditMeterQuote($model: String!, $inputTokens: Int!, $outputTokens: Int!) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens)\n}`;\n\nconst QUOTE_AI_CREDITS_WITH_CACHE_QUERY = `query AiCreditMeterQuoteWithCache($model: String!, $inputTokens: Int!, $outputTokens: Int!, $cacheReadTokens: Int, $cacheWriteTokens: Int) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens, cacheReadTokens: $cacheReadTokens, cacheWriteTokens: $cacheWriteTokens)\n}`;\n\nconst CACHE_PRICING_CAPABILITY_QUERY = `query AiCreditMeterCachePricingSupported {\n aiCacheTokenPricingSupported\n}`;\n\nconst TRACK_USAGE_MUTATION = `mutation AiCreditMeterTrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n}`;\n\nconst CHECK_WORKSPACE_QUOTA_QUERY = `query AiCreditMeterCheckQuota($workspaceId: ID!, $quotaName: String!, $amount: Float) {\n checkWorkspaceQuota(workspaceId: $workspaceId, quotaName: $quotaName, amount: $amount) { allowed assignmentId limitLeft noLimit }\n}`;\n\n/** Amount the pre-flight gate asks activity about: one credit, the smallest chargeable unit. */\nconst GATE_PROBE_AMOUNT = 1;\n\nconst WORKSPACE_QUOTA_ASSIGNMENTS_QUERY = `query AiCreditMeterQuotaAssignments($workspaceId: ID!) {\n workspaceQuotaAssignments(workspaceId: $workspaceId) { quotaName used limit noLimit isActive }\n}`;\n\nconst GET_USAGE_SETTLEMENT_QUERY = `query AiCreditMeterGetUsageSettlement($hash: String!, $quotaName: String!, $productId: String!, $payer: UsageSettlementPayerInput) {\n getUsageSettlement(hash: $hash, quotaName: $quotaName, productId: $productId, payer: $payer) { id status amount }\n}`;\n\nconst VALID_SETTLEMENT_STATUSES: ReadonlySet<string> = new Set<UsageSettlementStatus>(['pending', 'done', 'failed']);\n\nconst USAGE_HOLD_MARKER = 'USAGE_RECORD_HELD_FOR_REVIEW';\n\nexport interface AiCreditMeterOptions {\n /** Product id stamped on usage records, e.g. `vibecontrols`. */\n productId: string;\n /** This service's name; sent as the service identity. Default `SERVICE_IDENTITY` / `SERVICE_NAME` env. */\n serviceName?: string;\n /** Quota to charge. Default `<productId>.ai.credits`. */\n quotaName?: string;\n /**\n * Idempotency-hash prefix. Default `<productId>:aicredit`. A product that already\n * records under another prefix MUST keep it (see {@link aiCreditIdempotencyHash}).\n */\n hashPrefix?: string;\n /** wspace internal gateway URL. Default `WSPACE_INT_GATEWAY_URL` env (read per call). */\n activityGatewayUrl?: string;\n /** Cross-layer global gateway URL for pricing. Default `GLOBAL_PUBLIC_GATEWAY_URL` env (read per call). */\n billingGatewayUrl?: string;\n /**\n * Pricing transport, or a factory for one. Default: a lazily constructed be-sdk\n * `GatewayClient` bound to {@link billingGatewayUrl}, rebuilt if the URL changes.\n */\n pricingClient?:\n AiCreditPricingTransport | ((url: string) => AiCreditPricingTransport | Promise<AiCreditPricingTransport>);\n /** `fetch` for the activity-svc calls. Default: the global `fetch`. */\n fetch?: AiCreditFetch;\n /** Per-request timeout. Default 5s. */\n requestTimeoutMs?: number;\n /** Per-report token ceiling. Default {@link AI_CREDIT_MAX_TOKENS_PER_REPORT}. */\n maxTokensPerReport?: number;\n /** Optional pre-charge hook (e.g. a report-rate ceiling). */\n guard?: AiCreditChargeGuard;\n /** Logger. Default the be-sdk logger. */\n logger?: AiCreditLogger;\n}\n\ninterface GraphQLBody<T> {\n data?: T | null;\n errors?: { message: string }[] | null;\n}\n\ninterface AssignmentRow {\n quotaName: string;\n used: number;\n limit: number | null;\n noLimit: boolean;\n isActive: boolean;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction requireNonEmpty(value: string | undefined, field: string): string {\n const trimmed = value?.trim() ?? '';\n if (!trimmed) throw new Error(`AiCreditMeter: ${field} is required`);\n return trimmed;\n}\n\n/** Same-layer auth header the wspace internal gateway expects from in-cluster callers. */\nfunction internalServiceHeaders(): Record<string, string> {\n const token = process.env['TRUSTED_GATEWAY_TOKEN'] || process.env['INTERNAL_SERVICE_TOKEN'];\n return token ? { 'x-internal-service-token': token } : {};\n}\n\nexport class AiCreditMeter {\n readonly productId: string;\n readonly quotaName: string;\n readonly hashPrefix: string;\n private readonly serviceName: string | undefined;\n private readonly activityGatewayUrl: string | undefined;\n private readonly billingGatewayUrl: string | undefined;\n private readonly pricingOption: AiCreditMeterOptions['pricingClient'];\n private readonly fetchImpl: AiCreditFetch;\n private readonly requestTimeoutMs: number;\n private readonly maxTokensPerReport: number;\n private readonly guard: AiCreditChargeGuard | undefined;\n private readonly log: AiCreditLogger;\n private pricing: { url: string; client: Promise<AiCreditPricingTransport> } | null = null;\n\n constructor(options: AiCreditMeterOptions) {\n this.productId = requireNonEmpty(options.productId, 'productId');\n this.quotaName = options.quotaName?.trim() || aiCreditQuotaName(this.productId);\n this.hashPrefix = options.hashPrefix?.trim() || defaultAiCreditHashPrefix(this.productId);\n this.serviceName = options.serviceName?.trim() || undefined;\n this.activityGatewayUrl = options.activityGatewayUrl?.trim() || undefined;\n this.billingGatewayUrl = options.billingGatewayUrl?.trim() || undefined;\n this.pricingOption = options.pricingClient;\n this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));\n this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n if (!Number.isSafeInteger(this.requestTimeoutMs) || this.requestTimeoutMs <= 0) {\n throw new Error('AiCreditMeter: requestTimeoutMs must be a positive integer');\n }\n this.maxTokensPerReport = options.maxTokensPerReport ?? AI_CREDIT_MAX_TOKENS_PER_REPORT;\n if (!Number.isSafeInteger(this.maxTokensPerReport) || this.maxTokensPerReport <= 0) {\n throw new Error('AiCreditMeter: maxTokensPerReport must be a positive integer');\n }\n this.guard = options.guard;\n this.log = options.logger ?? sdkLogger;\n }\n\n /** The idempotency hash this meter records a turn under. */\n hashFor(sessionId: string, messageId: string): string {\n return aiCreditIdempotencyHash(this.hashPrefix, sessionId, messageId);\n }\n\n /**\n * Server-side price of one model call in credits, from billing's per-model\n * token table. Returns null — after logging why — when it cannot be priced.\n *\n * When the turn reports cache counts, billing is first asked whether it prices\n * them (`aiCacheTokenPricingSupported`). If it does, the cache counts are priced\n * with its cache-token prices; if it does not (an older billing, or the probe\n * fails), the turn is priced on input/output alone. The answer is not cached,\n * so a billing rollback is picked up on the next report.\n */\n async quote(input: AiCreditQuoteInput): Promise<number | null> {\n const url = this.billingGatewayUrl ?? process.env['GLOBAL_PUBLIC_GATEWAY_URL']?.trim();\n if (!url) {\n this.log.warn('[AiCreditMeter] GLOBAL_PUBLIC_GATEWAY_URL not set; cannot price AI credits', {\n productId: this.productId,\n model: input.model,\n });\n return null;\n }\n try {\n const client = await this.getPricingClient(url);\n const hasCacheCounts = input.cacheReadTokens != null || input.cacheWriteTokens != null;\n const priceCache = hasCacheCounts && (await this.supportsCachePricing(client, input.model));\n const response = await client.crossLayerQuery<{ quoteAiCredits?: number | null }>({\n ...this.pricingRequest(),\n query: priceCache ? QUOTE_AI_CREDITS_WITH_CACHE_QUERY : QUOTE_AI_CREDITS_QUERY,\n variables: {\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n ...(priceCache\n ? { cacheReadTokens: input.cacheReadTokens ?? 0, cacheWriteTokens: input.cacheWriteTokens ?? 0 }\n : {}),\n },\n });\n if (response.errors?.length) {\n throw new Error(response.errors.map((error) => error.message).join(', '));\n }\n const credits = response.data?.quoteAiCredits;\n if (typeof credits !== 'number' || !Number.isFinite(credits) || credits < 0) {\n throw new Error(`quoteAiCredits returned no usable value (${String(credits)})`);\n }\n return credits;\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to quote AI credits; skipping charge', {\n productId: this.productId,\n model: input.model,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Validate, price and record one completed assistant turn. See the module\n * header for the contract: throws only {@link AiCreditInputError}.\n */\n async charge(input: AiCreditChargeInput): Promise<AiCreditChargeResult> {\n const workspaceId = input.workspaceId?.trim() ?? '';\n if (!workspaceId) {\n throw new AiCreditInputError('WORKSPACE_ID_REQUIRED', 'This request has no workspace context.');\n }\n const invalid = validateAiTokenUsage(input, this.maxTokensPerReport);\n if (invalid) throw new AiCreditInputError(invalid.code, invalid.message);\n if (\n input.frozenCredits != null &&\n (typeof input.frozenCredits !== 'number' || !Number.isFinite(input.frozenCredits) || input.frozenCredits < 0)\n ) {\n throw new AiCreditInputError('FROZEN_CREDITS_INVALID', 'frozenCredits must be a finite non-negative number.');\n }\n\n const hash = this.hashFor(input.sessionId, input.messageId);\n const logFields = {\n productId: this.productId,\n quotaName: this.quotaName,\n workspaceId,\n sessionId: input.sessionId,\n messageId: input.messageId,\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n };\n const skipped = (reason: AiCreditSkipReason, credits: number | null, detail?: string): AiCreditChargeResult => {\n this.log.warn(`[AiCreditMeter] turn not charged (${reason})`, { ...logFields, credits, detail });\n return { status: 'skipped', reason, credits, hash, quotaName: this.quotaName, ...(detail ? { detail } : {}) };\n };\n\n if (this.guard) {\n try {\n const verdict = await this.guard({ ...input, workspaceId });\n if (!verdict.allow) return skipped('GUARD_REFUSED', null, verdict.detail);\n } catch (error) {\n // Fail open: a guard's infrastructure blip must not silently stop metering.\n this.log.warn('[AiCreditMeter] charge guard threw; charging anyway', {\n ...logFields,\n error: errorMessage(error),\n });\n }\n }\n\n const credits = input.frozenCredits != null ? input.frozenCredits : await this.quote(input);\n if (credits === null) return skipped('NOT_PRICED', null);\n if (credits <= 0) return skipped('ZERO_COST', credits);\n\n const billingAccountId = input.billingAccountId?.trim() || undefined;\n const quotaAssignmentId = input.quotaAssignmentId?.trim() || undefined;\n\n try {\n await this.trackUsage({\n workspaceId,\n amount: credits,\n description: input.description?.trim() || `AI credits for session ${input.sessionId}`,\n userId: input.userId ?? undefined,\n ...(billingAccountId ? { billingAccountId } : {}),\n ...(quotaAssignmentId ? { quotaAssignmentId } : {}),\n hash,\n metadata: {\n model: input.model,\n sessionId: input.sessionId,\n messageId: input.messageId,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n ...(input.cacheReadTokens != null || input.cacheWriteTokens != null\n ? { cacheReadTokens: input.cacheReadTokens ?? 0, cacheWriteTokens: input.cacheWriteTokens ?? 0 }\n : {}),\n credits,\n ...input.metadata,\n },\n });\n } catch (error) {\n const detail = errorMessage(error);\n if (detail.includes(USAGE_HOLD_MARKER)) {\n return skipped('HELD_FOR_REVIEW', credits, detail);\n }\n return skipped('RECORD_FAILED', credits, detail);\n }\n\n this.log.info(`[AiCreditMeter] Charged ${credits} AI credits for session ${input.sessionId}`, {\n ...logFields,\n credits,\n });\n return { status: 'charged', credits, hash, quotaName: this.quotaName };\n }\n\n /**\n * Read the quota's ENFORCED usage from wspace-activity-svc — the ledger the\n * charge lands on and the gateway's `@usage` check reads. All active rows are\n * summed, because a workspace can hold several (plan + add-ons, or duplicate\n * rows) and `checkWorkspaceQuota` sums them; a single-row read under-reports.\n *\n * Returns null (never throws) when activity is unreachable or no assignment\n * exists, so a screen can show \"not provisioned\" instead of a confident zero.\n */\n async readUsage(workspaceId: string, quotaName: string = this.quotaName): Promise<WorkspaceQuotaUsage | null> {\n try {\n const data = await this.activityRequest<{ workspaceQuotaAssignments?: AssignmentRow[] | null }>(\n workspaceId,\n WORKSPACE_QUOTA_ASSIGNMENTS_QUERY,\n { workspaceId: workspaceId.trim() }\n );\n const rows = (data.workspaceQuotaAssignments ?? []).filter((row) => row.isActive && row.quotaName === quotaName);\n if (rows.length === 0) return null;\n const used = rows.reduce((sum, row) => sum + (Number.isFinite(row.used) ? row.used : 0), 0);\n const noLimit = rows.some((row) => row.noLimit);\n const limit = noLimit ? null : rows.reduce((sum, row) => sum + (row.limit ?? 0), 0);\n return {\n quotaName,\n used,\n limit,\n noLimit,\n remaining: limit === null ? null : Math.max(limit - used, 0),\n assignments: rows.length,\n };\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to read workspace quota usage', {\n productId: this.productId,\n quotaName,\n workspaceId,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Ask wspace-activity-svc whether `amount` of the quota may be spent — the same\n * `checkWorkspaceQuota` the gateway's `@usage` gate runs, so every activity\n * enforcement rule (row aggregation, renamed keys, the\n * `TEST_ENTITLEMENT_WORKSPACE_IDS` entitlement) applies.\n *\n * Returns null (never throws) when activity cannot answer.\n */\n async checkAllowance(\n workspaceId: string,\n options: { amount?: number; quotaName?: string } = {}\n ): Promise<AiCreditAllowance | null> {\n const quotaName = options.quotaName ?? this.quotaName;\n const amount = options.amount ?? GATE_PROBE_AMOUNT;\n try {\n if (!Number.isFinite(amount) || amount < 0) throw new Error('amount must be a non-negative finite number');\n const data = await this.activityRequest<{\n checkWorkspaceQuota?: {\n allowed?: boolean | null;\n assignmentId?: string | null;\n limitLeft?: number | null;\n noLimit?: boolean | null;\n } | null;\n }>(workspaceId, CHECK_WORKSPACE_QUOTA_QUERY, { workspaceId: workspaceId.trim(), quotaName, amount });\n const result = data.checkWorkspaceQuota;\n if (!result || typeof result.allowed !== 'boolean') {\n throw new Error('checkWorkspaceQuota returned no verdict');\n }\n return {\n quotaName,\n allowed: result.allowed,\n provisioned: result.assignmentId != null,\n noLimit: result.noLimit === true,\n limitLeft: typeof result.limitLeft === 'number' && Number.isFinite(result.limitLeft) ? result.limitLeft : null,\n };\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to check workspace quota allowance', {\n productId: this.productId,\n quotaName,\n workspaceId,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Pre-flight gate for an AI call. Reads the ledger standing\n * ({@link readUsage}); when it shows a limited budget spent, the refusal is\n * confirmed with activity's {@link checkAllowance} before it is returned.\n *\n * - not provisioned or unreadable -> not exhausted (the call is not gated);\n * - budget left, or no limit -> not exhausted (no second call);\n * - spent and activity refuses -> exhausted;\n * - spent and activity cannot answer -> exhausted (fail closed on a known\n * spent budget, as before this check existed);\n * - spent but activity allows -> not exhausted, `entitled: true`. This\n * is a test-entitled doctor workspace; the call proceeds and\n * {@link charge} still records it.\n */\n async readGate(workspaceId: string, quotaName: string = this.quotaName): Promise<AiCreditGate> {\n const usage = await this.readUsage(workspaceId, quotaName);\n const spent = usage !== null && !usage.noLimit && (usage.remaining ?? 0) <= 0;\n if (!spent) return { usage, exhausted: false, entitled: false };\n\n const allowance = await this.checkAllowance(workspaceId, { quotaName });\n if (allowance?.allowed) {\n this.log.info('[AiCreditMeter] budget spent but activity allows the call (test entitlement); not refused', {\n productId: this.productId,\n quotaName,\n workspaceId,\n used: usage.used,\n limit: usage.limit,\n });\n return { usage, exhausted: false, entitled: true };\n }\n return { usage, exhausted: true, entitled: false };\n }\n\n /**\n * Read the payer-bound usage settlement receipt directly from wspace-activity-svc\n * (`getUsageSettlement`).\n *\n * Returns `null` ONLY when Activity explicitly confirms no matching record exists\n * for the workspace, hash, quota, product and payer scope. Throws on transport,\n * GraphQL, or malformed-response errors so a caller never mistakes an outage for\n * a missing settlement record.\n */\n async readSettlement(input: ReadUsageSettlementInput): Promise<UsageSettlementReceipt | null> {\n const workspaceId = input.workspaceId?.trim() ?? '';\n if (!workspaceId) {\n throw new AiCreditInputError('WORKSPACE_ID_REQUIRED', 'This request has no workspace context.');\n }\n const hash = input.hash?.trim() ?? '';\n if (!hash) {\n throw new Error('AiCreditMeter.readSettlement: hash is required');\n }\n const payer = input.payer\n ? {\n billingAccountId: requireNonEmpty(input.payer.billingAccountId, 'payer.billingAccountId'),\n ...(input.payer.quotaAssignmentId != null\n ? { quotaAssignmentId: requireNonEmpty(input.payer.quotaAssignmentId, 'payer.quotaAssignmentId') }\n : {}),\n }\n : undefined;\n\n const data = await this.activityRequest<{\n getUsageSettlement?: { id?: unknown; status?: unknown; amount?: unknown } | null;\n }>(workspaceId, GET_USAGE_SETTLEMENT_QUERY, {\n hash,\n quotaName: this.quotaName,\n productId: this.productId,\n ...(payer ? { payer } : {}),\n });\n\n const receipt = data.getUsageSettlement;\n if (receipt == null) return null;\n if (\n typeof receipt.id !== 'string' ||\n !receipt.id.trim() ||\n typeof receipt.status !== 'string' ||\n !VALID_SETTLEMENT_STATUSES.has(receipt.status) ||\n typeof receipt.amount !== 'number' ||\n !Number.isFinite(receipt.amount) ||\n receipt.amount < 0\n ) {\n throw new Error('getUsageSettlement returned a malformed settlement receipt');\n }\n return {\n id: receipt.id,\n status: receipt.status as UsageSettlementStatus, // Validated against VALID_SETTLEMENT_STATUSES above.\n amount: receipt.amount,\n };\n }\n\n private async trackUsage(record: {\n workspaceId: string;\n amount: number;\n description: string;\n userId: string | undefined;\n billingAccountId?: string;\n quotaAssignmentId?: string;\n hash: string;\n metadata: Record<string, unknown>;\n }): Promise<void> {\n const data = await this.activityRequest<{ trackUsage?: boolean | null }>(record.workspaceId, TRACK_USAGE_MUTATION, {\n input: {\n // Sent in the input AND as x-workspace-id: activity takes the workspace from request\n // context, and the @rbac directive resolves input.workspaceId.\n workspaceId: record.workspaceId,\n quotaName: this.quotaName,\n productId: this.productId,\n amount: record.amount,\n description: record.description,\n userId: record.userId,\n ...(record.billingAccountId ? { billingAccountId: record.billingAccountId } : {}),\n ...(record.quotaAssignmentId ? { quotaAssignmentId: record.quotaAssignmentId } : {}),\n hash: record.hash,\n metadata: record.metadata,\n },\n });\n if (data.trackUsage !== true) {\n throw new Error(`trackUsage did not confirm the record (returned ${String(data.trackUsage)})`);\n }\n }\n\n private async activityRequest<T>(workspaceId: string, query: string, variables: Record<string, unknown>): Promise<T> {\n const url = this.activityGatewayUrl ?? process.env['WSPACE_INT_GATEWAY_URL']?.trim();\n if (!url) throw new Error('WSPACE_INT_GATEWAY_URL not set; cannot reach wspace-activity-svc');\n const workspace = workspaceId.trim();\n if (!workspace) throw new Error('workspaceId is required');\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.requestTimeoutMs);\n try {\n const response = await this.fetchImpl(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-actor-type': 'service',\n 'x-actor-id': this.resolveServiceName(),\n ...internalServiceHeaders(),\n 'x-workspace-id': workspace,\n },\n body: JSON.stringify({ query, variables }),\n signal: controller.signal,\n });\n if (!response.ok) {\n const body = await response.text().catch(() => response.statusText);\n throw new Error(`activity request failed with HTTP ${response.status}: ${body.slice(0, 500)}`);\n }\n const result = (await response.json()) as GraphQLBody<T>;\n if (result.errors?.length) {\n throw new Error(result.errors.map((error) => error.message).join(', '));\n }\n if (!result.data) throw new Error('activity response did not include data');\n return result.data;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n /** Options shared by every pricing call. */\n private pricingRequest(): Pick<GraphQLRequestOptions, 'headers' | 'timeout' | 'skipRetry' | 'skipCircuitBreaker'> {\n return {\n // Only the actor type: the signed service JWT is the identity. An x-actor-id on a\n // service token is read as \"on behalf of\" and downgrades the actor.\n headers: { 'x-actor-type': 'service' },\n timeout: this.requestTimeoutMs,\n skipRetry: true,\n skipCircuitBreaker: true,\n };\n }\n\n /** Whether billing prices cache counts. Any failure reads as \"no\" and falls back to input/output. */\n private async supportsCachePricing(client: AiCreditPricingTransport, model: string): Promise<boolean> {\n try {\n const response = await client.crossLayerQuery<{ aiCacheTokenPricingSupported?: boolean | null }>({\n ...this.pricingRequest(),\n query: CACHE_PRICING_CAPABILITY_QUERY,\n variables: {},\n });\n if (response.data?.aiCacheTokenPricingSupported === true) return true;\n } catch {\n // Logged below; the turn is still priced on input/output.\n }\n this.log.warn('[AiCreditMeter] billing does not price cache tokens; quoting input/output only', {\n productId: this.productId,\n model,\n });\n return false;\n }\n\n private resolveServiceName(): string {\n return (\n this.serviceName ||\n process.env['SERVICE_IDENTITY'] ||\n process.env['SERVICE_NAME'] ||\n `wspace-${this.productId}-svc`\n );\n }\n\n private getPricingClient(url: string): Promise<AiCreditPricingTransport> {\n // Rebuilt when the URL changes, so a client bound to a stale URL cannot keep failing.\n if (this.pricing && this.pricing.url === url) return this.pricing.client;\n const option = this.pricingOption;\n const client = (async (): Promise<AiCreditPricingTransport> => {\n if (option && typeof option === 'function') return option(url);\n if (option) return option;\n const gateway = await import('../gateway/client.js');\n const identity = this.resolveServiceName();\n return new gateway.GatewayClient({\n // This service's OWN layer; the be-sdk signs the service JWT because the call leaves it.\n layer: 'wspace',\n serviceName: identity,\n serviceIdentity: identity,\n crossLayerGatewayUrl: url,\n timeout: this.requestTimeoutMs,\n enableLogging: process.env['NODE_ENV'] !== 'production',\n });\n })();\n this.pricing = { url, client };\n // A failed construction must not be cached forever.\n client.catch(() => {\n if (this.pricing?.client === client) this.pricing = null;\n });\n return client;\n }\n}\n","/**\n * @burdenoff/be-sdk/ai-credits\n *\n * Shared cost-weighted, idempotent AI-credit metering for assistant turns:\n * billing prices the turn (`quoteAiCredits`), wspace-activity-svc records it on\n * the workspace quota (`trackUsage`, deduped by `<prefix>:<session>:<message>`).\n *\n * - {@link AiCreditMeter} — `charge`, `quote`, `readUsage`, `checkAllowance`,\n * `readGate`, `hashFor`.\n * - {@link validateAiTokenUsage}, {@link aiCreditIdempotencyHash},\n * {@link aiCreditQuotaName} — the pure rules, for products' own tests and resolvers.\n *\n * @example\n * ```ts\n * import { AiCreditMeter, isAiCreditInputError } from '@burdenoff/be-sdk/ai-credits';\n *\n * const meter = new AiCreditMeter({ productId: 'healthybowl', hashPrefix: 'hb-assistant' });\n * const result = await meter.charge({ workspaceId, userId, sessionId, messageId, model, inputTokens, outputTokens });\n * ```\n */\n\nexport {\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n aiCreditIdempotencyHash,\n aiCreditQuotaName,\n defaultAiCreditHashPrefix,\n encodeAiCreditHashComponent,\n validateAiTokenUsage,\n type AiTokenUsageValidationError,\n type AiTokenUsageViolation,\n} from './validation.js';\n\nexport { AiCreditInputError, isAiCreditInputError, type AiCreditInputErrorCode } from './errors.js';\n\nexport { AiCreditMeter, type AiCreditMeterOptions } from './meter.js';\n\nexport type {\n AiCreditAllowance,\n AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditGate,\n AiCreditGuardVerdict,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditQuoteInput,\n AiCreditSkipReason,\n AiTokenUsageReport,\n ReadUsageSettlementInput,\n UsageSettlementPayer,\n UsageSettlementReceipt,\n UsageSettlementStatus,\n WorkspaceQuotaUsage,\n} from './types.js';\n"],"mappings":";;;;;;;;;AAWA,MAAa,kCAAkC;AAiB/C,SAAS,MAAM,OAA2C;CACxD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,WAAW;AAC9D;;;;;;;;;;AAWA,SAAgB,qBACd,QAEA,qBAA6B,iCACO;CACpC,MAAM,EAAE,WAAW,WAAW,OAAO,aAAa,iBAAiB;CAGnE,MAAM,SAAS;EAAC;EAAa;EAAc,OAAO,mBAAmB;EAAG,OAAO,oBAAoB;CAAC;CAEpG,IAAI,MAAM,SAAS,GAAG,OAAO;EAAE,MAAM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,WAAW,CAAC;GACd,CAAC,EACW,CAAC,MAAM,iCAAiC,MAAM,OAAO;EACnE,QAAQ,CAER;EACA,KAAK,IAAI,KAAK,kFAAkF;GAC9F,WAAW,KAAK;GAChB;EACF,CAAC;EACD,OAAO;CACT;CAEA,AAAQ,qBAA6B;EACnC,OACE,KAAK,eACL,QAAQ,IAAI,uBACZ,QAAQ,IAAI,mBACZ,UAAU,KAAK,UAAU;CAE7B;CAEA,AAAQ,iBAAiB,KAAgD;EAEvE,IAAI,KAAK,WAAW,KAAK,QAAQ,QAAQ,KAAK,OAAO,KAAK,QAAQ;EAClE,MAAM,SAAS,KAAK;EACpB,MAAM,UAAU,YAA+C;GAC7D,IAAI,UAAU,OAAO,WAAW,YAAY,OAAO,OAAO,GAAG;GAC7D,IAAI,QAAQ,OAAO;GACnB,MAAM,UAAU,MAAM,OAAO,uBAAuB;GACpD,MAAM,WAAW,KAAK,mBAAmB;GACzC,OAAO,IAAI,QAAQ,cAAc;IAE/B,OAAO;IACP,aAAa;IACb,iBAAiB;IACjB,sBAAsB;IACtB,SAAS,KAAK;IACd,eAAe,QAAQ,IAAI,gBAAgB;GAC7C,CAAC;EACH,EAAC,CAAE;EACH,KAAK,UAAU;GAAE;GAAK;EAAO;EAE7B,OAAO,YAAY;GACjB,IAAI,KAAK,SAAS,WAAW,QAAQ,KAAK,UAAU;EACtD,CAAC;EACD,OAAO;CACT;AACF"}
@@ -12,10 +12,13 @@ type AiCreditQuoteInput = Pick<AiTokenUsageReport, 'model' | 'inputTokens' | 'ou
12
12
  interface AiCreditChargeInput extends AiTokenUsageReport {
13
13
  workspaceId: string;
14
14
  userId?: string | null;
15
+ billingAccountId?: string | null;
16
+ quotaAssignmentId?: string | null;
17
+ frozenCredits?: number | null;
15
18
  description?: string;
16
19
  metadata?: Record<string, unknown>;
17
20
  }
18
- type AiCreditSkipReason = 'NOT_PRICED' | 'ZERO_COST' | 'GUARD_REFUSED' | 'RECORD_FAILED';
21
+ type AiCreditSkipReason = 'NOT_PRICED' | 'ZERO_COST' | 'GUARD_REFUSED' | 'HELD_FOR_REVIEW' | 'RECORD_FAILED';
19
22
  type AiCreditChargeResult = {
20
23
  status: 'charged';
21
24
  credits: number;
@@ -62,6 +65,21 @@ interface AiCreditLogger {
62
65
  interface AiCreditPricingTransport {
63
66
  crossLayerQuery<T = unknown>(options: GraphQLRequestOptions): Promise<GraphQLResponse<T>>;
64
67
  }
68
+ type UsageSettlementStatus = 'pending' | 'done' | 'failed';
69
+ interface UsageSettlementPayer {
70
+ billingAccountId: string;
71
+ quotaAssignmentId?: string | null;
72
+ }
73
+ interface ReadUsageSettlementInput {
74
+ workspaceId: string;
75
+ hash: string;
76
+ payer?: UsageSettlementPayer | null;
77
+ }
78
+ interface UsageSettlementReceipt {
79
+ id: string;
80
+ status: UsageSettlementStatus;
81
+ amount: number;
82
+ }
65
83
  type AiCreditFetch = (url: string, init?: RequestInit) => Promise<Response>;
66
84
  declare const AI_CREDIT_MAX_TOKENS_PER_REPORT = 2000000;
67
85
  type AiTokenUsageViolation = 'SESSION_ID_REQUIRED' | 'MESSAGE_ID_REQUIRED' | 'MODEL_REQUIRED' | 'TOKEN_COUNTS_NOT_INTEGERS' | 'TOKEN_COUNTS_NEGATIVE' | 'TOKEN_COUNTS_EXCEED_MAXIMUM';
@@ -74,7 +92,7 @@ declare function aiCreditQuotaName(productId: string): string;
74
92
  declare function defaultAiCreditHashPrefix(productId: string): string;
75
93
  declare function encodeAiCreditHashComponent(value: string): string;
76
94
  declare function aiCreditIdempotencyHash(prefix: string, sessionId: string, messageId: string): string;
77
- type AiCreditInputErrorCode = AiTokenUsageViolation | 'WORKSPACE_ID_REQUIRED';
95
+ type AiCreditInputErrorCode = AiTokenUsageViolation | 'WORKSPACE_ID_REQUIRED' | 'FROZEN_CREDITS_INVALID';
78
96
  declare class AiCreditInputError extends Error {
79
97
  readonly code: AiCreditInputErrorCode;
80
98
  readonly graphqlCode = "BAD_USER_INPUT";
@@ -119,6 +137,7 @@ declare class AiCreditMeter {
119
137
  quotaName?: string;
120
138
  }): Promise<AiCreditAllowance | null>;
121
139
  readGate(workspaceId: string, quotaName?: string): Promise<AiCreditGate>;
140
+ readSettlement(input: ReadUsageSettlementInput): Promise<UsageSettlementReceipt | null>;
122
141
  private trackUsage;
123
142
  private activityRequest;
124
143
  private pricingRequest;
@@ -127,6 +146,6 @@ declare class AiCreditMeter {
127
146
  private getPricingClient;
128
147
  }
129
148
  declare namespace index_d_exports {
130
- export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditAllowance, AiCreditChargeGuard, AiCreditChargeInput, AiCreditChargeResult, AiCreditFetch, AiCreditGate, AiCreditGuardVerdict, AiCreditInputError, AiCreditInputErrorCode, AiCreditLogger, AiCreditMeter, AiCreditMeterOptions, AiCreditPricingTransport, AiCreditQuoteInput, AiCreditSkipReason, AiTokenUsageReport, AiTokenUsageValidationError, AiTokenUsageViolation, WorkspaceQuotaUsage, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage };
149
+ export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditAllowance, AiCreditChargeGuard, AiCreditChargeInput, AiCreditChargeResult, AiCreditFetch, AiCreditGate, AiCreditGuardVerdict, AiCreditInputError, AiCreditInputErrorCode, AiCreditLogger, AiCreditMeter, AiCreditMeterOptions, AiCreditPricingTransport, AiCreditQuoteInput, AiCreditSkipReason, AiTokenUsageReport, AiTokenUsageValidationError, AiTokenUsageViolation, ReadUsageSettlementInput, UsageSettlementPayer, UsageSettlementReceipt, UsageSettlementStatus, WorkspaceQuotaUsage, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage };
131
150
  }
132
- export { AiCreditPricingTransport as C, WorkspaceQuotaUsage as D, AiTokenUsageReport as E, AiCreditLogger as S, AiCreditSkipReason as T, AiCreditChargeInput as _, AiCreditInputErrorCode as a, AiCreditGate as b, AiTokenUsageValidationError as c, aiCreditQuotaName as d, defaultAiCreditHashPrefix as f, AiCreditChargeGuard as g, AiCreditAllowance as h, AiCreditInputError as i, AiTokenUsageViolation as l, validateAiTokenUsage as m, AiCreditMeter as n, isAiCreditInputError as o, encodeAiCreditHashComponent as p, AiCreditMeterOptions as r, AI_CREDIT_MAX_TOKENS_PER_REPORT as s, index_d_exports as t, aiCreditIdempotencyHash as u, AiCreditChargeResult as v, AiCreditQuoteInput as w, AiCreditGuardVerdict as x, AiCreditFetch as y };
151
+ export { UsageSettlementStatus as A, AiCreditPricingTransport as C, ReadUsageSettlementInput as D, AiTokenUsageReport as E, UsageSettlementPayer as O, AiCreditLogger as S, AiCreditSkipReason as T, AiCreditChargeInput as _, AiCreditInputErrorCode as a, AiCreditGate as b, AiTokenUsageValidationError as c, aiCreditQuotaName as d, defaultAiCreditHashPrefix as f, AiCreditChargeGuard as g, AiCreditAllowance as h, AiCreditInputError as i, WorkspaceQuotaUsage as j, UsageSettlementReceipt as k, AiTokenUsageViolation as l, validateAiTokenUsage as m, AiCreditMeter as n, isAiCreditInputError as o, encodeAiCreditHashComponent as p, AiCreditMeterOptions as r, AI_CREDIT_MAX_TOKENS_PER_REPORT as s, index_d_exports as t, aiCreditIdempotencyHash as u, AiCreditChargeResult as v, AiCreditQuoteInput as w, AiCreditGuardVerdict as x, AiCreditFetch as y };
package/dist/index.d.ts CHANGED
@@ -23,7 +23,7 @@ import { BillingPlanTransport, PlanTier, RESOURCE_CAP_DEFAULTS, ResourceCap, Res
23
23
  import { t as index_d_exports$23 } from "./index-CliOgq6L.js";
24
24
  import { t as index_d_exports$24 } from "./index-BaskMO3C.js";
25
25
  import { t as index_d_exports$8 } from "./index-ieSQpD9r.js";
26
- import { t as index_d_exports } from "./index-BJwHEzpN.js";
26
+ import { t as index_d_exports } from "./index-SAUnwdbo.js";
27
27
  import { o as index_d_exports$1 } from "./index-SvWwlTUC.js";
28
28
  import { t as index_d_exports$18 } from "./index-BMIMnp6T.js";
29
29
  import { t as index_d_exports$19 } from "./index-C5uEKchX.js";
package/dist/index.js CHANGED
@@ -25,7 +25,7 @@ import { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, co
25
25
  import { t as sharing_exports } from "./sharing-CflDsSJ-.js";
26
26
  import { t as tags_exports } from "./tags-C316oA9r.js";
27
27
  import { t as files_exports } from "./files-BISdM0fh.js";
28
- import { t as ai_credits_exports } from "./ai-credits-xxfwGpHS.js";
28
+ import { t as ai_credits_exports } from "./ai-credits-B_IPVIu1.js";
29
29
  import { a as TemporalClient, i as TemporalWorkerManager, n as TemporalWorker, o as TemporalClientFactory, r as TemporalWorkerFactory, t as TemporalModule } from "./temporal-B534uYK8.js";
30
30
  import { t as cache_exports } from "./cache-CU0uLwcS.js";
31
31
  import { t as middleware_exports } from "./middleware-Cq0zFMGp.js";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/be-sdk",
3
- "version": "2026.1202.2",
3
+ "version": "2026.1202.3",
4
4
  "description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1 +0,0 @@
1
- {"version":3,"file":"ai-credits-xxfwGpHS.js","names":["sdkLogger"],"sources":["../src/ai-credits/validation.ts","../src/ai-credits/errors.ts","../src/ai-credits/meter.ts","../src/ai-credits/index.ts"],"sourcesContent":["/**\n * Pure rules for AI-credit metering: report validation, quota naming and the\n * idempotency hash. Dependency-free so products can unit-test against them.\n */\nimport type { AiTokenUsageReport } from './types.js';\n\n/**\n * Sanity ceiling for one turn's token counts. Real turns stay far below it even\n * with a large context window; credits price at roughly one credit per input\n * token, so an unbounded count would be an unbounded charge.\n */\nexport const AI_CREDIT_MAX_TOKENS_PER_REPORT = 2_000_000;\n\n/** Stable machine-readable reasons a report is rejected. */\nexport type AiTokenUsageViolation =\n | 'SESSION_ID_REQUIRED'\n | 'MESSAGE_ID_REQUIRED'\n | 'MODEL_REQUIRED'\n | 'TOKEN_COUNTS_NOT_INTEGERS'\n | 'TOKEN_COUNTS_NEGATIVE'\n | 'TOKEN_COUNTS_EXCEED_MAXIMUM';\n\nexport interface AiTokenUsageValidationError {\n code: AiTokenUsageViolation;\n /** Operator-readable reason. Products usually map it to their i18n key by `code`. */\n message: string;\n}\n\nfunction blank(value: string | null | undefined): boolean {\n return typeof value !== 'string' || value.trim().length === 0;\n}\n\n/**\n * Validate a reported turn. Returns null when it is acceptable, otherwise the\n * first violation. Does not throw, so callers choose the error type (VC raises\n * an i18n'd BAD_USER_INPUT, HB a client-facing error).\n *\n * `messageId` is required, not optional: without it the idempotency hash\n * collapses to the session and only the first turn of a conversation would ever\n * be charged. `model` is required because it selects the per-token price.\n */\nexport function validateAiTokenUsage(\n report: Partial<Pick<AiTokenUsageReport, 'sessionId' | 'messageId' | 'model'>> &\n Pick<AiTokenUsageReport, 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'>,\n maxTokensPerReport: number = AI_CREDIT_MAX_TOKENS_PER_REPORT\n): AiTokenUsageValidationError | null {\n const { sessionId, messageId, model, inputTokens, outputTokens } = report;\n // Cache counts are optional; an omitted/null count is zero. They are checked and\n // summed with the ordinary counts, because they are priced too.\n const counts = [inputTokens, outputTokens, report.cacheReadTokens ?? 0, report.cacheWriteTokens ?? 0];\n\n if (blank(sessionId)) return { code: 'SESSION_ID_REQUIRED', message: 'sessionId is required.' };\n if (blank(messageId)) return { code: 'MESSAGE_ID_REQUIRED', message: 'messageId is required.' };\n if (blank(model)) return { code: 'MODEL_REQUIRED', message: 'model is required.' };\n if (counts.some((count) => !Number.isSafeInteger(count))) {\n return { code: 'TOKEN_COUNTS_NOT_INTEGERS', message: 'Token counts must be integers.' };\n }\n if (counts.some((count) => count < 0)) {\n return { code: 'TOKEN_COUNTS_NEGATIVE', message: 'Token counts must be non-negative.' };\n }\n if (counts.reduce((sum, count) => sum + count, 0) > maxTokensPerReport) {\n return {\n code: 'TOKEN_COUNTS_EXCEED_MAXIMUM',\n message: `Reported tokens exceed the per-report maximum of ${maxTokensPerReport}.`,\n };\n }\n return null;\n}\n\n/**\n * The quota a product's AI credits draw from: `<productId>.ai.credits`\n * (`vibecontrols.ai.credits`, `healthybowl.ai.credits`, …). Must match what\n * billing seeds exactly — a name mismatch reads as \"not provisioned\".\n */\nexport function aiCreditQuotaName(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('aiCreditQuotaName requires a productId');\n return `${id}.ai.credits`;\n}\n\n/** Default hash prefix for a product: `<productId>:aicredit`. */\nexport function defaultAiCreditHashPrefix(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('defaultAiCreditHashPrefix requires a productId');\n return `${id}:aicredit`;\n}\n\n/**\n * Make a hash component unambiguous when joined with `:`. Ids are `ID!` and may\n * contain colons, so raw joining would let `(\"a:b\",\"c\")` and `(\"a\",\"b:c\")`\n * collide — and activity's unique `usage_records.hash` would then drop the second,\n * genuinely different turn as a replay. `%` is escaped first so the escape itself\n * cannot collide. A no-op for ids containing neither character (uuids, `msg_…`),\n * so existing hashes are reproduced byte-for-byte.\n */\nexport function encodeAiCreditHashComponent(value: string): string {\n return value.replaceAll('%', '%25').replaceAll(':', '%3A');\n}\n\n/**\n * Idempotency hash for one turn: `<prefix>:<sessionId>:<messageId>`.\n *\n * activity-svc's unique index is on `hash` ALONE, shared by every product, so\n * the prefix must be product-namespaced. Products that already write a different\n * prefix must keep passing it (`aicredit` for VibeControls, `hb-assistant` for\n * HealthyBowl) — changing a prefix re-hashes every in-flight turn, so a client\n * retry across the deploy would be charged twice.\n */\nexport function aiCreditIdempotencyHash(prefix: string, sessionId: string, messageId: string): string {\n const head = prefix.trim();\n if (!head) throw new Error('aiCreditIdempotencyHash requires a prefix');\n if (blank(sessionId) || blank(messageId)) {\n throw new Error('aiCreditIdempotencyHash requires a sessionId and a messageId');\n }\n return `${head}:${encodeAiCreditHashComponent(sessionId)}:${encodeAiCreditHashComponent(messageId)}`;\n}\n","/**\n * Errors raised by the AI-credit meter. Only caller mistakes throw; billing and\n * recording failures are returned as a skipped charge (see `AiCreditMeter.charge`).\n */\nimport type { AiTokenUsageViolation } from './validation.js';\n\nexport type AiCreditInputErrorCode = AiTokenUsageViolation | 'WORKSPACE_ID_REQUIRED';\n\n/** A malformed report or missing workspace context. Map it to BAD_USER_INPUT. */\nexport class AiCreditInputError extends Error {\n readonly code: AiCreditInputErrorCode;\n /** GraphQL error code products should surface. */\n readonly graphqlCode = 'BAD_USER_INPUT';\n\n constructor(code: AiCreditInputErrorCode, message: string) {\n super(message);\n this.name = 'AiCreditInputError';\n this.code = code;\n }\n}\n\nexport function isAiCreditInputError(error: unknown): error is AiCreditInputError {\n return error instanceof AiCreditInputError;\n}\n","/**\n * AiCreditMeter — cost-weighted, idempotent AI-credit charging for an assistant turn.\n *\n * VibeControls (`utils/usage-billing.ts` + `modules/aicredit`) and HealthyBowl\n * (`utils/ai-credit-usage.ts` + `HealthyBowlAiCreditProvider`) each carried their\n * own copy of this path. This is the shared version, built on the path that is\n * proven to record in prod:\n *\n * 1. **Price** — `quoteAiCredits(model, inputTokens, outputTokens[, cacheReadTokens,\n * cacheWriteTokens])` on global-billing-svc, cross-layer through the be-sdk `GatewayClient`\n * (`GLOBAL_PUBLIC_GATEWAY_URL`, which resolves to the peer VPC's internal ALB\n * over the Route53 private zone). The amount is always computed server-side\n * from billing's per-model prices; a client never supplies it.\n * 2. **Record** — wspace-activity-svc `trackUsage` on the workspace's\n * `WorkspaceQuotaAssignment`, same-layer through the wspace INTERNAL gateway\n * (`WSPACE_INT_GATEWAY_URL`) with `x-workspace-id`. Activity resolves the\n * assignment itself and dedupes on the unique `usage_records.hash`, so a\n * replayed report for the same session + message is a no-op charge.\n *\n * Contract:\n * - {@link AiCreditMeter.charge} validates first and THROWS\n * {@link AiCreditInputError} for a malformed report (a caller bug worth\n * surfacing). After that it never throws: the user already has the answer, so a\n * metering failure must not become a user-visible error. Every un-charged\n * outcome is returned as `status: 'skipped'` with a reason AND logged.\n * - A null quote skips the charge: under-charging during an outage is\n * recoverable, charging an invented amount is not.\n * - Recording only counts as success when activity answers `trackUsage: true`.\n *\n * The meter is a METER, not a gate. Products that need a pre-flight gate keep a\n * `@usage(checkQuota: true, trackUsage: false)` field (VC `checkAiCredits`), or\n * call {@link AiCreditMeter.readGate}, which defers the final refusal to the same\n * activity check that `@usage` runs. The charging field must carry NO\n * `@usage(trackUsage)` directive, or the turn is charged twice.\n *\n * Enforcement rules live in wspace-activity-svc only. In particular the\n * `TEST_ENTITLEMENT_WORKSPACE_IDS` doctor-workspace entitlement is applied by\n * activity's `checkWorkspaceQuota`; a gate built on the raw assignment rows\n * ({@link AiCreditMeter.readUsage}) would never see it. The entitlement waives\n * the refusal only: {@link AiCreditMeter.charge} still records every turn.\n *\n * @example\n * ```ts\n * import { AiCreditMeter } from '@burdenoff/be-sdk/ai-credits';\n *\n * const meter = new AiCreditMeter({\n * productId: 'vibecontrols',\n * serviceName: 'wspace-vibecontrols-svc',\n * hashPrefix: 'aicredit', // VC's existing prefix — never change a live prefix\n * });\n *\n * const result = await meter.charge({\n * workspaceId: requireWorkspaceId(ctx.workspace?.id),\n * userId: ctx.actor?.id,\n * sessionId: input.sessionId,\n * messageId: input.messageId,\n * model: input.model,\n * inputTokens: input.inputTokens,\n * outputTokens: input.outputTokens,\n * });\n * ```\n */\nimport type { GraphQLRequestOptions } from '../gateway/types.js';\nimport { logger as sdkLogger } from '../logger/index.js';\n\nimport { AiCreditInputError } from './errors.js';\nimport type {\n AiCreditAllowance,\n AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditGate,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditQuoteInput,\n AiCreditSkipReason,\n WorkspaceQuotaUsage,\n} from './types.js';\nimport {\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n aiCreditIdempotencyHash,\n aiCreditQuotaName,\n defaultAiCreditHashPrefix,\n validateAiTokenUsage,\n} from './validation.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\nconst QUOTE_AI_CREDITS_QUERY = `query AiCreditMeterQuote($model: String!, $inputTokens: Int!, $outputTokens: Int!) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens)\n}`;\n\nconst QUOTE_AI_CREDITS_WITH_CACHE_QUERY = `query AiCreditMeterQuoteWithCache($model: String!, $inputTokens: Int!, $outputTokens: Int!, $cacheReadTokens: Int, $cacheWriteTokens: Int) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens, cacheReadTokens: $cacheReadTokens, cacheWriteTokens: $cacheWriteTokens)\n}`;\n\nconst CACHE_PRICING_CAPABILITY_QUERY = `query AiCreditMeterCachePricingSupported {\n aiCacheTokenPricingSupported\n}`;\n\nconst TRACK_USAGE_MUTATION = `mutation AiCreditMeterTrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n}`;\n\nconst CHECK_WORKSPACE_QUOTA_QUERY = `query AiCreditMeterCheckQuota($workspaceId: ID!, $quotaName: String!, $amount: Float) {\n checkWorkspaceQuota(workspaceId: $workspaceId, quotaName: $quotaName, amount: $amount) { allowed assignmentId limitLeft noLimit }\n}`;\n\n/** Amount the pre-flight gate asks activity about: one credit, the smallest chargeable unit. */\nconst GATE_PROBE_AMOUNT = 1;\n\nconst WORKSPACE_QUOTA_ASSIGNMENTS_QUERY = `query AiCreditMeterQuotaAssignments($workspaceId: ID!) {\n workspaceQuotaAssignments(workspaceId: $workspaceId) { quotaName used limit noLimit isActive }\n}`;\n\nexport interface AiCreditMeterOptions {\n /** Product id stamped on usage records, e.g. `vibecontrols`. */\n productId: string;\n /** This service's name; sent as the service identity. Default `SERVICE_IDENTITY` / `SERVICE_NAME` env. */\n serviceName?: string;\n /** Quota to charge. Default `<productId>.ai.credits`. */\n quotaName?: string;\n /**\n * Idempotency-hash prefix. Default `<productId>:aicredit`. A product that already\n * records under another prefix MUST keep it (see {@link aiCreditIdempotencyHash}).\n */\n hashPrefix?: string;\n /** wspace internal gateway URL. Default `WSPACE_INT_GATEWAY_URL` env (read per call). */\n activityGatewayUrl?: string;\n /** Cross-layer global gateway URL for pricing. Default `GLOBAL_PUBLIC_GATEWAY_URL` env (read per call). */\n billingGatewayUrl?: string;\n /**\n * Pricing transport, or a factory for one. Default: a lazily constructed be-sdk\n * `GatewayClient` bound to {@link billingGatewayUrl}, rebuilt if the URL changes.\n */\n pricingClient?:\n AiCreditPricingTransport | ((url: string) => AiCreditPricingTransport | Promise<AiCreditPricingTransport>);\n /** `fetch` for the activity-svc calls. Default: the global `fetch`. */\n fetch?: AiCreditFetch;\n /** Per-request timeout. Default 5s. */\n requestTimeoutMs?: number;\n /** Per-report token ceiling. Default {@link AI_CREDIT_MAX_TOKENS_PER_REPORT}. */\n maxTokensPerReport?: number;\n /** Optional pre-charge hook (e.g. a report-rate ceiling). */\n guard?: AiCreditChargeGuard;\n /** Logger. Default the be-sdk logger. */\n logger?: AiCreditLogger;\n}\n\ninterface GraphQLBody<T> {\n data?: T | null;\n errors?: { message: string }[] | null;\n}\n\ninterface AssignmentRow {\n quotaName: string;\n used: number;\n limit: number | null;\n noLimit: boolean;\n isActive: boolean;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction requireNonEmpty(value: string | undefined, field: string): string {\n const trimmed = value?.trim() ?? '';\n if (!trimmed) throw new Error(`AiCreditMeter: ${field} is required`);\n return trimmed;\n}\n\n/** Same-layer auth header the wspace internal gateway expects from in-cluster callers. */\nfunction internalServiceHeaders(): Record<string, string> {\n const token = process.env['TRUSTED_GATEWAY_TOKEN'] || process.env['INTERNAL_SERVICE_TOKEN'];\n return token ? { 'x-internal-service-token': token } : {};\n}\n\nexport class AiCreditMeter {\n readonly productId: string;\n readonly quotaName: string;\n readonly hashPrefix: string;\n private readonly serviceName: string | undefined;\n private readonly activityGatewayUrl: string | undefined;\n private readonly billingGatewayUrl: string | undefined;\n private readonly pricingOption: AiCreditMeterOptions['pricingClient'];\n private readonly fetchImpl: AiCreditFetch;\n private readonly requestTimeoutMs: number;\n private readonly maxTokensPerReport: number;\n private readonly guard: AiCreditChargeGuard | undefined;\n private readonly log: AiCreditLogger;\n private pricing: { url: string; client: Promise<AiCreditPricingTransport> } | null = null;\n\n constructor(options: AiCreditMeterOptions) {\n this.productId = requireNonEmpty(options.productId, 'productId');\n this.quotaName = options.quotaName?.trim() || aiCreditQuotaName(this.productId);\n this.hashPrefix = options.hashPrefix?.trim() || defaultAiCreditHashPrefix(this.productId);\n this.serviceName = options.serviceName?.trim() || undefined;\n this.activityGatewayUrl = options.activityGatewayUrl?.trim() || undefined;\n this.billingGatewayUrl = options.billingGatewayUrl?.trim() || undefined;\n this.pricingOption = options.pricingClient;\n this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));\n this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n if (!Number.isSafeInteger(this.requestTimeoutMs) || this.requestTimeoutMs <= 0) {\n throw new Error('AiCreditMeter: requestTimeoutMs must be a positive integer');\n }\n this.maxTokensPerReport = options.maxTokensPerReport ?? AI_CREDIT_MAX_TOKENS_PER_REPORT;\n if (!Number.isSafeInteger(this.maxTokensPerReport) || this.maxTokensPerReport <= 0) {\n throw new Error('AiCreditMeter: maxTokensPerReport must be a positive integer');\n }\n this.guard = options.guard;\n this.log = options.logger ?? sdkLogger;\n }\n\n /** The idempotency hash this meter records a turn under. */\n hashFor(sessionId: string, messageId: string): string {\n return aiCreditIdempotencyHash(this.hashPrefix, sessionId, messageId);\n }\n\n /**\n * Server-side price of one model call in credits, from billing's per-model\n * token table. Returns null — after logging why — when it cannot be priced.\n *\n * When the turn reports cache counts, billing is first asked whether it prices\n * them (`aiCacheTokenPricingSupported`). If it does, the cache counts are priced\n * with its cache-token prices; if it does not (an older billing, or the probe\n * fails), the turn is priced on input/output alone. The answer is not cached,\n * so a billing rollback is picked up on the next report.\n */\n async quote(input: AiCreditQuoteInput): Promise<number | null> {\n const url = this.billingGatewayUrl ?? process.env['GLOBAL_PUBLIC_GATEWAY_URL']?.trim();\n if (!url) {\n this.log.warn('[AiCreditMeter] GLOBAL_PUBLIC_GATEWAY_URL not set; cannot price AI credits', {\n productId: this.productId,\n model: input.model,\n });\n return null;\n }\n try {\n const client = await this.getPricingClient(url);\n const hasCacheCounts = input.cacheReadTokens != null || input.cacheWriteTokens != null;\n const priceCache = hasCacheCounts && (await this.supportsCachePricing(client, input.model));\n const response = await client.crossLayerQuery<{ quoteAiCredits?: number | null }>({\n ...this.pricingRequest(),\n query: priceCache ? QUOTE_AI_CREDITS_WITH_CACHE_QUERY : QUOTE_AI_CREDITS_QUERY,\n variables: {\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n ...(priceCache\n ? { cacheReadTokens: input.cacheReadTokens ?? 0, cacheWriteTokens: input.cacheWriteTokens ?? 0 }\n : {}),\n },\n });\n if (response.errors?.length) {\n throw new Error(response.errors.map((error) => error.message).join(', '));\n }\n const credits = response.data?.quoteAiCredits;\n if (typeof credits !== 'number' || !Number.isFinite(credits) || credits < 0) {\n throw new Error(`quoteAiCredits returned no usable value (${String(credits)})`);\n }\n return credits;\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to quote AI credits; skipping charge', {\n productId: this.productId,\n model: input.model,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Validate, price and record one completed assistant turn. See the module\n * header for the contract: throws only {@link AiCreditInputError}.\n */\n async charge(input: AiCreditChargeInput): Promise<AiCreditChargeResult> {\n const workspaceId = input.workspaceId?.trim() ?? '';\n if (!workspaceId) {\n throw new AiCreditInputError('WORKSPACE_ID_REQUIRED', 'This request has no workspace context.');\n }\n const invalid = validateAiTokenUsage(input, this.maxTokensPerReport);\n if (invalid) throw new AiCreditInputError(invalid.code, invalid.message);\n\n const hash = this.hashFor(input.sessionId, input.messageId);\n const logFields = {\n productId: this.productId,\n quotaName: this.quotaName,\n workspaceId,\n sessionId: input.sessionId,\n messageId: input.messageId,\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n };\n const skipped = (reason: AiCreditSkipReason, credits: number | null, detail?: string): AiCreditChargeResult => {\n this.log.warn(`[AiCreditMeter] turn not charged (${reason})`, { ...logFields, credits, detail });\n return { status: 'skipped', reason, credits, hash, quotaName: this.quotaName, ...(detail ? { detail } : {}) };\n };\n\n if (this.guard) {\n try {\n const verdict = await this.guard({ ...input, workspaceId });\n if (!verdict.allow) return skipped('GUARD_REFUSED', null, verdict.detail);\n } catch (error) {\n // Fail open: a guard's infrastructure blip must not silently stop metering.\n this.log.warn('[AiCreditMeter] charge guard threw; charging anyway', {\n ...logFields,\n error: errorMessage(error),\n });\n }\n }\n\n const credits = await this.quote(input);\n if (credits === null) return skipped('NOT_PRICED', null);\n if (credits <= 0) return skipped('ZERO_COST', credits);\n\n try {\n await this.trackUsage({\n workspaceId,\n amount: credits,\n description: input.description?.trim() || `AI credits for session ${input.sessionId}`,\n userId: input.userId ?? undefined,\n hash,\n metadata: {\n model: input.model,\n sessionId: input.sessionId,\n messageId: input.messageId,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n ...(input.cacheReadTokens != null || input.cacheWriteTokens != null\n ? { cacheReadTokens: input.cacheReadTokens ?? 0, cacheWriteTokens: input.cacheWriteTokens ?? 0 }\n : {}),\n credits,\n ...input.metadata,\n },\n });\n } catch (error) {\n return skipped('RECORD_FAILED', credits, errorMessage(error));\n }\n\n this.log.info(`[AiCreditMeter] Charged ${credits} AI credits for session ${input.sessionId}`, {\n ...logFields,\n credits,\n });\n return { status: 'charged', credits, hash, quotaName: this.quotaName };\n }\n\n /**\n * Read the quota's ENFORCED usage from wspace-activity-svc — the ledger the\n * charge lands on and the gateway's `@usage` check reads. All active rows are\n * summed, because a workspace can hold several (plan + add-ons, or duplicate\n * rows) and `checkWorkspaceQuota` sums them; a single-row read under-reports.\n *\n * Returns null (never throws) when activity is unreachable or no assignment\n * exists, so a screen can show \"not provisioned\" instead of a confident zero.\n */\n async readUsage(workspaceId: string, quotaName: string = this.quotaName): Promise<WorkspaceQuotaUsage | null> {\n try {\n const data = await this.activityRequest<{ workspaceQuotaAssignments?: AssignmentRow[] | null }>(\n workspaceId,\n WORKSPACE_QUOTA_ASSIGNMENTS_QUERY,\n { workspaceId: workspaceId.trim() }\n );\n const rows = (data.workspaceQuotaAssignments ?? []).filter((row) => row.isActive && row.quotaName === quotaName);\n if (rows.length === 0) return null;\n const used = rows.reduce((sum, row) => sum + (Number.isFinite(row.used) ? row.used : 0), 0);\n const noLimit = rows.some((row) => row.noLimit);\n const limit = noLimit ? null : rows.reduce((sum, row) => sum + (row.limit ?? 0), 0);\n return {\n quotaName,\n used,\n limit,\n noLimit,\n remaining: limit === null ? null : Math.max(limit - used, 0),\n assignments: rows.length,\n };\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to read workspace quota usage', {\n productId: this.productId,\n quotaName,\n workspaceId,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Ask wspace-activity-svc whether `amount` of the quota may be spent — the same\n * `checkWorkspaceQuota` the gateway's `@usage` gate runs, so every activity\n * enforcement rule (row aggregation, renamed keys, the\n * `TEST_ENTITLEMENT_WORKSPACE_IDS` entitlement) applies.\n *\n * Returns null (never throws) when activity cannot answer.\n */\n async checkAllowance(\n workspaceId: string,\n options: { amount?: number; quotaName?: string } = {}\n ): Promise<AiCreditAllowance | null> {\n const quotaName = options.quotaName ?? this.quotaName;\n const amount = options.amount ?? GATE_PROBE_AMOUNT;\n try {\n if (!Number.isFinite(amount) || amount < 0) throw new Error('amount must be a non-negative finite number');\n const data = await this.activityRequest<{\n checkWorkspaceQuota?: {\n allowed?: boolean | null;\n assignmentId?: string | null;\n limitLeft?: number | null;\n noLimit?: boolean | null;\n } | null;\n }>(workspaceId, CHECK_WORKSPACE_QUOTA_QUERY, { workspaceId: workspaceId.trim(), quotaName, amount });\n const result = data.checkWorkspaceQuota;\n if (!result || typeof result.allowed !== 'boolean') {\n throw new Error('checkWorkspaceQuota returned no verdict');\n }\n return {\n quotaName,\n allowed: result.allowed,\n provisioned: result.assignmentId != null,\n noLimit: result.noLimit === true,\n limitLeft: typeof result.limitLeft === 'number' && Number.isFinite(result.limitLeft) ? result.limitLeft : null,\n };\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to check workspace quota allowance', {\n productId: this.productId,\n quotaName,\n workspaceId,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Pre-flight gate for an AI call. Reads the ledger standing\n * ({@link readUsage}); when it shows a limited budget spent, the refusal is\n * confirmed with activity's {@link checkAllowance} before it is returned.\n *\n * - not provisioned or unreadable -> not exhausted (the call is not gated);\n * - budget left, or no limit -> not exhausted (no second call);\n * - spent and activity refuses -> exhausted;\n * - spent and activity cannot answer -> exhausted (fail closed on a known\n * spent budget, as before this check existed);\n * - spent but activity allows -> not exhausted, `entitled: true`. This\n * is a test-entitled doctor workspace; the call proceeds and\n * {@link charge} still records it.\n */\n async readGate(workspaceId: string, quotaName: string = this.quotaName): Promise<AiCreditGate> {\n const usage = await this.readUsage(workspaceId, quotaName);\n const spent = usage !== null && !usage.noLimit && (usage.remaining ?? 0) <= 0;\n if (!spent) return { usage, exhausted: false, entitled: false };\n\n const allowance = await this.checkAllowance(workspaceId, { quotaName });\n if (allowance?.allowed) {\n this.log.info('[AiCreditMeter] budget spent but activity allows the call (test entitlement); not refused', {\n productId: this.productId,\n quotaName,\n workspaceId,\n used: usage.used,\n limit: usage.limit,\n });\n return { usage, exhausted: false, entitled: true };\n }\n return { usage, exhausted: true, entitled: false };\n }\n\n private async trackUsage(record: {\n workspaceId: string;\n amount: number;\n description: string;\n userId: string | undefined;\n hash: string;\n metadata: Record<string, unknown>;\n }): Promise<void> {\n const data = await this.activityRequest<{ trackUsage?: boolean | null }>(record.workspaceId, TRACK_USAGE_MUTATION, {\n input: {\n // Sent in the input AND as x-workspace-id: activity takes the workspace from request\n // context, and the @rbac directive resolves input.workspaceId.\n workspaceId: record.workspaceId,\n quotaName: this.quotaName,\n productId: this.productId,\n amount: record.amount,\n description: record.description,\n userId: record.userId,\n hash: record.hash,\n metadata: record.metadata,\n },\n });\n if (data.trackUsage !== true) {\n throw new Error(`trackUsage did not confirm the record (returned ${String(data.trackUsage)})`);\n }\n }\n\n private async activityRequest<T>(workspaceId: string, query: string, variables: Record<string, unknown>): Promise<T> {\n const url = this.activityGatewayUrl ?? process.env['WSPACE_INT_GATEWAY_URL']?.trim();\n if (!url) throw new Error('WSPACE_INT_GATEWAY_URL not set; cannot reach wspace-activity-svc');\n const workspace = workspaceId.trim();\n if (!workspace) throw new Error('workspaceId is required');\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.requestTimeoutMs);\n try {\n const response = await this.fetchImpl(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-actor-type': 'service',\n 'x-actor-id': this.resolveServiceName(),\n ...internalServiceHeaders(),\n 'x-workspace-id': workspace,\n },\n body: JSON.stringify({ query, variables }),\n signal: controller.signal,\n });\n if (!response.ok) {\n const body = await response.text().catch(() => response.statusText);\n throw new Error(`activity request failed with HTTP ${response.status}: ${body.slice(0, 500)}`);\n }\n const result = (await response.json()) as GraphQLBody<T>;\n if (result.errors?.length) {\n throw new Error(result.errors.map((error) => error.message).join(', '));\n }\n if (!result.data) throw new Error('activity response did not include data');\n return result.data;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n /** Options shared by every pricing call. */\n private pricingRequest(): Pick<GraphQLRequestOptions, 'headers' | 'timeout' | 'skipRetry' | 'skipCircuitBreaker'> {\n return {\n // Only the actor type: the signed service JWT is the identity. An x-actor-id on a\n // service token is read as \"on behalf of\" and downgrades the actor.\n headers: { 'x-actor-type': 'service' },\n timeout: this.requestTimeoutMs,\n skipRetry: true,\n skipCircuitBreaker: true,\n };\n }\n\n /** Whether billing prices cache counts. Any failure reads as \"no\" and falls back to input/output. */\n private async supportsCachePricing(client: AiCreditPricingTransport, model: string): Promise<boolean> {\n try {\n const response = await client.crossLayerQuery<{ aiCacheTokenPricingSupported?: boolean | null }>({\n ...this.pricingRequest(),\n query: CACHE_PRICING_CAPABILITY_QUERY,\n variables: {},\n });\n if (response.data?.aiCacheTokenPricingSupported === true) return true;\n } catch {\n // Logged below; the turn is still priced on input/output.\n }\n this.log.warn('[AiCreditMeter] billing does not price cache tokens; quoting input/output only', {\n productId: this.productId,\n model,\n });\n return false;\n }\n\n private resolveServiceName(): string {\n return (\n this.serviceName ||\n process.env['SERVICE_IDENTITY'] ||\n process.env['SERVICE_NAME'] ||\n `wspace-${this.productId}-svc`\n );\n }\n\n private getPricingClient(url: string): Promise<AiCreditPricingTransport> {\n // Rebuilt when the URL changes, so a client bound to a stale URL cannot keep failing.\n if (this.pricing && this.pricing.url === url) return this.pricing.client;\n const option = this.pricingOption;\n const client = (async (): Promise<AiCreditPricingTransport> => {\n if (option && typeof option === 'function') return option(url);\n if (option) return option;\n const gateway = await import('../gateway/client.js');\n const identity = this.resolveServiceName();\n return new gateway.GatewayClient({\n // This service's OWN layer; the be-sdk signs the service JWT because the call leaves it.\n layer: 'wspace',\n serviceName: identity,\n serviceIdentity: identity,\n crossLayerGatewayUrl: url,\n timeout: this.requestTimeoutMs,\n enableLogging: process.env['NODE_ENV'] !== 'production',\n });\n })();\n this.pricing = { url, client };\n // A failed construction must not be cached forever.\n client.catch(() => {\n if (this.pricing?.client === client) this.pricing = null;\n });\n return client;\n }\n}\n","/**\n * @burdenoff/be-sdk/ai-credits\n *\n * Shared cost-weighted, idempotent AI-credit metering for assistant turns:\n * billing prices the turn (`quoteAiCredits`), wspace-activity-svc records it on\n * the workspace quota (`trackUsage`, deduped by `<prefix>:<session>:<message>`).\n *\n * - {@link AiCreditMeter} — `charge`, `quote`, `readUsage`, `checkAllowance`,\n * `readGate`, `hashFor`.\n * - {@link validateAiTokenUsage}, {@link aiCreditIdempotencyHash},\n * {@link aiCreditQuotaName} — the pure rules, for products' own tests and resolvers.\n *\n * @example\n * ```ts\n * import { AiCreditMeter, isAiCreditInputError } from '@burdenoff/be-sdk/ai-credits';\n *\n * const meter = new AiCreditMeter({ productId: 'healthybowl', hashPrefix: 'hb-assistant' });\n * const result = await meter.charge({ workspaceId, userId, sessionId, messageId, model, inputTokens, outputTokens });\n * ```\n */\n\nexport {\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n aiCreditIdempotencyHash,\n aiCreditQuotaName,\n defaultAiCreditHashPrefix,\n encodeAiCreditHashComponent,\n validateAiTokenUsage,\n type AiTokenUsageValidationError,\n type AiTokenUsageViolation,\n} from './validation.js';\n\nexport { AiCreditInputError, isAiCreditInputError, type AiCreditInputErrorCode } from './errors.js';\n\nexport { AiCreditMeter, type AiCreditMeterOptions } from './meter.js';\n\nexport type {\n AiCreditAllowance,\n AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditGate,\n AiCreditGuardVerdict,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditQuoteInput,\n AiCreditSkipReason,\n AiTokenUsageReport,\n WorkspaceQuotaUsage,\n} from './types.js';\n"],"mappings":";;;;;;;;;AAWA,MAAa,kCAAkC;AAiB/C,SAAS,MAAM,OAA2C;CACxD,OAAO,OAAO,UAAU,YAAY,MAAM,KAAK,CAAC,CAAC,WAAW;AAC9D;;;;;;;;;;AAWA,SAAgB,qBACd,QAEA,qBAA6B,iCACO;CACpC,MAAM,EAAE,WAAW,WAAW,OAAO,aAAa,iBAAiB;CAGnE,MAAM,SAAS;EAAC;EAAa;EAAc,OAAO,mBAAmB;EAAG,OAAO,oBAAoB;CAAC;CAEpG,IAAI,MAAM,SAAS,GAAG,OAAO;EAAE,MAAM;EAAuB,SAAS;CAAyB;CAC9F,IAAI,MAAM,SAAS,G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