@burdenoff/be-sdk 2026.1111.1 → 2026.1113.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (83) hide show
  1. package/dist/activity/index.d.ts +2 -2
  2. package/dist/ai-credits/index.d.ts +1 -1
  3. package/dist/auth/index.d.ts +1 -1
  4. package/dist/bootstrap/index.d.ts +1 -1
  5. package/dist/bun-runtime-metrics-CPy5D6NT.js +58 -0
  6. package/dist/bun-runtime-metrics-CPy5D6NT.js.map +1 -0
  7. package/dist/cache/index.d.ts +1 -1
  8. package/dist/context/index.d.ts +1 -1
  9. package/dist/event-queue/index.d.ts +1 -1
  10. package/dist/export/index.d.ts +1 -1
  11. package/dist/export/index.js +1 -1
  12. package/dist/{export-DJXE3Osa.js → export-lqKewsuF.js} +2 -2
  13. package/dist/{export-DJXE3Osa.js.map → export-lqKewsuF.js.map} +1 -1
  14. package/dist/files/index.d.ts +1 -1
  15. package/dist/gateway/index.d.ts +3 -3
  16. package/dist/gateway/index.js +2 -2
  17. package/dist/gateway-2en8Gx_a.js +274 -0
  18. package/dist/gateway-2en8Gx_a.js.map +1 -0
  19. package/dist/graph/index.d.ts +1 -1
  20. package/dist/{graphql-CUDyhibV.d.ts → graphql-C8jKLLel.d.ts} +1 -1
  21. package/dist/{index-B2LCaK0R.d.ts → index-479i3w77.d.ts} +1 -1
  22. package/dist/{index-BGzMYJsm.d.ts → index-8pUSoT85.d.ts} +1 -1
  23. package/dist/{index-ADmsX0BI.d.ts → index-9MJVKzWA.d.ts} +3 -3
  24. package/dist/{index-FbXPfen7.d.ts → index-BJwHEzpN.d.ts} +1 -1
  25. package/dist/{index-CTTwo9av.d.ts → index-BTaQMEgB.d.ts} +1 -1
  26. package/dist/{index-CDOqxSIi.d.ts → index-Base-sg5.d.ts} +1 -1
  27. package/dist/{index-C_GXXF32.d.ts → index-Bh6W5JO4.d.ts} +3 -3
  28. package/dist/{index-BeVtqGO-.d.ts → index-Bwn5Z1h-.d.ts} +1 -1
  29. package/dist/{index-FRRaa6h2.d.ts → index-CEtULfb_.d.ts} +3 -3
  30. package/dist/{index-DqbGqfAy.d.ts → index-Cwu5Mpji.d.ts} +1 -1
  31. package/dist/{index-CaM9JUcc.d.ts → index-DSynXDRD.d.ts} +1 -1
  32. package/dist/{index-CVCyKzhB.d.ts → index-DWER4-_x.d.ts} +3 -3
  33. package/dist/{index-cmR9k9ga.d.ts → index-DhFP_AIB.d.ts} +1 -1
  34. package/dist/{index-zd_NPGJo.d.ts → index-DqpCL9kD.d.ts} +4 -4
  35. package/dist/{index-U_tu3zUl.d.ts → index-Dw_0wE4q.d.ts} +2 -2
  36. package/dist/{index-3KOZ1zN9.d.ts → index-HeUeEsMU.d.ts} +1 -1
  37. package/dist/{index-Cot73bdh.d.ts → index-KlrnELrN.d.ts} +1 -1
  38. package/dist/{index-MArCb8Aq.d.ts → index-SvWwlTUC.d.ts} +1 -1
  39. package/dist/{index-CHwMhK6v.d.ts → index-YMGOJins.d.ts} +2 -2
  40. package/dist/index-oJMtR3nl.d.ts +88 -0
  41. package/dist/index.d.ts +21 -21
  42. package/dist/index.js +5 -5
  43. package/dist/init/index.d.ts +1 -1
  44. package/dist/init/index.js +1 -1
  45. package/dist/{init-CQPFmOOe.js → init-D814LeLF.js} +2 -2
  46. package/dist/{init-CQPFmOOe.js.map → init-D814LeLF.js.map} +1 -1
  47. package/dist/instrumentation/index.d.ts +2 -2
  48. package/dist/layer/index.d.ts +2 -2
  49. package/dist/layer-Bcix-WCl.js.map +1 -1
  50. package/dist/{layer-BZBZZWeV.d.ts → layer-C0zxAUgR.d.ts} +1 -0
  51. package/dist/logger/index.d.ts +1 -1
  52. package/dist/notifications/index.d.ts +1 -1
  53. package/dist/payments/index.d.ts +2 -2
  54. package/dist/rbac/index.d.ts +1 -1
  55. package/dist/resource-caps/index.d.ts +1 -1
  56. package/dist/{sdk-B62itAH1.js → sdk-DqIqX-Ue.js} +33 -2
  57. package/dist/sdk-DqIqX-Ue.js.map +1 -0
  58. package/dist/search/index.d.ts +2 -2
  59. package/dist/security/index.d.ts +1 -1
  60. package/dist/security/rate-limit/index.d.ts +1 -1
  61. package/dist/server/index.js +2 -3
  62. package/dist/server/index.js.map +1 -1
  63. package/dist/tags/index.d.ts +1 -1
  64. package/dist/telemetry/index.d.ts +2 -2
  65. package/dist/telemetry/index.js +8 -4
  66. package/dist/telemetry/index.js.map +1 -1
  67. package/dist/temporal/index.d.ts +1 -1
  68. package/dist/tracker/index.d.ts +2 -2
  69. package/dist/tracker/index.js +2 -2
  70. package/dist/{tracker-PQztSlhJ.js → tracker-Cl3cGKe-.js} +2 -2
  71. package/dist/{tracker-PQztSlhJ.js.map → tracker-Cl3cGKe-.js.map} +1 -1
  72. package/dist/translation/index.d.ts +2 -2
  73. package/dist/types/index.d.ts +2 -2
  74. package/dist/{types-C6EKaS3V.d.ts → types-gJ9Qqi9E.d.ts} +1 -1
  75. package/dist/usage/index.d.ts +1 -1
  76. package/dist/usage/index.js +1 -1
  77. package/dist/{usage-BRqVP3CJ.js → usage-ygkKsxdd.js} +2 -2
  78. package/dist/{usage-BRqVP3CJ.js.map → usage-ygkKsxdd.js.map} +1 -1
  79. package/package.json +1 -1
  80. package/dist/gateway-ByVo-n37.js +0 -50
  81. package/dist/gateway-ByVo-n37.js.map +0 -1
  82. package/dist/index-YOShAwkq.d.ts +0 -45
  83. package/dist/sdk-B62itAH1.js.map +0 -1
@@ -1,2 +1,2 @@
1
- import { A as EntityTagInfo, B as TagVocabularyRef, C as ENTITY_TAGS_GRAPHQL_CODES, D as AvailableTag, E as isEntityTagsError, F as TagActor, H as TagsGatewayClient, I as TagActorType, L as TagAssignmentSource, M as RawTagAssignment, N as TAG_ACTOR_TYPES, O as CreateTagOptions, P as TAG_ASSIGNMENT_SOURCES, R as TagEntityOptions, S as entityTagsTypeNames, T as EntityTagsErrorCode, V as TaggedEntityPage, _ as slugifyTagKey, a as EntityTagMutationEvent, b as assertTagPrefix, c as createEntityTagResolvers, d as EntityTagsSdlOptions, f as UNIVERSAL_TAG_STUB_SDL, g as mapTagAssignment, h as TagsGatewayAdapterOptions, i as EntityTagBinding, j as FindEntitiesByTagsOptions, k as EntityTagAssignment, l as defaultTagActor, m as TagsGatewayAdapter, n as CreateEntityTagResolversOptions, o as EntityTagOperation, p as buildEntityTagsSdl, r as EntityTagAccessCheck, s as EntityTagResolvers, u as EntityTagsRbacOptions, v as EntityTagsFieldNames, w as EntityTagsError, x as entityTagsFieldNames, y as EntityTagsTypeNames, z as TagVocabularyConfig } from "../index-3KOZ1zN9.js";
1
+ import { A as EntityTagInfo, B as TagVocabularyRef, C as ENTITY_TAGS_GRAPHQL_CODES, D as AvailableTag, E as isEntityTagsError, F as TagActor, H as TagsGatewayClient, I as TagActorType, L as TagAssignmentSource, M as RawTagAssignment, N as TAG_ACTOR_TYPES, O as CreateTagOptions, P as TAG_ASSIGNMENT_SOURCES, R as TagEntityOptions, S as entityTagsTypeNames, T as EntityTagsErrorCode, V as TaggedEntityPage, _ as slugifyTagKey, a as EntityTagMutationEvent, b as assertTagPrefix, c as createEntityTagResolvers, d as EntityTagsSdlOptions, f as UNIVERSAL_TAG_STUB_SDL, g as mapTagAssignment, h as TagsGatewayAdapterOptions, i as EntityTagBinding, j as FindEntitiesByTagsOptions, k as EntityTagAssignment, l as defaultTagActor, m as TagsGatewayAdapter, n as CreateEntityTagResolversOptions, o as EntityTagOperation, p as buildEntityTagsSdl, r as EntityTagAccessCheck, s as EntityTagResolvers, u as EntityTagsRbacOptions, v as EntityTagsFieldNames, w as EntityTagsError, x as entityTagsFieldNames, y as EntityTagsTypeNames, z as TagVocabularyConfig } from "../index-HeUeEsMU.js";
2
2
  export { type AvailableTag, type CreateEntityTagResolversOptions, type CreateTagOptions, ENTITY_TAGS_GRAPHQL_CODES, type EntityTagAccessCheck, type EntityTagAssignment, type EntityTagBinding, type EntityTagInfo, type EntityTagMutationEvent, type EntityTagOperation, type EntityTagResolvers, EntityTagsError, type EntityTagsErrorCode, type EntityTagsFieldNames, type EntityTagsRbacOptions, type EntityTagsSdlOptions, type EntityTagsTypeNames, type FindEntitiesByTagsOptions, type RawTagAssignment, TAG_ACTOR_TYPES, TAG_ASSIGNMENT_SOURCES, type TagActor, type TagActorType, type TagAssignmentSource, type TagEntityOptions, type TagVocabularyConfig, type TagVocabularyRef, type TaggedEntityPage, TagsGatewayAdapter, type TagsGatewayAdapterOptions, type TagsGatewayClient, UNIVERSAL_TAG_STUB_SDL, assertTagPrefix, buildEntityTagsSdl, createEntityTagResolvers, defaultTagActor, entityTagsFieldNames, entityTagsTypeNames, isEntityTagsError, mapTagAssignment, slugifyTagKey };
