@burdenoff/be-sdk 2026.1028.2 → 2026.1028.4

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.
Files changed (47) hide show
  1. package/dist/ai-credits/index.js +1 -1
  2. package/dist/cache/index.js +2 -2
  3. package/dist/{chunk-GKOAAC6D.js → chunk-3YG5JRS5.js} +3 -3
  4. package/dist/{chunk-GKOAAC6D.js.map → chunk-3YG5JRS5.js.map} +1 -1
  5. package/dist/{chunk-PAQK3YF2.js → chunk-4YPW6NMW.js} +3 -3
  6. package/dist/{chunk-PAQK3YF2.js.map → chunk-4YPW6NMW.js.map} +1 -1
  7. package/dist/{chunk-E36LPO3K.js → chunk-5ZP576CV.js} +3 -3
  8. package/dist/{chunk-E36LPO3K.js.map → chunk-5ZP576CV.js.map} +1 -1
  9. package/dist/{chunk-RM6AIMZT.js → chunk-FG6QCKKO.js} +5 -4
  10. package/dist/chunk-FG6QCKKO.js.map +1 -0
  11. package/dist/{chunk-FYFA7WAS.js → chunk-LCDECFJJ.js} +3 -3
  12. package/dist/{chunk-FYFA7WAS.js.map → chunk-LCDECFJJ.js.map} +1 -1
  13. package/dist/{chunk-PNWFTWBQ.js → chunk-OHUBPOZ6.js} +3 -3
  14. package/dist/{chunk-PNWFTWBQ.js.map → chunk-OHUBPOZ6.js.map} +1 -1
  15. package/dist/{chunk-NBN52AEM.js → chunk-PIRHGTHJ.js} +2 -2
  16. package/dist/{chunk-NBN52AEM.js.map → chunk-PIRHGTHJ.js.map} +1 -1
  17. package/dist/{chunk-57GT6PJK.js → chunk-SC43G6HT.js} +3 -3
  18. package/dist/{chunk-57GT6PJK.js.map → chunk-SC43G6HT.js.map} +1 -1
  19. package/dist/{chunk-QCOC2SF3.js → chunk-WSAWJC4D.js} +3 -3
  20. package/dist/{chunk-QCOC2SF3.js.map → chunk-WSAWJC4D.js.map} +1 -1
  21. package/dist/{chunk-5RBIDJBZ.js → chunk-XQ5RHGME.js} +3 -3
  22. package/dist/{chunk-5RBIDJBZ.js.map → chunk-XQ5RHGME.js.map} +1 -1
  23. package/dist/{chunk-N2UT3ESH.js → chunk-XXNT4VCM.js} +84 -19
  24. package/dist/chunk-XXNT4VCM.js.map +1 -0
  25. package/dist/{chunk-QGADOWSG.js → chunk-ZWKJKL6Y.js} +23 -6
  26. package/dist/chunk-ZWKJKL6Y.js.map +1 -0
  27. package/dist/{client-7DW6EYSA.js → client-FUR7I6DB.js} +3 -3
  28. package/dist/{client-7DW6EYSA.js.map → client-FUR7I6DB.js.map} +1 -1
  29. package/dist/export/index.js +4 -4
  30. package/dist/files/index.js +1 -1
  31. package/dist/gateway/index.d.ts +1 -1
  32. package/dist/gateway/index.js +3 -3
  33. package/dist/gateway/security/index.js +1 -1
  34. package/dist/{index-DfYu1p9e.d.ts → index-D8HGwglK.d.ts} +16 -5
  35. package/dist/{index-Dcq8OduH.d.ts → index-szTxGaO6.d.ts} +4 -2
  36. package/dist/index.d.ts +2 -2
  37. package/dist/index.js +25 -25
  38. package/dist/init/index.js +4 -4
  39. package/dist/platform/index.d.ts +1 -1
  40. package/dist/platform/index.js +1 -1
  41. package/dist/prisma/index.js +2 -2
  42. package/dist/tags/index.js +1 -1
  43. package/dist/tracker/index.js +3 -3
  44. package/package.json +1 -1
  45. package/dist/chunk-N2UT3ESH.js.map +0 -1
  46. package/dist/chunk-QGADOWSG.js.map +0 -1
  47. package/dist/chunk-RM6AIMZT.js.map +0 -1
