@burdenoff/be-sdk 2026.1123.4 → 2026.1123.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/export/index.js +1 -1
- package/dist/{export-lqKewsuF.js → export-D3EySJjJ.js} +2 -2
- package/dist/{export-lqKewsuF.js.map → export-D3EySJjJ.js.map} +1 -1
- package/dist/gateway/index.d.ts +2 -2
- package/dist/gateway/index.js +2 -2
- package/dist/gateway/security/index.d.ts +1 -1
- package/dist/gateway/security/index.js +1 -1
- package/dist/{gateway-2en8Gx_a.js → gateway-B9p8PD82.js} +2 -2
- package/dist/{gateway-2en8Gx_a.js.map → gateway-B9p8PD82.js.map} +1 -1
- package/dist/{index-DWER4-_x.d.ts → index-C_WEvMzP.d.ts} +1 -1
- package/dist/{index-DqpCL9kD.d.ts → index-Cl2L2P47.d.ts} +1 -1
- package/dist/{index-oJMtR3nl.d.ts → index-XkPephwV.d.ts} +1 -1
- package/dist/{index-C0qLquY0.d.ts → index-srSv2xNE.d.ts} +2 -1
- package/dist/index.d.ts +3 -3
- package/dist/index.js +5 -5
- package/dist/init/index.js +1 -1
- package/dist/{init-4vv4gYEm.js → init-DaHOxzwF.js} +2 -2
- package/dist/{init-4vv4gYEm.js.map → init-DaHOxzwF.js.map} +1 -1
- package/dist/{security-DIG-95Ic.js → security-casihGNW.js} +24 -8
- package/dist/{security-DIG-95Ic.js.map → security-casihGNW.js.map} +1 -1
- package/dist/tracker/index.d.ts +2 -2
- package/dist/tracker/index.js +2 -2
- package/dist/{tracker-BXW8-5Yx.js → tracker-B1fEAM3i.js} +2 -2
- package/dist/{tracker-BXW8-5Yx.js.map → tracker-B1fEAM3i.js.map} +1 -1
- package/dist/usage/index.d.ts +1 -1
- package/dist/usage/index.js +1 -1
- package/dist/{usage-ygkKsxdd.js → usage-BK7eyP42.js} +2 -2
- package/dist/{usage-ygkKsxdd.js.map → usage-BK7eyP42.js.map} +1 -1
- package/package.json +1 -1
|
@@ -2,7 +2,7 @@ import { PermissionDeniedError, QuotaExceededError, ValidationError } from "./ty
|
|
|
2
2
|
import { a as logger } from "./logger-B6rCpb7D.js";
|
|
3
3
|
import { t as RBACModule } from "./rbac-pRCcWVS_.js";
|
|
4
4
|
import { ActivityModule, ActivitySeverity, ActivityStatus, ActivityType } from "./activity/index.js";
|
|
5
|
-
import { a as UsageModule } from "./usage-
|
|
5
|
+
import { a as UsageModule } from "./usage-BK7eyP42.js";
|
|
6
6
|
import { n as NotificationType, r as NotificationsModule } from "./notifications-DY_i37WN.js";
|
|
7
7
|
import { o as trackOperation } from "./stub-BUnfMiAS.js";
|
|
8
8
|
import { r as runInExplicitActivityScope, t as createExplicitActivityScope } from "./explicit-activity-scope-DikJ7NAE.js";
|
|
@@ -455,4 +455,4 @@ var TrackerModule = class {
|
|
|
455
455
|
};
|
|
456
456
|
|
|
457
457
|
export { trackAgentActivity as i, AGENT_ACTIVITY_ACTIONS as n, AGENT_ACTIVITY_RESOURCE_TYPE as r, TrackerModule as t };
|
|
458
|
-
//# sourceMappingURL=tracker-
|
|
458
|
+
//# sourceMappingURL=tracker-B1fEAM3i.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"tracker-BXW8-5Yx.js","names":[],"sources":["../src/tracker/agent-activity.ts","../src/tracker/index.ts"],"sourcesContent":["/**\n * AI-agent activity (BOFF-9684)\n *\n * Platform-wide activity actions for what an AI agent does, and a helper that records them with\n * the agent as an `app` actor. The audit trail can then separate agent actions from the human\n * actions around them (ISO/IEC 42001 Annex A.9 evidence) and link each one back to the person\n * who started the run (`onBehalfOf`).\n *\n * The action names follow the platform taxonomy `<domain>.<resource>.<verb>` and are shared by\n * every product that runs agents; the product is identified by `productId`.\n *\n * @example\n * ```ts\n * import { AGENT_ACTIVITY_ACTIONS, trackAgentActivity } from '@burdenoff/be-sdk/tracker';\n *\n * await trackAgentActivity({\n * action: AGENT_ACTIVITY_ACTIONS.TOOL_CALLED,\n * agentId: agent.id,\n * workspaceId,\n * onBehalfOf: userId,\n * productId: 'botmanor',\n * metadata: { toolName: 'search' },\n * });\n * ```\n *\n * @module tracker/agent-activity\n * @category Tracking\n */\nimport { createExplicitActivityScope, runInExplicitActivityScope } from '../activity/explicit-activity-scope.js';\nimport { trackOperation } from './stub.js';\n\n/** Activity actions for AI-agent behaviour. */\nexport const AGENT_ACTIVITY_ACTIONS = Object.freeze({\n /** An agent run (one turn) finished and produced a response. */\n RUN_COMPLETED: 'agent.run.completed',\n /** An agent run failed before producing a response. */\n RUN_FAILED: 'agent.run.failed',\n /** The agent called a tool (MCP or similar). `success: false` when the call failed. */\n TOOL_CALLED: 'agent.tool.called',\n /** The agent delegated a sub-task to another agent. */\n DELEGATION_SENT: 'agent.delegation.sent',\n /** A governance policy refused something the agent run attempted (input, output, tool, model, budget, rate). */\n POLICY_BLOCKED: 'agent.policy.blocked',\n} as const);\n\nexport type AgentActivityAction = (typeof AGENT_ACTIVITY_ACTIONS)[keyof typeof AGENT_ACTIVITY_ACTIONS];\n\n/** Default `resourceType` of agent activity rows; `resourceId` defaults to the agent id. */\nexport const AGENT_ACTIVITY_RESOURCE_TYPE = 'agent';\n\nconst FAILURE_ACTIONS: ReadonlySet<AgentActivityAction> = new Set<AgentActivityAction>([\n AGENT_ACTIVITY_ACTIONS.RUN_FAILED,\n AGENT_ACTIVITY_ACTIONS.POLICY_BLOCKED,\n]);\n\nexport interface AgentActivityOptions {\n action: AgentActivityAction;\n /** The agent that acted. Recorded as the row's actor (`userId`) with `actorType: 'app'`. */\n agentId: string;\n workspaceId: string;\n /** The human who started the run, when there is one. */\n onBehalfOf?: string;\n /** Product that runs the agent, e.g. `botmanor`. */\n productId?: string;\n /** Defaults to false for RUN_FAILED and POLICY_BLOCKED, true otherwise. */\n success?: boolean;\n errorMessage?: string;\n description?: string;\n /** Defaults to `AGENT_ACTIVITY_RESOURCE_TYPE`. */\n resourceType?: string;\n /** Defaults to `agentId`. */\n resourceId?: string;\n metadata?: Record<string, unknown>;\n /** Stable idempotency key, only for callers that may replay the same event. */\n dedupeKey?: string;\n}\n\n/**\n * Record one AI-agent activity row, attributed to the agent as an `app` actor.\n *\n * Fire-and-forget like `trackOperation`: it never throws for a delivery failure and never blocks\n * on the activity service. It runs in its own explicit-activity scope, so recording what the\n * agent did does not suppress the mutation-audit row of the human request that started the run.\n */\nexport function trackAgentActivity(options: AgentActivityOptions): Promise<boolean> {\n const success = options.success ?? !FAILURE_ACTIONS.has(options.action);\n return runInExplicitActivityScope(createExplicitActivityScope(), () =>\n trackOperation({\n operationName: options.action,\n userId: options.agentId,\n actorType: 'app',\n ...(options.onBehalfOf ? { onBehalfOf: options.onBehalfOf } : {}),\n workspaceId: options.workspaceId,\n ...(options.productId ? { productId: options.productId } : {}),\n success,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n activityOptions: {\n enabled: true,\n activityType: options.action,\n description: options.description ?? `Agent ${options.agentId}: ${options.action}`,\n workspaceId: options.workspaceId,\n resourceType: options.resourceType ?? AGENT_ACTIVITY_RESOURCE_TYPE,\n resourceId: options.resourceId ?? options.agentId,\n metadata: { ...options.metadata, agentId: options.agentId },\n ...(options.dedupeKey ? { dedupeKey: options.dedupeKey } : {}),\n },\n })\n );\n}\n","/**\n * Unified Tracker Module\n * Aggregates RBAC + Activity + Usage + Notifications in single function call\n * This is the MOST IMPORTANT module that products should use for most operations\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { PermissionDeniedError, QuotaExceededError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\nimport { RBACModule, type CheckPermissionOptions } from '../rbac/index.js';\nimport { ActivityModule, ActivityType, ActivityStatus, ActivitySeverity } from '../activity/index.js';\nimport { UsageModule, type UsageMetricType } from '../usage/index.js';\nimport { NotificationsModule, NotificationType } from '../notifications/index.js';\n\nexport interface TrackOptions {\n /** User performing the action */\n userId: string;\n /** Action being performed */\n action: string;\n /** Resource type */\n resourceType: string;\n /** Optional resource ID */\n resourceId?: string;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n /** Project context */\n projectId?: string;\n\n /** RBAC options */\n rbac?: {\n /** Check permission before executing (default: true) */\n enabled?: boolean;\n /** Custom permission action (defaults to action parameter) */\n permissionAction?: string;\n };\n\n /** Activity tracking options */\n activity?: {\n /** Enable activity tracking (default: true) */\n enabled?: boolean;\n /** Activity type (auto-inferred if not provided) */\n activityType?: ActivityType;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** IP address */\n ipAddress?: string;\n /** User agent */\n userAgent?: string;\n /** Severity level */\n severity?: ActivitySeverity;\n };\n\n /**\n * Usage tracking options.\n *\n * The tracker meters a workspace quota only when `quotaName` is set: it checks capacity\n * with the owner's `checkWorkspaceQuota` (for positive amounts) and records the amount\n * with `trackUsage`. Without a `quotaName` the usage step is skipped. Mutations whose\n * schema carries a gateway `@usage` directive are already metered by the gateway and\n * should not set `quotaName` here, or the quota is charged twice.\n */\n usage?: {\n /** Enable usage tracking (default: true) */\n enabled?: boolean;\n /** Workspace quota to charge, for example `platform.projects.created`. */\n quotaName?: string;\n /** Product that owns the quota. Defaults to the SDK context's `productId`. */\n productId?: string;\n /** Description stored on the usage record. Defaults to `<action> <resourceType>`. */\n description?: string;\n /**\n * Amount to record (default: 1). A negative amount releases usage, for example on\n * delete; the quota check is skipped for it.\n */\n amount?: number;\n /** Check quota before recording a positive amount (default: true) */\n checkQuota?: boolean;\n /**\n * Legacy metric name. The workspace usage owner has no metric types, so a metric type\n * without a `quotaName` is not metered by the tracker.\n */\n metricType?: UsageMetricType;\n /** Legacy entity type. Workspace quotas are always charged to the workspace. */\n entityType?: 'user' | 'workspace' | 'organization';\n };\n\n /** Notification options */\n notification?: {\n /** Send notification on success */\n onSuccess?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n /** Send notification on failure */\n onFailure?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n };\n}\n\n/** A usage step that meters a named workspace quota. */\ninterface ResolvedUsage {\n quotaName: string;\n amount: number;\n workspaceId: string;\n checkQuota: boolean;\n}\n\nexport interface TrackResult {\n success: boolean;\n /** Permission check result */\n permissionGranted: boolean;\n /** Quota check result (if quota checking enabled) */\n quotaAvailable?: boolean;\n quotaRemaining?: number;\n /** Activity record ID */\n activityId?: string;\n /** True when the usage step recorded the amount with the owner */\n usageTracked?: boolean;\n /**\n * @deprecated The owner's `trackUsage` returns `Boolean!` and no record id, so this is\n * never set. Read `usageTracked` instead.\n */\n usageRecordId?: string;\n /** Notification IDs sent */\n notificationIds?: string[];\n /** Error if operation failed */\n error?: {\n type: 'permission' | 'quota' | 'validation' | 'unknown';\n message: string;\n details?: Record<string, unknown>;\n };\n /** Operation duration in milliseconds */\n duration: number;\n}\n\n/**\n * Unified Tracker Module\n *\n * The primary module products should use for tracking operations.\n * Automatically handles RBAC checks, activity logging, usage tracking, and notifications.\n *\n * @example\n * ```typescript\n * const result = await sdk.tracker.track({\n * userId: 'user123',\n * action: 'create_project',\n * resourceType: 'project',\n * workspaceId: 'ws123',\n * usage: {\n * quotaName: 'myproduct.projects.count',\n * productId: 'myproduct',\n * amount: 1,\n * checkQuota: true,\n * },\n * notification: {\n * onSuccess: {\n * title: 'Project Created',\n * message: 'Your project has been created successfully',\n * },\n * },\n * });\n *\n * if (!result.success) {\n * // Handle error\n * }\n * ```\n */\nexport class TrackerModule {\n private rbac: RBACModule;\n private activity: ActivityModule;\n private usage: UsageModule;\n private notifications: NotificationsModule;\n\n constructor(\n client: BurdenoffGraphQLClient,\n private context: SDKContext = {}\n ) {\n this.rbac = new RBACModule(client, context);\n this.activity = new ActivityModule(client, context);\n this.usage = new UsageModule(client, context);\n this.notifications = new NotificationsModule(client, context);\n }\n\n /**\n * Track operation with RBAC, Activity, Usage, and Notifications\n * This is the primary method products should use\n */\n public async track(options: TrackOptions): Promise<TrackResult> {\n const startTime = Date.now();\n const result: TrackResult = {\n success: false,\n permissionGranted: false,\n duration: 0,\n };\n\n try {\n // Validate required fields\n this.validateOptions(options);\n\n // Step 1: Check RBAC permission (if enabled)\n if (options.rbac?.enabled !== false) {\n await this.checkPermission(options, result);\n if (!result.permissionGranted) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n } else {\n result.permissionGranted = true;\n }\n\n // Steps 2 and 3: check quota, then record usage (only for a named workspace quota)\n const usage = this.resolveUsage(options);\n if (usage) {\n let quotaAssignmentId: string | undefined;\n if (usage.checkQuota) {\n quotaAssignmentId = await this.checkQuota(options, usage, result);\n if (result.quotaAvailable === false) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n }\n await this.trackUsage(options, usage, quotaAssignmentId, result);\n }\n\n // Step 4: Log successful activity (if enabled)\n if (options.activity?.enabled !== false) {\n await this.logSuccessActivity(options, result, startTime);\n }\n\n // Step 5: Send success notification (if configured)\n if (options.notification?.onSuccess) {\n await this.sendSuccessNotification(options, result);\n }\n\n result.success = true;\n result.duration = Date.now() - startTime;\n\n logger.info('[Tracker] Operation tracked successfully', {\n action: options.action,\n duration: result.duration,\n });\n\n return result;\n } catch (error) {\n result.duration = Date.now() - startTime;\n result.success = false;\n\n // Categorize error\n if (error instanceof PermissionDeniedError) {\n result.error = {\n type: 'permission',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof QuotaExceededError) {\n result.error = {\n type: 'quota',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof ValidationError) {\n result.error = {\n type: 'validation',\n message: error.message,\n details: error.details,\n };\n } else {\n result.error = {\n type: 'unknown',\n message: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n\n // Log failed activity\n await this.logFailedActivity(options, result, startTime);\n\n // Send failure notification (if configured)\n if (options.notification?.onFailure) {\n await this.sendFailureNotification(options, result);\n }\n\n logger.error('[Tracker] Operation tracking failed', {\n action: options.action,\n error: result.error,\n duration: result.duration,\n });\n\n return result;\n }\n }\n\n /**\n * Track operation and throw on failure\n * Convenience method that throws errors instead of returning them in result\n */\n public async trackOrThrow(options: TrackOptions): Promise<TrackResult> {\n const result = await this.track(options);\n\n if (!result.success && result.error) {\n const errorMessage = result.error.message;\n const errorDetails = result.error.details;\n\n switch (result.error.type) {\n case 'permission':\n throw new PermissionDeniedError(errorMessage, errorDetails);\n case 'quota':\n throw new QuotaExceededError(errorMessage, errorDetails);\n case 'validation':\n throw new ValidationError(errorMessage, errorDetails);\n default:\n throw new Error(errorMessage);\n }\n }\n\n return result;\n }\n\n /**\n * Simplified track method for common operations.\n * The trailing metric type is accepted for source compatibility and is not metered.\n */\n public async trackSimple(\n userId: string,\n action: string,\n resourceType: string,\n resourceId?: string,\n _metricType?: UsageMetricType\n ): Promise<boolean> {\n // A metric type has no workspace quota on the owner, so trackSimple never meters usage.\n // Call track() with `usage.quotaName` to charge a quota.\n const result = await this.track({\n userId,\n action,\n resourceType,\n resourceId,\n workspaceId: this.context.workspaceId,\n usage: { enabled: false },\n });\n\n return result.success;\n }\n\n /**\n * Validate tracking options\n */\n private validateOptions(options: TrackOptions): void {\n if (!options.userId) {\n throw new ValidationError('User ID is required');\n }\n\n if (!options.action) {\n throw new ValidationError('Action is required');\n }\n\n if (!options.resourceType) {\n throw new ValidationError('Resource type is required');\n }\n }\n\n /**\n * Check RBAC permission\n */\n private async checkPermission(options: TrackOptions, result: TrackResult): Promise<void> {\n const permissionOptions: CheckPermissionOptions = {\n userId: options.userId,\n action: options.rbac?.permissionAction || options.action,\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n workspaceId: options.workspaceId,\n };\n\n const hasPermission = await this.rbac.checkPermission(permissionOptions);\n result.permissionGranted = hasPermission;\n\n if (!hasPermission) {\n result.error = {\n type: 'permission',\n message: 'Permission denied',\n details: permissionOptions as unknown as Record<string, unknown>,\n };\n }\n }\n\n /**\n * Resolve the usage step for an operation, or null when nothing is metered: usage is\n * disabled, or no workspace quota is named (a legacy `metricType` alone has no owner\n * quota to charge).\n */\n private resolveUsage(options: TrackOptions): ResolvedUsage | null {\n const usage = options.usage;\n if (!usage || usage.enabled === false) {\n return null;\n }\n const quotaName = usage.quotaName?.trim();\n if (!quotaName) {\n if (usage.metricType) {\n logger.debug('[Tracker] Usage step skipped: no quotaName for legacy metricType', {\n action: options.action,\n metricType: usage.metricType,\n });\n }\n return null;\n }\n const amount = usage.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount === 0) {\n throw new ValidationError('Usage amount must be a finite, non-zero number');\n }\n const workspaceId = options.workspaceId ?? this.context.workspaceId;\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required to track workspace quota usage');\n }\n return {\n quotaName,\n amount,\n workspaceId,\n // Only consumption is gated; a release (negative amount) must always go through.\n checkQuota: usage.checkQuota !== false && amount > 0,\n };\n }\n\n /**\n * Check workspace quota capacity. Returns the assignment to charge when one exists.\n */\n private async checkQuota(\n options: TrackOptions,\n usage: ResolvedUsage,\n result: TrackResult\n ): Promise<string | undefined> {\n const quotaCheck = await this.usage.checkWorkspaceQuota({\n quotaName: usage.quotaName,\n amount: usage.amount,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n });\n\n result.quotaAvailable = quotaCheck.allowed;\n result.quotaRemaining = quotaCheck.limitLeft ?? undefined;\n\n if (!quotaCheck.allowed) {\n const notProvisioned = quotaCheck.assignmentId === null;\n result.error = {\n type: 'quota',\n message: notProvisioned\n ? `Quota ${usage.quotaName} is not included in this workspace's plan`\n : 'Quota exceeded',\n details: {\n quotaName: usage.quotaName,\n requestedAmount: usage.amount,\n limitLeft: quotaCheck.limitLeft,\n notProvisioned,\n },\n };\n }\n\n return quotaCheck.assignmentId ?? undefined;\n }\n\n /**\n * Record workspace quota usage with the owner.\n */\n private async trackUsage(\n options: TrackOptions,\n usage: ResolvedUsage,\n quotaAssignmentId: string | undefined,\n result: TrackResult\n ): Promise<void> {\n result.usageTracked = await this.usage.trackUsage({\n quotaName: usage.quotaName,\n productId: options.usage?.productId,\n amount: usage.amount,\n description: options.usage?.description?.trim() || `${options.action} ${options.resourceType}`,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n quotaAssignmentId,\n metadata: {\n action: options.action,\n resourceType: options.resourceType,\n ...(options.resourceId ? { resourceId: options.resourceId } : {}),\n },\n });\n }\n\n /**\n * Log successful activity\n */\n private async logSuccessActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.SUCCESS,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: options.activity?.severity || ActivitySeverity.LOW,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n }\n\n /**\n * Log failed activity\n */\n private async logFailedActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n if (options.activity?.enabled === false) {\n return;\n }\n\n try {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.FAILURE,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: ActivitySeverity.HIGH,\n errorMessage: result.error?.message,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n } catch (error) {\n logger.error('[Tracker] Failed to log activity', { error });\n }\n }\n\n /**\n * Send success notification\n */\n private async sendSuccessNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onSuccess) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onSuccess.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onSuccess.title,\n message: options.notification.onSuccess.message,\n type: options.notification.onSuccess.type || NotificationType.SUCCESS,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send success notification', { error });\n }\n }\n\n /**\n * Send failure notification\n */\n private async sendFailureNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onFailure) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onFailure.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onFailure.title,\n message: options.notification.onFailure.message,\n type: options.notification.onFailure.type || NotificationType.ERROR,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send failure notification', { error });\n }\n }\n\n /**\n * Infer activity type from action\n */\n private inferActivityType(action: string): ActivityType {\n const actionLower = action.toLowerCase();\n\n if (actionLower.includes('create') || actionLower.includes('add')) return ActivityType.CREATE;\n if (actionLower.includes('update') || actionLower.includes('edit')) return ActivityType.UPDATE;\n if (actionLower.includes('delete') || actionLower.includes('remove')) return ActivityType.DELETE;\n if (actionLower.includes('read') || actionLower.includes('view')) return ActivityType.READ;\n if (actionLower.includes('login')) return ActivityType.LOGIN;\n if (actionLower.includes('logout')) return ActivityType.LOGOUT;\n if (actionLower.includes('export')) return ActivityType.EXPORT;\n if (actionLower.includes('import')) return ActivityType.IMPORT;\n if (actionLower.includes('share')) return ActivityType.SHARE;\n if (actionLower.includes('download')) return ActivityType.DOWNLOAD;\n if (actionLower.includes('upload')) return ActivityType.UPLOAD;\n\n return ActivityType.CUSTOM;\n }\n\n /**\n * Batch track multiple operations\n */\n public async trackBatch(operations: TrackOptions[]): Promise<TrackResult[]> {\n logger.debug('[Tracker] Batch tracking operations', { count: operations.length });\n\n const results = await Promise.all(operations.map((op) => this.track(op)));\n\n logger.info('[Tracker] Batch tracking completed', {\n total: results.length,\n successful: results.filter((r) => r.success).length,\n failed: results.filter((r) => !r.success).length,\n });\n\n return results;\n }\n}\n\n// Export stub implementation for services that don't need full tracking\nexport {\n trackOperation,\n createProductTracker,\n UnifiedTrackerStub,\n trackerStub,\n UNIFIED_TRACKER_CONSTANTS,\n} from './stub.js';\nexport { isTrackedActorType, resolveAssistantSession } from './stub.js';\n// Assistant-session attribution on activity rows (BOFF-9649)\nexport { AI_ASSISTANT_ACTOR_ORIGIN } from '../activity/assistant-session.js';\nexport type { ActorOrigin, AssistantSessionAttribution } from '../activity/assistant-session.js';\nexport type {\n TrackingEvent,\n RbacCheckOptions,\n UsageTrackingOptions,\n ActivityTrackingOptions,\n UnifiedTrackingOptions,\n ProductTracker,\n TrackedActorType,\n} from './stub.js';\n\n// AI-agent activity actions and recorder (BOFF-9684)\nexport { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, trackAgentActivity } from './agent-activity.js';\nexport type { AgentActivityAction, AgentActivityOptions } from './agent-activity.js';\n\n// Opt a resolver out of the mutation-audit backstop row (see server/mutation-audit.ts)\nexport { suppressMutationAudit } from '../activity/explicit-activity-scope.js';\n\n// Re-export UsageMetricType from usage module for convenience\nexport { UsageMetricType } from '../usage/index.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,yBAAyB,OAAO,OAAO;;CAElD,eAAe;;CAEf,YAAY;;CAEZ,aAAa;;CAEb,iBAAiB;;CAEjB,gBAAgB;AAClB,CAAU;;AAKV,MAAa,+BAA+B;AAE5C,MAAM,kCAAoD,IAAI,IAAyB,CACrF,uBAAuB,YACvB,uBAAuB,cACzB,CAAC;;;;;;;;AA+BD,SAAgB,mBAAmB,SAAiD;CAClF,MAAM,UAAU,QAAQ,WAAW,CAAC,gBAAgB,IAAI,QAAQ,MAAM;CACtE,OAAO,2BAA2B,4BAA4B,SAC5D,eAAe;EACb,eAAe,QAAQ;EAC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,YAAY,SAAS,MAAM,GAAG;EAClE,IAAI,YAAY,SAAS,OAAO,GAAG;EACnC,IAAI,YAAY,SAAS,QAAQ,GAAG;EACpC,IAAI,YAAY,SAAS,QAAQ,GAAG;EACpC,IAAI,YAAY,SAAS,QAAQ,GAAG;EACpC,IAAI,YAAY,SAAS,OAAO,GAAG;EACnC,IAAI,YAAY,SAAS,UAAU,GAAG;EACtC,IAAI,YAAY,SAAS,QAAQ,GAAG;EAEpC;CACF;;;;CAKA,MAAa,WAAW,YAAoD;EAC1E,OAAO,MAAM,uCAAuC,EAAE,OAAO,WAAW,OAAO,CAAC;EAEhF,MAAM,UAAU,MAAM,QAAQ,IAAI,WAAW,KAAK,OAAO,KAAK,MAAM,EAAE,CAAC,CAAC;EAExE,OAAO,KAAK,sCAAsC;GAChD,OAAO,QAAQ;GACf,YAAY,QAAQ,QAAQ,MAAM,EAAE,OAAO,CAAC,CAAC;GAC7C,QAAQ,QAAQ,QAAQ,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;EAC5C,CAAC;EAED,OAAO;CACT;AACF"}
|
|
1
|
+
{"version":3,"file":"tracker-B1fEAM3i.js","names":[],"sources":["../src/tracker/agent-activity.ts","../src/tracker/index.ts"],"sourcesContent":["/**\n * AI-agent activity (BOFF-9684)\n *\n * Platform-wide activity actions for what an AI agent does, and a helper that records them with\n * the agent as an `app` actor. The audit trail can then separate agent actions from the human\n * actions around them (ISO/IEC 42001 Annex A.9 evidence) and link each one back to the person\n * who started the run (`onBehalfOf`).\n *\n * The action names follow the platform taxonomy `<domain>.<resource>.<verb>` and are shared by\n * every product that runs agents; the product is identified by `productId`.\n *\n * @example\n * ```ts\n * import { AGENT_ACTIVITY_ACTIONS, trackAgentActivity } from '@burdenoff/be-sdk/tracker';\n *\n * await trackAgentActivity({\n * action: AGENT_ACTIVITY_ACTIONS.TOOL_CALLED,\n * agentId: agent.id,\n * workspaceId,\n * onBehalfOf: userId,\n * productId: 'botmanor',\n * metadata: { toolName: 'search' },\n * });\n * ```\n *\n * @module tracker/agent-activity\n * @category Tracking\n */\nimport { createExplicitActivityScope, runInExplicitActivityScope } from '../activity/explicit-activity-scope.js';\nimport { trackOperation } from './stub.js';\n\n/** Activity actions for AI-agent behaviour. */\nexport const AGENT_ACTIVITY_ACTIONS = Object.freeze({\n /** An agent run (one turn) finished and produced a response. */\n RUN_COMPLETED: 'agent.run.completed',\n /** An agent run failed before producing a response. */\n RUN_FAILED: 'agent.run.failed',\n /** The agent called a tool (MCP or similar). `success: false` when the call failed. */\n TOOL_CALLED: 'agent.tool.called',\n /** The agent delegated a sub-task to another agent. */\n DELEGATION_SENT: 'agent.delegation.sent',\n /** A governance policy refused something the agent run attempted (input, output, tool, model, budget, rate). */\n POLICY_BLOCKED: 'agent.policy.blocked',\n} as const);\n\nexport type AgentActivityAction = (typeof AGENT_ACTIVITY_ACTIONS)[keyof typeof AGENT_ACTIVITY_ACTIONS];\n\n/** Default `resourceType` of agent activity rows; `resourceId` defaults to the agent id. */\nexport const AGENT_ACTIVITY_RESOURCE_TYPE = 'agent';\n\nconst FAILURE_ACTIONS: ReadonlySet<AgentActivityAction> = new Set<AgentActivityAction>([\n AGENT_ACTIVITY_ACTIONS.RUN_FAILED,\n AGENT_ACTIVITY_ACTIONS.POLICY_BLOCKED,\n]);\n\nexport interface AgentActivityOptions {\n action: AgentActivityAction;\n /** The agent that acted. Recorded as the row's actor (`userId`) with `actorType: 'app'`. */\n agentId: string;\n workspaceId: string;\n /** The human who started the run, when there is one. */\n onBehalfOf?: string;\n /** Product that runs the agent, e.g. `botmanor`. */\n productId?: string;\n /** Defaults to false for RUN_FAILED and POLICY_BLOCKED, true otherwise. */\n success?: boolean;\n errorMessage?: string;\n description?: string;\n /** Defaults to `AGENT_ACTIVITY_RESOURCE_TYPE`. */\n resourceType?: string;\n /** Defaults to `agentId`. */\n resourceId?: string;\n metadata?: Record<string, unknown>;\n /** Stable idempotency key, only for callers that may replay the same event. */\n dedupeKey?: string;\n}\n\n/**\n * Record one AI-agent activity row, attributed to the agent as an `app` actor.\n *\n * Fire-and-forget like `trackOperation`: it never throws for a delivery failure and never blocks\n * on the activity service. It runs in its own explicit-activity scope, so recording what the\n * agent did does not suppress the mutation-audit row of the human request that started the run.\n */\nexport function trackAgentActivity(options: AgentActivityOptions): Promise<boolean> {\n const success = options.success ?? !FAILURE_ACTIONS.has(options.action);\n return runInExplicitActivityScope(createExplicitActivityScope(), () =>\n trackOperation({\n operationName: options.action,\n userId: options.agentId,\n actorType: 'app',\n ...(options.onBehalfOf ? { onBehalfOf: options.onBehalfOf } : {}),\n workspaceId: options.workspaceId,\n ...(options.productId ? { productId: options.productId } : {}),\n success,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n activityOptions: {\n enabled: true,\n activityType: options.action,\n description: options.description ?? `Agent ${options.agentId}: ${options.action}`,\n workspaceId: options.workspaceId,\n resourceType: options.resourceType ?? AGENT_ACTIVITY_RESOURCE_TYPE,\n resourceId: options.resourceId ?? options.agentId,\n metadata: { ...options.metadata, agentId: options.agentId },\n ...(options.dedupeKey ? { dedupeKey: options.dedupeKey } : {}),\n },\n })\n );\n}\n","/**\n * Unified Tracker Module\n * Aggregates RBAC + Activity + Usage + Notifications in single function call\n * This is the MOST IMPORTANT module that products should use for most operations\n */\n\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { PermissionDeniedError, QuotaExceededError, ValidationError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\nimport { RBACModule, type CheckPermissionOptions } from '../rbac/index.js';\nimport { ActivityModule, ActivityType, ActivityStatus, ActivitySeverity } from '../activity/index.js';\nimport { UsageModule, type UsageMetricType } from '../usage/index.js';\nimport { NotificationsModule, NotificationType } from '../notifications/index.js';\n\nexport interface TrackOptions {\n /** User performing the action */\n userId: string;\n /** Action being performed */\n action: string;\n /** Resource type */\n resourceType: string;\n /** Optional resource ID */\n resourceId?: string;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n /** Project context */\n projectId?: string;\n\n /** RBAC options */\n rbac?: {\n /** Check permission before executing (default: true) */\n enabled?: boolean;\n /** Custom permission action (defaults to action parameter) */\n permissionAction?: string;\n };\n\n /** Activity tracking options */\n activity?: {\n /** Enable activity tracking (default: true) */\n enabled?: boolean;\n /** Activity type (auto-inferred if not provided) */\n activityType?: ActivityType;\n /** Additional metadata */\n metadata?: Record<string, unknown>;\n /** IP address */\n ipAddress?: string;\n /** User agent */\n userAgent?: string;\n /** Severity level */\n severity?: ActivitySeverity;\n };\n\n /**\n * Usage tracking options.\n *\n * The tracker meters a workspace quota only when `quotaName` is set: it checks capacity\n * with the owner's `checkWorkspaceQuota` (for positive amounts) and records the amount\n * with `trackUsage`. Without a `quotaName` the usage step is skipped. Mutations whose\n * schema carries a gateway `@usage` directive are already metered by the gateway and\n * should not set `quotaName` here, or the quota is charged twice.\n */\n usage?: {\n /** Enable usage tracking (default: true) */\n enabled?: boolean;\n /** Workspace quota to charge, for example `platform.projects.created`. */\n quotaName?: string;\n /** Product that owns the quota. Defaults to the SDK context's `productId`. */\n productId?: string;\n /** Description stored on the usage record. Defaults to `<action> <resourceType>`. */\n description?: string;\n /**\n * Amount to record (default: 1). A negative amount releases usage, for example on\n * delete; the quota check is skipped for it.\n */\n amount?: number;\n /** Check quota before recording a positive amount (default: true) */\n checkQuota?: boolean;\n /**\n * Legacy metric name. The workspace usage owner has no metric types, so a metric type\n * without a `quotaName` is not metered by the tracker.\n */\n metricType?: UsageMetricType;\n /** Legacy entity type. Workspace quotas are always charged to the workspace. */\n entityType?: 'user' | 'workspace' | 'organization';\n };\n\n /** Notification options */\n notification?: {\n /** Send notification on success */\n onSuccess?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n /** Send notification on failure */\n onFailure?: {\n title: string;\n message: string;\n type?: NotificationType;\n /** Additional user IDs to notify */\n additionalUserIds?: string[];\n };\n };\n}\n\n/** A usage step that meters a named workspace quota. */\ninterface ResolvedUsage {\n quotaName: string;\n amount: number;\n workspaceId: string;\n checkQuota: boolean;\n}\n\nexport interface TrackResult {\n success: boolean;\n /** Permission check result */\n permissionGranted: boolean;\n /** Quota check result (if quota checking enabled) */\n quotaAvailable?: boolean;\n quotaRemaining?: number;\n /** Activity record ID */\n activityId?: string;\n /** True when the usage step recorded the amount with the owner */\n usageTracked?: boolean;\n /**\n * @deprecated The owner's `trackUsage` returns `Boolean!` and no record id, so this is\n * never set. Read `usageTracked` instead.\n */\n usageRecordId?: string;\n /** Notification IDs sent */\n notificationIds?: string[];\n /** Error if operation failed */\n error?: {\n type: 'permission' | 'quota' | 'validation' | 'unknown';\n message: string;\n details?: Record<string, unknown>;\n };\n /** Operation duration in milliseconds */\n duration: number;\n}\n\n/**\n * Unified Tracker Module\n *\n * The primary module products should use for tracking operations.\n * Automatically handles RBAC checks, activity logging, usage tracking, and notifications.\n *\n * @example\n * ```typescript\n * const result = await sdk.tracker.track({\n * userId: 'user123',\n * action: 'create_project',\n * resourceType: 'project',\n * workspaceId: 'ws123',\n * usage: {\n * quotaName: 'myproduct.projects.count',\n * productId: 'myproduct',\n * amount: 1,\n * checkQuota: true,\n * },\n * notification: {\n * onSuccess: {\n * title: 'Project Created',\n * message: 'Your project has been created successfully',\n * },\n * },\n * });\n *\n * if (!result.success) {\n * // Handle error\n * }\n * ```\n */\nexport class TrackerModule {\n private rbac: RBACModule;\n private activity: ActivityModule;\n private usage: UsageModule;\n private notifications: NotificationsModule;\n\n constructor(\n client: BurdenoffGraphQLClient,\n private context: SDKContext = {}\n ) {\n this.rbac = new RBACModule(client, context);\n this.activity = new ActivityModule(client, context);\n this.usage = new UsageModule(client, context);\n this.notifications = new NotificationsModule(client, context);\n }\n\n /**\n * Track operation with RBAC, Activity, Usage, and Notifications\n * This is the primary method products should use\n */\n public async track(options: TrackOptions): Promise<TrackResult> {\n const startTime = Date.now();\n const result: TrackResult = {\n success: false,\n permissionGranted: false,\n duration: 0,\n };\n\n try {\n // Validate required fields\n this.validateOptions(options);\n\n // Step 1: Check RBAC permission (if enabled)\n if (options.rbac?.enabled !== false) {\n await this.checkPermission(options, result);\n if (!result.permissionGranted) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n } else {\n result.permissionGranted = true;\n }\n\n // Steps 2 and 3: check quota, then record usage (only for a named workspace quota)\n const usage = this.resolveUsage(options);\n if (usage) {\n let quotaAssignmentId: string | undefined;\n if (usage.checkQuota) {\n quotaAssignmentId = await this.checkQuota(options, usage, result);\n if (result.quotaAvailable === false) {\n result.duration = Date.now() - startTime;\n await this.logFailedActivity(options, result, startTime);\n return result;\n }\n }\n await this.trackUsage(options, usage, quotaAssignmentId, result);\n }\n\n // Step 4: Log successful activity (if enabled)\n if (options.activity?.enabled !== false) {\n await this.logSuccessActivity(options, result, startTime);\n }\n\n // Step 5: Send success notification (if configured)\n if (options.notification?.onSuccess) {\n await this.sendSuccessNotification(options, result);\n }\n\n result.success = true;\n result.duration = Date.now() - startTime;\n\n logger.info('[Tracker] Operation tracked successfully', {\n action: options.action,\n duration: result.duration,\n });\n\n return result;\n } catch (error) {\n result.duration = Date.now() - startTime;\n result.success = false;\n\n // Categorize error\n if (error instanceof PermissionDeniedError) {\n result.error = {\n type: 'permission',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof QuotaExceededError) {\n result.error = {\n type: 'quota',\n message: error.message,\n details: error.details,\n };\n } else if (error instanceof ValidationError) {\n result.error = {\n type: 'validation',\n message: error.message,\n details: error.details,\n };\n } else {\n result.error = {\n type: 'unknown',\n message: error instanceof Error ? error.message : 'Unknown error',\n };\n }\n\n // Log failed activity\n await this.logFailedActivity(options, result, startTime);\n\n // Send failure notification (if configured)\n if (options.notification?.onFailure) {\n await this.sendFailureNotification(options, result);\n }\n\n logger.error('[Tracker] Operation tracking failed', {\n action: options.action,\n error: result.error,\n duration: result.duration,\n });\n\n return result;\n }\n }\n\n /**\n * Track operation and throw on failure\n * Convenience method that throws errors instead of returning them in result\n */\n public async trackOrThrow(options: TrackOptions): Promise<TrackResult> {\n const result = await this.track(options);\n\n if (!result.success && result.error) {\n const errorMessage = result.error.message;\n const errorDetails = result.error.details;\n\n switch (result.error.type) {\n case 'permission':\n throw new PermissionDeniedError(errorMessage, errorDetails);\n case 'quota':\n throw new QuotaExceededError(errorMessage, errorDetails);\n case 'validation':\n throw new ValidationError(errorMessage, errorDetails);\n default:\n throw new Error(errorMessage);\n }\n }\n\n return result;\n }\n\n /**\n * Simplified track method for common operations.\n * The trailing metric type is accepted for source compatibility and is not metered.\n */\n public async trackSimple(\n userId: string,\n action: string,\n resourceType: string,\n resourceId?: string,\n _metricType?: UsageMetricType\n ): Promise<boolean> {\n // A metric type has no workspace quota on the owner, so trackSimple never meters usage.\n // Call track() with `usage.quotaName` to charge a quota.\n const result = await this.track({\n userId,\n action,\n resourceType,\n resourceId,\n workspaceId: this.context.workspaceId,\n usage: { enabled: false },\n });\n\n return result.success;\n }\n\n /**\n * Validate tracking options\n */\n private validateOptions(options: TrackOptions): void {\n if (!options.userId) {\n throw new ValidationError('User ID is required');\n }\n\n if (!options.action) {\n throw new ValidationError('Action is required');\n }\n\n if (!options.resourceType) {\n throw new ValidationError('Resource type is required');\n }\n }\n\n /**\n * Check RBAC permission\n */\n private async checkPermission(options: TrackOptions, result: TrackResult): Promise<void> {\n const permissionOptions: CheckPermissionOptions = {\n userId: options.userId,\n action: options.rbac?.permissionAction || options.action,\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n workspaceId: options.workspaceId,\n };\n\n const hasPermission = await this.rbac.checkPermission(permissionOptions);\n result.permissionGranted = hasPermission;\n\n if (!hasPermission) {\n result.error = {\n type: 'permission',\n message: 'Permission denied',\n details: permissionOptions as unknown as Record<string, unknown>,\n };\n }\n }\n\n /**\n * Resolve the usage step for an operation, or null when nothing is metered: usage is\n * disabled, or no workspace quota is named (a legacy `metricType` alone has no owner\n * quota to charge).\n */\n private resolveUsage(options: TrackOptions): ResolvedUsage | null {\n const usage = options.usage;\n if (!usage || usage.enabled === false) {\n return null;\n }\n const quotaName = usage.quotaName?.trim();\n if (!quotaName) {\n if (usage.metricType) {\n logger.debug('[Tracker] Usage step skipped: no quotaName for legacy metricType', {\n action: options.action,\n metricType: usage.metricType,\n });\n }\n return null;\n }\n const amount = usage.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount === 0) {\n throw new ValidationError('Usage amount must be a finite, non-zero number');\n }\n const workspaceId = options.workspaceId ?? this.context.workspaceId;\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required to track workspace quota usage');\n }\n return {\n quotaName,\n amount,\n workspaceId,\n // Only consumption is gated; a release (negative amount) must always go through.\n checkQuota: usage.checkQuota !== false && amount > 0,\n };\n }\n\n /**\n * Check workspace quota capacity. Returns the assignment to charge when one exists.\n */\n private async checkQuota(\n options: TrackOptions,\n usage: ResolvedUsage,\n result: TrackResult\n ): Promise<string | undefined> {\n const quotaCheck = await this.usage.checkWorkspaceQuota({\n quotaName: usage.quotaName,\n amount: usage.amount,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n });\n\n result.quotaAvailable = quotaCheck.allowed;\n result.quotaRemaining = quotaCheck.limitLeft ?? undefined;\n\n if (!quotaCheck.allowed) {\n const notProvisioned = quotaCheck.assignmentId === null;\n result.error = {\n type: 'quota',\n message: notProvisioned\n ? `Quota ${usage.quotaName} is not included in this workspace's plan`\n : 'Quota exceeded',\n details: {\n quotaName: usage.quotaName,\n requestedAmount: usage.amount,\n limitLeft: quotaCheck.limitLeft,\n notProvisioned,\n },\n };\n }\n\n return quotaCheck.assignmentId ?? undefined;\n }\n\n /**\n * Record workspace quota usage with the owner.\n */\n private async trackUsage(\n options: TrackOptions,\n usage: ResolvedUsage,\n quotaAssignmentId: string | undefined,\n result: TrackResult\n ): Promise<void> {\n result.usageTracked = await this.usage.trackUsage({\n quotaName: usage.quotaName,\n productId: options.usage?.productId,\n amount: usage.amount,\n description: options.usage?.description?.trim() || `${options.action} ${options.resourceType}`,\n workspaceId: usage.workspaceId,\n userId: options.userId,\n quotaAssignmentId,\n metadata: {\n action: options.action,\n resourceType: options.resourceType,\n ...(options.resourceId ? { resourceId: options.resourceId } : {}),\n },\n });\n }\n\n /**\n * Log successful activity\n */\n private async logSuccessActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.SUCCESS,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: options.activity?.severity || ActivitySeverity.LOW,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n }\n\n /**\n * Log failed activity\n */\n private async logFailedActivity(options: TrackOptions, result: TrackResult, startTime: number): Promise<void> {\n if (options.activity?.enabled === false) {\n return;\n }\n\n try {\n const activityRecord = await this.activity.log({\n userId: options.userId,\n activityType: options.activity?.activityType || this.inferActivityType(options.action),\n resourceType: options.resourceType,\n resourceId: options.resourceId,\n action: options.action,\n status: ActivityStatus.FAILURE,\n workspaceId: options.workspaceId,\n organizationId: options.organizationId,\n projectId: options.projectId,\n ipAddress: options.activity?.ipAddress,\n userAgent: options.activity?.userAgent,\n metadata: options.activity?.metadata,\n severity: ActivitySeverity.HIGH,\n errorMessage: result.error?.message,\n duration: Date.now() - startTime,\n });\n\n result.activityId = activityRecord.id;\n } catch (error) {\n logger.error('[Tracker] Failed to log activity', { error });\n }\n }\n\n /**\n * Send success notification\n */\n private async sendSuccessNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onSuccess) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onSuccess.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onSuccess.title,\n message: options.notification.onSuccess.message,\n type: options.notification.onSuccess.type || NotificationType.SUCCESS,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send success notification', { error });\n }\n }\n\n /**\n * Send failure notification\n */\n private async sendFailureNotification(options: TrackOptions, result: TrackResult): Promise<void> {\n if (!options.notification?.onFailure) {\n return;\n }\n\n try {\n const userIds = [options.userId, ...(options.notification.onFailure.additionalUserIds || [])];\n\n const response = await this.notifications.send({\n title: options.notification.onFailure.title,\n message: options.notification.onFailure.message,\n type: options.notification.onFailure.type || NotificationType.ERROR,\n userIds,\n });\n\n result.notificationIds = response.notificationIds;\n } catch (error) {\n logger.error('[Tracker] Failed to send failure notification', { error });\n }\n }\n\n /**\n * Infer activity type from action\n */\n private inferActivityType(action: string): ActivityType {\n const actionLower = action.toLowerCase();\n\n if (actionLower.includes('create') || actionLower.includes('add')) return ActivityType.CREATE;\n if (actionLower.includes('update') || actionLower.includes('edit')) return ActivityType.UPDATE;\n if (actionLower.includes('delete') || actionLower.includes('remove')) return ActivityType.DELETE;\n if (actionLower.includes('read') || actionLower.includes('view')) return ActivityType.READ;\n if (actionLower.includes('login')) return ActivityType.LOGIN;\n if (actionLower.includes('logout')) return ActivityType.LOGOUT;\n if (actionLower.includes('export')) return ActivityType.EXPORT;\n if (actionLower.includes('import')) return ActivityType.IMPORT;\n if (actionLower.includes('share')) return ActivityType.SHARE;\n if (actionLower.includes('download')) return ActivityType.DOWNLOAD;\n if (actionLower.includes('upload')) return ActivityType.UPLOAD;\n\n return ActivityType.CUSTOM;\n }\n\n /**\n * Batch track multiple operations\n */\n public async trackBatch(operations: TrackOptions[]): Promise<TrackResult[]> {\n logger.debug('[Tracker] Batch tracking operations', { count: operations.length });\n\n const results = await Promise.all(operations.map((op) => this.track(op)));\n\n logger.info('[Tracker] Batch tracking completed', {\n total: results.length,\n successful: results.filter((r) => r.success).length,\n failed: results.filter((r) => !r.success).length,\n });\n\n return results;\n }\n}\n\n// Export stub implementation for services that don't need full tracking\nexport {\n trackOperation,\n createProductTracker,\n UnifiedTrackerStub,\n trackerStub,\n UNIFIED_TRACKER_CONSTANTS,\n} from './stub.js';\nexport { isTrackedActorType, resolveAssistantSession } from './stub.js';\n// Assistant-session attribution on activity rows (BOFF-9649)\nexport { AI_ASSISTANT_ACTOR_ORIGIN } from '../activity/assistant-session.js';\nexport type { ActorOrigin, AssistantSessionAttribution } from '../activity/assistant-session.js';\nexport type {\n TrackingEvent,\n RbacCheckOptions,\n UsageTrackingOptions,\n ActivityTrackingOptions,\n UnifiedTrackingOptions,\n ProductTracker,\n TrackedActorType,\n} from './stub.js';\n\n// AI-agent activity actions and recorder (BOFF-9684)\nexport { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, trackAgentActivity } from './agent-activity.js';\nexport type { AgentActivityAction, AgentActivityOptions } from './agent-activity.js';\n\n// Opt a resolver out of the mutation-audit backstop row (see server/mutation-audit.ts)\nexport { suppressMutationAudit } from '../activity/explicit-activity-scope.js';\n\n// Re-export UsageMetricType from usage module for convenience\nexport { UsageMetricType } from '../usage/index.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,MAAa,yBAAyB,OAAO,OAAO;;CAElD,eAAe;;CAEf,YAAY;;CAEZ,aAAa;;CAEb,iBAAiB;;CAEjB,gBAAgB;AAClB,CAAU;;AAKV,MAAa,+BAA+B;AAE5C,MAAM,kCAAoD,IAAI,IAAyB,CACrF,uBAAuB,YACvB,uBAAuB,cACzB,CAAC;;;;;;;;AA+BD,SAAgB,mBAAmB,SAAiD;CAClF,MAAM,UAAU,QAAQ,WAAW,CAAC,gBAAgB,IAAI,QAAQ,MAAM;CACtE,OAAO,2BAA2B,4BAA4B,SAC5D,eAAe;EACb,eAAe,QAAQ;EACvB,QAAQ,QAAQ;EAChB,WAAW;EACX,GAAI,QAAQ,aAAa,EAAE,YAAY,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,IAAI,YAAY,SAAS,QAAQ,GAAG;EACpC,IAAI,YAAY,SAAS,QAAQ,GAAG;EACpC,IAAI,YAAY,SAAS,QAAQ,GAAG;EACpC,IAAI,YAAY,SAAS,OAAO,GAAG;EACnC,IAAI,YAAY,SAAS,UAAU,GAAG;EACtC,IAAI,YAAY,SAAS,QAAQ,GAAG;EAEpC;CACF;;;;CAKA,MAAa,WAAW,YAAoD;EAC1E,OAAO,MAAM,uCAAuC,EAAE,OAAO,WAAW,OAAO,CAAC;EAEhF,MAAM,UAAU,MAAM,QAAQ,IAAI,WAAW,KAAK,OAAO,KAAK,MAAM,EAAE,CAAC,CAAC;EAExE,OAAO,KAAK,sCAAsC;GAChD,OAAO,QAAQ;GACf,YAAY,QAAQ,QAAQ,MAAM,EAAE,OAAO,CAAC,CAAC;GAC7C,QAAQ,QAAQ,QAAQ,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;EAC5C,CAAC;EAED,OAAO;CACT;AACF"}
|
package/dist/usage/index.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, _ as UsageSummary, a as Quota, b as BillingUsageClient, c as SetQuotaOptions, d as TrackWorkspaceUsageOptions, f as UsageEntityType, g as UsageRecord, h as UsageOperationUnsupportedError, i as GetUsageOptions, l as TRACK_USAGE_MUTATION, m as UsageModule, n as CheckQuotaOptions, o as QuotaCheckResult, p as UsageMetricType, r as CheckWorkspaceQuotaOptions, s as QuotaPeriod, t as CHECK_WORKSPACE_QUOTA_QUERY, u as TrackUsageOptions, v as WorkspaceQuotaCheckResult, w as QuotaLimit, x as BillingUsageClientConfig, y as buildTrackUsageInput } from "../index-
|
|
1
|
+
import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, _ as UsageSummary, a as Quota, b as BillingUsageClient, c as SetQuotaOptions, d as TrackWorkspaceUsageOptions, f as UsageEntityType, g as UsageRecord, h as UsageOperationUnsupportedError, i as GetUsageOptions, l as TRACK_USAGE_MUTATION, m as UsageModule, n as CheckQuotaOptions, o as QuotaCheckResult, p as UsageMetricType, r as CheckWorkspaceQuotaOptions, s as QuotaPeriod, t as CHECK_WORKSPACE_QUOTA_QUERY, u as TrackUsageOptions, v as WorkspaceQuotaCheckResult, w as QuotaLimit, x as BillingUsageClientConfig, y as buildTrackUsageInput } from "../index-C_WEvMzP.js";
|
|
2
2
|
export { BillingUsageClient, type BillingUsageClientConfig, type BillingUsageOperationInput, CHECK_WORKSPACE_QUOTA_QUERY, CheckQuotaOptions, CheckWorkspaceQuotaOptions, GetUsageOptions, type OrgBillingUsageOperationInput, Quota, QuotaCheckResult, type QuotaLimit, QuotaPeriod, SetQuotaOptions, TRACK_USAGE_MUTATION, TrackUsageOptions, TrackWorkspaceUsageOptions, UsageEntityType, UsageMetricType, UsageModule, UsageOperationUnsupportedError, UsageRecord, UsageSummary, type WorkspaceBillingUsageOperationInput, WorkspaceQuotaCheckResult, buildTrackUsageInput };
|
package/dist/usage/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as UsageModule, c as BillingUsageClient, i as UsageMetricType, n as QuotaPeriod, o as UsageOperationUnsupportedError, r as TRACK_USAGE_MUTATION, s as buildTrackUsageInput, t as CHECK_WORKSPACE_QUOTA_QUERY } from "../usage-
|
|
1
|
+
import { a as UsageModule, c as BillingUsageClient, i as UsageMetricType, n as QuotaPeriod, o as UsageOperationUnsupportedError, r as TRACK_USAGE_MUTATION, s as buildTrackUsageInput, t as CHECK_WORKSPACE_QUOTA_QUERY } from "../usage-BK7eyP42.js";
|
|
2
2
|
|
|
3
3
|
export { BillingUsageClient, CHECK_WORKSPACE_QUOTA_QUERY, QuotaPeriod, TRACK_USAGE_MUTATION, UsageMetricType, UsageModule, UsageOperationUnsupportedError, buildTrackUsageInput };
|
|
4
4
|
//# sourceMappingURL=index.js.map
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { QuotaExceededError, SDKError, ValidationError } from "./types/index.js";
|
|
2
2
|
import { t as GatewayClient } from "./client-sAJTrb4i.js";
|
|
3
3
|
import { a as logger } from "./logger-B6rCpb7D.js";
|
|
4
|
-
import "./gateway-
|
|
4
|
+
import "./gateway-B9p8PD82.js";
|
|
5
5
|
import { randomUUID } from "node:crypto";
|
|
6
6
|
|
|
7
7
|
// src/usage/billing.ts
|
|
@@ -679,4 +679,4 @@ var UsageModule = class {
|
|
|
679
679
|
};
|
|
680
680
|
|
|
681
681
|
export { UsageModule as a, BillingUsageClient as c, UsageMetricType as i, QuotaPeriod as n, UsageOperationUnsupportedError as o, TRACK_USAGE_MUTATION as r, buildTrackUsageInput as s, CHECK_WORKSPACE_QUOTA_QUERY as t };
|
|
682
|
-
//# sourceMappingURL=usage-
|
|
682
|
+
//# sourceMappingURL=usage-BK7eyP42.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"usage-ygkKsxdd.js","names":[],"sources":["../src/usage/billing.ts","../src/usage/index.ts"],"sourcesContent":["/**\n * Billing Usage Client\n *\n * Canonical cross-layer quota/usage surface for wspace services talking to\n * `global-billing-svc`. All transport (URL resolution, actor/service header\n * assembly, service-JWT minting, retries, circuit breaker, timeouts,\n * telemetry) comes from the {@link GatewayClient}:\n *\n * - **wspace -> wspace** (resolving a workspace's org) uses `internalQuery`\n * (same-layer internal gateway, `WSPACE_INT_GATEWAY_URL`).\n * - **wspace -> global** (billing account + quota + usage) uses\n * `crossLayerQuery`, which routes via the global PUBLIC gateway\n * (`GLOBAL_PUBLIC_GATEWAY_URL`) and mints a signed `service` JWT the\n * gateway trusts. Only `x-actor-type: service` is presented — never\n * `x-actor-id` (auth-middleware reads that as an on-behalf-of override and\n * downgrades the caller to `user`, yielding a 403). Actor identity for the\n * usage record is carried in the GraphQL variables (`userId`), not in\n * headers.\n *\n * Every read/write fails open (returns `null`/`false`, or `true` for the\n * workspace quota gate) so transient billing unavailability never blocks a\n * product operation; callers that need hard enforcement must layer it on top.\n *\n * @module usage/billing\n * @category Usage\n */\n\nimport { GatewayClient } from '../gateway/index.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Bound each gateway attempt so a slow billing gateway never stalls the\n * (blocking) quota-limit read.\n */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\n/** Default TTL for the in-process plan-limit cache. */\nconst DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS = 5 * 60 * 1000;\n\n/** Lazy prune threshold — keeps the plan-limit cache bounded without timers. */\nconst QUOTA_LIMIT_CACHE_MAX_ENTRIES = 1_000;\n\nconst GET_WORKSPACE_ORG_QUERY = `\n query GetWorkspaceOrg($workspaceId: ID!) {\n workspace(id: $workspaceId) {\n orgId\n }\n }\n`;\n\nconst GET_DEFAULT_BILLING_ACCOUNT_QUERY = `\n query GetDefaultBillingAccount($orgId: ID!) {\n getDefaultBillingAccountByOrgId(orgId: $orgId) {\n id\n }\n }\n`;\n\nconst CHECK_QUOTA_QUERY = `\n query CheckQuotaExhausted($billingAccountId: ID!, $quotaName: String!, $productId: String) {\n checkQuotaExhausted(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n productId: $productId\n ) {\n limitLeft\n noLimit\n quotaAssignmentId\n }\n }\n`;\n\nconst ADD_USAGE_MUTATION = `\n mutation AddUsage(\n $billingAccountId: ID!\n $quotaName: String!\n $value: Int!\n $description: String!\n $tags: JSON\n $hash: String\n $userId: ID\n $productId: String\n ) {\n addUsage(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n value: $value\n description: $description\n tags: $tags\n hash: $hash\n userId: $userId\n productId: $productId\n )\n }\n`;\n\nconst GET_QUOTA_LIMIT_QUERY = `\n query GetQuotaLimit($billingAccountId: ID!, $quotaName: String!, $productId: String) {\n getQuotaUsageAndLimit(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n productId: $productId\n ) {\n limit\n noLimit\n }\n }\n`;\n\nconst FREE_UP_USAGE_MUTATION = `\n mutation FreeUpUsage(\n $billingAccountId: ID!\n $quotaName: String!\n $value: Int!\n $description: String\n $tags: JSON\n $hash: String\n $userId: ID\n $productId: String\n ) {\n freeUpUsage(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n value: $value\n description: $description\n tags: $tags\n hash: $hash\n userId: $userId\n productId: $productId\n )\n }\n`;\n\ninterface WorkspaceOrgQueryData {\n workspace?: {\n orgId?: string | null;\n } | null;\n}\n\ninterface BillingAccountQueryData {\n getDefaultBillingAccountByOrgId?: {\n id?: string | null;\n } | null;\n}\n\ninterface QuotaCheckQueryData {\n checkQuotaExhausted?: {\n limitLeft: number;\n noLimit: boolean;\n quotaAssignmentId: string;\n } | null;\n}\n\ninterface QuotaLimitQueryData {\n getQuotaUsageAndLimit?: {\n limit: number;\n noLimit: boolean;\n } | null;\n}\n\ninterface UsageMutationData {\n addUsage?: boolean;\n freeUpUsage?: boolean;\n}\n\n/** Common input for a quota/usage operation against a billing account. */\nexport interface BillingUsageOperationInput {\n quotaName: string;\n value?: number;\n description: string;\n /**\n * Product scope for the quota/usage record. Required — every caller must be\n * explicit about which product's meter it is touching (there is no implicit\n * default, which historically shipped as a copy-paste `'vibecontrols'`).\n */\n productId: string;\n userId?: string;\n hash?: string;\n tags?: Record<string, unknown>;\n}\n\n/** Quota/usage operation addressed by organization. */\nexport interface OrgBillingUsageOperationInput extends BillingUsageOperationInput {\n orgId: string;\n}\n\n/** Quota/usage operation addressed by workspace (org resolved internally). */\nexport interface WorkspaceBillingUsageOperationInput extends BillingUsageOperationInput {\n workspaceId: string;\n}\n\n/** Plan limit for a quota, as stored by billing-svc. */\nexport interface QuotaLimit {\n limit: number;\n noLimit: boolean;\n}\n\n/** Configuration for {@link BillingUsageClient}. */\nexport interface BillingUsageClientConfig {\n /**\n * Owning service identity (e.g. `wspace-tags-svc`). Sent as the service\n * identity header and used for log attribution.\n */\n serviceName: string;\n /** Per-request timeout in milliseconds. Defaults to 5s. */\n timeout?: number;\n /**\n * Pre-built {@link GatewayClient}. When omitted, one is created for the\n * `wspace` layer (deriving internal/cross-layer gateway URLs from env).\n * Primarily a test seam.\n */\n gatewayClient?: GatewayClient;\n /** TTL for the in-process plan-limit cache. Defaults to 5 minutes. */\n quotaLimitCacheTtlMs?: number;\n}\n\ninterface CachedQuotaLimit extends QuotaLimit {\n expiresAt: number;\n}\n\nfunction unwrap<TData>(data: TData | undefined): TData {\n if (!data) {\n throw new Error('GraphQL response did not include data');\n }\n return data;\n}\n\n/**\n * Canonical quota/usage client for wspace -> global-billing-svc traffic.\n *\n * See the module docstring for the transport contract. All methods fail open;\n * see individual method docs for the exact fallback value.\n */\nexport class BillingUsageClient {\n private readonly gatewayClient: GatewayClient;\n private readonly quotaLimitCacheTtlMs: number;\n private readonly logPrefix: string;\n\n // In-process cache for plan limits (changes at most when a workspace\n // upgrades their plan). Lazily pruned on access — no timers in a library.\n private readonly quotaLimitCache = new Map<string, CachedQuotaLimit>();\n\n constructor(config: BillingUsageClientConfig) {\n if (!config.serviceName) {\n throw new TypeError('BillingUsageClient requires a serviceName');\n }\n this.gatewayClient =\n config.gatewayClient ??\n new GatewayClient({\n layer: 'wspace',\n serviceName: config.serviceName,\n timeout: config.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS,\n });\n this.quotaLimitCacheTtlMs = config.quotaLimitCacheTtlMs ?? DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS;\n this.logPrefix = `[billing-usage:${config.serviceName}]`;\n }\n\n /**\n * Same-layer (wspace -> wspace) internal-gateway call.\n */\n private async queryWorkspaceLayer<TData>(\n query: string,\n variables: Record<string, unknown>,\n workspaceId: string\n ): Promise<TData> {\n const response = await this.gatewayClient.internalQuery<TData>({\n query,\n variables,\n headers: { 'x-workspace-id': workspaceId },\n // Blocking on the create path — keep it single-shot & snappy; consumers fail open.\n skipRetry: true,\n });\n return unwrap(response.data);\n }\n\n /**\n * Cross-layer (wspace -> global) public-gateway call. No actor headers — the\n * signed service JWT carries identity; adding `x-actor-id` would 403.\n */\n private async queryGlobalLayer<TData>(query: string, variables: Record<string, unknown>): Promise<TData> {\n const response = await this.gatewayClient.crossLayerQuery<TData>({ query, variables });\n return unwrap(response.data);\n }\n\n /**\n * Resolve the organization that owns a workspace. Fails open (`null`).\n */\n async getOrgIdFromWorkspace(workspaceId: string): Promise<string | null> {\n try {\n const data = await this.queryWorkspaceLayer<WorkspaceOrgQueryData>(\n GET_WORKSPACE_ORG_QUERY,\n { workspaceId },\n workspaceId\n );\n return data.workspace?.orgId ?? null;\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to resolve workspace org`, {\n workspaceId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n /**\n * Resolve the default billing account for an organization via the global\n * layer. Fails open (`null`).\n */\n async getDefaultBillingAccountId(orgId: string): Promise<string | null> {\n try {\n const data = await this.queryGlobalLayer<BillingAccountQueryData>(GET_DEFAULT_BILLING_ACCOUNT_QUERY, {\n orgId,\n });\n return data.getDefaultBillingAccountByOrgId?.id ?? null;\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to resolve default billing account`, {\n orgId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n /**\n * Check that an organization still has quota headroom for `value` units of\n * `quotaName`. Returns `false` when no billing account exists or the quota\n * is exhausted; rethrows nothing — transport errors propagate to the caller\n * of this low-level variant (the workspace variant fails open instead).\n */\n async ensureQuotaAvailableForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for org quota check`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const amount = input.value ?? 1;\n const data = await this.queryGlobalLayer<QuotaCheckQueryData>(CHECK_QUOTA_QUERY, {\n billingAccountId,\n quotaName: input.quotaName,\n productId: input.productId,\n });\n\n const result = data.checkQuotaExhausted;\n if (!result) {\n return false;\n }\n\n if (result.noLimit) {\n return true;\n }\n\n return result.limitLeft >= amount;\n }\n\n /**\n * Workspace-addressed quota gate: resolves the org, then applies\n * {@link ensureQuotaAvailableForOrg}. Fails OPEN (`true`) when org\n * resolution fails (unbilled / dev / internal workspaces) so local-stack\n * test workspaces and workspaces with a transiently broken tenant lookup\n * are never locked out; real limits only kick in when the workspace has a\n * billable org.\n */\n async ensureQuotaAvailableForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available; allowing quota op (fail-open)`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return true;\n }\n\n return this.ensureQuotaAvailableForOrg({ ...input, orgId });\n }\n\n /**\n * Record usage against an organization's billing account. No-ops (`false`)\n * when there is no billing account.\n */\n async addUsageForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for addUsage`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const data = await this.queryGlobalLayer<UsageMutationData>(ADD_USAGE_MUTATION, {\n billingAccountId,\n quotaName: input.quotaName,\n value: input.value ?? 1,\n description: input.description,\n tags: input.tags,\n hash: input.hash,\n userId: input.userId,\n productId: input.productId,\n });\n\n return data.addUsage ?? false;\n }\n\n /**\n * Workspace-addressed {@link addUsageForOrg}. No-ops (`false`) when the\n * workspace has no org.\n */\n async addUsageForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available for workspace addUsage`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n return this.addUsageForOrg({ ...input, orgId });\n }\n\n /**\n * Credit usage back to an organization's billing account. No-ops (`false`)\n * when there is no billing account.\n */\n async freeUpUsageForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for freeUpUsage`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const data = await this.queryGlobalLayer<UsageMutationData>(FREE_UP_USAGE_MUTATION, {\n billingAccountId,\n quotaName: input.quotaName,\n value: input.value ?? 1,\n description: input.description,\n tags: input.tags,\n hash: input.hash,\n userId: input.userId,\n productId: input.productId,\n });\n\n return data.freeUpUsage ?? false;\n }\n\n /**\n * Workspace-addressed {@link freeUpUsageForOrg}. No-ops (`false`) when the\n * workspace has no org.\n */\n async freeUpUsageForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available for workspace freeUpUsage`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n return this.freeUpUsageForOrg({ ...input, orgId });\n }\n\n /**\n * Fetch the plan limit for a quota from billing-svc, bypassing billing's\n * internal usage counter (the caller's own DB is the source of truth for\n * current usage; billing only stores the plan maximum). Results are cached\n * in-process per workspace/quota/product. Fails open (`null`) when billing\n * is unreachable so dev/test workspaces without billing accounts are never\n * blocked.\n */\n async getQuotaLimitForWorkspace(\n workspaceId: string,\n quotaName: string,\n productId: string\n ): Promise<QuotaLimit | null> {\n const cacheKey = `${workspaceId}:${quotaName}:${productId}`;\n const cached = this.quotaLimitCache.get(cacheKey);\n if (cached && cached.expiresAt > Date.now()) {\n return { limit: cached.limit, noLimit: cached.noLimit };\n }\n\n const orgId = await this.getOrgIdFromWorkspace(workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No org found for quota limit lookup; failing open`, {\n workspaceId,\n quotaName,\n });\n return null;\n }\n\n const billingAccountId = await this.getDefaultBillingAccountId(orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account found for quota limit lookup; failing open`, {\n workspaceId,\n quotaName,\n });\n return null;\n }\n\n try {\n const data = await this.queryGlobalLayer<QuotaLimitQueryData>(GET_QUOTA_LIMIT_QUERY, {\n billingAccountId,\n quotaName,\n productId,\n });\n\n const result = data.getQuotaUsageAndLimit;\n if (!result) {\n return null;\n }\n\n this.rememberQuotaLimit(cacheKey, { limit: result.limit, noLimit: result.noLimit });\n return { limit: result.limit, noLimit: result.noLimit };\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to fetch quota limit; failing open`, {\n workspaceId,\n quotaName,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n private rememberQuotaLimit(cacheKey: string, value: QuotaLimit): void {\n if (this.quotaLimitCache.size >= QUOTA_LIMIT_CACHE_MAX_ENTRIES) {\n const now = Date.now();\n for (const [key, entry] of this.quotaLimitCache) {\n if (entry.expiresAt <= now) this.quotaLimitCache.delete(key);\n }\n // Still full after pruning (all entries fresh): drop the oldest-inserted\n // entries rather than refusing to cache. Plan limits are re-fetchable.\n if (this.quotaLimitCache.size >= QUOTA_LIMIT_CACHE_MAX_ENTRIES) {\n const overflow = this.quotaLimitCache.size - QUOTA_LIMIT_CACHE_MAX_ENTRIES + 1;\n let removed = 0;\n for (const key of this.quotaLimitCache.keys()) {\n this.quotaLimitCache.delete(key);\n removed += 1;\n if (removed >= overflow) break;\n }\n }\n }\n this.quotaLimitCache.set(cacheKey, { ...value, expiresAt: Date.now() + this.quotaLimitCacheTtlMs });\n }\n}\n","/**\n * Usage & Quota Module\n *\n * Checks and records workspace quota usage against the workspace usage owner\n * (wspace-activity-svc). The owner's published contract is:\n *\n * - `checkWorkspaceQuota(workspaceId, quotaName, amount): WorkspaceQuotaCheckResult!`\n * - `trackUsage(input: TrackUsageInput!): Boolean!`\n *\n * Quotas are keyed by `quotaName` (for example `platform.projects.created`), not by the\n * `entityId`/`entityType`/`metricType` triple this module used to send. That triple was\n * never part of the owner's schema, so every legacy call failed GraphQL validation\n * (BOFF-10955). The legacy methods remain for source compatibility and fail with\n * {@link UsageOperationUnsupportedError} before any network call.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { SDKError, ValidationError, QuotaExceededError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Legacy usage metric names. The workspace usage owner has no metric types; quotas are\n * addressed by `quotaName`. Kept so existing `sdk.tracker.track({ usage: { metricType } })`\n * call sites keep compiling; the tracker does not meter a metric type on its own.\n */\nexport enum UsageMetricType {\n API_CALLS = 'api_calls',\n STORAGE = 'storage',\n BANDWIDTH = 'bandwidth',\n USERS = 'users',\n PROJECTS = 'projects',\n WORKSPACES = 'workspaces',\n RECORDS = 'records',\n COMPUTE_TIME = 'compute_time',\n TRANSACTIONS = 'transactions',\n CUSTOM = 'custom',\n}\n\nexport enum QuotaPeriod {\n DAILY = 'daily',\n WEEKLY = 'weekly',\n MONTHLY = 'monthly',\n YEARLY = 'yearly',\n LIFETIME = 'lifetime',\n}\n\n/**\n * Entity type for usage tracking\n */\nexport type UsageEntityType = 'user' | 'workspace' | 'organization';\n\nexport interface TrackUsageOptions {\n /** User or workspace consuming the resource */\n entityId: string;\n /** Type of entity (user or workspace) */\n entityType: UsageEntityType;\n /** Metric type */\n metricType: UsageMetricType;\n /** Amount to increment */\n amount: number;\n /** Optional resource identifier */\n resourceId?: string;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n}\n\nexport interface CheckQuotaOptions {\n /** Entity to check quota for */\n entityId: string;\n /** Type of entity */\n entityType: UsageEntityType;\n /** Metric type */\n metricType: UsageMetricType;\n /** Amount to check availability for */\n requestedAmount: number;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n}\n\nexport interface QuotaCheckResult {\n allowed: boolean;\n currentUsage: number;\n quotaLimit: number;\n remainingQuota: number;\n resetAt?: string;\n period: QuotaPeriod;\n reason?: string;\n}\n\nexport interface UsageRecord {\n id: string;\n entityId: string;\n entityType: UsageEntityType;\n metricType: UsageMetricType;\n amount: number;\n resourceId?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n recordedAt: string;\n}\n\nexport interface UsageSummary {\n entityId: string;\n entityType: string;\n metricType: UsageMetricType;\n totalUsage: number;\n period: QuotaPeriod;\n periodStart: string;\n periodEnd: string;\n quotaLimit?: number;\n utilizationPercentage?: number;\n}\n\nexport interface SetQuotaOptions {\n entityId: string;\n entityType: UsageEntityType;\n metricType: UsageMetricType;\n limit: number;\n period: QuotaPeriod;\n workspaceId?: string;\n organizationId?: string;\n}\n\nexport interface Quota {\n id: string;\n entityId: string;\n entityType: string;\n metricType: UsageMetricType;\n limit: number;\n period: QuotaPeriod;\n currentUsage: number;\n resetAt: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface GetUsageOptions {\n entityId: string;\n entityType: UsageEntityType;\n metricType?: UsageMetricType;\n startDate?: string;\n endDate?: string;\n workspaceId?: string;\n organizationId?: string;\n limit?: number;\n offset?: number;\n}\n\n/** Thrown by SDK usage operations the workspace usage owner does not expose. */\nexport class UsageOperationUnsupportedError extends SDKError {\n constructor(operation: string, guidance: string) {\n super(\n `UsageModule.${operation} is not supported by the workspace usage owner: ${guidance}`,\n 'USAGE_OPERATION_UNSUPPORTED',\n { operation }\n );\n this.name = 'UsageOperationUnsupportedError';\n Object.setPrototypeOf(this, UsageOperationUnsupportedError.prototype);\n }\n}\n\n/**\n * Query sent to the owner's `checkWorkspaceQuota`. Every argument and selected field must\n * exist on the published wspace schema (see tests/usage-module.test.ts).\n */\nexport const CHECK_WORKSPACE_QUOTA_QUERY = `\n query CheckWorkspaceQuota($workspaceId: ID!, $quotaName: String!, $amount: Float) {\n checkWorkspaceQuota(workspaceId: $workspaceId, quotaName: $quotaName, amount: $amount) {\n allowed\n assignmentId\n limitLeft\n noLimit\n }\n }\n`;\n\n/** Mutation sent to the owner's `trackUsage`, which returns `Boolean!`. */\nexport const TRACK_USAGE_MUTATION = `\n mutation TrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n }\n`;\n\nexport interface CheckWorkspaceQuotaOptions {\n /** Quota to check, for example `platform.projects.created`. */\n quotaName: string;\n /** Amount the caller is about to consume. Must be positive; defaults to 1. */\n amount?: number;\n /** Workspace that owns the quota. Defaults to the SDK context's workspace. */\n workspaceId?: string;\n /** End user the check is made for. Defaults to the SDK context's actor. */\n userId?: string;\n}\n\n/** The owner's `WorkspaceQuotaCheckResult`. */\nexport interface WorkspaceQuotaCheckResult {\n /** True when the quota has enough remaining capacity for the requested amount. */\n allowed: boolean;\n /** Active assignment to charge, or null when the workspace's plan does not include the quota. */\n assignmentId: string | null;\n /** Remaining capacity after the requested amount; null when unlimited or not provisioned. */\n limitLeft: number | null;\n /** True when the quota is unlimited. */\n noLimit: boolean;\n}\n\nexport interface TrackWorkspaceUsageOptions {\n /** Quota to charge, for example `platform.projects.created`. */\n quotaName: string;\n /** Product the quota belongs to, for example `platform`. Defaults to the SDK context's product. */\n productId?: string;\n /**\n * Amount to record. A positive amount consumes quota; a negative amount releases it (for\n * example on delete). The owner only accepts negative amounts from services and super\n * admins, which is how this module relays the call. Zero is rejected.\n */\n amount: number;\n /** Human-readable reason stored on the usage record. */\n description: string;\n /** Workspace to charge. Defaults to the SDK context's workspace. */\n workspaceId?: string;\n /** End user the usage is recorded for. Defaults to the SDK context's actor. */\n userId?: string;\n /** Assignment returned by {@link UsageModule.checkWorkspaceQuota}; saves the owner a lookup. */\n quotaAssignmentId?: string;\n /** Billing account reference stored on the record. Omit for workspace quotas. */\n billingAccountId?: string;\n /**\n * Idempotency key. The owner records one charge per hash and workspace, so a retried\n * request cannot charge twice. A random key is generated per call when omitted.\n */\n hash?: string;\n /** Additional metadata stored on the usage record. */\n metadata?: Record<string, unknown>;\n}\n\nfunction legacyGuidance(replacement: string): string {\n return `quotas are addressed by quotaName on the workspace usage owner; use ${replacement}`;\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Builds the owner's `TrackUsageInput` from SDK options, filling defaults from the context.\n * Throws {@link ValidationError} for input the owner would refuse.\n */\nexport function buildTrackUsageInput(\n options: TrackWorkspaceUsageOptions,\n context: SDKContext = {}\n): Record<string, unknown> {\n const quotaName = nonEmpty(options.quotaName);\n if (!quotaName) {\n throw new ValidationError('Quota name is required');\n }\n const productId = nonEmpty(options.productId) ?? nonEmpty(context.productId);\n if (!productId) {\n throw new ValidationError('Product ID is required');\n }\n const description = nonEmpty(options.description);\n if (!description) {\n throw new ValidationError('Description is required');\n }\n if (typeof options.amount !== 'number' || !Number.isFinite(options.amount) || options.amount === 0) {\n throw new ValidationError('Amount must be a finite, non-zero number');\n }\n const workspaceId = nonEmpty(options.workspaceId) ?? nonEmpty(context.workspaceId);\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required');\n }\n\n const input: Record<string, unknown> = {\n quotaName,\n productId,\n amount: options.amount,\n description,\n workspaceId,\n hash: nonEmpty(options.hash) ?? `sdk-usage:${randomUUID()}`,\n };\n const userId = nonEmpty(options.userId) ?? nonEmpty(context.actorId);\n if (userId) input['userId'] = userId;\n if (options.quotaAssignmentId) input['quotaAssignmentId'] = options.quotaAssignmentId;\n if (options.billingAccountId) input['billingAccountId'] = options.billingAccountId;\n if (options.metadata) input['metadata'] = options.metadata;\n return input;\n}\n\n/**\n * Usage & Quota Module\n */\nexport class UsageModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Context for one owner call: relayed as a platform service acting for `userId`, with the\n * quota's workspace in scope. The owner takes the workspace from this context, never from\n * the input, and only lets services release (decrement) usage.\n */\n private requestContext(workspaceId: string, userId: string | undefined): SDKContext {\n const actorId = userId ?? this.context.actorId;\n return {\n ...this.context,\n ...(actorId ? { actorId } : {}),\n actorType: 'service',\n workspaceId,\n };\n }\n\n /**\n * Check whether a workspace quota has capacity for `amount` (default 1).\n */\n public async checkWorkspaceQuota(options: CheckWorkspaceQuotaOptions): Promise<WorkspaceQuotaCheckResult> {\n const quotaName = nonEmpty(options.quotaName);\n if (!quotaName) {\n throw new ValidationError('Quota name is required');\n }\n const amount = options.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {\n throw new ValidationError('Quota checks need a positive amount');\n }\n const workspaceId = nonEmpty(options.workspaceId) ?? nonEmpty(this.context.workspaceId);\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required');\n }\n\n logger.debug('[Usage] Checking workspace quota', { workspaceId, quotaName, amount });\n\n const response = await this.client.query<{ checkWorkspaceQuota: WorkspaceQuotaCheckResult }>(\n CHECK_WORKSPACE_QUOTA_QUERY,\n { workspaceId, quotaName, amount },\n this.requestContext(workspaceId, nonEmpty(options.userId))\n );\n\n const result = response.checkWorkspaceQuota;\n logger.debug('[Usage] Workspace quota check result', { workspaceId, quotaName, allowed: result.allowed });\n return result;\n }\n\n /**\n * Check a workspace quota and throw {@link QuotaExceededError} when it has no capacity.\n * Returns the check result so the caller can pass `assignmentId` to {@link trackUsage}.\n */\n public async requireWorkspaceQuota(options: CheckWorkspaceQuotaOptions): Promise<WorkspaceQuotaCheckResult> {\n const result = await this.checkWorkspaceQuota(options);\n if (!result.allowed) {\n const notProvisioned = result.assignmentId === null;\n throw new QuotaExceededError(\n notProvisioned ? `Quota ${options.quotaName} is not included in this workspace's plan` : 'Quota exceeded',\n {\n quotaName: options.quotaName,\n requestedAmount: options.amount ?? 1,\n limitLeft: result.limitLeft,\n notProvisioned,\n }\n );\n }\n return result;\n }\n\n /**\n * Record workspace quota usage. A negative amount releases previously recorded usage.\n * Resolves to `true` once the owner has stored (or deduplicated) the record.\n */\n public async trackUsage(options: TrackWorkspaceUsageOptions): Promise<boolean> {\n const input = buildTrackUsageInput(options, this.context);\n const workspaceId = input['workspaceId'] as string;\n\n logger.debug('[Usage] Tracking workspace usage', {\n workspaceId,\n quotaName: input['quotaName'],\n amount: input['amount'],\n });\n\n const response = await this.client.query<{ trackUsage: boolean }>(\n TRACK_USAGE_MUTATION,\n { input },\n this.requestContext(workspaceId, nonEmpty(options.userId))\n );\n\n logger.info('[Usage] Workspace usage tracked', { workspaceId, quotaName: input['quotaName'] });\n return response.trackUsage;\n }\n\n /**\n * @deprecated The workspace usage owner has no `trackUsage` record shape keyed by\n * `entityId`/`metricType`. Use {@link trackUsage} with a `quotaName`.\n */\n public async track(_options: TrackUsageOptions): Promise<UsageRecord> {\n throw new UsageOperationUnsupportedError('track', legacyGuidance('trackUsage({ quotaName, productId, amount })'));\n }\n\n /**\n * @deprecated The owner has no `checkQuota` operation. Use {@link checkWorkspaceQuota}.\n */\n public async checkQuota(_options: CheckQuotaOptions): Promise<QuotaCheckResult> {\n throw new UsageOperationUnsupportedError(\n 'checkQuota',\n legacyGuidance('checkWorkspaceQuota({ quotaName, amount })')\n );\n }\n\n /**\n * @deprecated The owner has no `checkQuota` operation. Use {@link requireWorkspaceQuota}.\n */\n public async requireQuota(_options: CheckQuotaOptions): Promise<void> {\n throw new UsageOperationUnsupportedError(\n 'requireQuota',\n legacyGuidance('requireWorkspaceQuota({ quotaName, amount })')\n );\n }\n\n /**\n * @deprecated Use {@link requireWorkspaceQuota} followed by {@link trackUsage}.\n */\n public async trackAndCheck(_options: TrackUsageOptions): Promise<{\n usage: UsageRecord;\n quotaCheck: QuotaCheckResult;\n }> {\n throw new UsageOperationUnsupportedError(\n 'trackAndCheck',\n legacyGuidance('requireWorkspaceQuota() and then trackUsage()')\n );\n }\n\n /**\n * @deprecated The owner has no `getUsage` operation; read records with the owner's\n * `getUsageRecords(filters, pagination)`.\n */\n public async getUsage(_options: GetUsageOptions): Promise<{\n records: UsageRecord[];\n total: number;\n }> {\n throw new UsageOperationUnsupportedError('getUsage', legacyGuidance(\"the owner's getUsageRecords query\"));\n }\n\n /**\n * @deprecated The owner's `getUsageSummary` takes `UsageFilters` and returns a list; this\n * signature does not map onto it.\n */\n public async getSummary(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType,\n _period: QuotaPeriod\n ): Promise<UsageSummary> {\n throw new UsageOperationUnsupportedError(\n 'getSummary',\n legacyGuidance(\"the owner's getUsageSummary(filters) query\")\n );\n }\n\n /**\n * @deprecated Quota limits are assigned by global-billing-svc through the owner's\n * `assignWorkspaceQuota`, which only billing's service identity may call.\n */\n public async setQuota(_options: SetQuotaOptions): Promise<Quota> {\n throw new UsageOperationUnsupportedError('setQuota', 'quota limits are assigned by global-billing-svc');\n }\n\n /**\n * @deprecated The owner has no `getQuota` operation; read `workspaceQuotaStatuses(workspaceId)`.\n */\n public async getQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<Quota | null> {\n throw new UsageOperationUnsupportedError('getQuota', legacyGuidance(\"the owner's workspaceQuotaStatuses query\"));\n }\n\n /**\n * @deprecated The owner has no `getQuotas` operation; read `workspaceQuotaAssignments(workspaceId)`.\n */\n public async getQuotas(_entityId: string, _entityType: UsageEntityType): Promise<Quota[]> {\n throw new UsageOperationUnsupportedError(\n 'getQuotas',\n legacyGuidance(\"the owner's workspaceQuotaAssignments query\")\n );\n }\n\n /**\n * @deprecated The owner has no `resetQuota` operation; quotas reset on their `resetPeriod`.\n */\n public async resetQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<boolean> {\n throw new UsageOperationUnsupportedError('resetQuota', \"quotas reset on the assignment's resetPeriod\");\n }\n\n /**\n * @deprecated The owner has no `deleteQuota` operation; billing deactivates assignments.\n */\n public async deleteQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<boolean> {\n throw new UsageOperationUnsupportedError('deleteQuota', 'quota assignments are deactivated by global-billing-svc');\n }\n\n /**\n * @deprecated The owner has no `trackUsageBulk` operation. Call {@link trackUsage} per record.\n */\n public async trackBulk(_records: TrackUsageOptions[]): Promise<UsageRecord[]> {\n throw new UsageOperationUnsupportedError('trackBulk', legacyGuidance('trackUsage() per record'));\n }\n}\n\nexport {\n BillingUsageClient,\n type BillingUsageClientConfig,\n type BillingUsageOperationInput,\n type OrgBillingUsageOperationInput,\n type WorkspaceBillingUsageOperationInput,\n type QuotaLimit,\n} from './billing.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,6BAA6B;;AAGnC,MAAM,mCAAmC;;AAGzC,MAAM,gCAAgC;AAEtC,MAAM,0BAA0B;;;;;;;AAQhC,MAAM,oCAAoC;;;;;;;AAQ1C,MAAM,oBAAoB;;;;;;;;;;;;;AAc1B,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;AAwB3B,MAAM,wBAAwB;;;;;;;;;;;;AAa9B,MAAM,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;AA+G/B,SAAS,OAAc,MAAgC;CACrD,IAAI,CAAC,MACH,MAAM,IAAI,MAAM,uCAAuC;CAEzD,OAAO;AACT;;;;;;;AAQA,IAAa,qBAAb,MAAgC;CAC9B,AAAiB;CACjB,AAAiB;CACjB,AAAiB;CAIjB,AAAiB,kCAAkB,IAAI,IAA8B;CAErE,YAAY,QAAkC;EAC5C,IAAI,CAAC,OAAO,aACV,MAAM,IAAI,UAAU,2CAA2C;EAEjE,KAAK,gBACH,OAAO,iBACP,IAAI,cAAc;GAChB,OAAO;GACP,aAAa,OAAO;GACpB,SAAS,OAAO,WAAW;EAC7B,CAAC;EACH,KAAK,uBAAuB,OAAO,wBAAwB;EAC3D,KAAK,YAAY,kBAAkB,OAAO,YAAY;CACxD;;;;CAKA,MAAc,oBACZ,OACA,WACA,aACgB;EAQhB,OAAO,QAAO,MAPS,KAAK,cAAc,cAAqB;GAC7D;GACA;GACA,SAAS,EAAE,kBAAkB,Y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F"}
|
|
1
|
+
{"version":3,"file":"usage-BK7eyP42.js","names":[],"sources":["../src/usage/billing.ts","../src/usage/index.ts"],"sourcesContent":["/**\n * Billing Usage Client\n *\n * Canonical cross-layer quota/usage surface for wspace services talking to\n * `global-billing-svc`. All transport (URL resolution, actor/service header\n * assembly, service-JWT minting, retries, circuit breaker, timeouts,\n * telemetry) comes from the {@link GatewayClient}:\n *\n * - **wspace -> wspace** (resolving a workspace's org) uses `internalQuery`\n * (same-layer internal gateway, `WSPACE_INT_GATEWAY_URL`).\n * - **wspace -> global** (billing account + quota + usage) uses\n * `crossLayerQuery`, which routes via the global PUBLIC gateway\n * (`GLOBAL_PUBLIC_GATEWAY_URL`) and mints a signed `service` JWT the\n * gateway trusts. Only `x-actor-type: service` is presented — never\n * `x-actor-id` (auth-middleware reads that as an on-behalf-of override and\n * downgrades the caller to `user`, yielding a 403). Actor identity for the\n * usage record is carried in the GraphQL variables (`userId`), not in\n * headers.\n *\n * Every read/write fails open (returns `null`/`false`, or `true` for the\n * workspace quota gate) so transient billing unavailability never blocks a\n * product operation; callers that need hard enforcement must layer it on top.\n *\n * @module usage/billing\n * @category Usage\n */\n\nimport { GatewayClient } from '../gateway/index.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Bound each gateway attempt so a slow billing gateway never stalls the\n * (blocking) quota-limit read.\n */\nconst DEFAULT_REQUEST_TIMEOUT_MS = 5_000;\n\n/** Default TTL for the in-process plan-limit cache. */\nconst DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS = 5 * 60 * 1000;\n\n/** Lazy prune threshold — keeps the plan-limit cache bounded without timers. */\nconst QUOTA_LIMIT_CACHE_MAX_ENTRIES = 1_000;\n\nconst GET_WORKSPACE_ORG_QUERY = `\n query GetWorkspaceOrg($workspaceId: ID!) {\n workspace(id: $workspaceId) {\n orgId\n }\n }\n`;\n\nconst GET_DEFAULT_BILLING_ACCOUNT_QUERY = `\n query GetDefaultBillingAccount($orgId: ID!) {\n getDefaultBillingAccountByOrgId(orgId: $orgId) {\n id\n }\n }\n`;\n\nconst CHECK_QUOTA_QUERY = `\n query CheckQuotaExhausted($billingAccountId: ID!, $quotaName: String!, $productId: String) {\n checkQuotaExhausted(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n productId: $productId\n ) {\n limitLeft\n noLimit\n quotaAssignmentId\n }\n }\n`;\n\nconst ADD_USAGE_MUTATION = `\n mutation AddUsage(\n $billingAccountId: ID!\n $quotaName: String!\n $value: Int!\n $description: String!\n $tags: JSON\n $hash: String\n $userId: ID\n $productId: String\n ) {\n addUsage(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n value: $value\n description: $description\n tags: $tags\n hash: $hash\n userId: $userId\n productId: $productId\n )\n }\n`;\n\nconst GET_QUOTA_LIMIT_QUERY = `\n query GetQuotaLimit($billingAccountId: ID!, $quotaName: String!, $productId: String) {\n getQuotaUsageAndLimit(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n productId: $productId\n ) {\n limit\n noLimit\n }\n }\n`;\n\nconst FREE_UP_USAGE_MUTATION = `\n mutation FreeUpUsage(\n $billingAccountId: ID!\n $quotaName: String!\n $value: Int!\n $description: String\n $tags: JSON\n $hash: String\n $userId: ID\n $productId: String\n ) {\n freeUpUsage(\n billingAccountId: $billingAccountId\n quotaName: $quotaName\n value: $value\n description: $description\n tags: $tags\n hash: $hash\n userId: $userId\n productId: $productId\n )\n }\n`;\n\ninterface WorkspaceOrgQueryData {\n workspace?: {\n orgId?: string | null;\n } | null;\n}\n\ninterface BillingAccountQueryData {\n getDefaultBillingAccountByOrgId?: {\n id?: string | null;\n } | null;\n}\n\ninterface QuotaCheckQueryData {\n checkQuotaExhausted?: {\n limitLeft: number;\n noLimit: boolean;\n quotaAssignmentId: string;\n } | null;\n}\n\ninterface QuotaLimitQueryData {\n getQuotaUsageAndLimit?: {\n limit: number;\n noLimit: boolean;\n } | null;\n}\n\ninterface UsageMutationData {\n addUsage?: boolean;\n freeUpUsage?: boolean;\n}\n\n/** Common input for a quota/usage operation against a billing account. */\nexport interface BillingUsageOperationInput {\n quotaName: string;\n value?: number;\n description: string;\n /**\n * Product scope for the quota/usage record. Required — every caller must be\n * explicit about which product's meter it is touching (there is no implicit\n * default, which historically shipped as a copy-paste `'vibecontrols'`).\n */\n productId: string;\n userId?: string;\n hash?: string;\n tags?: Record<string, unknown>;\n}\n\n/** Quota/usage operation addressed by organization. */\nexport interface OrgBillingUsageOperationInput extends BillingUsageOperationInput {\n orgId: string;\n}\n\n/** Quota/usage operation addressed by workspace (org resolved internally). */\nexport interface WorkspaceBillingUsageOperationInput extends BillingUsageOperationInput {\n workspaceId: string;\n}\n\n/** Plan limit for a quota, as stored by billing-svc. */\nexport interface QuotaLimit {\n limit: number;\n noLimit: boolean;\n}\n\n/** Configuration for {@link BillingUsageClient}. */\nexport interface BillingUsageClientConfig {\n /**\n * Owning service identity (e.g. `wspace-tags-svc`). Sent as the service\n * identity header and used for log attribution.\n */\n serviceName: string;\n /** Per-request timeout in milliseconds. Defaults to 5s. */\n timeout?: number;\n /**\n * Pre-built {@link GatewayClient}. When omitted, one is created for the\n * `wspace` layer (deriving internal/cross-layer gateway URLs from env).\n * Primarily a test seam.\n */\n gatewayClient?: GatewayClient;\n /** TTL for the in-process plan-limit cache. Defaults to 5 minutes. */\n quotaLimitCacheTtlMs?: number;\n}\n\ninterface CachedQuotaLimit extends QuotaLimit {\n expiresAt: number;\n}\n\nfunction unwrap<TData>(data: TData | undefined): TData {\n if (!data) {\n throw new Error('GraphQL response did not include data');\n }\n return data;\n}\n\n/**\n * Canonical quota/usage client for wspace -> global-billing-svc traffic.\n *\n * See the module docstring for the transport contract. All methods fail open;\n * see individual method docs for the exact fallback value.\n */\nexport class BillingUsageClient {\n private readonly gatewayClient: GatewayClient;\n private readonly quotaLimitCacheTtlMs: number;\n private readonly logPrefix: string;\n\n // In-process cache for plan limits (changes at most when a workspace\n // upgrades their plan). Lazily pruned on access — no timers in a library.\n private readonly quotaLimitCache = new Map<string, CachedQuotaLimit>();\n\n constructor(config: BillingUsageClientConfig) {\n if (!config.serviceName) {\n throw new TypeError('BillingUsageClient requires a serviceName');\n }\n this.gatewayClient =\n config.gatewayClient ??\n new GatewayClient({\n layer: 'wspace',\n serviceName: config.serviceName,\n timeout: config.timeout ?? DEFAULT_REQUEST_TIMEOUT_MS,\n });\n this.quotaLimitCacheTtlMs = config.quotaLimitCacheTtlMs ?? DEFAULT_QUOTA_LIMIT_CACHE_TTL_MS;\n this.logPrefix = `[billing-usage:${config.serviceName}]`;\n }\n\n /**\n * Same-layer (wspace -> wspace) internal-gateway call.\n */\n private async queryWorkspaceLayer<TData>(\n query: string,\n variables: Record<string, unknown>,\n workspaceId: string\n ): Promise<TData> {\n const response = await this.gatewayClient.internalQuery<TData>({\n query,\n variables,\n headers: { 'x-workspace-id': workspaceId },\n // Blocking on the create path — keep it single-shot & snappy; consumers fail open.\n skipRetry: true,\n });\n return unwrap(response.data);\n }\n\n /**\n * Cross-layer (wspace -> global) public-gateway call. No actor headers — the\n * signed service JWT carries identity; adding `x-actor-id` would 403.\n */\n private async queryGlobalLayer<TData>(query: string, variables: Record<string, unknown>): Promise<TData> {\n const response = await this.gatewayClient.crossLayerQuery<TData>({ query, variables });\n return unwrap(response.data);\n }\n\n /**\n * Resolve the organization that owns a workspace. Fails open (`null`).\n */\n async getOrgIdFromWorkspace(workspaceId: string): Promise<string | null> {\n try {\n const data = await this.queryWorkspaceLayer<WorkspaceOrgQueryData>(\n GET_WORKSPACE_ORG_QUERY,\n { workspaceId },\n workspaceId\n );\n return data.workspace?.orgId ?? null;\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to resolve workspace org`, {\n workspaceId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n /**\n * Resolve the default billing account for an organization via the global\n * layer. Fails open (`null`).\n */\n async getDefaultBillingAccountId(orgId: string): Promise<string | null> {\n try {\n const data = await this.queryGlobalLayer<BillingAccountQueryData>(GET_DEFAULT_BILLING_ACCOUNT_QUERY, {\n orgId,\n });\n return data.getDefaultBillingAccountByOrgId?.id ?? null;\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to resolve default billing account`, {\n orgId,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n /**\n * Check that an organization still has quota headroom for `value` units of\n * `quotaName`. Returns `false` when no billing account exists or the quota\n * is exhausted; rethrows nothing — transport errors propagate to the caller\n * of this low-level variant (the workspace variant fails open instead).\n */\n async ensureQuotaAvailableForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for org quota check`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const amount = input.value ?? 1;\n const data = await this.queryGlobalLayer<QuotaCheckQueryData>(CHECK_QUOTA_QUERY, {\n billingAccountId,\n quotaName: input.quotaName,\n productId: input.productId,\n });\n\n const result = data.checkQuotaExhausted;\n if (!result) {\n return false;\n }\n\n if (result.noLimit) {\n return true;\n }\n\n return result.limitLeft >= amount;\n }\n\n /**\n * Workspace-addressed quota gate: resolves the org, then applies\n * {@link ensureQuotaAvailableForOrg}. Fails OPEN (`true`) when org\n * resolution fails (unbilled / dev / internal workspaces) so local-stack\n * test workspaces and workspaces with a transiently broken tenant lookup\n * are never locked out; real limits only kick in when the workspace has a\n * billable org.\n */\n async ensureQuotaAvailableForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available; allowing quota op (fail-open)`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return true;\n }\n\n return this.ensureQuotaAvailableForOrg({ ...input, orgId });\n }\n\n /**\n * Record usage against an organization's billing account. No-ops (`false`)\n * when there is no billing account.\n */\n async addUsageForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for addUsage`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const data = await this.queryGlobalLayer<UsageMutationData>(ADD_USAGE_MUTATION, {\n billingAccountId,\n quotaName: input.quotaName,\n value: input.value ?? 1,\n description: input.description,\n tags: input.tags,\n hash: input.hash,\n userId: input.userId,\n productId: input.productId,\n });\n\n return data.addUsage ?? false;\n }\n\n /**\n * Workspace-addressed {@link addUsageForOrg}. No-ops (`false`) when the\n * workspace has no org.\n */\n async addUsageForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available for workspace addUsage`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n return this.addUsageForOrg({ ...input, orgId });\n }\n\n /**\n * Credit usage back to an organization's billing account. No-ops (`false`)\n * when there is no billing account.\n */\n async freeUpUsageForOrg(input: OrgBillingUsageOperationInput): Promise<boolean> {\n const billingAccountId = await this.getDefaultBillingAccountId(input.orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account available for freeUpUsage`, {\n orgId: input.orgId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n const data = await this.queryGlobalLayer<UsageMutationData>(FREE_UP_USAGE_MUTATION, {\n billingAccountId,\n quotaName: input.quotaName,\n value: input.value ?? 1,\n description: input.description,\n tags: input.tags,\n hash: input.hash,\n userId: input.userId,\n productId: input.productId,\n });\n\n return data.freeUpUsage ?? false;\n }\n\n /**\n * Workspace-addressed {@link freeUpUsageForOrg}. No-ops (`false`) when the\n * workspace has no org.\n */\n async freeUpUsageForWorkspace(input: WorkspaceBillingUsageOperationInput): Promise<boolean> {\n const orgId = await this.getOrgIdFromWorkspace(input.workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No organization available for workspace freeUpUsage`, {\n workspaceId: input.workspaceId,\n quotaName: input.quotaName,\n });\n return false;\n }\n\n return this.freeUpUsageForOrg({ ...input, orgId });\n }\n\n /**\n * Fetch the plan limit for a quota from billing-svc, bypassing billing's\n * internal usage counter (the caller's own DB is the source of truth for\n * current usage; billing only stores the plan maximum). Results are cached\n * in-process per workspace/quota/product. Fails open (`null`) when billing\n * is unreachable so dev/test workspaces without billing accounts are never\n * blocked.\n */\n async getQuotaLimitForWorkspace(\n workspaceId: string,\n quotaName: string,\n productId: string\n ): Promise<QuotaLimit | null> {\n const cacheKey = `${workspaceId}:${quotaName}:${productId}`;\n const cached = this.quotaLimitCache.get(cacheKey);\n if (cached && cached.expiresAt > Date.now()) {\n return { limit: cached.limit, noLimit: cached.noLimit };\n }\n\n const orgId = await this.getOrgIdFromWorkspace(workspaceId);\n if (!orgId) {\n logger.warn(`${this.logPrefix} No org found for quota limit lookup; failing open`, {\n workspaceId,\n quotaName,\n });\n return null;\n }\n\n const billingAccountId = await this.getDefaultBillingAccountId(orgId);\n if (!billingAccountId) {\n logger.warn(`${this.logPrefix} No billing account found for quota limit lookup; failing open`, {\n workspaceId,\n quotaName,\n });\n return null;\n }\n\n try {\n const data = await this.queryGlobalLayer<QuotaLimitQueryData>(GET_QUOTA_LIMIT_QUERY, {\n billingAccountId,\n quotaName,\n productId,\n });\n\n const result = data.getQuotaUsageAndLimit;\n if (!result) {\n return null;\n }\n\n this.rememberQuotaLimit(cacheKey, { limit: result.limit, noLimit: result.noLimit });\n return { limit: result.limit, noLimit: result.noLimit };\n } catch (error) {\n logger.warn(`${this.logPrefix} Failed to fetch quota limit; failing open`, {\n workspaceId,\n quotaName,\n error: error instanceof Error ? error.message : String(error),\n });\n return null;\n }\n }\n\n private rememberQuotaLimit(cacheKey: string, value: QuotaLimit): void {\n if (this.quotaLimitCache.size >= QUOTA_LIMIT_CACHE_MAX_ENTRIES) {\n const now = Date.now();\n for (const [key, entry] of this.quotaLimitCache) {\n if (entry.expiresAt <= now) this.quotaLimitCache.delete(key);\n }\n // Still full after pruning (all entries fresh): drop the oldest-inserted\n // entries rather than refusing to cache. Plan limits are re-fetchable.\n if (this.quotaLimitCache.size >= QUOTA_LIMIT_CACHE_MAX_ENTRIES) {\n const overflow = this.quotaLimitCache.size - QUOTA_LIMIT_CACHE_MAX_ENTRIES + 1;\n let removed = 0;\n for (const key of this.quotaLimitCache.keys()) {\n this.quotaLimitCache.delete(key);\n removed += 1;\n if (removed >= overflow) break;\n }\n }\n }\n this.quotaLimitCache.set(cacheKey, { ...value, expiresAt: Date.now() + this.quotaLimitCacheTtlMs });\n }\n}\n","/**\n * Usage & Quota Module\n *\n * Checks and records workspace quota usage against the workspace usage owner\n * (wspace-activity-svc). The owner's published contract is:\n *\n * - `checkWorkspaceQuota(workspaceId, quotaName, amount): WorkspaceQuotaCheckResult!`\n * - `trackUsage(input: TrackUsageInput!): Boolean!`\n *\n * Quotas are keyed by `quotaName` (for example `platform.projects.created`), not by the\n * `entityId`/`entityType`/`metricType` triple this module used to send. That triple was\n * never part of the owner's schema, so every legacy call failed GraphQL validation\n * (BOFF-10955). The legacy methods remain for source compatibility and fail with\n * {@link UsageOperationUnsupportedError} before any network call.\n */\n\nimport { randomUUID } from 'node:crypto';\nimport type { BurdenoffGraphQLClient } from '../client/graphql.js';\nimport type { SDKContext } from '../types/index.js';\nimport { SDKError, ValidationError, QuotaExceededError } from '../types/index.js';\nimport { logger } from '../logger/index.js';\n\n/**\n * Legacy usage metric names. The workspace usage owner has no metric types; quotas are\n * addressed by `quotaName`. Kept so existing `sdk.tracker.track({ usage: { metricType } })`\n * call sites keep compiling; the tracker does not meter a metric type on its own.\n */\nexport enum UsageMetricType {\n API_CALLS = 'api_calls',\n STORAGE = 'storage',\n BANDWIDTH = 'bandwidth',\n USERS = 'users',\n PROJECTS = 'projects',\n WORKSPACES = 'workspaces',\n RECORDS = 'records',\n COMPUTE_TIME = 'compute_time',\n TRANSACTIONS = 'transactions',\n CUSTOM = 'custom',\n}\n\nexport enum QuotaPeriod {\n DAILY = 'daily',\n WEEKLY = 'weekly',\n MONTHLY = 'monthly',\n YEARLY = 'yearly',\n LIFETIME = 'lifetime',\n}\n\n/**\n * Entity type for usage tracking\n */\nexport type UsageEntityType = 'user' | 'workspace' | 'organization';\n\nexport interface TrackUsageOptions {\n /** User or workspace consuming the resource */\n entityId: string;\n /** Type of entity (user or workspace) */\n entityType: UsageEntityType;\n /** Metric type */\n metricType: UsageMetricType;\n /** Amount to increment */\n amount: number;\n /** Optional resource identifier */\n resourceId?: string;\n /** Optional metadata */\n metadata?: Record<string, unknown>;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n}\n\nexport interface CheckQuotaOptions {\n /** Entity to check quota for */\n entityId: string;\n /** Type of entity */\n entityType: UsageEntityType;\n /** Metric type */\n metricType: UsageMetricType;\n /** Amount to check availability for */\n requestedAmount: number;\n /** Workspace context */\n workspaceId?: string;\n /** Organization context */\n organizationId?: string;\n}\n\nexport interface QuotaCheckResult {\n allowed: boolean;\n currentUsage: number;\n quotaLimit: number;\n remainingQuota: number;\n resetAt?: string;\n period: QuotaPeriod;\n reason?: string;\n}\n\nexport interface UsageRecord {\n id: string;\n entityId: string;\n entityType: UsageEntityType;\n metricType: UsageMetricType;\n amount: number;\n resourceId?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n organizationId?: string;\n recordedAt: string;\n}\n\nexport interface UsageSummary {\n entityId: string;\n entityType: string;\n metricType: UsageMetricType;\n totalUsage: number;\n period: QuotaPeriod;\n periodStart: string;\n periodEnd: string;\n quotaLimit?: number;\n utilizationPercentage?: number;\n}\n\nexport interface SetQuotaOptions {\n entityId: string;\n entityType: UsageEntityType;\n metricType: UsageMetricType;\n limit: number;\n period: QuotaPeriod;\n workspaceId?: string;\n organizationId?: string;\n}\n\nexport interface Quota {\n id: string;\n entityId: string;\n entityType: string;\n metricType: UsageMetricType;\n limit: number;\n period: QuotaPeriod;\n currentUsage: number;\n resetAt: string;\n createdAt: string;\n updatedAt: string;\n}\n\nexport interface GetUsageOptions {\n entityId: string;\n entityType: UsageEntityType;\n metricType?: UsageMetricType;\n startDate?: string;\n endDate?: string;\n workspaceId?: string;\n organizationId?: string;\n limit?: number;\n offset?: number;\n}\n\n/** Thrown by SDK usage operations the workspace usage owner does not expose. */\nexport class UsageOperationUnsupportedError extends SDKError {\n constructor(operation: string, guidance: string) {\n super(\n `UsageModule.${operation} is not supported by the workspace usage owner: ${guidance}`,\n 'USAGE_OPERATION_UNSUPPORTED',\n { operation }\n );\n this.name = 'UsageOperationUnsupportedError';\n Object.setPrototypeOf(this, UsageOperationUnsupportedError.prototype);\n }\n}\n\n/**\n * Query sent to the owner's `checkWorkspaceQuota`. Every argument and selected field must\n * exist on the published wspace schema (see tests/usage-module.test.ts).\n */\nexport const CHECK_WORKSPACE_QUOTA_QUERY = `\n query CheckWorkspaceQuota($workspaceId: ID!, $quotaName: String!, $amount: Float) {\n checkWorkspaceQuota(workspaceId: $workspaceId, quotaName: $quotaName, amount: $amount) {\n allowed\n assignmentId\n limitLeft\n noLimit\n }\n }\n`;\n\n/** Mutation sent to the owner's `trackUsage`, which returns `Boolean!`. */\nexport const TRACK_USAGE_MUTATION = `\n mutation TrackUsage($input: TrackUsageInput!) {\n trackUsage(input: $input)\n }\n`;\n\nexport interface CheckWorkspaceQuotaOptions {\n /** Quota to check, for example `platform.projects.created`. */\n quotaName: string;\n /** Amount the caller is about to consume. Must be positive; defaults to 1. */\n amount?: number;\n /** Workspace that owns the quota. Defaults to the SDK context's workspace. */\n workspaceId?: string;\n /** End user the check is made for. Defaults to the SDK context's actor. */\n userId?: string;\n}\n\n/** The owner's `WorkspaceQuotaCheckResult`. */\nexport interface WorkspaceQuotaCheckResult {\n /** True when the quota has enough remaining capacity for the requested amount. */\n allowed: boolean;\n /** Active assignment to charge, or null when the workspace's plan does not include the quota. */\n assignmentId: string | null;\n /** Remaining capacity after the requested amount; null when unlimited or not provisioned. */\n limitLeft: number | null;\n /** True when the quota is unlimited. */\n noLimit: boolean;\n}\n\nexport interface TrackWorkspaceUsageOptions {\n /** Quota to charge, for example `platform.projects.created`. */\n quotaName: string;\n /** Product the quota belongs to, for example `platform`. Defaults to the SDK context's product. */\n productId?: string;\n /**\n * Amount to record. A positive amount consumes quota; a negative amount releases it (for\n * example on delete). The owner only accepts negative amounts from services and super\n * admins, which is how this module relays the call. Zero is rejected.\n */\n amount: number;\n /** Human-readable reason stored on the usage record. */\n description: string;\n /** Workspace to charge. Defaults to the SDK context's workspace. */\n workspaceId?: string;\n /** End user the usage is recorded for. Defaults to the SDK context's actor. */\n userId?: string;\n /** Assignment returned by {@link UsageModule.checkWorkspaceQuota}; saves the owner a lookup. */\n quotaAssignmentId?: string;\n /** Billing account reference stored on the record. Omit for workspace quotas. */\n billingAccountId?: string;\n /**\n * Idempotency key. The owner records one charge per hash and workspace, so a retried\n * request cannot charge twice. A random key is generated per call when omitted.\n */\n hash?: string;\n /** Additional metadata stored on the usage record. */\n metadata?: Record<string, unknown>;\n}\n\nfunction legacyGuidance(replacement: string): string {\n return `quotas are addressed by quotaName on the workspace usage owner; use ${replacement}`;\n}\n\nfunction nonEmpty(value: string | undefined): string | undefined {\n const trimmed = value?.trim();\n return trimmed ? trimmed : undefined;\n}\n\n/**\n * Builds the owner's `TrackUsageInput` from SDK options, filling defaults from the context.\n * Throws {@link ValidationError} for input the owner would refuse.\n */\nexport function buildTrackUsageInput(\n options: TrackWorkspaceUsageOptions,\n context: SDKContext = {}\n): Record<string, unknown> {\n const quotaName = nonEmpty(options.quotaName);\n if (!quotaName) {\n throw new ValidationError('Quota name is required');\n }\n const productId = nonEmpty(options.productId) ?? nonEmpty(context.productId);\n if (!productId) {\n throw new ValidationError('Product ID is required');\n }\n const description = nonEmpty(options.description);\n if (!description) {\n throw new ValidationError('Description is required');\n }\n if (typeof options.amount !== 'number' || !Number.isFinite(options.amount) || options.amount === 0) {\n throw new ValidationError('Amount must be a finite, non-zero number');\n }\n const workspaceId = nonEmpty(options.workspaceId) ?? nonEmpty(context.workspaceId);\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required');\n }\n\n const input: Record<string, unknown> = {\n quotaName,\n productId,\n amount: options.amount,\n description,\n workspaceId,\n hash: nonEmpty(options.hash) ?? `sdk-usage:${randomUUID()}`,\n };\n const userId = nonEmpty(options.userId) ?? nonEmpty(context.actorId);\n if (userId) input['userId'] = userId;\n if (options.quotaAssignmentId) input['quotaAssignmentId'] = options.quotaAssignmentId;\n if (options.billingAccountId) input['billingAccountId'] = options.billingAccountId;\n if (options.metadata) input['metadata'] = options.metadata;\n return input;\n}\n\n/**\n * Usage & Quota Module\n */\nexport class UsageModule {\n constructor(\n private client: BurdenoffGraphQLClient,\n private context: SDKContext\n ) {}\n\n /**\n * Context for one owner call: relayed as a platform service acting for `userId`, with the\n * quota's workspace in scope. The owner takes the workspace from this context, never from\n * the input, and only lets services release (decrement) usage.\n */\n private requestContext(workspaceId: string, userId: string | undefined): SDKContext {\n const actorId = userId ?? this.context.actorId;\n return {\n ...this.context,\n ...(actorId ? { actorId } : {}),\n actorType: 'service',\n workspaceId,\n };\n }\n\n /**\n * Check whether a workspace quota has capacity for `amount` (default 1).\n */\n public async checkWorkspaceQuota(options: CheckWorkspaceQuotaOptions): Promise<WorkspaceQuotaCheckResult> {\n const quotaName = nonEmpty(options.quotaName);\n if (!quotaName) {\n throw new ValidationError('Quota name is required');\n }\n const amount = options.amount ?? 1;\n if (typeof amount !== 'number' || !Number.isFinite(amount) || amount <= 0) {\n throw new ValidationError('Quota checks need a positive amount');\n }\n const workspaceId = nonEmpty(options.workspaceId) ?? nonEmpty(this.context.workspaceId);\n if (!workspaceId) {\n throw new ValidationError('Workspace ID is required');\n }\n\n logger.debug('[Usage] Checking workspace quota', { workspaceId, quotaName, amount });\n\n const response = await this.client.query<{ checkWorkspaceQuota: WorkspaceQuotaCheckResult }>(\n CHECK_WORKSPACE_QUOTA_QUERY,\n { workspaceId, quotaName, amount },\n this.requestContext(workspaceId, nonEmpty(options.userId))\n );\n\n const result = response.checkWorkspaceQuota;\n logger.debug('[Usage] Workspace quota check result', { workspaceId, quotaName, allowed: result.allowed });\n return result;\n }\n\n /**\n * Check a workspace quota and throw {@link QuotaExceededError} when it has no capacity.\n * Returns the check result so the caller can pass `assignmentId` to {@link trackUsage}.\n */\n public async requireWorkspaceQuota(options: CheckWorkspaceQuotaOptions): Promise<WorkspaceQuotaCheckResult> {\n const result = await this.checkWorkspaceQuota(options);\n if (!result.allowed) {\n const notProvisioned = result.assignmentId === null;\n throw new QuotaExceededError(\n notProvisioned ? `Quota ${options.quotaName} is not included in this workspace's plan` : 'Quota exceeded',\n {\n quotaName: options.quotaName,\n requestedAmount: options.amount ?? 1,\n limitLeft: result.limitLeft,\n notProvisioned,\n }\n );\n }\n return result;\n }\n\n /**\n * Record workspace quota usage. A negative amount releases previously recorded usage.\n * Resolves to `true` once the owner has stored (or deduplicated) the record.\n */\n public async trackUsage(options: TrackWorkspaceUsageOptions): Promise<boolean> {\n const input = buildTrackUsageInput(options, this.context);\n const workspaceId = input['workspaceId'] as string;\n\n logger.debug('[Usage] Tracking workspace usage', {\n workspaceId,\n quotaName: input['quotaName'],\n amount: input['amount'],\n });\n\n const response = await this.client.query<{ trackUsage: boolean }>(\n TRACK_USAGE_MUTATION,\n { input },\n this.requestContext(workspaceId, nonEmpty(options.userId))\n );\n\n logger.info('[Usage] Workspace usage tracked', { workspaceId, quotaName: input['quotaName'] });\n return response.trackUsage;\n }\n\n /**\n * @deprecated The workspace usage owner has no `trackUsage` record shape keyed by\n * `entityId`/`metricType`. Use {@link trackUsage} with a `quotaName`.\n */\n public async track(_options: TrackUsageOptions): Promise<UsageRecord> {\n throw new UsageOperationUnsupportedError('track', legacyGuidance('trackUsage({ quotaName, productId, amount })'));\n }\n\n /**\n * @deprecated The owner has no `checkQuota` operation. Use {@link checkWorkspaceQuota}.\n */\n public async checkQuota(_options: CheckQuotaOptions): Promise<QuotaCheckResult> {\n throw new UsageOperationUnsupportedError(\n 'checkQuota',\n legacyGuidance('checkWorkspaceQuota({ quotaName, amount })')\n );\n }\n\n /**\n * @deprecated The owner has no `checkQuota` operation. Use {@link requireWorkspaceQuota}.\n */\n public async requireQuota(_options: CheckQuotaOptions): Promise<void> {\n throw new UsageOperationUnsupportedError(\n 'requireQuota',\n legacyGuidance('requireWorkspaceQuota({ quotaName, amount })')\n );\n }\n\n /**\n * @deprecated Use {@link requireWorkspaceQuota} followed by {@link trackUsage}.\n */\n public async trackAndCheck(_options: TrackUsageOptions): Promise<{\n usage: UsageRecord;\n quotaCheck: QuotaCheckResult;\n }> {\n throw new UsageOperationUnsupportedError(\n 'trackAndCheck',\n legacyGuidance('requireWorkspaceQuota() and then trackUsage()')\n );\n }\n\n /**\n * @deprecated The owner has no `getUsage` operation; read records with the owner's\n * `getUsageRecords(filters, pagination)`.\n */\n public async getUsage(_options: GetUsageOptions): Promise<{\n records: UsageRecord[];\n total: number;\n }> {\n throw new UsageOperationUnsupportedError('getUsage', legacyGuidance(\"the owner's getUsageRecords query\"));\n }\n\n /**\n * @deprecated The owner's `getUsageSummary` takes `UsageFilters` and returns a list; this\n * signature does not map onto it.\n */\n public async getSummary(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType,\n _period: QuotaPeriod\n ): Promise<UsageSummary> {\n throw new UsageOperationUnsupportedError(\n 'getSummary',\n legacyGuidance(\"the owner's getUsageSummary(filters) query\")\n );\n }\n\n /**\n * @deprecated Quota limits are assigned by global-billing-svc through the owner's\n * `assignWorkspaceQuota`, which only billing's service identity may call.\n */\n public async setQuota(_options: SetQuotaOptions): Promise<Quota> {\n throw new UsageOperationUnsupportedError('setQuota', 'quota limits are assigned by global-billing-svc');\n }\n\n /**\n * @deprecated The owner has no `getQuota` operation; read `workspaceQuotaStatuses(workspaceId)`.\n */\n public async getQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<Quota | null> {\n throw new UsageOperationUnsupportedError('getQuota', legacyGuidance(\"the owner's workspaceQuotaStatuses query\"));\n }\n\n /**\n * @deprecated The owner has no `getQuotas` operation; read `workspaceQuotaAssignments(workspaceId)`.\n */\n public async getQuotas(_entityId: string, _entityType: UsageEntityType): Promise<Quota[]> {\n throw new UsageOperationUnsupportedError(\n 'getQuotas',\n legacyGuidance(\"the owner's workspaceQuotaAssignments query\")\n );\n }\n\n /**\n * @deprecated The owner has no `resetQuota` operation; quotas reset on their `resetPeriod`.\n */\n public async resetQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<boolean> {\n throw new UsageOperationUnsupportedError('resetQuota', \"quotas reset on the assignment's resetPeriod\");\n }\n\n /**\n * @deprecated The owner has no `deleteQuota` operation; billing deactivates assignments.\n */\n public async deleteQuota(\n _entityId: string,\n _entityType: UsageEntityType,\n _metricType: UsageMetricType\n ): Promise<boolean> {\n throw new UsageOperationUnsupportedError('deleteQuota', 'quota assignments are deactivated by global-billing-svc');\n }\n\n /**\n * @deprecated The owner has no `trackUsageBulk` operation. Call {@link trackUsage} per record.\n */\n public async trackBulk(_records: TrackUsageOptions[]): Promise<UsageRecord[]> {\n throw new UsageOperationUnsupportedError('trackBulk', legacyGuidance('trackUsage() per record'));\n }\n}\n\nexport {\n BillingUsageClient,\n type BillingUsageClientConfig,\n type BillingUsageOperationInput,\n type OrgBillingUsageOperationInput,\n type WorkspaceBillingUsageOperationInput,\n type QuotaLimit,\n} from './billing.js';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkCA,MAAM,6BAA6B;;AAGnC,MAAM,mCAAmC;;AAGzC,MAAM,gCAAgC;AAEtC,MAAM,0BAA0B;;;;;;;AAQhC,MAAM,oCAAoC;;;;;;;AAQ1C,MAAM,oBAAoB;;;;;;;;;;;;;AAc1B,MAAM,qBAAqB;;;;;;;;;;;;;;;;;;;;;;;AAwB3B,MAAM,wBAAwB;;;;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Y,eAAe,mCAAmC,CAAC;CAC1G;;;;;CAMA,MAAa,WACX,WACA,aACA,aACA,SACuB;EACvB,MAAM,IAAI,+BACR,cACA,eAAe,4CAA4C,CAC7D;CACF;;;;;CAMA,MAAa,SAAS,UAA2C;EAC/D,MAAM,IAAI,+BAA+B,YAAY,iDAAiD;CACxG;;;;CAKA,MAAa,SACX,WACA,aACA,aACuB;EACvB,MAAM,IAAI,+BAA+B,YAAY,eAAe,0CAA0C,CAAC;CACjH;;;;CAKA,MAAa,UAAU,WAAmB,aAAgD;EACxF,MAAM,IAAI,+BACR,aACA,eAAe,6CAA6C,CAC9D;CACF;;;;CAKA,MAAa,WACX,WACA,aACA,aACkB;EAClB,MAAM,IAAI,+BAA+B,cAAc,8CAA8C;CACvG;;;;CAKA,MAAa,YACX,WACA,aACA,aACkB;EAClB,MAAM,IAAI,+BAA+B,eAAe,yDAAyD;CACnH;;;;CAKA,MAAa,UAAU,UAAuD;EAC5E,MAAM,IAAI,+BAA+B,aAAa,eAAe,yBAAyB,CAAC;CACjG;AACF"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@burdenoff/be-sdk",
|
|
3
|
-
"version": "2026.1123.
|
|
3
|
+
"version": "2026.1123.6",
|
|
4
4
|
"description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|