{"version":3,"file":"athena-diagnostics.cjs","sources":["../../src/diagnostics/athena-diagnostics.ts"],"sourcesContent":["/**\n * SDK diagnostics: one structured event bus for everything the SDK does that\n * can be slow or can fail — auth acquisition, thread-list fetches, statewire\n * attach/snapshot/connection changes, sends, first tokens, and every error.\n *\n * Design:\n * - Module-level singleton (one SDK, one bus), configured by `AthenaProvider`\n *   from its `debug` / `onDiagnostic` / `onError` props. Nothing here runs\n *   until something calls `emit`, and with defaults it costs a ring-buffer push.\n * - Every event carries `t` (ms since page navigation start via\n *   `performance.now()`) so the buffer reads as a waterfall. Timed spans use\n *   `performance.mark` / `performance.measure` too, so the browser Performance\n *   panel shows them as user timings without any extra tooling.\n * - Console output is opt-in (`debug` prop or `localStorage['athena:debug']`),\n *   prefixed `[AthenaSDK]`, and level-gated. Errors always reach `onError`.\n * - PostHog forwarding (opt-in) sends the timing events as\n *   `athena_sdk_<name>` with `duration_ms`, through the SDK's capture gate.\n *\n * Consumers read the buffer with `useAthenaDiagnostics()` or, in the browser\n * console, `window.__ATHENA_SDK__.diagnostics.snapshot()`.\n */\n\nimport { getPostHogInstance } from '../provider/PostHogProvider';\nimport { capturePosthogEvent, type PosthogCaptureClient } from '../lib/posthog/wrap-posthog-client';\nimport { ATHENA_REACT_SDK_VERSION } from '../version';\nimport { AthenaSdkError, isAthenaSdkError, toAthenaSdkError } from './errors';\n\nexport const ATHENA_DIAGNOSTIC_LEVELS = ['debug', 'info', 'warn', 'error'] as const;\nexport type AthenaDiagnosticLevel = (typeof ATHENA_DIAGNOSTIC_LEVELS)[number];\n\nconst LEVEL_RANK: Record<AthenaDiagnosticLevel, number> = {\n  debug: 0,\n  info: 1,\n  warn: 2,\n  error: 3,\n};\n\n/**\n * Event names. Dotted `area.event` so a consumer can filter by prefix. Names\n * are part of the public contract: renaming one is a breaking change for\n * dashboards, so add new ones instead of repurposing.\n */\nexport type AthenaDiagnosticEventName =\n  // Provider / configuration\n  | 'sdk.init'\n  | 'sdk.transport'\n  | 'sdk.config.warning'\n  // Auth acquisition + lifecycle\n  | 'auth.bridge.start'\n  | 'auth.bridge.ready'\n  | 'auth.bridge.timeout'\n  | 'auth.bridge.absent'\n  | 'auth.bridge.error'\n  | 'auth.bridge.retry'\n  | 'auth.bridge.config_rejected'\n  | 'auth.token.acquired'\n  | 'auth.token.refreshed'\n  | 'auth.token.refresh_failed'\n  | 'auth.token.stale'\n  | 'auth.sso.userinfo.start'\n  | 'auth.sso.userinfo.done'\n  | 'auth.sso.userinfo.error'\n  | 'auth.sso.userinfo.retry'\n  // Thread list + history\n  | 'threads.list.start'\n  | 'threads.list.done'\n  | 'threads.list.error'\n  | 'threads.list.aborted'\n  | 'threads.history.start'\n  | 'threads.history.done'\n  | 'threads.history.error'\n  | 'threads.history.aborted'\n  // Statewire transport\n  | 'statewire.attach.start'\n  | 'statewire.snapshot'\n  | 'statewire.connection'\n  | 'statewire.parked'\n  | 'statewire.error'\n  | 'statewire.read_only'\n  /** A write to the thread's server config lane (`config/patch`) was refused or dropped. */\n  | 'statewire.config'\n  // Runs\n  | 'run.send'\n  | 'run.first_token'\n  | 'run.done'\n  | 'run.error'\n  // Composer\n  | 'composer.attachment.error'\n  /** Files offered while Athena can't be reached were not attached (they could not upload). */\n  | 'composer.attachment.refused_offline'\n  | 'composer.cancel.error'\n  | 'composer.dictation'\n  | 'composer.handoff'\n  | 'voice.chat'\n  // Tool UIs + frontend tools\n  | 'tools.schema.warning'\n  | 'tools.debug'\n  // Mention suggestions\n  | 'mentions.fetch.error'\n  // Catch-all\n  | 'sdk.error';\n\nexport interface AthenaDiagnosticEvent {\n  /** Monotonic sequence number within this page. */\n  seq: number;\n  /** `performance.now()` at emit time (ms since navigation start). */\n  t: number;\n  /** Wall-clock ISO timestamp, for exports. */\n  at: string;\n  name: AthenaDiagnosticEventName;\n  level: AthenaDiagnosticLevel;\n  /** Milliseconds for a completed span (set on `*.done` / `*.ready` / `run.first_token`). */\n  durationMs?: number;\n  /** Structured context. Never contains credentials — see `redact`. */\n  data?: Record<string, unknown>;\n  /** Present on error-level events. */\n  error?: AthenaSdkError;\n}\n\nexport interface AthenaDiagnosticsConfig {\n  /** Minimum level echoed to the console. `false` disables console output. */\n  console: AthenaDiagnosticLevel | false;\n  /** Forward timing + error events to PostHog as `athena_sdk_*` events. */\n  posthog: boolean;\n  /** Receives every event (already redacted). */\n  onEvent?: (event: AthenaDiagnosticEvent) => void;\n  /** Receives every error-level event's `AthenaSdkError`. */\n  onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n  /** Ring-buffer capacity. */\n  bufferSize: number;\n}\n\nexport interface AthenaDiagnosticsSnapshot {\n  sdkVersion: string;\n  config: Omit<AthenaDiagnosticsConfig, 'onEvent' | 'onError'>;\n  events: AthenaDiagnosticEvent[];\n  /** Latest value per gauge (connection status, transport, auth mode, …). */\n  gauges: Record<string, unknown>;\n  /** Named span durations, most recent per name (`auth.bridge`, `threads.list`, …). */\n  timings: Record<string, number>;\n}\n\nconst DEFAULT_CONFIG: AthenaDiagnosticsConfig = {\n  console: false,\n  posthog: false,\n  bufferSize: 300,\n};\n\nconst CONSOLE_PREFIX = '[AthenaSDK]';\nconst LOCAL_STORAGE_DEBUG_KEY = 'athena:debug';\nconst GLOBAL_KEY = '__ATHENA_SDK__';\n\n// Keys whose values must never enter the buffer, the console, or PostHog.\nconst REDACT_KEYS = /token|secret|api[-_]?key|authorization|cookie|password/i;\n\nfunction redact(data: Record<string, unknown> | undefined): Record<string, unknown> | undefined {\n  if (!data) return undefined;\n  const out: Record<string, unknown> = {};\n  for (const [key, value] of Object.entries(data)) {\n    if (REDACT_KEYS.test(key)) {\n      out[key] = typeof value === 'string' && value.length > 0 ? `<redacted:${value.length}>` : '<redacted>';\n    } else {\n      out[key] = value;\n    }\n  }\n  return out;\n}\n\nfunction nowMs(): number {\n  return typeof performance !== 'undefined' && typeof performance.now === 'function'\n    ? performance.now()\n    : Date.now();\n}\n\nfunction readLocalDebugLevel(): AthenaDiagnosticLevel | null {\n  try {\n    if (typeof localStorage === 'undefined') return null;\n    const raw = localStorage.getItem(LOCAL_STORAGE_DEBUG_KEY);\n    if (!raw) return null;\n    if ((ATHENA_DIAGNOSTIC_LEVELS as readonly string[]).includes(raw)) {\n      return raw as AthenaDiagnosticLevel;\n    }\n    return raw === '1' || raw === 'true' ? 'debug' : null;\n  } catch {\n    return null;\n  }\n}\n\ntype Listener = (event: AthenaDiagnosticEvent) => void;\n\nclass AthenaDiagnosticsBus {\n  private config: AthenaDiagnosticsConfig = { ...DEFAULT_CONFIG };\n  private events: AthenaDiagnosticEvent[] = [];\n  private listeners = new Set<Listener>();\n  private snapshotListeners = new Set<() => void>();\n  private seq = 0;\n  private gauges: Record<string, unknown> = {};\n  private timings: Record<string, number> = {};\n  private spans = new Map<string, number>();\n  private cachedSnapshot: AthenaDiagnosticsSnapshot | null = null;\n\n  configure(partial: Partial<AthenaDiagnosticsConfig>): void {\n    this.config = { ...this.config, ...partial };\n    if (this.events.length > this.config.bufferSize) {\n      this.events = this.events.slice(-this.config.bufferSize);\n    }\n    this.invalidate();\n  }\n\n  getConfig(): AthenaDiagnosticsConfig {\n    return this.config;\n  }\n\n  /** Effective console level: the configured one, or `localStorage['athena:debug']`. */\n  private consoleLevel(): AthenaDiagnosticLevel | false {\n    if (this.config.console !== false) return this.config.console;\n    return readLocalDebugLevel() ?? false;\n  }\n\n  emit(\n    name: AthenaDiagnosticEventName,\n    options: {\n      level?: AthenaDiagnosticLevel;\n      data?: Record<string, unknown>;\n      durationMs?: number;\n      error?: unknown;\n    } = {},\n  ): AthenaDiagnosticEvent {\n    const level = options.level ?? (options.error !== undefined ? 'error' : 'info');\n    const error =\n      options.error === undefined\n        ? undefined\n        : toAthenaSdkError(options.error, {\n            code: 'unknown',\n            message: `Unexpected error during ${name}`,\n          });\n    const event: AthenaDiagnosticEvent = {\n      seq: ++this.seq,\n      t: Math.round(nowMs() * 10) / 10,\n      at: new Date().toISOString(),\n      name,\n      level,\n      ...(options.durationMs !== undefined && { durationMs: Math.round(options.durationMs) }),\n      ...(options.data && { data: redact(options.data) }),\n      ...(error && { error }),\n    };\n\n    this.events.push(event);\n    if (this.events.length > this.config.bufferSize) {\n      this.events.splice(0, this.events.length - this.config.bufferSize);\n    }\n    if (event.durationMs !== undefined) {\n      this.timings[name] = event.durationMs;\n    }\n    this.invalidate();\n\n    this.echoToConsole(event);\n    this.forwardToPostHog(event);\n    for (const listener of this.listeners) {\n      try {\n        listener(event);\n      } catch (listenerError) {\n        console.error(`${CONSOLE_PREFIX} diagnostics listener threw`, listenerError);\n      }\n    }\n    if (this.config.onEvent) {\n      try {\n        this.config.onEvent(event);\n      } catch (callbackError) {\n        console.error(`${CONSOLE_PREFIX} onDiagnostic callback threw`, callbackError);\n      }\n    }\n    if (error && this.config.onError) {\n      try {\n        this.config.onError(error, event);\n      } catch (callbackError) {\n        console.error(`${CONSOLE_PREFIX} onError callback threw`, callbackError);\n      }\n    }\n    for (const notify of this.snapshotListeners) notify();\n    return event;\n  }\n\n  /** Record an error-level event. Returns the normalized `AthenaSdkError`. */\n  error(\n    name: AthenaDiagnosticEventName,\n    error: unknown,\n    fallback: { code: AthenaSdkError['code']; message: string; hint?: string },\n    data?: Record<string, unknown>,\n  ): AthenaSdkError {\n    const normalized = toAthenaSdkError(error, fallback);\n    this.emit(name, { level: 'error', error: normalized, data });\n    return normalized;\n  }\n\n  /**\n   * Start a named span. Returns a function that ends it and emits `doneName`\n   * with `durationMs` (or `errorName` when passed an error). Also records a\n   * `performance.measure` so the span shows in the browser's Performance panel.\n   */\n  span(\n    spanName: string,\n    startName: AthenaDiagnosticEventName,\n    data?: Record<string, unknown>,\n  ): (\n    doneName: AthenaDiagnosticEventName,\n    doneOptions?: { data?: Record<string, unknown>; error?: unknown },\n  ) => number {\n    const startedAt = nowMs();\n    this.spans.set(spanName, startedAt);\n    this.mark(`${spanName}:start`);\n    this.emit(startName, { level: 'debug', data });\n    return (doneName, doneOptions = {}) => {\n      const durationMs = nowMs() - startedAt;\n      this.spans.delete(spanName);\n      this.mark(`${spanName}:end`);\n      this.measure(spanName);\n      this.emit(doneName, {\n        level: doneOptions.error !== undefined ? 'error' : 'info',\n        durationMs,\n        data: doneOptions.data,\n        error: doneOptions.error,\n      });\n      return durationMs;\n    };\n  }\n\n  /** Set a gauge (latest-value metric): connection status, transport, auth mode. */\n  gauge(name: string, value: unknown): void {\n    if (this.gauges[name] === value) return;\n    this.gauges[name] = value;\n    this.invalidate();\n    for (const notify of this.snapshotListeners) notify();\n  }\n\n  subscribe(listener: Listener): () => void {\n    this.listeners.add(listener);\n    return () => {\n      this.listeners.delete(listener);\n    };\n  }\n\n  /**\n   * Additive consumer registration: every registered consumer receives every\n   * event (and every error), unlike the single `onEvent`/`onError` config\n   * slots which are last-writer-wins. `AthenaProvider` registers through this\n   * so two mounted providers never clobber each other's callbacks.\n   */\n  addConsumer(consumer: {\n    onEvent?: (event: AthenaDiagnosticEvent) => void;\n    onError?: (error: AthenaSdkError, event: AthenaDiagnosticEvent) => void;\n  }): () => void {\n    return this.subscribe((event) => {\n      try {\n        consumer.onEvent?.(event);\n      } catch (callbackError) {\n        console.error(`${CONSOLE_PREFIX} onDiagnostic consumer threw`, callbackError);\n      }\n      if (event.error) {\n        try {\n          consumer.onError?.(event.error, event);\n        } catch (callbackError) {\n          console.error(`${CONSOLE_PREFIX} onError consumer threw`, callbackError);\n        }\n      }\n    });\n  }\n\n  /** Subscribe to snapshot changes (for `useSyncExternalStore`). */\n  subscribeSnapshot(listener: () => void): () => void {\n    this.snapshotListeners.add(listener);\n    return () => {\n      this.snapshotListeners.delete(listener);\n    };\n  }\n\n  snapshot(): AthenaDiagnosticsSnapshot {\n    if (!this.cachedSnapshot) {\n      const { onEvent: _onEvent, onError: _onError, ...config } = this.config;\n      this.cachedSnapshot = {\n        sdkVersion: ATHENA_REACT_SDK_VERSION,\n        config,\n        events: [...this.events],\n        gauges: { ...this.gauges },\n        timings: { ...this.timings },\n      };\n    }\n    return this.cachedSnapshot;\n  }\n\n  /** Copy-paste-able JSON of the current snapshot (errors serialized). */\n  export(): string {\n    return JSON.stringify(\n      this.snapshot(),\n      (_key, value) => (isAthenaSdkError(value) ? value.toJSON() : value),\n      2,\n    );\n  }\n\n  clear(): void {\n    this.events = [];\n    this.timings = {};\n    this.invalidate();\n    for (const notify of this.snapshotListeners) notify();\n  }\n\n  private invalidate(): void {\n    this.cachedSnapshot = null;\n  }\n\n  private mark(name: string): void {\n    try {\n      if (typeof performance !== 'undefined' && typeof performance.mark === 'function') {\n        performance.mark(`athena-sdk:${name}`);\n      }\n    } catch {\n      // User Timing is best-effort.\n    }\n  }\n\n  private measure(spanName: string): void {\n    try {\n      if (typeof performance !== 'undefined' && typeof performance.measure === 'function') {\n        performance.measure(\n          `athena-sdk:${spanName}`,\n          `athena-sdk:${spanName}:start`,\n          `athena-sdk:${spanName}:end`,\n        );\n      }\n    } catch {\n      // A missing start mark (e.g. after `performance.clearMarks`) is not an error.\n    }\n  }\n\n  private echoToConsole(event: AthenaDiagnosticEvent): void {\n    const level = this.consoleLevel();\n    if (level === false) {\n      // Errors are never silent: with console output off they still log once,\n      // compactly, so a broken integration is visible without enabling debug.\n      if (event.level === 'error' && event.error) {\n        console.error(`${CONSOLE_PREFIX} ${event.name}: ${event.error.describe()}`, event.data ?? '');\n      }\n      return;\n    }\n    if (LEVEL_RANK[event.level] < LEVEL_RANK[level]) return;\n    const suffix = event.durationMs !== undefined ? ` (${event.durationMs}ms)` : '';\n    const line = `${CONSOLE_PREFIX} ${event.name}${suffix}`;\n    const payload = event.error ? { ...event.data, error: event.error.describe() } : event.data;\n    const method =\n      event.level === 'error'\n        ? console.error\n        : event.level === 'warn'\n          ? console.warn\n          : event.level === 'debug'\n            ? console.debug\n            : console.info;\n    method(line, payload ?? '');\n  }\n\n  private forwardToPostHog(event: AthenaDiagnosticEvent): void {\n    if (!this.config.posthog) return;\n    if (event.durationMs === undefined && event.level !== 'error') return;\n    try {\n      const client = getPostHogInstance<PosthogCaptureClient>();\n      capturePosthogEvent(client, `athena_sdk_${event.name.replace(/\\./g, '_')}`, {\n        sdk_version: ATHENA_REACT_SDK_VERSION,\n        level: event.level,\n        ...(event.durationMs !== undefined && { duration_ms: event.durationMs }),\n        ...(event.error && {\n          error_code: event.error.code,\n          error_message: event.error.message,\n          error_status: event.error.status,\n        }),\n        ...event.data,\n      });\n    } catch {\n      // Analytics must never break the chat.\n    }\n  }\n}\n\nexport const athenaDiagnostics = new AthenaDiagnosticsBus();\n\n/**\n * Expose the bus on `window.__ATHENA_SDK__` so an integrator can inspect the\n * waterfall from the console (`__ATHENA_SDK__.diagnostics.snapshot()`) or turn\n * console echo on without a rebuild (`localStorage.setItem('athena:debug','debug')`).\n */\nexport function installAthenaDiagnosticsGlobal(): void {\n  if (typeof window === 'undefined') return;\n  const globalWindow = window as unknown as Record<string, unknown>;\n  const existing = (globalWindow[GLOBAL_KEY] ?? {}) as Record<string, unknown>;\n  globalWindow[GLOBAL_KEY] = {\n    ...existing,\n    version: ATHENA_REACT_SDK_VERSION,\n    diagnostics: {\n      snapshot: () => athenaDiagnostics.snapshot(),\n      export: () => athenaDiagnostics.export(),\n      clear: () => athenaDiagnostics.clear(),\n      enableConsole: (level: AthenaDiagnosticLevel = 'debug') => {\n        try {\n          localStorage.setItem(LOCAL_STORAGE_DEBUG_KEY, level);\n        } catch {\n          // localStorage may be unavailable.\n        }\n        athenaDiagnostics.configure({ console: level });\n      },\n      disableConsole: () => {\n        try {\n          localStorage.removeItem(LOCAL_STORAGE_DEBUG_KEY);\n        } catch {\n          // localStorage may be unavailable.\n        }\n        athenaDiagnostics.configure({ console: false });\n      },\n    },\n  };\n}\n\n/** Normalize the provider's `debug` prop into a diagnostics config patch. */\nexport function debugPropToDiagnosticsConfig(\n  debug: boolean | AthenaDiagnosticLevel | Partial<AthenaDiagnosticsConfig> | undefined,\n): Partial<AthenaDiagnosticsConfig> {\n  if (debug === undefined) return {};\n  if (debug === true) return { console: 'debug' };\n  if (debug === false) return { console: false };\n  if (typeof debug === 'string') return { console: debug };\n  return debug;\n}\n"],"names":["toAthenaSdkError","ATHENA_REACT_SDK_VERSION","isAthenaSdkError","getPostHogInstance","capturePosthogEvent"],"mappings":";;;;;;;;;AA2BO,MAAM,2BAA2B,CAAC,SAAS,QAAQ,QAAQ,OAAO;AAGzE,MAAM,aAAoD;AAAA,EACxD,OAAO;AAAA,EACP,MAAM;AAAA,EACN,MAAM;AAAA,EACN,OAAO;AACT;AA2GA,MAAM,iBAA0C;AAAA,EAC9C,SAAS;AAAA,EACT,SAAS;AAAA,EACT,YAAY;AACd;AAEA,MAAM,iBAAiB;AACvB,MAAM,0BAA0B;AAChC,MAAM,aAAa;AAGnB,MAAM,cAAc;AAEpB,SAAS,OAAO,MAAgF;AAC9F,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,MAA+B,CAAA;AACrC,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,IAAI,GAAG;AAC/C,QAAI,YAAY,KAAK,GAAG,GAAG;AACzB,UAAI,GAAG,IAAI,OAAO,UAAU,YAAY,MAAM,SAAS,IAAI,aAAa,MAAM,MAAM,MAAM;AAAA,IAC5F,OAAO;AACL,UAAI,GAAG,IAAI;AAAA,IACb;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,QAAgB;AACvB,SAAO,OAAO,gBAAgB,eAAe,OAAO,YAAY,QAAQ,aACpE,YAAY,QACZ,KAAK,IAAA;AACX;AAEA,SAAS,sBAAoD;AAC3D,MAAI;AACF,QAAI,OAAO,iBAAiB,YAAa,QAAO;AAChD,UAAM,MAAM,aAAa,QAAQ,uBAAuB;AACxD,QAAI,CAAC,IAAK,QAAO;AACjB,QAAK,yBAA+C,SAAS,GAAG,GAAG;AACjE,aAAO;AAAA,IACT;AACA,WAAO,QAAQ,OAAO,QAAQ,SAAS,UAAU;AAAA,EACnD,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAIA,MAAM,qBAAqB;AAAA,EAA3B;AACU,kCAAkC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