@@ -1 +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,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-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"]}
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","skipCircuit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AA,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-XQ5RHGME.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"]}
@@ -705,10 +705,11 @@ var LLMRouter = class {
705
705
 
706
706
  // src/platform/invocation-accounting/documents.ts
707
707
  var PROMPTS_V2_DOCUMENTS = Object.freeze({
708
- begin: "mutation SdkBeginInvocationAttemptV2($input:PromptBeginInvocationAttemptV2Input!){promptBeginInvocationAttemptV2(input:$input){id workspaceId attemptKey operationKey productKey providerKey modelKey startedAt createdBy origin fingerprint createdAt revisions{id attemptId revision predecessorId eventKey fingerprint outcome inputTokens outputTokens totalTokens cachedInputTokens costMicroUsd currency costKind pricingReference origin finishedAt createdAt} hasMoreRevisions}}",
708
+ begin: "mutation SdkBeginInvocationAttemptV2($input:PromptBeginInvocationAttemptV2Input!){promptBeginInvocationAttemptV2(input:$input){id workspaceId attemptKey operationKey productKey providerKey modelKey startedAt trigger subjectType subjectId subjectPartId sequence createdBy origin fingerprint createdAt revisions{id attemptId revision predecessorId eventKey fingerprint outcome inputTokens outputTokens totalTokens cachedInputTokens costMicroUsd currency costKind pricingReference origin finishedAt createdAt} hasMoreRevisions}}",
709
709
  record: "mutation SdkRecordInvocationUsageV2($input:PromptRecordInvocationUsageV2Input!){promptRecordInvocationUsageV2(input:$input){id attemptId revision predecessorId eventKey fingerprint outcome inputTokens outputTokens totalTokens cachedInputTokens costMicroUsd currency costKind pricingReference origin finishedAt createdAt}}",
710
- read: "query SdkInvocationAttemptV2($key:String!,$offset:Int){promptInvocationAttemptV2(attemptKey:$key,revisionOffset:$offset){id workspaceId attemptKey operationKey productKey providerKey modelKey startedAt createdBy origin fingerprint createdAt revisions{id attemptId revision predecessorId eventKey fingerprint outcome inputTokens outputTokens totalTokens cachedInputTokens costMicroUsd currency costKind pricingReference origin finishedAt createdAt} hasMoreRevisions}}",
711
- summary: "query SdkUsageSummaryV2($from:DateTime!,$to:DateTime!,$product:String,$operation:String){promptUsageSummaryV2(from:$from,to:$to,productKey:$product,operationKey:$operation){workspaceId from to scope productKey operationKey origin currency costKind operations attempts pendingAttempts knownAttempts partialAttempts unknownAttempts inputTokens{knownSubtotal knownAttempts missingAttempts} outputTokens{knownSubtotal knownAttempts missingAttempts} totalTokens{knownSubtotal knownAttempts missingAttempts} costMicroUsd{knownSubtotal knownAttempts missingAttempts}}}"
710
+ read: "query SdkInvocationAttemptV2($key:String!,$offset:Int){promptInvocationAttemptV2(attemptKey:$key,revisionOffset:$offset){id workspaceId attemptKey operationKey productKey providerKey modelKey startedAt trigger subjectType subjectId subjectPartId sequence createdBy origin fingerprint createdAt revisions{id attemptId revision predecessorId eventKey fingerprint outcome inputTokens outputTokens totalTokens cachedInputTokens costMicroUsd currency costKind pricingReference origin finishedAt createdAt} hasMoreRevisions}}",
711
+ summary: "query SdkUsageSummaryV2($from:DateTime!,$to:DateTime!,$product:String,$operation:String){promptUsageSummaryV2(from:$from,to:$to,productKey:$product,operationKey:$operation){workspaceId from to scope productKey operationKey origin currency costKind operations attempts pendingAttempts knownAttempts partialAttempts unknownAttempts inputTokens{knownSubtotal knownAttempts missingAttempts} outputTokens{knownSubtotal knownAttempts missingAttempts} totalTokens{knownSubtotal knownAttempts missingAttempts} costMicroUsd{knownSubtotal knownAttempts missingAttempts}}}",
712
+ breakdown: "query SdkUsageBreakdownV2($from:DateTime!,$to:DateTime!,$groupBy:[PromptUsageDimensionV2!]!,$product:String,$operation:String,$subjectType:String,$subjectId:String,$trigger:String){promptUsageBreakdownV2(from:$from,to:$to,groupBy:$groupBy,productKey:$product,operationKey:$operation,subjectType:$subjectType,subjectId:$subjectId,trigger:$trigger){workspaceId from to scope groupBy productKey operationKey subjectType subjectId trigger origin currency costKind truncated rows{productKey providerKey modelKey operationKey trigger subjectType subjectId subjectPartId attempts pendingAttempts inputTokens{knownSubtotal knownAttempts missingAttempts} outputTokens{knownSubtotal knownAttempts missingAttempts} totalTokens{knownSubtotal knownAttempts missingAttempts} costMicroUsd{knownSubtotal knownAttempts missingAttempts}}}}"
712
713
  });
713
714
 
714
715
  // src/platform/invocation-accounting/contracts.ts
@@ -735,6 +736,13 @@ function fields(value, names) {
735
736
  return value;
736
737
  }
737
738
  __name(fields, "fields");
739
+ function fieldsAllowing(value, required, optional) {
740
+ requireContract(isRecord(value));
741
+ requireContract(required.every((name) => Object.hasOwn(value, name)));
742
+ requireContract(Object.keys(value).every((name) => required.includes(name) || optional.includes(name)));
743
+ return value;
744
+ }
745
+ __name(fieldsAllowing, "fieldsAllowing");
738
746
  function uuid(value) {
739
747
  requireContract(typeof value === "string" && value === value.trim() && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value));
740
748
  return value.toLowerCase();
@@ -790,15 +798,62 @@ function sameIdentity(a, b) {
790
798
  return a.workspaceId === b.workspaceId && a.actorId === b.actorId && a.actorType === b.actorType && a.onBehalfOf === b.onBehalfOf;
791
799
  }
792
800
  __name(sameIdentity, "sameIdentity");
801
+ var ATTEMPT_FIELDS = [
802
+ "attemptKey",
803
+ "operationKey",
804
+ "productKey",
805
+ "providerKey",
806
+ "modelKey",
807
+ "startedAt"
808
+ ];
809
+ var DIMENSION_FIELDS = [
810
+ "trigger",
811
+ "subjectType",
812
+ "subjectId",
813
+ "subjectPartId",
814
+ "sequence"
815
+ ];
816
+ var TRIGGERS = [
817
+ "interactive",
818
+ "scheduled",
819
+ "event",
820
+ "api",
821
+ "webhook",
822
+ "test"
823
+ ];
824
+ function isTrigger(value) {
825
+ return typeof value === "string" && TRIGGERS.includes(value);
826
+ }
827
+ __name(isTrigger, "isTrigger");
828
+ function attemptDimensions(row) {
829
+ const present = /* @__PURE__ */ __name((name) => row[name] !== void 0 && row[name] !== null, "present");
830
+ const trigger = row["trigger"];
831
+ const sequence = row["sequence"];
832
+ if (present("trigger")) requireContract(isTrigger(trigger));
833
+ if (present("sequence")) requireContract(typeof sequence === "number" && Number.isInteger(sequence) && sequence >= 0 && sequence <= 2147483647);
834
+ requireContract(!present("subjectId") || present("subjectType"));
835
+ requireContract(!present("subjectPartId") || present("subjectId"));
836
+ return {
837
+ ...isTrigger(trigger) ? {
838
+ trigger
839
+ } : {},
840
+ ...present("subjectType") ? {
841
+ subjectType: key(row["subjectType"], 64)
842
+ } : {},
843
+ ...present("subjectId") ? {
844
+ subjectId: key(row["subjectId"])
845
+ } : {},
846
+ ...present("subjectPartId") ? {
847
+ subjectPartId: key(row["subjectPartId"])
848
+ } : {},
849
+ ...typeof sequence === "number" ? {
850
+ sequence
851
+ } : {}
852
+ };
853
+ }
854
+ __name(attemptDimensions, "attemptDimensions");
793
855
  function validateInvocationAttemptInput(value) {
794
- const row = fields(value, [
795
- "attemptKey",
796
- "operationKey",
797
- "productKey",
798
- "providerKey",
799
- "modelKey",
800
- "startedAt"
801
- ]);
856
+ const row = fieldsAllowing(value, ATTEMPT_FIELDS, DIMENSION_FIELDS);
802
857
  const modelKey = row["modelKey"];
803
858
  requireContract(typeof modelKey === "string" && modelKey.length <= 128 && modelKey.split("/").every((segment) => {
804
859
  key(segment);
@@ -811,7 +866,8 @@ function validateInvocationAttemptInput(value) {
811
866
  productKey: productSlugVariants(product).length > 1 ? emitProductSlug(product) : product,
812
867
  providerKey: key(row["providerKey"], 64),
813
868
  modelKey,
814
- startedAt: date(row["startedAt"])
869
+ startedAt: date(row["startedAt"]),
870
+ ...attemptDimensions(row)
815
871
  });
816
872
  }
817
873
  __name(validateInvocationAttemptInput, "validateInvocationAttemptInput");
@@ -916,8 +972,9 @@ __name(historyReceipt, "historyReceipt");
916
972
  function validateInvocationUsageReceipt(value, expected, attemptId) {
917
973
  const input = validateInvocationUsageInput(expected);
918
974
  const known = historyReceipt(value, input.attemptKey, uuid(attemptId));
919
- requireContract(known.pricingReference === null);
975
+ requireContract(known.costMicroUsd === null === (known.pricingReference === null));
920
976
  for (const [field, actual] of Object.entries(known)) {
977
+ if (field === "costMicroUsd") continue;
921
978
  const entry = Object.entries(input).find(([name]) => name === field);
922
979
  if (entry !== void 0) requireContract(entry[1] === actual);
923
980
  }
@@ -942,7 +999,7 @@ __name(envelope, "envelope");
942
999
  function validateInvocationAttemptReceipt(value, expected, identity) {
943
1000
  const context = validateInvocationIdentity(identity);
944
1001
  const selected = validateInvocationAttemptInput(expected);
945
- const row = fields(value, [
1002
+ const row = fieldsAllowing(value, [
946
1003
  "id",
947
1004
  "workspaceId",
948
1005
  "attemptKey",
@@ -957,14 +1014,18 @@ function validateInvocationAttemptReceipt(value, expected, identity) {
957
1014
  "createdAt",
958
1015
  "revisions",
959
1016
  "hasMoreRevisions"
960
- ]);
1017
+ ], DIMENSION_FIELDS);
961
1018
  const input = validateInvocationAttemptInput({
962
1019
  attemptKey: row["attemptKey"],
963
1020
  operationKey: row["operationKey"],
964
1021
  productKey: row["productKey"],
965
1022
  providerKey: row["providerKey"],
966
1023
  modelKey: row["modelKey"],
967
- startedAt: row["startedAt"]
1024
+ startedAt: row["startedAt"],
1025
+ ...Object.fromEntries(DIMENSION_FIELDS.filter((name) => Object.hasOwn(row, name)).map((name) => [
1026
+ name,
1027
+ row[name]
1028
+ ]))
968
1029
  });
969
1030
  requireContract(sameValues(input, selected) && row["workspaceId"] === context.workspaceId && row["createdBy"] === context.actorId && row["origin"] === "CALLER_REPORTED");
970
1031
  requireContract(Array.isArray(row["revisions"]) && row["revisions"].length <= 50 && typeof row["hasMoreRevisions"] === "boolean");
@@ -1190,8 +1251,12 @@ var InvocationAccountingCoordinator = class {
1190
1251
  }
1191
1252
  let raw;
1192
1253
  try {
1254
+ const input = intent.kind === "record" ? Object.freeze({
1255
+ ...intent.input,
1256
+ serverPricing: true
1257
+ }) : intent.input;
1193
1258
  raw = await this.options.transport(PROMPTS_V2_DOCUMENTS[intent.kind], Object.freeze({
1194
- input: intent.input
1259
+ input
1195
1260
  }));
1196
1261
  } catch {
1197
1262
  await this.unknown(previous, []);
@@ -1502,5 +1567,5 @@ function validateInvocationUsageSummary(value, selection) {
1502
1567
  __name(validateInvocationUsageSummary, "validateInvocationUsageSummary");
1503
1568
 
1504
1569
  export { CircuitBreakerOpenError, DEFAULT_GRAPHQL_PAGE_LIMIT, InvocationAccountingCoordinator, InvocationAccountingValidationError, LLMRouter, MAX_GRAPHQL_PAGE_LIMIT, PROMPTS_V2_DOCUMENTS, __resetHttpClientBreakers, buildCacheKey, buildConnection, buildLoaders, buildOffsetPage, clampGraphqlLimit, clampLimit, clampOffset, createClaudeUsageAccumulator, createHttpClient, createLeaderLease, decodeCursor, dropOldPartitions, encodeCursor, ensureMonthlyPartitions, getNamespaceVersion, httpClient, invalidateNamespace, monthlyPartitionName, normalizeClaudeUsage, normalizeCursorPagination, normalizeOffsetPagination, normalizeOpenAIUsage, normalizeRedisUrl, paginate, platform_exports, rateLimitIncr, resolveReferenceLoader, toPrismaPage, validateInvocationAttemptInput, validateInvocationAttemptReceipt, validateInvocationDelivery, validateInvocationIdentity, validateInvocationUsageInput, validateInvocationUsageReceipt, validateInvocationUsageSummary, withLeaderLock };
1505
- //# sourceMappingURL=chunk-N2UT3ESH.js.map
1506
- //# sourceMappingURL=chunk-N2UT3ESH.js.map
1570
+ //# sourceMappingURL=chunk-XXNT4VCM.js.map
1571
+ //# sourceMappingURL=chunk-XXNT4VCM.js.map