@burdenoff/be-sdk 2026.1202.1 → 2026.1202.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -9,7 +9,7 @@ import { c as tenant_notifications_exports, r as NotificationsModule, s as Tenan
9
9
  import { c as createRBACDirectiveFromEnv, o as createRBACDirective, s as createRBACDirectiveForLayer, t as RBACModule } from "./rbac-pRCcWVS_.js";
10
10
  import { ActivityModule, ActivityOperationUnsupportedError } from "./activity/index.js";
11
11
  import { a as UsageModule, c as BillingUsageClient } from "./usage-BK7eyP42.js";
12
- import { t as TrackerModule } from "./tracker-DnIlQldQ.js";
12
+ import { t as TrackerModule } from "./tracker-Cb58dqj9.js";
13
13
  import { DatabaseModule } from "./database/index.js";
14
14
  import { j as EventsModule, t as event_queue_exports } from "./event-queue-ANzylLK1.js";
15
15
  import { a as unregisterDisposable, i as registerDisposable, n as disposeAll, r as getRegisteredDisposableCount, t as lifecycle_exports } from "./lifecycle-DeoLSX0U.js";
@@ -1,6 +1,6 @@
1
1
  import { t as __exportAll } from "../rolldown-runtime-ad2WFvuA.js";
2
2
  import { a as logger } from "../logger-B6rCpb7D.js";
3
- import { c as ACTOR_ORIGIN_HEADER, d as ASSISTANT_SESSION_ID_HEADER, f as parseAssistantSessionHeaders, l as AI_ASSISTANT_ACTOR_ORIGIN, m as toAssistantSessionAttribution, o as trackOperation, p as readAssistantSessionAttribution, u as ASSISTANT_CORRELATION_ID_HEADER } from "../stub-BkPAoXnP.js";
3
+ import { c as ACTOR_ORIGIN_HEADER, d as ASSISTANT_SESSION_ID_HEADER, f as parseAssistantSessionHeaders, l as AI_ASSISTANT_ACTOR_ORIGIN, m as toAssistantSessionAttribution, o as trackOperation, p as readAssistantSessionAttribution, u as ASSISTANT_CORRELATION_ID_HEADER } from "../stub-D0g4EsW4.js";
4
4
  import { w as withWorkspaceContext, x as setWorkspaceContext } from "../workspace-extension-feJYFO9e.js";
5
5
  import { l as I18n } from "../i18n-BBMYFd0P.js";
6
6
  import { l as getMetricsRegistry } from "../metrics-collector-DXQrMUle.js";
@@ -342,6 +342,16 @@ function classifyGraphQLErrors(errors) {
342
342
  detail
343
343
  };
344
344
  }
