@burdenoff/be-sdk 2026.1202.3 → 2026.1202.5
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/ai-credits/index.d.ts +2 -2
- package/dist/ai-credits/index.js +2 -2
- package/dist/{ai-credits-B_IPVIu1.js → ai-credits-dt8pv7pF.js} +49 -4
- package/dist/ai-credits-dt8pv7pF.js.map +1 -0
- package/dist/{index-SAUnwdbo.d.ts → index-BtQ25xPq.d.ts} +11 -5
- package/dist/index.d.ts +1 -1
- package/dist/index.js +1 -1
- package/package.json +1 -1
- package/dist/ai-credits-B_IPVIu1.js.map +0 -1
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as
|
|
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
|
+
import { A as AiServiceTier, C as AiCreditFetch, D as AiCreditPricingTransport, E as AiCreditLogger, F as UsageSettlementStatus, I as WorkspaceQuotaUsage, M as ReadUsageSettlementInput, N as UsageSettlementPayer, O as AiCreditQuoteInput, P as UsageSettlementReceipt, S as AiCreditChargeResult, T as AiCreditGuardVerdict, _ as isAiServiceTier, a as AiCreditInputErrorCode, b as AiCreditChargeGuard, c as AI_CREDIT_MAX_TOKENS_PER_REPORT, d as AiTokenUsageViolation, f as aiCreditIdempotencyHash, g as encodeAiCreditHashComponent, h as defaultAiCreditHashPrefix, i as AiCreditInputError, j as AiTokenUsageReport, k as AiCreditSkipReason, l as AI_SERVICE_TIERS, m as applyAiServiceTier, n as AiCreditMeter, o as isAiCreditInputError, p as aiCreditQuotaName, r as AiCreditMeterOptions, s as AI_CREDIT_BATCH_RATE, u as AiTokenUsageValidationError, v as validateAiTokenUsage, w as AiCreditGate, x as AiCreditChargeInput, y as AiCreditAllowance } from "../index-BtQ25xPq.js";
|
|
2
|
+
export { AI_CREDIT_BATCH_RATE, AI_CREDIT_MAX_TOKENS_PER_REPORT, AI_SERVICE_TIERS, 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 AiServiceTier, type AiTokenUsageReport, type AiTokenUsageValidationError, type AiTokenUsageViolation, type ReadUsageSettlementInput, type UsageSettlementPayer, type UsageSettlementReceipt, type UsageSettlementStatus, type WorkspaceQuotaUsage, aiCreditIdempotencyHash, aiCreditQuotaName, applyAiServiceTier, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, isAiServiceTier, validateAiTokenUsage };
|
package/dist/ai-credits/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as
|
|
1
|
+
import { a as AI_CREDIT_BATCH_RATE, c as aiCreditIdempotencyHash, d as defaultAiCreditHashPrefix, f as encodeAiCreditHashComponent, i as isAiCreditInputError, l as aiCreditQuotaName, m as validateAiTokenUsage, n as AiCreditMeter, o as AI_CREDIT_MAX_TOKENS_PER_REPORT, p as isAiServiceTier, r as AiCreditInputError, s as AI_SERVICE_TIERS, u as applyAiServiceTier } from "../ai-credits-dt8pv7pF.js";
|
|
2
2
|
|
|
3
|
-
export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditInputError, AiCreditMeter, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage };
|
|
3
|
+
export { AI_CREDIT_BATCH_RATE, AI_CREDIT_MAX_TOKENS_PER_REPORT, AI_SERVICE_TIERS, AiCreditInputError, AiCreditMeter, aiCreditIdempotencyHash, aiCreditQuotaName, applyAiServiceTier, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, isAiServiceTier, validateAiTokenUsage };
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -8,6 +8,29 @@ import { a as logger } from "./logger-B6rCpb7D.js";
|
|
|
8
8
|
* token, so an unbounded count would be an unbounded charge.
|
|
9
9
|
*/
|
|
10
10
|
const AI_CREDIT_MAX_TOKENS_PER_REPORT = 2e6;
|
|
11
|
+
/** Every service tier the meter can price. */
|
|
12
|
+
const AI_SERVICE_TIERS = ["standard", "batch"];
|
|
13
|
+
/**
|
|
14
|
+
* Fraction of the standard price a `batch` call is charged. Providers bill
|
|
15
|
+
* batch calls at 50% of every token class, and billing's quote is linear in
|
|
16
|
+
* each class, so halving the quote halves every class.
|
|
17
|
+
*/
|
|
18
|
+
const AI_CREDIT_BATCH_RATE = .5;
|
|
19
|
+
/** True when `value` is a service tier the meter can price. Null/undefined are not tiers. */
|
|
20
|
+
function isAiServiceTier(value) {
|
|
21
|
+
return typeof value === "string" && AI_SERVICE_TIERS.includes(value);
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Apply a service tier to a standard-rate credit quote. Billing quotes whole
|
|
25
|
+
* credits, so the batch price is rounded to the nearest whole credit (half up).
|
|
26
|
+
* That keeps a 1-credit call at 1 credit instead of letting it fall to zero,
|
|
27
|
+
* and the result never differs from halving the unrounded cost by more than
|
|
28
|
+
* one credit. Omitted/null tier means `standard` (unchanged).
|
|
29
|
+
*/
|
|
30
|
+
function applyAiServiceTier(credits, serviceTier) {
|
|
31
|
+
if (serviceTier === "batch") return Math.round(credits * AI_CREDIT_BATCH_RATE);
|
|
32
|
+
return credits;
|
|
33
|
+
}
|
|
11
34
|
function blank(value) {
|
|
12
35
|
return typeof value !== "string" || value.trim().length === 0;
|
|
13
36
|
}
|
|
@@ -52,6 +75,10 @@ function validateAiTokenUsage(report, maxTokensPerReport = AI_CREDIT_MAX_TOKENS_
|
|
|
52
75
|
code: "TOKEN_COUNTS_EXCEED_MAXIMUM",
|
|
53
76
|
message: `Reported tokens exceed the per-report maximum of ${maxTokensPerReport}.`
|
|
54
77
|
};
|
|
78
|
+
if (report.serviceTier != null && !isAiServiceTier(report.serviceTier)) return {
|
|
79
|
+
code: "SERVICE_TIER_INVALID",
|
|
80
|
+
message: `serviceTier must be one of: ${AI_SERVICE_TIERS.join(", ")}.`
|
|
81
|
+
};
|
|
55
82
|
return null;
|
|
56
83
|
}
|
|
57
84
|
/**
|
|
@@ -200,8 +227,20 @@ var AiCreditMeter = class {
|
|
|
200
227
|
* with its cache-token prices; if it does not (an older billing, or the probe
|
|
201
228
|
* fails), the turn is priced on input/output alone. The answer is not cached,
|
|
202
229
|
* so a billing rollback is picked up on the next report.
|
|
230
|
+
*
|
|
231
|
+
* `serviceTier: 'batch'` prices the call at {@link AI_CREDIT_BATCH_RATE} of
|
|
232
|
+
* billing's standard quote (see {@link applyAiServiceTier}). An unknown tier
|
|
233
|
+
* cannot be priced and returns null.
|
|
203
234
|
*/
|
|
204
235
|
async quote(input) {
|
|
236
|
+
if (input.serviceTier != null && !isAiServiceTier(input.serviceTier)) {
|
|
237
|
+
this.log.warn("[AiCreditMeter] Unknown service tier; cannot price AI credits", {
|
|
238
|
+
productId: this.productId,
|
|
239
|
+
model: input.model,
|
|
240
|
+
serviceTier: String(input.serviceTier)
|
|
241
|
+
});
|
|
242
|
+
return null;
|
|
243
|
+
}
|
|
205
244
|
const url = this.billingGatewayUrl ?? process.env["GLOBAL_PUBLIC_GATEWAY_URL"]?.trim();
|
|
206
245
|
if (!url) {
|
|
207
246
|
this.log.warn("[AiCreditMeter] GLOBAL_PUBLIC_GATEWAY_URL not set; cannot price AI credits", {
|
|
@@ -229,7 +268,7 @@ var AiCreditMeter = class {
|
|
|
229
268
|
if (response.errors?.length) throw new Error(response.errors.map((error) => error.message).join(", "));
|
|
230
269
|
const credits = response.data?.quoteAiCredits;
|
|
231
270
|
if (typeof credits !== "number" || !Number.isFinite(credits) || credits < 0) throw new Error(`quoteAiCredits returned no usable value (${String(credits)})`);
|
|
232
|
-
return credits;
|
|
271
|
+
return applyAiServiceTier(credits, input.serviceTier);
|
|
233
272
|
} catch (error) {
|
|
234
273
|
this.log.warn("[AiCreditMeter] Failed to quote AI credits; skipping charge", {
|
|
235
274
|
productId: this.productId,
|
|
@@ -258,7 +297,8 @@ var AiCreditMeter = class {
|
|
|
258
297
|
messageId: input.messageId,
|
|
259
298
|
model: input.model,
|
|
260
299
|
inputTokens: input.inputTokens,
|
|
261
|
-
outputTokens: input.outputTokens
|
|
300
|
+
outputTokens: input.outputTokens,
|
|
301
|
+
serviceTier: input.serviceTier ?? "standard"
|
|
262
302
|
};
|
|
263
303
|
const skipped = (reason, credits, detail) => {
|
|
264
304
|
this.log.warn(`[AiCreditMeter] turn not charged (${reason})`, {
|
|
@@ -311,6 +351,7 @@ var AiCreditMeter = class {
|
|
|
311
351
|
cacheReadTokens: input.cacheReadTokens ?? 0,
|
|
312
352
|
cacheWriteTokens: input.cacheWriteTokens ?? 0
|
|
313
353
|
} : {},
|
|
354
|
+
...input.serviceTier != null ? { serviceTier: input.serviceTier } : {},
|
|
314
355
|
credits,
|
|
315
356
|
...input.metadata
|
|
316
357
|
}
|
|
@@ -581,16 +622,20 @@ var AiCreditMeter = class {
|
|
|
581
622
|
|
|
582
623
|
// src/ai-credits/index.ts
|
|
583
624
|
var ai_credits_exports = /* @__PURE__ */ __exportAll({
|
|
625
|
+
AI_CREDIT_BATCH_RATE: () => AI_CREDIT_BATCH_RATE,
|
|
584
626
|
AI_CREDIT_MAX_TOKENS_PER_REPORT: () => AI_CREDIT_MAX_TOKENS_PER_REPORT,
|
|
627
|
+
AI_SERVICE_TIERS: () => AI_SERVICE_TIERS,
|
|
585
628
|
AiCreditInputError: () => AiCreditInputError,
|
|
586
629
|
AiCreditMeter: () => AiCreditMeter,
|
|
587
630
|
aiCreditIdempotencyHash: () => aiCreditIdempotencyHash,
|
|
588
631
|
aiCreditQuotaName: () => aiCreditQuotaName,
|
|
632
|
+
applyAiServiceTier: () => applyAiServiceTier,
|
|
589
633
|
defaultAiCreditHashPrefix: () => defaultAiCreditHashPrefix,
|
|
590
634
|
encodeAiCreditHashComponent: () => encodeAiCreditHashComponent,
|
|
591
635
|
isAiCreditInputError: () => isAiCreditInputError,
|
|
636
|
+
isAiServiceTier: () => isAiServiceTier,
|
|
592
637
|
validateAiTokenUsage: () => validateAiTokenUsage
|
|
593
638
|
});
|
|
594
639
|
|
|
595
|
-
export {
|
|
596
|
-
//# sourceMappingURL=ai-credits-
|
|
640
|
+
export { AI_CREDIT_BATCH_RATE as a, aiCreditIdempotencyHash as c, defaultAiCreditHashPrefix as d, encodeAiCreditHashComponent as f, isAiCreditInputError as i, aiCreditQuotaName as l, validateAiTokenUsage as m, AiCreditMeter as n, AI_CREDIT_MAX_TOKENS_PER_REPORT as o, isAiServiceTier as p, AiCreditInputError as r, AI_SERVICE_TIERS as s, ai_credits_exports as t, applyAiServiceTier as u };
|
|
641
|
+
//# sourceMappingURL=ai-credits-dt8pv7pF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ai-credits-dt8pv7pF.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 { AiServiceTier, 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/** Every service tier the meter can price. */\nexport const AI_SERVICE_TIERS: readonly AiServiceTier[] = ['standard', 'batch'];\n\n/**\n * Fraction of the standard price a `batch` call is charged. Providers bill\n * batch calls at 50% of every token class, and billing's quote is linear in\n * each class, so halving the quote halves every class.\n */\nexport const AI_CREDIT_BATCH_RATE = 0.5;\n\n/** True when `value` is a service tier the meter can price. Null/undefined are not tiers. */\nexport function isAiServiceTier(value: unknown): value is AiServiceTier {\n return typeof value === 'string' && (AI_SERVICE_TIERS as readonly string[]).includes(value);\n}\n\n/**\n * Apply a service tier to a standard-rate credit quote. Billing quotes whole\n * credits, so the batch price is rounded to the nearest whole credit (half up).\n * That keeps a 1-credit call at 1 credit instead of letting it fall to zero,\n * and the result never differs from halving the unrounded cost by more than\n * one credit. Omitted/null tier means `standard` (unchanged).\n */\nexport function applyAiServiceTier(credits: number, serviceTier: AiServiceTier | null | undefined): number {\n if (serviceTier === 'batch') return Math.round(credits * AI_CREDIT_BATCH_RATE);\n return credits;\n}\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 | 'SERVICE_TIER_INVALID';\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' | 'serviceTier'>,\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 if (report.serviceTier != null && !isAiServiceTier(report.serviceTier)) {\n return { code: 'SERVICE_TIER_INVALID', message: `serviceTier must be one of: ${AI_SERVICE_TIERS.join(', ')}.` };\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 applyAiServiceTier,\n defaultAiCreditHashPrefix,\n isAiServiceTier,\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 * `serviceTier: 'batch'` prices the call at {@link AI_CREDIT_BATCH_RATE} of\n * billing's standard quote (see {@link applyAiServiceTier}). An unknown tier\n * cannot be priced and returns null.\n */\n async quote(input: AiCreditQuoteInput): Promise<number | null> {\n if (input.serviceTier != null && !isAiServiceTier(input.serviceTier)) {\n this.log.warn('[AiCreditMeter] Unknown service tier; cannot price AI credits', {\n productId: this.productId,\n model: input.model,\n serviceTier: String(input.serviceTier),\n });\n return null;\n }\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 applyAiServiceTier(credits, input.serviceTier);\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 serviceTier: input.serviceTier ?? 'standard',\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 // Recorded only when reported, so standard-tier records keep their existing shape.\n ...(input.serviceTier != null ? { serviceTier: input.serviceTier } : {}),\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_BATCH_RATE,\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n AI_SERVICE_TIERS,\n aiCreditIdempotencyHash,\n applyAiServiceTier,\n isAiServiceTier,\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 AiServiceTier,\n AiTokenUsageReport,\n ReadUsageSettlementInput,\n UsageSettlementPayer,\n UsageSettlementReceipt,\n UsageSettlementStatus,\n WorkspaceQuotaUsage,\n} from './types.js';\n"],"mappings":";;;;;;;;;AAWA,MAAa,kCAAkC;;AAG/C,MAAa,mBAA6C,CAAC,YAAY,OAAO;;;;;;AAO9E,MAAa,uBAAuB;;AAGpC,SAAgB,gBAAgB,OAAwC;CACtE,OAAO,OAAO,UAAU,YAAa,iBAAuC,SAAS,KAAK;AAC5F;;;;;;;;AASA,SAAgB,mBAAmB,SAAiB,aAAuD;CACzG,IAAI,gBAAgB,SAAS,OAAO,KAAK,MAAM,UAAU,oBAAoB;CAC7E,OAAO;AACT;AAkBA,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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I,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"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { c as GraphQLRequestOptions, l as GraphQLResponse } from "./types-gJ9Qqi9E.js";
|
|
2
|
+
type AiServiceTier = 'standard' | 'batch';
|
|
2
3
|
interface AiTokenUsageReport {
|
|
3
4
|
sessionId: string;
|
|
4
5
|
messageId: string;
|
|
@@ -7,8 +8,9 @@ interface AiTokenUsageReport {
|
|
|
7
8
|
outputTokens: number;
|
|
8
9
|
cacheReadTokens?: number | null;
|
|
9
10
|
cacheWriteTokens?: number | null;
|
|
11
|
+
serviceTier?: AiServiceTier | null;
|
|
10
12
|
}
|
|
11
|
-
type AiCreditQuoteInput = Pick<AiTokenUsageReport, 'model' | 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'>;
|
|
13
|
+
type AiCreditQuoteInput = Pick<AiTokenUsageReport, 'model' | 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens' | 'serviceTier'>;
|
|
12
14
|
interface AiCreditChargeInput extends AiTokenUsageReport {
|
|
13
15
|
workspaceId: string;
|
|
14
16
|
userId?: string | null;
|
|
@@ -82,12 +84,16 @@ interface UsageSettlementReceipt {
|
|
|
82
84
|
}
|
|
83
85
|
type AiCreditFetch = (url: string, init?: RequestInit) => Promise<Response>;
|
|
84
86
|
declare const AI_CREDIT_MAX_TOKENS_PER_REPORT = 2000000;
|
|
85
|
-
|
|
87
|
+
declare const AI_SERVICE_TIERS: readonly AiServiceTier[];
|
|
88
|
+
declare const AI_CREDIT_BATCH_RATE = 0.5;
|
|
89
|
+
declare function isAiServiceTier(value: unknown): value is AiServiceTier;
|
|
90
|
+
declare function applyAiServiceTier(credits: number, serviceTier: AiServiceTier | null | undefined): number;
|
|
91
|
+
type AiTokenUsageViolation = 'SESSION_ID_REQUIRED' | 'MESSAGE_ID_REQUIRED' | 'MODEL_REQUIRED' | 'TOKEN_COUNTS_NOT_INTEGERS' | 'TOKEN_COUNTS_NEGATIVE' | 'TOKEN_COUNTS_EXCEED_MAXIMUM' | 'SERVICE_TIER_INVALID';
|
|
86
92
|
interface AiTokenUsageValidationError {
|
|
87
93
|
code: AiTokenUsageViolation;
|
|
88
94
|
message: string;
|
|
89
95
|
}
|
|
90
|
-
declare function validateAiTokenUsage(report: Partial<Pick<AiTokenUsageReport, 'sessionId' | 'messageId' | 'model'>> & Pick<AiTokenUsageReport, 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'>, maxTokensPerReport?: number): AiTokenUsageValidationError | null;
|
|
96
|
+
declare function validateAiTokenUsage(report: Partial<Pick<AiTokenUsageReport, 'sessionId' | 'messageId' | 'model'>> & Pick<AiTokenUsageReport, 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens' | 'serviceTier'>, maxTokensPerReport?: number): AiTokenUsageValidationError | null;
|
|
91
97
|
declare function aiCreditQuotaName(productId: string): string;
|
|
92
98
|
declare function defaultAiCreditHashPrefix(productId: string): string;
|
|
93
99
|
declare function encodeAiCreditHashComponent(value: string): string;
|
|
@@ -146,6 +152,6 @@ declare class AiCreditMeter {
|
|
|
146
152
|
private getPricingClient;
|
|
147
153
|
}
|
|
148
154
|
declare namespace index_d_exports {
|
|
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 };
|
|
155
|
+
export { AI_CREDIT_BATCH_RATE, AI_CREDIT_MAX_TOKENS_PER_REPORT, AI_SERVICE_TIERS, AiCreditAllowance, AiCreditChargeGuard, AiCreditChargeInput, AiCreditChargeResult, AiCreditFetch, AiCreditGate, AiCreditGuardVerdict, AiCreditInputError, AiCreditInputErrorCode, AiCreditLogger, AiCreditMeter, AiCreditMeterOptions, AiCreditPricingTransport, AiCreditQuoteInput, AiCreditSkipReason, AiServiceTier, AiTokenUsageReport, AiTokenUsageValidationError, AiTokenUsageViolation, ReadUsageSettlementInput, UsageSettlementPayer, UsageSettlementReceipt, UsageSettlementStatus, WorkspaceQuotaUsage, aiCreditIdempotencyHash, aiCreditQuotaName, applyAiServiceTier, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, isAiServiceTier, validateAiTokenUsage };
|
|
150
156
|
}
|
|
151
|
-
export {
|
|
157
|
+
export { AiServiceTier as A, AiCreditFetch as C, AiCreditPricingTransport as D, AiCreditLogger as E, UsageSettlementStatus as F, WorkspaceQuotaUsage as I, ReadUsageSettlementInput as M, UsageSettlementPayer as N, AiCreditQuoteInput as O, UsageSettlementReceipt as P, AiCreditChargeResult as S, AiCreditGuardVerdict as T, isAiServiceTier as _, AiCreditInputErrorCode as a, AiCreditChargeGuard as b, AI_CREDIT_MAX_TOKENS_PER_REPORT as c, AiTokenUsageViolation as d, aiCreditIdempotencyHash as f, encodeAiCreditHashComponent as g, defaultAiCreditHashPrefix as h, AiCreditInputError as i, AiTokenUsageReport as j, AiCreditSkipReason as k, AI_SERVICE_TIERS as l, applyAiServiceTier as m, AiCreditMeter as n, isAiCreditInputError as o, aiCreditQuotaName as p, AiCreditMeterOptions as r, AI_CREDIT_BATCH_RATE as s, index_d_exports as t, AiTokenUsageValidationError as u, validateAiTokenUsage as v, AiCreditGate as w, AiCreditChargeInput as x, AiCreditAllowance 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-
|
|
26
|
+
import { t as index_d_exports } from "./index-BtQ25xPq.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-
|
|
28
|
+
import { t as ai_credits_exports } from "./ai-credits-dt8pv7pF.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.
|
|
3
|
+
"version": "2026.1202.5",
|
|
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-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,M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