@burdenoff/be-sdk 2026.1021.6 → 2026.1021.7

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/README.md CHANGED
@@ -253,6 +253,51 @@ const url = await files.getDownloadUrl(evidence.fileId, actor, { expiresInSecond
253
253
  const output = { attachment: toFileReference(stored) }; // workflow node output, no base64
254
254
  ```
255
255
 
256
+ ### AI-credit meter (`@burdenoff/be-sdk/ai-credits`)
257
+
258
+ Cost-weighted, idempotent charging of a completed assistant turn, shared by every product
259
+ that meters its assistant (replaces the VibeControls `usage-billing.ts` and HealthyBowl
260
+ `ai-credit-usage.ts` copies).
261
+
262
+ - `charge` validates the report (session, message, model, integer non-negative token
263
+ counts, ≤ 2,000,000 per report), prices it server-side with global-billing
264
+ `quoteAiCredits` (cross-layer `GatewayClient`, `GLOBAL_PUBLIC_GATEWAY_URL`) and records
265
+ it with wspace-activity `trackUsage` on `<productId>.ai.credits` through the wspace
266
+ internal gateway (`WSPACE_INT_GATEWAY_URL`, `x-workspace-id`).
267
+ - Idempotent: the usage record's hash is `<prefix>:<sessionId>:<messageId>` (components
268
+ `%`/`:`-escaped), and activity's unique `usage_records.hash` makes a replay a no-op. The
269
+ default prefix is `<productId>:aicredit`; a product that already records under another
270
+ prefix must keep it (`aicredit` for VibeControls, `hb-assistant` for HealthyBowl), or a
271
+ retry across the deploy is charged twice.
272
+ - Only a malformed report throws (`AiCreditInputError`, map to `BAD_USER_INPUT`). Pricing
273
+ or recording failures never fail the user's turn: they return
274
+ `{ status: 'skipped', reason: 'NOT_PRICED' | 'ZERO_COST' | 'GUARD_REFUSED' | 'RECORD_FAILED' }`
275
+ and are logged. A null quote never charges an invented amount.
276
+ - `guard` is an optional pre-charge hook (e.g. a per-workspace report-rate ceiling); a guard
277
+ that throws fails open.
278
+ - `readUsage(workspaceId)` returns the enforced counter (all active assignment rows summed,
279
+ as `checkWorkspaceQuota` sums them), or null when unreachable / not provisioned.
280
+ - The charging GraphQL field takes the workspace from the gateway context, carries `@rbac`,
281
+ and must NOT carry `@usage(trackUsage: true)` — that would charge a second, flat amount.
282
+ A pre-flight gate is a separate `@usage(checkQuota: true, trackUsage: false)` field.
283
+
284
+ ```typescript
285
+ import { AiCreditMeter, isAiCreditInputError } from '@burdenoff/be-sdk/ai-credits';
286
+
287
+ const meter = new AiCreditMeter({ productId: 'vibecontrols', serviceName: 'wspace-vibecontrols-svc', hashPrefix: 'aicredit' });
288
+
289
+ const result = await meter.charge({
290
+ workspaceId: requireWorkspaceId(ctx.workspace?.id), // gateway context, never the payload
291
+ userId: ctx.actor?.id,
292
+ sessionId: input.sessionId,
293
+ messageId: input.messageId,
294
+ model: input.model,
295
+ inputTokens: input.inputTokens,
296
+ outputTokens: input.outputTokens,
297
+ });
298
+ if (result.status === 'skipped') logAudit(/* … */);
299
+ ```
300
+
256
301
  ### Platform Primitives (`@burdenoff/be-sdk/platform`)
257
302
 
258
303
  Reusable building blocks consumed fleet-wide as part of the scale refactor:
@@ -0,0 +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 AiCreditSkipReason, n as AiTokenUsageReport, o as AiTokenUsageValidationError, p as AiTokenUsageViolation, W as WorkspaceQuotaUsage, q as aiCreditIdempotencyHash, r as aiCreditQuotaName, s as defaultAiCreditHashPrefix, t as encodeAiCreditHashComponent, u as isAiCreditInputError, v as validateAiTokenUsage } from '../index-DmxmEfAu.js';
2
+ import '../types-B376RbyK.js';
3
+ import '../layer-GNAVXBMf.js';
@@ -0,0 +1,5 @@
1
+ export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditInputError, AiCreditMeter, aiCreditIdempotencyHash, aiCreditQuotaName, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage } from '../chunk-PYB2DKL2.js';
2
+ import '../chunk-RU266375.js';
3
+ import '../chunk-XE4OXN2W.js';
4
+ //# sourceMappingURL=index.js.map
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"index.js"}
@@ -0,0 +1,435 @@
1
+ import { logger } from './chunk-RU266375.js';
2
+ import { __export, __name } from './chunk-XE4OXN2W.js';
3
+
4
+ // src/ai-credits/index.ts
5
+ var ai_credits_exports = {};
6
+ __export(ai_credits_exports, {
7
+ AI_CREDIT_MAX_TOKENS_PER_REPORT: () => AI_CREDIT_MAX_TOKENS_PER_REPORT,
8
+ AiCreditInputError: () => AiCreditInputError,
9
+ AiCreditMeter: () => AiCreditMeter,
10
+ aiCreditIdempotencyHash: () => aiCreditIdempotencyHash,
11
+ aiCreditQuotaName: () => aiCreditQuotaName,
12
+ defaultAiCreditHashPrefix: () => defaultAiCreditHashPrefix,
13
+ encodeAiCreditHashComponent: () => encodeAiCreditHashComponent,
14
+ isAiCreditInputError: () => isAiCreditInputError,
15
+ validateAiTokenUsage: () => validateAiTokenUsage
16
+ });
17
+
18
+ // src/ai-credits/validation.ts
19
+ var AI_CREDIT_MAX_TOKENS_PER_REPORT = 2e6;
20
+ function blank(value) {
21
+ return typeof value !== "string" || value.trim().length === 0;
22
+ }
23
+ __name(blank, "blank");
24
+ function validateAiTokenUsage(report, maxTokensPerReport = AI_CREDIT_MAX_TOKENS_PER_REPORT) {
25
+ const { sessionId, messageId, model, inputTokens, outputTokens } = report;
26
+ if (blank(sessionId)) return {
27
+ code: "SESSION_ID_REQUIRED",
28
+ message: "sessionId is required."
29
+ };
30
+ if (blank(messageId)) return {
31
+ code: "MESSAGE_ID_REQUIRED",
32
+ message: "messageId is required."
33
+ };
34
+ if (blank(model)) return {
35
+ code: "MODEL_REQUIRED",
36
+ message: "model is required."
37
+ };
38
+ if (!Number.isSafeInteger(inputTokens) || !Number.isSafeInteger(outputTokens)) {
39
+ return {
40
+ code: "TOKEN_COUNTS_NOT_INTEGERS",
41
+ message: "inputTokens and outputTokens must be integers."
42
+ };
43
+ }
44
+ if (inputTokens < 0 || outputTokens < 0) {
45
+ return {
46
+ code: "TOKEN_COUNTS_NEGATIVE",
47
+ message: "inputTokens and outputTokens must be non-negative."
48
+ };
49
+ }
50
+ if (inputTokens + outputTokens > maxTokensPerReport) {
51
+ return {
52
+ code: "TOKEN_COUNTS_EXCEED_MAXIMUM",
53
+ message: `Reported tokens exceed the per-report maximum of ${maxTokensPerReport}.`
54
+ };
55
+ }
56
+ return null;
57
+ }
58
+ __name(validateAiTokenUsage, "validateAiTokenUsage");
59
+ function aiCreditQuotaName(productId) {
60
+ const id = productId.trim();
61
+ if (!id) throw new Error("aiCreditQuotaName requires a productId");
62
+ return `${id}.ai.credits`;
63
+ }
64
+ __name(aiCreditQuotaName, "aiCreditQuotaName");
65
+ function defaultAiCreditHashPrefix(productId) {
66
+ const id = productId.trim();
67
+ if (!id) throw new Error("defaultAiCreditHashPrefix requires a productId");
68
+ return `${id}:aicredit`;
69
+ }
70
+ __name(defaultAiCreditHashPrefix, "defaultAiCreditHashPrefix");
71
+ function encodeAiCreditHashComponent(value) {
72
+ return value.replaceAll("%", "%25").replaceAll(":", "%3A");
73
+ }
74
+ __name(encodeAiCreditHashComponent, "encodeAiCreditHashComponent");
75
+ function aiCreditIdempotencyHash(prefix, sessionId, messageId) {
76
+ const head = prefix.trim();
77
+ if (!head) throw new Error("aiCreditIdempotencyHash requires a prefix");
78
+ if (blank(sessionId) || blank(messageId)) {
79
+ throw new Error("aiCreditIdempotencyHash requires a sessionId and a messageId");
80
+ }
81
+ return `${head}:${encodeAiCreditHashComponent(sessionId)}:${encodeAiCreditHashComponent(messageId)}`;
82
+ }
83
+ __name(aiCreditIdempotencyHash, "aiCreditIdempotencyHash");
84
+
85
+ // src/ai-credits/errors.ts
86
+ var AiCreditInputError = class extends Error {
87
+ static {
88
+ __name(this, "AiCreditInputError");
89
+ }
90
+ code;
91
+ /** GraphQL error code products should surface. */
92
+ graphqlCode = "BAD_USER_INPUT";
93
+ constructor(code, message) {
94
+ super(message);
95
+ this.name = "AiCreditInputError";
96
+ this.code = code;
97
+ }
98
+ };
99
+ function isAiCreditInputError(error) {
100
+ return error instanceof AiCreditInputError;
101
+ }
102
+ __name(isAiCreditInputError, "isAiCreditInputError");
103
+
104
+ // src/ai-credits/meter.ts
105
+ var DEFAULT_REQUEST_TIMEOUT_MS = 5e3;
106
+ var QUOTE_AI_CREDITS_QUERY = `query AiCreditMeterQuote($model: String!, $inputTokens: Int!, $outputTokens: Int!) {
107
+ quoteAiCredits(model: $model, inputTokens: $inputTokens, outputTokens: $outputTokens)
108
+ }`;
109
+ var TRACK_USAGE_MUTATION = `mutation AiCreditMeterTrackUsage($input: TrackUsageInput!) {
110
+ trackUsage(input: $input)
111
+ }`;
112
+ var WORKSPACE_QUOTA_ASSIGNMENTS_QUERY = `query AiCreditMeterQuotaAssignments($workspaceId: ID!) {
113
+ workspaceQuotaAssignments(workspaceId: $workspaceId) { quotaName used limit noLimit isActive }
114
+ }`;
115
+ function errorMessage(error) {
116
+ return error instanceof Error ? error.message : String(error);
117
+ }
118
+ __name(errorMessage, "errorMessage");
119
+ function requireNonEmpty(value, field) {
120
+ const trimmed = value?.trim() ?? "";
121
+ if (!trimmed) throw new Error(`AiCreditMeter: ${field} is required`);
122
+ return trimmed;
123
+ }
124
+ __name(requireNonEmpty, "requireNonEmpty");
125
+ function internalServiceHeaders() {
126
+ const token = process.env["TRUSTED_GATEWAY_TOKEN"] || process.env["INTERNAL_SERVICE_TOKEN"];
127
+ return token ? {
128
+ "x-internal-service-token": token
129
+ } : {};
130
+ }
131
+ __name(internalServiceHeaders, "internalServiceHeaders");
132
+ var AiCreditMeter = class {
133
+ static {
134
+ __name(this, "AiCreditMeter");
135
+ }
136
+ productId;
137
+ quotaName;
138
+ hashPrefix;
139
+ serviceName;
140
+ activityGatewayUrl;
141
+ billingGatewayUrl;
142
+ pricingOption;
143
+ fetchImpl;
144
+ requestTimeoutMs;
145
+ maxTokensPerReport;
146
+ guard;
147
+ log;
148
+ pricing = null;
149
+ constructor(options) {
150
+ this.productId = requireNonEmpty(options.productId, "productId");
151
+ this.quotaName = options.quotaName?.trim() || aiCreditQuotaName(this.productId);
152
+ this.hashPrefix = options.hashPrefix?.trim() || defaultAiCreditHashPrefix(this.productId);
153
+ this.serviceName = options.serviceName?.trim() || void 0;
154
+ this.activityGatewayUrl = options.activityGatewayUrl?.trim() || void 0;
155
+ this.billingGatewayUrl = options.billingGatewayUrl?.trim() || void 0;
156
+ this.pricingOption = options.pricingClient;
157
+ this.fetchImpl = options.fetch ?? ((url, init) => fetch(url, init));
158
+ this.requestTimeoutMs = options.requestTimeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
159
+ if (!Number.isSafeInteger(this.requestTimeoutMs) || this.requestTimeoutMs <= 0) {
160
+ throw new Error("AiCreditMeter: requestTimeoutMs must be a positive integer");
161
+ }
162
+ this.maxTokensPerReport = options.maxTokensPerReport ?? AI_CREDIT_MAX_TOKENS_PER_REPORT;
163
+ if (!Number.isSafeInteger(this.maxTokensPerReport) || this.maxTokensPerReport <= 0) {
164
+ throw new Error("AiCreditMeter: maxTokensPerReport must be a positive integer");
165
+ }
166
+ this.guard = options.guard;
167
+ this.log = options.logger ?? logger;
168
+ }
169
+ /** The idempotency hash this meter records a turn under. */
170
+ hashFor(sessionId, messageId) {
171
+ return aiCreditIdempotencyHash(this.hashPrefix, sessionId, messageId);
172
+ }
173
+ /**
174
+ * Server-side price of one model call in credits, from billing's per-model
175
+ * token table. Returns null — after logging why — when it cannot be priced.
176
+ */
177
+ async quote(input) {
178
+ const url = this.billingGatewayUrl ?? process.env["GLOBAL_PUBLIC_GATEWAY_URL"]?.trim();
179
+ if (!url) {
180
+ this.log.warn("[AiCreditMeter] GLOBAL_PUBLIC_GATEWAY_URL not set; cannot price AI credits", {
181
+ productId: this.productId,
182
+ model: input.model
183
+ });
184
+ return null;
185
+ }
186
+ try {
187
+ const client = await this.getPricingClient(url);
188
+ const response = await client.crossLayerQuery({
189
+ query: QUOTE_AI_CREDITS_QUERY,
190
+ variables: {
191
+ model: input.model,
192
+ inputTokens: input.inputTokens,
193
+ outputTokens: input.outputTokens
194
+ },
195
+ // Only the actor type: the signed service JWT is the identity. An x-actor-id on a
196
+ // service token is read as "on behalf of" and downgrades the actor.
197
+ headers: {
198
+ "x-actor-type": "service"
199
+ },
200
+ timeout: this.requestTimeoutMs,
201
+ skipRetry: true,
202
+ skipCircuitBreaker: true
203
+ });
204
+ if (response.errors?.length) {
205
+ throw new Error(response.errors.map((error) => error.message).join(", "));
206
+ }
207
+ const credits = response.data?.quoteAiCredits;
208
+ if (typeof credits !== "number" || !Number.isFinite(credits) || credits < 0) {
209
+ throw new Error(`quoteAiCredits returned no usable value (${String(credits)})`);
210
+ }
211
+ return credits;
212
+ } catch (error) {
213
+ this.log.warn("[AiCreditMeter] Failed to quote AI credits; skipping charge", {
214
+ productId: this.productId,
215
+ model: input.model,
216
+ error: errorMessage(error)
217
+ });
218
+ return null;
219
+ }
220
+ }
221
+ /**
222
+ * Validate, price and record one completed assistant turn. See the module
223
+ * header for the contract: throws only {@link AiCreditInputError}.
224
+ */
225
+ async charge(input) {
226
+ const workspaceId = input.workspaceId?.trim() ?? "";
227
+ if (!workspaceId) {
228
+ throw new AiCreditInputError("WORKSPACE_ID_REQUIRED", "This request has no workspace context.");
229
+ }
230
+ const invalid = validateAiTokenUsage(input, this.maxTokensPerReport);
231
+ if (invalid) throw new AiCreditInputError(invalid.code, invalid.message);
232
+ const hash = this.hashFor(input.sessionId, input.messageId);
233
+ const logFields = {
234
+ productId: this.productId,
235
+ quotaName: this.quotaName,
236
+ workspaceId,
237
+ sessionId: input.sessionId,
238
+ messageId: input.messageId,
239
+ model: input.model,
240
+ inputTokens: input.inputTokens,
241
+ outputTokens: input.outputTokens
242
+ };
243
+ const skipped = /* @__PURE__ */ __name((reason, credits2, detail) => {
244
+ this.log.warn(`[AiCreditMeter] turn not charged (${reason})`, {
245
+ ...logFields,
246
+ credits: credits2,
247
+ detail
248
+ });
249
+ return {
250
+ status: "skipped",
251
+ reason,
252
+ credits: credits2,
253
+ hash,
254
+ quotaName: this.quotaName,
255
+ ...detail ? {
256
+ detail
257
+ } : {}
258
+ };
259
+ }, "skipped");
260
+ if (this.guard) {
261
+ try {
262
+ const verdict = await this.guard({
263
+ ...input,
264
+ workspaceId
265
+ });
266
+ if (!verdict.allow) return skipped("GUARD_REFUSED", null, verdict.detail);
267
+ } catch (error) {
268
+ this.log.warn("[AiCreditMeter] charge guard threw; charging anyway", {
269
+ ...logFields,
270
+ error: errorMessage(error)
271
+ });
272
+ }
273
+ }
274
+ const credits = await this.quote(input);
275
+ if (credits === null) return skipped("NOT_PRICED", null);
276
+ if (credits <= 0) return skipped("ZERO_COST", credits);
277
+ try {
278
+ await this.trackUsage({
279
+ workspaceId,
280
+ amount: credits,
281
+ description: input.description?.trim() || `AI credits for session ${input.sessionId}`,
282
+ userId: input.userId ?? void 0,
283
+ hash,
284
+ metadata: {
285
+ model: input.model,
286
+ sessionId: input.sessionId,
287
+ messageId: input.messageId,
288
+ inputTokens: input.inputTokens,
289
+ outputTokens: input.outputTokens,
290
+ credits,
291
+ ...input.metadata
292
+ }
293
+ });
294
+ } catch (error) {
295
+ return skipped("RECORD_FAILED", credits, errorMessage(error));
296
+ }
297
+ this.log.info(`[AiCreditMeter] Charged ${credits} AI credits for session ${input.sessionId}`, {
298
+ ...logFields,
299
+ credits
300
+ });
301
+ return {
302
+ status: "charged",
303
+ credits,
304
+ hash,
305
+ quotaName: this.quotaName
306
+ };
307
+ }
308
+ /**
309
+ * Read the quota's ENFORCED usage from wspace-activity-svc — the ledger the
310
+ * charge lands on and the gateway's `@usage` check reads. All active rows are
311
+ * summed, because a workspace can hold several (plan + add-ons, or duplicate
312
+ * rows) and `checkWorkspaceQuota` sums them; a single-row read under-reports.
313
+ *
314
+ * Returns null (never throws) when activity is unreachable or no assignment
315
+ * exists, so a screen can show "not provisioned" instead of a confident zero.
316
+ */
317
+ async readUsage(workspaceId, quotaName = this.quotaName) {
318
+ try {
319
+ const data = await this.activityRequest(workspaceId, WORKSPACE_QUOTA_ASSIGNMENTS_QUERY, {
320
+ workspaceId: workspaceId.trim()
321
+ });
322
+ const rows = (data.workspaceQuotaAssignments ?? []).filter((row) => row.isActive && row.quotaName === quotaName);
323
+ if (rows.length === 0) return null;
324
+ const used = rows.reduce((sum, row) => sum + (Number.isFinite(row.used) ? row.used : 0), 0);
325
+ const noLimit = rows.some((row) => row.noLimit);
326
+ const limit = noLimit ? null : rows.reduce((sum, row) => sum + (row.limit ?? 0), 0);
327
+ return {
328
+ quotaName,
329
+ used,
330
+ limit,
331
+ noLimit,
332
+ remaining: limit === null ? null : Math.max(limit - used, 0),
333
+ assignments: rows.length
334
+ };
335
+ } catch (error) {
336
+ this.log.warn("[AiCreditMeter] Failed to read workspace quota usage", {
337
+ productId: this.productId,
338
+ quotaName,
339
+ workspaceId,
340
+ error: errorMessage(error)
341
+ });
342
+ return null;
343
+ }
344
+ }
345
+ async trackUsage(record) {
346
+ const data = await this.activityRequest(record.workspaceId, TRACK_USAGE_MUTATION, {
347
+ input: {
348
+ // Sent in the input AND as x-workspace-id: activity takes the workspace from request
349
+ // context, and the @rbac directive resolves input.workspaceId.
350
+ workspaceId: record.workspaceId,
351
+ quotaName: this.quotaName,
352
+ productId: this.productId,
353
+ amount: record.amount,
354
+ description: record.description,
355
+ userId: record.userId,
356
+ hash: record.hash,
357
+ metadata: record.metadata
358
+ }
359
+ });
360
+ if (data.trackUsage !== true) {
361
+ throw new Error(`trackUsage did not confirm the record (returned ${String(data.trackUsage)})`);
362
+ }
363
+ }
364
+ async activityRequest(workspaceId, query, variables) {
365
+ const url = this.activityGatewayUrl ?? process.env["WSPACE_INT_GATEWAY_URL"]?.trim();
366
+ if (!url) throw new Error("WSPACE_INT_GATEWAY_URL not set; cannot reach wspace-activity-svc");
367
+ const workspace = workspaceId.trim();
368
+ if (!workspace) throw new Error("workspaceId is required");
369
+ const controller = new AbortController();
370
+ const timeout = setTimeout(() => controller.abort(), this.requestTimeoutMs);
371
+ try {
372
+ const response = await this.fetchImpl(url, {
373
+ method: "POST",
374
+ headers: {
375
+ "Content-Type": "application/json",
376
+ "x-actor-type": "service",
377
+ "x-actor-id": this.resolveServiceName(),
378
+ ...internalServiceHeaders(),
379
+ "x-workspace-id": workspace
380
+ },
381
+ body: JSON.stringify({
382
+ query,
383
+ variables
384
+ }),
385
+ signal: controller.signal
386
+ });
387
+ if (!response.ok) {
388
+ const body = await response.text().catch(() => response.statusText);
389
+ throw new Error(`activity request failed with HTTP ${response.status}: ${body.slice(0, 500)}`);
390
+ }
391
+ const result = await response.json();
392
+ if (result.errors?.length) {
393
+ throw new Error(result.errors.map((error) => error.message).join(", "));
394
+ }
395
+ if (!result.data) throw new Error("activity response did not include data");
396
+ return result.data;
397
+ } finally {
398
+ clearTimeout(timeout);
399
+ }
400
+ }
401
+ resolveServiceName() {
402
+ return this.serviceName || process.env["SERVICE_IDENTITY"] || process.env["SERVICE_NAME"] || `wspace-${this.productId}-svc`;
403
+ }
404
+ getPricingClient(url) {
405
+ if (this.pricing && this.pricing.url === url) return this.pricing.client;
406
+ const option = this.pricingOption;
407
+ const client = (async () => {
408
+ if (option && typeof option === "function") return option(url);
409
+ if (option) return option;
410
+ const gateway = await import('./client-WSFUJHLI.js');
411
+ const identity = this.resolveServiceName();
412
+ return new gateway.GatewayClient({
413
+ // This service's OWN layer; the be-sdk signs the service JWT because the call leaves it.
414
+ layer: "wspace",
415
+ serviceName: identity,
416
+ serviceIdentity: identity,
417
+ crossLayerGatewayUrl: url,
418
+ timeout: this.requestTimeoutMs,
419
+ enableLogging: process.env["NODE_ENV"] !== "production"
420
+ });
421
+ })();
422
+ this.pricing = {
423
+ url,
424
+ client
425
+ };
426
+ client.catch(() => {
427
+ if (this.pricing?.client === client) this.pricing = null;
428
+ });
429
+ return client;
430
+ }
431
+ };
432
+
433
+ export { AI_CREDIT_MAX_TOKENS_PER_REPORT, AiCreditInputError, AiCreditMeter, aiCreditIdempotencyHash, aiCreditQuotaName, ai_credits_exports, defaultAiCreditHashPrefix, encodeAiCreditHashComponent, isAiCreditInputError, validateAiTokenUsage };
434
+ //# sourceMappingURL=chunk-PYB2DKL2.js.map
435
+ //# sourceMappingURL=chunk-PYB2DKL2.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","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,SAAAA,CAAAA,EAAY,OAAO;IAAEI,IAAAA,EAAM,qBAAA;IAAuBC,OAAAA,EAAS;AAAyB,GAAA;AAC9F,EAAA,IAAIb,KAAAA,CAAMS,KAAAA,CAAAA,EAAQ,OAAO;IAAEG,IAAAA,EAAM,gBAAA;IAAkBC,OAAAA,EAAS;AAAqB,GAAA;AACjF,EAAA,IAAI,CAACC,OAAOC,aAAAA,CAAcL,WAAAA,KAAgB,CAACI,MAAAA,CAAOC,aAAAA,CAAcJ,YAAAA,CAAAA,EAAe;AAC7E,IAAA,OAAO;MAAEC,IAAAA,EAAM,2BAAA;MAA6BC,OAAAA,EAAS;AAAiD,KAAA;AACxG,EAAA;AACA,EAAA,IAAIH,WAAAA,GAAc,CAAA,IAAKC,YAAAA,GA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2DKL2.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"]}
@@ -1,6 +1,6 @@
1
+ import { markExplicitActivity } from './chunk-GRGTUP44.js';
1
2
  import { NotificationsModule, NotificationType } from './chunk-INAZ3PKF.js';
2
3
  import { RBACModule } from './chunk-5JNHVKHG.js';
3
- import { markExplicitActivity } from './chunk-GRGTUP44.js';
4
4
  import { ValidationError, QuotaExceededError, PermissionDeniedError } from './chunk-QGBXVNRM.js';
5
5
  import { logger } from './chunk-RU266375.js';
6
6
  import { __name } from './chunk-XE4OXN2W.js';
@@ -1336,5 +1336,5 @@ var TrackerModule = class {
1336
1336
  };
1337
1337
 
1338
1338
  export { ActivityModule, TrackerModule, UsageMetricType, UsageModule };
1339
- //# sourceMappingURL=chunk-HDUS6UBO.js.map
1340
- //# sourceMappingURL=chunk-HDUS6UBO.js.map
1339
+ //# sourceMappingURL=chunk-STYD3MOS.js.map
1340
+ //# sourceMappingURL=chunk-STYD3MOS.js.map