@burdenoff/be-sdk 2026.1022.1 → 2026.1022.2
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 +1 -1
- package/dist/ai-credits/index.js +1 -1
- package/dist/{chunk-PYB2DKL2.js → chunk-QUF27D73.js} +69 -18
- package/dist/chunk-QUF27D73.js.map +1 -0
- package/dist/{index-DmxmEfAu.d.ts → index-HxigeZFh.d.ts} +10 -8
- package/dist/index.d.ts +1 -1
- package/dist/index.js +4 -4
- package/package.json +1 -1
- package/dist/chunk-PYB2DKL2.js.map +0 -1
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export { A as AI_CREDIT_MAX_TOKENS_PER_REPORT, a as AiCreditChargeGuard, b as AiCreditChargeInput, c as AiCreditChargeResult, d as AiCreditFetch, e as AiCreditGuardVerdict, f as AiCreditInputError, g as AiCreditInputErrorCode, h as AiCreditLogger, j as AiCreditMeter, k as AiCreditMeterOptions, l as AiCreditPricingTransport, m as
|
|
1
|
+
export { A as AI_CREDIT_MAX_TOKENS_PER_REPORT, a as AiCreditChargeGuard, b as AiCreditChargeInput, c as AiCreditChargeResult, d as AiCreditFetch, e as AiCreditGuardVerdict, f as AiCreditInputError, g as AiCreditInputErrorCode, h as AiCreditLogger, j as AiCreditMeter, k as AiCreditMeterOptions, l as AiCreditPricingTransport, m as AiCreditQuoteInput, n as AiCreditSkipReason, o as AiTokenUsageReport, p as AiTokenUsageValidationError, q as AiTokenUsageViolation, W as WorkspaceQuotaUsage, r as aiCreditIdempotencyHash, s as aiCreditQuotaName, t as defaultAiCreditHashPrefix, u as encodeAiCreditHashComponent, v as isAiCreditInputError, w as validateAiTokenUsage } from '../index-HxigeZFh.js';
|
|
2
2
|
import '../types-B376RbyK.js';
|
|
3
3
|
import '../layer-GNAVXBMf.js';
|
package/dist/ai-credits/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditInputError, AiCreditMeter, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage } from '../chunk-
|
|
1
|
+
export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditInputError, AiCreditMeter, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage } from '../chunk-QUF27D73.js';
|
|
2
2
|
import '../chunk-RU266375.js';
|
|
3
3
|
import '../chunk-XE4OXN2W.js';
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -23,6 +23,12 @@ function blank(value) {
|
|
|
23
23
|
__name(blank, "blank");
|
|
24
24
|
function validateAiTokenUsage(report, maxTokensPerReport = AI_CREDIT_MAX_TOKENS_PER_REPORT) {
|
|
25
25
|
const { sessionId, messageId, model, inputTokens, outputTokens } = report;
|
|
26
|
+
const counts = [
|
|
27
|
+
inputTokens,
|
|
28
|
+
outputTokens,
|
|
29
|
+
report.cacheReadTokens ?? 0,
|
|
30
|
+
report.cacheWriteTokens ?? 0
|
|
31
|
+
];
|
|
26
32
|
if (blank(sessionId)) return {
|
|
27
33
|
code: "SESSION_ID_REQUIRED",
|
|
28
34
|
message: "sessionId is required."
|
|
@@ -35,19 +41,19 @@ function validateAiTokenUsage(report, maxTokensPerReport = AI_CREDIT_MAX_TOKENS_
|
|
|
35
41
|
code: "MODEL_REQUIRED",
|
|
36
42
|
message: "model is required."
|
|
37
43
|
};
|
|
38
|
-
if (
|
|
44
|
+
if (counts.some((count) => !Number.isSafeInteger(count))) {
|
|
39
45
|
return {
|
|
40
46
|
code: "TOKEN_COUNTS_NOT_INTEGERS",
|
|
41
|
-
message: "
|
|
47
|
+
message: "Token counts must be integers."
|
|
42
48
|
};
|
|
43
49
|
}
|
|
44
|
-
if (
|
|
50
|
+
if (counts.some((count) => count < 0)) {
|
|
45
51
|
return {
|
|
46
52
|
code: "TOKEN_COUNTS_NEGATIVE",
|
|
47
|
-
message: "
|
|
53
|
+
message: "Token counts must be non-negative."
|
|
48
54
|
};
|
|
49
55
|
}
|
|
50
|
-
if (
|
|
56
|
+
if (counts.reduce((sum, count) => sum + count, 0) > maxTokensPerReport) {
|
|
51
57
|
return {
|
|
52
58
|
code: "TOKEN_COUNTS_EXCEED_MAXIMUM",
|
|
53
59
|
message: `Reported tokens exceed the per-report maximum of ${maxTokensPerReport}.`
|
|
@@ -106,6 +112,12 @@ var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
|
|
|
106
112
|
var QUOTE_AI_CREDITS_QUERY = `query AiCreditMeterQuote($model: String!, $inputTokens: Int!, $outputTokens: Int!) {
|
|
107
113
|
quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens)
|
|
108
114
|
}`;
|
|
115
|
+
var QUOTE_AI_CREDITS_WITH_CACHE_QUERY = `query AiCreditMeterQuoteWithCache($model: String!, $inputTokens: Int!, $outputTokens: Int!, $cacheReadTokens: Int, $cacheWriteTokens: Int) {
|
|
116
|
+
quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens, cacheReadTokens: $cacheReadTokens, cacheWriteTokens: $cacheWriteTokens)
|
|
117
|
+
}`;
|
|
118
|
+
var CACHE_PRICING_CAPABILITY_QUERY = `query AiCreditMeterCachePricingSupported {
|
|
119
|
+
aiCacheTokenPricingSupported
|
|
120
|
+
}`;
|
|
109
121
|
var TRACK_USAGE_MUTATION = `mutation AiCreditMeterTrackUsage($input: TrackUsageInput!) {
|
|
110
122
|
trackUsage(input: $input)
|
|
111
123
|
}`;
|
|
@@ -173,6 +185,12 @@ var AiCreditMeter = class {
|
|
|
173
185
|
/**
|
|
174
186
|
* Server-side price of one model call in credits, from billing's per-model
|
|
175
187
|
* token table. Returns null — after logging why — when it cannot be priced.
|
|
188
|
+
*
|
|
189
|
+
* When the turn reports cache counts, billing is first asked whether it prices
|
|
190
|
+
* them (`aiCacheTokenPricingSupported`). If it does, the cache counts are priced
|
|
191
|
+
* with its cache-token prices; if it does not (an older billing, or the probe
|
|
192
|
+
* fails), the turn is priced on input/output alone. The answer is not cached,
|
|
193
|
+
* so a billing rollback is picked up on the next report.
|
|
176
194
|
*/
|
|
177
195
|
async quote(input) {
|
|
178
196
|
const url = this.billingGatewayUrl ?? process.env["GLOBAL_PUBLIC_GATEWAY_URL"]?.trim();
|
|
@@ -185,21 +203,20 @@ var AiCreditMeter = class {
|
|
|
185
203
|
}
|
|
186
204
|
try {
|
|
187
205
|
const client = await this.getPricingClient(url);
|
|
206
|
+
const hasCacheCounts = input.cacheReadTokens != null || input.cacheWriteTokens != null;
|
|
207
|
+
const priceCache = hasCacheCounts && await this.supportsCachePricing(client, input.model);
|
|
188
208
|
const response = await client.crossLayerQuery({
|
|
189
|
-
|
|
209
|
+
...this.pricingRequest(),
|
|
210
|
+
query: priceCache ? QUOTE_AI_CREDITS_WITH_CACHE_QUERY : QUOTE_AI_CREDITS_QUERY,
|
|
190
211
|
variables: {
|
|
191
212
|
model: input.model,
|
|
192
213
|
inputTokens: input.inputTokens,
|
|
193
|
-
outputTokens: input.outputTokens
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
},
|
|
200
|
-
timeout: this.requestTimeoutMs,
|
|
201
|
-
skipRetry: true,
|
|
202
|
-
skipCircuitBreaker: true
|
|
214
|
+
outputTokens: input.outputTokens,
|
|
215
|
+
...priceCache ? {
|
|
216
|
+
cacheReadTokens: input.cacheReadTokens ?? 0,
|
|
217
|
+
cacheWriteTokens: input.cacheWriteTokens ?? 0
|
|
218
|
+
} : {}
|
|
219
|
+
}
|
|
203
220
|
});
|
|
204
221
|
if (response.errors?.length) {
|
|
205
222
|
throw new Error(response.errors.map((error) => error.message).join(", "));
|
|
@@ -287,6 +304,10 @@ var AiCreditMeter = class {
|
|
|
287
304
|
messageId: input.messageId,
|
|
288
305
|
inputTokens: input.inputTokens,
|
|
289
306
|
outputTokens: input.outputTokens,
|
|
307
|
+
...input.cacheReadTokens != null || input.cacheWriteTokens != null ? {
|
|
308
|
+
cacheReadTokens: input.cacheReadTokens ?? 0,
|
|
309
|
+
cacheWriteTokens: input.cacheWriteTokens ?? 0
|
|
310
|
+
} : {},
|
|
290
311
|
credits,
|
|
291
312
|
...input.metadata
|
|
292
313
|
}
|
|
@@ -398,6 +419,36 @@ var AiCreditMeter = class {
|
|
|
398
419
|
clearTimeout(timeout);
|
|
399
420
|
}
|
|
400
421
|
}
|
|
422
|
+
/** Options shared by every pricing call. */
|
|
423
|
+
pricingRequest() {
|
|
424
|
+
return {
|
|
425
|
+
// Only the actor type: the signed service JWT is the identity. An x-actor-id on a
|
|
426
|
+
// service token is read as "on behalf of" and downgrades the actor.
|
|
427
|
+
headers: {
|
|
428
|
+
"x-actor-type": "service"
|
|
429
|
+
},
|
|
430
|
+
timeout: this.requestTimeoutMs,
|
|
431
|
+
skipRetry: true,
|
|
432
|
+
skipCircuitBreaker: true
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
/** Whether billing prices cache counts. Any failure reads as "no" and falls back to input/output. */
|
|
436
|
+
async supportsCachePricing(client, model) {
|
|
437
|
+
try {
|
|
438
|
+
const response = await client.crossLayerQuery({
|
|
439
|
+
...this.pricingRequest(),
|
|
440
|
+
query: CACHE_PRICING_CAPABILITY_QUERY,
|
|
441
|
+
variables: {}
|
|
442
|
+
});
|
|
443
|
+
if (response.data?.aiCacheTokenPricingSupported === true) return true;
|
|
444
|
+
} catch {
|
|
445
|
+
}
|
|
446
|
+
this.log.warn("[AiCreditMeter] billing does not price cache tokens; quoting input/output only", {
|
|
447
|
+
productId: this.productId,
|
|
448
|
+
model
|
|
449
|
+
});
|
|
450
|
+
return false;
|
|
451
|
+
}
|
|
401
452
|
resolveServiceName() {
|
|
402
453
|
return this.serviceName || process.env["SERVICE_IDENTITY"] || process.env["SERVICE_NAME"] || `wspace-${this.productId}-svc`;
|
|
403
454
|
}
|
|
@@ -431,5 +482,5 @@ var AiCreditMeter = class {
|
|
|
431
482
|
};
|
|
432
483
|
|
|
433
484
|
export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditInputError, AiCreditMeter, aiCreditIdempotencyHash, aiCreditQuotaName, ai_credits_exports, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage };
|
|
434
|
-
//# sourceMappingURL=chunk-
|
|
435
|
-
//# sourceMappingURL=chunk-
|
|
485
|
+
//# sourceMappingURL=chunk-QUF27D73.js.map
|
|
486
|
+
//# sourceMappingURL=chunk-QUF27D73.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/ai-credits/index.ts","../src/ai-credits/validation.ts","../src/ai-credits/errors.ts","../src/ai-credits/meter.ts"],"names":["AI_CREDIT_MAX_TOKENS_PER_REPORT","blank","value","trim","length","validateAiTokenUsage","report","maxTokensPerReport","sessionId","messageId","model","inputTokens","outputTokens","counts","cacheReadTokens","cacheWriteTokens","code","message","some","count","Number","isSafeInteger","reduce","sum","aiCreditQuotaName","productId","id","Error","defaultAiCreditHashPrefix","encodeAiCreditHashComponent","replaceAll","aiCreditIdempotencyHash","prefix","head","AiCreditInputError","graphqlCode","name","isAiCreditInputError","error","DEFAULT_REQUEST_TIMEOUT_MS","QUOTE_AI_CREDITS_QUERY","QUOTE_AI_CREDITS_WITH_CACHE_QUERY","CACHE_PRICING_CAPABILITY_QUERY","TRACK_USAGE_MUTATION","WORKSPACE_QUOTA_ASSIGNMENTS_QUERY","errorMessage","String","requireNonEmpty","field","trimmed","internalServiceHeaders","token","process","env","AiCreditMeter","quotaName","hashPrefix","serviceName","activityGatewayUrl","billingGatewayUrl","pricingOption","fetchImpl","requestTimeoutMs","guard","log","pricing","options","undefined","pricingClient","fetch","url","init","logger","sdkLogger","hashFor","quote","input","warn","client","getPricingClient","hasCacheCounts","priceCache","supportsCachePricing","response","crossLayerQuery","pricingRequest","query","variables","errors","map","join","credits","data","quoteAiCredits","isFinite","charge","workspaceId","invalid","hash","logFields","skipped","reason","detail","status","verdict","allow","trackUsage","amount","description","userId","metadata","info","readUsage","activityRequest","rows","workspaceQuotaAssignments","filter","row","isActive","used","noLimit","limit","remaining","Math","max","assignments","record","workspace","controller","AbortController","timeout","setTimeout","abort","method","headers","resolveServiceName","body","JSON","stringify","signal","ok","text","catch","statusText","slice","result","json","clearTimeout","skipRetry","skipCircuitBreaker","aiCacheTokenPricingSupported","option","gateway","identity","GatewayClient","layer","serviceIdentity","crossLayerGatewayUrl","enableLogging"],"mappings":";;;;AAAA,IAAA,kBAAA,GAAA;;;;;;;;;;;;;;ACWO,IAAMA,+BAAAA,GAAkC;AAiB/C,SAASC,MAAMC,KAAAA,EAAgC;AAC7C,EAAA,OAAO,OAAOA,KAAAA,KAAU,QAAA,IAAYA,KAAAA,CAAMC,IAAAA,GAAOC,MAAAA,KAAW,CAAA;AAC9D;AAFSH,MAAAA,CAAAA,KAAAA,EAAAA,OAAAA,CAAAA;AAaF,SAASI,oBAAAA,CACdC,MAAAA,EAEAC,kBAAAA,GAA6BP,+BAAAA,EAA+B;AAE5D,EAAA,MAAM,EAAEQ,SAAAA,EAAWC,SAAAA,EAAWC,KAAAA,EAAOC,WAAAA,EAAaC,cAAY,GAAKN,MAAAA;AAGnE,EAAA,MAAMO,MAAAA,GAAS;AAACF,IAAAA,WAAAA;AAAaC,IAAAA,YAAAA;AAAcN,IAAAA,MAAAA,CAAOQ,eAAAA,IAAmB,CAAA;AAAGR,IAAAA,MAAAA,CAAOS,gBAAAA,IAAoB;;AAEnG,EAAA,IAAId,KAAAA,CAAMO,SAAAA,CAAAA,EAAY,OAAO;IAAEQ,IAAAA,EAAM,qBAAA;IAAuBC,OAAAA,EAAS;AAAyB,GAAA;AAC9F,EAAA,IAAIhB,KAAAA,CAAMQ,SAAAA,CAAAA,EAAY,OAAO;IAAEO,IAAAA,EAAM,qBAAA;IA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MAAA,MAAMC,OAAAA,GAAU,MAAM,OAAO,sBAAA,CAAA;AAC7B,MAAA,MAAMC,QAAAA,GAAW,KAAKlB,kBAAAA,EAAkB;AACxC,MAAA,OAAO,IAAIiB,QAAQE,aAAAA,CAAc;;QAE/BC,KAAAA,EAAO,QAAA;QACPlG,WAAAA,EAAagG,QAAAA;QACbG,eAAAA,EAAiBH,QAAAA;QACjBI,oBAAAA,EAAsBvF,GAAAA;AACtB4D,QAAAA,OAAAA,EAAS,IAAA,CAAKpE,gBAAAA;QACdgG,aAAAA,EAAe1G,OAAAA,CAAQC,GAAAA,CAAI,UAAA,CAAA,KAAgB;OAC7C,CAAA;IACF,CAAA,GAAA;AACA,IAAA,IAAA,CAAKY,OAAAA,GAAU;AAAEK,MAAAA,GAAAA;AAAKQ,MAAAA;AAAO,KAAA;AAE7BA,IAAAA,MAAAA,CAAOgE,MAAM,MAAA;AACX,MAAA,IAAI,IAAA,CAAK7E,OAAAA,EAASa,MAAAA,KAAWA,MAAAA,OAAab,OAAAA,GAAU,IAAA;IACtD,CAAA,CAAA;AACA,IAAA,OAAOa,MAAAA;AACT,EAAA;AACF","file":"chunk-QUF27D73.js","sourcesContent":["/**\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`, `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 AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditGuardVerdict,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditQuoteInput,\n AiCreditSkipReason,\n AiTokenUsageReport,\n WorkspaceQuotaUsage,\n} from './types.js';\n","/**\n * Pure rules for AI-credit metering: report validation, quota naming and the\n * idempotency hash. Dependency-free so products can unit-test against them.\n */\nimport type { AiTokenUsageReport } from './types.js';\n\n/**\n * Sanity ceiling for one turn's token counts. Real turns stay far below it even\n * with a large context window; credits price at roughly one credit per input\n * token, so an unbounded count would be an unbounded charge.\n */\nexport const AI_CREDIT_MAX_TOKENS_PER_REPORT = 2_000_000;\n\n/** Stable machine-readable reasons a report is rejected. */\nexport type AiTokenUsageViolation =\n | 'SESSION_ID_REQUIRED'\n | 'MESSAGE_ID_REQUIRED'\n | 'MODEL_REQUIRED'\n | 'TOKEN_COUNTS_NOT_INTEGERS'\n | 'TOKEN_COUNTS_NEGATIVE'\n | 'TOKEN_COUNTS_EXCEED_MAXIMUM';\n\nexport interface AiTokenUsageValidationError {\n code: AiTokenUsageViolation;\n /** Operator-readable reason. Products usually map it to their i18n key by `code`. */\n message: string;\n}\n\nfunction blank(value: string | null | undefined): boolean {\n return typeof value !== 'string' || value.trim().length === 0;\n}\n\n/**\n * Validate a reported turn. Returns null when it is acceptable, otherwise the\n * first violation. Does not throw, so callers choose the error type (VC raises\n * an i18n'd BAD_USER_INPUT, HB a client-facing error).\n *\n * `messageId` is required, not optional: without it the idempotency hash\n * collapses to the session and only the first turn of a conversation would ever\n * be charged. `model` is required because it selects the per-token price.\n */\nexport function validateAiTokenUsage(\n report: Partial<Pick<AiTokenUsageReport, 'sessionId' | 'messageId' | 'model'>> &\n Pick<AiTokenUsageReport, 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'>,\n maxTokensPerReport: number = AI_CREDIT_MAX_TOKENS_PER_REPORT\n): AiTokenUsageValidationError | null {\n const { sessionId, messageId, model, inputTokens, outputTokens } = report;\n // Cache counts are optional; an omitted/null count is zero. They are checked and\n // summed with the ordinary counts, because they are priced too.\n const counts = [inputTokens, outputTokens, report.cacheReadTokens ?? 0, report.cacheWriteTokens ?? 0];\n\n if (blank(sessionId)) return { code: 'SESSION_ID_REQUIRED', message: 'sessionId is required.' };\n if (blank(messageId)) return { code: 'MESSAGE_ID_REQUIRED', message: 'messageId is required.' };\n if (blank(model)) return { code: 'MODEL_REQUIRED', message: 'model is required.' };\n if (counts.some((count) => !Number.isSafeInteger(count))) {\n return { code: 'TOKEN_COUNTS_NOT_INTEGERS', message: 'Token counts must be integers.' };\n }\n if (counts.some((count) => count < 0)) {\n return { code: 'TOKEN_COUNTS_NEGATIVE', message: 'Token counts must be non-negative.' };\n }\n if (counts.reduce((sum, count) => sum + count, 0) > maxTokensPerReport) {\n return {\n code: 'TOKEN_COUNTS_EXCEED_MAXIMUM',\n message: `Reported tokens exceed the per-report maximum of ${maxTokensPerReport}.`,\n };\n }\n return null;\n}\n\n/**\n * The quota a product's AI credits draw from: `<productId>.ai.credits`\n * (`vibecontrols.ai.credits`, `healthybowl.ai.credits`, …). Must match what\n * billing seeds exactly — a name mismatch reads as \"not provisioned\".\n */\nexport function aiCreditQuotaName(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('aiCreditQuotaName requires a productId');\n return `${id}.ai.credits`;\n}\n\n/** Default hash prefix for a product: `<productId>:aicredit`. */\nexport function defaultAiCreditHashPrefix(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('defaultAiCreditHashPrefix requires a productId');\n return `${id}:aicredit`;\n}\n\n/**\n * Make a hash component unambiguous when joined with `:`. Ids are `ID!` and may\n * contain colons, so raw joining would let `(\"a:b\",\"c\")` and `(\"a\",\"b:c\")`\n * collide — and activity's unique `usage_records.hash` would then drop the second,\n * genuinely different turn as a replay. `%` is escaped first so the escape itself\n * cannot collide. A no-op for ids containing neither character (uuids, `msg_…`),\n * so existing hashes are reproduced byte-for-byte.\n */\nexport function encodeAiCreditHashComponent(value: string): string {\n return value.replaceAll('%', '%25').replaceAll(':', '%3A');\n}\n\n/**\n * Idempotency hash for one turn: `<prefix>:<sessionId>:<messageId>`.\n *\n * activity-svc's unique index is on `hash` ALONE, shared by every product, so\n * the prefix must be product-namespaced. Products that already write a different\n * prefix must keep passing it (`aicredit` for VibeControls, `hb-assistant` for\n * HealthyBowl) — changing a prefix re-hashes every in-flight turn, so a client\n * retry across the deploy would be charged twice.\n */\nexport function aiCreditIdempotencyHash(prefix: string, sessionId: string, messageId: string): string {\n const head = prefix.trim();\n if (!head) throw new Error('aiCreditIdempotencyHash requires a prefix');\n if (blank(sessionId) || blank(messageId)) {\n throw new Error('aiCreditIdempotencyHash requires a sessionId and a messageId');\n }\n return `${head}:${encodeAiCreditHashComponent(sessionId)}:${encodeAiCreditHashComponent(messageId)}`;\n}\n","/**\n * Errors raised by the AI-credit meter. Only caller mistakes throw; billing and\n * recording failures are returned as a skipped charge (see `AiCreditMeter.charge`).\n */\nimport type { AiTokenUsageViolation } from './validation.js';\n\nexport type AiCreditInputErrorCode = AiTokenUsageViolation | 'WORKSPACE_ID_REQUIRED';\n\n/** A malformed report or missing workspace context. Map it to BAD_USER_INPUT. */\nexport class AiCreditInputError extends Error {\n readonly code: AiCreditInputErrorCode;\n /** GraphQL error code products should surface. */\n readonly graphqlCode = 'BAD_USER_INPUT';\n\n constructor(code: AiCreditInputErrorCode, message: string) {\n super(message);\n this.name = 'AiCreditInputError';\n this.code = code;\n }\n}\n\nexport function isAiCreditInputError(error: unknown): error is AiCreditInputError {\n return error instanceof AiCreditInputError;\n}\n","/**\n * AiCreditMeter — cost-weighted, idempotent AI-credit charging for an assistant turn.\n *\n * VibeControls (`utils/usage-billing.ts` + `modules/aicredit`) and HealthyBowl\n * (`utils/ai-credit-usage.ts` + `HealthyBowlAiCreditProvider`) each carried their\n * own copy of this path. This is the shared version, built on the path that is\n * proven to record in prod:\n *\n * 1. **Price** — `quoteAiCredits(model, inputTokens, outputTokens[, cacheReadTokens,\n * cacheWriteTokens])` on global-billing-svc, cross-layer through the be-sdk `GatewayClient`\n * (`GLOBAL_PUBLIC_GATEWAY_URL`, which resolves to the peer VPC's internal ALB\n * over the Route53 private zone). The amount is always computed server-side\n * from billing's per-model prices; a client never supplies it.\n * 2. **Record** — wspace-activity-svc `trackUsage` on the workspace's\n * `WorkspaceQuotaAssignment`, same-layer through the wspace INTERNAL gateway\n * (`WSPACE_INT_GATEWAY_URL`) with `x-workspace-id`. Activity resolves the\n * assignment itself and dedupes on the unique `usage_records.hash`, so a\n * replayed report for the same session + message is a no-op charge.\n *\n * Contract:\n * - {@link AiCreditMeter.charge} validates first and THROWS\n * {@link AiCreditInputError} for a malformed report (a caller bug worth\n * surfacing). After that it never throws: the user already has the answer, so a\n * metering failure must not become a user-visible error. Every un-charged\n * outcome is returned as `status: 'skipped'` with a reason AND logged.\n * - A null quote skips the charge: under-charging during an outage is\n * recoverable, charging an invented amount is not.\n * - Recording only counts as success when activity answers `trackUsage: true`.\n *\n * The meter is a METER, not a gate. Products that need a pre-flight gate keep a\n * `@usage(checkQuota: true, trackUsage: false)` field (VC `checkAiCredits`); the\n * charging field must carry NO `@usage(trackUsage)` directive, or the turn is\n * charged twice.\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 AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditQuoteInput,\n AiCreditSkipReason,\n WorkspaceQuotaUsage,\n} from './types.js';\nimport {\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n aiCreditIdempotencyHash,\n aiCreditQuotaName,\n defaultAiCreditHashPrefix,\n validateAiTokenUsage,\n} from './validation.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\nconst QUOTE_AI_CREDITS_QUERY = `query AiCreditMeterQuote($model: String!, $inputTokens: Int!, $outputTokens: Int!) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens)\n}`;\n\nconst QUOTE_AI_CREDITS_WITH_CACHE_QUERY = `query AiCreditMeterQuoteWithCache($model: String!, $inputTokens: Int!, $outputTokens: Int!, $cacheReadTokens: Int, $cacheWriteTokens: Int) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens, cacheReadTokens: $cacheReadTokens, cacheWriteTokens: $cacheWriteTokens)\n}`;\n\nconst CACHE_PRICING_CAPABILITY_QUERY = `query AiCreditMeterCachePricingSupported {\n aiCacheTokenPricingSupported\n}`;\n\nconst TRACK_USAGE_MUTATION = `mutation AiCreditMeterTrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n}`;\n\nconst WORKSPACE_QUOTA_ASSIGNMENTS_QUERY = `query AiCreditMeterQuotaAssignments($workspaceId: ID!) {\n workspaceQuotaAssignments(workspaceId: $workspaceId) { quotaName used limit noLimit isActive }\n}`;\n\nexport interface AiCreditMeterOptions {\n /** Product id stamped on usage records, e.g. `vibecontrols`. */\n productId: string;\n /** This service's name; sent as the service identity. Default `SERVICE_IDENTITY` / `SERVICE_NAME` env. */\n serviceName?: string;\n /** Quota to charge. Default `<productId>.ai.credits`. */\n quotaName?: string;\n /**\n * Idempotency-hash prefix. Default `<productId>:aicredit`. A product that already\n * records under another prefix MUST keep it (see {@link aiCreditIdempotencyHash}).\n */\n hashPrefix?: string;\n /** wspace internal gateway URL. Default `WSPACE_INT_GATEWAY_URL` env (read per call). */\n activityGatewayUrl?: string;\n /** Cross-layer global gateway URL for pricing. Default `GLOBAL_PUBLIC_GATEWAY_URL` env (read per call). */\n billingGatewayUrl?: string;\n /**\n * Pricing transport, or a factory for one. Default: a lazily constructed be-sdk\n * `GatewayClient` bound to {@link billingGatewayUrl}, rebuilt if the URL changes.\n */\n pricingClient?:\n | AiCreditPricingTransport\n | ((url: string) => AiCreditPricingTransport | Promise<AiCreditPricingTransport>);\n /** `fetch` for the activity-svc calls. Default: the global `fetch`. */\n fetch?: AiCreditFetch;\n /** Per-request timeout. Default 5s. */\n requestTimeoutMs?: number;\n /** Per-report token ceiling. Default {@link AI_CREDIT_MAX_TOKENS_PER_REPORT}. */\n maxTokensPerReport?: number;\n /** Optional pre-charge hook (e.g. a report-rate ceiling). */\n guard?: AiCreditChargeGuard;\n /** Logger. Default the be-sdk logger. */\n logger?: AiCreditLogger;\n}\n\ninterface GraphQLBody<T> {\n data?: T | null;\n errors?: { message: string }[] | null;\n}\n\ninterface AssignmentRow {\n quotaName: string;\n used: number;\n limit: number | null;\n noLimit: boolean;\n isActive: boolean;\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error);\n}\n\nfunction requireNonEmpty(value: string | undefined, field: string): string {\n const trimmed = value?.trim() ?? '';\n if (!trimmed) throw new Error(`AiCreditMeter: ${field} is required`);\n return trimmed;\n}\n\n/** Same-layer auth header the wspace internal gateway expects from in-cluster callers. */\nfunction internalServiceHeaders(): Record<string, string> {\n const token = process.env['TRUSTED_GATEWAY_TOKEN'] || process.env['INTERNAL_SERVICE_TOKEN'];\n return token ? { 'x-internal-service-token': token } : {};\n}\n\nexport class AiCreditMeter {\n readonly productId: string;\n readonly quotaName: string;\n readonly hashPrefix: string;\n private readonly serviceName: string | undefined;\n private readonly activityGatewayUrl: string | undefined;\n private readonly billingGatewayUrl: string | undefined;\n private readonly pricingOption: AiCreditMeterOptions['pricingClient'];\n private readonly fetchImpl: AiCreditFetch;\n private readonly requestTimeoutMs: number;\n private readonly maxTokensPerReport: number;\n private readonly guard: AiCreditChargeGuard | undefined;\n private readonly log: AiCreditLogger;\n private pricing: { url: string; client: Promise<AiCreditPricingTransport> } | null = null;\n\n constructor(options: AiCreditMeterOptions) {\n this.productId = requireNonEmpty(options.productId, 'productId');\n this.quotaName = options.quotaName?.trim() || aiCreditQuotaName(this.productId);\n this.hashPrefix = options.hashPrefix?.trim() || defaultAiCreditHashPrefix(this.productId);\n this.serviceName = options.serviceName?.trim() || undefined;\n this.activityGatewayUrl = options.activityGatewayUrl?.trim() || undefined;\n this.billingGatewayUrl = options.billingGatewayUrl?.trim() || undefined;\n this.pricingOption = options.pricingClient;\n this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));\n this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;\n if (!Number.isSafeInteger(this.requestTimeoutMs) || this.requestTimeoutMs <= 0) {\n throw new Error('AiCreditMeter: requestTimeoutMs must be a positive integer');\n }\n this.maxTokensPerReport = options.maxTokensPerReport ?? AI_CREDIT_MAX_TOKENS_PER_REPORT;\n if (!Number.isSafeInteger(this.maxTokensPerReport) || this.maxTokensPerReport <= 0) {\n throw new Error('AiCreditMeter: maxTokensPerReport must be a positive integer');\n }\n this.guard = options.guard;\n this.log = options.logger ?? sdkLogger;\n }\n\n /** The idempotency hash this meter records a turn under. */\n hashFor(sessionId: string, messageId: string): string {\n return aiCreditIdempotencyHash(this.hashPrefix, sessionId, messageId);\n }\n\n /**\n * Server-side price of one model call in credits, from billing's per-model\n * token table. Returns null — after logging why — when it cannot be priced.\n *\n * When the turn reports cache counts, billing is first asked whether it prices\n * them (`aiCacheTokenPricingSupported`). If it does, the cache counts are priced\n * with its cache-token prices; if it does not (an older billing, or the probe\n * fails), the turn is priced on input/output alone. The answer is not cached,\n * so a billing rollback is picked up on the next report.\n */\n async quote(input: AiCreditQuoteInput): Promise<number | null> {\n const url = this.billingGatewayUrl ?? process.env['GLOBAL_PUBLIC_GATEWAY_URL']?.trim();\n if (!url) {\n this.log.warn('[AiCreditMeter] GLOBAL_PUBLIC_GATEWAY_URL not set; cannot price AI credits', {\n productId: this.productId,\n model: input.model,\n });\n return null;\n }\n try {\n const client = await this.getPricingClient(url);\n const hasCacheCounts = input.cacheReadTokens != null || input.cacheWriteTokens != null;\n const priceCache = hasCacheCounts && (await this.supportsCachePricing(client, input.model));\n const response = await client.crossLayerQuery<{ quoteAiCredits?: number | null }>({\n ...this.pricingRequest(),\n query: priceCache ? QUOTE_AI_CREDITS_WITH_CACHE_QUERY : QUOTE_AI_CREDITS_QUERY,\n variables: {\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n ...(priceCache\n ? { cacheReadTokens: input.cacheReadTokens ?? 0, cacheWriteTokens: input.cacheWriteTokens ?? 0 }\n : {}),\n },\n });\n if (response.errors?.length) {\n throw new Error(response.errors.map((error) => error.message).join(', '));\n }\n const credits = response.data?.quoteAiCredits;\n if (typeof credits !== 'number' || !Number.isFinite(credits) || credits < 0) {\n throw new Error(`quoteAiCredits returned no usable value (${String(credits)})`);\n }\n return credits;\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to quote AI credits; skipping charge', {\n productId: this.productId,\n model: input.model,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Validate, price and record one completed assistant turn. See the module\n * header for the contract: throws only {@link AiCreditInputError}.\n */\n async charge(input: AiCreditChargeInput): Promise<AiCreditChargeResult> {\n const workspaceId = input.workspaceId?.trim() ?? '';\n if (!workspaceId) {\n throw new AiCreditInputError('WORKSPACE_ID_REQUIRED', 'This request has no workspace context.');\n }\n const invalid = validateAiTokenUsage(input, this.maxTokensPerReport);\n if (invalid) throw new AiCreditInputError(invalid.code, invalid.message);\n\n const hash = this.hashFor(input.sessionId, input.messageId);\n const logFields = {\n productId: this.productId,\n quotaName: this.quotaName,\n workspaceId,\n sessionId: input.sessionId,\n messageId: input.messageId,\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n };\n const skipped = (reason: AiCreditSkipReason, credits: number | null, detail?: string): AiCreditChargeResult => {\n this.log.warn(`[AiCreditMeter] turn not charged (${reason})`, { ...logFields, credits, detail });\n return { status: 'skipped', reason, credits, hash, quotaName: this.quotaName, ...(detail ? { detail } : {}) };\n };\n\n if (this.guard) {\n try {\n const verdict = await this.guard({ ...input, workspaceId });\n if (!verdict.allow) return skipped('GUARD_REFUSED', null, verdict.detail);\n } catch (error) {\n // Fail open: a guard's infrastructure blip must not silently stop metering.\n this.log.warn('[AiCreditMeter] charge guard threw; charging anyway', {\n ...logFields,\n error: errorMessage(error),\n });\n }\n }\n\n const credits = await this.quote(input);\n if (credits === null) return skipped('NOT_PRICED', null);\n if (credits <= 0) return skipped('ZERO_COST', credits);\n\n try {\n await this.trackUsage({\n workspaceId,\n amount: credits,\n description: input.description?.trim() || `AI credits for session ${input.sessionId}`,\n userId: input.userId ?? undefined,\n hash,\n metadata: {\n model: input.model,\n sessionId: input.sessionId,\n messageId: input.messageId,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n ...(input.cacheReadTokens != null || input.cacheWriteTokens != null\n ? { cacheReadTokens: input.cacheReadTokens ?? 0, cacheWriteTokens: input.cacheWriteTokens ?? 0 }\n : {}),\n credits,\n ...input.metadata,\n },\n });\n } catch (error) {\n return skipped('RECORD_FAILED', credits, errorMessage(error));\n }\n\n this.log.info(`[AiCreditMeter] Charged ${credits} AI credits for session ${input.sessionId}`, {\n ...logFields,\n credits,\n });\n return { status: 'charged', credits, hash, quotaName: this.quotaName };\n }\n\n /**\n * Read the quota's ENFORCED usage from wspace-activity-svc — the ledger the\n * charge lands on and the gateway's `@usage` check reads. All active rows are\n * summed, because a workspace can hold several (plan + add-ons, or duplicate\n * rows) and `checkWorkspaceQuota` sums them; a single-row read under-reports.\n *\n * Returns null (never throws) when activity is unreachable or no assignment\n * exists, so a screen can show \"not provisioned\" instead of a confident zero.\n */\n async readUsage(workspaceId: string, quotaName: string = this.quotaName): Promise<WorkspaceQuotaUsage | null> {\n try {\n const data = await this.activityRequest<{ workspaceQuotaAssignments?: AssignmentRow[] | null }>(\n workspaceId,\n WORKSPACE_QUOTA_ASSIGNMENTS_QUERY,\n { workspaceId: workspaceId.trim() }\n );\n const rows = (data.workspaceQuotaAssignments ?? []).filter((row) => row.isActive && row.quotaName === quotaName);\n if (rows.length === 0) return null;\n const used = rows.reduce((sum, row) => sum + (Number.isFinite(row.used) ? row.used : 0), 0);\n const noLimit = rows.some((row) => row.noLimit);\n const limit = noLimit ? null : rows.reduce((sum, row) => sum + (row.limit ?? 0), 0);\n return {\n quotaName,\n used,\n limit,\n noLimit,\n remaining: limit === null ? null : Math.max(limit - used, 0),\n assignments: rows.length,\n };\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to read workspace quota usage', {\n productId: this.productId,\n quotaName,\n workspaceId,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n private async trackUsage(record: {\n workspaceId: string;\n amount: number;\n description: string;\n userId: string | undefined;\n hash: string;\n metadata: Record<string, unknown>;\n }): Promise<void> {\n const data = await this.activityRequest<{ trackUsage?: boolean | null }>(record.workspaceId, TRACK_USAGE_MUTATION, {\n input: {\n // Sent in the input AND as x-workspace-id: activity takes the workspace from request\n // context, and the @rbac directive resolves input.workspaceId.\n workspaceId: record.workspaceId,\n quotaName: this.quotaName,\n productId: this.productId,\n amount: record.amount,\n description: record.description,\n userId: record.userId,\n hash: record.hash,\n metadata: record.metadata,\n },\n });\n if (data.trackUsage !== true) {\n throw new Error(`trackUsage did not confirm the record (returned ${String(data.trackUsage)})`);\n }\n }\n\n private async activityRequest<T>(workspaceId: string, query: string, variables: Record<string, unknown>): Promise<T> {\n const url = this.activityGatewayUrl ?? process.env['WSPACE_INT_GATEWAY_URL']?.trim();\n if (!url) throw new Error('WSPACE_INT_GATEWAY_URL not set; cannot reach wspace-activity-svc');\n const workspace = workspaceId.trim();\n if (!workspace) throw new Error('workspaceId is required');\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.requestTimeoutMs);\n try {\n const response = await this.fetchImpl(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-actor-type': 'service',\n 'x-actor-id': this.resolveServiceName(),\n ...internalServiceHeaders(),\n 'x-workspace-id': workspace,\n },\n body: JSON.stringify({ query, variables }),\n signal: controller.signal,\n });\n if (!response.ok) {\n const body = await response.text().catch(() => response.statusText);\n throw new Error(`activity request failed with HTTP ${response.status}: ${body.slice(0, 500)}`);\n }\n const result = (await response.json()) as GraphQLBody<T>;\n if (result.errors?.length) {\n throw new Error(result.errors.map((error) => error.message).join(', '));\n }\n if (!result.data) throw new Error('activity response did not include data');\n return result.data;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n /** Options shared by every pricing call. */\n private pricingRequest(): Pick<GraphQLRequestOptions, 'headers' | 'timeout' | 'skipRetry' | 'skipCircuitBreaker'> {\n return {\n // Only the actor type: the signed service JWT is the identity. An x-actor-id on a\n // service token is read as \"on behalf of\" and downgrades the actor.\n headers: { 'x-actor-type': 'service' },\n timeout: this.requestTimeoutMs,\n skipRetry: true,\n skipCircuitBreaker: true,\n };\n }\n\n /** Whether billing prices cache counts. Any failure reads as \"no\" and falls back to input/output. */\n private async supportsCachePricing(client: AiCreditPricingTransport, model: string): Promise<boolean> {\n try {\n const response = await client.crossLayerQuery<{ aiCacheTokenPricingSupported?: boolean | null }>({\n ...this.pricingRequest(),\n query: CACHE_PRICING_CAPABILITY_QUERY,\n variables: {},\n });\n if (response.data?.aiCacheTokenPricingSupported === true) return true;\n } catch {\n // Logged below; the turn is still priced on input/output.\n }\n this.log.warn('[AiCreditMeter] billing does not price cache tokens; quoting input/output only', {\n productId: this.productId,\n model,\n });\n return false;\n }\n\n private resolveServiceName(): string {\n return (\n this.serviceName ||\n process.env['SERVICE_IDENTITY'] ||\n process.env['SERVICE_NAME'] ||\n `wspace-${this.productId}-svc`\n );\n }\n\n private getPricingClient(url: string): Promise<AiCreditPricingTransport> {\n // Rebuilt when the URL changes, so a client bound to a stale URL cannot keep failing.\n if (this.pricing && this.pricing.url === url) return this.pricing.client;\n const option = this.pricingOption;\n const client = (async (): Promise<AiCreditPricingTransport> => {\n if (option && typeof option === 'function') return option(url);\n if (option) return option;\n const gateway = await import('../gateway/client.js');\n const identity = this.resolveServiceName();\n return new gateway.GatewayClient({\n // This service's OWN layer; the be-sdk signs the service JWT because the call leaves it.\n layer: 'wspace',\n serviceName: identity,\n serviceIdentity: identity,\n crossLayerGatewayUrl: url,\n timeout: this.requestTimeoutMs,\n enableLogging: process.env['NODE_ENV'] !== 'production',\n });\n })();\n this.pricing = { url, client };\n // A failed construction must not be cached forever.\n client.catch(() => {\n if (this.pricing?.client === client) this.pricing = null;\n });\n return client;\n }\n}\n"]}
|
|
@@ -6,7 +6,10 @@ interface AiTokenUsageReport {
|
|
|
6
6
|
model: string;
|
|
7
7
|
inputTokens: number;
|
|
8
8
|
outputTokens: number;
|
|
9
|
+
cacheReadTokens?: number | null;
|
|
10
|
+
cacheWriteTokens?: number | null;
|
|
9
11
|
}
|
|
12
|
+
type AiCreditQuoteInput = Pick<AiTokenUsageReport, 'model' | 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'>;
|
|
10
13
|
interface AiCreditChargeInput extends AiTokenUsageReport {
|
|
11
14
|
workspaceId: string;
|
|
12
15
|
userId?: string | null;
|
|
@@ -56,7 +59,7 @@ interface AiTokenUsageValidationError {
|
|
|
56
59
|
code: AiTokenUsageViolation;
|
|
57
60
|
message: string;
|
|
58
61
|
}
|
|
59
|
-
declare function validateAiTokenUsage(report: Partial<Pick<AiTokenUsageReport, 'sessionId' | 'messageId' | 'model'>> & Pick<AiTokenUsageReport, 'inputTokens' | 'outputTokens'>, maxTokensPerReport?: number): AiTokenUsageValidationError | null;
|
|
62
|
+
declare function validateAiTokenUsage(report: Partial<Pick<AiTokenUsageReport, 'sessionId' | 'messageId' | 'model'>> & Pick<AiTokenUsageReport, 'inputTokens' | 'outputTokens' | 'cacheReadTokens' | 'cacheWriteTokens'>, maxTokensPerReport?: number): AiTokenUsageValidationError | null;
|
|
60
63
|
declare function aiCreditQuotaName(productId: string): string;
|
|
61
64
|
declare function defaultAiCreditHashPrefix(productId: string): string;
|
|
62
65
|
declare function encodeAiCreditHashComponent(value: string): string;
|
|
@@ -100,15 +103,13 @@ declare class AiCreditMeter {
|
|
|
100
103
|
private pricing;
|
|
101
104
|
constructor(options: AiCreditMeterOptions);
|
|
102
105
|
hashFor(sessionId: string, messageId: string): string;
|
|
103
|
-
quote(input:
|
|
104
|
-
model: string;
|
|
105
|
-
inputTokens: number;
|
|
106
|
-
outputTokens: number;
|
|
107
|
-
}): Promise<number | null>;
|
|
106
|
+
quote(input: AiCreditQuoteInput): Promise<number | null>;
|
|
108
107
|
charge(input: AiCreditChargeInput): Promise<AiCreditChargeResult>;
|
|
109
108
|
readUsage(workspaceId: string, quotaName?: string): Promise<WorkspaceQuotaUsage | null>;
|
|
110
109
|
private trackUsage;
|
|
111
110
|
private activityRequest;
|
|
111
|
+
private pricingRequest;
|
|
112
|
+
private supportsCachePricing;
|
|
112
113
|
private resolveServiceName;
|
|
113
114
|
private getPricingClient;
|
|
114
115
|
}
|
|
@@ -127,6 +128,7 @@ type index_AiCreditMeter = AiCreditMeter;
|
|
|
127
128
|
declare const index_AiCreditMeter: typeof AiCreditMeter;
|
|
128
129
|
type index_AiCreditMeterOptions = AiCreditMeterOptions;
|
|
129
130
|
type index_AiCreditPricingTransport = AiCreditPricingTransport;
|
|
131
|
+
type index_AiCreditQuoteInput = AiCreditQuoteInput;
|
|
130
132
|
type index_AiCreditSkipReason = AiCreditSkipReason;
|
|
131
133
|
type index_AiTokenUsageReport = AiTokenUsageReport;
|
|
132
134
|
type index_AiTokenUsageValidationError = AiTokenUsageValidationError;
|
|
@@ -139,7 +141,7 @@ declare const index_encodeAiCreditHashComponent: typeof encodeAiCreditHashCompon
|
|
|
139
141
|
declare const index_isAiCreditInputError: typeof isAiCreditInputError;
|
|
140
142
|
declare const index_validateAiTokenUsage: typeof validateAiTokenUsage;
|
|
141
143
|
declare namespace index {
|
|
142
|
-
export { index_AI_CREDIT_MAX_TOKENS_PER_REPORT as AI_CREDIT_MAX_TOKENS_PER_REPORT, type index_AiCreditChargeGuard as AiCreditChargeGuard, type index_AiCreditChargeInput as AiCreditChargeInput, type index_AiCreditChargeResult as AiCreditChargeResult, type index_AiCreditFetch as AiCreditFetch, type index_AiCreditGuardVerdict as AiCreditGuardVerdict, index_AiCreditInputError as AiCreditInputError, type index_AiCreditInputErrorCode as AiCreditInputErrorCode, type index_AiCreditLogger as AiCreditLogger, index_AiCreditMeter as AiCreditMeter, type index_AiCreditMeterOptions as AiCreditMeterOptions, type index_AiCreditPricingTransport as AiCreditPricingTransport, type index_AiCreditSkipReason as AiCreditSkipReason, type index_AiTokenUsageReport as AiTokenUsageReport, type index_AiTokenUsageValidationError as AiTokenUsageValidationError, type index_AiTokenUsageViolation as AiTokenUsageViolation, type index_WorkspaceQuotaUsage as WorkspaceQuotaUsage, index_aiCreditIdempotencyHash as aiCreditIdempotencyHash, index_aiCreditQuotaName as aiCreditQuotaName, index_defaultAiCreditHashPrefix as defaultAiCreditHashPrefix, index_encodeAiCreditHashComponent as encodeAiCreditHashComponent, index_isAiCreditInputError as isAiCreditInputError, index_validateAiTokenUsage as validateAiTokenUsage };
|
|
144
|
+
export { index_AI_CREDIT_MAX_TOKENS_PER_REPORT as AI_CREDIT_MAX_TOKENS_PER_REPORT, type index_AiCreditChargeGuard as AiCreditChargeGuard, type index_AiCreditChargeInput as AiCreditChargeInput, type index_AiCreditChargeResult as AiCreditChargeResult, type index_AiCreditFetch as AiCreditFetch, type index_AiCreditGuardVerdict as AiCreditGuardVerdict, index_AiCreditInputError as AiCreditInputError, type index_AiCreditInputErrorCode as AiCreditInputErrorCode, type index_AiCreditLogger as AiCreditLogger, index_AiCreditMeter as AiCreditMeter, type index_AiCreditMeterOptions as AiCreditMeterOptions, type index_AiCreditPricingTransport as AiCreditPricingTransport, type index_AiCreditQuoteInput as AiCreditQuoteInput, type index_AiCreditSkipReason as AiCreditSkipReason, type index_AiTokenUsageReport as AiTokenUsageReport, type index_AiTokenUsageValidationError as AiTokenUsageValidationError, type index_AiTokenUsageViolation as AiTokenUsageViolation, type index_WorkspaceQuotaUsage as WorkspaceQuotaUsage, index_aiCreditIdempotencyHash as aiCreditIdempotencyHash, index_aiCreditQuotaName as aiCreditQuotaName, index_defaultAiCreditHashPrefix as defaultAiCreditHashPrefix, index_encodeAiCreditHashComponent as encodeAiCreditHashComponent, index_isAiCreditInputError as isAiCreditInputError, index_validateAiTokenUsage as validateAiTokenUsage };
|
|
143
145
|
}
|
|
144
146
|
|
|
145
|
-
export { AI_CREDIT_MAX_TOKENS_PER_REPORT as A, type WorkspaceQuotaUsage as W, type AiCreditChargeGuard as a, type AiCreditChargeInput as b, type AiCreditChargeResult as c, type AiCreditFetch as d, type AiCreditGuardVerdict as e, AiCreditInputError as f, type AiCreditInputErrorCode as g, type AiCreditLogger as h, index as i, AiCreditMeter as j, type AiCreditMeterOptions as k, type AiCreditPricingTransport as l, type
|
|
147
|
+
export { AI_CREDIT_MAX_TOKENS_PER_REPORT as A, type WorkspaceQuotaUsage as W, type AiCreditChargeGuard as a, type AiCreditChargeInput as b, type AiCreditChargeResult as c, type AiCreditFetch as d, type AiCreditGuardVerdict as e, AiCreditInputError as f, type AiCreditInputErrorCode as g, type AiCreditLogger as h, index as i, AiCreditMeter as j, type AiCreditMeterOptions as k, type AiCreditPricingTransport as l, type AiCreditQuoteInput as m, type AiCreditSkipReason as n, type AiTokenUsageReport as o, type AiTokenUsageValidationError as p, type AiTokenUsageViolation as q, aiCreditIdempotencyHash as r, aiCreditQuotaName as s, defaultAiCreditHashPrefix as t, encodeAiCreditHashComponent as u, isAiCreditInputError as v, validateAiTokenUsage as w };
|
package/dist/index.d.ts
CHANGED
|
@@ -22,7 +22,7 @@ export { BillingPlanTransport, PlanTier, RESOURCE_CAP_DEFAULTS, ResourceCap, Res
|
|
|
22
22
|
export { i as Sharing } from './index-kssw5ziY.js';
|
|
23
23
|
export { i as Tags } from './index-C_t30VyQ.js';
|
|
24
24
|
export { i as Files } from './index-CN4RA1PN.js';
|
|
25
|
-
export { i as AiCredits } from './index-
|
|
25
|
+
export { i as AiCredits } from './index-HxigeZFh.js';
|
|
26
26
|
export { i as Cache } from './index-Cx5I3ydM.js';
|
|
27
27
|
export { i as Middleware } from './index-DSOpj8DI.js';
|
|
28
28
|
export { i as Observability } from './index-4gKQKZ2B.js';
|
package/dist/index.js
CHANGED
|
@@ -5,21 +5,21 @@ export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker,
|
|
|
5
5
|
import { ActivityModule, UsageModule, TrackerModule } from './chunk-STYD3MOS.js';
|
|
6
6
|
export { ActivityModule, TrackerModule, UsageModule } from './chunk-STYD3MOS.js';
|
|
7
7
|
import './chunk-GRGTUP44.js';
|
|
8
|
-
export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
|
|
9
8
|
import { TenantNotificationsModule, NotificationsModule } from './chunk-INAZ3PKF.js';
|
|
10
9
|
export { tenant_notifications_exports as Notifications, NotificationsModule } from './chunk-INAZ3PKF.js';
|
|
11
10
|
export { observability_exports as Observability } from './chunk-VAT66FJA.js';
|
|
11
|
+
export { init_exports as Init } from './chunk-PPFJTSHA.js';
|
|
12
12
|
export { platform_exports as Platform } from './chunk-N2UT3ESH.js';
|
|
13
13
|
export { prisma_exports as Prisma } from './chunk-Y2ZUUZNU.js';
|
|
14
14
|
import './chunk-3Z2VRCT6.js';
|
|
15
15
|
export { PRODUCT_RENAMES, PRODUCT_RENAME_EMIT, PRODUCT_SLUG_ALIASES, product_alias_exports as ProductAlias, RENAME_CONCERNS, billingIdVariants, emitBillingId, emitName, emitProductSlug, emitQuotaKey, emitRbacResource, emitTemplateKey, isLegacyName, isSameBillingId, isSameGraphQLName, isSameName, isSameProductSlug, isSameQuotaKey, isSameRbacResource, isSameTemplateKey, nameVariants, normalizeBillingId, normalizeGraphQLName, normalizeProductSlug, normalizeQuotaKey, normalizeRbacResource, normalizeTemplateKey, productSlugVariants, quotaKeyVariants, rbacResourceVariants, readRenamedEnv, templateKeyVariants, toCurrentName, toLegacyName } from './chunk-OBBCR6WY.js';
|
|
16
16
|
import { RBACModule } from './chunk-5JNHVKHG.js';
|
|
17
17
|
export { RBACModule, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './chunk-5JNHVKHG.js';
|
|
18
|
-
export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-EBDHIL7V.js';
|
|
19
|
-
export { init_exports as Init } from './chunk-PPFJTSHA.js';
|
|
20
18
|
export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from './chunk-MZCBEJ67.js';
|
|
19
|
+
export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-EBDHIL7V.js';
|
|
21
20
|
export { instrumentation_exports as Instrumentation } from './chunk-E5DTAGCA.js';
|
|
22
21
|
import './chunk-AWPNRV3L.js';
|
|
22
|
+
export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
|
|
23
23
|
export { dataloader_exports as DataLoader } from './chunk-NUB5GQTU.js';
|
|
24
24
|
export { export_exports as Export } from './chunk-XJKVW34Q.js';
|
|
25
25
|
export { feature_flags_exports as FeatureFlags } from './chunk-UNASM5VJ.js';
|
|
@@ -44,7 +44,7 @@ import { resolveEventStreamsUrl } from './chunk-KS2HQCJR.js';
|
|
|
44
44
|
export { graphql_exports as GraphQL } from './chunk-KMNSVLDS.js';
|
|
45
45
|
import './chunk-MWPYA2HD.js';
|
|
46
46
|
import './chunk-LKCBI6B2.js';
|
|
47
|
-
export { ai_credits_exports as AiCredits } from './chunk-
|
|
47
|
+
export { ai_credits_exports as AiCredits } from './chunk-QUF27D73.js';
|
|
48
48
|
import { AuthModule } from './chunk-GJWQK3IU.js';
|
|
49
49
|
export { AuthModule } from './chunk-GJWQK3IU.js';
|
|
50
50
|
export { utils_exports as Utils } from './chunk-B7I4TABG.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/be-sdk",
|
|
3
|
-
"version": "2026.1022.
|
|
3
|
+
"version": "2026.1022.2",
|
|
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,"sources":["../src/ai-credits/index.ts","../src/ai-credits/validation.ts","../src/ai-credits/errors.ts","../src/ai-credits/meter.ts"],"names":["AI_CREDIT_MAX_TOKENS_PER_REPORT","blank","value","trim","length","validateAiTokenUsage","report","maxTokensPerReport","sessionId","messageId","model","inputTokens","outputTokens","code","message","Number","isSafeInteger","aiCreditQuotaName","productId","id","Error","defaultAiCreditHashPrefix","encodeAiCreditHashComponent","replaceAll","aiCreditIdempotencyHash","prefix","head","AiCreditInputError","graphqlCode","name","isAiCreditInputError","error","DEFAULT_REQUEST_TIMEOUT_MS","QUOTE_AI_CREDITS_QUERY","TRACK_USAGE_MUTATION","WORKSPACE_QUOTA_ASSIGNMENTS_QUERY","errorMessage","String","requireNonEmpty","field","trimmed","internalServiceHeaders","token","process","env","AiCreditMeter","quotaName","hashPrefix","serviceName","activityGatewayUrl","billingGatewayUrl","pricingOption","fetchImpl","requestTimeoutMs","guard","log","pricing","options","undefined","pricingClient","fetch","url","init","logger","sdkLogger","hashFor","quote","input","warn","client","getPricingClient","response","crossLayerQuery","query","variables","headers","timeout","skipRetry","skipCircuitBreaker","errors","map","join","credits","data","quoteAiCredits","isFinite","charge","workspaceId","invalid","hash","logFields","skipped","reason","detail","status","verdict","allow","trackUsage","amount","description","userId","metadata","info","readUsage","activityRequest","rows","workspaceQuotaAssignments","filter","row","isActive","used","reduce","sum","noLimit","some","limit","remaining","Math","max","assignments","record","workspace","controller","AbortController","setTimeout","abort","method","resolveServiceName","body","JSON","stringify","signal","ok","text","catch","statusText","slice","result","json","clearTimeout","option","gateway","identity","GatewayClient","layer","serviceIdentity","crossLayerGatewayUrl","enableLogging"],"mappings":";;;;AAAA,IAAA,kBAAA,GAAA;;;;;;;;;;;;;;ACWO,IAAMA,+BAAAA,GAAkC;AAiB/C,SAASC,MAAMC,KAAAA,EAAgC;AAC7C,EAAA,OAAO,OAAOA,KAAAA,KAAU,QAAA,IAAYA,KAAAA,CAAMC,IAAAA,GAAOC,MAAAA,KAAW,CAAA;AAC9D;AAFSH,MAAAA,CAAAA,KAAAA,EAAAA,OAAAA,CAAAA;AAaF,SAASI,oBAAAA,CACdC,MAAAA,EAEAC,kBAAAA,GAA6BP,+BAAAA,EAA+B;AAE5D,EAAA,MAAM,EAAEQ,SAAAA,EAAWC,SAAAA,EAAWC,KAAAA,EAAOC,WAAAA,EAAaC,cAAY,GAAKN,MAAAA;AAEnE,EAAA,IAAIL,KAAAA,CAAMO,SAAAA,CAAAA,EAAY,OAAO;IAAEK,IAAAA,EAAM,qBAAA;IAAuBC,OAAAA,EAAS;AAAyB,GAAA;AAC9F,EAAA,IAAIb,KAAAA,CAAMQ,S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AA;QACjBI,oBAAAA,EAAsBrF,GAAAA;AACtBe,QAAAA,OAAAA,EAAS,IAAA,CAAKvB,gBAAAA;QACd8F,aAAAA,EAAexG,OAAAA,CAAQC,GAAAA,CAAI,UAAA,CAAA,KAAgB;OAC7C,CAAA;IACF,CAAA,GAAA;AACA,IAAA,IAAA,CAAKY,OAAAA,GAAU;AAAEK,MAAAA,GAAAA;AAAKQ,MAAAA;AAAO,KAAA;AAE7BA,IAAAA,MAAAA,CAAOiE,MAAM,MAAA;AACX,MAAA,IAAI,IAAA,CAAK9E,OAAAA,EAASa,MAAAA,KAAWA,MAAAA,OAAab,OAAAA,GAAU,IAAA;IACtD,CAAA,CAAA;AACA,IAAA,OAAOa,MAAAA;AACT,EAAA;AACF","file":"chunk-PYB2DKL2.js","sourcesContent":["/**\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`, `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 AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditGuardVerdict,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditSkipReason,\n AiTokenUsageReport,\n WorkspaceQuotaUsage,\n} from './types.js';\n","/**\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'>,\n maxTokensPerReport: number = AI_CREDIT_MAX_TOKENS_PER_REPORT\n): AiTokenUsageValidationError | null {\n const { sessionId, messageId, model, inputTokens, outputTokens } = report;\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 (!Number.isSafeInteger(inputTokens) || !Number.isSafeInteger(outputTokens)) {\n return { code: 'TOKEN_COUNTS_NOT_INTEGERS', message: 'inputTokens and outputTokens must be integers.' };\n }\n if (inputTokens < 0 || outputTokens < 0) {\n return { code: 'TOKEN_COUNTS_NEGATIVE', message: 'inputTokens and outputTokens must be non-negative.' };\n }\n if (inputTokens + outputTokens > maxTokensPerReport) {\n return {\n code: 'TOKEN_COUNTS_EXCEED_MAXIMUM',\n message: `Reported tokens exceed the per-report maximum of ${maxTokensPerReport}.`,\n };\n }\n return null;\n}\n\n/**\n * The quota a product's AI credits draw from: `<productId>.ai.credits`\n * (`vibecontrols.ai.credits`, `healthybowl.ai.credits`, …). Must match what\n * billing seeds exactly — a name mismatch reads as \"not provisioned\".\n */\nexport function aiCreditQuotaName(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('aiCreditQuotaName requires a productId');\n return `${id}.ai.credits`;\n}\n\n/** Default hash prefix for a product: `<productId>:aicredit`. */\nexport function defaultAiCreditHashPrefix(productId: string): string {\n const id = productId.trim();\n if (!id) throw new Error('defaultAiCreditHashPrefix requires a productId');\n return `${id}:aicredit`;\n}\n\n/**\n * Make a hash component unambiguous when joined with `:`. Ids are `ID!` and may\n * contain colons, so raw joining would let `(\"a:b\",\"c\")` and `(\"a\",\"b:c\")`\n * collide — and activity's unique `usage_records.hash` would then drop the second,\n * genuinely different turn as a replay. `%` is escaped first so the escape itself\n * cannot collide. A no-op for ids containing neither character (uuids, `msg_…`),\n * so existing hashes are reproduced byte-for-byte.\n */\nexport function encodeAiCreditHashComponent(value: string): string {\n return value.replaceAll('%', '%25').replaceAll(':', '%3A');\n}\n\n/**\n * Idempotency hash for one turn: `<prefix>:<sessionId>:<messageId>`.\n *\n * activity-svc's unique index is on `hash` ALONE, shared by every product, so\n * the prefix must be product-namespaced. Products that already write a different\n * prefix must keep passing it (`aicredit` for VibeControls, `hb-assistant` for\n * HealthyBowl) — changing a prefix re-hashes every in-flight turn, so a client\n * retry across the deploy would be charged twice.\n */\nexport function aiCreditIdempotencyHash(prefix: string, sessionId: string, messageId: string): string {\n const head = prefix.trim();\n if (!head) throw new Error('aiCreditIdempotencyHash requires a prefix');\n if (blank(sessionId) || blank(messageId)) {\n throw new Error('aiCreditIdempotencyHash requires a sessionId and a messageId');\n }\n return `${head}:${encodeAiCreditHashComponent(sessionId)}:${encodeAiCreditHashComponent(messageId)}`;\n}\n","/**\n * Errors raised by the AI-credit meter. Only caller mistakes throw; billing and\n * recording failures are returned as a skipped charge (see `AiCreditMeter.charge`).\n */\nimport type { AiTokenUsageViolation } from './validation.js';\n\nexport type AiCreditInputErrorCode = AiTokenUsageViolation | 'WORKSPACE_ID_REQUIRED';\n\n/** A malformed report or missing workspace context. Map it to BAD_USER_INPUT. */\nexport class AiCreditInputError extends Error {\n readonly code: AiCreditInputErrorCode;\n /** GraphQL error code products should surface. */\n readonly graphqlCode = 'BAD_USER_INPUT';\n\n constructor(code: AiCreditInputErrorCode, message: string) {\n super(message);\n this.name = 'AiCreditInputError';\n this.code = code;\n }\n}\n\nexport function isAiCreditInputError(error: unknown): error is AiCreditInputError {\n return error instanceof AiCreditInputError;\n}\n","/**\n * AiCreditMeter — cost-weighted, idempotent AI-credit charging for an assistant turn.\n *\n * VibeControls (`utils/usage-billing.ts` + `modules/aicredit`) and HealthyBowl\n * (`utils/ai-credit-usage.ts` + `HealthyBowlAiCreditProvider`) each carried their\n * own copy of this path. This is the shared version, built on the path that is\n * proven to record in prod:\n *\n * 1. **Price** — `quoteAiCredits(model, inputTokens, outputTokens)` on\n * 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`); the\n * charging field must carry NO `@usage(trackUsage)` directive, or the turn is\n * charged twice.\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 { logger as sdkLogger } from '../logger/index.js';\n\nimport { AiCreditInputError } from './errors.js';\nimport type {\n AiCreditChargeGuard,\n AiCreditChargeInput,\n AiCreditChargeResult,\n AiCreditFetch,\n AiCreditLogger,\n AiCreditPricingTransport,\n AiCreditSkipReason,\n WorkspaceQuotaUsage,\n} from './types.js';\nimport {\n AI_CREDIT_MAX_TOKENS_PER_REPORT,\n aiCreditIdempotencyHash,\n aiCreditQuotaName,\n defaultAiCreditHashPrefix,\n validateAiTokenUsage,\n} from './validation.js';\n\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\nconst QUOTE_AI_CREDITS_QUERY = `query AiCreditMeterQuote($model: String!, $inputTokens: Int!, $outputTokens: Int!) {\n quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens)\n}`;\n\nconst TRACK_USAGE_MUTATION = `mutation AiCreditMeterTrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n}`;\n\nconst WORKSPACE_QUOTA_ASSIGNMENTS_QUERY = `query AiCreditMeterQuotaAssignments($workspaceId: ID!) {\n workspaceQuotaAssignments(workspaceId: $workspaceId) { quotaName used limit noLimit isActive }\n}`;\n\nexport interface AiCreditMeterOptions {\n /** Product id stamped on usage records, e.g. `vibecontrols`. */\n productId: string;\n /** This service's name; sent as the service identity. Default `SERVICE_IDENTITY` / `SERVICE_NAME` env. */\n serviceName?: string;\n /** Quota to charge. Default `<productId>.ai.credits`. */\n quotaName?: string;\n /**\n * Idempotency-hash prefix. Default `<productId>:aicredit`. A product that already\n * records under another prefix MUST keep it (see {@link aiCreditIdempotencyHash}).\n */\n hashPrefix?: string;\n /** wspace internal gateway URL. Default `WSPACE_INT_GATEWAY_URL` env (read per call). */\n activityGatewayUrl?: string;\n /** Cross-layer global gateway URL for pricing. Default `GLOBAL_PUBLIC_GATEWAY_URL` env (read per call). */\n billingGatewayUrl?: string;\n /**\n * Pricing transport, or a factory for one. Default: a lazily constructed be-sdk\n * `GatewayClient` bound to {@link billingGatewayUrl}, rebuilt if the URL changes.\n */\n pricingClient?:\n | AiCreditPricingTransport\n | ((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 async quote(input: { model: string; inputTokens: number; outputTokens: number }): 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 response = await client.crossLayerQuery<{ quoteAiCredits?: number | null }>({\n query: QUOTE_AI_CREDITS_QUERY,\n variables: { model: input.model, inputTokens: input.inputTokens, outputTokens: input.outputTokens },\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 if (response.errors?.length) {\n throw new Error(response.errors.map((error) => error.message).join(', '));\n }\n const credits = response.data?.quoteAiCredits;\n if (typeof credits !== 'number' || !Number.isFinite(credits) || credits < 0) {\n throw new Error(`quoteAiCredits returned no usable value (${String(credits)})`);\n }\n return credits;\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to quote AI credits; skipping charge', {\n productId: this.productId,\n model: input.model,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n /**\n * Validate, price and record one completed assistant turn. See the module\n * header for the contract: throws only {@link AiCreditInputError}.\n */\n async charge(input: AiCreditChargeInput): Promise<AiCreditChargeResult> {\n const workspaceId = input.workspaceId?.trim() ?? '';\n if (!workspaceId) {\n throw new AiCreditInputError('WORKSPACE_ID_REQUIRED', 'This request has no workspace context.');\n }\n const invalid = validateAiTokenUsage(input, this.maxTokensPerReport);\n if (invalid) throw new AiCreditInputError(invalid.code, invalid.message);\n\n const hash = this.hashFor(input.sessionId, input.messageId);\n const logFields = {\n productId: this.productId,\n quotaName: this.quotaName,\n workspaceId,\n sessionId: input.sessionId,\n messageId: input.messageId,\n model: input.model,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n };\n const skipped = (reason: AiCreditSkipReason, credits: number | null, detail?: string): AiCreditChargeResult => {\n this.log.warn(`[AiCreditMeter] turn not charged (${reason})`, { ...logFields, credits, detail });\n return { status: 'skipped', reason, credits, hash, quotaName: this.quotaName, ...(detail ? { detail } : {}) };\n };\n\n if (this.guard) {\n try {\n const verdict = await this.guard({ ...input, workspaceId });\n if (!verdict.allow) return skipped('GUARD_REFUSED', null, verdict.detail);\n } catch (error) {\n // Fail open: a guard's infrastructure blip must not silently stop metering.\n this.log.warn('[AiCreditMeter] charge guard threw; charging anyway', {\n ...logFields,\n error: errorMessage(error),\n });\n }\n }\n\n const credits = await this.quote(input);\n if (credits === null) return skipped('NOT_PRICED', null);\n if (credits <= 0) return skipped('ZERO_COST', credits);\n\n try {\n await this.trackUsage({\n workspaceId,\n amount: credits,\n description: input.description?.trim() || `AI credits for session ${input.sessionId}`,\n userId: input.userId ?? undefined,\n hash,\n metadata: {\n model: input.model,\n sessionId: input.sessionId,\n messageId: input.messageId,\n inputTokens: input.inputTokens,\n outputTokens: input.outputTokens,\n credits,\n ...input.metadata,\n },\n });\n } catch (error) {\n return skipped('RECORD_FAILED', credits, errorMessage(error));\n }\n\n this.log.info(`[AiCreditMeter] Charged ${credits} AI credits for session ${input.sessionId}`, {\n ...logFields,\n credits,\n });\n return { status: 'charged', credits, hash, quotaName: this.quotaName };\n }\n\n /**\n * Read the quota's ENFORCED usage from wspace-activity-svc — the ledger the\n * charge lands on and the gateway's `@usage` check reads. All active rows are\n * summed, because a workspace can hold several (plan + add-ons, or duplicate\n * rows) and `checkWorkspaceQuota` sums them; a single-row read under-reports.\n *\n * Returns null (never throws) when activity is unreachable or no assignment\n * exists, so a screen can show \"not provisioned\" instead of a confident zero.\n */\n async readUsage(workspaceId: string, quotaName: string = this.quotaName): Promise<WorkspaceQuotaUsage | null> {\n try {\n const data = await this.activityRequest<{ workspaceQuotaAssignments?: AssignmentRow[] | null }>(\n workspaceId,\n WORKSPACE_QUOTA_ASSIGNMENTS_QUERY,\n { workspaceId: workspaceId.trim() }\n );\n const rows = (data.workspaceQuotaAssignments ?? []).filter((row) => row.isActive && row.quotaName === quotaName);\n if (rows.length === 0) return null;\n const used = rows.reduce((sum, row) => sum + (Number.isFinite(row.used) ? row.used : 0), 0);\n const noLimit = rows.some((row) => row.noLimit);\n const limit = noLimit ? null : rows.reduce((sum, row) => sum + (row.limit ?? 0), 0);\n return {\n quotaName,\n used,\n limit,\n noLimit,\n remaining: limit === null ? null : Math.max(limit - used, 0),\n assignments: rows.length,\n };\n } catch (error) {\n this.log.warn('[AiCreditMeter] Failed to read workspace quota usage', {\n productId: this.productId,\n quotaName,\n workspaceId,\n error: errorMessage(error),\n });\n return null;\n }\n }\n\n private async trackUsage(record: {\n workspaceId: string;\n amount: number;\n description: string;\n userId: string | undefined;\n hash: string;\n metadata: Record<string, unknown>;\n }): Promise<void> {\n const data = await this.activityRequest<{ trackUsage?: boolean | null }>(record.workspaceId, TRACK_USAGE_MUTATION, {\n input: {\n // Sent in the input AND as x-workspace-id: activity takes the workspace from request\n // context, and the @rbac directive resolves input.workspaceId.\n workspaceId: record.workspaceId,\n quotaName: this.quotaName,\n productId: this.productId,\n amount: record.amount,\n description: record.description,\n userId: record.userId,\n hash: record.hash,\n metadata: record.metadata,\n },\n });\n if (data.trackUsage !== true) {\n throw new Error(`trackUsage did not confirm the record (returned ${String(data.trackUsage)})`);\n }\n }\n\n private async activityRequest<T>(workspaceId: string, query: string, variables: Record<string, unknown>): Promise<T> {\n const url = this.activityGatewayUrl ?? process.env['WSPACE_INT_GATEWAY_URL']?.trim();\n if (!url) throw new Error('WSPACE_INT_GATEWAY_URL not set; cannot reach wspace-activity-svc');\n const workspace = workspaceId.trim();\n if (!workspace) throw new Error('workspaceId is required');\n\n const controller = new AbortController();\n const timeout = setTimeout(() => controller.abort(), this.requestTimeoutMs);\n try {\n const response = await this.fetchImpl(url, {\n method: 'POST',\n headers: {\n 'Content-Type': 'application/json',\n 'x-actor-type': 'service',\n 'x-actor-id': this.resolveServiceName(),\n ...internalServiceHeaders(),\n 'x-workspace-id': workspace,\n },\n body: JSON.stringify({ query, variables }),\n signal: controller.signal,\n });\n if (!response.ok) {\n const body = await response.text().catch(() => response.statusText);\n throw new Error(`activity request failed with HTTP ${response.status}: ${body.slice(0, 500)}`);\n }\n const result = (await response.json()) as GraphQLBody<T>;\n if (result.errors?.length) {\n throw new Error(result.errors.map((error) => error.message).join(', '));\n }\n if (!result.data) throw new Error('activity response did not include data');\n return result.data;\n } finally {\n clearTimeout(timeout);\n }\n }\n\n 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"]}
|