@@ -1,5 +1,5 @@
1
- import { r as Logger } from "../index-Cot73bdh.js";
2
- import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-B2LCaK0R.js";
1
+ import { r as Logger } from "../index-KlrnELrN.js";
2
+ import { l as setupInstrumentation, n as InstrumentationSetupResult, o as initializeInstrumentation, r as SetupInstrumentationOptions } from "../index-479i3w77.js";
3
3
  interface TelemetryIdGenerator {
4
4
  generateTraceId(): string;
5
5
  generateSpanId(): string;
@@ -2,6 +2,7 @@ import { t as __exportAll } from "../rolldown-runtime-ad2WFvuA.js";
2
2
  import { a as logger, s as redactSensitiveFields, t as Logger } from "../logger-B6rCpb7D.js";
3
3
  import { n as initializeInstrumentation, o as setupInstrumentation, w as setActiveTelemetryLogger } from "../instrumentation-xkkmDgJ0.js";
4
4
  import { a as resolveCollectorLayer, i as defaultCollectorTracesEndpoint, n as OTLP_HTTP_PORT, r as defaultCollectorEndpoint, t as COLLECTOR_SERVICE } from "../collector-endpoint-iyQYeI50.js";
5
+ import { t as collectPromDefaultMetrics } from "../bun-runtime-metrics-CPy5D6NT.js";
5
6
 
6
7
  // src/telemetry/id-generator.ts
7
8
  /**
@@ -27,12 +28,15 @@ function createHealthRoutes(_deps = {}) {
27
28
  }
28
29
 
29
30
  // src/telemetry/metrics-endpoint.ts
31
+ /**
32
+ * Prometheus `/metrics` route mounter. Uses the shared `prom-client`
33
+ * default registry so all instrumentation (GraphQL Envelop, Prisma,
34
+ * runtime) shows up on a single endpoint.
35
+ */
30
36
  async function loadDefaultRegistry() {
31
37
  try {
32
38
  const mod = await import("prom-client");
33
- try {
34
- mod.collectDefaultMetrics({ register: mod.register });
35
- } catch {}
39
+ collectPromDefaultMetrics(mod);
36
40
  return mod.register;
37
41
  } catch {
38
42
  return null;
@@ -348,7 +352,7 @@ async function bootstrapTelemetry(cfg) {
348
352
  if (resolveOtelSdkEnabled()) {
349
353
  console.log("[telemetry] OTel SDK bootstrap starting...");
350
354
  try {
351
- const { createOtelSdk } = await import("../sdk-B62itAH1.js");
355
+ const { createOtelSdk } = await import("../sdk-DqIqX-Ue.js");
352
356
  otelSdk = await createOtelSdk({
353
357
  serviceName: cfg.serviceName,
354
358
  serviceVersion,
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":["BaseLogger","anyApi","logger"],"sources":["../../src/telemetry/id-generator.ts","../../src/telemetry/health.ts","../../src/telemetry/metrics-endpoint.ts","../../src/telemetry/prisma-logging.ts","../../src/telemetry/pino-redaction.ts","../../src/telemetry/pino-logger.ts","../../src/telemetry/index.ts"],"sourcesContent":["/**\n * Custom trace/span id generation for `bootstrapTelemetry`.\n *\n * `@opentelemetry/sdk-node` accepts an `idGenerator` that the tracer provider\n * uses for every new trace id and span id. Services pass one when they need\n * span ids that are derived rather than random — for example, a workflow run\n * that executes across many jobs and pods but must surface as one trace with a\n * single, deterministic `workflow.run` parent span.\n *\n * The interface below is a structural twin of `IdGenerator` from\n * `@opentelemetry/sdk-trace-base`, declared here so the SDK's public types do\n * not require that optional peer dependency to be installed. Any\n * `IdGenerator` implementation (including `RandomIdGenerator`) satisfies it.\n */\n\nexport interface TelemetryIdGenerator {\n /** Returns a trace id: 32 lowercase hex characters (16 bytes), not all zero. */\n generateTraceId(): string;\n /** Returns a span id: 16 lowercase hex characters (8 bytes), not all zero. */\n generateSpanId(): string;\n}\n\n/**\n * Validate a caller-supplied id generator before it reaches the OTel SDK.\n *\n * A generator without both methods would make the tracer provider throw on\n * the first span, long after startup. Failing at bootstrap instead surfaces\n * the misconfiguration where it was made. `undefined` is accepted and means\n * \"use the SDK's default random generator\".\n */\nexport function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined {\n if (candidate === undefined) return;\n if (typeof candidate !== 'object' || candidate === null) {\n throw new TypeError('bootstrapTelemetry: idGenerator must be an object with generateTraceId and generateSpanId');\n }\n const { generateTraceId, generateSpanId } = candidate as {\n generateTraceId?: unknown;\n generateSpanId?: unknown;\n };\n if (typeof generateTraceId !== 'function' || typeof generateSpanId !== 'function') {\n throw new TypeError('bootstrapTelemetry: idGenerator must implement both generateTraceId() and generateSpanId()');\n }\n}\n","/**\n * `/health`, `/health/live`, `/health/ready` Elysia routes with a 1s\n * result cache so readiness checks can't stampede Postgres.\n *\n * Dependencies (prisma, eventQueue, valkey) are optional — omit any client and\n * the readiness check simply skips it.\n */\n\ninterface PrismaLike {\n $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;\n}\ninterface EventQueueLike {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\ninterface ValkeyLike {\n ping: () => Promise<unknown>;\n}\n\nexport interface HealthDeps {\n prisma?: PrismaLike;\n eventQueue?: EventQueueLike;\n valkey?: ValkeyLike;\n /** Service version reported on /health. */\n version?: string;\n /** Service name reported on /health. */\n serviceName?: string;\n}\n\ninterface CachedStatus {\n ready: boolean;\n checked: Record<string, { ok: boolean; error?: string }>;\n at: number;\n}\n\nconst CACHE_TTL_MS = 1000;\n\nasync function probeReady(deps: HealthDeps): Promise<CachedStatus> {\n const checked: Record<string, { ok: boolean; error?: string }> = {};\n\n if (deps.prisma) {\n try {\n await deps.prisma.$queryRaw`SELECT 1`;\n checked['postgres'] = { ok: true };\n } catch (err) {\n checked['postgres'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.eventQueue) {\n try {\n const connected =\n typeof deps.eventQueue.isConnected === 'function'\n ? await Promise.resolve(deps.eventQueue.isConnected())\n : ((await deps.eventQueue.healthCheck?.())?.ok ?? true);\n checked['eventQueue'] = { ok: Boolean(connected) };\n } catch (err) {\n checked['eventQueue'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.valkey) {\n try {\n await deps.valkey.ping();\n checked['valkey'] = { ok: true };\n } catch (err) {\n checked['valkey'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const ready = Object.values(checked).every((c) => c.ok);\n return { ready, checked, at: Date.now() };\n}\n\nexport function createHealthRoutes(_deps: HealthDeps = {}): unknown {\n // Return an Elysia app lazily so be-sdk doesn't hard-require elysia.\n return new Proxy(\n {},\n {\n get(_target, prop): unknown {\n // Tell TypeScript consumers the returned object is an Elysia plugin;\n // the actual mount happens via `createHealthRoutesImpl`. Services\n // that prefer direct use can call `createHealthRoutesImpl(elysia, deps)`.\n if (prop === 'use' || prop === 'then') return undefined;\n return undefined;\n },\n }\n );\n}\n\n/**\n * Mount health routes on an existing Elysia app. Callers hold a reference\n * to Elysia themselves; be-sdk stays decoupled.\n */\nexport function createHealthRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, deps: HealthDeps = {}): App {\n let cache: CachedStatus | null = null;\n\n const getStatus = async (): Promise<CachedStatus> => {\n if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache;\n cache = await probeReady(deps);\n return cache;\n };\n\n app.get('/health/live', () => ({\n status: 'ok',\n serviceName: deps.serviceName,\n version: deps.version,\n }));\n\n app.get('/health/ready', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n };\n });\n\n app.get('/health', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n uptime_s: Math.round(process.uptime()),\n };\n });\n\n return app;\n}\n","/**\n * Prometheus `/metrics` route mounter. Uses the shared `prom-client`\n * default registry so all instrumentation (GraphQL Envelop, Prisma,\n * runtime) shows up on a single endpoint.\n */\n\ninterface PromRegistryLike {\n metrics: () => Promise<string> | string;\n contentType?: string;\n}\n\nexport interface MetricsMountOptions {\n registry?: PromRegistryLike;\n path?: string;\n}\n\nexport async function loadDefaultRegistry(): Promise<PromRegistryLike | null> {\n try {\n const mod = (await import('prom-client')) as unknown as {\n register: PromRegistryLike;\n collectDefaultMetrics: (opts?: Record<string, unknown>) => void;\n };\n // Kick runtime metrics into the default registry if not already.\n try {\n mod.collectDefaultMetrics({ register: mod.register });\n } catch {\n // Already registered — ignore duplicate-metric errors.\n }\n return mod.register;\n } catch {\n return null;\n }\n}\n\nexport function createMetricsRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, opts: MetricsMountOptions = {}): App {\n const path = opts.path ?? '/metrics';\n\n app.get(path, async (ctx: unknown): Promise<unknown> => {\n const registry = opts.registry ?? (await loadDefaultRegistry());\n const ctxWithSet = ctx as { set?: { status?: number; headers?: Record<string, string> } };\n if (!registry) {\n if (ctxWithSet.set) ctxWithSet.set.status = 503;\n return '# prom-client not installed\\n';\n }\n if (ctxWithSet.set) {\n ctxWithSet.set.status = 200;\n ctxWithSet.set.headers = {\n 'content-type': registry.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n };\n }\n return registry.metrics();\n });\n\n return app;\n}\n\n/**\n * Legacy export name used by the service template. Composes the Elysia\n * plugin-style function that `new Elysia().use(...)` accepts.\n */\nexport function createMetricsRoutes(opts: MetricsMountOptions = {}): unknown {\n return (app: Parameters<typeof createMetricsRoutesImpl>[0]): unknown => createMetricsRoutesImpl(app, opts);\n}\n","/**\n * Prisma client extension that pipes query events through the SDK logger\n * with trace/span correlation fields auto-injected. The\n * `@prisma/instrumentation` peer provides the spans\n * themselves; this extension only adds structured log events on top.\n */\nimport type { Logger } from '../logger/index.js';\nimport { redactSensitiveFields } from '../logger/index.js';\n\ntype PrismaQueryArgs = {\n model?: string;\n operation: string;\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n};\n\n/**\n * Returns a Prisma Client extension object compatible with the\n * `$extends()` API (Prisma v5+).\n *\n * ```ts\n * export const prisma = new PrismaClient().$extends(\n * createPrismaLoggingExtension(logger)\n * );\n * ```\n */\nexport function createPrismaLoggingExtension(logger: Logger): {\n name: string;\n query: {\n $allOperations: (args: PrismaQueryArgs) => Promise<unknown>;\n };\n} {\n return {\n name: 'burdenoff-pino-logging',\n query: {\n async $allOperations({ model, operation, args, query }: PrismaQueryArgs): Promise<unknown> {\n const start = Date.now();\n try {\n const result = await query(args);\n logger.debug('prisma.query', {\n model,\n operation,\n duration_ms: Date.now() - start,\n args: redactSensitiveFields(args),\n });\n return result;\n } catch (err) {\n logger.error('prisma.error', {\n model,\n operation,\n duration_ms: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n },\n },\n };\n}\n","/**\n * Default Pino redact paths — covers the Burdenoff authorization +\n * gateway header + NATS/GraphQL payload surface area.\n *\n * Services can extend this list via their own Pino options.\n */\nexport const DEFAULT_REDACT_PATHS: readonly string[] = Object.freeze([\n 'password',\n '*.password',\n '*.*.password',\n 'token',\n 'authToken',\n 'workspaceToken',\n 'accessToken',\n 'refreshToken',\n 'clientSecret',\n 'apiKey',\n '*.apiKey',\n 'authorization',\n 'req.headers.authorization',\n 'req.headers[\"x-workspace-authorization\"]',\n 'req.headers.cookie',\n 'res.headers[\"set-cookie\"]',\n 'params.*.password',\n 'params.*.token',\n 'params.*.secret',\n]);\n","/**\n * Pino logger wrapper that emits structured JSON with trace/span correlation\n * fields. Falls back to the SDK's built-in Logger when `pino` isn't installed\n * so services without the peer dep still compile and run.\n *\n * # ACA stdout compatibility\n *\n * In Azure Container Apps the ContainerAppConsoleLogs agent captures\n * `console.log` / `process.stdout.write` output but does *not* reliably\n * capture Pino's default async sonic-boom destination (which writes to fd 1\n * through Node.js `fs.writeSync` / `fs.write`). This means every log line\n * produced through Pino's default destination is invisible in Log Analytics.\n *\n * The fix mirrors what the gateway's own `logger.ts` does in production:\n * pass `pino.destination({ sync: true })` as the second argument to the\n * Pino factory so writes are synchronous and go through a path that ACA\n * captures correctly.\n */\nimport { Logger as BaseLogger } from '../logger/index.js';\nimport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\n\nexport interface PinoLoggerConfig {\n serviceName: string;\n env: 'alpha' | 'prod' | 'dev';\n version: string;\n /** Override Pino log level. Default: warn (prod), info (alpha/dev). */\n level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n /** Extra redact paths appended to DEFAULT_REDACT_PATHS. */\n redactPaths?: string[];\n}\n\ninterface PinoLike {\n level: string;\n fatal: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n trace: (...args: unknown[]) => void;\n child: (bindings: Record<string, unknown>) => PinoLike;\n}\n\n/**\n * Loaded Pino module: factory function + a synchronous destination factory.\n * In ACA, Pino's default async sonic-boom destination is invisible in Log\n * Analytics, so we always use a sync destination.\n */\ninterface PinoLoader {\n factory: (opts: unknown, dest?: unknown) => PinoLike;\n makeDest: () => unknown;\n}\n\nasync function tryLoadPino(): Promise<PinoLoader | null> {\n try {\n const mod = (await import('pino')) as unknown as { default?: unknown };\n const candidate = (mod.default ?? mod) as unknown;\n if (typeof candidate === 'function') {\n const factory = candidate as (opts: unknown, dest?: unknown) => PinoLike;\n const destination = (factory as unknown as Record<string, unknown>)?.['destination'] as\n ((opts?: { sync?: boolean }) => unknown) | undefined;\n const makeDest = typeof destination === 'function' ? () => destination({ sync: true }) : () => undefined;\n return { factory, makeDest };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nclass PinoAdapter extends BaseLogger {\n constructor(private readonly pino: PinoLike) {\n super({\n level: (pino.level as BaseLogger['getLevel'] extends () => infer L ? L : never) ?? 'info',\n console: false,\n });\n }\n\n public override debug(message: string, ...args: unknown[]): void {\n this.pino.debug(this.mergeArgs(args), message);\n }\n public override info(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override warn(message: string, ...args: unknown[]): void {\n this.pino.warn(this.mergeArgs(args), message);\n }\n public override error(message: string, ...args: unknown[]): void {\n this.pino.error(this.mergeArgs(args), message);\n }\n public override log(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override trace(message: string, ...args: unknown[]): void {\n this.pino.trace(this.mergeArgs(args), message);\n }\n\n private mergeArgs(args: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const arg of args) {\n if (arg instanceof Error) {\n out['err'] = { message: arg.message, stack: arg.stack, name: arg.name };\n } else if (arg && typeof arg === 'object') {\n Object.assign(out, arg as Record<string, unknown>);\n } else if (arg !== undefined && arg !== null) {\n out['data'] = arg;\n }\n }\n return out;\n }\n}\n\n/**\n * Build a logger instance. Returns a Pino-backed adapter when `pino` is\n * installed; otherwise falls back to the SDK's built-in JSON Logger.\n *\n * Services call this through `bootstrapTelemetry`, not directly.\n */\nexport async function createPinoLogger(cfg: PinoLoggerConfig): Promise<BaseLogger> {\n const loader = await tryLoadPino();\n if (!loader) {\n // No pino — fall back to the built-in Logger with console output.\n const fallback = new BaseLogger({ level: cfg.env === 'prod' ? 'warn' : 'info', console: true });\n fallback.setContext({\n service: cfg.serviceName,\n env: cfg.env,\n version: cfg.version,\n });\n return fallback;\n }\n\n const redactPaths = [...DEFAULT_REDACT_PATHS, ...(cfg.redactPaths ?? [])];\n const dest = loader.makeDest();\n const pino = loader.factory(\n {\n name: cfg.serviceName,\n level: cfg.level ?? (cfg.env === 'prod' ? 'warn' : 'info'),\n base: {\n service: { name: cfg.serviceName, version: cfg.version },\n env: cfg.env,\n },\n redact: {\n paths: redactPaths,\n censor: '[REDACTED]',\n remove: false,\n },\n timestamp: () => `,\"time\":\"${new Date().toISOString()}\"`,\n mixin: () => pickTraceFields(),\n },\n // Explicit sync destination so output is visible in ACA Log Analytics.\n // Without this, Pino uses its default async sonic-boom which writes to fd 1\n // but the ContainerAppConsoleLogs agent doesn't capture it on Bun.\n dest\n );\n return new PinoAdapter(pino);\n}\n\nfunction pickTraceFields(): Record<string, string> {\n try {\n // Pull active span context via @opentelemetry/api if installed.\n // Use require-style dynamic access to keep this file dep-free.\n const api = (globalThis as unknown as { __otelApi?: unknown }).__otelApi;\n if (!api) return {};\n const anyApi = api as {\n trace: {\n getActiveSpan: () => { spanContext: () => { traceId: string; spanId: string; traceFlags: number } } | undefined;\n };\n };\n const span = anyApi.trace.getActiveSpan();\n if (!span) return {};\n const ctx = span.spanContext();\n return {\n trace_id: ctx.traceId,\n span_id: ctx.spanId,\n trace_flags: ctx.traceFlags.toString(16).padStart(2, '0'),\n };\n } catch {\n return {};\n }\n}\n","/**\n * Unified telemetry bootstrap for Burdenoff services.\n *\n * Composes the existing `instrumentation/` + `observability/` + `logger/`\n * modules and adds:\n * - `bootstrapTelemetry({ serviceName, boundary, module, env })` — single\n * call that initializes OTel, wires Pino logger with trace fields,\n * exposes GraphQL Yoga plugins, registers process exit hooks.\n * - `createHealthRoutes({ prisma, nats, valkey, version })` — `/health`,\n * `/health/live`, `/health/ready` Elysia routes.\n * - `createMetricsRoutes(registry?)` — `/metrics` Prometheus exposition.\n * - `createPrismaLoggingExtension(logger)` — Prisma extension that pipes\n * query events through Pino with trace/span correlation ids.\n *\n * The module does not pull in `@opentelemetry/sdk-node` or `pino` as direct\n * deps — services install those as optional peers, and imports are lazy so\n * services that don't install them still load.\n */\n\nimport type { Logger as BaseLogger } from '../logger/index.js';\nimport { logger as defaultLogger } from '../logger/index.js';\nimport {\n initializeInstrumentation,\n setupInstrumentation,\n type SetupInstrumentationOptions,\n type InstrumentationSetupResult,\n} from '../instrumentation/index.js';\nimport { defaultCollectorEndpoint } from './collector-endpoint.js';\nimport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nimport { setActiveTelemetryLogger } from './logger-state.js';\nimport type { OtelModules, OtelSdkHandle } from './sdk.js';\n\nexport type { OtelModules, OtelPeerPackage } from './sdk.js';\n\nexport { createHealthRoutes } from './health.js';\nexport { createMetricsRoutes } from './metrics-endpoint.js';\nexport { createPrismaLoggingExtension } from './prisma-logging.js';\nexport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\nexport { createPinoLogger } from './pino-logger.js';\nexport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nexport {\n COLLECTOR_SERVICE,\n OTLP_HTTP_PORT,\n defaultCollectorEndpoint,\n defaultCollectorTracesEndpoint,\n resolveCollectorLayer,\n type CollectorLayer,\n} from './collector-endpoint.js';\n\nexport type Boundary = 'wspace' | 'global' | 'gateway';\nexport type Env = 'alpha' | 'prod' | 'dev';\n\nexport interface TelemetryConfig {\n /** Full service name, e.g. \"wspace-auth-svc\". */\n serviceName: string;\n /** Semver of the service deployment; defaults to `process.env.npm_package_version`. */\n serviceVersion?: string;\n /** Monorepo boundary: `wspace`, `global`, or `gateway`. */\n boundary: Boundary;\n /** Module slug, e.g. `auth` (omit for gateways). */\n module?: string;\n /** Deployment environment; defaults to alpha for non-production NODE_ENV. */\n env?: Env;\n /**\n * OTLP endpoint for spans/metrics/logs. Defaults to\n * `$OTEL_EXPORTER_OTLP_ENDPOINT`, then to this service's own in-cluster\n * collector — `otel-collector` in the global layer,\n * `otel-collector-wspace` in the wspace layer.\n */\n otlpEndpoint?: string;\n /** Head-based sampling ratio. Default: alpha=1.0, prod=0.1. */\n sampleRatio?: number;\n /** Extra options forwarded to `setupInstrumentation`. */\n instrumentation?: SetupInstrumentationOptions;\n /**\n * Optional trace/span id generator for the OTel tracer provider. Omit it to\n * keep the SDK's default random ids. Pass one when span ids must be derived\n * (for example a deterministic run span shared by many jobs and pods). It\n * must implement both `generateTraceId()` and `generateSpanId()`;\n * `bootstrapTelemetry` throws a `TypeError` at startup otherwise. Any\n * `IdGenerator` from `@opentelemetry/sdk-trace-base` fits.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name (see\n * `OtelModules`). Needed by services built with `bun build --compile`,\n * which have no `node_modules` to load the optional peers from at runtime.\n */\n otelModules?: OtelModules;\n}\n\nexport interface TelemetryHandle {\n /** The configured service name (for use in health routes, etc.). */\n serviceName: string;\n /** The resolved service version. */\n serviceVersion: string;\n /** Environment. */\n env: Env;\n /** The Pino-backed logger. */\n logger: BaseLogger;\n /** Initialized instrumentation (tracer + metrics + plugins). */\n instrumentation: InstrumentationSetupResult;\n /** Cleanup hook; services call on SIGTERM. */\n shutdown: () => Promise<void>;\n}\n\nfunction resolveEnv(explicit?: Env): Env {\n if (explicit) return explicit;\n const fromEnv = process.env['DEPLOY_ENV'] ?? process.env['NODE_ENV'] ?? '';\n if (fromEnv === 'production' || fromEnv === 'prod') return 'prod';\n if (fromEnv === 'development' || fromEnv === 'dev') return 'dev';\n return 'alpha';\n}\n\nfunction resolveVersion(explicit?: string): string {\n if (explicit) return explicit;\n return process.env['npm_package_version'] ?? process.env['SERVICE_VERSION'] ?? '0.0.0';\n}\n\nfunction resolveEndpoint(serviceName: string, boundary: Boundary, explicit?: string): string {\n if (explicit) return explicit;\n const fromEnv = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n if (fromEnv) return fromEnv;\n // Default to the collector in this service's OWN cluster. The previous\n // default was `alloy.sre.svc.cluster.local:4318`, which never worked on the\n // AWS estate: Alloy lives in the `monitoring` namespace (not `sre`), and its\n // OTLP receiver forwards logs to Loki only — it does not accept traces. Since\n // only the gateways and a handful of workers set OTEL_EXPORTER_OTLP_ENDPOINT\n // explicitly, that dead default is why tracing was broken fleet-wide.\n return defaultCollectorEndpoint(serviceName, boundary);\n}\n\nfunction resolveSampling(explicit: number | undefined, env: Env): number {\n if (typeof explicit === 'number' && Number.isFinite(explicit)) return Math.min(1, Math.max(0, explicit));\n const fromEnv = process.env['OTEL_TRACES_SAMPLER_ARG'];\n if (fromEnv) {\n const parsed = Number(fromEnv);\n if (Number.isFinite(parsed)) return Math.min(1, Math.max(0, parsed));\n }\n if (env === 'prod') return 0.1;\n return 1.0;\n}\n\nfunction resolveOtelSdkEnabled(): boolean {\n const sdkDisabled = process.env['OTEL_SDK_DISABLED'];\n if (sdkDisabled === 'true' || sdkDisabled === '1') return false;\n const otelEnabled = process.env['OTEL_ENABLED'];\n if (otelEnabled === 'false' || otelEnabled === '0') return false;\n return true;\n}\n\n/**\n * Bootstrap the full telemetry stack for a service.\n *\n * Services call this ONCE at startup **before** importing Prisma / GraphQL\n * Yoga / NATS so OTel can auto-instrument their dependencies.\n *\n * ```ts\n * // src/telemetry.ts\n * import { bootstrapTelemetry } from '@burdenoff/be-sdk/telemetry';\n * export const telemetry = await bootstrapTelemetry({\n * serviceName: 'wspace-auth-svc',\n * boundary: 'wspace',\n * module: 'auth',\n * });\n *\n * // src/index.ts — must be the FIRST import line.\n * import './telemetry.js';\n * ```\n */\nexport async function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle> {\n // Validate before any side effect so a broken generator fails loudly at\n // startup instead of inside the tracer provider on the first span.\n assertTelemetryIdGenerator(cfg.idGenerator);\n const env = resolveEnv(cfg.env);\n const serviceVersion = resolveVersion(cfg.serviceVersion);\n const otlpEndpoint = resolveEndpoint(cfg.serviceName, cfg.boundary, cfg.otlpEndpoint);\n const sampleRatio = resolveSampling(cfg.sampleRatio, env);\n\n // Pino logger with trace/span correlation + redaction.\n // createPinoLogger is async (loads pino via dynamic import); awaiting it\n // is required — without await, `logger` is a Promise and calls like\n // logger.warn(...) crash with \"logger.warn is not a function\" during the\n // sdk-node fallback path.\n const { createPinoLogger } = await import('./pino-logger.js');\n const logger = await createPinoLogger({\n serviceName: cfg.serviceName,\n env,\n version: serviceVersion,\n });\n setActiveTelemetryLogger(logger);\n\n // Initialize core instrumentation (tracer, metrics registry, envelop plugins).\n // `setupInstrumentation` internally calls `initializeInstrumentation`.\n const instrumentation = setupInstrumentation(cfg.serviceName, {\n ...cfg.instrumentation,\n tracing: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.tracing ?? {}),\n samplingRate: sampleRatio,\n },\n metrics: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.metrics ?? {}),\n },\n });\n\n // Start the NodeSDK exporter pipeline if sdk-node is present (optional).\n let otelSdk: OtelSdkHandle | undefined;\n if (resolveOtelSdkEnabled()) {\n // Use console.log as a Pino-independent fallback for the critical OTel\n // bootstrap path. In ACA, Pino's default async sonic-boom destination is\n // not captured by ContainerAppConsoleLogs (see pino-logger.ts), so if the\n // sync-destination fix hasn't been deployed yet the *only* way operators\n // can see OTel startup/failure messages is through console.log.\n console.log('[telemetry] OTel SDK bootstrap starting...');\n try {\n const { createOtelSdk } = await import('./sdk.js');\n otelSdk = await createOtelSdk({\n serviceName: cfg.serviceName,\n serviceVersion,\n boundary: cfg.boundary,\n module: cfg.module,\n env,\n otlpEndpoint,\n sampleRatio,\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(cfg.otelModules ? { modules: cfg.otelModules } : {}),\n });\n // Explicit success log includes metrics path status so an operator can\n // distinguish traces-only startup from full traces+metrics startup.\n logger.info('[telemetry] OpenTelemetry exporter pipeline started', {\n serviceName: cfg.serviceName,\n otlpEndpoint: otlpEndpoint ? '<configured>' : '<not set>',\n sampleRatio,\n metricsEnabled: otelSdk.metricsEnabled,\n customIdGenerator: cfg.idGenerator !== undefined,\n });\n console.log('[telemetry] OTel SDK exporter pipeline started');\n\n if (!otelSdk.metricsEnabled && otelSdk.metricsDropReason) {\n logger.warn('[telemetry] OpenTelemetry metrics reader disabled; continuing with traces only', {\n serviceName: cfg.serviceName,\n reason: otelSdk.metricsDropReason,\n });\n console.warn('[telemetry] OTel SDK metrics reader disabled:', otelSdk.metricsDropReason);\n }\n } catch (err) {\n logger.warn('[telemetry] OpenTelemetry exporter pipeline failed to start; continuing with logs only', {\n error: err instanceof Error ? err.message : String(err),\n });\n // console.error is always captured by ACA, ensuring the failure reason\n // is visible to operators even when Pino output is not.\n console.error('[telemetry] OTel SDK failed:', err);\n }\n } else {\n logger.info('[telemetry] OTel SDK exporter disabled by env');\n console.log('[telemetry] OTel SDK exporter disabled by env');\n }\n\n const shutdown = async (): Promise<void> => {\n try {\n if (otelSdk?.shutdown) await otelSdk.shutdown();\n } catch (err) {\n logger.warn('[telemetry] shutdown error (ignored)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Mirror defaultLogger so services that still use the singleton get trace-enriched output.\n defaultLogger.setLevel(logger.getLevel?.() ?? 'info');\n\n return {\n serviceName: cfg.serviceName,\n serviceVersion,\n env,\n logger: logger,\n instrumentation,\n shutdown,\n };\n}\n\n// Re-export what services typically import.\nexport { initializeInstrumentation, setupInstrumentation };\n"],"mappings":";;;;;;;;;;;;;;AA8BA,SAAgB,2BAA2B,WAA2E;CACpH,IAAI,cAAc,QAAW;CAC7B,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,IAAI,UAAU,2FAA2F;CAEjH,MAAM,EAAE,iBAAiB,mBAAmB;CAI5C,IAAI,OAAO,oBAAoB,cAAc,OAAO,mBAAmB,YACrE,MAAM,IAAI,UAAU,4FAA4F;AAEpH;;;ACyCA,SAAgB,mBAAmB,QAAoB,CAAC,GAAY;CAElE,OAAO,IAAI,MACT,CAAC,GACD,EACE,IAAI,SAAS,MAAe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CAAC,QAAQ,kBAAkB,QAAQ,mBAAmB;IACxD,SAAO,KAAK,kFAAkF;KAC5F,aAAa,IAAI;KACjB,QAAQ,QAAQ;IAClB,CAAC;IACD,QAAQ,KAAK,iDAAiD,QAAQ,iBAAiB;GACzF;EACF,SAAS,KAAK;GACZ,SAAO,KAAK,0FAA0F,EACpG,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;GAGD,QAAQ,MAAM,gCAAgC,GAAG;EACnD;CACF,OAAO;EACL,SAAO,KAAK,+CAA+C;EAC3D,QAAQ,IAAI,+CAA+C;CAC7D;CAEA,MAAM,WAAW,YAA2B;EAC1C,IAAI;GACF,IAAI,SAAS,UAAU,MAAM,QAAQ,SAAS;EAChD,SAAS,KAAK;GACZ,SAAO,KAAK,wCAAwC,EAClD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;EACH;CACF;CAGA,OAAc,SAASA,SAAO,WAAW,KAAK,MAAM;CAEpD,OAAO;EACL,aAAa,IAAI;EACjB;EACA;EACA,QAAQA;EACR;EACA;CACF;AACF"}
1
+ {"version":3,"file":"index.js","names":["BaseLogger","anyApi","logger"],"sources":["../../src/telemetry/id-generator.ts","../../src/telemetry/health.ts","../../src/telemetry/metrics-endpoint.ts","../../src/telemetry/prisma-logging.ts","../../src/telemetry/pino-redaction.ts","../../src/telemetry/pino-logger.ts","../../src/telemetry/index.ts"],"sourcesContent":["/**\n * Custom trace/span id generation for `bootstrapTelemetry`.\n *\n * `@opentelemetry/sdk-node` accepts an `idGenerator` that the tracer provider\n * uses for every new trace id and span id. Services pass one when they need\n * span ids that are derived rather than random — for example, a workflow run\n * that executes across many jobs and pods but must surface as one trace with a\n * single, deterministic `workflow.run` parent span.\n *\n * The interface below is a structural twin of `IdGenerator` from\n * `@opentelemetry/sdk-trace-base`, declared here so the SDK's public types do\n * not require that optional peer dependency to be installed. Any\n * `IdGenerator` implementation (including `RandomIdGenerator`) satisfies it.\n */\n\nexport interface TelemetryIdGenerator {\n /** Returns a trace id: 32 lowercase hex characters (16 bytes), not all zero. */\n generateTraceId(): string;\n /** Returns a span id: 16 lowercase hex characters (8 bytes), not all zero. */\n generateSpanId(): string;\n}\n\n/**\n * Validate a caller-supplied id generator before it reaches the OTel SDK.\n *\n * A generator without both methods would make the tracer provider throw on\n * the first span, long after startup. Failing at bootstrap instead surfaces\n * the misconfiguration where it was made. `undefined` is accepted and means\n * \"use the SDK's default random generator\".\n */\nexport function assertTelemetryIdGenerator(candidate: unknown): asserts candidate is TelemetryIdGenerator | undefined {\n if (candidate === undefined) return;\n if (typeof candidate !== 'object' || candidate === null) {\n throw new TypeError('bootstrapTelemetry: idGenerator must be an object with generateTraceId and generateSpanId');\n }\n const { generateTraceId, generateSpanId } = candidate as {\n generateTraceId?: unknown;\n generateSpanId?: unknown;\n };\n if (typeof generateTraceId !== 'function' || typeof generateSpanId !== 'function') {\n throw new TypeError('bootstrapTelemetry: idGenerator must implement both generateTraceId() and generateSpanId()');\n }\n}\n","/**\n * `/health`, `/health/live`, `/health/ready` Elysia routes with a 1s\n * result cache so readiness checks can't stampede Postgres.\n *\n * Dependencies (prisma, eventQueue, valkey) are optional — omit any client and\n * the readiness check simply skips it.\n */\n\ninterface PrismaLike {\n $queryRaw: (strings: TemplateStringsArray) => Promise<unknown>;\n}\ninterface EventQueueLike {\n isConnected?: () => boolean | Promise<boolean>;\n healthCheck?: () => Promise<{ ok: boolean }>;\n}\ninterface ValkeyLike {\n ping: () => Promise<unknown>;\n}\n\nexport interface HealthDeps {\n prisma?: PrismaLike;\n eventQueue?: EventQueueLike;\n valkey?: ValkeyLike;\n /** Service version reported on /health. */\n version?: string;\n /** Service name reported on /health. */\n serviceName?: string;\n}\n\ninterface CachedStatus {\n ready: boolean;\n checked: Record<string, { ok: boolean; error?: string }>;\n at: number;\n}\n\nconst CACHE_TTL_MS = 1000;\n\nasync function probeReady(deps: HealthDeps): Promise<CachedStatus> {\n const checked: Record<string, { ok: boolean; error?: string }> = {};\n\n if (deps.prisma) {\n try {\n await deps.prisma.$queryRaw`SELECT 1`;\n checked['postgres'] = { ok: true };\n } catch (err) {\n checked['postgres'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.eventQueue) {\n try {\n const connected =\n typeof deps.eventQueue.isConnected === 'function'\n ? await Promise.resolve(deps.eventQueue.isConnected())\n : ((await deps.eventQueue.healthCheck?.())?.ok ?? true);\n checked['eventQueue'] = { ok: Boolean(connected) };\n } catch (err) {\n checked['eventQueue'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n if (deps.valkey) {\n try {\n await deps.valkey.ping();\n checked['valkey'] = { ok: true };\n } catch (err) {\n checked['valkey'] = {\n ok: false,\n error: err instanceof Error ? err.message : String(err),\n };\n }\n }\n\n const ready = Object.values(checked).every((c) => c.ok);\n return { ready, checked, at: Date.now() };\n}\n\nexport function createHealthRoutes(_deps: HealthDeps = {}): unknown {\n // Return an Elysia app lazily so be-sdk doesn't hard-require elysia.\n return new Proxy(\n {},\n {\n get(_target, prop): unknown {\n // Tell TypeScript consumers the returned object is an Elysia plugin;\n // the actual mount happens via `createHealthRoutesImpl`. Services\n // that prefer direct use can call `createHealthRoutesImpl(elysia, deps)`.\n if (prop === 'use' || prop === 'then') return undefined;\n return undefined;\n },\n }\n );\n}\n\n/**\n * Mount health routes on an existing Elysia app. Callers hold a reference\n * to Elysia themselves; be-sdk stays decoupled.\n */\nexport function createHealthRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, deps: HealthDeps = {}): App {\n let cache: CachedStatus | null = null;\n\n const getStatus = async (): Promise<CachedStatus> => {\n if (cache && Date.now() - cache.at < CACHE_TTL_MS) return cache;\n cache = await probeReady(deps);\n return cache;\n };\n\n app.get('/health/live', () => ({\n status: 'ok',\n serviceName: deps.serviceName,\n version: deps.version,\n }));\n\n app.get('/health/ready', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n };\n });\n\n app.get('/health', async (ctx: unknown): Promise<unknown> => {\n const status = await getStatus();\n const ctxWithSet = ctx as { set?: { status?: number } };\n if (!status.ready && ctxWithSet.set) ctxWithSet.set.status = 503;\n return {\n status: status.ready ? 'ok' : 'degraded',\n serviceName: deps.serviceName,\n version: deps.version,\n checks: status.checked,\n uptime_s: Math.round(process.uptime()),\n };\n });\n\n return app;\n}\n","/**\n * Prometheus `/metrics` route mounter. Uses the shared `prom-client`\n * default registry so all instrumentation (GraphQL Envelop, Prisma,\n * runtime) shows up on a single endpoint.\n */\n\nimport { collectPromDefaultMetrics, type PromDefaultMetricsClient } from './bun-runtime-metrics.js';\n\ninterface PromRegistryLike {\n metrics: () => Promise<string> | string;\n contentType?: string;\n}\n\nexport interface MetricsMountOptions {\n registry?: PromRegistryLike;\n path?: string;\n}\n\nexport async function loadDefaultRegistry(): Promise<PromRegistryLike | null> {\n try {\n const mod = (await import('prom-client')) as unknown as PromDefaultMetricsClient & {\n register: PromRegistryLike;\n };\n // Kick runtime metrics into the default registry if not already. Under Bun\n // this leaves out the heap-space gauges, whose collect walks the heap (BOFF-12287).\n collectPromDefaultMetrics(mod);\n return mod.register;\n } catch {\n return null;\n }\n}\n\nexport function createMetricsRoutesImpl<\n App extends {\n get: (path: string, handler: (ctx: unknown) => unknown) => App;\n },\n>(app: App, opts: MetricsMountOptions = {}): App {\n const path = opts.path ?? '/metrics';\n\n app.get(path, async (ctx: unknown): Promise<unknown> => {\n const registry = opts.registry ?? (await loadDefaultRegistry());\n const ctxWithSet = ctx as { set?: { status?: number; headers?: Record<string, string> } };\n if (!registry) {\n if (ctxWithSet.set) ctxWithSet.set.status = 503;\n return '# prom-client not installed\\n';\n }\n if (ctxWithSet.set) {\n ctxWithSet.set.status = 200;\n ctxWithSet.set.headers = {\n 'content-type': registry.contentType ?? 'text/plain; version=0.0.4; charset=utf-8',\n };\n }\n return registry.metrics();\n });\n\n return app;\n}\n\n/**\n * Legacy export name used by the service template. Composes the Elysia\n * plugin-style function that `new Elysia().use(...)` accepts.\n */\nexport function createMetricsRoutes(opts: MetricsMountOptions = {}): unknown {\n return (app: Parameters<typeof createMetricsRoutesImpl>[0]): unknown => createMetricsRoutesImpl(app, opts);\n}\n","/**\n * Prisma client extension that pipes query events through the SDK logger\n * with trace/span correlation fields auto-injected. The\n * `@prisma/instrumentation` peer provides the spans\n * themselves; this extension only adds structured log events on top.\n */\nimport type { Logger } from '../logger/index.js';\nimport { redactSensitiveFields } from '../logger/index.js';\n\ntype PrismaQueryArgs = {\n model?: string;\n operation: string;\n args: unknown;\n query: (args: unknown) => Promise<unknown>;\n};\n\n/**\n * Returns a Prisma Client extension object compatible with the\n * `$extends()` API (Prisma v5+).\n *\n * ```ts\n * export const prisma = new PrismaClient().$extends(\n * createPrismaLoggingExtension(logger)\n * );\n * ```\n */\nexport function createPrismaLoggingExtension(logger: Logger): {\n name: string;\n query: {\n $allOperations: (args: PrismaQueryArgs) => Promise<unknown>;\n };\n} {\n return {\n name: 'burdenoff-pino-logging',\n query: {\n async $allOperations({ model, operation, args, query }: PrismaQueryArgs): Promise<unknown> {\n const start = Date.now();\n try {\n const result = await query(args);\n logger.debug('prisma.query', {\n model,\n operation,\n duration_ms: Date.now() - start,\n args: redactSensitiveFields(args),\n });\n return result;\n } catch (err) {\n logger.error('prisma.error', {\n model,\n operation,\n duration_ms: Date.now() - start,\n error: err instanceof Error ? err.message : String(err),\n });\n throw err;\n }\n },\n },\n };\n}\n","/**\n * Default Pino redact paths — covers the Burdenoff authorization +\n * gateway header + NATS/GraphQL payload surface area.\n *\n * Services can extend this list via their own Pino options.\n */\nexport const DEFAULT_REDACT_PATHS: readonly string[] = Object.freeze([\n 'password',\n '*.password',\n '*.*.password',\n 'token',\n 'authToken',\n 'workspaceToken',\n 'accessToken',\n 'refreshToken',\n 'clientSecret',\n 'apiKey',\n '*.apiKey',\n 'authorization',\n 'req.headers.authorization',\n 'req.headers[\"x-workspace-authorization\"]',\n 'req.headers.cookie',\n 'res.headers[\"set-cookie\"]',\n 'params.*.password',\n 'params.*.token',\n 'params.*.secret',\n]);\n","/**\n * Pino logger wrapper that emits structured JSON with trace/span correlation\n * fields. Falls back to the SDK's built-in Logger when `pino` isn't installed\n * so services without the peer dep still compile and run.\n *\n * # ACA stdout compatibility\n *\n * In Azure Container Apps the ContainerAppConsoleLogs agent captures\n * `console.log` / `process.stdout.write` output but does *not* reliably\n * capture Pino's default async sonic-boom destination (which writes to fd 1\n * through Node.js `fs.writeSync` / `fs.write`). This means every log line\n * produced through Pino's default destination is invisible in Log Analytics.\n *\n * The fix mirrors what the gateway's own `logger.ts` does in production:\n * pass `pino.destination({ sync: true })` as the second argument to the\n * Pino factory so writes are synchronous and go through a path that ACA\n * captures correctly.\n */\nimport { Logger as BaseLogger } from '../logger/index.js';\nimport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\n\nexport interface PinoLoggerConfig {\n serviceName: string;\n env: 'alpha' | 'prod' | 'dev';\n version: string;\n /** Override Pino log level. Default: warn (prod), info (alpha/dev). */\n level?: 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';\n /** Extra redact paths appended to DEFAULT_REDACT_PATHS. */\n redactPaths?: string[];\n}\n\ninterface PinoLike {\n level: string;\n fatal: (...args: unknown[]) => void;\n error: (...args: unknown[]) => void;\n warn: (...args: unknown[]) => void;\n info: (...args: unknown[]) => void;\n debug: (...args: unknown[]) => void;\n trace: (...args: unknown[]) => void;\n child: (bindings: Record<string, unknown>) => PinoLike;\n}\n\n/**\n * Loaded Pino module: factory function + a synchronous destination factory.\n * In ACA, Pino's default async sonic-boom destination is invisible in Log\n * Analytics, so we always use a sync destination.\n */\ninterface PinoLoader {\n factory: (opts: unknown, dest?: unknown) => PinoLike;\n makeDest: () => unknown;\n}\n\nasync function tryLoadPino(): Promise<PinoLoader | null> {\n try {\n const mod = (await import('pino')) as unknown as { default?: unknown };\n const candidate = (mod.default ?? mod) as unknown;\n if (typeof candidate === 'function') {\n const factory = candidate as (opts: unknown, dest?: unknown) => PinoLike;\n const destination = (factory as unknown as Record<string, unknown>)?.['destination'] as\n ((opts?: { sync?: boolean }) => unknown) | undefined;\n const makeDest = typeof destination === 'function' ? () => destination({ sync: true }) : () => undefined;\n return { factory, makeDest };\n }\n return null;\n } catch {\n return null;\n }\n}\n\nclass PinoAdapter extends BaseLogger {\n constructor(private readonly pino: PinoLike) {\n super({\n level: (pino.level as BaseLogger['getLevel'] extends () => infer L ? L : never) ?? 'info',\n console: false,\n });\n }\n\n public override debug(message: string, ...args: unknown[]): void {\n this.pino.debug(this.mergeArgs(args), message);\n }\n public override info(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override warn(message: string, ...args: unknown[]): void {\n this.pino.warn(this.mergeArgs(args), message);\n }\n public override error(message: string, ...args: unknown[]): void {\n this.pino.error(this.mergeArgs(args), message);\n }\n public override log(message: string, ...args: unknown[]): void {\n this.pino.info(this.mergeArgs(args), message);\n }\n public override trace(message: string, ...args: unknown[]): void {\n this.pino.trace(this.mergeArgs(args), message);\n }\n\n private mergeArgs(args: unknown[]): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n for (const arg of args) {\n if (arg instanceof Error) {\n out['err'] = { message: arg.message, stack: arg.stack, name: arg.name };\n } else if (arg && typeof arg === 'object') {\n Object.assign(out, arg as Record<string, unknown>);\n } else if (arg !== undefined && arg !== null) {\n out['data'] = arg;\n }\n }\n return out;\n }\n}\n\n/**\n * Build a logger instance. Returns a Pino-backed adapter when `pino` is\n * installed; otherwise falls back to the SDK's built-in JSON Logger.\n *\n * Services call this through `bootstrapTelemetry`, not directly.\n */\nexport async function createPinoLogger(cfg: PinoLoggerConfig): Promise<BaseLogger> {\n const loader = await tryLoadPino();\n if (!loader) {\n // No pino — fall back to the built-in Logger with console output.\n const fallback = new BaseLogger({ level: cfg.env === 'prod' ? 'warn' : 'info', console: true });\n fallback.setContext({\n service: cfg.serviceName,\n env: cfg.env,\n version: cfg.version,\n });\n return fallback;\n }\n\n const redactPaths = [...DEFAULT_REDACT_PATHS, ...(cfg.redactPaths ?? [])];\n const dest = loader.makeDest();\n const pino = loader.factory(\n {\n name: cfg.serviceName,\n level: cfg.level ?? (cfg.env === 'prod' ? 'warn' : 'info'),\n base: {\n service: { name: cfg.serviceName, version: cfg.version },\n env: cfg.env,\n },\n redact: {\n paths: redactPaths,\n censor: '[REDACTED]',\n remove: false,\n },\n timestamp: () => `,\"time\":\"${new Date().toISOString()}\"`,\n mixin: () => pickTraceFields(),\n },\n // Explicit sync destination so output is visible in ACA Log Analytics.\n // Without this, Pino uses its default async sonic-boom which writes to fd 1\n // but the ContainerAppConsoleLogs agent doesn't capture it on Bun.\n dest\n );\n return new PinoAdapter(pino);\n}\n\nfunction pickTraceFields(): Record<string, string> {\n try {\n // Pull active span context via @opentelemetry/api if installed.\n // Use require-style dynamic access to keep this file dep-free.\n const api = (globalThis as unknown as { __otelApi?: unknown }).__otelApi;\n if (!api) return {};\n const anyApi = api as {\n trace: {\n getActiveSpan: () => { spanContext: () => { traceId: string; spanId: string; traceFlags: number } } | undefined;\n };\n };\n const span = anyApi.trace.getActiveSpan();\n if (!span) return {};\n const ctx = span.spanContext();\n return {\n trace_id: ctx.traceId,\n span_id: ctx.spanId,\n trace_flags: ctx.traceFlags.toString(16).padStart(2, '0'),\n };\n } catch {\n return {};\n }\n}\n","/**\n * Unified telemetry bootstrap for Burdenoff services.\n *\n * Composes the existing `instrumentation/` + `observability/` + `logger/`\n * modules and adds:\n * - `bootstrapTelemetry({ serviceName, boundary, module, env })` — single\n * call that initializes OTel, wires Pino logger with trace fields,\n * exposes GraphQL Yoga plugins, registers process exit hooks.\n * - `createHealthRoutes({ prisma, nats, valkey, version })` — `/health`,\n * `/health/live`, `/health/ready` Elysia routes.\n * - `createMetricsRoutes(registry?)` — `/metrics` Prometheus exposition.\n * - `createPrismaLoggingExtension(logger)` — Prisma extension that pipes\n * query events through Pino with trace/span correlation ids.\n *\n * The module does not pull in `@opentelemetry/sdk-node` or `pino` as direct\n * deps — services install those as optional peers, and imports are lazy so\n * services that don't install them still load.\n */\n\nimport type { Logger as BaseLogger } from '../logger/index.js';\nimport { logger as defaultLogger } from '../logger/index.js';\nimport {\n initializeInstrumentation,\n setupInstrumentation,\n type SetupInstrumentationOptions,\n type InstrumentationSetupResult,\n} from '../instrumentation/index.js';\nimport { defaultCollectorEndpoint } from './collector-endpoint.js';\nimport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nimport { setActiveTelemetryLogger } from './logger-state.js';\nimport type { OtelModules, OtelSdkHandle } from './sdk.js';\n\nexport type { OtelModules, OtelPeerPackage } from './sdk.js';\n\nexport { createHealthRoutes } from './health.js';\nexport { createMetricsRoutes } from './metrics-endpoint.js';\nexport { createPrismaLoggingExtension } from './prisma-logging.js';\nexport { DEFAULT_REDACT_PATHS } from './pino-redaction.js';\nexport { createPinoLogger } from './pino-logger.js';\nexport { assertTelemetryIdGenerator, type TelemetryIdGenerator } from './id-generator.js';\nexport {\n COLLECTOR_SERVICE,\n OTLP_HTTP_PORT,\n defaultCollectorEndpoint,\n defaultCollectorTracesEndpoint,\n resolveCollectorLayer,\n type CollectorLayer,\n} from './collector-endpoint.js';\n\nexport type Boundary = 'wspace' | 'global' | 'gateway';\nexport type Env = 'alpha' | 'prod' | 'dev';\n\nexport interface TelemetryConfig {\n /** Full service name, e.g. \"wspace-auth-svc\". */\n serviceName: string;\n /** Semver of the service deployment; defaults to `process.env.npm_package_version`. */\n serviceVersion?: string;\n /** Monorepo boundary: `wspace`, `global`, or `gateway`. */\n boundary: Boundary;\n /** Module slug, e.g. `auth` (omit for gateways). */\n module?: string;\n /** Deployment environment; defaults to alpha for non-production NODE_ENV. */\n env?: Env;\n /**\n * OTLP endpoint for spans/metrics/logs. Defaults to\n * `$OTEL_EXPORTER_OTLP_ENDPOINT`, then to this service's own in-cluster\n * collector — `otel-collector` in the global layer,\n * `otel-collector-wspace` in the wspace layer.\n */\n otlpEndpoint?: string;\n /** Head-based sampling ratio. Default: alpha=1.0, prod=0.1. */\n sampleRatio?: number;\n /** Extra options forwarded to `setupInstrumentation`. */\n instrumentation?: SetupInstrumentationOptions;\n /**\n * Optional trace/span id generator for the OTel tracer provider. Omit it to\n * keep the SDK's default random ids. Pass one when span ids must be derived\n * (for example a deterministic run span shared by many jobs and pods). It\n * must implement both `generateTraceId()` and `generateSpanId()`;\n * `bootstrapTelemetry` throws a `TypeError` at startup otherwise. Any\n * `IdGenerator` from `@opentelemetry/sdk-trace-base` fits.\n */\n idGenerator?: TelemetryIdGenerator;\n /**\n * Pre-loaded OpenTelemetry packages, keyed by package name (see\n * `OtelModules`). Needed by services built with `bun build --compile`,\n * which have no `node_modules` to load the optional peers from at runtime.\n */\n otelModules?: OtelModules;\n}\n\nexport interface TelemetryHandle {\n /** The configured service name (for use in health routes, etc.). */\n serviceName: string;\n /** The resolved service version. */\n serviceVersion: string;\n /** Environment. */\n env: Env;\n /** The Pino-backed logger. */\n logger: BaseLogger;\n /** Initialized instrumentation (tracer + metrics + plugins). */\n instrumentation: InstrumentationSetupResult;\n /** Cleanup hook; services call on SIGTERM. */\n shutdown: () => Promise<void>;\n}\n\nfunction resolveEnv(explicit?: Env): Env {\n if (explicit) return explicit;\n const fromEnv = process.env['DEPLOY_ENV'] ?? process.env['NODE_ENV'] ?? '';\n if (fromEnv === 'production' || fromEnv === 'prod') return 'prod';\n if (fromEnv === 'development' || fromEnv === 'dev') return 'dev';\n return 'alpha';\n}\n\nfunction resolveVersion(explicit?: string): string {\n if (explicit) return explicit;\n return process.env['npm_package_version'] ?? process.env['SERVICE_VERSION'] ?? '0.0.0';\n}\n\nfunction resolveEndpoint(serviceName: string, boundary: Boundary, explicit?: string): string {\n if (explicit) return explicit;\n const fromEnv = process.env['OTEL_EXPORTER_OTLP_ENDPOINT'];\n if (fromEnv) return fromEnv;\n // Default to the collector in this service's OWN cluster. The previous\n // default was `alloy.sre.svc.cluster.local:4318`, which never worked on the\n // AWS estate: Alloy lives in the `monitoring` namespace (not `sre`), and its\n // OTLP receiver forwards logs to Loki only — it does not accept traces. Since\n // only the gateways and a handful of workers set OTEL_EXPORTER_OTLP_ENDPOINT\n // explicitly, that dead default is why tracing was broken fleet-wide.\n return defaultCollectorEndpoint(serviceName, boundary);\n}\n\nfunction resolveSampling(explicit: number | undefined, env: Env): number {\n if (typeof explicit === 'number' && Number.isFinite(explicit)) return Math.min(1, Math.max(0, explicit));\n const fromEnv = process.env['OTEL_TRACES_SAMPLER_ARG'];\n if (fromEnv) {\n const parsed = Number(fromEnv);\n if (Number.isFinite(parsed)) return Math.min(1, Math.max(0, parsed));\n }\n if (env === 'prod') return 0.1;\n return 1.0;\n}\n\nfunction resolveOtelSdkEnabled(): boolean {\n const sdkDisabled = process.env['OTEL_SDK_DISABLED'];\n if (sdkDisabled === 'true' || sdkDisabled === '1') return false;\n const otelEnabled = process.env['OTEL_ENABLED'];\n if (otelEnabled === 'false' || otelEnabled === '0') return false;\n return true;\n}\n\n/**\n * Bootstrap the full telemetry stack for a service.\n *\n * Services call this ONCE at startup **before** importing Prisma / GraphQL\n * Yoga / NATS so OTel can auto-instrument their dependencies.\n *\n * ```ts\n * // src/telemetry.ts\n * import { bootstrapTelemetry } from '@burdenoff/be-sdk/telemetry';\n * export const telemetry = await bootstrapTelemetry({\n * serviceName: 'wspace-auth-svc',\n * boundary: 'wspace',\n * module: 'auth',\n * });\n *\n * // src/index.ts — must be the FIRST import line.\n * import './telemetry.js';\n * ```\n */\nexport async function bootstrapTelemetry(cfg: TelemetryConfig): Promise<TelemetryHandle> {\n // Validate before any side effect so a broken generator fails loudly at\n // startup instead of inside the tracer provider on the first span.\n assertTelemetryIdGenerator(cfg.idGenerator);\n const env = resolveEnv(cfg.env);\n const serviceVersion = resolveVersion(cfg.serviceVersion);\n const otlpEndpoint = resolveEndpoint(cfg.serviceName, cfg.boundary, cfg.otlpEndpoint);\n const sampleRatio = resolveSampling(cfg.sampleRatio, env);\n\n // Pino logger with trace/span correlation + redaction.\n // createPinoLogger is async (loads pino via dynamic import); awaiting it\n // is required — without await, `logger` is a Promise and calls like\n // logger.warn(...) crash with \"logger.warn is not a function\" during the\n // sdk-node fallback path.\n const { createPinoLogger } = await import('./pino-logger.js');\n const logger = await createPinoLogger({\n serviceName: cfg.serviceName,\n env,\n version: serviceVersion,\n });\n setActiveTelemetryLogger(logger);\n\n // Initialize core instrumentation (tracer, metrics registry, envelop plugins).\n // `setupInstrumentation` internally calls `initializeInstrumentation`.\n const instrumentation = setupInstrumentation(cfg.serviceName, {\n ...cfg.instrumentation,\n tracing: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.tracing ?? {}),\n samplingRate: sampleRatio,\n },\n metrics: {\n serviceName: cfg.serviceName,\n ...(cfg.instrumentation?.metrics ?? {}),\n },\n });\n\n // Start the NodeSDK exporter pipeline if sdk-node is present (optional).\n let otelSdk: OtelSdkHandle | undefined;\n if (resolveOtelSdkEnabled()) {\n // Use console.log as a Pino-independent fallback for the critical OTel\n // bootstrap path. In ACA, Pino's default async sonic-boom destination is\n // not captured by ContainerAppConsoleLogs (see pino-logger.ts), so if the\n // sync-destination fix hasn't been deployed yet the *only* way operators\n // can see OTel startup/failure messages is through console.log.\n console.log('[telemetry] OTel SDK bootstrap starting...');\n try {\n const { createOtelSdk } = await import('./sdk.js');\n otelSdk = await createOtelSdk({\n serviceName: cfg.serviceName,\n serviceVersion,\n boundary: cfg.boundary,\n module: cfg.module,\n env,\n otlpEndpoint,\n sampleRatio,\n ...(cfg.idGenerator ? { idGenerator: cfg.idGenerator } : {}),\n ...(cfg.otelModules ? { modules: cfg.otelModules } : {}),\n });\n // Explicit success log includes metrics path status so an operator can\n // distinguish traces-only startup from full traces+metrics startup.\n logger.info('[telemetry] OpenTelemetry exporter pipeline started', {\n serviceName: cfg.serviceName,\n otlpEndpoint: otlpEndpoint ? '<configured>' : '<not set>',\n sampleRatio,\n metricsEnabled: otelSdk.metricsEnabled,\n customIdGenerator: cfg.idGenerator !== undefined,\n });\n console.log('[telemetry] OTel SDK exporter pipeline started');\n\n if (!otelSdk.metricsEnabled && otelSdk.metricsDropReason) {\n logger.warn('[telemetry] OpenTelemetry metrics reader disabled; continuing with traces only', {\n serviceName: cfg.serviceName,\n reason: otelSdk.metricsDropReason,\n });\n console.warn('[telemetry] OTel SDK metrics reader disabled:', otelSdk.metricsDropReason);\n }\n } catch (err) {\n logger.warn('[telemetry] OpenTelemetry exporter pipeline failed to start; continuing with logs only', {\n error: err instanceof Error ? err.message : String(err),\n });\n // console.error is always captured by ACA, ensuring the failure reason\n // is visible to operators even when Pino output is not.\n console.error('[telemetry] OTel SDK failed:', err);\n }\n } else {\n logger.info('[telemetry] OTel SDK exporter disabled by env');\n console.log('[telemetry] OTel SDK exporter disabled by env');\n }\n\n const shutdown = async (): Promise<void> => {\n try {\n if (otelSdk?.shutdown) await otelSdk.shutdown();\n } catch (err) {\n logger.warn('[telemetry] shutdown error (ignored)', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n };\n\n // Mirror defaultLogger so services that still use the singleton get trace-enriched output.\n defaultLogger.setLevel(logger.getLevel?.() ?? 'info');\n\n return {\n serviceName: cfg.serviceName,\n serviceVersion,\n env,\n logger: logger,\n instrumentation,\n shutdown,\n };\n}\n\n// Re-export what services typically import.\nexport { initializeInstrumentation, setupInstrumentation };\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,SAAgB,2BAA2B,WAA2E;CACpH,IAAI,cAAc,QAAW;CAC7B,IAAI,OAAO,cAAc,YAAY,cAAc,MACjD,MAAM,IAAI,UAAU,2FAA2F;CAEjH,MAAM,EAAE,iBAAiB,mBAAmB;CAI5C,IAAI,OAAO,oBAAoB,cAAc,OAAO,mB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BAAgB,QAAQ;IACxB,mBAAmB,IAAI,gBAAgB;GACzC,CAAC;GACD,QAAQ,IAAI,gDAAgD;GAE5D,IAAI,CAAC,QAAQ,kBAAkB,QAAQ,mBAAmB;IACxD,SAAO,KAAK,kFAAkF;KAC5F,aAAa,IAAI;KACjB,QAAQ,QAAQ;IAClB,CAAC;IACD,QAAQ,KAAK,iDAAiD,QAAQ,iBAAiB;GACzF;EACF,SAAS,KAAK;GACZ,SAAO,KAAK,0FAA0F,EACpG,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;GAGD,QAAQ,MAAM,gCAAgC,GAAG;EACnD;CACF,OAAO;EACL,SAAO,KAAK,+CAA+C;EAC3D,QAAQ,IAAI,+CAA+C;CAC7D;CAEA,MAAM,WAAW,YAA2B;EAC1C,IAAI;GACF,IAAI,SAAS,UAAU,MAAM,QAAQ,SAAS;EAChD,SAAS,KAAK;GACZ,SAAO,KAAK,wCAAwC,EAClD,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EACxD,CAAC;EACH;CACF;CAGA,OAAc,SAASA,SAAO,WAAW,KAAK,MAAM;CAEpD,OAAO;EACL,aAAa,IAAI;EACjB;EACA;EACA,QAAQA;EACR;EACA;CACF;AACF"}
@@ -1,2 +1,2 @@
1
- import { a as TemporalWorkerManager, c as TemporalClientFactory, i as TemporalWorkerFactory, l as WorkflowStartOptions, n as TemporalWorker, o as TemporalClient, r as TemporalWorkerConfig, s as TemporalClientConfig, t as TemporalModule } from "../index-CaM9JUcc.js";
1
+ import { a as TemporalWorkerManager, c as TemporalClientFactory, i as TemporalWorkerFactory, l as WorkflowStartOptions, n as TemporalWorker, o as TemporalClient, r as TemporalWorkerConfig, s as TemporalClientConfig, t as TemporalModule } from "../index-DSynXDRD.js";
2
2
  export { TemporalClient, type TemporalClientConfig, TemporalClientFactory, TemporalModule, TemporalWorker, type TemporalWorkerConfig, TemporalWorkerFactory, TemporalWorkerManager, type WorkflowStartOptions };
@@ -1,5 +1,5 @@
1
1
  import { a as ActorOrigin, n as AI_ASSISTANT_ACTOR_ORIGIN, o as AssistantSessionAttribution } from "../assistant-session-DA5ZKJOr.js";
2
2
  import { t as suppressMutationAudit } from "../explicit-activity-scope-D8VeGGpt.js";
3
- import { p as UsageMetricType } from "../index-CVCyKzhB.js";
4
- import { S as trackerStub, _ as UsageTrackingOptions, a as AGENT_ACTIVITY_RESOURCE_TYPE, b as resolveAssistantSession, c as trackAgentActivity, d as RbacCheckOptions, f as TrackedActorType, g as UnifiedTrackingOptions, h as UnifiedTrackerStub, i as AGENT_ACTIVITY_ACTIONS, l as ActivityTrackingOptions, m as UNIFIED_TRACKER_CONSTANTS, n as TrackResult, o as AgentActivityAction, p as TrackingEvent, r as TrackerModule, s as AgentActivityOptions, t as TrackOptions, u as ProductTracker, v as createProductTracker, x as trackOperation, y as isTrackedActorType } from "../index-zd_NPGJo.js";
3
+ import { p as UsageMetricType } from "../index-DWER4-_x.js";
4
+ import { S as trackerStub, _ as UsageTrackingOptions, a as AGENT_ACTIVITY_RESOURCE_TYPE, b as resolveAssistantSession, c as trackAgentActivity, d as RbacCheckOptions, f as TrackedActorType, g as UnifiedTrackingOptions, h as UnifiedTrackerStub, i as AGENT_ACTIVITY_ACTIONS, l as ActivityTrackingOptions, m as UNIFIED_TRACKER_CONSTANTS, n as TrackResult, o as AgentActivityAction, p as TrackingEvent, r as TrackerModule, s as AgentActivityOptions, t as TrackOptions, u as ProductTracker, v as createProductTracker, x as trackOperation, y as isTrackedActorType } from "../index-DqpCL9kD.js";
5
5
  export { AGENT_ACTIVITY_ACTIONS, AGENT_ACTIVITY_RESOURCE_TYPE, AI_ASSISTANT_ACTOR_ORIGIN, type ActivityTrackingOptions, type ActorOrigin, type AgentActivityAction, type AgentActivityOptions, type AssistantSessionAttribution, type ProductTracker, type RbacCheckOptions, TrackOptions, TrackResult, type TrackedActorType, TrackerModule, type TrackingEvent, UNIFIED_TRACKER_CONSTANTS, UnifiedTrackerStub, type UnifiedTrackingOptions, UsageMetricType, type UsageTrackingOptions, createProductTracker, isTrackedActorType, resolveAssistantSession, suppressMutationAudit, trackAgentActivity, trackOperation, trackerStub };
@@ -1,8 +1,8 @@
1
1
  import { i as suppressMutationAudit } from "../explicit-activity-scope-DikJ7NAE.js";
2
2
  import "../activity/index.js";
3
- import { i as UsageMetricType } from "../usage-BRqVP3CJ.js";
3
+ import { i as UsageMetricType } from "../usage-ygkKsxdd.js";
4
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-BUnfMiAS.js";
5
- import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-PQztSlhJ.js";
5
+ import { i as trackAgentActivity, n as AGENT_ACTIVITY_ACTIONS, r as AGENT_ACTIVITY_RESOURCE_TYPE, t as TrackerModule } from "../tracker-Cl3cGKe-.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
@@ -2,7 +2,7 @@ import { PermissionDeniedError, QuotaExceededError, ValidationError } from "./ty
2
2
  import { a as logger } from "./logger-B6rCpb7D.js";
3
3
  import { t as RBACModule } from "./rbac-Dvz0YzEt.js";
4
4
  import { ActivityModule, ActivitySeverity, ActivityStatus, ActivityType } from "./activity/index.js";
5
- import { a as UsageModule } from "./usage-BRqVP3CJ.js";
5
+ import { a as UsageModule } from "./usage-ygkKsxdd.js";
6
6
  import { n as NotificationType, r as NotificationsModule } from "./notifications-DY_i37WN.js";
7
7
  import { o as trackOperation } from "./stub-BUnfMiAS.js";
8
8
  import { r as runInExplicitActivityScope, t as createExplicitActivityScope } from "./explicit-activity-scope-DikJ7NAE.js";
@@ -455,4 +455,4 @@ var TrackerModule = class {
455
455
  };
456
456
 
457
457
  export { trackAgentActivity as i, AGENT_ACTIVITY_ACTIONS as n, AGENT_ACTIVITY_RESOURCE_TYPE as r, TrackerModule as t };
458
- //# sourceMappingURL=tracker-PQztSlhJ.js.map
458
+ //# sourceMappingURL=tracker-Cl3cGKe-.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"tracker-PQztSlhJ.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,QA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C;EAEhF,MAAM,UAAU,MAAM,QAAQ,IAAI,WAAW,KAAK,OAAO,KAAK,MAAM,EAAE,CAAC,CAAC;EAExE,OAAO,KAAK,sCAAsC;GAChD,OAAO,QAAQ;GACf,YAAY,QAAQ,QAAQ,MAAM,EAAE,OAAO,CAAC,CAAC;GAC7C,QAAQ,QAAQ,QAAQ,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;EAC5C,CAAC;EAED,OAAO;CACT;AACF"}
1
+ {"version":3,"file":"tracker-Cl3cGKe-.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;IA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AAE,CAAC,CAAC;EAExE,OAAO,KAAK,sCAAsC;GAChD,OAAO,QAAQ;GACf,YAAY,QAAQ,QAAQ,MAAM,EAAE,OAAO,CAAC,CAAC;GAC7C,QAAQ,QAAQ,QAAQ,MAAM,CAAC,EAAE,OAAO,CAAC,CAAC;EAC5C,CAAC;EAED,OAAO;CACT;AACF"}
@@ -1,5 +1,5 @@
1
- import { t as BurdenoffGraphQLClient } from "../graphql-CUDyhibV.js";
2
- import { p as SDKContext } from "../index-CTTwo9av.js";
1
+ import { t as BurdenoffGraphQLClient } from "../graphql-C8jKLLel.js";
2
+ import { p as SDKContext } from "../index-BTaQMEgB.js";
3
3
  export type SupportedLanguage = 'en' | 'es' | 'fr' | 'de' | 'it' | 'pt' | 'ru' | 'zh' | 'ja' | 'ko' | 'ar' | 'hi' | 'bn' | 'ta' | 'te' | 'ml';
4
4
  export interface TranslationOptions {
5
5
  text: string;
@@ -1,3 +1,3 @@
1
- import { a as DEFAULT_LAYER_RESOURCES, c as GatewayRetryConfig, d as LayerFullConfig, f as LayerGatewayConfig, i as DEFAULT_GATEWAY_ROUTING, l as GatewayRoutingConfig, m as ServiceLayer, n as DEFAULT_CIRCUIT_BREAKER_CONFIG, o as DEFAULT_LAYER_STREAMS, p as LayerResourceUrls, r as DEFAULT_GATEWAY_RETRY_CONFIG, s as GatewayRequestHeaders, t as CircuitBreakerConfig, u as LayerConfig } from "../layer-BZBZZWeV.js";
2
- import { _ as TemporalHealthStatus, a as EventQueueSDKConfig, c as NetworkError, d as RetryConfig, f as SDKConfig, g as SDKShutdownOptions, h as SDKHealthStatus, i as EventQueueHealthStatus, l as PermissionDeniedError, m as SDKError, n as ActorType, o as LoggerConfig, p as SDKContext, r as AuthenticationError, s as LoggerTransport, t as APIError, u as QuotaExceededError, v as TimeoutError, y as ValidationError } from "../index-CTTwo9av.js";
1
+ import { a as DEFAULT_LAYER_RESOURCES, c as GatewayRetryConfig, d as LayerFullConfig, f as LayerGatewayConfig, i as DEFAULT_GATEWAY_ROUTING, l as GatewayRoutingConfig, m as ServiceLayer, n as DEFAULT_CIRCUIT_BREAKER_CONFIG, o as DEFAULT_LAYER_STREAMS, p as LayerResourceUrls, r as DEFAULT_GATEWAY_RETRY_CONFIG, s as GatewayRequestHeaders, t as CircuitBreakerConfig, u as LayerConfig } from "../layer-C0zxAUgR.js";
2
+ import { _ as TemporalHealthStatus, a as EventQueueSDKConfig, c as NetworkError, d as RetryConfig, f as SDKConfig, g as SDKShutdownOptions, h as SDKHealthStatus, i as EventQueueHealthStatus, l as PermissionDeniedError, m as SDKError, n as ActorType, o as LoggerConfig, p as SDKContext, r as AuthenticationError, s as LoggerTransport, t as APIError, u as QuotaExceededError, v as TimeoutError, y as ValidationError } from "../index-BTaQMEgB.js";
3
3
  export { APIError, ActorType, AuthenticationError, type CircuitBreakerConfig, DEFAULT_CIRCUIT_BREAKER_CONFIG, DEFAULT_GATEWAY_RETRY_CONFIG, DEFAULT_GATEWAY_ROUTING, DEFAULT_LAYER_RESOURCES, DEFAULT_LAYER_STREAMS, EventQueueHealthStatus, EventQueueSDKConfig, type GatewayRequestHeaders, type GatewayRetryConfig, type GatewayRoutingConfig, type LayerConfig, type LayerFullConfig, type LayerGatewayConfig, type LayerResourceUrls, LoggerConfig, LoggerTransport, NetworkError, PermissionDeniedError, QuotaExceededError, RetryConfig, SDKConfig, SDKContext, SDKError, SDKHealthStatus, SDKShutdownOptions, type ServiceLayer, TemporalHealthStatus, TimeoutError, ValidationError };
@@ -1,4 +1,4 @@
1
- import { c as GatewayRetryConfig, m as ServiceLayer, s as GatewayRequestHeaders, t as CircuitBreakerConfig } from "./layer-BZBZZWeV.js";
1
+ import { c as GatewayRetryConfig, m as ServiceLayer, s as GatewayRequestHeaders, t as CircuitBreakerConfig } from "./layer-C0zxAUgR.js";
2
2
  interface GatewayClientConfig {
3
3
  layer: ServiceLayer;
4
4
  serviceName: string;
@@ -1,2 +1,2 @@
1
- import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, _ as UsageSummary, a as Quota, b as BillingUsageClient, c as SetQuotaOptions, d as TrackWorkspaceUsageOptions, f as UsageEntityType, g as UsageRecord, h as UsageOperationUnsupportedError, i as GetUsageOptions, l as TRACK_USAGE_MUTATION, m as UsageModule, n as CheckQuotaOptions, o as QuotaCheckResult, p as UsageMetricType, r as CheckWorkspaceQuotaOptions, s as QuotaPeriod, t as CHECK_WORKSPACE_QUOTA_QUERY, u as TrackUsageOptions, v as WorkspaceQuotaCheckResult, w as QuotaLimit, x as BillingUsageClientConfig, y as buildTrackUsageInput } from "../index-CVCyKzhB.js";
1
+ import { C as OrgBillingUsageOperationInput, S as BillingUsageOperationInput, T as WorkspaceBillingUsageOperationInput, _ as UsageSummary, a as Quota, b as BillingUsageClient, c as SetQuotaOptions, d as TrackWorkspaceUsageOptions, f as UsageEntityType, g as UsageRecord, h as UsageOperationUnsupportedError, i as GetUsageOptions, l as TRACK_USAGE_MUTATION, m as UsageModule, n as CheckQuotaOptions, o as QuotaCheckResult, p as UsageMetricType, r as CheckWorkspaceQuotaOptions, s as QuotaPeriod, t as CHECK_WORKSPACE_QUOTA_QUERY, u as TrackUsageOptions, v as WorkspaceQuotaCheckResult, w as QuotaLimit, x as BillingUsageClientConfig, y as buildTrackUsageInput } from "../index-DWER4-_x.js";
2
2
  export { BillingUsageClient, type BillingUsageClientConfig, type BillingUsageOperationInput, CHECK_WORKSPACE_QUOTA_QUERY, CheckQuotaOptions, CheckWorkspaceQuotaOptions, GetUsageOptions, type OrgBillingUsageOperationInput, Quota, QuotaCheckResult, type QuotaLimit, QuotaPeriod, SetQuotaOptions, TRACK_USAGE_MUTATION, TrackUsageOptions, TrackWorkspaceUsageOptions, UsageEntityType, UsageMetricType, UsageModule, UsageOperationUnsupportedError, UsageRecord, UsageSummary, type WorkspaceBillingUsageOperationInput, WorkspaceQuotaCheckResult, buildTrackUsageInput };
@@ -1,4 +1,4 @@
1
- import { a as UsageModule, c as BillingUsageClient, i as UsageMetricType, n as QuotaPeriod, o as UsageOperationUnsupportedError, r as TRACK_USAGE_MUTATION, s as buildTrackUsageInput, t as CHECK_WORKSPACE_QUOTA_QUERY } from "../usage-BRqVP3CJ.js";
1
+ import { a as UsageModule, c as BillingUsageClient, i as UsageMetricType, n as QuotaPeriod, o as UsageOperationUnsupportedError, r as TRACK_USAGE_MUTATION, s as buildTrackUsageInput, t as CHECK_WORKSPACE_QUOTA_QUERY } from "../usage-ygkKsxdd.js";
2
2
 
3
3
  export { BillingUsageClient, CHECK_WORKSPACE_QUOTA_QUERY, QuotaPeriod, TRACK_USAGE_MUTATION, UsageMetricType, UsageModule, UsageOperationUnsupportedError, buildTrackUsageInput };
4
4
  //# sourceMappingURL=index.js.map
@@ -1,7 +1,7 @@
1
1
  import { QuotaExceededError, SDKError, ValidationError } from "./types/index.js";
2
2
  import { t as GatewayClient } from "./client-sAJTrb4i.js";
3
3
  import { a as logger } from "./logger-B6rCpb7D.js";
4
- import "./gateway-ByVo-n37.js";
4
+ import "./gateway-2en8Gx_a.js";
5
5
  import { randomUUID } from "node:crypto";
6
6
 
7
7
  // src/usage/billing.ts
@@ -679,4 +679,4 @@ var UsageModule = class {
679
679
  };
680
680
 
681
681
  export { UsageModule as a, BillingUsageClient as c, UsageMetricType as i, QuotaPeriod as n, UsageOperationUnsupportedError as o, TRACK_USAGE_MUTATION as r, buildTrackUsageInput as s, CHECK_WORKSPACE_QUOTA_QUERY as t };
682
- //# sourceMappingURL=usage-BRqVP3CJ.js.map
682
+ //# sourceMappingURL=usage-ygkKsxdd.js.map