@burdenoff/be-sdk 2026.1027.3 → 2026.1028.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.
@@ -1,4 +1,4 @@
1
- import { getWorkspaceContext } from './chunk-3Z2VRCT6.js';
1
+ import { getWorkspaceContext, getScopedWorkspaceContext } from './chunk-E4QNLVY4.js';
2
2
  import { logger } from './chunk-RU266375.js';
3
3
  import { __name } from './chunk-XE4OXN2W.js';
4
4
  import { AsyncLocalStorage } from 'async_hooks';
@@ -26,6 +26,41 @@ function suppressMutationAudit() {
26
26
  if (scope) scope.suppressed = true;
27
27
  }
28
28
  __name(suppressMutationAudit, "suppressMutationAudit");
29
+
30
+ // src/activity/assistant-session.ts
31
+ var AI_ASSISTANT_ACTOR_ORIGIN = "ai_assistant";
32
+ var ACTOR_ORIGIN_HEADER = "x-actor-origin";
33
+ var ASSISTANT_SESSION_ID_HEADER = "x-assistant-session-id";
34
+ var ASSISTANT_CORRELATION_ID_HEADER = "x-assistant-correlation-id";
35
+ var ATTRIBUTION_ID_PATTERN = /^[A-Za-z0-9_-]{1,128}$/;
36
+ function attributionId(value) {
37
+ return typeof value === "string" && ATTRIBUTION_ID_PATTERN.test(value) ? value : void 0;
38
+ }
39
+ __name(attributionId, "attributionId");
40
+ function toAssistantSessionAttribution(actorOrigin, assistantSessionId, assistantCorrelationId) {
41
+ if (actorOrigin !== AI_ASSISTANT_ACTOR_ORIGIN) return void 0;
42
+ const sessionId = attributionId(assistantSessionId);
43
+ if (!sessionId) return void 0;
44
+ const correlationId = attributionId(assistantCorrelationId);
45
+ return {
46
+ actorOrigin: AI_ASSISTANT_ACTOR_ORIGIN,
47
+ assistantSessionId: sessionId,
48
+ ...correlationId ? {
49
+ assistantCorrelationId: correlationId
50
+ } : {}
51
+ };
52
+ }
53
+ __name(toAssistantSessionAttribution, "toAssistantSessionAttribution");
54
+ function parseAssistantSessionHeaders(getHeader) {
55
+ return toAssistantSessionAttribution(getHeader(ACTOR_ORIGIN_HEADER), getHeader(ASSISTANT_SESSION_ID_HEADER), getHeader(ASSISTANT_CORRELATION_ID_HEADER));
56
+ }
57
+ __name(parseAssistantSessionHeaders, "parseAssistantSessionHeaders");
58
+ function readAssistantSessionAttribution(value) {
59
+ if (typeof value !== "object" || value === null) return void 0;
60
+ const record = value;
61
+ return toAssistantSessionAttribution(record["actorOrigin"], record["assistantSessionId"], record["assistantCorrelationId"]);
62
+ }
63
+ __name(readAssistantSessionAttribution, "readAssistantSessionAttribution");
29
64
  var TRACKED_ACTOR_TYPES = /* @__PURE__ */ new Set([
30
65
  "user",
31
66
  "app",
@@ -39,20 +74,34 @@ __name(isTrackedActorType, "isTrackedActorType");
39
74
  var _gatewayUrl;
40
75
  var _gatewayLayer;
41
76
  var _gatewayUrlResolved = false;
77
+ function declaredServiceLayer() {
78
+ const layer = process.env["SERVICE_LAYER"];
79
+ if (layer === "global" || layer === "wspace") return layer;
80
+ const name = process.env["SERVICE_NAME"] ?? "";
81
+ if (name.startsWith("global-")) return "global";
82
+ if (name.startsWith("wspace-")) return "wspace";
83
+ return void 0;
84
+ }
85
+ __name(declaredServiceLayer, "declaredServiceLayer");
42
86
  function getGatewayUrl() {
43
87
  if (!_gatewayUrlResolved) {
44
88
  const wspaceUrl = process.env["WSPACE_INT_GATEWAY_URL"];
45
89
  const globalUrl = process.env["GLOBAL_INT_GATEWAY_URL"];
46
- if (wspaceUrl) {
47
- _gatewayUrl = wspaceUrl;
48
- _gatewayLayer = "wspace";
49
- } else if (globalUrl) {
90
+ const declared = declaredServiceLayer();
91
+ const useGlobal = Boolean(globalUrl) && (declared === "global" || !wspaceUrl);
92
+ if (useGlobal) {
50
93
  _gatewayUrl = globalUrl;
51
94
  _gatewayLayer = "global";
95
+ } else if (wspaceUrl) {
96
+ _gatewayUrl = wspaceUrl;
97
+ _gatewayLayer = "wspace";
52
98
  } else {
53
99
  _gatewayUrl = void 0;
54
100
  _gatewayLayer = void 0;
55
101
  }
102
+ if (declared && _gatewayLayer && declared !== _gatewayLayer) {
103
+ logger.warn(`[trackOperation] ${declared} service has no ${declared === "global" ? "GLOBAL" : "WSPACE"}_INT_GATEWAY_URL; activity goes to the ${_gatewayLayer} activity owner instead`);
104
+ }
56
105
  _gatewayUrlResolved = true;
57
106
  if (_gatewayUrl) {
58
107
  logger.info(`[trackOperation] Real tracking enabled via ${_gatewayLayer} gateway: ${_gatewayUrl}`);
@@ -112,9 +161,19 @@ function resolveOnBehalfOf(options) {
112
161
  return typeof fromContext === "string" && fromContext.length > 0 ? fromContext : void 0;
113
162
  }
114
163
  __name(resolveOnBehalfOf, "resolveOnBehalfOf");
164
+ function resolveAssistantSession(options) {
165
+ if (options.assistantSession !== void 0) return readAssistantSessionAttribution(options.assistantSession);
166
+ const fromContext = readAssistantSessionAttribution(readRecord(options.context)?.["assistantSession"]);
167
+ if (fromContext) return fromContext;
168
+ return readAssistantSessionAttribution(getScopedWorkspaceContext()?.assistantSession);
169
+ }
170
+ __name(resolveAssistantSession, "resolveAssistantSession");
115
171
  var ATTRIBUTION_FIELDS = [
116
172
  "actorType",
117
- "onBehalfOf"
173
+ "onBehalfOf",
174
+ "actorOrigin",
175
+ "assistantSessionId",
176
+ "assistantCorrelationId"
118
177
  ];
119
178
  function isUnknownAttributionFieldRejection(detail) {
120
179
  return ATTRIBUTION_FIELDS.some((field) => detail.includes(`"${field}"`) && /not defined|unknown field|is not defined by type/i.test(detail));
@@ -137,6 +196,7 @@ function buildActivityInput(options, layer) {
137
196
  errorMessage: options.errorMessage
138
197
  } : {}
139
198
  };
199
+ const assistantSession = layer === "global" ? resolveAssistantSession(options) : void 0;
140
200
  const input = layer === "global" ? {
141
201
  action,
142
202
  // Required (non-nullable) on global-activity-svc.
@@ -148,7 +208,11 @@ function buildActivityInput(options, layer) {
148
208
  actorId: options.userId,
149
209
  tenantId: options.tenantId,
150
210
  workspaceId,
151
- metadata
211
+ metadata,
212
+ // AI-originated change (BOFF-9649): which assistant session made it.
213
+ actorOrigin: assistantSession?.actorOrigin,
214
+ assistantSessionId: assistantSession?.assistantSessionId,
215
+ assistantCorrelationId: assistantSession?.assistantCorrelationId
152
216
  } : {
153
217
  action,
154
218
  description,
@@ -292,7 +356,7 @@ async function fireActivityLog(gatewayUrl, options, layer) {
292
356
  input: stripped
293
357
  }
294
358
  });
295
- logger.warn(`[trackOperation] ${layer}-activity subgraph does not accept actorType/onBehalfOf yet; resending "${operation}" without them`);
359
+ logger.warn(`[trackOperation] ${layer}-activity subgraph does not accept the actor attribution fields yet; resending "${operation}" without them`);
296
360
  attempt -= 1;
297
361
  continue;
298
362
  }
@@ -452,6 +516,6 @@ var UNIFIED_TRACKER_CONSTANTS = {
452
516
  PRODUCTS: {}
453
517
  };
454
518
 
455
- export { UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, createExplicitActivityScope, createProductTracker, isTrackedActorType, markExplicitActivity, runInExplicitActivityScope, suppressMutationAudit, trackOperation, trackerStub };
456
- //# sourceMappingURL=chunk-Q3SWU4VF.js.map
457
- //# sourceMappingURL=chunk-Q3SWU4VF.js.map
519
+ export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, createExplicitActivityScope, createProductTracker, isTrackedActorType, markExplicitActivity, parseAssistantSessionHeaders, readAssistantSessionAttribution, resolveAssistantSession, runInExplicitActivityScope, suppressMutationAudit, toAssistantSessionAttribution, trackOperation, trackerStub };
520
+ //# sourceMappingURL=chunk-TANAOLAV.js.map
521
+ //# sourceMappingURL=chunk-TANAOLAV.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/activity/explicit-activity-scope.ts","../src/activity/assistant-session.ts","../src/tracker/stub.ts"],"names":["scopeStorage","AsyncLocalStorage","createExplicitActivityScope","explicitCount","suppressed","runInExplicitActivityScope","scope","fn","run","markExplicitActivity","getStore","suppressMutationAudit","AI_ASSISTANT_ACTOR_ORIGIN","ACTOR_ORIGIN_HEADER","ASSISTANT_SESSION_ID_HEADER","ASSISTANT_CORRELATION_ID_HEADER","ATTRIBUTION_ID_PATTERN","attributionId","value","test","undefined","toAssistantSessionAttribution","actorOrigin","assistantSessionId","assistantCorrelationId","sessionId","correlationId","parseAssistantSessionHeaders","getHeader","readAssistantSessionAttribution","record","TRACKED_ACTOR_TYPES","Set","isTrackedActorType","has","_gatewayUrl","_gatewayLayer","_gatewayUrlResolved","declaredServiceLayer","layer","process","env","name","startsWith","getGatewayUrl","wspaceUrl","globalUrl","declared","useGlobal","Boolean","logger","warn","info","debug","getGatewayLayer","LOG_ACTIVITY_MUTATION","deriveResource","options","explicit","activityOptions","resourceType","trim","length","op","operationName","head","split","readRecord","resolveTrackedActorType","actorType","context","actor","fromContext","ambient","getWorkspaceContext","resolveOnBehalfOf","onBehalfOf","resolveAssistantSession","assistantSession","getScopedWorkspaceContext","ATTRIBUTION_FIELDS","isUnknownAttributionFieldRejection","detail","some","field","includes","buildActivityInput","actOpts","action","activityType","description","resourceId","workspaceId","metadata","success","errorMessage","input","resource","userId","actorId","tenantId","targetUserId","teamId","productId","dedupeKey","randomUUID","ACTIVITY_ATTEMPT_TIMEOUT_MS","DEFAULT_ACTIVITY_RETRY_DELAYS_MS","activityRetryDelaysMs","RETRYABLE_HTTP_STATUSES","RETRYABLE_GRAPHQL_CODES","classifyGraphQLErrors","errors","map","e","message","join","slice","transient","every","code","extensions","kind","attemptActivityDelivery","gatewayUrl","headers","body","response","fetch","method","signal","AbortSignal","timeout","ok","status","parsed","json","catch","err","fireActivityLog","key","Object","keys","operation","JSON","stringify","query","variables","attributionStripped","maxAttempts","attempt","outcome","stripped","error","delay","Promise","resolve","setTimeout","UnifiedTrackerStub","instance","getInstance","track","event","eventType","entityType","entityId","enabled","trackBatch","events","trackerStub","trackOperation","activityEnabled","createProductTracker","billingAccountId","defaultContext","additionalOptions","freeUp","trackActivityOnly","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AAAA,CAAYpH,eAAe+G,iBAAAA,EAAiB;AAChD,MAAA,OAAOL,cAAAA,CAAe;QACpB,GAAGI,cAAAA;AACHvE,QAAAA,SAAAA;AACAvC,QAAAA,aAAAA;AACAkC,QAAAA,MAAAA;QACA,GAAG6E;OACL,CAAA;AACF,IAAA,CAAA;AACAxE,IAAAA,SAAAA;AACAL,IAAAA,MAAAA;AACA2E,IAAAA,gBAAAA;AACAC,IAAAA;AACF,GAAA;AACF;AAlEgBF,MAAAA,CAAAA,oBAAAA,EAAAA,sBAAAA,CAAAA;AAuET,IAAMS,yBAAAA,GAA4B;EACvCC,kBAAAA,EAAoB,QAAA;AACpBC,EAAAA,UAAAA,EAAY,EAAC;AACbC,EAAAA,QAAAA,EAAU;AACZ","file":"chunk-TANAOLAV.js","sourcesContent":["/**\n * Explicit-activity scope\n *\n * Lets the mutation-audit backstop (`createMutationAuditPlugin` in\n * `@burdenoff/be-sdk/server`) know whether a GraphQL operation already wrote an\n * activity row through an explicit call (`trackOperation`, `trackerStub.track`,\n * `ActivityModule.log`, or a service's own `logAudit` wrapper over them). When it\n * did, the backstop skips its generic `graphql.mutation` row so the activity feed\n * never carries two rows for one mutation.\n *\n * The scope is entered with `AsyncLocalStorage.run()` around the operation's\n * execute function. `run()` (unlike `enterWith()`) propagates through every\n * promise continuation started inside it, including fire-and-forget calls made\n * by resolvers, so concurrent requests never see each other's marks.\n *\n * Outside a scope (background jobs, event consumers, REST handlers) every\n * function here is a no-op.\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\n\n/** Per-operation record of explicit activity writes. */\nexport interface ExplicitActivityScope {\n /** Number of explicit activity writes made while the operation executed. */\n explicitCount: number;\n /** True once `suppressMutationAudit()` was called for this operation. */\n suppressed: boolean;\n}\n\nconst scopeStorage = new AsyncLocalStorage<ExplicitActivityScope>();\n\n/** Create a fresh, unmarked scope. */\nexport function createExplicitActivityScope(): ExplicitActivityScope {\n return { explicitCount: 0, suppressed: false };\n}\n\n/** Run `fn` with `scope` as the active explicit-activity scope. */\nexport function runInExplicitActivityScope<T>(scope: ExplicitActivityScope, fn: () => T): T {\n return scopeStorage.run(scope, fn);\n}\n\n/** The active scope, or undefined outside a GraphQL operation that mounts the backstop. */\nexport function getExplicitActivityScope(): ExplicitActivityScope | undefined {\n return scopeStorage.getStore();\n}\n\n/**\n * Record that an explicit activity write happened in the current operation.\n * Called by the SDK's own activity writers; services never need to call it.\n */\nexport function markExplicitActivity(): void {\n const scope = scopeStorage.getStore();\n if (scope) scope.explicitCount += 1;\n}\n\n/**\n * Tell the mutation-audit backstop not to write its generic row for the current\n * operation.\n *\n * Use it in a resolver whose audit trail goes through a path the SDK cannot see\n * (for example a direct call to the activity subgraph), or for a mutation that\n * must deliberately leave no activity row. Has no effect outside an operation\n * that mounts the backstop.\n */\nexport function suppressMutationAudit(): void {\n const scope = scopeStorage.getStore();\n if (scope) scope.suppressed = true;\n}\n","/**\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';\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' }\n | { kind: 'rejected'; detail: string }\n | { 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 * 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 actOpts = options.activityOptions;\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: 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 if (options.workspaceId ?? actOpts?.workspaceId) {\n headers['x-workspace-id'] = (options.workspaceId ?? actOpts?.workspaceId) as string;\n }\n\n const operation = options.operationName ?? 'operation';\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, 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"]}
@@ -1,9 +1,10 @@
1
- export { E as EvaluationContext, F as FeatureFlagProvider, a as FeatureFlagProviderConfig, b as FlagEvaluation, c as FlagType, G as GatedOperationType, O as OperationsFlagGatePluginOptions, R as ResolutionDetails, d as createOperationsFlagGatePlugin } from '../index-Rc5EphmY.js';
2
- import '../types-C-6m9NoG.js';
1
+ export { E as EvaluationContext, F as FeatureFlagProvider, a as FeatureFlagProviderConfig, b as FlagEvaluation, c as FlagType, G as GatedOperationType, O as OperationsFlagGatePluginOptions, R as ResolutionDetails, d as createOperationsFlagGatePlugin } from '../index-B2YkcG0J.js';
2
+ import '../types-DLFCJD3D.js';
3
3
  import 'graphql';
4
4
  import 'graphql-yoga';
5
5
  import '../client-CCXpAZ2r.js';
6
6
  import '@prisma/adapter-pg';
7
7
  import 'pg';
8
- import '../workspace-extension-DiNiTLa3.js';
8
+ import '../workspace-extension-BGwTOV_r.js';
9
+ import '../assistant-session-CJZhF4D6.js';
9
10
  import '../types-C8TbSdEj.js';
@@ -1,4 +1,4 @@
1
- import { Y as YogaPlugin } from './types-C-6m9NoG.js';
1
+ import { Y as YogaPlugin } from './types-DLFCJD3D.js';
2
2
 
3
3
  type FlagType = 'BOOLEAN' | 'STRING' | 'NUMBER' | 'JSON';
4
4
  interface EvaluationContext {
@@ -1,6 +1,6 @@
1
1
  import { P as PrismaClientBase, b as PrismaClientWrapper, c as PrismaClientConfig, a as PrismaClientConstructorOptions, D as DatabaseReturnType, d as DatabaseHealth, C as ConnectionState, e as PrismaEvent, f as PrismaLogDefinition, g as PrismaLogEvent, h as PrismaLogLevel, i as PrismaQueryEvent, j as PrismaTransactionOptions, k as configurePrismaLogging, l as createConnectionPool, m as createPrismaAdapter, n as createPrismaClient, o as ensureServiceApplicationName, p as installAcquireRetry, q as isTransientAcquireError } from './client-CCXpAZ2r.js';
2
2
  import { G as GraphEventEmitter } from './prisma-extension-gYhYriA0.js';
3
- import { W as WorkspaceExtensionConfig, C as CallerTransaction, P as PrismaQueryInternalParams, R as RawPrismaForCallerTransaction, T as TransactionContextStatement, a as WorkspaceContext, b as addWorkspaceExtension, c as buildTransactionContextStatement, d as defaultWorkspaceExtensionConfig, g as getCallerTransaction, e as getWorkspaceContext, i as injectCreateFields, f as injectWhereWorkspaceId, m as maybeSetRlsGuc, h as maybeTagConnection, r as resetCallerTransactionStateForTests, j as runOperationInCallerTransaction, k as runOperationWithRlsGuc, s as setWorkspaceContext, w as withWorkspaceContext, l as withWorkspaceContextSync } from './workspace-extension-DiNiTLa3.js';
3
+ import { W as WorkspaceExtensionConfig, C as CallerTransaction, P as PrismaQueryInternalParams, R as RawPrismaForCallerTransaction, T as TransactionContextStatement, a as WorkspaceContext, b as addWorkspaceExtension, c as buildTransactionContextStatement, d as defaultWorkspaceExtensionConfig, g as getCallerTransaction, e as getScopedWorkspaceContext, f as getWorkspaceContext, i as injectCreateFields, h as injectWhereWorkspaceId, m as maybeSetRlsGuc, j as maybeTagConnection, r as resetCallerTransactionStateForTests, k as runOperationInCallerTransaction, l as runOperationWithRlsGuc, s as setWorkspaceContext, w as withWorkspaceContext, n as withWorkspaceContextSync } from './workspace-extension-BGwTOV_r.js';
4
4
 
5
5
  interface DatabaseClientConfig extends PrismaClientConfig {
6
6
  productName: string;
@@ -169,6 +169,7 @@ declare const index_getDatabaseStats: typeof getDatabaseStats;
169
169
  declare const index_getDatabaseVersion: typeof getDatabaseVersion;
170
170
  declare const index_getDb: typeof getDb;
171
171
  declare const index_getModelFields: typeof getModelFields;
172
+ declare const index_getScopedWorkspaceContext: typeof getScopedWorkspaceContext;
172
173
  declare const index_getWorkspaceContext: typeof getWorkspaceContext;
173
174
  declare const index_hasModel: typeof hasModel;
174
175
  declare const index_initializeDatabase: typeof initializeDatabase;
@@ -194,7 +195,7 @@ declare const index_toContextJson: typeof toContextJson;
194
195
  declare const index_withWorkspaceContext: typeof withWorkspaceContext;
195
196
  declare const index_withWorkspaceContextSync: typeof withWorkspaceContextSync;
196
197
  declare namespace index {
197
- export { index_CallerTransaction as CallerTransaction, index_ConnectionState as ConnectionState, type index_ContextFilterInput as ContextFilterInput, type index_ContextWhereCondition as ContextWhereCondition, type index_DatabaseClient as DatabaseClient, type index_DatabaseClientConfig as DatabaseClientConfig, index_DatabaseHealth as DatabaseHealth, index_DatabaseReturnType as DatabaseReturnType, type index_FieldExtractionOptions as FieldExtractionOptions, type index_FieldExtractionResult as FieldExtractionResult, type index_InputJsonValue as InputJsonValue, type index_JsonValue as JsonValue, type index_ModelFieldsMap as ModelFieldsMap, type index_OperationContext as OperationContext, type index_PoolTuningEnv as PoolTuningEnv, index_PrismaClientBase as PrismaClientBase, index_PrismaClientConfig as PrismaClientConfig, index_PrismaClientConstructorOptions as PrismaClientConstructorOptions, index_PrismaClientWrapper as PrismaClientWrapper, index_PrismaEvent as PrismaEvent, type index_PrismaJsonFilter as PrismaJsonFilter, index_PrismaLogDefinition as PrismaLogDefinition, index_PrismaLogEvent as PrismaLogEvent, index_PrismaLogLevel as PrismaLogLevel, index_PrismaQueryEvent as PrismaQueryEvent, index_PrismaQueryInternalParams as PrismaQueryInternalParams, index_PrismaTransactionOptions as PrismaTransactionOptions, index_RawPrismaForCallerTransaction as RawPrismaForCallerTransaction, index_TransactionContextStatement as TransactionContextStatement, index_WorkspaceContext as WorkspaceContext, index_WorkspaceExtensionConfig as WorkspaceExtensionConfig, index_addWorkspaceExtension as addWorkspaceExtension, index_buildContextWhereClause as buildContextWhereClause, index_buildContextWhereConditions as buildContextWhereConditions, index_buildTransactionContextStatement as buildTransactionContextStatement, index_checkDatabaseHealth as checkDatabaseHealth, index_configurePrismaLogging as configurePrismaLogging, index_contextMatches as contextMatches, index_createConnectionPool as createConnectionPool, index_createContextFromSDK as createContextFromSDK, index_createDatabaseClient as createDatabaseClient, index_createDatabaseClientFromEnv as createDatabaseClientFromEnv, index_createPrismaAdapter as createPrismaAdapter, index_createPrismaClient as createPrismaClient, index_defaultWorkspaceExtensionConfig as defaultWorkspaceExtensionConfig, index_ensureServiceApplicationName as ensureServiceApplicationName, index_extractFieldsFromModel as extractFieldsFromModel, index_getAllModelNames as getAllModelNames, index_getCallerTransaction as getCallerTransaction, index_getDatabaseManager as getDatabaseManager, index_getDatabaseProductName as getDatabaseProductName, index_getDatabaseStats as getDatabaseStats, index_getDatabaseVersion as getDatabaseVersion, index_getDb as getDb, index_getModelFields as getModelFields, index_getWorkspaceContext as getWorkspaceContext, index_hasModel as hasModel, index_initializeDatabase as initializeDatabase, index_initializeDatabaseWithConfig as initializeDatabaseWithConfig, index_injectCreateFields as injectCreateFields, index_injectWhereWorkspaceId as injectWhereWorkspaceId, index_installAcquireRetry as installAcquireRetry, index_isDatabaseInitialized as isDatabaseInitialized, index_isTransientAcquireError as isTransientAcquireError, index_loadGeneratedFields as loadGeneratedFields, index_maybeSetRlsGuc as maybeSetRlsGuc, index_maybeTagConnection as maybeTagConnection, index_mergeContext as mergeContext, index_parseContext as parseContext, index_resetCallerTransactionStateForTests as resetCallerTransactionStateForTests, index_resetDatabaseManager as resetDatabaseManager, index_resolvePoolTuningFromEnv as resolvePoolTuningFromEnv, index_runOperationInCallerTransaction as runOperationInCallerTransaction, index_runOperationWithRlsGuc as runOperationWithRlsGuc, index_setWorkspaceContext as setWorkspaceContext, index_testConnection as testConnection, index_toContextJson as toContextJson, index_withWorkspaceContext as withWorkspaceContext, index_withWorkspaceContextSync as withWorkspaceContextSync };
198
+ export { index_CallerTransaction as CallerTransaction, index_ConnectionState as ConnectionState, type index_ContextFilterInput as ContextFilterInput, type index_ContextWhereCondition as ContextWhereCondition, type index_DatabaseClient as DatabaseClient, type index_DatabaseClientConfig as DatabaseClientConfig, index_DatabaseHealth as DatabaseHealth, index_DatabaseReturnType as DatabaseReturnType, type index_FieldExtractionOptions as FieldExtractionOptions, type index_FieldExtractionResult as FieldExtractionResult, type index_InputJsonValue as InputJsonValue, type index_JsonValue as JsonValue, type index_ModelFieldsMap as ModelFieldsMap, type index_OperationContext as OperationContext, type index_PoolTuningEnv as PoolTuningEnv, index_PrismaClientBase as PrismaClientBase, index_PrismaClientConfig as PrismaClientConfig, index_PrismaClientConstructorOptions as PrismaClientConstructorOptions, index_PrismaClientWrapper as PrismaClientWrapper, index_PrismaEvent as PrismaEvent, type index_PrismaJsonFilter as PrismaJsonFilter, index_PrismaLogDefinition as PrismaLogDefinition, index_PrismaLogEvent as PrismaLogEvent, index_PrismaLogLevel as PrismaLogLevel, index_PrismaQueryEvent as PrismaQueryEvent, index_PrismaQueryInternalParams as PrismaQueryInternalParams, index_PrismaTransactionOptions as PrismaTransactionOptions, index_RawPrismaForCallerTransaction as RawPrismaForCallerTransaction, index_TransactionContextStatement as TransactionContextStatement, index_WorkspaceContext as WorkspaceContext, index_WorkspaceExtensionConfig as WorkspaceExtensionConfig, index_addWorkspaceExtension as addWorkspaceExtension, index_buildContextWhereClause as buildContextWhereClause, index_buildContextWhereConditions as buildContextWhereConditions, index_buildTransactionContextStatement as buildTransactionContextStatement, index_checkDatabaseHealth as checkDatabaseHealth, index_configurePrismaLogging as configurePrismaLogging, index_contextMatches as contextMatches, index_createConnectionPool as createConnectionPool, index_createContextFromSDK as createContextFromSDK, index_createDatabaseClient as createDatabaseClient, index_createDatabaseClientFromEnv as createDatabaseClientFromEnv, index_createPrismaAdapter as createPrismaAdapter, index_createPrismaClient as createPrismaClient, index_defaultWorkspaceExtensionConfig as defaultWorkspaceExtensionConfig, index_ensureServiceApplicationName as ensureServiceApplicationName, index_extractFieldsFromModel as extractFieldsFromModel, index_getAllModelNames as getAllModelNames, index_getCallerTransaction as getCallerTransaction, index_getDatabaseManager as getDatabaseManager, index_getDatabaseProductName as getDatabaseProductName, index_getDatabaseStats as getDatabaseStats, index_getDatabaseVersion as getDatabaseVersion, index_getDb as getDb, index_getModelFields as getModelFields, index_getScopedWorkspaceContext as getScopedWorkspaceContext, index_getWorkspaceContext as getWorkspaceContext, index_hasModel as hasModel, index_initializeDatabase as initializeDatabase, index_initializeDatabaseWithConfig as initializeDatabaseWithConfig, index_injectCreateFields as injectCreateFields, index_injectWhereWorkspaceId as injectWhereWorkspaceId, index_installAcquireRetry as installAcquireRetry, index_isDatabaseInitialized as isDatabaseInitialized, index_isTransientAcquireError as isTransientAcquireError, index_loadGeneratedFields as loadGeneratedFields, index_maybeSetRlsGuc as maybeSetRlsGuc, index_maybeTagConnection as maybeTagConnection, index_mergeContext as mergeContext, index_parseContext as parseContext, index_resetCallerTransactionStateForTests as resetCallerTransactionStateForTests, index_resetDatabaseManager as resetDatabaseManager, index_resolvePoolTuningFromEnv as resolvePoolTuningFromEnv, index_runOperationInCallerTransaction as runOperationInCallerTransaction, index_runOperationWithRlsGuc as runOperationWithRlsGuc, index_setWorkspaceContext as setWorkspaceContext, index_testConnection as testConnection, index_toContextJson as toContextJson, index_withWorkspaceContext as withWorkspaceContext, index_withWorkspaceContextSync as withWorkspaceContextSync };
198
199
  }
199
200
 
200
201
  export { parseContext as A, resetDatabaseManager as B, type ContextFilterInput as C, type DatabaseClient as D, resolvePoolTuningFromEnv as E, type FieldExtractionOptions as F, testConnection as G, toContextJson as H, type InputJsonValue as I, type JsonValue as J, type ModelFieldsMap as M, type OperationContext as O, type PoolTuningEnv as P, type ContextWhereCondition as a, type DatabaseClientConfig as b, type FieldExtractionResult as c, type PrismaJsonFilter as d, buildContextWhereClause as e, buildContextWhereConditions as f, checkDatabaseHealth as g, contextMatches as h, index as i, createContextFromSDK as j, createDatabaseClient as k, createDatabaseClientFromEnv as l, extractFieldsFromModel as m, getAllModelNames as n, getDatabaseManager as o, getDatabaseProductName as p, getDatabaseStats as q, getDatabaseVersion as r, getDb as s, getModelFields as t, hasModel as u, initializeDatabase as v, initializeDatabaseWithConfig as w, isDatabaseInitialized as x, loadGeneratedFields as y, mergeContext as z };
@@ -1,6 +1,7 @@
1
1
  import { B as BurdenoffGraphQLClient } from './graphql-BUbw43Zx.js';
2
2
  import { a as SDKContext } from './index-CV3r9Taj.js';
3
3
  import { N as NotificationType } from './index-BKOBmdq7.js';
4
+ import { A as AssistantSessionAttribution } from './assistant-session-CJZhF4D6.js';
4
5
  import './explicit-activity-scope-CCoxVwAr.js';
5
6
 
6
7
  declare enum ActivityType {
@@ -298,6 +299,7 @@ interface UnifiedTrackingOptions {
298
299
  userId?: string;
299
300
  actorType?: TrackedActorType;
300
301
  onBehalfOf?: string;
302
+ assistantSession?: AssistantSessionAttribution;
301
303
  context?: unknown;
302
304
  rbacCheck?: RbacCheckOptions;
303
305
  activityOptions?: ActivityTrackingOptions;
@@ -313,6 +315,7 @@ interface UnifiedTrackingOptions {
313
315
  workspaceId?: string;
314
316
  tenantId?: string;
315
317
  }
318
+ declare function resolveAssistantSession(options: UnifiedTrackingOptions): AssistantSessionAttribution | undefined;
316
319
  declare class UnifiedTrackerStub {
317
320
  private static instance;
318
321
  static getInstance(): UnifiedTrackerStub;
@@ -443,4 +446,4 @@ declare class TrackerModule {
443
446
  trackBatch(operations: TrackOptions[]): Promise<TrackResult[]>;
444
447
  }
445
448
 
446
- export { ActivityModule as A, type ProductTracker as P, type RbacCheckOptions as R, TrackerModule as T, UsageModule as U, AGENT_ACTIVITY_ACTIONS as a, AGENT_ACTIVITY_RESOURCE_TYPE as b, type ActivityTrackingOptions as c, type AgentActivityAction as d, type AgentActivityOptions as e, type TrackOptions as f, type TrackResult as g, type TrackedActorType as h, type TrackingEvent as i, UNIFIED_TRACKER_CONSTANTS as j, UnifiedTrackerStub as k, type UnifiedTrackingOptions as l, UsageMetricType as m, type UsageTrackingOptions as n, createProductTracker as o, isTrackedActorType as p, trackOperation as q, trackerStub as r, trackAgentActivity as t };
449
+ export { ActivityModule as A, type ProductTracker as P, type RbacCheckOptions as R, TrackerModule as T, UsageModule as U, AGENT_ACTIVITY_ACTIONS as a, AGENT_ACTIVITY_RESOURCE_TYPE as b, type ActivityTrackingOptions as c, type AgentActivityAction as d, type AgentActivityOptions as e, type TrackOptions as f, type TrackResult as g, type TrackedActorType as h, type TrackingEvent as i, UNIFIED_TRACKER_CONSTANTS as j, UnifiedTrackerStub as k, type UnifiedTrackingOptions as l, UsageMetricType as m, type UsageTrackingOptions as n, createProductTracker as o, isTrackedActorType as p, trackOperation as q, resolveAssistantSession as r, trackerStub as s, trackAgentActivity as t };
package/dist/index.d.ts CHANGED
@@ -7,7 +7,7 @@ import { T as TenantNotificationsModule, a as NotificationsModule } from './inde
7
7
  export { t as Notifications } from './index-BKOBmdq7.js';
8
8
  import { RBACModule } from './rbac/index.js';
9
9
  export { LayerAwareRBACConfig, RBACDirectiveConfig, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './rbac/index.js';
10
- import { A as ActivityModule, U as UsageModule, T as TrackerModule } from './index-C135w4ur.js';
10
+ import { A as ActivityModule, U as UsageModule, T as TrackerModule } from './index-DJCb-l2J.js';
11
11
  import { DatabaseConfig, DatabaseModule } from './database/index.js';
12
12
  import { E as EventsModule, I as IEventPublisher } from './index-JTx7ZQHe.js';
13
13
  export { i as EventQueue } from './index-JTx7ZQHe.js';
@@ -27,7 +27,7 @@ export { i as Cache } from './index-BvkVcW8I.js';
27
27
  export { i as Middleware } from './index-DSOpj8DI.js';
28
28
  export { i as Observability } from './index-4gKQKZ2B.js';
29
29
  export { i as GraphQL } from './index-joONjwLt.js';
30
- export { i as Prisma } from './index-CL7koBpQ.js';
30
+ export { i as Prisma } from './index-BTMt4OjA.js';
31
31
  export { i as Utils } from './index-PaojfSdd.js';
32
32
  export { i as I18n, I as I18nCapableContext, T as Translator, c as createTranslator, g as getLanguage, a as getLocale, h as hasI18n, t } from './index-D4l1u8VR.js';
33
33
  export { i as Export } from './index-CWmH_-RZ.js';
@@ -37,20 +37,21 @@ export { i as Instrumentation } from './index-Coua7_P7.js';
37
37
  export { i as Layer } from './index-ffmipXSA.js';
38
38
  export { i as Crypto } from './index-e_18DzAg.js';
39
39
  export { i as Gateway } from './index-Dcq8OduH.js';
40
- export { i as FeatureFlags } from './index-Rc5EphmY.js';
40
+ export { i as FeatureFlags } from './index-B2YkcG0J.js';
41
41
  export { i as Captcha, R as RecaptchaVerifyOptions, a as RecaptchaVerifyResult, b as isCaptchaEnabled, v as verifyCaptcha, c as verifyCaptchaIfEnabled } from './index-B70b5mYS.js';
42
42
  export { i as Platform } from './index-DfYu1p9e.js';
43
43
  export { N as NAME_MAX_LENGTH, a as NAME_MIN_LENGTH, b as NameErrorCode, c as NameValidationResult, R as RbacCoverageError, d as RbacCoverageOptions, e as RbacCoverageReport, f as RbacCoverageSource, U as USERNAME_MAX_LENGTH, g as USERNAME_MIN_LENGTH, h as UserFieldError, i as UserFieldKey, j as UserFieldsValidationResult, k as UsernameErrorCode, l as UsernameValidationResult, V as ValidatedUserFields, m as Validation, n as analyzeRbacCoverage, o as assertRbacCoverage, p as lengthInCodePoints, v as validateName, q as validateUserFields, r as validateUsername } from './index-qwG_TaUg.js';
44
44
  export { E as EmitGeneration, P as PRODUCT_RENAMES, a as PRODUCT_RENAME_EMIT, b as PRODUCT_SLUG_ALIASES, i as ProductAlias, c as ProductRename, R as RENAME_CONCERNS, d as RenameConcern, e as billingIdVariants, f as emitBillingId, g as emitName, h as emitProductSlug, j as emitQuotaKey, k as emitRbacResource, l as emitTemplateKey, m as isLegacyName, n as isSameBillingId, o as isSameGraphQLName, p as isSameName, q as isSameProductSlug, r as isSameQuotaKey, s as isSameRbacResource, t as isSameTemplateKey, u as nameVariants, v as normalizeBillingId, w as normalizeGraphQLName, x as normalizeProductSlug, y as normalizeQuotaKey, z as normalizeRbacResource, A as normalizeTemplateKey, B as productSlugVariants, C as quotaKeyVariants, D as rbacResourceVariants, F as readRenamedEnv, G as templateKeyVariants, H as toCurrentName, I as toLegacyName } from './index-BuAj5nXg.js';
45
45
  export { C as CircuitBreakerConfig, h as DEFAULT_CIRCUIT_BREAKER_CONFIG, i as DEFAULT_GATEWAY_RETRY_CONFIG, D as DEFAULT_GATEWAY_ROUTING, b as DEFAULT_LAYER_RESOURCES, c as DEFAULT_LAYER_STREAMS, f as GatewayRequestHeaders, g as GatewayRetryConfig, G as GatewayRoutingConfig, L as LayerConfig, a as LayerFullConfig, d as LayerGatewayConfig, e as LayerResourceUrls, S as ServiceLayer } from './layer-Cv9vSwBx.js';
46
46
  export { S as ShutdownDisposable, d as disposeAll, g as getRegisteredDisposableCount, r as registerDisposable, u as unregisterDisposable } from './shutdown-registry-CW9LryO8.js';
47
- import './types-C-6m9NoG.js';
47
+ import './types-DLFCJD3D.js';
48
48
  import 'graphql';
49
49
  import 'graphql-yoga';
50
50
  import './client-CCXpAZ2r.js';
51
51
  import '@prisma/adapter-pg';
52
52
  import 'pg';
53
- import './workspace-extension-DiNiTLa3.js';
53
+ import './workspace-extension-BGwTOV_r.js';
54
+ import './assistant-session-CJZhF4D6.js';
54
55
  import './types-C8TbSdEj.js';
55
56
  import 'graphql-request';
56
57
  import '@envelop/core';
package/dist/index.js CHANGED
@@ -2,24 +2,25 @@ export { NAME_MAX_LENGTH, NAME_MIN_LENGTH, RbacCoverageError, USERNAME_MAX_LENGT
2
2
  export { sharing_exports as Sharing } from './chunk-DS3YMJ4X.js';
3
3
  export { tags_exports as Tags } from './chunk-PNWFTWBQ.js';
4
4
  export { TemporalClient, TemporalClientFactory, TemporalModule, TemporalWorker, TemporalWorkerFactory, TemporalWorkerManager } from './chunk-VXVLKRU6.js';
5
- import { ActivityModule, UsageModule, TrackerModule } from './chunk-V3GSTCVC.js';
6
- export { ActivityModule, TrackerModule, UsageModule } from './chunk-V3GSTCVC.js';
7
- export { init_exports as Init } from './chunk-E36LPO3K.js';
5
+ import { ActivityModule, UsageModule, TrackerModule } from './chunk-57GT6PJK.js';
6
+ export { ActivityModule, TrackerModule, UsageModule } from './chunk-57GT6PJK.js';
7
+ import './chunk-TANAOLAV.js';
8
+ export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
8
9
  import { TenantNotificationsModule, NotificationsModule } from './chunk-INAZ3PKF.js';
9
10
  export { tenant_notifications_exports as Notifications, NotificationsModule } from './chunk-INAZ3PKF.js';
10
11
  export { observability_exports as Observability } from './chunk-VAT66FJA.js';
11
12
  export { platform_exports as Platform } from './chunk-N2UT3ESH.js';
12
- export { prisma_exports as Prisma } from './chunk-YCPVIFDN.js';
13
+ export { prisma_exports as Prisma } from './chunk-QCOC2SF3.js';
14
+ import './chunk-E4QNLVY4.js';
13
15
  export { PRODUCT_RENAMES, PRODUCT_RENAME_EMIT, PRODUCT_SLUG_ALIASES, product_alias_exports as ProductAlias, RENAME_CONCERNS, billingIdVariants, emitBillingId, emitName, emitProductSlug, emitQuotaKey, emitRbacResource, emitTemplateKey, isLegacyName, isSameBillingId, isSameGraphQLName, isSameName, isSameProductSlug, isSameQuotaKey, isSameRbacResource, isSameTemplateKey, nameVariants, normalizeBillingId, normalizeGraphQLName, normalizeProductSlug, normalizeQuotaKey, normalizeRbacResource, normalizeTemplateKey, productSlugVariants, quotaKeyVariants, rbacResourceVariants, readRenamedEnv, templateKeyVariants, toCurrentName, toLegacyName } from './chunk-OBBCR6WY.js';
14
16
  import { RBACModule } from './chunk-PQGMZH6K.js';
15
17
  export { RBACModule, createRBACDirective, createRBACDirectiveForLayer, createRBACDirectiveFromEnv } from './chunk-PQGMZH6K.js';
16
- export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from './chunk-MZCBEJ67.js';
17
- import './chunk-Q3SWU4VF.js';
18
- import './chunk-3Z2VRCT6.js';
19
18
  export { i18n_exports as I18n, createTranslator, getLanguage, getLocale, hasI18n, t } from './chunk-EBDHIL7V.js';
19
+ export { init_exports as Init } from './chunk-E36LPO3K.js';
20
+ export { RESOURCE_CAP_DEFAULTS, ResourceCapExceededError, ResourceCapsModule, configureResourceCaps, getResourceCaps } from './chunk-MZCBEJ67.js';
20
21
  export { instrumentation_exports as Instrumentation } from './chunk-E5DTAGCA.js';
21
22
  import './chunk-AWPNRV3L.js';
22
- export { middleware_exports as Middleware } from './chunk-ELU7VL3E.js';
23
+ export { dataloader_exports as DataLoader } from './chunk-NUB5GQTU.js';
23
24
  export { export_exports as Export } from './chunk-GKOAAC6D.js';
24
25
  export { feature_flags_exports as FeatureFlags } from './chunk-UNASM5VJ.js';
25
26
  export { files_exports as Files } from './chunk-FYFA7WAS.js';
@@ -43,7 +44,6 @@ import { resolveEventStreamsUrl } from './chunk-KS2HQCJR.js';
43
44
  export { graphql_exports as GraphQL } from './chunk-NGAGKLAM.js';
44
45
  import './chunk-MWPYA2HD.js';
45
46
  import './chunk-ENEDTQET.js';
46
- export { captcha_exports as Captcha, isCaptchaEnabled, verifyCaptcha, verifyCaptchaIfEnabled } from './chunk-YMZEUTD2.js';
47
47
  export { ai_credits_exports as AiCredits } from './chunk-5RBIDJBZ.js';
48
48
  import { AuthModule } from './chunk-GJWQK3IU.js';
49
49
  export { AuthModule } from './chunk-GJWQK3IU.js';
@@ -52,6 +52,7 @@ export { cache_exports as Cache } from './chunk-PAQK3YF2.js';
52
52
  import './chunk-A5F6Z5UE.js';
53
53
  import { disposeAll } from './chunk-KO2ZXZ7W.js';
54
54
  export { lifecycle_exports as Lifecycle, disposeAll, getRegisteredDisposableCount, registerDisposable, unregisterDisposable } from './chunk-KO2ZXZ7W.js';
55
+ export { captcha_exports as Captcha, isCaptchaEnabled, verifyCaptcha, verifyCaptchaIfEnabled } from './chunk-YMZEUTD2.js';
55
56
  export { createInternalClient, createInternalClientForTenant, createInternalClientForWorkspaces } from './chunk-KJOSPVB2.js';
56
57
  export { crypto_exports as Crypto } from './chunk-SBS4S2PJ.js';
57
58
  import { DatabaseModule } from './chunk-UD5PPGVU.js';
@@ -60,7 +61,6 @@ import { APIError, NetworkError, TimeoutError, ValidationError } from './chunk-Q
60
61
  export { DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG, DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS } from './chunk-5CAFHK2Z.js';
61
62
  import { logger } from './chunk-RU266375.js';
62
63
  export { logger_exports as Logger } from './chunk-RU266375.js';
63
- export { dataloader_exports as DataLoader } from './chunk-NUB5GQTU.js';
64
64
  import { __name } from './chunk-XE4OXN2W.js';
65
65
  import { GraphQLClient } from 'graphql-request';
66
66
 
@@ -1,6 +1,7 @@
1
- export { C as ContextFilterInput, a as ContextWhereCondition, D as DatabaseClient, b as DatabaseClientConfig, F as FieldExtractionOptions, c as FieldExtractionResult, I as InputJsonValue, J as JsonValue, M as ModelFieldsMap, O as OperationContext, P as PoolTuningEnv, d as PrismaJsonFilter, e as buildContextWhereClause, f as buildContextWhereConditions, g as checkDatabaseHealth, h as contextMatches, j as createContextFromSDK, k as createDatabaseClient, l as createDatabaseClientFromEnv, m as extractFieldsFromModel, n as getAllModelNames, o as getDatabaseManager, p as getDatabaseProductName, q as getDatabaseStats, r as getDatabaseVersion, s as getDb, t as getModelFields, u as hasModel, v as initializeDatabase, w as initializeDatabaseWithConfig, x as isDatabaseInitialized, y as loadGeneratedFields, z as mergeContext, A as parseContext, B as resetDatabaseManager, E as resolvePoolTuningFromEnv, G as testConnection, H as toContextJson } from '../index-CL7koBpQ.js';
1
+ export { C as ContextFilterInput, a as ContextWhereCondition, D as DatabaseClient, b as DatabaseClientConfig, F as FieldExtractionOptions, c as FieldExtractionResult, I as InputJsonValue, J as JsonValue, M as ModelFieldsMap, O as OperationContext, P as PoolTuningEnv, d as PrismaJsonFilter, e as buildContextWhereClause, f as buildContextWhereConditions, g as checkDatabaseHealth, h as contextMatches, j as createContextFromSDK, k as createDatabaseClient, l as createDatabaseClientFromEnv, m as extractFieldsFromModel, n as getAllModelNames, o as getDatabaseManager, p as getDatabaseProductName, q as getDatabaseStats, r as getDatabaseVersion, s as getDb, t as getModelFields, u as hasModel, v as initializeDatabase, w as initializeDatabaseWithConfig, x as isDatabaseInitialized, y as loadGeneratedFields, z as mergeContext, A as parseContext, B as resetDatabaseManager, E as resolvePoolTuningFromEnv, G as testConnection, H as toContextJson } from '../index-BTMt4OjA.js';
2
2
  export { C as ConnectionState, d as DatabaseHealth, D as DatabaseReturnType, P as PrismaClientBase, c as PrismaClientConfig, a as PrismaClientConstructorOptions, b as PrismaClientWrapper, e as PrismaEvent, f as PrismaLogDefinition, g as PrismaLogEvent, h as PrismaLogLevel, i as PrismaQueryEvent, j as PrismaTransactionOptions, k as configurePrismaLogging, l as createConnectionPool, m as createPrismaAdapter, n as createPrismaClient, o as ensureServiceApplicationName, p as installAcquireRetry, q as isTransientAcquireError } from '../client-CCXpAZ2r.js';
3
- export { C as CallerTransaction, P as PrismaQueryInternalParams, R as RawPrismaForCallerTransaction, T as TransactionContextStatement, a as WorkspaceContext, W as WorkspaceExtensionConfig, b as addWorkspaceExtension, c as buildTransactionContextStatement, d as defaultWorkspaceExtensionConfig, g as getCallerTransaction, e as getWorkspaceContext, i as injectCreateFields, f as injectWhereWorkspaceId, m as maybeSetRlsGuc, h as maybeTagConnection, r as resetCallerTransactionStateForTests, j as runOperationInCallerTransaction, k as runOperationWithRlsGuc, s as setWorkspaceContext, w as withWorkspaceContext, l as withWorkspaceContextSync } from '../workspace-extension-DiNiTLa3.js';
3
+ export { C as CallerTransaction, P as PrismaQueryInternalParams, R as RawPrismaForCallerTransaction, T as TransactionContextStatement, a as WorkspaceContext, W as WorkspaceExtensionConfig, b as addWorkspaceExtension, c as buildTransactionContextStatement, d as defaultWorkspaceExtensionConfig, g as getCallerTransaction, e as getScopedWorkspaceContext, f as getWorkspaceContext, i as injectCreateFields, h as injectWhereWorkspaceId, m as maybeSetRlsGuc, j as maybeTagConnection, r as resetCallerTransactionStateForTests, k as runOperationInCallerTransaction, l as runOperationWithRlsGuc, s as setWorkspaceContext, w as withWorkspaceContext, n as withWorkspaceContextSync } from '../workspace-extension-BGwTOV_r.js';
4
4
  import '../prisma-extension-gYhYriA0.js';
5
5
  import '@prisma/adapter-pg';
6
6
  import 'pg';
7
+ import '../assistant-session-CJZhF4D6.js';
@@ -1,6 +1,6 @@
1
- export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson } from '../chunk-YCPVIFDN.js';
1
+ export { buildContextWhereClause, buildContextWhereConditions, checkDatabaseHealth, contextMatches, createContextFromSDK, createDatabaseClient, createDatabaseClientFromEnv, extractFieldsFromModel, getAllModelNames, getDatabaseManager, getDatabaseProductName, getDatabaseStats, getDatabaseVersion, getDb, getModelFields, hasModel, initializeDatabase, initializeDatabaseWithConfig, isDatabaseInitialized, loadGeneratedFields, mergeContext, parseContext, resetDatabaseManager, resolvePoolTuningFromEnv, testConnection, toContextJson } from '../chunk-QCOC2SF3.js';
2
+ export { addWorkspaceExtension, buildTransactionContextStatement, defaultWorkspaceExtensionConfig, getCallerTransaction, getScopedWorkspaceContext, getWorkspaceContext, injectCreateFields, injectWhereWorkspaceId, maybeSetRlsGuc, maybeTagConnection, resetCallerTransactionStateForTests, runOperationInCallerTransaction, runOperationWithRlsGuc, setWorkspaceContext, withWorkspaceContext, withWorkspaceContextSync } from '../chunk-E4QNLVY4.js';
2
3
  import '../chunk-OBBCR6WY.js';
3
- export { addWorkspaceExtension, buildTransactionContextStatement, defaultWorkspaceExtensionConfig, getCallerTransaction, getWorkspaceContext, injectCreateFields, injectWhereWorkspaceId, maybeSetRlsGuc, maybeTagConnection, resetCallerTransactionStateForTests, runOperationInCallerTransaction, runOperationWithRlsGuc, setWorkspaceContext, withWorkspaceContext, withWorkspaceContextSync } from '../chunk-3Z2VRCT6.js';
4
4
  export { PrismaClientWrapper, configurePrismaLogging, createConnectionPool, createPrismaAdapter, createPrismaClient, ensureServiceApplicationName, installAcquireRetry, isTransientAcquireError } from '../chunk-K52ICDCP.js';
5
5
  import '../chunk-TX2GDIWP.js';
6
6
  import '../chunk-SIAOIYHW.js';
@@ -1,14 +1,15 @@
1
- import { W as WorkspaceSecret, I as IActor, J as JWTPayload, S as ServerDefinition, a as ServerInstance, R as RESTEndpoint, b as ITenant, G as GraphQLContext, V as VerifiedDelegationContext, Y as YogaPlugin } from '../types-C-6m9NoG.js';
2
- export { A as ActorProvenance, C as ConsentContext, E as ElysiaApp, c as IContextFilterInput, d as IOperationContext, e as IOrganization, f as IProduct, g as IProject, h as ITracking, i as IWorkspace, M as ModuleGraphConfig, P as PrismaClientConstructor, j as ServerConfig, k as ServerI18nConfig, l as ServerInfo, m as WspaceGraphQLContext } from '../types-C-6m9NoG.js';
1
+ import { W as WorkspaceSecret, I as IActor, J as JWTPayload, S as ServerDefinition, a as ServerInstance, R as RESTEndpoint, b as ITenant, G as GraphQLContext, V as VerifiedDelegationContext, Y as YogaPlugin } from '../types-DLFCJD3D.js';
2
+ export { A as ActorProvenance, C as ConsentContext, E as ElysiaApp, c as IContextFilterInput, d as IOperationContext, e as IOrganization, f as IProduct, g as IProject, h as ITracking, i as IWorkspace, M as ModuleGraphConfig, P as PrismaClientConstructor, j as ServerConfig, k as ServerI18nConfig, l as ServerInfo, m as WspaceGraphQLContext } from '../types-DLFCJD3D.js';
3
3
  import * as jose from 'jose';
4
4
  import { VerifyOptions } from 'jsonwebtoken';
5
5
  import { I as I18n } from '../i18n-DrdPTann.js';
6
+ export { c as ACTOR_ORIGIN_HEADER, a as AI_ASSISTANT_ACTOR_ORIGIN, d as ASSISTANT_CORRELATION_ID_HEADER, e as ASSISTANT_SESSION_ID_HEADER, b as ActorOrigin, A as AssistantSessionAttribution, p as parseAssistantSessionHeaders, r as readAssistantSessionAttribution, t as toAssistantSessionAttribution } from '../assistant-session-CJZhF4D6.js';
6
7
  import { DocumentNode, GraphQLError } from 'graphql';
7
8
  import { Plugin } from 'graphql-yoga';
8
9
  export { s as suppressMutationAudit } from '../explicit-activity-scope-CCoxVwAr.js';
9
10
  export { I as I18nContext, L as LocaleCode } from '../types-C8TbSdEj.js';
10
11
  export { P as PrismaClientBase } from '../client-CCXpAZ2r.js';
11
- import '../workspace-extension-DiNiTLa3.js';
12
+ import '../workspace-extension-BGwTOV_r.js';
12
13
  import '@prisma/adapter-pg';
13
14
  import 'pg';
14
15
 
@@ -1,9 +1,9 @@
1
1
  import { createHumanReadableErrorPlugin, formatHttpError, normalizeGraphQLResponse, createHttpErrorResponse } from '../chunk-6GL4SLU7.js';
2
2
  export { UserFacingGraphQLError, createHttpErrorResponse, createHumanReadableErrorPlugin, createWorkspaceGuardPlugin, formatHttpError, normalizeError, normalizeExecutionResultErrors, normalizeGraphQLResponse, normalizeGraphQLResponsePayload, toUserFacingGraphQLError } from '../chunk-6GL4SLU7.js';
3
3
  import { getWorkspaceQuotaRegistry } from '../chunk-WTEHAVBX.js';
4
- import { trackOperation, createExplicitActivityScope, runInExplicitActivityScope } from '../chunk-Q3SWU4VF.js';
5
- export { suppressMutationAudit } from '../chunk-Q3SWU4VF.js';
6
- import { setWorkspaceContext, withWorkspaceContext } from '../chunk-3Z2VRCT6.js';
4
+ import { parseAssistantSessionHeaders, readAssistantSessionAttribution, trackOperation, createExplicitActivityScope, runInExplicitActivityScope } from '../chunk-TANAOLAV.js';
5
+ export { ACTOR_ORIGIN_HEADER, AI_ASSISTANT_ACTOR_ORIGIN, ASSISTANT_CORRELATION_ID_HEADER, ASSISTANT_SESSION_ID_HEADER, parseAssistantSessionHeaders, readAssistantSessionAttribution, suppressMutationAudit, toAssistantSessionAttribution } from '../chunk-TANAOLAV.js';
6
+ import { setWorkspaceContext, withWorkspaceContext } from '../chunk-E4QNLVY4.js';
7
7
  import { I18n } from '../chunk-EBDHIL7V.js';
8
8
  import { getMetricsRegistry } from '../chunk-AWPNRV3L.js';
9
9
  import { ContextManager } from '../chunk-RZOFS2BQ.js';
@@ -446,7 +446,9 @@ async function buildContext(request) {
446
446
  const project = extractProject(request);
447
447
  const product = extractProduct(request);
448
448
  const tracking = extractTracking(request);
449
- const verifiedDelegation = decodeVerifiedDelegation(getHeader(request, "x-verified-delegation"), actor, workspace?.id, shouldTrustActorHeaders(request));
449
+ const trustedGatewayHeaders = shouldTrustActorHeaders(request);
450
+ const verifiedDelegation = decodeVerifiedDelegation(getHeader(request, "x-verified-delegation"), actor, workspace?.id, trustedGatewayHeaders);
451
+ const assistantSession = actor && trustedGatewayHeaders ? parseAssistantSessionHeaders((name) => getHeader(request, name)) : void 0;
450
452
  let i18n;
451
453
  if (contextOptions.i18n) {
452
454
  i18n = contextOptions.i18n.createContextFromRequest(request);
@@ -481,7 +483,10 @@ async function buildContext(request) {
481
483
  actorType: actor?.type,
482
484
  organizationId: organization?.id,
483
485
  projectId: project?.id,
484
- onBehalfOf
486
+ onBehalfOf,
487
+ ...assistantSession ? {
488
+ assistantSession
489
+ } : {}
485
490
  };
486
491
  logger.debug("[ServerContext] Setting workspace context", {
487
492
  workspaceId: wsCtxPayload.workspaceId ?? "NONE",
@@ -500,6 +505,9 @@ async function buildContext(request) {
500
505
  product,
501
506
  tracking,
502
507
  verifiedDelegation,
508
+ ...assistantSession ? {
509
+ assistantSession
510
+ } : {},
503
511
  onBehalfOf: onBehalfOf || actor?.id || "",
504
512
  db: contextOptions.getDb(),
505
513
  i18n,
@@ -527,7 +535,11 @@ function id(value) {
527
535
  __name(id, "id");
528
536
  function executionContext(value) {
529
537
  if (!record(value)) return {};
538
+ const assistantSession = readAssistantSessionAttribution(value["assistantSession"]);
530
539
  return {
540
+ ...assistantSession ? {
541
+ assistantSession
542
+ } : {},
531
543
  workspaceId: id(value["workspace"]),
532
544
  tenantId: id(value["tenant"]),
533
545
  organizationId: id(value["organization"]),