345
+ /**
346
+ * Detail for a non-2xx answer. A gateway can answer a refused GraphQL write with HTTP 400 and the
347
+ * subgraph's `errors` array (BOFF-17562: "Activity ... has no workspace"); log those messages next
348
+ * to the status so the caller sees why, instead of a bare status. The classification stays by status.
349
+ */
350
+ async function httpFailureDetail(response) {
351
+ const status = `HTTP ${response.status}`;
352
+ const messages = (await response.json().catch(() => void 0))?.errors?.map((error) => error?.message).filter((message) => typeof message === "string" && message.length > 0);
353
+ return messages && messages.length > 0 ? `${status}: ${messages.join("; ")}`.slice(0, 500) : status;
354
+ }
345
355
  async function attemptActivityDelivery(gatewayUrl, headers, body) {
346
356
  try {
347
357
  const response = await fetch(gatewayUrl, {
@@ -351,7 +361,7 @@ async function attemptActivityDelivery(gatewayUrl, headers, body) {
351
361
  signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS)
352
362
  });
353
363
  if (!response.ok) {
354
- const detail = `HTTP ${response.status}`;
364
+ const detail = await httpFailureDetail(response);
355
365
  return RETRYABLE_HTTP_STATUSES.has(response.status) ? {
356
366
  kind: "transient",
357
367
  detail
@@ -632,4 +642,4 @@ const UNIFIED_TRACKER_CONSTANTS = {
632
642
  };
633
643
 
634
644
  export { resolveAssistantSession as a, ACTOR_ORIGIN_HEADER as c, ASSISTANT_SESSION_ID_HEADER as d, parseAssistantSessionHeaders as f, isTrackedActorType as i, AI_ASSISTANT_ACTOR_ORIGIN as l, toAssistantSessionAttribution as m, UnifiedTrackerStub as n, trackOperation as o, readAssistantSessionAttribution as p, createProductTracker as r, trackerStub as s, UNIFIED_TRACKER_CONSTANTS as t, ASSISTANT_CORRELATION_ID_HEADER as u };
635
- //# sourceMappingURL=stub-BkPAoXnP.js.map
645
+ //# sourceMappingURL=stub-D0g4EsW4.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stub-D0g4EsW4.js","names":[],"sources":["../src/activity/assistant-session.ts","../src/tracker/stub.ts"],"sourcesContent":["/**\n * Assistant-session attribution (BOFF-9649)\n *\n * When an AI assistant session runs a GraphQL mutation for its owner, the\n * assistant session relay (wspace-sandbox-svc) forwards it to a public gateway\n * as the owner, with a signed assistant-session marker. The gateway verifies\n * that marker against the owner's verified token, strips any copy a client\n * sent, and passes the result to subgraphs as three headers:\n *\n * x-actor-origin: ai_assistant\n * x-assistant-session-id: <the relay session id (the assistant sandbox id)>\n * x-assistant-correlation-id: <the proposal / idempotency key, when there is one>\n *\n * A service never verifies these itself. `buildContext` reads them only when it\n * already trusts the gateway's actor headers, exposes them as\n * `context.assistantSession`, and binds them to the operation's workspace\n * context so `trackOperation` can stamp every activity row written while the\n * operation runs, without each service re-implementing audit.\n *\n * Values outside the vocabulary or the id pattern are dropped, never coerced:\n * a wrong attribution is worse than none.\n */\n\n/** The only actor origin the platform records today. */\nexport const AI_ASSISTANT_ACTOR_ORIGIN = 'ai_assistant';\n\nexport type ActorOrigin = typeof AI_ASSISTANT_ACTOR_ORIGIN;\n\n/** Gateway-to-subgraph headers. Clients cannot set them: the public gateways strip them. */\nexport const ACTOR_ORIGIN_HEADER = 'x-actor-origin';\nexport const ASSISTANT_SESSION_ID_HEADER = 'x-assistant-session-id';\nexport const ASSISTANT_CORRELATION_ID_HEADER = 'x-assistant-correlation-id';\n\n/** Session ids (UUIDs, cuid-style ids) and proposal / idempotency keys. */\nconst ATTRIBUTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The assistant session an operation ran under. */\nexport interface AssistantSessionAttribution {\n actorOrigin: ActorOrigin;\n /** The relay session id: the assistant sandbox that ran the mutation. */\n assistantSessionId: string;\n /** The proposal / idempotency key the mutation ran under, when it had one. */\n assistantCorrelationId?: string;\n}\n\nfunction attributionId(value: unknown): string | undefined {\n return typeof value === 'string' && ATTRIBUTION_ID_PATTERN.test(value) ? value : undefined;\n}\n\n/**\n * Build an attribution from raw values. Undefined unless the origin is\n * `ai_assistant` and the session id is well formed; a malformed correlation id\n * is dropped on its own.\n */\nexport function toAssistantSessionAttribution(\n actorOrigin: unknown,\n assistantSessionId: unknown,\n assistantCorrelationId?: unknown\n): AssistantSessionAttribution | undefined {\n if (actorOrigin !== AI_ASSISTANT_ACTOR_ORIGIN) return undefined;\n const sessionId = attributionId(assistantSessionId);\n if (!sessionId) return undefined;\n const correlationId = attributionId(assistantCorrelationId);\n return {\n actorOrigin: AI_ASSISTANT_ACTOR_ORIGIN,\n assistantSessionId: sessionId,\n ...(correlationId ? { assistantCorrelationId: correlationId } : {}),\n };\n}\n\n/**\n * Read the gateway's assistant-session headers. The caller decides whether the\n * request's gateway headers are trusted at all; this only parses them.\n */\nexport function parseAssistantSessionHeaders(\n getHeader: (name: string) => string | null | undefined\n): AssistantSessionAttribution | undefined {\n return toAssistantSessionAttribution(\n getHeader(ACTOR_ORIGIN_HEADER),\n getHeader(ASSISTANT_SESSION_ID_HEADER),\n getHeader(ASSISTANT_CORRELATION_ID_HEADER)\n );\n}\n\n/** Re-validate an attribution-shaped value (from a request context or caller options). */\nexport function readAssistantSessionAttribution(value: unknown): AssistantSessionAttribution | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n return toAssistantSessionAttribution(\n record['actorOrigin'],\n record['assistantSessionId'],\n record['assistantCorrelationId']\n );\n}\n","/**\n * Unified Tracking — Auto-Promoting Implementation\n *\n * Automatically promotes from stub to real tracking when gateway URLs are configured.\n * When WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL is set, this module will:\n * - Log activity events via GraphQL to the activity service\n * - Track usage via GraphQL to the usage service (if usage options provided)\n * - RBAC checks are NOT performed here (handled by gateway @rbac directives)\n *\n * When no gateway URL is configured, falls back to debug-level logging (stub mode).\n *\n * This is a backward-compatible drop-in replacement for the original stub. All 1,100+\n * existing call sites continue to work without modification.\n *\n * @module tracker/stub\n * @category Tracking\n */\nimport { randomUUID } from 'node:crypto';\n\nimport { logger } from '../logger/index.js';\nimport { markExplicitActivity } from '../activity/explicit-activity-scope.js';\nimport { readAssistantSessionAttribution, type AssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { getScopedWorkspaceContext, getWorkspaceContext } from '../prisma/workspace-extension.js';\nimport { signServiceJwt } from '../gateway/service-jwt.js';\n\n/**\n * Tracking event interface\n */\nexport interface TrackingEvent {\n eventType: string;\n entityType: string;\n entityId: string;\n userId?: string;\n workspaceId?: string;\n metadata?: Record<string, unknown>;\n timestamp?: Date;\n}\n\n/**\n * RBAC check options\n */\nexport interface RbacCheckOptions {\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n skipRbacCheck?: boolean;\n options?: {\n allowOwnerAccess?: boolean;\n allowWorkspaceAdmin?: boolean;\n scope?: string;\n };\n}\n\n/**\n * Usage tracking options\n */\nexport interface UsageTrackingOptions {\n billingAccountId?: string;\n addUsage?: boolean;\n description?: string;\n tags?: Record<string, unknown>;\n quotaName?: string;\n value?: number;\n}\n\n/**\n * Activity tracking options\n */\nexport interface ActivityTrackingOptions {\n activityType?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n teamId?: string;\n groupId?: string;\n projectId?: string;\n targetUserId?: string;\n resourceType?: string;\n resourceId?: string;\n enabled?: boolean;\n /**\n * Idempotency key forwarded to the activity owner's `RecordActivityInput.dedupeKey`.\n * When omitted, a unique key is generated per tracked operation so that delivery retries of the\n * SAME operation converge to exactly one activity row. Supply a stable key only when the caller\n * itself may replay the same logical event (backfill/import).\n */\n dedupeKey?: string;\n}\n\n/**\n * Kind of actor behind a tracked operation — the gateway `x-actor-type` vocabulary.\n *\n * An AI agent acting through a product service is an `app` actor; recording it lets the\n * activity owner tell agent actions apart from human ones (BOFF-9684).\n */\nexport type TrackedActorType = 'user' | 'app' | 'service' | 'super_admin';\n\nconst TRACKED_ACTOR_TYPES: ReadonlySet<string> = new Set<TrackedActorType>(['user', 'app', 'service', 'super_admin']);\n\nexport function isTrackedActorType(value: unknown): value is TrackedActorType {\n return typeof value === 'string' && TRACKED_ACTOR_TYPES.has(value);\n}\n\n/**\n * Unified tracking options\n */\nexport interface UnifiedTrackingOptions {\n operationName?: string;\n userId?: string;\n /**\n * Kind of actor `userId` identifies. When omitted it is taken from `context` (`actor.type` or\n * `actorType`) or, with no `context`, from the ambient be-sdk workspace context; a value outside\n * the vocabulary is dropped rather than sent. The activity owner honours it because the tracker\n * calls it as a relaying `service`.\n */\n actorType?: TrackedActorType;\n /**\n * The user on whose behalf `userId` acted — for an AI-agent action, the human who started the\n * run. When omitted it is taken from `context.onBehalfOf`; the activity owner otherwise records\n * the actor itself.\n */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation ran under (BOFF-9649). When omitted it is taken from\n * `context.assistantSession` or, failing that, from the operation's own async scope (never from\n * another request's). Sent to global-activity-svc as `actorOrigin` / `assistantSessionId` /\n * `assistantCorrelationId`.\n */\n assistantSession?: AssistantSessionAttribution;\n context?: unknown;\n rbacCheck?: RbacCheckOptions;\n activityOptions?: ActivityTrackingOptions;\n usageOptions?: UsageTrackingOptions & { enabled?: boolean };\n success?: boolean;\n errorMessage?: string;\n productId?: string;\n // Legacy properties for backward compatibility (can be at top level or in nested objects)\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n tenantId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway URL resolution — cached at module level for performance\n// ---------------------------------------------------------------------------\n\nlet _gatewayUrl: string | undefined;\nlet _gatewayLayer: ActivityLayer | undefined;\nlet _gatewayUrlResolved = false;\n\n/**\n * Which activity subgraph the resolved gateway fronts.\n *\n * The two canonical activity owners accept DIFFERENT `RecordActivityInput` shapes, so the\n * payload must be built per layer:\n * - `wspace` → wspace-activity-svc: requires `action`; carries workspace-scoped fields\n * (workspaceId/teamId/targetUserId/productId/success).\n * - `global` → global-activity-svc: requires `action` AND `resource`; carries tenant-scoped\n * fields (tenantId/actorId/ipAddress/userAgent).\n * Sending one layer's shape to the other fails GraphQL validation.\n */\nexport type ActivityLayer = 'wspace' | 'global';\n\n/**\n * The layer the running service belongs to, when its environment says so: `SERVICE_LAYER`, then a\n * `global-` / `wspace-` `SERVICE_NAME` prefix (the same rule the RBAC directive and the Temporal\n * client use). Undefined when neither says.\n */\nfunction declaredServiceLayer(): ActivityLayer | undefined {\n const layer = process.env['SERVICE_LAYER'];\n if (layer === 'global' || layer === 'wspace') return layer;\n const name = process.env['SERVICE_NAME'] ?? '';\n if (name.startsWith('global-')) return 'global';\n if (name.startsWith('wspace-')) return 'wspace';\n return undefined;\n}\n\n/**\n * Resolve the internal gateway URL from environment.\n *\n * Activity belongs to the service's OWN layer: workspace services record in wspace-activity-svc\n * through WSPACE_INT_GATEWAY_URL, global services in global-activity-svc through\n * GLOBAL_INT_GATEWAY_URL. Global services also hold WSPACE_INT_GATEWAY_URL for cross-layer\n * calls, so the URL that happens to be set is not a layer signal: the declared layer\n * (`SERVICE_LAYER` / `SERVICE_NAME`) decides, and only an undeclared service falls back to\n * \"workspace URL first\" (BOFF-9649 — every global service was sending its audit rows to the\n * workspace activity owner, which rejected them). Undefined (stub mode) when no URL is set.\n */\nfunction getGatewayUrl(): string | undefined {\n if (!_gatewayUrlResolved) {\n const wspaceUrl = process.env['WSPACE_INT_GATEWAY_URL'];\n const globalUrl = process.env['GLOBAL_INT_GATEWAY_URL'];\n const declared = declaredServiceLayer();\n\n // A declared global service uses its own owner; anything else keeps \"workspace URL first\".\n const useGlobal = Boolean(globalUrl) && (declared === 'global' || !wspaceUrl);\n if (useGlobal) {\n _gatewayUrl = globalUrl;\n _gatewayLayer = 'global';\n } else if (wspaceUrl) {\n _gatewayUrl = wspaceUrl;\n _gatewayLayer = 'wspace';\n } else {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n }\n if (declared && _gatewayLayer && declared !== _gatewayLayer) {\n logger.warn(\n `[trackOperation] ${declared} service has no ${declared === 'global' ? 'GLOBAL' : 'WSPACE'}_INT_GATEWAY_URL; activity goes to the ${_gatewayLayer} activity owner instead`\n );\n }\n _gatewayUrlResolved = true;\n\n if (_gatewayUrl) {\n logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);\n } else {\n logger.debug('[trackOperation] No gateway URL configured — running in stub mode');\n }\n }\n return _gatewayUrl;\n}\n\n/**\n * Resolve which activity layer the configured gateway fronts.\n * Always call `getGatewayUrl()` first — it performs the resolution.\n */\nfunction getGatewayLayer(): ActivityLayer {\n // Default to 'wspace': the overwhelming majority of services are workspace-layer, and a wspace\n // payload omits only optional global fields, so a mis-detection degrades rather than fails.\n return _gatewayLayer ?? 'wspace';\n}\n\n/**\n * Reset the cached gateway resolution. Test-only seam — module-level caching would otherwise make\n * per-layer behaviour untestable within a single process.\n */\nexport function __resetGatewayCacheForTests(): void {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n _gatewayUrlResolved = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fire-and-forget GraphQL helper\n// ---------------------------------------------------------------------------\n\nconst LOG_ACTIVITY_MUTATION = /* GraphQL */ `\n mutation RecordActivity($input: RecordActivityInput!) {\n recordActivity(input: $input) {\n id\n }\n }\n`;\n\n/**\n * Derive the `resource` value required by global-activity-svc.\n *\n * Prefers an explicit resourceType; otherwise falls back to the leading dotted segment of the\n * operation name (`auth.session.revoke` → `auth`), which matches the platform's\n * `<domain>.<resource>.<verb>` activity taxonomy. Never returns empty — `resource` is non-nullable\n * on global-activity-svc and an empty string would be silently useless in the audit trail.\n */\nfunction deriveResource(options: UnifiedTrackingOptions): string {\n const explicit = options.activityOptions?.resourceType ?? options.resourceType;\n if (explicit && explicit.trim().length > 0) return explicit;\n\n const op = options.operationName;\n if (op && op.trim().length > 0) {\n const [head] = op.split('.');\n if (head && head.trim().length > 0) return head;\n }\n return 'unknown';\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/**\n * Resolve the kind of actor behind a tracked operation. Exported for unit tests.\n *\n * Precedence: the explicit `actorType` option, then the request `context` the caller passed\n * (`actor.type`, then the flat `actorType`), then the ambient be-sdk workspace context. A request\n * context is authoritative once given: an unknown kind there yields undefined rather than falling\n * through to the ambient context, which could belong to a different request in the same async\n * chain. A wrong attribution is worse than none.\n */\nexport function resolveTrackedActorType(options: UnifiedTrackingOptions): TrackedActorType | undefined {\n if (options.actorType !== undefined) {\n return isTrackedActorType(options.actorType) ? options.actorType : undefined;\n }\n const context = readRecord(options.context);\n if (context) {\n const actor = readRecord(context['actor']);\n const fromContext = actor?.['type'] ?? context['actorType'];\n return isTrackedActorType(fromContext) ? fromContext : undefined;\n }\n const ambient = getWorkspaceContext()?.actorType;\n return isTrackedActorType(ambient) ? ambient : undefined;\n}\n\nfunction resolveOnBehalfOf(options: UnifiedTrackingOptions): string | undefined {\n if (options.onBehalfOf) return options.onBehalfOf;\n const fromContext = readRecord(options.context)?.['onBehalfOf'];\n return typeof fromContext === 'string' && fromContext.length > 0 ? fromContext : undefined;\n}\n\n/**\n * Resolve the assistant session behind a tracked operation (BOFF-9649). Exported for unit tests.\n *\n * Precedence: the explicit `assistantSession` option, then `context.assistantSession`, then the\n * workspace context bound to the operation's own async scope. The module-level fallback context is\n * never read: it belongs to whichever request built its context last, and tagging a human's row\n * as AI-originated (or the reverse) is worse than leaving it untagged.\n */\nexport function resolveAssistantSession(options: UnifiedTrackingOptions): AssistantSessionAttribution | undefined {\n if (options.assistantSession !== undefined) return readAssistantSessionAttribution(options.assistantSession);\n const fromContext = readAssistantSessionAttribution(readRecord(options.context)?.['assistantSession']);\n if (fromContext) return fromContext;\n return readAssistantSessionAttribution(getScopedWorkspaceContext()?.assistantSession);\n}\n\n/**\n * Input fields an older activity owner may not define yet: wspace-activity-svc before BOFF-9684\n * (`actorType`, `onBehalfOf`), global-activity-svc before BOFF-9649 (assistant-session fields).\n */\nconst ATTRIBUTION_FIELDS = [\n 'actorType',\n 'onBehalfOf',\n 'actorOrigin',\n 'assistantSessionId',\n 'assistantCorrelationId',\n] as const;\n\n/**\n * True when the activity owner rejected the write only because it predates the attribution\n * fields (`Field \"actorType\" is not defined by type \"RecordActivityInput\"`).\n */\nfunction isUnknownAttributionFieldRejection(detail: string): boolean {\n return ATTRIBUTION_FIELDS.some(\n (field) => detail.includes(`\"${field}\"`) && /not defined|unknown field|is not defined by type/i.test(detail)\n );\n}\n\n/**\n * Build the layer-appropriate `RecordActivityInput`.\n *\n * Exported for unit testing: the whole class of defect this guards against is a payload that is\n * structurally plausible but rejected by the owning subgraph, which — because delivery is\n * fire-and-forget — is invisible at runtime.\n */\nexport function buildActivityInput(options: UnifiedTrackingOptions, layer: ActivityLayer): Record<string, unknown> {\n const actOpts = options.activityOptions;\n\n // `action` is REQUIRED by both layers. It is the field that was previously sent as the\n // (non-existent) `activityType`, which made every audit write fail validation.\n const action = actOpts?.activityType ?? options.action ?? options.operationName ?? 'unknown';\n\n const description = actOpts?.description ?? `${options.operationName ?? 'operation'} executed`;\n const resourceType = actOpts?.resourceType ?? options.resourceType;\n const resourceId = actOpts?.resourceId ?? options.resourceId;\n const workspaceId = actOpts?.workspaceId ?? options.workspaceId;\n\n const metadata: Record<string, unknown> = {\n ...actOpts?.metadata,\n success: options.success ?? true,\n ...(options.operationName ? { operationName: options.operationName } : {}),\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n };\n\n const assistantSession = layer === 'global' ? resolveAssistantSession(options) : undefined;\n\n const input: Record<string, unknown> =\n layer === 'global'\n ? {\n action,\n // Required (non-nullable) on global-activity-svc.\n resource: deriveResource(options),\n description,\n resourceType,\n resourceId,\n userId: options.userId,\n actorId: options.userId,\n tenantId: options.tenantId,\n workspaceId,\n metadata,\n // AI-originated change (BOFF-9649): which assistant session made it.\n actorOrigin: assistantSession?.actorOrigin,\n assistantSessionId: assistantSession?.assistantSessionId,\n assistantCorrelationId: assistantSession?.assistantCorrelationId,\n }\n : {\n action,\n description,\n resourceType,\n resourceId,\n workspaceId,\n targetUserId: actOpts?.targetUserId,\n teamId: actOpts?.teamId,\n productId: options.productId,\n success: options.success ?? true,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n metadata: { ...metadata, userId: options.userId },\n // Who acted (BOFF-9684). wspace-activity-svc only; global-activity-svc has no such fields.\n actorType: resolveTrackedActorType(options),\n onBehalfOf: resolveOnBehalfOf(options),\n };\n\n // Both activity owners accept `dedupeKey` and return the existing row when it is replayed, which\n // is what makes delivery retries safe (a timed-out attempt may still have committed).\n input['dedupeKey'] = actOpts?.dedupeKey ?? `sdk:${randomUUID()}`;\n\n return input;\n}\n\n/**\n * Delivery policy for activity writes.\n *\n * A single attempt silently lost audit records whenever the internal gateway or the activity\n * subgraph was briefly unavailable (e.g. during a single-replica rolling deploy): the write timed\n * out, was logged at warn level, and the attributed activity never existed. Writes now retry\n * transient failures with backoff. Retrying is idempotent because every input carries a\n * `dedupeKey` (see {@link buildActivityInput}).\n */\nconst ACTIVITY_ATTEMPT_TIMEOUT_MS = 5000;\nconst DEFAULT_ACTIVITY_RETRY_DELAYS_MS: readonly number[] = [1000, 3000, 8000];\nlet activityRetryDelaysMs: readonly number[] = DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n\n/** HTTP statuses that mean \"the request may not have been processed — try again\". */\nconst RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);\n\n/**\n * GraphQL error codes that describe an unavailable dependency rather than a rejected payload.\n * The internal gateways mask an unreachable subgraph as INTERNAL_SERVER_ERROR, and surface request\n * validation failures as BAD_USER_INPUT (or with no code at all from graphql-js), so a payload the\n * owner rejects is never retried.\n */\nconst RETRYABLE_GRAPHQL_CODES = new Set([\n 'INTERNAL_SERVER_ERROR',\n 'SERVICE_UNAVAILABLE',\n 'AUTH_SERVICE_UNAVAILABLE',\n 'DOWNSTREAM_SERVICE_ERROR',\n 'GATEWAY_TIMEOUT',\n]);\n\n/**\n * Override the retry backoff schedule. Test-only seam so retry behaviour can be exercised without\n * real sleeps; pass `undefined` to restore the default schedule.\n */\nexport function __setActivityRetryDelaysForTests(delaysMs: readonly number[] | undefined): void {\n activityRetryDelaysMs = delaysMs ?? DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n}\n\ntype GraphQLErrorBody = { errors?: Array<{ message?: string; extensions?: { code?: unknown } }> };\n\ntype AttemptOutcome =\n { kind: 'delivered' } | { kind: 'rejected'; detail: string } | { kind: 'transient'; detail: string };\n\nfunction classifyGraphQLErrors(errors: NonNullable<GraphQLErrorBody['errors']>): AttemptOutcome {\n const detail = errors\n .map((e) => e?.message ?? 'unknown error')\n .join('; ')\n .slice(0, 500);\n const transient = errors.every((e) => {\n const code = e?.extensions?.code;\n return typeof code === 'string' && RETRYABLE_GRAPHQL_CODES.has(code);\n });\n return transient ? { kind: 'transient', detail } : { kind: 'rejected', detail };\n}\n\n/**\n * Detail for a non-2xx answer. A gateway can answer a refused GraphQL write with HTTP 400 and the\n * subgraph's `errors` array (BOFF-17562: \"Activity ... has no workspace\"); log those messages next\n * to the status so the caller sees why, instead of a bare status. The classification stays by status.\n */\nasync function httpFailureDetail(response: Response): Promise<string> {\n const status = `HTTP ${response.status}`;\n const parsed = (await response.json().catch(() => undefined)) as GraphQLErrorBody | undefined;\n const messages = parsed?.errors\n ?.map((error) => error?.message)\n .filter((message): message is string => typeof message === 'string' && message.length > 0);\n return messages && messages.length > 0 ? `${status}: ${messages.join('; ')}`.slice(0, 500) : status;\n}\n\nasync function attemptActivityDelivery(\n gatewayUrl: string,\n headers: Record<string, string>,\n body: string\n): Promise<AttemptOutcome> {\n try {\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS), // never block the caller for long\n });\n\n if (!response.ok) {\n const detail = await httpFailureDetail(response);\n return RETRYABLE_HTTP_STATUSES.has(response.status)\n ? { kind: 'transient', detail }\n : { kind: 'rejected', detail };\n }\n\n // A GraphQL validation/execution failure is returned as HTTP 200 with an `errors` array.\n // Without this check a malformed payload is indistinguishable from a successful write, which\n // is exactly how a fleet-wide audit outage stayed invisible: every call \"succeeded\" at the\n // HTTP layer while the subgraph rejected the input.\n const parsed = (await response.json().catch(() => undefined)) as GraphQLErrorBody | undefined;\n const errors = parsed?.errors;\n if (errors && errors.length > 0) {\n return classifyGraphQLErrors(errors);\n }\n return { kind: 'delivered' };\n } catch (err) {\n // Network failure or per-attempt timeout: the write may or may not have landed; the dedupeKey\n // makes a retry safe either way.\n return { kind: 'transient', detail: (err as Error).message };\n }\n}\n\n/**\n * The calling service's own identity (`SERVICE_IDENTITY`, else `SERVICE_NAME`), as the gateway\n * client and the proactive identity helper read it. Undefined when neither is set.\n */\nfunction trackerServiceIdentity(): string | undefined {\n return (process.env['SERVICE_IDENTITY'] || process.env['SERVICE_NAME'])?.trim() || undefined;\n}\n\n/**\n * Headers that prove who is writing a platform-level activity row (BOFF-17562).\n *\n * wspace-activity-svc records an activity without a workspace only from a service whose identity\n * the internal gateway verified from a signed `service-v1` JWT; header-only callers are refused.\n * For such a write the tracker therefore presents a short-lived service JWT minted for the calling\n * service. The gateway then binds the actor to that service, so the original actor is kept as\n * `onBehalfOf` (see {@link fireActivityLog}). Returns no header when the service has no identity\n * or no `SERVICE_JWT_SECRET`; the owner then refuses the write with a clear, non-retryable error.\n */\nasync function platformWriteAuthorization(): Promise<Record<string, string>> {\n const identity = trackerServiceIdentity();\n if (!identity) return {};\n const token = await signServiceJwt(identity);\n return token ? { Authorization: `Bearer ${token}` } : {};\n}\n\n/**\n * Re-mint the platform-write token before each delivery attempt. The service JWT lives 60 s and\n * the retries can span more than that, so a token built once could expire before the last retry;\n * `signServiceJwt` returns its cached token while more than 10 s of it remain.\n */\nasync function withFreshAuthorization(headers: Record<string, string>): Promise<Record<string, string>> {\n if (!headers['Authorization']) return headers;\n return { ...headers, ...(await platformWriteAuthorization()) };\n}\n\n/** Log label naming the operation, the action and the calling service of an activity write. */\nfunction describeActivityWrite(operation: string, input: Record<string, unknown>): string {\n const action = typeof input['action'] === 'string' ? input['action'] : 'unknown';\n return `\"${operation}\" (action ${action}, service ${trackerServiceIdentity() ?? 'unknown'})`;\n}\n\n/**\n * Request headers for one activity write. A workspace write carries the caller as the actor and\n * the workspace header. A platform-level write to the workspace owner (no workspace) also carries\n * the calling service's JWT (BOFF-17562); the gateway then binds the actor to that service, so the\n * original actor is kept in `input.onBehalfOf` unless the caller set one.\n */\nasync function buildActivityHeaders(\n options: UnifiedTrackingOptions,\n input: Record<string, unknown>,\n layer: ActivityLayer\n): Promise<Record<string, string>> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Forward actor context if available\n if (options.userId) {\n headers['x-actor-id'] = options.userId;\n headers['x-actor-type'] = 'service';\n }\n\n const workspaceId = options.workspaceId ?? options.activityOptions?.workspaceId;\n if (workspaceId) {\n headers['x-workspace-id'] = workspaceId;\n return headers;\n }\n if (layer !== 'wspace') return headers;\n\n const authorization = await platformWriteAuthorization();\n if (!authorization['Authorization']) return headers;\n Object.assign(headers, authorization);\n if (input['onBehalfOf'] === undefined && options.userId && options.userId !== trackerServiceIdentity()) {\n input['onBehalfOf'] = options.userId;\n }\n return headers;\n}\n\n/**\n * Fire-and-forget activity log via GraphQL, retrying transient failures.\n * Never throws — logs errors and continues.\n */\nasync function fireActivityLog(\n gatewayUrl: string,\n options: UnifiedTrackingOptions,\n layer: ActivityLayer\n): Promise<void> {\n try {\n const input = buildActivityInput(options, layer);\n\n // Strip undefined values\n for (const key of Object.keys(input)) {\n if (input[key] === undefined) delete input[key];\n }\n\n const headers = await buildActivityHeaders(options, input, layer);\n\n const operation = describeActivityWrite(options.operationName ?? 'operation', input);\n // Serialize once, outside the retry loop: a payload JSON cannot encode (bigint, cycles) is a\n // deterministic failure and must not be retried as if it were a network error.\n let body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input } });\n let attributionStripped = false;\n const maxAttempts = activityRetryDelaysMs.length + 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await attemptActivityDelivery(gatewayUrl, await withFreshAuthorization(headers), body);\n if (outcome.kind === 'delivered') {\n if (attempt > 1) {\n logger.info(`[trackOperation] Activity log delivered on attempt ${attempt}: ${operation}`);\n }\n return;\n }\n if (\n outcome.kind === 'rejected' &&\n !attributionStripped &&\n ATTRIBUTION_FIELDS.some((field) => field in input) &&\n isUnknownAttributionFieldRejection(outcome.detail)\n ) {\n // The owner predates the attribution fields (rollout skew). Losing the audit row would\n // be worse than losing who-acted on it, so resend once without them.\n attributionStripped = true;\n const stripped = { ...input };\n for (const field of ATTRIBUTION_FIELDS) delete stripped[field];\n body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input: stripped } });\n logger.warn(\n `[trackOperation] ${layer}-activity subgraph does not accept the actor attribution fields yet; resending ${operation} without them`\n );\n attempt -= 1;\n continue;\n }\n if (outcome.kind === 'rejected') {\n logger.error(\n `[trackOperation] Activity log REJECTED by ${layer}-activity subgraph for ${operation}: ${outcome.detail}`\n );\n return;\n }\n const delay = activityRetryDelaysMs[attempt - 1];\n if (delay === undefined) {\n // An audit record is about to be lost: this must be visible at error level.\n logger.error(\n `[trackOperation] Activity log failed after ${attempt} attempts for ${operation}: ${outcome.detail}`\n );\n return;\n }\n logger.warn(\n `[trackOperation] Activity log attempt ${attempt} failed for ${operation}: ${outcome.detail}; retrying in ${delay}ms`\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (err) {\n // Fire-and-forget: log but never throw\n logger.warn(`[trackOperation] Activity log failed: ${(err as Error).message}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main trackOperation function\n// ---------------------------------------------------------------------------\n\n/**\n * Simple tracker class with auto-promoting behavior\n */\nexport class UnifiedTrackerStub {\n private static instance: UnifiedTrackerStub;\n\n static getInstance(): UnifiedTrackerStub {\n if (!UnifiedTrackerStub.instance) {\n UnifiedTrackerStub.instance = new UnifiedTrackerStub();\n }\n return UnifiedTrackerStub.instance;\n }\n\n async track(event: TrackingEvent): Promise<void> {\n markExplicitActivity();\n const gatewayUrl = getGatewayUrl();\n if (gatewayUrl) {\n await fireActivityLog(\n gatewayUrl,\n {\n operationName: event.eventType,\n userId: event.userId,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n activityOptions: {\n activityType: event.eventType,\n metadata: event.metadata,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n enabled: true,\n },\n },\n getGatewayLayer()\n );\n } else {\n logger.debug('[UnifiedTracker:Stub]', event.eventType, event.entityType, event.entityId);\n }\n }\n\n async trackBatch(events: TrackingEvent[]): Promise<void> {\n for (const event of events) {\n await this.track(event);\n }\n }\n}\n\nexport const trackerStub = UnifiedTrackerStub.getInstance();\n\n/**\n * Unified tracking function — auto-promoting\n *\n * When a gateway URL is configured (WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL),\n * this function makes real fire-and-forget GraphQL calls for activity logging.\n * When no gateway URL is configured, it falls back to debug-level logging (stub mode).\n *\n * RBAC checks are NOT performed here — they are handled by gateway @rbac directives.\n * The rbacCheck option is accepted for interface compatibility but not enforced.\n *\n * @param options - Tracking options\n * @returns Always returns true (never blocks the calling operation)\n */\nexport async function trackOperation(options: UnifiedTrackingOptions): Promise<boolean> {\n const { operationName, userId, success = true } = options;\n const gatewayUrl = getGatewayUrl();\n const activityEnabled = options.activityOptions?.enabled !== false;\n\n // An explicit activity write: the mutation-audit backstop must not add a second row for this\n // operation. Marked in stub mode too, so dedupe behaves the same locally as when deployed.\n if (activityEnabled) markExplicitActivity();\n\n if (!gatewayUrl) {\n // Stub mode — debug log only\n logger.debug(`[trackOperation:Stub] ${operationName} for user ${userId} - success: ${success}`);\n return true;\n }\n\n // Real mode — fire-and-forget activity logging\n if (activityEnabled) {\n // Do NOT await — fire and forget so we never block the caller\n void fireActivityLog(gatewayUrl, options, getGatewayLayer());\n } else {\n logger.debug(`[trackOperation] ${operationName} for user ${userId} - activity disabled, skipping`);\n }\n\n return true;\n}\n\n/**\n * Product tracker type definition\n */\nexport type ProductTracker = {\n track: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n freeUp: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackActivityOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackUsageOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackCustom: (operationName: string, additionalOptions: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n productId: string;\n userId: string;\n billingAccountId: string | undefined;\n defaultContext: Partial<UnifiedTrackingOptions> | undefined;\n};\n\n/**\n * Create a product-scoped tracker (auto-promoting implementation)\n *\n * @param productId - Product identifier\n * @param userId - User identifier\n * @param billingAccountId - Optional billing account ID\n * @param defaultContext - Optional default tracking context\n * @returns Product tracker instance\n */\nexport function createProductTracker(\n productId: string,\n userId: string,\n billingAccountId?: string,\n defaultContext?: Partial<UnifiedTrackingOptions>\n): ProductTracker {\n return {\n async track(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n async freeUp(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: {\n ...defaultContext?.activityOptions,\n ...additionalOptions?.activityOptions,\n activityType: 'free_up',\n },\n });\n },\n async trackActivityOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { ...defaultContext?.activityOptions, ...additionalOptions?.activityOptions, enabled: true },\n usageOptions: { enabled: false },\n });\n },\n async trackUsageOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { enabled: false },\n usageOptions: { ...defaultContext?.usageOptions, ...additionalOptions?.usageOptions, enabled: true },\n });\n },\n async trackCustom(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n productId,\n userId,\n billingAccountId,\n defaultContext,\n };\n}\n\n/**\n * Constants for tracking\n */\nexport const UNIFIED_TRACKER_CONSTANTS = {\n DEFAULT_PRODUCT_ID: 'module',\n OPERATIONS: {} as const,\n PRODUCTS: {} as const,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,4BAA4B;;AAKzC,MAAa,sBAAsB;AACnC,MAAa,8BAA8B;AAC3C,MAAa,kCAAkC;;AAG/C,MAAM,yBAAyB;AAW/B,SAAS,cAAc,OAAoC;CACzD,OAAO,OAAO,UAAU,YAAY,uBAAuB,KAAK,KAAK,IAAI,QAAQ;AACnF;;;;;;AAOA,SAAgB,8BACd,aACA,oBACA,wBACyC;CACzC,IAAI,gCAA2C,OAAO;CACtD,MAAM,YAAY,cAAc,kBAAkB;CAClD,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,gBAAgB,cAAc,sBAAsB;CAC1D,OAAO;EACL,aAAa;EACb,oBAAoB;EACpB,GAAI,gBAAgB,EAAE,wBAAwB,cAAc,IAAI,CAAC;CACnE;AACF;;;;;AAMA,SAAgB,6BACd,WACyC;CACzC,OAAO,8BACL,UAAU,mBAAmB,GAC7B,UAAU,2BAA2B,GACrC,UAAU,+BAA+B,CAC3C;AACF;;AAGA,SAAgB,gCAAgC,OAAyD;CACvG,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,SAAS;CACf,OAAO,8BACL,OAAO,gBACP,OAAO,uBACP,OAAO,yBACT;AACF;;;;;;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cAAc,YAAY,OAAO,cAAc,SAAS;EAC9F,OAAO;CACT;CAGA,IAAI,iBAEF,AAAK,gBAAgB,YAAY,SAAS,gBAAgB,CAAC;MAE3D,OAAO,MAAM,oBAAoB,cAAc,YAAY,OAAO,+BAA+B;CAGnG,OAAO;AACT;;;;;;;;;;AA0BA,SAAgB,qBACd,WACA,QACA,kBACA,gBACgB;CAChB,OAAO;EACL,MAAM,MAAM,eAAe,mBAAqC;GAC9D,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;GACL,CAAC;EACH;EACA,MAAM,OAAO,eAAe,mBAAqC;GAC/D,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;IACH,iBAAiB;KACf,GAAG,gBAAgB;KACnB,GAAG,mBAAmB;KACtB,cAAc;IAChB;GACF,CAAC;EACH;EACA,MAAM,kBAAkB,eAAe,mBAAqC;GAC1E,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;IACH,iBAAiB;KAAE,GAAG,gBAAgB;KAAiB,GAAG,mBAAmB;KAAiB,SAAS;IAAK;IAC5G,cAAc,EAAE,SAAS,MAAM;GACjC,CAAC;EACH;EACA,MAAM,eAAe,eAAe,mBAAqC;GACvE,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;IACH,iBAAiB,EAAE,SAAS,MAAM;IAClC,cAAc;KAAE,GAAG,gBAAgB;KAAc,GAAG,mBAAmB;KAAc,SAAS;IAAK;GACrG,CAAC;EACH;EACA,MAAM,YAAY,eAAe,mBAAqC;GACpE,OAAO,eAAe;IACpB,GAAG;IACH;IACA;IACA;IACA,GAAG;GACL,CAAC;EACH;EACA;EACA;EACA;EACA;CACF;AACF;;;;AAKA,MAAa,4BAA4B;CACvC,oBAAoB;CACpB,YAAY,CAAC;CACb,UAAU,CAAC;AACb"}
@@ -1,8 +1,8 @@
1
1
  import { i as suppressMutationAudit } from "../explicit-activity-scope-DikJ7NAE.js";
2
2
  import "../activity/index.js";
3
3
  import { i as UsageMetricType } from "../usage-BK7eyP42.js";
4
- import { a as resolveAssistantSession, i as isTrackedActorType, l as AI_ASSISTANT_ACTOR_ORIGIN, n as UnifiedTrackerStub, o as trackOperation, r as createProductTracker, s as trackerStub, t as UNIFIED_TRACKER_CONSTANTS } from "../stub-BkPAoXnP.js";
5
- import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-DnIlQldQ.js";
4
+ import { a as resolveAssistantSession, i as isTrackedActorType, l as AI_ASSISTANT_ACTOR_ORIGIN, n as UnifiedTrackerStub, o as trackOperation, r as createProductTracker, s as trackerStub, t as UNIFIED_TRACKER_CONSTANTS } from "../stub-D0g4EsW4.js";
5
+ import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-Cb58dqj9.js";
6
6
 
7
7
  export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, AI_ASSISTANT_ACTOR_ORIGIN, TrackerModule, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, UsageMetricType, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackAgentActivity, trackOperation, trackerStub };
8
8
  //# sourceMappingURL=index.js.map
@@ -4,7 +4,7 @@ import { t as RBACModule } from "./rbac-pRCcWVS_.js";
4
4
  import { ActivityModule, ActivitySeverity, ActivityStatus, ActivityType } from "./activity/index.js";
5
5
  import { a as UsageModule } from "./usage-BK7eyP42.js";
6
6
  import { n as NotificationType, r as NotificationsModule } from "./notifications-DY_i37WN.js";
7
- import { o as trackOperation } from "./stub-BkPAoXnP.js";
7
+ import { o as trackOperation } from "./stub-D0g4EsW4.js";
8
8
  import { r as runInExplicitActivityScope, t as createExplicitActivityScope } from "./explicit-activity-scope-DikJ7NAE.js";
9
9
 
10
10
  // src/tracker/agent-activity.ts
@@ -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-DnIlQldQ.js.map
458
+ //# sourceMappingURL=tracker-Cb58dqj9.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tracker-DnIlQldQ.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,QAAQ,WAAW,IAAI,CAAC;EAC/D,aAAa,QAAQ;EACrB,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D;EACA,GAAI,QAAQ,eAAe,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;EACrE,iBAAiB;GACf,SAAS;GACT,cAAc,QAAQ;GACtB,aAAa,QAAQ,eAAe,SAAS,QAAQ,QAAQ,IAAI,QAAQ;GACzE,aAAa,QAAQ;GACrB,cAAc,QAAQ;GACtB,YAAY,QAAQ,cAAc,QAAQ;GAC1C,UAAU;IAAE,GAAG,QAAQ;IAAU,SAAS,QAAQ;GAAQ;GAC1D,GAAI,QAAQ,YAAY,EAAE,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AAQ;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-Cb58dqj9.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,QAAQ,WAAW,IAAI,CAAC;EAC/D,aAAa,QAAQ;EACrB,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC5D;EACA,GAAI,QAAQ,eAAe,EAAE,cAAc,QAAQ,aAAa,IAAI,CAAC;EACrE,iBAAiB;GACf,SAAS;GACT,cAAc,QAAQ;GACtB,aAAa,QAAQ,eAAe,SAAS,QAAQ,QAAQ,IAAI,QAAQ;GACzE,aAAa,QAAQ;GACrB,cAAc,QAAQ;GACtB,YAAY,QAAQ,cAAc,QAAQ;GAC1C,UAAU;IAAE,GAAG,QAAQ;IAAU,SAAS,QAAQ;GAAQ;GAC1D,GAAI,QAAQ,YAAY,EAAE,WAAW,QAAQ,UAAU,IAAI,CAAC;EAC9D;CACF,CAAC,CACH;AACF;;;;;;;;;;;;;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,QAAQ,QAAQ,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;EAC5C,CAAC;EAED,OAAO;CACT;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@burdenoff/be-sdk",
3
- "version": "2026.1202.1",
3
+ "version": "2026.1202.2",
4
4
  "description": "Backend SDK for Burdenoff products providing unified access to notifications, RBAC, activity tracking, usage monitoring, and more",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -1 +0,0 @@
1
- {"version":3,"file":"stub-BkPAoXnP.js","names":[],"sources":["../src/activity/assistant-session.ts","../src/tracker/stub.ts"],"sourcesContent":["/**\n * Assistant-session attribution (BOFF-9649)\n *\n * When an AI assistant session runs a GraphQL mutation for its owner, the\n * assistant session relay (wspace-sandbox-svc) forwards it to a public gateway\n * as the owner, with a signed assistant-session marker. The gateway verifies\n * that marker against the owner's verified token, strips any copy a client\n * sent, and passes the result to subgraphs as three headers:\n *\n * x-actor-origin: ai_assistant\n * x-assistant-session-id: <the relay session id (the assistant sandbox id)>\n * x-assistant-correlation-id: <the proposal / idempotency key, when there is one>\n *\n * A service never verifies these itself. `buildContext` reads them only when it\n * already trusts the gateway's actor headers, exposes them as\n * `context.assistantSession`, and binds them to the operation's workspace\n * context so `trackOperation` can stamp every activity row written while the\n * operation runs, without each service re-implementing audit.\n *\n * Values outside the vocabulary or the id pattern are dropped, never coerced:\n * a wrong attribution is worse than none.\n */\n\n/** The only actor origin the platform records today. */\nexport const AI_ASSISTANT_ACTOR_ORIGIN = 'ai_assistant';\n\nexport type ActorOrigin = typeof AI_ASSISTANT_ACTOR_ORIGIN;\n\n/** Gateway-to-subgraph headers. Clients cannot set them: the public gateways strip them. */\nexport const ACTOR_ORIGIN_HEADER = 'x-actor-origin';\nexport const ASSISTANT_SESSION_ID_HEADER = 'x-assistant-session-id';\nexport const ASSISTANT_CORRELATION_ID_HEADER = 'x-assistant-correlation-id';\n\n/** Session ids (UUIDs, cuid-style ids) and proposal / idempotency keys. */\nconst ATTRIBUTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;\n\n/** The assistant session an operation ran under. */\nexport interface AssistantSessionAttribution {\n actorOrigin: ActorOrigin;\n /** The relay session id: the assistant sandbox that ran the mutation. */\n assistantSessionId: string;\n /** The proposal / idempotency key the mutation ran under, when it had one. */\n assistantCorrelationId?: string;\n}\n\nfunction attributionId(value: unknown): string | undefined {\n return typeof value === 'string' && ATTRIBUTION_ID_PATTERN.test(value) ? value : undefined;\n}\n\n/**\n * Build an attribution from raw values. Undefined unless the origin is\n * `ai_assistant` and the session id is well formed; a malformed correlation id\n * is dropped on its own.\n */\nexport function toAssistantSessionAttribution(\n actorOrigin: unknown,\n assistantSessionId: unknown,\n assistantCorrelationId?: unknown\n): AssistantSessionAttribution | undefined {\n if (actorOrigin !== AI_ASSISTANT_ACTOR_ORIGIN) return undefined;\n const sessionId = attributionId(assistantSessionId);\n if (!sessionId) return undefined;\n const correlationId = attributionId(assistantCorrelationId);\n return {\n actorOrigin: AI_ASSISTANT_ACTOR_ORIGIN,\n assistantSessionId: sessionId,\n ...(correlationId ? { assistantCorrelationId: correlationId } : {}),\n };\n}\n\n/**\n * Read the gateway's assistant-session headers. The caller decides whether the\n * request's gateway headers are trusted at all; this only parses them.\n */\nexport function parseAssistantSessionHeaders(\n getHeader: (name: string) => string | null | undefined\n): AssistantSessionAttribution | undefined {\n return toAssistantSessionAttribution(\n getHeader(ACTOR_ORIGIN_HEADER),\n getHeader(ASSISTANT_SESSION_ID_HEADER),\n getHeader(ASSISTANT_CORRELATION_ID_HEADER)\n );\n}\n\n/** Re-validate an attribution-shaped value (from a request context or caller options). */\nexport function readAssistantSessionAttribution(value: unknown): AssistantSessionAttribution | undefined {\n if (typeof value !== 'object' || value === null) return undefined;\n const record = value as Record<string, unknown>;\n return toAssistantSessionAttribution(\n record['actorOrigin'],\n record['assistantSessionId'],\n record['assistantCorrelationId']\n );\n}\n","/**\n * Unified Tracking — Auto-Promoting Implementation\n *\n * Automatically promotes from stub to real tracking when gateway URLs are configured.\n * When WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL is set, this module will:\n * - Log activity events via GraphQL to the activity service\n * - Track usage via GraphQL to the usage service (if usage options provided)\n * - RBAC checks are NOT performed here (handled by gateway @rbac directives)\n *\n * When no gateway URL is configured, falls back to debug-level logging (stub mode).\n *\n * This is a backward-compatible drop-in replacement for the original stub. All 1,100+\n * existing call sites continue to work without modification.\n *\n * @module tracker/stub\n * @category Tracking\n */\nimport { randomUUID } from 'node:crypto';\n\nimport { logger } from '../logger/index.js';\nimport { markExplicitActivity } from '../activity/explicit-activity-scope.js';\nimport { readAssistantSessionAttribution, type AssistantSessionAttribution } from '../activity/assistant-session.js';\nimport { getScopedWorkspaceContext, getWorkspaceContext } from '../prisma/workspace-extension.js';\nimport { signServiceJwt } from '../gateway/service-jwt.js';\n\n/**\n * Tracking event interface\n */\nexport interface TrackingEvent {\n eventType: string;\n entityType: string;\n entityId: string;\n userId?: string;\n workspaceId?: string;\n metadata?: Record<string, unknown>;\n timestamp?: Date;\n}\n\n/**\n * RBAC check options\n */\nexport interface RbacCheckOptions {\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n skipRbacCheck?: boolean;\n options?: {\n allowOwnerAccess?: boolean;\n allowWorkspaceAdmin?: boolean;\n scope?: string;\n };\n}\n\n/**\n * Usage tracking options\n */\nexport interface UsageTrackingOptions {\n billingAccountId?: string;\n addUsage?: boolean;\n description?: string;\n tags?: Record<string, unknown>;\n quotaName?: string;\n value?: number;\n}\n\n/**\n * Activity tracking options\n */\nexport interface ActivityTrackingOptions {\n activityType?: string;\n description?: string;\n metadata?: Record<string, unknown>;\n workspaceId?: string;\n teamId?: string;\n groupId?: string;\n projectId?: string;\n targetUserId?: string;\n resourceType?: string;\n resourceId?: string;\n enabled?: boolean;\n /**\n * Idempotency key forwarded to the activity owner's `RecordActivityInput.dedupeKey`.\n * When omitted, a unique key is generated per tracked operation so that delivery retries of the\n * SAME operation converge to exactly one activity row. Supply a stable key only when the caller\n * itself may replay the same logical event (backfill/import).\n */\n dedupeKey?: string;\n}\n\n/**\n * Kind of actor behind a tracked operation — the gateway `x-actor-type` vocabulary.\n *\n * An AI agent acting through a product service is an `app` actor; recording it lets the\n * activity owner tell agent actions apart from human ones (BOFF-9684).\n */\nexport type TrackedActorType = 'user' | 'app' | 'service' | 'super_admin';\n\nconst TRACKED_ACTOR_TYPES: ReadonlySet<string> = new Set<TrackedActorType>(['user', 'app', 'service', 'super_admin']);\n\nexport function isTrackedActorType(value: unknown): value is TrackedActorType {\n return typeof value === 'string' && TRACKED_ACTOR_TYPES.has(value);\n}\n\n/**\n * Unified tracking options\n */\nexport interface UnifiedTrackingOptions {\n operationName?: string;\n userId?: string;\n /**\n * Kind of actor `userId` identifies. When omitted it is taken from `context` (`actor.type` or\n * `actorType`) or, with no `context`, from the ambient be-sdk workspace context; a value outside\n * the vocabulary is dropped rather than sent. The activity owner honours it because the tracker\n * calls it as a relaying `service`.\n */\n actorType?: TrackedActorType;\n /**\n * The user on whose behalf `userId` acted — for an AI-agent action, the human who started the\n * run. When omitted it is taken from `context.onBehalfOf`; the activity owner otherwise records\n * the actor itself.\n */\n onBehalfOf?: string;\n /**\n * The AI assistant session the operation ran under (BOFF-9649). When omitted it is taken from\n * `context.assistantSession` or, failing that, from the operation's own async scope (never from\n * another request's). Sent to global-activity-svc as `actorOrigin` / `assistantSessionId` /\n * `assistantCorrelationId`.\n */\n assistantSession?: AssistantSessionAttribution;\n context?: unknown;\n rbacCheck?: RbacCheckOptions;\n activityOptions?: ActivityTrackingOptions;\n usageOptions?: UsageTrackingOptions & { enabled?: boolean };\n success?: boolean;\n errorMessage?: string;\n productId?: string;\n // Legacy properties for backward compatibility (can be at top level or in nested objects)\n action?: string;\n resourceType?: string;\n resourceId?: string;\n workspaceId?: string;\n tenantId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Gateway URL resolution — cached at module level for performance\n// ---------------------------------------------------------------------------\n\nlet _gatewayUrl: string | undefined;\nlet _gatewayLayer: ActivityLayer | undefined;\nlet _gatewayUrlResolved = false;\n\n/**\n * Which activity subgraph the resolved gateway fronts.\n *\n * The two canonical activity owners accept DIFFERENT `RecordActivityInput` shapes, so the\n * payload must be built per layer:\n * - `wspace` → wspace-activity-svc: requires `action`; carries workspace-scoped fields\n * (workspaceId/teamId/targetUserId/productId/success).\n * - `global` → global-activity-svc: requires `action` AND `resource`; carries tenant-scoped\n * fields (tenantId/actorId/ipAddress/userAgent).\n * Sending one layer's shape to the other fails GraphQL validation.\n */\nexport type ActivityLayer = 'wspace' | 'global';\n\n/**\n * The layer the running service belongs to, when its environment says so: `SERVICE_LAYER`, then a\n * `global-` / `wspace-` `SERVICE_NAME` prefix (the same rule the RBAC directive and the Temporal\n * client use). Undefined when neither says.\n */\nfunction declaredServiceLayer(): ActivityLayer | undefined {\n const layer = process.env['SERVICE_LAYER'];\n if (layer === 'global' || layer === 'wspace') return layer;\n const name = process.env['SERVICE_NAME'] ?? '';\n if (name.startsWith('global-')) return 'global';\n if (name.startsWith('wspace-')) return 'wspace';\n return undefined;\n}\n\n/**\n * Resolve the internal gateway URL from environment.\n *\n * Activity belongs to the service's OWN layer: workspace services record in wspace-activity-svc\n * through WSPACE_INT_GATEWAY_URL, global services in global-activity-svc through\n * GLOBAL_INT_GATEWAY_URL. Global services also hold WSPACE_INT_GATEWAY_URL for cross-layer\n * calls, so the URL that happens to be set is not a layer signal: the declared layer\n * (`SERVICE_LAYER` / `SERVICE_NAME`) decides, and only an undeclared service falls back to\n * \"workspace URL first\" (BOFF-9649 — every global service was sending its audit rows to the\n * workspace activity owner, which rejected them). Undefined (stub mode) when no URL is set.\n */\nfunction getGatewayUrl(): string | undefined {\n if (!_gatewayUrlResolved) {\n const wspaceUrl = process.env['WSPACE_INT_GATEWAY_URL'];\n const globalUrl = process.env['GLOBAL_INT_GATEWAY_URL'];\n const declared = declaredServiceLayer();\n\n // A declared global service uses its own owner; anything else keeps \"workspace URL first\".\n const useGlobal = Boolean(globalUrl) && (declared === 'global' || !wspaceUrl);\n if (useGlobal) {\n _gatewayUrl = globalUrl;\n _gatewayLayer = 'global';\n } else if (wspaceUrl) {\n _gatewayUrl = wspaceUrl;\n _gatewayLayer = 'wspace';\n } else {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n }\n if (declared && _gatewayLayer && declared !== _gatewayLayer) {\n logger.warn(\n `[trackOperation] ${declared} service has no ${declared === 'global' ? 'GLOBAL' : 'WSPACE'}_INT_GATEWAY_URL; activity goes to the ${_gatewayLayer} activity owner instead`\n );\n }\n _gatewayUrlResolved = true;\n\n if (_gatewayUrl) {\n logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);\n } else {\n logger.debug('[trackOperation] No gateway URL configured — running in stub mode');\n }\n }\n return _gatewayUrl;\n}\n\n/**\n * Resolve which activity layer the configured gateway fronts.\n * Always call `getGatewayUrl()` first — it performs the resolution.\n */\nfunction getGatewayLayer(): ActivityLayer {\n // Default to 'wspace': the overwhelming majority of services are workspace-layer, and a wspace\n // payload omits only optional global fields, so a mis-detection degrades rather than fails.\n return _gatewayLayer ?? 'wspace';\n}\n\n/**\n * Reset the cached gateway resolution. Test-only seam — module-level caching would otherwise make\n * per-layer behaviour untestable within a single process.\n */\nexport function __resetGatewayCacheForTests(): void {\n _gatewayUrl = undefined;\n _gatewayLayer = undefined;\n _gatewayUrlResolved = false;\n}\n\n// ---------------------------------------------------------------------------\n// Fire-and-forget GraphQL helper\n// ---------------------------------------------------------------------------\n\nconst LOG_ACTIVITY_MUTATION = /* GraphQL */ `\n mutation RecordActivity($input: RecordActivityInput!) {\n recordActivity(input: $input) {\n id\n }\n }\n`;\n\n/**\n * Derive the `resource` value required by global-activity-svc.\n *\n * Prefers an explicit resourceType; otherwise falls back to the leading dotted segment of the\n * operation name (`auth.session.revoke` → `auth`), which matches the platform's\n * `<domain>.<resource>.<verb>` activity taxonomy. Never returns empty — `resource` is non-nullable\n * on global-activity-svc and an empty string would be silently useless in the audit trail.\n */\nfunction deriveResource(options: UnifiedTrackingOptions): string {\n const explicit = options.activityOptions?.resourceType ?? options.resourceType;\n if (explicit && explicit.trim().length > 0) return explicit;\n\n const op = options.operationName;\n if (op && op.trim().length > 0) {\n const [head] = op.split('.');\n if (head && head.trim().length > 0) return head;\n }\n return 'unknown';\n}\n\nfunction readRecord(value: unknown): Record<string, unknown> | undefined {\n return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : undefined;\n}\n\n/**\n * Resolve the kind of actor behind a tracked operation. Exported for unit tests.\n *\n * Precedence: the explicit `actorType` option, then the request `context` the caller passed\n * (`actor.type`, then the flat `actorType`), then the ambient be-sdk workspace context. A request\n * context is authoritative once given: an unknown kind there yields undefined rather than falling\n * through to the ambient context, which could belong to a different request in the same async\n * chain. A wrong attribution is worse than none.\n */\nexport function resolveTrackedActorType(options: UnifiedTrackingOptions): TrackedActorType | undefined {\n if (options.actorType !== undefined) {\n return isTrackedActorType(options.actorType) ? options.actorType : undefined;\n }\n const context = readRecord(options.context);\n if (context) {\n const actor = readRecord(context['actor']);\n const fromContext = actor?.['type'] ?? context['actorType'];\n return isTrackedActorType(fromContext) ? fromContext : undefined;\n }\n const ambient = getWorkspaceContext()?.actorType;\n return isTrackedActorType(ambient) ? ambient : undefined;\n}\n\nfunction resolveOnBehalfOf(options: UnifiedTrackingOptions): string | undefined {\n if (options.onBehalfOf) return options.onBehalfOf;\n const fromContext = readRecord(options.context)?.['onBehalfOf'];\n return typeof fromContext === 'string' && fromContext.length > 0 ? fromContext : undefined;\n}\n\n/**\n * Resolve the assistant session behind a tracked operation (BOFF-9649). Exported for unit tests.\n *\n * Precedence: the explicit `assistantSession` option, then `context.assistantSession`, then the\n * workspace context bound to the operation's own async scope. The module-level fallback context is\n * never read: it belongs to whichever request built its context last, and tagging a human's row\n * as AI-originated (or the reverse) is worse than leaving it untagged.\n */\nexport function resolveAssistantSession(options: UnifiedTrackingOptions): AssistantSessionAttribution | undefined {\n if (options.assistantSession !== undefined) return readAssistantSessionAttribution(options.assistantSession);\n const fromContext = readAssistantSessionAttribution(readRecord(options.context)?.['assistantSession']);\n if (fromContext) return fromContext;\n return readAssistantSessionAttribution(getScopedWorkspaceContext()?.assistantSession);\n}\n\n/**\n * Input fields an older activity owner may not define yet: wspace-activity-svc before BOFF-9684\n * (`actorType`, `onBehalfOf`), global-activity-svc before BOFF-9649 (assistant-session fields).\n */\nconst ATTRIBUTION_FIELDS = [\n 'actorType',\n 'onBehalfOf',\n 'actorOrigin',\n 'assistantSessionId',\n 'assistantCorrelationId',\n] as const;\n\n/**\n * True when the activity owner rejected the write only because it predates the attribution\n * fields (`Field \"actorType\" is not defined by type \"RecordActivityInput\"`).\n */\nfunction isUnknownAttributionFieldRejection(detail: string): boolean {\n return ATTRIBUTION_FIELDS.some(\n (field) => detail.includes(`\"${field}\"`) && /not defined|unknown field|is not defined by type/i.test(detail)\n );\n}\n\n/**\n * Build the layer-appropriate `RecordActivityInput`.\n *\n * Exported for unit testing: the whole class of defect this guards against is a payload that is\n * structurally plausible but rejected by the owning subgraph, which — because delivery is\n * fire-and-forget — is invisible at runtime.\n */\nexport function buildActivityInput(options: UnifiedTrackingOptions, layer: ActivityLayer): Record<string, unknown> {\n const actOpts = options.activityOptions;\n\n // `action` is REQUIRED by both layers. It is the field that was previously sent as the\n // (non-existent) `activityType`, which made every audit write fail validation.\n const action = actOpts?.activityType ?? options.action ?? options.operationName ?? 'unknown';\n\n const description = actOpts?.description ?? `${options.operationName ?? 'operation'} executed`;\n const resourceType = actOpts?.resourceType ?? options.resourceType;\n const resourceId = actOpts?.resourceId ?? options.resourceId;\n const workspaceId = actOpts?.workspaceId ?? options.workspaceId;\n\n const metadata: Record<string, unknown> = {\n ...actOpts?.metadata,\n success: options.success ?? true,\n ...(options.operationName ? { operationName: options.operationName } : {}),\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n };\n\n const assistantSession = layer === 'global' ? resolveAssistantSession(options) : undefined;\n\n const input: Record<string, unknown> =\n layer === 'global'\n ? {\n action,\n // Required (non-nullable) on global-activity-svc.\n resource: deriveResource(options),\n description,\n resourceType,\n resourceId,\n userId: options.userId,\n actorId: options.userId,\n tenantId: options.tenantId,\n workspaceId,\n metadata,\n // AI-originated change (BOFF-9649): which assistant session made it.\n actorOrigin: assistantSession?.actorOrigin,\n assistantSessionId: assistantSession?.assistantSessionId,\n assistantCorrelationId: assistantSession?.assistantCorrelationId,\n }\n : {\n action,\n description,\n resourceType,\n resourceId,\n workspaceId,\n targetUserId: actOpts?.targetUserId,\n teamId: actOpts?.teamId,\n productId: options.productId,\n success: options.success ?? true,\n ...(options.errorMessage ? { errorMessage: options.errorMessage } : {}),\n metadata: { ...metadata, userId: options.userId },\n // Who acted (BOFF-9684). wspace-activity-svc only; global-activity-svc has no such fields.\n actorType: resolveTrackedActorType(options),\n onBehalfOf: resolveOnBehalfOf(options),\n };\n\n // Both activity owners accept `dedupeKey` and return the existing row when it is replayed, which\n // is what makes delivery retries safe (a timed-out attempt may still have committed).\n input['dedupeKey'] = actOpts?.dedupeKey ?? `sdk:${randomUUID()}`;\n\n return input;\n}\n\n/**\n * Delivery policy for activity writes.\n *\n * A single attempt silently lost audit records whenever the internal gateway or the activity\n * subgraph was briefly unavailable (e.g. during a single-replica rolling deploy): the write timed\n * out, was logged at warn level, and the attributed activity never existed. Writes now retry\n * transient failures with backoff. Retrying is idempotent because every input carries a\n * `dedupeKey` (see {@link buildActivityInput}).\n */\nconst ACTIVITY_ATTEMPT_TIMEOUT_MS = 5000;\nconst DEFAULT_ACTIVITY_RETRY_DELAYS_MS: readonly number[] = [1000, 3000, 8000];\nlet activityRetryDelaysMs: readonly number[] = DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n\n/** HTTP statuses that mean \"the request may not have been processed — try again\". */\nconst RETRYABLE_HTTP_STATUSES = new Set([408, 425, 429, 500, 502, 503, 504]);\n\n/**\n * GraphQL error codes that describe an unavailable dependency rather than a rejected payload.\n * The internal gateways mask an unreachable subgraph as INTERNAL_SERVER_ERROR, and surface request\n * validation failures as BAD_USER_INPUT (or with no code at all from graphql-js), so a payload the\n * owner rejects is never retried.\n */\nconst RETRYABLE_GRAPHQL_CODES = new Set([\n 'INTERNAL_SERVER_ERROR',\n 'SERVICE_UNAVAILABLE',\n 'AUTH_SERVICE_UNAVAILABLE',\n 'DOWNSTREAM_SERVICE_ERROR',\n 'GATEWAY_TIMEOUT',\n]);\n\n/**\n * Override the retry backoff schedule. Test-only seam so retry behaviour can be exercised without\n * real sleeps; pass `undefined` to restore the default schedule.\n */\nexport function __setActivityRetryDelaysForTests(delaysMs: readonly number[] | undefined): void {\n activityRetryDelaysMs = delaysMs ?? DEFAULT_ACTIVITY_RETRY_DELAYS_MS;\n}\n\ntype GraphQLErrorBody = { errors?: Array<{ message?: string; extensions?: { code?: unknown } }> };\n\ntype AttemptOutcome =\n { kind: 'delivered' } | { kind: 'rejected'; detail: string } | { kind: 'transient'; detail: string };\n\nfunction classifyGraphQLErrors(errors: NonNullable<GraphQLErrorBody['errors']>): AttemptOutcome {\n const detail = errors\n .map((e) => e?.message ?? 'unknown error')\n .join('; ')\n .slice(0, 500);\n const transient = errors.every((e) => {\n const code = e?.extensions?.code;\n return typeof code === 'string' && RETRYABLE_GRAPHQL_CODES.has(code);\n });\n return transient ? { kind: 'transient', detail } : { kind: 'rejected', detail };\n}\n\nasync function attemptActivityDelivery(\n gatewayUrl: string,\n headers: Record<string, string>,\n body: string\n): Promise<AttemptOutcome> {\n try {\n const response = await fetch(gatewayUrl, {\n method: 'POST',\n headers,\n body,\n signal: AbortSignal.timeout(ACTIVITY_ATTEMPT_TIMEOUT_MS), // never block the caller for long\n });\n\n if (!response.ok) {\n const detail = `HTTP ${response.status}`;\n return RETRYABLE_HTTP_STATUSES.has(response.status)\n ? { kind: 'transient', detail }\n : { kind: 'rejected', detail };\n }\n\n // A GraphQL validation/execution failure is returned as HTTP 200 with an `errors` array.\n // Without this check a malformed payload is indistinguishable from a successful write, which\n // is exactly how a fleet-wide audit outage stayed invisible: every call \"succeeded\" at the\n // HTTP layer while the subgraph rejected the input.\n const parsed = (await response.json().catch(() => undefined)) as GraphQLErrorBody | undefined;\n const errors = parsed?.errors;\n if (errors && errors.length > 0) {\n return classifyGraphQLErrors(errors);\n }\n return { kind: 'delivered' };\n } catch (err) {\n // Network failure or per-attempt timeout: the write may or may not have landed; the dedupeKey\n // makes a retry safe either way.\n return { kind: 'transient', detail: (err as Error).message };\n }\n}\n\n/**\n * The calling service's own identity (`SERVICE_IDENTITY`, else `SERVICE_NAME`), as the gateway\n * client and the proactive identity helper read it. Undefined when neither is set.\n */\nfunction trackerServiceIdentity(): string | undefined {\n return (process.env['SERVICE_IDENTITY'] || process.env['SERVICE_NAME'])?.trim() || undefined;\n}\n\n/**\n * Headers that prove who is writing a platform-level activity row (BOFF-17562).\n *\n * wspace-activity-svc records an activity without a workspace only from a service whose identity\n * the internal gateway verified from a signed `service-v1` JWT; header-only callers are refused.\n * For such a write the tracker therefore presents a short-lived service JWT minted for the calling\n * service. The gateway then binds the actor to that service, so the original actor is kept as\n * `onBehalfOf` (see {@link fireActivityLog}). Returns no header when the service has no identity\n * or no `SERVICE_JWT_SECRET`; the owner then refuses the write with a clear, non-retryable error.\n */\nasync function platformWriteAuthorization(): Promise<Record<string, string>> {\n const identity = trackerServiceIdentity();\n if (!identity) return {};\n const token = await signServiceJwt(identity);\n return token ? { Authorization: `Bearer ${token}` } : {};\n}\n\n/**\n * Re-mint the platform-write token before each delivery attempt. The service JWT lives 60 s and\n * the retries can span more than that, so a token built once could expire before the last retry;\n * `signServiceJwt` returns its cached token while more than 10 s of it remain.\n */\nasync function withFreshAuthorization(headers: Record<string, string>): Promise<Record<string, string>> {\n if (!headers['Authorization']) return headers;\n return { ...headers, ...(await platformWriteAuthorization()) };\n}\n\n/** Log label naming the operation, the action and the calling service of an activity write. */\nfunction describeActivityWrite(operation: string, input: Record<string, unknown>): string {\n const action = typeof input['action'] === 'string' ? input['action'] : 'unknown';\n return `\"${operation}\" (action ${action}, service ${trackerServiceIdentity() ?? 'unknown'})`;\n}\n\n/**\n * Request headers for one activity write. A workspace write carries the caller as the actor and\n * the workspace header. A platform-level write to the workspace owner (no workspace) also carries\n * the calling service's JWT (BOFF-17562); the gateway then binds the actor to that service, so the\n * original actor is kept in `input.onBehalfOf` unless the caller set one.\n */\nasync function buildActivityHeaders(\n options: UnifiedTrackingOptions,\n input: Record<string, unknown>,\n layer: ActivityLayer\n): Promise<Record<string, string>> {\n const headers: Record<string, string> = {\n 'Content-Type': 'application/json',\n };\n\n // Forward actor context if available\n if (options.userId) {\n headers['x-actor-id'] = options.userId;\n headers['x-actor-type'] = 'service';\n }\n\n const workspaceId = options.workspaceId ?? options.activityOptions?.workspaceId;\n if (workspaceId) {\n headers['x-workspace-id'] = workspaceId;\n return headers;\n }\n if (layer !== 'wspace') return headers;\n\n const authorization = await platformWriteAuthorization();\n if (!authorization['Authorization']) return headers;\n Object.assign(headers, authorization);\n if (input['onBehalfOf'] === undefined && options.userId && options.userId !== trackerServiceIdentity()) {\n input['onBehalfOf'] = options.userId;\n }\n return headers;\n}\n\n/**\n * Fire-and-forget activity log via GraphQL, retrying transient failures.\n * Never throws — logs errors and continues.\n */\nasync function fireActivityLog(\n gatewayUrl: string,\n options: UnifiedTrackingOptions,\n layer: ActivityLayer\n): Promise<void> {\n try {\n const input = buildActivityInput(options, layer);\n\n // Strip undefined values\n for (const key of Object.keys(input)) {\n if (input[key] === undefined) delete input[key];\n }\n\n const headers = await buildActivityHeaders(options, input, layer);\n\n const operation = describeActivityWrite(options.operationName ?? 'operation', input);\n // Serialize once, outside the retry loop: a payload JSON cannot encode (bigint, cycles) is a\n // deterministic failure and must not be retried as if it were a network error.\n let body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input } });\n let attributionStripped = false;\n const maxAttempts = activityRetryDelaysMs.length + 1;\n for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {\n const outcome = await attemptActivityDelivery(gatewayUrl, await withFreshAuthorization(headers), body);\n if (outcome.kind === 'delivered') {\n if (attempt > 1) {\n logger.info(`[trackOperation] Activity log delivered on attempt ${attempt}: ${operation}`);\n }\n return;\n }\n if (\n outcome.kind === 'rejected' &&\n !attributionStripped &&\n ATTRIBUTION_FIELDS.some((field) => field in input) &&\n isUnknownAttributionFieldRejection(outcome.detail)\n ) {\n // The owner predates the attribution fields (rollout skew). Losing the audit row would\n // be worse than losing who-acted on it, so resend once without them.\n attributionStripped = true;\n const stripped = { ...input };\n for (const field of ATTRIBUTION_FIELDS) delete stripped[field];\n body = JSON.stringify({ query: LOG_ACTIVITY_MUTATION, variables: { input: stripped } });\n logger.warn(\n `[trackOperation] ${layer}-activity subgraph does not accept the actor attribution fields yet; resending ${operation} without them`\n );\n attempt -= 1;\n continue;\n }\n if (outcome.kind === 'rejected') {\n logger.error(\n `[trackOperation] Activity log REJECTED by ${layer}-activity subgraph for ${operation}: ${outcome.detail}`\n );\n return;\n }\n const delay = activityRetryDelaysMs[attempt - 1];\n if (delay === undefined) {\n // An audit record is about to be lost: this must be visible at error level.\n logger.error(\n `[trackOperation] Activity log failed after ${attempt} attempts for ${operation}: ${outcome.detail}`\n );\n return;\n }\n logger.warn(\n `[trackOperation] Activity log attempt ${attempt} failed for ${operation}: ${outcome.detail}; retrying in ${delay}ms`\n );\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n } catch (err) {\n // Fire-and-forget: log but never throw\n logger.warn(`[trackOperation] Activity log failed: ${(err as Error).message}`);\n }\n}\n\n// ---------------------------------------------------------------------------\n// Main trackOperation function\n// ---------------------------------------------------------------------------\n\n/**\n * Simple tracker class with auto-promoting behavior\n */\nexport class UnifiedTrackerStub {\n private static instance: UnifiedTrackerStub;\n\n static getInstance(): UnifiedTrackerStub {\n if (!UnifiedTrackerStub.instance) {\n UnifiedTrackerStub.instance = new UnifiedTrackerStub();\n }\n return UnifiedTrackerStub.instance;\n }\n\n async track(event: TrackingEvent): Promise<void> {\n markExplicitActivity();\n const gatewayUrl = getGatewayUrl();\n if (gatewayUrl) {\n await fireActivityLog(\n gatewayUrl,\n {\n operationName: event.eventType,\n userId: event.userId,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n activityOptions: {\n activityType: event.eventType,\n metadata: event.metadata,\n workspaceId: event.workspaceId,\n resourceType: event.entityType,\n resourceId: event.entityId,\n enabled: true,\n },\n },\n getGatewayLayer()\n );\n } else {\n logger.debug('[UnifiedTracker:Stub]', event.eventType, event.entityType, event.entityId);\n }\n }\n\n async trackBatch(events: TrackingEvent[]): Promise<void> {\n for (const event of events) {\n await this.track(event);\n }\n }\n}\n\nexport const trackerStub = UnifiedTrackerStub.getInstance();\n\n/**\n * Unified tracking function — auto-promoting\n *\n * When a gateway URL is configured (WSPACE_INT_GATEWAY_URL or GLOBAL_INT_GATEWAY_URL),\n * this function makes real fire-and-forget GraphQL calls for activity logging.\n * When no gateway URL is configured, it falls back to debug-level logging (stub mode).\n *\n * RBAC checks are NOT performed here — they are handled by gateway @rbac directives.\n * The rbacCheck option is accepted for interface compatibility but not enforced.\n *\n * @param options - Tracking options\n * @returns Always returns true (never blocks the calling operation)\n */\nexport async function trackOperation(options: UnifiedTrackingOptions): Promise<boolean> {\n const { operationName, userId, success = true } = options;\n const gatewayUrl = getGatewayUrl();\n const activityEnabled = options.activityOptions?.enabled !== false;\n\n // An explicit activity write: the mutation-audit backstop must not add a second row for this\n // operation. Marked in stub mode too, so dedupe behaves the same locally as when deployed.\n if (activityEnabled) markExplicitActivity();\n\n if (!gatewayUrl) {\n // Stub mode — debug log only\n logger.debug(`[trackOperation:Stub] ${operationName} for user ${userId} - success: ${success}`);\n return true;\n }\n\n // Real mode — fire-and-forget activity logging\n if (activityEnabled) {\n // Do NOT await — fire and forget so we never block the caller\n void fireActivityLog(gatewayUrl, options, getGatewayLayer());\n } else {\n logger.debug(`[trackOperation] ${operationName} for user ${userId} - activity disabled, skipping`);\n }\n\n return true;\n}\n\n/**\n * Product tracker type definition\n */\nexport type ProductTracker = {\n track: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n freeUp: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackActivityOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackUsageOnly: (operationName: string, additionalOptions?: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n trackCustom: (operationName: string, additionalOptions: Partial<UnifiedTrackingOptions>) => Promise<boolean>;\n productId: string;\n userId: string;\n billingAccountId: string | undefined;\n defaultContext: Partial<UnifiedTrackingOptions> | undefined;\n};\n\n/**\n * Create a product-scoped tracker (auto-promoting implementation)\n *\n * @param productId - Product identifier\n * @param userId - User identifier\n * @param billingAccountId - Optional billing account ID\n * @param defaultContext - Optional default tracking context\n * @returns Product tracker instance\n */\nexport function createProductTracker(\n productId: string,\n userId: string,\n billingAccountId?: string,\n defaultContext?: Partial<UnifiedTrackingOptions>\n): ProductTracker {\n return {\n async track(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n async freeUp(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: {\n ...defaultContext?.activityOptions,\n ...additionalOptions?.activityOptions,\n activityType: 'free_up',\n },\n });\n },\n async trackActivityOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { ...defaultContext?.activityOptions, ...additionalOptions?.activityOptions, enabled: true },\n usageOptions: { enabled: false },\n });\n },\n async trackUsageOnly(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n activityOptions: { enabled: false },\n usageOptions: { ...defaultContext?.usageOptions, ...additionalOptions?.usageOptions, enabled: true },\n });\n },\n async trackCustom(operationName, additionalOptions): Promise<boolean> {\n return trackOperation({\n ...defaultContext,\n productId,\n operationName,\n userId,\n ...additionalOptions,\n });\n },\n productId,\n userId,\n billingAccountId,\n defaultContext,\n };\n}\n\n/**\n * Constants for tracking\n */\nexport const UNIFIED_TRACKER_CONSTANTS = {\n DEFAULT_PRODUCT_ID: 'module',\n OPERATIONS: {} as const,\n PRODUCTS: {} as const,\n} as const;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwBA,MAAa,4BAA4B;;AAKzC,MAAa,sBAAsB;AACnC,MAAa,8BAA8B;AAC3C,MAAa,kCAAkC;;AAG/C,MAAM,yBAAyB;AAW/B,SAAS,cAAc,OAAoC;CACzD,OAAO,OAAO,UAAU,YAAY,uBAAuB,KAAK,KAAK,IAAI,QAAQ;AACnF;;;;;;AAOA,SAAgB,8BACd,aACA,oBACA,wBACyC;CACzC,IAAI,gCAA2C,OAAO;CACtD,MAAM,YAAY,cAAc,kBAAkB;CAClD,IAAI,CAAC,WAAW,OAAO;CACvB,MAAM,gBAAgB,cAAc,sBAAsB;CAC1D,OAAO;EACL,aAAa;EACb,oBAAoB;EACpB,GAAI,gBAAgB,EAAE,wBAAwB,cAAc,IAAI,CAAC;CACnE;AACF;;;;;AAMA,SAAgB,6BACd,WACyC;CACzC,OAAO,8BACL,UAAU,mBAAmB,GAC7B,UAAU,2BAA2B,GACrC,UAAU,+BAA+B,CAC3C;AACF;;AAGA,SAAgB,gCAAgC,OAAyD;CACvG,IAAI,OAAO,UAAU,YAAY,UAAU,MAAM,OAAO;CACxD,MAAM,SAAS;CACf,OAAO,8BACL,OAAO,gBACP,OAAO,uBACP,OAAO,yBACT;AACF;;;;;;;;;;;;;;;;;;;;ACKA,MAAM,sCAA2C,IAAI,IAAsB;CAAC;CAAQ;CAAO;CAAW;AA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