{"version":3,"file":"index.mjs","names":["logger","logger","logger","logger","contextApi","logger","logger","SDK_VERSION","logger","context","contextApi","logger","logger","SDK_VERSION","laminarObserve","SDK_VERSION","laminarObserve","observe","logger","SDK_VERSION","logger","SDK_VERSION","laminarObserve","observe","safeSetAttribute","setRequestAttributes","setResponseAttributes","WRAPPED_SYMBOL","SDK_VERSION","SDK_VERSION","logger","applyUsage","logger","logger","SDK_VERSION","SDK_VERSION","safeSetAttribute","recordError","setRequestAttributes","setResponseAttributes","PATCH_STATE_SYMBOL","SDK_VERSION","logger","logger","ExporterHttp","ExporterGrpc","SDK_VERSION","logger","contextApi","logger","logger","SDK_VERSION","logger","StagehandV3Instrumentation","logger","SDK_VERSION","logger","logger","logger","logger","TRACEPARENT_HEADER","LAMINAR_SPAN_CONTEXT_HEADER","serializeJSON","normalizeProvider","logger","normalizeProvider","serializeJSON","contextApi","SDK_VERSION","contextApi"],"sources":["../src/datasets/prng.ts","../src/datasets.ts","../src/opentelemetry-lib/tracing/compat.ts","../src/opentelemetry-lib/instrumentation/aisdk/utils.ts","../src/opentelemetry-lib/tracing/stream-utils.ts","../src/debug/debug-session-file.ts","../src/debug/config.ts","../src/debug/pointer.ts","../src/debug/index.ts","../src/opentelemetry-lib/tracing/span.ts","../src/opentelemetry-lib/tracing/context.ts","../src/opentelemetry-lib/instrumentation/claude-agent-sdk/proxy.ts","../src/opentelemetry-lib/instrumentation/claude-agent-sdk/index.ts","../src/laminar.ts","../src/browser/recorder.ts","../src/browser/utils.ts","../src/browser/playwright.ts","../src/browser/stagehand/shared-llm-wrapper.ts","../src/browser/stagehand/v2.ts","../src/browser/puppeteer.ts","../src/browser/stagehand/v3/constants.ts","../src/browser/stagehand/v3/cdp-helpers.ts","../src/browser/stagehand/v3/event-handlers.ts","../src/browser/stagehand/v3/instrumentation.ts","../src/opentelemetry-lib/instrumentation/google-genai/utils.ts","../src/opentelemetry-lib/instrumentation/google-genai/index.ts","../src/opentelemetry-lib/instrumentation/kernel.ts","../src/opentelemetry-lib/instrumentation/openai-agents/helpers.ts","../src/opentelemetry-lib/instrumentation/openai-agents/messages.ts","../src/opentelemetry-lib/instrumentation/openai-agents/span-data.ts","../src/opentelemetry-lib/instrumentation/openai-agents/processor.ts","../src/opentelemetry-lib/instrumentation/openai-agents/index.ts","../src/opentelemetry-lib/instrumentation/opencode.ts","../src/opentelemetry-lib/instrumentation/openrouter/utils.ts","../src/opentelemetry-lib/instrumentation/openrouter/index.ts","../src/version.ts","../src/opentelemetry-lib/tracing/batch-processor.ts","../src/opentelemetry-lib/tracing/exporter.ts","../src/opentelemetry-lib/tracing/processor.ts","../src/opentelemetry-lib/instrumentation/temporal/helpers.ts","../src/opentelemetry-lib/instrumentation/temporal/interceptors.ts","../src/opentelemetry-lib/instrumentation/temporal/workflow-span.ts","../src/opentelemetry-lib/instrumentation/temporal/index.ts","../src/opentelemetry-lib/instrumentation/typesafe/utils.ts","../src/opentelemetry-lib/instrumentation/typesafe/index.ts","../src/opentelemetry-lib/tracing/instrumentations.ts","../src/opentelemetry-lib/tracing/tracer.ts","../src/opentelemetry-lib/tracing/utils.ts","../src/opentelemetry-lib/tracing/index.ts","../src/opentelemetry-lib/configuration/index.ts","../src/opentelemetry-lib/tracing/decorators.ts","../src/decorators.ts","../src/evaluations.ts","../src/integrations/eve.ts","../src/debug/hash.ts","../src/debug/replay.ts","../src/opentelemetry-lib/instrumentation/aisdk/active-llm-span.ts","../src/opentelemetry-lib/instrumentation/aisdk/v7-integration/utils.ts","../src/opentelemetry-lib/instrumentation/aisdk/base-language-model.ts","../src/opentelemetry-lib/instrumentation/aisdk/v2.ts","../src/opentelemetry-lib/instrumentation/aisdk/v3.ts","../src/opentelemetry-lib/instrumentation/aisdk/v4.ts","../src/opentelemetry-lib/instrumentation/aisdk/index.ts","../src/opentelemetry-lib/instrumentation/aisdk/v7-integration/package-versions.ts","../src/opentelemetry-lib/instrumentation/aisdk/v7-integration/types.ts","../src/opentelemetry-lib/instrumentation/aisdk/v7-integration/index.ts","../src/opentelemetry-lib/instrumentation/mastra/types.ts","../src/opentelemetry-lib/instrumentation/mastra/utils.ts","../src/opentelemetry-lib/instrumentation/mastra/exporter.ts"],"sourcesContent":["// Mirrors the Python SDK's `seeded_perm` byte-for-byte. Do NOT swap in an\n// off-the-shelf RNG: no library is byte-identical across JS and Python.\n\nconst UINT32 = 0x100000000; // 2^32\n\n// Deterministic permutation of `[0, n)`. `seed` is an integer, reduced mod 2^32.\nexport const seededPerm = (n: number, seed: number): number[] => {\n  let state = seed >>> 0; // seed mod 2^32\n\n  // mulberry32 -> float in [0, 1)\n  const next = (): number => {\n    state = (state + 0x6d2b79f5) >>> 0;\n    let t = state;\n    t = Math.imul(t ^ (t >>> 15), t | 1);\n    t ^= t + Math.imul(t ^ (t >>> 7), t | 61);\n    return ((t ^ (t >>> 14)) >>> 0) / UINT32;\n  };\n\n  const ix = Array.from({ length: n }, (_, i) => i);\n  // Fisher–Yates, downward.\n  for (let i = n - 1; i > 0; i--) {\n    const j = Math.floor(next() * (i + 1));\n    [ix[i], ix[j]] = [ix[j], ix[i]];\n  }\n  return ix;\n};\n","import { LaminarClient } from \"@lmnr-ai/client\";\nimport { type StringUUID } from \"@lmnr-ai/types\";\n\nimport { seededPerm } from \"./datasets/prng\";\nimport { Datapoint } from \"./evaluations\";\n\nconst DEFAULT_FETCH_SIZE = 25;\n\n// A known-length, index-addressable collection of datapoints. Each subsampling\n// op (`take` / `select` / `shuffle`) returns a NEW dataset, so ops chain.\nexport abstract class EvaluationDataset<D, T> {\n  public async slice(start: number, end: number): Promise<Datapoint<D, T>[]> {\n    const result = [];\n    for (\n      let i = Math.max(start, 0);\n      i < Math.min(end, await this.size());\n      i++\n    ) {\n      result.push(await this.get(i));\n    }\n    return result;\n  }\n  public abstract size(): Promise<number> | number;\n  public abstract get(\n    index: number,\n  ): Promise<Datapoint<D, T>> | Datapoint<D, T>;\n\n  // The underlying remote-backed source dataset, resolved through any depth of\n  // chaining. `undefined` when the dataset has no remote source.\n  public sourceDataset(): LaminarDataset<D, T> | undefined {\n    return undefined;\n  }\n\n  // The first `n` datapoints (or all of them if `n` exceeds the size).\n  public take(n: number): EvaluationDataset<D, T> {\n    return new Transformed<D, T>(this, async (base) => {\n      if (!Number.isInteger(n)) {\n        throw new Error(`take count ${n} is not an integer`);\n      }\n      const size = await base.size();\n      const count = Math.max(0, Math.min(n, size));\n      return Array.from({ length: count }, (_, i) => i);\n    });\n  }\n\n  // Exactly these datapoints, in this order. Throws at resolve time on a\n  // non-integer or out-of-range index. No clamping, no negative indices.\n  public select(indices: number[]): EvaluationDataset<D, T> {\n    // Snapshot the selection at call time so later mutations to the caller's\n    // array can't change which indices are validated and returned.\n    const selected = [...indices];\n    return new Transformed<D, T>(this, async (base) => {\n      const size = await base.size();\n      for (const index of selected) {\n        if (!Number.isInteger(index)) {\n          throw new Error(`select index ${index} is not an integer`);\n        }\n        if (index < 0 || index >= size) {\n          throw new Error(\n            `select index ${index} is out of range for dataset of size ${size}`,\n          );\n        }\n      }\n      return selected;\n    });\n  }\n\n  // A reproducible random permutation: the order is a pure function of\n  // `(size, seed)`, so the same seed always yields the same order.\n  public shuffle({\n    seed = 0,\n  }: {\n    seed?: number;\n  } = {}): EvaluationDataset<D, T> {\n    return new Transformed<D, T>(this, async (base) =>\n      seededPerm(await base.size(), seed),\n    );\n  }\n}\n\n// An immutable subsampling wrapper: an immediate `base` plus a lazy, once-only\n// `resolve` that produces indices into that base, so chain orders compose.\nexport class Transformed<D, T> extends EvaluationDataset<D, T> {\n  private base: EvaluationDataset<D, T>;\n  private resolve: (base: EvaluationDataset<D, T>) => Promise<number[]>;\n  private indices: number[] | null = null;\n  private resolving: Promise<number[]> | null = null;\n\n  constructor(\n    base: EvaluationDataset<D, T>,\n    resolve: (base: EvaluationDataset<D, T>) => Promise<number[]>,\n  ) {\n    super();\n    this.base = base;\n    this.resolve = resolve;\n  }\n\n  private resolveIndices(): Promise<number[]> {\n    if (this.indices !== null) {\n      return Promise.resolve(this.indices);\n    }\n    if (this.resolving === null) {\n      // Drop a failed resolve so a transient `size`/`get` error can be retried\n      // instead of poisoning every later access. Mirrors `fetchPage`.\n      this.resolving = this.resolve(this.base)\n        .then((indices) => {\n          this.indices = indices;\n          return indices;\n        })\n        .catch((err) => {\n          this.resolving = null;\n          throw err;\n        });\n    }\n    return this.resolving;\n  }\n\n  public async size(): Promise<number> {\n    return (await this.resolveIndices()).length;\n  }\n\n  public async get(index: number): Promise<Datapoint<D, T>> {\n    const indices = await this.resolveIndices();\n    if (index < 0 || index >= indices.length) {\n      throw new Error(\n        `Index ${index} is out of range for dataset of size ${indices.length}`,\n      );\n    }\n    return await this.base.get(indices[index]);\n  }\n\n  public sourceDataset(): LaminarDataset<D, T> | undefined {\n    return this.base.sourceDataset();\n  }\n}\n\nexport class LaminarDataset<D, T> extends EvaluationDataset<D, T> {\n  // Page cache keyed by page offset. Each page's in-flight/settled fetch is\n  // stored so a page is fetched at most once even under concurrent access.\n  private pages: Map<number, Promise<Datapoint<D, T>[]>> = new Map();\n  private len: number | null = null;\n  private fetchSize: number;\n  private client: LaminarClient | undefined = undefined;\n\n  public name: string | undefined;\n  public id?: StringUUID;\n\n  constructor(\n    name?: string,\n    options?: { id?: StringUUID; fetchSize?: number },\n  ) {\n    super();\n    if (!name && !options?.id) {\n      throw new Error(\"Either name or id must be provided\");\n    }\n    if (name && options?.id) {\n      throw new Error(\"Only one of name or id must be provided\");\n    }\n    this.name = name;\n    this.id = options?.id;\n    this.fetchSize = options?.fetchSize || DEFAULT_FETCH_SIZE;\n  }\n\n  public setClient(client: LaminarClient) {\n    this.client = client;\n  }\n\n  public sourceDataset(): LaminarDataset<D, T> | undefined {\n    return this;\n  }\n\n  private fetchPage(offset: number): Promise<Datapoint<D, T>[]> {\n    const existing = this.pages.get(offset);\n    if (existing) {\n      return existing;\n    }\n    // Drop a failed fetch from the cache so it can be retried; a successful\n    // page stays cached and is never fetched again.\n    const pending = this.doFetchPage(offset).catch((err) => {\n      this.pages.delete(offset);\n      throw err;\n    });\n    this.pages.set(offset, pending);\n    return pending;\n  }\n\n  private async doFetchPage(offset: number): Promise<Datapoint<D, T>[]> {\n    if (!this.client) {\n      throw new Error(\"Client not set\");\n    }\n    const identifier = this.id ? { id: this.id } : { name: this.name! };\n    const resp = await this.client.datasets.pull<D, T>({\n      ...identifier,\n      offset,\n      limit: this.fetchSize,\n    });\n    if (this.len === null) {\n      this.len = resp.totalCount;\n    }\n    return resp.items;\n  }\n\n  public async size(): Promise<number> {\n    if (this.len === null) {\n      await this.fetchPage(0);\n    }\n    return this.len!;\n  }\n\n  public async get(index: number): Promise<Datapoint<D, T>> {\n    if (index < 0) {\n      throw new Error(`Index ${index} is out of range`);\n    }\n    // When the length is already known, reject an out-of-range index without\n    // a wasted page fetch.\n    if (this.len !== null && index >= this.len) {\n      throw new Error(\n        `Index ${index} is out of range for dataset of size ${this.len}`,\n      );\n    }\n    const offset = Math.floor(index / this.fetchSize) * this.fetchSize;\n    const page = await this.fetchPage(offset);\n    const local = index - offset;\n    if (local >= page.length) {\n      throw new Error(\n        `Index ${index} is out of range for dataset of size ${this.len ?? \"unknown\"}`,\n      );\n    }\n    return page[local];\n  }\n\n  /**\n   * Push data from files to this dataset.\n   *\n   * @param {string | string[]} paths - Path(s) to files or directories containing data\n   * @param {boolean} recursive - Whether to recursively read files in directories\n   */\n  public async push(\n    paths: string | string[],\n    recursive: boolean = false,\n  ): Promise<void> {\n    if (!this.client) {\n      throw new Error(\"Client not set\");\n    }\n\n    // Dynamic import to avoid circular dependency\n    const { loadFromPaths } = await import(\"./cli/file-utils.js\");\n\n    const pathArray = Array.isArray(paths) ? paths : [paths];\n    const data = await loadFromPaths(pathArray, recursive);\n\n    if (data.length === 0) {\n      console.warn(\"No data to push. Skipping\");\n      return;\n    }\n\n    const identifier = this.id ? { id: this.id } : { name: this.name! };\n    await this.client.datasets.push({\n      points: data,\n      ...identifier,\n    });\n\n    console.log(`Successfully pushed ${data.length} datapoints to dataset`);\n  }\n}\n","// Forward-compatibility with OTel v2 / v0.200 SDKs\nimport { SpanContext } from \"@opentelemetry/api\";\nimport { ReadableSpan, Span as SdkSpan } from \"@opentelemetry/sdk-trace-base\";\n\nimport { initializeLogger } from \"../../utils\";\n\nconst logger = initializeLogger();\n\n// Type definitions that cover both OTel SDK v1 and v2\n// In v1: spans have parentSpanId and instrumentationLibrary\n// In v2: spans have parentSpanContext and instrumentationScope\nexport type OTelSpanCompat = SdkSpan &\n  ReadableSpan & {\n    parentSpanId?: string;\n    parentSpanContext?: SpanContext;\n    instrumentationLibrary?: any;\n    instrumentationScope?: any;\n  };\n\ntype OTelReadableSpanCompat = ReadableSpan & {\n  parentSpanId?: string;\n  parentSpanContext?: SpanContext;\n  instrumentationLibrary?: any;\n  instrumentationScope?: any;\n};\n\n// In-place edits on span object for compatibility between OTel v1 and v2 SDKs\nexport const makeSpanOtelV2Compatible = (\n  span: OTelSpanCompat | OTelReadableSpanCompat,\n) => {\n  const spanAny = span as any;\n  if (spanAny.instrumentationScope && !spanAny.instrumentationLibrary) {\n    // Making the spans from V2 compatible with V1\n    Object.assign(span, {\n      instrumentationLibrary: spanAny.instrumentationScope,\n    });\n  } else if (spanAny.instrumentationLibrary && !spanAny.instrumentationScope) {\n    // Making the spans from V1 compatible with V2\n    Object.assign(span, {\n      instrumentationScope: spanAny.instrumentationLibrary,\n    });\n  }\n\n  // Handle parent span compatibility between SDK v1 and v2\n  // SDK v1 uses parentSpanId (string), SDK v2 uses parentSpanContext (SpanContext)\n  if (spanAny.parentSpanContext && !spanAny.parentSpanId) {\n    // SDK v2 -> SDK v1: Extract spanId from parentSpanContext\n    Object.defineProperty(span, \"parentSpanId\", {\n      value: spanAny.parentSpanContext.spanId,\n      writable: true,\n      enumerable: true,\n      configurable: true,\n    });\n  } else if (spanAny.parentSpanId && !spanAny.parentSpanContext) {\n    // SDK v1 -> SDK v2: Create a proper SpanContext object\n    // We need to get the traceId from the span's own spanContext\n    const spanContext = span.spanContext();\n    Object.defineProperty(span, \"parentSpanContext\", {\n      value: {\n        traceId: spanContext.traceId,\n        spanId: spanAny.parentSpanId,\n        traceFlags: spanContext.traceFlags,\n        traceState: spanContext.traceState,\n        isRemote: spanContext.isRemote,\n      },\n      writable: true,\n      enumerable: true,\n      configurable: true,\n    });\n  }\n};\n\nexport const getParentSpanId = (\n  span: OTelSpanCompat | OTelReadableSpanCompat,\n): string | undefined => {\n  const spanAny = span as any;\n  return spanAny.parentSpanContext?.spanId ?? spanAny.parentSpanId;\n};\n\n/**\n * Creates a Resource object compatible with both OTel v1 and v2.\n *\n * In v1, Resource is a class constructor: new Resource(attributes)\n * In v2, Resource class is not exported; use resourceFromAttributes(attributes) instead\n *\n * This function automatically detects which version is available and uses the appropriate API.\n */\nexport const createResource = (attributes: Record<string, string>): any => {\n  // type IResource from `@opentelemetry/resources`\n  try {\n    // biome-ignore lint/style/noCommonJs: dynamically resolve dependencies to remain compatible with both versions\n    const resources = require(\"@opentelemetry/resources\");\n\n    // v2 uses resourceFromAttributes (0.200+ SDK, 2.x API)\n    if (resources.resourceFromAttributes) {\n      return resources.resourceFromAttributes(attributes);\n    }\n\n    // v1 uses Resource constructor (0.57.x SDK, 1.x API)\n    if (resources.Resource) {\n      return new resources.Resource(attributes);\n    }\n\n    throw new Error(\"Unable to create Resource: neither v1 nor v2 API found\");\n  } catch {\n    logger.debug(\n      \"Laminar failed to @opentelemetry/resources, continuing without it\",\n    );\n    return undefined;\n  }\n};\n","import {\n  type LanguageModelV4Message,\n  type LanguageModelV4Prompt,\n} from \"@ai-sdk/provider\";\nimport {\n  type LanguageModelV2Message,\n  type LanguageModelV2Prompt,\n} from \"@ai-sdk/provider-v2\";\nimport {\n  type LanguageModelV3Message,\n  type LanguageModelV3Prompt,\n} from \"@ai-sdk/provider-v3\";\nimport { errorMessage } from \"@lmnr-ai/types\";\nimport { type DataContent } from \"ai\";\n\n// Mirrors https://github.com/vercel/ai/blob/ai@6.0.221/packages/ai/src/telemetry/stringify-for-telemetry.ts\n// This function is initially implemented by us, and is not exported from the ai sdk.\n// We copy it here for our own use.\nexport const stringifyPromptForTelemetry = (\n  prompt: LanguageModelV2Prompt | LanguageModelV3Prompt | LanguageModelV4Prompt,\n): string =>\n  JSON.stringify(\n    prompt.map(\n      (\n        message:\n          | LanguageModelV2Message\n          | LanguageModelV3Message\n          | LanguageModelV4Message,\n      ) => ({\n        ...message,\n        content:\n          typeof message.content === \"string\"\n            ? message.content\n            : message.content.map((part) =>\n                part.type === \"file\"\n                  ? {\n                      ...part,\n                      data:\n                        part.data instanceof Uint8Array\n                          ? convertDataContentToBase64String(part.data)\n                          : part.data &&\n                              typeof part.data === \"object\" &&\n                              (part.data as { type?: string }).type ===\n                                \"data\" &&\n                              (part.data as { data?: unknown }).data instanceof\n                                Uint8Array\n                            ? {\n                                ...part.data,\n                                data: convertDataContentToBase64String(\n                                  (part.data as { data: Uint8Array }).data,\n                                ),\n                              }\n                            : part.data,\n                    }\n                  : part,\n              ),\n      }),\n    ),\n  );\n\n// https://github.com/vercel/ai/blob/main/packages/ai/src/prompt/data-content.ts\n/**\nConverts data content to a base64-encoded string.\n\n@param content - Data content to convert.\n@returns Base64-encoded string.\n*/\nconst convertDataContentToBase64String = (content: DataContent): string => {\n  if (typeof content === \"string\") {\n    return content;\n  }\n\n  if (content instanceof ArrayBuffer) {\n    return convertUint8ArrayToBase64(new Uint8Array(content));\n  }\n\n  return convertUint8ArrayToBase64(content);\n};\n\n// https://github.com/vercel/ai/blob/main/packages/provider-utils/src/uint8-utils.ts\nexport function convertUint8ArrayToBase64(array: Uint8Array): string {\n  let latin1string = \"\";\n\n  // Note: regular for loop to support older JavaScript versions that\n  // do not support for..of on Uint8Array\n  for (let i = 0; i < array.length; i++) {\n    latin1string += String.fromCodePoint(array[i]);\n  }\n\n  return btoa(latin1string);\n}\n\n/**\n * Information about a detected stream\n */\nexport type StreamInfo =\n  | { type: \"aisdk-result\"; result: any }\n  | { type: \"readable-stream\"; stream: ReadableStream<unknown> }\n  | { type: \"async-iterable\"; iterable: AsyncIterable<unknown> }\n  | { type: \"response\"; response: Response }\n  | { type: null };\n\n/**\n * Checks whether `key` looks like an AI SDK stream property WITHOUT reading it.\n *\n * Reading is not safe here: AI SDK exposes `textStream` / `fullStream` as getters that build a\n * fresh stream on every access. On `streamText` that tees (and mutates) the internal base stream,\n * leaving an abandoned branch that buffers the whole response; on `streamObject` it `pipeThrough`s\n * the base stream directly, permanently LOCKING it so the caller's own access throws. So we only\n * inspect the property descriptor: AI SDK's are accessors, whereas a same-named host API (e.g.\n * Node 26's `Response.prototype.textStream`) is a data property holding a method.\n */\nconst hasStreamAccessor = (obj: object, key: string): boolean => {\n  for (\n    let o: object | null = obj;\n    o !== null;\n    o = Object.getPrototypeOf(o) as object | null\n  ) {\n    const descriptor = Object.getOwnPropertyDescriptor(o, key);\n    if (descriptor) {\n      // An accessor, or a data property holding an already-built stream — but never a method.\n      return typeof descriptor.value !== \"function\";\n    }\n  }\n  return false;\n};\n\n/**\n * This function checks if an object is stream or stream-like, and returns information\n * about the stream type and how to handle it.\n * @param response - The result of a function, either an AI SDK result, a raw stream, or any other\n * response.\n * @returns - StreamInfo object describing the stream type, or { type: null } if not a stream.\n */\nexport const getStream = (response: unknown): StreamInfo => {\n  if (!response || typeof response !== \"object\") {\n    return { type: null };\n  }\n\n  // Check for Response object (from createUIMessageStreamResponse, createTextStreamResponse, etc.)\n  // NOTE: this MUST come before the AI SDK check below — Node 26's `Response` has a `textStream()`\n  // method, which would otherwise be mistaken for a StreamTextResult.\n  if (response instanceof Response) {\n    return { type: \"response\", response };\n  }\n\n  // Check for ReadableStream\n  if (response instanceof ReadableStream) {\n    return { type: \"readable-stream\", stream: response };\n  }\n\n  // Check for AI SDK StreamTextResult (has a textStream or fullStream accessor)\n  if (\n    hasStreamAccessor(response, \"textStream\") ||\n    hasStreamAccessor(response, \"fullStream\")\n  ) {\n    return { type: \"aisdk-result\", result: response };\n  }\n\n  // Check for AsyncIterable (but not ReadableStream, which also implements AsyncIterable)\n  if (\n    Symbol.asyncIterator in response &&\n    !(response instanceof ReadableStream)\n  ) {\n    return {\n      type: \"async-iterable\",\n      iterable: response as AsyncIterable<unknown>,\n    };\n  }\n\n  return { type: null };\n};\n\n/**\n * Consumes an AI SDK StreamTextResult and returns structured output\n * @param result - The AI SDK StreamTextResult object\n * @returns Promise that resolves to structured output with all relevant fields\n */\nexport const consumeAISDKResult = async (result: any): Promise<any> => {\n  const output: any = {};\n  const errors: any[] = [];\n\n  // Helper to safely await a promise property\n  const safeAwait = async (key: string, promise: PromiseLike<any>) => {\n    try {\n      output[key] = await promise;\n    } catch (error) {\n      errors.push({ field: key, error: errorMessage(error) });\n    }\n  };\n\n  // Collect all the promise properties in parallel\n  const promises: Promise<void>[] = [];\n\n  if (\"text\" in result) promises.push(safeAwait(\"text\", result.text));\n  if (\"toolCalls\" in result)\n    promises.push(safeAwait(\"toolCalls\", result.toolCalls));\n  if (\"reasoning\" in result)\n    promises.push(safeAwait(\"reasoning\", result.reasoning));\n  if (\"finishReason\" in result)\n    promises.push(safeAwait(\"finishReason\", result.finishReason));\n  if (\"usage\" in result) promises.push(safeAwait(\"usage\", result.usage));\n  if (\"files\" in result) promises.push(safeAwait(\"files\", result.files));\n  if (\"sources\" in result) promises.push(safeAwait(\"sources\", result.sources));\n\n  await Promise.all(promises);\n\n  if (errors.length > 0) {\n    output._errors = errors;\n  }\n\n  return output;\n};\n\n/**\n * Consumes a ReadableStream while teeing it to pass through to the caller\n * @param stream - The ReadableStream to consume\n * @returns Object with the teed stream for the caller and a promise for the collected data\n */\nexport const consumeAndTeeReadableStream = <T>(\n  stream: ReadableStream<T>,\n): {\n  stream: ReadableStream<T>;\n  dataPromise: Promise<{ chunks: T[]; error?: any }>;\n} => {\n  const [stream1, stream2] = stream.tee();\n\n  const dataPromise = (async () => {\n    const chunks: T[] = [];\n    let error: any = undefined;\n\n    try {\n      const reader = stream2.getReader();\n      try {\n        while (true) {\n          const { done, value } = await reader.read();\n          if (done) break;\n          chunks.push(value);\n        }\n      } finally {\n        reader.releaseLock();\n      }\n    } catch (err) {\n      error = err;\n    }\n\n    return { chunks, error };\n  })();\n\n  return { stream: stream1, dataPromise };\n};\n\n/**\n * Consumes an AsyncIterable while yielding items to the caller\n * @param iterable - The AsyncIterable to consume\n * @returns Object with a wrapped iterable for the caller and a promise for the collected data\n */\nexport const consumeAndTeeAsyncIterable = <T>(\n  iterable: AsyncIterable<T>,\n): {\n  iterable: AsyncIterable<T>;\n  dataPromise: Promise<{ chunks: T[]; error?: any }>;\n} => {\n  const chunks: T[] = [];\n  let error: any = undefined;\n  let resolveData!: (value: { chunks: T[]; error?: any }) => void;\n  const dataPromise = new Promise<{ chunks: T[]; error?: any }>((resolve) => {\n    resolveData = resolve;\n  });\n\n  const wrappedIterable = (async function* () {\n    try {\n      for await (const item of iterable) {\n        chunks.push(item);\n        yield item;\n      }\n    } catch (err) {\n      error = err;\n      throw err;\n    } finally {\n      resolveData({ chunks, error });\n    }\n  })();\n\n  return { iterable: wrappedIterable, dataPromise };\n};\n\n/**\n * Consumes a Response object's body stream\n * @param response - The Response object to consume\n * @returns Promise that resolves to the consumed data\n */\nexport const consumeResponse = async (\n  response: Response,\n): Promise<{ chunks: any[]; error?: any }> => {\n  const chunks: any[] = [];\n  let error: any = undefined;\n\n  if (!response.body) {\n    return { chunks };\n  }\n\n  try {\n    const reader = response.body.getReader();\n    const decoder = new TextDecoder();\n\n    try {\n      while (true) {\n        const { done, value } = await reader.read();\n        if (done) break;\n        chunks.push(decoder.decode(value, { stream: true }));\n      }\n    } finally {\n      reader.releaseLock();\n    }\n  } catch (err) {\n    error = err;\n  }\n\n  return { chunks, error };\n};\n","import { errorMessage } from \"@lmnr-ai/types\";\nimport type { Span } from \"@opentelemetry/api\";\n\nimport { initializeLogger } from \"../../utils\";\nimport {\n  consumeAISDKResult,\n  consumeAndTeeAsyncIterable,\n  consumeAndTeeReadableStream,\n  consumeResponse,\n  getStream,\n} from \"../instrumentation/aisdk/utils\";\nimport { shouldSendTraces } from \".\";\nimport { SPAN_OUTPUT } from \"./attributes\";\n\nconst logger = initializeLogger();\n\n// Track pending stream processing promises\nconst pendingStreamProcessing = new Set<Promise<void>>();\n\n/**\n * Wait for all pending stream processing to complete with a timeout\n * @param timeoutMs - Maximum time to wait in milliseconds (default: 5000)\n */\nexport const waitForPendingStreams = async (\n  timeoutMs: number = 5000,\n): Promise<void> => {\n  if (pendingStreamProcessing.size === 0) {\n    return;\n  }\n  logger.debug(`Waiting for ${pendingStreamProcessing.size} pending stream(s)`);\n\n  const initialCount = pendingStreamProcessing.size;\n  const pendingPromises = Array.from(pendingStreamProcessing);\n\n  let timedOut = false;\n  const timeoutPromise = new Promise<void>((resolve) => {\n    setTimeout(() => {\n      timedOut = true;\n      resolve();\n    }, timeoutMs);\n  });\n\n  await Promise.race([Promise.allSettled(pendingPromises), timeoutPromise]);\n\n  if (timedOut && pendingStreamProcessing.size > 0) {\n    logger.warn(\n      `Timeout waiting for ${pendingStreamProcessing.size} pending stream(s) ` +\n        `after ${timeoutMs}ms (started with ${initialCount})`,\n    );\n  }\n};\n\n/**\n * Consumes a stream result to ensure background processing completes.\n * This is useful in debugger mode where there's no caller to consume the stream.\n * @param result - The result that might be a stream\n * @returns The same result, or accumulated data if it was a stream\n */\nexport const consumeStreamResult = async (\n  result: unknown,\n): Promise<unknown> => {\n  const streamInfo = getStream(result);\n\n  if (streamInfo.type === null) {\n    // Not a stream, return as-is\n    logger.debug(\"Result is not a stream, returning as-is\");\n    return result;\n  }\n\n  logger.debug(\"Result is a stream, consuming...\");\n\n  if (streamInfo.type === \"aisdk-result\") {\n    // For AI SDK results, just await the text property to trigger consumption\n    // The background task will handle collecting all data\n    try {\n      if (\"text\" in streamInfo.result) {\n        await streamInfo.result.text;\n      }\n    } catch (error) {\n      logger.warn(\n        \"Error consuming AI SDK result stream: \" + errorMessage(error),\n      );\n    }\n    return result;\n  }\n\n  if (streamInfo.type === \"readable-stream\") {\n    // Consume the ReadableStream\n    const chunks: unknown[] = [];\n    try {\n      const reader = streamInfo.stream.getReader();\n      try {\n        while (true) {\n          const { done, value } = await reader.read();\n          if (done) break;\n          chunks.push(value);\n        }\n      } finally {\n        reader.releaseLock();\n      }\n    } catch (error) {\n      logger.warn(\"Error consuming ReadableStream: \" + errorMessage(error));\n    }\n    return { type: \"stream\", chunks };\n  }\n\n  if (streamInfo.type === \"async-iterable\") {\n    // Consume the AsyncIterable\n    const chunks: unknown[] = [];\n    try {\n      for await (const chunk of streamInfo.iterable) {\n        chunks.push(chunk);\n      }\n    } catch (error) {\n      logger.warn(\"Error consuming AsyncIterable: \" + errorMessage(error));\n    }\n    return { type: \"async-iterable\", chunks };\n  }\n\n  if (streamInfo.type === \"response\") {\n    // Consume the Response body\n    try {\n      const { chunks, error } = await consumeResponse(streamInfo.response);\n      if (error) {\n        logger.warn(\"Error consuming Response: \" + errorMessage(error));\n      }\n      return { type: \"response\", chunks };\n    } catch (error) {\n      logger.warn(\"Error consuming Response: \" + errorMessage(error));\n      return result;\n    }\n  }\n\n  return result;\n};\n\n/**\n * Track a background promise and ensure cleanup\n */\nconst trackStreamProcessing = (task: () => Promise<void>): void => {\n  const processingPromise = task().finally(() => {\n    pendingStreamProcessing.delete(processingPromise);\n  });\n\n  pendingStreamProcessing.add(processingPromise);\n};\n\n/**\n * Handles streaming results by consuming the stream in the background\n * while passing through the original result to the caller\n */\nexport const handleStreamResult = <T>(\n  originalResult: T,\n  streamInfo: ReturnType<typeof getStream>,\n  span: Span,\n  ignoreOutput: boolean | undefined,\n  serialize: (payload: unknown) => string,\n): T | ReadableStream<unknown> | AsyncIterable<unknown> | Response => {\n  logger.debug(`Handling stream result of type: ${streamInfo.type}`);\n\n  if (streamInfo.type === \"aisdk-result\") {\n    // For AI SDK results, consume the promise properties in the background\n    trackStreamProcessing(async () => {\n      logger.debug(\"Starting background processing for AI SDK result\");\n\n      let partialOutput: any = {};\n      try {\n        partialOutput = await consumeAISDKResult(streamInfo.result);\n\n        if (shouldSendTraces() && !ignoreOutput) {\n          try {\n            span.setAttribute(SPAN_OUTPUT, serialize(partialOutput));\n          } catch (error) {\n            logger.warn(\n              \"Failed to serialize AI SDK stream output: \" +\n                errorMessage(error),\n            );\n          }\n        }\n      } catch (error) {\n        // Record partial output if we have any\n        if (\n          Object.keys(partialOutput).length > 0 &&\n          shouldSendTraces() &&\n          !ignoreOutput\n        ) {\n          try {\n            span.setAttribute(SPAN_OUTPUT, serialize(partialOutput));\n          } catch (serError) {\n            logger.warn(\n              \"Failed to serialize partial AI SDK output: \" +\n                errorMessage(serError),\n            );\n          }\n        }\n        span.recordException(error as Error);\n      } finally {\n        logger.debug(\"Ending span for AI SDK result\");\n        span.end();\n      }\n    });\n\n    return originalResult;\n  }\n\n  if (streamInfo.type === \"readable-stream\") {\n    logger.debug(\"Setting up background processing for ReadableStream\");\n    const { stream, dataPromise } = consumeAndTeeReadableStream(\n      streamInfo.stream,\n    );\n\n    // Consume in background\n    trackStreamProcessing(async () => {\n      try {\n        const { chunks, error } = await dataPromise;\n\n        if (shouldSendTraces() && !ignoreOutput) {\n          try {\n            const output = { type: \"stream\", chunks };\n            span.setAttribute(SPAN_OUTPUT, serialize(output));\n          } catch (serError) {\n            logger.warn(\n              \"Failed to serialize stream output: \" + errorMessage(serError),\n            );\n          }\n        }\n\n        if (error) {\n          span.recordException(error as Error);\n        }\n      } finally {\n        logger.debug(\"Ending span for ReadableStream\");\n        span.end();\n      }\n    });\n\n    return stream;\n  }\n\n  if (streamInfo.type === \"async-iterable\") {\n    logger.debug(\"Setting up background processing for AsyncIterable\");\n    const { iterable, dataPromise } = consumeAndTeeAsyncIterable(\n      streamInfo.iterable,\n    );\n\n    // Consume in background\n    trackStreamProcessing(async () => {\n      try {\n        const { chunks, error } = await dataPromise;\n\n        if (shouldSendTraces() && !ignoreOutput) {\n          try {\n            const output = { type: \"async-iterable\", chunks };\n            span.setAttribute(SPAN_OUTPUT, serialize(output));\n          } catch (serError) {\n            logger.warn(\n              \"Failed to serialize async iterable output: \" +\n                errorMessage(serError),\n            );\n          }\n        }\n\n        if (error) {\n          span.recordException(error as Error);\n        }\n      } finally {\n        logger.debug(\"Ending span for AsyncIterable\");\n        span.end();\n      }\n    });\n\n    return iterable;\n  }\n\n  if (streamInfo.type === \"response\") {\n    logger.debug(\"Setting up background processing for Response\");\n    // For Response objects, extract the body stream and tee it\n    const originalResponse = streamInfo.response;\n\n    if (!originalResponse.body) {\n      // No body, just return as-is and end span\n      span.end();\n      return originalResult;\n    }\n\n    const [stream1, stream2] = originalResponse.body.tee();\n\n    // Create a new Response with the teed stream for the caller\n    const newResponse = new Response(stream1, {\n      status: originalResponse.status,\n      statusText: originalResponse.statusText,\n      headers: originalResponse.headers,\n    });\n\n    // Consume the other stream in background\n    trackStreamProcessing(async () => {\n      try {\n        // Create a temporary Response to use consumeResponse helper\n        const tempResponse = new Response(stream2);\n        const { chunks, error } = await consumeResponse(tempResponse);\n\n        if (shouldSendTraces() && !ignoreOutput) {\n          try {\n            const output = { type: \"response\", chunks };\n            span.setAttribute(SPAN_OUTPUT, serialize(output));\n          } catch (serError) {\n            logger.warn(\n              \"Failed to serialize response output: \" + errorMessage(serError),\n            );\n          }\n        }\n\n        if (error) {\n          span.recordException(error as Error);\n        }\n      } catch (err) {\n        span.recordException(err as Error);\n      } finally {\n        logger.debug(\"Ending span for Response\");\n        span.end();\n      }\n    });\n\n    return newResponse;\n  }\n\n  // Should never reach here, but just in case\n  logger.warn(\"Stream type not handled, ending span immediately\");\n  span.end();\n  return originalResult;\n};\n","import { mkdirSync, readFileSync, writeFileSync } from \"node:fs\";\nimport { dirname, join, parse, resolve } from \"node:path\";\n\nimport {\n  DEBUG_SESSION_DIR,\n  DEBUG_SESSION_FILE,\n  type DebugSessionFile,\n} from \"@lmnr-ai/types\";\n\n// Coerce an unknown field to a non-empty string, else null — the file is\n// best-effort local state that an agent may hand-edit, so every field is treated\n// defensively rather than trusted.\nconst str = (v: unknown): string | null =>\n  typeof v === \"string\" && v.length > 0 ? v : null;\n\n/**\n * Read `${dir ?? cwd}/.lmnr/debug-session.json`. Best-effort: returns null on a\n * missing / unreadable / malformed file, or one with no usable `session_id`\n * (the caller treats null as \"no existing session\" and mints a fresh one).\n */\nexport const readDebugSessionFile = (\n  dir: string = process.cwd(),\n): DebugSessionFile | null => {\n  try {\n    const raw = readFileSync(\n      join(dir, DEBUG_SESSION_DIR, DEBUG_SESSION_FILE),\n      \"utf-8\",\n    );\n    const r = JSON.parse(raw) as Record<string, unknown>;\n    const session_id = str(r.session_id);\n    if (!session_id) return null;\n    return {\n      session_id,\n      trace_id: str(r.trace_id),\n      replay_trace_id: str(r.replay_trace_id),\n      cache_until: str(r.cache_until),\n      debugger_url: str(r.debugger_url),\n      started_at: str(r.started_at) ?? new Date().toISOString(),\n    };\n  } catch {\n    return null;\n  }\n};\n\n/**\n * Find the nearest directory (walking up from `startDir` to the filesystem\n * root) whose `.lmnr/debug-session.json` holds a usable session record, so a\n * debug run started from a subdirectory of a project joins the project's\n * session. Returns null when no ancestor (including `startDir`) has one.\n */\nexport const findDebugSessionDir = (\n  startDir: string = process.cwd(),\n): string | null => {\n  let dir = resolve(startDir);\n  const root = parse(dir).root;\n  while (true) {\n    if (readDebugSessionFile(dir) !== null) return dir;\n    const parent = dirname(dir);\n    if (parent === dir || dir === root) return null;\n    dir = parent;\n  }\n};\n\n/**\n * The directory the debug-session file should be read from AND written to: the\n * nearest ancestor (incl. `startDir`) that already has one, else `startDir`\n * itself. Read and write MUST share this anchor — reading from an ancestor but\n * writing to cwd would strand the ancestor's copy stale and shadow it with a\n * nested one.\n */\nexport const resolveDebugSessionDir = (\n  startDir: string = process.cwd(),\n): string => findDebugSessionDir(startDir) ?? resolve(startDir);\n\n/**\n * Write the debug-session file (mkdir -p first). Best-effort: swallows any IO\n * error so a read-only working directory never breaks a run.\n */\nexport const writeDebugSessionFile = (\n  file: DebugSessionFile,\n  dir: string = process.cwd(),\n): boolean => {\n  try {\n    const directory = join(dir, DEBUG_SESSION_DIR);\n    mkdirSync(directory, { recursive: true });\n    writeFileSync(\n      join(directory, DEBUG_SESSION_FILE),\n      JSON.stringify(file),\n      \"utf-8\",\n    );\n    return true;\n  } catch {\n    return false;\n  }\n};\n","/**\n * Debug-mode environment parsing.\n *\n * Reads the `LMNR_DEBUG*` env vars once at SDK init and produces an immutable\n * DebugConfig. See the shared debugger spec (§4, §5) for the authoritative\n * contract. This file is part of the cross-language parity surface — keep its\n * logic line-comparable with the Python `config.py`.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\nimport { type DebugContext } from \"@lmnr-ai/types\";\n\nimport { initializeLogger } from \"../utils\";\nimport {\n  readDebugSessionFile,\n  resolveDebugSessionDir,\n} from \"./debug-session-file\";\n\nconst logger = initializeLogger();\n\n// Truthy set for LMNR_DEBUG, case-insensitive. Must match the Python SDK exactly.\nconst TRUTHY = new Set([\"true\", \"1\", \"yes\", \"on\"]);\n\n// A span-id needle is hyphen-stripped, lowercased hex of at most 32 chars (a\n// full UUID is 32 hex). Must match the Python SDK exactly.\nconst HEX_RE = /^[0-9a-f]+$/;\n\nexport const isTruthy = (value: string | undefined): boolean =>\n  value !== undefined && TRUTHY.has(value.trim().toLowerCase());\n\n/**\n * Normalize a span-id-shaped value to a hyphen-stripped lowercase hex needle.\n *\n * Accepts any of the spans a user might copy from the UI: a full UUID\n * (`00000000-0000-0000-0123-456789abcdef`), the last two UUID groups\n * (`0123-456789abcdef`), the raw 16-hex OTel span id (`0123456789abcdef`), or a\n * short hex suffix (`abcdef`). Returns the needle (hyphens removed, lowercased)\n * that `matchSpanId` suffix-matches against a span's UUID, or null when the\n * value isn't span-id-shaped (not hex, empty, or longer than a full UUID).\n */\nconst normalizeSpanId = (value: string): string | null => {\n  const needle = value.trim().toLowerCase().replace(/-/g, \"\");\n  if (needle.length > 0 && needle.length <= 32 && HEX_RE.test(needle)) {\n    return needle;\n  }\n  return null;\n};\n\n/**\n * Parse LMNR_DEBUG_CACHE_UNTIL into a span-id needle.\n *\n * In debug-replay v2 the cache window is ALWAYS a span id (the count form was\n * removed): the server resolves the needle into a stop point. Accepts any\n * UUID-ish shape a user copies from the UI. Returns null for an empty value, and\n * warns (then returns null) for a value that isn't span-id shaped.\n */\nconst parseCacheUntil = (value: string | undefined): string | null => {\n  if (value === undefined || value === \"\") {\n    return null;\n  }\n  const spanId = normalizeSpanId(value);\n  if (spanId !== null) {\n    return spanId;\n  }\n  logger.warn(\n    `LMNR_DEBUG_CACHE_UNTIL=${JSON.stringify(value)} is not a span id; ` +\n      \"ignoring\",\n  );\n  return null;\n};\n\n/** Immutable debug configuration, built once at process start. */\nexport interface DebugConfig {\n  sessionId: string;\n  replayTraceId: string | null;\n  // Hyphen-stripped lowercase hex needle of the span id that bounds the replay\n  // window (LMNR_DEBUG_CACHE_UNTIL). Sent verbatim to the cache endpoint, which\n  // resolves it server-side. null when no span id was given — replay is then\n  // not configured.\n  cacheUntilSpanId: string | null;\n  // True when this process is the ORIGIN of the debug run (config built from\n  // local env vars). False when inherited from an upstream service via a\n  // propagated LaminarSpanContext debug block — a downstream run must not open\n  // the browser or emit the run pointer (the origin owns both).\n  localOrigin: boolean;\n  // True ONLY when the SDK minted a fresh session id — i.e. neither\n  // LMNR_DEBUG_SESSION_ID nor an existing `.lmnr/debug-session.json` supplied\n  // one. Gates the one-time browser open: a reused session id (explicit env or a\n  // continuation from the file) is NOT a fresh run, so the browser is not\n  // reopened.\n  sessionMinted: boolean;\n}\n\n/**\n * True when both a replay trace and a cache-until span id are set, i.e. at least\n * one call should consult the cache. The server resolves the span-id window, so\n * the SDK only needs both ids present to arm replay.\n */\nexport const replayEnabledForConfig = (config: DebugConfig): boolean =>\n  config.replayTraceId !== null && config.cacheUntilSpanId !== null;\n\n/**\n * Build the debug config from the environment.\n *\n * Returns null when debug mode is disabled (LMNR_DEBUG falsey/absent) — the\n * caller treats null as \"everything inert\".\n *\n * The `.lmnr/debug-session.json` file is now DEFAULT-ON: it is read\n * unconditionally (no opt-in env gate). The decision tree:\n *\n *  1. Read the file (best-effort → `existing | null`).\n *  2. `sessionId` precedence: `LMNR_DEBUG_SESSION_ID` → `existing.session_id` →\n *     a freshly-minted UUID.\n *  3. `sessionMinted` is true ONLY when we minted (neither env nor file supplied\n *     a session id). A file-present run is a CONTINUATION: it rejoins the same\n *     session silently (no browser).\n *  4. `replayTraceId`: `LMNR_DEBUG_REPLAY_TRACE_ID` → `existing.replay_trace_id`\n *     → null. NOTE: continuation is NOT auto-replay — we do NOT promote the prior\n *     run's `trace_id` into `replayTraceId`. Replay is armed explicitly by the\n *     agent via the env var or the file's `replay_trace_id`.\n *  5. `cacheUntilSpanId`: parsed from `LMNR_DEBUG_CACHE_UNTIL ??\n *     existing.cache_until`.\n */\nexport const buildDebugConfig = (): DebugConfig | null => {\n  if (!isTruthy(process.env.LMNR_DEBUG)) {\n    return null;\n  }\n\n  // Nearest-ancestor resolution: a run started from a subdirectory of a\n  // project joins the project's session.\n  const existing = readDebugSessionFile(resolveDebugSessionDir());\n\n  const providedSessionId =\n    process.env.LMNR_DEBUG_SESSION_ID || existing?.session_id || undefined;\n  const sessionId = providedSessionId || randomUUID();\n  // The browser is opened once per fresh run; a reused session id (explicit env\n  // OR a continuation from the file) is NOT a fresh run, so it is not reopened.\n  const sessionMinted = providedSessionId === undefined;\n  // Continuation is NOT replay: only an explicit replay trace (env or the file's\n  // `replay_trace_id`) arms replay. The prior run's `trace_id` is never promoted.\n  const replayTraceId =\n    process.env.LMNR_DEBUG_REPLAY_TRACE_ID || existing?.replay_trace_id || null;\n  const cacheUntilValue =\n    process.env.LMNR_DEBUG_CACHE_UNTIL ?? existing?.cache_until ?? undefined;\n  const cacheUntilSpanId = parseCacheUntil(cacheUntilValue);\n\n  return {\n    sessionId,\n    replayTraceId,\n    cacheUntilSpanId,\n    localOrigin: true,\n    sessionMinted,\n  };\n};\n\n/**\n * Build a debug config from a propagated `DebugContext` (the inherited path).\n *\n * Unlike `buildDebugConfig` (which reads `LMNR_DEBUG*`), this consumes the debug\n * block carried inside a `LaminarSpanContext` that arrived from an upstream\n * service. Keep line-comparable with the Python `build_debug_config_from_context`.\n *\n * Returns null when the block is absent or not armed (`enabled` falsey). We are\n * the only producer, so an unarmed/forged block is treated as absent (behaviour\n * explicitly undefined). A block with no session id is also ignored — without\n * it the run can't be tied to a cache window.\n *\n * The resulting config is `localOrigin: false`: a downstream run reuses the\n * upstream session and may consult the cache, but must NOT open a browser or\n * emit the run pointer (the origin owns those).\n */\nexport const buildDebugConfigFromContext = (\n  debug: DebugContext | undefined,\n): DebugConfig | null => {\n  if (!debug || !debug.enabled || !debug.sessionId) {\n    return null;\n  }\n  // The needle is propagated verbatim; re-run it through the same parser the\n  // env path uses so a downstream config holds an identical needle form.\n  const cacheUntilSpanId = parseCacheUntil(debug.cacheUntil);\n  return {\n    sessionId: debug.sessionId,\n    replayTraceId: debug.replayTraceId ?? null,\n    cacheUntilSpanId,\n    localOrigin: false,\n    sessionMinted: false,\n  };\n};\n","/**\n * Emit the debug-session record (§5, §I).\n *\n * On a debug run we always print one console line prefixed with `LMNR_DEBUG_RUN `\n * followed by compact JSON, AND write the same payload to\n * `${CWD}/.lmnr/debug-session.json` (default-on now — there is no longer an\n * opt-in env gate). The file write is best-effort (any IO error is swallowed so\n * a read-only working directory never breaks the run) and delegates to the\n * local `writeDebugSessionFile` helper, which writes the SAME shape (the\n * `DebugSessionFile` contract + filename consts from `@lmnr-ai/types`) the CLI\n * writes, so the on-disk file stays consistent across both writers.\n *\n * Part of the cross-language parity surface — keep line-comparable with the\n * Python `pointer.py` (identical prefix and best-effort semantics).\n */\n\nimport { type DebugSessionFile } from \"@lmnr-ai/types\";\n\nimport {\n  readDebugSessionFile,\n  resolveDebugSessionDir,\n  writeDebugSessionFile,\n} from \"./debug-session-file\";\n\n// Console marker the orchestrating tooling greps for. Must match the Python SDK.\nexport const CONSOLE_PREFIX = \"LMNR_DEBUG_RUN \";\n\n/**\n * Build the persisted debug-session record.\n *\n * `startedAt` is the run's start time, captured by `DebugRuntime` at SDK init so\n * the record reflects when tracing began rather than when it was emitted\n * (shutdown). Defaults to now for standalone callers.\n */\nexport const buildDebugSessionFile = (args: {\n  sessionId: string;\n  traceId: string | null;\n  replayTraceId: string | null;\n  cacheUntil: string | null;\n  debuggerUrl: string | null;\n  startedAt?: string;\n}): DebugSessionFile => ({\n  session_id: args.sessionId,\n  trace_id: args.traceId,\n  replay_trace_id: args.replayTraceId,\n  cache_until: args.cacheUntil,\n  debugger_url: args.debuggerUrl,\n  started_at: args.startedAt ?? new Date().toISOString(),\n});\n\n/**\n * Print the console line, then best-effort write the debug-session file.\n *\n * The pointer is emitted at shutdown (via the `exit` hook / `Laminar.shutdown()`),\n * which can be long after the run started. If a newer session was minted in the\n * meantime — e.g. `lmnr-cli debug session new` reset `.lmnr/debug-session.json`\n * while this (older) process was still running — blindly writing our in-memory\n * session would clobber that fresher session id. So skip the file write when the\n * on-disk `session_id` is present and differs from ours; we no longer own the\n * file. The console marker is always printed regardless.\n *\n * The file location is the nearest-ancestor anchor (`resolveDebugSessionDir`),\n * matching where startup (`config.ts`) read the session from — the guard's\n * re-read and the write must hit the SAME file or the guard is meaningless.\n */\nexport const emitPointer = (file: DebugSessionFile): void => {\n  console.log(`${CONSOLE_PREFIX}${JSON.stringify(file)}`);\n  const dir = resolveDebugSessionDir();\n  const onDisk = readDebugSessionFile(dir);\n  if (onDisk !== null && onDisk.session_id !== file.session_id) {\n    return;\n  }\n  writeDebugSessionFile(file, dir);\n};\n","/**\n * In-process debug runtime.\n *\n * A debug run is just a normal process execution started with `LMNR_DEBUG*` env\n * vars. At SDK init the runtime is built once from the environment (§4, §5):\n *\n * 1. Parse `DebugConfig` from the environment.\n * 2. If replay is enabled (a replay trace + a cache-until span id), the provider\n *    LLM wrappers consult the per-call cache endpoint at call time (§9). There is\n *    no source-trace fetch or in-process cache build any more — the server owns\n *    the cache, keyed by the per-call input hash.\n * 3. The run's pointer (§5) is emitted once at process shutdown, after the root\n *    trace id of this run is known.\n *\n * The provider LLM wrappers consult `getRuntime()` to decide replay-vs-live; init\n * stamps `rollout.session_id` on the trace metadata. When debug mode is off,\n * `getRuntime()` returns null and everything is inert (§8). Part of the\n * cross-language parity surface — keep line-comparable with the Python\n * `debug/__init__.py`.\n */\n\nimport { type CacheOutcome, RolloutSessionsResource } from \"@lmnr-ai/client\";\nimport { type DebugContext } from \"@lmnr-ai/types\";\n\nimport {\n  buildDebugConfig,\n  buildDebugConfigFromContext,\n  DebugConfig,\n  isTruthy,\n  replayEnabledForConfig,\n} from \"./config\";\nimport { buildDebugSessionFile, emitPointer } from \"./pointer\";\n\nexport { isTruthy };\n\n/**\n * Holds the immutable debug config plus the handle used to look up the\n * server-side replay cache per LLM call.\n *\n * Also tracks the run's root trace id so the pointer (§5) can be emitted once at\n * shutdown, when the trace id is guaranteed to be known.\n */\nexport class DebugRuntime {\n  private readonly _config: DebugConfig;\n  private _rolloutSessions: RolloutSessionsResource;\n  private readonly _debuggerUrl: string | null;\n  private _projectId: string | null = null;\n  private _traceId: string | null = null;\n  private _emitted = false;\n  // Captured at construction (SDK init) so the pointer's `started_at` reflects\n  // when the run began, not when the pointer is emitted (shutdown).\n  private readonly _startedAt = new Date().toISOString();\n\n  constructor(\n    config: DebugConfig,\n    rolloutSessions: RolloutSessionsResource,\n    debuggerUrl: string | null,\n  ) {\n    this._config = config;\n    this._rolloutSessions = rolloutSessions;\n    this._debuggerUrl = debuggerUrl;\n  }\n\n  /**\n   * Swap in a fresh rollout-sessions handle for cache lookups.\n   *\n   * A from-context runtime can be armed (deep in span creation) BEFORE\n   * `initialize()` runs, so its client is built from unset connection args and\n   * falls back to env/defaults. Once `initialize()` supplies the real\n   * baseUrl/port/api-key, it rebinds the handle so replay `lookupCache` calls\n   * reach the same backend as the rest of the SDK. No-op on the local-origin\n   * path (the env runtime is only ever built after args are known).\n   */\n  rebindRolloutSessions(rolloutSessions: RolloutSessionsResource): void {\n    this._rolloutSessions = rolloutSessions;\n  }\n\n  /** The rollout-sessions handle this runtime routes cache lookups through. */\n  get rolloutSessions(): RolloutSessionsResource {\n    return this._rolloutSessions;\n  }\n\n  /**\n   * Refresh the DYNAMIC replay coordinates from a freshly-parsed context config.\n   *\n   * The transport (client / rollout-sessions handle) is STABLE and reused; only\n   * the per-request coordinates move — `sessionId`, `replayTraceId`,\n   * `cacheUntilSpanId`. This is what lets a long-lived downstream service follow\n   * each incoming request's `LaminarSpanContext` instead of freezing on the very\n   * first one. `localOrigin` / `sessionMinted` are part of the run's IDENTITY and\n   * never change here (the caller only ever updates a `localOrigin:false`\n   * runtime; env-origin config keeps precedence).\n   *\n   * Returns true when the session id changed, so the caller can re-register the\n   * new session and re-stamp `rollout.session_id`.\n   */\n  updateContextConfig(config: DebugConfig): boolean {\n    const configChanged =\n      this._config.sessionId !== config.sessionId ||\n      this._config.replayTraceId !== config.replayTraceId ||\n      this._config.cacheUntilSpanId !== config.cacheUntilSpanId;\n    this._config.sessionId = config.sessionId;\n    this._config.replayTraceId = config.replayTraceId;\n    this._config.cacheUntilSpanId = config.cacheUntilSpanId;\n    return configChanged;\n  }\n\n  get sessionId(): string {\n    return this._config.sessionId;\n  }\n\n  get replayTraceId(): string | null {\n    return this._config.replayTraceId;\n  }\n\n  get cacheUntilSpanId(): string | null {\n    return this._config.cacheUntilSpanId;\n  }\n\n  /** True when replay is configured for this run (replay trace + cache window). */\n  get replayConfigured(): boolean {\n    return replayEnabledForConfig(this._config);\n  }\n\n  /**\n   * True when this process originated the run (config from local env). False\n   * when armed from a propagated `DebugContext`: a downstream run reuses the\n   * upstream session and may consult the cache, but must not open a browser or\n   * emit the run pointer.\n   */\n  get localOrigin(): boolean {\n    return this._config.localOrigin;\n  }\n\n  /**\n   * True when this run should open the debugger URL in a browser once. Only a\n   * local-origin run that minted a fresh session id qualifies: a reused session\n   * id (continuation/replay) or a context-armed downstream run must not reopen\n   * the browser.\n   */\n  get shouldOpenBrowser(): boolean {\n    return this._config.localOrigin && this._config.sessionMinted;\n  }\n\n  /**\n   * Look up the server-side replay cache for one LLM call (debug-replay v2).\n   *\n   * Routes through the runtime (rather than a static `Laminar.client`) so the\n   * resource is captured at init and the lookup stays testable. Returns\n   * `{ kind: \"live\" }` defensively when replay isn't fully configured — callers\n   * gate on `replayConfigured` first, so this only guards against misuse.\n   */\n  async lookupCache(inputHash: string): Promise<CacheOutcome> {\n    const replayTraceId = this._config.replayTraceId;\n    const cacheUntil = this._config.cacheUntilSpanId;\n    if (replayTraceId === null || cacheUntil === null) {\n      return { kind: \"live\" };\n    }\n    return this._rolloutSessions.cache({\n      sessionId: this._config.sessionId,\n      replayTraceId,\n      cacheUntil,\n      inputHash,\n    });\n  }\n\n  /** Remember the root trace id of this run (first root span wins). */\n  recordTraceId(traceId: string): void {\n    if (this._traceId === null) {\n      this._traceId = traceId;\n    }\n  }\n\n  /**\n   * Remember the backend-resolved project id (first wins).\n   *\n   * Resolved by the session-register call AFTER construction, so the runtime\n   * starts with only the base `debuggerUrl`; this lets `debuggerSessionUrl`\n   * upgrade to the full per-session URL once known.\n   */\n  recordProjectId(projectId: string): void {\n    if (this._projectId === null) {\n      this._projectId = projectId;\n    }\n  }\n\n  /**\n   * The human-facing debugger URL for this run, or null.\n   *\n   * Single source of truth for the URL printed to the console AND stored in the\n   * run pointer's `debugger_url` field. When the project id is known (register\n   * succeeded) it is the full\n   * `<base>/project/<projectId>/debugger-sessions/<sessionId>`; otherwise it\n   * falls back to the base `debuggerUrl` (null when even that is unset).\n   */\n  debuggerSessionUrl(): string | null {\n    if (this._debuggerUrl === null) {\n      return null;\n    }\n    if (this._projectId === null) {\n      return this._debuggerUrl;\n    }\n    return (\n      `${this._debuggerUrl}/project/${this._projectId}` +\n      `/debugger-sessions/${this._config.sessionId}`\n    );\n  }\n\n  /**\n   * Emit the debug-session record once (console line + best-effort file write\n   * to `.lmnr/debug-session.json`).\n   *\n   * No-op on a downstream run (`localOrigin: false`): a runtime armed from a\n   * propagated `DebugContext` joins the upstream replay session and must NOT\n   * own/overwrite the file — the origin owns it. Gated here (not just at the\n   * call sites) so `shutdown()` and any exit hook stay safe. Mirrors Python's\n   * `emit_pointer`.\n   */\n  emitPointer(): void {\n    if (!this._config.localOrigin) {\n      return;\n    }\n    if (this._emitted) {\n      return;\n    }\n    this._emitted = true;\n    const file = buildDebugSessionFile({\n      sessionId: this._config.sessionId,\n      traceId: this._traceId,\n      replayTraceId: this._config.replayTraceId,\n      cacheUntil: this._config.cacheUntilSpanId,\n      debuggerUrl: this.debuggerSessionUrl(),\n      startedAt: this._startedAt,\n    });\n    emitPointer(file);\n  }\n}\n\nlet runtime: DebugRuntime | null = null;\nlet initialized = false;\n\n/** Return the process-wide debug runtime, or null when debug mode is off. */\nexport const getRuntime = (): DebugRuntime | null => runtime;\n\n/**\n * Build the debug runtime once. Idempotent; safe to call from initialize().\n *\n * Fully synchronous now: the server owns the replay cache (looked up per call),\n * so there is no source-trace fetch to await. The runtime is registered\n * immediately, making `sessionId` available for metadata stamping and the cache\n * endpoint reachable via `runtime.lookupCache`.\n *\n * Never throws: a null config (debug mode off) simply yields a null runtime.\n */\nexport const initDebugRuntime = (\n  rolloutSessions: RolloutSessionsResource,\n  debuggerUrl: string | null = null,\n): { runtime: DebugRuntime | null } => {\n  if (initialized) {\n    return { runtime };\n  }\n\n  const config = buildDebugConfig();\n  if (config === null) {\n    // Debug mode is off: nothing was built, so do NOT latch the one-shot flag.\n    // Otherwise a later init (e.g. after the env flips LMNR_DEBUG on) would\n    // short-circuit until resetDebugRuntime(). The off path only reads env\n    // vars, so re-running it on a repeat call is cheap.\n    return { runtime: null };\n  }\n  initialized = true;\n\n  runtime = new DebugRuntime(config, rolloutSessions, debuggerUrl);\n  return { runtime };\n};\n\n/**\n * Arm OR refresh the debug runtime from a propagated `DebugContext`.\n *\n * Called deep in span creation when a parent `LaminarSpanContext` carrying a\n * debug block parses — so a downstream service joins the upstream run regardless\n * of how the span originated. The whole point of propagating coordinates through\n * the span context is that they are DYNAMIC: a long-lived downstream service\n * handling many requests must follow each request's `sessionId` / `replayTraceId`\n * / `cacheUntil`, not freeze on the first one it ever saw.\n *\n * So the transport is stable but the coordinates move:\n * - No runtime yet → build one from the context (latch `initialized`).\n * - A `localOrigin` (env) runtime exists → env config wins; leave it untouched.\n *   The local process owns the run; a propagated context must not hijack it.\n * - A `localOrigin:false` (context-armed) runtime exists → REUSE its client and\n *   just refresh the dynamic coordinates from the new context.\n *\n * Returns `{ runtime: null }` without latching when the block is absent /\n * unarmed, so a later valid context can still arm the runtime. Never throws.\n */\nexport const initDebugRuntimeFromContext = (\n  debug: DebugContext | undefined,\n  rolloutSessions: RolloutSessionsResource,\n  debuggerUrl: string | null = null,\n): { runtime: DebugRuntime | null; configChanged: boolean } => {\n  const config = buildDebugConfigFromContext(debug);\n  if (config === null) {\n    return { runtime: runtime, configChanged: false };\n  }\n\n  if (runtime !== null) {\n    // An env-origin run owns the process — a propagated context never overrides\n    // it. A context-armed run, by contrast, tracks the live request: refresh its\n    // dynamic coordinates in place and reuse the already-built client.\n    if (runtime.localOrigin) {\n      return { runtime, configChanged: false };\n    }\n    const configChanged = runtime.updateContextConfig(config);\n    return { runtime, configChanged };\n  }\n\n  initialized = true;\n  runtime = new DebugRuntime(config, rolloutSessions, debuggerUrl);\n  return { runtime, configChanged: true };\n};\n\n/**\n * Reset module state so a later `initDebugRuntime` re-reads `LMNR_DEBUG*`.\n *\n * Called by `Laminar.shutdown()` (which supports a subsequent `initialize()`)\n * and by tests. Without this, the one-shot `initialized` flag would pin the\n * first run's runtime — stale session metadata and a spent pointer — across a\n * shutdown/initialize cycle. Mirrors Python's `reset_debug_runtime`.\n */\nexport const resetDebugRuntime = (): void => {\n  runtime = null;\n  initialized = false;\n};\n","import {\n  type DebugContext,\n  LaminarSpanContext,\n  TraceType,\n  TracingLevel,\n} from \"@lmnr-ai/types\";\nimport {\n  Attributes,\n  AttributeValue,\n  type Context,\n  Exception,\n  HrTime,\n  Link,\n  type Span,\n  SpanContext,\n  SpanKind,\n  SpanStatus,\n  TimeInput,\n} from \"@opentelemetry/api\";\nimport { type InstrumentationScope } from \"@opentelemetry/core\";\nimport {\n  ReadableSpan,\n  type Span as SdkSpan,\n  TimedEvent,\n} from \"@opentelemetry/sdk-trace-base\";\n\nimport { getRuntime } from \"../../debug\";\nimport {\n  initializeLogger,\n  metadataToAttributes,\n  otelSpanIdToUUID,\n  otelTraceIdToUUID,\n  StringUUID,\n  truncateSpanPayload,\n} from \"../../utils\";\nimport {\n  ASSOCIATION_PROPERTIES,\n  SESSION_ID,\n  SPAN_IDS_PATH,\n  SPAN_INPUT,\n  SPAN_OUTPUT,\n  SPAN_PATH,\n  TRACE_TYPE,\n  USER_ID,\n} from \"./attributes\";\nimport { getParentSpanId, makeSpanOtelV2Compatible } from \"./compat\";\nimport { LaminarContextManager } from \"./context\";\n\nconst logger = initializeLogger();\n\n/**\n * Build the debug block to propagate, or undefined when debug mode is off.\n *\n * Reads the process-wide debug runtime so a serialized span context carries the\n * run's coordinates to downstream services. Only an armed (`enabled: true`)\n * block is ever produced — we are the sole producer. Best-effort: any failure\n * (or no runtime) yields undefined so serialization never breaks. Keep\n * line-comparable with the Python `_current_debug_context`.\n */\nconst currentDebugContext = (): DebugContext | undefined => {\n  try {\n    const runtime = getRuntime();\n    if (runtime === null) {\n      return undefined;\n    }\n    return {\n      enabled: true,\n      sessionId: runtime.sessionId,\n      replayTraceId: runtime.replayTraceId ?? undefined,\n      cacheUntil: runtime.cacheUntilSpanId ?? undefined,\n    };\n  } catch {\n    return undefined;\n  }\n};\n\n// We decided to implement raw otel Span interface and have _span: SdkSpan because SdkSpan\n// discourages use of its constructor directly in favour of Tracer.startSpan()\n// We are using constructor directly because we're implementing Tracer interface as well.\nexport class LaminarSpan implements Span, ReadableSpan {\n  private _span: SdkSpan;\n  // Whether the span is started by Laminar.startActiveSpan()\n  private _activated: boolean;\n  // When set, the span was pushed onto the process-global context stack via\n  // `Laminar.startActiveSpan({ global: true })`. We remember the exact Context\n  // reference so `end()` can pop the matching entry, even if spans end out of\n  // order.\n  private _globalActiveContext?: Context;\n\n  constructor(span: Span, activated?: boolean) {\n    if (span instanceof LaminarSpan) {\n      this._activated = span.isActivated;\n      this._span = span._span;\n    } else {\n      this._activated = activated ?? false;\n\n      // This line assumes that the span passed here is an SdkSpan. Reason:\n      // When using default OpenTelemetry Node SDK, i.e. NodeTracerProvider.getTracer().startSpan(),\n      // the span returned is an SdkSpan. SDK span implements ReadableSpan, so attributes\n      // can be accessed. Span, i.e. OpenTelemetry API Span, does not require that, so custom\n      // SDK implementations may not implement certain ReadableSpan methods, in particular\n      // `attributes` that we need to access.\n      this._span = span as SdkSpan;\n    }\n\n    this.name = this._span.name;\n    this.kind = this._span.kind;\n    this.startTime = this._span.startTime;\n    this.endTime = this._span.endTime;\n    this.status = this._span.status;\n    this.attributes = this._span.attributes;\n    this.links = this._span.links;\n    this.events = this._span.events;\n    this.duration = this._span.duration;\n    this.ended = this._span.ended;\n    this.resource = this._span.resource;\n    this.instrumentationLibrary = (this._span as any).instrumentationLibrary;\n    this.droppedAttributesCount = this._span.droppedAttributesCount;\n    this.droppedEventsCount = this._span.droppedEventsCount;\n    this.droppedLinksCount = this._span.droppedLinksCount;\n    this.makeOtelV2Compatible();\n    LaminarContextManager.addActiveSpan(this.spanContext().spanId);\n  }\n\n  name: string;\n  kind: SpanKind;\n  parentSpanId?: string | undefined;\n  startTime: HrTime;\n  endTime: HrTime;\n  status: SpanStatus;\n  attributes: Attributes;\n  links: Link[];\n  events: TimedEvent[];\n  duration: HrTime;\n  ended: boolean;\n  resource: any; // type IResource from `@opentelemetry/resources`\n  instrumentationLibrary: any; // type InstrumentationLibrary from `@opentelemetry/core`\n  droppedAttributesCount: number;\n  droppedEventsCount: number;\n  droppedLinksCount: number;\n\n  public spanContext(): SpanContext {\n    return this._span.spanContext();\n  }\n\n  public setAttribute(key: string, value: AttributeValue): this {\n    this._span.setAttribute(key, value);\n    return this;\n  }\n\n  public setAttributes(attributes: Attributes): this {\n    this._span.setAttributes(attributes);\n    return this;\n  }\n\n  public addEvent(\n    name: string,\n    attributesOrStartTime?: Attributes | TimeInput,\n    startTime?: TimeInput,\n  ): this {\n    this._span.addEvent(name, attributesOrStartTime, startTime);\n    return this;\n  }\n\n  public addLink(link: Link): this {\n    this._span.addLink(link);\n    return this;\n  }\n\n  public addLinks(links: Link[]): this {\n    this._span.addLinks(links);\n    return this;\n  }\n\n  public setStatus(status: SpanStatus): this {\n    this._span.setStatus(status);\n    return this;\n  }\n\n  public updateName(name: string): this {\n    this._span.updateName(name);\n    return this;\n  }\n\n  public end(endTime?: TimeInput): void {\n    if (!this._span.isRecording()) {\n      // This will log a warning and do nothing.\n      return this._span.end(endTime);\n    }\n\n    // Remove from global registry on end\n    LaminarContextManager.removeActiveSpan(this.spanContext().spanId);\n\n    if (this._activated) {\n      LaminarContextManager.popContext();\n    }\n    if (this._globalActiveContext !== undefined) {\n      LaminarContextManager.popGlobalContext(this._globalActiveContext);\n      this._globalActiveContext = undefined;\n    }\n    return this._span.end(endTime);\n  }\n\n  public setGlobalActiveContext(context: Context): void {\n    this._globalActiveContext = context;\n  }\n\n  public set activated(activated: boolean) {\n    this._activated = activated;\n  }\n\n  public isRecording(): boolean {\n    return this._span.isRecording();\n  }\n\n  public recordException(exception: Exception, time?: TimeInput): void {\n    return this._span.recordException(exception, time);\n  }\n\n  // ================================\n  // Laminar specific methods\n  // ================================\n\n  public setTraceSessionId(sessionId: string): void {\n    this._span.setAttribute(SESSION_ID, sessionId);\n  }\n\n  public setTraceUserId(userId: string): void {\n    this._span.setAttribute(USER_ID, userId);\n  }\n\n  public setTraceMetadata(metadata: Record<string, any>): void {\n    this._span.setAttributes(metadataToAttributes(metadata));\n  }\n\n  public setInput(input: any): void {\n    const finalInput =\n      typeof input === \"string\" ? input : JSON.stringify(input);\n    this._span.setAttribute(\n      SPAN_INPUT,\n      truncateSpanPayload(finalInput, \"input\"),\n    );\n  }\n\n  public setOutput(output: any): void {\n    const finalOutput =\n      typeof output === \"string\" ? output : JSON.stringify(output);\n    this._span.setAttribute(\n      SPAN_OUTPUT,\n      truncateSpanPayload(finalOutput, \"output\"),\n    );\n  }\n\n  public setTags(tags: string[]): void {\n    this._span.setAttribute(\n      `${ASSOCIATION_PROPERTIES}.tags`,\n      Array.from(new Set(tags)),\n    );\n  }\n\n  public addTags(tags: string[]): void {\n    const currentTags = this.tags;\n    this.setTags(Array.from(new Set([...currentTags, ...tags])));\n  }\n\n  public getLaminarSpanContext(): LaminarSpanContext {\n    let spanPath: string[] = [];\n    let spanIdsPath: StringUUID[] = [];\n    let userId;\n    let sessionId;\n    let traceType;\n    let tracingLevel = TracingLevel.ALL;\n    const metadata: Record<string, AttributeValue> = {};\n\n    if (this._span.attributes) {\n      spanPath = this._span.attributes[SPAN_PATH] as string[];\n      spanIdsPath = this._span.attributes[SPAN_IDS_PATH] as StringUUID[];\n      userId = this._span.attributes[USER_ID] as string;\n      sessionId = this._span.attributes[SESSION_ID] as string;\n      traceType = this._span.attributes[TRACE_TYPE] as TraceType;\n      tracingLevel =\n        (this._span.attributes[\n          `${ASSOCIATION_PROPERTIES}.tracing_level`\n        ] as TracingLevel) ?? TracingLevel.ALL;\n      for (const [key, rawValue] of Object.entries(this._span.attributes)) {\n        if (key.startsWith(`${ASSOCIATION_PROPERTIES}.metadata.`)) {\n          let value = rawValue!;\n          try {\n            value = JSON.parse(value as string);\n          } catch {\n            // Ignore\n          }\n          metadata[key.replace(`${ASSOCIATION_PROPERTIES}.metadata.`, \"\")] =\n            value;\n        }\n      }\n    } else {\n      logger.warn(\n        \"Attributes object is not available. Most likely the span is not a LaminarSpan \" +\n          \"and not an OpenTelemetry default SDK Span. Span path and ids path will be empty.\",\n      );\n    }\n\n    return {\n      spanId: otelSpanIdToUUID(this._span.spanContext().spanId) as StringUUID,\n      traceId: otelTraceIdToUUID(this._span.spanContext().traceId),\n      isRemote: this._span.spanContext().isRemote ?? false,\n      spanPath,\n      spanIdsPath,\n      userId,\n      sessionId,\n      metadata,\n      traceType,\n      tracingLevel,\n      debug: currentDebugContext(),\n    };\n  }\n\n  public spanId(format: \"otel\" | \"uuid\" = \"otel\"): string {\n    const spanId = this._span.spanContext().spanId;\n    if (format === \"otel\") {\n      return spanId;\n    }\n    return otelSpanIdToUUID(spanId);\n  }\n\n  public traceId(format: \"otel\" | \"uuid\" = \"otel\"): string {\n    const traceId = this._span.spanContext().traceId;\n    if (format === \"otel\") {\n      return traceId;\n    }\n    return otelTraceIdToUUID(traceId);\n  }\n\n  public get tags(): string[] {\n    if (!this._span.attributes) {\n      logger.warn(\n        \"[LaminarSpan.tags] WARNING. Current span does not have attributes object. \" +\n          \"Possibly, the span was created with a custom OTel SDK. Returning an empty list. \" +\n          \"Help: OpenTelemetry API does not guarantee reading attributes from a span, but OTel \" +\n          \"SDK allows it by default. Laminar SDK allows to read attributes too.\",\n      );\n      return [];\n    }\n    return (\n      (this._span.attributes[`${ASSOCIATION_PROPERTIES}.tags`] as string[]) ??\n      []\n    );\n  }\n\n  public get laminarAssociationProperties(): {\n    metadata?: Record<string, any>;\n    userId?: string;\n    sessionId?: string;\n    traceType?: TraceType;\n    tracingLevel?: TracingLevel;\n  } {\n    if (!this._span.attributes) {\n      logger.warn(\n        \"[LaminarSpan.laminarAssociationProperties] WARNING. Current span does not have \" +\n          \"attributes object. Possibly, the span was created with a custom OTel SDK. Returning \" +\n          \"an \" +\n          \"empty object. Help: OpenTelemetry API does not guarantee reading attributes from a \" +\n          \"span, but OTel SDK allows it by default. Laminar SDK allows to read attributes too.\",\n      );\n      return {};\n    }\n    try {\n      const properties: Record<string, any> = {};\n      const metadata: Record<string, any> = {};\n      for (const [key, rawValue] of Object.entries(this._span.attributes)) {\n        if (!key.startsWith(`${ASSOCIATION_PROPERTIES}.`)) {\n          continue;\n        }\n        let value = rawValue!;\n        if (key.startsWith(`${ASSOCIATION_PROPERTIES}.metadata.`)) {\n          const metaKey = key.replace(\n            `${ASSOCIATION_PROPERTIES}.metadata.`,\n            \"\",\n          );\n          try {\n            value = JSON.parse(value as string);\n          } catch {\n            // Ignore\n          }\n          metadata[metaKey] = value;\n        }\n      }\n      properties.tracingLevel =\n        (this._span.attributes[\n          `${ASSOCIATION_PROPERTIES}.tracing_level`\n        ] as TracingLevel) ?? TracingLevel.ALL;\n      properties.userId =\n        (this._span.attributes[USER_ID] as string) ?? undefined;\n      properties.sessionId =\n        (this._span.attributes[SESSION_ID] as string) ?? undefined;\n      properties.traceType =\n        (this._span.attributes[TRACE_TYPE] as TraceType) ?? undefined;\n      return {\n        metadata,\n        ...properties,\n      };\n    } catch {\n      return {};\n    }\n  }\n\n  // ================================\n  // OTel V2 compatibility\n  // ================================\n\n  public makeOtelV2Compatible(): void {\n    makeSpanOtelV2Compatible(this._span);\n  }\n\n  public get instrumentationScope(): InstrumentationScope {\n    return (this._span as any).instrumentationLibrary as InstrumentationScope;\n  }\n\n  public get parentSpanContext(): SpanContext | undefined {\n    const parentSpanId = getParentSpanId(this._span);\n    if (!parentSpanId) {\n      return undefined;\n    }\n    return {\n      spanId: parentSpanId,\n      traceId: this.spanContext().traceId,\n      // TODO: somehow get the traceFlags from the parent span\n      traceFlags: this.spanContext().traceFlags,\n    };\n  }\n\n  public getParentSpanId(): string | undefined {\n    return getParentSpanId(this._span);\n  }\n\n  public get isActivated(): boolean {\n    return this._activated;\n  }\n}\n","import { TraceType, TracingLevel } from \"@lmnr-ai/types\";\nimport {\n  Context,\n  context as contextApi,\n  createContextKey,\n  ROOT_CONTEXT,\n  trace,\n} from \"@opentelemetry/api\";\nimport { AsyncLocalStorage } from \"async_hooks\";\n\nimport { LaminarSpan } from \"./span\";\n\nexport const CONTEXT_SPAN_PATH_KEY = createContextKey(\"span_path\");\nexport const ASSOCIATION_PROPERTIES_KEY = createContextKey(\n  \"association_properties\",\n);\nexport const CONTEXT_GLOBAL_METADATA_KEY = createContextKey(\"global_metadata\");\n\nexport class LaminarContextManager {\n  private static _asyncLocalStorage = new AsyncLocalStorage<Context[]>();\n  private static _globalMetadata: Record<string, any> = {};\n  private static _inheritGlobalContext: boolean = false;\n  // Static registry for cross-async span management\n  // We're keeping track of spans have started (and running) here for the cases when span\n  // is started in one async context and ended in another\n  // We use this registry to ignore the context of spans that were already ended in\n  // another async context.\n  // LaminarSpan adds and removes itself to and from this registry in start()\n  // and end() methods respectively.\n  private static _activeSpans: Set<string> = new Set();\n  // Process-global stack of contexts marked globally active via\n  // `Laminar.startActiveSpan({ global: true })`. Unlike the AsyncLocalStorage\n  // stack, this one is visible from any async task in the process. We use it\n  // as the fallback parent when the ALS stack is empty. Spans push onto this\n  // stack when started globally and pop in `LaminarSpan.end()`.\n  private static _globalActiveContexts: Context[] = [];\n\n  private constructor() {\n    throw new Error(\n      \"LaminarContextManager is a static class and cannot be instantiated\",\n    );\n  }\n\n  private static isValidContext(context: Context): boolean {\n    const span = trace.getSpan(context);\n    if (!span) {\n      return true;\n    }\n    if (!span.isRecording() && span.spanContext().isRemote) {\n      return true;\n    }\n    if (!(span instanceof LaminarSpan)) {\n      return true;\n    }\n    if (!span.isActivated) {\n      return true;\n    }\n    try {\n      return this._activeSpans.has(span.spanContext().spanId);\n    } catch {\n      return true;\n    }\n  }\n\n  private static findLatestValidContext(\n    contexts: Context[],\n  ): Context | undefined {\n    // Walk through contexts from most recent to oldest and return the most\n    // recent one that is still valid (has a live activated span, or has no\n    // span at all).\n    for (let i = contexts.length - 1; i >= 0; i--) {\n      if (this.isValidContext(contexts[i])) {\n        return contexts[i];\n      }\n    }\n    return undefined;\n  }\n\n  public static getContext(): Context {\n    // Prefer the per-async context stack so local control flow wins over any\n    // globally-registered span. Fall back to the global stack so spans started\n    // via `startActiveSpan({ global: true })` act as parents for descendants\n    // that run in unrelated async tasks.\n    const asyncContext = this.findLatestValidContext(this.getContextStack());\n    if (asyncContext !== undefined) {\n      return asyncContext;\n    }\n    const globalContext = this.findLatestValidContext(\n      this._globalActiveContexts,\n    );\n    if (globalContext !== undefined) {\n      return globalContext;\n    }\n    return ROOT_CONTEXT;\n  }\n\n  public static pushContext(context: Context) {\n    const contexts = this.getContextStack();\n    const newContexts = [...contexts, context];\n    this._asyncLocalStorage.enterWith(newContexts);\n  }\n\n  public static popContext() {\n    const contexts = this.getContextStack();\n    if (contexts.length > 0) {\n      // Remove the last context and filter out any contexts with inactive spans\n      const newContexts = contexts.slice(0, -1).filter((context) => {\n        const span = trace.getSpan(context);\n\n        if (!span) {\n          // No span in this context, it's valid\n          return true;\n        }\n\n        // Check if the span in this context has been ended\n        try {\n          return this._activeSpans.has(span.spanContext().spanId);\n        } catch {\n          // If we can't check the span, assume it's valid\n          return true;\n        }\n      });\n\n      this._asyncLocalStorage.enterWith(newContexts);\n    }\n  }\n\n  public static pushGlobalContext(context: Context) {\n    this._globalActiveContexts.push(context);\n  }\n\n  // Remove a specific context reference from the ALS stack. Unlike\n  // `popContext`, this does not assume LIFO order — it locates the most\n  // recent entry `=== context` and splices it out. Used by callers (e.g. the\n  // OpenAI Agents processor) that activate spans so nested instrumentation\n  // inherits them, but whose spans can end in arbitrary order with respect to\n  // other activated spans on the same async frame.\n  public static removeContext(context: Context) {\n    const contexts = this.getContextStack();\n    if (contexts.length === 0) {\n      return;\n    }\n    for (let i = contexts.length - 1; i >= 0; i--) {\n      if (contexts[i] === context) {\n        const newContexts = contexts.slice(0, i).concat(contexts.slice(i + 1));\n        this._asyncLocalStorage.enterWith(newContexts);\n        return;\n      }\n    }\n  }\n\n  public static popGlobalContext(context?: Context) {\n    if (context !== undefined) {\n      // Remove the specific context entry (most recent occurrence) to keep\n      // the stack consistent when spans end out of order across async tasks.\n      for (let i = this._globalActiveContexts.length - 1; i >= 0; i--) {\n        if (this._globalActiveContexts[i] === context) {\n          this._globalActiveContexts.splice(i, 1);\n          return;\n        }\n      }\n      return;\n    }\n    if (this._globalActiveContexts.length > 0) {\n      this._globalActiveContexts.pop();\n    }\n  }\n\n  public static clearContexts() {\n    this._asyncLocalStorage.enterWith([]);\n    this._globalActiveContexts = [];\n  }\n\n  public static clearActiveSpans() {\n    this._activeSpans.clear();\n  }\n\n  public static getContextStack(): Context[] {\n    return (\n      this._asyncLocalStorage.getStore() ||\n      (this._inheritGlobalContext ? [contextApi.active()] : [])\n    );\n  }\n\n  /**\n   * Run a function with an isolated context stack.\n   * This ensures that parallel executions don't interfere with each other.\n   */\n  public static runWithIsolatedContext<T>(\n    initialStack: Context[],\n    fn: () => T,\n  ): T {\n    return this._asyncLocalStorage.run(initialStack, fn);\n  }\n\n  public static addActiveSpan(spanId: string): void {\n    this._activeSpans.add(spanId);\n  }\n\n  public static removeActiveSpan(spanId: string): void {\n    this._activeSpans.delete(spanId);\n  }\n\n  public static setAssociationProperties(\n    span: LaminarSpan,\n    context: Context,\n  ): Context {\n    const properties = span.laminarAssociationProperties;\n\n    return this.setRawAssociationProperties(properties, context);\n  }\n\n  public static setRawAssociationProperties(\n    properties: Record<string, any>,\n    context: Context,\n  ): Context {\n    let entityContext = context;\n    const userId = properties.userId;\n    const sessionId = properties.sessionId;\n    const traceType = properties.traceType;\n    const metadata = properties.metadata;\n    const tracingLevel = properties.tracingLevel;\n    entityContext = entityContext.setValue(ASSOCIATION_PROPERTIES_KEY, {\n      userId,\n      sessionId,\n      traceType,\n      metadata,\n      tracingLevel,\n    });\n    return entityContext;\n  }\n\n  public static setGlobalMetadata(globalMetadata: Record<string, any>) {\n    this._globalMetadata = globalMetadata;\n  }\n\n  public static getGlobalMetadata(): Record<string, any> {\n    return this._globalMetadata;\n  }\n\n  public static getAssociationProperties(): {\n    userId?: string;\n    sessionId?: string;\n    traceType?: TraceType;\n    tracingLevel?: TracingLevel;\n    metadata?: Record<string, any>;\n  } {\n    const entityContext = this.getContext();\n    return entityContext.getValue(ASSOCIATION_PROPERTIES_KEY) ?? {};\n  }\n\n  public static set inheritGlobalContext(inheritGlobalContext: boolean) {\n    this._inheritGlobalContext = inheritGlobalContext;\n  }\n}\n","import { errorMessage } from \"@lmnr-ai/types\";\nimport { trace } from \"@opentelemetry/api\";\nimport type { ReadableSpan } from \"@opentelemetry/sdk-trace-base\";\nimport * as fs from \"fs\";\nimport * as net from \"net\";\nimport * as os from \"os\";\nimport * as path from \"path\";\n\nimport { Laminar } from \"../../../laminar\";\nimport { initializeLogger } from \"../../../utils\";\nimport { SPAN_IDS_PATH, SPAN_PATH } from \"../../tracing/attributes\";\nimport { LaminarContextManager } from \"../../tracing/context\";\n\nconst logger = initializeLogger();\n\nconst DEFAULT_ANTHROPIC_BASE_URL = \"https://api.anthropic.com\";\nconst DEFAULT_CC_PROXY_PORT = 45667;\nconst CC_PROXY_PORT_ATTEMPTS = 50;\n\n// Foundry configuration constants\nconst FOUNDRY_BASE_URL_ENV = \"ANTHROPIC_FOUNDRY_BASE_URL\";\nconst FOUNDRY_RESOURCE_ENV = \"ANTHROPIC_FOUNDRY_RESOURCE\";\nconst FOUNDRY_USE_ENV = \"CLAUDE_CODE_USE_FOUNDRY\";\n\n// Bedrock configuration constants\nconst BEDROCK_BASE_URL_ENV = \"ANTHROPIC_BEDROCK_BASE_URL\";\nconst BEDROCK_USE_ENV = \"CLAUDE_CODE_USE_BEDROCK\";\nconst BEDROCK_AWS_REGION_ENV = \"AWS_REGION\";\n\n// Vertex AI configuration constants\nconst VERTEX_BASE_URL_ENV = \"ANTHROPIC_VERTEX_BASE_URL\";\nconst VERTEX_USE_ENV = \"CLAUDE_CODE_USE_VERTEX\";\n\n// Base-URL keys that must point at our proxy in the flag-settings layer.\nexport const PROXY_BASE_URL_ENV_KEYS = [\n  \"ANTHROPIC_BASE_URL\",\n  FOUNDRY_BASE_URL_ENV,\n  BEDROCK_BASE_URL_ENV,\n  VERTEX_BASE_URL_ENV,\n];\n\n// Provider base-URL keys paired with the flag that turns that provider on. A\n// provider can be configured without its base-URL key (e.g. Foundry via\n// ANTHROPIC_FOUNDRY_RESOURCE alone), so the flag is what tells us the key is in\n// play and must be pinned to the proxy.\nconst PROVIDER_BASE_URL_ENV_KEYS: [string, string][] = [\n  [FOUNDRY_BASE_URL_ENV, FOUNDRY_USE_ENV],\n  [BEDROCK_BASE_URL_ENV, BEDROCK_USE_ENV],\n  [VERTEX_BASE_URL_ENV, VERTEX_USE_ENV],\n];\n\n// Forward-proxy env vars in BOTH cases. Claude Code reads the lowercase spelling\n// too (and prefers it), so handling only the uppercase form lets a lowercase\n// corporate proxy divert traffic away from us.\nconst PROXY_ENV_KEYS = [\n  \"HTTP_PROXY\",\n  \"HTTPS_PROXY\",\n  \"http_proxy\",\n  \"https_proxy\",\n];\n\n// Keys that must be blanked in the flag-settings layer: they would otherwise\n// redirect the CLI away from our proxy. Removing them from the flag layer is not\n// enough — settings layers merge per key, so a lower layer's value would win.\nconst PROXY_NEUTRALIZED_ENV_KEYS = [...PROXY_ENV_KEYS, FOUNDRY_RESOURCE_ENV];\n\n// Transport-level forward proxies, NOT Anthropic API base URLs. They outrank\n// every base URL when resolving our upstream, so reading them from the settings\n// layers would make a settings-defined corporate proxy shadow the gateway\n// configured right beside it. The pre-existing options.env / process.env\n// handling is unchanged; settings simply do not contribute these keys.\nconst UPSTREAM_SETTINGS_EXCLUDED_ENV_KEYS = PROXY_ENV_KEYS;\n\n// Track all active proxy instances for cleanup\nconst activeProxyServers = new Set<any>(); // Set<ProxyServer>\nlet globalShutdownRegistered = false;\n\n/**\n * Check whether an env value enables a feature.\n *\n * Claude Code accepts `1`, `true`, `yes`, and `on` (case-insensitive) — verified\n * against the bundled CLI. Accepting only `\"1\"` would miss a provider the CLI\n * considers enabled, so we would blank its routing keys without pinning a base\n * URL and break the run.\n */\nconst isTruthyEnv = (value: unknown): boolean => {\n  // Settings JSON can carry booleans / numbers; never crash proxy setup on a\n  // value that was not normalized to a string upstream.\n  if (typeof value !== \"string\") {\n    return value === true;\n  }\n  return [\"1\", \"true\", \"yes\", \"on\"].includes(value.trim().toLowerCase());\n};\n\n/**\n * Whether a provider flag is enabled in the given env, using the CLI's own\n * truthiness rules.\n *\n * Exported so the subprocess-env pin path shares ONE definition of \"enabled\"\n * with `getEnvVarsToRemove` / `buildProxyFlagSettings`. If they disagree, the\n * resource gets stripped without a base URL being pinned and the CLI hard-fails.\n */\nexport const isProviderEnabledInEnv = (\n  env: Record<string, string | undefined>,\n  useKey: string,\n): boolean => isTruthyEnv(env[useKey]);\n\n/**\n * Load a Claude settings JSON file, or `null` when it could not be read.\n *\n * `null` (unreadable / malformed / not a JSON object) is deliberately distinct\n * from `{}` (a valid but empty settings file): callers that would otherwise\n * REPLACE a user's settings need to know they failed to read it.\n */\nconst loadSettingsFile = (filePath: string): Record<string, unknown> | null => {\n  try {\n    const parsed: unknown = JSON.parse(fs.readFileSync(filePath, \"utf-8\"));\n    if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n      return parsed as Record<string, unknown>;\n    }\n  } catch {\n    // Missing or malformed settings are simply absent.\n  }\n  return null;\n};\n\nconst settingsEnvBlock = (\n  settings: Record<string, unknown>,\n): Record<string, string> => {\n  const env = settings.env;\n  if (!env || typeof env !== \"object\" || Array.isArray(env)) {\n    return {};\n  }\n  const result: Record<string, string> = {};\n  for (const [key, value] of Object.entries(env as Record<string, unknown>)) {\n    if (\n      typeof value === \"string\" ||\n      typeof value === \"number\" ||\n      typeof value === \"boolean\"\n    ) {\n      result[key] = String(value);\n    }\n  }\n  return result;\n};\n\n/**\n * Read the merged `env` block from Claude Code's on-disk settings layers.\n *\n * Claude Code applies these to the CLI session with HIGHER priority than the\n * subprocess environment, so a user with `ANTHROPIC_BASE_URL` in\n * `~/.claude/settings.json` silently bypasses our proxy. We read them to resolve\n * the real upstream and to detect conflicts.\n *\n * Precedence (highest first): local project, shared project, user.\n *\n * `settingSources` mirrors `options.settingSources` and gates which layers are\n * read: `undefined` means the CLI loads all of them, an array means only those,\n * and `[]` disables on-disk settings entirely. Honoring it matters because\n * reading a layer the CLI was told to ignore would resolve an upstream the CLI\n * never uses, pointing the proxy at an unintended host.\n */\nexport const readClaudeSettingsEnv = (\n  cwd?: string,\n  settingSources?: string[],\n): Record<string, string> => {\n  const sessionCwd = cwd ?? process.cwd();\n  const userDir =\n    process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), \".claude\");\n\n  // Lowest priority first so higher layers overwrite.\n  const layers: [string, string][] = [\n    [\"user\", path.join(userDir, \"settings.json\")],\n    [\"project\", path.join(sessionCwd, \".claude\", \"settings.json\")],\n    [\"local\", path.join(sessionCwd, \".claude\", \"settings.local.json\")],\n  ];\n\n  const merged: Record<string, string> = {};\n  for (const [source, filePath] of layers) {\n    if (settingSources !== undefined && !settingSources.includes(source)) {\n      continue;\n    }\n    // An unreadable layer just means we cannot see it; carry on.\n    Object.assign(merged, settingsEnvBlock(loadSettingsFile(filePath) ?? {}));\n  }\n  return merged;\n};\n\n/**\n * Read the `env` block out of the caller's `options.settings` (the flag layer).\n *\n * This layer OUTRANKS every on-disk layer, so a gateway or provider config that\n * lives only here is what the CLI would actually use — and\n * `buildProxyFlagSettings` is about to overwrite those keys with the proxy URL.\n * Upstream resolution must therefore see it FIRST, or we forward to the wrong\n * host (or to the default endpoint) while the caller's gateway is silently lost.\n *\n * Returns `{}` for a value we could not read; the caller's own bail-out logic in\n * `buildProxyFlagSettings` handles that case.\n */\nexport const flagSettingsEnv = (\n  existing: string | Record<string, unknown> | undefined,\n  cwd?: string,\n): Record<string, string> => {\n  if (typeof existing === \"object\" && existing !== null) {\n    return settingsEnvBlock(existing);\n  }\n  if (typeof existing !== \"string\" || !existing.trim()) {\n    return {};\n  }\n  const trimmed = existing.trim();\n  if (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n    try {\n      const parsed: unknown = JSON.parse(trimmed);\n      if (parsed && typeof parsed === \"object\" && !Array.isArray(parsed)) {\n        return settingsEnvBlock(parsed as Record<string, unknown>);\n      }\n    } catch {\n      // Unparseable inline JSON contributes nothing.\n    }\n    return {};\n  }\n  const resolved = path.isAbsolute(trimmed)\n    ? trimmed\n    : path.join(cwd ?? process.cwd(), trimmed);\n  return settingsEnvBlock(loadSettingsFile(resolved) ?? {});\n};\n\n/**\n * Build the `--settings` value that forces the CLI through our proxy.\n *\n * Claude Code resolves `env` from its settings layers with higher priority than\n * the subprocess environment, so rewriting `options.env` alone leaves a user with\n * `ANTHROPIC_BASE_URL` in `~/.claude/settings.json` talking straight to their\n * upstream while the proxy sees zero traffic (lmnr#2167). `--settings` is the\n * highest user-controlled layer, so writing the proxy URL there wins without ever\n * touching the user's files on disk.\n *\n * Layers merge per key, so keys we simply omit keep their lower-layer value.\n * Redirecting keys are therefore blanked rather than dropped.\n *\n * Returns the value to assign to `options.settings`, or `null` when the caller's\n * existing value is a file path we could not read (in that case the path must be\n * left alone so the CLI can still resolve it itself).\n */\nexport const buildProxyFlagSettings = (\n  existing: string | Record<string, unknown> | undefined,\n  proxyUrl: string,\n  cwd?: string,\n  settingSources?: string[],\n): Record<string, unknown> | null => {\n  let settingsObj: Record<string, unknown> = {};\n\n  if (typeof existing === \"object\" && existing !== null) {\n    settingsObj = { ...existing };\n  } else if (typeof existing === \"string\" && existing.trim()) {\n    const trimmed = existing.trim();\n    if (trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\")) {\n      let parsed: unknown;\n      try {\n        parsed = JSON.parse(trimmed);\n      } catch {\n        return null;\n      }\n      if (!parsed || typeof parsed !== \"object\" || Array.isArray(parsed)) {\n        return null;\n      }\n      settingsObj = parsed as Record<string, unknown>;\n    } else {\n      const resolved = path.isAbsolute(trimmed)\n        ? trimmed\n        : path.join(cwd ?? process.cwd(), trimmed);\n      // Bail on any value we could not fully read, not just a missing file:\n      // emitting a proxy-only blob would drop every setting the user actually\n      // configured for this run.\n      const loaded = loadSettingsFile(resolved);\n      if (loaded === null) {\n        return null;\n      }\n      settingsObj = loaded;\n    }\n  }\n\n  const envDict: Record<string, string> = { ...settingsEnvBlock(settingsObj) };\n  const settingsEnv = readClaudeSettingsEnv(cwd, settingSources);\n  const inPlay = (key: string): boolean =>\n    key in envDict || key in settingsEnv || process.env[key] !== undefined;\n\n  envDict.ANTHROPIC_BASE_URL = proxyUrl;\n  for (const [baseUrlKey, useKey] of PROVIDER_BASE_URL_ENV_KEYS) {\n    // Pin a provider base URL when the provider is enabled OR its base URL is\n    // already set — never introduce one the user has nothing to do with. Keying\n    // only off the base-URL key would miss a provider configured by another\n    // route (e.g. Foundry via ANTHROPIC_FOUNDRY_RESOURCE), leaving it with its\n    // routing key blanked below and no proxy URL to fall back on.\n    const enabled =\n      isTruthyEnv(envDict[useKey]) ||\n      isTruthyEnv(settingsEnv[useKey]) ||\n      isTruthyEnv(process.env[useKey]);\n    if (enabled || inPlay(baseUrlKey)) {\n      envDict[baseUrlKey] = proxyUrl;\n    }\n    // The Foundry resource is mutually exclusive with the base URL we just\n    // pinned — the CLI hard-fails (\"baseURL and resource are mutually\n    // exclusive\") if both are live. Blank it whenever Foundry is in play, even\n    // when the resource only exists in the process env, since the flag layer is\n    // the only place we can override it for the subprocess.\n    if (\n      baseUrlKey === FOUNDRY_BASE_URL_ENV &&\n      envDict[baseUrlKey] === proxyUrl\n    ) {\n      envDict[FOUNDRY_RESOURCE_ENV] = \"\";\n    }\n  }\n  for (const key of PROXY_NEUTRALIZED_ENV_KEYS) {\n    if (\n      key in settingsEnv ||\n      key in envDict ||\n      process.env[key] !== undefined\n    ) {\n      envDict[key] = \"\";\n    }\n  }\n\n  return { ...settingsObj, env: envDict };\n};\n\n/**\n * Read region for a given profile from ~/.aws/config.\n */\nconst getRegionFromAwsConfig = (profile: string): string | null => {\n  const configPath = path.join(os.homedir(), \".aws\", \"config\");\n  let content: string;\n  try {\n    content = fs.readFileSync(configPath, \"utf-8\");\n  } catch {\n    return null;\n  }\n\n  const profileHeader =\n    profile === \"default\" ? \"default\" : `profile ${profile}`;\n  const escapedHeader = profileHeader.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n  const regex = new RegExp(\n    `\\\\[${escapedHeader}\\\\][^\\\\[]*?^\\\\s*region\\\\s*=\\\\s*([^\\\\s\\\\n]+)`,\n    \"ms\",\n  );\n  const match = content.match(regex);\n  return match ? match[1] : null;\n};\n\n/**\n * Resolve target URL from environment dictionary with process.env fallback.\n *\n * This is the single source of truth for determining the target URL for the proxy.\n *\n * Resolution order (highest to lowest priority):\n * 1. HTTPS_PROXY - if set, use as target (our proxy will forward to it)\n * 2. HTTP_PROXY - if set, use as target (our proxy will forward to it)\n * 3. Third-party provider URLs (e.g., Foundry, Bedrock):\n *    - If CLAUDE_CODE_USE_FOUNDRY is truthy:\n *      - Use ANTHROPIC_FOUNDRY_BASE_URL, or\n *      - Construct from ANTHROPIC_FOUNDRY_RESOURCE\n *    - If CLAUDE_CODE_USE_BEDROCK is truthy:\n *      - Use ANTHROPIC_BEDROCK_BASE_URL, or\n *      - Construct from AWS_REGION env var, or\n *      - Construct by reading region from ~/.aws/config via AWS_PROFILE\n *    - If CLAUDE_CODE_USE_VERTEX is truthy:\n *      - Use ANTHROPIC_VERTEX_BASE_URL, or\n *      - Construct from CLOUD_ML_REGION and ANTHROPIC_VERTEX_PROJECT_ID\n * 4. ANTHROPIC_BASE_URL - standard Anthropic API base URL\n * 5. Fall back to default (https://api.anthropic.com)\n *\n * For each environment variable, checks envDict first, then process.env, then\n * Claude Code's on-disk settings `env` block. The settings layer is checked last\n * as a source for the *upstream* URL, but note it wins over process env inside\n * the CLI itself — see `buildProxyFlagSettings`.\n *\n * @param envDict - Dictionary of environment variables (e.g., from options.env)\n * @param fallback - Fallback URL if no other source found (default: DEFAULT_ANTHROPIC_BASE_URL)\n * @param cwd - Session root used to locate project settings (`options.cwd`)\n * @returns Resolved target URL, or null if provider is misconfigured\n */\nexport const resolveTargetUrlFromEnv = (\n  envDict: Record<string, string | undefined>,\n  fallback: string = DEFAULT_ANTHROPIC_BASE_URL,\n  cwd?: string,\n  settingSources?: string[],\n  settings?: string | Record<string, unknown>,\n): string | null => {\n  // The caller's flag layer outranks the on-disk layers inside the CLI, and we\n  // are about to overwrite its base URLs with the proxy — so read it here or a\n  // gateway configured only there is lost and we forward to the wrong host.\n  const flagEnv = flagSettingsEnv(settings, cwd);\n  const settingsEnv = readClaudeSettingsEnv(cwd, settingSources);\n\n  // Helper: options.env, then process.env, then flag settings, then on-disk\n  // Claude settings env.\n  // HTTP_PROXY / HTTPS_PROXY are deliberately NOT taken from settings — they are\n  // forward proxies rather than API bases and outrank every base URL below, so a\n  // settings-defined corporate proxy would shadow the gateway next to it.\n  const getEnvValue = (key: string): string | undefined => {\n    const value = envDict[key] || process.env[key];\n    if (value || UPSTREAM_SETTINGS_EXCLUDED_ENV_KEYS.includes(key)) {\n      return value;\n    }\n    return flagEnv[key] || settingsEnv[key];\n  };\n\n  // 1. Check for HTTPS_PROXY (highest priority)\n  const httpsProxy = getEnvValue(\"HTTPS_PROXY\") || getEnvValue(\"https_proxy\");\n  if (httpsProxy) {\n    return httpsProxy.replace(/\\/$/, \"\");\n  }\n\n  // 2. Check for HTTP_PROXY\n  const httpProxy = getEnvValue(\"HTTP_PROXY\") || getEnvValue(\"http_proxy\");\n  if (httpProxy) {\n    return httpProxy.replace(/\\/$/, \"\");\n  }\n\n  // 3. Check for third-party providers (Foundry)\n  const foundryEnabled = isTruthyEnv(getEnvValue(FOUNDRY_USE_ENV));\n  if (foundryEnabled) {\n    // Try to get Foundry base URL first\n    const foundryBaseUrl = getEnvValue(FOUNDRY_BASE_URL_ENV);\n    if (foundryBaseUrl) {\n      return foundryBaseUrl.replace(/\\/$/, \"\");\n    }\n\n    // Try to construct from resource\n    const foundryResource = getEnvValue(FOUNDRY_RESOURCE_ENV);\n    if (foundryResource) {\n      return `https://${foundryResource}.services.ai.azure.com/anthropic`;\n    }\n\n    // Foundry is enabled but misconfigured\n    logger.error(\n      `${FOUNDRY_USE_ENV} is set but neither ${FOUNDRY_BASE_URL_ENV} ` +\n        `nor ${FOUNDRY_RESOURCE_ENV} is configured. ` +\n        `Microsoft Foundry requires one of these values.`,\n    );\n    return null;\n  }\n\n  // 3b. Check for Bedrock\n  const bedrockEnabled = isTruthyEnv(getEnvValue(BEDROCK_USE_ENV));\n  if (bedrockEnabled) {\n    const bedrockBaseUrl = getEnvValue(BEDROCK_BASE_URL_ENV);\n    if (bedrockBaseUrl) {\n      return bedrockBaseUrl.replace(/\\/$/, \"\");\n    }\n\n    let region = getEnvValue(BEDROCK_AWS_REGION_ENV);\n    if (!region) {\n      const awsProfile = getEnvValue(\"AWS_PROFILE\") || \"default\";\n      region = getRegionFromAwsConfig(awsProfile) ?? undefined;\n    }\n\n    if (region) {\n      return `https://bedrock-runtime.${region}.amazonaws.com`;\n    }\n\n    logger.error(\n      `${BEDROCK_USE_ENV} is set but could not determine AWS region. ` +\n        `Set ${BEDROCK_AWS_REGION_ENV} or configure a region ` +\n        \"in ~/.aws/config for the active profile.\",\n    );\n    return null;\n  }\n\n  // 3c. Check for Vertex AI\n  const vertexEnabled = isTruthyEnv(getEnvValue(VERTEX_USE_ENV));\n  if (vertexEnabled) {\n    // unlike for Foundry or Bedrock, we don't parse the project or region config, because\n    // they affect the URL path, not the base URL, so CC can handle this part internally\n    const vertexBaseUrl = getEnvValue(VERTEX_BASE_URL_ENV);\n    if (vertexBaseUrl) {\n      return vertexBaseUrl.replace(/\\/$/, \"\");\n    }\n    return `https://aiplatform.googleapis.com/v1`;\n  }\n\n  // 4. Check for ANTHROPIC_BASE_URL\n  const anthropicBaseUrl = getEnvValue(\"ANTHROPIC_BASE_URL\");\n  if (anthropicBaseUrl) {\n    return anthropicBaseUrl.replace(/\\/$/, \"\");\n  }\n\n  // 5. Use fallback\n  return fallback;\n};\n\n/**\n * Get environment variables to remove from subprocess after resolving target URL.\n * These are variables that should not be passed to the subprocess because they\n * would interfere with our proxy setup.\n *\n * @param envDict - Dictionary of environment variables\n * @returns Array of environment variable keys to remove\n */\nexport const getEnvVarsToRemove = (\n  envDict: Record<string, string | undefined>,\n  cwd?: string,\n  settingSources?: string[],\n): string[] => {\n  const toRemove: string[] = [...PROXY_ENV_KEYS];\n\n  const settingsEnv = readClaudeSettingsEnv(cwd, settingSources);\n\n  // Helper: envDict, then process.env, then Claude settings env. Settings are\n  // included because Foundry is often enabled only there, and the resource is\n  // mutually exclusive with the base URL we set — leaving it in options.env\n  // makes the CLI hard-fail.\n  const getEnvValue = (key: string): string | undefined =>\n    envDict[key] || process.env[key] || settingsEnv[key];\n\n  // Remove FOUNDRY_RESOURCE if Foundry is enabled\n  // (it's mutually exclusive with ANTHROPIC_BASE_URL which we'll set)\n  const foundryEnabled = isTruthyEnv(getEnvValue(FOUNDRY_USE_ENV));\n  if (foundryEnabled) {\n    toRemove.push(FOUNDRY_RESOURCE_ENV);\n  }\n\n  return toRemove;\n};\n\n/**\n * Find an available port starting from the given port\n */\nconst findAvailablePort = (\n  startPort: number,\n  attempts: number,\n): Promise<number | null> =>\n  new Promise((resolve) => {\n    let currentAttempt = 0;\n\n    const tryPort = (port: number) => {\n      const server = net.createServer();\n\n      server.once(\"error\", () => {\n        server.close();\n        currentAttempt++;\n        if (currentAttempt < attempts) {\n          tryPort(startPort + currentAttempt);\n        } else {\n          resolve(null);\n        }\n      });\n\n      server.once(\"listening\", () => {\n        server.close(() => {\n          resolve(port);\n        });\n      });\n\n      server.listen(port, \"127.0.0.1\");\n    };\n\n    tryPort(startPort);\n  });\n\n/**\n * Wait for a port to be available\n */\nconst waitForPort = (\n  port: number,\n  timeoutMs: number = 5000,\n): Promise<boolean> =>\n  new Promise((resolve) => {\n    const deadline = Date.now() + timeoutMs;\n\n    const checkPort = () => {\n      if (Date.now() >= deadline) {\n        resolve(false);\n        return;\n      }\n\n      const socket = new net.Socket();\n\n      socket.setTimeout(200);\n\n      socket.once(\"connect\", () => {\n        socket.destroy();\n        resolve(true);\n      });\n\n      socket.once(\"timeout\", () => {\n        socket.destroy();\n        setTimeout(checkPort, 100);\n      });\n\n      socket.once(\"error\", () => {\n        socket.destroy();\n        setTimeout(checkPort, 100);\n      });\n\n      socket.connect(port, \"127.0.0.1\");\n    };\n\n    checkPort();\n  });\n\n/**\n * Register global cleanup on process exit for all active proxies\n */\nconst registerGlobalProxyShutdown = () => {\n  if (!globalShutdownRegistered) {\n    process.on(\"exit\", () => {\n      logger.debug('process.on(\"exit\") called - stopping all active proxies');\n      for (const proxyServer of activeProxyServers) {\n        try {\n          proxyServer.stopServer();\n        } catch (e) {\n          logger.debug(`Failed to stop proxy: ${errorMessage(e)}`);\n        }\n      }\n      activeProxyServers.clear();\n    });\n    globalShutdownRegistered = true;\n  }\n};\n\n/**\n * Interface for a proxy instance with its metadata\n */\nexport interface ProxyInstance {\n  server: any; // ProxyServer\n  baseUrl: string;\n  port: number;\n  targetUrl: string;\n}\n\n/**\n * Create and start a new claude-code proxy server instance\n * Each call creates an independent proxy on a unique port\n */\nexport const createProxyInstance = async ({\n  env,\n  cwd,\n  settingSources,\n  settings,\n  targetUrl: resolvedTargetUrl,\n}: {\n  env: Record<string, string | undefined>;\n  cwd?: string;\n  settingSources?: string[];\n  settings?: string | Record<string, unknown>;\n  targetUrl?: string | null;\n}): Promise<ProxyInstance | null> => {\n  try {\n    const port = await findAvailablePort(\n      DEFAULT_CC_PROXY_PORT,\n      CC_PROXY_PORT_ATTEMPTS,\n    );\n    if (port === null) {\n      logger.warn(\"Unable to allocate port for cc-proxy.\");\n      return null;\n    }\n\n    // Prefer the caller's already-resolved upstream. Re-resolving here without\n    // the session cwd would miss a gateway configured only in project or local\n    // settings, and the proxy would forward to the default Anthropic API while\n    // ANTHROPIC_ORIGINAL_BASE_URL pointed at the gateway.\n    const targetUrl =\n      resolvedTargetUrl ??\n      resolveTargetUrlFromEnv(env, undefined, cwd, settingSources, settings);\n    if (!targetUrl) {\n      logger.warn(\n        \"Unable to resolve target URL for cc-proxy (provider misconfigured).\",\n      );\n      return null;\n    }\n\n    logger.debug(\n      `Creating proxy instance on port ${port} targeting: ${targetUrl}`,\n    );\n\n    try {\n      // Dynamically import ProxyServer class\n      // biome-ignore lint/style/noCommonJs: dynamic import needed, so a faulty import doesn't fail the application code\n      const { ProxyServer } = require(\"@lmnr-ai/claude-code-proxy\");\n\n      const proxyServer = new ProxyServer(port);\n      proxyServer.runServer(targetUrl);\n\n      const isReady = await waitForPort(port);\n      if (!isReady) {\n        logger.warn(`cc-proxy failed to start on port ${port}`);\n        proxyServer.stopServer();\n        return null;\n      }\n\n      const proxyBaseUrl = `http://127.0.0.1:${port}`;\n\n      // Track this proxy for cleanup\n      activeProxyServers.add(proxyServer);\n      registerGlobalProxyShutdown();\n\n      logger.info(`Started claude proxy server on: ${proxyBaseUrl}`);\n\n      return {\n        server: proxyServer,\n        baseUrl: proxyBaseUrl,\n        port,\n        targetUrl,\n      };\n    } catch (e) {\n      logger.warn(`Unable to start cc-proxy: ${errorMessage(e)}`);\n      return null;\n    }\n  } catch (e) {\n    logger.warn(`Failed to create proxy instance: ${errorMessage(e)}`);\n    return null;\n  }\n};\n\n/**\n * Stop a specific proxy instance\n */\nexport const stopProxyInstance = (instance: ProxyInstance | null): void => {\n  if (!instance) {\n    return;\n  }\n\n  try {\n    logger.debug(`Stopping proxy instance on port ${instance.port}`);\n    instance.server.stopServer();\n    activeProxyServers.delete(instance.server);\n  } catch (e) {\n    logger.debug(`Failed to stop proxy instance: ${errorMessage(e)}`);\n  }\n};\n\n/**\n * Force stop all active proxy servers\n * Used during shutdown to ensure cleanup\n */\nexport const forceReleaseProxy = (): void => {\n  logger.debug(\n    `Force stopping all ${activeProxyServers.size} active proxy servers`,\n  );\n  for (const proxyServer of activeProxyServers) {\n    try {\n      proxyServer.stopServer();\n    } catch (e) {\n      logger.debug(`Failed to stop proxy: ${errorMessage(e)}`);\n    }\n  }\n  activeProxyServers.clear();\n};\n\n/**\n * Get the current span context payload for proxy\n */\nconst getSpanContextPayload = (): {\n  trace_id: string;\n  span_id: string;\n  project_api_key: string;\n  span_ids_path: string[];\n  span_path: string[];\n  laminar_url: string;\n} | null => {\n  const currentSpan = trace.getSpan(LaminarContextManager.getContext());\n  if (\n    !currentSpan ||\n    (!currentSpan.spanContext().isRemote && !currentSpan.isRecording())\n  ) {\n    return null;\n  }\n\n  const spanContext = currentSpan.spanContext();\n  if (!spanContext || !spanContext.traceId) {\n    return null;\n  }\n\n  let spanIdsPath: string[] = [];\n  let spanPath: string[] = [];\n\n  // Try to extract span path attributes from readable span\n  try {\n    const readableSpan = currentSpan as unknown as ReadableSpan;\n    if (readableSpan.attributes) {\n      const idsPath = readableSpan.attributes[SPAN_IDS_PATH];\n      const path = readableSpan.attributes[SPAN_PATH];\n\n      if (Array.isArray(idsPath)) {\n        spanIdsPath = idsPath as string[];\n      }\n      if (Array.isArray(path)) {\n        spanPath = path as string[];\n      }\n    }\n  } catch {\n    // If we can't access attributes, continue with empty arrays\n  }\n\n  const projectApiKey = Laminar.getProjectApiKey();\n  const laminarUrl = Laminar.getHttpUrl();\n\n  return {\n    trace_id: spanContext.traceId,\n    span_id: spanContext.spanId,\n    project_api_key: projectApiKey || \"\",\n    span_ids_path: spanIdsPath,\n    span_path: spanPath,\n    laminar_url: laminarUrl || \"https://api.lmnr.ai\",\n  };\n};\n\n/**\n * Set the trace context for a specific proxy instance\n */\nexport const setTraceToProxyInstance = async (\n  instance: ProxyInstance | null,\n): Promise<void> => {\n  if (!instance) {\n    return;\n  }\n\n  const payload = getSpanContextPayload();\n  if (!payload) {\n    return;\n  }\n\n  try {\n    await instance.server.setCurrentTrace({\n      traceId: payload.trace_id,\n      spanId: payload.span_id,\n      projectApiKey: payload.project_api_key,\n      spanIdsPath: payload.span_ids_path,\n      spanPath: payload.span_path,\n      laminarUrl: payload.laminar_url,\n    });\n    logger.debug(`Set trace context to proxy on port ${instance.port}`);\n  } catch (e: any) {\n    logger.debug(\n      `Unable to set trace context to proxy on port ${instance.port}: ` +\n        errorMessage(e),\n    );\n  }\n};\n","// biome-ignore-all lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\nimport { diag } from \"@opentelemetry/api\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\n\nimport { version as SDK_VERSION } from \"../../../../package.json\";\nimport { Laminar } from \"../../../laminar\";\nimport { initializeLogger } from \"../../../utils\";\nimport { SPAN_INPUT, SPAN_OUTPUT } from \"../../tracing/attributes\";\nimport {\n  buildProxyFlagSettings,\n  createProxyInstance,\n  forceReleaseProxy,\n  getEnvVarsToRemove,\n  isProviderEnabledInEnv,\n  PROXY_BASE_URL_ENV_KEYS,\n  type ProxyInstance,\n  readClaudeSettingsEnv,\n  resolveTargetUrlFromEnv,\n  setTraceToProxyInstance,\n  stopProxyInstance,\n} from \"./proxy\";\n\n// Re-export forceReleaseProxy for cleanup in Laminar.shutdown()\nexport { forceReleaseProxy };\n\nconst logger = initializeLogger();\n\n/**\n * Create an instrumented version of the claude-agent-sdk query function.\n * This can be used when importing the query function before Laminar initialization.\n *\n * @param originalQuery - The original query function from claude-agent-sdk\n * @returns The instrumented query function\n */\nexport function instrumentClaudeAgentQuery(\n  originalQuery: any, // typeof ClaudeAgentSDK.query\n): any {\n  // typeof ClaudeAgentSDK.Query\n  return (params: {\n    prompt: string | AsyncIterable<any>; // AsyncIterable<ClaudeAgentSDK.SDKUserMessage>\n    options?: any; // ClaudeAgentSDK.Options\n  }) => {\n    const laminarActive =\n      Laminar.initialized() || !!process.env.LMNR_PROJECT_API_KEY;\n\n    if (!laminarActive) {\n      return originalQuery(params);\n    }\n\n    const span = Laminar.startSpan({\n      name: \"query\",\n      spanType: \"DEFAULT\",\n    });\n\n    span.setAttribute(\n      SPAN_INPUT,\n      JSON.stringify({\n        prompt: typeof params.prompt === \"string\" ? params.prompt : \"<stream>\",\n      }),\n    );\n\n    const generator = async function* () {\n      const collected: any[] = []; // ClaudeAgentSDK.SDKMessage[]\n      let proxyInstance: ProxyInstance | null = null;\n\n      try {\n        // Merge environment variables: process.env + params.options.env\n        // params.options.env takes precedence\n        const mergedEnv = {\n          ...process.env,\n          ...(params.options?.env ?? {}),\n        };\n\n        // Resolve target URL before creating proxy\n        const sessionCwd: string | undefined =\n          typeof params.options?.cwd === \"string\"\n            ? params.options.cwd\n            : undefined;\n        // options.settingSources gates which on-disk settings layers the CLI\n        // loads; reading a layer it was told to ignore would resolve an upstream\n        // the CLI never uses.\n        const settingSources: string[] | undefined = Array.isArray(\n          params.options?.settingSources,\n        )\n          ? (params.options.settingSources as string[])\n          : undefined;\n        // The caller's own options.settings is the highest layer the CLI reads,\n        // and buildProxyFlagSettings below overwrites its base URLs with the\n        // proxy — so resolve the upstream from it before that happens.\n        const callerSettings = params.options?.settings as\n          | string\n          | Record<string, unknown>\n          | undefined;\n        const targetUrl = resolveTargetUrlFromEnv(\n          mergedEnv,\n          undefined,\n          sessionCwd,\n          settingSources,\n          callerSettings,\n        );\n\n        // Create a dedicated proxy instance for this request\n        proxyInstance = await createProxyInstance({\n          env: mergedEnv,\n          cwd: sessionCwd,\n          settingSources,\n          settings: callerSettings,\n          targetUrl,\n        });\n\n        // Configure the request to use the proxy\n        if (proxyInstance && targetUrl) {\n          logger.debug(`Using proxy on port ${proxyInstance.port}`);\n\n          // Set trace context for this specific proxy instance\n          await Laminar.withSpan(span, async () => {\n            logger.debug(\"Setting trace to proxy instance...\");\n            await setTraceToProxyInstance(proxyInstance);\n          });\n\n          // Get environment variables that should be removed\n          const varsToRemove = getEnvVarsToRemove(\n            mergedEnv,\n            sessionCwd,\n            settingSources,\n          );\n\n          // Update environment for subprocess\n          if (!params.options) {\n            params.options = {};\n          }\n          if (!params.options.env) {\n            params.options.env = {};\n          }\n\n          // Start with merged env and update for proxy\n          params.options.env = { ...mergedEnv };\n\n          // Set proxy URL\n          params.options.env.ANTHROPIC_BASE_URL = proxyInstance.baseUrl;\n\n          // Store original target URL so proxy knows where to forward\n          params.options.env.ANTHROPIC_ORIGINAL_BASE_URL = targetUrl;\n\n          // Remove proxy-related variables that would interfere\n          for (const varName of varsToRemove) {\n            delete params.options.env[varName];\n          }\n\n          // Pin each enabled provider's base URL. Truthiness MUST go through\n          // isTruthyEnv (1/true/yes/on) rather than a `=== \"1\"` check: the\n          // resource-stripping in getEnvVarsToRemove already uses isTruthyEnv, so\n          // a narrower check here strips ANTHROPIC_FOUNDRY_RESOURCE without\n          // leaving a base URL behind and the CLI hard-fails.\n          const subprocessEnv = params.options.env as Record<\n            string,\n            string | undefined\n          >;\n          if (\n            isProviderEnabledInEnv(subprocessEnv, \"CLAUDE_CODE_USE_FOUNDRY\")\n          ) {\n            subprocessEnv.ANTHROPIC_FOUNDRY_BASE_URL = proxyInstance.baseUrl;\n          }\n          if (\n            isProviderEnabledInEnv(subprocessEnv, \"CLAUDE_CODE_USE_BEDROCK\")\n          ) {\n            subprocessEnv.ANTHROPIC_BEDROCK_BASE_URL = proxyInstance.baseUrl;\n          }\n          if (isProviderEnabledInEnv(subprocessEnv, \"CLAUDE_CODE_USE_VERTEX\")) {\n            subprocessEnv.ANTHROPIC_VERTEX_BASE_URL = proxyInstance.baseUrl;\n          }\n\n          // Claude Code's settings `env` outranks the subprocess environment, so\n          // options.env alone does not redirect a user whose base URL lives in\n          // ~/.claude/settings.json (lmnr#2167). `settings` is the highest\n          // user-controlled layer; their files on disk are never modified.\n          const flagSettings = buildProxyFlagSettings(\n            callerSettings,\n            proxyInstance.baseUrl,\n            sessionCwd,\n            settingSources,\n          );\n          if (flagSettings === null) {\n            logger.warn(\n              `Could not read options.settings ${JSON.stringify(callerSettings)}; ` +\n                \"Claude Code settings that define a base URL will bypass the \" +\n                \"Laminar proxy and produce no LLM spans.\",\n            );\n          } else {\n            params.options.settings = flagSettings;\n\n            const conflicting = Object.entries(\n              readClaudeSettingsEnv(sessionCwd, settingSources),\n            )\n              .filter(\n                ([key, value]) =>\n                  PROXY_BASE_URL_ENV_KEYS.includes(key) &&\n                  value !== \"\" &&\n                  value !== proxyInstance?.baseUrl,\n              )\n              .map(([key]) => key);\n            if (conflicting.length > 0) {\n              logger.info(\n                `Claude Code settings define ${conflicting.sort().join(\", \")}, which ` +\n                  \"outranks the subprocess environment. Injected settings so the \" +\n                  `Laminar proxy at ${proxyInstance.baseUrl} still intercepts API ` +\n                  \"traffic; your settings files were not modified.\",\n              );\n            }\n          }\n        } else {\n          logger.debug(\n            \"No claude proxy server available. Proceeding without proxy.\",\n          );\n        }\n\n        // Call original and wrap the generator\n        const originalGenerator = originalQuery(params);\n\n        // Yield items and collect\n        for await (const message of originalGenerator) {\n          collected.push(message);\n          yield message;\n        }\n      } catch (error) {\n        Laminar.withSpan(span, () => {\n          span.recordException(error as Error);\n        });\n        throw error;\n      } finally {\n        // Stop this proxy instance\n        stopProxyInstance(proxyInstance);\n        span.setAttribute(SPAN_OUTPUT, JSON.stringify(collected));\n        span.end();\n      }\n    };\n\n    return generator() as any; // ClaudeAgentSDK.Query\n  };\n}\n\nexport class ClaudeAgentSDKInstrumentation extends InstrumentationBase {\n  constructor() {\n    super(\"@lmnr/claude-agent-instrumentation\", SDK_VERSION, {\n      enabled: true,\n    });\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    const module = new InstrumentationNodeModuleDefinition(\n      \"@anthropic-ai/claude-agent-sdk\",\n      [\">=0.1.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n\n    return module;\n  }\n\n  // { query?: typeof ClaudeAgentSDK.query }\n  public manuallyInstrument(claudeAgentModule: { query?: any }) {\n    // Only instrument the query function if provided\n    if (\n      claudeAgentModule.query &&\n      typeof claudeAgentModule.query === \"function\"\n    ) {\n      this._wrap(claudeAgentModule, \"query\", this.patchQuery());\n    } else {\n      logger.debug(\n        \"query function not found in claudeAgentSDK module, skipping instrumentation\",\n      );\n    }\n  }\n\n  private patchQuery(): any {\n    // casts to ClaudeAgentSDK.query\n    return (original: Function) => instrumentClaudeAgentQuery(original as any);\n  }\n\n  private patch(moduleExports: any): any {\n    // typeof ClaudeAgentSDK\n    diag.debug(\"Patching @anthropic-ai/claude-agent-sdk\");\n\n    // Wrap the query function for automatic instrumentation\n    if (moduleExports.query && typeof moduleExports.query === \"function\") {\n      this._wrap(moduleExports, \"query\", this.patchQuery());\n    }\n\n    return moduleExports;\n  }\n\n  private unpatch(moduleExports: any): void {\n    // typeof ClaudeAgentSDK\n    diag.debug(\"Unpatching @anthropic-ai/claude-agent-sdk\");\n\n    // Unwrap the query function\n    this._unwrap(moduleExports, \"query\");\n  }\n}\n","import { spawn } from \"node:child_process\";\n\nimport { LaminarClient } from \"@lmnr-ai/client\";\nimport {\n  errorMessage,\n  type LaminarSpanContext,\n  type SessionRecordingOptions,\n  type SpanType,\n  type TraceType,\n  TracingLevel,\n} from \"@lmnr-ai/types\";\nimport {\n  AttributeValue,\n  Context,\n  context as contextApi,\n  isSpanContextValid,\n  type Span,\n  TimeInput,\n  trace,\n} from \"@opentelemetry/api\";\nimport { SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\n\nimport {\n  getRuntime,\n  initDebugRuntime,\n  initDebugRuntimeFromContext,\n  isTruthy,\n  resetDebugRuntime,\n} from \"./debug\";\nimport {\n  InitializeOptions,\n  initializeTracing,\n  LaminarSpanProcessor,\n} from \"./opentelemetry-lib\";\nimport { _resetConfiguration } from \"./opentelemetry-lib/configuration\";\nimport {\n  forceReleaseProxy as forceReleaseClaudeProxy,\n  instrumentClaudeAgentQuery,\n} from \"./opentelemetry-lib/instrumentation/claude-agent-sdk\";\nimport {\n  forceFlush,\n  getSpanProcessor,\n  getTracer,\n  patchModules,\n} from \"./opentelemetry-lib/tracing\";\nimport {\n  ASSOCIATION_PROPERTIES,\n  LaminarAttributes,\n  PARENT_SPAN_IDS_PATH,\n  PARENT_SPAN_PATH,\n  SESSION_ID,\n  SPAN_TYPE,\n  TRACE_TYPE,\n  USER_ID,\n} from \"./opentelemetry-lib/tracing/attributes\";\nimport { LaminarContextManager } from \"./opentelemetry-lib/tracing/context\";\nimport { LaminarSpan } from \"./opentelemetry-lib/tracing/span\";\nimport {\n  deserializeLaminarSpanContext,\n  getFrontendUrl,\n  initializeLogger,\n  loadEnv,\n  metadataToAttributes,\n  otelTraceIdToUUID,\n  type StringUUID,\n  tryToOtelSpanContext,\n  validateTracingConfig,\n} from \"./utils\";\n\nloadEnv();\n\nconst logger = initializeLogger();\n\nexport interface LaminarInitializeProps {\n  projectApiKey?: string;\n  baseUrl?: string;\n  baseHttpUrl?: string;\n  httpPort?: number;\n  grpcPort?: number;\n  instrumentModules?: InitializeOptions[\"instrumentModules\"];\n  disableBatch?: boolean;\n  traceExportTimeoutMillis?: number;\n  logLevel?: \"debug\" | \"info\" | \"warn\" | \"error\";\n  maxExportBatchSize?: number;\n  maxExportBatchSizeBytes?: number;\n  flushBySize?: boolean;\n  forceHttp?: boolean;\n  sessionRecordingOptions?: SessionRecordingOptions;\n  metadata?: Record<string, any>;\n  inheritGlobalContext?: boolean;\n  spanProcessor?: SpanProcessor;\n}\n\ntype LaminarAttributesProp = Record<\n  (typeof LaminarAttributes)[keyof typeof LaminarAttributes],\n  AttributeValue\n>;\n\nexport class Laminar {\n  private static baseHttpUrl: string;\n  private static projectApiKey: string;\n  private static isInitialized: boolean = false;\n  private static globalMetadata: Record<string, any> = {};\n  // The debug run's `exit` pointer hook, kept by reference so shutdown() can\n  // remove it. `process.once` only auto-detaches after `exit` fires, so without\n  // this an initialize()/shutdown() loop (common in tests) would accumulate\n  // stale listeners and trip Node's MaxListenersExceededWarning.\n  private static debugExitHook: (() => void) | null = null;\n  // Base url / http port captured at initialize(), reused to build the client\n  // when the debug runtime is armed late from a propagated context (the\n  // from-context path has no access to initialize()'s args).\n  private static baseUrlForDebug: string | undefined = undefined;\n  private static httpPortForDebug: number | undefined = undefined;\n  /**\n   * Process-wide latch for debug-replay v2: once any LLM call gets a cache MISS,\n   * every subsequent call runs live (skipping the cache lookup) for the rest of\n   * the process. A COLD/`live` outcome runs that single call live WITHOUT\n   * setting this flag. Read by the AI SDK wrapper's caching path; reset in\n   * {@link shutdown} so an init/shutdown loop (tests) starts clean.\n   */\n  public static debugRunLive: boolean = false;\n  /**\n   * Initialize Laminar context across the application.\n   * This method must be called before using any other Laminar methods or decorators.\n   *\n   * @param {LaminarInitializeProps} props - Configuration object.\n   * @param {string} props.projectApiKey - Laminar project api key. You can generate one by going\n   * to the projects settings page on the Laminar dashboard.\n   * If not specified, it will try to read from the LMNR_PROJECT_API_KEY environment variable.\n   * @param {string} props.baseUrl - Laminar API url. Do not include the port, use\n   * `httpPort` and `grpcPort` instead.\n   * If not specified, defaults to https://api.lmnr.ai.\n   * @param {string} props.baseHttpUrl - Laminar API http url. If not specified, defaults to\n   * baseUrl. Only use this if you want to proxy HTTP requests through a different host.\n   * @param {number} props.httpPort - Laminar API http port.\n   * If not specified, defaults to 443.\n   * @param {number} props.grpcPort - Laminar API grpc port.\n   * If not specified, defaults to 8443.\n   * @param {InitializeOptions[\"instrumentModules\"]} props.instrumentModules - Record\n   * of modules to instrument.\n   * If not specified, all auto-instrumentable modules will be instrumented, which include\n   * LLM calls (OpenAI, Anthropic, etc), Langchain, VectorDB calls (Pinecone, Qdrant, etc).\n   * Pass an empty object {} to disable any kind of automatic instrumentation.\n   * If you only want to auto-instrument specific modules, then pass them in the object.\n   * @param {boolean} props.disableBatch - Whether to disable batching of spans. Useful for debug\n   * environments. If true, spans will be sent immediately using {@link SimpleSpanProcessor}\n   * instead of {@link BatchSpanProcessor}.\n   * @param {number} props.traceExportTimeoutMillis - Timeout for trace export.\n   * Defaults to 30_000 (30 seconds),\n   * which is over the default OTLP exporter timeout of 10_000 (10 seconds).\n   * @param {string} props.logLevel - OTel log level. Defaults to \"error\".\n   * @param {number} props.maxExportBatchSize - Maximum number of spans to export in a single batch.\n   * Ignored when `disableBatch` is true.\n   * @param {boolean} props.flushBySize - Whether to also flush batches by approximate payload\n   * size, not just by span count and schedule delay. The batch is flushed when the next span\n   * would push it past `maxExportBatchSizeBytes`, so a few large spans are exported without\n   * waiting for `maxExportBatchSize` spans to accumulate. Useful when spans carry large prompts\n   * or completions and exports get rejected for being too big. Defaults to false.\n   * @param {number} props.maxExportBatchSizeBytes - Approximate maximum size, in bytes, of the\n   * spans buffered in one batch. Only used when `flushBySize` is true. Defaults to 32 MiB.\n   * @param {boolean} props.forceHttp - Whether to force HTTP export. Not recommended.\n   * @param {SessionRecordingOptions} props.sessionRecordingOptions - Options for browser\n   * session recording.\n   * Currently supports 'maskInputOptions' to control whether input fields are masked during\n   * recording. Defaults to undefined (uses default masking behavior).\n   * @param {Record<string, any>} props.metadata - Global metadata to associate with all spans.\n   * This metadata will be associated with all spans, and merged with any metadata passed to\n   * each span. Must be JSON serializable.\n   * @param {boolean} props.inheritGlobalContext - Whether to inherit the global OpenTelemetry\n   * context. Defaults to false. This is useful if your library is instrumented with OpenTelemetry\n   * and you want Laminar spans to be children of the existing spans.\n   * @param {SpanProcessor} props.spanProcessor - The span processor to use. If passed, some of\n   * the other options will be ignored.\n   *\n   * @example\n   * import { Laminar } from '@lmnr-ai/lmnr';\n   * import { OpenAI } from 'openai';\n   * import * as ChainsModule from \"langchain/chains\";\n   *\n   * // Initialize Laminar while auto-instrumenting Langchain and OpenAI modules.\n   * Laminar.initialize({\n   *   projectApiKey: \"<LMNR_PROJECT_API_KEY>\",\n   *   instrumentModules: {\n   *     langchain: {\n   *       chainsModule: ChainsModule\n   *     },\n   *     openAI: OpenAI\n   *   }\n   * });\n   *\n   * @throws {Error} - If project API key is not set\n   */\n  public static initialize({\n    projectApiKey,\n    baseUrl,\n    baseHttpUrl,\n    httpPort,\n    grpcPort,\n    instrumentModules,\n    disableBatch,\n    traceExportTimeoutMillis,\n    logLevel,\n    maxExportBatchSize,\n    maxExportBatchSizeBytes,\n    flushBySize,\n    forceHttp,\n    sessionRecordingOptions,\n    metadata,\n    inheritGlobalContext,\n    spanProcessor,\n  }: LaminarInitializeProps = {}) {\n    if (this.isInitialized) {\n      logger.warn(\n        \"Laminar has already been initialized. Skipping initialization.\",\n      );\n      return;\n    }\n    const key = projectApiKey ?? process?.env?.LMNR_PROJECT_API_KEY;\n\n    // Validate that either API key or OTEL configuration is present\n    validateTracingConfig(key);\n\n    this.projectApiKey = key ?? \"\";\n    let url = baseUrl ?? process?.env?.LMNR_BASE_URL;\n\n    // Only set default URL if we have an API key (traditional Laminar setup)\n    if (key && !url) {\n      url = \"https://api.lmnr.ai\";\n    }\n\n    const httpUrl = baseHttpUrl ?? url;\n    let port: number | undefined = httpPort;\n\n    if (httpUrl) {\n      if (!port) {\n        const m = httpUrl.match(/:\\d{1,5}$/g);\n        port = m ? parseInt(m[0].slice(1)) : 443;\n      }\n      const httpUrlWithoutSlash = httpUrl\n        .replace(/\\/$/, \"\")\n        .replace(/:\\d{1,5}$/g, \"\");\n      this.baseHttpUrl = `${httpUrlWithoutSlash}:${port}`;\n    } else {\n      this.baseHttpUrl = \"\";\n    }\n\n    const envMetadata = process.env.LMNR_TRACE_METADATA\n      ? (JSON.parse(process.env.LMNR_TRACE_METADATA) as Record<string, unknown>)\n      : {};\n    this.globalMetadata = { ...envMetadata, ...(metadata ?? {}) };\n    if (inheritGlobalContext) {\n      LaminarContextManager.inheritGlobalContext = true;\n    }\n    if (spanProcessor && !(spanProcessor instanceof LaminarSpanProcessor)) {\n      logger.warn(\n        \"Span processor is not a LaminarSpanProcessor. Some functionality may be impaired.\",\n      );\n    }\n    this.isInitialized = true;\n\n    const urlWithoutSlash = url?.replace(/\\/$/, \"\").replace(/:\\d{1,5}$/g, \"\");\n    const httpUrlWithoutSlash = httpUrl\n      ?.replace(/\\/$/, \"\")\n      .replace(/:\\d{1,5}$/g, \"\");\n\n    initializeTracing({\n      baseUrl: urlWithoutSlash,\n      baseHttpUrl: httpUrlWithoutSlash,\n      apiKey: key,\n      port: grpcPort,\n      forceHttp,\n      httpPort,\n      silenceInitializationMessage: true,\n      instrumentModules,\n      logLevel: logLevel ?? \"error\",\n      disableBatch,\n      maxExportBatchSize,\n      maxExportBatchSizeBytes,\n      flushBySize,\n      traceExportTimeoutMillis,\n      sessionRecordingOptions,\n      spanProcessor,\n    });\n\n    // Build the debug runtime only after tracing is up. It has no dependency on\n    // initializeTracing (which never reads the runtime or global metadata), so\n    // running it here means a tracing-init failure aborts before any debug side\n    // effects — backend session registration, the `rollout.session_id` stamp,\n    // the process-exit pointer hook — instead of leaving them live on a process\n    // whose tracing never came up. It must still precede setGlobalMetadata (so\n    // `rollout.session_id` is stamped on every span) and _initializeContextFromEnv\n    // (so the runtime is registered before the inherited trace id is recorded).\n    this._initDebugRuntime(url, port);\n    LaminarContextManager.setGlobalMetadata(this.globalMetadata);\n\n    this._initializeContextFromEnv();\n  }\n\n  /**\n   * Initialize Laminar context from the LMNR_SPAN_CONTEXT environment variable.\n   * This allows continuing traces across process boundaries.\n   * @private\n   */\n  private static _initializeContextFromEnv(): void {\n    const envContext = process?.env?.LMNR_SPAN_CONTEXT;\n    if (!envContext) {\n      return;\n    }\n\n    try {\n      const laminarContext = deserializeLaminarSpanContext(envContext);\n\n      // Arm the debug runtime from a propagated debug block (first-wins,\n      // idempotent — env config from _initDebugRuntime still takes precedence).\n      // Without this, a child continued purely via LMNR_SPAN_CONTEXT (no\n      // LMNR_DEBUG) never joins the upstream debug session or enables replay.\n      // Must run BEFORE recordTraceId below, which reads getRuntime().\n      this._armDebugRuntimeFromContext(laminarContext.debug);\n\n      // Convert to OpenTelemetry span context\n      const otelSpanContext = tryToOtelSpanContext(laminarContext);\n      // If we've parsed the context from the environment variable, it's remote\n      otelSpanContext.isRemote = true;\n\n      // Set parent path info in the span processor\n      const processor = getSpanProcessor();\n      if (\n        processor &&\n        processor instanceof LaminarSpanProcessor &&\n        laminarContext.spanPath &&\n        laminarContext.spanIdsPath\n      ) {\n        processor.setParentPathInfo(\n          otelSpanContext.spanId,\n          laminarContext.spanPath,\n          laminarContext.spanIdsPath,\n        );\n      }\n\n      // Create a non-recording span and push the context\n      const baseContext = trace.setSpan(\n        LaminarContextManager.getContext(),\n        trace.wrapSpanContext(otelSpanContext),\n      );\n      const ctx = LaminarContextManager.setRawAssociationProperties(\n        laminarContext,\n        baseContext,\n      );\n      LaminarContextManager.pushContext(ctx);\n\n      // On a debug run attached via LMNR_SPAN_CONTEXT, no span has a null parent\n      // (everything descends from the injected context), so the processor's\n      // root-span hook never fires. Record the inherited trace id here so the\n      // run pointer (§5) isn't emitted with an empty trace_id.\n      try {\n        getRuntime()?.recordTraceId(otelTraceIdToUUID(otelSpanContext.traceId));\n      } catch (e) {\n        logger.debug(\n          \"Failed to record debug trace id from env: \" + errorMessage(e),\n        );\n      }\n\n      logger.debug(\n        \"Initialized Laminar parent context from LMNR_SPAN_CONTEXT.\",\n      );\n    } catch (e) {\n      logger.warn(\n        \"LMNR_SPAN_CONTEXT is set but could not be used: \" + errorMessage(e),\n      );\n    }\n  }\n\n  /**\n   * Build the in-process debug runtime (§4, §5) when LMNR_DEBUG is set.\n   *\n   * On a debug run the session id from the config is stamped into the global\n   * trace metadata as `rollout.session_id`, and a process-exit hook emits the\n   * run pointer once the root trace id is known. When debug mode is off this is\n   * a no-op and the SDK behaves exactly as before.\n   * @private\n   */\n  private static _initDebugRuntime(\n    baseUrl: string | undefined,\n    httpPort: number | undefined,\n  ): void {\n    // Capture the connection args so a later context-armed runtime (built deep\n    // in span creation, with no access to initialize()'s args) can construct\n    // its own client. Set unconditionally — even when local debug is off, a\n    // downstream span may arrive carrying a debug block.\n    this.baseUrlForDebug = baseUrl;\n    this.httpPortForDebug = httpPort;\n\n    try {\n      // A debug block propagated to a span created BEFORE initialize() may have\n      // already armed a from-context runtime (via _armDebugRuntimeFromContext),\n      // stamping rollout.session_id onto a globalMetadata that initialize() just\n      // rebuilt from env/options — discarding it. Such a downstream run has no\n      // LMNR_DEBUG, so the stamp below never runs. Re-stamp from the live\n      // runtime so spans keep rollout.session_id (and replay stays attributed).\n      // No-op on the common path (getRuntime() is null) and harmless on the\n      // LMNR_DEBUG path (the stamp below re-applies the same session id).\n      const armedRuntime = getRuntime();\n      if (armedRuntime !== null) {\n        this.globalMetadata = {\n          ...this.globalMetadata,\n          \"rollout.session_id\": armedRuntime.sessionId,\n        };\n        // A from-context runtime armed before initialize() built its cache\n        // client from unset connection args (env/default fallback). Now that the\n        // real baseUrl/port/api-key are known, rebind its rollout-sessions handle\n        // so replay lookupCache reaches the same backend as the rest of the SDK.\n        // Only the inherited (localOrigin:false) path can predate initialize();\n        // the local-origin env runtime is built later in this method with the\n        // correct args, so guard on it to avoid a needless client allocation.\n        if (!armedRuntime.localOrigin) {\n          const debugClient = new LaminarClient({\n            baseUrl,\n            projectApiKey: this.projectApiKey,\n            port: httpPort,\n          });\n          armedRuntime.rebindRolloutSessions(debugClient.rolloutSessions);\n        }\n      }\n\n      // Bail before allocating a client on the common (non-debug) path. The\n      // LMNR_DEBUG gate also lives inside buildDebugConfig (called by\n      // initDebugRuntime), but that runs only after the client and debugger URL\n      // are built — so check it up front to avoid the wasted allocation on\n      // every initialize(). Mirrors Python's _is_truthy guard in\n      // _init_debug_runtime.\n      if (!isTruthy(process.env.LMNR_DEBUG)) {\n        return;\n      }\n      const client = new LaminarClient({\n        baseUrl,\n        projectApiKey: this.projectApiKey,\n        port: httpPort,\n      });\n      const debuggerUrl =\n        process?.env?.LMNR_FRONTEND_URL ?? getFrontendUrl(baseUrl);\n      const { runtime } = initDebugRuntime(client.rolloutSessions, debuggerUrl);\n      if (runtime === null) {\n        return;\n      }\n\n      // Register the session with the backend so it shows up in the UI. The\n      // SDK owns the session id; this idempotent upsert is what makes a bare\n      // `LMNR_DEBUG=true` run (no replay) useful. Best-effort and fire-and-\n      // forget — initialize() is synchronous and registration must never block\n      // or crash it. The backend returns the project id (derived from the API\n      // key) so we can print the human-facing session URL.\n      void client.rolloutSessions\n        .register({ sessionId: runtime.sessionId })\n        .then((projectId) => {\n          if (projectId) {\n            // Record the project id so the run pointer's debugger_url field\n            // carries the SAME full per-session URL we print here (single code\n            // path via debuggerSessionUrl).\n            runtime.recordProjectId(projectId);\n            const sessionUrl = runtime.debuggerSessionUrl()!;\n            logger.info(`Laminar debugger session: ${sessionUrl}`);\n            if (runtime.shouldOpenBrowser) {\n              // only open URL in browser on first run when we minted a fresh\n              // session id ourselves. A reused session id (passed explicitly via\n              // LMNR_DEBUG_SESSION_ID or continued from an existing\n              // .lmnr/debug-session.json) is a continuation, and a context-armed\n              // downstream run is not the origin — neither reopens the browser.\n              // The decision reads the resolved config (runtime.shouldOpenBrowser)\n              // rather than re-reading env vars.\n              const opener =\n                process.platform === \"win32\"\n                  ? \"start\"\n                  : process.platform === \"darwin\"\n                    ? \"open\"\n                    : \"xdg-open\";\n              spawn(opener, [sessionUrl], {\n                detached: true,\n                stdio: \"ignore\",\n              }).unref();\n            }\n          }\n        })\n        .catch((e) => {\n          logger.warn(\"Failed to register debug session: \" + errorMessage(e));\n        });\n\n      this.globalMetadata = {\n        ...this.globalMetadata,\n        \"rollout.session_id\": runtime.sessionId,\n      };\n      // `exit` fires on both natural event-loop drain and explicit\n      // process.exit(), and emitPointer is synchronous, so a single `exit`\n      // hook covers process teardown. Do NOT also hook `beforeExit`: it fires\n      // on any transient event-loop idle, which can happen before the run's\n      // root trace id is recorded — emitPointer is one-shot, so a premature\n      // call would permanently spend the pointer with an empty trace_id.\n      // Mirrors Python's single atexit hook. Drop any prior hook first so a\n      // repeated initialize() (or an init/shutdown loop) doesn't pile up\n      // listeners; keep this one by reference for shutdown() to remove.\n      if (this.debugExitHook !== null) {\n        process.removeListener(\"exit\", this.debugExitHook);\n      }\n      this.debugExitHook = () => runtime.emitPointer();\n      process.once(\"exit\", this.debugExitHook);\n    } catch (e) {\n      // never let debug setup crash initialization\n      logger.warn(\"Failed to initialize debug runtime: \" + errorMessage(e));\n    }\n  }\n\n  /**\n   * Arm OR refresh the debug runtime from a propagated `DebugContext`.\n   *\n   * Called from `_startSpan` (the funnel for explicit span creation) and from\n   * `observeBase` (the funnel for `observe()` / the observe decorators), when a\n   * parent `LaminarSpanContext` carrying an armed debug block parses — so a\n   * downstream service joins the upstream debug run regardless of how its spans\n   * originate (auto-instrumentation, manual observe, external library).\n   *\n   * The coordinates carried in the span context are DYNAMIC: a long-lived\n   * downstream service handling many requests must follow each request's\n   * session / replay-trace / cache-until, not freeze on the first context it\n   * ever saw. So the transport (client) is built once and reused, while the\n   * replay coordinates are refreshed in place on every new context. An env-origin\n   * runtime is the exception — it owns the process, so a propagated context never\n   * overrides it. A context-armed (downstream) runtime reuses the upstream\n   * session and may consult the cache, but — unlike the local-origin path — does\n   * NOT open the browser, print the session URL, or register an exit-time pointer\n   * hook (the origin owns those). It (re-)registers the session and re-stamps\n   * `rollout.session_id` only when the session id actually changes.\n   *\n   * Never throws: any failure leaves debug inert.\n   *\n   * @internal Public only so `observeBase` (in opentelemetry-lib) can reach it\n   * without an import cycle; not part of the supported API.\n   */\n  public static _armDebugRuntimeFromContext(\n    debug: LaminarSpanContext[\"debug\"],\n  ): void {\n    try {\n      // No armed block: nothing to do. Strict `=== true`, NOT a truthy check: a\n      // string `parentSpanContext` is run through `deserializeDebugContext`\n      // (which coerces `enabled` to a real boolean via `=== true`), but an OBJECT\n      // `parentSpanContext` reaches here verbatim — so a forged block with e.g.\n      // `enabled: \"false\"` (truthy) would otherwise arm a downstream runtime.\n      // Mirror the deserializer's contract. Bail before any allocation so this\n      // stays cheap on the hot span path.\n      if (!debug || debug.enabled !== true || !debug.sessionId) {\n        return;\n      }\n\n      // An env-origin run owns the process and pins its own coordinates — a\n      // propagated context never overrides it, so there is nothing to refresh.\n      const existing = getRuntime();\n      if (existing !== null && existing.localOrigin) {\n        return;\n      }\n\n      // Reuse the already-built client when a context-armed runtime exists — the\n      // transport is stable; only the dynamic coordinates (session / replay /\n      // cache-until) move per request. Build a client only on first arm so a\n      // long-lived downstream service doesn't allocate one per span.\n      const rolloutSessions =\n        existing?.rolloutSessions ??\n        new LaminarClient({\n          baseUrl: this.baseUrlForDebug,\n          projectApiKey: this.projectApiKey,\n          port: this.httpPortForDebug,\n        }).rolloutSessions;\n      const debuggerUrl =\n        process?.env?.LMNR_FRONTEND_URL ?? getFrontendUrl(this.baseUrlForDebug);\n      const { runtime, configChanged } = initDebugRuntimeFromContext(\n        debug,\n        rolloutSessions,\n        debuggerUrl,\n      );\n      if (runtime === null) {\n        return;\n      }\n\n      if (configChanged) {\n        this.debugRunLive = false;\n\n        void runtime.rolloutSessions\n          .register({ sessionId: runtime.sessionId })\n          .then((projectId) => {\n            if (projectId) {\n              runtime.recordProjectId(projectId);\n            }\n          })\n          .catch((e) => {\n            logger.debug(\n              \"Failed to register downstream debug session: \" + errorMessage(e),\n            );\n          });\n\n        this.globalMetadata = {\n          ...this.globalMetadata,\n          \"rollout.session_id\": runtime.sessionId,\n        };\n        // Unlike the local-origin path (synced by initialize() at startup), this\n        // runs during span creation, so re-sync to LaminarContextManager here or\n        // LaminarSpanProcessor.onStart misses rollout.session_id on auto spans.\n        LaminarContextManager.setGlobalMetadata(this.globalMetadata);\n      }\n      // No `exit` pointer hook: a downstream run must not emit the pointer.\n    } catch (e) {\n      // never let debug arming crash span creation\n      logger.debug(\n        \"Failed to arm debug runtime from context: \" + errorMessage(e),\n      );\n    }\n  }\n\n  /**\n   * Patch modules manually. Use this in setups where {@link Laminar.initialize()}\n   * and in particular its `instrumentModules` option is not working, e.g. in\n   * Next.js place Laminar initialize in `instrumentation.ts`, and then patch\n   * the modules in server components or API routes.\n   *\n   * Make sure to call this after {@link Laminar.initialize()}.\n   *\n   * @param {InitializeOptions[\"instrumentModules\"]} modules - Record of modules to instrument.\n   */\n  public static patch(modules: InitializeOptions[\"instrumentModules\"]) {\n    if (!this.isInitialized) {\n      logger.warn(\n        \"Laminar must be initialized before patching modules. Skipping patch.\",\n      );\n      return;\n    }\n    if (!modules || Object.keys(modules).length === 0) {\n      throw new Error(\"Pass at least one module to patch\");\n    }\n    patchModules(modules);\n  }\n\n  /**\n   * Check if Laminar has been initialized. Utility to make sure other methods\n   * are called after initialization.\n   */\n  public static initialized(): boolean {\n    return this.isInitialized;\n  }\n\n  /**\n   * Associates an event with the current span. If the event is created outside\n   * of a span context, a new span is created and the event is associated with it.\n   *\n   * @param {object} options\n   * @param {string} options.name - The name of the event.\n   * @param {Record<string, AttributeValue>} options.attributes - The attributes of the event.\n   * Values must be of a supported type.\n   * @param {TimeInput} options.timestamp - The timestamp of the event. If not specified, relies on\n   * the underlying OpenTelemetry implementation.\n   * If specified as an integer, it must be epoch nanoseconds.\n   * @param {string} options.sessionId - The session ID to associate with the event.\n   * If not specified, the session ID of the current trace is used.\n   * @param {string} options.userId - The user ID to associate with the event. If not specified,\n   * the user ID of the current trace is used.\n   */\n  public static event({\n    name,\n    attributes,\n    timestamp,\n    sessionId,\n    userId,\n  }: {\n    name: string;\n    attributes?: Record<string, AttributeValue>;\n    timestamp?: TimeInput;\n    sessionId?: string;\n    userId?: string;\n  }) {\n    if (!Laminar.initialized()) {\n      return;\n    }\n\n    const allAttributes = {\n      ...(attributes ?? {}),\n      ...(sessionId ? { \"lmnr.event.session_id\": sessionId } : {}),\n      ...(userId ? { \"lmnr.event.user_id\": userId } : {}),\n    } as Record<string, AttributeValue>;\n\n    const currentSpan = Laminar.getCurrentSpan();\n\n    if (currentSpan === undefined) {\n      const newSpan = Laminar.startSpan({ name });\n      newSpan?.addEvent(name, allAttributes, timestamp);\n      newSpan?.end();\n      return;\n    }\n\n    currentSpan.addEvent(name, allAttributes, timestamp);\n  }\n\n  public static getCurrentSpan(context?: Context): LaminarSpan | undefined {\n    const currentSpan =\n      trace.getSpan(context ?? LaminarContextManager.getContext()) ??\n      trace.getActiveSpan();\n    if (\n      currentSpan === undefined ||\n      !isSpanContextValid(currentSpan.spanContext())\n    ) {\n      return undefined;\n    }\n    if (currentSpan instanceof LaminarSpan) {\n      return currentSpan;\n    }\n    return new LaminarSpan(currentSpan);\n  }\n\n  /**\n   * Set attributes for the current span. Useful for manual\n   * instrumentation.\n   * @param {LaminarAttributesProp} attributes - The attributes to set for the current span.\n   *\n   * @example\n   * import { Laminar as L, observe } from '@lmnr-ai/laminar';\n   * await observe({ name: 'mySpanName', spanType: 'LLM' }, async (msg: string) => {\n   *   const response = await myCustomCallToOpenAI(msg);\n   *   L.setSpanAttributes({\n   *     [LaminarAttributes.PROVIDER]: 'openai',\n   *     [LaminarAttributes.REQUEST_MODEL]: \"requested_model\",\n   *     [LaminarAttributes.RESPONSE_MODEL]: response.model,\n   *     [LaminarAttributes.INPUT_TOKEN_COUNT]: response.usage.prompt_tokens,\n   *     [LaminarAttributes.OUTPUT_TOKEN_COUNT]: response.usage.completion_tokens,\n   *   })\n   * }, userMessage);\n   */\n  public static setSpanAttributes(attributes: LaminarAttributesProp) {\n    const currentSpan = Laminar.getCurrentSpan();\n    if (currentSpan) {\n      for (const [key, value] of Object.entries(attributes)) {\n        currentSpan.setAttribute(key, value);\n      }\n    }\n  }\n\n  /**\n   * Set the output of the current span. Useful for manual instrumentation.\n   * @param output - Output of the span. Will be sent as an attribute, so must\n   * be serializable to JSON.\n   */\n  public static setSpanOutput(output: any) {\n    if (output == null) {\n      return;\n    }\n    const currentSpan = Laminar.getCurrentSpan();\n    if (currentSpan) {\n      currentSpan.setOutput(output);\n    }\n  }\n\n  public static setTraceMetadata(metadata: Record<string, any>) {\n    const currentSpan = Laminar.getCurrentSpan();\n    if (currentSpan) {\n      currentSpan.setTraceMetadata(metadata);\n    }\n  }\n\n  public static setTraceSessionId(sessionId: string) {\n    const currentSpan = Laminar.getCurrentSpan();\n    if (currentSpan) {\n      currentSpan.setTraceSessionId(sessionId);\n    }\n  }\n\n  public static setTraceUserId(userId: string) {\n    const currentSpan = Laminar.getCurrentSpan();\n    if (currentSpan) {\n      currentSpan.setTraceUserId(userId);\n    }\n  }\n\n  public static setSpanTags(tags: string[]) {\n    const currentSpan = Laminar.getCurrentSpan();\n    if (\n      currentSpan !== undefined &&\n      isSpanContextValid(currentSpan.spanContext())\n    ) {\n      currentSpan.setTags(tags);\n    }\n  }\n\n  public static addSpanTags(tags: string[]) {\n    const currentSpan = Laminar.getCurrentSpan();\n    if (\n      currentSpan !== undefined &&\n      isSpanContextValid(currentSpan.spanContext())\n    ) {\n      currentSpan.addTags(tags);\n    }\n  }\n\n  /**\n   * Start a new span, but don't set it as active. Useful for\n   * manual instrumentation. If span type is 'LLM', you should report usage\n   * manually. See {@link setSpanAttributes} for more information.\n   *\n   * @param {Object} options\n   * @param {string} options.name - name of the span\n   * @param {any} options.input - input to the span. Will be sent as an attribute, so must\n   * be JSON serializable\n   * @param {string} options.spanType - type of the span. Defaults to 'DEFAULT'\n   * @param {Context} options.context - raw OpenTelemetry context to bind the span to.\n   * @param {string | LaminarSpanContext} options.parentSpanContext - parent span context\n   * to bind the span to.\n   * @param {string[]} options.tags - tags to associate with the span.\n   * @param {string} options.userId - user ID to associate with the span.\n   * @param {string} options.sessionId - session ID to associate with the span.\n   * @param {Record<string, any>} options.metadata - metadata to associate with the span.\n   * @returns The started span.\n   *\n   * @example\n   * import { Laminar, observe } from '@lmnr-ai/lmnr';\n   * const foo = async (span: Span) => {\n   *   await Laminar.withSpan(span, async () => {\n   *     await observe({ name: 'foo' }, async () => {\n   *       // Your code here\n   *     })\n   *   })\n   * };\n   * const bar = async (span: Span) => {\n   *   await Laminar.withSpan(span, async () => {\n   *     await openai_client.chat.completions.create();\n   *   })\n   * };\n   *\n   * const parentSpan = Laminar.startSpan({name: \"outer\"});\n   * foo(parentSpan);\n   * await bar(parentSpan);\n   * // IMPORTANT: Don't forget to end the span!\n   * parentSpan.end();\n   *\n   * // Results in:\n   * // | outer\n   * // |  | foo\n   * // |  |  | ...\n   * // |  | openai.chat\n   */\n  public static startSpan({\n    name,\n    input,\n    spanType,\n    context,\n    parentSpanContext,\n    tags,\n    userId,\n    sessionId,\n    metadata,\n    startTime,\n  }: {\n    name: string;\n    input?: any;\n    spanType?: SpanType;\n    context?: Context;\n    parentSpanContext?: string | LaminarSpanContext;\n    tags?: string[];\n    userId?: string;\n    sessionId?: string;\n    metadata?: Record<string, any>;\n    startTime?: TimeInput;\n  }): Span {\n    return this._startSpan({\n      name,\n      input,\n      spanType,\n      context,\n      parentSpanContext,\n      tags,\n      userId,\n      sessionId,\n      metadata,\n      activated: false,\n      startTime,\n    });\n  }\n\n  /**\n   * Start a new span, and set it as active. It is the caller's responsibility\n   * to end the span. It is important to end the span, to avoid context mixing up.\n   * We suggest ending the span in a finally block.\n   * This is useful for manual instrumentation.\n   * If span type is 'LLM', you should report usage manually.\n   * See {@link setSpanAttributes} for more information.\n   *\n   * @param {Object} options\n   * @param {string} options.name - name of the span\n   * @param {any} options.input - input to the span. Will be sent as an attribute, so must\n   * be JSON serializable\n   * @param {string} options.spanType - type of the span. Defaults to 'DEFAULT'\n   * @param {Context} options.context - raw OpenTelemetry context to bind the span to.\n   * @param {string | LaminarSpanContext} options.parentSpanContext - parent span context\n   * to bind the span to.\n   * @param {string[]} options.tags - tags to associate with the span.\n   * @param {string} options.userId - user ID to associate with the span.\n   * @param {string} options.sessionId - session ID to associate with the span.\n   * @param {Record<string, any>} options.metadata - metadata to associate with the span.\n   * @param {boolean} options.global - when true, the span is registered on a\n   * process-global context stack so that any subsequent `startSpan` /\n   * `startActiveSpan` call (including from unrelated async tasks) uses it as\n   * the parent. Use this for spans that span multiple disconnected async\n   * callbacks — e.g. the root span of an OpenAI Agents trace, where child\n   * spans are created from independent `TracingProcessor` callbacks that do\n   * not share an async context. Defaults to false; the span still activates\n   * within the current async context as usual.\n   * @returns The started span.\n   *\n   * @example\n   * import { Laminar, observe } from '@lmnr-ai/lmnr';\n   * const foo = async () => {\n   *   await observe({ name: 'foo' }, async () => {\n   *     // Your code here\n   *   })\n   * };\n   * const bar = async (span: Span) => {\n   *   await observe({ name: 'bar' }, async () => {\n   *     await openai_client.chat.completions.create();\n   *   })\n   * };\n   *\n   * try {\n   *   const parentSpan = Laminar.startActiveSpan({name: \"outer\"});\n   *   foo();\n   *   await bar();\n   * } finally {\n   *   parentSpan.end();\n   * }\n   *\n   * // Results in:\n   * // | outer\n   * // |  | foo\n   * // |  |  | ...\n   * // |  | bar\n   * // |  |  | openai.chat\n   */\n  public static startActiveSpan({\n    name,\n    input,\n    spanType,\n    context,\n    parentSpanContext,\n    tags,\n    userId,\n    sessionId,\n    metadata,\n    startTime,\n    global,\n  }: {\n    name: string;\n    input?: any;\n    spanType?: SpanType;\n    context?: Context;\n    parentSpanContext?: string | LaminarSpanContext;\n    tags?: string[];\n    userId?: string;\n    sessionId?: string;\n    metadata?: Record<string, any>;\n    startTime?: TimeInput;\n    global?: boolean;\n  }): Span {\n    return this._startSpan({\n      name,\n      input,\n      spanType,\n      context,\n      parentSpanContext,\n      tags,\n      userId,\n      sessionId,\n      metadata,\n      activated: true,\n      startTime,\n      global,\n    });\n  }\n\n  private static _startSpan({\n    name,\n    input,\n    spanType,\n    context,\n    parentSpanContext,\n    tags,\n    userId,\n    sessionId,\n    metadata,\n    activated,\n    startTime,\n    global,\n  }: {\n    name: string;\n    input?: any;\n    spanType?: SpanType;\n    context?: Context;\n    parentSpanContext?: string | LaminarSpanContext;\n    tags?: string[];\n    userId?: string;\n    sessionId?: string;\n    metadata?: Record<string, any>;\n    activated?: boolean;\n    startTime?: TimeInput;\n    global?: boolean;\n  }): Span {\n    let entityContext = context ?? LaminarContextManager.getContext();\n\n    // Extract parent path information before converting to OpenTelemetry span context\n    let parentPath: string[] | undefined;\n    let parentIdsPath: string[] | undefined;\n    let parentMetadata: Record<string, any> | undefined;\n    let parentTraceType: TraceType | undefined;\n    let parentTracingLevel: TracingLevel | undefined;\n    let parentUserId: string | undefined;\n    let parentSessionId: string | undefined;\n\n    if (parentSpanContext) {\n      try {\n        const laminarContext =\n          typeof parentSpanContext === \"string\"\n            ? deserializeLaminarSpanContext(parentSpanContext)\n            : parentSpanContext;\n\n        parentPath = laminarContext.spanPath;\n        parentIdsPath = laminarContext.spanIdsPath;\n        parentMetadata = laminarContext.metadata;\n        parentTraceType = laminarContext.traceType;\n        parentTracingLevel = laminarContext.tracingLevel;\n        parentUserId = laminarContext.userId;\n        parentSessionId = laminarContext.sessionId;\n\n        // Arm the debug runtime from a propagated debug block (first-wins,\n        // idempotent, no-op when already armed or no block present). Placed\n        // here — deep in span creation, before any caching instrumentation\n        // consults the runtime — so a downstream run joins the upstream debug\n        // session regardless of how its spans originate.\n        this._armDebugRuntimeFromContext(laminarContext.debug);\n\n        const spanContext = tryToOtelSpanContext(laminarContext);\n        entityContext = trace.setSpan(\n          entityContext,\n          trace.wrapSpanContext(spanContext),\n        );\n      } catch (e) {\n        logger.warn(\"Failed to parse parent span context: \" + errorMessage(e));\n      }\n    }\n    const tagProperties = tags\n      ? { [`${ASSOCIATION_PROPERTIES}.tags`]: Array.from(new Set(tags)) }\n      : {};\n    const ctxAssociationProperties =\n      LaminarContextManager.getAssociationProperties();\n    const userIdValue =\n      userId ?? parentUserId ?? ctxAssociationProperties.userId;\n    const sessionIdValue =\n      sessionId ?? parentSessionId ?? ctxAssociationProperties.sessionId;\n    const traceTypeValue =\n      parentTraceType ??\n      ((spanType as string) === \"EVALUATION\" ? \"EVALUATION\" : undefined) ??\n      ctxAssociationProperties.traceType;\n    const tracingLevelValue =\n      parentTracingLevel ?? ctxAssociationProperties.tracingLevel;\n    const ctxMetadata = ctxAssociationProperties.metadata;\n\n    const userIdProperties = userIdValue ? { [USER_ID]: userIdValue } : {};\n    const sessionIdProperties = sessionIdValue\n      ? { [SESSION_ID]: sessionIdValue }\n      : {};\n    const traceTypeProperties = traceTypeValue\n      ? { [TRACE_TYPE]: traceTypeValue }\n      : {};\n    const tracingLevelProperties = tracingLevelValue\n      ? { [`${ASSOCIATION_PROPERTIES}.tracing_level`]: tracingLevelValue }\n      : {};\n\n    const mergedMetadata = {\n      ...this.globalMetadata,\n      ...ctxMetadata,\n      ...parentMetadata,\n      ...metadata,\n    };\n\n    const metadataProperties = metadataToAttributes(mergedMetadata);\n    const attributes = {\n      [SPAN_TYPE]: spanType ?? \"DEFAULT\",\n      ...tagProperties,\n      ...userIdProperties,\n      ...sessionIdProperties,\n      ...metadataProperties,\n      ...traceTypeProperties,\n      ...tracingLevelProperties,\n      ...(parentPath ? { [PARENT_SPAN_PATH]: parentPath } : {}),\n      ...(parentIdsPath ? { [PARENT_SPAN_IDS_PATH]: parentIdsPath } : {}),\n    };\n\n    const span = new LaminarSpan(\n      getTracer().startSpan(name, { attributes, startTime }, entityContext),\n    );\n    span.activated = activated ?? false;\n\n    if (input) {\n      span.setInput(input);\n    }\n    if (activated) {\n      entityContext = LaminarContextManager.setAssociationProperties(\n        span,\n        entityContext,\n      );\n      entityContext = trace.setSpan(entityContext, span);\n      LaminarContextManager.pushContext(entityContext);\n      if (global) {\n        LaminarContextManager.pushGlobalContext(entityContext);\n        span.setGlobalActiveContext(entityContext);\n      }\n    }\n    return span;\n  }\n\n  /**\n   * A utility wrapper around OpenTelemetry's `context.with()`. Useful for\n   * passing spans around in manual instrumentation:\n   *\n   * @param {Span} span - Parent span to bind the execution to.\n   * @param {Function} fn - Function to execute within the span context.\n   * @param {boolean} endOnExit - Whether to end the span after the function has\n   * executed. Defaults to `false`. If `false`, you MUST manually call\n   * `span.end()` at the end of the execution, so that spans are not lost.\n   * @returns The result of the function execution.\n   *\n   * See {@link startSpan} docs for a usage example\n   */\n  public static withSpan<T>(span: Span, fn: () => T, endOnExit?: boolean): T {\n    const ctx = LaminarContextManager.getContext();\n    const laminarSpan = new LaminarSpan(span);\n    const ctxWithAssociationProperties =\n      LaminarContextManager.setAssociationProperties(laminarSpan, ctx);\n    const context = trace.setSpan(ctxWithAssociationProperties, span);\n    return contextApi.with(context, () =>\n      LaminarContextManager.runWithIsolatedContext([context], () => {\n        try {\n          const result = fn();\n          if (result instanceof Promise) {\n            return result\n              .catch((err) => {\n                span.recordException(err as Error);\n                throw err;\n              })\n              .finally(() => {\n                if (endOnExit !== undefined && endOnExit) {\n                  span.end();\n                }\n              }) as T;\n          }\n          if (endOnExit !== undefined && endOnExit) {\n            span.end();\n          }\n          return result;\n        } catch (error) {\n          span.recordException(error as Error);\n          if (endOnExit !== undefined && endOnExit) {\n            span.end();\n          }\n          throw error;\n        }\n      }),\n    );\n  }\n\n  public static serializeLaminarSpanContext(span?: Span): string | null {\n    const laminarSpanContext = this.getLaminarSpanContext(span);\n    if (laminarSpanContext === null) {\n      return null;\n    }\n    return JSON.stringify(laminarSpanContext);\n  }\n\n  public static getLaminarSpanContext(span?: Span): LaminarSpanContext | null {\n    let currentSpan = span ?? Laminar.getCurrentSpan();\n    if (\n      currentSpan === undefined ||\n      !isSpanContextValid(currentSpan.spanContext())\n    ) {\n      return null;\n    }\n    if (!(currentSpan instanceof LaminarSpan)) {\n      currentSpan = new LaminarSpan(currentSpan);\n    }\n    return (currentSpan as LaminarSpan).getLaminarSpanContext();\n  }\n\n  /**\n   * Get the trace id of the current span. Returns null if there is no active span.\n   * @returns {StringUUID | null} The trace id of the current span.\n   */\n  public static getTraceId(): StringUUID | null {\n    return this.getLaminarSpanContext()?.traceId ?? null;\n  }\n\n  public static async flush() {\n    if (this.isInitialized) {\n      logger.debug(\"Flushing spans\");\n      await forceFlush();\n    }\n  }\n\n  public static async shutdown() {\n    if (this.isInitialized) {\n      logger.debug(\"Shutting down Laminar\");\n      // Emit the debug-session record before flushing so flows that shut down\n      // without terminating the process still get LMNR_DEBUG_RUN +\n      // .lmnr/debug-session.json. Idempotent — the process-exit hooks are a\n      // fallback.\n      getRuntime()?.emitPointer();\n      await forceFlush();\n      // Unlike Python where asynchronous nature of `BatchSpanProcessor.forceFlush()`\n      // forces us to actually use `SpanProcessor.shutdown()` and make any\n      // further interactions with OTEL API impossible, here we call\n      // SpanProcessor.forceFlush() (and safely await it). Thus, users can\n      // call `shutdown()` and then `initialize()` again. This is why we\n      // reset the keys, contexts, and configuration here.\n      this.isInitialized = false;\n      _resetConfiguration();\n      LaminarContextManager.clearContexts();\n      LaminarContextManager.clearActiveSpans();\n      // Clear the one-shot debug-runtime state so a subsequent initialize()\n      // re-reads LMNR_DEBUG* instead of resurrecting the previous run.\n      resetDebugRuntime();\n      // Clear the process-wide live latch so a re-initialized run starts by\n      // consulting the cache again instead of inheriting the prior run's MISS.\n      this.debugRunLive = false;\n      // The pointer was just emitted above, so the `exit` hook would be a\n      // redundant no-op; remove it so init/shutdown loops don't leak listeners.\n      if (this.debugExitHook !== null) {\n        process.removeListener(\"exit\", this.debugExitHook);\n        this.debugExitHook = null;\n      }\n\n      // Force release the claude-code proxy if it was started (ignores ref count)\n      forceReleaseClaudeProxy();\n    }\n  }\n\n  public static getHttpUrl(): string {\n    return this.baseHttpUrl;\n  }\n\n  public static getProjectApiKey(): string {\n    return this.projectApiKey;\n  }\n\n  /**\n   * Instrument the claude-agent-sdk query function.\n   * Use this when you need to import the query function before calling Laminar.initialize().\n   *\n   * @param originalQuery - The original query function from @anthropic-ai/claude-agent-sdk\n   * @returns The instrumented query function\n   *\n   * @example\n   * ```typescript\n   * import { query as originalQuery } from \"@anthropic-ai/claude-agent-sdk\";\n   * import { Laminar } from \"@lmnr-ai/lmnr\";\n   *\n   * Laminar.initialize({ projectApiKey: \"...\" });\n   *\n   * const query = Laminar.instrumentClaudeAgentQuery(originalQuery);\n   *\n   * // Now use the instrumented query function\n   * const result = query({ prompt: \"Hello!\" });\n   * ```\n   */\n  // biome-ignore lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\n  public static wrapClaudeAgentQuery<T extends Function>(originalQuery: T): T {\n    return instrumentClaudeAgentQuery(originalQuery as any);\n  }\n}\n","// If you want to update the content, make the following changes to minified source\n// 0. Make sure your editor is not formatting the file on save.\n// 1. Replace every \\ with \\\\ (important: this must come first)\n// 2. Replace every ` with a \\`\n// 3. Replace every ${ with a \\${\nexport const RECORDER = `(function (g, f) {\n    if (\"object\" == typeof exports && \"object\" == typeof module) {\n      module.exports = f();\n    } else if (\"function\" == typeof define && define.amd) {\n      define(\"lmnrRrweb\", [], f);\n    } else if (\"object\" == typeof exports) {\n      exports[\"lmnrRrweb\"] = f();\n    } else {\n      g[\"lmnrRrweb\"] = f();\n    }\n  }(this, () => {\nvar exports = {};\nvar module = { exports };\n\"use strict\";var Fo=Object.defineProperty,Uo=Object.defineProperties;var Bo=Object.getOwnPropertyDescriptors;var ft=Object.getOwnPropertySymbols;var zs=Object.prototype.hasOwnProperty,Ws=Object.prototype.propertyIsEnumerable;var Bs=(s,e,t)=>e in s?Fo(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,x=(s,e)=>{for(var t in e||(e={}))zs.call(e,t)&&Bs(s,t,e[t]);if(ft)for(var t of ft(e))Ws.call(e,t)&&Bs(s,t,e[t]);return s},ee=(s,e)=>Uo(s,Bo(e));var xe=(s,e)=>{var t={};for(var r in s)zs.call(s,r)&&e.indexOf(r)<0&&(t[r]=s[r]);if(s!=null&&ft)for(var r of ft(s))e.indexOf(r)<0&&Ws.call(s,r)&&(t[r]=s[r]);return t};Object.defineProperty(exports,Symbol.toStringTag,{value:\"Module\"});var zo=Object.defineProperty,Wo=(s,e,t)=>e in s?zo(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,w=(s,e,t)=>Wo(s,typeof e!=\"symbol\"?e+\"\":e,t),Gs,Go=Object.defineProperty,Vo=(s,e,t)=>e in s?Go(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,Vs=(s,e,t)=>Vo(s,typeof e!=\"symbol\"?e+\"\":e,t),j=(s=>(s[s.Document=0]=\"Document\",s[s.DocumentType=1]=\"DocumentType\",s[s.Element=2]=\"Element\",s[s.Text=3]=\"Text\",s[s.CDATA=4]=\"CDATA\",s[s.Comment=5]=\"Comment\",s))(j||{});const js={Node:[\"childNodes\",\"parentNode\",\"parentElement\",\"textContent\"],ShadowRoot:[\"host\",\"styleSheets\"],Element:[\"shadowRoot\",\"querySelector\",\"querySelectorAll\"],MutationObserver:[]},Hs={Node:[\"contains\",\"getRootNode\"],ShadowRoot:[\"getSelection\"],Element:[],MutationObserver:[\"constructor\"]},pt={},jo=()=>!!globalThis.Zone;function cs(s){if(pt[s])return pt[s];const e=globalThis[s],t=e.prototype,r=s in js?js[s]:void 0,i=!!(r&&r.every(l=>{var a,u;return!!((u=(a=Object.getOwnPropertyDescriptor(t,l))==null?void 0:a.get)!=null&&u.toString().includes(\"[native code]\"))})),n=s in Hs?Hs[s]:void 0,o=!!(n&&n.every(l=>{var a;return typeof t[l]==\"function\"&&((a=t[l])==null?void 0:a.toString().includes(\"[native code]\"))}));if(i&&o&&!jo())return pt[s]=e.prototype,e.prototype;try{const l=document.createElement(\"iframe\");document.body.appendChild(l);const a=l.contentWindow;if(!a)return e.prototype;const u=a[s].prototype;return document.body.removeChild(l),u?pt[s]=u:t}catch(l){return t}}const mr={};function me(s,e,t){var r;const i=\\`\\${s}.\\${String(t)}\\`;if(mr[i])return mr[i].call(e);const n=cs(s),o=(r=Object.getOwnPropertyDescriptor(n,t))==null?void 0:r.get;return o?(mr[i]=o,o.call(e)):e[t]}const gr={};function Wi(s,e,t){const r=\\`\\${s}.\\${String(t)}\\`;if(gr[r])return gr[r].bind(e);const n=cs(s)[t];return typeof n!=\"function\"?e[t]:(gr[r]=n,n.bind(e))}function Ho(s){return me(\"Node\",s,\"childNodes\")}function Yo(s){return me(\"Node\",s,\"parentNode\")}function Zo(s){return me(\"Node\",s,\"parentElement\")}function Jo(s){return me(\"Node\",s,\"textContent\")}function Xo(s,e){return Wi(\"Node\",s,\"contains\")(e)}function Ko(s){return Wi(\"Node\",s,\"getRootNode\")()}function Qo(s){return!s||!(\"host\"in s)?null:me(\"ShadowRoot\",s,\"host\")}function qo(s){return s.styleSheets}function ea(s){return!s||!(\"shadowRoot\"in s)?null:me(\"Element\",s,\"shadowRoot\")}function ta(s,e){return me(\"Element\",s,\"querySelector\")(e)}function ra(s,e){return me(\"Element\",s,\"querySelectorAll\")(e)}function sa(){return cs(\"MutationObserver\").constructor}const Z={childNodes:Ho,parentNode:Yo,parentElement:Zo,textContent:Jo,contains:Xo,getRootNode:Ko,host:Qo,styleSheets:qo,shadowRoot:ea,querySelector:ta,querySelectorAll:ra,mutationObserver:sa};function Gi(s){return s.nodeType===s.ELEMENT_NODE}function je(s){const e=s&&\"host\"in s&&\"mode\"in s&&Z.host(s)||null;return!!(e&&\"shadowRoot\"in e&&Z.shadowRoot(e)===s)}function He(s){return Object.prototype.toString.call(s)===\"[object ShadowRoot]\"}function ia(s){return s.includes(\" background-clip: text;\")&&!s.includes(\" -webkit-background-clip: text;\")&&(s=s.replace(/\\\\sbackground-clip:\\\\s*text;/g,\" -webkit-background-clip: text; background-clip: text;\")),s}function na(s){const{cssText:e}=s;if(e.split('\"').length<3)return e;const t=[\"@import\",\\`url(\\${JSON.stringify(s.href)})\\`];return s.layerName===\"\"?t.push(\"layer\"):s.layerName&&t.push(\\`layer(\\${s.layerName})\\`),s.supportsText&&t.push(\\`supports(\\${s.supportsText})\\`),s.media.length&&t.push(s.media.mediaText),t.join(\" \")+\";\"}function $r(s){try{const e=s.rules||s.cssRules;if(!e)return null;let t=s.href;!t&&s.ownerNode&&s.ownerNode.ownerDocument&&(t=s.ownerNode.ownerDocument.location.href);const r=Array.from(e,i=>Vi(i,t)).join(\"\");return ia(r)}catch(e){return null}}function Vi(s,e){if(aa(s)){let t;try{t=$r(s.styleSheet)||na(s)}catch(r){t=s.cssText}return s.styleSheet.href?Wt(t,s.styleSheet.href):t}else{let t=s.cssText;return la(s)&&s.selectorText.includes(\":\")&&(t=oa(t)),e?Wt(t,e):t}}function oa(s){const e=/(\\\\[(?:[\\\\w-]+)[^\\\\\\\\])(:(?:[\\\\w-]+)\\\\])/gm;return s.replace(e,\"$1\\\\\\\\$2\")}function aa(s){return\"styleSheet\"in s}function la(s){return\"selectorText\"in s}class ji{constructor(){Vs(this,\"idNodeMap\",new Map),Vs(this,\"nodeMetaMap\",new WeakMap)}getId(e){var t;if(!e)return-1;const r=(t=this.getMeta(e))==null?void 0:t.id;return r!=null?r:-1}getNode(e){return this.idNodeMap.get(e)||null}getIds(){return Array.from(this.idNodeMap.keys())}getMeta(e){return this.nodeMetaMap.get(e)||null}removeNodeFromMap(e){const t=this.getId(e);this.idNodeMap.delete(t),e.childNodes&&e.childNodes.forEach(r=>this.removeNodeFromMap(r))}has(e){return this.idNodeMap.has(e)}hasNode(e){return this.nodeMetaMap.has(e)}add(e,t){const r=t.id;this.idNodeMap.set(r,e),this.nodeMetaMap.set(e,t)}replace(e,t){const r=this.getNode(e);if(r){const i=this.nodeMetaMap.get(r);i&&this.nodeMetaMap.set(t,i)}this.idNodeMap.set(e,t)}reset(){this.idNodeMap=new Map,this.nodeMetaMap=new WeakMap}}function ua(){return new ji}function hs({element:s,maskInputOptions:e,tagName:t,type:r,value:i,maskInputFn:n}){let o=i||\"\";const l=r&&Ce(r);return(e[t.toLowerCase()]||l&&e[l])&&(n?o=n(o,s):o=\"*\".repeat(o.length)),o}function Ce(s){return s.toLowerCase()}const Ys=\"__rrweb_original__\";function ca(s){const e=s.getContext(\"2d\");if(!e)return!0;const t=50;for(let r=0;r<s.width;r+=t)for(let i=0;i<s.height;i+=t){const n=e.getImageData,o=Ys in n?n[Ys]:n;if(new Uint32Array(o.call(e,r,i,Math.min(t,s.width-r),Math.min(t,s.height-i)).data.buffer).some(a=>a!==0))return!1}return!0}function fs(s){const e=s.type;return s.hasAttribute(\"data-rr-is-password\")?\"password\":e?Ce(e):null}function Hi(s,e){var n;let t;try{t=new URL(s,e!=null?e:window.location.href)}catch(o){return null}const r=/\\\\.([0-9a-z]+)(?:$)/i,i=t.pathname.match(r);return(n=i==null?void 0:i[1])!=null?n:null}function ha(s){let e=\"\";return s.indexOf(\"//\")>-1?e=s.split(\"/\").slice(0,3).join(\"/\"):e=s.split(\"/\")[0],e=e.split(\"?\")[0],e}const fa=/url\\\\((?:(')([^']*)'|(\")(.*?)\"|([^)]*))\\\\)/gm,pa=/^(?:[a-z+]+:)?\\\\/\\\\//i,da=/^www\\\\..*/i,ma=/^(data:)([^,]*),(.*)/i;function Wt(s,e){return(s||\"\").replace(fa,(t,r,i,n,o,l)=>{const a=i||o||l,u=r||n||\"\";if(!a)return t;if(pa.test(a)||da.test(a))return\\`url(\\${u}\\${a}\\${u})\\`;if(ma.test(a))return\\`url(\\${u}\\${a}\\${u})\\`;if(a[0]===\"/\")return\\`url(\\${u}\\${ha(e)+a}\\${u})\\`;const c=e.split(\"/\"),h=a.split(\"/\");c.pop();for(const d of h)d!==\".\"&&(d===\"..\"?c.pop():c.push(d));return\\`url(\\${u}\\${c.join(\"/\")}\\${u})\\`})}function yr(s){return s.replace(/(\\\\/\\\\*[^*]*\\\\*\\\\/)|[\\\\s;]/g,\"\")}function ga(s,e){const t=Array.from(e.childNodes),r=[];if(t.length>1&&s&&typeof s==\"string\"){const i=yr(s);for(let n=1;n<t.length;n++)if(t[n].textContent&&typeof t[n].textContent==\"string\"){const o=yr(t[n].textContent);for(let l=3;l<o.length;l++){const a=o.substring(0,l);if(i.split(a).length===2){const u=i.indexOf(a);for(let c=u;c<s.length;c++)if(yr(s.substring(0,c)).length===u){r.push(s.substring(0,c)),s=s.substring(c);break}break}}}}return r.push(s),r}function ya(s,e){return ga(s,e).join(\"/* rr_split */\")}let wa=1;const Sa=new RegExp(\"[^a-z0-9-_:]\"),Ze=-2;function Yi(){return wa++}function ba(s){if(s instanceof HTMLFormElement)return\"form\";const e=Ce(s.tagName);return Sa.test(e)?\"div\":e}let Oe,Zs;const Ca=/^[^ \\\\t\\\\n\\\\r\\\\u000c]+/,va=/^[, \\\\t\\\\n\\\\r\\\\u000c]+/;function Ia(s,e){if(e.trim()===\"\")return e;let t=0;function r(n){let o;const l=n.exec(e.substring(t));return l?(o=l[0],t+=o.length,o):\"\"}const i=[];for(;r(va),!(t>=e.length);){let n=r(Ca);if(n.slice(-1)===\",\")n=Me(s,n.substring(0,n.length-1)),i.push(n);else{let o=\"\";n=Me(s,n);let l=!1;for(;;){const a=e.charAt(t);if(a===\"\"){i.push((n+o).trim());break}else if(l)a===\")\"&&(l=!1);else if(a===\",\"){t+=1,i.push((n+o).trim());break}else a===\"(\"&&(l=!0);o+=a,t+=1}}}return i.join(\", \")}const Js=new WeakMap;function Me(s,e){return!e||e.trim()===\"\"?e:ps(s,e)}function xa(s){return!!(s.tagName===\"svg\"||s.ownerSVGElement)}function ps(s,e){let t=Js.get(s);if(t||(t=s.createElement(\"a\"),Js.set(s,t)),!e)e=\"\";else if(e.startsWith(\"blob:\")||e.startsWith(\"data:\"))return e;return t.setAttribute(\"href\",e),t.href}function Zi(s,e,t,r){return r&&(t===\"src\"||t===\"href\"&&!(e===\"use\"&&r[0]===\"#\")||t===\"xlink:href\"&&r[0]!==\"#\"||t===\"background\"&&(e===\"table\"||e===\"td\"||e===\"th\")?Me(s,r):t===\"srcset\"?Ia(s,r):t===\"style\"?Wt(r,ps(s)):e===\"object\"&&t===\"data\"?Me(s,r):r)}function Ji(s,e,t){return(s===\"video\"||s===\"audio\")&&e===\"autoplay\"}function Oa(s,e,t){try{if(typeof e==\"string\"){if(s.classList.contains(e))return!0}else for(let r=s.classList.length;r--;){const i=s.classList[r];if(e.test(i))return!0}if(t)return s.matches(t)}catch(r){}return!1}function Gt(s,e,t){if(!s)return!1;if(s.nodeType!==s.ELEMENT_NODE)return t?Gt(Z.parentNode(s),e,t):!1;for(let r=s.classList.length;r--;){const i=s.classList[r];if(e.test(i))return!0}return t?Gt(Z.parentNode(s),e,t):!1}function Xi(s,e,t,r){let i;if(Gi(s)){if(i=s,!Z.childNodes(i).length)return!1}else{if(Z.parentElement(s)===null)return!1;i=Z.parentElement(s)}try{if(typeof e==\"string\"){if(r){if(i.closest(\\`.\\${e}\\`))return!0}else if(i.classList.contains(e))return!0}else if(Gt(i,e,r))return!0;if(t){if(r){if(i.closest(t))return!0}else if(i.matches(t))return!0}}catch(n){}return!1}function Ra(s,e,t){const r=s.contentWindow;if(!r)return;let i=!1,n;try{n=r.document.readyState}catch(l){return}if(n!==\"complete\"){const l=setTimeout(()=>{i||(e(),i=!0)},t);s.addEventListener(\"load\",()=>{clearTimeout(l),i=!0,e()});return}const o=\"about:blank\";if(r.location.href!==o||s.src===o||s.src===\"\")return setTimeout(e,0),s.addEventListener(\"load\",e);s.addEventListener(\"load\",e)}function Aa(s,e,t){let r=!1,i;try{i=s.sheet}catch(o){return}if(i)return;const n=setTimeout(()=>{r||(e(),r=!0)},t);s.addEventListener(\"load\",()=>{clearTimeout(n),r=!0,e()})}function Ma(s,e){const{doc:t,mirror:r,blockClass:i,blockSelector:n,needsMask:o,inlineStylesheet:l,maskInputOptions:a={},maskTextFn:u,maskInputFn:c,dataURLOptions:h={},inlineImages:d,recordCanvas:m,keepIframeSrcFn:g,newlyAddedElement:p=!1,cssCaptured:f=!1}=e,S=Ea(t,r);switch(s.nodeType){case s.DOCUMENT_NODE:return s.compatMode!==\"CSS1Compat\"?{type:j.Document,childNodes:[],compatMode:s.compatMode}:{type:j.Document,childNodes:[]};case s.DOCUMENT_TYPE_NODE:return{type:j.DocumentType,name:s.name,publicId:s.publicId,systemId:s.systemId,rootId:S};case s.ELEMENT_NODE:return Na(s,{doc:t,blockClass:i,blockSelector:n,inlineStylesheet:l,maskInputOptions:a,maskInputFn:c,dataURLOptions:h,inlineImages:d,recordCanvas:m,keepIframeSrcFn:g,newlyAddedElement:p,rootId:S});case s.TEXT_NODE:return $a(s,{doc:t,needsMask:o,maskTextFn:u,rootId:S,cssCaptured:f});case s.CDATA_SECTION_NODE:return{type:j.CDATA,textContent:\"\",rootId:S};case s.COMMENT_NODE:return{type:j.Comment,textContent:Z.textContent(s)||\"\",rootId:S};default:return!1}}function Ea(s,e){if(!e.hasNode(s))return;const t=e.getId(s);return t===1?void 0:t}function $a(s,e){const{needsMask:t,maskTextFn:r,rootId:i,cssCaptured:n}=e,o=Z.parentNode(s),l=o&&o.tagName;let a=\"\";const u=l===\"STYLE\"?!0:void 0,c=l===\"SCRIPT\"?!0:void 0;return c?a=\"SCRIPT_PLACEHOLDER\":n||(a=Z.textContent(s),u&&a&&(a=Wt(a,ps(e.doc)))),!u&&!c&&a&&t&&(a=r?r(a,Z.parentElement(s)):a.replace(/[\\\\S]/g,\"*\")),{type:j.Text,textContent:a||\"\",rootId:i}}function Na(s,e){const{doc:t,blockClass:r,blockSelector:i,inlineStylesheet:n,maskInputOptions:o={},maskInputFn:l,dataURLOptions:a={},inlineImages:u,recordCanvas:c,keepIframeSrcFn:h,newlyAddedElement:d=!1,rootId:m}=e,g=Oa(s,r,i),p=ba(s);let f={};const S=s.attributes.length;for(let y=0;y<S;y++){const C=s.attributes[y];Ji(p,C.name,C.value)||(f[C.name]=Zi(t,p,Ce(C.name),C.value))}if(p===\"link\"&&n){const y=Array.from(t.styleSheets).find(N=>N.href===s.href);let C=null;y&&(C=$r(y)),C&&(delete f.rel,delete f.href,f._cssText=C)}if(p===\"style\"&&s.sheet){let y=$r(s.sheet);y&&(s.childNodes.length>1&&(y=ya(y,s)),f._cssText=y)}if(p===\"input\"||p===\"textarea\"||p===\"select\"){const y=s.value,C=s.checked;f.type!==\"radio\"&&f.type!==\"checkbox\"&&f.type!==\"submit\"&&f.type!==\"button\"&&y?f.value=hs({element:s,type:fs(s),tagName:p,value:y,maskInputOptions:o,maskInputFn:l}):C&&(f.checked=C)}if(p===\"option\"&&(s.selected&&!o.select?f.selected=!0:delete f.selected),p===\"dialog\"&&s.open&&(f.rr_open_mode=s.matches(\"dialog:modal\")?\"modal\":\"non-modal\"),p===\"canvas\"&&c){if(s.__context===\"2d\")ca(s)||(f.rr_dataURL=s.toDataURL(a.type,a.quality));else if(!(\"__context\"in s)){const y=s.toDataURL(a.type,a.quality),C=t.createElement(\"canvas\");C.width=s.width,C.height=s.height;const N=C.toDataURL(a.type,a.quality);y!==N&&(f.rr_dataURL=y)}}if(p===\"img\"&&u){Oe||(Oe=t.createElement(\"canvas\"),Zs=Oe.getContext(\"2d\"));const y=s,C=y.currentSrc||y.getAttribute(\"src\")||\"<unknown-src>\",N=y.crossOrigin,D=()=>{y.removeEventListener(\"load\",D);try{Oe.width=y.naturalWidth,Oe.height=y.naturalHeight,Zs.drawImage(y,0,0),f.rr_dataURL=Oe.toDataURL(a.type,a.quality)}catch(H){if(y.crossOrigin!==\"anonymous\"){y.crossOrigin=\"anonymous\",y.complete&&y.naturalWidth!==0?D():y.addEventListener(\"load\",D);return}else console.warn(\\`Cannot inline img src=\\${C}! Error: \\${H}\\`)}y.crossOrigin===\"anonymous\"&&(N?f.crossOrigin=N:y.removeAttribute(\"crossorigin\"))};y.complete&&y.naturalWidth!==0?D():y.addEventListener(\"load\",D)}if(p===\"audio\"||p===\"video\"){const y=f;y.rr_mediaState=s.paused?\"paused\":\"played\",y.rr_mediaCurrentTime=s.currentTime,y.rr_mediaPlaybackRate=s.playbackRate,y.rr_mediaMuted=s.muted,y.rr_mediaLoop=s.loop,y.rr_mediaVolume=s.volume}if(d||(s.scrollLeft&&(f.rr_scrollLeft=s.scrollLeft),s.scrollTop&&(f.rr_scrollTop=s.scrollTop)),g){const{width:y,height:C}=s.getBoundingClientRect();f={class:f.class,rr_width:\\`\\${y}px\\`,rr_height:\\`\\${C}px\\`}}p===\"iframe\"&&!h(f.src)&&(s.contentDocument||(f.rr_src=f.src),delete f.src);let b;try{customElements.get(p)&&(b=!0)}catch(y){}return{type:j.Element,tagName:p,attributes:f,childNodes:[],isSVG:xa(s)||void 0,needBlock:g,rootId:m,isCustom:b}}function P(s){return s==null?\"\":s.toLowerCase()}function ka(s,e){if(e.comment&&s.type===j.Comment)return!0;if(s.type===j.Element){if(e.script&&(s.tagName===\"script\"||s.tagName===\"link\"&&(s.attributes.rel===\"preload\"||s.attributes.rel===\"modulepreload\")&&s.attributes.as===\"script\"||s.tagName===\"link\"&&s.attributes.rel===\"prefetch\"&&typeof s.attributes.href==\"string\"&&Hi(s.attributes.href)===\"js\"))return!0;if(e.headFavicon&&(s.tagName===\"link\"&&s.attributes.rel===\"shortcut icon\"||s.tagName===\"meta\"&&(P(s.attributes.name).match(/^msapplication-tile(image|color)$/)||P(s.attributes.name)===\"application-name\"||P(s.attributes.rel)===\"icon\"||P(s.attributes.rel)===\"apple-touch-icon\"||P(s.attributes.rel)===\"shortcut icon\")))return!0;if(s.tagName===\"meta\"){if(e.headMetaDescKeywords&&P(s.attributes.name).match(/^description|keywords$/))return!0;if(e.headMetaSocial&&(P(s.attributes.property).match(/^(og|twitter|fb):/)||P(s.attributes.name).match(/^(og|twitter):/)||P(s.attributes.name)===\"pinterest\"))return!0;if(e.headMetaRobots&&(P(s.attributes.name)===\"robots\"||P(s.attributes.name)===\"googlebot\"||P(s.attributes.name)===\"bingbot\"))return!0;if(e.headMetaHttpEquiv&&s.attributes[\"http-equiv\"]!==void 0)return!0;if(e.headMetaAuthorship&&(P(s.attributes.name)===\"author\"||P(s.attributes.name)===\"generator\"||P(s.attributes.name)===\"framework\"||P(s.attributes.name)===\"publisher\"||P(s.attributes.name)===\"progid\"||P(s.attributes.property).match(/^article:/)||P(s.attributes.property).match(/^product:/)))return!0;if(e.headMetaVerification&&(P(s.attributes.name)===\"google-site-verification\"||P(s.attributes.name)===\"yandex-verification\"||P(s.attributes.name)===\"csrf-token\"||P(s.attributes.name)===\"p:domain_verify\"||P(s.attributes.name)===\"verify-v1\"||P(s.attributes.name)===\"verification\"||P(s.attributes.name)===\"shopify-checkout-api-token\"))return!0}}return!1}function Ee(s,e){const{doc:t,mirror:r,blockClass:i,blockSelector:n,maskTextClass:o,maskTextSelector:l,skipChild:a=!1,inlineStylesheet:u=!0,maskInputOptions:c={},maskTextFn:h,maskInputFn:d,slimDOMOptions:m,dataURLOptions:g={},inlineImages:p=!1,recordCanvas:f=!1,onSerialize:S,onIframeLoad:b,iframeLoadTimeout:y=5e3,onStylesheetLoad:C,stylesheetLoadTimeout:N=5e3,keepIframeSrcFn:D=()=>!1,newlyAddedElement:H=!1,cssCaptured:_=!1}=e;let{needsMask:G}=e,{preserveWhiteSpace:Y=!0}=e;G||(G=Xi(s,o,l,G===void 0));const Q=Ma(s,{doc:t,mirror:r,blockClass:i,blockSelector:n,needsMask:G,inlineStylesheet:u,maskInputOptions:c,maskTextFn:h,maskInputFn:d,dataURLOptions:g,inlineImages:p,recordCanvas:f,keepIframeSrcFn:D,newlyAddedElement:H,cssCaptured:_});if(!Q)return console.warn(s,\"not serialized\"),null;let oe;r.hasNode(s)?oe=r.getId(s):ka(Q,m)||!Y&&Q.type===j.Text&&!Q.textContent.replace(/^\\\\s+|\\\\s+$/gm,\"\").length?oe=Ze:oe=Yi();const A=Object.assign(Q,{id:oe});if(r.add(s,A),oe===Ze)return null;S&&S(s);let Ue=!a;if(A.type===j.Element){Ue=Ue&&!A.needBlock,delete A.needBlock;const V=Z.shadowRoot(s);V&&He(V)&&(A.isShadowHost=!0)}if((A.type===j.Document||A.type===j.Element)&&Ue){m.headWhitespace&&A.type===j.Element&&A.tagName===\"head\"&&(Y=!1);const V={doc:t,mirror:r,blockClass:i,blockSelector:n,needsMask:G,maskTextClass:o,maskTextSelector:l,skipChild:a,inlineStylesheet:u,maskInputOptions:c,maskTextFn:h,maskInputFn:d,slimDOMOptions:m,dataURLOptions:g,inlineImages:p,recordCanvas:f,preserveWhiteSpace:Y,onSerialize:S,onIframeLoad:b,iframeLoadTimeout:y,onStylesheetLoad:C,stylesheetLoadTimeout:N,keepIframeSrcFn:D,cssCaptured:!1};if(!(A.type===j.Element&&A.tagName===\"textarea\"&&A.attributes.value!==void 0)){A.type===j.Element&&A.attributes._cssText!==void 0&&typeof A.attributes._cssText==\"string\"&&(V.cssCaptured=!0);for(const ye of Array.from(Z.childNodes(s))){const ae=Ee(ye,V);ae&&A.childNodes.push(ae)}}let q=null;if(Gi(s)&&(q=Z.shadowRoot(s)))for(const ye of Array.from(Z.childNodes(q))){const ae=Ee(ye,V);ae&&(He(q)&&(ae.isShadow=!0),A.childNodes.push(ae))}}const Be=Z.parentNode(s);return Be&&je(Be)&&He(Be)&&(A.isShadow=!0),A.type===j.Element&&A.tagName===\"iframe\"&&Ra(s,()=>{const V=s.contentDocument;if(V&&b){const q=Ee(V,{doc:V,mirror:r,blockClass:i,blockSelector:n,needsMask:G,maskTextClass:o,maskTextSelector:l,skipChild:!1,inlineStylesheet:u,maskInputOptions:c,maskTextFn:h,maskInputFn:d,slimDOMOptions:m,dataURLOptions:g,inlineImages:p,recordCanvas:f,preserveWhiteSpace:Y,onSerialize:S,onIframeLoad:b,iframeLoadTimeout:y,onStylesheetLoad:C,stylesheetLoadTimeout:N,keepIframeSrcFn:D});q&&b(s,q)}},y),A.type===j.Element&&A.tagName===\"link\"&&typeof A.attributes.rel==\"string\"&&(A.attributes.rel===\"stylesheet\"||A.attributes.rel===\"preload\"&&typeof A.attributes.href==\"string\"&&Hi(A.attributes.href)===\"css\")&&Aa(s,()=>{if(C){const V=Ee(s,{doc:t,mirror:r,blockClass:i,blockSelector:n,needsMask:G,maskTextClass:o,maskTextSelector:l,skipChild:!1,inlineStylesheet:u,maskInputOptions:c,maskTextFn:h,maskInputFn:d,slimDOMOptions:m,dataURLOptions:g,inlineImages:p,recordCanvas:f,preserveWhiteSpace:Y,onSerialize:S,onIframeLoad:b,iframeLoadTimeout:y,onStylesheetLoad:C,stylesheetLoadTimeout:N,keepIframeSrcFn:D});V&&C(s,V)}},N),A}function Pa(s,e){const{mirror:t=new ji,blockClass:r=\"rr-block\",blockSelector:i=null,maskTextClass:n=\"rr-mask\",maskTextSelector:o=null,inlineStylesheet:l=!0,inlineImages:a=!1,recordCanvas:u=!1,maskAllInputs:c=!1,maskTextFn:h,maskInputFn:d,slimDOM:m=!1,dataURLOptions:g,preserveWhiteSpace:p,onSerialize:f,onIframeLoad:S,iframeLoadTimeout:b,onStylesheetLoad:y,stylesheetLoadTimeout:C,keepIframeSrcFn:N=()=>!1}=e||{};return Ee(s,{doc:s,mirror:t,blockClass:r,blockSelector:i,maskTextClass:n,maskTextSelector:o,skipChild:!1,inlineStylesheet:l,maskInputOptions:c===!0?{color:!0,date:!0,\"datetime-local\":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:c===!1?{password:!0}:c,maskTextFn:h,maskInputFn:d,slimDOMOptions:m===!0||m===\"all\"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaDescKeywords:m===\"all\",headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaAuthorship:!0,headMetaVerification:!0}:m===!1?{}:m,dataURLOptions:g,inlineImages:a,recordCanvas:u,preserveWhiteSpace:p,onSerialize:f,onIframeLoad:S,iframeLoadTimeout:b,onStylesheetLoad:y,stylesheetLoadTimeout:C,keepIframeSrcFn:N,newlyAddedElement:!1})}function Da(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,\"default\")?s.default:s}function La(s){if(s.__esModule)return s;var e=s.default;if(typeof e==\"function\"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,\"__esModule\",{value:!0}),Object.keys(s).forEach(function(r){var i=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return s[r]}})}),t}var ds={exports:{}},L=String,Ki=function(){return{isColorSupported:!1,reset:L,bold:L,dim:L,italic:L,underline:L,inverse:L,hidden:L,strikethrough:L,black:L,red:L,green:L,yellow:L,blue:L,magenta:L,cyan:L,white:L,gray:L,bgBlack:L,bgRed:L,bgGreen:L,bgYellow:L,bgBlue:L,bgMagenta:L,bgCyan:L,bgWhite:L}};ds.exports=Ki();ds.exports.createColors=Ki;var Ta=ds.exports;const _a={},Fa=Object.freeze(Object.defineProperty({__proto__:null,default:_a},Symbol.toStringTag,{value:\"Module\"})),ie=La(Fa);let Xs=Ta,Ks=ie,Nr=class Qi extends Error{constructor(e,t,r,i,n,o){super(e),this.name=\"CssSyntaxError\",this.reason=e,n&&(this.file=n),i&&(this.source=i),o&&(this.plugin=o),typeof t!=\"undefined\"&&typeof r!=\"undefined\"&&(typeof t==\"number\"?(this.line=t,this.column=r):(this.line=t.line,this.column=t.column,this.endLine=r.line,this.endColumn=r.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,Qi)}setMessage(){this.message=this.plugin?this.plugin+\": \":\"\",this.message+=this.file?this.file:\"<css input>\",typeof this.line!=\"undefined\"&&(this.message+=\":\"+this.line+\":\"+this.column),this.message+=\": \"+this.reason}showSourceCode(e){if(!this.source)return\"\";let t=this.source;e==null&&(e=Xs.isColorSupported),Ks&&e&&(t=Ks(t));let r=t.split(/\\\\r?\\\\n/),i=Math.max(this.line-3,0),n=Math.min(this.line+2,r.length),o=String(n).length,l,a;if(e){let{bold:u,gray:c,red:h}=Xs.createColors(!0);l=d=>u(h(d)),a=d=>c(d)}else l=a=u=>u;return r.slice(i,n).map((u,c)=>{let h=i+1+c,d=\" \"+(\" \"+h).slice(-o)+\" | \";if(h===this.line){let m=a(d.replace(/\\\\d/g,\" \"))+u.slice(0,this.column-1).replace(/[^\\\\t]/g,\" \");return l(\">\")+a(d)+u+\\`\n \\`+m+l(\"^\")}return\" \"+a(d)+u}).join(\\`\n\\`)}toString(){let e=this.showSourceCode();return e&&(e=\\`\n\n\\`+e+\\`\n\\`),this.name+\": \"+this.message+e}};var ms=Nr;Nr.default=Nr;var it={};it.isClean=Symbol(\"isClean\");it.my=Symbol(\"my\");const Qs={after:\\`\n\\`,beforeClose:\\`\n\\`,beforeComment:\\`\n\\`,beforeDecl:\\`\n\\`,beforeOpen:\" \",beforeRule:\\`\n\\`,colon:\": \",commentLeft:\" \",commentRight:\" \",emptyBody:\"\",indent:\"    \",semicolon:!1};function Ua(s){return s[0].toUpperCase()+s.slice(1)}let kr=class{constructor(e){this.builder=e}atrule(e,t){let r=\"@\"+e.name,i=e.params?this.rawValue(e,\"params\"):\"\";if(typeof e.raws.afterName!=\"undefined\"?r+=e.raws.afterName:i&&(r+=\" \"),e.nodes)this.block(e,r+i);else{let n=(e.raws.between||\"\")+(t?\";\":\"\");this.builder(r+i+n,e)}}beforeAfter(e,t){let r;e.type===\"decl\"?r=this.raw(e,null,\"beforeDecl\"):e.type===\"comment\"?r=this.raw(e,null,\"beforeComment\"):t===\"before\"?r=this.raw(e,null,\"beforeRule\"):r=this.raw(e,null,\"beforeClose\");let i=e.parent,n=0;for(;i&&i.type!==\"root\";)n+=1,i=i.parent;if(r.includes(\\`\n\\`)){let o=this.raw(e,null,\"indent\");if(o.length)for(let l=0;l<n;l++)r+=o}return r}block(e,t){let r=this.raw(e,\"between\",\"beforeOpen\");this.builder(t+r+\"{\",e,\"start\");let i;e.nodes&&e.nodes.length?(this.body(e),i=this.raw(e,\"after\")):i=this.raw(e,\"after\",\"emptyBody\"),i&&this.builder(i),this.builder(\"}\",e,\"end\")}body(e){let t=e.nodes.length-1;for(;t>0&&e.nodes[t].type===\"comment\";)t-=1;let r=this.raw(e,\"semicolon\");for(let i=0;i<e.nodes.length;i++){let n=e.nodes[i],o=this.raw(n,\"before\");o&&this.builder(o),this.stringify(n,t!==i||r)}}comment(e){let t=this.raw(e,\"left\",\"commentLeft\"),r=this.raw(e,\"right\",\"commentRight\");this.builder(\"/*\"+t+e.text+r+\"*/\",e)}decl(e,t){let r=this.raw(e,\"between\",\"colon\"),i=e.prop+r+this.rawValue(e,\"value\");e.important&&(i+=e.raws.important||\" !important\"),t&&(i+=\";\"),this.builder(i,e)}document(e){this.body(e)}raw(e,t,r){let i;if(r||(r=t),t&&(i=e.raws[t],typeof i!=\"undefined\"))return i;let n=e.parent;if(r===\"before\"&&(!n||n.type===\"root\"&&n.first===e||n&&n.type===\"document\"))return\"\";if(!n)return Qs[r];let o=e.root();if(o.rawCache||(o.rawCache={}),typeof o.rawCache[r]!=\"undefined\")return o.rawCache[r];if(r===\"before\"||r===\"after\")return this.beforeAfter(e,r);{let l=\"raw\"+Ua(r);this[l]?i=this[l](o,e):o.walk(a=>{if(i=a.raws[t],typeof i!=\"undefined\")return!1})}return typeof i==\"undefined\"&&(i=Qs[r]),o.rawCache[r]=i,i}rawBeforeClose(e){let t;return e.walk(r=>{if(r.nodes&&r.nodes.length>0&&typeof r.raws.after!=\"undefined\")return t=r.raws.after,t.includes(\\`\n\\`)&&(t=t.replace(/[^\\\\n]+$/,\"\")),!1}),t&&(t=t.replace(/\\\\S/g,\"\")),t}rawBeforeComment(e,t){let r;return e.walkComments(i=>{if(typeof i.raws.before!=\"undefined\")return r=i.raws.before,r.includes(\\`\n\\`)&&(r=r.replace(/[^\\\\n]+$/,\"\")),!1}),typeof r==\"undefined\"?r=this.raw(t,null,\"beforeDecl\"):r&&(r=r.replace(/\\\\S/g,\"\")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(i=>{if(typeof i.raws.before!=\"undefined\")return r=i.raws.before,r.includes(\\`\n\\`)&&(r=r.replace(/[^\\\\n]+$/,\"\")),!1}),typeof r==\"undefined\"?r=this.raw(t,null,\"beforeRule\"):r&&(r=r.replace(/\\\\S/g,\"\")),r}rawBeforeOpen(e){let t;return e.walk(r=>{if(r.type!==\"decl\"&&(t=r.raws.between,typeof t!=\"undefined\"))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&typeof r.raws.before!=\"undefined\")return t=r.raws.before,t.includes(\\`\n\\`)&&(t=t.replace(/[^\\\\n]+$/,\"\")),!1}),t&&(t=t.replace(/\\\\S/g,\"\")),t}rawColon(e){let t;return e.walkDecls(r=>{if(typeof r.raws.between!=\"undefined\")return t=r.raws.between.replace(/[^\\\\s:]/g,\"\"),!1}),t}rawEmptyBody(e){let t;return e.walk(r=>{if(r.nodes&&r.nodes.length===0&&(t=r.raws.after,typeof t!=\"undefined\"))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let i=r.parent;if(i&&i!==e&&i.parent&&i.parent===e&&typeof r.raws.before!=\"undefined\"){let n=r.raws.before.split(\\`\n\\`);return t=n[n.length-1],t=t.replace(/\\\\S/g,\"\"),!1}}),t}rawSemicolon(e){let t;return e.walk(r=>{if(r.nodes&&r.nodes.length&&r.last.type===\"decl\"&&(t=r.raws.semicolon,typeof t!=\"undefined\"))return!1}),t}rawValue(e,t){let r=e[t],i=e.raws[t];return i&&i.value===r?i.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,\"selector\")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,\"end\")}stringify(e,t){if(!this[e.type])throw new Error(\"Unknown AST node type \"+e.type+\". Maybe you need to change PostCSS stringifier.\");this[e.type](e,t)}};var qi=kr;kr.default=kr;let Ba=qi;function Pr(s,e){new Ba(e).stringify(s)}var tr=Pr;Pr.default=Pr;let{isClean:dt,my:za}=it,Wa=ms,Ga=qi,Va=tr;function Dr(s,e){let t=new s.constructor;for(let r in s){if(!Object.prototype.hasOwnProperty.call(s,r)||r===\"proxyCache\")continue;let i=s[r],n=typeof i;r===\"parent\"&&n===\"object\"?e&&(t[r]=e):r===\"source\"?t[r]=i:Array.isArray(i)?t[r]=i.map(o=>Dr(o,t)):(n===\"object\"&&i!==null&&(i=Dr(i)),t[r]=i)}return t}let Lr=class{constructor(e={}){this.raws={},this[dt]=!1,this[za]=!0;for(let t in e)if(t===\"nodes\"){this.nodes=[];for(let r of e[t])typeof r.clone==\"function\"?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\\\\n\\\\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\\\\n\\\\s{4}at /,\\`$&\\${t.input.from}:\\${t.start.line}:\\${t.start.column}$&\\`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=Dr(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:i}=this.rangeBy(t);return this.source.input.error(e,{column:i.column,line:i.line},{column:r.column,line:r.line},t)}return new Wa(e)}getProxyProcessor(){return{get(e,t){return t===\"proxyOf\"?e:t===\"root\"?()=>e.root().toProxy():e[t]},set(e,t,r){return e[t]===r||(e[t]=r,(t===\"prop\"||t===\"value\"||t===\"name\"||t===\"params\"||t===\"important\"||t===\"text\")&&e.markDirty()),!0}}}markDirty(){if(this[dt]){this[dt]=!1;let e=this;for(;e=e.parent;)e[dt]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){t=this.toString();let i=t.indexOf(e.word);i!==-1&&(r=this.positionInside(i,t))}return r}positionInside(e,t){let r=t||this.toString(),i=this.source.start.column,n=this.source.start.line;for(let o=0;o<e;o++)r[o]===\\`\n\\`?(i=1,n+=1):i+=1;return{column:i,line:n}}prev(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e-1]}rangeBy(e){let t={column:this.source.start.column,line:this.source.start.line},r=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:t.column+1,line:t.line};if(e.word){let i=this.toString(),n=i.indexOf(e.word);n!==-1&&(t=this.positionInside(n,i),r=this.positionInside(n+e.word.length,i))}else e.start?t={column:e.start.column,line:e.start.line}:e.index&&(t=this.positionInside(e.index)),e.end?r={column:e.end.column,line:e.end.line}:typeof e.endIndex==\"number\"?r=this.positionInside(e.endIndex):e.index&&(r=this.positionInside(e.index+1));return(r.line<t.line||r.line===t.line&&r.column<=t.column)&&(r={column:t.column+1,line:t.line}),{end:r,start:t}}raw(e,t){return new Ga().raw(this,e,t)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...e){if(this.parent){let t=this,r=!1;for(let i of e)i===this?r=!0:r?(this.parent.insertAfter(t,i),t=i):this.parent.insertBefore(t,i);r||this.remove()}return this}root(){let e=this;for(;e.parent&&e.parent.type!==\"document\";)e=e.parent;return e}toJSON(e,t){let r={},i=t==null;t=t||new Map;let n=0;for(let o in this){if(!Object.prototype.hasOwnProperty.call(this,o)||o===\"parent\"||o===\"proxyCache\")continue;let l=this[o];if(Array.isArray(l))r[o]=l.map(a=>typeof a==\"object\"&&a.toJSON?a.toJSON(null,t):a);else if(typeof l==\"object\"&&l.toJSON)r[o]=l.toJSON(null,t);else if(o===\"source\"){let a=t.get(l.input);a==null&&(a=n,t.set(l.input,n),n++),r[o]={end:l.end,inputId:a,start:l.start}}else r[o]=l}return i&&(r.inputs=[...t.keys()].map(o=>o.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Va){e.stringify&&(e=e.stringify);let t=\"\";return e(this,r=>{t+=r}),t}warn(e,t,r){let i={node:this};for(let n in r)i[n]=r[n];return e.warn(t,i)}get proxyOf(){return this}};var rr=Lr;Lr.default=Lr;let ja=rr,Tr=class extends ja{constructor(e){e&&typeof e.value!=\"undefined\"&&typeof e.value!=\"string\"&&(e=ee(x({},e),{value:String(e.value)})),super(e),this.type=\"decl\"}get variable(){return this.prop.startsWith(\"--\")||this.prop[0]===\"$\"}};var sr=Tr;Tr.default=Tr;let Ha=\"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict\",Ya=(s,e=21)=>(t=e)=>{let r=\"\",i=t;for(;i--;)r+=s[Math.random()*s.length|0];return r},Za=(s=21)=>{let e=\"\",t=s;for(;t--;)e+=Ha[Math.random()*64|0];return e};var Ja={nanoid:Za,customAlphabet:Ya};let{SourceMapConsumer:qs,SourceMapGenerator:ei}=ie,{existsSync:Xa,readFileSync:Ka}=ie,{dirname:wr,join:Qa}=ie;function qa(s){return Buffer?Buffer.from(s,\"base64\").toString():window.atob(s)}let _r=class{constructor(e,t){if(t.map===!1)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,\"data:\");let r=t.map?t.map.prev:void 0,i=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=wr(this.mapFile)),i&&(this.text=i)}consumer(){return this.consumerCache||(this.consumerCache=new qs(this.text)),this.consumerCache}decodeInline(e){let t=/^data:application\\\\/json;charset=utf-?8;base64,/,r=/^data:application\\\\/json;base64,/,i=/^data:application\\\\/json;charset=utf-?8,/,n=/^data:application\\\\/json,/;if(i.test(e)||n.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(t.test(e)||r.test(e))return qa(e.substr(RegExp.lastMatch.length));let o=e.match(/data:application\\\\/json;([^,]+),/)[1];throw new Error(\"Unsupported source map encoding \"+o)}getAnnotationURL(e){return e.replace(/^\\\\/\\\\*\\\\s*# sourceMappingURL=/,\"\").trim()}isMap(e){return typeof e!=\"object\"?!1:typeof e.mappings==\"string\"||typeof e._mappings==\"string\"||Array.isArray(e.sections)}loadAnnotation(e){let t=e.match(/\\\\/\\\\*\\\\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),i=e.indexOf(\"*/\",r);r>-1&&i>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,i)))}loadFile(e){if(this.root=wr(e),Xa(e))return this.mapFile=e,Ka(e,\"utf-8\").toString().trim()}loadMap(e,t){if(t===!1)return!1;if(t){if(typeof t==\"string\")return t;if(typeof t==\"function\"){let r=t(e);if(r){let i=this.loadFile(r);if(!i)throw new Error(\"Unable to load previous source map: \"+r.toString());return i}}else{if(t instanceof qs)return ei.fromSourceMap(t).toString();if(t instanceof ei)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error(\"Unsupported previous source map format: \"+t.toString())}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let r=this.annotation;return e&&(r=Qa(wr(e),r)),this.loadFile(r)}}}startWith(e,t){return e?e.substr(0,t.length)===t:!1}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var en=_r;_r.default=_r;let{SourceMapConsumer:el,SourceMapGenerator:tl}=ie,{fileURLToPath:ti,pathToFileURL:mt}=ie,{isAbsolute:Fr,resolve:Ur}=ie,{nanoid:rl}=Ja,Sr=ie,ri=ms,sl=en,br=Symbol(\"fromOffsetCache\"),il=!!(el&&tl),si=!!(Ur&&Fr),Vt=class{constructor(e,t={}){if(e===null||typeof e==\"undefined\"||typeof e==\"object\"&&!e.toString)throw new Error(\\`PostCSS received \\${e} instead of CSS string\\`);if(this.css=e.toString(),this.css[0]===\"\\\\uFEFF\"||this.css[0]===\"\\\\uFFFE\"?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!si||/^\\\\w+:\\\\/\\\\//.test(t.from)||Fr(t.from)?this.file=t.from:this.file=Ur(t.from)),si&&il){let r=new sl(this.css,t);if(r.text){this.map=r;let i=r.consumer().file;!this.file&&i&&(this.file=this.mapResolve(i))}}this.file||(this.id=\"<input css \"+rl(6)+\">\"),this.map&&(this.map.file=this.from)}error(e,t,r,i={}){let n,o,l;if(t&&typeof t==\"object\"){let u=t,c=r;if(typeof u.offset==\"number\"){let h=this.fromOffset(u.offset);t=h.line,r=h.col}else t=u.line,r=u.column;if(typeof c.offset==\"number\"){let h=this.fromOffset(c.offset);o=h.line,l=h.col}else o=c.line,l=c.column}else if(!r){let u=this.fromOffset(t);t=u.line,r=u.col}let a=this.origin(t,r,o,l);return a?n=new ri(e,a.endLine===void 0?a.line:{column:a.column,line:a.line},a.endLine===void 0?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,i.plugin):n=new ri(e,o===void 0?t:{column:r,line:t},o===void 0?r:{column:l,line:o},this.css,this.file,i.plugin),n.input={column:r,endColumn:l,endLine:o,line:t,source:this.css},this.file&&(mt&&(n.input.url=mt(this.file).toString()),n.input.file=this.file),n}fromOffset(e){let t,r;if(this[br])r=this[br];else{let n=this.css.split(\\`\n\\`);r=new Array(n.length);let o=0;for(let l=0,a=n.length;l<a;l++)r[l]=o,o+=n[l].length+1;this[br]=r}t=r[r.length-1];let i=0;if(e>=t)i=r.length-1;else{let n=r.length-2,o;for(;i<n;)if(o=i+(n-i>>1),e<r[o])n=o-1;else if(e>=r[o+1])i=o+1;else{i=o;break}}return{col:e-r[i]+1,line:i+1}}mapResolve(e){return/^\\\\w+:\\\\/\\\\//.test(e)?e:Ur(this.map.consumer().sourceRoot||this.map.root||\".\",e)}origin(e,t,r,i){if(!this.map)return!1;let n=this.map.consumer(),o=n.originalPositionFor({column:t,line:e});if(!o.source)return!1;let l;typeof r==\"number\"&&(l=n.originalPositionFor({column:i,line:r}));let a;Fr(o.source)?a=mt(o.source):a=new URL(o.source,this.map.consumer().sourceRoot||mt(this.map.mapFile));let u={column:o.column,endColumn:l&&l.column,endLine:l&&l.line,line:o.line,url:a.toString()};if(a.protocol===\"file:\")if(ti)u.file=ti(a);else throw new Error(\"file: protocol is not available in this PostCSS build\");let c=n.sourceContentFor(o.source);return c&&(u.source=c),u}toJSON(){let e={};for(let t of[\"hasBOM\",\"css\",\"file\",\"id\"])this[t]!=null&&(e[t]=this[t]);return this.map&&(e.map=x({},this.map),e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var ir=Vt;Vt.default=Vt;Sr&&Sr.registerInput&&Sr.registerInput(Vt);let{SourceMapConsumer:tn,SourceMapGenerator:Tt}=ie,{dirname:_t,relative:rn,resolve:sn,sep:nn}=ie,{pathToFileURL:ii}=ie,nl=ir,ol=!!(tn&&Tt),al=!!(_t&&sn&&rn&&nn),ll=class{constructor(e,t,r,i){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=i,this.originalCSS=i,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;this.isInline()?e=\"data:application/json;base64,\"+this.toBase64(this.map.toString()):typeof this.mapOpts.annotation==\"string\"?e=this.mapOpts.annotation:typeof this.mapOpts.annotation==\"function\"?e=this.mapOpts.annotation(this.opts.to,this.root):e=this.outputFile()+\".map\";let t=\\`\n\\`;this.css.includes(\\`\\\\r\n\\`)&&(t=\\`\\\\r\n\\`),this.css+=t+\"/*# sourceMappingURL=\"+e+\" */\"}applyPrevMaps(){for(let e of this.previous()){let t=this.toUrl(this.path(e.file)),r=e.root||_t(e.file),i;this.mapOpts.sourcesContent===!1?(i=new tn(e.text),i.sourcesContent&&(i.sourcesContent=null)):i=e.consumer(),this.map.applySourceMap(i,t,this.toUrl(this.path(r)))}}clearAnnotation(){if(this.mapOpts.annotation!==!1)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],e.type===\"comment\"&&e.text.indexOf(\"# sourceMappingURL=\")===0&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\\\\n*?\\\\/\\\\*#[\\\\S\\\\s]*?\\\\*\\\\/$/gm,\"\"))}generate(){if(this.clearAnnotation(),al&&ol&&this.isMap())return this.generateMap();{let e=\"\";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(this.previous().length===1){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=Tt.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Tt({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):\"<no source>\"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css=\"\",this.map=new Tt({file:this.outputFile(),ignoreInvalidMapping:!0});let e=1,t=1,r=\"<no source>\",i={generated:{column:0,line:0},original:{column:0,line:0},source:\"\"},n,o;this.stringify(this.root,(l,a,u)=>{if(this.css+=l,a&&u!==\"end\"&&(i.generated.line=e,i.generated.column=t-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=r,i.original.line=1,i.original.column=0,this.map.addMapping(i))),n=l.match(/\\\\n/g),n?(e+=n.length,o=l.lastIndexOf(\\`\n\\`),t=l.length-o):t+=l.length,a&&u!==\"start\"){let c=a.parent||{raws:{}};(!(a.type===\"decl\"||a.type===\"atrule\"&&!a.nodes)||a!==c.last||c.raws.semicolon)&&(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=e,i.generated.column=t-2,this.map.addMapping(i)):(i.source=r,i.original.line=1,i.original.column=0,i.generated.line=e,i.generated.column=t-1,this.map.addMapping(i)))}})}isAnnotation(){return this.isInline()?!0:typeof this.mapOpts.annotation!=\"undefined\"?this.mapOpts.annotation:this.previous().length?this.previous().some(e=>e.annotation):!0}isInline(){if(typeof this.mapOpts.inline!=\"undefined\")return this.mapOpts.inline;let e=this.mapOpts.annotation;return typeof e!=\"undefined\"&&e!==!0?!1:this.previous().length?this.previous().some(t=>t.inline):!0}isMap(){return typeof this.opts.map!=\"undefined\"?!!this.opts.map:this.previous().length>0}isSourcesContent(){return typeof this.mapOpts.sourcesContent!=\"undefined\"?this.mapOpts.sourcesContent:this.previous().length?this.previous().some(e=>e.withContent()):!0}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):\"to.css\"}path(e){if(this.mapOpts.absolute||e.charCodeAt(0)===60||/^\\\\w+:\\\\/\\\\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?_t(this.opts.to):\".\";typeof this.mapOpts.annotation==\"string\"&&(r=_t(sn(r,this.mapOpts.annotation)));let i=rn(r,e);return this.memoizedPaths.set(e,i),i}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new nl(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let i=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(i,t.source.input.css)}}});else if(this.css){let t=this.opts.from?this.toUrl(this.path(this.opts.from)):\"<no source>\";this.map.setSourceContent(t,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString(\"base64\"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(ii){let r=ii(e).toString();return this.memoizedFileURLs.set(e,r),r}else throw new Error(\"\\`map.absolute\\` option is not available in this PostCSS build\")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;nn===\"\\\\\\\\\"&&(e=e.replace(/\\\\\\\\/g,\"/\"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};var on=ll;let ul=rr,Br=class extends ul{constructor(e){super(e),this.type=\"comment\"}};var nr=Br;Br.default=Br;let{isClean:an,my:ln}=it,un=sr,cn=nr,cl=rr,hn,gs,ys,fn;function pn(s){return s.map(e=>(e.nodes&&(e.nodes=pn(e.nodes)),delete e.source,e))}function dn(s){if(s[an]=!1,s.proxyOf.nodes)for(let e of s.proxyOf.nodes)dn(e)}let fe=class mn extends cl{append(...e){for(let t of e){let r=this.normalize(t,this.last);for(let i of r)this.proxyOf.nodes.push(i)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t=this.getIterator(),r,i;for(;this.indexes[t]<this.proxyOf.nodes.length&&(r=this.indexes[t],i=e(this.proxyOf.nodes[r],r),i!==!1);)this.indexes[t]+=1;return delete this.indexes[t],i}every(e){return this.nodes.every(e)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}getProxyProcessor(){return{get(e,t){return t===\"proxyOf\"?e:e[t]?t===\"each\"||typeof t==\"string\"&&t.startsWith(\"walk\")?(...r)=>e[t](...r.map(i=>typeof i==\"function\"?(n,o)=>i(n.toProxy(),o):i)):t===\"every\"||t===\"some\"?r=>e[t]((i,...n)=>r(i.toProxy(),...n)):t===\"root\"?()=>e.root().toProxy():t===\"nodes\"?e.nodes.map(r=>r.toProxy()):t===\"first\"||t===\"last\"?e[t].toProxy():e[t]:e[t]},set(e,t,r){return e[t]===r||(e[t]=r,(t===\"name\"||t===\"params\"||t===\"selector\")&&e.markDirty()),!0}}}index(e){return typeof e==\"number\"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r=this.index(e),i=this.normalize(t,this.proxyOf.nodes[r]).reverse();r=this.index(e);for(let o of i)this.proxyOf.nodes.splice(r+1,0,o);let n;for(let o in this.indexes)n=this.indexes[o],r<n&&(this.indexes[o]=n+i.length);return this.markDirty(),this}insertBefore(e,t){let r=this.index(e),i=r===0?\"prepend\":!1,n=this.normalize(t,this.proxyOf.nodes[r],i).reverse();r=this.index(e);for(let l of n)this.proxyOf.nodes.splice(r,0,l);let o;for(let l in this.indexes)o=this.indexes[l],r<=o&&(this.indexes[l]=o+n.length);return this.markDirty(),this}normalize(e,t){if(typeof e==\"string\")e=pn(hn(e).nodes);else if(typeof e==\"undefined\")e=[];else if(Array.isArray(e)){e=e.slice(0);for(let i of e)i.parent&&i.parent.removeChild(i,\"ignore\")}else if(e.type===\"root\"&&this.type!==\"document\"){e=e.nodes.slice(0);for(let i of e)i.parent&&i.parent.removeChild(i,\"ignore\")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value==\"undefined\")throw new Error(\"Value field is missed in node creation\");typeof e.value!=\"string\"&&(e.value=String(e.value)),e=[new un(e)]}else if(e.selector)e=[new gs(e)];else if(e.name)e=[new ys(e)];else if(e.text)e=[new cn(e)];else throw new Error(\"Unknown node type in node creation\");return e.map(i=>(i[ln]||mn.rebuild(i),i=i.proxyOf,i.parent&&i.parent.removeChild(i),i[an]&&dn(i),typeof i.raws.before==\"undefined\"&&t&&typeof t.raws.before!=\"undefined\"&&(i.raws.before=t.raws.before.replace(/\\\\S/g,\"\")),i.parent=this.proxyOf,i))}prepend(...e){e=e.reverse();for(let t of e){let r=this.normalize(t,this.first,\"prepend\").reverse();for(let i of r)this.proxyOf.nodes.unshift(i);for(let i in this.indexes)this.indexes[i]=this.indexes[i]+r.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);let t;for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(i=>{t.props&&!t.props.includes(i.prop)||t.fast&&!i.value.includes(t.fast)||(i.value=i.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let i;try{i=e(t,r)}catch(n){throw t.addToError(n)}return i!==!1&&t.walk&&(i=t.walk(e)),i})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,i)=>{if(r.type===\"atrule\"&&e.test(r.name))return t(r,i)}):this.walk((r,i)=>{if(r.type===\"atrule\"&&r.name===e)return t(r,i)}):(t=e,this.walk((r,i)=>{if(r.type===\"atrule\")return t(r,i)}))}walkComments(e){return this.walk((t,r)=>{if(t.type===\"comment\")return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,i)=>{if(r.type===\"decl\"&&e.test(r.prop))return t(r,i)}):this.walk((r,i)=>{if(r.type===\"decl\"&&r.prop===e)return t(r,i)}):(t=e,this.walk((r,i)=>{if(r.type===\"decl\")return t(r,i)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,i)=>{if(r.type===\"rule\"&&e.test(r.selector))return t(r,i)}):this.walk((r,i)=>{if(r.type===\"rule\"&&r.selector===e)return t(r,i)}):(t=e,this.walk((r,i)=>{if(r.type===\"rule\")return t(r,i)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};fe.registerParse=s=>{hn=s};fe.registerRule=s=>{gs=s};fe.registerAtRule=s=>{ys=s};fe.registerRoot=s=>{fn=s};var ve=fe;fe.default=fe;fe.rebuild=s=>{s.type===\"atrule\"?Object.setPrototypeOf(s,ys.prototype):s.type===\"rule\"?Object.setPrototypeOf(s,gs.prototype):s.type===\"decl\"?Object.setPrototypeOf(s,un.prototype):s.type===\"comment\"?Object.setPrototypeOf(s,cn.prototype):s.type===\"root\"&&Object.setPrototypeOf(s,fn.prototype),s[ln]=!0,s.nodes&&s.nodes.forEach(e=>{fe.rebuild(e)})};let hl=ve,gn,yn,Je=class extends hl{constructor(e){super(x({type:\"document\"},e)),this.nodes||(this.nodes=[])}toResult(e={}){return new gn(new yn,this,e).stringify()}};Je.registerLazyResult=s=>{gn=s};Je.registerProcessor=s=>{yn=s};var ws=Je;Je.default=Je;let zr=class{constructor(e,t={}){if(this.type=\"warning\",this.text=e,t.node&&t.node.source){let r=t.node.rangeBy(t);this.line=r.start.line,this.column=r.start.column,this.endLine=r.end.line,this.endColumn=r.end.column}for(let r in t)this[r]=t[r]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+\": \"+this.text:this.text}};var wn=zr;zr.default=zr;let fl=wn,Wr=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new fl(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>e.type===\"warning\")}get content(){return this.css}};var Ss=Wr;Wr.default=Wr;const Cr=39,ni=34,gt=92,oi=47,yt=10,ze=32,wt=12,St=9,bt=13,pl=91,dl=93,ml=40,gl=41,yl=123,wl=125,Sl=59,bl=42,Cl=58,vl=64,Ct=/[\\\\t\\\\n\\\\f\\\\r \"#'()/;[\\\\\\\\\\\\]{}]/g,vt=/[\\\\t\\\\n\\\\f\\\\r !\"#'():;@[\\\\\\\\\\\\]{}]|\\\\/(?=\\\\*)/g,Il=/.[\\\\r\\\\n\"'(/\\\\\\\\]/,ai=/[\\\\da-f]/i;var xl=function(e,t={}){let r=e.css.valueOf(),i=t.ignoreErrors,n,o,l,a,u,c,h,d,m,g,p=r.length,f=0,S=[],b=[];function y(){return f}function C(_){throw e.error(\"Unclosed \"+_,f)}function N(){return b.length===0&&f>=p}function D(_){if(b.length)return b.pop();if(f>=p)return;let G=_?_.ignoreUnclosed:!1;switch(n=r.charCodeAt(f),n){case yt:case ze:case St:case bt:case wt:{o=f;do o+=1,n=r.charCodeAt(o);while(n===ze||n===yt||n===St||n===bt||n===wt);g=[\"space\",r.slice(f,o)],f=o-1;break}case pl:case dl:case yl:case wl:case Cl:case Sl:case gl:{let Y=String.fromCharCode(n);g=[Y,Y,f];break}case ml:{if(d=S.length?S.pop()[1]:\"\",m=r.charCodeAt(f+1),d===\"url\"&&m!==Cr&&m!==ni&&m!==ze&&m!==yt&&m!==St&&m!==wt&&m!==bt){o=f;do{if(c=!1,o=r.indexOf(\")\",o+1),o===-1)if(i||G){o=f;break}else C(\"bracket\");for(h=o;r.charCodeAt(h-1)===gt;)h-=1,c=!c}while(c);g=[\"brackets\",r.slice(f,o+1),f,o],f=o}else o=r.indexOf(\")\",f+1),a=r.slice(f,o+1),o===-1||Il.test(a)?g=[\"(\",\"(\",f]:(g=[\"brackets\",a,f,o],f=o);break}case Cr:case ni:{l=n===Cr?\"'\":'\"',o=f;do{if(c=!1,o=r.indexOf(l,o+1),o===-1)if(i||G){o=f+1;break}else C(\"string\");for(h=o;r.charCodeAt(h-1)===gt;)h-=1,c=!c}while(c);g=[\"string\",r.slice(f,o+1),f,o],f=o;break}case vl:{Ct.lastIndex=f+1,Ct.test(r),Ct.lastIndex===0?o=r.length-1:o=Ct.lastIndex-2,g=[\"at-word\",r.slice(f,o+1),f,o],f=o;break}case gt:{for(o=f,u=!0;r.charCodeAt(o+1)===gt;)o+=1,u=!u;if(n=r.charCodeAt(o+1),u&&n!==oi&&n!==ze&&n!==yt&&n!==St&&n!==bt&&n!==wt&&(o+=1,ai.test(r.charAt(o)))){for(;ai.test(r.charAt(o+1));)o+=1;r.charCodeAt(o+1)===ze&&(o+=1)}g=[\"word\",r.slice(f,o+1),f,o],f=o;break}default:{n===oi&&r.charCodeAt(f+1)===bl?(o=r.indexOf(\"*/\",f+2)+1,o===0&&(i||G?o=r.length:C(\"comment\")),g=[\"comment\",r.slice(f,o+1),f,o],f=o):(vt.lastIndex=f+1,vt.test(r),vt.lastIndex===0?o=r.length-1:o=vt.lastIndex-2,g=[\"word\",r.slice(f,o+1),f,o],S.push(g),f=o);break}}return f++,g}function H(_){b.push(_)}return{back:H,endOfFile:N,nextToken:D,position:y}};let Sn=ve,jt=class extends Sn{constructor(e){super(e),this.type=\"atrule\"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var bs=jt;jt.default=jt;Sn.registerAtRule(jt);let bn=ve,Cn,vn,Ne=class extends bn{constructor(e){super(e),this.type=\"root\",this.nodes||(this.nodes=[])}normalize(e,t,r){let i=super.normalize(e);if(t){if(r===\"prepend\")this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let n of i)n.raws.before=t.raws.before}return i}removeChild(e,t){let r=this.index(e);return!t&&r===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new Cn(new vn,this,e).stringify()}};Ne.registerLazyResult=s=>{Cn=s};Ne.registerProcessor=s=>{vn=s};var nt=Ne;Ne.default=Ne;bn.registerRoot(Ne);let Xe={comma(s){return Xe.split(s,[\",\"],!0)},space(s){let e=[\" \",\\`\n\\`,\"\t\"];return Xe.split(s,e)},split(s,e,t){let r=[],i=\"\",n=!1,o=0,l=!1,a=\"\",u=!1;for(let c of s)u?u=!1:c===\"\\\\\\\\\"?u=!0:l?c===a&&(l=!1):c==='\"'||c===\"'\"?(l=!0,a=c):c===\"(\"?o+=1:c===\")\"?o>0&&(o-=1):o===0&&e.includes(c)&&(n=!0),n?(i!==\"\"&&r.push(i.trim()),i=\"\",n=!1):i+=c;return(t||i!==\"\")&&r.push(i.trim()),r}};var In=Xe;Xe.default=Xe;let xn=ve,Ol=In,Ht=class extends xn{constructor(e){super(e),this.type=\"rule\",this.nodes||(this.nodes=[])}get selectors(){return Ol.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\\\\s*/):null,r=t?t[0]:\",\"+this.raw(\"between\",\"beforeOpen\");this.selector=e.join(r)}};var Cs=Ht;Ht.default=Ht;xn.registerRule(Ht);let Rl=sr,Al=xl,Ml=nr,El=bs,$l=nt,li=Cs;const ui={empty:!0,space:!0};function Nl(s){for(let e=s.length-1;e>=0;e--){let t=s[e],r=t[3]||t[2];if(r)return r}}let kl=class{constructor(e){this.input=e,this.root=new $l,this.current=this.root,this.spaces=\"\",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t=new El;t.name=e[1].slice(1),t.name===\"\"&&this.unnamedAtrule(t,e),this.init(t,e[2]);let r,i,n,o=!1,l=!1,a=[],u=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),r=e[0],r===\"(\"||r===\"[\"?u.push(r===\"(\"?\")\":\"]\"):r===\"{\"&&u.length>0?u.push(\"}\"):r===u[u.length-1]&&u.pop(),u.length===0)if(r===\";\"){t.source.end=this.getPosition(e[2]),t.source.end.offset++,this.semicolon=!0;break}else if(r===\"{\"){l=!0;break}else if(r===\"}\"){if(a.length>0){for(n=a.length-1,i=a[n];i&&i[0]===\"space\";)i=a[--n];i&&(t.source.end=this.getPosition(i[3]||i[2]),t.source.end.offset++)}this.end(e);break}else a.push(e);else a.push(e);if(this.tokenizer.endOfFile()){o=!0;break}}t.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(t.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(t,\"params\",a),o&&(e=a[a.length-1],t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++,this.spaces=t.raws.between,t.raws.between=\"\")):(t.raws.afterName=\"\",t.params=\"\"),l&&(t.nodes=[],this.current=t)}checkMissedSemicolon(e){let t=this.colon(e);if(t===!1)return;let r=0,i;for(let n=t-1;n>=0&&(i=e[n],!(i[0]!==\"space\"&&(r+=1,r===2)));n--);throw this.input.error(\"Missed semicolon\",i[0]===\"word\"?i[3]+1:i[2])}colon(e){let t=0,r,i,n;for(let[o,l]of e.entries()){if(r=l,i=r[0],i===\"(\"&&(t+=1),i===\")\"&&(t-=1),t===0&&i===\":\")if(!n)this.doubleColon(r);else{if(n[0]===\"word\"&&n[1]===\"progid\")continue;return o}n=r}return!1}comment(e){let t=new Ml;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\\\\s*$/.test(r))t.text=\"\",t.raws.left=r,t.raws.right=\"\";else{let i=r.match(/^(\\\\s*)([^]*\\\\S)(\\\\s*)$/);t.text=i[2],t.raws.left=i[1],t.raws.right=i[3]}}createTokenizer(){this.tokenizer=Al(this.input)}decl(e,t){let r=new Rl;this.init(r,e[0][2]);let i=e[e.length-1];for(i[0]===\";\"&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(i[3]||i[2]||Nl(e)),r.source.end.offset++;e[0][0]!==\"word\";)e.length===1&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop=\"\";e.length;){let u=e[0][0];if(u===\":\"||u===\"space\"||u===\"comment\")break;r.prop+=e.shift()[1]}r.raws.between=\"\";let n;for(;e.length;)if(n=e.shift(),n[0]===\":\"){r.raws.between+=n[1];break}else n[0]===\"word\"&&/\\\\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1];(r.prop[0]===\"_\"||r.prop[0]===\"*\")&&(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let o=[],l;for(;e.length&&(l=e[0][0],!(l!==\"space\"&&l!==\"comment\"));)o.push(e.shift());this.precheckMissedSemicolon(e);for(let u=e.length-1;u>=0;u--){if(n=e[u],n[1].toLowerCase()===\"!important\"){r.important=!0;let c=this.stringFrom(e,u);c=this.spacesFromEnd(e)+c,c!==\" !important\"&&(r.raws.important=c);break}else if(n[1].toLowerCase()===\"important\"){let c=e.slice(0),h=\"\";for(let d=u;d>0;d--){let m=c[d][0];if(h.trim().indexOf(\"!\")===0&&m!==\"space\")break;h=c.pop()[1]+h}h.trim().indexOf(\"!\")===0&&(r.important=!0,r.raws.important=h,e=c)}if(n[0]!==\"space\"&&n[0]!==\"comment\")break}e.some(u=>u[0]!==\"space\"&&u[0]!==\"comment\")&&(r.raws.between+=o.map(u=>u[1]).join(\"\"),o=[]),this.raw(r,\"value\",o.concat(e),t),r.value.includes(\":\")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error(\"Double colon\",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new li;this.init(t,e[2]),t.selector=\"\",t.raws.between=\"\",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||\"\")+this.spaces,this.spaces=\"\",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||\"\")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let t=this.current.nodes[this.current.nodes.length-1];t&&t.type===\"rule\"&&!t.raws.ownSemicolon&&(t.raws.ownSemicolon=this.spaces,this.spaces=\"\")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces=\"\",e.type!==\"comment\"&&(this.semicolon=!1)}other(e){let t=!1,r=null,i=!1,n=null,o=[],l=e[1].startsWith(\"--\"),a=[],u=e;for(;u;){if(r=u[0],a.push(u),r===\"(\"||r===\"[\")n||(n=u),o.push(r===\"(\"?\")\":\"]\");else if(l&&i&&r===\"{\")n||(n=u),o.push(\"}\");else if(o.length===0)if(r===\";\")if(i){this.decl(a,l);return}else break;else if(r===\"{\"){this.rule(a);return}else if(r===\"}\"){this.tokenizer.back(a.pop()),t=!0;break}else r===\":\"&&(i=!0);else r===o[o.length-1]&&(o.pop(),o.length===0&&(n=null));u=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),o.length>0&&this.unclosedBracket(n),t&&i){if(!l)for(;a.length&&(u=a[a.length-1][0],!(u!==\"space\"&&u!==\"comment\"));)this.tokenizer.back(a.pop());this.decl(a,l)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case\"space\":this.spaces+=e[1];break;case\";\":this.freeSemicolon(e);break;case\"}\":this.end(e);break;case\"comment\":this.comment(e);break;case\"at-word\":this.atrule(e);break;case\"{\":this.emptyRule(e);break;default:this.other(e);break}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,i){let n,o,l=r.length,a=\"\",u=!0,c,h;for(let d=0;d<l;d+=1)n=r[d],o=n[0],o===\"space\"&&d===l-1&&!i?u=!1:o===\"comment\"?(h=r[d-1]?r[d-1][0]:\"empty\",c=r[d+1]?r[d+1][0]:\"empty\",!ui[h]&&!ui[c]?a.slice(-1)===\",\"?u=!1:a+=n[1]:u=!1):a+=n[1];if(!u){let d=r.reduce((m,g)=>m+g[1],\"\");e.raws[t]={raw:d,value:a}}e[t]=a}rule(e){e.pop();let t=new li;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,\"selector\",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r=\"\";for(;e.length&&(t=e[e.length-1][0],!(t!==\"space\"&&t!==\"comment\"));)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r=\"\";for(;e.length&&(t=e[0][0],!(t!==\"space\"&&t!==\"comment\"));)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r=\"\";for(;e.length&&(t=e[e.length-1][0],t===\"space\");)r=e.pop()[1]+r;return r}stringFrom(e,t){let r=\"\";for(let i=t;i<e.length;i++)r+=e[i][1];return e.splice(t,e.length-t),r}unclosedBlock(){let e=this.current.source.start;throw this.input.error(\"Unclosed block\",e.line,e.column)}unclosedBracket(e){throw this.input.error(\"Unclosed bracket\",{offset:e[2]},{offset:e[2]+1})}unexpectedClose(e){throw this.input.error(\"Unexpected }\",{offset:e[2]},{offset:e[2]+1})}unknownWord(e){throw this.input.error(\"Unknown word\",{offset:e[0][2]},{offset:e[0][2]+e[0][1].length})}unnamedAtrule(e,t){throw this.input.error(\"At-rule without name\",{offset:t[2]},{offset:t[2]+t[1].length})}};var Pl=kl;let Dl=ve,Ll=Pl,Tl=ir;function Yt(s,e){let t=new Tl(s,e),r=new Ll(t);try{r.parse()}catch(i){throw i}return r.root}var vs=Yt;Yt.default=Yt;Dl.registerParse(Yt);let{isClean:ue,my:_l}=it,Fl=on,Ul=tr,Bl=ve,zl=ws;let ci=Ss,Wl=vs,Gl=nt;const Vl={atrule:\"AtRule\",comment:\"Comment\",decl:\"Declaration\",document:\"Document\",root:\"Root\",rule:\"Rule\"},jl={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},Hl={Once:!0,postcssPlugin:!0,prepare:!0},ke=0;function We(s){return typeof s==\"object\"&&typeof s.then==\"function\"}function On(s){let e=!1,t=Vl[s.type];return s.type===\"decl\"?e=s.prop.toLowerCase():s.type===\"atrule\"&&(e=s.name.toLowerCase()),e&&s.append?[t,t+\"-\"+e,ke,t+\"Exit\",t+\"Exit-\"+e]:e?[t,t+\"-\"+e,t+\"Exit\",t+\"Exit-\"+e]:s.append?[t,ke,t+\"Exit\"]:[t,t+\"Exit\"]}function hi(s){let e;return s.type===\"document\"?e=[\"Document\",ke,\"DocumentExit\"]:s.type===\"root\"?e=[\"Root\",ke,\"RootExit\"]:e=On(s),{eventIndex:0,events:e,iterator:0,node:s,visitorIndex:0,visitors:[]}}function Gr(s){return s[ue]=!1,s.nodes&&s.nodes.forEach(e=>Gr(e)),s}let Vr={},Pe=class Rn{constructor(e,t,r){this.stringified=!1,this.processed=!1;let i;if(typeof t==\"object\"&&t!==null&&(t.type===\"root\"||t.type===\"document\"))i=Gr(t);else if(t instanceof Rn||t instanceof ci)i=Gr(t.root),t.map&&(typeof r.map==\"undefined\"&&(r.map={}),r.map.inline||(r.map.inline=!1),r.map.prev=t.map);else{let n=Wl;r.syntax&&(n=r.syntax.parse),r.parser&&(n=r.parser),n.parse&&(n=n.parse);try{i=n(t,r)}catch(o){this.processed=!0,this.error=o}i&&!i[_l]&&Bl.rebuild(i)}this.result=new ci(e,i,r),this.helpers=ee(x({},Vr),{postcss:Vr,result:this.result}),this.plugins=this.processor.plugins.map(n=>typeof n==\"object\"&&n.prepare?x(x({},n),n.prepare(this.result)):n)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error(\"Use process(css).then(cb) to work with async plugins\")}handleError(e,t){let r=this.result.lastPlugin;try{t&&t.addToError(e),this.error=e,e.name===\"CssSyntaxError\"&&!e.plugin?(e.plugin=r.postcssPlugin,e.setMessage()):r.postcssVersion}catch(i){console&&console.error&&console.error(i)}return e}prepareVisitors(){this.listeners={};let e=(t,r,i)=>{this.listeners[r]||(this.listeners[r]=[]),this.listeners[r].push([t,i])};for(let t of this.plugins)if(typeof t==\"object\")for(let r in t){if(!jl[r]&&/^[A-Z]/.test(r))throw new Error(\\`Unknown event \\${r} in \\${t.postcssPlugin}. Try to update PostCSS (\\${this.processor.version} now).\\`);if(!Hl[r])if(typeof t[r]==\"object\")for(let i in t[r])i===\"*\"?e(t,r,t[r][i]):e(t,r+\"-\"+i.toLowerCase(),t[r][i]);else typeof t[r]==\"function\"&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e<this.plugins.length;e++){let t=this.plugins[e],r=this.runOnRoot(t);if(We(r))try{await r}catch(i){throw this.handleError(i)}}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[ue];){e[ue]=!0;let t=[hi(e)];for(;t.length>0;){let r=this.visitTick(t);if(We(r))try{await r}catch(i){let n=t[t.length-1].node;throw this.handleError(i,n)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if(e.type===\"document\"){let i=e.nodes.map(n=>r(n,this.helpers));await Promise.all(i)}else await r(e,this.helpers)}catch(i){throw this.handleError(i)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if(typeof e==\"object\"&&e.Once){if(this.result.root.type===\"document\"){let t=this.result.root.nodes.map(r=>e.Once(r,this.helpers));return We(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}else if(typeof e==\"function\")return e(this.result.root,this.result)}catch(t){throw this.handleError(t)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=Ul;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let i=new Fl(t,this.result.root,this.result.opts).generate();return this.result.css=i[0],this.result.map=i[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){let t=this.runOnRoot(e);if(We(t))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[ue];)e[ue]=!0,this.walkSync(e);if(this.listeners.OnceExit)if(e.type===\"document\")for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,i]of e){this.result.lastPlugin=r;let n;try{n=i(t,this.helpers)}catch(o){throw this.handleError(o,t.proxyOf)}if(t.type!==\"root\"&&t.type!==\"document\"&&!t.parent)return!0;if(We(n))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:i}=t;if(r.type!==\"root\"&&r.type!==\"document\"&&!r.parent){e.pop();return}if(i.length>0&&t.visitorIndex<i.length){let[o,l]=i[t.visitorIndex];t.visitorIndex+=1,t.visitorIndex===i.length&&(t.visitors=[],t.visitorIndex=0),this.result.lastPlugin=o;try{return l(r.toProxy(),this.helpers)}catch(a){throw this.handleError(a,r)}}if(t.iterator!==0){let o=t.iterator,l;for(;l=r.nodes[r.indexes[o]];)if(r.indexes[o]+=1,!l[ue]){l[ue]=!0,e.push(hi(l));return}t.iterator=0,delete r.indexes[o]}let n=t.events;for(;t.eventIndex<n.length;){let o=n[t.eventIndex];if(t.eventIndex+=1,o===ke){r.nodes&&r.nodes.length&&(r[ue]=!0,t.iterator=r.getIterator());return}else if(this.listeners[o]){t.visitors=this.listeners[o];return}}e.pop()}walkSync(e){e[ue]=!0;let t=On(e);for(let r of t)if(r===ke)e.nodes&&e.each(i=>{i[ue]||this.walkSync(i)});else{let i=this.listeners[r];if(i&&this.visitSync(i,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return\"LazyResult\"}};Pe.registerPostcss=s=>{Vr=s};var An=Pe;Pe.default=Pe;Gl.registerLazyResult(Pe);zl.registerLazyResult(Pe);let Yl=on,Zl=tr;let Jl=vs;const Xl=Ss;let jr=class{constructor(e,t,r){t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let i,n=Zl;this.result=new Xl(this._processor,i,this._opts),this.result.css=t;let o=this;Object.defineProperty(this.result,\"root\",{get(){return o.root}});let l=new Yl(n,i,this._opts,t);if(l.isMap()){let[a,u]=l.generate();a&&(this.result.css=a),u&&(this.result.map=u)}else l.clearAnnotation(),this.result.css=l.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=Jl;try{e=t(this._css,this._opts)}catch(r){this.error=r}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return\"NoWorkResult\"}};var Kl=jr;jr.default=jr;let Ql=Kl,ql=An,eu=ws,tu=nt,Ke=class{constructor(e=[]){this.version=\"8.4.38\",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(r.postcss===!0?r=r():r.postcss&&(r=r.postcss),typeof r==\"object\"&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if(typeof r==\"object\"&&r.postcssPlugin)t.push(r);else if(typeof r==\"function\")t.push(r);else if(!(typeof r==\"object\"&&(r.parse||r.stringify)))throw new Error(r+\" is not a PostCSS plugin\");return t}process(e,t={}){return!this.plugins.length&&!t.parser&&!t.stringifier&&!t.syntax?new Ql(this,e,t):new ql(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var ru=Ke;Ke.default=Ke;tu.registerProcessor(Ke);eu.registerProcessor(Ke);let su=sr,iu=en,nu=nr,ou=bs,au=ir,lu=nt,uu=Cs;function Qe(s,e){if(Array.isArray(s))return s.map(o=>Qe(o));let i=s,{inputs:t}=i,r=xe(i,[\"inputs\"]);if(t){e=[];for(let o of t){let l=ee(x({},o),{__proto__:au.prototype});l.map&&(l.map=ee(x({},l.map),{__proto__:iu.prototype})),e.push(l)}}if(r.nodes&&(r.nodes=s.nodes.map(o=>Qe(o,e))),r.source){let n=r.source,{inputId:o}=n,l=xe(n,[\"inputId\"]);r.source=l,o!=null&&(r.source.input=e[o])}if(r.type===\"root\")return new lu(r);if(r.type===\"decl\")return new su(r);if(r.type===\"rule\")return new uu(r);if(r.type===\"comment\")return new nu(r);if(r.type===\"atrule\")return new ou(r);throw new Error(\"Unknown node type: \"+s.type)}var cu=Qe;Qe.default=Qe;let hu=ms,Mn=sr,fu=An,pu=ve,Is=ru,du=tr,mu=cu,En=ws,gu=wn,$n=nr,Nn=bs,yu=Ss,wu=ir,Su=vs,bu=In,kn=Cs,Pn=nt,Cu=rr;function E(...s){return s.length===1&&Array.isArray(s[0])&&(s=s[0]),new Is(s)}E.plugin=function(e,t){let r=!1;function i(...o){console&&console.warn&&!r&&(r=!0,console.warn(e+\\`: postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration\\`),process.env.LANG&&process.env.LANG.startsWith(\"cn\")&&console.warn(e+\\`: \\\\u91CC\\\\u9762 postcss.plugin \\\\u88AB\\\\u5F03\\\\u7528. \\\\u8FC1\\\\u79FB\\\\u6307\\\\u5357:\nhttps://www.w3ctech.com/topic/2226\\`));let l=t(...o);return l.postcssPlugin=e,l.postcssVersion=new Is().version,l}let n;return Object.defineProperty(i,\"postcss\",{get(){return n||(n=i()),n}}),i.process=function(o,l,a){return E([i(a)]).process(o,l)},i};E.stringify=du;E.parse=Su;E.fromJSON=mu;E.list=bu;E.comment=s=>new $n(s);E.atRule=s=>new Nn(s);E.decl=s=>new Mn(s);E.rule=s=>new kn(s);E.root=s=>new Pn(s);E.document=s=>new En(s);E.CssSyntaxError=hu;E.Declaration=Mn;E.Container=pu;E.Processor=Is;E.Document=En;E.Comment=$n;E.Warning=gu;E.AtRule=Nn;E.Result=yu;E.Input=wu;E.Rule=kn;E.Root=Pn;E.Node=Cu;fu.registerPostcss(E);var vu=E;E.default=E;const F=Da(vu);F.stringify;F.fromJSON;F.plugin;F.parse;F.list;F.document;F.comment;F.atRule;F.rule;F.decl;F.root;F.CssSyntaxError;F.Declaration;F.Container;F.Processor;F.Document;F.Comment;F.Warning;F.AtRule;F.Result;F.Input;F.Rule;F.Root;F.Node;var Iu=Object.defineProperty,xu=(s,e,t)=>e in s?Iu(s,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):s[e]=t,te=(s,e,t)=>xu(s,typeof e!=\"symbol\"?e+\"\":e,t);function Ou(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,\"default\")?s.default:s}function Ru(s){if(s.__esModule)return s;var e=s.default;if(typeof e==\"function\"){var t=function r(){return this instanceof r?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};t.prototype=e.prototype}else t={};return Object.defineProperty(t,\"__esModule\",{value:!0}),Object.keys(s).forEach(function(r){var i=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:function(){return s[r]}})}),t}var xs={exports:{}},T=String,Dn=function(){return{isColorSupported:!1,reset:T,bold:T,dim:T,italic:T,underline:T,inverse:T,hidden:T,strikethrough:T,black:T,red:T,green:T,yellow:T,blue:T,magenta:T,cyan:T,white:T,gray:T,bgBlack:T,bgRed:T,bgGreen:T,bgYellow:T,bgBlue:T,bgMagenta:T,bgCyan:T,bgWhite:T}};xs.exports=Dn();xs.exports.createColors=Dn;var Au=xs.exports;const Mu={},Eu=Object.freeze(Object.defineProperty({__proto__:null,default:Mu},Symbol.toStringTag,{value:\"Module\"})),ne=Ru(Eu);let fi=Au,pi=ne,Hr=class Ln extends Error{constructor(e,t,r,i,n,o){super(e),this.name=\"CssSyntaxError\",this.reason=e,n&&(this.file=n),i&&(this.source=i),o&&(this.plugin=o),typeof t!=\"undefined\"&&typeof r!=\"undefined\"&&(typeof t==\"number\"?(this.line=t,this.column=r):(this.line=t.line,this.column=t.column,this.endLine=r.line,this.endColumn=r.column)),this.setMessage(),Error.captureStackTrace&&Error.captureStackTrace(this,Ln)}setMessage(){this.message=this.plugin?this.plugin+\": \":\"\",this.message+=this.file?this.file:\"<css input>\",typeof this.line!=\"undefined\"&&(this.message+=\":\"+this.line+\":\"+this.column),this.message+=\": \"+this.reason}showSourceCode(e){if(!this.source)return\"\";let t=this.source;e==null&&(e=fi.isColorSupported),pi&&e&&(t=pi(t));let r=t.split(/\\\\r?\\\\n/),i=Math.max(this.line-3,0),n=Math.min(this.line+2,r.length),o=String(n).length,l,a;if(e){let{bold:u,gray:c,red:h}=fi.createColors(!0);l=d=>u(h(d)),a=d=>c(d)}else l=a=u=>u;return r.slice(i,n).map((u,c)=>{let h=i+1+c,d=\" \"+(\" \"+h).slice(-o)+\" | \";if(h===this.line){let m=a(d.replace(/\\\\d/g,\" \"))+u.slice(0,this.column-1).replace(/[^\\\\t]/g,\" \");return l(\">\")+a(d)+u+\\`\n \\`+m+l(\"^\")}return\" \"+a(d)+u}).join(\\`\n\\`)}toString(){let e=this.showSourceCode();return e&&(e=\\`\n\n\\`+e+\\`\n\\`),this.name+\": \"+this.message+e}};var Os=Hr;Hr.default=Hr;var ot={};ot.isClean=Symbol(\"isClean\");ot.my=Symbol(\"my\");const di={after:\\`\n\\`,beforeClose:\\`\n\\`,beforeComment:\\`\n\\`,beforeDecl:\\`\n\\`,beforeOpen:\" \",beforeRule:\\`\n\\`,colon:\": \",commentLeft:\" \",commentRight:\" \",emptyBody:\"\",indent:\"    \",semicolon:!1};function $u(s){return s[0].toUpperCase()+s.slice(1)}let Yr=class{constructor(e){this.builder=e}atrule(e,t){let r=\"@\"+e.name,i=e.params?this.rawValue(e,\"params\"):\"\";if(typeof e.raws.afterName!=\"undefined\"?r+=e.raws.afterName:i&&(r+=\" \"),e.nodes)this.block(e,r+i);else{let n=(e.raws.between||\"\")+(t?\";\":\"\");this.builder(r+i+n,e)}}beforeAfter(e,t){let r;e.type===\"decl\"?r=this.raw(e,null,\"beforeDecl\"):e.type===\"comment\"?r=this.raw(e,null,\"beforeComment\"):t===\"before\"?r=this.raw(e,null,\"beforeRule\"):r=this.raw(e,null,\"beforeClose\");let i=e.parent,n=0;for(;i&&i.type!==\"root\";)n+=1,i=i.parent;if(r.includes(\\`\n\\`)){let o=this.raw(e,null,\"indent\");if(o.length)for(let l=0;l<n;l++)r+=o}return r}block(e,t){let r=this.raw(e,\"between\",\"beforeOpen\");this.builder(t+r+\"{\",e,\"start\");let i;e.nodes&&e.nodes.length?(this.body(e),i=this.raw(e,\"after\")):i=this.raw(e,\"after\",\"emptyBody\"),i&&this.builder(i),this.builder(\"}\",e,\"end\")}body(e){let t=e.nodes.length-1;for(;t>0&&e.nodes[t].type===\"comment\";)t-=1;let r=this.raw(e,\"semicolon\");for(let i=0;i<e.nodes.length;i++){let n=e.nodes[i],o=this.raw(n,\"before\");o&&this.builder(o),this.stringify(n,t!==i||r)}}comment(e){let t=this.raw(e,\"left\",\"commentLeft\"),r=this.raw(e,\"right\",\"commentRight\");this.builder(\"/*\"+t+e.text+r+\"*/\",e)}decl(e,t){let r=this.raw(e,\"between\",\"colon\"),i=e.prop+r+this.rawValue(e,\"value\");e.important&&(i+=e.raws.important||\" !important\"),t&&(i+=\";\"),this.builder(i,e)}document(e){this.body(e)}raw(e,t,r){let i;if(r||(r=t),t&&(i=e.raws[t],typeof i!=\"undefined\"))return i;let n=e.parent;if(r===\"before\"&&(!n||n.type===\"root\"&&n.first===e||n&&n.type===\"document\"))return\"\";if(!n)return di[r];let o=e.root();if(o.rawCache||(o.rawCache={}),typeof o.rawCache[r]!=\"undefined\")return o.rawCache[r];if(r===\"before\"||r===\"after\")return this.beforeAfter(e,r);{let l=\"raw\"+$u(r);this[l]?i=this[l](o,e):o.walk(a=>{if(i=a.raws[t],typeof i!=\"undefined\")return!1})}return typeof i==\"undefined\"&&(i=di[r]),o.rawCache[r]=i,i}rawBeforeClose(e){let t;return e.walk(r=>{if(r.nodes&&r.nodes.length>0&&typeof r.raws.after!=\"undefined\")return t=r.raws.after,t.includes(\\`\n\\`)&&(t=t.replace(/[^\\\\n]+$/,\"\")),!1}),t&&(t=t.replace(/\\\\S/g,\"\")),t}rawBeforeComment(e,t){let r;return e.walkComments(i=>{if(typeof i.raws.before!=\"undefined\")return r=i.raws.before,r.includes(\\`\n\\`)&&(r=r.replace(/[^\\\\n]+$/,\"\")),!1}),typeof r==\"undefined\"?r=this.raw(t,null,\"beforeDecl\"):r&&(r=r.replace(/\\\\S/g,\"\")),r}rawBeforeDecl(e,t){let r;return e.walkDecls(i=>{if(typeof i.raws.before!=\"undefined\")return r=i.raws.before,r.includes(\\`\n\\`)&&(r=r.replace(/[^\\\\n]+$/,\"\")),!1}),typeof r==\"undefined\"?r=this.raw(t,null,\"beforeRule\"):r&&(r=r.replace(/\\\\S/g,\"\")),r}rawBeforeOpen(e){let t;return e.walk(r=>{if(r.type!==\"decl\"&&(t=r.raws.between,typeof t!=\"undefined\"))return!1}),t}rawBeforeRule(e){let t;return e.walk(r=>{if(r.nodes&&(r.parent!==e||e.first!==r)&&typeof r.raws.before!=\"undefined\")return t=r.raws.before,t.includes(\\`\n\\`)&&(t=t.replace(/[^\\\\n]+$/,\"\")),!1}),t&&(t=t.replace(/\\\\S/g,\"\")),t}rawColon(e){let t;return e.walkDecls(r=>{if(typeof r.raws.between!=\"undefined\")return t=r.raws.between.replace(/[^\\\\s:]/g,\"\"),!1}),t}rawEmptyBody(e){let t;return e.walk(r=>{if(r.nodes&&r.nodes.length===0&&(t=r.raws.after,typeof t!=\"undefined\"))return!1}),t}rawIndent(e){if(e.raws.indent)return e.raws.indent;let t;return e.walk(r=>{let i=r.parent;if(i&&i!==e&&i.parent&&i.parent===e&&typeof r.raws.before!=\"undefined\"){let n=r.raws.before.split(\\`\n\\`);return t=n[n.length-1],t=t.replace(/\\\\S/g,\"\"),!1}}),t}rawSemicolon(e){let t;return e.walk(r=>{if(r.nodes&&r.nodes.length&&r.last.type===\"decl\"&&(t=r.raws.semicolon,typeof t!=\"undefined\"))return!1}),t}rawValue(e,t){let r=e[t],i=e.raws[t];return i&&i.value===r?i.raw:r}root(e){this.body(e),e.raws.after&&this.builder(e.raws.after)}rule(e){this.block(e,this.rawValue(e,\"selector\")),e.raws.ownSemicolon&&this.builder(e.raws.ownSemicolon,e,\"end\")}stringify(e,t){if(!this[e.type])throw new Error(\"Unknown AST node type \"+e.type+\". Maybe you need to change PostCSS stringifier.\");this[e.type](e,t)}};var Tn=Yr;Yr.default=Yr;let Nu=Tn;function Zr(s,e){new Nu(e).stringify(s)}var or=Zr;Zr.default=Zr;let{isClean:It,my:ku}=ot,Pu=Os,Du=Tn,Lu=or;function Jr(s,e){let t=new s.constructor;for(let r in s){if(!Object.prototype.hasOwnProperty.call(s,r)||r===\"proxyCache\")continue;let i=s[r],n=typeof i;r===\"parent\"&&n===\"object\"?e&&(t[r]=e):r===\"source\"?t[r]=i:Array.isArray(i)?t[r]=i.map(o=>Jr(o,t)):(n===\"object\"&&i!==null&&(i=Jr(i)),t[r]=i)}return t}let Xr=class{constructor(e={}){this.raws={},this[It]=!1,this[ku]=!0;for(let t in e)if(t===\"nodes\"){this.nodes=[];for(let r of e[t])typeof r.clone==\"function\"?this.append(r.clone()):this.append(r)}else this[t]=e[t]}addToError(e){if(e.postcssNode=this,e.stack&&this.source&&/\\\\n\\\\s{4}at /.test(e.stack)){let t=this.source;e.stack=e.stack.replace(/\\\\n\\\\s{4}at /,\\`$&\\${t.input.from}:\\${t.start.line}:\\${t.start.column}$&\\`)}return e}after(e){return this.parent.insertAfter(this,e),this}assign(e={}){for(let t in e)this[t]=e[t];return this}before(e){return this.parent.insertBefore(this,e),this}cleanRaws(e){delete this.raws.before,delete this.raws.after,e||delete this.raws.between}clone(e={}){let t=Jr(this);for(let r in e)t[r]=e[r];return t}cloneAfter(e={}){let t=this.clone(e);return this.parent.insertAfter(this,t),t}cloneBefore(e={}){let t=this.clone(e);return this.parent.insertBefore(this,t),t}error(e,t={}){if(this.source){let{end:r,start:i}=this.rangeBy(t);return this.source.input.error(e,{column:i.column,line:i.line},{column:r.column,line:r.line},t)}return new Pu(e)}getProxyProcessor(){return{get(e,t){return t===\"proxyOf\"?e:t===\"root\"?()=>e.root().toProxy():e[t]},set(e,t,r){return e[t]===r||(e[t]=r,(t===\"prop\"||t===\"value\"||t===\"name\"||t===\"params\"||t===\"important\"||t===\"text\")&&e.markDirty()),!0}}}markDirty(){if(this[It]){this[It]=!1;let e=this;for(;e=e.parent;)e[It]=!1}}next(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e+1]}positionBy(e,t){let r=this.source.start;if(e.index)r=this.positionInside(e.index,t);else if(e.word){t=this.toString();let i=t.indexOf(e.word);i!==-1&&(r=this.positionInside(i,t))}return r}positionInside(e,t){let r=t||this.toString(),i=this.source.start.column,n=this.source.start.line;for(let o=0;o<e;o++)r[o]===\\`\n\\`?(i=1,n+=1):i+=1;return{column:i,line:n}}prev(){if(!this.parent)return;let e=this.parent.index(this);return this.parent.nodes[e-1]}rangeBy(e){let t={column:this.source.start.column,line:this.source.start.line},r=this.source.end?{column:this.source.end.column+1,line:this.source.end.line}:{column:t.column+1,line:t.line};if(e.word){let i=this.toString(),n=i.indexOf(e.word);n!==-1&&(t=this.positionInside(n,i),r=this.positionInside(n+e.word.length,i))}else e.start?t={column:e.start.column,line:e.start.line}:e.index&&(t=this.positionInside(e.index)),e.end?r={column:e.end.column,line:e.end.line}:typeof e.endIndex==\"number\"?r=this.positionInside(e.endIndex):e.index&&(r=this.positionInside(e.index+1));return(r.line<t.line||r.line===t.line&&r.column<=t.column)&&(r={column:t.column+1,line:t.line}),{end:r,start:t}}raw(e,t){return new Du().raw(this,e,t)}remove(){return this.parent&&this.parent.removeChild(this),this.parent=void 0,this}replaceWith(...e){if(this.parent){let t=this,r=!1;for(let i of e)i===this?r=!0:r?(this.parent.insertAfter(t,i),t=i):this.parent.insertBefore(t,i);r||this.remove()}return this}root(){let e=this;for(;e.parent&&e.parent.type!==\"document\";)e=e.parent;return e}toJSON(e,t){let r={},i=t==null;t=t||new Map;let n=0;for(let o in this){if(!Object.prototype.hasOwnProperty.call(this,o)||o===\"parent\"||o===\"proxyCache\")continue;let l=this[o];if(Array.isArray(l))r[o]=l.map(a=>typeof a==\"object\"&&a.toJSON?a.toJSON(null,t):a);else if(typeof l==\"object\"&&l.toJSON)r[o]=l.toJSON(null,t);else if(o===\"source\"){let a=t.get(l.input);a==null&&(a=n,t.set(l.input,n),n++),r[o]={end:l.end,inputId:a,start:l.start}}else r[o]=l}return i&&(r.inputs=[...t.keys()].map(o=>o.toJSON())),r}toProxy(){return this.proxyCache||(this.proxyCache=new Proxy(this,this.getProxyProcessor())),this.proxyCache}toString(e=Lu){e.stringify&&(e=e.stringify);let t=\"\";return e(this,r=>{t+=r}),t}warn(e,t,r){let i={node:this};for(let n in r)i[n]=r[n];return e.warn(t,i)}get proxyOf(){return this}};var ar=Xr;Xr.default=Xr;let Tu=ar,Kr=class extends Tu{constructor(e){e&&typeof e.value!=\"undefined\"&&typeof e.value!=\"string\"&&(e=ee(x({},e),{value:String(e.value)})),super(e),this.type=\"decl\"}get variable(){return this.prop.startsWith(\"--\")||this.prop[0]===\"$\"}};var lr=Kr;Kr.default=Kr;let _u=\"useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict\",Fu=(s,e=21)=>(t=e)=>{let r=\"\",i=t;for(;i--;)r+=s[Math.random()*s.length|0];return r},Uu=(s=21)=>{let e=\"\",t=s;for(;t--;)e+=_u[Math.random()*64|0];return e};var Bu={nanoid:Uu,customAlphabet:Fu};let{SourceMapConsumer:mi,SourceMapGenerator:gi}=ne,{existsSync:zu,readFileSync:Wu}=ne,{dirname:vr,join:Gu}=ne;function Vu(s){return Buffer?Buffer.from(s,\"base64\").toString():window.atob(s)}let Qr=class{constructor(e,t){if(t.map===!1)return;this.loadAnnotation(e),this.inline=this.startWith(this.annotation,\"data:\");let r=t.map?t.map.prev:void 0,i=this.loadMap(t.from,r);!this.mapFile&&t.from&&(this.mapFile=t.from),this.mapFile&&(this.root=vr(this.mapFile)),i&&(this.text=i)}consumer(){return this.consumerCache||(this.consumerCache=new mi(this.text)),this.consumerCache}decodeInline(e){let t=/^data:application\\\\/json;charset=utf-?8;base64,/,r=/^data:application\\\\/json;base64,/,i=/^data:application\\\\/json;charset=utf-?8,/,n=/^data:application\\\\/json,/;if(i.test(e)||n.test(e))return decodeURIComponent(e.substr(RegExp.lastMatch.length));if(t.test(e)||r.test(e))return Vu(e.substr(RegExp.lastMatch.length));let o=e.match(/data:application\\\\/json;([^,]+),/)[1];throw new Error(\"Unsupported source map encoding \"+o)}getAnnotationURL(e){return e.replace(/^\\\\/\\\\*\\\\s*# sourceMappingURL=/,\"\").trim()}isMap(e){return typeof e!=\"object\"?!1:typeof e.mappings==\"string\"||typeof e._mappings==\"string\"||Array.isArray(e.sections)}loadAnnotation(e){let t=e.match(/\\\\/\\\\*\\\\s*# sourceMappingURL=/gm);if(!t)return;let r=e.lastIndexOf(t.pop()),i=e.indexOf(\"*/\",r);r>-1&&i>-1&&(this.annotation=this.getAnnotationURL(e.substring(r,i)))}loadFile(e){if(this.root=vr(e),zu(e))return this.mapFile=e,Wu(e,\"utf-8\").toString().trim()}loadMap(e,t){if(t===!1)return!1;if(t){if(typeof t==\"string\")return t;if(typeof t==\"function\"){let r=t(e);if(r){let i=this.loadFile(r);if(!i)throw new Error(\"Unable to load previous source map: \"+r.toString());return i}}else{if(t instanceof mi)return gi.fromSourceMap(t).toString();if(t instanceof gi)return t.toString();if(this.isMap(t))return JSON.stringify(t);throw new Error(\"Unsupported previous source map format: \"+t.toString())}}else{if(this.inline)return this.decodeInline(this.annotation);if(this.annotation){let r=this.annotation;return e&&(r=Gu(vr(e),r)),this.loadFile(r)}}}startWith(e,t){return e?e.substr(0,t.length)===t:!1}withContent(){return!!(this.consumer().sourcesContent&&this.consumer().sourcesContent.length>0)}};var _n=Qr;Qr.default=Qr;let{SourceMapConsumer:ju,SourceMapGenerator:Hu}=ne,{fileURLToPath:yi,pathToFileURL:xt}=ne,{isAbsolute:qr,resolve:es}=ne,{nanoid:Yu}=Bu,Ir=ne,wi=Os,Zu=_n,xr=Symbol(\"fromOffsetCache\"),Ju=!!(ju&&Hu),Si=!!(es&&qr),Zt=class{constructor(e,t={}){if(e===null||typeof e==\"undefined\"||typeof e==\"object\"&&!e.toString)throw new Error(\\`PostCSS received \\${e} instead of CSS string\\`);if(this.css=e.toString(),this.css[0]===\"\\\\uFEFF\"||this.css[0]===\"\\\\uFFFE\"?(this.hasBOM=!0,this.css=this.css.slice(1)):this.hasBOM=!1,t.from&&(!Si||/^\\\\w+:\\\\/\\\\//.test(t.from)||qr(t.from)?this.file=t.from:this.file=es(t.from)),Si&&Ju){let r=new Zu(this.css,t);if(r.text){this.map=r;let i=r.consumer().file;!this.file&&i&&(this.file=this.mapResolve(i))}}this.file||(this.id=\"<input css \"+Yu(6)+\">\"),this.map&&(this.map.file=this.from)}error(e,t,r,i={}){let n,o,l;if(t&&typeof t==\"object\"){let u=t,c=r;if(typeof u.offset==\"number\"){let h=this.fromOffset(u.offset);t=h.line,r=h.col}else t=u.line,r=u.column;if(typeof c.offset==\"number\"){let h=this.fromOffset(c.offset);o=h.line,l=h.col}else o=c.line,l=c.column}else if(!r){let u=this.fromOffset(t);t=u.line,r=u.col}let a=this.origin(t,r,o,l);return a?n=new wi(e,a.endLine===void 0?a.line:{column:a.column,line:a.line},a.endLine===void 0?a.column:{column:a.endColumn,line:a.endLine},a.source,a.file,i.plugin):n=new wi(e,o===void 0?t:{column:r,line:t},o===void 0?r:{column:l,line:o},this.css,this.file,i.plugin),n.input={column:r,endColumn:l,endLine:o,line:t,source:this.css},this.file&&(xt&&(n.input.url=xt(this.file).toString()),n.input.file=this.file),n}fromOffset(e){let t,r;if(this[xr])r=this[xr];else{let n=this.css.split(\\`\n\\`);r=new Array(n.length);let o=0;for(let l=0,a=n.length;l<a;l++)r[l]=o,o+=n[l].length+1;this[xr]=r}t=r[r.length-1];let i=0;if(e>=t)i=r.length-1;else{let n=r.length-2,o;for(;i<n;)if(o=i+(n-i>>1),e<r[o])n=o-1;else if(e>=r[o+1])i=o+1;else{i=o;break}}return{col:e-r[i]+1,line:i+1}}mapResolve(e){return/^\\\\w+:\\\\/\\\\//.test(e)?e:es(this.map.consumer().sourceRoot||this.map.root||\".\",e)}origin(e,t,r,i){if(!this.map)return!1;let n=this.map.consumer(),o=n.originalPositionFor({column:t,line:e});if(!o.source)return!1;let l;typeof r==\"number\"&&(l=n.originalPositionFor({column:i,line:r}));let a;qr(o.source)?a=xt(o.source):a=new URL(o.source,this.map.consumer().sourceRoot||xt(this.map.mapFile));let u={column:o.column,endColumn:l&&l.column,endLine:l&&l.line,line:o.line,url:a.toString()};if(a.protocol===\"file:\")if(yi)u.file=yi(a);else throw new Error(\"file: protocol is not available in this PostCSS build\");let c=n.sourceContentFor(o.source);return c&&(u.source=c),u}toJSON(){let e={};for(let t of[\"hasBOM\",\"css\",\"file\",\"id\"])this[t]!=null&&(e[t]=this[t]);return this.map&&(e.map=x({},this.map),e.map.consumerCache&&(e.map.consumerCache=void 0)),e}get from(){return this.file||this.id}};var ur=Zt;Zt.default=Zt;Ir&&Ir.registerInput&&Ir.registerInput(Zt);let{SourceMapConsumer:Fn,SourceMapGenerator:Ft}=ne,{dirname:Ut,relative:Un,resolve:Bn,sep:zn}=ne,{pathToFileURL:bi}=ne,Xu=ur,Ku=!!(Fn&&Ft),Qu=!!(Ut&&Bn&&Un&&zn),qu=class{constructor(e,t,r,i){this.stringify=e,this.mapOpts=r.map||{},this.root=t,this.opts=r,this.css=i,this.originalCSS=i,this.usesFileUrls=!this.mapOpts.from&&this.mapOpts.absolute,this.memoizedFileURLs=new Map,this.memoizedPaths=new Map,this.memoizedURLs=new Map}addAnnotation(){let e;this.isInline()?e=\"data:application/json;base64,\"+this.toBase64(this.map.toString()):typeof this.mapOpts.annotation==\"string\"?e=this.mapOpts.annotation:typeof this.mapOpts.annotation==\"function\"?e=this.mapOpts.annotation(this.opts.to,this.root):e=this.outputFile()+\".map\";let t=\\`\n\\`;this.css.includes(\\`\\\\r\n\\`)&&(t=\\`\\\\r\n\\`),this.css+=t+\"/*# sourceMappingURL=\"+e+\" */\"}applyPrevMaps(){for(let e of this.previous()){let t=this.toUrl(this.path(e.file)),r=e.root||Ut(e.file),i;this.mapOpts.sourcesContent===!1?(i=new Fn(e.text),i.sourcesContent&&(i.sourcesContent=null)):i=e.consumer(),this.map.applySourceMap(i,t,this.toUrl(this.path(r)))}}clearAnnotation(){if(this.mapOpts.annotation!==!1)if(this.root){let e;for(let t=this.root.nodes.length-1;t>=0;t--)e=this.root.nodes[t],e.type===\"comment\"&&e.text.indexOf(\"# sourceMappingURL=\")===0&&this.root.removeChild(t)}else this.css&&(this.css=this.css.replace(/\\\\n*?\\\\/\\\\*#[\\\\S\\\\s]*?\\\\*\\\\/$/gm,\"\"))}generate(){if(this.clearAnnotation(),Qu&&Ku&&this.isMap())return this.generateMap();{let e=\"\";return this.stringify(this.root,t=>{e+=t}),[e]}}generateMap(){if(this.root)this.generateString();else if(this.previous().length===1){let e=this.previous()[0].consumer();e.file=this.outputFile(),this.map=Ft.fromSourceMap(e,{ignoreInvalidMapping:!0})}else this.map=new Ft({file:this.outputFile(),ignoreInvalidMapping:!0}),this.map.addMapping({generated:{column:0,line:1},original:{column:0,line:1},source:this.opts.from?this.toUrl(this.path(this.opts.from)):\"<no source>\"});return this.isSourcesContent()&&this.setSourcesContent(),this.root&&this.previous().length>0&&this.applyPrevMaps(),this.isAnnotation()&&this.addAnnotation(),this.isInline()?[this.css]:[this.css,this.map]}generateString(){this.css=\"\",this.map=new Ft({file:this.outputFile(),ignoreInvalidMapping:!0});let e=1,t=1,r=\"<no source>\",i={generated:{column:0,line:0},original:{column:0,line:0},source:\"\"},n,o;this.stringify(this.root,(l,a,u)=>{if(this.css+=l,a&&u!==\"end\"&&(i.generated.line=e,i.generated.column=t-1,a.source&&a.source.start?(i.source=this.sourcePath(a),i.original.line=a.source.start.line,i.original.column=a.source.start.column-1,this.map.addMapping(i)):(i.source=r,i.original.line=1,i.original.column=0,this.map.addMapping(i))),n=l.match(/\\\\n/g),n?(e+=n.length,o=l.lastIndexOf(\\`\n\\`),t=l.length-o):t+=l.length,a&&u!==\"start\"){let c=a.parent||{raws:{}};(!(a.type===\"decl\"||a.type===\"atrule\"&&!a.nodes)||a!==c.last||c.raws.semicolon)&&(a.source&&a.source.end?(i.source=this.sourcePath(a),i.original.line=a.source.end.line,i.original.column=a.source.end.column-1,i.generated.line=e,i.generated.column=t-2,this.map.addMapping(i)):(i.source=r,i.original.line=1,i.original.column=0,i.generated.line=e,i.generated.column=t-1,this.map.addMapping(i)))}})}isAnnotation(){return this.isInline()?!0:typeof this.mapOpts.annotation!=\"undefined\"?this.mapOpts.annotation:this.previous().length?this.previous().some(e=>e.annotation):!0}isInline(){if(typeof this.mapOpts.inline!=\"undefined\")return this.mapOpts.inline;let e=this.mapOpts.annotation;return typeof e!=\"undefined\"&&e!==!0?!1:this.previous().length?this.previous().some(t=>t.inline):!0}isMap(){return typeof this.opts.map!=\"undefined\"?!!this.opts.map:this.previous().length>0}isSourcesContent(){return typeof this.mapOpts.sourcesContent!=\"undefined\"?this.mapOpts.sourcesContent:this.previous().length?this.previous().some(e=>e.withContent()):!0}outputFile(){return this.opts.to?this.path(this.opts.to):this.opts.from?this.path(this.opts.from):\"to.css\"}path(e){if(this.mapOpts.absolute||e.charCodeAt(0)===60||/^\\\\w+:\\\\/\\\\//.test(e))return e;let t=this.memoizedPaths.get(e);if(t)return t;let r=this.opts.to?Ut(this.opts.to):\".\";typeof this.mapOpts.annotation==\"string\"&&(r=Ut(Bn(r,this.mapOpts.annotation)));let i=Un(r,e);return this.memoizedPaths.set(e,i),i}previous(){if(!this.previousMaps)if(this.previousMaps=[],this.root)this.root.walk(e=>{if(e.source&&e.source.input.map){let t=e.source.input.map;this.previousMaps.includes(t)||this.previousMaps.push(t)}});else{let e=new Xu(this.originalCSS,this.opts);e.map&&this.previousMaps.push(e.map)}return this.previousMaps}setSourcesContent(){let e={};if(this.root)this.root.walk(t=>{if(t.source){let r=t.source.input.from;if(r&&!e[r]){e[r]=!0;let i=this.usesFileUrls?this.toFileUrl(r):this.toUrl(this.path(r));this.map.setSourceContent(i,t.source.input.css)}}});else if(this.css){let t=this.opts.from?this.toUrl(this.path(this.opts.from)):\"<no source>\";this.map.setSourceContent(t,this.css)}}sourcePath(e){return this.mapOpts.from?this.toUrl(this.mapOpts.from):this.usesFileUrls?this.toFileUrl(e.source.input.from):this.toUrl(this.path(e.source.input.from))}toBase64(e){return Buffer?Buffer.from(e).toString(\"base64\"):window.btoa(unescape(encodeURIComponent(e)))}toFileUrl(e){let t=this.memoizedFileURLs.get(e);if(t)return t;if(bi){let r=bi(e).toString();return this.memoizedFileURLs.set(e,r),r}else throw new Error(\"\\`map.absolute\\` option is not available in this PostCSS build\")}toUrl(e){let t=this.memoizedURLs.get(e);if(t)return t;zn===\"\\\\\\\\\"&&(e=e.replace(/\\\\\\\\/g,\"/\"));let r=encodeURI(e).replace(/[#?]/g,encodeURIComponent);return this.memoizedURLs.set(e,r),r}};var Wn=qu;let ec=ar,ts=class extends ec{constructor(e){super(e),this.type=\"comment\"}};var cr=ts;ts.default=ts;let{isClean:Gn,my:Vn}=ot,jn=lr,Hn=cr,tc=ar,Yn,Rs,As,Zn;function Jn(s){return s.map(e=>(e.nodes&&(e.nodes=Jn(e.nodes)),delete e.source,e))}function Xn(s){if(s[Gn]=!1,s.proxyOf.nodes)for(let e of s.proxyOf.nodes)Xn(e)}let pe=class Kn extends tc{append(...e){for(let t of e){let r=this.normalize(t,this.last);for(let i of r)this.proxyOf.nodes.push(i)}return this.markDirty(),this}cleanRaws(e){if(super.cleanRaws(e),this.nodes)for(let t of this.nodes)t.cleanRaws(e)}each(e){if(!this.proxyOf.nodes)return;let t=this.getIterator(),r,i;for(;this.indexes[t]<this.proxyOf.nodes.length&&(r=this.indexes[t],i=e(this.proxyOf.nodes[r],r),i!==!1);)this.indexes[t]+=1;return delete this.indexes[t],i}every(e){return this.nodes.every(e)}getIterator(){this.lastEach||(this.lastEach=0),this.indexes||(this.indexes={}),this.lastEach+=1;let e=this.lastEach;return this.indexes[e]=0,e}getProxyProcessor(){return{get(e,t){return t===\"proxyOf\"?e:e[t]?t===\"each\"||typeof t==\"string\"&&t.startsWith(\"walk\")?(...r)=>e[t](...r.map(i=>typeof i==\"function\"?(n,o)=>i(n.toProxy(),o):i)):t===\"every\"||t===\"some\"?r=>e[t]((i,...n)=>r(i.toProxy(),...n)):t===\"root\"?()=>e.root().toProxy():t===\"nodes\"?e.nodes.map(r=>r.toProxy()):t===\"first\"||t===\"last\"?e[t].toProxy():e[t]:e[t]},set(e,t,r){return e[t]===r||(e[t]=r,(t===\"name\"||t===\"params\"||t===\"selector\")&&e.markDirty()),!0}}}index(e){return typeof e==\"number\"?e:(e.proxyOf&&(e=e.proxyOf),this.proxyOf.nodes.indexOf(e))}insertAfter(e,t){let r=this.index(e),i=this.normalize(t,this.proxyOf.nodes[r]).reverse();r=this.index(e);for(let o of i)this.proxyOf.nodes.splice(r+1,0,o);let n;for(let o in this.indexes)n=this.indexes[o],r<n&&(this.indexes[o]=n+i.length);return this.markDirty(),this}insertBefore(e,t){let r=this.index(e),i=r===0?\"prepend\":!1,n=this.normalize(t,this.proxyOf.nodes[r],i).reverse();r=this.index(e);for(let l of n)this.proxyOf.nodes.splice(r,0,l);let o;for(let l in this.indexes)o=this.indexes[l],r<=o&&(this.indexes[l]=o+n.length);return this.markDirty(),this}normalize(e,t){if(typeof e==\"string\")e=Jn(Yn(e).nodes);else if(typeof e==\"undefined\")e=[];else if(Array.isArray(e)){e=e.slice(0);for(let i of e)i.parent&&i.parent.removeChild(i,\"ignore\")}else if(e.type===\"root\"&&this.type!==\"document\"){e=e.nodes.slice(0);for(let i of e)i.parent&&i.parent.removeChild(i,\"ignore\")}else if(e.type)e=[e];else if(e.prop){if(typeof e.value==\"undefined\")throw new Error(\"Value field is missed in node creation\");typeof e.value!=\"string\"&&(e.value=String(e.value)),e=[new jn(e)]}else if(e.selector)e=[new Rs(e)];else if(e.name)e=[new As(e)];else if(e.text)e=[new Hn(e)];else throw new Error(\"Unknown node type in node creation\");return e.map(i=>(i[Vn]||Kn.rebuild(i),i=i.proxyOf,i.parent&&i.parent.removeChild(i),i[Gn]&&Xn(i),typeof i.raws.before==\"undefined\"&&t&&typeof t.raws.before!=\"undefined\"&&(i.raws.before=t.raws.before.replace(/\\\\S/g,\"\")),i.parent=this.proxyOf,i))}prepend(...e){e=e.reverse();for(let t of e){let r=this.normalize(t,this.first,\"prepend\").reverse();for(let i of r)this.proxyOf.nodes.unshift(i);for(let i in this.indexes)this.indexes[i]=this.indexes[i]+r.length}return this.markDirty(),this}push(e){return e.parent=this,this.proxyOf.nodes.push(e),this}removeAll(){for(let e of this.proxyOf.nodes)e.parent=void 0;return this.proxyOf.nodes=[],this.markDirty(),this}removeChild(e){e=this.index(e),this.proxyOf.nodes[e].parent=void 0,this.proxyOf.nodes.splice(e,1);let t;for(let r in this.indexes)t=this.indexes[r],t>=e&&(this.indexes[r]=t-1);return this.markDirty(),this}replaceValues(e,t,r){return r||(r=t,t={}),this.walkDecls(i=>{t.props&&!t.props.includes(i.prop)||t.fast&&!i.value.includes(t.fast)||(i.value=i.value.replace(e,r))}),this.markDirty(),this}some(e){return this.nodes.some(e)}walk(e){return this.each((t,r)=>{let i;try{i=e(t,r)}catch(n){throw t.addToError(n)}return i!==!1&&t.walk&&(i=t.walk(e)),i})}walkAtRules(e,t){return t?e instanceof RegExp?this.walk((r,i)=>{if(r.type===\"atrule\"&&e.test(r.name))return t(r,i)}):this.walk((r,i)=>{if(r.type===\"atrule\"&&r.name===e)return t(r,i)}):(t=e,this.walk((r,i)=>{if(r.type===\"atrule\")return t(r,i)}))}walkComments(e){return this.walk((t,r)=>{if(t.type===\"comment\")return e(t,r)})}walkDecls(e,t){return t?e instanceof RegExp?this.walk((r,i)=>{if(r.type===\"decl\"&&e.test(r.prop))return t(r,i)}):this.walk((r,i)=>{if(r.type===\"decl\"&&r.prop===e)return t(r,i)}):(t=e,this.walk((r,i)=>{if(r.type===\"decl\")return t(r,i)}))}walkRules(e,t){return t?e instanceof RegExp?this.walk((r,i)=>{if(r.type===\"rule\"&&e.test(r.selector))return t(r,i)}):this.walk((r,i)=>{if(r.type===\"rule\"&&r.selector===e)return t(r,i)}):(t=e,this.walk((r,i)=>{if(r.type===\"rule\")return t(r,i)}))}get first(){if(this.proxyOf.nodes)return this.proxyOf.nodes[0]}get last(){if(this.proxyOf.nodes)return this.proxyOf.nodes[this.proxyOf.nodes.length-1]}};pe.registerParse=s=>{Yn=s};pe.registerRule=s=>{Rs=s};pe.registerAtRule=s=>{As=s};pe.registerRoot=s=>{Zn=s};var Ie=pe;pe.default=pe;pe.rebuild=s=>{s.type===\"atrule\"?Object.setPrototypeOf(s,As.prototype):s.type===\"rule\"?Object.setPrototypeOf(s,Rs.prototype):s.type===\"decl\"?Object.setPrototypeOf(s,jn.prototype):s.type===\"comment\"?Object.setPrototypeOf(s,Hn.prototype):s.type===\"root\"&&Object.setPrototypeOf(s,Zn.prototype),s[Vn]=!0,s.nodes&&s.nodes.forEach(e=>{pe.rebuild(e)})};let rc=Ie,Qn,qn,qe=class extends rc{constructor(e){super(x({type:\"document\"},e)),this.nodes||(this.nodes=[])}toResult(e={}){return new Qn(new qn,this,e).stringify()}};qe.registerLazyResult=s=>{Qn=s};qe.registerProcessor=s=>{qn=s};var Ms=qe;qe.default=qe;let rs=class{constructor(e,t={}){if(this.type=\"warning\",this.text=e,t.node&&t.node.source){let r=t.node.rangeBy(t);this.line=r.start.line,this.column=r.start.column,this.endLine=r.end.line,this.endColumn=r.end.column}for(let r in t)this[r]=t[r]}toString(){return this.node?this.node.error(this.text,{index:this.index,plugin:this.plugin,word:this.word}).message:this.plugin?this.plugin+\": \"+this.text:this.text}};var eo=rs;rs.default=rs;let sc=eo,ss=class{constructor(e,t,r){this.processor=e,this.messages=[],this.root=t,this.opts=r,this.css=void 0,this.map=void 0}toString(){return this.css}warn(e,t={}){t.plugin||this.lastPlugin&&this.lastPlugin.postcssPlugin&&(t.plugin=this.lastPlugin.postcssPlugin);let r=new sc(e,t);return this.messages.push(r),r}warnings(){return this.messages.filter(e=>e.type===\"warning\")}get content(){return this.css}};var Es=ss;ss.default=ss;const Or=39,Ci=34,Ot=92,vi=47,Rt=10,Ge=32,At=12,Mt=9,Et=13,ic=91,nc=93,oc=40,ac=41,lc=123,uc=125,cc=59,hc=42,fc=58,pc=64,$t=/[\\\\t\\\\n\\\\f\\\\r \"#'()/;[\\\\\\\\\\\\]{}]/g,Nt=/[\\\\t\\\\n\\\\f\\\\r !\"#'():;@[\\\\\\\\\\\\]{}]|\\\\/(?=\\\\*)/g,dc=/.[\\\\r\\\\n\"'(/\\\\\\\\]/,Ii=/[\\\\da-f]/i;var mc=function(e,t={}){let r=e.css.valueOf(),i=t.ignoreErrors,n,o,l,a,u,c,h,d,m,g,p=r.length,f=0,S=[],b=[];function y(){return f}function C(_){throw e.error(\"Unclosed \"+_,f)}function N(){return b.length===0&&f>=p}function D(_){if(b.length)return b.pop();if(f>=p)return;let G=_?_.ignoreUnclosed:!1;switch(n=r.charCodeAt(f),n){case Rt:case Ge:case Mt:case Et:case At:{o=f;do o+=1,n=r.charCodeAt(o);while(n===Ge||n===Rt||n===Mt||n===Et||n===At);g=[\"space\",r.slice(f,o)],f=o-1;break}case ic:case nc:case lc:case uc:case fc:case cc:case ac:{let Y=String.fromCharCode(n);g=[Y,Y,f];break}case oc:{if(d=S.length?S.pop()[1]:\"\",m=r.charCodeAt(f+1),d===\"url\"&&m!==Or&&m!==Ci&&m!==Ge&&m!==Rt&&m!==Mt&&m!==At&&m!==Et){o=f;do{if(c=!1,o=r.indexOf(\")\",o+1),o===-1)if(i||G){o=f;break}else C(\"bracket\");for(h=o;r.charCodeAt(h-1)===Ot;)h-=1,c=!c}while(c);g=[\"brackets\",r.slice(f,o+1),f,o],f=o}else o=r.indexOf(\")\",f+1),a=r.slice(f,o+1),o===-1||dc.test(a)?g=[\"(\",\"(\",f]:(g=[\"brackets\",a,f,o],f=o);break}case Or:case Ci:{l=n===Or?\"'\":'\"',o=f;do{if(c=!1,o=r.indexOf(l,o+1),o===-1)if(i||G){o=f+1;break}else C(\"string\");for(h=o;r.charCodeAt(h-1)===Ot;)h-=1,c=!c}while(c);g=[\"string\",r.slice(f,o+1),f,o],f=o;break}case pc:{$t.lastIndex=f+1,$t.test(r),$t.lastIndex===0?o=r.length-1:o=$t.lastIndex-2,g=[\"at-word\",r.slice(f,o+1),f,o],f=o;break}case Ot:{for(o=f,u=!0;r.charCodeAt(o+1)===Ot;)o+=1,u=!u;if(n=r.charCodeAt(o+1),u&&n!==vi&&n!==Ge&&n!==Rt&&n!==Mt&&n!==Et&&n!==At&&(o+=1,Ii.test(r.charAt(o)))){for(;Ii.test(r.charAt(o+1));)o+=1;r.charCodeAt(o+1)===Ge&&(o+=1)}g=[\"word\",r.slice(f,o+1),f,o],f=o;break}default:{n===vi&&r.charCodeAt(f+1)===hc?(o=r.indexOf(\"*/\",f+2)+1,o===0&&(i||G?o=r.length:C(\"comment\")),g=[\"comment\",r.slice(f,o+1),f,o],f=o):(Nt.lastIndex=f+1,Nt.test(r),Nt.lastIndex===0?o=r.length-1:o=Nt.lastIndex-2,g=[\"word\",r.slice(f,o+1),f,o],S.push(g),f=o);break}}return f++,g}function H(_){b.push(_)}return{back:H,endOfFile:N,nextToken:D,position:y}};let to=Ie,Jt=class extends to{constructor(e){super(e),this.type=\"atrule\"}append(...e){return this.proxyOf.nodes||(this.nodes=[]),super.append(...e)}prepend(...e){return this.proxyOf.nodes||(this.nodes=[]),super.prepend(...e)}};var $s=Jt;Jt.default=Jt;to.registerAtRule(Jt);let ro=Ie,so,io,De=class extends ro{constructor(e){super(e),this.type=\"root\",this.nodes||(this.nodes=[])}normalize(e,t,r){let i=super.normalize(e);if(t){if(r===\"prepend\")this.nodes.length>1?t.raws.before=this.nodes[1].raws.before:delete t.raws.before;else if(this.first!==t)for(let n of i)n.raws.before=t.raws.before}return i}removeChild(e,t){let r=this.index(e);return!t&&r===0&&this.nodes.length>1&&(this.nodes[1].raws.before=this.nodes[r].raws.before),super.removeChild(e)}toResult(e={}){return new so(new io,this,e).stringify()}};De.registerLazyResult=s=>{so=s};De.registerProcessor=s=>{io=s};var at=De;De.default=De;ro.registerRoot(De);let et={comma(s){return et.split(s,[\",\"],!0)},space(s){let e=[\" \",\\`\n\\`,\"\t\"];return et.split(s,e)},split(s,e,t){let r=[],i=\"\",n=!1,o=0,l=!1,a=\"\",u=!1;for(let c of s)u?u=!1:c===\"\\\\\\\\\"?u=!0:l?c===a&&(l=!1):c==='\"'||c===\"'\"?(l=!0,a=c):c===\"(\"?o+=1:c===\")\"?o>0&&(o-=1):o===0&&e.includes(c)&&(n=!0),n?(i!==\"\"&&r.push(i.trim()),i=\"\",n=!1):i+=c;return(t||i!==\"\")&&r.push(i.trim()),r}};var no=et;et.default=et;let oo=Ie,gc=no,Xt=class extends oo{constructor(e){super(e),this.type=\"rule\",this.nodes||(this.nodes=[])}get selectors(){return gc.comma(this.selector)}set selectors(e){let t=this.selector?this.selector.match(/,\\\\s*/):null,r=t?t[0]:\",\"+this.raw(\"between\",\"beforeOpen\");this.selector=e.join(r)}};var Ns=Xt;Xt.default=Xt;oo.registerRule(Xt);let yc=lr,wc=mc,Sc=cr,bc=$s,Cc=at,xi=Ns;const Oi={empty:!0,space:!0};function vc(s){for(let e=s.length-1;e>=0;e--){let t=s[e],r=t[3]||t[2];if(r)return r}}let Ic=class{constructor(e){this.input=e,this.root=new Cc,this.current=this.root,this.spaces=\"\",this.semicolon=!1,this.createTokenizer(),this.root.source={input:e,start:{column:1,line:1,offset:0}}}atrule(e){let t=new bc;t.name=e[1].slice(1),t.name===\"\"&&this.unnamedAtrule(t,e),this.init(t,e[2]);let r,i,n,o=!1,l=!1,a=[],u=[];for(;!this.tokenizer.endOfFile();){if(e=this.tokenizer.nextToken(),r=e[0],r===\"(\"||r===\"[\"?u.push(r===\"(\"?\")\":\"]\"):r===\"{\"&&u.length>0?u.push(\"}\"):r===u[u.length-1]&&u.pop(),u.length===0)if(r===\";\"){t.source.end=this.getPosition(e[2]),t.source.end.offset++,this.semicolon=!0;break}else if(r===\"{\"){l=!0;break}else if(r===\"}\"){if(a.length>0){for(n=a.length-1,i=a[n];i&&i[0]===\"space\";)i=a[--n];i&&(t.source.end=this.getPosition(i[3]||i[2]),t.source.end.offset++)}this.end(e);break}else a.push(e);else a.push(e);if(this.tokenizer.endOfFile()){o=!0;break}}t.raws.between=this.spacesAndCommentsFromEnd(a),a.length?(t.raws.afterName=this.spacesAndCommentsFromStart(a),this.raw(t,\"params\",a),o&&(e=a[a.length-1],t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++,this.spaces=t.raws.between,t.raws.between=\"\")):(t.raws.afterName=\"\",t.params=\"\"),l&&(t.nodes=[],this.current=t)}checkMissedSemicolon(e){let t=this.colon(e);if(t===!1)return;let r=0,i;for(let n=t-1;n>=0&&(i=e[n],!(i[0]!==\"space\"&&(r+=1,r===2)));n--);throw this.input.error(\"Missed semicolon\",i[0]===\"word\"?i[3]+1:i[2])}colon(e){let t=0,r,i,n;for(let[o,l]of e.entries()){if(r=l,i=r[0],i===\"(\"&&(t+=1),i===\")\"&&(t-=1),t===0&&i===\":\")if(!n)this.doubleColon(r);else{if(n[0]===\"word\"&&n[1]===\"progid\")continue;return o}n=r}return!1}comment(e){let t=new Sc;this.init(t,e[2]),t.source.end=this.getPosition(e[3]||e[2]),t.source.end.offset++;let r=e[1].slice(2,-2);if(/^\\\\s*$/.test(r))t.text=\"\",t.raws.left=r,t.raws.right=\"\";else{let i=r.match(/^(\\\\s*)([^]*\\\\S)(\\\\s*)$/);t.text=i[2],t.raws.left=i[1],t.raws.right=i[3]}}createTokenizer(){this.tokenizer=wc(this.input)}decl(e,t){let r=new yc;this.init(r,e[0][2]);let i=e[e.length-1];for(i[0]===\";\"&&(this.semicolon=!0,e.pop()),r.source.end=this.getPosition(i[3]||i[2]||vc(e)),r.source.end.offset++;e[0][0]!==\"word\";)e.length===1&&this.unknownWord(e),r.raws.before+=e.shift()[1];for(r.source.start=this.getPosition(e[0][2]),r.prop=\"\";e.length;){let u=e[0][0];if(u===\":\"||u===\"space\"||u===\"comment\")break;r.prop+=e.shift()[1]}r.raws.between=\"\";let n;for(;e.length;)if(n=e.shift(),n[0]===\":\"){r.raws.between+=n[1];break}else n[0]===\"word\"&&/\\\\w/.test(n[1])&&this.unknownWord([n]),r.raws.between+=n[1];(r.prop[0]===\"_\"||r.prop[0]===\"*\")&&(r.raws.before+=r.prop[0],r.prop=r.prop.slice(1));let o=[],l;for(;e.length&&(l=e[0][0],!(l!==\"space\"&&l!==\"comment\"));)o.push(e.shift());this.precheckMissedSemicolon(e);for(let u=e.length-1;u>=0;u--){if(n=e[u],n[1].toLowerCase()===\"!important\"){r.important=!0;let c=this.stringFrom(e,u);c=this.spacesFromEnd(e)+c,c!==\" !important\"&&(r.raws.important=c);break}else if(n[1].toLowerCase()===\"important\"){let c=e.slice(0),h=\"\";for(let d=u;d>0;d--){let m=c[d][0];if(h.trim().indexOf(\"!\")===0&&m!==\"space\")break;h=c.pop()[1]+h}h.trim().indexOf(\"!\")===0&&(r.important=!0,r.raws.important=h,e=c)}if(n[0]!==\"space\"&&n[0]!==\"comment\")break}e.some(u=>u[0]!==\"space\"&&u[0]!==\"comment\")&&(r.raws.between+=o.map(u=>u[1]).join(\"\"),o=[]),this.raw(r,\"value\",o.concat(e),t),r.value.includes(\":\")&&!t&&this.checkMissedSemicolon(e)}doubleColon(e){throw this.input.error(\"Double colon\",{offset:e[2]},{offset:e[2]+e[1].length})}emptyRule(e){let t=new xi;this.init(t,e[2]),t.selector=\"\",t.raws.between=\"\",this.current=t}end(e){this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.semicolon=!1,this.current.raws.after=(this.current.raws.after||\"\")+this.spaces,this.spaces=\"\",this.current.parent?(this.current.source.end=this.getPosition(e[2]),this.current.source.end.offset++,this.current=this.current.parent):this.unexpectedClose(e)}endFile(){this.current.parent&&this.unclosedBlock(),this.current.nodes&&this.current.nodes.length&&(this.current.raws.semicolon=this.semicolon),this.current.raws.after=(this.current.raws.after||\"\")+this.spaces,this.root.source.end=this.getPosition(this.tokenizer.position())}freeSemicolon(e){if(this.spaces+=e[1],this.current.nodes){let t=this.current.nodes[this.current.nodes.length-1];t&&t.type===\"rule\"&&!t.raws.ownSemicolon&&(t.raws.ownSemicolon=this.spaces,this.spaces=\"\")}}getPosition(e){let t=this.input.fromOffset(e);return{column:t.col,line:t.line,offset:e}}init(e,t){this.current.push(e),e.source={input:this.input,start:this.getPosition(t)},e.raws.before=this.spaces,this.spaces=\"\",e.type!==\"comment\"&&(this.semicolon=!1)}other(e){let t=!1,r=null,i=!1,n=null,o=[],l=e[1].startsWith(\"--\"),a=[],u=e;for(;u;){if(r=u[0],a.push(u),r===\"(\"||r===\"[\")n||(n=u),o.push(r===\"(\"?\")\":\"]\");else if(l&&i&&r===\"{\")n||(n=u),o.push(\"}\");else if(o.length===0)if(r===\";\")if(i){this.decl(a,l);return}else break;else if(r===\"{\"){this.rule(a);return}else if(r===\"}\"){this.tokenizer.back(a.pop()),t=!0;break}else r===\":\"&&(i=!0);else r===o[o.length-1]&&(o.pop(),o.length===0&&(n=null));u=this.tokenizer.nextToken()}if(this.tokenizer.endOfFile()&&(t=!0),o.length>0&&this.unclosedBracket(n),t&&i){if(!l)for(;a.length&&(u=a[a.length-1][0],!(u!==\"space\"&&u!==\"comment\"));)this.tokenizer.back(a.pop());this.decl(a,l)}else this.unknownWord(a)}parse(){let e;for(;!this.tokenizer.endOfFile();)switch(e=this.tokenizer.nextToken(),e[0]){case\"space\":this.spaces+=e[1];break;case\";\":this.freeSemicolon(e);break;case\"}\":this.end(e);break;case\"comment\":this.comment(e);break;case\"at-word\":this.atrule(e);break;case\"{\":this.emptyRule(e);break;default:this.other(e);break}this.endFile()}precheckMissedSemicolon(){}raw(e,t,r,i){let n,o,l=r.length,a=\"\",u=!0,c,h;for(let d=0;d<l;d+=1)n=r[d],o=n[0],o===\"space\"&&d===l-1&&!i?u=!1:o===\"comment\"?(h=r[d-1]?r[d-1][0]:\"empty\",c=r[d+1]?r[d+1][0]:\"empty\",!Oi[h]&&!Oi[c]?a.slice(-1)===\",\"?u=!1:a+=n[1]:u=!1):a+=n[1];if(!u){let d=r.reduce((m,g)=>m+g[1],\"\");e.raws[t]={raw:d,value:a}}e[t]=a}rule(e){e.pop();let t=new xi;this.init(t,e[0][2]),t.raws.between=this.spacesAndCommentsFromEnd(e),this.raw(t,\"selector\",e),this.current=t}spacesAndCommentsFromEnd(e){let t,r=\"\";for(;e.length&&(t=e[e.length-1][0],!(t!==\"space\"&&t!==\"comment\"));)r=e.pop()[1]+r;return r}spacesAndCommentsFromStart(e){let t,r=\"\";for(;e.length&&(t=e[0][0],!(t!==\"space\"&&t!==\"comment\"));)r+=e.shift()[1];return r}spacesFromEnd(e){let t,r=\"\";for(;e.length&&(t=e[e.length-1][0],t===\"space\");)r=e.pop()[1]+r;return r}stringFrom(e,t){let r=\"\";for(let i=t;i<e.length;i++)r+=e[i][1];return e.splice(t,e.length-t),r}unclosedBlock(){let e=this.current.source.start;throw this.input.error(\"Unclosed block\",e.line,e.column)}unclosedBracket(e){throw this.input.error(\"Unclosed bracket\",{offset:e[2]},{offset:e[2]+1})}unexpectedClose(e){throw this.input.error(\"Unexpected }\",{offset:e[2]},{offset:e[2]+1})}unknownWord(e){throw this.input.error(\"Unknown word\",{offset:e[0][2]},{offset:e[0][2]+e[0][1].length})}unnamedAtrule(e,t){throw this.input.error(\"At-rule without name\",{offset:t[2]},{offset:t[2]+t[1].length})}};var xc=Ic;let Oc=Ie,Rc=xc,Ac=ur;function Kt(s,e){let t=new Ac(s,e),r=new Rc(t);try{r.parse()}catch(i){throw i}return r.root}var ks=Kt;Kt.default=Kt;Oc.registerParse(Kt);let{isClean:ce,my:Mc}=ot,Ec=Wn,$c=or,Nc=Ie,kc=Ms;let Ri=Es,Pc=ks,Dc=at;const Lc={atrule:\"AtRule\",comment:\"Comment\",decl:\"Declaration\",document:\"Document\",root:\"Root\",rule:\"Rule\"},Tc={AtRule:!0,AtRuleExit:!0,Comment:!0,CommentExit:!0,Declaration:!0,DeclarationExit:!0,Document:!0,DocumentExit:!0,Once:!0,OnceExit:!0,postcssPlugin:!0,prepare:!0,Root:!0,RootExit:!0,Rule:!0,RuleExit:!0},_c={Once:!0,postcssPlugin:!0,prepare:!0},Le=0;function Ve(s){return typeof s==\"object\"&&typeof s.then==\"function\"}function ao(s){let e=!1,t=Lc[s.type];return s.type===\"decl\"?e=s.prop.toLowerCase():s.type===\"atrule\"&&(e=s.name.toLowerCase()),e&&s.append?[t,t+\"-\"+e,Le,t+\"Exit\",t+\"Exit-\"+e]:e?[t,t+\"-\"+e,t+\"Exit\",t+\"Exit-\"+e]:s.append?[t,Le,t+\"Exit\"]:[t,t+\"Exit\"]}function Ai(s){let e;return s.type===\"document\"?e=[\"Document\",Le,\"DocumentExit\"]:s.type===\"root\"?e=[\"Root\",Le,\"RootExit\"]:e=ao(s),{eventIndex:0,events:e,iterator:0,node:s,visitorIndex:0,visitors:[]}}function is(s){return s[ce]=!1,s.nodes&&s.nodes.forEach(e=>is(e)),s}let ns={},Te=class lo{constructor(e,t,r){this.stringified=!1,this.processed=!1;let i;if(typeof t==\"object\"&&t!==null&&(t.type===\"root\"||t.type===\"document\"))i=is(t);else if(t instanceof lo||t instanceof Ri)i=is(t.root),t.map&&(typeof r.map==\"undefined\"&&(r.map={}),r.map.inline||(r.map.inline=!1),r.map.prev=t.map);else{let n=Pc;r.syntax&&(n=r.syntax.parse),r.parser&&(n=r.parser),n.parse&&(n=n.parse);try{i=n(t,r)}catch(o){this.processed=!0,this.error=o}i&&!i[Mc]&&Nc.rebuild(i)}this.result=new Ri(e,i,r),this.helpers=ee(x({},ns),{postcss:ns,result:this.result}),this.plugins=this.processor.plugins.map(n=>typeof n==\"object\"&&n.prepare?x(x({},n),n.prepare(this.result)):n)}async(){return this.error?Promise.reject(this.error):this.processed?Promise.resolve(this.result):(this.processing||(this.processing=this.runAsync()),this.processing)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}getAsyncError(){throw new Error(\"Use process(css).then(cb) to work with async plugins\")}handleError(e,t){let r=this.result.lastPlugin;try{t&&t.addToError(e),this.error=e,e.name===\"CssSyntaxError\"&&!e.plugin?(e.plugin=r.postcssPlugin,e.setMessage()):r.postcssVersion}catch(i){console&&console.error&&console.error(i)}return e}prepareVisitors(){this.listeners={};let e=(t,r,i)=>{this.listeners[r]||(this.listeners[r]=[]),this.listeners[r].push([t,i])};for(let t of this.plugins)if(typeof t==\"object\")for(let r in t){if(!Tc[r]&&/^[A-Z]/.test(r))throw new Error(\\`Unknown event \\${r} in \\${t.postcssPlugin}. Try to update PostCSS (\\${this.processor.version} now).\\`);if(!_c[r])if(typeof t[r]==\"object\")for(let i in t[r])i===\"*\"?e(t,r,t[r][i]):e(t,r+\"-\"+i.toLowerCase(),t[r][i]);else typeof t[r]==\"function\"&&e(t,r,t[r])}this.hasListener=Object.keys(this.listeners).length>0}async runAsync(){this.plugin=0;for(let e=0;e<this.plugins.length;e++){let t=this.plugins[e],r=this.runOnRoot(t);if(Ve(r))try{await r}catch(i){throw this.handleError(i)}}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[ce];){e[ce]=!0;let t=[Ai(e)];for(;t.length>0;){let r=this.visitTick(t);if(Ve(r))try{await r}catch(i){let n=t[t.length-1].node;throw this.handleError(i,n)}}}if(this.listeners.OnceExit)for(let[t,r]of this.listeners.OnceExit){this.result.lastPlugin=t;try{if(e.type===\"document\"){let i=e.nodes.map(n=>r(n,this.helpers));await Promise.all(i)}else await r(e,this.helpers)}catch(i){throw this.handleError(i)}}}return this.processed=!0,this.stringify()}runOnRoot(e){this.result.lastPlugin=e;try{if(typeof e==\"object\"&&e.Once){if(this.result.root.type===\"document\"){let t=this.result.root.nodes.map(r=>e.Once(r,this.helpers));return Ve(t[0])?Promise.all(t):t}return e.Once(this.result.root,this.helpers)}else if(typeof e==\"function\")return e(this.result.root,this.result)}catch(t){throw this.handleError(t)}}stringify(){if(this.error)throw this.error;if(this.stringified)return this.result;this.stringified=!0,this.sync();let e=this.result.opts,t=$c;e.syntax&&(t=e.syntax.stringify),e.stringifier&&(t=e.stringifier),t.stringify&&(t=t.stringify);let i=new Ec(t,this.result.root,this.result.opts).generate();return this.result.css=i[0],this.result.map=i[1],this.result}sync(){if(this.error)throw this.error;if(this.processed)return this.result;if(this.processed=!0,this.processing)throw this.getAsyncError();for(let e of this.plugins){let t=this.runOnRoot(e);if(Ve(t))throw this.getAsyncError()}if(this.prepareVisitors(),this.hasListener){let e=this.result.root;for(;!e[ce];)e[ce]=!0,this.walkSync(e);if(this.listeners.OnceExit)if(e.type===\"document\")for(let t of e.nodes)this.visitSync(this.listeners.OnceExit,t);else this.visitSync(this.listeners.OnceExit,e)}return this.result}then(e,t){return this.async().then(e,t)}toString(){return this.css}visitSync(e,t){for(let[r,i]of e){this.result.lastPlugin=r;let n;try{n=i(t,this.helpers)}catch(o){throw this.handleError(o,t.proxyOf)}if(t.type!==\"root\"&&t.type!==\"document\"&&!t.parent)return!0;if(Ve(n))throw this.getAsyncError()}}visitTick(e){let t=e[e.length-1],{node:r,visitors:i}=t;if(r.type!==\"root\"&&r.type!==\"document\"&&!r.parent){e.pop();return}if(i.length>0&&t.visitorIndex<i.length){let[o,l]=i[t.visitorIndex];t.visitorIndex+=1,t.visitorIndex===i.length&&(t.visitors=[],t.visitorIndex=0),this.result.lastPlugin=o;try{return l(r.toProxy(),this.helpers)}catch(a){throw this.handleError(a,r)}}if(t.iterator!==0){let o=t.iterator,l;for(;l=r.nodes[r.indexes[o]];)if(r.indexes[o]+=1,!l[ce]){l[ce]=!0,e.push(Ai(l));return}t.iterator=0,delete r.indexes[o]}let n=t.events;for(;t.eventIndex<n.length;){let o=n[t.eventIndex];if(t.eventIndex+=1,o===Le){r.nodes&&r.nodes.length&&(r[ce]=!0,t.iterator=r.getIterator());return}else if(this.listeners[o]){t.visitors=this.listeners[o];return}}e.pop()}walkSync(e){e[ce]=!0;let t=ao(e);for(let r of t)if(r===Le)e.nodes&&e.each(i=>{i[ce]||this.walkSync(i)});else{let i=this.listeners[r];if(i&&this.visitSync(i,e.toProxy()))return}}warnings(){return this.sync().warnings()}get content(){return this.stringify().content}get css(){return this.stringify().css}get map(){return this.stringify().map}get messages(){return this.sync().messages}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){return this.sync().root}get[Symbol.toStringTag](){return\"LazyResult\"}};Te.registerPostcss=s=>{ns=s};var uo=Te;Te.default=Te;Dc.registerLazyResult(Te);kc.registerLazyResult(Te);let Fc=Wn,Uc=or;let Bc=ks;const zc=Es;let os=class{constructor(e,t,r){t=t.toString(),this.stringified=!1,this._processor=e,this._css=t,this._opts=r,this._map=void 0;let i,n=Uc;this.result=new zc(this._processor,i,this._opts),this.result.css=t;let o=this;Object.defineProperty(this.result,\"root\",{get(){return o.root}});let l=new Fc(n,i,this._opts,t);if(l.isMap()){let[a,u]=l.generate();a&&(this.result.css=a),u&&(this.result.map=u)}else l.clearAnnotation(),this.result.css=l.css}async(){return this.error?Promise.reject(this.error):Promise.resolve(this.result)}catch(e){return this.async().catch(e)}finally(e){return this.async().then(e,e)}sync(){if(this.error)throw this.error;return this.result}then(e,t){return this.async().then(e,t)}toString(){return this._css}warnings(){return[]}get content(){return this.result.css}get css(){return this.result.css}get map(){return this.result.map}get messages(){return[]}get opts(){return this.result.opts}get processor(){return this.result.processor}get root(){if(this._root)return this._root;let e,t=Bc;try{e=t(this._css,this._opts)}catch(r){this.error=r}if(this.error)throw this.error;return this._root=e,e}get[Symbol.toStringTag](){return\"NoWorkResult\"}};var Wc=os;os.default=os;let Gc=Wc,Vc=uo,jc=Ms,Hc=at,tt=class{constructor(e=[]){this.version=\"8.4.38\",this.plugins=this.normalize(e)}normalize(e){let t=[];for(let r of e)if(r.postcss===!0?r=r():r.postcss&&(r=r.postcss),typeof r==\"object\"&&Array.isArray(r.plugins))t=t.concat(r.plugins);else if(typeof r==\"object\"&&r.postcssPlugin)t.push(r);else if(typeof r==\"function\")t.push(r);else if(!(typeof r==\"object\"&&(r.parse||r.stringify)))throw new Error(r+\" is not a PostCSS plugin\");return t}process(e,t={}){return!this.plugins.length&&!t.parser&&!t.stringifier&&!t.syntax?new Gc(this,e,t):new Vc(this,e,t)}use(e){return this.plugins=this.plugins.concat(this.normalize([e])),this}};var Yc=tt;tt.default=tt;Hc.registerProcessor(tt);jc.registerProcessor(tt);let Zc=lr,Jc=_n,Xc=cr,Kc=$s,Qc=ur,qc=at,eh=Ns;function rt(s,e){if(Array.isArray(s))return s.map(o=>rt(o));let i=s,{inputs:t}=i,r=xe(i,[\"inputs\"]);if(t){e=[];for(let o of t){let l=ee(x({},o),{__proto__:Qc.prototype});l.map&&(l.map=ee(x({},l.map),{__proto__:Jc.prototype})),e.push(l)}}if(r.nodes&&(r.nodes=s.nodes.map(o=>rt(o,e))),r.source){let n=r.source,{inputId:o}=n,l=xe(n,[\"inputId\"]);r.source=l,o!=null&&(r.source.input=e[o])}if(r.type===\"root\")return new qc(r);if(r.type===\"decl\")return new Zc(r);if(r.type===\"rule\")return new eh(r);if(r.type===\"comment\")return new Xc(r);if(r.type===\"atrule\")return new Kc(r);throw new Error(\"Unknown node type: \"+s.type)}var th=rt;rt.default=rt;let rh=Os,co=lr,sh=uo,ih=Ie,Ps=Yc,nh=or,oh=th,ho=Ms,ah=eo,fo=cr,po=$s,lh=Es,uh=ur,ch=ks,hh=no,mo=Ns,go=at,fh=ar;function $(...s){return s.length===1&&Array.isArray(s[0])&&(s=s[0]),new Ps(s)}$.plugin=function(e,t){let r=!1;function i(...o){console&&console.warn&&!r&&(r=!0,console.warn(e+\\`: postcss.plugin was deprecated. Migration guide:\nhttps://evilmartians.com/chronicles/postcss-8-plugin-migration\\`),process.env.LANG&&process.env.LANG.startsWith(\"cn\")&&console.warn(e+\\`: \\\\u91CC\\\\u9762 postcss.plugin \\\\u88AB\\\\u5F03\\\\u7528. \\\\u8FC1\\\\u79FB\\\\u6307\\\\u5357:\nhttps://www.w3ctech.com/topic/2226\\`));let l=t(...o);return l.postcssPlugin=e,l.postcssVersion=new Ps().version,l}let n;return Object.defineProperty(i,\"postcss\",{get(){return n||(n=i()),n}}),i.process=function(o,l,a){return $([i(a)]).process(o,l)},i};$.stringify=nh;$.parse=ch;$.fromJSON=oh;$.list=hh;$.comment=s=>new fo(s);$.atRule=s=>new po(s);$.decl=s=>new co(s);$.rule=s=>new mo(s);$.root=s=>new go(s);$.document=s=>new ho(s);$.CssSyntaxError=rh;$.Declaration=co;$.Container=ih;$.Processor=Ps;$.Document=ho;$.Comment=fo;$.Warning=ah;$.AtRule=po;$.Result=lh;$.Input=uh;$.Rule=mo;$.Root=go;$.Node=fh;sh.registerPostcss($);var ph=$;$.default=$;const U=Ou(ph);U.stringify;U.fromJSON;U.plugin;U.parse;U.list;U.document;U.comment;U.atRule;U.rule;U.decl;U.root;U.CssSyntaxError;U.Declaration;U.Container;U.Processor;U.Document;U.Comment;U.Warning;U.AtRule;U.Result;U.Input;U.Rule;U.Root;U.Node;class Ds{constructor(...e){te(this,\"parentElement\",null),te(this,\"parentNode\",null),te(this,\"ownerDocument\"),te(this,\"firstChild\",null),te(this,\"lastChild\",null),te(this,\"previousSibling\",null),te(this,\"nextSibling\",null),te(this,\"ELEMENT_NODE\",1),te(this,\"TEXT_NODE\",3),te(this,\"nodeType\"),te(this,\"nodeName\"),te(this,\"RRNodeType\")}get childNodes(){const e=[];let t=this.firstChild;for(;t;)e.push(t),t=t.nextSibling;return e}contains(e){if(e instanceof Ds){if(e.ownerDocument!==this.ownerDocument)return!1;if(e===this)return!0}else return!1;for(;e.parentNode;){if(e.parentNode===this)return!0;e=e.parentNode}return!1}appendChild(e){throw new Error(\"RRDomException: Failed to execute 'appendChild' on 'RRNode': This RRNode type does not support this method.\")}insertBefore(e,t){throw new Error(\"RRDomException: Failed to execute 'insertBefore' on 'RRNode': This RRNode type does not support this method.\")}removeChild(e){throw new Error(\"RRDomException: Failed to execute 'removeChild' on 'RRNode': This RRNode type does not support this method.\")}toString(){return\"RRNode\"}}const Mi={Node:[\"childNodes\",\"parentNode\",\"parentElement\",\"textContent\"],ShadowRoot:[\"host\",\"styleSheets\"],Element:[\"shadowRoot\",\"querySelector\",\"querySelectorAll\"],MutationObserver:[]},Ei={Node:[\"contains\",\"getRootNode\"],ShadowRoot:[\"getSelection\"],Element:[],MutationObserver:[\"constructor\"]},kt={},dh=()=>!!globalThis.Zone;function Ls(s){if(kt[s])return kt[s];const e=globalThis[s],t=e.prototype,r=s in Mi?Mi[s]:void 0,i=!!(r&&r.every(l=>{var a,u;return!!((u=(a=Object.getOwnPropertyDescriptor(t,l))==null?void 0:a.get)!=null&&u.toString().includes(\"[native code]\"))})),n=s in Ei?Ei[s]:void 0,o=!!(n&&n.every(l=>{var a;return typeof t[l]==\"function\"&&((a=t[l])==null?void 0:a.toString().includes(\"[native code]\"))}));if(i&&o&&!dh())return kt[s]=e.prototype,e.prototype;try{const l=document.createElement(\"iframe\");document.body.appendChild(l);const a=l.contentWindow;if(!a)return e.prototype;const u=a[s].prototype;return document.body.removeChild(l),u?kt[s]=u:t}catch(l){return t}}const Rr={};function ge(s,e,t){var r;const i=\\`\\${s}.\\${String(t)}\\`;if(Rr[i])return Rr[i].call(e);const n=Ls(s),o=(r=Object.getOwnPropertyDescriptor(n,t))==null?void 0:r.get;return o?(Rr[i]=o,o.call(e)):e[t]}const Ar={};function yo(s,e,t){const r=\\`\\${s}.\\${String(t)}\\`;if(Ar[r])return Ar[r].bind(e);const n=Ls(s)[t];return typeof n!=\"function\"?e[t]:(Ar[r]=n,n.bind(e))}function mh(s){return ge(\"Node\",s,\"childNodes\")}function gh(s){return ge(\"Node\",s,\"parentNode\")}function yh(s){return ge(\"Node\",s,\"parentElement\")}function wh(s){return ge(\"Node\",s,\"textContent\")}function Sh(s,e){return yo(\"Node\",s,\"contains\")(e)}function bh(s){return yo(\"Node\",s,\"getRootNode\")()}function Ch(s){return!s||!(\"host\"in s)?null:ge(\"ShadowRoot\",s,\"host\")}function vh(s){return s.styleSheets}function Ih(s){return!s||!(\"shadowRoot\"in s)?null:ge(\"Element\",s,\"shadowRoot\")}function xh(s,e){return ge(\"Element\",s,\"querySelector\")(e)}function Oh(s,e){return ge(\"Element\",s,\"querySelectorAll\")(e)}function wo(){return Ls(\"MutationObserver\").constructor}const v={childNodes:mh,parentNode:gh,parentElement:yh,textContent:wh,contains:Sh,getRootNode:bh,host:Ch,styleSheets:vh,shadowRoot:Ih,querySelector:xh,querySelectorAll:Oh,mutationObserver:wo};function J(s,e,t=document){const r={capture:!0,passive:!0};return t.addEventListener(s,e,r),()=>t.removeEventListener(s,e,r)}const Re=\\`Please stop import mirror directly. Instead of that,\\\\r\nnow you can use replayer.getMirror() to access the mirror instance of a replayer,\\\\r\nor you can use record.mirror to access the mirror instance during recording.\\`;let $i={map:{},getId(){return console.error(Re),-1},getNode(){return console.error(Re),null},removeNodeFromMap(){console.error(Re)},has(){return console.error(Re),!1},reset(){console.error(Re)}};typeof window!=\"undefined\"&&window.Proxy&&window.Reflect&&($i=new Proxy($i,{get(s,e,t){return e===\"map\"&&console.error(Re),Reflect.get(s,e,t)}}));function st(s,e,t={}){let r=null,i=0;return function(...n){const o=Date.now();!i&&t.leading===!1&&(i=o);const l=e-(o-i),a=this;l<=0||l>e?(r&&(clearTimeout(r),r=null),i=o,s.apply(a,n)):!r&&t.trailing!==!1&&(r=setTimeout(()=>{i=t.leading===!1?0:Date.now(),r=null,s.apply(a,n)},l))}}function hr(s,e,t,r,i=window){const n=i.Object.getOwnPropertyDescriptor(s,e);return i.Object.defineProperty(s,e,r?t:{set(o){setTimeout(()=>{t.set.call(this,o)},0),n&&n.set&&n.set.call(this,o)}}),()=>hr(s,e,n||{},!0)}function Fe(s,e,t){try{if(!(e in s))return()=>{};const r=s[e],i=t(r);return typeof i==\"function\"&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:r}})),s[e]=i,()=>{s[e]=r}}catch(r){return()=>{}}}let Qt=Date.now;/[1-9][0-9]{12}/.test(Date.now().toString())||(Qt=()=>new Date().getTime());function So(s){var e,t,r,i;const n=s.document;return{left:n.scrollingElement?n.scrollingElement.scrollLeft:s.pageXOffset!==void 0?s.pageXOffset:n.documentElement.scrollLeft||(n==null?void 0:n.body)&&((e=v.parentElement(n.body))==null?void 0:e.scrollLeft)||((t=n==null?void 0:n.body)==null?void 0:t.scrollLeft)||0,top:n.scrollingElement?n.scrollingElement.scrollTop:s.pageYOffset!==void 0?s.pageYOffset:(n==null?void 0:n.documentElement.scrollTop)||(n==null?void 0:n.body)&&((r=v.parentElement(n.body))==null?void 0:r.scrollTop)||((i=n==null?void 0:n.body)==null?void 0:i.scrollTop)||0}}function bo(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function Co(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function vo(s){return s?s.nodeType===s.ELEMENT_NODE?s:v.parentElement(s):null}function X(s,e,t,r){if(!s)return!1;const i=vo(s);if(!i)return!1;try{if(typeof e==\"string\"){if(i.classList.contains(e)||r&&i.closest(\".\"+e)!==null)return!0}else if(Gt(i,e,r))return!0}catch(n){}return!!(t&&(i.matches(t)||r&&i.closest(t)!==null))}function Rh(s,e){return e.getId(s)!==-1}function Mr(s,e,t){return s.tagName===\"TITLE\"&&t.headTitleMutations?!0:e.getId(s)===Ze}function Io(s,e){if(je(s))return!1;const t=e.getId(s);if(!e.has(t))return!0;const r=v.parentNode(s);return r&&r.nodeType===s.DOCUMENT_NODE?!1:r?Io(r,e):!0}function as(s){return!!s.changedTouches}function Ah(s=window){\"NodeList\"in s&&!s.NodeList.prototype.forEach&&(s.NodeList.prototype.forEach=Array.prototype.forEach),\"DOMTokenList\"in s&&!s.DOMTokenList.prototype.forEach&&(s.DOMTokenList.prototype.forEach=Array.prototype.forEach)}function xo(s,e){return!!(s.nodeName===\"IFRAME\"&&e.getMeta(s))}function Oo(s,e){return!!(s.nodeName===\"LINK\"&&s.nodeType===s.ELEMENT_NODE&&s.getAttribute&&s.getAttribute(\"rel\")===\"stylesheet\"&&e.getMeta(s))}function ls(s){return s?s instanceof Ds&&\"shadowRoot\"in s?!!s.shadowRoot:!!v.shadowRoot(s):!1}class Mh{constructor(){w(this,\"id\",1),w(this,\"styleIDMap\",new WeakMap),w(this,\"idStyleMap\",new Map)}getId(e){var t;return(t=this.styleIDMap.get(e))!=null?t:-1}has(e){return this.styleIDMap.has(e)}add(e,t){if(this.has(e))return this.getId(e);let r;return t===void 0?r=this.id++:r=t,this.styleIDMap.set(e,r),this.idStyleMap.set(r,e),r}getStyle(e){return this.idStyleMap.get(e)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function Ro(s){var e;let t=null;return\"getRootNode\"in s&&((e=v.getRootNode(s))==null?void 0:e.nodeType)===Node.DOCUMENT_FRAGMENT_NODE&&v.host(v.getRootNode(s))&&(t=v.host(v.getRootNode(s))),t}function Eh(s){let e=s,t;for(;t=Ro(e);)e=t;return e}function $h(s){const e=s.ownerDocument;if(!e)return!1;const t=Eh(s);return v.contains(e,t)}function Ao(s){const e=s.ownerDocument;return e?v.contains(e,s)||$h(s):!1}var R=(s=>(s[s.DomContentLoaded=0]=\"DomContentLoaded\",s[s.Load=1]=\"Load\",s[s.FullSnapshot=2]=\"FullSnapshot\",s[s.IncrementalSnapshot=3]=\"IncrementalSnapshot\",s[s.Meta=4]=\"Meta\",s[s.Custom=5]=\"Custom\",s[s.Plugin=6]=\"Plugin\",s))(R||{}),I=(s=>(s[s.Mutation=0]=\"Mutation\",s[s.MouseMove=1]=\"MouseMove\",s[s.MouseInteraction=2]=\"MouseInteraction\",s[s.Scroll=3]=\"Scroll\",s[s.ViewportResize=4]=\"ViewportResize\",s[s.Input=5]=\"Input\",s[s.TouchMove=6]=\"TouchMove\",s[s.MediaInteraction=7]=\"MediaInteraction\",s[s.StyleSheetRule=8]=\"StyleSheetRule\",s[s.CanvasMutation=9]=\"CanvasMutation\",s[s.Font=10]=\"Font\",s[s.Log=11]=\"Log\",s[s.Drag=12]=\"Drag\",s[s.StyleDeclaration=13]=\"StyleDeclaration\",s[s.Selection=14]=\"Selection\",s[s.AdoptedStyleSheet=15]=\"AdoptedStyleSheet\",s[s.CustomElement=16]=\"CustomElement\",s))(I||{}),K=(s=>(s[s.MouseUp=0]=\"MouseUp\",s[s.MouseDown=1]=\"MouseDown\",s[s.Click=2]=\"Click\",s[s.ContextMenu=3]=\"ContextMenu\",s[s.DblClick=4]=\"DblClick\",s[s.Focus=5]=\"Focus\",s[s.Blur=6]=\"Blur\",s[s.TouchStart=7]=\"TouchStart\",s[s.TouchMove_Departed=8]=\"TouchMove_Departed\",s[s.TouchEnd=9]=\"TouchEnd\",s[s.TouchCancel=10]=\"TouchCancel\",s))(K||{}),he=(s=>(s[s.Mouse=0]=\"Mouse\",s[s.Pen=1]=\"Pen\",s[s.Touch=2]=\"Touch\",s))(he||{}),_e=(s=>(s[s[\"2D\"]=0]=\"2D\",s[s.WebGL=1]=\"WebGL\",s[s.WebGL2=2]=\"WebGL2\",s))(_e||{}),Ae=(s=>(s[s.Play=0]=\"Play\",s[s.Pause=1]=\"Pause\",s[s.Seeked=2]=\"Seeked\",s[s.VolumeChange=3]=\"VolumeChange\",s[s.RateChange=4]=\"RateChange\",s))(Ae||{}),Mo=(s=>(s[s.Document=0]=\"Document\",s[s.DocumentType=1]=\"DocumentType\",s[s.Element=2]=\"Element\",s[s.Text=3]=\"Text\",s[s.CDATA=4]=\"CDATA\",s[s.Comment=5]=\"Comment\",s))(Mo||{});function Ni(s){return\"__ln\"in s}class Nh{constructor(){w(this,\"length\",0),w(this,\"head\",null),w(this,\"tail\",null)}get(e){if(e>=this.length)throw new Error(\"Position outside of list range\");let t=this.head;for(let r=0;r<e;r++)t=(t==null?void 0:t.next)||null;return t}addNode(e){const t={value:e,previous:null,next:null};if(e.__ln=t,e.previousSibling&&Ni(e.previousSibling)){const r=e.previousSibling.__ln.next;t.next=r,t.previous=e.previousSibling.__ln,e.previousSibling.__ln.next=t,r&&(r.previous=t)}else if(e.nextSibling&&Ni(e.nextSibling)&&e.nextSibling.__ln.previous){const r=e.nextSibling.__ln.previous;t.previous=r,t.next=e.nextSibling.__ln,e.nextSibling.__ln.previous=t,r&&(r.next=t)}else this.head&&(this.head.previous=t),t.next=this.head,this.head=t;t.next===null&&(this.tail=t),this.length++}removeNode(e){const t=e.__ln;this.head&&(t.previous?(t.previous.next=t.next,t.next?t.next.previous=t.previous:this.tail=t.previous):(this.head=t.next,this.head?this.head.previous=null:this.tail=null),e.__ln&&delete e.__ln,this.length--)}}const ki=(s,e)=>\\`\\${s}@\\${e}\\`;class kh{constructor(){w(this,\"frozen\",!1),w(this,\"locked\",!1),w(this,\"texts\",[]),w(this,\"attributes\",[]),w(this,\"attributeMap\",new WeakMap),w(this,\"removes\",[]),w(this,\"mapRemoves\",[]),w(this,\"movedMap\",{}),w(this,\"addedSet\",new Set),w(this,\"movedSet\",new Set),w(this,\"droppedSet\",new Set),w(this,\"removesSubTreeCache\",new Set),w(this,\"mutationCb\"),w(this,\"blockClass\"),w(this,\"blockSelector\"),w(this,\"maskTextClass\"),w(this,\"maskTextSelector\"),w(this,\"inlineStylesheet\"),w(this,\"maskInputOptions\"),w(this,\"maskTextFn\"),w(this,\"maskInputFn\"),w(this,\"keepIframeSrcFn\"),w(this,\"recordCanvas\"),w(this,\"inlineImages\"),w(this,\"slimDOMOptions\"),w(this,\"dataURLOptions\"),w(this,\"doc\"),w(this,\"mirror\"),w(this,\"iframeManager\"),w(this,\"stylesheetManager\"),w(this,\"shadowDomManager\"),w(this,\"canvasManager\"),w(this,\"processedNodeManager\"),w(this,\"unattachedDoc\"),w(this,\"processMutations\",e=>{e.forEach(this.processMutation),this.emit()}),w(this,\"emit\",()=>{if(this.frozen||this.locked)return;const e=[],t=new Set,r=new Nh,i=a=>{let u=a,c=Ze;for(;c===Ze;)u=u&&u.nextSibling,c=u&&this.mirror.getId(u);return c},n=a=>{const u=v.parentNode(a);if(!u||!Ao(a))return;let c=!1;if(a.nodeType===Node.TEXT_NODE){const g=u.tagName;if(g===\"TEXTAREA\")return;g===\"STYLE\"&&this.addedSet.has(u)&&(c=!0)}const h=je(u)?this.mirror.getId(Ro(a)):this.mirror.getId(u),d=i(a);if(h===-1||d===-1)return r.addNode(a);const m=Ee(a,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskTextClass:this.maskTextClass,maskTextSelector:this.maskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:g=>{xo(g,this.mirror)&&this.iframeManager.addIframe(g),Oo(g,this.mirror)&&this.stylesheetManager.trackLinkElement(g),ls(a)&&this.shadowDomManager.addShadowRoot(v.shadowRoot(a),this.doc)},onIframeLoad:(g,p)=>{this.iframeManager.attachIframe(g,p),this.shadowDomManager.observeAttachShadow(g)},onStylesheetLoad:(g,p)=>{this.stylesheetManager.attachLinkElement(g,p)},cssCaptured:c});m&&(e.push({parentId:h,nextId:d,node:m}),t.add(m.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const a of this.movedSet)Pi(this.removesSubTreeCache,a,this.mirror)&&!this.movedSet.has(v.parentNode(a))||n(a);for(const a of this.addedSet)!Di(this.droppedSet,a)&&!Pi(this.removesSubTreeCache,a,this.mirror)||Di(this.movedSet,a)?n(a):this.droppedSet.add(a);let o=null;for(;r.length;){let a=null;if(o){const u=this.mirror.getId(v.parentNode(o.value)),c=i(o.value);u!==-1&&c!==-1&&(a=o)}if(!a){let u=r.tail;for(;u;){const c=u;if(u=u.previous,c){const h=this.mirror.getId(v.parentNode(c.value));if(i(c.value)===-1)continue;if(h!==-1){a=c;break}else{const m=c.value,g=v.parentNode(m);if(g&&g.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const p=v.host(g);if(this.mirror.getId(p)!==-1){a=c;break}}}}}}if(!a){for(;r.head;)r.removeNode(r.head.value);break}o=a.previous,r.removeNode(a.value),n(a.value)}const l={texts:this.texts.map(a=>{const u=a.node,c=v.parentNode(u);return c&&c.tagName===\"TEXTAREA\"&&this.genTextAreaValueMutation(c),{id:this.mirror.getId(u),value:a.value}}).filter(a=>!t.has(a.id)).filter(a=>this.mirror.has(a.id)),attributes:this.attributes.map(a=>{const{attributes:u}=a;if(typeof u.style==\"string\"){const c=JSON.stringify(a.styleDiff),h=JSON.stringify(a._unchangedStyles);c.length<u.style.length&&(c+h).split(\"var(\").length===u.style.split(\"var(\").length&&(u.style=a.styleDiff)}return{id:this.mirror.getId(a.node),attributes:u}}).filter(a=>!t.has(a.id)).filter(a=>this.mirror.has(a.id)),removes:this.removes,adds:e};!l.texts.length&&!l.attributes.length&&!l.removes.length&&!l.adds.length||(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.removesSubTreeCache=new Set,this.movedMap={},this.mutationCb(l))}),w(this,\"genTextAreaValueMutation\",e=>{let t=this.attributeMap.get(e);t||(t={node:e,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(t),this.attributeMap.set(e,t)),t.attributes.value=Array.from(v.childNodes(e),r=>v.textContent(r)||\"\").join(\"\")}),w(this,\"processMutation\",e=>{if(!Mr(e.target,this.mirror,this.slimDOMOptions))switch(e.type){case\"characterData\":{const t=v.textContent(e.target);!X(e.target,this.blockClass,this.blockSelector,!1)&&t!==e.oldValue&&this.texts.push({value:Xi(e.target,this.maskTextClass,this.maskTextSelector,!0)&&t?this.maskTextFn?this.maskTextFn(t,vo(e.target)):t.replace(/[\\\\S]/g,\"*\"):t,node:e.target});break}case\"attributes\":{const t=e.target;let r=e.attributeName,i=e.target.getAttribute(r);if(r===\"value\"){const o=fs(t);i=hs({element:t,maskInputOptions:this.maskInputOptions,tagName:t.tagName,type:o,value:i,maskInputFn:this.maskInputFn})}if(X(e.target,this.blockClass,this.blockSelector,!1)||i===e.oldValue)return;let n=this.attributeMap.get(e.target);if(t.tagName===\"IFRAME\"&&r===\"src\"&&!this.keepIframeSrcFn(i))if(!t.contentDocument)r=\"rr_src\";else return;if(n||(n={node:e.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(n),this.attributeMap.set(e.target,n)),r===\"type\"&&t.tagName===\"INPUT\"&&(e.oldValue||\"\").toLowerCase()===\"password\"&&t.setAttribute(\"data-rr-is-password\",\"true\"),!Ji(t.tagName,r))if(n.attributes[r]=Zi(this.doc,Ce(t.tagName),Ce(r),i),r===\"style\"){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch(l){this.unattachedDoc=this.doc}const o=this.unattachedDoc.createElement(\"span\");e.oldValue&&o.setAttribute(\"style\",e.oldValue);for(const l of Array.from(t.style)){const a=t.style.getPropertyValue(l),u=t.style.getPropertyPriority(l);a!==o.style.getPropertyValue(l)||u!==o.style.getPropertyPriority(l)?u===\"\"?n.styleDiff[l]=a:n.styleDiff[l]=[a,u]:n._unchangedStyles[l]=[a,u]}for(const l of Array.from(o.style))t.style.getPropertyValue(l)===\"\"&&(n.styleDiff[l]=!1)}else r===\"open\"&&t.tagName===\"DIALOG\"&&(t.matches(\"dialog:modal\")?n.attributes.rr_open_mode=\"modal\":n.attributes.rr_open_mode=\"non-modal\");break}case\"childList\":{if(X(e.target,this.blockClass,this.blockSelector,!0))return;if(e.target.tagName===\"TEXTAREA\"){this.genTextAreaValueMutation(e.target);return}e.addedNodes.forEach(t=>this.genAdds(t,e.target)),e.removedNodes.forEach(t=>{const r=this.mirror.getId(t),i=je(e.target)?this.mirror.getId(v.host(e.target)):this.mirror.getId(e.target);X(e.target,this.blockClass,this.blockSelector,!1)||Mr(t,this.mirror,this.slimDOMOptions)||!Rh(t,this.mirror)||(this.addedSet.has(t)?(us(this.addedSet,t),this.droppedSet.add(t)):this.addedSet.has(e.target)&&r===-1||Io(e.target,this.mirror)||(this.movedSet.has(t)&&this.movedMap[ki(r,i)]?us(this.movedSet,t):(this.removes.push({parentId:i,id:r,isShadow:je(e.target)&&He(e.target)?!0:void 0}),Ph(t,this.removesSubTreeCache))),this.mapRemoves.push(t))});break}}}),w(this,\"genAdds\",(e,t)=>{if(!this.processedNodeManager.inOtherBuffer(e,this)&&!(this.addedSet.has(e)||this.movedSet.has(e))){if(this.mirror.hasNode(e)){if(Mr(e,this.mirror,this.slimDOMOptions))return;this.movedSet.add(e);let r=null;t&&this.mirror.hasNode(t)&&(r=this.mirror.getId(t)),r&&r!==-1&&(this.movedMap[ki(this.mirror.getId(e),r)]=!0)}else this.addedSet.add(e),this.droppedSet.delete(e);X(e,this.blockClass,this.blockSelector,!1)||(v.childNodes(e).forEach(r=>this.genAdds(r)),ls(e)&&v.childNodes(v.shadowRoot(e)).forEach(r=>{this.processedNodeManager.add(r,this),this.genAdds(r,e)}))}})}init(e){[\"mutationCb\",\"blockClass\",\"blockSelector\",\"maskTextClass\",\"maskTextSelector\",\"inlineStylesheet\",\"maskInputOptions\",\"maskTextFn\",\"maskInputFn\",\"keepIframeSrcFn\",\"recordCanvas\",\"inlineImages\",\"slimDOMOptions\",\"dataURLOptions\",\"doc\",\"mirror\",\"iframeManager\",\"stylesheetManager\",\"shadowDomManager\",\"canvasManager\",\"processedNodeManager\"].forEach(t=>{this[t]=e[t]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function us(s,e){s.delete(e),v.childNodes(e).forEach(t=>us(s,t))}function Ph(s,e){const t=[s];for(;t.length;){const r=t.pop();e.has(r)||(e.add(r),v.childNodes(r).forEach(i=>t.push(i)))}}function Pi(s,e,t){return s.size===0?!1:Dh(s,e)}function Dh(s,e,t){const r=v.parentNode(e);return r?s.has(r):!1}function Di(s,e){return s.size===0?!1:Eo(s,e)}function Eo(s,e){const t=v.parentNode(e);return t?s.has(t)?!0:Eo(s,t):!1}let Ye;function Lh(s){Ye=s}function Th(){Ye=void 0}const O=s=>Ye?(...t)=>{try{return s(...t)}catch(r){if(Ye&&Ye(r)===!0)return;throw r}}:s,be=[];function lt(s){try{if(\"composedPath\"in s){const e=s.composedPath();if(e.length)return e[0]}else if(\"path\"in s&&s.path.length)return s.path[0]}catch(e){}return s&&s.target}function $o(s,e){const t=new kh;be.push(t),t.init(s);const r=new(wo())(O(t.processMutations.bind(t)));return r.observe(e,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),r}function _h({mousemoveCb:s,sampling:e,doc:t,mirror:r}){if(e.mousemove===!1)return()=>{};const i=typeof e.mousemove==\"number\"?e.mousemove:50,n=typeof e.mousemoveCallback==\"number\"?e.mousemoveCallback:500;let o=[],l;const a=st(O(h=>{const d=Date.now()-l;s(o.map(m=>(m.timeOffset-=d,m)),h),o=[],l=null}),n),u=O(st(O(h=>{const d=lt(h),{clientX:m,clientY:g}=as(h)?h.changedTouches[0]:h;l||(l=Qt()),o.push({x:m,y:g,id:r.getId(d),timeOffset:Qt()-l}),a(typeof DragEvent!=\"undefined\"&&h instanceof DragEvent?I.Drag:h instanceof MouseEvent?I.MouseMove:I.TouchMove)}),i,{trailing:!1})),c=[J(\"mousemove\",u,t),J(\"touchmove\",u,t),J(\"drag\",u,t)];return O(()=>{c.forEach(h=>h())})}function Fh({mouseInteractionCb:s,doc:e,mirror:t,blockClass:r,blockSelector:i,sampling:n}){if(n.mouseInteraction===!1)return()=>{};const o=n.mouseInteraction===!0||n.mouseInteraction===void 0?{}:n.mouseInteraction,l=[];let a=null;const u=c=>h=>{const d=lt(h);if(X(d,r,i,!0))return;let m=null,g=c;if(\"pointerType\"in h){switch(h.pointerType){case\"mouse\":m=he.Mouse;break;case\"touch\":m=he.Touch;break;case\"pen\":m=he.Pen;break}m===he.Touch?K[c]===K.MouseDown?g=\"TouchStart\":K[c]===K.MouseUp&&(g=\"TouchEnd\"):he.Pen}else as(h)&&(m=he.Touch);m!==null?(a=m,(g.startsWith(\"Touch\")&&m===he.Touch||g.startsWith(\"Mouse\")&&m===he.Mouse)&&(m=null)):K[c]===K.Click&&(m=a,a=null);const p=as(h)?h.changedTouches[0]:h;if(!p)return;const f=t.getId(d),{clientX:S,clientY:b}=p;O(s)(x({type:K[g],id:f,x:S,y:b},m!==null&&{pointerType:m}))};return Object.keys(K).filter(c=>Number.isNaN(Number(c))&&!c.endsWith(\"_Departed\")&&o[c]!==!1).forEach(c=>{let h=Ce(c);const d=u(c);if(window.PointerEvent)switch(K[c]){case K.MouseDown:case K.MouseUp:h=h.replace(\"mouse\",\"pointer\");break;case K.TouchStart:case K.TouchEnd:return}l.push(J(h,d,e))}),O(()=>{l.forEach(c=>c())})}function No({scrollCb:s,doc:e,mirror:t,blockClass:r,blockSelector:i,sampling:n}){const o=O(st(O(l=>{const a=lt(l);if(!a||X(a,r,i,!0))return;const u=t.getId(a);if(a===e&&e.defaultView){const c=So(e.defaultView);s({id:u,x:c.left,y:c.top})}else s({id:u,x:a.scrollLeft,y:a.scrollTop})}),n.scroll||100));return J(\"scroll\",o,e)}function Uh({viewportResizeCb:s},{win:e}){let t=-1,r=-1;const i=O(st(O(()=>{const n=bo(),o=Co();(t!==n||r!==o)&&(s({width:Number(o),height:Number(n)}),t=n,r=o)}),200));return J(\"resize\",i,e)}const Bh=[\"INPUT\",\"TEXTAREA\",\"SELECT\"],Li=new WeakMap;function zh({inputCb:s,doc:e,mirror:t,blockClass:r,blockSelector:i,ignoreClass:n,ignoreSelector:o,maskInputOptions:l,maskInputFn:a,sampling:u,userTriggeredOnInput:c}){function h(b){let y=lt(b);const C=b.isTrusted,N=y&&y.tagName;if(y&&N===\"OPTION\"&&(y=v.parentElement(y)),!y||!N||Bh.indexOf(N)<0||X(y,r,i,!0)||y.classList.contains(n)||o&&y.matches(o))return;let D=y.value,H=!1;const _=fs(y)||\"\";_===\"radio\"||_===\"checkbox\"?H=y.checked:(l[N.toLowerCase()]||l[_])&&(D=hs({element:y,maskInputOptions:l,tagName:N,type:_,value:D,maskInputFn:a})),d(y,c?{text:D,isChecked:H,userTriggered:C}:{text:D,isChecked:H});const G=y.name;_===\"radio\"&&G&&H&&e.querySelectorAll(\\`input[type=\"radio\"][name=\"\\${G}\"]\\`).forEach(Y=>{if(Y!==y){const Q=Y.value;d(Y,c?{text:Q,isChecked:!H,userTriggered:!1}:{text:Q,isChecked:!H})}})}function d(b,y){const C=Li.get(b);if(!C||C.text!==y.text||C.isChecked!==y.isChecked){Li.set(b,y);const N=t.getId(b);O(s)(ee(x({},y),{id:N}))}}const g=(u.input===\"last\"?[\"change\"]:[\"input\",\"change\"]).map(b=>J(b,O(h),e)),p=e.defaultView;if(!p)return()=>{g.forEach(b=>b())};const f=p.Object.getOwnPropertyDescriptor(p.HTMLInputElement.prototype,\"value\"),S=[[p.HTMLInputElement.prototype,\"value\"],[p.HTMLInputElement.prototype,\"checked\"],[p.HTMLSelectElement.prototype,\"value\"],[p.HTMLTextAreaElement.prototype,\"value\"],[p.HTMLSelectElement.prototype,\"selectedIndex\"],[p.HTMLOptionElement.prototype,\"selected\"]];return f&&f.set&&g.push(...S.map(b=>hr(b[0],b[1],{set(){O(h)({target:this,isTrusted:!1})}},!1,p))),O(()=>{g.forEach(b=>b())})}function qt(s){const e=[];function t(r,i){if(Pt(\"CSSGroupingRule\")&&r.parentRule instanceof CSSGroupingRule||Pt(\"CSSMediaRule\")&&r.parentRule instanceof CSSMediaRule||Pt(\"CSSSupportsRule\")&&r.parentRule instanceof CSSSupportsRule||Pt(\"CSSConditionRule\")&&r.parentRule instanceof CSSConditionRule){const o=Array.from(r.parentRule.cssRules).indexOf(r);i.unshift(o)}else if(r.parentStyleSheet){const o=Array.from(r.parentStyleSheet.cssRules).indexOf(r);i.unshift(o)}return i}return t(s,e)}function de(s,e,t){let r,i;return s?(s.ownerNode?r=e.getId(s.ownerNode):i=t.getId(s),{styleId:i,id:r}):{}}function Wh({styleSheetRuleCb:s,mirror:e,stylesheetManager:t},{win:r}){if(!r.CSSStyleSheet||!r.CSSStyleSheet.prototype)return()=>{};const i=r.CSSStyleSheet.prototype.insertRule;r.CSSStyleSheet.prototype.insertRule=new Proxy(i,{apply:O((c,h,d)=>{const[m,g]=d,{id:p,styleId:f}=de(h,e,t.styleMirror);return(p&&p!==-1||f&&f!==-1)&&s({id:p,styleId:f,adds:[{rule:m,index:g}]}),c.apply(h,d)})}),r.CSSStyleSheet.prototype.addRule=function(c,h,d=this.cssRules.length){const m=\\`\\${c} { \\${h} }\\`;return r.CSSStyleSheet.prototype.insertRule.apply(this,[m,d])};const n=r.CSSStyleSheet.prototype.deleteRule;r.CSSStyleSheet.prototype.deleteRule=new Proxy(n,{apply:O((c,h,d)=>{const[m]=d,{id:g,styleId:p}=de(h,e,t.styleMirror);return(g&&g!==-1||p&&p!==-1)&&s({id:g,styleId:p,removes:[{index:m}]}),c.apply(h,d)})}),r.CSSStyleSheet.prototype.removeRule=function(c){return r.CSSStyleSheet.prototype.deleteRule.apply(this,[c])};let o;r.CSSStyleSheet.prototype.replace&&(o=r.CSSStyleSheet.prototype.replace,r.CSSStyleSheet.prototype.replace=new Proxy(o,{apply:O((c,h,d)=>{const[m]=d,{id:g,styleId:p}=de(h,e,t.styleMirror);return(g&&g!==-1||p&&p!==-1)&&s({id:g,styleId:p,replace:m}),c.apply(h,d)})}));let l;r.CSSStyleSheet.prototype.replaceSync&&(l=r.CSSStyleSheet.prototype.replaceSync,r.CSSStyleSheet.prototype.replaceSync=new Proxy(l,{apply:O((c,h,d)=>{const[m]=d,{id:g,styleId:p}=de(h,e,t.styleMirror);return(g&&g!==-1||p&&p!==-1)&&s({id:g,styleId:p,replaceSync:m}),c.apply(h,d)})}));const a={};Dt(\"CSSGroupingRule\")?a.CSSGroupingRule=r.CSSGroupingRule:(Dt(\"CSSMediaRule\")&&(a.CSSMediaRule=r.CSSMediaRule),Dt(\"CSSConditionRule\")&&(a.CSSConditionRule=r.CSSConditionRule),Dt(\"CSSSupportsRule\")&&(a.CSSSupportsRule=r.CSSSupportsRule));const u={};return Object.entries(a).forEach(([c,h])=>{u[c]={insertRule:h.prototype.insertRule,deleteRule:h.prototype.deleteRule},h.prototype.insertRule=new Proxy(u[c].insertRule,{apply:O((d,m,g)=>{const[p,f]=g,{id:S,styleId:b}=de(m.parentStyleSheet,e,t.styleMirror);return(S&&S!==-1||b&&b!==-1)&&s({id:S,styleId:b,adds:[{rule:p,index:[...qt(m),f||0]}]}),d.apply(m,g)})}),h.prototype.deleteRule=new Proxy(u[c].deleteRule,{apply:O((d,m,g)=>{const[p]=g,{id:f,styleId:S}=de(m.parentStyleSheet,e,t.styleMirror);return(f&&f!==-1||S&&S!==-1)&&s({id:f,styleId:S,removes:[{index:[...qt(m),p]}]}),d.apply(m,g)})})}),O(()=>{r.CSSStyleSheet.prototype.insertRule=i,r.CSSStyleSheet.prototype.deleteRule=n,o&&(r.CSSStyleSheet.prototype.replace=o),l&&(r.CSSStyleSheet.prototype.replaceSync=l),Object.entries(a).forEach(([c,h])=>{h.prototype.insertRule=u[c].insertRule,h.prototype.deleteRule=u[c].deleteRule})})}function ko({mirror:s,stylesheetManager:e},t){var r,i,n;let o=null;t.nodeName===\"#document\"?o=s.getId(t):o=s.getId(v.host(t));const l=t.nodeName===\"#document\"?(r=t.defaultView)==null?void 0:r.Document:(n=(i=t.ownerDocument)==null?void 0:i.defaultView)==null?void 0:n.ShadowRoot,a=l!=null&&l.prototype?Object.getOwnPropertyDescriptor(l==null?void 0:l.prototype,\"adoptedStyleSheets\"):void 0;return o===null||o===-1||!l||!a?()=>{}:(Object.defineProperty(t,\"adoptedStyleSheets\",{configurable:a.configurable,enumerable:a.enumerable,get(){var u;return(u=a.get)==null?void 0:u.call(this)},set(u){var c;const h=(c=a.set)==null?void 0:c.call(this,u);if(o!==null&&o!==-1)try{e.adoptStyleSheets(u,o)}catch(d){}return h}}),O(()=>{Object.defineProperty(t,\"adoptedStyleSheets\",{configurable:a.configurable,enumerable:a.enumerable,get:a.get,set:a.set})}))}function Gh({styleDeclarationCb:s,mirror:e,ignoreCSSAttributes:t,stylesheetManager:r},{win:i}){const n=i.CSSStyleDeclaration.prototype.setProperty;i.CSSStyleDeclaration.prototype.setProperty=new Proxy(n,{apply:O((l,a,u)=>{var c;const[h,d,m]=u;if(t.has(h))return n.apply(a,[h,d,m]);const{id:g,styleId:p}=de((c=a.parentRule)==null?void 0:c.parentStyleSheet,e,r.styleMirror);return(g&&g!==-1||p&&p!==-1)&&s({id:g,styleId:p,set:{property:h,value:d,priority:m},index:qt(a.parentRule)}),l.apply(a,u)})});const o=i.CSSStyleDeclaration.prototype.removeProperty;return i.CSSStyleDeclaration.prototype.removeProperty=new Proxy(o,{apply:O((l,a,u)=>{var c;const[h]=u;if(t.has(h))return o.apply(a,[h]);const{id:d,styleId:m}=de((c=a.parentRule)==null?void 0:c.parentStyleSheet,e,r.styleMirror);return(d&&d!==-1||m&&m!==-1)&&s({id:d,styleId:m,remove:{property:h},index:qt(a.parentRule)}),l.apply(a,u)})}),O(()=>{i.CSSStyleDeclaration.prototype.setProperty=n,i.CSSStyleDeclaration.prototype.removeProperty=o})}function Vh({mediaInteractionCb:s,blockClass:e,blockSelector:t,mirror:r,sampling:i,doc:n}){const o=O(a=>st(O(u=>{const c=lt(u);if(!c||X(c,e,t,!0))return;const{currentTime:h,volume:d,muted:m,playbackRate:g,loop:p}=c;s({type:a,id:r.getId(c),currentTime:h,volume:d,muted:m,playbackRate:g,loop:p})}),i.media||500)),l=[J(\"play\",o(Ae.Play),n),J(\"pause\",o(Ae.Pause),n),J(\"seeked\",o(Ae.Seeked),n),J(\"volumechange\",o(Ae.VolumeChange),n),J(\"ratechange\",o(Ae.RateChange),n)];return O(()=>{l.forEach(a=>a())})}function jh({fontCb:s,doc:e}){const t=e.defaultView;if(!t)return()=>{};const r=[],i=new WeakMap,n=t.FontFace;t.FontFace=function(a,u,c){const h=new n(a,u,c);return i.set(h,{family:a,buffer:typeof u!=\"string\",descriptors:c,fontSource:typeof u==\"string\"?u:JSON.stringify(Array.from(new Uint8Array(u)))}),h};const o=Fe(e.fonts,\"add\",function(l){return function(a){return setTimeout(O(()=>{const u=i.get(a);u&&(s(u),i.delete(a))}),0),l.apply(this,[a])}});return r.push(()=>{t.FontFace=n}),r.push(o),O(()=>{r.forEach(l=>l())})}function Hh(s){const{doc:e,mirror:t,blockClass:r,blockSelector:i,selectionCb:n}=s;let o=!0;const l=O(()=>{const a=e.getSelection();if(!a||o&&(a!=null&&a.isCollapsed))return;o=a.isCollapsed||!1;const u=[],c=a.rangeCount||0;for(let h=0;h<c;h++){const d=a.getRangeAt(h),{startContainer:m,startOffset:g,endContainer:p,endOffset:f}=d;X(m,r,i,!0)||X(p,r,i,!0)||u.push({start:t.getId(m),startOffset:g,end:t.getId(p),endOffset:f})}n({ranges:u})});return l(),J(\"selectionchange\",l)}function Yh({doc:s,customElementCb:e}){const t=s.defaultView;return!t||!t.customElements?()=>{}:Fe(t.customElements,\"define\",function(i){return function(n,o,l){try{e({define:{name:n}})}catch(a){console.warn(\\`Custom element callback failed for \\${n}\\`)}return i.apply(this,[n,o,l])}})}function Zh(s,e){const{mutationCb:t,mousemoveCb:r,mouseInteractionCb:i,scrollCb:n,viewportResizeCb:o,inputCb:l,mediaInteractionCb:a,styleSheetRuleCb:u,styleDeclarationCb:c,canvasMutationCb:h,fontCb:d,selectionCb:m,customElementCb:g}=s;s.mutationCb=(...p)=>{e.mutation&&e.mutation(...p),t(...p)},s.mousemoveCb=(...p)=>{e.mousemove&&e.mousemove(...p),r(...p)},s.mouseInteractionCb=(...p)=>{e.mouseInteraction&&e.mouseInteraction(...p),i(...p)},s.scrollCb=(...p)=>{e.scroll&&e.scroll(...p),n(...p)},s.viewportResizeCb=(...p)=>{e.viewportResize&&e.viewportResize(...p),o(...p)},s.inputCb=(...p)=>{e.input&&e.input(...p),l(...p)},s.mediaInteractionCb=(...p)=>{e.mediaInteaction&&e.mediaInteaction(...p),a(...p)},s.styleSheetRuleCb=(...p)=>{e.styleSheetRule&&e.styleSheetRule(...p),u(...p)},s.styleDeclarationCb=(...p)=>{e.styleDeclaration&&e.styleDeclaration(...p),c(...p)},s.canvasMutationCb=(...p)=>{e.canvasMutation&&e.canvasMutation(...p),h(...p)},s.fontCb=(...p)=>{e.font&&e.font(...p),d(...p)},s.selectionCb=(...p)=>{e.selection&&e.selection(...p),m(...p)},s.customElementCb=(...p)=>{e.customElement&&e.customElement(...p),g(...p)}}function Jh(s,e={}){const t=s.doc.defaultView;if(!t)return()=>{};Zh(s,e);let r;s.recordDOM&&(r=$o(s,s.doc));const i=_h(s),n=Fh(s),o=No(s),l=Uh(s,{win:t}),a=zh(s),u=Vh(s);let c=()=>{},h=()=>{},d=()=>{},m=()=>{};s.recordDOM&&(c=Wh(s,{win:t}),h=ko(s,s.doc),d=Gh(s,{win:t}),s.collectFonts&&(m=jh(s)));const g=Hh(s),p=Yh(s),f=[];for(const S of s.plugins)f.push(S.observer(S.callback,t,S.options));return O(()=>{be.forEach(S=>S.reset()),r==null||r.disconnect(),i(),n(),o(),l(),a(),u(),c(),h(),d(),m(),g(),p(),f.forEach(S=>S())})}function Pt(s){return typeof window[s]!=\"undefined\"}function Dt(s){return!!(typeof window[s]!=\"undefined\"&&window[s].prototype&&\"insertRule\"in window[s].prototype&&\"deleteRule\"in window[s].prototype)}class Ti{constructor(e){w(this,\"iframeIdToRemoteIdMap\",new WeakMap),w(this,\"iframeRemoteIdToIdMap\",new WeakMap),this.generateIdFn=e}getId(e,t,r,i){const n=r||this.getIdToRemoteIdMap(e),o=i||this.getRemoteIdToIdMap(e);let l=n.get(t);return l||(l=this.generateIdFn(),n.set(t,l),o.set(l,t)),l}getIds(e,t){const r=this.getIdToRemoteIdMap(e),i=this.getRemoteIdToIdMap(e);return t.map(n=>this.getId(e,n,r,i))}getRemoteId(e,t,r){const i=r||this.getRemoteIdToIdMap(e);if(typeof t!=\"number\")return t;const n=i.get(t);return n||-1}getRemoteIds(e,t){const r=this.getRemoteIdToIdMap(e);return t.map(i=>this.getRemoteId(e,i,r))}reset(e){if(!e){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(e),this.iframeRemoteIdToIdMap.delete(e)}getIdToRemoteIdMap(e){let t=this.iframeIdToRemoteIdMap.get(e);return t||(t=new Map,this.iframeIdToRemoteIdMap.set(e,t)),t}getRemoteIdToIdMap(e){let t=this.iframeRemoteIdToIdMap.get(e);return t||(t=new Map,this.iframeRemoteIdToIdMap.set(e,t)),t}}class Xh{constructor(e){w(this,\"iframes\",new WeakMap),w(this,\"crossOriginIframeMap\",new WeakMap),w(this,\"crossOriginIframeMirror\",new Ti(Yi)),w(this,\"crossOriginIframeStyleMirror\"),w(this,\"crossOriginIframeRootIdMap\",new WeakMap),w(this,\"mirror\"),w(this,\"mutationCb\"),w(this,\"wrappedEmit\"),w(this,\"loadListener\"),w(this,\"stylesheetManager\"),w(this,\"recordCrossOriginIframes\"),this.mutationCb=e.mutationCb,this.wrappedEmit=e.wrappedEmit,this.stylesheetManager=e.stylesheetManager,this.recordCrossOriginIframes=e.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new Ti(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=e.mirror,this.recordCrossOriginIframes&&window.addEventListener(\"message\",this.handleMessage.bind(this))}addIframe(e){this.iframes.set(e,!0),e.contentWindow&&this.crossOriginIframeMap.set(e.contentWindow,e)}addLoadListener(e){this.loadListener=e}attachIframe(e,t){var r,i;this.mutationCb({adds:[{parentId:this.mirror.getId(e),nextId:null,node:t}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),this.recordCrossOriginIframes&&((r=e.contentWindow)==null||r.addEventListener(\"message\",this.handleMessage.bind(this))),(i=this.loadListener)==null||i.call(this,e),e.contentDocument&&e.contentDocument.adoptedStyleSheets&&e.contentDocument.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(e.contentDocument.adoptedStyleSheets,this.mirror.getId(e.contentDocument))}handleMessage(e){const t=e;if(t.data.type!==\"rrweb\"||t.origin!==t.data.origin||!e.source)return;const i=this.crossOriginIframeMap.get(e.source);if(!i)return;const n=this.transformCrossOriginEvent(i,t.data.event);n&&this.wrappedEmit(n,t.data.isCheckout)}transformCrossOriginEvent(e,t){var r;switch(t.type){case R.FullSnapshot:{this.crossOriginIframeMirror.reset(e),this.crossOriginIframeStyleMirror.reset(e),this.replaceIdOnNode(t.data.node,e);const i=t.data.node.id;return this.crossOriginIframeRootIdMap.set(e,i),this.patchRootIdOnNode(t.data.node,i),{timestamp:t.timestamp,type:R.IncrementalSnapshot,data:{source:I.Mutation,adds:[{parentId:this.mirror.getId(e),nextId:null,node:t.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case R.Meta:case R.Load:case R.DomContentLoaded:return!1;case R.Plugin:return t;case R.Custom:return this.replaceIds(t.data.payload,e,[\"id\",\"parentId\",\"previousId\",\"nextId\"]),t;case R.IncrementalSnapshot:switch(t.data.source){case I.Mutation:return t.data.adds.forEach(i=>{this.replaceIds(i,e,[\"parentId\",\"nextId\",\"previousId\"]),this.replaceIdOnNode(i.node,e);const n=this.crossOriginIframeRootIdMap.get(e);n&&this.patchRootIdOnNode(i.node,n)}),t.data.removes.forEach(i=>{this.replaceIds(i,e,[\"parentId\",\"id\"])}),t.data.attributes.forEach(i=>{this.replaceIds(i,e,[\"id\"])}),t.data.texts.forEach(i=>{this.replaceIds(i,e,[\"id\"])}),t;case I.Drag:case I.TouchMove:case I.MouseMove:return t.data.positions.forEach(i=>{this.replaceIds(i,e,[\"id\"])}),t;case I.ViewportResize:return!1;case I.MediaInteraction:case I.MouseInteraction:case I.Scroll:case I.CanvasMutation:case I.Input:return this.replaceIds(t.data,e,[\"id\"]),t;case I.StyleSheetRule:case I.StyleDeclaration:return this.replaceIds(t.data,e,[\"id\"]),this.replaceStyleIds(t.data,e,[\"styleId\"]),t;case I.Font:return t;case I.Selection:return t.data.ranges.forEach(i=>{this.replaceIds(i,e,[\"start\",\"end\"])}),t;case I.AdoptedStyleSheet:return this.replaceIds(t.data,e,[\"id\"]),this.replaceStyleIds(t.data,e,[\"styleIds\"]),(r=t.data.styles)==null||r.forEach(i=>{this.replaceStyleIds(i,e,[\"styleId\"])}),t}}return!1}replace(e,t,r,i){for(const n of i)!Array.isArray(t[n])&&typeof t[n]!=\"number\"||(Array.isArray(t[n])?t[n]=e.getIds(r,t[n]):t[n]=e.getId(r,t[n]));return t}replaceIds(e,t,r){return this.replace(this.crossOriginIframeMirror,e,t,r)}replaceStyleIds(e,t,r){return this.replace(this.crossOriginIframeStyleMirror,e,t,r)}replaceIdOnNode(e,t){this.replaceIds(e,t,[\"id\",\"rootId\"]),\"childNodes\"in e&&e.childNodes.forEach(r=>{this.replaceIdOnNode(r,t)})}patchRootIdOnNode(e,t){e.type!==Mo.Document&&!e.rootId&&(e.rootId=t),\"childNodes\"in e&&e.childNodes.forEach(r=>{this.patchRootIdOnNode(r,t)})}}class Kh{constructor(e){w(this,\"shadowDoms\",new WeakSet),w(this,\"mutationCb\"),w(this,\"scrollCb\"),w(this,\"bypassOptions\"),w(this,\"mirror\"),w(this,\"restoreHandlers\",[]),this.mutationCb=e.mutationCb,this.scrollCb=e.scrollCb,this.bypassOptions=e.bypassOptions,this.mirror=e.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(e,t){if(!He(e)||this.shadowDoms.has(e))return;this.shadowDoms.add(e);const r=$o(ee(x({},this.bypassOptions),{doc:t,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this}),e);this.restoreHandlers.push(()=>r.disconnect()),this.restoreHandlers.push(No(ee(x({},this.bypassOptions),{scrollCb:this.scrollCb,doc:e,mirror:this.mirror}))),setTimeout(()=>{e.adoptedStyleSheets&&e.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(e.adoptedStyleSheets,this.mirror.getId(v.host(e))),this.restoreHandlers.push(ko({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},e))},0)}observeAttachShadow(e){!e.contentWindow||!e.contentDocument||this.patchAttachShadow(e.contentWindow.Element,e.contentDocument)}patchAttachShadow(e,t){const r=this;this.restoreHandlers.push(Fe(e.prototype,\"attachShadow\",function(i){return function(n){const o=i.call(this,n),l=v.shadowRoot(this);return l&&Ao(this)&&r.addShadowRoot(l,t),o}}))}reset(){this.restoreHandlers.forEach(e=>{try{e()}catch(t){}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet}}var $e=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",Qh=typeof Uint8Array==\"undefined\"?[]:new Uint8Array(256);for(var Lt=0;Lt<$e.length;Lt++)Qh[$e.charCodeAt(Lt)]=Lt;var qh=function(s){var e=new Uint8Array(s),t,r=e.length,i=\"\";for(t=0;t<r;t+=3)i+=$e[e[t]>>2],i+=$e[(e[t]&3)<<4|e[t+1]>>4],i+=$e[(e[t+1]&15)<<2|e[t+2]>>6],i+=$e[e[t+2]&63];return r%3===2?i=i.substring(0,i.length-1)+\"=\":r%3===1&&(i=i.substring(0,i.length-2)+\"==\"),i};const _i=new Map;function ef(s,e){let t=_i.get(s);return t||(t=new Map,_i.set(s,t)),t.has(e)||t.set(e,[]),t.get(e)}const Po=(s,e,t)=>{if(!s||!(Lo(s,e)||typeof s==\"object\"))return;const r=s.constructor.name,i=ef(t,r);let n=i.indexOf(s);return n===-1&&(n=i.length,i.push(s)),n};function Bt(s,e,t){if(s instanceof Array)return s.map(r=>Bt(r,e,t));if(s===null)return s;if(s instanceof Float32Array||s instanceof Float64Array||s instanceof Int32Array||s instanceof Uint32Array||s instanceof Uint8Array||s instanceof Uint16Array||s instanceof Int16Array||s instanceof Int8Array||s instanceof Uint8ClampedArray)return{rr_type:s.constructor.name,args:[Object.values(s)]};if(s instanceof ArrayBuffer){const r=s.constructor.name,i=qh(s);return{rr_type:r,base64:i}}else{if(s instanceof DataView)return{rr_type:s.constructor.name,args:[Bt(s.buffer,e,t),s.byteOffset,s.byteLength]};if(s instanceof HTMLImageElement){const r=s.constructor.name,{src:i}=s;return{rr_type:r,src:i}}else if(s instanceof HTMLCanvasElement){const r=\"HTMLImageElement\",i=s.toDataURL();return{rr_type:r,src:i}}else{if(s instanceof ImageData)return{rr_type:s.constructor.name,args:[Bt(s.data,e,t),s.width,s.height]};if(Lo(s,e)||typeof s==\"object\"){const r=s.constructor.name,i=Po(s,e,t);return{rr_type:r,index:i}}}}return s}const Do=(s,e,t)=>s.map(r=>Bt(r,e,t)),Lo=(s,e)=>!![\"WebGLActiveInfo\",\"WebGLBuffer\",\"WebGLFramebuffer\",\"WebGLProgram\",\"WebGLRenderbuffer\",\"WebGLShader\",\"WebGLShaderPrecisionFormat\",\"WebGLTexture\",\"WebGLUniformLocation\",\"WebGLVertexArrayObject\",\"WebGLVertexArrayObjectOES\"].filter(i=>typeof e[i]==\"function\").find(i=>s instanceof e[i]);function tf(s,e,t,r){const i=[],n=Object.getOwnPropertyNames(e.CanvasRenderingContext2D.prototype);for(const o of n)try{if(typeof e.CanvasRenderingContext2D.prototype[o]!=\"function\")continue;const l=Fe(e.CanvasRenderingContext2D.prototype,o,function(a){return function(...u){return X(this.canvas,t,r,!0)||setTimeout(()=>{const c=Do(u,e,this);s(this.canvas,{type:_e[\"2D\"],property:o,args:c})},0),a.apply(this,u)}});i.push(l)}catch(l){const a=hr(e.CanvasRenderingContext2D.prototype,o,{set(u){s(this.canvas,{type:_e[\"2D\"],property:o,args:[u],setter:!0})}});i.push(a)}return()=>{i.forEach(o=>o())}}function rf(s){return s===\"experimental-webgl\"?\"webgl\":s}function Fi(s,e,t,r){const i=[];try{const n=Fe(s.HTMLCanvasElement.prototype,\"getContext\",function(o){return function(l,...a){if(!X(this,e,t,!0)){const u=rf(l);if(\"__context\"in this||(this.__context=u),r&&[\"webgl\",\"webgl2\"].includes(u))if(a[0]&&typeof a[0]==\"object\"){const c=a[0];c.preserveDrawingBuffer||(c.preserveDrawingBuffer=!0)}else a.splice(0,1,{preserveDrawingBuffer:!0})}return o.apply(this,[l,...a])}});i.push(n)}catch(n){console.error(\"failed to patch HTMLCanvasElement.prototype.getContext\")}return()=>{i.forEach(n=>n())}}function Ui(s,e,t,r,i,n){const o=[],l=Object.getOwnPropertyNames(s);for(const a of l)if(![\"isContextLost\",\"canvas\",\"drawingBufferWidth\",\"drawingBufferHeight\"].includes(a))try{if(typeof s[a]!=\"function\")continue;const u=Fe(s,a,function(c){return function(...h){const d=c.apply(this,h);if(Po(d,n,this),\"tagName\"in this.canvas&&!X(this.canvas,r,i,!0)){const m=Do(h,n,this),g={type:e,property:a,args:m};t(this.canvas,g)}return d}});o.push(u)}catch(u){const c=hr(s,a,{set(h){t(this.canvas,{type:e,property:a,args:[h],setter:!0})}});o.push(c)}return o}function sf(s,e,t,r){const i=[];return i.push(...Ui(e.WebGLRenderingContext.prototype,_e.WebGL,s,t,r,e)),typeof e.WebGL2RenderingContext!=\"undefined\"&&i.push(...Ui(e.WebGL2RenderingContext.prototype,_e.WebGL2,s,t,r,e)),()=>{i.forEach(n=>n())}}const To=\"KGZ1bmN0aW9uKCkgewogICJ1c2Ugc3RyaWN0IjsKICB2YXIgY2hhcnMgPSAiQUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVphYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ejAxMjM0NTY3ODkrLyI7CiAgdmFyIGxvb2t1cCA9IHR5cGVvZiBVaW50OEFycmF5ID09PSAidW5kZWZpbmVkIiA/IFtdIDogbmV3IFVpbnQ4QXJyYXkoMjU2KTsKICBmb3IgKHZhciBpID0gMDsgaSA8IGNoYXJzLmxlbmd0aDsgaSsrKSB7CiAgICBsb29rdXBbY2hhcnMuY2hhckNvZGVBdChpKV0gPSBpOwogIH0KICB2YXIgZW5jb2RlID0gZnVuY3Rpb24oYXJyYXlidWZmZXIpIHsKICAgIHZhciBieXRlcyA9IG5ldyBVaW50OEFycmF5KGFycmF5YnVmZmVyKSwgaTIsIGxlbiA9IGJ5dGVzLmxlbmd0aCwgYmFzZTY0ID0gIiI7CiAgICBmb3IgKGkyID0gMDsgaTIgPCBsZW47IGkyICs9IDMpIHsKICAgICAgYmFzZTY0ICs9IGNoYXJzW2J5dGVzW2kyXSA+PiAyXTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMl0gJiAzKSA8PCA0IHwgYnl0ZXNbaTIgKyAxXSA+PiA0XTsKICAgICAgYmFzZTY0ICs9IGNoYXJzWyhieXRlc1tpMiArIDFdICYgMTUpIDw8IDIgfCB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zKGlkKSAmJiBhd2FpdCB0cmFuc3BhcmVudEJhc2U2NCA9PT0gYmFzZTY0KSB7CiAgICAgICAgbGFzdEJsb2JNYXAuc2V0KGlkLCBiYXNlNjQpOwogICAgICAgIHJldHVybiB3b3JrZXIucG9zdE1lc3NhZ2UoeyBpZCB9KTsKICAgICAgfQogICAgICBpZiAobGFzdEJsb2JNYXAuZ2V0KGlkKSA9PT0gYmFzZTY0KSByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQgfSk7CiAgICAgIHdvcmtlci5wb3N0TWVzc2FnZSh7CiAgICAgICAgaWQsCiAgICAgICAgdHlwZSwKICAgICAgICBiYXNlNjQsCiAgICAgICAgd2lkdGgsCiAgICAgICAgaGVpZ2h0CiAgICAgIH0pOwogICAgICBsYXN0QmxvYk1hcC5zZXQoaWQsIGJhc2U2NCk7CiAgICB9IGVsc2UgewogICAgICByZXR1cm4gd29ya2VyLnBvc3RNZXNzYWdlKHsgaWQ6IGUuZGF0YS5pZCB9KTsKICAgIH0KICB9Owp9KSgpOwovLyMgc291cmNlTWFwcGluZ1VSTD1pbWFnZS1iaXRtYXAtZGF0YS11cmwtd29ya2VyLUlKcEM3Z19iLmpzLm1hcAo=\",nf=s=>Uint8Array.from(atob(s),e=>e.charCodeAt(0)),Bi=typeof window!=\"undefined\"&&window.Blob&&new Blob([nf(To)],{type:\"text/javascript;charset=utf-8\"});function of(s){let e;try{if(e=Bi&&(window.URL||window.webkitURL).createObjectURL(Bi),!e)throw\"\";const t=new Worker(e,{name:s==null?void 0:s.name});return t.addEventListener(\"error\",()=>{(window.URL||window.webkitURL).revokeObjectURL(e)}),t}catch(t){return new Worker(\"data:text/javascript;base64,\"+To,{name:s==null?void 0:s.name})}finally{e&&(window.URL||window.webkitURL).revokeObjectURL(e)}}class af{constructor(e){w(this,\"pendingCanvasMutations\",new Map),w(this,\"rafStamps\",{latestId:0,invokeId:null}),w(this,\"mirror\"),w(this,\"mutationCb\"),w(this,\"resetObservers\"),w(this,\"frozen\",!1),w(this,\"locked\",!1),w(this,\"processMutation\",(a,u)=>{(this.rafStamps.invokeId&&this.rafStamps.latestId!==this.rafStamps.invokeId||!this.rafStamps.invokeId)&&(this.rafStamps.invokeId=this.rafStamps.latestId),this.pendingCanvasMutations.has(a)||this.pendingCanvasMutations.set(a,[]),this.pendingCanvasMutations.get(a).push(u)});const{sampling:t=\"all\",win:r,blockClass:i,blockSelector:n,recordCanvas:o,dataURLOptions:l}=e;this.mutationCb=e.mutationCb,this.mirror=e.mirror,o&&t===\"all\"&&this.initCanvasMutationObserver(r,i,n),o&&typeof t==\"number\"&&this.initCanvasFPSObserver(t,r,i,n,{dataURLOptions:l})}reset(){this.pendingCanvasMutations.clear(),this.resetObservers&&this.resetObservers()}freeze(){this.frozen=!0}unfreeze(){this.frozen=!1}lock(){this.locked=!0}unlock(){this.locked=!1}initCanvasFPSObserver(e,t,r,i,n){const o=Fi(t,r,i,!0),l=new Map,a=new of;a.onmessage=g=>{const{id:p}=g.data;if(l.set(p,!1),!(\"base64\"in g.data))return;const{base64:f,type:S,width:b,height:y}=g.data;this.mutationCb({id:p,type:_e[\"2D\"],commands:[{property:\"clearRect\",args:[0,0,b,y]},{property:\"drawImage\",args:[{rr_type:\"ImageBitmap\",args:[{rr_type:\"Blob\",data:[{rr_type:\"ArrayBuffer\",base64:f}],type:S}]},0,0]}]})};const u=1e3/e;let c=0,h;const d=()=>{const g=[];return t.document.querySelectorAll(\"canvas\").forEach(p=>{X(p,r,i,!0)||g.push(p)}),g},m=g=>{if(c&&g-c<u){h=requestAnimationFrame(m);return}c=g,d().forEach(async p=>{var f;const S=this.mirror.getId(p);if(l.get(S)||p.width===0||p.height===0)return;if(l.set(S,!0),[\"webgl\",\"webgl2\"].includes(p.__context)){const y=p.getContext(p.__context);((f=y==null?void 0:y.getContextAttributes())==null?void 0:f.preserveDrawingBuffer)===!1&&y.clear(y.COLOR_BUFFER_BIT)}const b=await createImageBitmap(p);a.postMessage({id:S,bitmap:b,width:p.width,height:p.height,dataURLOptions:n.dataURLOptions},[b])}),h=requestAnimationFrame(m)};h=requestAnimationFrame(m),this.resetObservers=()=>{o(),cancelAnimationFrame(h)}}initCanvasMutationObserver(e,t,r){this.startRAFTimestamping(),this.startPendingCanvasMutationFlusher();const i=Fi(e,t,r,!1),n=tf(this.processMutation.bind(this),e,t,r),o=sf(this.processMutation.bind(this),e,t,r);this.resetObservers=()=>{i(),n(),o()}}startPendingCanvasMutationFlusher(){requestAnimationFrame(()=>this.flushPendingCanvasMutations())}startRAFTimestamping(){const e=t=>{this.rafStamps.latestId=t,requestAnimationFrame(e)};requestAnimationFrame(e)}flushPendingCanvasMutations(){this.pendingCanvasMutations.forEach((e,t)=>{const r=this.mirror.getId(t);this.flushPendingCanvasMutationFor(t,r)}),requestAnimationFrame(()=>this.flushPendingCanvasMutations())}flushPendingCanvasMutationFor(e,t){if(this.frozen||this.locked)return;const r=this.pendingCanvasMutations.get(e);if(!r||t===-1)return;const i=r.map(o=>{const u=o,{type:l}=u;return xe(u,[\"type\"])}),{type:n}=r[0];this.mutationCb({id:t,type:n,commands:i}),this.pendingCanvasMutations.delete(e)}}class lf{constructor(e){w(this,\"trackedLinkElements\",new WeakSet),w(this,\"mutationCb\"),w(this,\"adoptedStyleSheetCb\"),w(this,\"styleMirror\",new Mh),this.mutationCb=e.mutationCb,this.adoptedStyleSheetCb=e.adoptedStyleSheetCb}attachLinkElement(e,t){\"_cssText\"in t.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:t.id,attributes:t.attributes}]}),this.trackLinkElement(e)}trackLinkElement(e){this.trackedLinkElements.has(e)||(this.trackedLinkElements.add(e),this.trackStylesheetInLinkElement(e))}adoptStyleSheets(e,t){if(e.length===0)return;const r={id:t,styleIds:[]},i=[];for(const n of e){let o;this.styleMirror.has(n)?o=this.styleMirror.getId(n):(o=this.styleMirror.add(n),i.push({styleId:o,rules:Array.from(n.rules||CSSRule,(l,a)=>({rule:Vi(l,n.href),index:a}))})),r.styleIds.push(o)}i.length>0&&(r.styles=i),this.adoptedStyleSheetCb(r)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(e){}}class uf{constructor(){w(this,\"nodeMap\",new WeakMap),w(this,\"active\",!1)}inOtherBuffer(e,t){const r=this.nodeMap.get(e);return r&&Array.from(r).some(i=>i!==t)}add(e,t){this.active||(this.active=!0,requestAnimationFrame(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(e,(this.nodeMap.get(e)||new Set).add(t))}destroy(){}}let W,zt,Er,er=!1;try{if(Array.from([1],s=>s*2)[0]!==2){const s=document.createElement(\"iframe\");document.body.appendChild(s),Array.from=((Gs=s.contentWindow)==null?void 0:Gs.Array.from)||Array.from,document.body.removeChild(s)}}catch(s){console.debug(\"Unable to override Array.from\",s)}const se=ua();function ut(s={}){const{emit:e,checkoutEveryNms:t,checkoutEveryNth:r,blockClass:i=\"rr-block\",blockSelector:n=null,ignoreClass:o=\"rr-ignore\",ignoreSelector:l=null,maskTextClass:a=\"rr-mask\",maskTextSelector:u=null,inlineStylesheet:c=!0,maskAllInputs:h,maskInputOptions:d,slimDOMOptions:m,maskInputFn:g,maskTextFn:p,hooks:f,packFn:S,sampling:b={},dataURLOptions:y={},mousemoveWait:C,recordDOM:N=!0,recordCanvas:D=!1,recordCrossOriginIframes:H=!1,recordAfter:_=s.recordAfter===\"DOMContentLoaded\"?s.recordAfter:\"load\",userTriggeredOnInput:G=!1,collectFonts:Y=!1,inlineImages:Q=!1,plugins:oe,keepIframeSrcFn:A=()=>!1,ignoreCSSAttributes:Ue=new Set([]),errorHandler:Be}=s;Lh(Be);const V=H?window.parent===window:!0;let q=!1;if(!V)try{window.parent.document&&(q=!1)}catch(M){q=!0}if(V&&!e)throw new Error(\"emit function is required\");if(!V&&!q)return()=>{};C!==void 0&&b.mousemove===void 0&&(b.mousemove=C),se.reset();const ye=h===!0?{color:!0,date:!0,\"datetime-local\":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,password:!0}:d!==void 0?d:{password:!0},ae=m===!0||m===\"all\"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:m===\"all\",headMetaDescKeywords:m===\"all\",headTitleMutations:m===\"all\"}:m||{};Ah();let Ts,fr=0;const _s=M=>{for(const re of oe||[])re.eventProcessor&&(M=re.eventProcessor(M));return S&&!q&&(M=S(M)),M};W=(M,re)=>{var B;const z=M;if(z.timestamp=Qt(),(B=be[0])!=null&&B.isFrozen()&&z.type!==R.FullSnapshot&&!(z.type===R.IncrementalSnapshot&&z.data.source===I.Mutation)&&be.forEach(le=>le.unfreeze()),V)e==null||e(_s(z),re);else if(q){const le={type:\"rrweb\",event:_s(z),origin:window.location.origin,isCheckout:re};window.parent.postMessage(le,\"*\")}if(z.type===R.FullSnapshot)Ts=z,fr=0;else if(z.type===R.IncrementalSnapshot){if(z.data.source===I.Mutation&&z.data.isAttachIframe)return;fr++;const le=r&&fr>=r,k=t&&z.timestamp-Ts.timestamp>t;(le||k)&&zt(!0)}};const ct=M=>{W({type:R.IncrementalSnapshot,data:x({source:I.Mutation},M)})},Fs=M=>W({type:R.IncrementalSnapshot,data:x({source:I.Scroll},M)}),Us=M=>W({type:R.IncrementalSnapshot,data:x({source:I.CanvasMutation},M)}),_o=M=>W({type:R.IncrementalSnapshot,data:x({source:I.AdoptedStyleSheet},M)}),we=new lf({mutationCb:ct,adoptedStyleSheetCb:_o}),Se=new Xh({mirror:se,mutationCb:ct,stylesheetManager:we,recordCrossOriginIframes:H,wrappedEmit:W});for(const M of oe||[])M.getMirror&&M.getMirror({nodeMirror:se,crossOriginIframeMirror:Se.crossOriginIframeMirror,crossOriginIframeStyleMirror:Se.crossOriginIframeStyleMirror});const pr=new uf;Er=new af({recordCanvas:D,mutationCb:Us,win:window,blockClass:i,blockSelector:n,mirror:se,sampling:b.canvas,dataURLOptions:y});const ht=new Kh({mutationCb:ct,scrollCb:Fs,bypassOptions:{blockClass:i,blockSelector:n,maskTextClass:a,maskTextSelector:u,inlineStylesheet:c,maskInputOptions:ye,dataURLOptions:y,maskTextFn:p,maskInputFn:g,recordCanvas:D,inlineImages:Q,sampling:b,slimDOMOptions:ae,iframeManager:Se,stylesheetManager:we,canvasManager:Er,keepIframeSrcFn:A,processedNodeManager:pr},mirror:se});zt=(M=!1)=>{if(!N)return;W({type:R.Meta,data:{href:window.location.href,width:Co(),height:bo()}},M),we.reset(),ht.init(),be.forEach(B=>B.lock());const re=Pa(document,{mirror:se,blockClass:i,blockSelector:n,maskTextClass:a,maskTextSelector:u,inlineStylesheet:c,maskAllInputs:ye,maskTextFn:p,maskInputFn:g,slimDOM:ae,dataURLOptions:y,recordCanvas:D,inlineImages:Q,onSerialize:B=>{xo(B,se)&&Se.addIframe(B),Oo(B,se)&&we.trackLinkElement(B),ls(B)&&ht.addShadowRoot(v.shadowRoot(B),document)},onIframeLoad:(B,z)=>{Se.attachIframe(B,z),ht.observeAttachShadow(B)},onStylesheetLoad:(B,z)=>{we.attachLinkElement(B,z)},keepIframeSrcFn:A});if(!re)return console.warn(\"Failed to snapshot the document\");W({type:R.FullSnapshot,data:{node:re,initialOffset:So(window)}},M),be.forEach(B=>B.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&we.adoptStyleSheets(document.adoptedStyleSheets,se.getId(document))};try{const M=[],re=z=>{var le;return O(Jh)({mutationCb:ct,mousemoveCb:(k,dr)=>W({type:R.IncrementalSnapshot,data:{source:dr,positions:k}}),mouseInteractionCb:k=>W({type:R.IncrementalSnapshot,data:x({source:I.MouseInteraction},k)}),scrollCb:Fs,viewportResizeCb:k=>W({type:R.IncrementalSnapshot,data:x({source:I.ViewportResize},k)}),inputCb:k=>W({type:R.IncrementalSnapshot,data:x({source:I.Input},k)}),mediaInteractionCb:k=>W({type:R.IncrementalSnapshot,data:x({source:I.MediaInteraction},k)}),styleSheetRuleCb:k=>W({type:R.IncrementalSnapshot,data:x({source:I.StyleSheetRule},k)}),styleDeclarationCb:k=>W({type:R.IncrementalSnapshot,data:x({source:I.StyleDeclaration},k)}),canvasMutationCb:Us,fontCb:k=>W({type:R.IncrementalSnapshot,data:x({source:I.Font},k)}),selectionCb:k=>{W({type:R.IncrementalSnapshot,data:x({source:I.Selection},k)})},customElementCb:k=>{W({type:R.IncrementalSnapshot,data:x({source:I.CustomElement},k)})},blockClass:i,ignoreClass:o,ignoreSelector:l,maskTextClass:a,maskTextSelector:u,maskInputOptions:ye,inlineStylesheet:c,sampling:b,recordDOM:N,recordCanvas:D,inlineImages:Q,userTriggeredOnInput:G,collectFonts:Y,doc:z,maskInputFn:g,maskTextFn:p,keepIframeSrcFn:A,blockSelector:n,slimDOMOptions:ae,dataURLOptions:y,mirror:se,iframeManager:Se,stylesheetManager:we,shadowDomManager:ht,processedNodeManager:pr,canvasManager:Er,ignoreCSSAttributes:Ue,plugins:((le=oe==null?void 0:oe.filter(k=>k.observer))==null?void 0:le.map(k=>({observer:k.observer,options:k.options,callback:dr=>W({type:R.Plugin,data:{plugin:k.name,payload:dr}})})))||[]},f)};Se.addLoadListener(z=>{try{M.push(re(z.contentDocument))}catch(le){console.warn(le)}});const B=()=>{zt(),M.push(re(document)),er=!0};return document.readyState===\"interactive\"||document.readyState===\"complete\"?B():(M.push(J(\"DOMContentLoaded\",()=>{W({type:R.DomContentLoaded,data:{}}),_===\"DOMContentLoaded\"&&B()})),M.push(J(\"load\",()=>{W({type:R.Load,data:{}}),_===\"load\"&&B()},window))),()=>{M.forEach(z=>z()),pr.destroy(),er=!1,Th()}}catch(M){console.warn(M)}}ut.addCustomEvent=(s,e)=>{if(!er)throw new Error(\"please add custom event after start recording\");W({type:R.Custom,data:{tag:s,payload:e}})};ut.freezePage=()=>{be.forEach(s=>s.freeze())};ut.takeFullSnapshot=s=>{if(!er)throw new Error(\"please take full snapshot after start recording\");zt(s)};ut.mirror=se;var zi;(function(s){s[s.NotStarted=0]=\"NotStarted\",s[s.Running=1]=\"Running\",s[s.Stopped=2]=\"Stopped\"})(zi||(zi={}));exports.record=ut;\nif (typeof module.exports == \"object\" && typeof exports == \"object\") {\n  var __cp = (to, from, except, desc) => {\n    if ((from && typeof from === \"object\") || typeof from === \"function\") {\n      for (let key of Object.getOwnPropertyNames(from)) {\n        if (!Object.prototype.hasOwnProperty.call(to, key) && key !== except)\n        Object.defineProperty(to, key, {\n          get: () => from[key],\n          enumerable: !(desc = Object.getOwnPropertyDescriptor(from, key)) || desc.enumerable,\n        });\n      }\n    }\n    return to;\n  };\n  module.exports = __cp(module.exports, exports);\n}\nreturn module.exports;\n}))\n//# sourceMappingURL=record.umd.min.cjs.map`;\n","import {\n  errorMessage,\n  type SessionRecordingOptions,\n  type StringUUID,\n} from \"@lmnr-ai/types\";\nimport { Page as PlaywrightPage } from \"playwright\";\nimport { Page as PuppeteerPage } from \"puppeteer\";\n\nimport { LaminarClient } from \"..\";\nimport { initializeLogger } from \"../utils\";\nimport { RECORDER } from \"./recorder\";\n\nexport const LMNR_SEND_EVENTS_FUNCTION_NAME = \"lmnrSendEvents\";\n\nconst logger = initializeLogger();\n\ninterface LmnrWindow extends Window {\n  lmnrRrwebEventsBatch: any[];\n  lmnrChunkSequence: number;\n  lmnrSendInProgress: boolean;\n  lmnrStartedRecordingEvents: boolean;\n  lmnrRrweb: any;\n  lmnrSendEvents: (chunk: any) => void;\n}\n\n/**\n * If the first argument is a string, return an object with the name of the method\n * and the argument as the value.\n * Otherwise, return the shallow copy of the arguments.\n *\n * This is useful for Stagehand, where the first argument is often a string, but is named\n * 'instruction', so we add a name to it on the spans.\n *\n * @param args - Args of a function.\n * @param name - The name to add on the first argument if it is a string.\n * @returns The arguments as an object with the name of the method and the argument\n * as the value, or the arguments as is.\n */\nexport const nameArgsOrCopy = (args: any[], name: string = \"instruction\") => {\n  if (args.length === 1 && typeof args[0] === \"string\") {\n    return { [name]: args[0] };\n  }\n  return [...args];\n};\n\nexport interface EventChunk {\n  batchId: string;\n  chunkIndex: number;\n  totalChunks: number;\n  data: string;\n  isFinal: boolean;\n}\n\nexport const takeFullSnapshot = async (\n  page: PlaywrightPage | PuppeteerPage,\n): Promise<boolean> =>\n  await (page as PlaywrightPage).evaluate(() => {\n    if ((window as unknown as LmnrWindow).lmnrRrweb) {\n      try {\n        (window as unknown as LmnrWindow).lmnrRrweb.record.takeFullSnapshot();\n        return true;\n      } catch (error) {\n        logger.error(\"Error taking full snapshot: \" + errorMessage(error));\n        return false;\n      }\n    }\n    return false;\n  });\n\nexport const injectSessionRecorder = async (\n  page: PlaywrightPage | PuppeteerPage,\n  sessionRecordingOptions?: SessionRecordingOptions,\n) => {\n  const tryRunScript = async <R>(\n    script: (...args: any[]) => Promise<R>,\n    maxAttempts: number = 5,\n  ): Promise<R | undefined> => {\n    for (let i = 0; i < maxAttempts; i++) {\n      try {\n        return await script();\n      } catch (error) {\n        logger.error(\n          \"Operation \" + script.name + \" failed: \" + errorMessage(error),\n        );\n      }\n      await new Promise((resolve) => setTimeout(resolve, 500));\n    }\n  };\n\n  // Both Puppeteer and Playwright have a evaluate method, but the types are different\n  // and TypeScript is not liking that the signature is different.\n\n  const castedPage = page as PlaywrightPage;\n\n  let isRrwebPresent = false;\n  try {\n    isRrwebPresent = await castedPage.evaluate(\n      () => typeof (window as unknown as LmnrWindow).lmnrRrweb !== \"undefined\",\n    );\n  } catch (error) {\n    logger.debug(\n      \"Failed to check if session recorder is loaded: \" + errorMessage(error),\n    );\n  }\n\n  // Load rrweb and set up recording\n  if (!isRrwebPresent) {\n    const result = await tryRunScript(async function injectSessionRecorder() {\n      await castedPage.evaluate(RECORDER);\n      return true;\n    });\n    if (!result) {\n      logger.error(\"Failed to load session recorder\");\n      return;\n    }\n    try {\n      await castedPage.evaluate(injectScript, sessionRecordingOptions);\n    } catch (error) {\n      logger.debug(\"Failed to inject session recorder: \" + errorMessage(error));\n    }\n  }\n};\n\n// Removes the heavy client prop and the apiKey to avoid security issues\nexport const cleanStagehandLLMClient = (llmClient: object): object =>\n  Object.fromEntries(\n    Object.entries(llmClient)\n      .filter(([key]) => key !== \"client\")\n      .map(([key, value]) =>\n        key === \"clientOptions\"\n          ? [\n              key,\n              Object.fromEntries(\n                Object.entries(value).filter(([key]) => key !== \"apiKey\"),\n              ),\n            ]\n          : [key, value],\n      ),\n  );\n\n// Stagehand uses zod 3.x or 4.x, so we need to support both versions via duck-typing\nexport const prettyPrintZodSchema = (schema: any, indent = 2): string => {\n  // Use duck-typing instead of instanceof to support both Zod v3 and v4\n  const def = schema?._def;\n  if (!def || def.typeName !== \"ZodObject\") {\n    throw new Error(\"Not a Zod object schema\");\n  }\n\n  const indentString = \" \".repeat(indent);\n\n  const shape = schema.shape;\n  const entries = Object.entries(shape);\n\n  const reconstructed: string[] = entries.map(([key, value]) => {\n    // Base type detection function using duck-typing\n    const getBaseType = (val: any): string => {\n      const valDef = val?._def;\n      if (!valDef) return \"z.unknown()\";\n\n      const typeName = valDef.typeName;\n\n      if (typeName === \"ZodString\") {\n        return \"z.string()\";\n      }\n      if (typeName === \"ZodNumber\") {\n        return \"z.number()\";\n      }\n      if (typeName === \"ZodBoolean\") {\n        return \"z.boolean()\";\n      }\n      if (typeName === \"ZodArray\") {\n        const elementType = valDef.type;\n        if (elementType?._def?.typeName === \"ZodObject\") {\n          return `z.array(${prettyPrintZodSchema(elementType)})`;\n        } else {\n          return `z.array(${getBaseType(elementType)})`;\n        }\n      }\n      if (typeName === \"ZodObject\") {\n        return prettyPrintZodSchema(val);\n      }\n      if (typeName === \"ZodEnum\") {\n        const enumValues = valDef.values;\n        if (Array.isArray(enumValues)) {\n          return `z.enum([${enumValues.map((v) => `'${v}'`).join(\", \")}])`;\n        }\n        return \"z.enum([...])\";\n      }\n      if (typeName === \"ZodLiteral\") {\n        const literalValue = valDef.value;\n        if (typeof literalValue === \"string\") {\n          return `z.literal('${literalValue}')`;\n        }\n        return `z.literal(${literalValue})`;\n      }\n      if (typeName === \"ZodUnion\") {\n        const options = valDef.options;\n        if (Array.isArray(options)) {\n          return `z.union([${options.map(getBaseType).join(\", \")}])`;\n        }\n        return \"z.union([...])\";\n      }\n      if (typeName === \"ZodDate\") {\n        return \"z.date()\";\n      }\n      if (typeName === \"ZodRecord\") {\n        const keyType = valDef.keyType;\n        const valueType = valDef.valueType;\n\n        let keyTypeStr = \"z.string()\";\n        if (keyType && keyType._def?.typeName !== \"ZodString\") {\n          keyTypeStr = getBaseType(keyType);\n        }\n\n        let valueTypeStr = \"z.any()\";\n        if (valueType) {\n          valueTypeStr = getBaseType(valueType);\n        }\n\n        return `z.record(${keyTypeStr}, ${valueTypeStr})`;\n      }\n      if (typeName === \"ZodMap\") {\n        const keyType = valDef.keyType;\n        const valueType = valDef.valueType;\n\n        let keyTypeStr = \"z.any()\";\n        if (keyType) {\n          keyTypeStr = getBaseType(keyType);\n        }\n\n        let valueTypeStr = \"z.any()\";\n        if (valueType) {\n          valueTypeStr = getBaseType(valueType);\n        }\n\n        return `z.map(${keyTypeStr}, ${valueTypeStr})`;\n      }\n      if (typeName === \"ZodTuple\") {\n        const items = valDef.items;\n\n        if (Array.isArray(items)) {\n          const itemsTypeStr = items\n            .map((item) => getBaseType(item))\n            .join(\", \");\n          return `z.tuple([${itemsTypeStr}])`;\n        }\n        return \"z.tuple([])\";\n      }\n      if (typeName === \"ZodNullable\") {\n        return `${getBaseType(valDef.innerType)}.nullable()`;\n      }\n      if (typeName === \"ZodOptional\") {\n        return `${getBaseType(valDef.innerType)}.optional()`;\n      }\n      // Add more type checks as needed\n      return \"z.any()\";\n    };\n\n    // Check for modifiers and description\n    const applyModifiers = (val: any, baseType: string): string => {\n      let result = baseType;\n      let currentVal = val;\n\n      // Check for .nullable() modifier using duck-typing\n      if (currentVal?._def?.typeName === \"ZodNullable\") {\n        result = `${getBaseType(currentVal._def.innerType)}.nullable()`;\n        currentVal = currentVal._def.innerType;\n      }\n\n      // Check for .optional() modifier using duck-typing\n      if (currentVal?._def?.typeName === \"ZodOptional\") {\n        if (!result.endsWith(\".nullable()\")) {\n          result = `${getBaseType(currentVal._def.innerType)}.optional()`;\n        }\n      }\n\n      // Check for description\n      const description = val?._def?.description;\n      if (typeof description === \"string\") {\n        result += `.describe('${description.replace(/'/g, \"\\\\'\")}')`;\n      }\n\n      return result;\n    };\n\n    const baseType = getBaseType(value);\n    const finalType = applyModifiers(value, baseType);\n\n    return `${indentString}${key}: ${finalType},`;\n  });\n\n  return `z.object({\\n${reconstructed.join(\"\\n\")}\\n})`;\n};\n\n// copied from https://github.com/browserbase/stagehand/blob/main/lib/llm/LLMProvider.ts#L62\nconst modelToProviderMap: Record<string, string> = {\n  \"gpt-4.1\": \"openai\",\n  \"gpt-4.1-mini\": \"openai\",\n  \"gpt-4.1-nano\": \"openai\",\n  \"o4-mini\": \"openai\",\n  //prettier-ignore\n  o3: \"openai\",\n  \"o3-mini\": \"openai\",\n  //prettier-ignore\n  o1: \"openai\",\n  \"o1-mini\": \"openai\",\n  \"gpt-4o\": \"openai\",\n  \"gpt-4o-mini\": \"openai\",\n  \"gpt-4o-2024-08-06\": \"openai\",\n  \"gpt-4.5-preview\": \"openai\",\n  \"o1-preview\": \"openai\",\n  \"claude-3-5-sonnet-latest\": \"anthropic\",\n  \"claude-3-5-sonnet-20240620\": \"anthropic\",\n  \"claude-3-5-sonnet-20241022\": \"anthropic\",\n  \"claude-3-7-sonnet-20250219\": \"anthropic\",\n  \"claude-3-7-sonnet-latest\": \"anthropic\",\n  \"cerebras-llama-3.3-70b\": \"cerebras\",\n  \"cerebras-llama-3.1-8b\": \"cerebras\",\n  \"groq-llama-3.3-70b-versatile\": \"groq\",\n  \"groq-llama-3.3-70b-specdec\": \"groq\",\n  \"moonshotai/kimi-k2-instruct\": \"groq\",\n  \"gemini-1.5-flash\": \"google\",\n  \"gemini-1.5-pro\": \"google\",\n  \"gemini-1.5-flash-8b\": \"google\",\n  \"gemini-2.0-flash-lite\": \"google\",\n  \"gemini-2.0-flash\": \"google\",\n  \"gemini-2.5-flash-preview-04-17\": \"google\",\n  \"gemini-2.5-pro-preview-03-25\": \"google\",\n};\n\nexport const modelToProvider = (model: string): string | undefined => {\n  const clean = model.toLowerCase().trim();\n  if (clean.startsWith(\"gpt-\") || clean.match(/^o\\d-/)) {\n    return \"openai\";\n  }\n  if (clean.startsWith(\"claude-\")) {\n    return \"anthropic\";\n  }\n  if (clean.startsWith(\"gemini-\")) {\n    return \"google\";\n  }\n  if (clean.startsWith(\"cerebras-\")) {\n    return \"cerebras\";\n  }\n  if (clean.startsWith(\"groq-\")) {\n    return \"groq\";\n  }\n  return modelToProviderMap[clean];\n};\n\n/**\n * The session recording inject script function.\n * This function runs in the browser context and sets up rrweb recording.\n * Exported so it can be converted to a string for CDP Runtime.evaluate.\n * @param {SessionRecordingOptions} sessionRecordingOptions - Optional recording options\n * for masking inputs\n * @param {boolean} stringifyCallbackArgs - If true, stringify arguments when calling\n * lmnrSendEvents (for raw CDP bindings).\n */\nexport const injectScript = (\n  sessionRecordingOptions?: SessionRecordingOptions,\n  stringifyCallbackArgs?: boolean,\n) => {\n  const BATCH_TIMEOUT = 2000; // Send events every 2 seconds\n  const HEARTBEAT_INTERVAL = 1000;\n  const CHUNK_SIZE = 256 * 1024; // 256KB chunks for CDP message limits\n\n  (window as unknown as LmnrWindow).lmnrRrwebEventsBatch = [];\n  (window as unknown as LmnrWindow).lmnrChunkSequence = 0;\n  (window as unknown as LmnrWindow).lmnrSendInProgress = false;\n\n  // Define a wrapper function that handles stringification based on the parameter\n  const sendEvent = stringifyCallbackArgs\n    ? (chunk: any) =>\n        (window as unknown as LmnrWindow).lmnrSendEvents(JSON.stringify(chunk))\n    : (chunk: any) => (window as unknown as LmnrWindow).lmnrSendEvents(chunk);\n\n  // Gzip compress a string using CompressionStream API (main thread, no workers)\n  const gzipCompress = async (\n    str: string,\n  ): Promise<Uint8Array<ArrayBuffer>> => {\n    const encoder = new TextEncoder();\n    const inputBytes = encoder.encode(str);\n\n    const cs = new CompressionStream(\"gzip\");\n    const writer = cs.writable.getWriter();\n    const reader = cs.readable.getReader();\n\n    // TODO: investigate why the events are not sent if we await the write and close\n    writer.write(inputBytes);\n    writer.close();\n\n    const parts = [];\n    let totalLength = 0;\n    while (true) {\n      const { done, value } = await reader.read();\n      if (done) break;\n      parts.push(value);\n      totalLength += value.length;\n    }\n\n    const result = new Uint8Array(totalLength);\n    let offset = 0;\n    for (const part of parts) {\n      result.set(part, offset);\n      offset += part.length;\n    }\n    return result;\n  };\n\n  // Convert a Uint8Array to base64 string\n  const bufferToBase64 = async (\n    buffer: Uint8Array<ArrayBuffer>,\n  ): Promise<string> => {\n    const base64url = await new Promise<string>((r) => {\n      const reader = new FileReader();\n      reader.onload = () => r(reader.result as string);\n      reader.readAsDataURL(new Blob([buffer]));\n    });\n    return base64url.slice(base64url.indexOf(\",\") + 1);\n  };\n\n  // Create chunks from a string with metadata\n  const createChunks = (str: string, batchId: string): EventChunk[] => {\n    const chunks = [];\n    const totalChunks = Math.ceil(str.length / CHUNK_SIZE);\n\n    for (let i = 0; i < str.length; i += CHUNK_SIZE) {\n      const chunk = str.slice(i, i + CHUNK_SIZE);\n      chunks.push({\n        batchId: batchId,\n        chunkIndex: chunks.length,\n        totalChunks: totalChunks,\n        data: chunk,\n        isFinal: chunks.length === totalChunks - 1,\n      });\n    }\n\n    return chunks;\n  };\n\n  const sendBatchIfReady = async () => {\n    if ((window as unknown as LmnrWindow).lmnrRrwebEventsBatch.length === 0) {\n      return;\n    }\n    if (\n      typeof (window as unknown as LmnrWindow).lmnrSendEvents !== \"function\"\n    ) {\n      return;\n    }\n    // Prevent overlapping sends - if previous send is still in progress,\n    // events stay in the batch and will be picked up next interval\n    if ((window as unknown as LmnrWindow).lmnrSendInProgress) {\n      return;\n    }\n\n    (window as unknown as LmnrWindow).lmnrSendInProgress = true;\n    const events = (window as unknown as LmnrWindow).lmnrRrwebEventsBatch;\n    (window as unknown as LmnrWindow).lmnrRrwebEventsBatch = [];\n\n    try {\n      // Compress each event's data field individually\n      const compressedEvents = [];\n      for (const event of events) {\n        try {\n          const dataString = JSON.stringify(event.data);\n          const compressed = await gzipCompress(dataString);\n          const base64Data = await bufferToBase64(compressed);\n          compressedEvents.push({\n            ...event,\n            data: base64Data,\n          });\n        } catch (e) {\n          console.error(\"Failed to compress event:\", e);\n        }\n      }\n\n      const batchId = `${Date.now()}_${(window as unknown as LmnrWindow).lmnrChunkSequence++}`;\n      const batchString = JSON.stringify(compressedEvents);\n\n      if (batchString.length <= CHUNK_SIZE) {\n        sendEvent({\n          batchId: batchId,\n          chunkIndex: 0,\n          totalChunks: 1,\n          data: batchString,\n          isFinal: true,\n        });\n      } else {\n        const chunks = createChunks(batchString, batchId);\n        for (const chunk of chunks) {\n          sendEvent(chunk);\n        }\n      }\n    } catch (error) {\n      console.error(\"Failed to send events:\", error);\n    } finally {\n      (window as unknown as LmnrWindow).lmnrSendInProgress = false;\n    }\n  };\n\n  if (!(window as unknown as LmnrWindow).lmnrStartedRecordingEvents) {\n    // It's fine to retrigger the interval even if the original function\n    // is async and still running.\n    setInterval(sendBatchIfReady, BATCH_TIMEOUT);\n\n    const recordOptions = {\n      emit(event: any) {\n        // Synchronous emit - just push to batch, no async processing.\n        // Compression happens later in sendBatchIfReady.\n        (window as unknown as LmnrWindow).lmnrRrwebEventsBatch.push(event);\n      },\n      recordCanvas: true,\n      collectFonts: true,\n      recordCrossOriginIframes: true,\n      maskInputOptions: {\n        password: true,\n        textarea: sessionRecordingOptions?.maskInputOptions?.textarea || false,\n        text: sessionRecordingOptions?.maskInputOptions?.text || false,\n        number: sessionRecordingOptions?.maskInputOptions?.number || false,\n        select: sessionRecordingOptions?.maskInputOptions?.select || false,\n        email: sessionRecordingOptions?.maskInputOptions?.email || false,\n        tel: sessionRecordingOptions?.maskInputOptions?.tel || false,\n      },\n    };\n\n    (window as unknown as LmnrWindow).lmnrRrweb.record(recordOptions);\n\n    // Heartbeat events to indicate the session is still alive\n    setInterval(() => {\n      try {\n        (window as unknown as LmnrWindow).lmnrRrweb.record.addCustomEvent(\n          \"heartbeat\",\n          {\n            title: document.title,\n            url: document.URL,\n          },\n        );\n      } catch {\n        // Sometimes due to race conditions with raw CDP events, recorder may\n        // not be initialized at this point, so we re-initialized here\n        (window as unknown as LmnrWindow).lmnrRrweb.record(recordOptions);\n      }\n    }, HEARTBEAT_INTERVAL);\n\n    (window as unknown as LmnrWindow).lmnrStartedRecordingEvents = true;\n  }\n};\n\n// Buffer for storing incomplete chunk batches\nexport interface ChunkBuffer {\n  chunks: Map<number, string>;\n  total: number;\n  timestamp: number;\n}\n\nconst OLD_BUFFER_TIMEOUT = 60000; // 60 seconds in milliseconds\n\nexport async function sendEvents(\n  chunk: EventChunk,\n  client: LaminarClient,\n  chunkBuffers: Map<string, ChunkBuffer>,\n  sessionId: StringUUID,\n  traceId: StringUUID,\n): Promise<void> {\n  try {\n    // Handle chunked data\n    const { batchId, chunkIndex, totalChunks, data } = chunk;\n\n    // Validate required fields\n    if (!sessionId || !traceId) {\n      logger.debug(\"Missing sessionId or traceId in chunk\");\n      return;\n    }\n\n    // Initialize buffer for this batch if needed\n    if (!chunkBuffers.has(batchId)) {\n      chunkBuffers.set(batchId, {\n        chunks: new Map(),\n        total: totalChunks,\n        timestamp: Date.now(),\n      });\n    }\n\n    const buffer = chunkBuffers.get(batchId)!;\n\n    // Store chunk\n    buffer.chunks.set(chunkIndex, data);\n\n    // Check if we have all chunks\n    if (buffer.chunks.size === totalChunks) {\n      // Reassemble the full message\n      let fullData = \"\";\n      for (let i = 0; i < totalChunks; i++) {\n        fullData += buffer.chunks.get(i);\n      }\n\n      // Parse the JSON\n      const events = JSON.parse(fullData) as Record<string, any>[];\n\n      // Send to server\n      if (events && events.length > 0) {\n        // Fire and forget - don't await to avoid blocking\n        await client.browserEvents\n          .send({ sessionId, traceId, events })\n          .catch((error) => {\n            logger.debug(\"Failed to send events: \" + errorMessage(error));\n          });\n      }\n\n      // Clean up buffer\n      chunkBuffers.delete(batchId);\n    }\n\n    // Clean up old incomplete buffers\n    const currentTime = Date.now();\n    const toDelete: string[] = [];\n\n    for (const [bid, buffer] of chunkBuffers.entries()) {\n      if (currentTime - buffer.timestamp > OLD_BUFFER_TIMEOUT) {\n        toDelete.push(bid);\n      }\n    }\n\n    for (const bid of toDelete) {\n      logger.debug(`Cleaning up incomplete chunk buffer: ${bid}`);\n      chunkBuffers.delete(bid);\n    }\n  } catch (error) {\n    logger.debug(\"Could not send events: \" + errorMessage(error));\n  }\n}\n","// biome-ignore-all lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\nimport { LaminarClient } from \"@lmnr-ai/client\";\nimport { errorMessage, SessionRecordingOptions } from \"@lmnr-ai/types\";\nimport { diag, type Span, trace } from \"@opentelemetry/api\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\nimport type * as PlaywrightLib from \"playwright\";\nimport type { Browser, BrowserContext, Page } from \"playwright\";\n\nimport { version as SDK_VERSION } from \"../../package.json\";\nimport { observe } from \"../decorators\";\nimport { Laminar } from \"../laminar\";\nimport { TRACE_HAS_BROWSER_SESSION } from \"../opentelemetry-lib/tracing/attributes\";\nimport { LaminarContextManager } from \"../opentelemetry-lib/tracing/context\";\nimport {\n  initializeLogger,\n  NIL_UUID,\n  newUUID,\n  otelTraceIdToUUID,\n  StringUUID,\n} from \"../utils\";\nimport {\n  ChunkBuffer,\n  EventChunk,\n  injectSessionRecorder,\n  LMNR_SEND_EVENTS_FUNCTION_NAME,\n  sendEvents,\n  takeFullSnapshot,\n} from \"./utils\";\n\nconst logger = initializeLogger();\n\nexport class PlaywrightInstrumentation extends InstrumentationBase {\n  private _patchedBrowsers: Set<Browser> = new Set();\n  private _parentSpans: Map<StringUUID, Span> = new Map();\n  private _client: LaminarClient;\n  private _sessionRecordingOptions?: SessionRecordingOptions;\n\n  constructor(\n    client: LaminarClient,\n    sessionRecordingOptions?: SessionRecordingOptions,\n  ) {\n    super(\"@lmnr/playwright-instrumentation\", SDK_VERSION, {\n      enabled: true,\n    });\n    this._client = client;\n    this._sessionRecordingOptions = sessionRecordingOptions;\n  }\n\n  // It's the caller's responsibility to ensure the span is ended\n  public setParentSpanForSession(sessionId: StringUUID, span: Span) {\n    this._parentSpans.set(sessionId, span);\n  }\n\n  public removeAndEndParentSpanForSession(sessionId: StringUUID) {\n    const span = this._parentSpans.get(sessionId);\n    if (span && span.isRecording()) {\n      span.end();\n    }\n    this._parentSpans.delete(sessionId);\n  }\n\n  public getParentSpanForSession(sessionId: StringUUID): Span | undefined {\n    return this._parentSpans.get(sessionId);\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    const module = new InstrumentationNodeModuleDefinition(\n      \"playwright\",\n      // TODO: test if the older versions work\n      [\">=1.0.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n\n    return module;\n  }\n\n  public manuallyInstrument(pwModule: {\n    chromium?: typeof PlaywrightLib.chromium;\n    firefox?: typeof PlaywrightLib.firefox;\n    webkit?: typeof PlaywrightLib.webkit;\n  }) {\n    const browsers = [\n      pwModule.chromium,\n      pwModule.firefox,\n      pwModule.webkit,\n    ] as const;\n\n    for (const browserType of browsers) {\n      if (browserType) {\n        this._wrap(browserType, \"launch\", this.patchNewBrowser());\n\n        this._wrap(browserType, \"connect\", this.patchNewBrowser());\n\n        this._wrap(browserType, \"connectOverCDP\", this.patchNewBrowser());\n\n        this._wrap(\n          browserType,\n          \"launchPersistentContext\",\n          this.patchBrowserNewContext(),\n        );\n      }\n    }\n\n    return pwModule;\n  }\n\n  private patch(moduleExports: typeof PlaywrightLib, moduleVersion?: string) {\n    diag.debug(`patching playwright ${moduleVersion}`);\n    const browsers = [\"chromium\", \"firefox\", \"webkit\"] as const;\n\n    for (const browserType of browsers) {\n      if (moduleExports[browserType]) {\n        // First we need to patch the browser launch to get access to the Page class\n        this._wrap(\n          moduleExports[browserType],\n          `launch`,\n          this.patchNewBrowser(),\n        );\n\n        this._wrap(\n          moduleExports[browserType],\n          `connect`,\n          this.patchNewBrowser(),\n        );\n\n        this._wrap(\n          moduleExports[browserType],\n          \"connectOverCDP\",\n          this.patchNewBrowser(),\n        );\n\n        this._wrap(\n          moduleExports[browserType],\n          \"launchPersistentContext\",\n          this.patchBrowserNewContext(),\n        );\n      }\n    }\n\n    return moduleExports;\n  }\n\n  private unpatch(moduleExports: typeof PlaywrightLib, moduleVersion?: string) {\n    diag.debug(`unpatching playwright ${moduleVersion}`);\n    const browsers = [\"chromium\", \"firefox\", \"webkit\"] as const;\n\n    for (const browserType of browsers) {\n      if (moduleExports[browserType]) {\n        // First we need to patch the browser launch to get access to the Page class\n        this._wrap(\n          moduleExports[browserType],\n          `launch`,\n          this.patchNewBrowser(),\n        );\n      }\n    }\n\n    for (const browser of this._patchedBrowsers) {\n      this._unwrap(browser, \"newContext\");\n    }\n  }\n\n  private patchNewBrowser() {\n    const plugin = this;\n    return (original: Function) =>\n      async function method(this: Browser, ...args: any[]) {\n        const browser: Browser = await original.call(this, ...args);\n        const sessionId = newUUID();\n\n        for (const context of browser.contexts()) {\n          context.on(\"page\", (page: Page) => plugin.patchPage(page, sessionId));\n          for (const page of context.pages()) {\n            await plugin.patchPage(page, sessionId);\n          }\n        }\n\n        plugin._wrap(browser, \"newContext\", plugin.patchBrowserNewContext());\n\n        plugin._patchedBrowsers.add(browser);\n        return browser;\n      };\n  }\n\n  private patchBrowserNewContext() {\n    const plugin = this;\n    return (original: Function) =>\n      async function method(this: Browser, ...args: unknown[]) {\n        const context: BrowserContext = await original\n          .bind(this)\n          .apply(this, args);\n        const sessionId = newUUID();\n        // Patch pages created by browser, e.g. new tab\n        context.on(\"page\", async (page) => plugin.patchPage(page, sessionId));\n\n        // Patch pages that are already created\n        for (const page of context.pages()) {\n          await plugin.patchPage(page, sessionId);\n        }\n\n        return context;\n      };\n  }\n\n  public async patchPage(page: Page, sessionId: StringUUID) {\n    const wrapped = async () => {\n      // Note: be careful with await here, if the await is removed,\n      // this creates a race condition, and playwright fails.\n      await observe({ name: \"playwright.page\" }, async () => {\n        await this._patchPage(page, sessionId);\n      });\n    };\n\n    const parentSpan = this.getParentSpanForSession(sessionId);\n    if (parentSpan) {\n      return await Laminar.withSpan(parentSpan, wrapped);\n    }\n\n    return await wrapped();\n  }\n\n  private async _patchPage(page: Page, sessionId: StringUUID) {\n    const originalBringToFront = page.bringToFront.bind(page);\n    page.bringToFront = async () => {\n      await originalBringToFront();\n      await takeFullSnapshot(page);\n    };\n\n    const currentSpan =\n      trace.getSpan(LaminarContextManager.getContext()) ??\n      trace.getActiveSpan();\n    currentSpan?.setAttribute(TRACE_HAS_BROWSER_SESSION, true);\n    const otelTraceId = currentSpan?.spanContext().traceId;\n    const traceId = otelTraceId ? otelTraceIdToUUID(otelTraceId) : NIL_UUID;\n\n    page.on(\"domcontentloaded\", async () => {\n      try {\n        await injectSessionRecorder(page, this._sessionRecordingOptions);\n      } catch (error) {\n        logger.error(\"Error in onLoad handler: \" + errorMessage(error));\n      }\n    });\n\n    const chunkBuffers = new Map<string, ChunkBuffer>();\n\n    await injectSessionRecorder(page, this._sessionRecordingOptions);\n    try {\n      await page.exposeFunction(\n        LMNR_SEND_EVENTS_FUNCTION_NAME,\n        async (chunk: EventChunk) => {\n          await sendEvents(\n            chunk,\n            this._client,\n            chunkBuffers,\n            sessionId,\n            traceId,\n          );\n        },\n      );\n    } catch (error) {\n      logger.debug(\n        \"Could not expose function \" +\n          LMNR_SEND_EVENTS_FUNCTION_NAME +\n          \": \" +\n          errorMessage(error),\n      );\n    }\n  }\n}\n","import { trace } from \"@opentelemetry/api\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\n\nimport { observe as laminarObserve } from \"../../decorators\";\nimport { SPAN_TYPE } from \"../../opentelemetry-lib/tracing/attributes\";\nimport { LaminarContextManager } from \"../../opentelemetry-lib/tracing/context\";\nimport { modelToProvider } from \"../utils\";\n\nexport interface GlobalLLMClientOptions {\n  provider: \"openai\" | \"anthropic\" | \"cerebras\" | \"groq\" | (string & {});\n  model: string;\n}\n\ninterface CreateChatCompletionOptions {\n  options: {\n    messages?: any[];\n    temperature?: number;\n    top_p?: number;\n    frequency_penalty?: number;\n    presence_penalty?: number;\n    maxTokens?: number;\n    maxOutputTokens?: number;\n    response_model?: {\n      name: string;\n      schema: any;\n    };\n    tools?: any[];\n  };\n  logger?: (message: any) => void;\n  retries?: number;\n}\n\ninterface LLMResponse {\n  id: string;\n  object: string;\n  created: number;\n  model: string;\n  choices?: {\n    index: number;\n    message: {\n      role: string;\n      content: string | null;\n      tool_calls?: {\n        id: string;\n        type: string;\n        function: {\n          name: string;\n          arguments: string;\n        };\n      }[];\n    };\n    finish_reason: string;\n  }[];\n  usage: {\n    prompt_tokens: number;\n    completion_tokens: number;\n    total_tokens: number;\n  };\n}\n\n/**\n * Creates a wrapper function for LLM client's createChatCompletion method\n * that adds OpenTelemetry tracing with detailed span attributes.\n *\n * This wrapper is shared between Stagehand v2 and v3 instrumentations.\n *\n * @param globalLLMClientOptions - WeakMap to track LLM client options (provider and model)\n * @returns A wrapper function compatible with OpenTelemetry's _wrap method\n */\nexport const createLLMClientCreateChatCompletionWrapper =\n  (globalLLMClientOptions: WeakMap<any, GlobalLLMClientOptions | undefined>) =>\n  (original: (...args: any[]) => Promise<any>) =>\n    async function createChatCompletion(this: any, ...args: any[]) {\n      const options = args[0] as CreateChatCompletionOptions;\n      return await laminarObserve(\n        {\n          name: \"createChatCompletion\",\n          // input and output are set as gen_ai.prompt and gen_ai.completion\n          ignoreInput: true,\n          ignoreOutput: true,\n        },\n        async () => {\n          const currentSpan =\n            trace.getSpan(LaminarContextManager.getContext()) ??\n            trace.getActiveSpan();\n          const span = currentSpan!;\n          const innerOptions = options.options;\n          const recordedProvider = globalLLMClientOptions.get(this)?.provider;\n          const provider =\n            recordedProvider === \"aisdk\" &&\n            globalLLMClientOptions.get(this)?.model\n              ? (modelToProvider(globalLLMClientOptions.get(this)!.model) ??\n                \"aisdk\")\n              : recordedProvider;\n\n          // Set request attributes\n          span.setAttributes({\n            [SPAN_TYPE]: \"LLM\",\n            ...(innerOptions.temperature\n              ? {\n                  \"gen_ai.request.temperature\": innerOptions.temperature,\n                }\n              : {}),\n            ...(innerOptions.top_p\n              ? {\n                  \"gen_ai.request.top_p\": innerOptions.top_p,\n                }\n              : {}),\n            ...(innerOptions.frequency_penalty\n              ? {\n                  \"gen_ai.request.frequency_penalty\":\n                    innerOptions.frequency_penalty,\n                }\n              : {}),\n            ...(innerOptions.presence_penalty\n              ? {\n                  \"gen_ai.request.presence_penalty\":\n                    innerOptions.presence_penalty,\n                }\n              : {}),\n            ...(innerOptions.maxTokens !== undefined ||\n            innerOptions.maxOutputTokens !== undefined\n              ? {\n                  \"gen_ai.request.max_tokens\":\n                    innerOptions.maxTokens ?? innerOptions.maxOutputTokens,\n                }\n              : {}),\n            ...(globalLLMClientOptions.get(this)\n              ? {\n                  \"gen_ai.request.model\":\n                    globalLLMClientOptions.get(this)?.model,\n                  \"gen_ai.system\": provider,\n                }\n              : {}),\n          });\n\n          // Set message attributes\n          innerOptions.messages?.forEach((message, index) => {\n            span.setAttributes({\n              [`gen_ai.prompt.${index}.role`]: message.role,\n              [`gen_ai.prompt.${index}.content`]: JSON.stringify(\n                message.content,\n              ),\n            });\n          });\n\n          // Set tool/function attributes\n          innerOptions.tools?.forEach((tool, index) => {\n            span.setAttributes({\n              [`llm.request.functions.${index}.name`]: tool.name,\n              [`llm.request.functions.${index}.description`]: tool.description,\n              [`llm.request.functions.${index}.parameters`]: JSON.stringify(\n                tool.parameters,\n              ),\n            });\n          });\n\n          // Set structured output schema if present\n          if (innerOptions.response_model?.schema) {\n            const schema = zodToJsonSchema(innerOptions.response_model.schema);\n            if (schema) {\n              span.setAttributes({\n                [`gen_ai.request.structured_output_schema`]:\n                  JSON.stringify(schema),\n              });\n            }\n          }\n\n          // Execute the original method\n          const result = (await original\n            .bind(this)\n            .apply(this, args)) as LLMResponse;\n\n          // Set response attributes\n          span.setAttributes({\n            \"gen_ai.response.model\": result.model,\n            \"gen_ai.usage.input_tokens\": result.usage?.prompt_tokens ?? 0,\n            \"gen_ai.usage.output_tokens\": result.usage?.completion_tokens ?? 0,\n            \"llm.usage.total_tokens\": result.usage?.total_tokens ?? 0,\n          });\n\n          // Set completion attributes\n          result.choices?.forEach((choice) => {\n            const index = choice.index;\n            span.setAttributes({\n              [`gen_ai.completion.${index}.finish_reason`]:\n                choice.finish_reason,\n              [`gen_ai.completion.${index}.role`]: choice.message.role,\n            });\n            if (choice.message.content) {\n              span.setAttribute(\n                `gen_ai.completion.${index}.content`,\n                JSON.stringify(choice.message.content),\n              );\n            }\n            choice.message.tool_calls?.forEach((toolCall, toolCallIndex) => {\n              span.setAttributes({\n                [`gen_ai.completion.${index}.message.tool_calls.${toolCallIndex}.id`]:\n                  toolCall.id,\n                [`gen_ai.completion.${index}.message.tool_calls.${toolCallIndex}.name`]:\n                  toolCall.function.name,\n                [`gen_ai.completion.${index}.message.tool_calls.${toolCallIndex}.arguments`]:\n                  JSON.stringify(toolCall.function.arguments),\n              });\n            });\n          });\n\n          // Handle special case when choices is empty (structured output mode)\n          if (!result.choices || result.choices.length === 0) {\n            const data = (result as any).data;\n            if (data) {\n              span.setAttributes({\n                \"gen_ai.completion.0.role\": \"assistant\",\n                \"gen_ai.completion.0.content\":\n                  typeof data === \"string\" ? data : JSON.stringify(data),\n              });\n            }\n          }\n\n          return result;\n        },\n      );\n    };\n","// biome-ignore-all lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\nimport { diag, trace } from \"@opentelemetry/api\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\nimport { z } from \"zod/v3\";\n\nimport { version as SDK_VERSION } from \"../../../package.json\";\nimport { observe as laminarObserve } from \"../../decorators\";\nimport { Laminar } from \"../../laminar\";\nimport { LaminarContextManager } from \"../../opentelemetry-lib/tracing/context\";\nimport { newUUID, StringUUID } from \"../../utils\";\nimport { PlaywrightInstrumentation } from \"../playwright\";\nimport {\n  cleanStagehandLLMClient,\n  nameArgsOrCopy,\n  prettyPrintZodSchema,\n} from \"../utils\";\nimport { createLLMClientCreateChatCompletionWrapper } from \"./shared-llm-wrapper\";\n\n// Stagehand interfaces:\ntype AvailableModel = string;\n\ninterface ActOptions {\n  action: string;\n  modelName?: AvailableModel;\n  modelClientOptions?: any; // ClientOptions\n  variables?: Record<string, string>;\n  domSettleTimeoutMs?: number;\n  timeoutMs?: number;\n  iframes?: boolean;\n  frameId?: string;\n}\ntype LLMResponse = {\n  id: string;\n  object: string;\n  created: number;\n  model: string;\n  choices: {\n    index: number;\n    message: {\n      role: string;\n      content: string | null;\n      tool_calls: {\n        id: string;\n        type: string;\n        function: {\n          name: string;\n          arguments: string;\n        };\n      }[];\n    };\n    finish_reason: string;\n  }[];\n  usage: {\n    prompt_tokens: number;\n    completion_tokens: number;\n    total_tokens: number;\n  };\n};\n\ninterface ChatCompletionInnerOptions {\n  messages: any[]; // ChatMessage[]\n  temperature?: number;\n  top_p?: number;\n  frequency_penalty?: number;\n  presence_penalty?: number;\n  image?: {\n    buffer: Buffer;\n    description?: string;\n  };\n  response_model?: {\n    name: string;\n    schema: any; // ZodType\n  };\n  tools?: any[]; // LLMTool[]\n  tool_choice?: \"auto\" | \"none\" | \"required\";\n  maxTokens?: number;\n  requestId?: string;\n}\n\ninterface CreateChatCompletionOptions {\n  options: ChatCompletionInnerOptions;\n  logger: (message: any) => void;\n  retries?: number;\n}\n\ndeclare abstract class LLMClient {\n  type: \"openai\" | \"anthropic\" | \"cerebras\" | \"groq\" | (string & {});\n  modelName: AvailableModel | (string & {});\n  hasVision: boolean;\n  clientOptions: any; // ClientOptions\n  userProvidedInstructions?: string;\n  constructor(modelName: AvailableModel, userProvidedInstructions?: string);\n  abstract createChatCompletion<T = LLMResponse>(\n    options: CreateChatCompletionOptions,\n  ): Promise<T>;\n  generateText: (args: any) => Promise<any>;\n  streamText: (args: any) => any;\n  streamObject: (args: any) => any;\n  generateImage: (args: any) => Promise<any>;\n  embed: (args: any) => Promise<any>;\n  embedMany: (args: any) => Promise<any>;\n  transcribe: (args: any) => Promise<any>;\n  generateSpeech: (args: any) => Promise<any>;\n}\n\ninterface StagehandPage {\n  act: (args: any) => Promise<any>;\n  extract: (args: any) => Promise<any>;\n  observe: (args: any) => Promise<any>;\n  on: (args: any) => any;\n}\n// ================================\n\ninterface GlobalLLMClientOptions {\n  // named `type` in Stagehand\n  provider: \"openai\" | \"anthropic\" | \"cerebras\" | \"groq\" | (string & {});\n  model: string;\n}\n\ntype AgentClient = {\n  execute: (instructionOrOptions: string | object) => Promise<object>;\n};\n\nexport class StagehandV2Instrumentation extends InstrumentationBase {\n  private playwrightInstrumentation: PlaywrightInstrumentation;\n  private globalLLMClientOptions: WeakMap<\n    LLMClient,\n    GlobalLLMClientOptions | undefined\n  > = new WeakMap();\n  private globalAgentOptions: WeakMap<object, Record<string, any> | undefined> =\n    new WeakMap();\n  private stagehandInstanceToSessionId: WeakMap<object, StringUUID> =\n    new WeakMap();\n\n  constructor(playwrightInstrumentation: PlaywrightInstrumentation) {\n    super(\"@lmnr/browserbase-stagehand-instrumentation\", SDK_VERSION, {\n      enabled: true,\n    });\n    this.playwrightInstrumentation = playwrightInstrumentation;\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    const module = new InstrumentationNodeModuleDefinition(\n      \"@browserbasehq/stagehand\",\n      [\">=1.0.0 <3.0.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n\n    return module;\n  }\n\n  private patch(moduleExports: any, moduleVersion?: string) {\n    diag.debug(`patching stagehand ${moduleVersion}`);\n    // Check if Stagehand is non-configurable\n    const descriptor = Object.getOwnPropertyDescriptor(\n      moduleExports,\n      \"Stagehand\",\n    );\n    if (descriptor && !descriptor.configurable) {\n      // Create a proxy for the entire module exports\n      const originalStagehand = moduleExports.Stagehand;\n      const patchedConstructor =\n        this.patchStagehandConstructor()(originalStagehand);\n\n      // Create a proxy for the module exports\n      return new Proxy(moduleExports, {\n        get: (target, prop) => {\n          if (prop === \"Stagehand\") {\n            return patchedConstructor;\n          }\n          return target[prop as keyof typeof target];\n        },\n      });\n    } else {\n      // If it's configurable, use the standard _wrap method\n      this._wrap(moduleExports, \"Stagehand\", this.patchStagehandConstructor());\n\n      return moduleExports;\n    }\n  }\n\n  public manuallyInstrument(Stagehand: any) {\n    diag.debug(\"manually instrumenting stagehand\");\n\n    // Since we can't replace the Stagehand constructor directly due to non-configurable property,\n    // we'll patch the prototype methods of the existing constructor\n\n    // First, patch the init method on the prototype\n    if (Stagehand && Stagehand.prototype) {\n      this._wrap(Stagehand.prototype, \"init\", this.patchStagehandInit());\n      this._wrap(Stagehand.prototype, \"close\", this.patchStagehandClose());\n    }\n  }\n\n  private unpatch(moduleExports: any, moduleVersion?: string) {\n    diag.debug(`unpatching stagehand ${moduleVersion}`);\n    this._unwrap(moduleExports, \"Stagehand\");\n\n    if (moduleExports.Stagehand) {\n      this._unwrap(moduleExports.Stagehand.prototype, \"init\");\n      this._unwrap(moduleExports.Stagehand.prototype, \"close\");\n      if (moduleExports.Stagehand.prototype?.page) {\n        this._unwrap(moduleExports.Stagehand.prototype.page, \"act\");\n        this._unwrap(moduleExports.Stagehand.prototype.page, \"extract\");\n        this._unwrap(moduleExports.Stagehand.prototype.page, \"observe\");\n        const observeHandler =\n          moduleExports.Stagehand.prototype.page.observeHandler;\n        if (observeHandler) {\n          this._unwrap(observeHandler, \"observe\");\n        }\n        const extractHandler =\n          moduleExports.Stagehand.prototype.page.extractHandler;\n        if (extractHandler) {\n          this._unwrap(extractHandler, \"textExtract\");\n          this._unwrap(extractHandler, \"domExtract\");\n        }\n        const actHandler = moduleExports.Stagehand.prototype.page.actHandler;\n        if (actHandler) {\n          this._unwrap(actHandler, \"act\");\n        }\n      }\n    }\n\n    return moduleExports;\n  }\n\n  private patchStagehandConstructor() {\n    const instrumentation = this;\n\n    return (Original: any) => {\n      // Create a constructor function that maintains the same signature\n      const Stagehand = function (\n        this: InstanceType<typeof Original>,\n        ...args: any[]\n      ) {\n        // Only apply if this is a new instance\n        if (!(this instanceof Stagehand)) {\n          return new Stagehand(...args);\n        }\n\n        const instance = new Original(args.length > 0 ? args[0] : undefined);\n        Object.assign(this, instance);\n\n        instrumentation._wrap(\n          this,\n          \"init\",\n          instrumentation.patchStagehandInit(),\n        );\n\n        instrumentation._wrap(\n          this,\n          \"close\",\n          instrumentation.patchStagehandClose(),\n        );\n\n        return this;\n      } as unknown as typeof Original;\n\n      // Copy static properties\n      Object.setPrototypeOf(Stagehand, Original);\n      // Copy prototype properties\n      Stagehand.prototype = Object.create(Original.prototype);\n      Stagehand.prototype.constructor = Stagehand;\n\n      return Stagehand;\n    };\n  }\n\n  private patchStagehandInit() {\n    const instrumentation = this;\n\n    return (original: any) =>\n      async function method(this: any) {\n        const sessionId = newUUID();\n\n        // Make sure the parent span is set before calling the original init method\n        // so that playwright instrumentation does not set its default parent span\n        const parentSpan = Laminar.startSpan({\n          name: \"Stagehand\",\n        });\n        instrumentation.playwrightInstrumentation.setParentSpanForSession(\n          sessionId,\n          parentSpan,\n        );\n\n        const result = await original.bind(this).apply(this);\n        for (const page of this.context.pages()) {\n          await instrumentation.playwrightInstrumentation.patchPage(\n            page,\n            sessionId,\n          );\n        }\n        await instrumentation.playwrightInstrumentation.patchPage(\n          this.page,\n          sessionId,\n        );\n\n        instrumentation._wrap(\n          this,\n          \"agent\",\n          instrumentation.patchStagehandAgentInitializer(sessionId),\n        );\n\n        // when new playwright page opens, we need to add playwright instrumentation\n        // to it and instrument the stagehand page stored on the stagehand instance\n        this.context.on(\"page\", async (page: any) => {\n          await instrumentation.playwrightInstrumentation.patchPage(\n            page,\n            sessionId,\n          );\n          instrumentation.patchStagehandPage(this.stagehandPage, sessionId);\n        });\n\n        instrumentation.patchStagehandPage(this.stagehandPage, sessionId);\n        if (this.llmClient) {\n          instrumentation.globalLLMClientOptions.set(this.llmClient, {\n            provider: this.llmClient.type,\n            model: this.llmClient.modelName,\n          });\n          instrumentation._wrap(\n            this.llmClient,\n            \"createChatCompletion\",\n            instrumentation.patchStagehandLLMClientCreateChatCompletion(),\n          );\n        }\n\n        instrumentation.stagehandInstanceToSessionId.set(this, sessionId);\n        return result;\n      };\n  }\n\n  private patchStagehandClose() {\n    const instrumentation = this;\n    return (original: Function) =>\n      async function method(this: any, ...args: any[]) {\n        // Clean up the session from the registry\n        const sessionId =\n          instrumentation.stagehandInstanceToSessionId.get(this);\n        if (sessionId) {\n          instrumentation.playwrightInstrumentation.removeAndEndParentSpanForSession(\n            sessionId,\n          );\n          instrumentation.stagehandInstanceToSessionId.delete(this);\n        }\n\n        await original.bind(this).apply(this, args);\n      };\n  }\n\n  private patchStagehandPage(page: StagehandPage, sessionId: StringUUID) {\n    const actHandler = (page as any).actHandler;\n    if (actHandler) {\n      if (actHandler.act) {\n        this._wrap(actHandler, \"act\", this.patchStagehandV1ActHandlerAct());\n      }\n      if (actHandler.actFromObserveResult) {\n        this._wrap(\n          actHandler,\n          \"actFromObserveResult\",\n          this.patchStagehandV2ActHandlerActFromObserveResult(),\n        );\n      }\n      if (actHandler.observeAct) {\n        this._wrap(\n          actHandler,\n          \"observeAct\",\n          this.patchStagehandV2ActHandlerObserveAct(),\n        );\n      }\n    }\n\n    const observeHandler = (page as any).observeHandler;\n    if (observeHandler) {\n      this._wrap(\n        observeHandler,\n        \"observe\",\n        this.patchStagehandObserveHandler(),\n      );\n    }\n\n    const extractHandler = (page as any).extractHandler;\n    if (extractHandler) {\n      if (extractHandler.textExtract) {\n        this._wrap(\n          extractHandler,\n          \"textExtract\",\n          this.patchStagehandExtractHandlerTextExtract(),\n        );\n      }\n\n      if (extractHandler.domExtract) {\n        this._wrap(\n          extractHandler,\n          \"domExtract\",\n          this.patchStagehandExtractHandlerDomExtract(),\n        );\n      }\n    }\n\n    this._wrap(page, \"act\", this.patchStagehandGlobalMethod(\"act\", sessionId));\n\n    this._wrap(\n      page,\n      \"extract\",\n      this.patchStagehandGlobalMethod(\"extract\", sessionId),\n    );\n\n    this._wrap(\n      page,\n      \"observe\",\n      this.patchStagehandGlobalMethod(\"observe\", sessionId),\n    );\n  }\n\n  private patchStagehandGlobalMethod(\n    methodName: string,\n    sessionId: StringUUID,\n  ) {\n    const instrumentation = this;\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function method(this: any, ...args: any[]) {\n        const input = nameArgsOrCopy(args);\n        if (\n          methodName === \"extract\" &&\n          Array.isArray(input) &&\n          input.length > 0 &&\n          input[0]?.schema\n        ) {\n          // We need to clone the input object to avoid mutating the original object\n          // because the original object is passed to the LLM client\n          const { schema, ...rest } = input[0];\n          let prettySchema = schema?.shape;\n          try {\n            prettySchema = prettyPrintZodSchema(schema);\n          } catch (error) {\n            diag.warn(\"Error pretty printing zod schema\", { error });\n          }\n          input[0] = { ...rest, schema: prettySchema };\n        }\n        return await Laminar.withSpan(\n          instrumentation.playwrightInstrumentation.getParentSpanForSession(\n            sessionId,\n          )!,\n          async () =>\n            await laminarObserve(\n              {\n                name: `stagehand.${methodName}`,\n                input,\n              },\n              async (thisArg: any, rest: any[]) =>\n                await original.apply(thisArg, rest),\n              this,\n              args,\n            ),\n        );\n      };\n  }\n\n  private patchStagehandV1ActHandlerAct() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function act(this: any, ...args: any[]) {\n        return await laminarObserve(\n          {\n            name: \"stagehand.actHandler.act\",\n            input: {\n              action: args[0].action,\n              llmClient: cleanStagehandLLMClient(args[0].llmClient ?? {}),\n              chunksSeen: args[0].chunksSeen,\n              steps: args[0].steps,\n              requestId: args[0].requestId,\n              schema: args[0].schema,\n              retries: args[0].retries,\n              variables: args[0].variables,\n              previousSelectors: args[0].previousSelectors,\n              skipActionCacheForThisStep: args[0].skipActionCacheForThisStep,\n              domSettleTimeoutMs: args[0].domSettleTimeoutMs,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  private patchStagehandV2ActHandlerActFromObserveResult() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function act(this: any, ...args: any[]) {\n        return await laminarObserve(\n          {\n            name: \"stagehand.actHandler.actFromObserveResult\",\n            input: {\n              observe: args?.[0] ?? null,\n              domSettleTimeoutMs: args?.[1] ?? null,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  private patchStagehandV2ActHandlerObserveAct() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function act(this: any, ...args: any[]) {\n        const actOptions = args?.[0] as ActOptions | undefined;\n        const llmClient = args.filter((arg) =>\n          Object.keys(arg).includes(\"modelName\"),\n        )[0] as LLMClient | undefined;\n        const requestId = typeof args?.[3] === \"string\" ? args?.[3] : null;\n        return await laminarObserve(\n          {\n            name: \"stagehand.actHandler.observeAct\",\n            input: {\n              action: actOptions?.action,\n              modelName: actOptions?.modelName,\n              variables: actOptions?.variables,\n              domSettleTimeoutMs: actOptions?.domSettleTimeoutMs,\n              timeoutMs: actOptions?.timeoutMs,\n              llmClient: cleanStagehandLLMClient(llmClient ?? {}),\n              requestId: requestId,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  // Stagehand uses zod 3.x, so we need to use the v3 version of zod\n  private patchStagehandExtractHandlerTextExtract() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function textExtract(this: any, ...args: any[]) {\n        const schema = args[0].schema as z.AnyZodObject;\n        let prettySchema = schema?.shape;\n        try {\n          prettySchema = prettyPrintZodSchema(schema);\n        } catch (error) {\n          diag.warn(\"Error pretty printing zod schema\", { error });\n        }\n        return await laminarObserve(\n          {\n            name: \"stagehand.extractHandler.textExtract\",\n            input: {\n              instruction: args[0].instruction,\n              llmClient: cleanStagehandLLMClient(args[0].llmClient ?? {}),\n              requestId: args[0].requestId,\n              schema: prettySchema,\n              content: args[0].content,\n              domSettleTimeoutMs: args[0].domSettleTimeoutMs,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  private patchStagehandExtractHandlerDomExtract() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function domExtract(this: any, ...args: any[]) {\n        const schema = args[0].schema as z.AnyZodObject;\n        let prettySchema = schema?.shape;\n        try {\n          prettySchema = prettyPrintZodSchema(schema);\n        } catch (error) {\n          diag.warn(\"Error pretty printing zod schema\", { error });\n        }\n\n        return await laminarObserve(\n          {\n            name: \"stagehand.extractHandler.domExtract\",\n            input: {\n              instruction: args[0].instruction,\n              llmClient: cleanStagehandLLMClient(args[0].llmClient ?? {}),\n              requestId: args[0].requestId,\n              schema: prettySchema,\n              content: args[0].content,\n              chunksSeen: args[0].chunksSeen,\n              domSettleTimeoutMs: args[0].domSettleTimeoutMs,\n            },\n          },\n          async () => await original.apply(this, args),\n        );\n      };\n  }\n\n  private patchStagehandObserveHandler() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function observe(this: any, ...args: any[]) {\n        return await laminarObserve(\n          {\n            name: \"stagehand.observeHandler.observe\",\n            input: {\n              instruction: args[0].instruction,\n              llmClient: cleanStagehandLLMClient(args[0].llmClient ?? {}),\n              requestId: args[0].requestId,\n              returnAction: args[0].returnAction,\n              onlyVisible: args[0].onlyVisible,\n              drawOverlay: args[0].drawOverlay,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  private patchStagehandLLMClientCreateChatCompletion() {\n    return createLLMClientCreateChatCompletionWrapper(\n      this.globalLLMClientOptions,\n    );\n  }\n\n  private patchStagehandAgentInitializer(sessionId: StringUUID) {\n    const instrumentation = this;\n    return (original: (...args: any[]) => any) =>\n      function agent(this: any, ...args: any[]) {\n        if (args.length > 0 && typeof args[0] === \"object\") {\n          instrumentation.globalAgentOptions.set(this, args[0]);\n        }\n        const agent = original.bind(this).apply(this, args);\n        instrumentation.patchStagehandAgent(agent, sessionId);\n        return agent;\n      };\n  }\n\n  private patchStagehandAgent(agent: AgentClient, sessionId: StringUUID) {\n    this._wrap(agent, \"execute\", this.patchStagehandAgentExecute(sessionId));\n  }\n\n  private patchStagehandAgentExecute(sessionId: StringUUID) {\n    const instrumentation = this;\n    return (original: (this: any, ...args: any[]) => Promise<any>) =>\n      async function execute(this: any, ...args: any[]) {\n        const input = nameArgsOrCopy(args);\n\n        return await Laminar.withSpan(\n          instrumentation.playwrightInstrumentation.getParentSpanForSession(\n            sessionId,\n          )!,\n          async () =>\n            await laminarObserve(\n              {\n                name: \"stagehand.agent.execute\",\n                input,\n              },\n              async () =>\n                await laminarObserve(\n                  {\n                    name: \"execute\",\n                    // input and output are set as gen_ai.prompt and gen_ai.completion\n                    ignoreInput: true,\n                    ignoreOutput: true,\n                    spanType: \"LLM\",\n                  },\n                  async () => {\n                    const span =\n                      trace.getSpan(LaminarContextManager.getContext()) ??\n                      trace.getActiveSpan();\n\n                    const provider =\n                      instrumentation.globalAgentOptions.get(this)?.provider ??\n                      instrumentation.globalLLMClientOptions.get(this)\n                        ?.provider;\n                    const model =\n                      instrumentation.globalAgentOptions.get(this)?.model ??\n                      instrumentation.globalLLMClientOptions.get(this)?.model;\n                    span?.setAttributes({\n                      ...(provider ? { \"gen_ai.system\": provider } : {}),\n                      ...(model ? { \"gen_ai.request.model\": model } : {}),\n                    });\n\n                    let promptIndex = 0;\n                    if (\n                      instrumentation.globalAgentOptions.get(this)?.instructions\n                    ) {\n                      span?.setAttributes({\n                        \"gen_ai.prompt.0.content\":\n                          instrumentation.globalAgentOptions.get(this)\n                            ?.instructions,\n                        \"gen_ai.prompt.0.role\": \"system\",\n                      });\n                      promptIndex++;\n                    }\n\n                    const instruction =\n                      typeof input === \"string\"\n                        ? input\n                        : (input as any).instruction;\n                    if (instruction) {\n                      span?.setAttributes({\n                        [`gen_ai.prompt.${promptIndex}.content`]: instruction,\n                        [`gen_ai.prompt.${promptIndex}.role`]: \"user\",\n                      });\n                    }\n\n                    const result = await original.bind(this).apply(this, args);\n\n                    if (result.completed && result.success && result.message) {\n                      const content = [{ type: \"text\", text: result.message }];\n                      if (result.actions && result.actions.length > 0) {\n                        content.push({\n                          type: \"text\",\n                          text: JSON.stringify({ actions: result.actions }),\n                        });\n                      }\n                      span?.setAttributes({\n                        \"gen_ai.completion.0.content\": JSON.stringify(content),\n                        \"gen_ai.completion.0.role\": \"assistant\",\n                      });\n                    } else if (result.completed && !result.success) {\n                      span?.recordException(new Error(result.message));\n                    }\n                    if (result.usage) {\n                      span?.setAttributes({\n                        \"gen_ai.usage.input_tokens\": result.usage.input_tokens,\n                        \"gen_ai.usage.output_tokens\":\n                          result.usage.output_tokens,\n                        \"llm.usage.total_tokens\":\n                          result.usage.input_tokens +\n                          result.usage.output_tokens,\n                      });\n                    }\n                    return result;\n                  },\n                ),\n            ),\n        );\n      };\n  }\n}\n","// biome-ignore-all lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\nimport { LaminarClient } from \"@lmnr-ai/client\";\nimport { errorMessage, SessionRecordingOptions } from \"@lmnr-ai/types\";\nimport { diag, trace } from \"@opentelemetry/api\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\nimport type * as PuppeteerLib from \"puppeteer\";\nimport type { Browser, BrowserContext, Page } from \"puppeteer\";\nimport type * as PuppeteerCoreLib from \"puppeteer-core\";\n\nimport { version as SDK_VERSION } from \"../../package.json\";\nimport { observe } from \"../decorators\";\nimport { TRACE_HAS_BROWSER_SESSION } from \"../opentelemetry-lib/tracing/attributes\";\nimport { LaminarContextManager } from \"../opentelemetry-lib/tracing/context\";\nimport {\n  initializeLogger,\n  NIL_UUID,\n  newUUID,\n  otelTraceIdToUUID,\n  StringUUID,\n} from \"../utils\";\nimport {\n  ChunkBuffer,\n  EventChunk,\n  injectSessionRecorder,\n  LMNR_SEND_EVENTS_FUNCTION_NAME,\n  sendEvents,\n  takeFullSnapshot,\n} from \"./utils\";\n\nconst logger = initializeLogger();\n\nexport class PuppeteerInstrumentation extends InstrumentationBase {\n  private _patchedBrowsers: Set<Browser> = new Set();\n  private _client: LaminarClient;\n  private _sessionRecordingOptions?: SessionRecordingOptions;\n\n  constructor(\n    client: LaminarClient,\n    sessionRecordingOptions?: SessionRecordingOptions,\n  ) {\n    super(\"@lmnr/puppeteer-instrumentation\", SDK_VERSION, {\n      enabled: true,\n    });\n    this._client = client;\n    this._sessionRecordingOptions = sessionRecordingOptions;\n  }\n\n  protected init(): InstrumentationModuleDefinition[] {\n    const puppeteerInstrumentation = new InstrumentationNodeModuleDefinition(\n      \"puppeteer\",\n      // About two years before first writing this instrumentation\n      // and apparently no big breaking changes afterwards\n      // https://github.com/puppeteer/puppeteer/releases\n      [\">=19.0.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n\n    const puppeteerCoreInstrumentation =\n      new InstrumentationNodeModuleDefinition(\n        \"puppeteer-core\",\n        [\">=19.0.0\"],\n        this.patch.bind(this),\n        this.unpatch.bind(this),\n      );\n\n    return [puppeteerInstrumentation, puppeteerCoreInstrumentation];\n  }\n\n  public manuallyInstrument(\n    puppeteerModule: typeof PuppeteerLib | typeof PuppeteerCoreLib,\n  ) {\n    this._wrap(puppeteerModule, \"launch\", this.patchNewBrowser());\n\n    this._wrap(puppeteerModule, \"connect\", this.patchNewBrowser());\n\n    return puppeteerModule;\n  }\n\n  private patch(\n    moduleExports: typeof PuppeteerLib | typeof PuppeteerCoreLib,\n    moduleVersion?: string,\n  ) {\n    diag.debug(`patching puppeteer ${moduleVersion}`);\n    this._wrap(moduleExports, `launch`, this.patchNewBrowser());\n\n    this._wrap(\n      moduleExports.PuppeteerNode.prototype,\n      `launch`,\n      this.patchNewBrowser(),\n    );\n\n    this._wrap(moduleExports, `connect`, this.patchNewBrowser());\n\n    this._wrap(\n      moduleExports.Puppeteer.prototype,\n      `connect`,\n      this.patchNewBrowser(),\n    );\n\n    this._wrap(moduleExports.default, `launch`, this.patchNewBrowser());\n\n    this._wrap(moduleExports.default, `connect`, this.patchNewBrowser());\n\n    return moduleExports;\n  }\n\n  private unpatch(moduleExports: typeof PuppeteerLib, moduleVersion?: string) {\n    diag.debug(`unpatching puppeteer ${moduleVersion}`);\n    this._unwrap(moduleExports, `launch`);\n\n    this._unwrap(moduleExports, `connect`);\n\n    this._unwrap(moduleExports.PuppeteerNode.prototype, `launch`);\n\n    this._unwrap(moduleExports.Puppeteer.prototype, `connect`);\n\n    this._unwrap(moduleExports.default, `connect`);\n\n    this._unwrap(moduleExports.default, `launch`);\n\n    for (const browser of this._patchedBrowsers) {\n      this._unwrap(browser, \"createBrowserContext\");\n    }\n  }\n\n  private patchNewBrowser() {\n    const plugin = this;\n    return (original: Function) =>\n      async function method(this: Browser, ...args: any[]) {\n        const browser: Browser = await original.call(this, ...args);\n        const sessionId = newUUID();\n\n        for (const context of browser.browserContexts()) {\n          context.on(\"targetcreated\", (target) => {\n            target\n              .page()\n              .then((page) => {\n                if (page) {\n                  plugin.patchPage(page, sessionId).catch((error) => {\n                    logger.error(\n                      \"Failed to patch page: \" + errorMessage(error),\n                    );\n                  });\n                }\n              })\n              .catch((error) => {\n                logger.error(\"Failed to patch page: \" + errorMessage(error));\n              });\n          });\n          await Promise.all(\n            (await context.pages()).map((page) =>\n              plugin.patchPage(page, sessionId),\n            ),\n          );\n        }\n\n        plugin._wrap(\n          browser,\n          \"createBrowserContext\",\n          plugin.patchBrowserNewContext(),\n        );\n\n        plugin._patchedBrowsers.add(browser);\n        return browser;\n      };\n  }\n\n  private patchBrowserNewContext() {\n    const plugin = this;\n    return (original: Function) =>\n      async function method(this: Browser, ...args: unknown[]) {\n        const context: BrowserContext = await original\n          .bind(this)\n          .apply(this, args);\n        const sessionId = newUUID();\n        // Patch pages created by browser, e.g. new tab\n        context.on(\"targetcreated\", (target) => {\n          target\n            .page()\n            .then((page) => {\n              if (page) {\n                plugin.patchPage(page, sessionId).catch((error) => {\n                  logger.error(\"Failed to patch page: \" + errorMessage(error));\n                });\n              }\n            })\n            .catch((error) => {\n              logger.error(\"Failed to patch page: \" + errorMessage(error));\n            });\n        });\n        context.on(\"targetchanged\", (target) => {\n          target\n            .page()\n            .then((page) => {\n              if (page) {\n                plugin.patchPage(page, sessionId).catch((error) => {\n                  logger.error(\"Failed to patch page: \" + errorMessage(error));\n                });\n              }\n            })\n            .catch((error) => {\n              logger.error(\"Failed to patch page: \" + errorMessage(error));\n            });\n        });\n\n        // Patch pages that are already created\n        for (const page of await context.pages()) {\n          await plugin.patchPage(page, sessionId);\n        }\n\n        return context;\n      };\n  }\n\n  public async patchPage(page: Page, sessionId: StringUUID) {\n    return await observe({ name: \"puppeteer.page\" }, async () => {\n      await this._patchPage(page, sessionId);\n    });\n  }\n\n  private async _patchPage(page: Page, sessionId: StringUUID) {\n    const originalBringToFront = page.bringToFront.bind(page);\n\n    page.bringToFront = async () => {\n      await originalBringToFront();\n      await takeFullSnapshot(page);\n    };\n\n    const currentSpan =\n      trace.getSpan(LaminarContextManager.getContext()) ??\n      trace.getActiveSpan();\n    currentSpan?.setAttribute(TRACE_HAS_BROWSER_SESSION, true);\n    const otelTraceId = currentSpan?.spanContext().traceId;\n    const traceId = otelTraceId ? otelTraceIdToUUID(otelTraceId) : NIL_UUID;\n\n    page.on(\"domcontentloaded\", () => {\n      injectSessionRecorder(page, this._sessionRecordingOptions).catch(\n        (error) => {\n          logger.error(\"Error in onLoad handler: \" + errorMessage(error));\n        },\n      );\n    });\n\n    await injectSessionRecorder(page, this._sessionRecordingOptions);\n\n    const chunkBuffers = new Map<string, ChunkBuffer>();\n\n    try {\n      await page.exposeFunction(\n        LMNR_SEND_EVENTS_FUNCTION_NAME,\n        async (chunk: EventChunk) => {\n          await sendEvents(\n            chunk,\n            this._client,\n            chunkBuffers,\n            sessionId,\n            traceId,\n          );\n        },\n      );\n    } catch (error) {\n      logger.debug(\n        \"Could not expose function \" +\n          LMNR_SEND_EVENTS_FUNCTION_NAME +\n          \": \" +\n          errorMessage(error),\n      );\n    }\n  }\n}\n","import { initializeLogger } from \"../../../utils\";\n\nexport const logger = initializeLogger();\n\n// CDP timeout for operations\nexport const CDP_OPERATION_TIMEOUT_MS = 10000;\n\n// URLs that should be skipped for recording\nexport const SKIP_URL_PATTERNS = [\n  \"about:blank\",\n  \"chrome-error://\",\n  \"chrome://\",\n  \"edge-error://\",\n  \"edge://\",\n  \"about:neterror\",\n  \"about:certerror\",\n  \"devtools://\",\n];\n","import { errorMessage, SessionRecordingOptions } from \"@lmnr-ai/types\";\n\nimport { RECORDER } from \"../../recorder\";\nimport { injectScript } from \"../../utils\";\nimport {\n  CDP_OPERATION_TIMEOUT_MS,\n  logger,\n  SKIP_URL_PATTERNS,\n} from \"./constants\";\nimport {\n  type FrameTree,\n  type RuntimeBindingCalledEvent,\n  type RuntimeEvaluateResult,\n  type StagehandCdpConnection,\n  type StagehandV3Page,\n  type V3RecorderState,\n} from \"./types\";\n\n/**\n * Check if a URL should be skipped for recording (error pages, blank pages, etc.)\n */\nexport function shouldSkipUrl(url: string): boolean {\n  if (!url) return true;\n  return SKIP_URL_PATTERNS.some((pattern) => url.startsWith(pattern));\n}\n\n/**\n * Send a CDP command to the given page. Works across Stagehand 3.0.x and 3.1.x+.\n *\n * `page.sendCDP` was added in Stagehand 3.1.0. On 3.0.x we fall back to\n * `getSessionForFrame(mainFrameId()).send(...)` (both methods are public on\n * the 3.0.x Page; `mainSession` is not).\n */\nexport async function sendCDP<T = unknown>(\n  page: StagehandV3Page,\n  method: string,\n  params?: object,\n): Promise<T> {\n  if (typeof page.sendCDP === \"function\") {\n    return await page.sendCDP<T>(method, params);\n  }\n  if (typeof page.getSessionForFrame === \"function\") {\n    const session = page.getSessionForFrame(page.mainFrameId());\n    return await session.send<T>(method, params);\n  }\n  throw new Error(\n    \"Stagehand page does not expose sendCDP or getSessionForFrame; \" +\n      \"unable to send CDP commands\",\n  );\n}\n\n/**\n * Create an isolated world for a page and return the execution context ID\n */\nexport async function getOrCreateIsolatedWorld(\n  page: StagehandV3Page,\n): Promise<{ contextId: number; frameId: string } | null> {\n  try {\n    // Get the frame tree to find the main frame\n    const frameTreeResult = await Promise.race([\n      sendCDP<{ frameTree: FrameTree }>(page, \"Page.getFrameTree\"),\n      new Promise<null>((_, reject) =>\n        setTimeout(\n          () => reject(new Error(\"Timeout getting frame tree\")),\n          CDP_OPERATION_TIMEOUT_MS,\n        ),\n      ),\n    ]);\n\n    if (!frameTreeResult) return null;\n\n    const frameId = frameTreeResult.frameTree.frame.id;\n\n    // Create isolated world\n    const isolatedWorldResult = await Promise.race([\n      sendCDP<{ executionContextId: number }>(\n        page,\n        \"Page.createIsolatedWorld\",\n        {\n          frameId,\n          worldName: \"laminar-recorder\",\n        },\n      ),\n      new Promise<null>((_, reject) =>\n        setTimeout(\n          () => reject(new Error(\"Timeout creating isolated world\")),\n          CDP_OPERATION_TIMEOUT_MS,\n        ),\n      ),\n    ]);\n\n    if (!isolatedWorldResult) return null;\n\n    return {\n      contextId: isolatedWorldResult.executionContextId,\n      frameId,\n    };\n  } catch (error) {\n    logger.debug(\"Failed to create isolated world: \" + errorMessage(error));\n    return null;\n  }\n}\n\n/**\n * Check if the session recorder is already present in the page\n */\nexport async function isRecorderPresent(\n  page: StagehandV3Page,\n  contextId: number,\n): Promise<boolean> {\n  try {\n    const result = await Promise.race([\n      sendCDP<RuntimeEvaluateResult>(page, \"Runtime.evaluate\", {\n        expression: \"typeof window.lmnrRrweb !== 'undefined'\",\n        contextId,\n        returnByValue: true,\n      }),\n      new Promise<null>((_, reject) =>\n        setTimeout(\n          () => reject(new Error(\"Timeout checking recorder\")),\n          CDP_OPERATION_TIMEOUT_MS,\n        ),\n      ),\n    ]);\n\n    if (!result) return true; // On timeout, assume present to avoid double injection\n    return result.result?.value === true;\n  } catch (error) {\n    logger.debug(\n      \"Failed to check if recorder is present: \" + errorMessage(error),\n    );\n    return true; // On error, assume present to be safe\n  }\n}\n\n/**\n * Inject the session recorder into a page using CDP\n */\nexport async function injectRecorderViaCDP(\n  page: StagehandV3Page,\n  state: V3RecorderState,\n  conn: StagehandCdpConnection,\n  sessionRecordingOptions?: SessionRecordingOptions,\n  bindingHandler?: (event: RuntimeBindingCalledEvent) => void,\n): Promise<number | null> {\n  try {\n    // Check if we should skip this page\n    let url: string;\n    try {\n      url = page.url();\n    } catch (error) {\n      logger.debug(\n        \"Failed to get page URL, page might be closed: \" + errorMessage(error),\n      );\n      return null;\n    }\n\n    if (shouldSkipUrl(url)) {\n      logger.debug(`Skipping recorder injection for URL: ${url}`);\n      return null;\n    }\n\n    // Get or create isolated world\n    const worldResult = await getOrCreateIsolatedWorld(page);\n    if (!worldResult) {\n      logger.debug(\"Failed to get isolated world for page\");\n      return null;\n    }\n\n    const { contextId, frameId } = worldResult;\n\n    // Check if already injected\n    if (await isRecorderPresent(page, contextId)) {\n      logger.debug(\"Recorder already present, skipping injection\");\n      // Still register the context mapping\n      state.contextIdToSession.set(contextId, {\n        sessionId: state.sessionId,\n        traceId: state.traceId,\n      });\n      return contextId;\n    }\n\n    // Inject rrweb base\n    try {\n      await sendCDP(page, \"Runtime.evaluate\", {\n        expression: RECORDER,\n        contextId,\n      });\n    } catch (error) {\n      logger.debug(\"Failed to inject rrweb: \" + errorMessage(error));\n      return null;\n    }\n\n    // Inject recording setup script using the existing injectScript function\n    // Convert function to string and create an IIFE with options\n    // Pass true for stringifyCallbackArgs since CDP bindings require stringified arguments\n    const optionsJson = JSON.stringify(sessionRecordingOptions ?? {});\n    const injectExpression = `(${injectScript.toString()})(${optionsJson}, true);`;\n    try {\n      await sendCDP(page, \"Runtime.evaluate\", {\n        expression: injectExpression,\n        contextId,\n      });\n    } catch (error) {\n      logger.debug(\"Failed to inject recording setup: \" + errorMessage(error));\n      return null;\n    }\n\n    // Add binding globally (not scoped to execution context)\n    // The Runtime.bindingCalled event will include the executionContextId\n    try {\n      await sendCDP(page, \"Runtime.addBinding\", {\n        name: \"lmnrSendEvents\",\n      });\n      logger.debug(\n        `Added binding 'lmnrSendEvents' for page ${frameId}, context ${contextId}`,\n      );\n    } catch (error) {\n      // Binding might already exist, that's ok\n      logger.debug(\"Binding may already exist: \" + errorMessage(error));\n    }\n\n    // Set up binding handler on this page using the internal Stagehand CDP session\n    // The page.sendCDP method goes through the page's mainSession, so we need to listen there\n    // We can access the session through the connection's internal structure\n    if (bindingHandler) {\n      try {\n        const pageTargetId = page.targetId();\n        if (!state.pageSessionHandlers.has(pageTargetId)) {\n          // Access the connection's sessions map to find the session for this page\n          const connInternal = conn as unknown as {\n            getSession(sessionId: string):\n              | {\n                  on<P>(event: string, handler: (params: P) => void): void;\n                }\n              | undefined;\n            sessions: Map<string, unknown>;\n          };\n\n          // In Stagehand v3, each page has a corresponding session\n          // We need to find the session that owns this page/target\n          // The session for a page target is tracked in the context\n          // We can iterate sessions and try to set up the listener\n          if (connInternal.sessions) {\n            for (const [\n              sessionId,\n              session,\n            ] of connInternal.sessions.entries()) {\n              try {\n                // Set up the handler on each session (the correct one will receive the events)\n                const sessionTyped = session as {\n                  on<P>(event: string, handler: (params: P) => void): void;\n                };\n                if (sessionTyped.on) {\n                  sessionTyped.on<RuntimeBindingCalledEvent>(\n                    \"Runtime.bindingCalled\",\n                    bindingHandler,\n                  );\n                  logger.debug(\n                    `Set up binding handler on session ${sessionId}`,\n                  );\n                }\n              } catch (error) {\n                // Session might be closed, continue with next session\n                logger.debug(\n                  `Failed to set up binding handler on session ${sessionId}: ` +\n                    errorMessage(error),\n                );\n              }\n            }\n          }\n          state.pageSessionHandlers.set(pageTargetId, bindingHandler);\n        }\n      } catch (error) {\n        logger.debug(\n          \"Failed to set up binding handler: \" + errorMessage(error),\n        );\n      }\n    }\n\n    // Register context mapping\n    state.contextIdToSession.set(contextId, {\n      sessionId: state.sessionId,\n      traceId: state.traceId,\n    });\n    logger.debug(\n      `Registered context mapping: contextId=${contextId}, sessionId=${state.sessionId}`,\n    );\n\n    // Mark page as instrumented\n    state.instrumentedPageIds.add(frameId);\n\n    logger.debug(`Successfully injected recorder into page ${frameId}`);\n    return contextId;\n  } catch (error) {\n    logger.debug(\"Error injecting recorder: \" + errorMessage(error));\n    return null;\n  }\n}\n","import {\n  errorMessage,\n  type SessionRecordingOptions,\n  type StringUUID,\n} from \"@lmnr-ai/types\";\n\nimport { EventChunk, sendEvents } from \"../../utils\";\nimport { injectRecorderViaCDP, shouldSkipUrl } from \"./cdp-helpers\";\nimport { logger } from \"./constants\";\nimport {\n  RuntimeBindingCalledEvent,\n  StagehandV3Context,\n  TargetCreatedEvent,\n  TargetInfoChangedEvent,\n  V3RecorderState,\n} from \"./types\";\n\n/**\n * Handle Runtime.bindingCalled events\n */\nexport function createBindingHandler(\n  state: V3RecorderState,\n): (event: RuntimeBindingCalledEvent) => void {\n  return (event: RuntimeBindingCalledEvent) => {\n    if (event.name !== \"lmnrSendEvents\") return;\n    const sessionInfo = state.contextIdToSession.get(event.executionContextId);\n    if (!sessionInfo) {\n      logger.debug(\n        \"No session info found for context ID: \" + event.executionContextId,\n      );\n      // Try to find any matching session (for cases where context ID changed)\n      // This is a fallback - normally the context should be mapped\n      if (state.contextIdToSession.size > 0) {\n        // Use the first available session info as fallback\n        const [, fallbackInfo] = state.contextIdToSession.entries().next()\n          .value as [number, { sessionId: StringUUID; traceId: StringUUID }];\n        if (fallbackInfo) {\n          try {\n            const chunk = JSON.parse(event.payload) as EventChunk;\n            void sendEvents(\n              chunk,\n              state.client,\n              state.chunkBuffers,\n              fallbackInfo.sessionId,\n              fallbackInfo.traceId,\n            );\n          } catch (error) {\n            logger.debug(\n              \"Failed to parse binding payload: \" + errorMessage(error),\n            );\n          }\n        }\n      }\n      return;\n    }\n\n    try {\n      const chunk = JSON.parse(event.payload) as EventChunk;\n      void sendEvents(\n        chunk,\n        state.client,\n        state.chunkBuffers,\n        sessionInfo.sessionId,\n        sessionInfo.traceId,\n      );\n    } catch (error) {\n      logger.debug(\"Failed to handle binding event: \" + errorMessage(error));\n    }\n  };\n}\n\n/**\n * Handle Target.targetCreated events for new pages\n */\nexport function createTargetCreatedHandler(\n  context: StagehandV3Context,\n  state: V3RecorderState,\n  sessionRecordingOptions?: SessionRecordingOptions,\n): (event: TargetCreatedEvent) => Promise<void> {\n  return async (event: TargetCreatedEvent) => {\n    try {\n      if (event.targetInfo.type !== \"page\") return;\n\n      // Wait a bit for the page to be available in the context\n      await new Promise((resolve) => setTimeout(resolve, 200));\n      // Try to inject into all uninstrumented pages\n      for (const page of context.pages()) {\n        try {\n          const pageId = page.mainFrameId();\n          if (!state.instrumentedPageIds.has(pageId)) {\n            await injectRecorderViaCDP(\n              page,\n              state,\n              context.conn,\n              sessionRecordingOptions,\n              state.bindingHandler ?? undefined,\n            );\n          }\n        } catch (error) {\n          // Page might have been closed or CDP session lost, continue with next page\n          logger.debug(\n            \"Error injecting recorder into new page: \" + errorMessage(error),\n          );\n        }\n      }\n    } catch (error) {\n      logger.debug(\n        \"Error handling target created event: \" + errorMessage(error),\n      );\n    }\n  };\n}\n\n/**\n * Handle Target.targetInfoChanged events for URL changes/navigation\n */\nexport function createTargetInfoChangedHandler(\n  context: StagehandV3Context,\n  state: V3RecorderState,\n  sessionRecordingOptions?: SessionRecordingOptions,\n): (event: TargetInfoChangedEvent) => Promise<void> {\n  return async (event: TargetInfoChangedEvent) => {\n    // Only handle page targets\n    if (event.targetInfo.type !== \"page\") return;\n\n    const url = event.targetInfo.url;\n\n    if (shouldSkipUrl(url)) return;\n\n    logger.debug(\n      `Target URL changed to ${url}, checking if recorder injection needed`,\n    );\n\n    await new Promise((resolve) => setTimeout(resolve, 150));\n\n    try {\n      for (const page of context.pages()) {\n        // Try to match by target ID\n        const targetId = page.targetId();\n        if (targetId === event.targetInfo.targetId) {\n          await injectRecorderViaCDP(\n            page,\n            state,\n            context.conn,\n            sessionRecordingOptions,\n            state.bindingHandler ?? undefined,\n          );\n          break;\n        }\n      }\n    } catch (error) {\n      logger.debug(\"Error handling target info change: \" + errorMessage(error));\n    }\n  };\n}\n","// biome-ignore-all lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\nimport { LaminarClient } from \"@lmnr-ai/client\";\nimport { errorMessage, type SessionRecordingOptions } from \"@lmnr-ai/types\";\nimport { diag, type Span, trace } from \"@opentelemetry/api\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\n\nimport { version as SDK_VERSION } from \"../../../../package.json\";\nimport { observe as laminarObserve } from \"../../../decorators\";\nimport { Laminar } from \"../../../laminar\";\nimport { TRACE_HAS_BROWSER_SESSION } from \"../../../opentelemetry-lib/tracing/attributes\";\nimport { LaminarContextManager } from \"../../../opentelemetry-lib/tracing/context\";\nimport { newUUID, otelTraceIdToUUID, StringUUID } from \"../../../utils\";\nimport {\n  modelToProvider,\n  nameArgsOrCopy,\n  prettyPrintZodSchema,\n} from \"../../utils\";\nimport {\n  createLLMClientCreateChatCompletionWrapper,\n  GlobalLLMClientOptions,\n} from \"../shared-llm-wrapper\";\nimport { injectRecorderViaCDP } from \"./cdp-helpers\";\nimport { logger } from \"./constants\";\nimport {\n  createBindingHandler,\n  createTargetCreatedHandler,\n  createTargetInfoChangedHandler,\n} from \"./event-handlers\";\nimport {\n  StagehandV3Context,\n  TargetCreatedEvent,\n  TargetInfoChangedEvent,\n  V3RecorderState,\n} from \"./types\";\n\n/**\n * Guarded _wrap: only wraps `target[methodName]` if it exists as a function.\n * Prevents the \"Cannot wrap non-existent method\" warning from\n * InstrumentationBase._wrap when a handler/method was renamed or removed\n * in the upstream library (e.g. Stagehand v2 vs v3 differences).\n */\nconst safeWrap = (\n  instrumentation: any,\n  target: any,\n  methodName: string,\n  wrapper: (original: any) => any,\n): boolean => {\n  if (!target) return false;\n  if (typeof target[methodName] !== \"function\") return false;\n  instrumentation._wrap(target, methodName, wrapper);\n  return true;\n};\n\n/**\n * Guarded _unwrap counterpart to safeWrap. Only unwraps when the target method\n * exists AND was previously wrapped via shimmer (has the `__original` marker).\n */\nconst safeUnwrap = (\n  instrumentation: any,\n  target: any,\n  methodName: string,\n): void => {\n  if (!target) return;\n  const current = target[methodName];\n  if (typeof current !== \"function\") return;\n  if (!current.__original) return;\n  instrumentation._unwrap(target, methodName);\n};\n\nexport class StagehandInstrumentation extends InstrumentationBase {\n  private stagehandInstanceToSessionId: WeakMap<object, StringUUID> =\n    new WeakMap();\n  private globalLLMClientOptions: WeakMap<\n    any,\n    GlobalLLMClientOptions | undefined\n  > = new WeakMap();\n  private globalAgentOptions: WeakMap<object, Record<string, any> | undefined> =\n    new WeakMap();\n  private sessionIdToParentSpan: Map<StringUUID, Span> = new Map();\n\n  // Session recording state per Stagehand instance\n  private stagehandInstanceToRecorderState: WeakMap<object, V3RecorderState> =\n    new WeakMap();\n\n  // LaminarClient for sending events (set externally)\n  private _client: LaminarClient | null = null;\n\n  // Session recording options\n  private _sessionRecordingOptions?: SessionRecordingOptions;\n\n  constructor(sessionRecordingOptions?: SessionRecordingOptions) {\n    super(\"@lmnr/browserbase-stagehand-instrumentation\", SDK_VERSION, {\n      enabled: true,\n    });\n    this._sessionRecordingOptions = sessionRecordingOptions;\n  }\n\n  /**\n   * Set the LaminarClient to use for sending browser events.\n   * This must be called before Stagehand.init() to enable session recording.\n   */\n  public setClient(client: LaminarClient): void {\n    this._client = client;\n  }\n\n  /**\n   * Get the LaminarClient instance\n   */\n  public get client(): LaminarClient | null {\n    return this._client;\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    const module = new InstrumentationNodeModuleDefinition(\n      \"@browserbasehq/stagehand\",\n      [\">=3.0.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n\n    return module;\n  }\n\n  private patch(moduleExports: any, moduleVersion?: string) {\n    diag.debug(`patching stagehand ${moduleVersion}`);\n\n    // Check if Stagehand is non-configurable\n    const descriptor = Object.getOwnPropertyDescriptor(\n      moduleExports,\n      \"Stagehand\",\n    );\n    if (descriptor && !descriptor.configurable) {\n      // Create a proxy for the entire module exports\n      const originalStagehand = moduleExports.Stagehand;\n      const patchedConstructor =\n        this.patchStagehandConstructor()(originalStagehand);\n\n      // Create a proxy for the module exports\n      return new Proxy(moduleExports, {\n        get: (target, prop) => {\n          if (prop === \"Stagehand\") {\n            return patchedConstructor;\n          }\n          return target[prop as keyof typeof target];\n        },\n      });\n    } else {\n      // If it's configurable, use the standard _wrap method\n      this._wrap(moduleExports, \"Stagehand\", this.patchStagehandConstructor());\n\n      return moduleExports;\n    }\n  }\n\n  public manuallyInstrument(Stagehand: any) {\n    diag.debug(\"manually instrumenting stagehand\");\n\n    // Patch the prototype methods of the existing constructor\n    if (Stagehand && Stagehand.prototype) {\n      this._wrap(Stagehand.prototype, \"init\", this.patchStagehandInit());\n      this._wrap(Stagehand.prototype, \"close\", this.patchStagehandClose());\n    }\n  }\n\n  private unpatch(moduleExports: any, moduleVersion?: string) {\n    diag.debug(`unpatching stagehand ${moduleVersion}`);\n    safeUnwrap(this, moduleExports, \"Stagehand\");\n\n    if (moduleExports.Stagehand && moduleExports.Stagehand.prototype) {\n      const prototype = moduleExports.Stagehand.prototype;\n      safeUnwrap(this, prototype, \"init\");\n      safeUnwrap(this, prototype, \"close\");\n      safeUnwrap(this, prototype, \"act\");\n      safeUnwrap(this, prototype, \"extract\");\n      safeUnwrap(this, prototype, \"observe\");\n      safeUnwrap(this, prototype, \"agent\");\n\n      // Try to unwrap handler methods if they exist on the prototype\n      if (prototype.actHandler) {\n        safeUnwrap(this, prototype.actHandler, \"act\");\n        safeUnwrap(this, prototype.actHandler, \"actFromObserveResult\");\n      }\n      if (prototype.extractHandler) {\n        safeUnwrap(this, prototype.extractHandler, \"extract\");\n      }\n      if (prototype.observeHandler) {\n        safeUnwrap(this, prototype.observeHandler, \"observe\");\n      }\n      // Try to unwrap LLM client if it exists\n      if (prototype.llmClient) {\n        safeUnwrap(this, prototype.llmClient, \"createChatCompletion\");\n      }\n      // Try to unwrap API client (BROWSERBASE remote mode) if it exists\n      if (prototype.apiClient) {\n        safeUnwrap(this, prototype.apiClient, \"act\");\n        safeUnwrap(this, prototype.apiClient, \"extract\");\n        safeUnwrap(this, prototype.apiClient, \"observe\");\n        safeUnwrap(this, prototype.apiClient, \"agentExecute\");\n      }\n    }\n\n    return moduleExports;\n  }\n\n  private patchStagehandConstructor() {\n    const instrumentation = this;\n\n    return (Original: any) => {\n      // Create a constructor function that maintains the same signature\n      const Stagehand = function (\n        this: InstanceType<typeof Original>,\n        ...args: any[]\n      ) {\n        // Only apply if this is a new instance\n        if (!(this instanceof Stagehand)) {\n          return new Stagehand(...args);\n        }\n\n        const instance = new Original(args.length > 0 ? args[0] : undefined);\n        Object.assign(this, instance);\n\n        instrumentation._wrap(\n          this,\n          \"init\",\n          instrumentation.patchStagehandInit(),\n        );\n\n        instrumentation._wrap(\n          this,\n          \"close\",\n          instrumentation.patchStagehandClose(),\n        );\n\n        return this;\n      } as unknown as typeof Original;\n\n      // Copy static properties\n      Object.setPrototypeOf(Stagehand, Original);\n      // Copy prototype properties\n      Stagehand.prototype = Object.create(Original.prototype);\n      Stagehand.prototype.constructor = Stagehand;\n\n      return Stagehand;\n    };\n  }\n\n  private patchStagehandInit() {\n    const instrumentation = this;\n\n    return (original: any) =>\n      async function method(this: any) {\n        const sessionId = newUUID();\n\n        // Create parent span for this Stagehand session\n        const parentSpan = Laminar.startSpan({\n          name: \"Stagehand\",\n        });\n        instrumentation.sessionIdToParentSpan.set(sessionId, parentSpan);\n\n        instrumentation.stagehandInstanceToSessionId.set(this, sessionId);\n\n        // Get trace ID from current span context\n        const currentSpan =\n          trace.getSpan(LaminarContextManager.getContext()) ??\n          trace.getActiveSpan();\n        currentSpan?.setAttribute(TRACE_HAS_BROWSER_SESSION, true);\n        const otelTraceId = parentSpan.spanContext().traceId;\n        const traceId = otelTraceIdToUUID(otelTraceId);\n\n        // Call the original init method first\n        const result = await original.bind(this).apply(this);\n\n        // After init, wrap the global methods on the stagehand instance\n        safeWrap(\n          instrumentation,\n          this,\n          \"act\",\n          instrumentation.patchStagehandGlobalMethod(\n            \"act\",\n            sessionId,\n            parentSpan,\n          ),\n        );\n\n        safeWrap(\n          instrumentation,\n          this,\n          \"extract\",\n          instrumentation.patchStagehandGlobalMethod(\n            \"extract\",\n            sessionId,\n            parentSpan,\n          ),\n        );\n\n        safeWrap(\n          instrumentation,\n          this,\n          \"observe\",\n          instrumentation.patchStagehandGlobalMethod(\n            \"observe\",\n            sessionId,\n            parentSpan,\n          ),\n        );\n\n        // Wrap handler methods if they exist. In BROWSERBASE remote mode\n        // (env: \"BROWSERBASE\" with server-side API enabled), Stagehand routes\n        // act/extract/observe through `this.apiClient` instead of these local\n        // handlers, so these handlers' methods may not be invoked — but we still\n        // wrap them defensively for local/experimental modes.\n        if (this.actHandler) {\n          instrumentation.patchActHandler(this.actHandler);\n        }\n\n        if (this.extractHandler) {\n          instrumentation.patchExtractHandler(this.extractHandler);\n        }\n\n        if (this.observeHandler) {\n          instrumentation.patchObserveHandler(this.observeHandler);\n        }\n\n        // Wrap LLM client if it exists. Note: in BROWSERBASE remote mode the\n        // LLM calls happen server-side on the Stagehand API, so this wrapper\n        // never fires. Remote LLM spans are surfaced by wrapping `apiClient`\n        // below instead.\n        if (this.llmClient) {\n          instrumentation.globalLLMClientOptions.set(this.llmClient, {\n            provider: this.llmClient.type,\n            model: this.llmClient.modelName,\n          });\n          safeWrap(\n            instrumentation,\n            this.llmClient,\n            \"createChatCompletion\",\n            instrumentation.patchStagehandLLMClientCreateChatCompletion(),\n          );\n        }\n\n        // In BROWSERBASE remote mode Stagehand creates an internal\n        // `apiClient` that performs act/extract/observe/agentExecute calls\n        // on the Stagehand server. Wrap those methods so we still emit\n        // stagehand.* spans (with LLM usage propagated where available)\n        // even when the local handlers and local llmClient are bypassed.\n        if (this.apiClient) {\n          instrumentation.patchStagehandApiClient(\n            this.apiClient,\n            parentSpan,\n            this,\n          );\n        }\n\n        // Wrap agent method if it exists\n        safeWrap(\n          instrumentation,\n          this,\n          \"agent\",\n          instrumentation.patchStagehandAgentInitializer(sessionId, parentSpan),\n        );\n\n        // Set up session recording if client is available\n        if (instrumentation._client) {\n          await instrumentation.setupSessionRecording(this, sessionId, traceId);\n        }\n\n        // Patch all existing pages\n        if (this.context && this.context.pages) {\n          for (const page of this.context.pages()) {\n            instrumentation.patchStagehandPage(page, parentSpan);\n          }\n        }\n\n        // Set up listener for new pages\n        if (this.context && this.context.on) {\n          this.context.on(\"page\", (page: any) => {\n            instrumentation.patchStagehandPage(page, parentSpan);\n          });\n        }\n\n        return result;\n      };\n  }\n\n  /**\n   * Set up session recording for a Stagehand instance\n   */\n  private async setupSessionRecording(\n    stagehandInstance: any,\n    sessionId: StringUUID,\n    traceId: StringUUID,\n  ): Promise<void> {\n    if (!this._client) {\n      logger.debug(\n        \"No Laminar client available, skipping session recording setup\",\n      );\n      return;\n    }\n\n    // Get the context from the Stagehand instance\n    const context = stagehandInstance.context as StagehandV3Context | undefined;\n    if (!context || !context.conn) {\n      logger.debug(\n        \"No context or connection available, skipping session recording setup\",\n      );\n      return;\n    }\n    // Create recorder state\n    const recorderState: V3RecorderState = {\n      sessionId,\n      traceId,\n      client: this._client,\n      chunkBuffers: new Map(),\n      contextIdToSession: new Map(),\n      instrumentedPageIds: new Set(),\n      bindingHandler: null,\n      targetCreatedHandler: null,\n      targetInfoChangedHandler: null,\n      pageSessionHandlers: new Map(),\n    };\n\n    // Store recorder state\n    this.stagehandInstanceToRecorderState.set(stagehandInstance, recorderState);\n\n    // Set up binding event handler\n    // (will be registered on individual page sessions during injection)\n    const bindingHandler = createBindingHandler(recorderState);\n    recorderState.bindingHandler = bindingHandler;\n\n    // Set up target created handler for new pages\n    const targetCreatedHandler = createTargetCreatedHandler(\n      context,\n      recorderState,\n      this._sessionRecordingOptions,\n    );\n    recorderState.targetCreatedHandler = targetCreatedHandler;\n    context.conn.on<TargetCreatedEvent>(\n      \"Target.targetCreated\",\n      targetCreatedHandler,\n    );\n\n    // Set up target info changed handler for re-injection after navigation\n    const targetInfoChangedHandler = createTargetInfoChangedHandler(\n      context,\n      recorderState,\n      this._sessionRecordingOptions,\n    );\n    recorderState.targetInfoChangedHandler = targetInfoChangedHandler;\n    context.conn.on<TargetInfoChangedEvent>(\n      \"Target.targetInfoChanged\",\n      targetInfoChangedHandler,\n    );\n\n    // Inject recorder into all existing pages\n    try {\n      const pages = context.pages();\n      let injectedCount = 0;\n      for (const page of pages) {\n        try {\n          const result = await injectRecorderViaCDP(\n            page,\n            recorderState,\n            context.conn,\n            this._sessionRecordingOptions,\n            bindingHandler,\n          );\n          if (result !== null) {\n            injectedCount++;\n          }\n        } catch (error) {\n          // Page might have been closed or CDP session lost, continue with next page\n          logger.debug(\n            \"Error injecting recorder into page: \" + errorMessage(error),\n          );\n        }\n      }\n      logger.debug(\n        `Injected session recorder into ${injectedCount} of ${pages.length} existing page(s)`,\n      );\n    } catch (error) {\n      logger.debug(\n        \"Error accessing pages for recorder injection: \" + errorMessage(error),\n      );\n    }\n  }\n\n  private patchStagehandClose() {\n    const instrumentation = this;\n    return (original: Function) =>\n      async function method(this: any, ...args: any[]) {\n        // Clean up session recording before closing\n        instrumentation.cleanupSessionRecording(this);\n\n        // Clean up the session from the registry\n        const sessionId =\n          instrumentation.stagehandInstanceToSessionId.get(this);\n        if (sessionId) {\n          instrumentation.stagehandInstanceToSessionId.delete(this);\n        }\n\n        await original.bind(this).apply(this, args);\n\n        // Clean up the parent span from the registry\n        if (sessionId) {\n          const parentSpan =\n            instrumentation.sessionIdToParentSpan.get(sessionId);\n          if (parentSpan) {\n            parentSpan.end();\n            instrumentation.sessionIdToParentSpan.delete(sessionId);\n          }\n        }\n      };\n  }\n\n  /**\n   * Clean up session recording resources for a Stagehand instance\n   */\n  private cleanupSessionRecording(stagehandInstance: any): void {\n    const recorderState =\n      this.stagehandInstanceToRecorderState.get(stagehandInstance);\n    if (!recorderState) return;\n\n    // Get the context to remove event listeners\n    const context = stagehandInstance.context as StagehandV3Context | undefined;\n    if (context && context.conn) {\n      // Remove target created handler\n      if (recorderState.targetCreatedHandler) {\n        try {\n          context.conn.off(\n            \"Target.targetCreated\",\n            recorderState.targetCreatedHandler,\n          );\n        } catch (error) {\n          logger.debug(\n            \"Error removing target created handler: \" + errorMessage(error),\n          );\n        }\n      }\n\n      // Remove target info changed handler\n      if (recorderState.targetInfoChangedHandler) {\n        try {\n          context.conn.off(\n            \"Target.targetInfoChanged\",\n            recorderState.targetInfoChangedHandler,\n          );\n        } catch (error) {\n          logger.debug(\n            \"Error removing target info changed handler: \" +\n              errorMessage(error),\n          );\n        }\n      }\n    }\n\n    // Clear state\n    recorderState.contextIdToSession.clear();\n    recorderState.instrumentedPageIds.clear();\n    recorderState.chunkBuffers.clear();\n    recorderState.pageSessionHandlers.clear();\n    recorderState.bindingHandler = null;\n    recorderState.targetCreatedHandler = null;\n    recorderState.targetInfoChangedHandler = null;\n\n    // Remove from WeakMap\n    this.stagehandInstanceToRecorderState.delete(stagehandInstance);\n\n    logger.debug(\"Cleaned up session recording for Stagehand instance\");\n  }\n\n  private patchStagehandGlobalMethod(\n    methodName: string,\n    sessionId: StringUUID,\n    parentSpan: any,\n  ) {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function method(this: any, ...args: any[]) {\n        const input = nameArgsOrCopy(args);\n        const currentSpan =\n          trace.getSpan(LaminarContextManager.getContext()) ??\n          trace.getActiveSpan();\n\n        // Handle extract schema pretty-printing\n        if (\n          methodName === \"extract\" &&\n          Array.isArray(input) &&\n          input.length > 1 &&\n          input[1]?.shape\n        ) {\n          // We need to clone the input object to avoid mutating the original object\n          // because the original object is passed to the LLM client\n          const schema = input[1];\n          let prettySchema = schema?.shape;\n          try {\n            prettySchema = prettyPrintZodSchema(schema);\n          } catch (error) {\n            diag.warn(\"Error pretty printing zod schema\", { error });\n          }\n          input[1] = prettySchema;\n        }\n\n        // Also handle extract when options contain schema\n        if (\n          methodName === \"extract\" &&\n          Array.isArray(input) &&\n          input.length > 0 &&\n          typeof input[0] === \"string\" &&\n          input.length > 1 &&\n          input[1]?.shape\n        ) {\n          const schema = input[1];\n          let prettySchema = schema?.shape;\n          try {\n            prettySchema = prettyPrintZodSchema(schema);\n          } catch (error) {\n            diag.warn(\"Error pretty printing zod schema\", { error });\n          }\n          input[1] = prettySchema;\n        }\n\n        return await Laminar.withSpan(\n          currentSpan ?? parentSpan,\n          async () =>\n            await laminarObserve(\n              {\n                name: `stagehand.${methodName}`,\n                input,\n              },\n              async (thisArg: any, rest: any[]) => {\n                const span =\n                  trace.getSpan(LaminarContextManager.getContext()) ??\n                  trace.getActiveSpan();\n                span?.setAttribute(TRACE_HAS_BROWSER_SESSION, true);\n                return await original.apply(thisArg, rest);\n              },\n              this,\n              args,\n            ),\n        );\n      };\n  }\n\n  private patchActHandler(actHandler: any) {\n    // Patch the main act method on the handler (guarded because the\n    // upstream handler shape may change across Stagehand versions).\n    safeWrap(this, actHandler, \"act\", this.patchActHandlerAct());\n\n    // Patch actFromObserveResult (v2 only; v3 moved this to\n    // `takeDeterministicAction`, so guard to avoid wrapping non-existent methods)\n    safeWrap(\n      this,\n      actHandler,\n      \"actFromObserveResult\",\n      this.patchActHandlerActFromObserveResult(),\n    );\n  }\n\n  private patchActHandlerAct() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function act(this: any, ...args: any[]) {\n        const params = args[0];\n        return await laminarObserve(\n          {\n            name: \"stagehand.actHandler.act\",\n            input: {\n              instruction: params?.instruction,\n              variables: params?.variables,\n              timeout: params?.timeout,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  private patchActHandlerActFromObserveResult() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function actFromObserveResult(this: any, ...args: any[]) {\n        const action = args[0];\n        const domSettleTimeoutMs = args[2];\n        return await laminarObserve(\n          {\n            name: \"stagehand.actHandler.actFromObserveResult\",\n            input: {\n              action: action,\n              domSettleTimeoutMs: domSettleTimeoutMs,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  private patchExtractHandler(extractHandler: any) {\n    // Patch the main extract method on the handler\n    safeWrap(\n      this,\n      extractHandler,\n      \"extract\",\n      this.patchExtractHandlerExtract(),\n    );\n  }\n\n  private patchExtractHandlerExtract() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function extract(this: any, ...args: any[]) {\n        const params = args[0];\n        const schema = params?.schema;\n        let prettySchema = schema?.shape;\n\n        if (schema) {\n          try {\n            prettySchema = prettyPrintZodSchema(schema);\n          } catch (error) {\n            diag.warn(\"Error pretty printing zod schema\", { error });\n          }\n        }\n\n        return await laminarObserve(\n          {\n            name: \"stagehand.extractHandler.extract\",\n            input: {\n              instruction: params?.instruction,\n              schema: prettySchema,\n              timeout: params?.timeout,\n              selector: params?.selector,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  private patchObserveHandler(observeHandler: any) {\n    // Patch the main observe method on the handler\n    safeWrap(\n      this,\n      observeHandler,\n      \"observe\",\n      this.patchObserveHandlerObserve(),\n    );\n  }\n\n  private patchObserveHandlerObserve() {\n    return (original: (...args: any[]) => Promise<any>) =>\n      async function observe(this: any, ...args: any[]) {\n        const params = args[0];\n        return await laminarObserve(\n          {\n            name: \"stagehand.observeHandler.observe\",\n            input: {\n              instruction: params?.instruction,\n              timeout: params?.timeout,\n              selector: params?.selector,\n            },\n          },\n          async () => await original.bind(this).apply(this, args),\n        );\n      };\n  }\n\n  private patchStagehandLLMClientCreateChatCompletion() {\n    return createLLMClientCreateChatCompletionWrapper(\n      this.globalLLMClientOptions,\n    );\n  }\n\n  private patchStagehandAgentInitializer(\n    sessionId: StringUUID,\n    parentSpan: Span,\n  ) {\n    const instrumentation = this;\n    return (original: (...args: any[]) => any) =>\n      function agent(this: any, ...args: any[]) {\n        const agent = original.bind(this).apply(this, args);\n        if (args.length > 0 && typeof args[0] === \"object\") {\n          instrumentation.globalAgentOptions.set(agent, args[0]);\n        }\n        instrumentation.patchStagehandAgent(agent, sessionId, parentSpan);\n        return agent;\n      };\n  }\n\n  private patchStagehandAgent(\n    agent: any,\n    sessionId: StringUUID,\n    parentSpan: Span,\n  ) {\n    safeWrap(\n      this,\n      agent,\n      \"execute\",\n      this.patchStagehandAgentExecute(sessionId, parentSpan),\n    );\n\n    // Wrap additional agent methods (already no-ops when the method is missing\n    // via wrapAgentMethod's own guard)\n    this.wrapAgentMethod(agent, \"captureScreenshot\", parentSpan, {\n      spanType: \"TOOL\",\n      ignoreOutput: true,\n    });\n    this.wrapAgentMethod(agent, \"setViewport\", parentSpan);\n    this.wrapAgentMethod(agent, \"setCurrentUrl\", parentSpan);\n  }\n\n  private patchStagehandAgentExecute(sessionId: StringUUID, parentSpan: Span) {\n    const instrumentation = this;\n    return (original: (this: any, ...args: any[]) => Promise<any>) =>\n      async function execute(this: any, ...args: any[]) {\n        const input = nameArgsOrCopy(args);\n\n        return await Laminar.withSpan(\n          parentSpan,\n          async () =>\n            await laminarObserve(\n              {\n                name: \"stagehand.agent.execute\",\n                input,\n              },\n              async () =>\n                await laminarObserve(\n                  {\n                    name: \"execute\",\n                    // input and output are set as gen_ai.prompt and gen_ai.completion\n                    ignoreInput: true,\n                    ignoreOutput: true,\n                    spanType: \"LLM\",\n                  },\n                  async () => {\n                    const span =\n                      trace.getSpan(LaminarContextManager.getContext()) ??\n                      trace.getActiveSpan();\n                    span?.setAttribute(TRACE_HAS_BROWSER_SESSION, true);\n\n                    const agentOptions =\n                      instrumentation.globalAgentOptions.get(this);\n                    const maybeModelName: string | undefined =\n                      agentOptions?.model?.modelName ??\n                      (typeof agentOptions?.model === \"string\"\n                        ? agentOptions.model\n                        : undefined);\n                    const provider =\n                      agentOptions?.model?.provider ??\n                      (maybeModelName?.includes(\"/\")\n                        ? maybeModelName?.split(\"/\")[0]\n                        : instrumentation.globalLLMClientOptions.get(this)\n                            ?.provider);\n                    const model =\n                      maybeModelName ??\n                      instrumentation.globalLLMClientOptions.get(this)?.model;\n                    span?.setAttributes({\n                      ...(provider ? { \"gen_ai.system\": provider } : {}),\n                      ...(model ? { \"gen_ai.request.model\": model } : {}),\n                    });\n\n                    let promptIndex = 0;\n                    if (agentOptions?.systemPrompt) {\n                      span?.setAttributes({\n                        \"gen_ai.prompt.0.content\": agentOptions.systemPrompt,\n                        \"gen_ai.prompt.0.role\": \"system\",\n                      });\n                      promptIndex++;\n                    }\n\n                    const instruction =\n                      typeof input === \"string\"\n                        ? input\n                        : (input as any).instruction;\n                    if (instruction) {\n                      span?.setAttributes({\n                        [`gen_ai.prompt.${promptIndex}.content`]: instruction,\n                        [`gen_ai.prompt.${promptIndex}.role`]: \"user\",\n                      });\n                    }\n\n                    const result = await original.bind(this).apply(this, args);\n\n                    if (result.completed && result.success && result.message) {\n                      const content = [{ type: \"text\", text: result.message }];\n                      if (result.actions && result.actions.length > 0) {\n                        content.push({\n                          type: \"text\",\n                          text: JSON.stringify({ actions: result.actions }),\n                        });\n                      }\n                      span?.setAttributes({\n                        \"gen_ai.completion.0.content\": JSON.stringify(content),\n                        \"gen_ai.completion.0.role\": \"assistant\",\n                      });\n                    } else if (result.completed && !result.success) {\n                      span?.recordException(new Error(result.message));\n                    }\n                    if (result.usage) {\n                      span?.setAttributes({\n                        \"gen_ai.usage.input_tokens\": result.usage.input_tokens,\n                        \"gen_ai.usage.output_tokens\":\n                          result.usage.output_tokens,\n                        \"llm.usage.total_tokens\":\n                          result.usage.input_tokens +\n                          result.usage.output_tokens,\n                      });\n                    }\n                    return result;\n                  },\n                ),\n            ),\n        );\n      };\n  }\n\n  private wrapAgentMethod(\n    agent: any,\n    methodName: string,\n    parentSpan: Span,\n    options?: {\n      spanType?:\n        | \"TOOL\"\n        | \"LLM\"\n        | \"DEFAULT\"\n        | \"EVALUATOR\"\n        | \"EVALUATION\"\n        | \"EXECUTOR\";\n      ignoreOutput?: boolean;\n    },\n  ) {\n    safeWrap(\n      this,\n      agent,\n      methodName,\n      (original: (...args: any[]) => Promise<any>) =>\n        async function method(this: any, ...args: any[]) {\n          const currentSpan =\n            trace.getSpan(LaminarContextManager.getContext()) ??\n            trace.getActiveSpan();\n          return await Laminar.withSpan(\n            currentSpan ?? parentSpan,\n            async () =>\n              await laminarObserve(\n                {\n                  name: `stagehand.agent.${methodName}`,\n                  ...(options?.spanType ? { spanType: options.spanType } : {}),\n                  ...(options?.ignoreOutput ? { ignoreOutput: true } : {}),\n                },\n                async (argVals: any[]) =>\n                  await original.bind(this).apply(this, argVals),\n                args,\n              ),\n          );\n        },\n    );\n  }\n\n  private patchStagehandPage(page: any, parentSpan: Span) {\n    const pageMethods = [\n      \"goto\",\n      \"reload\",\n      \"goBack\",\n      \"goForward\",\n      \"click\",\n      \"scroll\",\n      \"dragAndDrop\",\n      \"type\",\n      \"keyPress\",\n      \"keyDown\",\n      \"keyUp\",\n    ];\n\n    for (const methodName of pageMethods) {\n      safeWrap(\n        this,\n        page,\n        methodName,\n        (original: (...args: any[]) => Promise<any>) =>\n          async function method(this: any, ...args: any[]) {\n            const currentSpan =\n              trace.getSpan(LaminarContextManager.getContext()) ??\n              trace.getActiveSpan();\n            return await Laminar.withSpan(\n              currentSpan ?? parentSpan,\n              async () =>\n                await laminarObserve(\n                  {\n                    name: `stagehand.page.${methodName}`,\n                  },\n                  async (argVals: any[]) =>\n                    await original.bind(this).apply(this, argVals),\n                  args,\n                ),\n            );\n          },\n      );\n    }\n  }\n\n  /**\n   * In BROWSERBASE remote mode Stagehand's top-level `act`/`extract`/`observe`/\n   * agent `execute` are routed through an internal `StagehandAPIClient` which\n   * makes HTTP calls to the Stagehand Cloud API. The local `llmClient` and the\n   * local `actHandler`/`extractHandler`/`observeHandler` are therefore never\n   * invoked and our existing wrappers do not fire.\n   *\n   * Wrap the apiClient methods directly so we still emit child spans for the\n   * LLM-backed calls and surface token usage from the response where available.\n   */\n  private patchStagehandApiClient(\n    apiClient: any,\n    parentSpan: Span,\n    stagehandInstance: any,\n  ) {\n    let baseProvider = stagehandInstance?.llmClient?.type as string | undefined;\n    const baseModel = stagehandInstance?.llmClient?.modelName as\n      | string\n      | undefined;\n\n    if (baseModel && !baseProvider) {\n      baseProvider = modelToProvider(baseModel) ?? \"aisdk\";\n    }\n\n    const wrapApiMethod = (methodName: \"act\" | \"extract\" | \"observe\") => {\n      safeWrap(\n        this,\n        apiClient,\n        methodName,\n        (original: (...args: any[]) => Promise<any>) =>\n          async function method(this: any, ...args: any[]) {\n            const currentSpan =\n              trace.getSpan(LaminarContextManager.getContext()) ??\n              trace.getActiveSpan();\n\n            const input = nameArgsOrCopy(args);\n\n            const spanName = `stagehand.apiClient.${methodName}`;\n\n            return await Laminar.withSpan(\n              currentSpan ?? parentSpan,\n              async () =>\n                await laminarObserve(\n                  {\n                    name: spanName,\n                    input,\n                    spanType: \"LLM\",\n                    ignoreInput: true,\n                    ignoreOutput: true,\n                  },\n                  async () => {\n                    const span =\n                      trace.getSpan(LaminarContextManager.getContext()) ??\n                      trace.getActiveSpan();\n                    span?.setAttribute(TRACE_HAS_BROWSER_SESSION, true);\n\n                    // Best-effort provider/model attribution. Stagehand's\n                    // remote API does not echo these back in the SSE stream,\n                    // so fall back to the model configured on the instance.\n                    if (baseProvider) {\n                      span?.setAttribute(\"gen_ai.system\", baseProvider);\n                    }\n                    if (baseModel) {\n                      span?.setAttribute(\"gen_ai.request.model\", baseModel);\n                    }\n\n                    // Capture the user-facing instruction as the LLM prompt\n                    // when available so traces are not empty.\n                    try {\n                      const firstArg = args[0];\n                      const instruction =\n                        typeof firstArg === \"string\"\n                          ? firstArg\n                          : (firstArg?.input ?? firstArg?.instruction);\n                      if (\n                        typeof instruction === \"string\" &&\n                        instruction.length > 0\n                      ) {\n                        span?.setAttributes({\n                          \"gen_ai.prompt.0.role\": \"user\",\n                          \"gen_ai.prompt.0.content\": instruction,\n                        });\n                      }\n                    } catch {\n                      // best-effort; do not break the call if attribute extraction fails\n                    }\n\n                    const result = await original.bind(this).apply(this, args);\n\n                    try {\n                      const usage = result?.usage;\n                      if (usage) {\n                        const inputTokens =\n                          usage.input_tokens ?? usage.prompt_tokens ?? 0;\n                        const outputTokens =\n                          usage.output_tokens ?? usage.completion_tokens ?? 0;\n                        span?.setAttributes({\n                          \"gen_ai.usage.input_tokens\": inputTokens,\n                          \"gen_ai.usage.output_tokens\": outputTokens,\n                          \"llm.usage.total_tokens\": inputTokens + outputTokens,\n                        });\n                      }\n                      span?.setAttribute(\n                        \"gen_ai.output.messages\",\n                        JSON.stringify([\n                          {\n                            role: \"assistant\",\n                            content: result,\n                          },\n                        ]),\n                      );\n                    } catch {\n                      // best-effort\n                    }\n\n                    return result;\n                  },\n                ),\n            );\n          },\n      );\n    };\n\n    // There's no agentExecute here, as the local wrapper\n    // adds sufficient information onto the resulting spans\n    wrapApiMethod(\"act\");\n    wrapApiMethod(\"extract\");\n    wrapApiMethod(\"observe\");\n  }\n}\n","import { SpanStatusCode } from \"@opentelemetry/api\";\n\nimport { LaminarSpan } from \"../../tracing/span\";\n\n// Re-export attribute keys we use frequently\nconst LLM_REQUEST_MODEL = \"gen_ai.request.model\";\nconst LLM_RESPONSE_MODEL = \"gen_ai.response.model\";\nconst LLM_SYSTEM = \"gen_ai.system\";\nconst LLM_USAGE_TOTAL_TOKENS = \"llm.usage.total_tokens\";\n\n/**\n * Set an attribute on a span only if the value is non-null, non-undefined, and non-empty.\n */\nfunction safeSetAttribute(\n  span: LaminarSpan,\n  key: string,\n  value: unknown,\n): void {\n  if (value === null || value === undefined) return;\n  if (typeof value === \"string\" && value.length === 0) return;\n  if (Array.isArray(value) && value.length === 0) return;\n  span.setAttribute(key, value as any);\n}\n\n/**\n * Convert an SDK object to a plain JSON-serializable object.\n */\nfunction toDict(obj: unknown): unknown {\n  if (obj === null || obj === undefined) return obj;\n  if (typeof obj !== \"object\") return obj;\n  if (Array.isArray(obj)) return obj.map(toDict);\n  const result: Record<string, unknown> = {};\n  for (const [k, v] of Object.entries(obj as Record<string, unknown>)) {\n    if (v !== undefined) {\n      result[k] = toDict(v);\n    }\n  }\n  return result;\n}\n\n/**\n * Normalize contents to an array of {role, parts} message objects.\n * The GenAI SDK accepts many content shapes; this normalizes them for attribute logging.\n */\nfunction contentToMessages(\n  contents: unknown,\n  systemInstruction?: unknown,\n): unknown[] {\n  const messages: unknown[] = [];\n\n  if (systemInstruction) {\n    if (typeof systemInstruction === \"string\") {\n      messages.push({ role: \"system\", content: systemInstruction });\n    } else if (\n      typeof systemInstruction === \"object\" &&\n      systemInstruction !== null\n    ) {\n      messages.push({\n        role: \"system\",\n        ...(toDict(systemInstruction) as Record<string, any>),\n      });\n    }\n  }\n\n  if (typeof contents === \"string\") {\n    messages.push({ role: \"user\", content: contents });\n  } else if (Array.isArray(contents)) {\n    for (const item of contents) {\n      if (typeof item === \"string\") {\n        messages.push({ role: \"user\", content: item });\n      } else {\n        messages.push(toDict(item));\n      }\n    }\n  } else if (contents && typeof contents === \"object\") {\n    messages.push(toDict(contents));\n  }\n\n  return messages;\n}\n\n/**\n * Extract function declarations from the tools config.\n */\nfunction extractToolDefinitions(config: any): any[] {\n  if (!config?.tools) return [];\n  const tools: any[] = [];\n  const toolsArray = Array.isArray(config.tools)\n    ? config.tools\n    : [config.tools];\n\n  for (const tool of toolsArray) {\n    if (!tool) continue;\n    // Tool can be a Tool object with functionDeclarations\n    if (tool.functionDeclarations) {\n      for (const fd of tool.functionDeclarations) {\n        tools.push(toDict(fd));\n      }\n    }\n    // Or it could be a single FunctionDeclaration-like object\n    if (tool.name && !tool.functionDeclarations) {\n      tools.push(toDict(tool));\n    }\n  }\n  return tools;\n}\n\n/**\n * Set request attributes on a span from generateContent params.\n */\nexport function setRequestAttributes(\n  span: LaminarSpan,\n  params: any,\n  traceContent: boolean,\n): void {\n  safeSetAttribute(span, LLM_SYSTEM, \"gemini\");\n\n  safeSetAttribute(span, LLM_REQUEST_MODEL, params?.model);\n\n  const config = params?.config;\n  if (config) {\n    safeSetAttribute(span, \"gen_ai.request.temperature\", config.temperature);\n    safeSetAttribute(span, \"gen_ai.request.top_p\", config.topP);\n    safeSetAttribute(span, \"gen_ai.request.top_k\", config.topK);\n    safeSetAttribute(span, \"gen_ai.request.max_tokens\", config.maxOutputTokens);\n    safeSetAttribute(\n      span,\n      \"gen_ai.request.frequency_penalty\",\n      config.frequencyPenalty,\n    );\n    safeSetAttribute(\n      span,\n      \"gen_ai.request.presence_penalty\",\n      config.presencePenalty,\n    );\n    safeSetAttribute(span, \"gen_ai.request.seed\", config.seed);\n    safeSetAttribute(\n      span,\n      \"gen_ai.request.choice_count\",\n      config.candidateCount,\n    );\n\n    if (config.stopSequences && config.stopSequences.length > 0) {\n      safeSetAttribute(\n        span,\n        \"gen_ai.request.stop_sequences\",\n        JSON.stringify(config.stopSequences),\n      );\n    }\n\n    const outputSchema = config.responseSchema ?? config.responseJsonSchema;\n    if (outputSchema) {\n      safeSetAttribute(\n        span,\n        \"gen_ai.request.structured_output_schema\",\n        JSON.stringify(toDict(outputSchema)),\n      );\n    }\n\n    // Tool definitions\n    const toolDefs = extractToolDefinitions(config);\n    if (toolDefs.length > 0) {\n      safeSetAttribute(\n        span,\n        \"gen_ai.tool.definitions\",\n        JSON.stringify(toolDefs),\n      );\n    }\n  }\n\n  // Input messages (content-traced only)\n  if (traceContent) {\n    const messages = contentToMessages(\n      params?.contents,\n      config?.systemInstruction,\n    );\n    if (messages.length > 0) {\n      safeSetAttribute(span, \"gen_ai.input.messages\", JSON.stringify(messages));\n    }\n  }\n}\n\n/**\n * Set response attributes on a span from a GenerateContentResponse.\n */\nexport function setResponseAttributes(\n  span: LaminarSpan,\n  response: any,\n  traceContent: boolean,\n): void {\n  if (!response) return;\n\n  safeSetAttribute(span, LLM_RESPONSE_MODEL, response.modelVersion);\n\n  // Usage metadata\n  const usage = response.usageMetadata;\n  if (usage) {\n    safeSetAttribute(span, \"gen_ai.usage.input_tokens\", usage.promptTokenCount);\n\n    const outputTokens =\n      (usage.candidatesTokenCount ?? 0) + (usage.thoughtsTokenCount ?? 0);\n    if (outputTokens > 0) {\n      safeSetAttribute(span, \"gen_ai.usage.output_tokens\", outputTokens);\n    }\n\n    safeSetAttribute(span, LLM_USAGE_TOTAL_TOKENS, usage.totalTokenCount);\n    safeSetAttribute(\n      span,\n      \"gen_ai.usage.reasoning_tokens\",\n      usage.thoughtsTokenCount,\n    );\n    safeSetAttribute(\n      span,\n      \"gen_ai.usage.cache_read_input_tokens\",\n      usage.cachedContentTokenCount,\n    );\n  }\n\n  // Response content (content-traced only)\n  if (traceContent && response.candidates) {\n    const outputMessages: any[] = [];\n\n    for (let i = 0; i < response.candidates.length; i++) {\n      const candidate = response.candidates[i];\n      const content = candidate?.content;\n      if (!content) continue;\n\n      const role = content.role ?? \"model\";\n\n      // Extract text content and tool calls\n      const parts = content.parts ?? [];\n      const textParts: string[] = [];\n      const toolCalls: any[] = [];\n\n      for (let j = 0; j < parts.length; j++) {\n        const part = parts[j];\n        if (part.text !== undefined) {\n          textParts.push(part.text);\n        }\n        if (part.functionCall) {\n          toolCalls.push({\n            name: part.functionCall.name,\n            id: part.functionCall.id,\n            arguments: JSON.stringify(toDict(part.functionCall.args)),\n          });\n        }\n      }\n\n      const completionContent = textParts.join(\"\");\n\n      outputMessages.push({\n        role,\n        content: completionContent,\n        ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),\n      });\n    }\n\n    if (outputMessages.length > 0) {\n      safeSetAttribute(\n        span,\n        \"gen_ai.output.messages\",\n        JSON.stringify(outputMessages),\n      );\n    }\n  }\n}\n\n/**\n * Merge consecutive text parts in accumulated streaming parts.\n */\nfunction mergeTextParts(parts: any[]): any[] {\n  if (parts.length === 0) return parts;\n\n  const merged: any[] = [];\n  for (const part of parts) {\n    if (\n      part.text !== undefined &&\n      merged.length > 0 &&\n      merged[merged.length - 1].text !== undefined\n    ) {\n      merged[merged.length - 1] = {\n        ...merged[merged.length - 1],\n        text: merged[merged.length - 1].text + part.text,\n      };\n    } else {\n      merged.push({ ...part });\n    }\n  }\n  return merged;\n}\n\n/**\n * Wrap a streaming async generator to accumulate response data and set span attributes\n * when iteration completes, throws, or is terminated early by the consumer.\n *\n * generateContentStream returns Promise<AsyncGenerator<GenerateContentResponse>>.\n * This wraps the inner async generator.\n */\nexport function wrapStreamingResponse(\n  span: LaminarSpan,\n  asyncGen: AsyncGenerator<any>,\n  traceContent: boolean,\n): AsyncGenerator<any> {\n  const accumulatedParts: any[] = [];\n  let promptTokenCount: number | undefined;\n  let candidatesTokenCount: number | undefined;\n  let thoughtsTokenCount: number | undefined;\n  let totalTokenCount: number | undefined;\n  let cachedContentTokenCount: number | undefined;\n  let role: string | undefined;\n  let modelVersion: string | undefined;\n  let sawUsageMetadata = false;\n\n  async function* wrapper(): AsyncGenerator<any> {\n    let streamError: unknown;\n    let finalizeError: unknown;\n    try {\n      for await (const chunk of asyncGen) {\n        // Accumulate parts\n        if (chunk?.candidates) {\n          for (const candidate of chunk.candidates) {\n            const parts = candidate?.content?.parts;\n            if (parts) {\n              accumulatedParts.push(...parts);\n            }\n            if (candidate?.content?.role && !role) {\n              role = candidate.content.role;\n            }\n          }\n        }\n\n        // Accumulate usage\n        const usage = chunk?.usageMetadata;\n        if (usage) {\n          sawUsageMetadata = true;\n          if (\n            promptTokenCount === undefined &&\n            usage.promptTokenCount !== undefined\n          ) {\n            promptTokenCount = usage.promptTokenCount;\n          }\n          if (usage.candidatesTokenCount !== undefined) {\n            candidatesTokenCount = usage.candidatesTokenCount;\n          }\n          if (usage.thoughtsTokenCount !== undefined) {\n            thoughtsTokenCount = usage.thoughtsTokenCount;\n          }\n          if (usage.totalTokenCount !== undefined) {\n            totalTokenCount = usage.totalTokenCount;\n          }\n          if (\n            cachedContentTokenCount === undefined &&\n            usage.cachedContentTokenCount !== undefined\n          ) {\n            cachedContentTokenCount = usage.cachedContentTokenCount;\n          }\n        }\n\n        if (chunk?.modelVersion && !modelVersion) {\n          modelVersion = chunk.modelVersion;\n        }\n\n        yield chunk;\n      }\n    } catch (error) {\n      streamError = error;\n      span.setAttribute(\n        \"error.type\",\n        (error as Error).constructor?.name ?? \"Error\",\n      );\n      span.recordException(error as Error);\n      span.setStatus({ code: SpanStatusCode.ERROR });\n      throw error;\n    } finally {\n      try {\n        const hasResponseData =\n          modelVersion !== undefined ||\n          role !== undefined ||\n          accumulatedParts.length > 0 ||\n          sawUsageMetadata;\n        if (hasResponseData) {\n          const mergedParts = mergeTextParts(accumulatedParts);\n          const compoundResponse = {\n            modelVersion,\n            candidates: [\n              {\n                content: {\n                  role: role ?? \"model\",\n                  parts: mergedParts,\n                },\n              },\n            ],\n            usageMetadata: {\n              promptTokenCount,\n              candidatesTokenCount,\n              thoughtsTokenCount,\n              totalTokenCount,\n              cachedContentTokenCount,\n            },\n          };\n\n          setResponseAttributes(span, compoundResponse, traceContent);\n        }\n      } catch (caughtFinalizeError) {\n        // Do not override the original stream error.\n        if (!streamError) {\n          finalizeError = caughtFinalizeError;\n        }\n      } finally {\n        span.end();\n      }\n    }\n    if (finalizeError) {\n      if (finalizeError instanceof Error) {\n        throw finalizeError;\n      }\n      throw new Error(\"Failed to finalize google-genai stream span\");\n    }\n  }\n\n  return wrapper();\n}\n","import { context, diag, SpanStatusCode } from \"@opentelemetry/api\";\nimport { isTracingSuppressed } from \"@opentelemetry/core\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\n\nimport { version as SDK_VERSION } from \"../../../../package.json\";\nimport { Laminar } from \"../../../laminar\";\nimport { LaminarSpan } from \"../../tracing/span\";\nimport {\n  setRequestAttributes,\n  setResponseAttributes,\n  wrapStreamingResponse,\n} from \"./utils\";\n\nconst WRAPPED_SYMBOL = Symbol(\"lmnr.google-genai.wrapped\");\nconst CLASS_PATCH_DATA_SYMBOL = Symbol(\"lmnr.google-genai.classPatchData\");\n\ntype ClassPatchData = {\n  instrumentation: GoogleGenAiInstrumentation;\n  traceContent: boolean;\n  originalModelsDescriptor: PropertyDescriptor | undefined;\n};\n\nexport class GoogleGenAiInstrumentation extends InstrumentationBase {\n  private traceContent: boolean;\n\n  constructor(config?: { traceContent?: boolean }) {\n    super(\"@lmnr/google-genai-instrumentation\", SDK_VERSION, { enabled: true });\n    this.traceContent = config?.traceContent ?? true;\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    return new InstrumentationNodeModuleDefinition(\n      \"@google/genai\",\n      [\">=1.0.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n  }\n\n  public manuallyInstrument(genaiModule: any): void {\n    diag.debug(\"Manually instrumenting @google/genai\");\n    const GoogleGenAIClass = this.resolveGoogleGenAIClass(genaiModule);\n    if (GoogleGenAIClass) {\n      this.patchGoogleGenAIClass(GoogleGenAIClass);\n    } else {\n      diag.warn(\n        \"Could not find GoogleGenAI class in google_genai manual instrumentation input. \" +\n          \"Pass either GoogleGenAI class or module object with GoogleGenAI export.\",\n      );\n    }\n  }\n\n  private patch(moduleExports: any): any {\n    diag.debug(\"Patching @google/genai\");\n    const GoogleGenAIClass = this.resolveGoogleGenAIClass(moduleExports);\n    if (GoogleGenAIClass) {\n      this.patchGoogleGenAIClass(GoogleGenAIClass);\n    }\n    return moduleExports;\n  }\n\n  private unpatch(moduleExports: any): void {\n    diag.debug(\"Unpatching @google/genai\");\n    const GoogleGenAIClass = this.resolveGoogleGenAIClass(moduleExports);\n    if (GoogleGenAIClass) {\n      this.unpatchGoogleGenAIClass(GoogleGenAIClass);\n    }\n  }\n\n  private resolveGoogleGenAIClass(moduleOrClass: any): any {\n    if (typeof moduleOrClass === \"function\") {\n      return moduleOrClass;\n    }\n    if (\n      moduleOrClass?.GoogleGenAI &&\n      typeof moduleOrClass.GoogleGenAI === \"function\"\n    ) {\n      return moduleOrClass.GoogleGenAI;\n    }\n    return undefined;\n  }\n\n  private patchGoogleGenAIClass(GoogleGenAIClass: any): void {\n    const classPatchData = GoogleGenAIClass[CLASS_PATCH_DATA_SYMBOL] as\n      | ClassPatchData\n      | undefined;\n    if (classPatchData) {\n      classPatchData.instrumentation = this;\n      classPatchData.traceContent = this.traceContent;\n      return;\n    }\n\n    const originalModelsDescriptor = Object.getOwnPropertyDescriptor(\n      GoogleGenAIClass.prototype,\n      \"models\",\n    );\n    if (originalModelsDescriptor && !originalModelsDescriptor.configurable) {\n      diag.warn(\n        \"Could not patch GoogleGenAI.prototype.models: descriptor is non-configurable.\",\n      );\n      return;\n    }\n\n    const patchData: ClassPatchData = {\n      instrumentation: this,\n      traceContent: this.traceContent,\n      originalModelsDescriptor,\n    };\n    Object.defineProperty(GoogleGenAIClass, CLASS_PATCH_DATA_SYMBOL, {\n      value: patchData,\n      writable: true,\n      configurable: true,\n      enumerable: false,\n    });\n\n    Object.defineProperty(GoogleGenAIClass.prototype, \"models\", {\n      configurable: true,\n      enumerable: originalModelsDescriptor?.enumerable ?? true,\n      get: function () {\n        if (originalModelsDescriptor?.get) {\n          return originalModelsDescriptor.get.call(this);\n        }\n        return undefined;\n      },\n      set: function (value: any) {\n        patchData.instrumentation.patchModelsInstance(value, patchData);\n        if (originalModelsDescriptor?.set) {\n          originalModelsDescriptor.set.call(this, value);\n          return;\n        }\n        Object.defineProperty(this, \"models\", {\n          value,\n          writable: true,\n          configurable: true,\n          enumerable: true,\n        });\n      },\n    });\n  }\n\n  private unpatchGoogleGenAIClass(GoogleGenAIClass: any): void {\n    const classPatchData = GoogleGenAIClass[CLASS_PATCH_DATA_SYMBOL] as\n      | ClassPatchData\n      | undefined;\n    if (!classPatchData) {\n      return;\n    }\n    if (classPatchData.originalModelsDescriptor) {\n      Object.defineProperty(\n        GoogleGenAIClass.prototype,\n        \"models\",\n        classPatchData.originalModelsDescriptor,\n      );\n    } else {\n      delete GoogleGenAIClass.prototype.models;\n    }\n    delete GoogleGenAIClass[CLASS_PATCH_DATA_SYMBOL];\n  }\n\n  private patchModelsInstance(\n    models: any,\n    classPatchData: ClassPatchData,\n  ): void {\n    if (!models || typeof models !== \"object\") return;\n    if (typeof models.generateContent !== \"function\") return;\n    if (typeof models.generateContentStream !== \"function\") return;\n\n    // Guard against double-wrapping\n    if (models[WRAPPED_SYMBOL]) return;\n\n    const originalGenerateContent = models.generateContent.bind(models);\n    const originalGenerateContentStream =\n      models.generateContentStream.bind(models);\n    models.generateContent = async function (params: any) {\n      if (isTracingSuppressed(context.active())) {\n        return originalGenerateContent(params);\n      }\n\n      const span = Laminar.startSpan({\n        name: \"gemini.generate_content\",\n        spanType: \"LLM\",\n      }) as LaminarSpan;\n\n      setRequestAttributes(span, params, classPatchData.traceContent);\n\n      return Laminar.withSpan(\n        span,\n        async () => {\n          try {\n            const response = await originalGenerateContent(params);\n            setResponseAttributes(span, response, classPatchData.traceContent);\n            return response;\n          } catch (error) {\n            span.setAttribute(\n              \"error.type\",\n              (error as Error).constructor?.name ?? \"Error\",\n            );\n            span.setStatus({ code: SpanStatusCode.ERROR });\n            throw error;\n          }\n        },\n        true,\n      );\n    };\n\n    models.generateContentStream = async function (params: any) {\n      if (isTracingSuppressed(context.active())) {\n        return originalGenerateContentStream(params);\n      }\n\n      const span = Laminar.startSpan({\n        name: \"gemini.generate_content_stream\",\n        spanType: \"LLM\",\n      }) as LaminarSpan;\n\n      setRequestAttributes(span, params, classPatchData.traceContent);\n\n      try {\n        const asyncGen = await originalGenerateContentStream(params);\n        return wrapStreamingResponse(\n          span,\n          asyncGen,\n          classPatchData.traceContent,\n        );\n      } catch (error) {\n        span.setAttribute(\n          \"error.type\",\n          (error as Error).constructor?.name ?? \"Error\",\n        );\n        span.recordException(error as Error);\n        span.setStatus({ code: SpanStatusCode.ERROR });\n        span.end();\n        throw error;\n      }\n    };\n\n    models[WRAPPED_SYMBOL] = true;\n  }\n}\n","// biome-ignore-all lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\nimport type * as KernelSDK from \"@onkernel/sdk\";\nimport { diag } from \"@opentelemetry/api\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\n\nimport { version as SDK_VERSION } from \"../../../package.json\";\nimport { observe } from \"../../decorators\";\nimport { Laminar } from \"../../laminar\";\n\nconst WRAPPED_BROWSER_METHODS: (keyof KernelSDK.Kernel.Browsers)[] = [\n  \"create\",\n  \"retrieve\",\n  \"list\",\n  \"deleteByID\",\n  \"loadExtensions\",\n];\n\nconst WRAPPED_COMPUTER_METHODS: (keyof KernelSDK.Kernel.Browsers.Computer)[] = [\n  \"captureScreenshot\",\n  \"clickMouse\",\n  \"dragMouse\",\n  \"moveMouse\",\n  \"pressKey\",\n  \"scroll\",\n  \"typeText\",\n];\n\nconst WRAPPED_PROCESS_METHODS: (keyof KernelSDK.Kernel.Browsers.Process)[] = [\n  \"exec\",\n  \"kill\",\n  \"spawn\",\n  \"status\",\n  \"stdin\",\n  \"stdoutStream\",\n];\n\nexport class KernelInstrumentation extends InstrumentationBase {\n  constructor() {\n    super(\"@lmnr/kernel-instrumentation\", SDK_VERSION, {\n      enabled: true,\n    });\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    const module = new InstrumentationNodeModuleDefinition(\n      \"@onkernel/sdk\",\n      [\">=0.7.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n\n    return module;\n  }\n\n  public manuallyInstrument(kernelModule: typeof KernelSDK) {\n    // Instrument resource classes\n    for (const wrappedMethod of WRAPPED_BROWSER_METHODS) {\n      this._wrap(\n        kernelModule.Kernel.Browsers.prototype,\n        wrappedMethod,\n        this.patchMethod(\"Browser\", wrappedMethod, \"DEFAULT\"),\n      );\n    }\n    for (const wrappedMethod of WRAPPED_COMPUTER_METHODS) {\n      if (wrappedMethod === \"captureScreenshot\") {\n        this._wrap(\n          kernelModule.Kernel.Browsers.Computer.prototype,\n          wrappedMethod,\n          this.patchTakeScreenshot(),\n        );\n      } else {\n        this._wrap(\n          kernelModule.Kernel.Browsers.Computer.prototype,\n          wrappedMethod,\n          this.patchMethod(\"Computer\", wrappedMethod, \"TOOL\"),\n        );\n      }\n    }\n    for (const wrappedMethod of WRAPPED_PROCESS_METHODS) {\n      this._wrap(\n        kernelModule.Kernel.Browsers.Process.prototype,\n        wrappedMethod,\n        this.patchProcessMethod(wrappedMethod),\n      );\n    }\n\n    // Wrap the Kernel.app() factory method to patch KernelApp.action()\n    this._wrap(kernelModule.Kernel.prototype, \"app\", this.patchAppFactory());\n  }\n\n  private patchMethod(\n    className: string,\n    method: string,\n    spanType: \"DEFAULT\" | \"TOOL\",\n  ): any {\n    const plugin = this;\n    return (original: (...args: any[]) => KernelSDK.APIPromise<unknown>) =>\n      async function (this: any, ...args: any[]) {\n        // Use observe() to automatically handle span lifecycle, input/output capture, and errors\n        return await observe(\n          {\n            name: `${className}.${method}`,\n            spanType,\n            input: plugin.formatInput(args),\n          },\n          async (innerArgs: any[]) =>\n            await original.bind(this).apply(this, innerArgs),\n          args,\n        );\n      };\n  }\n\n  private patchTakeScreenshot(): any {\n    const plugin = this;\n    return (original: (...args: any[]) => KernelSDK.APIPromise<unknown>) =>\n      async function (this: any, ...args: any[]) {\n        // Use observe() to automatically handle span lifecycle, input/output capture, and errors\n        const span = Laminar.startSpan({\n          name: `Computer.captureScreenshot`,\n          spanType: \"TOOL\",\n          input: plugin.formatInput(args),\n        });\n        try {\n          const res = (await original\n            .bind(this)\n            .apply(this, args)) as KernelSDK.APIPromise<unknown>;\n          // We could actually parse binary and decode here, but we would need to consume\n          // the api response byte stream, which may break the subsequent operations\n          // on the response.\n          span.setAttribute(\"lmnr.span.output\", \"<BASE64_ENCODED_IMAGE>\");\n          return res;\n        } finally {\n          span.end();\n        }\n      };\n  }\n\n  private patchProcessMethod(method: string): any {\n    const plugin = this;\n    return (original: (...args: any[]) => KernelSDK.APIPromise<unknown>) =>\n      async function (this: any, ...args: any[]) {\n        // First parameter of spawn and exec is the session ID, for others its PID (string)\n        const input = [\"spawn\", \"exec\"].includes(method)\n          ? plugin.formatInput(args)\n          : plugin.formatProcessInput(args);\n        const span = Laminar.startSpan({\n          name: `Process.${method}`,\n          spanType: \"TOOL\",\n          input,\n        });\n        try {\n          const result = await (original\n            .bind(this)\n            .apply(this, args) as KernelSDK.APIPromise<{\n            stderr_b64?: string;\n            stdout_b64?: string;\n          }>);\n          const output = {\n            ...(result?.stderr_b64\n              ? {\n                  stderr: Buffer.from(result.stderr_b64, \"base64\").toString(\n                    \"utf-8\",\n                  ),\n                }\n              : {}),\n            ...(result?.stdout_b64\n              ? {\n                  stdout: Buffer.from(result.stdout_b64, \"base64\").toString(\n                    \"utf-8\",\n                  ),\n                }\n              : {}),\n            ...result,\n          };\n          span.setAttribute(\"lmnr.span.output\", JSON.stringify(output));\n          return result;\n        } finally {\n          span.end();\n        }\n      };\n  }\n\n  private patchAppFactory() {\n    const plugin = this;\n    return (original: Function) =>\n      function (this: any, name: string): any {\n        // Call the original app() method to get the KernelApp instance\n        const kernelApp = original.call(this, name);\n\n        // Patch the action method on the returned KernelApp instance\n        plugin._wrap(kernelApp, \"action\", plugin.patchKernelAppAction());\n\n        return kernelApp;\n      };\n  }\n\n  private patchKernelAppAction() {\n    return (original: any) =>\n      function (this: any, name: string, handler: Function): any {\n        // Wrap the handler with observe\n        const wrappedHandler = async (context: any, payload?: any) => {\n          const result = await observe(\n            {\n              name: `action.${name}`,\n              spanType: \"DEFAULT\",\n            },\n            async (innerCtx: any, innerPayload: any) => {\n              const result = await handler(innerCtx, innerPayload);\n              return result;\n            },\n            context,\n            payload,\n          );\n          await Laminar.flush();\n          return result;\n        };\n\n        // Register the wrapped handler with the original action method\n        return original.call(this, name, wrappedHandler);\n      };\n  }\n\n  private formatInput(args: unknown[]): unknown[] {\n    if (args.length === 0) {\n      return [];\n    }\n    if (typeof args[0] === \"string\") {\n      return [{ session_id: args[0] }, ...args.slice(1)];\n    }\n    return args;\n  }\n\n  private formatProcessInput(args: unknown[]): unknown[] {\n    if (args.length === 0) {\n      return [];\n    }\n    if (typeof args[0] === \"string\") {\n      if (args.length === 1) {\n        return [{ processID: args[0] }];\n      }\n      const requestParams = args[1] as { id?: string };\n      if (requestParams.id) {\n        return [\n          { processID: args[0], session_id: requestParams.id },\n          ...args.slice(1),\n        ];\n      }\n      return [{ processID: args[0] }, ...args.slice(1)];\n    }\n    return args;\n  }\n\n  private patch(moduleExports: typeof KernelSDK): any {\n    diag.debug(\"Patching @onkernel/sdk\");\n    this.manuallyInstrument(moduleExports);\n    return moduleExports;\n  }\n\n  private unpatch(moduleExports: typeof KernelSDK): void {\n    diag.debug(\"Unpatching @onkernel/sdk\");\n\n    // Unwrap resource classes\n    for (const wrappedMethod of WRAPPED_BROWSER_METHODS) {\n      this._unwrap(moduleExports.Kernel.Browsers.prototype, wrappedMethod);\n    }\n    for (const wrappedMethod of WRAPPED_COMPUTER_METHODS) {\n      this._unwrap(\n        moduleExports.Kernel.Browsers.Computer.prototype,\n        wrappedMethod,\n      );\n    }\n    for (const wrappedMethod of WRAPPED_PROCESS_METHODS) {\n      this._unwrap(\n        moduleExports.Kernel.Browsers.Process.prototype,\n        wrappedMethod,\n      );\n    }\n\n    // Unwrap Kernel.app\n    this._unwrap(moduleExports.Kernel.prototype, \"app\");\n  }\n}\n","import { createContextKey } from \"@opentelemetry/api\";\nimport { AsyncLocalStorage } from \"async_hooks\";\n\n// Laminar context key used to tell the OpenAI Responses API instrumentation\n// (once we add one to the TS SDK) that the current call is already being\n// tracked by the OpenAI Agents trace processor, so it should skip creating\n// a duplicate span for the same underlying HTTP request.\n//\n// We keep the raw key string alongside the symbol because\n// @opentelemetry/api's createContextKey returns an opaque symbol and some\n// downstream code (or future OpenAI Responses instrumentation) may want to\n// reference the human-readable name.\nexport const DISABLE_OPENAI_RESPONSES_INSTRUMENTATION_CONTEXT_KEY_RAW =\n  \"LMNR_DISABLE_OPENAI_RESPONSES_INSTRUMENTATION\";\nexport const DISABLE_OPENAI_RESPONSES_INSTRUMENTATION_CONTEXT_KEY =\n  createContextKey(DISABLE_OPENAI_RESPONSES_INSTRUMENTATION_CONTEXT_KEY_RAW);\n\n// Task-local system instructions for the currently-executing model call.\n// Set by the wrapped getResponse / getStreamedResponse methods in index.ts\n// and read by the response/generation span_data handlers so the system\n// prompt can be prepended to gen_ai.input.messages.\nconst systemInstructionsStorage = new AsyncLocalStorage<string | undefined>();\n\nexport const getCurrentSystemInstructions = (): string | undefined =>\n  systemInstructionsStorage.getStore();\n\nexport const runWithSystemInstructions = <T>(\n  value: string | undefined,\n  fn: () => T,\n): T => systemInstructionsStorage.run(value, fn);\n\n// Wrap an async iterable so that the system instructions ALS value is set for\n// each iteration step. We can't simply call `systemInstructionsStorage.run()`\n// once around generator creation, because the ALS context is restored as soon\n// as `.run()` returns — subsequent `next()` calls would see the old value.\nexport const wrapStreamWithSystemInstructions = <T>(\n  value: string | undefined,\n  source: AsyncIterable<T>,\n): AsyncIterable<T> => ({\n  [Symbol.asyncIterator]() {\n    let iterator: AsyncIterator<T> | undefined;\n    const getIterator = (): AsyncIterator<T> => {\n      if (iterator === undefined) {\n        iterator = systemInstructionsStorage.run(value, () =>\n          source[Symbol.asyncIterator](),\n        );\n      }\n      return iterator;\n    };\n    return {\n      next: (..._args: [] | [undefined]) =>\n        systemInstructionsStorage.run(value, () => getIterator().next()),\n      return: (returnValue?: any) => {\n        const it = getIterator();\n        return it.return\n          ? systemInstructionsStorage.run(value, () => it.return!(returnValue))\n          : Promise.resolve({ done: true, value: returnValue });\n      },\n      throw: (err?: any) => {\n        const it = getIterator();\n        return it.throw\n          ? systemInstructionsStorage.run(value, () => it.throw!(err))\n          : Promise.reject(err);\n      },\n    };\n  },\n});\n\nexport const spanKind = (spanData: any): string => {\n  if (spanData == null) {\n    return \"\";\n  }\n  return typeof spanData.type === \"string\" ? (spanData.type as string) : \"\";\n};\n\nexport const spanName = (span: any, spanData: any): string => {\n  const name = span?.name;\n  if (typeof name === \"string\" && name) {\n    return name;\n  }\n  const kind = spanKind(spanData);\n  if (kind) {\n    if (\n      kind === \"agent\" ||\n      kind === \"custom\" ||\n      kind === \"function\" ||\n      kind === \"tool\"\n    ) {\n      return nameFromSpanData(spanData) || `agents.${kind}`;\n    }\n    return `agents.${kind}`;\n  }\n  return \"agents.span\";\n};\n\nexport type LaminarAgentsSpanType = \"LLM\" | \"TOOL\" | \"DEFAULT\";\n\nexport const mapSpanType = (spanData: any): LaminarAgentsSpanType => {\n  const kind = spanKind(spanData);\n  if (\n    kind === \"generation\" ||\n    kind === \"response\" ||\n    kind === \"transcription\" ||\n    kind === \"speech\" ||\n    kind === \"speech_group\"\n  ) {\n    return \"LLM\";\n  }\n  if (\n    kind === \"function\" ||\n    kind === \"tool\" ||\n    kind === \"mcp_list_tools\" ||\n    kind === \"mcp_tools\" ||\n    kind === \"handoff\"\n  ) {\n    return \"TOOL\";\n  }\n  return \"DEFAULT\";\n};\n\nexport const nameFromSpanData = (agent: any): string => {\n  if (agent == null) {\n    return \"\";\n  }\n  if (typeof agent === \"string\") {\n    return agent;\n  }\n  if (typeof agent === \"object\") {\n    if (typeof agent.name === \"string\") {\n      return agent.name as string;\n    }\n  }\n  return \"\";\n};\n\nexport const getFirstNotNull = (d: any, ...keys: string[]): any => {\n  if (d == null) {\n    return undefined;\n  }\n  for (const key of keys) {\n    const v = d[key];\n    if (v !== undefined && v !== null) {\n      return v;\n    }\n  }\n  return undefined;\n};\n\nexport const modelAsDict = (obj: any): Record<string, any> | undefined => {\n  if (obj == null) {\n    return undefined;\n  }\n  if (typeof obj !== \"object\") {\n    return undefined;\n  }\n  if (Array.isArray(obj)) {\n    return undefined;\n  }\n  // Plain object\n  return obj as Record<string, any>;\n};\n\nexport const normalizeMessages = (\n  data: any,\n  role: string = \"user\",\n): Record<string, any>[] => {\n  if (data == null) {\n    return [];\n  }\n\n  if (typeof data === \"string\") {\n    return [{ role, content: data }];\n  }\n\n  if (Array.isArray(data)) {\n    const messages: Record<string, any>[] = [];\n    for (const item of data) {\n      if (item != null && typeof item === \"object\" && !Array.isArray(item)) {\n        messages.push(item as Record<string, any>);\n      } else {\n        messages.push({ role, content: String(item) });\n      }\n    }\n    return messages;\n  }\n\n  if (typeof data === \"object\") {\n    return [data as Record<string, any>];\n  }\n\n  return [{ role, content: String(data) }];\n};\n","import type { Span } from \"@opentelemetry/api\";\n\nimport { initializeLogger } from \"../../../utils\";\nimport {\n  LaminarAttributes,\n  SPAN_INPUT,\n  SPAN_OUTPUT,\n} from \"../../tracing/attributes\";\nimport { getFirstNotNull, modelAsDict, normalizeMessages } from \"./helpers\";\n\nconst logger = initializeLogger();\n\n// ---------------------------------------------------------------------------\n// gen_ai.input.messages / gen_ai.output.messages helpers\n// ---------------------------------------------------------------------------\n\nexport const setLmnrSpanIo = (\n  lmnrSpan: Span,\n  inputData: any,\n  outputData: any,\n): void => {\n  if (inputData !== undefined && inputData !== null) {\n    lmnrSpan.setAttribute(SPAN_INPUT, JSON.stringify(inputData));\n  }\n  if (outputData !== undefined && outputData !== null) {\n    lmnrSpan.setAttribute(SPAN_OUTPUT, JSON.stringify(outputData));\n  }\n};\n\nexport const setGenAiInputMessages = (\n  lmnrSpan: Span,\n  inputData: any,\n  systemInstructions?: string | null,\n): void => {\n  const hasInput = inputData !== undefined && inputData !== null;\n  if (!hasInput && !systemInstructions) {\n    return;\n  }\n  const messages: Record<string, any>[] = hasInput\n    ? normalizeMessages(inputData)\n    : [];\n  if (systemInstructions) {\n    messages.unshift({\n      role: \"system\",\n      content: [{ type: \"input_text\", text: systemInstructions }],\n    });\n  }\n  if (messages.length > 0) {\n    lmnrSpan.setAttribute(\"gen_ai.input.messages\", JSON.stringify(messages));\n  }\n};\n\nexport const setGenAiOutputMessages = (\n  lmnrSpan: Span,\n  outputData: any,\n): void => {\n  if (outputData === undefined || outputData === null) {\n    return;\n  }\n  const messages = normalizeMessages(outputData, \"assistant\");\n  if (messages.length > 0) {\n    lmnrSpan.setAttribute(\"gen_ai.output.messages\", JSON.stringify(messages));\n  }\n};\n\nexport const setGenAiOutputMessagesFromResponse = (\n  lmnrSpan: Span,\n  response: any,\n): void => {\n  if (response == null) {\n    return;\n  }\n\n  let outputItems = response.output;\n  if (!outputItems) {\n    return;\n  }\n\n  const id = response.id;\n\n  if (!Array.isArray(outputItems)) {\n    logger.debug(\n      \"Laminar OpenAI agents instrumentation, failed to parse output items. Expected array\",\n    );\n    outputItems = [];\n  }\n\n  const result = {\n    id,\n    object: \"response\",\n    output: outputItems,\n  };\n\n  lmnrSpan.setAttribute(\"gen_ai.output.messages\", JSON.stringify(result));\n};\n\n// ---------------------------------------------------------------------------\n// Tool definitions\n// ---------------------------------------------------------------------------\n\nexport const setToolDefinitionsFromResponse = (\n  lmnrSpan: Span,\n  response: any,\n): void => {\n  const tools = response?.tools;\n  if (!tools || !Array.isArray(tools)) {\n    return;\n  }\n\n  const toolDefs: Record<string, any>[] = [];\n  for (const tool of tools) {\n    const toolDict = modelAsDict(tool);\n    if (!toolDict) {\n      continue;\n    }\n    const toolType = toolDict.type;\n    if (toolType === \"function\") {\n      const funcDef: Record<string, any> = { type: \"function\" };\n      const functionInfo = toolDict.function ?? toolDict;\n      const fn: Record<string, any> = {\n        name: functionInfo.name ?? \"\",\n      };\n      const desc = functionInfo.description;\n      if (desc) {\n        fn.description = desc;\n      }\n      const params = functionInfo.parameters;\n      if (params) {\n        fn.parameters = params;\n      }\n      const strict = functionInfo.strict;\n      if (strict !== undefined && strict !== null) {\n        fn.strict = strict;\n      }\n      funcDef.function = fn;\n      toolDefs.push(funcDef);\n    } else {\n      toolDefs.push(toolDict);\n    }\n  }\n\n  if (toolDefs.length > 0) {\n    lmnrSpan.setAttribute(\"gen_ai.tool.definitions\", JSON.stringify(toolDefs));\n  }\n};\n\n// ---------------------------------------------------------------------------\n// LLM attributes (model, usage, response_id)\n// ---------------------------------------------------------------------------\n\nexport const applyLlmAttributes = (\n  lmnrSpan: Span,\n  data: Record<string, any>,\n): void => {\n  if (!data) {\n    return;\n  }\n\n  const model = data.model;\n  if (model) {\n    lmnrSpan.setAttribute(LaminarAttributes.REQUEST_MODEL, model);\n    lmnrSpan.setAttribute(LaminarAttributes.RESPONSE_MODEL, model);\n    lmnrSpan.setAttribute(LaminarAttributes.PROVIDER, \"openai\");\n  }\n\n  const usage = data.usage;\n  if (usage != null) {\n    applyUsage(lmnrSpan, usage);\n  }\n\n  let responseId = data.response_id;\n  if (responseId == null) {\n    responseId = data.id;\n  }\n  if (responseId != null) {\n    lmnrSpan.setAttribute(\"gen_ai.response.id\", responseId);\n  }\n};\n\nconst applyUsage = (lmnrSpan: Span, usage: any): void => {\n  if (usage == null) {\n    return;\n  }\n\n  const inputTokens = getFirstNotNull(\n    usage,\n    \"input_tokens\",\n    \"prompt_tokens\",\n    \"input\",\n  );\n  const outputTokens = getFirstNotNull(\n    usage,\n    \"output_tokens\",\n    \"completion_tokens\",\n    \"output\",\n  );\n  const totalTokens = getFirstNotNull(usage, \"total_tokens\", \"total\");\n  const inputTokensDetails = getFirstNotNull(\n    usage,\n    \"input_tokens_details\",\n    \"prompt_tokens_details\",\n  );\n  const outputTokensDetails = getFirstNotNull(\n    usage,\n    \"output_tokens_details\",\n    \"completion_tokens_details\",\n  );\n\n  let cachedInputTokens: number | undefined;\n  let reasoningOutputTokens: number | undefined;\n\n  if (\n    inputTokensDetails?.cached_tokens !== undefined &&\n    inputTokensDetails?.cached_tokens !== null\n  ) {\n    cachedInputTokens = Number(inputTokensDetails.cached_tokens);\n  }\n  if (\n    outputTokensDetails?.reasoning_tokens !== undefined &&\n    outputTokensDetails?.reasoning_tokens !== null\n  ) {\n    reasoningOutputTokens = Number(outputTokensDetails.reasoning_tokens);\n  }\n  if (inputTokens !== undefined && inputTokens !== null) {\n    lmnrSpan.setAttribute(\n      LaminarAttributes.INPUT_TOKEN_COUNT,\n      Number(inputTokens),\n    );\n  }\n  if (cachedInputTokens !== undefined) {\n    lmnrSpan.setAttribute(\n      \"gen_ai.usage.cache_read_input_tokens\",\n      cachedInputTokens,\n    );\n  }\n  if (outputTokens !== undefined && outputTokens !== null) {\n    lmnrSpan.setAttribute(\n      LaminarAttributes.OUTPUT_TOKEN_COUNT,\n      Number(outputTokens),\n    );\n  }\n  if (reasoningOutputTokens !== undefined) {\n    lmnrSpan.setAttribute(\n      \"gen_ai.usage.reasoning_output_tokens\",\n      reasoningOutputTokens,\n    );\n  }\n  if (totalTokens !== undefined && totalTokens !== null) {\n    lmnrSpan.setAttribute(\n      LaminarAttributes.TOTAL_TOKEN_COUNT,\n      Number(totalTokens),\n    );\n  } else if (\n    inputTokens !== undefined &&\n    inputTokens !== null &&\n    outputTokens !== undefined &&\n    outputTokens !== null\n  ) {\n    lmnrSpan.setAttribute(\n      LaminarAttributes.TOTAL_TOKEN_COUNT,\n      Number(inputTokens) + Number(outputTokens),\n    );\n  }\n};\n\nexport const responseToLlmData = (response: any): Record<string, any> => {\n  if (response == null) {\n    return {};\n  }\n  return {\n    model: response.model,\n    usage: response.usage,\n    response_id: response.id,\n  };\n};\n","import { type Span, SpanStatusCode } from \"@opentelemetry/api\";\n\nimport { LaminarAttributes } from \"../../tracing/attributes\";\nimport {\n  getCurrentSystemInstructions,\n  nameFromSpanData,\n  spanKind,\n} from \"./helpers\";\nimport {\n  applyLlmAttributes,\n  responseToLlmData,\n  setGenAiInputMessages,\n  setGenAiOutputMessages,\n  setGenAiOutputMessagesFromResponse,\n  setLmnrSpanIo,\n  setToolDefinitionsFromResponse,\n} from \"./messages\";\n\n// ---------------------------------------------------------------------------\n// Error handling\n// ---------------------------------------------------------------------------\n\nexport const applySpanError = (lmnrSpan: Span, span: any): void => {\n  const error = span?.error;\n  if (!error) {\n    return;\n  }\n  try {\n    const message = error.message ?? String(error);\n    lmnrSpan.setStatus({ code: SpanStatusCode.ERROR, message });\n  } catch {\n    // ignore\n  }\n};\n\n// ---------------------------------------------------------------------------\n// Span data extraction\n// ---------------------------------------------------------------------------\n\nexport const applySpanData = (lmnrSpan: Span, spanData: any): void => {\n  if (spanData == null) {\n    return;\n  }\n\n  const kind = spanKind(spanData);\n\n  if (kind === \"agent\") {\n    applyAgentSpanData(lmnrSpan, spanData);\n  } else if (kind === \"function\" || kind === \"tool\") {\n    applyFunctionSpanData(lmnrSpan, spanData);\n  } else if (kind === \"generation\") {\n    applyGenerationSpanData(lmnrSpan, spanData);\n  } else if (kind === \"response\") {\n    applyResponseSpanData(lmnrSpan, spanData);\n  } else if (kind === \"handoff\") {\n    applyHandoffSpanData(lmnrSpan, spanData);\n  } else if (kind === \"guardrail\") {\n    applyGuardrailSpanData(lmnrSpan, spanData);\n  } else if (kind === \"custom\") {\n    applyCustomSpanData(lmnrSpan, spanData);\n  } else if (kind === \"mcp_list_tools\" || kind === \"mcp_tools\") {\n    applyMcpSpanData(lmnrSpan, spanData);\n  } else if (kind === \"speech\") {\n    applySpeechSpanData(lmnrSpan, spanData);\n  } else if (kind === \"transcription\") {\n    applyTranscriptionSpanData(lmnrSpan, spanData);\n  } else if (kind === \"speech_group\") {\n    applySpeechGroupSpanData(lmnrSpan, spanData);\n  } else {\n    // Fallback: set generic I/O\n    setLmnrSpanIo(lmnrSpan, spanData?.input, spanData?.output);\n  }\n};\n\nconst applyAgentSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const res: Record<string, any> = {};\n  const name = spanData?.name;\n  if (name) {\n    res.name = name;\n  }\n  const handoffs = spanData?.handoffs;\n  if (handoffs) {\n    res.handoffs = handoffs;\n  }\n  const tools = spanData?.tools;\n  if (tools) {\n    res.tools = tools;\n  }\n  const outputType = spanData?.output_type;\n  if (outputType) {\n    res.output_type = outputType;\n  }\n  setLmnrSpanIo(lmnrSpan, res, null);\n};\n\nconst applyFunctionSpanData = (lmnrSpan: Span, spanData: any): void => {\n  setLmnrSpanIo(lmnrSpan, spanData?.input, spanData?.output);\n};\n\nconst applyGenerationSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const inputData = spanData?.input;\n  setGenAiInputMessages(lmnrSpan, inputData, getCurrentSystemInstructions());\n\n  const outputData = spanData?.output;\n  setGenAiOutputMessages(lmnrSpan, outputData);\n\n  const llmData: Record<string, any> = {\n    model: spanData?.model,\n    usage: spanData?.usage,\n    response_id: spanData?.response_id ?? spanData?.id,\n  };\n  applyLlmAttributes(lmnrSpan, llmData);\n};\n\nconst applyResponseSpanData = (lmnrSpan: Span, spanData: any): void => {\n  // TS SDK stores the raw response under `_response` and raw input under `_input`\n  // for non-OpenAI exporters (the OpenAI exporter strips them via\n  // removePrivateFields). See\n  // @openai/agents-core/dist/tracing/spans.d.ts::ResponseSpanData.\n  const response = spanData?._response ?? spanData?.response;\n  const responseInput = spanData?._input ?? spanData?.input;\n\n  setGenAiInputMessages(\n    lmnrSpan,\n    responseInput,\n    getCurrentSystemInstructions(),\n  );\n\n  if (response != null) {\n    setGenAiOutputMessagesFromResponse(lmnrSpan, response);\n    setToolDefinitionsFromResponse(lmnrSpan, response);\n    applyLlmAttributes(lmnrSpan, responseToLlmData(response));\n  } else if (spanData?.response_id) {\n    // If we only have the response_id (OpenAI path strips the response body),\n    // still surface it so callers can correlate.\n    lmnrSpan.setAttribute(\"gen_ai.response.id\", spanData.response_id);\n  }\n};\n\nconst applyHandoffSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const fromAgent = spanData?.from_agent;\n  const toAgent = spanData?.to_agent;\n  if (fromAgent) {\n    lmnrSpan.setAttribute(\n      \"openai.agents.handoff.from\",\n      nameFromSpanData(fromAgent),\n    );\n  }\n  if (toAgent) {\n    lmnrSpan.setAttribute(\n      \"openai.agents.handoff.to\",\n      nameFromSpanData(toAgent),\n    );\n  }\n};\n\nconst applyGuardrailSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const name = spanData?.name;\n  if (name) {\n    lmnrSpan.setAttribute(\"openai.agents.guardrail.name\", name);\n  }\n  const triggered = spanData?.triggered;\n  if (triggered !== undefined && triggered !== null) {\n    lmnrSpan.setAttribute(\n      \"openai.agents.guardrail.triggered\",\n      Boolean(triggered),\n    );\n  }\n};\n\nconst applyCustomSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const name = spanData?.name;\n  if (name) {\n    lmnrSpan.setAttribute(\"openai.agents.custom.name\", name);\n  }\n  const customData = spanData?.data;\n  if (customData !== undefined && customData !== null) {\n    lmnrSpan.setAttribute(\n      \"openai.agents.custom.data\",\n      JSON.stringify(customData),\n    );\n  }\n};\n\nconst applyMcpSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const server = spanData?.server;\n  if (server) {\n    lmnrSpan.setAttribute(\"openai.agents.mcp.server\", server);\n  }\n  const result = spanData?.result;\n  if (result !== undefined && result !== null) {\n    lmnrSpan.setAttribute(\"openai.agents.mcp.result\", JSON.stringify(result));\n  }\n};\n\nconst applySpeechSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const model = spanData?.model;\n  if (model) {\n    lmnrSpan.setAttribute(LaminarAttributes.REQUEST_MODEL, model);\n    lmnrSpan.setAttribute(LaminarAttributes.RESPONSE_MODEL, model);\n    lmnrSpan.setAttribute(LaminarAttributes.PROVIDER, \"openai\");\n  }\n\n  const inputText = spanData?.input;\n  if (inputText) {\n    setGenAiInputMessages(lmnrSpan, inputText);\n  }\n\n  const outputData = spanData?.output;\n  if (outputData) {\n    if (typeof outputData === \"object\" && !Array.isArray(outputData)) {\n      // Speech output is {data: ..., format: ...}\n      setGenAiOutputMessages(lmnrSpan, outputData.data);\n    } else {\n      setGenAiOutputMessages(lmnrSpan, outputData);\n    }\n  }\n};\n\nconst applyTranscriptionSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const model = spanData?.model;\n  if (model) {\n    lmnrSpan.setAttribute(LaminarAttributes.REQUEST_MODEL, model);\n    lmnrSpan.setAttribute(LaminarAttributes.RESPONSE_MODEL, model);\n    lmnrSpan.setAttribute(LaminarAttributes.PROVIDER, \"openai\");\n  }\n\n  const inputData = spanData?.input;\n  if (inputData) {\n    if (typeof inputData === \"object\" && !Array.isArray(inputData)) {\n      setGenAiInputMessages(lmnrSpan, inputData.data);\n    } else {\n      setGenAiInputMessages(lmnrSpan, inputData);\n    }\n  }\n\n  const outputText = spanData?.output;\n  if (outputText) {\n    setGenAiOutputMessages(lmnrSpan, outputText);\n  }\n};\n\nconst applySpeechGroupSpanData = (lmnrSpan: Span, spanData: any): void => {\n  const inputText = spanData?.input;\n  if (inputText) {\n    setGenAiInputMessages(lmnrSpan, inputText);\n  }\n\n  const outputText = spanData?.output;\n  if (outputText) {\n    setGenAiOutputMessages(lmnrSpan, outputText);\n  }\n};\n","import type {\n  Span as AgentsSpan,\n  SpanData,\n  Trace,\n  TracingProcessor,\n} from \"@openai/agents\";\nimport {\n  type Context,\n  type Span as OtelSpan,\n  ROOT_CONTEXT,\n  trace,\n} from \"@opentelemetry/api\";\n\nimport { Laminar } from \"../../../laminar\";\nimport { initializeLogger } from \"../../../utils\";\nimport { LaminarContextManager } from \"../../tracing/context\";\nimport { LaminarSpan } from \"../../tracing/span\";\nimport {\n  DISABLE_OPENAI_RESPONSES_INSTRUMENTATION_CONTEXT_KEY,\n  mapSpanType,\n  nameFromSpanData,\n  spanKind,\n  spanName,\n} from \"./helpers\";\nimport { applySpanData, applySpanError } from \"./span-data\";\n\nconst logger = initializeLogger();\n\ninterface SpanEntry {\n  lmnrSpan: OtelSpan;\n  agentsSpan: AgentsSpan<SpanData>;\n  // Context reference that was pushed onto the Laminar ALS stack when this\n  // span started, so nested Laminar instrumentations (google-genai, etc.)\n  // running inside the agents callback pick this span up as their parent.\n  // `onSpanEnd` removes this exact reference via\n  // `LaminarContextManager.removeContext` — using the reference (not a LIFO\n  // pop) keeps the stack consistent when agent spans end out of order with\n  // respect to other activated spans sharing the same async frame.\n  activationContext?: Context;\n}\n\ninterface TraceState {\n  rootSpan: OtelSpan | undefined;\n  spans: Map<string, SpanEntry>;\n  // When true, the trace has been marked as ended (via onTraceEnd or shutdown)\n  // and we should not write any more spans into it.\n  ended: boolean;\n  // Maps destination agent name -> handoff parent Laminar span context so the\n  // subsequent agent span becomes a sibling of the handoff span (both children\n  // of the handoff's parent).\n  pendingHandoffCtxs: Map<string, string>;\n}\n\nexport class LaminarAgentsTraceProcessor implements TracingProcessor {\n  private traces: Map<string, TraceState> = new Map();\n  private disabled: boolean = false;\n\n  start(): void {\n    // Nothing to do - we don't run an export loop.\n  }\n\n  async onTraceStart(agentsTrace: Trace): Promise<void> {\n    if (this.disabled) {\n      return;\n    }\n    const traceId = agentsTrace.traceId;\n    if (!traceId) {\n      return;\n    }\n    try {\n      const state = this.getOrCreateTrace(agentsTrace);\n\n      // Update root span name to the actual trace name (it defaults to\n      // \"agents.trace\" at creation time; see getOrCreateTrace).\n      const traceName = agentsTrace.name;\n      if (traceName && state.rootSpan !== undefined) {\n        try {\n          state.rootSpan.updateName(traceName);\n        } catch {\n          // ignore\n        }\n      }\n      this.applyTraceMetadata(state.rootSpan, agentsTrace);\n    } catch (e) {\n      logger.debug(`Error in onTraceStart: ${String(e)}`);\n    }\n  }\n\n  async onTraceEnd(agentsTrace: Trace): Promise<void> {\n    if (this.disabled) {\n      return;\n    }\n    const traceId = agentsTrace.traceId;\n    if (!traceId) {\n      return;\n    }\n    const state = this.traces.get(traceId);\n    if (!state || state.ended) {\n      return;\n    }\n    state.ended = true;\n    this.endTraceState(state);\n    this.traces.delete(traceId);\n  }\n\n  async onSpanStart(span: AgentsSpan<SpanData>): Promise<void> {\n    if (this.disabled) {\n      return;\n    }\n    const traceId = span.traceId;\n    if (!traceId) {\n      return;\n    }\n    let lmnrSpan: OtelSpan | undefined;\n    try {\n      const state = this.getOrCreateTrace(span);\n\n      let parentSpanContext: string | undefined;\n\n      const spanData = span.spanData;\n\n      // If this is an agent span, check if a handoff targeting this agent is\n      // pending. If so, make this span a child of the handoff's parent so the\n      // subagent is nested correctly.\n      if (spanKind(spanData) === \"agent\") {\n        const thisAgentName = nameFromSpanData(\n          (spanData as any)?.name ?? spanData,\n        );\n        const handoffCtx = state.pendingHandoffCtxs.get(thisAgentName);\n        if (handoffCtx !== undefined) {\n          state.pendingHandoffCtxs.delete(thisAgentName);\n          parentSpanContext = handoffCtx;\n        }\n      }\n\n      // Resolve the parent Laminar span explicitly via the agents SDK's\n      // parentId (or falling back to the trace's root span). Relying on\n      // LaminarContextManager.getContext() would consult a process-global\n      // stack, which is unsafe when multiple agent runs execute concurrently.\n      if (parentSpanContext === undefined) {\n        const parentId = span.parentId;\n        const parentEntry =\n          parentId != null ? state.spans.get(parentId) : undefined;\n        const parentLmnrSpan =\n          parentEntry !== undefined ? parentEntry.lmnrSpan : state.rootSpan;\n        if (parentLmnrSpan !== undefined) {\n          try {\n            const ctx = (\n              parentLmnrSpan as LaminarSpan\n            ).getLaminarSpanContext?.();\n            if (ctx) {\n              parentSpanContext = JSON.stringify(ctx);\n            }\n          } catch {\n            // ignore\n          }\n        }\n      }\n\n      const spanType = mapSpanType(spanData);\n      const name = spanName(span, spanData);\n\n      // Mark the context so any future OpenAI Responses API instrumentation\n      // (on the TS side) knows to skip — the agents run already records a\n      // matching span for this underlying HTTP call. Start from ROOT_CONTEXT\n      // (not getContext()) so the per-trace parent we resolved above — rather\n      // than whatever happens to be globally active on the shared stack —\n      // determines hierarchy. This keeps concurrent traces isolated.\n      const ctx = ROOT_CONTEXT.setValue(\n        DISABLE_OPENAI_RESPONSES_INSTRUMENTATION_CONTEXT_KEY,\n        true,\n      );\n\n      // Use startSpan (not startActiveSpan) so we don't push onto the ALS\n      // stack via Laminar's built-in activation path — that path uses\n      // `popContext` (blunt LIFO) on `end()`, which corrupts the stack when\n      // agent spans end out of order with respect to other activated spans.\n      lmnrSpan = Laminar.startSpan({\n        name,\n        spanType,\n        parentSpanContext,\n        context: ctx,\n      });\n\n      const key = span.spanId;\n      if (!key) {\n        logger.debug(\"Span missing spanId, cannot track\");\n        try {\n          lmnrSpan.end();\n        } catch {\n          // ignore\n        }\n        return;\n      }\n\n      // Register the new span on the Laminar ALS stack so nested Laminar\n      // instrumentation (google-genai, etc.) that runs inside the agent /\n      // tool callback picks it up as parent via `getContext()`. We push the\n      // context reference here and remove that exact reference in onSpanEnd\n      // — never relying on LIFO order — so concurrent or out-of-order agent\n      // span ends cannot corrupt the stack for unrelated activations sharing\n      // the same async frame.\n      let activationContext: Context | undefined;\n      try {\n        activationContext = trace.setSpan(ctx, lmnrSpan);\n        LaminarContextManager.pushContext(activationContext);\n      } catch {\n        activationContext = undefined;\n      }\n      state.spans.set(key, { lmnrSpan, agentsSpan: span, activationContext });\n    } catch (e) {\n      logger.debug(`Error in onSpanStart: ${String(e)}`);\n      if (lmnrSpan !== undefined) {\n        try {\n          lmnrSpan.end();\n        } catch {\n          // ignore\n        }\n      }\n    }\n  }\n\n  async onSpanEnd(span: AgentsSpan<SpanData>): Promise<void> {\n    if (this.disabled) {\n      return;\n    }\n    const traceId = span.traceId;\n    if (!traceId) {\n      return;\n    }\n\n    const key = span.spanId;\n    if (!key) {\n      return;\n    }\n\n    const state = this.traces.get(traceId);\n    const entry = state?.spans.get(key);\n    if (!entry || !state) {\n      return;\n    }\n    state.spans.delete(key);\n\n    const spanData = span.spanData;\n    try {\n      try {\n        applySpanData(entry.lmnrSpan, spanData);\n        applySpanError(entry.lmnrSpan, span);\n      } catch {\n        // ignore\n      }\n\n      // When a handoff span ends, save the *parent* span's Laminar context keyed\n      // by the destination agent name. The next agent span's start will consume\n      // this so it becomes a sibling of the handoff span.\n      if (spanKind(spanData) === \"handoff\") {\n        try {\n          const toAgent = nameFromSpanData((spanData as any)?.to_agent);\n          if (toAgent) {\n            const parentId = span.parentId;\n            const parentEntry =\n              parentId != null ? state.spans.get(parentId) : undefined;\n            const parentLmnrSpan =\n              parentEntry !== undefined ? parentEntry.lmnrSpan : state.rootSpan;\n            if (parentLmnrSpan !== undefined) {\n              const handoffCtx = (\n                parentLmnrSpan as LaminarSpan\n              ).getLaminarSpanContext?.();\n              if (handoffCtx) {\n                state.pendingHandoffCtxs.set(\n                  toAgent,\n                  JSON.stringify(handoffCtx),\n                );\n              }\n            }\n          }\n        } catch {\n          // ignore\n        }\n      }\n\n      if (entry.activationContext !== undefined) {\n        try {\n          LaminarContextManager.removeContext(entry.activationContext);\n        } catch {\n          // ignore\n        }\n      }\n\n      try {\n        entry.lmnrSpan.end();\n      } catch {\n        // ignore\n      }\n    } catch {\n      // ignore\n    }\n  }\n\n  async shutdown(_timeout?: number): Promise<void> {\n    this.disabled = true;\n    const states = Array.from(this.traces.values()).filter((s) => !s.ended);\n    for (const s of states) {\n      s.ended = true;\n    }\n    this.traces.clear();\n    for (const state of states) {\n      this.endTraceState(state);\n    }\n    try {\n      await Laminar.flush();\n    } catch {\n      // ignore\n    }\n  }\n\n  async forceFlush(): Promise<void> {\n    try {\n      await Laminar.flush();\n    } catch {\n      // ignore\n    }\n  }\n\n  private endTraceState(state: TraceState): void {\n    // End all child spans (LIFO) then the root span.\n    const remaining = Array.from(state.spans.values());\n    state.spans.clear();\n    for (let i = remaining.length - 1; i >= 0; i--) {\n      const entry = remaining[i];\n      try {\n        const spanData = entry.agentsSpan?.spanData;\n        applySpanData(entry.lmnrSpan, spanData);\n        applySpanError(entry.lmnrSpan, entry.agentsSpan);\n      } catch {\n        // ignore\n      }\n      if (entry.activationContext !== undefined) {\n        try {\n          LaminarContextManager.removeContext(entry.activationContext);\n        } catch {\n          // ignore\n        }\n      }\n      try {\n        entry.lmnrSpan.end();\n      } catch {\n        // ignore\n      }\n    }\n    try {\n      state.rootSpan?.end();\n    } catch {\n      // ignore\n    }\n  }\n\n  private getOrCreateTrace(\n    traceOrSpan: Trace | AgentsSpan<SpanData>,\n  ): TraceState {\n    let traceId: string | undefined = (traceOrSpan as any).traceId;\n    if (!traceId) {\n      traceId = \"unknown\";\n    }\n    const existing = this.traces.get(traceId);\n    if (existing) {\n      return existing;\n    }\n\n    // Generic name; onTraceStart will update it to the actual trace name.\n    // Start from ROOT_CONTEXT so the root span of a concurrently-running\n    // agent trace cannot become a child of another trace's currently-active\n    // span on the shared async context. Use startSpan (not startActiveSpan)\n    // so the processor never touches the ALS context stack — see the child\n    // span call-site for the rationale.\n    const rootSpan = Laminar.startSpan({\n      name: \"agents.trace\",\n      context: ROOT_CONTEXT,\n    });\n    const state: TraceState = {\n      rootSpan,\n      spans: new Map(),\n      ended: false,\n      pendingHandoffCtxs: new Map(),\n    };\n    this.traces.set(traceId, state);\n    return state;\n  }\n\n  private applyTraceMetadata(\n    rootSpan: OtelSpan | undefined,\n    agentsTrace: Trace,\n  ): void {\n    if (rootSpan === undefined) {\n      return;\n    }\n    const metadata: Record<string, any> = {};\n    const traceMetadata = agentsTrace.metadata;\n    if (traceMetadata !== undefined && traceMetadata !== null) {\n      Object.assign(metadata, traceMetadata);\n    }\n    const groupId = agentsTrace.groupId;\n    if (groupId) {\n      metadata[\"openai.agents.group_id\"] = groupId;\n    }\n    if (agentsTrace.name) {\n      metadata[\"openai.agents.trace_name\"] = agentsTrace.name;\n    }\n    if (Object.keys(metadata).length > 0) {\n      try {\n        (rootSpan as LaminarSpan).setTraceMetadata?.(metadata);\n      } catch {\n        // ignore\n      }\n    }\n    const sessionId = metadata.session_id;\n    const userId = metadata.user_id;\n    if (sessionId) {\n      try {\n        (rootSpan as LaminarSpan).setTraceSessionId?.(String(sessionId));\n      } catch {\n        // ignore\n      }\n    }\n    if (userId) {\n      try {\n        (rootSpan as LaminarSpan).setTraceUserId?.(String(userId));\n      } catch {\n        // ignore\n      }\n    }\n  }\n}\n","// biome-ignore-all lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\nimport { diag } from \"@opentelemetry/api\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\n\nimport { version as SDK_VERSION } from \"../../../../package.json\";\nimport { initializeLogger } from \"../../../utils\";\nimport {\n  runWithSystemInstructions,\n  wrapStreamWithSystemInstructions,\n} from \"./helpers\";\nimport { LaminarAgentsTraceProcessor } from \"./processor\";\n\nexport {\n  DISABLE_OPENAI_RESPONSES_INSTRUMENTATION_CONTEXT_KEY,\n  DISABLE_OPENAI_RESPONSES_INSTRUMENTATION_CONTEXT_KEY_RAW,\n} from \"./helpers\";\nexport { LaminarAgentsTraceProcessor } from \"./processor\";\n\nconst logger = initializeLogger();\n\ntype ModelRequestLike =\n  | {\n      systemInstructions?: string;\n    }\n  | undefined;\n\nconst wrapGetResponse = (original: Function): Function =>\n  function (this: any, request: ModelRequestLike, ...rest: any[]) {\n    const systemInstructions = request?.systemInstructions;\n    return runWithSystemInstructions(systemInstructions, () =>\n      original.call(this, request, ...rest),\n    );\n  };\n\nconst wrapGetStreamedResponse = (original: Function): Function =>\n  function (this: any, request: ModelRequestLike, ...rest: any[]) {\n    const systemInstructions = request?.systemInstructions;\n    const source = original.call(this, request, ...rest) as AsyncIterable<any>;\n    return wrapStreamWithSystemInstructions(systemInstructions, source);\n  };\n\nconst MODEL_METHODS: readonly [\"getResponse\", \"getStreamedResponse\"] = [\n  \"getResponse\",\n  \"getStreamedResponse\",\n];\n\ntype AgentsOpenAIModule = {\n  OpenAIResponsesModel?: { prototype: any };\n  OpenAIChatCompletionsModel?: { prototype: any };\n};\n\ntype AgentsTracingModule = {\n  addTraceProcessor?: (processor: any) => void;\n};\n\nexport class OpenAIAgentsInstrumentation extends InstrumentationBase {\n  private _processor: LaminarAgentsTraceProcessor | undefined;\n  private _wrappedPrototypes: WeakSet<object> = new WeakSet();\n\n  constructor() {\n    super(\"@lmnr/openai-agents-instrumentation\", SDK_VERSION, {\n      enabled: true,\n    });\n  }\n\n  protected init(): InstrumentationModuleDefinition[] {\n    return [\n      new InstrumentationNodeModuleDefinition(\n        \"@openai/agents\",\n        [\">=0.0.1\"],\n        this.patchAgents.bind(this),\n        this.unpatchAgents.bind(this),\n      ),\n      new InstrumentationNodeModuleDefinition(\n        \"@openai/agents-openai\",\n        [\">=0.0.1\"],\n        this.patchAgentsOpenAI.bind(this),\n        this.unpatchAgentsOpenAI.bind(this),\n      ),\n    ];\n  }\n\n  public manuallyInstrument(agentsModule: any) {\n    if (!agentsModule) {\n      logger.debug(\"@openai/agents module not provided, skipping\");\n      return;\n    }\n    this.registerProcessor(agentsModule);\n    this.patchModel(agentsModule);\n  }\n\n  private registerProcessor(module: AgentsTracingModule) {\n    if (this._processor !== undefined) {\n      return;\n    }\n    const addTraceProcessor = module.addTraceProcessor;\n    if (typeof addTraceProcessor !== \"function\") {\n      logger.debug(\"addTraceProcessor not found in @openai/agents module\");\n      return;\n    }\n    try {\n      const processor = new LaminarAgentsTraceProcessor();\n      addTraceProcessor(processor);\n      this._processor = processor;\n    } catch (e) {\n      logger.debug(`Failed to register Laminar Agents processor: ${String(e)}`);\n    }\n  }\n\n  private patchModel(module: AgentsOpenAIModule) {\n    for (const cls of [\n      module.OpenAIResponsesModel,\n      module.OpenAIChatCompletionsModel,\n    ]) {\n      if (!cls || !cls.prototype) {\n        continue;\n      }\n      // @openai/agents re-exports the model classes from @openai/agents-openai,\n      // so we may see the same prototype twice. Skip if already wrapped to\n      // avoid double-wrapping getResponse/getStreamedResponse.\n      if (this._wrappedPrototypes.has(cls.prototype)) {\n        continue;\n      }\n      for (const method of MODEL_METHODS) {\n        if (typeof cls.prototype[method] !== \"function\") {\n          continue;\n        }\n        const wrapper =\n          method === \"getResponse\" ? wrapGetResponse : wrapGetStreamedResponse;\n        try {\n          this._wrap(cls.prototype, method, wrapper as any);\n        } catch (e) {\n          logger.debug(`Failed to wrap ${method}: ${String(e)}`);\n        }\n      }\n      this._wrappedPrototypes.add(cls.prototype);\n    }\n  }\n\n  private unpatchModel(module: AgentsOpenAIModule) {\n    for (const cls of [\n      module.OpenAIResponsesModel,\n      module.OpenAIChatCompletionsModel,\n    ]) {\n      if (!cls || !cls.prototype) {\n        continue;\n      }\n      if (!this._wrappedPrototypes.has(cls.prototype)) {\n        continue;\n      }\n      for (const method of MODEL_METHODS) {\n        try {\n          this._unwrap(cls.prototype, method);\n        } catch {\n          // ignore\n        }\n      }\n      this._wrappedPrototypes.delete(cls.prototype);\n    }\n  }\n\n  private patchAgents(moduleExports: any): any {\n    diag.debug(\"Patching @openai/agents\");\n    this.registerProcessor(moduleExports as AgentsTracingModule);\n    // @openai/agents re-exports @openai/agents-openai, so model classes are here\n    this.patchModel(moduleExports as AgentsOpenAIModule);\n    return moduleExports;\n  }\n\n  private unpatchAgents(moduleExports: any): void {\n    diag.debug(\"Unpatching @openai/agents\");\n    this.unpatchModel(moduleExports as AgentsOpenAIModule);\n  }\n\n  private patchAgentsOpenAI(moduleExports: any): any {\n    diag.debug(\"Patching @openai/agents-openai\");\n    this.patchModel(moduleExports as AgentsOpenAIModule);\n    return moduleExports;\n  }\n\n  private unpatchAgentsOpenAI(moduleExports: any): void {\n    diag.debug(\"Unpatching @openai/agents-openai\");\n    this.unpatchModel(moduleExports as AgentsOpenAIModule);\n  }\n}\n","// biome-ignore-all lint/complexity/noBannedTypes: instrumentation wraps arbitrary Functions\nimport { diag } from \"@opentelemetry/api\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\n\nimport { version as SDK_VERSION } from \"../../../package.json\";\nimport { Laminar } from \"../../laminar\";\n\nexport class OpencodeInstrumentation extends InstrumentationBase {\n  constructor() {\n    super(\"lmnr-opencode-instrumentation\", SDK_VERSION, { enabled: true });\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    return new InstrumentationNodeModuleDefinition(\n      \"@opencode-ai/sdk\",\n      [\">=1.0.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n  }\n\n  public manuallyInstrument(opencodeModule: any): void {\n    diag.debug(\"Manually instrumenting @opencode-ai/sdk\");\n    const SessionClass = this.resolveSessionClass(opencodeModule);\n    if (SessionClass) {\n      this.patchSessionClass(SessionClass);\n    } else {\n      diag.warn(\n        \"Could not find Session class in opencode manual instrumentation input. \" +\n          \"Pass the OpencodeClient class or the module object.\",\n      );\n    }\n  }\n\n  private resolveSessionClass(input: any): any {\n    // Module-level import: { OpencodeClient, ... }\n    if (input?.OpencodeClient) {\n      return this.getSessionClass(input.OpencodeClient);\n    }\n    // Direct class passed\n    if (typeof input === \"function\" && input.prototype) {\n      return this.getSessionClass(input);\n    }\n    return null;\n  }\n\n  // session is a class field on OpencodeClient (not on the prototype), so we\n  // must instantiate to trigger field initialization and discover Session's constructor.\n  private getSessionClass(ClientClass: any): Function | null {\n    try {\n      const instance = new ClientClass();\n      if (instance.session) {\n        return instance.session.constructor;\n      }\n    } catch {\n      // fall through\n    }\n    return null;\n  }\n\n  private patchSessionClass(SessionClass: Function): void {\n    this._wrap(SessionClass.prototype, \"prompt\", this.patchPromptMethod());\n    this._wrap(SessionClass.prototype, \"promptAsync\", this.patchPromptMethod());\n  }\n\n  private patchPromptMethod(): (original: Function) => Function {\n    return (original: Function) =>\n      function (this: any, ...args: any[]) {\n        const options = args[0];\n        if (options?.body?.parts && Array.isArray(options.body.parts)) {\n          const serializedContext = Laminar.serializeLaminarSpanContext();\n          if (serializedContext) {\n            options.body.parts = [\n              ...options.body.parts,\n              {\n                type: \"text\",\n                metadata: {\n                  lmnrSpanContext: serializedContext,\n                },\n                text: \"\",\n                ignored: true,\n                synthetic: true,\n              },\n            ];\n          } else {\n            diag.debug(\n              \"OpencodeInstrumentation: no active Laminar span context to \" +\n                \"propagate. Opencode-side spans will start a new trace \" +\n                \"instead of being children of the caller's span.\",\n            );\n          }\n        }\n        return original.apply(this, args);\n      };\n  }\n\n  private patch(moduleExports: any): any {\n    diag.debug(\"Patching @opencode-ai/sdk\");\n    const SessionClass = this.resolveSessionClass(moduleExports);\n    if (SessionClass) {\n      this.patchSessionClass(SessionClass);\n    }\n    return moduleExports;\n  }\n\n  private unpatch(moduleExports: any): void {\n    diag.debug(\"Unpatching @opencode-ai/sdk\");\n    const SessionClass = this.resolveSessionClass(moduleExports);\n    if (SessionClass) {\n      this._unwrap(SessionClass.prototype, \"prompt\");\n      this._unwrap(SessionClass.prototype, \"promptAsync\");\n    }\n  }\n}\n","import { SpanStatusCode } from \"@opentelemetry/api\";\n\nimport { LaminarSpan } from \"../../tracing/span\";\n\nexport type ResourceKind = \"chat\" | \"responses\" | \"embeddings\";\n\nconst TERMINAL_RESPONSE_EVENTS = new Set([\n  \"response.completed\",\n  \"response.incomplete\",\n  \"response.failed\",\n]);\n\n// A `responses` result in one of these states carries no usable completion.\nconst ERROR_RESPONSE_STATUSES = new Set([\"failed\", \"incomplete\"]);\n\nconst safeSetAttribute = (\n  span: LaminarSpan,\n  key: string,\n  value: unknown,\n): void => {\n  if (value === null || value === undefined) return;\n  if (typeof value === \"string\" && value.length === 0) return;\n  span.setAttribute(key, value as any);\n};\n\nexport const recordError = (span: LaminarSpan, error: unknown): void => {\n  span.setAttribute(\n    \"error.type\",\n    (error as Error)?.constructor?.name ?? \"Error\",\n  );\n  span.recordException(error as Error);\n  span.setStatus({ code: SpanStatusCode.ERROR });\n};\n\nexport const isAsyncIterable = (value: unknown): value is AsyncIterable<any> =>\n  typeof (value as any)?.[Symbol.asyncIterator] === \"function\";\n\nexport const responsesInputMessages = (request: any): any[] => {\n  const messages: any[] = [];\n  if (request?.instructions) {\n    messages.push({ role: \"system\", content: request.instructions });\n  }\n  if (typeof request?.input === \"string\") {\n    messages.push({ role: \"user\", content: request.input });\n  } else if (Array.isArray(request?.input)) {\n    messages.push(...request.input);\n  }\n  return messages;\n};\n\nconst structuredOutputSchema = (kind: ResourceKind, request: any): unknown => {\n  const format =\n    kind === \"chat\" ? request?.responseFormat : request?.text?.format;\n  if (format?.type !== \"json_schema\") return undefined;\n  return kind === \"chat\" ? format.jsonSchema?.schema : format.schema;\n};\n\n/**\n * `input` is either one document or a batch of them. A flat array of numbers is\n * a single token-id sequence, not a batch — the API returns one embedding for it.\n */\nconst embeddingsInputMessages = (input: unknown): unknown[] => {\n  const isBatch =\n    Array.isArray(input) && !(input.length > 0 && typeof input[0] === \"number\");\n  return (isBatch ? input : [input]).map((content) => ({ content }));\n};\n\nexport const setRequestAttributes = (\n  span: LaminarSpan,\n  kind: ResourceKind,\n  request: any,\n  traceContent: boolean,\n): void => {\n  safeSetAttribute(span, \"gen_ai.request.model\", request?.model);\n  safeSetAttribute(span, \"llm.user\", request?.user);\n\n  if (kind === \"embeddings\") {\n    if (traceContent && request?.input !== undefined) {\n      safeSetAttribute(\n        span,\n        \"gen_ai.input.messages\",\n        JSON.stringify(embeddingsInputMessages(request.input)),\n      );\n    }\n    return;\n  }\n\n  safeSetAttribute(span, \"gen_ai.request.temperature\", request?.temperature);\n  safeSetAttribute(span, \"gen_ai.request.top_p\", request?.topP);\n  safeSetAttribute(\n    span,\n    \"gen_ai.request.frequency_penalty\",\n    request?.frequencyPenalty,\n  );\n  safeSetAttribute(\n    span,\n    \"gen_ai.request.presence_penalty\",\n    request?.presencePenalty,\n  );\n  // `chat` takes a flat `reasoningEffort`, `responses` nests it under `reasoning`.\n  safeSetAttribute(\n    span,\n    \"gen_ai.request.reasoning_effort\",\n    request?.reasoningEffort ?? request?.reasoning?.effort,\n  );\n  safeSetAttribute(\n    span,\n    \"gen_ai.request.max_tokens\",\n    kind === \"chat\" ? request?.maxTokens : request?.maxOutputTokens,\n  );\n  const schema = structuredOutputSchema(kind, request);\n  if (schema) {\n    safeSetAttribute(\n      span,\n      \"gen_ai.request.structured_output_schema\",\n      JSON.stringify(schema),\n    );\n  }\n  if (request?.stream) {\n    safeSetAttribute(span, \"llm.is_streaming\", true);\n  }\n\n  if (!traceContent) return;\n  if (Array.isArray(request?.tools) && request.tools.length > 0) {\n    safeSetAttribute(\n      span,\n      \"gen_ai.tool.definitions\",\n      JSON.stringify(request.tools),\n    );\n  }\n  const messages =\n    kind === \"chat\" ? request?.messages : responsesInputMessages(request);\n  if (Array.isArray(messages) && messages.length > 0) {\n    safeSetAttribute(span, \"gen_ai.input.messages\", JSON.stringify(messages));\n  }\n};\n\nconst setUsageAttributes = (\n  span: LaminarSpan,\n  usage: any,\n  inputKey: string,\n  outputKey: string,\n  inputCostKey: string,\n  outputCostKey: string,\n): void => {\n  if (!usage) return;\n  safeSetAttribute(span, \"gen_ai.usage.input_tokens\", usage[inputKey]);\n  safeSetAttribute(span, \"gen_ai.usage.output_tokens\", usage[outputKey]);\n  safeSetAttribute(span, \"llm.usage.total_tokens\", usage.totalTokens);\n\n  const inputDetails = usage[`${inputKey}Details`];\n  safeSetAttribute(\n    span,\n    \"gen_ai.usage.cache_read_input_tokens\",\n    inputDetails?.cachedTokens,\n  );\n  safeSetAttribute(\n    span,\n    \"gen_ai.usage.cache_creation_input_tokens\",\n    inputDetails?.cacheWriteTokens,\n  );\n  safeSetAttribute(\n    span,\n    \"gen_ai.usage.reasoning_tokens\",\n    usage[`${outputKey}Details`]?.reasoningTokens,\n  );\n\n  safeSetAttribute(span, \"gen_ai.usage.cost\", usage.cost);\n  safeSetAttribute(\n    span,\n    \"gen_ai.usage.input_cost\",\n    usage.costDetails?.[inputCostKey],\n  );\n  safeSetAttribute(\n    span,\n    \"gen_ai.usage.output_cost\",\n    usage.costDetails?.[outputCostKey],\n  );\n};\n\n/** Message to fail the span with, or `undefined` if the response succeeded. */\nconst responsesErrorMessage = (response: any): string | undefined => {\n  if (!ERROR_RESPONSE_STATUSES.has(response?.status)) return undefined;\n  return (\n    response.error?.message ??\n    response.incompleteDetails?.reason ??\n    response.status\n  );\n};\n\nexport const setResponseAttributes = (\n  span: LaminarSpan,\n  kind: ResourceKind,\n  response: any,\n  traceContent: boolean,\n): void => {\n  if (!response) return;\n  safeSetAttribute(span, \"gen_ai.response.id\", response.id);\n  safeSetAttribute(span, \"gen_ai.response.model\", response.model);\n\n  if (kind === \"responses\") {\n    setUsageAttributes(\n      span,\n      response.usage,\n      \"inputTokens\",\n      \"outputTokens\",\n      \"upstreamInferenceInputCost\",\n      \"upstreamInferenceOutputCost\",\n    );\n    const error = responsesErrorMessage(response);\n    if (error) {\n      span.setAttribute(\"error.type\", response.status);\n      span.setStatus({ code: SpanStatusCode.ERROR, message: error });\n    }\n  } else {\n    // `embeddings` usage carries no completion counters, but the keys it does\n    // carry match `chat`.\n    setUsageAttributes(\n      span,\n      response.usage,\n      \"promptTokens\",\n      \"completionTokens\",\n      \"upstreamInferencePromptCost\",\n      \"upstreamInferenceCompletionsCost\",\n    );\n  }\n\n  if (!traceContent || kind === \"embeddings\") return;\n  const output = kind === \"chat\" ? response.choices : response.output;\n  if (Array.isArray(output) && output.length > 0) {\n    safeSetAttribute(span, \"gen_ai.output.messages\", JSON.stringify(output));\n  }\n};\n\nconst aggregateChatChunks = (chunks: any[]): any => {\n  const result: any = { id: undefined, model: undefined, usage: undefined };\n  const choices = new Map<number, any>();\n  const toolCalls = new Map<number, Map<number, any>>();\n\n  for (const chunk of chunks) {\n    result.id ??= chunk?.id;\n    result.model ??= chunk?.model;\n    if (chunk?.usage) result.usage = chunk.usage;\n\n    for (const choice of chunk?.choices ?? []) {\n      const index = choice.index ?? 0;\n      if (!choices.has(index)) {\n        choices.set(index, {\n          index,\n          message: { role: \"assistant\", content: \"\" },\n          finishReason: undefined,\n        });\n      }\n      const accumulated = choices.get(index);\n      const delta = choice.delta ?? {};\n      if (delta.role) accumulated.message.role = delta.role;\n      if (delta.content) accumulated.message.content += delta.content;\n      for (const call of delta.toolCalls ?? []) {\n        if (!toolCalls.has(index)) toolCalls.set(index, new Map());\n        const calls = toolCalls.get(index)!;\n        const callIndex = call.index ?? 0;\n        if (!calls.has(callIndex)) {\n          calls.set(callIndex, {\n            id: undefined,\n            type: \"function\",\n            function: { name: \"\", arguments: \"\" },\n          });\n        }\n        const slot = calls.get(callIndex);\n        slot.id ??= call.id;\n        slot.function.name += call.function?.name ?? \"\";\n        slot.function.arguments += call.function?.arguments ?? \"\";\n      }\n      if (choice.finishReason) accumulated.finishReason = choice.finishReason;\n    }\n  }\n\n  for (const [index, calls] of toolCalls) {\n    choices.get(index).message.toolCalls = [...calls.keys()]\n      .sort((a, b) => a - b)\n      .map((key) => calls.get(key));\n  }\n  result.choices = [...choices.keys()]\n    .sort((a, b) => a - b)\n    .map((key) => choices.get(key));\n  return result;\n};\n\nconst responseFromStreamEvents = (events: any[]): any => {\n  for (let i = events.length - 1; i >= 0; i--) {\n    if (TERMINAL_RESPONSE_EVENTS.has(events[i]?.type)) {\n      return events[i].response;\n    }\n  }\n  return undefined;\n};\n\n/**\n * Replaces the stream's async iterator so the span is finalized once the\n * consumer finishes (or abandons) iteration. The stream object is returned as-is.\n */\nexport const wrapStream = <T extends AsyncIterable<any>>(\n  span: LaminarSpan,\n  kind: ResourceKind,\n  stream: T,\n  traceContent: boolean,\n): T => {\n  const originalIterator = stream[Symbol.asyncIterator].bind(stream);\n\n  async function* wrapper(): AsyncGenerator<any> {\n    const chunks: any[] = [];\n    try {\n      for await (const chunk of { [Symbol.asyncIterator]: originalIterator }) {\n        chunks.push(chunk);\n        yield chunk;\n      }\n    } catch (error) {\n      recordError(span, error);\n      throw error;\n    } finally {\n      try {\n        const response =\n          kind === \"chat\"\n            ? aggregateChatChunks(chunks)\n            : responseFromStreamEvents(chunks);\n        setResponseAttributes(span, kind, response, traceContent);\n      } finally {\n        span.end();\n      }\n    }\n  }\n\n  (stream as any)[Symbol.asyncIterator] = wrapper;\n  return stream;\n};\n","import { context, diag } from \"@opentelemetry/api\";\nimport { isTracingSuppressed } from \"@opentelemetry/core\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\n\nimport { version as SDK_VERSION } from \"../../../../package.json\";\nimport { Laminar } from \"../../../laminar\";\nimport { LaminarSpan } from \"../../tracing/span\";\nimport {\n  isAsyncIterable,\n  ResourceKind,\n  recordError,\n  responsesInputMessages,\n  setRequestAttributes,\n  setResponseAttributes,\n  wrapStream,\n} from \"./utils\";\n\nconst WRAPPED_SYMBOL = Symbol(\"lmnr.openrouter.wrapped\");\nconst PATCH_STATE_SYMBOL = Symbol(\"lmnr.openrouter.patch-state\");\n\n/** The method each resource sends on, and the key its request is wrapped in. */\nconst RESOURCE_METHODS: Record<\n  ResourceKind,\n  { method: string; requestKey: string }\n> = {\n  chat: { method: \"send\", requestKey: \"chatRequest\" },\n  responses: { method: \"send\", requestKey: \"responsesRequest\" },\n  embeddings: { method: \"generate\", requestKey: \"requestBody\" },\n};\n\nconst RESOURCE_KINDS = Object.keys(RESOURCE_METHODS) as ResourceKind[];\n\ntype PatchState = {\n  traceContent: boolean;\n  chat: PropertyDescriptor | undefined;\n  responses: PropertyDescriptor | undefined;\n  embeddings: PropertyDescriptor | undefined;\n  callModel: ((...args: any[]) => any) | undefined;\n};\n\nexport class OpenRouterInstrumentation extends InstrumentationBase {\n  private traceContent: boolean;\n\n  constructor(config?: { traceContent?: boolean }) {\n    super(\"@lmnr/openrouter-instrumentation\", SDK_VERSION, { enabled: true });\n    this.traceContent = config?.traceContent ?? true;\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    return new InstrumentationNodeModuleDefinition(\n      \"@openrouter/sdk\",\n      [\">=1.0.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n  }\n\n  public manuallyInstrument(openRouterModule: any): void {\n    diag.debug(\"Manually instrumenting @openrouter/sdk\");\n    const OpenRouterClass = this.resolveOpenRouterClass(openRouterModule);\n    if (OpenRouterClass) {\n      this.patchOpenRouterClass(OpenRouterClass);\n    } else {\n      diag.warn(\n        \"Could not find OpenRouter class in openrouter manual instrumentation input. \" +\n          \"Pass either the OpenRouter class or the module object with an OpenRouter export.\",\n      );\n    }\n  }\n\n  private patch(moduleExports: any): any {\n    diag.debug(\"Patching @openrouter/sdk\");\n    const OpenRouterClass = this.resolveOpenRouterClass(moduleExports);\n    if (OpenRouterClass) {\n      this.patchOpenRouterClass(OpenRouterClass);\n    }\n    return moduleExports;\n  }\n\n  private unpatch(moduleExports: any): void {\n    diag.debug(\"Unpatching @openrouter/sdk\");\n    const OpenRouterClass = this.resolveOpenRouterClass(moduleExports);\n    if (OpenRouterClass) {\n      this.unpatchOpenRouterClass(OpenRouterClass);\n    }\n  }\n\n  private resolveOpenRouterClass(moduleOrClass: any): any {\n    if (typeof moduleOrClass === \"function\") {\n      return moduleOrClass;\n    }\n    if (typeof moduleOrClass?.OpenRouter === \"function\") {\n      return moduleOrClass.OpenRouter;\n    }\n    return undefined;\n  }\n\n  private patchOpenRouterClass(OpenRouterClass: any): void {\n    const proto = OpenRouterClass.prototype;\n    const existing = proto[PATCH_STATE_SYMBOL] as PatchState | undefined;\n    if (existing) {\n      existing.traceContent = this.traceContent;\n      return;\n    }\n\n    const state: PatchState = {\n      traceContent: this.traceContent,\n      chat: Object.getOwnPropertyDescriptor(proto, \"chat\"),\n      responses: Object.getOwnPropertyDescriptor(proto, \"responses\"),\n      embeddings: Object.getOwnPropertyDescriptor(proto, \"embeddings\"),\n      callModel: proto.callModel,\n    };\n    proto[PATCH_STATE_SYMBOL] = state;\n\n    for (const kind of RESOURCE_KINDS) {\n      patchResourceGetter(proto, kind, state);\n    }\n    if (typeof state.callModel === \"function\") {\n      patchCallModel(proto, state);\n    }\n  }\n\n  private unpatchOpenRouterClass(OpenRouterClass: any): void {\n    const proto = OpenRouterClass.prototype;\n    const state = proto[PATCH_STATE_SYMBOL] as PatchState | undefined;\n    if (!state) return;\n\n    for (const kind of RESOURCE_KINDS) {\n      if (state[kind]) {\n        Object.defineProperty(proto, kind, state[kind]);\n      } else {\n        delete proto[kind];\n      }\n    }\n    if (state.callModel) {\n      proto.callModel = state.callModel;\n    }\n    delete proto[PATCH_STATE_SYMBOL];\n  }\n}\n\nconst patchResourceGetter = (\n  proto: any,\n  kind: ResourceKind,\n  state: PatchState,\n): void => {\n  const descriptor = state[kind];\n  if (!descriptor?.get || !descriptor.configurable) {\n    diag.warn(`Could not patch OpenRouter.prototype.${kind} getter.`);\n    return;\n  }\n  const originalGet = descriptor.get;\n  Object.defineProperty(proto, kind, {\n    configurable: true,\n    enumerable: descriptor.enumerable ?? false,\n    get() {\n      const resource = originalGet.call(this);\n      patchResourceMethod(resource, kind, state);\n      return resource;\n    },\n  });\n};\n\nconst patchResourceMethod = (\n  resource: any,\n  kind: ResourceKind,\n  state: PatchState,\n): void => {\n  if (!resource || resource[WRAPPED_SYMBOL]) return;\n  const { method, requestKey } = RESOURCE_METHODS[kind];\n  if (typeof resource[method] !== \"function\") return;\n\n  const original = resource[method].bind(resource);\n\n  resource[method] = async (request: any, options?: any) => {\n    if (isTracingSuppressed(context.active())) {\n      return original(request, options);\n    }\n\n    const { traceContent } = state;\n    const span = Laminar.startSpan({\n      name: `openrouter.${kind}`,\n      spanType: \"LLM\",\n    }) as LaminarSpan;\n    span.setAttribute(\"gen_ai.system\", \"openrouter\");\n    setRequestAttributes(span, kind, request?.[requestKey], traceContent);\n\n    try {\n      const response = await Laminar.withSpan(span, () =>\n        original(request, options),\n      );\n      if (isAsyncIterable(response)) {\n        return wrapStream(span, kind, response, traceContent);\n      }\n      setResponseAttributes(span, kind, response, traceContent);\n      span.end();\n      return response;\n    } catch (error) {\n      recordError(span, error);\n      span.end();\n      throw error;\n    }\n  };\n  resource[WRAPPED_SYMBOL] = true;\n};\n\nconst patchCallModel = (proto: any, state: PatchState): void => {\n  const originalCallModel = state.callModel as (...args: any[]) => any;\n\n  proto.callModel = function (request: any, options?: any) {\n    if (isTracingSuppressed(context.active())) {\n      return originalCallModel.call(this, request, options);\n    }\n\n    const { traceContent } = state;\n    const span = Laminar.startSpan({\n      name: \"openrouter.call_model\",\n      input: traceContent ? responsesInputMessages(request) : undefined,\n    }) as LaminarSpan;\n\n    const tools = Array.isArray(request?.tools)\n      ? request.tools.map((tool: any) => wrapTool(tool, span, traceContent))\n      : undefined;\n    try {\n      const result = Laminar.withSpan(span, () =>\n        originalCallModel.call(\n          this,\n          tools ? { ...request, tools } : request,\n          options,\n        ),\n      );\n      instrumentModelResult(result, span, traceContent);\n      return result;\n    } catch (error) {\n      recordError(span, error);\n      span.end();\n      throw error;\n    }\n  };\n};\n\nconst wrapTool = (\n  tool: any,\n  parentSpan: LaminarSpan,\n  traceContent: boolean,\n) => {\n  const fn = tool?.function;\n  if (typeof fn?.execute !== \"function\" || fn.eventSchema) return tool;\n\n  const execute = fn.execute;\n  return {\n    ...tool,\n    function: {\n      ...fn,\n      execute: (input: any, ctx: any) =>\n        Laminar.withSpan(parentSpan, () => {\n          const span = Laminar.startSpan({\n            name: fn.name,\n            spanType: \"TOOL\",\n            input: traceContent ? input : undefined,\n          }) as LaminarSpan;\n          return Laminar.withSpan(\n            span,\n            async () => {\n              try {\n                const result = await execute(input, ctx);\n                if (traceContent) span.setOutput(result);\n                return result;\n              } catch (error) {\n                recordError(span, error);\n                throw error;\n              }\n            },\n            true,\n          );\n        }),\n    },\n  };\n};\n\n/**\n * ModelResult runs lazily on first consumption. Each turn's request goes through\n * getInitialResponse / makeFollowupRequest, and executeToolsIfNeeded is the\n * memoized promise every consumption path awaits.\n */\nconst instrumentModelResult = (\n  result: any,\n  parentSpan: LaminarSpan,\n  traceContent: boolean,\n): void => {\n  if (!result || typeof result.executeToolsIfNeeded !== \"function\") {\n    parentSpan.end();\n    return;\n  }\n\n  for (const method of [\"getInitialResponse\", \"makeFollowupRequest\"]) {\n    if (typeof result[method] !== \"function\") continue;\n    const original = result[method].bind(result);\n    result[method] = (...args: any[]) =>\n      Laminar.withSpan(parentSpan, () => {\n        const span = Laminar.startSpan({\n          name: \"openrouter.responses\",\n          spanType: \"LLM\",\n        }) as LaminarSpan;\n        span.setAttribute(\"gen_ai.system\", \"openrouter\");\n        return Laminar.withSpan(\n          span,\n          async () => {\n            try {\n              const response = await original(...args);\n              setRequestAttributes(\n                span,\n                \"responses\",\n                result.resolvedRequest,\n                traceContent,\n              );\n              setResponseAttributes(span, \"responses\", response, traceContent);\n              return response;\n            } catch (error) {\n              recordError(span, error);\n              throw error;\n            }\n          },\n          true,\n        );\n      });\n  }\n\n  const originalExecute = result.executeToolsIfNeeded.bind(result);\n  let execution: Promise<void> | undefined;\n  result.executeToolsIfNeeded = () => {\n    if (execution) return execution;\n    const promise: Promise<void> = originalExecute();\n    execution = promise;\n    promise.then(\n      () => {\n        if (traceContent && result.finalResponse?.output) {\n          parentSpan.setOutput(result.finalResponse.output);\n        }\n        parentSpan.end();\n      },\n      (error: unknown) => {\n        recordError(parentSpan, error);\n        parentSpan.end();\n      },\n    );\n    return execution;\n  };\n};\n","export const getLangVersion: () => string | undefined = () => {\n  if (process?.versions?.node) {\n    return `node@${process.versions.node}`;\n  }\n  //   else if (Deno?.version) {\n  //     return `deno@${Deno?.version?.deno}`;\n  //   }\n};\n","import { TraceFlags } from \"@opentelemetry/api\";\nimport {\n  BatchSpanProcessor,\n  type BufferConfig,\n  type ReadableSpan,\n} from \"@opentelemetry/sdk-trace-base\";\n\nimport { initializeLogger } from \"../../utils\";\n\nconst logger = initializeLogger();\n\n/**\n * GenAI spans carry whole prompts and completions as string attributes, so a\n * batch of only a few dozen of them can be tens of megabytes. 32 MiB keeps a\n * single export comfortably under the ingest limits while still batching.\n */\nexport const DEFAULT_MAX_EXPORT_BATCH_SIZE_BYTES = 32 * 1024 * 1024;\n\n/**\n * Non-string attribute values (numbers, booleans) are counted as a flat 8 bytes\n * instead of being measured — they never dominate a GenAI payload.\n */\nconst FIXED_ATTRIBUTE_VALUE_SIZE = 8;\n\nconst valueSize = (value: unknown): number => {\n  if (typeof value === \"string\") {\n    return utf8Size(value);\n  }\n  if (Array.isArray(value)) {\n    return value.reduce<number>((total, item) => total + valueSize(item), 0);\n  }\n  return FIXED_ATTRIBUTE_VALUE_SIZE;\n};\n\nconst attributesSize = (\n  attributes: Record<string, unknown> | undefined,\n): number => {\n  if (!attributes) {\n    return 0;\n  }\n  return Object.entries(attributes).reduce(\n    (total, [key, value]) => total + utf8Size(key) + valueSize(value),\n    0,\n  );\n};\n\n/**\n * Byte length of `value` encoded as UTF-8.\n *\n * `.length` counts UTF-16 code units, which undercounts CJK by ~3x and\n * Cyrillic/Arabic/emoji by ~2x — on GenAI payloads that made a batch several\n * times the configured limit, the exact oversized-export case this limit exists\n * to prevent.\n *\n * Unlike the Python SDK, which samples a strided subset of long strings, this\n * measures exactly. `Buffer.byteLength` walks the string in native code without\n * allocating the encoded bytes, so it is both cheaper and more accurate than\n * sampling here: measured ~27us on a 20k-character CJK string, against ~16us for\n * a sampled estimate that was also *wrong* for emoji (+11.7%, because indexing a\n * string splits surrogate pairs and each half encodes as U+FFFD). Python has no\n * equivalent primitive — `len(s.encode())` allocates the whole encoded copy —\n * which is the only reason it samples.\n */\nexport const utf8Size = (value: string): number =>\n  Buffer.byteLength(value, \"utf8\");\n\n/**\n * Approximate the exported size of a span, in bytes.\n *\n * Deliberately an underestimate: protobuf framing, ids and timestamps are\n * ignored, and non-string values are counted flat. Underestimating small spans\n * is fine — the count and schedule-delay limits fire first for those. What\n * matters is that a span carrying a large prompt or completion is measured close\n * to its real weight.\n */\nexport const approximateSpanSize = (span: ReadableSpan): number => {\n  let total = utf8Size(span.name ?? \"\");\n  total += attributesSize(span.attributes);\n  for (const event of span.events ?? []) {\n    total += utf8Size(event.name ?? \"\") + attributesSize(event.attributes);\n  }\n  for (const link of span.links ?? []) {\n    total += attributesSize(link.attributes);\n  }\n  if (span.status?.message) {\n    total += utf8Size(span.status.message);\n  }\n  return total;\n};\n\nexport type SizeLimitedBufferConfig = BufferConfig & {\n  /**\n   * Approximate maximum size, in bytes, of the spans buffered in one batch.\n   * Defaults to {@link DEFAULT_MAX_EXPORT_BATCH_SIZE_BYTES}.\n   */\n  maxExportBatchSizeBytes?: number;\n};\n\n/**\n * `BatchSpanProcessor` with a third, size-based flush trigger.\n *\n * Opt-in via `Laminar.initialize({ flushBySize: true })`; the default transport\n * is the plain upstream `BatchSpanProcessor`.\n *\n * Upstream flushes on whichever comes first: `maxExportBatchSize` spans\n * buffered, or `scheduledDelayMillis` elapsed. Neither bounds the *payload*, so\n * a handful of large GenAI spans can produce an export big enough for the\n * backend to reject. This adds `maxExportBatchSizeBytes`: when the span being\n * ended would push the buffer past the limit, the buffer is flushed first and\n * the span then starts a fresh batch.\n *\n * The Python SDK needs considerably more machinery for this — a dedicated flush\n * thread, a lock around the running total, a fork handler, and an inline\n * fallback for backpressure — none of which is needed here, because the two\n * runtimes behave differently in three ways:\n *\n * 1. `forceFlush()` moves the buffered spans out synchronously and only *awaits*\n *    the network, so calling it from `onEnd` never blocks the caller (measured:\n *    0.34ms worst case against a 300ms export). Python's `force_flush` performs\n *    the export itself on the calling thread, which load testing measured at a\n *    p99 of ~664ms and is why it needs a background thread.\n * 2. Because the flush is synchronous with respect to the buffer, the batch stays\n *    bounded even when a producer emits in a tight loop, so no inline-fallback\n *    backpressure path is needed. Python's asynchronous handoff can be outrun.\n * 3. `onEnd` calls `super.onEnd(span)` *after* flushing, so the triggering span\n *    is genuinely excluded from the batch it caused. Python cannot do this — its\n *    flush is asynchronous, so the triggering span rides along, which is why it\n *    needs a separate \"span is at least half the limit\" rule to bound overshoot.\n *    Here a batch never exceeds the limit by more than the last span under it.\n *\n * Single-threaded event loop, so no lock guards the running total, and there is\n * no `fork` story to handle.\n */\nexport class SizeLimitedBatchSpanProcessor extends BatchSpanProcessor {\n  private readonly maxExportBatchSizeBytes: number;\n  private pendingSizeBytes = 0;\n\n  constructor(\n    exporter: ConstructorParameters<typeof BatchSpanProcessor>[0],\n    config?: SizeLimitedBufferConfig,\n  ) {\n    super(exporter, config);\n    this.maxExportBatchSizeBytes =\n      config?.maxExportBatchSizeBytes ?? DEFAULT_MAX_EXPORT_BATCH_SIZE_BYTES;\n  }\n\n  public onEnd(span: ReadableSpan): void {\n    // Upstream drops unsampled spans without buffering them, so they must not\n    // count toward the running total either.\n    if ((span.spanContext().traceFlags & TraceFlags.SAMPLED) === 0) {\n      super.onEnd(span);\n      return;\n    }\n\n    // The running total can go stale when upstream drains the buffer on its own\n    // count or schedule-delay trigger. Deliberately NOT corrected here, unlike\n    // Python, which resets the total whenever it observes an empty buffer: the\n    // only consequence of a stale total is an early flush, and an early flush on\n    // an already-drained buffer is a no-op in JS (upstream's `_flushOneBatch`\n    // returns immediately on an empty buffer — no export, no wire traffic). In\n    // Python the same spurious flush is a real blocking network round trip on a\n    // user's thread, which is what makes the correction load-bearing there.\n    // Reading upstream's private `_finishedSpans` to fix an unobservable\n    // discrepancy is not worth the coupling.\n    const size = approximateSpanSize(span);\n    const shouldFlush =\n      this.pendingSizeBytes > 0 &&\n      this.pendingSizeBytes + size > this.maxExportBatchSizeBytes;\n    this.pendingSizeBytes = shouldFlush ? size : this.pendingSizeBytes + size;\n\n    if (shouldFlush) {\n      // Flush BEFORE enqueueing this span, so the batch that goes out is\n      // everything that preceded it and this span opens the next one.\n      //\n      // The `catch` is required, not defensive: `forceFlush()` rejects when an\n      // export fails, and nothing awaits this promise, so without it a failed\n      // export becomes an unhandled rejection — which crashes the process under\n      // Node's default `--unhandled-rejections=throw`. Verified: three failing\n      // exports produced three unhandled rejections.\n      void this.forceFlush().catch((error: unknown) => {\n        logger.debug(`Size-triggered span flush failed: ${String(error)}`);\n      });\n    }\n\n    super.onEnd(span);\n  }\n}\n","// This class could be just an initialization of the OTLP exporter,\n// but OTel v2 has some breaking changes, so we're applying\n// a small backward-compatibility fix here.\n\nimport { Metadata } from \"@grpc/grpc-js\";\nimport { ExportResult } from \"@opentelemetry/core\";\nimport { OTLPTraceExporter as ExporterGrpc } from \"@opentelemetry/exporter-trace-otlp-grpc\";\nimport { OTLPTraceExporter as ExporterHttp } from \"@opentelemetry/exporter-trace-otlp-proto\";\nimport { ReadableSpan, SpanExporter } from \"@opentelemetry/sdk-trace-base\";\n\nimport { getOtelEnvVar, initializeLogger, parseOtelHeaders } from \"../../utils\";\nimport { makeSpanOtelV2Compatible } from \"./compat\";\n\nconst logger = initializeLogger();\n\nexport class LaminarSpanExporter implements SpanExporter {\n  private exporter: SpanExporter;\n\n  constructor(\n    options: {\n      baseUrl?: string;\n      port?: number;\n      apiKey?: string;\n      forceHttp?: boolean;\n      timeoutMillis?: number;\n    } = {},\n  ) {\n    let url = options.baseUrl ?? process?.env?.LMNR_BASE_URL;\n    let port = options.port;\n    let forceHttp = options.forceHttp ?? false;\n    const key = options.apiKey ?? process?.env?.LMNR_PROJECT_API_KEY;\n\n    // Determine headers - either from API key or OTEL env vars\n    let headers: Record<string, string> = {};\n    if (key) {\n      headers = forceHttp\n        ? { Authorization: `Bearer ${key}` }\n        : { authorization: `Bearer ${key}` };\n      if (!url) {\n        url = \"https://api.lmnr.ai\";\n      }\n    } else {\n      const otelHeaders = getOtelEnvVar(\"HEADERS\");\n      if (otelHeaders) {\n        headers = parseOtelHeaders(otelHeaders);\n      }\n      // Check for OTEL endpoint configuration\n      const otelEndpoint = getOtelEnvVar(\"ENDPOINT\");\n      if (otelEndpoint && !url) {\n        url = otelEndpoint;\n\n        // Determine protocol from OTEL env vars\n        const otelProtocol = getOtelEnvVar(\"PROTOCOL\") || \"grpc/protobuf\";\n        const otelExporter = process?.env?.OTEL_EXPORTER;\n        forceHttp =\n          otelProtocol === \"http/protobuf\" ||\n          otelProtocol === \"http/json\" ||\n          otelExporter === \"otlp_http\";\n      } else if (otelEndpoint && url) {\n        logger.warn(\n          \"OTEL_ENDPOINT is set, but Laminar base URL is also set. Ignoring OTEL_ENDPOINT.\",\n        );\n      }\n    }\n\n    if (!url) {\n      throw new Error(\n        \"Laminar base URL is not set and OTEL_ENDPOINT is not set. Please either\\n\" +\n          \"- set the LMNR_BASE_URL environment variable\\n\" +\n          \"- set the OTEL_ENDPOINT environment variable (if you are not using a Laminar API key)\\n\" +\n          \"- pass the baseUrl parameter to Laminar.initialize\",\n      );\n    }\n\n    // Calculate port\n    if (!port) {\n      port = url.match(/:\\d{1,5}$/g)\n        ? parseInt(url.match(/:\\d{1,5}$/g)![0].slice(1))\n        : forceHttp\n          ? 443\n          : 8443;\n    }\n\n    const urlWithoutSlash = url.replace(/\\/$/, \"\").replace(/:\\d{1,5}$/g, \"\");\n\n    if (forceHttp) {\n      this.exporter = new ExporterHttp({\n        url: `${urlWithoutSlash}:${port}/v1/traces`,\n        headers,\n        timeoutMillis: options.timeoutMillis ?? 30000,\n      });\n    } else {\n      const metadata = new Metadata();\n      Object.entries(headers).forEach(([key, value]) => {\n        metadata.set(key, value);\n      });\n      this.exporter = new ExporterGrpc({\n        url: `${urlWithoutSlash}:${port}`,\n        metadata,\n        timeoutMillis: options.timeoutMillis ?? 30000,\n      });\n    }\n  }\n\n  export(\n    items: ReadableSpan[],\n    resultCallback: (result: ExportResult) => void,\n  ) {\n    // ==== //\n    // OTel v2 has renamed the instrumentationLibrary field to instrumentationScope,\n    // but spans may be created by older versions of the SDK that don't have that change.\n    // This is a small hack to support those older spans.\n    items.forEach(makeSpanOtelV2Compatible);\n    // ==== //\n\n    return this.exporter.export(items, resultCallback);\n  }\n\n  async shutdown(): Promise<void> {\n    return this.exporter.shutdown();\n  }\n\n  async forceFlush(): Promise<void> {\n    return this.exporter.forceFlush?.();\n  }\n}\n","import { Context, context } from \"@opentelemetry/api\";\nimport {\n  BatchSpanProcessor,\n  SimpleSpanProcessor,\n  type Span,\n  SpanExporter,\n  SpanProcessor,\n} from \"@opentelemetry/sdk-trace-base\";\nimport { Logger } from \"pino\";\n\nimport { version as SDK_VERSION } from \"../../../package.json\";\nimport { getRuntime } from \"../../debug\";\nimport {\n  initializeLogger,\n  metadataToAttributes,\n  otelSpanIdToUUID,\n  otelTraceIdToUUID,\n  StringUUID,\n} from \"../../utils\";\nimport { getLangVersion } from \"../../version\";\nimport {\n  ASSOCIATION_PROPERTIES,\n  ASSOCIATION_PROPERTIES_OVERRIDES,\n  PARENT_SPAN_IDS_PATH,\n  PARENT_SPAN_PATH,\n  SESSION_ID,\n  SPAN_IDS_PATH,\n  SPAN_INSTRUMENTATION_SOURCE,\n  SPAN_LANGUAGE_VERSION,\n  SPAN_PATH,\n  SPAN_SDK_VERSION,\n  TRACE_TYPE,\n  USER_ID,\n} from \"./attributes\";\nimport { SizeLimitedBatchSpanProcessor } from \"./batch-processor\";\nimport {\n  getParentSpanId,\n  makeSpanOtelV2Compatible,\n  OTelSpanCompat,\n} from \"./compat\";\nimport {\n  ASSOCIATION_PROPERTIES_KEY,\n  CONTEXT_SPAN_PATH_KEY,\n  LaminarContextManager,\n} from \"./context\";\nimport { LaminarSpanExporter } from \"./exporter\";\n\ninterface LaminarSpanProcessorOptions {\n  /**\n   * The base URL of the Laminar API. Optional.\n   * Defaults to https://api.lmnr.ai.\n   */\n  baseUrl?: string;\n  /**\n   * The port of the Laminar API. Optional.\n   * Defaults to 8443.\n   */\n  port?: number;\n  /**\n   * Laminar project API key. Optional.\n   * If not provided, the LMNR_PROJECT_API_KEY environment variable will be used.\n   */\n  apiKey?: string;\n  /**\n   * The maximum number of spans to export at a time. Optional.\n   * Defaults to 512.\n   */\n  maxExportBatchSize?: number;\n  /**\n   * Whether to disable batching. Optional.\n   * Defaults to false.\n   */\n  disableBatch?: boolean;\n  /**\n   * Approximate maximum size, in bytes, of the spans buffered in a single batch.\n   * Only used when `flushBySize` is true. Optional.\n   * Defaults to 32 MiB.\n   */\n  maxExportBatchSizeBytes?: number;\n  /**\n   * Whether to also flush batches by approximate payload size. Optional.\n   * Defaults to false.\n   */\n  flushBySize?: boolean;\n  /**\n   * Whether to force HTTP and use OpenTelemetry HTTP/protobuf exporter.\n   * Not recommended with Laminar backends.\n   * Optional.\n   * Defaults to false.\n   */\n  forceHttp?: boolean;\n  /**\n   * The timeout for sending traces data. Optional.\n   * Defaults to 30 seconds.\n   */\n  traceExportTimeoutMillis?: number;\n\n  /**\n   * The exporter to use. Optional. If specified, some of the other options will be ignored.\n   * Defaults to a new LaminarSpanExporter.\n   */\n  exporter?: SpanExporter;\n\n  /**\n   * The span processor to use. If passed, some of the other options will be ignored.\n   * If passed, wraps the underlying span processor.\n   */\n  spanProcessor?: SpanProcessor;\n\n  /**\n   * The HTTP port to use. Optional.\n   * If not provided, the `port` option will be used.\n   */\n  httpPort?: number;\n}\n\nexport class LaminarSpanProcessor implements SpanProcessor {\n  private instance: BatchSpanProcessor | SimpleSpanProcessor;\n  private logger: Logger;\n  private readonly _spanIdToPath: Map<string, string[]> = new Map();\n  private readonly _spanIdLists: Map<string, string[]> = new Map();\n\n  /**\n   * @param {object} options - The options for the Laminar span processor.\n   * @param {string} options.baseUrl - The base URL of the Laminar API.\n   * @param {number} options.port - The port of the Laminar API.\n   * @param {string} options.apiKey - Laminar project API key or any other\n   * authorization set as bearer token.\n   * @param {boolean} options.disableBatch - Whether to disable batching (uses SimpleSpanProcessor).\n   * @param {number} options.maxExportBatchSize - The maximum number of spans to export at a time\n   * if disableBatch is false.\n   * @param {number} options.traceExportTimeoutMillis - The timeout for sending traces data.\n   * Defaults to 30 seconds.\n   * @param {boolean} options.forceHttp - Whether to force HTTP and use OpenTelemetry\n   * HTTP/protobuf exporter.\n   * Not recommended with Laminar backends.\n   */\n  constructor(options: LaminarSpanProcessorOptions = {}) {\n    this.logger = initializeLogger();\n    if (\n      options.spanProcessor &&\n      options.spanProcessor instanceof LaminarSpanProcessor\n    ) {\n      this.instance = options.spanProcessor.instance;\n      // Set by reference, so that updates from the inside are reflected here.\n      this._spanIdToPath = options.spanProcessor._spanIdToPath;\n      this._spanIdLists = options.spanProcessor._spanIdLists;\n    } else if (options.spanProcessor) {\n      this.instance = options.spanProcessor as\n        | BatchSpanProcessor\n        | SimpleSpanProcessor;\n    } else {\n      const exporter = options.exporter ?? new LaminarSpanExporter(options);\n      const batchConfig = {\n        maxExportBatchSize: options.maxExportBatchSize ?? 512,\n        exportTimeoutMillis: options.traceExportTimeoutMillis ?? 30000,\n      };\n      if (options.disableBatch) {\n        this.instance = new SimpleSpanProcessor(exporter);\n      } else if (options.flushBySize) {\n        this.instance = new SizeLimitedBatchSpanProcessor(exporter, {\n          ...batchConfig,\n          maxExportBatchSizeBytes: options.maxExportBatchSizeBytes,\n        });\n      } else {\n        this.instance = new BatchSpanProcessor(exporter, batchConfig);\n      }\n    }\n  }\n\n  forceFlush(): Promise<void> {\n    return this.instance.forceFlush();\n  }\n\n  shutdown(): Promise<void> {\n    return this.instance.shutdown();\n  }\n\n  onStart(spanArg: any, parentContext: Context): void {\n    const span = spanArg as OTelSpanCompat;\n    // Check for parent path attributes first (from serialized span context)\n    const parentPathFromAttribute = span.attributes?.[PARENT_SPAN_PATH] as\n      | string[]\n      | undefined;\n    const parentIdsPathFromAttribute = span.attributes?.[\n      PARENT_SPAN_IDS_PATH\n    ] as StringUUID[] | undefined;\n\n    const parentSpanId = getParentSpanId(span);\n\n    // Use parent path from attributes if available, otherwise fall back to cached paths\n    const parentSpanPath =\n      parentPathFromAttribute ??\n      (parentSpanId !== undefined\n        ? this._spanIdToPath.get(parentSpanId)\n        : undefined);\n\n    const spanId = span.spanContext().spanId;\n    // A parent created in ANOTHER process (context restored from a traceparent\n    // header or a queue carrier) is not in `_spanIdLists`. Seeding the path with\n    // the parent's own id keeps this span off the head of its ids_path, which is\n    // what stops the backend from treating it as a root and discarding the\n    // parent (`is_top_span` in app-server/src/traces/utils.rs).\n    const parentSpanIdsPath =\n      parentIdsPathFromAttribute ??\n      (parentSpanId\n        ? (this._spanIdLists.get(parentSpanId) ?? [\n            otelSpanIdToUUID(parentSpanId),\n          ])\n        : []);\n    const spanPath = parentSpanPath\n      ? [...parentSpanPath, span.name]\n      : [span.name];\n\n    const spanIdUuid = otelSpanIdToUUID(spanId);\n    const spanIdsPath = parentSpanIdsPath\n      ? [...parentSpanIdsPath, spanIdUuid]\n      : [spanIdUuid];\n\n    span.setAttribute(SPAN_IDS_PATH, spanIdsPath);\n    this._spanIdLists.set(spanId, spanIdsPath);\n\n    span.setAttribute(SPAN_PATH, spanPath);\n    context.active().setValue(CONTEXT_SPAN_PATH_KEY, spanPath);\n    this._spanIdToPath.set(spanId, spanPath);\n\n    span.setAttribute(SPAN_INSTRUMENTATION_SOURCE, \"javascript\");\n    span.setAttribute(SPAN_SDK_VERSION, SDK_VERSION);\n    const langVersion = getLangVersion();\n    if (langVersion) {\n      span.setAttribute(SPAN_LANGUAGE_VERSION, langVersion);\n    }\n\n    // Stamp global metadata (e.g. the debug run's `rollout.session_id`) onto\n    // every span. Unlike association properties, global metadata is not carried\n    // on the OTEL context, so traces built purely from auto-instrumentation\n    // (no observe / startActiveSpan) would otherwise never receive it. The\n    // association-properties block below re-applies the per-span metadata, which\n    // already merges global metadata in (see buildContextProperties), so any\n    // span-level overrides still win.\n    const globalMetadata = LaminarContextManager.getGlobalMetadata();\n    if (globalMetadata && Object.keys(globalMetadata).length > 0) {\n      span.setAttributes(metadataToAttributes(globalMetadata));\n    }\n\n    // This sets the properties only if the context has them\n    const associationProperties = context\n      .active()\n      .getValue(ASSOCIATION_PROPERTIES_KEY);\n    if (associationProperties) {\n      for (const [key, value] of Object.entries(associationProperties)) {\n        if (Object.keys(ASSOCIATION_PROPERTIES_OVERRIDES).includes(key)) {\n          span.setAttribute(ASSOCIATION_PROPERTIES_OVERRIDES[key], value);\n        } else if (key === \"tracing_level\") {\n          span.setAttribute(\"lmnr.internal.tracing_level\", value);\n        } else if (\n          key === \"metadata\" &&\n          typeof value === \"object\" &&\n          value !== null\n        ) {\n          // Flatten metadata into individual attributes\n          const metadataAttrs = metadataToAttributes(\n            value as Record<string, unknown>,\n          );\n          span.setAttributes(metadataAttrs);\n        } else if (key === \"userId\") {\n          span.setAttribute(USER_ID, value);\n        } else if (key === \"sessionId\") {\n          span.setAttribute(SESSION_ID, value);\n        } else if (key === \"traceType\") {\n          span.setAttribute(TRACE_TYPE, value);\n        } else if (key === \"tracingLevel\") {\n          span.setAttribute(\"lmnr.internal.tracing_level\", value);\n        } else {\n          span.setAttribute(`${ASSOCIATION_PROPERTIES}.${key}`, value);\n        }\n      }\n    }\n\n    makeSpanOtelV2Compatible(span);\n\n    // On a debug run, remember the root trace id so the run pointer (§5) can be\n    // emitted at shutdown.\n    if (parentSpanId === undefined) {\n      this.recordDebugTraceId(span);\n    }\n\n    this.instance.onStart(span, parentContext);\n  }\n\n  /**\n   * Record the root trace id on the debug runtime, if this is a debug run.\n   *\n   * No-op when debug mode is off. Best-effort: never break tracing.\n   */\n  private recordDebugTraceId(span: OTelSpanCompat): void {\n    try {\n      const runtime = getRuntime();\n      if (runtime === null) {\n        return;\n      }\n      runtime.recordTraceId(otelTraceIdToUUID(span.spanContext().traceId));\n    } catch (e) {\n      this.logger.debug(`Failed to record debug trace id: ${String(e)}`);\n    }\n  }\n\n  // type ReadableSpan\n  onEnd(span: any): void {\n    const spanId = (span as Span).spanContext().spanId;\n    this._spanIdLists.delete(spanId);\n    this._spanIdToPath.delete(spanId);\n    makeSpanOtelV2Compatible(span);\n    this.instance.onEnd(span as Span);\n  }\n\n  /**\n   * Set parent path information for a given span ID.\n   * Used when initializing context from environment variables.\n   *\n   * @param parentSpanId - The span ID to set path information for\n   * @param spanPath - The span path (array of span names)\n   * @param spanIdsPath - The span IDs path (array of span ID UUIDs)\n   */\n  setParentPathInfo(\n    parentSpanId: string,\n    spanPath: string[],\n    spanIdsPath: StringUUID[],\n  ): void {\n    this._spanIdToPath.set(parentSpanId, spanPath);\n    this._spanIdLists.set(parentSpanId, spanIdsPath);\n  }\n\n  /**\n   * Drop cached path entries for a given span id. For exporters that stamp\n   * their own span id over the SDK-allocated one after `startSpan` has fired\n   * `onStart` — without this, `onEnd` reads the mutated id and its delete is\n   * a no-op, so the original entry leaks one pair of map entries per span.\n   */\n  dropPathInfo(spanId: string): void {\n    this._spanIdToPath.delete(spanId);\n    this._spanIdLists.delete(spanId);\n  }\n\n  clear() {\n    this._spanIdToPath.clear();\n    this._spanIdLists.clear();\n  }\n}\n","import { errorMessage, LaminarSpanContext } from \"@lmnr-ai/types\";\nimport {\n  Context,\n  isSpanContextValid,\n  ROOT_CONTEXT,\n  trace,\n} from \"@opentelemetry/api\";\n\nimport {\n  deserializeLaminarSpanContext,\n  initializeLogger,\n  otelSpanIdToUUID,\n  otelTraceIdToUUID,\n  tryToOtelSpanContext,\n} from \"../../../utils\";\nimport { LaminarContextManager } from \"../../tracing/context\";\nimport { getSpanProcessor } from \"../../tracing/index\";\nimport { LaminarSpanProcessor } from \"../../tracing/processor\";\nimport { LaminarSpan } from \"../../tracing/span\";\nimport { LAMINAR_SPAN_CONTEXT_HEADER, TRACEPARENT_HEADER } from \"./consts\";\n\nconst logger = initializeLogger();\n// ─── Payload codec helpers ────────────────────────────────────────────────────\n// Temporal headers are `Record<string, Payload>` where Payload is a protobuf\n// envelope with `metadata.encoding` and `data` fields.  We avoid importing\n// @temporalio/common so that it stays a soft peer-dep.\n\nconst _enc = new TextEncoder();\nconst _dec = new TextDecoder();\n\nexport const encodePayload = (value: string): unknown => ({\n  metadata: { encoding: _enc.encode(\"json/plain\") },\n  data: _enc.encode(JSON.stringify(value)),\n});\n\nexport const decodePayload = (payload: unknown): string | undefined => {\n  if (!payload || typeof payload !== \"object\") return undefined;\n  const p = payload as { data?: Uint8Array | null };\n  if (!p.data) return undefined;\n  try {\n    return JSON.parse(_dec.decode(p.data)) as string;\n  } catch {\n    return undefined;\n  }\n};\n\n// ─── Context serialisation ────────────────────────────────────────────────────\n\n/**\n * Read the currently active Laminar span and encode its context into a headers\n * map.  Writes both `x-lmnr-span-context` (full Laminar JSON) and\n * `traceparent` (W3C, for interop with non-Laminar workers).\n *\n * Returns the headers map unchanged if there is no active Laminar span.\n */\nexport const buildHeaders = (\n  existing: Record<string, unknown>,\n): Record<string, unknown> => {\n  const rawSpan =\n    trace.getSpan(LaminarContextManager.getContext()) ?? trace.getActiveSpan();\n\n  if (!rawSpan || !isSpanContextValid(rawSpan.spanContext())) {\n    return existing;\n  }\n\n  let laminarCtx: LaminarSpanContext | null = null;\n  if (rawSpan instanceof LaminarSpan) {\n    try {\n      laminarCtx = rawSpan.getLaminarSpanContext();\n    } catch {\n      // fall through to OTel-only path\n    }\n  }\n\n  const headers: Record<string, unknown> = { ...existing };\n\n  if (laminarCtx) {\n    headers[LAMINAR_SPAN_CONTEXT_HEADER] = encodePayload(\n      JSON.stringify(laminarCtx),\n    );\n    const traceHex = laminarCtx.traceId.replace(/-/g, \"\");\n    const spanHex = laminarCtx.spanId.replace(/-/g, \"\").slice(16);\n    headers[TRACEPARENT_HEADER] = encodePayload(`00-${traceHex}-${spanHex}-01`);\n  } else {\n    const ctx = rawSpan.spanContext();\n    headers[TRACEPARENT_HEADER] = encodePayload(\n      `00-${ctx.traceId}-${ctx.spanId}-01`,\n    );\n  }\n\n  return headers;\n};\n\n// ─── Context restoration ──────────────────────────────────────────────────────\n\n/** The trace context restored from Temporal headers. */\nexport interface RestoredContext {\n  /** The Laminar span context to use as a span's `parentSpanContext`. */\n  laminarCtx: LaminarSpanContext;\n  /**\n   * The enriched OTel `Context` that was pushed onto Laminar's ALS stack. It\n   * carries the restored remote parent span and the association properties.\n   * Callers that don't create their own activity span should activate this on\n   * the standard OTel context (`contextApi.with(otelContext, ...)`) so that\n   * OTel-aware auto-instrumentations (OpenAI, etc.) — which read\n   * `context.active()` rather than Laminar's ALS — nest under the remote\n   * parent instead of starting detached root traces.\n   */\n  otelContext: Context;\n}\n\n/**\n * Read `x-lmnr-span-context` (preferred) or `traceparent` (fallback) from\n * Temporal headers and push the restored context onto Laminar's ALS stack.\n *\n * Returns the restored context (Laminar + OTel) or `undefined` if headers\n * contain no usable trace context.\n */\nexport const restoreContextFromHeaders = (\n  headers: Record<string, unknown> | undefined,\n): RestoredContext | undefined => {\n  if (!headers) return undefined;\n\n  // Preferred: full Laminar context header\n  const laminarRaw = decodePayload(headers[LAMINAR_SPAN_CONTEXT_HEADER]);\n  if (laminarRaw) {\n    try {\n      const ctx = deserializeLaminarSpanContext(laminarRaw);\n      const otelContext = pushLaminarContext(ctx);\n      return { laminarCtx: ctx, otelContext };\n    } catch (e) {\n      logger.warn(\n        `[Laminar] Could not restore ${LAMINAR_SPAN_CONTEXT_HEADER}: ${errorMessage(e)}`,\n      );\n    }\n  }\n\n  // Fallback: W3C traceparent\n  const traceparent = decodePayload(headers[TRACEPARENT_HEADER]);\n  if (traceparent) {\n    const parts = traceparent.split(\"-\");\n    if (parts.length >= 3) {\n      const [, traceHex, spanHex] = parts;\n      try {\n        const traceId = otelTraceIdToUUID(traceHex);\n        const spanId = otelSpanIdToUUID(\n          spanHex,\n        ) as LaminarSpanContext[\"spanId\"];\n        const ctx: LaminarSpanContext = { traceId, spanId, isRemote: true };\n        const otelContext = pushLaminarContext(ctx);\n        return { laminarCtx: ctx, otelContext };\n      } catch (e) {\n        logger.warn(\n          `[Laminar] Could not restore traceparent: ${errorMessage(e)}`,\n        );\n      }\n    }\n  }\n\n  return undefined;\n};\n\n/**\n * Push a LaminarSpanContext onto the Laminar ALS stack as a remote parent and\n * return the enriched OTel `Context` that was pushed.\n */\nconst pushLaminarContext = (laminarCtx: LaminarSpanContext): Context => {\n  const otelCtx = tryToOtelSpanContext(laminarCtx);\n  otelCtx.isRemote = true;\n\n  const processor = getSpanProcessor();\n  if (\n    processor instanceof LaminarSpanProcessor &&\n    laminarCtx.spanPath &&\n    laminarCtx.spanIdsPath\n  ) {\n    processor.setParentPathInfo(\n      otelCtx.spanId,\n      laminarCtx.spanPath,\n      laminarCtx.spanIdsPath,\n    );\n  }\n\n  // Base the restored parent on ROOT_CONTEXT, NOT `getContext()`. On the worker\n  // side an activity has no legitimate ambient parent, and `getContext()` falls\n  // back to the process-global active-span stack when the ALS stack is empty —\n  // basing on it would let an unrelated worker-thread span's baggage /\n  // association properties leak into the restored remote context.\n  const base = trace.setSpan(ROOT_CONTEXT, trace.wrapSpanContext(otelCtx));\n  const enriched = LaminarContextManager.setRawAssociationProperties(\n    laminarCtx,\n    base,\n  );\n  LaminarContextManager.pushContext(enriched);\n  return enriched;\n};\n","import { errorMessage } from \"@lmnr-ai/types\";\nimport { context as contextApi, ROOT_CONTEXT } from \"@opentelemetry/api\";\n\nimport { Laminar } from \"../../../laminar\";\nimport { initializeLogger } from \"../../../utils\";\nimport { LaminarContextManager } from \"../../tracing/context\";\nimport { LaminarSpan } from \"../../tracing/span\";\nimport { buildHeaders, restoreContextFromHeaders } from \"./helpers\";\n\n/**\n * Options for Laminar Temporal interceptors.\n */\nexport interface LaminarTemporalInterceptorOptions {\n  /**\n   * Whether the activity inbound interceptor should wrap each activity\n   * execution in a Laminar span named after the activity type.\n   *\n   * Defaults to `true`. Set to `false` if you want only context restoration\n   * (letting your own `observe()` calls act as roots inside the activity).\n   */\n  createActivitySpan?: boolean;\n\n  /**\n   * Whether to record the activity's arguments as the span input.\n   *\n   * Defaults to `true`. Set to `false` to omit potentially large or sensitive\n   * activity arguments from the span. Ignored when `createActivitySpan` is\n   * `false`.\n   */\n  recordActivityArgs?: boolean;\n\n  /**\n   * Whether to record the activity's return value as the span output.\n   *\n   * Defaults to `true`. Set to `false` to omit potentially large or sensitive\n   * activity results from the span. Ignored when `createActivitySpan` is\n   * `false`.\n   */\n  recordActivityOutput?: boolean;\n}\n\n// Inject Laminar span-context headers and forward, preserving input/output types.\n// T is unconstrained so Temporal's concrete input types (some of which lack a\n// `headers` field entirely) are accepted without an index-signature requirement.\nconst withLaminarHeaders = async <T, R>(\n  input: T,\n  next: (i: T) => Promise<R>,\n): Promise<R> => {\n  const existing = (input as { headers?: Record<string, unknown> }).headers;\n  return next({\n    ...(input as object),\n    headers: buildHeaders(existing ?? {}),\n  } as T);\n};\n\nconst withLaminarHeadersIterable = <T, R>(\n  input: T,\n  next: (i: T) => AsyncIterable<R>,\n): AsyncIterable<R> => {\n  const existing = (input as { headers?: Record<string, unknown> }).headers;\n  return next({\n    ...(input as object),\n    headers: buildHeaders(existing ?? {}),\n  } as T);\n};\n\n// ─── WorkflowClientInterceptor ────────────────────────────────────────────────\n\n/**\n * Temporal client-side workflow interceptor. Injects the active Laminar span context\n * into every workflow-start / signal / query / update-start call via headers.\n *\n * **Explicit usage:**\n * ```typescript\n * const client = new Client({\n *   interceptors: {\n *     workflow: [new LaminarTemporalInterceptors.WorkflowClientInterceptor()],\n *   },\n * });\n * ```\n */\nexport class WorkflowClientInterceptor {\n  async start<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async startWithDetails<T, R>(\n    input: T,\n    next: (i: T) => Promise<R>,\n  ): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async startUpdate<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async startUpdateWithStart<T, R>(\n    input: T,\n    next: (i: T) => Promise<R>,\n  ): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async signal<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async signalWithStart<T, R>(\n    input: T,\n    next: (i: T) => Promise<R>,\n  ): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async query<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async terminate<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async describe<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n}\n\n// ─── ScheduleClientInterceptor ────────────────────────────────────────────────\n\n/**\n * Temporal client-side schedule interceptor.\n *\n * Deliberately a no-op: it does NOT inject Laminar trace headers on schedule\n * `create`. A Schedule is a long-lived server-side object, and the headers\n * attached to its workflow-start action are a stored template replayed on every\n * triggered run — runs that may fire hours or days later. Injecting the active\n * span at creation time would pin every future scheduled run to that single,\n * long-dead parent trace instead of letting each run start its own root trace.\n * Temporal exposes no per-run client-side hook to inject fresh context, so the\n * correct behavior is to forward unchanged and let each triggered workflow be\n * its own root.\n *\n * Kept as a registered interceptor (rather than omitted) so the wiring stays\n * explicit and stable, and so future per-run context support has a home.\n *\n * **Explicit usage:**\n * ```typescript\n * const client = new Client({\n *   interceptors: {\n *     schedule: [new LaminarTemporalInterceptors.ScheduleClientInterceptor()],\n *   },\n * });\n * ```\n */\nexport class ScheduleClientInterceptor {\n  async create<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return next(input);\n  }\n}\n\n/**\n * Warning: Standalone Activities are experimental in Temporal. If the API changes,\n * this interceptor may not work as expected.\n * Temporal client-side activity interceptor. Injects the active Laminar span context\n * into every activity start / terminate call via headers.\n *\n * **Explicit usage:**\n * ```typescript\n * const client = new Client({\n *   interceptors: {\n *     schedule: [new LaminarTemporalInterceptors.ScheduleClientInterceptor()],\n *   },\n * });\n * ```\n */\nexport class ActivityClientInterceptor {\n  async start<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async getResult<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async describe<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async cancel<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  async terminate<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n\n  list<T, R>(input: T, next: (i: T) => AsyncIterable<R>): AsyncIterable<R> {\n    return withLaminarHeadersIterable(input, next);\n  }\n\n  async count<T, R>(input: T, next: (i: T) => Promise<R>): Promise<R> {\n    return withLaminarHeaders(input, next);\n  }\n}\n\n// ─── ActivityInboundInterceptor ───────────────────────────────────────────────\n\n/**\n * Temporal worker-side interceptor. Reads the Laminar span context from\n * Temporal headers and restores it as the parent context before each activity\n * executes. When `createActivitySpan` is `true` (default), also wraps the\n * activity in a Laminar span named after the activity type.\n *\n * **Explicit usage:**\n * ```typescript\n * const worker = await Worker.create({\n *   interceptors: {\n *     activityInbound: [\n *       () => new LaminarTemporalInterceptors.ActivityInboundInterceptor(),\n *     ],\n *   },\n * });\n * ```\n */\nclass ActivityInboundInterceptor {\n  readonly createActivitySpan: boolean;\n  readonly recordActivityArgs: boolean;\n  readonly recordActivityOutput: boolean;\n  readonly activityType: string | undefined;\n  readonly logger;\n\n  constructor(\n    options: LaminarTemporalInterceptorOptions = {},\n    activityContext?: any,\n  ) {\n    this.createActivitySpan = options.createActivitySpan ?? true;\n    this.recordActivityArgs = options.recordActivityArgs ?? true;\n    this.recordActivityOutput = options.recordActivityOutput ?? true;\n    this.activityType = activityContext?.info?.activityType;\n    this.logger = initializeLogger();\n  }\n\n  execute = async <\n    T extends { headers: Record<string, unknown> | undefined; args: unknown[] },\n    R,\n  >(\n    input: T,\n    next: (i: T) => Promise<R>,\n  ): Promise<R> =>\n    // Wrap the entire execution in an isolated ALS scope seeded with an\n    // explicit ROOT_CONTEXT. An activity's only legitimate parent is the remote\n    // context carried in its headers — never the worker thread's ambient stack.\n    // We seed `[ROOT_CONTEXT]` rather than `[]` because `getContext()` falls\n    // through to the process-global active-span stack when the ALS stack is\n    // EMPTY (see `LaminarContextManager.getContext`); a single ROOT entry makes\n    // the lookup short-circuit at root, so when header restoration fails the\n    // activity runs detached instead of attaching to an unrelated in-process\n    // trace left on the worker's async lineage.\n    LaminarContextManager.runWithIsolatedContext([ROOT_CONTEXT], async () => {\n      const restored = restoreContextFromHeaders(input.headers);\n      if (!restored) {\n        return next(input);\n      }\n\n      // When we don't create our own activity span, the remote parent is only\n      // on Laminar's ALS stack — so `observe()` / `Laminar.startActiveSpan()`\n      // nest correctly, but OTel-aware auto-instrumentations (OpenAI, etc.)\n      // read the standard OTel context (`context.active()`), which is still\n      // ROOT here, and would start detached root traces. Activate the restored\n      // OTel context for the activity body so those spans nest under the\n      // remote parent too.\n      if (!this.createActivitySpan) {\n        return contextApi.with(restored.otelContext, () => next(input));\n      }\n\n      const activityName = this.activityType ?? \"temporal.activity\";\n\n      const span = Laminar.startSpan({\n        name: activityName,\n        parentSpanContext: restored.laminarCtx,\n        input: this.recordActivityArgs ? input.args : undefined,\n      });\n\n      return Laminar.withSpan(\n        span,\n        async () => {\n          const res = await next(input);\n          if (this.recordActivityOutput) {\n            try {\n              (span as LaminarSpan).setOutput(res);\n            } catch (e) {\n              this.logger.debug(\n                `failed to set output to activity span: ${errorMessage(e)}`,\n              );\n            }\n          }\n          return res;\n        },\n        true,\n      );\n    });\n}\n\nexport const ActivityInterceptorFactory =\n  (options?: LaminarTemporalInterceptorOptions) => (ctx: any) => ({\n    inbound: new ActivityInboundInterceptor(options, ctx),\n  });\n","import { errorMessage } from \"@lmnr-ai/types\";\nimport { type Span } from \"@opentelemetry/api\";\n\nimport { Laminar } from \"../../../laminar\";\nimport { initializeLogger } from \"../../../utils\";\nimport { LaminarSpan } from \"../../tracing/span\";\n\nconst logger = initializeLogger();\n\n// Minimal structural view of the WorkflowClient methods we patch. The real\n// types live in @temporalio/client, which is a soft peer-dep we don't import.\ninterface WorkflowClientLike {\n  prototype: {\n    start: (...args: unknown[]) => Promise<WorkflowHandleLike>;\n    execute: (...args: unknown[]) => Promise<unknown>;\n    signalWithStart: (...args: unknown[]) => Promise<WorkflowHandleLike>;\n  };\n}\n\ninterface WorkflowHandleLike {\n  result: (...args: unknown[]) => Promise<unknown>;\n  cancel: (...args: unknown[]) => Promise<unknown>;\n  terminate: (...args: unknown[]) => Promise<unknown>;\n}\n\nconst _patchedWorkflowClients = new WeakSet<object>();\n\n// `start(workflowTypeOrFunc, options)`: derive a span name from the workflow\n// type and read the workflow arguments from `options.args`.\nconst workflowName = (args: unknown[]): string => {\n  const wf = args[0];\n  if (typeof wf === \"string\") {\n    return wf;\n  }\n  const name = (wf as { name?: string } | undefined)?.name;\n  return name && name.length > 0 ? name : \"temporal.workflow\";\n};\n\nconst workflowArgs = (args: unknown[]): unknown[] | undefined =>\n  (args[1] as { args?: unknown[] } | undefined)?.args;\n\n// Wrap a workflow handle so the lifecycle span (started at `start()`) ends on\n// the FIRST terminal call — `result()` resolving/rejecting, `cancel()`, or\n// `terminate()`. For cancel/terminate we additionally record a dedicated child\n// span. The `closed` guard ensures the workflow span is ended exactly once even\n// when callers follow the canonical `cancel()` → `result()` pattern.\nconst wrapHandle = (handle: WorkflowHandleLike, span: Span): void => {\n  let closed = false;\n  const closeWith = (finalize: () => void): void => {\n    if (closed) {\n      return;\n    }\n    closed = true;\n    finalize();\n    span.end();\n  };\n\n  const origResult = handle.result.bind(handle);\n  const origCancel = handle.cancel.bind(handle);\n  const origTerminate = handle.terminate.bind(handle);\n\n  const childSpanContext = (): string | undefined => {\n    try {\n      return Laminar.serializeLaminarSpanContext(span) ?? undefined;\n    } catch (e) {\n      logger.debug(\n        `failed to derive workflow child span parent: ${errorMessage(e)}`,\n      );\n      return undefined;\n    }\n  };\n\n  handle.result = async (...args: unknown[]): Promise<unknown> => {\n    if (closed) {\n      return origResult(...args);\n    }\n    try {\n      const res = await origResult(...args);\n      closeWith(() => {\n        try {\n          (span as LaminarSpan).setOutput(res);\n        } catch (e) {\n          logger.debug(\n            `failed to set workflow span output: ${errorMessage(e)}`,\n          );\n        }\n      });\n      return res;\n    } catch (e) {\n      closeWith(() => span.recordException(e as Error));\n      throw e;\n    }\n  };\n\n  const wrapTerminating =\n    (name: string, orig: (...args: unknown[]) => Promise<unknown>) =>\n    async (...args: unknown[]): Promise<unknown> => {\n      if (closed) {\n        return orig(...args);\n      }\n      const childSpan = Laminar.startSpan({\n        name,\n        parentSpanContext: childSpanContext(),\n      });\n      try {\n        const res = await orig(...args);\n        childSpan.end();\n        closeWith(() => {\n          /* intentionally empty */\n        });\n        return res;\n      } catch (e) {\n        childSpan.recordException(e as Error);\n        childSpan.end();\n        closeWith(() => span.recordException(e as Error));\n        throw e;\n      }\n    };\n\n  handle.cancel = wrapTerminating(\"temporal.workflow.cancel\", origCancel);\n  handle.terminate = wrapTerminating(\n    \"temporal.workflow.terminate\",\n    origTerminate,\n  );\n};\n\n/**\n * Patch `WorkflowClient.prototype` so a Laminar workflow span tracks each\n * workflow's client-side lifecycle: it starts when `start()` / `signalWithStart()`\n * / `execute()` is called and ends when the workflow completes (`result()`\n * resolves) or is cancelled / terminated.\n *\n * The span is kept active for the duration of the start RPC so that\n * `WorkflowClientInterceptor.start` injects the workflow span's context into the\n * Temporal headers — that is what makes the worker-side workflow and its\n * activities nest under this span.\n *\n * Idempotent — patching the same module object more than once is a no-op.\n */\nexport const patchWorkflowClient = (clientModule: {\n  WorkflowClient?: WorkflowClientLike;\n}): void => {\n  const WorkflowClient = clientModule.WorkflowClient;\n  if (\n    !WorkflowClient?.prototype ||\n    _patchedWorkflowClients.has(WorkflowClient)\n  ) {\n    return;\n  }\n  _patchedWorkflowClients.add(WorkflowClient);\n\n  const proto = WorkflowClient.prototype;\n  const origStart = proto.start;\n  const origExecute = proto.execute;\n  const origSignalWithStart = proto.signalWithStart;\n\n  // start / signalWithStart return a handle; keep the span open and hand it to\n  // wrapHandle so a later terminal call ends it.\n  const patchStartLike = (\n    orig: (...args: unknown[]) => Promise<WorkflowHandleLike>,\n  ) =>\n    async function (\n      this: unknown,\n      ...args: unknown[]\n    ): Promise<WorkflowHandleLike> {\n      const span = Laminar.startSpan({\n        name: workflowName(args),\n        input: workflowArgs(args),\n      });\n      try {\n        const handle = await Laminar.withSpan(\n          span,\n          () => orig.apply(this, args),\n          false,\n        );\n        wrapHandle(handle, span);\n        return handle;\n      } catch (e) {\n        // withSpan already recorded the exception on the span.\n        span.end();\n        throw e;\n      }\n    };\n\n  proto.start = patchStartLike(origStart);\n  proto.signalWithStart = patchStartLike(origSignalWithStart);\n\n  // execute() starts the workflow and awaits its result in one call, so the\n  // whole span lifecycle is local to this method.\n  proto.execute = async function (\n    this: unknown,\n    ...args: unknown[]\n  ): Promise<unknown> {\n    const span = Laminar.startSpan({\n      name: workflowName(args),\n      input: workflowArgs(args),\n    });\n    try {\n      const res = await Laminar.withSpan(\n        span,\n        () => origExecute.apply(this, args),\n        false,\n      );\n      try {\n        (span as LaminarSpan).setOutput(res);\n      } catch (e) {\n        logger.debug(`failed to set workflow span output: ${errorMessage(e)}`);\n      }\n      span.end();\n      return res;\n    } catch (e) {\n      span.end();\n      throw e;\n    }\n  };\n};\n","/**\n * Laminar Temporal interceptors for distributed trace context propagation.\n *\n * Usage — Option A (explicit, always works):\n *\n * ```typescript\n * import { LaminarTemporalInterceptors } from '@lmnr-ai/lmnr';\n * import { Worker } from '@temporalio/worker';\n * import { Client } from '@temporalio/client';\n *\n * const worker = await Worker.create({\n *   interceptors: {\n *     activity: [LaminarTemporalInterceptors.ActivityInterceptorFactory()],\n *     workflowModules: [require.resolve('@lmnr-ai/lmnr/temporal-workflow-interceptors')],\n *   },\n *   // ...\n * });\n *\n * const client = new Client({\n *   interceptors: {\n *     workflow: [new LaminarTemporalInterceptors.WorkflowClientInterceptor()],\n *     activity: [new LaminarTemporalInterceptors.ActivityClientInterceptor()],\n *     schedule: [new LaminarTemporalInterceptors.ScheduleClientInterceptor()],\n *   },\n * });\n * ```\n *\n * Usage — Option B (auto-patch via instrumentModules):\n *\n * In Temporal, the worker and client typically run in separate processes\n * (separate entry-point files). Call `Laminar.initialize()` in each file,\n * passing only the module that belongs to that process:\n *\n * worker.ts:\n * ```typescript\n * import * as temporalWorker from '@temporalio/worker';\n * import { Laminar } from '@lmnr-ai/lmnr';\n *\n * Laminar.initialize({\n *   instrumentModules: { temporal: { worker: temporalWorker } },\n * });\n *\n * // Worker.create() now automatically includes Laminar activity interceptors\n * // and the workflow interceptor module.\n * const worker = await temporalWorker.Worker.create({ ... });\n * ```\n *\n * NOTE: if the worker is created with a pre-built `workflowBundle`, Temporal\n * ignores `interceptors.workflowModules`, so the workflow interceptor cannot be\n * auto-injected. Register it at bundle time instead:\n * ```typescript\n * await bundleWorkflowCode({\n *   workflowsPath: require.resolve('./workflows'),\n *   workflowInterceptorModules: [\n *     require.resolve('@lmnr-ai/lmnr/temporal-workflow-interceptors'),\n *   ],\n * });\n * ```\n *\n * client.ts:\n * ```typescript\n * import * as temporalClient from '@temporalio/client';\n * import { Laminar } from '@lmnr-ai/lmnr';\n *\n * Laminar.initialize({\n *   instrumentModules: { temporal: { client: temporalClient } },\n * });\n *\n * // new temporalClient.Client() now automatically includes Laminar interceptors.\n * const client = new temporalClient.Client({ ... });\n * ```\n */\n\nimport { initializeLogger } from \"../../../utils\";\nimport {\n  ActivityClientInterceptor,\n  ActivityInterceptorFactory,\n  LaminarTemporalInterceptorOptions,\n  ScheduleClientInterceptor,\n  WorkflowClientInterceptor,\n} from \"./interceptors\";\nimport { patchWorkflowClient } from \"./workflow-span\";\n\nexport { patchWorkflowClient } from \"./workflow-span\";\n\nconst logger = initializeLogger();\n\n// ─── Auto-patch helpers ───────────────────────────────────────────────────────\n\nconst _patchedWorkerModules = new WeakSet<object>();\nconst _patchedClientModules = new WeakSet<object>();\n\nlet _warnedWorkflowBundleOnce = false;\n\n// Temporal ignores `interceptors.workflowModules` whenever a pre-built\n// `workflowBundle` is supplied — the bundle is produced before `Worker.create`\n// runs, so there is no hook for us to inject the Laminar workflow interceptor\n// after the fact (see @temporalio/worker WorkerOptions.workflowBundle /\n// .interceptors docs). When that happens the workflow-side outbound header\n// propagation never runs, so trace headers from workflow start are not\n// forwarded to activities / child workflows scheduled from inside the workflow.\n// Warn once with the exact bundle-time fix instead of silently injecting a\n// module Temporal will drop.\nconst warnWorkflowBundleOnce = (): void => {\n  if (_warnedWorkflowBundleOnce) {\n    return;\n  }\n  _warnedWorkflowBundleOnce = true;\n  logger.warn(\n    \"[Laminar] Temporal Worker.create was called with a pre-built \" +\n      \"`workflowBundle`; Temporal ignores `interceptors.workflowModules` in \" +\n      \"that case, so Laminar's workflow interceptor cannot be auto-injected. \" +\n      \"Trace context from workflow start will NOT propagate to activities or \" +\n      \"child workflows scheduled inside the workflow. Register the interceptor \" +\n      \"at bundle time: bundleWorkflowCode({ workflowInterceptorModules: \" +\n      \"[require.resolve('@lmnr-ai/lmnr/temporal-workflow-interceptors')], ... }).\",\n  );\n};\n\n/**\n * Patch a `@temporalio/worker` module object so that every `Worker.create()`\n * call automatically includes `ActivityInboundInterceptor`.\n *\n * Idempotent — calling with the same module object more than once is a no-op.\n *\n * Called by `manuallyInitInstrumentations` when\n * `instrumentModules.temporal.worker` is provided.\n */\nexport const patchTemporalWorker = (\n  workerModule: {\n    Worker: { create: (...args: unknown[]) => Promise<unknown> };\n  },\n  options: LaminarTemporalInterceptorOptions = {},\n): void => {\n  if (_patchedWorkerModules.has(workerModule)) {\n    return;\n  }\n  _patchedWorkerModules.add(workerModule);\n\n  const originalCreate = workerModule.Worker.create.bind(workerModule.Worker);\n\n  workerModule.Worker.create = async (...args: unknown[]) => {\n    const [rawOpts, ...rest] = args as [\n      {\n        workflowBundle?: unknown;\n        interceptors?: {\n          activity: ((options: LaminarTemporalInterceptorOptions) => (\n            ctx: any,\n          ) => {\n            inbound: any;\n          })[];\n          [k: string]: unknown;\n        };\n        [k: string]: unknown;\n      },\n      ...unknown[],\n    ];\n\n    // Temporal ignores `interceptors.workflowModules` when a pre-built\n    // `workflowBundle` is supplied (the bundle is already compiled), so we must\n    // NOT inject it there — the user has to register it at bundle time. Warn\n    // once and leave the workflow interceptors untouched.\n    const usesWorkflowBundle = rawOpts?.workflowBundle != null;\n    if (usesWorkflowBundle) {\n      warnWorkflowBundleOnce();\n    }\n\n    const interceptors: Record<string, unknown> = {\n      ...rawOpts?.interceptors,\n      activity: [\n        ActivityInterceptorFactory(options),\n        ...(rawOpts?.interceptors?.activity ?? []),\n      ],\n    };\n\n    if (!usesWorkflowBundle) {\n      interceptors.workflowModules = [\n        require.resolve(\"@lmnr-ai/lmnr/temporal-workflow-interceptors\"),\n        ...((rawOpts?.interceptors?.workflowModules as string[] | undefined) ??\n          []),\n      ];\n    }\n\n    const patched = {\n      ...rawOpts,\n      interceptors,\n    };\n\n    return originalCreate(patched, ...rest);\n  };\n};\n\n/**\n * Patch a `@temporalio/client` module object so that every `new Client()`\n * call automatically includes `WorkflowClientInterceptor`.\n *\n * Mutates `clientModule.Client` in place so any code that reads `Client`\n * from the module after `Laminar.initialize()` gets the patched class\n * automatically.\n *\n * Idempotent — calling with the same module object more than once is a no-op.\n *\n * Called by `manuallyInitInstrumentations` when\n * `instrumentModules.temporal.client` is provided.\n */\nexport const patchTemporalClient = (clientModule: {\n  Client: new (...args: unknown[]) => unknown;\n  WorkflowClient?: { prototype: any };\n}): void => {\n  if (_patchedClientModules.has(clientModule)) {\n    return;\n  }\n  _patchedClientModules.add(clientModule);\n\n  // Patch WorkflowClient.prototype so a workflow span tracks each workflow's\n  // client-side lifecycle (start → result / cancel / terminate). The high-level\n  // `Client` constructs its `workflow` sub-client from this same WorkflowClient\n  // class, so patching the prototype covers both `new Client()` and direct\n  // `new WorkflowClient()` usage.\n  patchWorkflowClient(clientModule);\n\n  const OriginalClient = clientModule.Client;\n\n  type ClientOptions = {\n    interceptors?: {\n      workflow?: WorkflowClientInterceptor[];\n      activity?: ActivityClientInterceptor[];\n      schedule?: ScheduleClientInterceptor[];\n      [k: string]: unknown;\n    };\n    [k: string]: unknown;\n  };\n\n  clientModule.Client =\n    class LaminarTemporalClient extends (OriginalClient as new (\n      opts?: ClientOptions,\n    ) => any) {\n      constructor(opts?: ClientOptions) {\n        super({\n          ...opts,\n          interceptors: {\n            ...opts?.interceptors,\n            workflow: [\n              new WorkflowClientInterceptor(),\n              ...(opts?.interceptors?.workflow ?? []),\n            ],\n            activity: [\n              new ActivityClientInterceptor(),\n              ...(opts?.interceptors?.activity ?? []),\n            ],\n            schedule: [\n              new ScheduleClientInterceptor(),\n              ...(opts?.interceptors?.schedule ?? []),\n            ],\n          },\n        });\n      }\n    } as unknown as new (\n      ...args: unknown[]\n    ) => unknown;\n};\n\n// ─── Convenience namespace ────────────────────────────────────────────────────\n\n/** Namespace export: `LaminarTemporalInterceptors.WorkflowClientInterceptor`. */\nexport const LaminarTemporalInterceptors = {\n  WorkflowClientInterceptor,\n  ScheduleClientInterceptor,\n  ActivityClientInterceptor,\n  ActivityInterceptorFactory,\n};\n","import { SpanStatusCode } from \"@opentelemetry/api\";\n\nimport { LaminarSpan } from \"../../tracing/span\";\n\nconst safeSetAttribute = (\n  span: LaminarSpan,\n  key: string,\n  value: unknown,\n): void => {\n  if (value === null || value === undefined) return;\n  if (typeof value === \"string\" && value.length === 0) return;\n  span.setAttribute(key, value as any);\n};\n\nexport const recordError = (span: LaminarSpan, error: unknown): void => {\n  span.setAttribute(\n    \"error.type\",\n    (error as Error)?.constructor?.name ?? \"Error\",\n  );\n  span.recordException(error as Error);\n  span.setStatus({ code: SpanStatusCode.ERROR });\n};\n\nexport const setRequestAttributes = (\n  span: LaminarSpan,\n  request: any,\n  defaultModel: string | undefined,\n  traceContent: boolean,\n): void => {\n  safeSetAttribute(\n    span,\n    \"gen_ai.request.model\",\n    request?.model ?? defaultModel,\n  );\n  if (!traceContent) return;\n\n  const state = request?.state;\n  if (state !== null && state !== undefined) {\n    const content = typeof state === \"string\" ? state : JSON.stringify(state);\n    safeSetAttribute(\n      span,\n      \"gen_ai.input.messages\",\n      JSON.stringify([{ role: \"user\", content }]),\n    );\n  }\n  const questions = request?.questions;\n  if (questions && Object.keys(questions).length > 0) {\n    safeSetAttribute(\n      span,\n      \"gen_ai.request.structured_output_schema\",\n      JSON.stringify(questions),\n    );\n  }\n};\n\n/** `body` is the raw `/v1/systemone` JSON: `{ model, usage, answers }`. */\nexport const setResponseAttributes = (\n  span: LaminarSpan,\n  body: any,\n  traceContent: boolean,\n): void => {\n  if (!body) return;\n  safeSetAttribute(span, \"gen_ai.response.model\", body.model);\n  safeSetAttribute(span, \"gen_ai.usage.input_tokens\", body.usage?.input_tokens);\n  safeSetAttribute(\n    span,\n    \"gen_ai.usage.output_tokens\",\n    body.usage?.output_tokens,\n  );\n  if (body.answers && traceContent) {\n    safeSetAttribute(\n      span,\n      \"gen_ai.output.messages\",\n      JSON.stringify([\n        { role: \"assistant\", content: JSON.stringify(body.answers) },\n      ]),\n    );\n  }\n};\n","import { context, diag, trace } from \"@opentelemetry/api\";\nimport { isTracingSuppressed } from \"@opentelemetry/core\";\nimport {\n  InstrumentationBase,\n  InstrumentationModuleDefinition,\n  InstrumentationNodeModuleDefinition,\n} from \"@opentelemetry/instrumentation\";\n\nimport { version as SDK_VERSION } from \"../../../../package.json\";\nimport { Laminar } from \"../../../laminar\";\nimport { LaminarSpan } from \"../../tracing/span\";\nimport {\n  recordError,\n  setRequestAttributes,\n  setResponseAttributes,\n} from \"./utils\";\n\nconst PATCH_STATE_SYMBOL = Symbol(\"lmnr.typesafe.patch-state\");\n\ntype PatchState = {\n  traceContent: boolean;\n  systemOne: (...args: any[]) => any;\n};\n\nexport class TypeSafeInstrumentation extends InstrumentationBase {\n  private traceContent: boolean;\n\n  constructor(config?: { traceContent?: boolean }) {\n    super(\"@lmnr/typesafe-instrumentation\", SDK_VERSION, { enabled: true });\n    this.traceContent = config?.traceContent ?? true;\n  }\n\n  protected init(): InstrumentationModuleDefinition {\n    return new InstrumentationNodeModuleDefinition(\n      \"@typesafe-ai/sdk\",\n      [\">=0.1.0\"],\n      this.patch.bind(this),\n      this.unpatch.bind(this),\n    );\n  }\n\n  public manuallyInstrument(typeSafeModule: any): void {\n    diag.debug(\"Manually instrumenting @typesafe-ai/sdk\");\n    const TypeSafeClientClass = this.resolveClientClass(typeSafeModule);\n    if (TypeSafeClientClass) {\n      this.patchClientClass(TypeSafeClientClass);\n    } else {\n      diag.warn(\n        \"Could not find TypeSafeClient class in typesafe manual instrumentation input. \" +\n          \"Pass either the TypeSafeClient class or the module object with a TypeSafeClient export.\",\n      );\n    }\n  }\n\n  private patch(moduleExports: any): any {\n    diag.debug(\"Patching @typesafe-ai/sdk\");\n    const TypeSafeClientClass = this.resolveClientClass(moduleExports);\n    if (TypeSafeClientClass) {\n      this.patchClientClass(TypeSafeClientClass);\n    }\n    return moduleExports;\n  }\n\n  private unpatch(moduleExports: any): void {\n    diag.debug(\"Unpatching @typesafe-ai/sdk\");\n    const TypeSafeClientClass = this.resolveClientClass(moduleExports);\n    if (TypeSafeClientClass) {\n      this.unpatchClientClass(TypeSafeClientClass);\n    }\n  }\n\n  private resolveClientClass(moduleOrClass: any): any {\n    if (typeof moduleOrClass === \"function\") {\n      return moduleOrClass;\n    }\n    if (typeof moduleOrClass?.TypeSafeClient === \"function\") {\n      return moduleOrClass.TypeSafeClient;\n    }\n    return undefined;\n  }\n\n  private patchClientClass(TypeSafeClientClass: any): void {\n    const proto = TypeSafeClientClass.prototype;\n    const existing = proto[PATCH_STATE_SYMBOL] as PatchState | undefined;\n    if (existing) {\n      existing.traceContent = this.traceContent;\n      return;\n    }\n    if (typeof proto.systemOne !== \"function\") {\n      diag.warn(\"Could not patch TypeSafeClient.prototype.systemOne.\");\n      return;\n    }\n\n    const state: PatchState = {\n      traceContent: this.traceContent,\n      systemOne: proto.systemOne,\n    };\n    proto[PATCH_STATE_SYMBOL] = state;\n    proto.systemOne = wrapSystemOne(state);\n  }\n\n  private unpatchClientClass(TypeSafeClientClass: any): void {\n    const proto = TypeSafeClientClass.prototype;\n    const state = proto[PATCH_STATE_SYMBOL] as PatchState | undefined;\n    if (!state) return;\n\n    proto.systemOne = state.systemOne;\n    delete proto[PATCH_STATE_SYMBOL];\n  }\n}\n\nconst wrapSystemOne = (state: PatchState) =>\n  function (this: any, request: any, options?: any) {\n    const original = state.systemOne;\n    if (isTracingSuppressed(context.active())) {\n      return original.call(this, request, options);\n    }\n\n    const { traceContent } = state;\n    const span = Laminar.startSpan({\n      name: \"typesafe.system_one\",\n      spanType: \"LLM\",\n    }) as LaminarSpan;\n    span.setAttribute(\"gen_ai.system\", \"typesafe\");\n    setRequestAttributes(span, request, this?.defaultModel, traceContent);\n\n    // `systemOne` returns an APIPromise whose `then` triggers the SDK's body\n    // parse, and `asResponse()` hands the caller the same Response object. So\n    // the wrapper must return the promise untouched (no async/await, no\n    // Laminar.withSpan promise chaining) and record from a clone of the raw\n    // response, which the SDK has already buffered.\n    let promise: any;\n    try {\n      promise = context.with(trace.setSpan(context.active(), span), () =>\n        original.call(this, request, options),\n      );\n    } catch (error) {\n      // Synchronous request validation, e.g. an empty questions map.\n      recordError(span, error);\n      span.end();\n      throw error;\n    }\n\n    const onError = (error: unknown) => {\n      recordError(span, error);\n      span.end();\n    };\n    // Recording must never break the caller: any surprise from a future\n    // APIPromise shape degrades to a span without response attributes.\n    try {\n      if (typeof promise?.asResponse === \"function\") {\n        promise.asResponse().then(async (response: Response) => {\n          try {\n            setResponseAttributes(\n              span,\n              await response.clone().json(),\n              traceContent,\n            );\n          } catch {\n            // Leave the span without response attributes.\n          }\n          span.end();\n        }, onError);\n      } else if (typeof promise?.then === \"function\") {\n        // Defensive: a parsed result has the same shape as the raw body.\n        promise.then((result: any) => {\n          setResponseAttributes(span, result, traceContent);\n          span.end();\n        }, onError);\n      } else {\n        span.end();\n      }\n    } catch {\n      span.end();\n    }\n    return promise;\n  };\n","import { LaminarClient } from \"@lmnr-ai/client\";\nimport { SessionRecordingOptions } from \"@lmnr-ai/types\";\nimport { Instrumentation } from \"@opentelemetry/instrumentation\";\nimport { AnthropicInstrumentation } from \"@traceloop/instrumentation-anthropic\";\nimport { BedrockInstrumentation } from \"@traceloop/instrumentation-bedrock\";\nimport { ChromaDBInstrumentation } from \"@traceloop/instrumentation-chromadb\";\nimport { CohereInstrumentation } from \"@traceloop/instrumentation-cohere\";\nimport { LangChainInstrumentation } from \"@traceloop/instrumentation-langchain\";\nimport { OpenAIInstrumentation } from \"@traceloop/instrumentation-openai\";\nimport { PineconeInstrumentation } from \"@traceloop/instrumentation-pinecone\";\nimport { QdrantInstrumentation } from \"@traceloop/instrumentation-qdrant\";\nimport { TogetherInstrumentation } from \"@traceloop/instrumentation-together\";\n\nimport { PlaywrightInstrumentation } from \"../../browser\";\nimport { PuppeteerInstrumentation } from \"../../browser/puppeteer\";\nimport { StagehandV2Instrumentation } from \"../../browser/stagehand/v2\";\nimport { StagehandInstrumentation as StagehandV3Instrumentation } from \"../../browser/stagehand/v3\";\nimport { initializeLogger } from \"../../utils\";\nimport { ClaudeAgentSDKInstrumentation } from \"../instrumentation/claude-agent-sdk\";\nimport { GoogleGenAiInstrumentation } from \"../instrumentation/google-genai\";\nimport { KernelInstrumentation } from \"../instrumentation/kernel\";\nimport { OpenAIAgentsInstrumentation } from \"../instrumentation/openai-agents\";\nimport { OpencodeInstrumentation } from \"../instrumentation/opencode\";\nimport { OpenRouterInstrumentation } from \"../instrumentation/openrouter\";\nimport {\n  patchTemporalClient,\n  patchTemporalWorker,\n} from \"../instrumentation/temporal\";\nimport { TypeSafeInstrumentation } from \"../instrumentation/typesafe\";\nimport { InitializeOptions } from \"../interfaces\";\n\nconst logger = initializeLogger();\n\n/**\n * Initialize and return Laminar instrumentations.\n * Useful to use with libraries that initialize tracing and can register passed\n * instrumentations.\n *\n * @param options\n * @param {string} options.baseUrl - Base URL of the Laminar API.\n * @param {string} options.apiKey - Laminar project API key. If not provided, will use\n * the LMNR_PROJECT_API_KEY environment variable.\n * @param {number} options.httpPort - Laminar API http port. If not provided, will use\n * the port from the baseUrl or defaults to 443. Only required for Playwright/Puppeteer\n * instrumentations for sending browser sessions.\n * @param {boolean} options.suppressContentTracing - Whether to suppress content tracing.\n * @param {InitializeOptions[\"instrumentModules\"]} options.instrumentModules - Record of modules\n * to instrument.\n * If not provided, all auto-instrumentable modules will be instrumented, which include\n * LLM calls (OpenAI, Anthropic, etc), Langchain, VectorDB calls (Pinecone, Qdrant, etc).\n * Pass an empty object {} to disable any kind of automatic instrumentation.\n * If you only want to auto-instrument specific modules, then pass them in the object.\n *\n * @returns {Instrumentation[]} Array of enabled instrumentations. It is your responsibility\n * to enable them and register them with the OpenTelemetry SDK. For example, you could use\n * registerInstrumentations from the opentelemetry-api to register them.\n */\nexport const initializeLaminarInstrumentations = (\n  options: {\n    baseUrl?: string;\n    apiKey?: string;\n    httpPort?: number;\n    suppressContentTracing?: boolean;\n    instrumentModules?: InitializeOptions[\"instrumentModules\"];\n    sessionRecordingOptions?: SessionRecordingOptions;\n  } = {},\n) => {\n  const apiKey = options.apiKey ?? process.env.LMNR_PROJECT_API_KEY;\n\n  // Only create client if we have an API key. That is, only send browser\n  // session events to Laminar backend, but not other OTEL backends.\n  let client: LaminarClient | undefined;\n  if (apiKey) {\n    const url =\n      options.baseUrl ?? process?.env?.LMNR_BASE_URL ?? \"https://api.lmnr.ai\";\n    const port =\n      options.httpPort ??\n      (url.match(/:\\d{1,5}$/g)\n        ? parseInt(url.match(/:\\d{1,5}$/g)![0].slice(1))\n        : 443);\n    const urlWithoutSlash = url.replace(/\\/$/, \"\").replace(/:\\d{1,5}$/g, \"\");\n    client = new LaminarClient({\n      baseUrl: `${urlWithoutSlash}:${port}`,\n      projectApiKey: apiKey,\n    });\n  }\n\n  return options?.instrumentModules !== undefined\n    ? manuallyInitInstrumentations(\n        client,\n        options.instrumentModules,\n        options.suppressContentTracing,\n        options.sessionRecordingOptions,\n      )\n    : initInstrumentations(\n        client,\n        options.suppressContentTracing,\n        options.sessionRecordingOptions,\n      );\n};\n\n/**\n * Get the appropriate Stagehand instrumentation based on the installed version.\n * Returns v3 instrumentation for stagehand >= 3.0.0, otherwise v2.\n */\nconst getStagehandInstrumentation = (\n  playwrightInstrumentation: PlaywrightInstrumentation,\n  client: LaminarClient,\n  sessionRecordingOptions?: SessionRecordingOptions,\n): StagehandV2Instrumentation | StagehandV3Instrumentation => {\n  try {\n    // Try to require the stagehand package to get its version\n    // biome-ignore lint/style/noCommonJs: dynamic import to dynamically resolve version\n    const stagehandPkg = require(\"@browserbasehq/stagehand/package.json\");\n    const version = stagehandPkg.version;\n    const majorVersion = parseInt(version.split(\".\")[0], 10);\n\n    if (majorVersion >= 3) {\n      const stagehandInstrumentation = new StagehandV3Instrumentation(\n        sessionRecordingOptions,\n      );\n      stagehandInstrumentation.setClient(client);\n      return stagehandInstrumentation;\n    } else {\n      return new StagehandV2Instrumentation(playwrightInstrumentation);\n    }\n  } catch {\n    // If we can't find the package, default to v3\n  }\n\n  const stagehandInstrumentation = new StagehandV3Instrumentation(\n    sessionRecordingOptions,\n  );\n  stagehandInstrumentation.setClient(client);\n  return stagehandInstrumentation;\n};\n\nconst initInstrumentations = (\n  client: LaminarClient | undefined,\n  suppressContentTracing?: boolean,\n  sessionRecordingOptions?: SessionRecordingOptions,\n): Instrumentation[] => {\n  const enrichTokens = false;\n  const instrumentations: Instrumentation[] = [];\n\n  instrumentations.push(\n    new OpenAIInstrumentation({\n      enrichTokens,\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(\n    new AnthropicInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(\n    new CohereInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(\n    new BedrockInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(new PineconeInstrumentation());\n\n  instrumentations.push(\n    new LangChainInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(\n    new TogetherInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(\n    new ChromaDBInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(\n    new QdrantInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  // Browser instrumentations require a client (API key)\n  if (client) {\n    const playwrightInstrumentation = new PlaywrightInstrumentation(\n      client,\n      sessionRecordingOptions,\n    );\n    instrumentations.push(playwrightInstrumentation);\n\n    instrumentations.push(\n      getStagehandInstrumentation(\n        playwrightInstrumentation,\n        client,\n        sessionRecordingOptions,\n      ),\n    );\n\n    instrumentations.push(\n      new PuppeteerInstrumentation(client, sessionRecordingOptions),\n    );\n  }\n\n  instrumentations.push(\n    new GoogleGenAiInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(new KernelInstrumentation());\n\n  instrumentations.push(new ClaudeAgentSDKInstrumentation());\n\n  instrumentations.push(new OpencodeInstrumentation());\n\n  instrumentations.push(new OpenAIAgentsInstrumentation());\n\n  instrumentations.push(\n    new OpenRouterInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  instrumentations.push(\n    new TypeSafeInstrumentation({\n      traceContent: !suppressContentTracing,\n    }),\n  );\n\n  return instrumentations;\n};\n\nconst manuallyInitInstrumentations = (\n  client: LaminarClient | undefined,\n  instrumentModules: InitializeOptions[\"instrumentModules\"],\n  suppressContentTracing?: boolean,\n  sessionRecordingOptions?: SessionRecordingOptions,\n): Instrumentation[] => {\n  const enrichTokens = false;\n  const instrumentations: Instrumentation[] = [];\n  let playwrightInstrumentation: PlaywrightInstrumentation | undefined;\n\n  if (instrumentModules?.OpenAI && instrumentModules?.openAI) {\n    throw new Error(\n      \"`openAI` is deprecated, but both `OpenAI` and `openAI` are provided. \" +\n        \"Please use `OpenAI` only.\",\n    );\n  }\n\n  if (instrumentModules?.openAI) {\n    const openAIInstrumentation = new OpenAIInstrumentation({\n      enrichTokens,\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(openAIInstrumentation);\n    openAIInstrumentation.manuallyInstrument(instrumentModules.openAI);\n  }\n\n  if (instrumentModules?.OpenAI) {\n    const openAIInstrumentation = new OpenAIInstrumentation({\n      enrichTokens,\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(openAIInstrumentation);\n    openAIInstrumentation.manuallyInstrument(instrumentModules.OpenAI);\n  }\n\n  if (instrumentModules?.anthropic) {\n    const anthropicInstrumentation = new AnthropicInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(anthropicInstrumentation);\n    anthropicInstrumentation.manuallyInstrument(instrumentModules.anthropic);\n  }\n\n  if (instrumentModules?.azureOpenAI) {\n    logger.warn(\n      \"Azure OpenAI instrumentation is no longer supported. Not enabling any instrumentation.\",\n    );\n  }\n\n  if (instrumentModules?.cohere) {\n    const cohereInstrumentation = new CohereInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(cohereInstrumentation);\n    cohereInstrumentation.manuallyInstrument(instrumentModules.cohere);\n  }\n\n  if (instrumentModules?.bedrock) {\n    const bedrockInstrumentation = new BedrockInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(bedrockInstrumentation);\n    bedrockInstrumentation.manuallyInstrument(instrumentModules.bedrock);\n  }\n\n  if (instrumentModules?.pinecone) {\n    const instrumentation = new PineconeInstrumentation();\n    instrumentations.push(instrumentation);\n    instrumentation.manuallyInstrument(instrumentModules.pinecone);\n  }\n\n  if (instrumentModules?.langchain) {\n    const langchainInstrumentation = new LangChainInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(langchainInstrumentation);\n    langchainInstrumentation.manuallyInstrument(instrumentModules.langchain);\n  }\n\n  if (instrumentModules?.llamaIndex) {\n    logger.warn(\n      \"Llamaindex JS is deprecated. Not enabling any instrumentation.\",\n    );\n  }\n\n  if (instrumentModules?.chromadb) {\n    const chromadbInstrumentation = new ChromaDBInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(chromadbInstrumentation);\n    chromadbInstrumentation.manuallyInstrument(instrumentModules.chromadb);\n  }\n\n  if (instrumentModules?.qdrant) {\n    const qdrantInstrumentation = new QdrantInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(qdrantInstrumentation);\n    qdrantInstrumentation.manuallyInstrument(instrumentModules.qdrant);\n  }\n\n  if (instrumentModules?.together) {\n    const togetherInstrumentation = new TogetherInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(togetherInstrumentation);\n    togetherInstrumentation.manuallyInstrument(instrumentModules.together);\n  }\n\n  if (instrumentModules?.playwright && client) {\n    playwrightInstrumentation = new PlaywrightInstrumentation(\n      client,\n      sessionRecordingOptions,\n    );\n    instrumentations.push(playwrightInstrumentation);\n    playwrightInstrumentation.manuallyInstrument(instrumentModules.playwright);\n  }\n\n  if (instrumentModules?.puppeteer && client) {\n    const puppeteerInstrumentation = new PuppeteerInstrumentation(\n      client,\n      sessionRecordingOptions,\n    );\n    instrumentations.push(puppeteerInstrumentation);\n    puppeteerInstrumentation.manuallyInstrument(instrumentModules.puppeteer);\n  }\n\n  if (instrumentModules?.stagehand && client) {\n    if (!playwrightInstrumentation) {\n      playwrightInstrumentation = new PlaywrightInstrumentation(\n        client,\n        sessionRecordingOptions,\n      );\n      instrumentations.push(playwrightInstrumentation);\n    }\n    const stagehandInstrumentation = getStagehandInstrumentation(\n      playwrightInstrumentation,\n      client,\n      sessionRecordingOptions,\n    );\n    instrumentations.push(stagehandInstrumentation);\n    stagehandInstrumentation.manuallyInstrument(instrumentModules.stagehand);\n  }\n\n  if (instrumentModules?.google_genai) {\n    const googleGenAiInstrumentation = new GoogleGenAiInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(googleGenAiInstrumentation);\n    googleGenAiInstrumentation.manuallyInstrument(\n      instrumentModules.google_genai,\n    );\n  }\n\n  if (instrumentModules?.openrouter) {\n    const openRouterInstrumentation = new OpenRouterInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(openRouterInstrumentation);\n    openRouterInstrumentation.manuallyInstrument(instrumentModules.openrouter);\n  }\n\n  if (instrumentModules?.typesafe) {\n    const typeSafeInstrumentation = new TypeSafeInstrumentation({\n      traceContent: !suppressContentTracing,\n    });\n    instrumentations.push(typeSafeInstrumentation);\n    typeSafeInstrumentation.manuallyInstrument(instrumentModules.typesafe);\n  }\n\n  if (instrumentModules?.kernel) {\n    const kernelInstrumentation = new KernelInstrumentation();\n    instrumentations.push(kernelInstrumentation);\n    kernelInstrumentation.manuallyInstrument(instrumentModules.kernel);\n  }\n\n  if (instrumentModules?.claudeAgentSDK) {\n    const claudeAgentInstrumentation = new ClaudeAgentSDKInstrumentation();\n    instrumentations.push(claudeAgentInstrumentation);\n    claudeAgentInstrumentation.manuallyInstrument(\n      instrumentModules.claudeAgentSDK,\n    );\n  }\n\n  if (instrumentModules?.opencode) {\n    const opencodeInstrumentation = new OpencodeInstrumentation();\n    instrumentations.push(opencodeInstrumentation);\n    opencodeInstrumentation.manuallyInstrument(instrumentModules.opencode);\n  }\n\n  if (instrumentModules?.openAIAgents) {\n    const openAIAgentsInstrumentation = new OpenAIAgentsInstrumentation();\n    instrumentations.push(openAIAgentsInstrumentation);\n    openAIAgentsInstrumentation.manuallyInstrument(\n      instrumentModules.openAIAgents,\n    );\n  }\n\n  if (instrumentModules?.temporal) {\n    const {\n      worker,\n      client,\n      createActivitySpan,\n      recordActivityArgs,\n      recordActivityOutput,\n    } = instrumentModules.temporal;\n    const activityOptions = {\n      ...(createActivitySpan !== undefined ? { createActivitySpan } : {}),\n      ...(recordActivityArgs !== undefined ? { recordActivityArgs } : {}),\n      ...(recordActivityOutput !== undefined ? { recordActivityOutput } : {}),\n    };\n    if (worker?.Worker?.create) {\n      patchTemporalWorker(worker, activityOptions);\n    }\n    if (client?.Client) {\n      // Mutate client.Client in place so every subsequent `new client.Client()`\n      // (or `new temporalClient.Client()` from the user's module reference)\n      // gets the patched subclass automatically.\n      patchTemporalClient(client);\n    }\n  }\n\n  return instrumentations;\n};\n","import {\n  Context,\n  type Span,\n  type SpanOptions,\n  type Tracer,\n  trace,\n} from \"@opentelemetry/api\";\n\nimport { LaminarContextManager } from \"./context\";\nimport { LaminarSpan } from \"./span\";\n\nexport class LaminarTracer implements Tracer {\n  private _tracer: Tracer;\n  constructor(tracer: Tracer) {\n    this._tracer = tracer;\n  }\n\n  public startSpan(\n    name: string,\n    options?: SpanOptions,\n    context?: Context,\n  ): Span {\n    return new LaminarSpan(\n      this._tracer.startSpan(\n        name,\n        options,\n        context || LaminarContextManager.getContext(),\n      ),\n    );\n  }\n\n  public startActiveSpan<F extends (span: Span) => unknown>(\n    name: string,\n    fn: F,\n  ): ReturnType<F>;\n  public startActiveSpan<F extends (span: Span) => unknown>(\n    name: string,\n    options: SpanOptions,\n    fn: F,\n  ): ReturnType<F>;\n  public startActiveSpan<F extends (span: Span) => unknown>(\n    name: string,\n    options: SpanOptions,\n    context: Context,\n    fn: F,\n  ): ReturnType<F>;\n\n  public startActiveSpan<F extends (span: Span) => unknown>(\n    name: string,\n    optionsOrFn?: SpanOptions | F,\n    contextOrFn?: Context | F,\n    fn?: F,\n  ): ReturnType<F> {\n    let contextToUse: Context;\n    if (typeof contextOrFn !== \"function\" && contextOrFn !== undefined) {\n      contextToUse = contextOrFn;\n    } else {\n      contextToUse = LaminarContextManager.getContext();\n    }\n\n    const wrapped =\n      (fn: F) =>\n      (span: Span): ReturnType<F> => {\n        const laminarSpan = new LaminarSpan(span);\n        const ctxWithAssociationProperties =\n          LaminarContextManager.setAssociationProperties(\n            laminarSpan,\n            contextToUse,\n          );\n        const newContext = trace.setSpan(\n          ctxWithAssociationProperties,\n          laminarSpan,\n        );\n        const currentStack = LaminarContextManager.getContextStack();\n        const res = LaminarContextManager.runWithIsolatedContext(\n          [...currentStack, newContext],\n          () => fn(laminarSpan) as ReturnType<F>,\n        );\n        // We don't pop the context here, because it is the caller's responsibility to\n        // end the span. LaminarSpan.end() will pop the context.\n        return res;\n      };\n    if (typeof optionsOrFn === \"function\") {\n      return this._tracer.startActiveSpan(\n        name,\n        {},\n        contextToUse,\n        wrapped(optionsOrFn),\n      );\n    }\n    if (typeof contextOrFn === \"function\") {\n      return this._tracer.startActiveSpan(\n        name,\n        optionsOrFn as SpanOptions,\n        contextToUse,\n        wrapped(contextOrFn),\n      );\n    }\n\n    // Use the provided context or the current Laminar context\n    return this._tracer.startActiveSpan(\n      name,\n      optionsOrFn as SpanOptions,\n      contextToUse,\n      wrapped(fn as F),\n    );\n  }\n}\n","import {\n  Context,\n  context,\n  createContextKey,\n  ROOT_CONTEXT,\n} from \"@opentelemetry/api\";\n\nimport { CONTEXT_SPAN_PATH_KEY } from \"./context\";\n\n// Function to check if a global context manager is already configured\nexport const isGlobalContextManagerConfigured = () => {\n  // Create a temporary context key for testing\n  const testKey = createContextKey(\"lmnr-test-context-manager-check\");\n\n  // Create a context with this key\n  const testContext = ROOT_CONTEXT.setValue(testKey, \"lmnr-test-value\");\n\n  // Try to make this context active\n  let isContextManagerWorking = false;\n\n  context.with(testContext, () => {\n    // If the context manager is configured and enabled,\n    // active() should return our test context\n    const activeContext = context.active();\n    isContextManagerWorking =\n      activeContext.getValue(testKey) === \"lmnr-test-value\";\n  });\n\n  return isContextManagerWorking;\n};\n\nexport const getSpanPath = (entityContext: Context): string | undefined => {\n  const path = entityContext.getValue(CONTEXT_SPAN_PATH_KEY) as\n    | string\n    | undefined;\n  return path ? `${path}` : undefined;\n};\n","import { context, Tracer, TracerProvider, trace } from \"@opentelemetry/api\";\nimport { AsyncLocalStorageContextManager } from \"@opentelemetry/context-async-hooks\";\nimport { registerInstrumentations } from \"@opentelemetry/instrumentation\";\nimport { AlwaysOnSampler } from \"@opentelemetry/sdk-trace-base\";\nimport { NodeTracerProvider } from \"@opentelemetry/sdk-trace-node\";\nimport {\n  ATTR_SERVICE_NAME,\n  ATTR_SERVICE_VERSION,\n} from \"@opentelemetry/semantic-conventions\";\n\nimport { version as SDK_VERSION } from \"../../../package.json\";\nimport { initializeLogger } from \"../../utils\";\nimport { _configuration } from \"../configuration\";\nimport { InitializeOptions } from \"../interfaces\";\nimport { createResource } from \"./compat\";\nimport { consumeStreamResult, waitForPendingStreams } from \"./stream-utils\";\n\nexport { consumeStreamResult, waitForPendingStreams };\n\nimport { initializeLaminarInstrumentations } from \"./instrumentations\";\nimport { LaminarSpanProcessor } from \"./processor\";\nimport { LaminarTracer } from \"./tracer\";\nimport { isGlobalContextManagerConfigured } from \"./utils\";\n\nconst logger = initializeLogger();\n\nlet spanProcessor: LaminarSpanProcessor;\nlet tracerProvider: TracerProvider | undefined;\nlet _baseHttpUrl: string = \"https://api.lmnr.ai:443\";\nlet _apiKey: string | undefined;\n\n/**\n * Initializes the Tracing SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions}\n * for details.\n */\nexport const startTracing = (options: InitializeOptions) => {\n  _baseHttpUrl = `${options.baseHttpUrl ?? options.baseUrl}:${options.httpPort ?? 443}`;\n  _apiKey = options.apiKey;\n\n  const instrumentations = initializeLaminarInstrumentations({\n    baseUrl: _baseHttpUrl,\n    apiKey: _apiKey,\n    suppressContentTracing: !shouldSendTraces(),\n    instrumentModules: options.instrumentModules,\n    sessionRecordingOptions: options.sessionRecordingOptions,\n  });\n\n  const port = options.forceHttp ? options.httpPort : options.port;\n\n  spanProcessor = new LaminarSpanProcessor({\n    spanProcessor: options.spanProcessor,\n    baseUrl: options.baseUrl,\n    port,\n    httpPort: options.httpPort,\n    apiKey: options.apiKey,\n    forceHttp: options.forceHttp,\n    traceExportTimeoutMillis: options.traceExportTimeoutMillis,\n    maxExportBatchSize: options.maxExportBatchSize,\n    maxExportBatchSizeBytes: options.maxExportBatchSizeBytes,\n    flushBySize: options.flushBySize,\n    exporter: options.exporter,\n    disableBatch: options.disableBatch,\n  });\n\n  const newProvider = new NodeTracerProvider({\n    spanProcessors: [spanProcessor],\n    sampler: new AlwaysOnSampler(),\n    resource: createResource({\n      [ATTR_SERVICE_NAME]: \"laminar-tracer-resource\",\n      [ATTR_SERVICE_VERSION]: SDK_VERSION,\n    }),\n  });\n\n  tracerProvider = newProvider;\n\n  // Usually, we would do `tracerProvider.register()`, which does three things:\n  // 1. Sets the global tracer provider\n  // 2. Sets the global context manager to a default one, unless we specify a custom one\n  // 3. Sets the global propagator to a default one, unless we specify a custom one\n  // We don't do that, because Opentelemetry only allows setting these global\n  // OTel API instances once.\n  //\n  // Instead, we do the following:\n  // 1. Carry the global tracer provider around without globally registering it.\n  //    - Set this tracer provider in the auto-instrumentations from OpenLLMetry\n  //    - expose the `getTracer` function, which will return a tracer from our\n  //      tracer provider.\n  // 2. Set a context manager globally, only if we are the first ones to do so.\n  //    - If we are not the first ones, we don't set the global context manager.\n  //      - If an existing context manager is not broken, it suffices for our purposes\n  //        for carrying the parent span context.\n  //    - If any library tries to do so afterwards (and they will, e.g. @vercel/otel\n  //      or @sentry/node do tracerProvider.register() internally), there will be\n  //      an error message at their initialization.\n  //      - We recommend to initialize Laminar after other tracing libraries to avoid that\n  // 3. We don't do anything about the propagator, because no Laminar functionality\n  //    depends on it. We might want to revisit this in the future w.r.t. `LaminarSpanContext`.\n\n  // This is a small hack to only set the global context manager if there is none.\n  if (!isGlobalContextManagerConfigured()) {\n    const contextManager = new AsyncLocalStorageContextManager();\n    contextManager.enable();\n    context.setGlobalContextManager(contextManager);\n    logger.debug(\"Laminar set global OTel Context Manager\");\n  }\n  logger.debug(\"Global OTel Context Manager exists\");\n\n  logger.debug(\n    `Laminar registering ${instrumentations.length} instrumentations`,\n  );\n  // Similarly, we carry our global tracer provider around without globally\n  // registering it.\n  registerInstrumentations({\n    instrumentations,\n    tracerProvider: newProvider,\n  });\n};\n\nexport const patchModules = (\n  modules: InitializeOptions[\"instrumentModules\"],\n) => {\n  const instrumentations = initializeLaminarInstrumentations({\n    baseUrl: _baseHttpUrl,\n    apiKey: _apiKey,\n    instrumentModules: modules,\n    suppressContentTracing: !shouldSendTraces(),\n    sessionRecordingOptions: _configuration?.sessionRecordingOptions,\n  });\n  registerInstrumentations({\n    instrumentations,\n    tracerProvider: tracerProvider,\n  });\n};\n\nexport const shouldSendTraces = () => {\n  if (!_configuration) {\n    /**\n     * We've only seen this happen in Next.js where apparently\n     * the initialization in `instrumentation.ts` somehow does not\n     * respect `Object.freeze`. Unlike original OpenLLMetry/Traceloop,\n     * we return true here, because we have other mechanisms\n     * {@link withTracingLevel} to disable tracing inputs and outputs.\n     */\n    return true;\n  }\n\n  if (\n    _configuration.traceContent === false ||\n    (process.env.TRACELOOP_TRACE_CONTENT || \"true\").toLowerCase() === \"false\"\n  ) {\n    return false;\n  }\n\n  return true;\n};\n\n/**\n * Get the tracer provider. Returns Laminar's tracer provider if Laminar is initialized,\n * otherwise returns the global tracer provider.\n * @returns The tracer provider.\n */\nexport const getTracerProvider = (): TracerProvider =>\n  tracerProvider ?? trace.getTracerProvider();\n\n/**\n * Get the tracer.\n * @returns Laminar's tracer if Laminar is initialized,\n * otherwise returns Laminar's tracer from the global tracer provider\n *\n * @example\n * // instrumentation.ts\n * import { Laminar } from '@lmnr-ai/lmnr';\n * Laminar.initialize()\n *\n * // File that calls AI SDK.\n * import { getTracer } from '@lmnr-ai/lmnr';\n * import { openai } from \"@ai-sdk/openai\";\n * import { generateText } from \"ai\";\n *\n * const response = await generateText({\n *   model: openai(\"gpt-4.1-nano\"),\n *   prompt: \"What is the capital of France?\",\n *   experimental_telemetry: {\n *     isEnabled: true,\n *     tracer: getTracer(),\n *   }\n * })\n */\nexport const getTracer = (): Tracer => {\n  const TRACER_NAME = \"lmnr.tracer\";\n  const TRACER_VERSION = \"0.0.1\";\n  const provider = getTracerProvider();\n  return new LaminarTracer(provider.getTracer(TRACER_NAME, TRACER_VERSION));\n};\n\n/**\n * Get the span processor.\n * Used internally for setting parent path information when initializing from environment.\n * @returns The span processor, or undefined if not initialized.\n */\nexport const getSpanProcessor = (): LaminarSpanProcessor | undefined =>\n  spanProcessor;\n\n/**\n * The API key the initialized pipeline exports with. Used internally so an\n * integration that carries its own credentials can detect that it would ship\n * spans to a different project than its own API calls.\n * @returns The API key, or undefined if tracing is not initialized.\n */\nexport const getConfiguredApiKey = (): string | undefined => _apiKey;\n\nexport const forceFlush = async () => {\n  // Wait for pending stream processing with 5 second timeout\n  await waitForPendingStreams(5000);\n  await spanProcessor.forceFlush();\n};\n\nexport const clearSpanProcessor = () => {\n  spanProcessor.clear();\n};\n","import { DiagConsoleLogger, DiagLogLevel, diag } from \"@opentelemetry/api\";\n\nimport { type InitializeOptions } from \"../interfaces\";\nimport { startTracing } from \"../tracing\";\n\nexport let _configuration: InitializeOptions | undefined;\n\n/**\n * Initializes the SDK.\n * Must be called once before any other SDK methods.\n *\n * @param options - The options to initialize the SDK. See the {@link InitializeOptions}\n * for details.\n * @throws {InitializationError} if the configuration is invalid or if failed to fetch\n * feature data.\n */\nexport const initializeTracing = (options: InitializeOptions) => {\n  if (_configuration) {\n    return;\n  }\n\n  // Only set defaults if not already provided and if we have an API key\n  // (when using OTEL env vars, we don't need a baseUrl or API key)\n  const apiKey = options.apiKey ?? process.env.LMNR_PROJECT_API_KEY;\n  if (!options.baseUrl && apiKey) {\n    options.baseUrl = process.env.LMNR_BASE_URL || \"https://api.lmnr.ai:8443\";\n  }\n  if (!options.apiKey) {\n    options.apiKey = apiKey;\n  }\n\n  _configuration = Object.freeze(options);\n\n  if (options.logLevel) {\n    diag.setLogger(new DiagConsoleLogger(), {\n      logLevel: logLevelToOtelLogLevel(options.logLevel),\n      suppressOverrideMessage: true,\n    });\n  }\n\n  startTracing(_configuration);\n};\n\nconst logLevelToOtelLogLevel = (\n  logLevel: \"debug\" | \"info\" | \"warn\" | \"error\",\n) => {\n  switch (logLevel) {\n    case \"debug\":\n      return DiagLogLevel.DEBUG;\n    case \"info\":\n      return DiagLogLevel.INFO;\n    case \"warn\":\n      return DiagLogLevel.WARN;\n    case \"error\":\n      return DiagLogLevel.ERROR;\n  }\n};\n\nexport const _resetConfiguration = () => {\n  _configuration = undefined;\n};\n","import {\n  errorMessage,\n  LaminarSpanContext,\n  TraceType,\n  TracingLevel,\n} from \"@lmnr-ai/types\";\nimport { AttributeValue, context, type Span, trace } from \"@opentelemetry/api\";\nimport { suppressTracing } from \"@opentelemetry/core\";\n\nimport { Laminar } from \"../../laminar\";\nimport {\n  deserializeLaminarSpanContext,\n  initializeLogger,\n  truncateSpanPayload,\n  tryToOtelSpanContext,\n} from \"../../utils\";\nimport { getStream, StreamInfo } from \"../instrumentation/aisdk/utils\";\nimport { getTracer, shouldSendTraces } from \".\";\nimport { SPAN_INPUT, SPAN_OUTPUT } from \"./attributes\";\nimport { ASSOCIATION_PROPERTIES_KEY, LaminarContextManager } from \"./context\";\nimport { handleStreamResult } from \"./stream-utils\";\n\nconst logger = initializeLogger();\n\nexport { consumeStreamResult, waitForPendingStreams } from \"./stream-utils\";\n\nexport type DecoratorConfig = {\n  name: string;\n  contextProperties?: {\n    userId?: string;\n    sessionId?: string;\n    traceType?: TraceType;\n    tracingLevel?: TracingLevel;\n    metadata?: Record<string, any>;\n  };\n  spanAttributes?: Record<string, AttributeValue>;\n  input?: unknown;\n  ignoreInput?: boolean;\n  ignoreOutput?: boolean;\n  inputParameters?: unknown[];\n  suppressTracing?: boolean;\n  parentSpanContext?: string | LaminarSpanContext;\n};\n\n// Overload for when thisArg is provided (method call)\nexport function observeBase<\n  A extends unknown[],\n  This,\n  F extends (this: This, ...args: A) => ReturnType<F>,\n>(config: DecoratorConfig, fn: F, thisArg: This, ...args: A): ReturnType<F>;\n\n// Overload for when thisArg is not provided (standalone function)\nexport function observeBase<\n  A extends unknown[],\n  F extends (...args: A) => ReturnType<F>,\n>(\n  config: DecoratorConfig,\n  fn: F,\n  thisArg: undefined,\n  ...args: A\n): ReturnType<F>;\n\n// Implementation signature (more permissive to handle both cases)\nexport function observeBase<\n  A extends unknown[],\n  F extends (this: ThisParameterType<F>, ...args: A) => ReturnType<F>,\n>(\n  {\n    name,\n    contextProperties,\n    spanAttributes,\n    input,\n    ignoreInput,\n    ignoreOutput,\n    inputParameters,\n    suppressTracing: shouldSuppressTracing,\n    parentSpanContext,\n  }: DecoratorConfig,\n  fn: F,\n  thisArg?: ThisParameterType<F>,\n  ...args: A\n): ReturnType<F> {\n  let entityContext = LaminarContextManager.getContext();\n\n  if (shouldSuppressTracing) {\n    entityContext = suppressTracing(entityContext);\n  }\n\n  if (parentSpanContext) {\n    try {\n      const laminarContext =\n        typeof parentSpanContext === \"string\"\n          ? deserializeLaminarSpanContext(parentSpanContext)\n          : parentSpanContext;\n\n      // Arm the debug runtime from a propagated debug block (first-wins,\n      // idempotent, no-op when already armed or no block present). observe()\n      // spans bypass Laminar._startSpan, so without this a downstream process\n      // whose first traced work is observe({ parentSpanContext }) would never\n      // join the upstream debug session, replay, or rollout.session_id stamping.\n      Laminar._armDebugRuntimeFromContext(laminarContext.debug);\n\n      const spanContext = tryToOtelSpanContext(laminarContext);\n      entityContext = trace.setSpan(\n        entityContext,\n        trace.wrapSpanContext(spanContext),\n      );\n    } catch (e) {\n      logger.warn(\"Failed to parse parent span context: \" + errorMessage(e));\n    }\n  }\n\n  // Set context properties for propagation to child spans\n  try {\n    if (contextProperties && Object.keys(contextProperties).length > 0) {\n      const currentAssociationProperties =\n        entityContext.getValue(ASSOCIATION_PROPERTIES_KEY) ?? {};\n      entityContext = entityContext.setValue(ASSOCIATION_PROPERTIES_KEY, {\n        ...currentAssociationProperties,\n        ...contextProperties,\n      });\n    }\n  } catch (e) {\n    logger.warn(\"Failed to set context properties: \" + errorMessage(e));\n  }\n\n  return context.with(entityContext, () =>\n    getTracer().startActiveSpan(\n      name,\n      {\n        attributes: spanAttributes,\n      },\n      entityContext,\n      (span: Span) => {\n        if (shouldSendTraces() && !ignoreInput) {\n          try {\n            const spanInput = inputParameters ?? args;\n            if (input !== undefined) {\n              span.setAttribute(\n                SPAN_INPUT,\n                typeof input === \"string\"\n                  ? truncateSpanPayload(input, \"input\")\n                  : serialize(input, \"input\"),\n              );\n            } else if (\n              spanInput.length === 1 &&\n              typeof spanInput[0] === \"object\" &&\n              !(spanInput[0] instanceof Map)\n            ) {\n              span.setAttribute(\n                SPAN_INPUT,\n                typeof spanInput[0] === \"string\"\n                  ? truncateSpanPayload(spanInput[0], \"input\")\n                  : serialize(spanInput[0], \"input\"),\n              );\n            } else {\n              // pass an array of the arguments without names\n              // Need to convert it to map from argument name to value,\n              // if we figure out how to do it elegantly\n              span.setAttribute(\n                SPAN_INPUT,\n                serialize(spanInput.length > 0 ? spanInput : {}, \"input\"),\n              );\n            }\n          } catch (error) {\n            logger.warn(\"Failed to serialize input: \" + errorMessage(error));\n          }\n        }\n\n        let res: ReturnType<F>;\n        try {\n          res = fn.apply(thisArg as ThisParameterType<F>, args);\n        } catch (error) {\n          try {\n            span.recordException(error as Error);\n            span.end();\n          } catch (error) {\n            logger.warn(\n              \"Failed to record exception and end span: \" + errorMessage(error),\n            );\n          }\n          throw error;\n        }\n\n        if (res instanceof Promise) {\n          return res\n            .then((resolvedRes) => {\n              // Check if the resolved result is a stream\n              let streamInfo: StreamInfo = { type: null };\n              try {\n                streamInfo = getStream(resolvedRes);\n              } catch (error) {\n                logger.warn(\n                  \"Failed to get stream info: \" + errorMessage(error),\n                );\n              }\n              if (streamInfo.type !== null) {\n                return handleStreamResult(\n                  resolvedRes,\n                  streamInfo,\n                  span,\n                  ignoreOutput,\n                  serialize,\n                ) as ReturnType<F>;\n              }\n\n              // Not a stream, handle normally\n              try {\n                if (shouldSendTraces() && !ignoreOutput) {\n                  span.setAttribute(SPAN_OUTPUT, serialize(resolvedRes));\n                }\n              } catch (error) {\n                logger.warn(\n                  \"Failed to serialize async output: \" + errorMessage(error),\n                );\n              } finally {\n                try {\n                  span.end();\n                } catch (error) {\n                  logger.warn(\"Failed to end span: \" + errorMessage(error));\n                }\n              }\n\n              return resolvedRes;\n            })\n            .catch((error) => {\n              try {\n                span.recordException(error as Error);\n                span.end();\n              } catch (error) {\n                logger.warn(\n                  \"Failed to record exception and end span: \" +\n                    errorMessage(error),\n                );\n              }\n              throw error;\n            }) as ReturnType<F>;\n        }\n\n        // Check if the result is a stream\n        let streamInfo: StreamInfo = { type: null };\n        try {\n          streamInfo = getStream(res);\n        } catch (error) {\n          logger.warn(\"Failed to get stream info: \" + errorMessage(error));\n        }\n        if (streamInfo.type !== null) {\n          return handleStreamResult(\n            res,\n            streamInfo,\n            span,\n            ignoreOutput,\n            serialize,\n          ) as ReturnType<F>;\n        }\n\n        try {\n          if (shouldSendTraces() && !ignoreOutput) {\n            span.setAttribute(\n              SPAN_OUTPUT,\n              typeof res === \"string\"\n                ? truncateSpanPayload(res, \"output\")\n                : serialize(res),\n            );\n          }\n        } catch (error) {\n          logger.warn(\"Failed to serialize output: \" + errorMessage(error));\n        } finally {\n          try {\n            span.end();\n          } catch (error) {\n            logger.warn(\"Failed to end span: \" + errorMessage(error));\n          }\n        }\n\n        return res;\n      },\n    ),\n  );\n}\n\nconst normalizePayload = (payload: unknown, seen: WeakSet<any>): unknown => {\n  if (payload instanceof Map) {\n    return Array.from(payload.entries());\n  } else if (Array.isArray(payload)) {\n    return payload.map((value) => normalizePayload(value, seen));\n  } else if (!payload) {\n    return payload;\n  } else if (typeof payload === \"object\") {\n    if (seen.has(payload)) {\n      return \"[Circular reference]\";\n    }\n    seen.add(payload);\n\n    // serialize object one by one\n    const output: any = {};\n    Object.entries(payload as any).forEach(([key, value]) => {\n      output[key] = normalizePayload(value, seen);\n    });\n    return output;\n  }\n\n  return payload;\n};\n\nconst serialize = (\n  payload: unknown,\n  kind: \"input\" | \"output\" = \"output\",\n): string =>\n  truncateSpanPayload(\n    JSON.stringify(normalizePayload(payload, new WeakSet())),\n    kind,\n  );\n","import {\n  errorMessage,\n  LaminarSpanContext,\n  TraceType,\n  TracingLevel,\n} from \"@lmnr-ai/types\";\nimport { AttributeValue } from \"@opentelemetry/api\";\n\nimport { observeBase } from \"./opentelemetry-lib\";\nimport {\n  ASSOCIATION_PROPERTIES,\n  PARENT_SPAN_IDS_PATH,\n  PARENT_SPAN_PATH,\n  SPAN_TYPE,\n} from \"./opentelemetry-lib/tracing/attributes\";\nimport {\n  ASSOCIATION_PROPERTIES_KEY,\n  LaminarContextManager,\n} from \"./opentelemetry-lib/tracing/context\";\nimport { deserializeLaminarSpanContext, initializeLogger } from \"./utils\";\n\nconst logger = initializeLogger();\n\ninterface ObserveOptions {\n  name?: string;\n  sessionId?: string;\n  userId?: string;\n  traceType?: TraceType;\n  spanType?:\n    | \"DEFAULT\"\n    | \"LLM\"\n    | \"TOOL\"\n    | \"EVALUATOR\"\n    | \"EVALUATION\"\n    | \"EXECUTOR\";\n  input?: unknown;\n  ignoreInput?: boolean;\n  ignoreOutput?: boolean;\n  parentSpanContext?: string | LaminarSpanContext;\n  metadata?: Record<string, any>;\n  tags?: string[];\n}\n\n/**\n * The main decorator entrypoint for Laminar. This is used to wrap\n * functions and methods to create spans.\n *\n * @param options - Configuration options for the span\n * @param options.name - Name of the span. Function name is used if not specified.\n * @param options.sessionId - Session ID to associate with the span and the following context.\n * @param options.userId - User ID to associate with the span and the following context.\n * This is different from the id of a Laminar user.\n * @param options.traceType - Type of the trace. Unless it is within evaluation, it should be\n * 'DEFAULT'.\n * @param options.spanType - Type of the span. 'DEFAULT' is used if not specified. If the type\n * is 'LLM', you must manually specify some attributes. See `Laminar.setSpanAttributes`\n * for more information.\n * @param options.input - Force override the input for the span. If not specified, the\n * input will be the arguments passed to the function.\n * @param options.ignoreInput - Whether to ignore the input altogether.\n * @param options.ignoreOutput - Whether to ignore the output altogether.\n * @param options.parentSpanContext - Parent span context to associate with this span.\n * @param options.metadata - Metadata to add to a trace for further filtering. Must be\n * JSON serializable.\n * @param options.tags - Tags to associate with the span.\n * @param fn - The function to wrap\n * @param args - Arguments to pass to the function\n * @returns Promise with the result of the wrapped function.\n * @throws Exception - Re-throws the exception if the wrapped function throws an exception.\n *\n * @example\n * ```typescript\n * await observe({ name: 'my_function' }, async (x: string) => {\n *    // Your code here\n *    return x.toUpperCase();\n * }, 'hello');\n * ```\n */\nexport function observe<\n  A extends unknown[],\n  F extends (...args: A) => ReturnType<F>,\n>(options: ObserveOptions, fn: F, ...args: A): ReturnType<F> {\n  if (fn === undefined || typeof fn !== \"function\") {\n    throw new Error(\n      \"Invalid `observe` usage. Second argument `fn` must be a function.\",\n    );\n  }\n\n  const {\n    name,\n    sessionId,\n    userId,\n    traceType,\n    spanType,\n    input,\n    ignoreInput,\n    ignoreOutput,\n    parentSpanContext,\n    metadata,\n    tags,\n  } = options;\n  const spanName = name ?? fn.name;\n\n  const observeOptions = {\n    sessionId,\n    traceType,\n    spanType,\n    userId,\n    tags,\n    metadata,\n    parentSpanContext,\n  };\n\n  const contextProperties = buildContextProperties(observeOptions);\n  const spanAttributes = buildSpanAttributes(observeOptions);\n\n  return observeBase<A, F>(\n    {\n      name: spanName,\n      contextProperties,\n      spanAttributes,\n      input,\n      ignoreInput,\n      ignoreOutput,\n      parentSpanContext,\n    },\n    fn,\n    undefined,\n    ...args,\n  );\n}\n\n/**\n * Sets the tracing level for any spans inside the function. This is useful for\n * conditionally disabling the tracing for certain functions.\n * Tracing level must be one of the values in {@link TracingLevel}. Returns the\n * result of the wrapped function, so you can use it in an `await` statement if\n * needed.\n *\n * @param tracingLevel - The tracing level to set.\n * @returns The result of the wrapped function.\n *\n * @example\n * ```typescript\n * import { withTracingLevel, TracingLevel } from '@lmnr-ai/lmnr';\n *\n * const result = await withTracingLevel(TracingLevel.META_ONLY, () => {\n *    openai.chat.completions.create({});\n * });\n * ```\n */\nexport function withTracingLevel<\n  A extends unknown[],\n  F extends (...args: A) => ReturnType<F>,\n>(tracingLevel: TracingLevel, fn: F, ...args: A): ReturnType<F> {\n  let entityContext = LaminarContextManager.getContext();\n  const currentAssociationProperties =\n    entityContext.getValue(ASSOCIATION_PROPERTIES_KEY) ?? {};\n\n  entityContext = entityContext.setValue(ASSOCIATION_PROPERTIES_KEY, {\n    ...currentAssociationProperties,\n    tracing_level: tracingLevel,\n  });\n\n  const result = LaminarContextManager.runWithIsolatedContext(\n    [entityContext],\n    () => fn(...args),\n  );\n\n  const newAssociationProperties = (entityContext.getValue(\n    ASSOCIATION_PROPERTIES_KEY,\n  ) ?? {}) as Record<string, any>;\n  delete newAssociationProperties[\"tracing_level\"];\n\n  entityContext.setValue(ASSOCIATION_PROPERTIES_KEY, newAssociationProperties);\n\n  return result;\n}\n\n/**\n * Builds context-level association properties that propagate to child spans.\n * These properties flow through the OpenTelemetry context and are inherited by\n * any child spans created with startActiveSpan.\n */\nconst buildContextProperties = (\n  options: Partial<ObserveOptions>,\n): {\n  userId?: string;\n  sessionId?: string;\n  traceType?: TraceType;\n  tracingLevel?: TracingLevel;\n  metadata?: Record<string, any>;\n} => {\n  const parentSpanContext = options.parentSpanContext;\n  const globalMetadata = LaminarContextManager.getGlobalMetadata();\n  const ctxAssociationProperties =\n    LaminarContextManager.getAssociationProperties();\n\n  let parentMetadata: Record<string, any> | undefined;\n  let parentTraceType: TraceType | undefined;\n  let parentTracingLevel: TracingLevel | undefined;\n  let parentUserId: string | undefined;\n  let parentSessionId: string | undefined;\n\n  if (parentSpanContext) {\n    try {\n      const laminarContext =\n        typeof parentSpanContext === \"string\"\n          ? deserializeLaminarSpanContext(parentSpanContext)\n          : parentSpanContext;\n\n      parentMetadata = laminarContext.metadata;\n      parentTraceType = laminarContext.traceType;\n      parentTracingLevel = laminarContext.tracingLevel;\n      parentUserId = laminarContext.userId;\n      parentSessionId = laminarContext.sessionId;\n    } catch (e) {\n      logger.warn(\"Failed to parse parent span context: \" + errorMessage(e));\n    }\n  }\n\n  const contextProperties: {\n    userId?: string;\n    sessionId?: string;\n    traceType?: TraceType;\n    tracingLevel?: TracingLevel;\n    metadata?: Record<string, any>;\n  } = {};\n\n  const sessionIdValue =\n    options.sessionId ?? parentSessionId ?? ctxAssociationProperties.sessionId;\n  if (sessionIdValue) {\n    contextProperties.sessionId = sessionIdValue;\n  }\n\n  const userIdValue =\n    options.userId ?? parentUserId ?? ctxAssociationProperties.userId;\n  if (userIdValue) {\n    contextProperties.userId = userIdValue;\n  }\n\n  const traceTypeValue =\n    options.traceType ??\n    parentTraceType ??\n    ([\"EVALUATION\", \"EXECUTOR\", \"EVALUATOR\"].includes(\n      options.spanType ?? \"DEFAULT\",\n    )\n      ? \"EVALUATION\"\n      : undefined) ??\n    ctxAssociationProperties.traceType ??\n    \"DEFAULT\";\n  if (traceTypeValue) {\n    contextProperties.traceType = traceTypeValue;\n  }\n\n  const tracingLevelValue =\n    parentTracingLevel ?? ctxAssociationProperties.tracingLevel;\n  if (tracingLevelValue) {\n    contextProperties.tracingLevel = tracingLevelValue;\n  }\n\n  const mergedMetadata = {\n    ...globalMetadata,\n    ...ctxAssociationProperties.metadata,\n    ...parentMetadata,\n    ...options.metadata,\n  };\n\n  if (Object.keys(mergedMetadata).length > 0) {\n    contextProperties.metadata = mergedMetadata;\n  }\n\n  return contextProperties;\n};\n\n/**\n * Builds span-specific attributes that do NOT propagate to child spans.\n * These include spanType, tags, and parent span path information.\n */\nconst buildSpanAttributes = (\n  options: Partial<ObserveOptions>,\n): Record<string, AttributeValue> => {\n  const spanAttributes: Record<string, AttributeValue> = {};\n\n  if (options.spanType) {\n    spanAttributes[SPAN_TYPE] = options.spanType;\n  }\n\n  if (options.tags) {\n    spanAttributes[`${ASSOCIATION_PROPERTIES}.tags`] = Array.from(\n      new Set(options.tags),\n    );\n  }\n\n  if (options.parentSpanContext) {\n    try {\n      const laminarContext =\n        typeof options.parentSpanContext === \"string\"\n          ? deserializeLaminarSpanContext(options.parentSpanContext)\n          : options.parentSpanContext;\n\n      if (laminarContext.spanPath) {\n        spanAttributes[PARENT_SPAN_PATH] = laminarContext.spanPath;\n      }\n      if (laminarContext.spanIdsPath) {\n        spanAttributes[PARENT_SPAN_IDS_PATH] = laminarContext.spanIdsPath;\n      }\n    } catch (e) {\n      logger.warn(\n        \"Failed to parse parent span context for span attributes: \" +\n          errorMessage(e),\n      );\n    }\n  }\n\n  return spanAttributes;\n};\n\n/**\n * Decorator that wraps a method to automatically observe it with Laminar tracing.\n * This decorator uses the TypeScript 5.0+ standard decorator syntax.\n *\n * **Important**: Use this decorator only if your `tsconfig.json` does NOT have\n * `experimentalDecorators: true`. If you're using experimental decorators, use\n * {@link observeExperimentalDecorator} instead.\n *\n * This decorator can be used on class methods to automatically create spans.\n *\n * @param config - Configuration for the observe decorator, can be static or a function\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * // In your tsconfig.json, ensure experimentalDecorators is NOT enabled:\n * // {\n * //   \"compilerOptions\": {\n * //     \"experimentalDecorators\": false  // or omit this line\n * //   }\n * // }\n *\n * import { observeDecorator } from '@lmnr-ai/lmnr';\n *\n * class MyService {\n *   @observeDecorator({ name: 'processData', spanType: 'DEFAULT' })\n *   async processData(input: string) {\n *     // Your code here\n *     return `processed: ${input}`;\n *   }\n *\n *   @observeDecorator((thisArg, ...args) => ({\n *     name: `dynamicMethod_${args[0]}`,\n *     sessionId: thisArg.sessionId\n *   }))\n *   async dynamicMethod(id: string) {\n *     // Your code here\n *   }\n * }\n * ```\n */\nexport function observeDecorator<This, Args extends unknown[], Return>(\n  config:\n    | Partial<ObserveOptions>\n    | ((thisArg: This, ...funcArgs: Args) => Partial<ObserveOptions>),\n) {\n  return function (\n    originalMethod: (this: This, ...args: Args) => Return,\n    context: ClassMethodDecoratorContext<\n      This,\n      (this: This, ...args: Args) => Return\n    >,\n  ) {\n    if (context.kind !== \"method\") {\n      throw new Error(\n        `observeDecorator can only be applied to methods. Applied to: ${String(context.name)}`,\n      );\n    }\n\n    const methodName = String(context.name);\n\n    return function (this: This, ...args: Args): Return {\n      let actualConfig: Partial<ObserveOptions>;\n\n      if (typeof config === \"function\") {\n        actualConfig = config(this, ...args);\n      } else {\n        actualConfig = config;\n      }\n\n      const observeName = actualConfig.name ?? methodName;\n      const contextProperties = buildContextProperties(actualConfig);\n      const spanAttributes = buildSpanAttributes(actualConfig);\n\n      return observeBase(\n        {\n          name: observeName,\n          contextProperties,\n          spanAttributes,\n          input: actualConfig.input,\n          ignoreInput: actualConfig.ignoreInput,\n          ignoreOutput: actualConfig.ignoreOutput,\n          parentSpanContext: actualConfig.parentSpanContext,\n        },\n        originalMethod,\n        this,\n        ...args,\n      );\n    };\n  };\n}\n\n/**\n * Decorator that wraps a method to automatically observe it with Laminar tracing.\n * This decorator uses the legacy experimental decorator syntax\n * (requires `--experimentalDecorators` flag).\n *\n * **Important**: Use this decorator only if your `tsconfig.json` has\n * `experimentalDecorators: true` in the `compilerOptions` section\n * (or if you compile with the `--experimentalDecorators` flag).\n * For TypeScript 5.0+ projects without experimental decorators, use\n * {@link observeDecorator} instead.\n *\n * This decorator can be used on class methods to automatically create spans.\n *\n * Use this only if you need the legacy experimental decorator syntax.\n * @param config - Configuration for the observe decorator, can be static or a function\n * @returns A method decorator\n *\n * @example\n * ```typescript\n * // In your tsconfig.json, ensure experimentalDecorators is enabled:\n * // {\n * //   \"compilerOptions\": {\n * //     \"experimentalDecorators\": true\n * //   }\n * // }\n *\n * import { observeExperimentalDecorator } from '@lmnr-ai/lmnr';\n *\n * class MyService {\n *   @observeExperimentalDecorator({ name: 'processData', spanType: 'DEFAULT' })\n *   async processData(input: string) {\n *     // Your code here\n *     return `processed: ${input}`;\n *   }\n *\n *   @observeExperimentalDecorator((thisArg, ...args) => ({\n *     name: `dynamicMethod_${args[0]}`,\n *     sessionId: thisArg.sessionId\n *   }))\n *   async dynamicMethod(id: string) {\n *     // Your code here\n *   }\n * }\n * ```\n */\nexport function observeExperimentalDecorator(\n  config:\n    | Partial<ObserveOptions>\n    | ((thisArg: unknown, ...funcArgs: unknown[]) => Partial<ObserveOptions>),\n) {\n  return function (\n    _target: unknown,\n    propertyKey: string,\n    descriptor: PropertyDescriptor,\n  ) {\n    if (!descriptor || typeof descriptor.value !== \"function\") {\n      throw new Error(\n        \"observeExperimentalDecorator can only be applied to methods. \" +\n          `Applied to: ${String(propertyKey)}`,\n      );\n    }\n\n    const originalMethod = descriptor.value;\n\n    descriptor.value = function (...args: unknown[]) {\n      let actualConfig: Partial<ObserveOptions>;\n\n      if (typeof config === \"function\") {\n        actualConfig = config(this, ...args);\n      } else {\n        actualConfig = config;\n      }\n\n      const observeName = actualConfig.name ?? originalMethod.name;\n      const contextProperties = buildContextProperties(actualConfig);\n      const spanAttributes = buildSpanAttributes(actualConfig);\n\n      return observeBase(\n        {\n          name: observeName,\n          contextProperties,\n          spanAttributes,\n          input: actualConfig.input,\n          ignoreInput: actualConfig.ignoreInput,\n          ignoreOutput: actualConfig.ignoreOutput,\n          parentSpanContext: actualConfig.parentSpanContext,\n        },\n        originalMethod,\n        this,\n        ...args,\n      );\n    };\n  };\n}\n","import { LaminarClient } from \"@lmnr-ai/client\";\nimport { EvaluationDatapoint, errorMessage } from \"@lmnr-ai/types\";\nimport { trace } from \"@opentelemetry/api\";\nimport * as cliProgress from \"cli-progress\";\n\nimport { EvaluationDataset, LaminarDataset } from \"./datasets\";\nimport { getRuntime } from \"./debug\";\nimport { observe } from \"./decorators\";\nimport { Laminar } from \"./laminar\";\nimport { InitializeOptions } from \"./opentelemetry-lib/interfaces\";\nimport {\n  HUMAN_EVALUATOR_OPTIONS,\n  SPAN_TYPE,\n} from \"./opentelemetry-lib/tracing/attributes\";\nimport {\n  ASSOCIATION_PROPERTIES_KEY,\n  LaminarContextManager,\n} from \"./opentelemetry-lib/tracing/context\";\nimport {\n  getFrontendUrl,\n  initializeLogger,\n  loadEnv,\n  newUUID,\n  otelSpanIdToUUID,\n  otelTraceIdToUUID,\n  Semaphore,\n  StringUUID,\n} from \"./utils\";\n\nloadEnv();\n\nconst DEFAULT_CONCURRENCY = 5;\nconst MAX_EXPORT_BATCH_SIZE = 64;\n\ndeclare global {\n  var _evaluations: Evaluation<any, any, any>[] | undefined;\n  // If true, then we need to set the evaluation globally without running it\n  var _set_global_evaluation: boolean;\n}\n\nconst logger = initializeLogger();\n\nconst getEvaluationUrl = (\n  projectId: string,\n  evaluationId: string,\n  baseUrl?: string,\n  frontendPort?: number,\n): string => {\n  const url = getFrontendUrl(baseUrl, frontendPort);\n  return `${url}/project/${projectId}/evaluations/${evaluationId}`;\n};\n\n// Evaluation-metadata key that links an eval run to its debug session. Kept as\n// `rollout.session_id` (matching the trace-metadata key the debugger stamps) so\n// the eval and its debug session cross-reference under one identifier.\nconst SESSION_METADATA_KEY = \"rollout.session_id\";\n\n/**\n * When this eval runs under a debug session, auto-stamp the session id into the\n * evaluation metadata so the created evaluation links back to it with no extra\n * step. The session id is resolved by the debug runtime EXACTLY like traces —\n * `LMNR_DEBUG_SESSION_ID` env → `.lmnr/debug-session.json` → freshly minted — so\n * a plain `LMNR_DEBUG=1 <run-your-eval>` groups the eval under the current debug\n * session (no CLI wrapper needed). `getRuntime()` is null when debug mode is off,\n * so the metadata is returned unchanged.\n *\n * The backend writes the `evaluation` block from this key at eval creation; notes\n * are attached separately as `text` blocks keyed by the same session id\n * (`lmnr-cli debug session add-note`). Called after `Laminar.initialize()`, so\n * the runtime (and its resolved session id) already exist.\n */\nconst withSessionMetadata = (\n  metadata: Record<string, any> | undefined,\n): Record<string, any> | undefined => {\n  const sessionId = getRuntime()?.sessionId ?? null;\n  if (sessionId === null) {\n    return metadata;\n  }\n  return { ...(metadata ?? {}), [SESSION_METADATA_KEY]: sessionId };\n};\n\nconst getAverageScores = <D, T, O>(\n  results: EvaluationDatapoint<D, T, O>[],\n): Record<string, number> => {\n  const perScoreValues: Record<string, number[]> = {};\n  for (const result of results) {\n    for (const key in result.scores) {\n      const score = result.scores[key];\n      if (perScoreValues[key] && score !== null) {\n        perScoreValues[key].push(score);\n      } else {\n        perScoreValues[key] = score !== null ? [score] : [];\n      }\n    }\n  }\n\n  const averageScores: Record<string, number> = {};\n  for (const key in perScoreValues) {\n    averageScores[key] =\n      perScoreValues[key].reduce((a, b) => a + b, 0) /\n      perScoreValues[key].length;\n  }\n\n  return averageScores;\n};\n\n/**\n * Configuration for the Evaluator\n */\ninterface EvaluationConfig {\n  /**\n   * The number of data points to evaluate in parallel at a time. Defaults to 5.\n   */\n  concurrencyLimit?: number;\n  /**\n   * The project API key to use for the evaluation. If not provided,\n   * the API key from the environment variable `LMNR_PROJECT_API_KEY` will be used.\n   */\n  projectApiKey?: string;\n  /**\n   * The base URL of the Laminar API. If not provided, the default is\n   * `https://api.lmnr.ai`. Useful with self-hosted Laminar instances.\n   * Do NOT include the port in the URL, use `httpPort` and `grpcPort` instead.\n   */\n  baseUrl?: string;\n  /**\n   * The base HTTP URL of the Laminar API. If not provided, the default is\n   * `baseUrl`. Only use this if you want to proxy HTTP requests through a different host.\n   */\n  baseHttpUrl?: string;\n  /**\n   * The HTTP port of the Laminar API. If not provided, the default is 443.\n   */\n  httpPort?: number;\n  /**\n   * The gRPC port of the Laminar API. If not provided, the default is 8443.\n   */\n  grpcPort?: number;\n  /**\n   * Object with modules to instrument. If not provided, all\n   * available modules are instrumented.\n   * See {@link https://laminar.sh/docs/sdk/typescript/instrumentation#instrumentmodules}\n   */\n  instrumentModules?: InitializeOptions[\"instrumentModules\"];\n  /**\n   * If true, then the spans will not be batched.\n   */\n  traceDisableBatch?: boolean;\n  /**\n   * Timeout for trace export. Defaults to 30_000 (30 seconds), which is over\n   * the default OTLP exporter timeout of 10_000 (10 seconds).\n   */\n  traceExportTimeoutMillis?: number;\n  /**\n   * Defines default log level for SDK and all instrumentations.\n   */\n  logLevel?: \"debug\" | \"info\" | \"warn\" | \"error\";\n\n  /**\n   * Maximum number of spans to export at a time. Defaults to 64.\n   */\n  traceExportBatchSize?: number;\n  /**\n   * The port for the Laminar , when running self-hosted. If not provided, the default is 5667.\n   */\n  frontendPort?: number;\n}\n\n/**\n * Datapoint is a single data point in the evaluation. `D` is the type of the input data,\n * `T` is the type of the target data.\n */\nexport type Datapoint<D, T> = {\n  /**\n   * input to the executor function. Must be json serializable. Required.\n   */\n  data: D;\n  /**\n   * input to the evaluator function (alongside the executor output).\n   * Must be json serializable.\n   */\n  target?: T;\n  /**\n   * metadata to the evaluator function. Must be json serializable.\n   */\n  metadata?: Record<string, any>;\n  /**\n   * Optional ID of the datapoint (from dataset)\n   */\n  id?: StringUUID;\n  /**\n   * Optional creation timestamp (from dataset)\n   */\n  createdAt?: string;\n};\n\n/**\n * HumanEvaluator is a class to register a human evaluator.\n */\nexport class HumanEvaluator {\n  public options?: { value: number; label: string }[];\n\n  constructor(options?: { value: number; label: string }[]) {\n    this.options = options;\n  }\n}\n\nexport type EvaluatorFunctionReturn = number | Record<string, number>;\n\n/**\n * EvaluatorFunction is a function that takes the output of the executor, the\n * target, and the data, and returns a score. The score can be a single number or a record\n * of string keys and number values. The latter is useful for evaluating\n * multiple criteria in one go instead of running multiple evaluators.\n */\nexport type EvaluatorFunction<O, T, D = any> = (\n  output: O,\n  target?: T,\n  data?: D,\n  ...args: any[]\n) => EvaluatorFunctionReturn | Promise<EvaluatorFunctionReturn>;\n\ninterface EvaluationConstructorProps<D, T, O> {\n  /**\n   * List of data points to evaluate. `data` is the input to the executor function,\n   * `target` is the input to the evaluator function.\n   */\n  data: Datapoint<D, T>[] | EvaluationDataset<D, T>;\n  /**\n   * The executor function. Takes the data point + any additional arguments\n   * and returns the output to evaluate.\n   */\n  executor: (data: D, ...args: any[]) => O | Promise<O>;\n  /**\n   * Evaluator functions and names. Each evaluator function takes the output of\n   * the executor, the target, and the data, and returns a score. The score can be a\n   * single number or a dict of string keys and number values. If the score is a\n   * single number, it will be named after the evaluator function. Evaluator\n   * function names must contain only letters, digits, hyphens, underscores,\n   * or spaces.\n   */\n  evaluators: Record<string, EvaluatorFunction<O, T, D> | HumanEvaluator>;\n  /**\n   * Name of the evaluation. If not provided, a random name will be assigned.\n   */\n  name?: string;\n  /**\n   * Optional group id of the evaluation. Only evaluations within the same\n   * group_id can be visually compared. Defaults to \"default\".\n   */\n  groupName?: string;\n  /**\n   * Optional metadata to evaluation\n   */\n  metadata?: Record<string, any>;\n  /**\n   * Optional override configurations for the evaluator.\n   */\n  config?: EvaluationConfig;\n}\n\ninterface EvaluationRunResult {\n  averageScores: Record<string, number>;\n  projectId: string;\n  evaluationId: string;\n  url: string;\n  errorMessage?: string;\n}\n\n/**\n * Reports the whole progress to the console.\n */\nclass EvaluationReporter {\n  private cliProgress: cliProgress.SingleBar = new cliProgress.SingleBar(\n    {},\n    cliProgress.Presets.shades_classic,\n  );\n  private progressCounter: number = 0;\n  public baseUrl: string;\n  public frontendPort?: number;\n\n  constructor(baseUrl?: string, frontendPort?: number) {\n    this.baseUrl = baseUrl ?? \"https://api.lmnr.ai\";\n    this.frontendPort = frontendPort;\n  }\n\n  public start({ length }: { length: number }) {\n    this.cliProgress.start(length, 0);\n  }\n\n  public update(batchLength: number) {\n    this.progressCounter += batchLength;\n    this.cliProgress.update(this.progressCounter);\n  }\n\n  // Call either error or stop, not both\n  public stopWithError(error: Error) {\n    this.cliProgress.stop();\n    process.stdout.write(`\\nError: ${error.message}\\n`);\n  }\n\n  // Call either error or stop, not both\n  public stop({\n    averageScores,\n    projectId,\n    evaluationId,\n  }: {\n    averageScores: Record<string, number>;\n    projectId: string;\n    evaluationId: string;\n  }) {\n    this.cliProgress.stop();\n    const url = getEvaluationUrl(\n      projectId,\n      evaluationId,\n      this.baseUrl,\n      this.frontendPort,\n    );\n    process.stdout.write(\"\\n\");\n    process.stdout.write(\"\\nAverage scores:\\n\");\n    for (const key in averageScores) {\n      process.stdout.write(`${key}: ${averageScores[key]}\\n`);\n    }\n    process.stdout.write(`\\nCheck results at ${url}\\n`);\n  }\n}\n\nexport class Evaluation<D, T, O> {\n  private isFinished: boolean = false;\n  private progressReporter: EvaluationReporter;\n  private data: Datapoint<D, T>[] | EvaluationDataset<D, T>;\n  private executor: (data: D, ...args: any[]) => O | Promise<O>;\n  private evaluators: Record<\n    string,\n    EvaluatorFunction<O, T, D> | HumanEvaluator\n  >;\n  private groupName?: string;\n  private frontendPort?: number;\n  private name?: string;\n  private metadata?: Record<string, any>;\n  private concurrencyLimit: number = DEFAULT_CONCURRENCY;\n  private traceDisableBatch: boolean = false;\n  private traceExportTimeoutMillis?: number;\n  private traceExportBatchSize: number = MAX_EXPORT_BATCH_SIZE;\n  private uploadPromises: Promise<any>[] = [];\n  private client: LaminarClient;\n  // The remote source behind `data`, resolved once — it is invariant per run.\n  private datasetSource: LaminarDataset<D, T> | undefined;\n\n  constructor({\n    data,\n    executor,\n    evaluators,\n    groupName,\n    name,\n    metadata,\n    config,\n  }: EvaluationConstructorProps<D, T, O>) {\n    if (Object.keys(evaluators).length === 0) {\n      throw new Error(\"No evaluators provided\");\n    }\n\n    const evaluatorNameRegex = /^[\\w\\s-]+$/;\n    // Validate evaluator keys\n    for (const key in evaluators) {\n      if (!evaluatorNameRegex.test(key)) {\n        throw new Error(\n          `Invalid evaluator key: \"${key}\".` +\n            \"Keys must only contain letters, digits, hyphens, underscores, or spaces.\",\n        );\n      }\n    }\n\n    this.frontendPort = config?.frontendPort;\n    this.progressReporter = new EvaluationReporter(\n      config?.baseUrl,\n      config?.frontendPort,\n    );\n    this.data = data;\n    this.datasetSource =\n      data instanceof EvaluationDataset ? data.sourceDataset() : undefined;\n    this.executor = executor;\n    this.evaluators = evaluators;\n    this.groupName = groupName;\n    this.metadata = metadata;\n    this.name = name;\n\n    if (config) {\n      if (\n        config.concurrencyLimit !== undefined &&\n        config.concurrencyLimit < 1\n      ) {\n        logger.warn(\n          `concurrencyLimit must be greater than 0. Setting to default of ${DEFAULT_CONCURRENCY}`,\n        );\n        this.concurrencyLimit = DEFAULT_CONCURRENCY;\n      } else {\n        this.concurrencyLimit = config.concurrencyLimit ?? DEFAULT_CONCURRENCY;\n      }\n      this.traceDisableBatch = config.traceDisableBatch ?? false;\n      this.traceExportTimeoutMillis = config.traceExportTimeoutMillis;\n      this.traceExportBatchSize =\n        config.traceExportBatchSize ?? MAX_EXPORT_BATCH_SIZE;\n    }\n\n    if (Laminar.initialized()) {\n      this.client = new LaminarClient({\n        baseUrl: Laminar.getHttpUrl(),\n        projectApiKey: Laminar.getProjectApiKey(),\n      });\n      if (\n        config?.projectApiKey &&\n        config.projectApiKey !== Laminar.getProjectApiKey()\n      ) {\n        logger.warn(\n          \"Laminar was already initialized with a different project API key. \" +\n            \"Ignoring the project API key from the evaluation config.\",\n        );\n      }\n      return;\n    }\n\n    const key = config?.projectApiKey ?? process.env.LMNR_PROJECT_API_KEY;\n    if (key === undefined) {\n      throw new Error(\n        \"Please initialize the Laminar object with your project API key \" +\n          \"or set the LMNR_PROJECT_API_KEY environment variable\",\n      );\n    }\n\n    const url =\n      config?.baseUrl ?? process?.env?.LMNR_BASE_URL ?? \"https://api.lmnr.ai\";\n    const httpUrl = config?.baseHttpUrl ?? url;\n    const httpPort =\n      config?.httpPort ??\n      (httpUrl.match(/:\\d{1,5}$/g)\n        ? parseInt(httpUrl.match(/:\\d{1,5}$/g)![0].slice(1))\n        : 443);\n    const urlWithoutSlash = httpUrl\n      .replace(/\\/$/, \"\")\n      .replace(/:\\d{1,5}$/g, \"\");\n    const baseHttpUrl = `${urlWithoutSlash}:${httpPort}`;\n\n    this.client = new LaminarClient({\n      baseUrl: baseHttpUrl,\n      projectApiKey: key,\n    });\n\n    Laminar.initialize({\n      projectApiKey: config?.projectApiKey,\n      baseUrl: url,\n      baseHttpUrl,\n      httpPort,\n      grpcPort: config?.grpcPort,\n      instrumentModules: config?.instrumentModules,\n      disableBatch: this.traceDisableBatch,\n      traceExportTimeoutMillis: this.traceExportTimeoutMillis,\n      maxExportBatchSize: this.traceExportBatchSize,\n    });\n  }\n\n  public async run(): Promise<EvaluationRunResult> {\n    if (this.isFinished) {\n      throw new Error(\"Evaluation is already finished\");\n    }\n    if (this.data instanceof EvaluationDataset) {\n      // The remote source is resolved through any depth of chaining, so a\n      // subsampled dataset still gets the client injected.\n      const source = this.datasetSource;\n      source?.setClient(this.client);\n      // Fetch dataset ID if not already set\n      if (source && !source.id) {\n        try {\n          const datasets = await this.client.datasets.getDatasetByName(\n            source.name!,\n          );\n          if (datasets.length > 0) {\n            source.id = datasets[0].id;\n          } else {\n            logger.warn(`Dataset ${source.name} not found`);\n          }\n        } catch (error) {\n          // Backward compatibility with old Laminar API (self-hosted)\n          logger.warn(\n            `Error getting dataset ${source.name}: ` + errorMessage(error),\n          );\n        }\n      }\n    }\n\n    let resultDatapoints: EvaluationDatapoint<D, T, O>[];\n    try {\n      // Resolve the length first: a resolve-time failure (bad `select` index, a\n      // failed fetch) must not leave an orphan evaluation on the server.\n      const length = await this.getLength();\n      const evaluation = await this.client.evals.init(\n        this.name,\n        this.groupName,\n        withSessionMetadata(this.metadata),\n      );\n      const url = getEvaluationUrl(\n        evaluation.projectId,\n        evaluation.id,\n        this.progressReporter.baseUrl,\n        this.frontendPort,\n      );\n      process.stdout.write(`\\nCheck results at ${url}\\n`);\n      this.progressReporter.start({ length });\n\n      resultDatapoints = await this.evaluateInBatches(evaluation.id);\n      const averageScores = getAverageScores(resultDatapoints);\n      if (this.uploadPromises.length > 0) {\n        await Promise.all(this.uploadPromises);\n      }\n      this.progressReporter.stop({\n        averageScores,\n        projectId: evaluation.projectId,\n        evaluationId: evaluation.id,\n      });\n      this.isFinished = true;\n\n      await Laminar.shutdown();\n      return {\n        averageScores,\n        projectId: evaluation.projectId,\n        evaluationId: evaluation.id,\n        url,\n      };\n    } catch (e) {\n      this.progressReporter.stopWithError(e as Error);\n      this.isFinished = true;\n      return {\n        averageScores: {},\n        projectId: \"\",\n        evaluationId: \"\",\n        url: \"\",\n        errorMessage: errorMessage(e),\n      };\n    }\n  }\n\n  public async evaluateInBatches(\n    evalId: StringUUID,\n  ): Promise<EvaluationDatapoint<D, T, O>[]> {\n    const baseContext = LaminarContextManager.getContext();\n    const currentAssociationProperties = (baseContext.getValue(\n      ASSOCIATION_PROPERTIES_KEY,\n    ) ?? {}) as Record<string, any>;\n    const entityContext = baseContext.setValue(ASSOCIATION_PROPERTIES_KEY, {\n      ...currentAssociationProperties,\n      metadata: {\n        ...(currentAssociationProperties.metadata ?? {}),\n        evaluation_id: evalId,\n      },\n    });\n\n    return LaminarContextManager.runWithIsolatedContext<\n      Promise<EvaluationDatapoint<D, T, O>[]>\n    >([entityContext], async () => {\n      const semaphore = new Semaphore(this.concurrencyLimit);\n      const tasks: Promise<[number, EvaluationDatapoint<D, T, O>]>[] = [];\n\n      const evaluateTask = async (\n        datapoint: Datapoint<D, T>,\n        index: number,\n      ): Promise<[number, EvaluationDatapoint<D, T, O>]> => {\n        try {\n          const result = await this.evaluateDatapoint(evalId, datapoint, index);\n          this.progressReporter.update(1);\n          return [index, result];\n        } finally {\n          semaphore.release();\n        }\n      };\n\n      for (let i = 0; i < (await this.getLength()); i++) {\n        await semaphore.acquire();\n        const datapoint = Array.isArray(this.data)\n          ? this.data[i]\n          : await this.data.get(i);\n        tasks.push(evaluateTask(datapoint, i));\n      }\n      const results = await Promise.all(tasks);\n\n      return results.sort((a, b) => a[0] - b[0]).map(([, result]) => result);\n    });\n  }\n\n  private async evaluateDatapoint(\n    evalId: StringUUID,\n    datapoint: Datapoint<D, T>,\n    index: number,\n  ): Promise<EvaluationDatapoint<D, T, O>> {\n    return observe(\n      { name: \"evaluation\", traceType: \"EVALUATION\" },\n      async () => {\n        trace\n          .getSpan(LaminarContextManager.getContext())!\n          .setAttribute(SPAN_TYPE, \"EVALUATION\");\n        const executorSpan = Laminar.startSpan({\n          name: \"executor\",\n          input: datapoint.data,\n        });\n        executorSpan.setAttribute(SPAN_TYPE, \"EXECUTOR\");\n        const executorSpanId = otelSpanIdToUUID(\n          executorSpan.spanContext().spanId,\n        );\n        const datapointId = newUUID();\n        const partialDatapoint = {\n          id: datapointId,\n          data: datapoint.data,\n          target: datapoint.target,\n          metadata: datapoint.metadata,\n          traceId: otelTraceIdToUUID(\n            trace.getSpan(LaminarContextManager.getContext())!.spanContext()\n              .traceId,\n          ),\n          executorSpanId,\n          index,\n        } as EvaluationDatapoint<D, T, O>;\n\n        // Add dataset link if data comes from a (possibly chained) remote\n        // dataset.\n        if (this.datasetSource?.id && datapoint.id && datapoint.createdAt) {\n          partialDatapoint.datasetLink = {\n            datasetId: this.datasetSource.id,\n            datapointId: datapoint.id,\n            createdAt: datapoint.createdAt,\n          };\n        }\n\n        // first create the datapoint in the database and await\n        await this.client.evals.saveDatapoints({\n          evalId,\n          datapoints: [partialDatapoint],\n          groupName: this.groupName,\n        });\n\n        const output = await Laminar.withSpan(\n          executorSpan,\n          async () => {\n            const result = await this.executor(datapoint.data);\n            Laminar.setSpanOutput(result);\n            return result;\n          },\n          true,\n        );\n        const target = datapoint.target;\n\n        let scores: Record<string, number | null> = {};\n        for (const [evaluatorName, evaluator] of Object.entries(\n          this.evaluators,\n        )) {\n          const value = await observe(\n            { name: evaluatorName },\n            async (output: O, target?: T, data?: D) => {\n              if (evaluator instanceof HumanEvaluator) {\n                const activeSpan = trace.getSpan(\n                  LaminarContextManager.getContext(),\n                );\n                if (activeSpan) {\n                  activeSpan.setAttribute(SPAN_TYPE, \"HUMAN_EVALUATOR\");\n                  if (evaluator.options) {\n                    activeSpan.setAttribute(\n                      HUMAN_EVALUATOR_OPTIONS,\n                      JSON.stringify(evaluator.options),\n                    );\n                  }\n                }\n                return null;\n              } else {\n                const activeSpan = trace.getSpan(\n                  LaminarContextManager.getContext(),\n                );\n                if (activeSpan) {\n                  activeSpan.setAttribute(SPAN_TYPE, \"EVALUATOR\");\n                }\n                return await evaluator(output, target, data);\n              }\n            },\n            output,\n            datapoint.target,\n            datapoint.data,\n          );\n\n          if (evaluator instanceof HumanEvaluator) {\n            scores[evaluatorName] = null;\n            continue;\n          }\n\n          if (typeof value === \"number\") {\n            if (isNaN(value)) {\n              throw new Error(`Evaluator ${evaluatorName} returned NaN`);\n            }\n            scores[evaluatorName] = value;\n          } else if (value !== null) {\n            scores = { ...scores, ...value };\n          }\n        }\n\n        const resultDatapoint = {\n          id: datapointId,\n          executorOutput: output,\n          data: datapoint.data,\n          target,\n          metadata: datapoint.metadata,\n          scores,\n          traceId: otelTraceIdToUUID(\n            trace.getSpan(LaminarContextManager.getContext())!.spanContext()\n              .traceId,\n          ),\n          executorSpanId,\n          index,\n        } as EvaluationDatapoint<D, T, O>;\n\n        // Add dataset link if data comes from a (possibly chained) remote\n        // dataset.\n        if (this.datasetSource?.id && datapoint.id && datapoint.createdAt) {\n          resultDatapoint.datasetLink = {\n            datasetId: this.datasetSource.id,\n            datapointId: datapoint.id,\n            createdAt: datapoint.createdAt,\n          };\n        }\n\n        const uploadPromise = this.client.evals.saveDatapoints({\n          evalId,\n          datapoints: [resultDatapoint],\n          groupName: this.groupName,\n        });\n        this.uploadPromises.push(uploadPromise);\n\n        return resultDatapoint;\n      },\n    );\n  }\n\n  private async getLength(): Promise<number> {\n    return this.data instanceof EvaluationDataset\n      ? await this.data.size()\n      : this.data.length;\n  }\n\n  public setFrontendPort(port: number) {\n    this.frontendPort = port;\n    this.progressReporter.frontendPort = port;\n  }\n}\n\n/**\n * If added to the file which is called through lmnr eval command, then simply\n * registers the evaluation. Otherwise, returns a promise which resolves when\n * the evaluation is finished. If the evaluation has no async logic, then it\n * will be executed synchronously.\n *\n * @param props.data List of data points to evaluate. `data` is the input to the\n * executor function, `target` is the input to the evaluator function.\n * @param props.executor The executor function. Takes the data point + any\n * additional arguments and returns the output to evaluate.\n * @param props.evaluators Map from evaluator name to evaluator function. Each\n * evaluator function takes the output of the executor and the target data, and\n * returns.\n * @param props.name Optional name of the evaluation. Used to easily identify\n * the evaluation in the group.\n * @param props.metadata Optional metadata to evaluation\n * @param props.config Optional override configurations for the evaluator.\n */\nexport async function evaluate<D, T, O>({\n  data,\n  executor,\n  evaluators,\n  groupName,\n  name,\n  metadata,\n  config,\n}: EvaluationConstructorProps<D, T, O>): Promise<\n  EvaluationRunResult | undefined\n> {\n  const evaluation = new Evaluation<D, T, O>({\n    data,\n    executor,\n    evaluators,\n    name,\n    groupName,\n    metadata,\n    config,\n  });\n  if (globalThis._set_global_evaluation) {\n    // TODO: if we load files concurrently, we need to use a mutex to protect\n    // concurrent writes to globalThis._evaluations\n    globalThis._evaluations = [...(globalThis._evaluations ?? []), evaluation];\n  } else {\n    return await evaluation.run();\n  }\n}\n","import { LaminarClient } from \"@lmnr-ai/client\";\nimport {\n  errorMessage,\n  type LaminarSpanContext,\n  type StringUUID,\n} from \"@lmnr-ai/types\";\nimport {\n  ROOT_CONTEXT,\n  type Span,\n  type Tracer,\n  trace,\n} from \"@opentelemetry/api\";\nimport { type SpanProcessor } from \"@opentelemetry/sdk-trace-base\";\n\nimport { Laminar } from \"../laminar\";\nimport { getConfiguredApiKey, getTracer } from \"../opentelemetry-lib/tracing\";\nimport {\n  SPAN_INPUT,\n  SPAN_OUTPUT,\n  SPAN_TYPE,\n  TRACE_TYPE,\n} from \"../opentelemetry-lib/tracing/attributes\";\nimport { LaminarContextManager } from \"../opentelemetry-lib/tracing/context\";\nimport {\n  getFrontendUrl,\n  initializeLogger,\n  metadataToAttributes,\n  otelSpanIdToUUID,\n  otelTraceIdToUUID,\n} from \"../utils\";\n\nconst logger = initializeLogger();\n\nconst EVE_REPORTER_TRACER_NAME = \"@lmnr-ai/lmnr/eve-reporter\";\nconst EVE_CLIENT_MODULE = \"eve/client\";\nconst TRACEPARENT_HEADER = \"traceparent\";\n/** Same wire name the Temporal instrumentation uses (`temporal/consts.ts`). */\nconst LAMINAR_SPAN_CONTEXT_HEADER = \"x-lmnr-span-context\";\n/**\n * Root span name for every propagated eval, and it never changes. eve calls\n * `ClientSession.send` before any hook that knows which eval is in flight, and\n * eve exposes no `onEvalStart`, so the id simply is not knowable here. Renaming\n * the span later would invalidate the `lmnr.span.path` the processor already\n * stamped on it and on every descendant, and would make the path we propagate\n * to the agent stale. The eval id rides on `lmnr.eve.eval.id`, on the trace\n * metadata, and on the datapoint instead.\n */\nconst ROOT_SPAN_NAME = \"eve eval\";\nconst EXECUTOR_SPAN_NAME = \"executor\";\n\n/**\n * Narrow local mirrors of eve's `eve/evals` types. We intentionally do NOT\n * import from `eve` so the SDK carries no peer dependency on it (same pattern\n * as the Mastra exporter). The fields mirror eve 0.22.x; every field a reporter\n * reads is optional so a shape change on eve's side degrades gracefully instead\n * of throwing. Array fields must stay `readonly` — eve's own types are\n * readonly, and a mutable mirror is not assignable to them (TS2322 for users\n * registering the reporter).\n */\nexport interface EveEval {\n  /** Path-derived stable id of the eval, e.g. \"brooklyn-forecast\". */\n  id?: string;\n  description?: string;\n  metadata?: Record<string, any>;\n}\n\nexport interface EveEvalTarget {\n  /** \"local\" for a dev server the runner boots, \"remote\" for a deployment. */\n  kind?: string;\n  /** Base HTTP URL the eval client connects to. */\n  url?: string;\n  [key: string]: any;\n}\n\n/** How a failing assertion affects the verdict. */\nexport type EveAssertionSeverity = \"gate\" | \"soft\";\n\n/** The recorded outcome of one assertion eve ran against an eval. */\nexport interface EveAssertionResult {\n  name?: string;\n  /** Score in [0, 1]; boolean assertions score exactly 0 or 1. */\n  score?: number;\n  /** \"gate\" (hard) or \"soft\" (tracked / thresholded). */\n  severity?: EveAssertionSeverity;\n  threshold?: number;\n  passed?: boolean;\n  /** Human-readable failure detail. */\n  message?: string;\n  metadata?: Record<string, any>;\n}\n\n/** One tool call eve extracted from the captured stream. */\nexport interface EveEvalToolCall {\n  name?: string;\n  [key: string]: any;\n}\n\n/** Execution facts eve derives from a completed session's stream. */\nexport interface EveEvalDerivedFacts {\n  toolCalls?: readonly EveEvalToolCall[];\n  toolCallCount?: number;\n  subagentCallCount?: number;\n  messageCount?: number;\n  reasoningBlockCount?: number;\n  parked?: boolean;\n  failureCode?: string;\n}\n\n/** Runtime identity eve captures from the `session.started` stream event. */\nexport interface EveRuntimeIdentity {\n  agentId?: string;\n  agentName?: string;\n  eveVersion?: string;\n  modelId?: string;\n}\n\n/** Result of executing one eval against an eve agent. */\nexport interface EveEvalTaskResult {\n  /** Final structured data, or the last assistant message when absent. */\n  output?: any;\n  /** The agent's last assistant message, or null when none was produced. */\n  finalMessage?: string | null;\n  /** eve session id after the first successful send. */\n  sessionId?: string;\n  /** How the run's final turn ended. */\n  status?: \"completed\" | \"failed\" | \"waiting\";\n  logs?: readonly string[];\n  derived?: EveEvalDerivedFacts;\n  runtimeIdentity?: EveRuntimeIdentity;\n}\n\n/** Per-eval verdict computed by the runner. */\nexport type EveEvalVerdict = \"passed\" | \"failed\" | \"scored\" | \"skipped\";\n\n/** Result of executing and asserting one eval. eve hands this to reporters. */\nexport interface EveEvalResult {\n  /** Path-derived eval id (e.g. \"weather\"). */\n  id?: string;\n  /** Execution result (output, session, derived facts). */\n  result?: EveEvalTaskResult;\n  /** Every assertion recorded by the eval's `test(t)`, in record order. */\n  assertions?: readonly EveAssertionResult[];\n  /** Per-eval verdict. */\n  verdict?: EveEvalVerdict;\n  /** Execution error message, when the eval threw. */\n  error?: string;\n  /** Reason supplied to `t.skip(reason)`. */\n  skipReason?: string;\n  startedAt?: string;\n  completedAt?: string;\n}\n\nexport interface EveEvalRunSummary {\n  total?: number;\n  passed?: number;\n  failed?: number;\n  scored?: number;\n  skipped?: number;\n  errored?: number;\n  [key: string]: any;\n}\n\n/**\n * The contract eve invokes. Mirrors `EvalReporter` from `eve/evals/reporters`.\n */\nexport interface EvalReporter {\n  onRunStart(\n    evaluations: readonly EveEval[],\n    target: EveEvalTarget,\n  ): void | Promise<void>;\n  onEvalComplete(result: EveEvalResult): void | Promise<void>;\n  onRunComplete(summary: EveEvalRunSummary): void | Promise<void>;\n}\n\nexport interface LaminarReporterOptions {\n  /** Name of the Laminar evaluation created for the run. */\n  name?: string;\n  /** Group name to chart regressions across runs of the same eval suite. */\n  groupName?: string;\n  /** Metadata attached to the Laminar evaluation. */\n  metadata?: Record<string, any>;\n  /** Project API key. Falls back to `LMNR_PROJECT_API_KEY`. */\n  projectApiKey?: string;\n  /** Override the Laminar API base URL (e.g. for self-hosted). */\n  baseUrl?: string;\n  /**\n   * Provide a pre-constructed client (e.g. to share auth across reporters).\n   * When set, `projectApiKey` / `baseUrl` are ignored.\n   */\n  client?: LaminarClient;\n  /**\n   * Span processor for the tracing this reporter initializes. Intended for\n   * tests; production defaults to Laminar's. Ignored when something already\n   * called `Laminar.initialize()` — see {@link LaminarReporter.ensureTracing}.\n   */\n  spanProcessor?: SpanProcessor;\n  /**\n   * Mint the trace in the runner and push it to the agent as a `traceparent`\n   * header (see {@link patchEveClientSession}). Defaults to `true`. Set `false`\n   * only to disable the patch — every datapoint then links to a reporter-owned\n   * trace that holds the grade but none of the agent's work.\n   */\n  propagateTraceContext?: boolean;\n}\n\n// ─── Trace-context propagation ────────────────────────────────────────────────\n// The runner MINTS the trace: before eve's client sends a turn, the reporter\n// opens the eval's root Laminar span and injects its W3C `traceparent` into the\n// request headers. eve's agent adopts it as the parent of the turn when\n// `agent/instrumentation.ts` sets `traceChannelRequests: true`, so the datapoint\n// needs no lookup at all.\n\n/** The subset of eve's `MessageResponse` the patch reads. */\ninterface EveMessageResponse {\n  readonly sessionId?: string;\n}\n\n/** The subset of eve's `SendTurnPayload` the patch rewrites. */\ninterface EveSendTurnPayload {\n  headers?: Record<string, string>;\n  [key: string]: unknown;\n}\n\ntype EveSend = (this: object, input: unknown) => Promise<EveMessageResponse>;\n\n/** The subset of eve's `ClientSession` class the patch needs. */\nexport interface EveClientSessionClass {\n  prototype: object & { send?: EveSend };\n}\n\n/** One eve client session's Laminar trace, minted on its first `send`. */\ninterface EveSessionTrace {\n  /** Laminar trace id every span and the datapoint share. */\n  traceId: StringUUID;\n  /** Root EVALUATION span; the Laminar trace's root. */\n  rootSpan: Span;\n  /** EXECUTOR child the agent's turn hangs off; the `traceparent` parent. */\n  executorSpan: Span;\n  /** Tracer used for the EVALUATOR children created at grade time. */\n  tracer: Tracer;\n  /** Headers merged into every `send` on this client session. */\n  headers: Record<string, string>;\n  /** eve session ids this client session reported. */\n  sessionIds: Set<string>;\n  ended: boolean;\n}\n\n/** Prototypes already patched — `send` must never be wrapped twice. */\nconst patchedSendPrototypes = new WeakSet<object>();\n/**\n * Per-eve-client-session state. Keyed off the `ClientSession` instance rather\n * than an AsyncLocalStorage frame or a \"current eval\" global: eve runs up to\n * `maxConcurrency` evals at once, and each eval builds its own `ClientSession`\n * (`EvalSessionManager` calls `client.session()` per `EvalSessionDriver`), so\n * the instance is the only correct correlation key available inside `send`.\n */\nconst traceByClientSession = new WeakMap<object, EveSessionTrace>();\n/** eve session id -> trace, read by `onEvalComplete` via `result.sessionId`. */\nconst traceByEveSessionId = new Map<string, EveSessionTrace>();\n/** Set by the running reporter's `onRunStart`; cleared by `onRunComplete`. */\nlet activeSessionTraceFactory: (() => EveSessionTrace | undefined) | null =\n  null;\n\n/** Mirrors eve's own `normalizeSendTurnInput`, then merges the trace headers. */\nconst withTraceHeaders = (\n  input: unknown,\n  headers: Record<string, string>,\n): EveSendTurnPayload => {\n  const payload: EveSendTurnPayload =\n    typeof input === \"string\"\n      ? { message: input }\n      : { ...(input as EveSendTurnPayload) };\n  payload.headers = { ...(payload.headers ?? {}), ...headers };\n  return payload;\n};\n\nconst openSessionTrace = (\n  clientSession: object,\n): EveSessionTrace | undefined => {\n  try {\n    const existing = traceByClientSession.get(clientSession);\n    if (existing) {\n      return existing;\n    }\n    const minted = activeSessionTraceFactory?.();\n    if (minted) {\n      traceByClientSession.set(clientSession, minted);\n    }\n    return minted;\n  } catch (error) {\n    logger.warn(\n      `Laminar eve reporter: failed to open a session trace: ` +\n        errorMessage(error),\n    );\n    return undefined;\n  }\n};\n\n/**\n * eve assigns the session id on the POST that `send` awaits, so the returned\n * `MessageResponse` is the earliest place the runner can bind the eve session\n * id to the trace it minted.\n */\nconst recordEveSessionId = (\n  response: EveMessageResponse | undefined,\n  sessionTrace: EveSessionTrace,\n): void => {\n  const sessionId = response?.sessionId;\n  if (typeof sessionId !== \"string\" || sessionId.length === 0) {\n    return;\n  }\n  sessionTrace.sessionIds.add(sessionId);\n  traceByEveSessionId.set(sessionId, sessionTrace);\n};\n\n/**\n * Build the propagation headers for the EXECUTOR span. Plain HTTP strings — eve\n * forwards `SendTurnPayload.headers` verbatim to `fetch`.\n *\n * The Laminar context carries the full path. Laminar nests spans by\n * `lmnr.span.ids_path`, not by OTel `parentSpanId`, so a receiver that adopts\n * only the ids lands its spans as a second root on our trace. The path is what\n * makes the agent's subtree render UNDER the executor. Both paths are constants\n * here — neither the root nor the executor span is ever renamed.\n */\nconst buildTraceHeaders = (\n  rootSpan: Span,\n  executorSpan: Span,\n): Record<string, string> => {\n  const spanContext = executorSpan.spanContext();\n  const laminarContext: LaminarSpanContext = {\n    traceId: otelTraceIdToUUID(spanContext.traceId),\n    spanId: otelSpanIdToUUID(spanContext.spanId) as StringUUID,\n    isRemote: true,\n    spanPath: [ROOT_SPAN_NAME, EXECUTOR_SPAN_NAME],\n    spanIdsPath: [\n      otelSpanIdToUUID(rootSpan.spanContext().spanId) as StringUUID,\n      otelSpanIdToUUID(spanContext.spanId) as StringUUID,\n    ],\n  };\n  return {\n    // eve reads ONLY `traceparent` (see its `traceChannelRequest`).\n    [TRACEPARENT_HEADER]: `00-${spanContext.traceId}-${spanContext.spanId}-01`,\n    // For Laminar-aware agents; eve ignores it.\n    [LAMINAR_SPAN_CONTEXT_HEADER]: JSON.stringify(laminarContext),\n  };\n};\n\n/**\n * Bind this session's ROOT span into the calling eval's async context, so work\n * the eval does in the RUNNER process after `send` resolves lands on this trace\n * instead of opening its own. The concrete case is `t.judge.autoevals.*`: eve\n * runs the judge's model call in the runner, and Laminar's AI SDK integration\n * parents it to `LaminarContextManager.getContext()`.\n *\n * The root — not a pre-opened judge span — is the binding target on purpose.\n * An eval may record any number of judge assertions, and each one runs its own\n * model call. Binding the root gives every judge its own child of the root; a\n * single pre-opened parent would collect all of them under whichever judge\n * happened to run first.\n *\n * `pushContext` uses `AsyncLocalStorage.enterWith`, so this MUST run\n * synchronously before `send`'s first `await` — at that point we are still\n * executing in the caller's async context, so the store we set is the one\n * `test(t)` continues with. Each eval's `test(t)` runs in its own async chain,\n * so concurrent evals never see each other's root span; do NOT replace this\n * with the process-global context stack, which would cross-attribute.\n *\n * Judge spans reach Laminar only when the runner opts in — `Laminar.initialize()`\n * plus a globally registered AI SDK telemetry integration. Without that the\n * binding is inert, never wrong.\n *\n * Never popped: the store dies with the eval's async chain.\n */\nconst bindEvalContext = (sessionTrace: EveSessionTrace): void => {\n  try {\n    LaminarContextManager.pushContext(\n      trace.setSpan(ROOT_CONTEXT, sessionTrace.rootSpan),\n    );\n  } catch (error) {\n    logger.warn(\n      `Laminar eve reporter: failed to bind the eval context: ` +\n        errorMessage(error),\n    );\n  }\n};\n\n/**\n * Wrap `ClientSession.prototype.send` so every eve turn carries the trace\n * context of a runner-minted Laminar span. Idempotent per prototype.\n *\n * @internal Exported for tests, which drive it with a stub class so the suite\n * keeps no dependency on eve.\n */\nexport const patchEveClientSession = (\n  sessionClass: EveClientSessionClass | undefined,\n): boolean => {\n  const prototype = sessionClass?.prototype;\n  const original = prototype?.send;\n  if (!prototype || typeof original !== \"function\") {\n    return false;\n  }\n  if (patchedSendPrototypes.has(prototype)) {\n    return true;\n  }\n  // A prototype method needs a real `this`, so this cannot be an arrow.\n  prototype.send = async function (this: object, input: unknown) {\n    const sessionTrace = openSessionTrace(this);\n    if (!sessionTrace) {\n      return original.call(this, input);\n    }\n    bindEvalContext(sessionTrace);\n    const response = await original.call(\n      this,\n      withTraceHeaders(input, sessionTrace.headers),\n    );\n    try {\n      recordEveSessionId(response, sessionTrace);\n    } catch (error) {\n      logger.warn(\n        `Laminar eve reporter: failed to record the eve session id: ` +\n          errorMessage(error),\n      );\n    }\n    return response;\n  };\n  patchedSendPrototypes.add(prototype);\n  return true;\n};\n\n/**\n * Load eve's `ClientSession` without depending on eve. Mirrors the guarded\n * dynamic import in eve's own Braintrust reporter (`loadBraintrustSdk`), except\n * a missing eve degrades instead of throwing — the reporter must keep working\n * when it is registered outside an eve run.\n */\nconst loadEveClientSession = async (): Promise<\n  EveClientSessionClass | undefined\n> => {\n  try {\n    const module = (await import(EVE_CLIENT_MODULE)) as {\n      ClientSession?: unknown;\n    };\n    const sessionClass = module.ClientSession;\n    return typeof sessionClass === \"function\" ? sessionClass : undefined;\n  } catch {\n    return undefined;\n  }\n};\n\nconst didAssertionPass = (assertion: EveAssertionResult): boolean => {\n  if (typeof assertion.passed === \"boolean\") {\n    return assertion.passed;\n  }\n  // Degradation path: eve's real AssertionResult always carries `passed`, so\n  // this only runs when eve's shape drifted. Infer from score semantics rather\n  // than defaulting to passed — a failed gate must never read as a pass.\n  if (typeof assertion.score === \"number\") {\n    if (typeof assertion.threshold === \"number\") {\n      return assertion.score >= assertion.threshold;\n    }\n    if (assertion.severity === \"gate\") {\n      // Gates score exactly 0 or 1.\n      return assertion.score > 0;\n    }\n  }\n  return true;\n};\n\n/**\n * Keep Laminar's top-level score columns stable across heterogeneous eve evals.\n * Detailed assertion outcomes live in metadata; sparse per-assertion score keys\n * make Laminar's eval UI look incomplete when different eval files assert\n * different things.\n */\nconst resultToScores = (result: EveEvalResult): Record<string, number> => {\n  const assertions = result.assertions ?? [];\n  const gateAssertions = assertions.filter(\n    (assertion) => assertion.severity === \"gate\",\n  );\n  const thresholdedSoftAssertions = assertions.filter(\n    (assertion) =>\n      assertion.severity === \"soft\" && typeof assertion.threshold === \"number\",\n  );\n\n  return {\n    \"eve.verdict.passed\": result.verdict === \"passed\" ? 1 : 0,\n    \"eve.gates.passed\": gateAssertions.every(didAssertionPass) ? 1 : 0,\n    \"eve.soft_thresholds.passed\": thresholdedSoftAssertions.every(\n      didAssertionPass,\n    )\n      ? 1\n      : 0,\n  };\n};\n\nconst assertionsMetadata = (\n  assertions: readonly EveAssertionResult[],\n): Array<Record<string, any>> =>\n  assertions.map((assertion) => ({\n    name: assertion.name,\n    score: assertion.score,\n    severity: assertion.severity,\n    threshold: assertion.threshold,\n    passed: assertion.passed,\n    message: assertion.message,\n    metadata: assertion.metadata,\n  }));\n\n/** Surface failed assertions in metadata so a failing run is debuggable. */\nconst failedAssertionsMetadata = (\n  assertions: readonly EveAssertionResult[],\n): Record<string, any> => {\n  const failed = assertions\n    .filter((assertion) => !didAssertionPass(assertion))\n    .map((assertion) => ({ name: assertion.name, message: assertion.message }));\n  return failed.length > 0 ? { failedAssertions: failed } : {};\n};\n\nconst traceIdFromSpan = (span: Span) =>\n  otelTraceIdToUUID(span.spanContext().traceId);\n\ntype TraceResolution =\n  | { traceId: string; source: \"propagated\"; sessionTrace: EveSessionTrace }\n  | { traceId: string; source: \"reporter-fallback\"; span: Span };\n\n/**\n * A Laminar reporter for eve evals. Register it globally in `evals.config.ts`\n * or per-eval via the `reporters` field — eve runs and grades each eval, then\n * hands the graded result here, and this reporter ships it to Laminar as an\n * evaluation run with one datapoint per eval.\n *\n * The datapoint's trace id is never looked up — the reporter OWNS the trace.\n * `patchEveClientSession` wraps eve's `ClientSession.send` and mints the\n * EVALUATION root + EXECUTOR child on the first turn of each session, so the\n * runner already knows the trace id and pushes it to the agent as a\n * `traceparent` header. The eve session id is only the in-process key that ties\n * the send we instrumented to the graded result eve hands back later.\n *\n * Two outcomes, recorded on `metadata.traceResolution`:\n *\n * 1. `\"propagated\"` — the normal path, above. The agent joins the trace only\n *    when `agent/instrumentation.ts` sets `traceChannelRequests: true` and the\n *    agent process runs with `WORKFLOW_TRACE_MODE=continuous`.\n * 2. `\"reporter-fallback\"` — no session trace was minted (propagation disabled,\n *    or eve produced no session id). The reporter opens its own EVALUATION span\n *    so the grade still lands somewhere debuggable; it holds no agent work.\n *\n * `t.judge.autoevals.*` model calls run in the RUNNER process, and they reach\n * Laminar only when the runner registers an AI SDK telemetry integration. eve\n * imports `generateText` inside its own bundle, so `wrapAISDK` cannot reach it —\n * but AI SDK v7 reads registered integrations off `globalThis`, which does. One\n * line in `evals.config.ts`:\n *\n * ```ts\n * registerTelemetry(new LaminarAiSdkTelemetry());\n * ```\n *\n * Judge spans and eve eval spans then share ONE tracer provider — whichever of\n * the two initialized Laminar first (see {@link LaminarReporter.ensureTracing}).\n * Each judge gets its own span under the eval's root — see\n * {@link bindEvalContext}, and {@link LaminarReporter.flush} for how spans ship.\n * Without that line the reporter still records every assertion's score as an\n * EVALUATOR span; only the model call is missing.\n *\n * @example\n * ```ts\n * import { defineEvalConfig } from \"eve/evals\";\n * import { LaminarReporter } from \"@lmnr-ai/lmnr\";\n *\n * export default defineEvalConfig({\n *   reporters: [new LaminarReporter({ name: \"weather-agent\" })],\n * });\n * ```\n */\nexport class LaminarReporter implements EvalReporter {\n  private readonly options: LaminarReporterOptions;\n  private client?: LaminarClient;\n  private evalId?: string;\n  private evalsById = new Map<string, EveEval>();\n  private index = 0;\n  /** Session traces minted this run and not yet graded. */\n  private openSessionTraces = new Set<EveSessionTrace>();\n  /** Stable identity so `onRunComplete` only clears its own registration. */\n  private readonly sessionTraceFactory = (): EveSessionTrace | undefined =>\n    this.mintSessionTrace();\n\n  constructor(options: LaminarReporterOptions = {}) {\n    this.options = options;\n  }\n\n  async onRunStart(\n    evaluations: readonly EveEval[],\n    target: EveEvalTarget,\n  ): Promise<void> {\n    // Reset up front so a reused reporter whose start fails cannot attach this\n    // run's results to a previous run's evaluation.\n    this.evalId = undefined;\n    this.evalsById = new Map(\n      evaluations\n        .filter(\n          (evaluation): evaluation is EveEval & { id: string } =>\n            typeof evaluation.id === \"string\",\n        )\n        .map((evaluation) => [evaluation.id, evaluation]),\n    );\n    this.index = 0;\n    // Spans from a previous run that never reached onRunComplete (eve crashed\n    // mid-run) are closed here rather than abandoned mid-trace.\n    this.finishOpenSessionTraces();\n    try {\n      this.client =\n        this.options.client ??\n        new LaminarClient({\n          baseUrl: this.options.baseUrl,\n          projectApiKey: this.options.projectApiKey,\n        });\n      this.ensureTracing();\n      // Register the factory and patch eve BEFORE `evals.init` — eve awaits\n      // `onRunStart` before the first eval, but the patch has to be in place\n      // for the very first `send`, and a slow init must not shrink that margin.\n      if (this.options.propagateTraceContext !== false) {\n        activeSessionTraceFactory = this.sessionTraceFactory;\n        patchEveClientSession(await loadEveClientSession());\n      }\n      const evaluation = await this.client.evals.init(\n        this.options.name,\n        this.options.groupName,\n        {\n          // User metadata first so the run facts below always win on key\n          // collisions — `source: \"eve\"` etc. are used for attribution.\n          ...(this.options.metadata ?? {}),\n          source: \"eve\",\n          targetKind: target?.kind,\n          targetUrl: target?.url,\n          evalCount: evaluations.length,\n        },\n      );\n      this.evalId = evaluation.id;\n      // Same line the native evaluator prints. Without it a run reports nothing\n      // about where its results went, and eve's own output never mentions it.\n      const url =\n        getFrontendUrl(this.client.configuredBaseUrl ?? this.options.baseUrl) +\n        `/project/${evaluation.projectId}/evaluations/${evaluation.id}`;\n      process.stdout.write(`\\nLaminar: check eve eval results at ${url}\\n`);\n    } catch (error) {\n      logger.error(\n        `Laminar eve reporter: failed to start run: ${errorMessage(error)}`,\n      );\n      if (!this.evalId) {\n        // No evaluation to attach results to, so stop minting traces for it.\n        // A live factory would keep opening an EVALUATION span on every `send`\n        // that `onEvalComplete` then drops on its `!evalId` guard, and\n        // `onRunComplete` would still flush those orphans to Laminar.\n        this.client = undefined;\n        if (activeSessionTraceFactory === this.sessionTraceFactory) {\n          activeSessionTraceFactory = null;\n        }\n      }\n    }\n  }\n\n  async onEvalComplete(result: EveEvalResult): Promise<void> {\n    // Capture run state in locals: `this.evalId` is cleared by onRunComplete and\n    // replaced by a later onRunStart, so re-reading it after an await could pair\n    // this run's datapoint with another run's evaluation.\n    const client = this.client;\n    const evalId = this.evalId;\n    if (!client || !evalId) {\n      // onRunStart failed; nothing to attach this result to.\n      return;\n    }\n    const index = this.index++;\n    const task = result.result ?? {};\n    const derived = task.derived ?? {};\n    const assertions = result.assertions ?? [];\n    const evalDefinition =\n      typeof result.id === \"string\" ? this.evalsById.get(result.id) : undefined;\n    const evalDescription = evalDefinition?.description;\n    const traceResolution = this.resolveDatapointTrace({\n      evalId: result.id ?? String(index),\n      description: evalDescription,\n      verdict: result.verdict,\n      sessionId: task.sessionId,\n    });\n    try {\n      const datapointId = await client.evals.createDatapoint({\n        evalId,\n        // eve drives the agent itself; the eval id is the closest thing to an\n        // input the reporter is handed (the prompt lives inside `test(t)`).\n        data: result.id ?? null,\n        target: task.finalMessage ?? null,\n        index,\n        traceId: traceResolution.traceId,\n        metadata: {\n          name: result.id,\n          verdict: result.verdict,\n          status: task.status,\n          description: evalDescription,\n          sessionId: task.sessionId,\n          traceResolution: traceResolution.source,\n          skipReason: result.skipReason,\n          error: result.error,\n          toolCalls: (derived.toolCalls ?? [])\n            .map((call) => call.name)\n            .filter((name): name is string => typeof name === \"string\"),\n          toolCallCount: derived.toolCallCount,\n          parked: derived.parked,\n          failureCode: derived.failureCode,\n          modelId: task.runtimeIdentity?.modelId,\n          assertions: assertionsMetadata(assertions),\n          ...failedAssertionsMetadata(assertions),\n        },\n      });\n\n      const executorOutput = task.output ?? task.finalMessage ?? null;\n      await client.evals.updateDatapoint({\n        evalId,\n        datapointId,\n        scores: resultToScores(result),\n        executorOutput,\n      });\n    } catch (error) {\n      if (traceResolution.source === \"reporter-fallback\") {\n        traceResolution.span.recordException(error as Error);\n      }\n      logger.error(\n        `Laminar eve reporter: failed to report eval ` +\n          `\"${result.id ?? index}\": ${errorMessage(error)}`,\n      );\n    } finally {\n      if (traceResolution.source === \"reporter-fallback\") {\n        traceResolution.span.end();\n      }\n      if (traceResolution.source === \"propagated\") {\n        this.finishSessionTrace(traceResolution.sessionTrace, {\n          evalId: result.id,\n          description: evalDescription,\n          verdict: result.verdict,\n          status: task.status,\n          output: task.output ?? task.finalMessage ?? null,\n          assertions,\n        });\n      }\n      // Both paths own their trace, so eval metadata is stamped as span\n      // attributes before this flush. Pushing it over HTTP instead would race\n      // the ingest of the very spans that create the trace.\n      await this.flush();\n    }\n  }\n\n  async onRunComplete(): Promise<void> {\n    // Laminar derives average scores server-side from the datapoints, so there\n    // is nothing to push here. Datapoint writes are awaited per-eval already.\n    // Secondary eve sessions (`t.sessions.newSession()`) and evals that threw\n    // before producing a session id never reach onEvalComplete, so their spans\n    // are closed here.\n    this.finishOpenSessionTraces();\n    if (activeSessionTraceFactory === this.sessionTraceFactory) {\n      activeSessionTraceFactory = null;\n    }\n    await this.flush();\n    this.evalId = undefined;\n    this.evalsById.clear();\n  }\n\n  /**\n   * Point the process's Laminar tracing at this reporter's project, unless\n   * something already initialized it. Mirrors `LaminarAiSdkTelemetry`, which\n   * initializes the same way for judge spans — so eve eval spans and judge\n   * spans share ONE tracer provider however the run was set up. Without this,\n   * `getTracer()` returns a noop whenever nobody registered the AI SDK\n   * integration, and every eve span would be dropped silently.\n   */\n  private ensureTracing(): void {\n    if (Laminar.initialized()) {\n      // Spans follow the initialized pipeline's project; datapoints follow the\n      // reporter's client. Same key is the normal case and stays silent — a\n      // genuine mismatch would put the datapoints and their traces in different\n      // projects, so the trace ids they reference would not resolve.\n      const ourKey = this.client?.apiKey ?? this.options.projectApiKey;\n      const tracingKey = getConfiguredApiKey();\n      if (ourKey && tracingKey && ourKey !== tracingKey) {\n        logger.warn(\n          \"Laminar eve reporter: Laminar is already initialized with a different \" +\n            \"project API key. eve eval spans go to that project while datapoints go \" +\n            \"to the reporter's, so datapoint trace ids will not resolve. Point both \" +\n            \"at the same project.\",\n        );\n      }\n      return;\n    }\n    Laminar.initialize({\n      // Derive from the client so a pre-constructed `client` option and the\n      // spans it links to share auth and base URL.\n      projectApiKey: this.client?.apiKey ?? this.options.projectApiKey,\n      baseUrl: this.client?.configuredBaseUrl ?? this.options.baseUrl,\n      spanProcessor: this.options.spanProcessor,\n      // Registering a reporter is not consent to monkey-patch the runner's LLM\n      // and vector-store libraries, which is what the default (`undefined`)\n      // does. A host that wants auto-instrumentation calls\n      // `Laminar.initialize()` itself — it runs at `evals.config.ts` module\n      // load, long before `onRunStart`, so its options win.\n      instrumentModules: {},\n      // eve ends `eve eval` with `process.exit()`, which skips `beforeExit`, so\n      // a batch queue has no reliable drain point beyond our own flushes.\n      disableBatch: true,\n    });\n  }\n\n  /**\n   * Flush the process's Laminar pipeline — eve eval spans AND judge spans, which\n   * now share one provider. eve ends `eve eval` with `process.exit()` (skipping\n   * `beforeExit`), so these calls are the only points at which spans ship.\n   * Never `shutdown()`: the pipeline may belong to the host, not to us.\n   */\n  private async flush(): Promise<void> {\n    try {\n      await Laminar.flush();\n    } catch (error) {\n      logger.warn(\n        `Laminar eve reporter: failed to flush spans: ` + errorMessage(error),\n      );\n    }\n  }\n\n  /**\n   * Open the eval's Laminar spans for one eve client session: an EVALUATION\n   * root plus the EXECUTOR child the agent's turn is parented to. Called from\n   * the patched `send`, so it must never throw into the user's eval.\n   */\n  private mintSessionTrace(): EveSessionTrace | undefined {\n    const tracer = getTracer();\n    // ROOT_CONTEXT, not the active context: concurrent evals must not nest\n    // inside whichever span happens to be active on the runner's stack.\n    const rootSpan = tracer.startSpan(\n      ROOT_SPAN_NAME,\n      {\n        attributes: {\n          [SPAN_TYPE]: \"EVALUATION\",\n          [TRACE_TYPE]: \"EVALUATION\",\n          \"lmnr.eve.reporter\": EVE_REPORTER_TRACER_NAME,\n        },\n      },\n      ROOT_CONTEXT,\n    );\n    // TRACE_TYPE is stamped on descendants too, matching what `observe`'s\n    // association properties give the native evaluator on every child span.\n    const executorSpan = tracer.startSpan(\n      EXECUTOR_SPAN_NAME,\n      {\n        attributes: {\n          [SPAN_TYPE]: \"EXECUTOR\",\n          [TRACE_TYPE]: \"EVALUATION\",\n        },\n      },\n      trace.setSpan(ROOT_CONTEXT, rootSpan),\n    );\n    const sessionTrace: EveSessionTrace = {\n      traceId: otelTraceIdToUUID(rootSpan.spanContext().traceId),\n      rootSpan,\n      executorSpan,\n      tracer,\n      headers: buildTraceHeaders(rootSpan, executorSpan),\n      sessionIds: new Set(),\n      ended: false,\n    };\n    this.openSessionTraces.add(sessionTrace);\n    return sessionTrace;\n  }\n\n  /** Grade, close and release one session trace. Idempotent. */\n  private finishSessionTrace(\n    sessionTrace: EveSessionTrace,\n    grade: {\n      evalId?: string;\n      description?: string;\n      verdict?: EveEvalVerdict;\n      status?: string;\n      output?: any;\n      assertions?: readonly EveAssertionResult[];\n    },\n  ): void {\n    if (sessionTrace.ended) {\n      return;\n    }\n    sessionTrace.ended = true;\n    this.openSessionTraces.delete(sessionTrace);\n    for (const sessionId of sessionTrace.sessionIds) {\n      traceByEveSessionId.delete(sessionId);\n    }\n    try {\n      sessionTrace.rootSpan.setAttributes({\n        \"lmnr.eve.eval.id\": grade.evalId ?? \"\",\n        \"lmnr.eve.eval.verdict\": grade.verdict ?? \"\",\n        \"lmnr.eve.eval.status\": grade.status ?? \"\",\n        [SPAN_INPUT]: JSON.stringify({\n          evalId: grade.evalId,\n          description: grade.description,\n        }),\n        [SPAN_OUTPUT]: JSON.stringify(grade.output ?? null),\n        // Trace metadata is stamped as span attributes, never pushed over HTTP —\n        // the spans that create this trace have not been flushed yet, so a\n        // metadata POST would race its own ingest.\n        ...metadataToAttributes({\n          source: \"eve\",\n          eveEvalId: grade.evalId ?? \"\",\n          eveEvalDescription: grade.description ?? \"\",\n          eveEvalVerdict: grade.verdict ?? \"\",\n          eveSessionId: [...sessionTrace.sessionIds].join(\",\"),\n        }),\n      });\n      sessionTrace.executorSpan.setAttribute(\n        SPAN_OUTPUT,\n        JSON.stringify(grade.output ?? null),\n      );\n      this.recordEvaluatorSpans(sessionTrace, grade.assertions ?? []);\n      sessionTrace.executorSpan.end();\n      sessionTrace.rootSpan.end();\n    } catch (error) {\n      logger.warn(\n        `Laminar eve reporter: failed to finish the session trace: ` +\n          errorMessage(error),\n      );\n    }\n  }\n\n  /**\n   * One EVALUATOR span per eve assertion, judge or not. They are created at\n   * grade time (the assertions only exist then) as short children of the\n   * still-open root. No explicit parent path is needed: the root keeps the name\n   * it was minted with, so the processor's cached path for it is still correct.\n   */\n  private recordEvaluatorSpans(\n    sessionTrace: EveSessionTrace,\n    assertions: readonly EveAssertionResult[],\n  ): void {\n    const rootContext = trace.setSpan(ROOT_CONTEXT, sessionTrace.rootSpan);\n    for (const assertion of assertions) {\n      const name = assertion.name ?? \"assertion\";\n      const output = JSON.stringify({\n        score: assertion.score ?? null,\n        passed: didAssertionPass(assertion),\n        severity: assertion.severity,\n        threshold: assertion.threshold,\n        message: assertion.message,\n      });\n      sessionTrace.tracer\n        .startSpan(\n          name,\n          {\n            attributes: {\n              [SPAN_TYPE]: \"EVALUATOR\",\n              [TRACE_TYPE]: \"EVALUATION\",\n              [SPAN_OUTPUT]: output,\n            },\n          },\n          rootContext,\n        )\n        .end();\n    }\n  }\n\n  private finishOpenSessionTraces(): void {\n    for (const sessionTrace of [...this.openSessionTraces]) {\n      this.finishSessionTrace(sessionTrace, {});\n    }\n  }\n\n  /**\n   * Resolve the trace this datapoint links to. There is no lookup: either\n   * `patchEveClientSession` already minted the session's trace (and we know its\n   * id), or we open a reporter-owned EVALUATION span to hold the grade.\n   */\n  private resolveDatapointTrace({\n    evalId,\n    description,\n    verdict,\n    sessionId,\n  }: {\n    evalId: string;\n    description?: string;\n    verdict?: EveEvalVerdict;\n    sessionId?: string;\n  }): TraceResolution {\n    const sessionTrace = sessionId\n      ? traceByEveSessionId.get(sessionId)\n      : undefined;\n    if (sessionTrace) {\n      return {\n        traceId: sessionTrace.traceId,\n        source: \"propagated\",\n        sessionTrace,\n      };\n    }\n\n    const span = getTracer().startSpan(\n      `eve eval ${evalId}`,\n      {\n        attributes: {\n          [SPAN_TYPE]: \"EVALUATION\",\n          // Same pair `mintSessionTrace` stamps: the trace type is what associates\n          // the trace with the evaluation, and a datapoint on a trace without it\n          // loses that association.\n          [TRACE_TYPE]: \"EVALUATION\",\n          \"lmnr.eve.reporter\": EVE_REPORTER_TRACER_NAME,\n          \"lmnr.eve.eval.id\": evalId,\n          \"lmnr.eve.eval.verdict\": verdict ?? \"\",\n          ...(sessionId ? { \"lmnr.eve.session.id\": sessionId } : {}),\n          \"lmnr.eve.trace_resolution\": \"reporter-fallback\",\n          // Stamped as attributes rather than pushed over HTTP: this trace is\n          // created by the span we are opening right now, so a metadata POST would\n          // race its own ingest and fail with \"Trace ... not found\".\n          ...metadataToAttributes({\n            source: \"eve\",\n            eveEvalId: evalId,\n            eveEvalDescription: description ?? \"\",\n            eveEvalVerdict: verdict ?? \"\",\n            eveSessionId: sessionId ?? \"\",\n          }),\n        },\n        // ROOT_CONTEXT for the same reason `mintSessionTrace` uses it, and this\n        // path needs it more: the datapoint's `traceId` is read straight off this\n        // span. `getTracer()` defaults to `LaminarContextManager.getContext()`, so\n        // without it another eval's root — bound by `bindEvalContext`, or pushed\n        // by any `startActiveSpan({ global: true })` in the runner — adopts this\n        // span and the datapoint silently links to that eval's trace.\n      },\n      ROOT_CONTEXT,\n    );\n    return {\n      traceId: traceIdFromSpan(span),\n      source: \"reporter-fallback\",\n      span,\n    };\n  }\n}\n","/**\n * Debug-replay input hashing.\n *\n * Computes the per-LLM-call `input_hash` the server-side debugger cache (v2) is\n * keyed by. The SDK and the Rust app-server MUST produce byte-identical hashes,\n * so this is a faithful port of the app-server primitives:\n *   - `canonical_json`     — `app-server/src/traces/input_dedup.rs`\n *   - `debug_input_hash`   — `app-server/src/traces/input_dedup.rs`\n *\n * The whole non-system message array is hashed as ONE blob: strip EVERY\n * `role === \"system\"` message (regardless of content or position), canonicalize\n * the remaining array, then blake3 over its UTF-8 bytes and hex-encode the\n * digest.\n *\n * Keep this file line-comparable with the Python `debug/hash.py`.\n */\n\nimport { blake3 } from \"@noble/hashes/blake3.js\";\nimport { bytesToHex } from \"@noble/hashes/utils.js\";\n\n/**\n * JSON with object keys sorted lexicographically (recursively); array order is\n * preserved. Mirrors Rust `canonical_json`.\n *\n * Limitation (parity with v1 server): there is NO number canonicalization, so a\n * value parsed as `1.0` serializes as `1` here (JS) and as `1.0` under serde —\n * a known v1 gap, documented in the shared spec §5.1. Object keys are assumed\n * ASCII (message-shape keys always are), so default UTF-16 sort matches Rust's\n * byte-wise `String::cmp`.\n */\nexport const canonicalJson = (value: unknown): string => {\n  if (value === null || value === undefined) {\n    return \"null\";\n  }\n  if (Array.isArray(value)) {\n    return `[${value.map(canonicalJson).join(\",\")}]`;\n  }\n  if (typeof value === \"object\") {\n    const entries = Object.entries(value as Record<string, unknown>)\n      // serde skips `None` fields, so an `undefined` value is omitted entirely\n      // rather than serialized — keep parity by dropping it before sorting.\n      .filter(([, v]) => v !== undefined)\n      .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));\n    const body = entries\n      .map(([k, v]) => `${JSON.stringify(k)}:${canonicalJson(v)}`)\n      .join(\",\");\n    return `{${body}}`;\n  }\n  // Scalars (string / number / boolean): JSON.stringify matches serde for\n  // strings, booleans and integers; floats differ (see limitation above).\n  return JSON.stringify(value);\n};\n\n/**\n * Drop EVERY `role === \"system\"` message, matching the server.\n *\n * Content and position are irrelevant: an empty system string, a block-array\n * system, or repeated/trailing system messages are all stripped. The coding\n * agent may add/remove/edit its own system prompt(s) between iterations and\n * those edits must not change the cache key.\n */\nconst stripSystemMessages = (messages: unknown[]): unknown[] =>\n  messages.filter(\n    (m) =>\n      !(\n        m !== null &&\n        typeof m === \"object\" &&\n        (m as Record<string, unknown>).role === \"system\"\n      ),\n  );\n\n/**\n * Compute the hex blake3 `input_hash` for a message array.\n *\n * `messages` is the verbatim LanguageModel-level prompt\n * (`JSON.parse(stringifyPromptForTelemetry(options.prompt))`) — the same bytes\n * the SDK records as `gen_ai.input.messages` and the server hashes on ingest.\n * System messages are stripped, the remainder canonicalized, and the digest\n * hex-encoded (64 chars).\n */\nexport const debugInputHash = (messages: unknown[]): string => {\n  const stripped = stripSystemMessages(messages);\n  const canonical = canonicalJson(stripped);\n  const digest = blake3(new TextEncoder().encode(canonical));\n  return bytesToHex(digest);\n};\n","/**\n * Shared replay helpers for the per-provider LLM wrappers (§G, §H).\n *\n * The provider wrappers keep their own cached-response reconstruction and\n * streaming wrappers; everything generic — the replay decision, span-path\n * resolution, and the CACHED span marking — lives here so all providers stay in\n * lockstep. Part of the cross-language parity surface — keep line-comparable\n * with the Python `replay.py`.\n */\n\nimport { Span } from \"@opentelemetry/api\";\n\nimport { SPAN_PATH } from \"../opentelemetry-lib/tracing/attributes\";\nimport { getRuntime } from \"./index\";\n\n/**\n * True when this process is a debug run with replay configured (a replay trace\n * + a cache-until span id). A debug-no-replay run (`LMNR_DEBUG` set but no\n * `LMNR_DEBUG_REPLAY_TRACE_ID` / `LMNR_DEBUG_CACHE_UNTIL`) returns false — the\n * provider wrappers then skip the per-call cache lookup entirely.\n */\nexport const replayEnabled = (): boolean =>\n  getRuntime()?.replayConfigured ?? false;\n\n/**\n * Resolve the dot-joined span path from a span's attributes.\n *\n * Provider spans are created with `tracer.startSpan()` and aren't registered in\n * Laminar's context, so the path is read from the attribute the processor\n * already set (a string[]; see `LaminarSpanProcessor.onStart`).\n */\nexport const spanPathFromSpan = (\n  span: Span | undefined | null,\n): string | null => {\n  if (!span) {\n    return null;\n  }\n  const pathList = (span as unknown as { attributes?: Record<string, unknown> })\n    .attributes?.[SPAN_PATH];\n  if (Array.isArray(pathList) && pathList.length > 0) {\n    return pathList.join(\".\");\n  }\n  return null;\n};\n\n/** Stamp the CACHED boundary attributes the frontend renders (§9). */\nexport const markSpanCached = (span: Span | undefined | null): void => {\n  if (span && span.isRecording()) {\n    span.setAttributes({\n      \"lmnr.span.type\": \"CACHED\",\n      \"lmnr.span.original_type\": \"LLM\",\n    });\n  }\n};\n","import type { Span } from \"@opentelemetry/api\";\n\n/**\n * Bridge between the v7 telemetry integration and the replay wrapper.\n *\n * On a v7 run the actual `ai.llm` span is created by `LaminarAiSdkTelemetry`\n * (`v7-integration/index.ts`) and parked in its `llmByKey` map — it is NEVER\n * placed on the OTel context. The replay wrapper (`base-language-model.ts`),\n * however, runs as the wrapped `model.doGenerate` / `doStream` and needs to\n * stamp the CACHED boundary on the span that actually serves the reconstructed\n * output. `Laminar.getCurrentSpan()` only sees the on-context operation span\n * (`ai.generateText`), not the parked LLM span, so on a HIT it would mark the\n * wrong span.\n *\n * This module is the missing link: the integration pushes each open LLM span\n * here and removes it when the call ends; the replay wrapper peeks the most\n * recently pushed still-open span at its synchronous call entry. AI SDK fires\n * `onLanguageModelCallStart` immediately before invoking `model.doGenerate`\n * (no `await` in between), so in sequential execution the top of the stack is\n * this exact call's LLM span. On v6 the integration is not used, the stack is\n * empty, and the wrapper falls back to `getCurrentSpan()` (which on v6 IS the\n * live `doGenerate` LLM span the SDK activated on context).\n *\n * This is TS-only AI-SDK glue — NOT part of the cross-language debug parity\n * surface.\n */\nconst openLlmSpans: Span[] = [];\n\n/** Register an `ai.llm` span as open. Call from the integration's callStart. */\nexport const pushActiveLlmSpan = (span: Span): void => {\n  openLlmSpans.push(span);\n};\n\n/** Remove a previously registered span (matched by reference). */\nexport const removeActiveLlmSpan = (span: Span): void => {\n  for (let i = openLlmSpans.length - 1; i >= 0; i--) {\n    if (openLlmSpans[i] === span) {\n      openLlmSpans.splice(i, 1);\n      return;\n    }\n  }\n};\n\n/** Most recently pushed still-open LLM span, or undefined if none. */\nexport const peekActiveLlmSpan = (): Span | undefined =>\n  openLlmSpans.length > 0 ? openLlmSpans[openLlmSpans.length - 1] : undefined;\n","import { LanguageModelV4Prompt } from \"@ai-sdk/provider\";\nimport type { HrTime, Span } from \"@opentelemetry/api\";\n\nimport { LaminarAttributes } from \"../../../tracing/attributes\";\nimport { stringifyPromptForTelemetry } from \"../utils\";\n\nexport const serializeJSON = (value: unknown): string => {\n  if (typeof value === \"string\") return value;\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return \"[unserializable]\";\n  }\n};\n\nexport const normalizeProvider = (\n  provider: string | undefined,\n): string | undefined => {\n  if (!provider) return undefined;\n  const head = provider.split(\".\").shift();\n  return (\n    head?.toLowerCase().trim() || provider.toLowerCase().trim() || undefined\n  );\n};\n\nexport const applyUsage = (\n  attributes: Record<string, any>,\n  usage: any,\n): void => {\n  if (!usage || typeof usage !== \"object\") return;\n  if (typeof usage.inputTokens === \"number\") {\n    attributes[LaminarAttributes.INPUT_TOKEN_COUNT] = usage.inputTokens;\n  }\n  if (typeof usage.outputTokens === \"number\") {\n    attributes[LaminarAttributes.OUTPUT_TOKEN_COUNT] = usage.outputTokens;\n  }\n  if (typeof usage.totalTokens === \"number\") {\n    attributes[LaminarAttributes.TOTAL_TOKEN_COUNT] = usage.totalTokens;\n  } else if (\n    typeof usage.inputTokens === \"number\" ||\n    typeof usage.outputTokens === \"number\"\n  ) {\n    attributes[LaminarAttributes.TOTAL_TOKEN_COUNT] =\n      (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);\n  }\n  if (typeof usage.reasoningTokens === \"number\") {\n    attributes[\"gen_ai.usage.reasoning_tokens\"] = usage.reasoningTokens;\n  } else if (typeof usage.outputTokenDetails?.reasoningTokens === \"number\") {\n    attributes[\"gen_ai.usage.reasoning_tokens\"] =\n      usage.outputTokenDetails.reasoningTokens;\n  }\n  if (typeof usage.cachedInputTokens === \"number\") {\n    attributes[\"gen_ai.usage.cache_read_input_tokens\"] =\n      usage.cachedInputTokens;\n  } else if (typeof usage.inputTokenDetails?.cacheReadTokens === \"number\") {\n    attributes[\"gen_ai.usage.cache_read_input_tokens\"] =\n      usage.inputTokenDetails.cacheReadTokens;\n  }\n  if (typeof usage.inputTokenDetails?.cacheWriteTokens === \"number\") {\n    attributes[\"gen_ai.usage.cache_creation_input_tokens\"] =\n      usage.inputTokenDetails.cacheWriteTokens;\n  }\n};\n\n// Convert a StandardizedPrompt-shaped event (`system`/`instructions` +\n// `messages`) into a verbatim message array: the system prompt becomes a\n// leading system message and `messages` are appended UNCHANGED — no key\n// renames, no part filtering, no string→text-block rewriting. Used as the\n// input fallback when the LanguageModel-level prompt is unavailable.\nexport const verbatimStandardizedMessages = (event: {\n  system?: any;\n  instructions?: any;\n  messages?: any[];\n}): any[] => {\n  const messages: any[] = [];\n  const sys = event.instructions || event.system;\n  if (typeof sys === \"string\" && sys.length > 0) {\n    messages.push({ role: \"system\", content: sys });\n  } else if (Array.isArray(sys)) {\n    for (const m of sys) messages.push(m);\n  } else if (sys && typeof sys === \"object\") {\n    messages.push(sys);\n  }\n  if (Array.isArray(event.messages)) {\n    for (const m of event.messages) messages.push(m);\n  }\n  return messages;\n};\n\n// Build the verbatim `gen_ai.output.messages` payload from an assistant\n// turn's `LanguageModelContent` array (`event.content` on\n// onLanguageModelCallEnd). The content parts are recorded EXACTLY as the\n// provider returned them — no key renames, no part filtering — wrapped in a\n// single assistant message. The backend stores this verbatim on the span\n// output and the debugger replays from it. Returns the JSON string, or\n// `undefined` when there is nothing to emit.\nexport const buildVerbatimOutputMessages = (\n  content: any[] | undefined,\n): string | undefined => {\n  if (!Array.isArray(content) || content.length === 0) return undefined;\n  try {\n    return JSON.stringify([{ role: \"assistant\", content }]);\n  } catch {\n    return undefined;\n  }\n};\n\n// Fallback output shape for paths where the verbatim provider content is not\n// available (buffered stream deltas on aborted/errored streams, objectText on\n// generateObject/streamObject): a single verbatim-style text part.\nexport const buildTextOutputMessages = (text: string): string | undefined =>\n  text.length > 0\n    ? buildVerbatimOutputMessages([{ type: \"text\", text }])\n    : undefined;\n\n// Apply `applyUsage` output directly onto a span, skipping undefined values.\nexport const applyUsageToSpan = (span: Span, usage: any): void => {\n  const attrs: Record<string, any> = {};\n  applyUsage(attrs, usage);\n  for (const [k, v] of Object.entries(attrs)) {\n    if (v !== undefined) span.setAttribute(k, v);\n  }\n};\n\n// Set the dual finish-reason attributes used by both ai.* and gen_ai.* parsers.\nexport const applyFinishReason = (span: Span, finishReason: string): void => {\n  span.setAttribute(\"gen_ai.response.finish_reason\", finishReason);\n  span.setAttribute(\"ai.response.finishReason\", finishReason);\n};\n\n// Set provider + request-model attributes on an LLM span.\nexport const applyRequestModelAttributes = (span: Span, event: any): void => {\n  if (typeof event.provider === \"string\") {\n    const provider = normalizeProvider(event.provider);\n    if (provider) span.setAttribute(LaminarAttributes.PROVIDER, provider);\n    span.setAttribute(\"ai.model.provider\", event.provider);\n  }\n  if (typeof event.modelId === \"string\") {\n    span.setAttribute(LaminarAttributes.REQUEST_MODEL, event.modelId);\n    span.setAttribute(\"ai.model.id\", event.modelId);\n  }\n};\n\nexport const compareHrTime = (a: HrTime, b: HrTime): number => {\n  if (a[0] !== b[0]) return a[0] - b[0];\n  return a[1] - b[1];\n};\n\n// LaminarSpan wraps an SDK Span and copies `endTime` in its constructor (before\n// `end()` was called), so reading it from the wrapper yields the stale\n// `[0, 0]` snapshot. The underlying `_span` (an SDK span) mutates its own\n// `endTime` on `end()`, which is what we need. Probe both fields defensively\n// so exotic Span implementations still degrade gracefully.\nexport const readSpanEndTime = (span: Span): HrTime | undefined => {\n  const inner = (span as unknown as { _span?: { endTime?: HrTime } })._span;\n  const innerEnd = inner?.endTime;\n  if (innerEnd && (innerEnd[0] !== 0 || innerEnd[1] !== 0)) return innerEnd;\n  const outerEnd = (span as unknown as { endTime?: HrTime }).endTime;\n  if (outerEnd && (outerEnd[0] !== 0 || outerEnd[1] !== 0)) return outerEnd;\n  return undefined;\n};\n\n// The recorded `gen_ai.input.messages` attribute (v7 integration) and the\n// debugger-replay input hash (base-language-model.ts) MUST be computed from\n// the same serialized bytes, or record-time and replay-time cache keys drift.\n// Both go through these two helpers — do NOT serialize the prompt any other\n// way on either path.\nexport const verbatimPromptString = (prompt: unknown): string | null => {\n  try {\n    const serialized = stringifyPromptForTelemetry(\n      prompt as LanguageModelV4Prompt,\n    );\n    return typeof serialized === \"string\" ? serialized : null;\n  } catch {\n    return null;\n  }\n};\n\nexport const verbatimPromptMessages = (prompt: unknown): unknown[] | null => {\n  const serialized = verbatimPromptString(prompt);\n  if (serialized === null) return null;\n  try {\n    const parsed: unknown = JSON.parse(serialized);\n    return Array.isArray(parsed) ? parsed : null;\n  } catch {\n    return null;\n  }\n};\n","import {\n  type LanguageModelV4,\n  type LanguageModelV4CallOptions,\n  type LanguageModelV4Content,\n  type LanguageModelV4FinishReason,\n  type LanguageModelV4ResponseMetadata,\n  type LanguageModelV4Usage,\n  type SharedV4Headers,\n  type SharedV4ProviderMetadata,\n  type SharedV4Warning,\n} from \"@ai-sdk/provider\";\nimport {\n  type LanguageModelV2,\n  type LanguageModelV2CallOptions,\n  type LanguageModelV2CallWarning,\n  type LanguageModelV2Content,\n  type LanguageModelV2FinishReason,\n  type LanguageModelV2ResponseMetadata,\n  type LanguageModelV2Usage,\n  type SharedV2Headers,\n  type SharedV2ProviderMetadata,\n} from \"@ai-sdk/provider-v2\";\nimport {\n  type LanguageModelV3,\n  type LanguageModelV3CallOptions,\n  type LanguageModelV3Content,\n  type LanguageModelV3FinishReason,\n  type LanguageModelV3ResponseMetadata,\n  type LanguageModelV3Usage,\n  type SharedV3Headers,\n  type SharedV3ProviderMetadata,\n  type SharedV3Warning,\n} from \"@ai-sdk/provider-v3\";\nimport { CachedSpan } from \"@lmnr-ai/types\";\n\nimport { debugInputHash } from \"../../../debug/hash\";\nimport { getRuntime } from \"../../../debug/index\";\nimport { markSpanCached, replayEnabled } from \"../../../debug/replay\";\nimport { Laminar } from \"../../../laminar\";\nimport { peekActiveLlmSpan } from \"./active-llm-span\";\nimport { verbatimPromptMessages } from \"./v7-integration/utils\";\n\ntype CacheResponse =\n  | {\n      type: \"raw\";\n      response: Record<string, any> | Record<string, any>[];\n      finishReasons?: string[] | null;\n      model?: string | null;\n    }\n  | {\n      type: \"genAi\";\n      messages: Record<string, any>[];\n      finishReasons?: string[] | null;\n      model?: string | null;\n    };\n\n/**\n * Parsed HIT `output`. The server-side response shape is not yet frozen\n * (app-server plan 01 §4.3 stores EITHER the raw provider response OR a bare\n * `gen_ai.output.messages` array, and a discriminated {@link CacheResponse}\n * wrapper is the firmed-up form), so the consumer accepts all three and stays\n * tolerant rather than throwing on an unwrapped payload.\n */\ntype CacheOutput = CacheResponse | Record<string, any> | Record<string, any>[];\n\n/**\n * Base class for Laminar language model wrappers.\n * Implements shared replay-cache logic for both V2 and V3 specifications.\n * Uses method overloads for type safety across versions.\n */\nexport abstract class BaseLaminarLanguageModel {\n  protected readonly innerLanguageModel:\n    | LanguageModelV2\n    | LanguageModelV3\n    | LanguageModelV4;\n  readonly provider: string;\n  readonly modelId: string;\n  readonly supportedUrls:\n    | PromiseLike<Record<string, RegExp[]>>\n    | Record<string, RegExp[]>;\n\n  constructor(\n    languageModel: LanguageModelV2 | LanguageModelV3 | LanguageModelV4,\n  ) {\n    this.innerLanguageModel = languageModel;\n    this.provider = languageModel.provider;\n    this.modelId = languageModel.modelId;\n    this.supportedUrls = languageModel.supportedUrls;\n  }\n\n  /**\n   * Creates a version-specific usage object.\n   * V2 and V3 have different usage structures, so this must be implemented by subclasses.\n   */\n  protected abstract createUsageObject():\n    | LanguageModelV2Usage\n    | LanguageModelV3Usage\n    | LanguageModelV4Usage;\n\n  /**\n   * Creates a version-specific stream from cached response data.\n   * V2 and V3 have different stream part types, so this must be implemented by subclasses.\n   */\n  protected abstract createStreamFromCachedResponse(\n    content: Array<\n      LanguageModelV2Content | LanguageModelV3Content | LanguageModelV4Content\n    >,\n    finishReason:\n      | LanguageModelV2FinishReason\n      | LanguageModelV3FinishReason\n      | LanguageModelV4FinishReason,\n    usage: LanguageModelV2Usage | LanguageModelV3Usage | LanguageModelV4Usage,\n  ): ReadableStream<any>;\n\n  /**\n   * Main generation method with caching support for V2\n   */\n  protected doGenerateWithCaching(\n    options: LanguageModelV2CallOptions,\n    doGenerateFn: (opts: LanguageModelV2CallOptions) => PromiseLike<{\n      content: Array<LanguageModelV2Content>;\n      finishReason: LanguageModelV2FinishReason;\n      usage: LanguageModelV2Usage;\n      providerMetadata?: SharedV2ProviderMetadata;\n      request?: { body?: unknown };\n      response?: LanguageModelV2ResponseMetadata & {\n        headers?: SharedV2Headers;\n        body?: unknown;\n      };\n      warnings: Array<LanguageModelV2CallWarning>;\n    }>,\n  ): PromiseLike<{\n    content: Array<LanguageModelV2Content>;\n    finishReason: LanguageModelV2FinishReason;\n    usage: LanguageModelV2Usage;\n    providerMetadata?: SharedV2ProviderMetadata;\n    request?: { body?: unknown };\n    response?: LanguageModelV2ResponseMetadata & {\n      headers?: SharedV2Headers;\n      body?: unknown;\n    };\n    warnings: Array<LanguageModelV2CallWarning>;\n  }>;\n\n  /**\n   * Main generation method with caching support for V3\n   */\n  protected doGenerateWithCaching(\n    options: LanguageModelV3CallOptions,\n    doGenerateFn: (opts: LanguageModelV3CallOptions) => PromiseLike<{\n      content: Array<LanguageModelV3Content>;\n      finishReason: LanguageModelV3FinishReason;\n      usage: LanguageModelV3Usage;\n      providerMetadata?: SharedV3ProviderMetadata;\n      request?: { body?: unknown };\n      response?: LanguageModelV3ResponseMetadata & {\n        headers?: SharedV3Headers;\n        body?: unknown;\n      };\n      warnings: Array<SharedV3Warning>;\n    }>,\n  ): PromiseLike<{\n    content: Array<LanguageModelV3Content>;\n    finishReason: LanguageModelV3FinishReason;\n    usage: LanguageModelV3Usage;\n    providerMetadata?: SharedV3ProviderMetadata;\n    request?: { body?: unknown };\n    response?: LanguageModelV3ResponseMetadata & {\n      headers?: SharedV3Headers;\n      body?: unknown;\n    };\n    warnings: Array<SharedV3Warning>;\n  }>;\n\n  /**\n   * Main generation method with caching support for V4\n   */\n  protected doGenerateWithCaching(\n    options: LanguageModelV4CallOptions,\n    doGenerateFn: (opts: LanguageModelV4CallOptions) => PromiseLike<{\n      content: Array<LanguageModelV4Content>;\n      finishReason: LanguageModelV4FinishReason;\n      usage: LanguageModelV4Usage;\n      providerMetadata?: SharedV4ProviderMetadata;\n      request?: { body?: unknown };\n      response?: LanguageModelV4ResponseMetadata & {\n        headers?: SharedV4Headers;\n        body?: unknown;\n      };\n      warnings: Array<SharedV4Warning>;\n    }>,\n  ): PromiseLike<{\n    content: Array<LanguageModelV4Content>;\n    finishReason: LanguageModelV4FinishReason;\n    usage: LanguageModelV4Usage;\n    providerMetadata?: SharedV4ProviderMetadata;\n    request?: { body?: unknown };\n    response?: LanguageModelV4ResponseMetadata & {\n      headers?: SharedV4Headers;\n      body?: unknown;\n    };\n    warnings: Array<SharedV4Warning>;\n  }>;\n\n  /**\n   * Implementation of doGenerateWithCaching\n   * Consults the in-process replay cache (§G); falls through to the live call.\n   */\n  protected doGenerateWithCaching(\n    options:\n      | LanguageModelV2CallOptions\n      | LanguageModelV3CallOptions\n      | LanguageModelV4CallOptions,\n    doGenerateFn: (opts: any) => PromiseLike<any>,\n  ): PromiseLike<any> {\n    return this.doGenerateOrStreamWithCaching(options, doGenerateFn, (cached) =>\n      this.cachedDoGenerate(cached),\n    );\n  }\n\n  /**\n   * Main streaming method with caching support for V2\n   */\n  protected doStreamWithCaching(\n    options: LanguageModelV2CallOptions,\n    doStreamFn: (opts: LanguageModelV2CallOptions) => PromiseLike<{\n      stream: ReadableStream<any>;\n      request?: { body?: unknown };\n      response?: { headers?: SharedV2Headers };\n    }>,\n  ): PromiseLike<{\n    stream: ReadableStream<any>;\n    request?: { body?: unknown };\n    response?: { headers?: SharedV2Headers };\n  }>;\n\n  /**\n   * Main streaming method with caching support for V3\n   */\n  protected doStreamWithCaching(\n    options: LanguageModelV3CallOptions,\n    doStreamFn: (opts: LanguageModelV3CallOptions) => PromiseLike<{\n      stream: ReadableStream<any>;\n      request?: { body?: unknown };\n      response?: { headers?: SharedV3Headers };\n    }>,\n  ): PromiseLike<{\n    stream: ReadableStream<any>;\n    request?: { body?: unknown };\n    response?: { headers?: SharedV3Headers };\n  }>;\n\n  /**\n   * Main streaming method with caching support for V4\n   */\n  protected doStreamWithCaching(\n    options: LanguageModelV4CallOptions,\n    doStreamFn: (opts: LanguageModelV4CallOptions) => PromiseLike<{\n      stream: ReadableStream<any>;\n      request?: { body?: unknown };\n      response?: { headers?: SharedV4Headers };\n    }>,\n  ): PromiseLike<{\n    stream: ReadableStream<any>;\n    request?: { body?: unknown };\n    response?: { headers?: SharedV4Headers };\n  }>;\n\n  /**\n   * Implementation of doStreamWithCaching\n   * Consults the in-process replay cache (§H); falls through to the live call.\n   */\n  protected doStreamWithCaching(\n    options:\n      | LanguageModelV2CallOptions\n      | LanguageModelV3CallOptions\n      | LanguageModelV4CallOptions,\n    doStreamFn: (opts: any) => PromiseLike<any>,\n  ): PromiseLike<any> {\n    return this.doGenerateOrStreamWithCaching(options, doStreamFn, (cached) =>\n      this.cachedDoStream(cached),\n    );\n  }\n\n  /**\n   * Common implementation for both doGenerateWithCaching and doStreamWithCaching.\n   *\n   * On a debug replay run, hashes this call's input messages and consults the\n   * server-side replay cache (debug-replay v2, §9). Three outcomes:\n   *   - HIT  — reconstruct the response from the cached span and mark CACHED.\n   *   - MISS — latch process-wide live mode and run this (and every later) call\n   *            live; the server records the response so the cache warms up.\n   *   - LIVE — run THIS call live WITHOUT latching (server COLD warmup-timeout\n   *            degrade, or any transport/parse error in the lookup).\n   * A non-debug or no-replay run falls through to the live provider call.\n   */\n  private async doGenerateOrStreamWithCaching(\n    options:\n      | LanguageModelV2CallOptions\n      | LanguageModelV3CallOptions\n      | LanguageModelV4CallOptions,\n    originalFn: (opts: any) => PromiseLike<any>,\n    buildFromCached: (cached: CachedSpan) => any,\n  ): Promise<any> {\n    if (!replayEnabled() || Laminar.debugRunLive) {\n      return originalFn(options);\n    }\n\n    // Capture the span to mark CACHED on a HIT, synchronously at call entry\n    // (before any await). On v7 the real `ai.llm` span is created by the\n    // telemetry integration and parked off the OTel context, so\n    // `Laminar.getCurrentSpan()` would resolve to the top-level operation span\n    // (`ai.generateText`) instead — the wrong span. The integration publishes\n    // each open LLM span to `peekActiveLlmSpan`, and AI SDK fires\n    // `onLanguageModelCallStart` immediately before this `doGenerate`/`doStream`\n    // with no await between, so the top of that stack is THIS call's LLM span.\n    // On v6 the integration isn't used (stack empty) and the SDK activates the\n    // live `doGenerate` LLM span on context, so `getCurrentSpan()` is correct.\n    const spanToMark = peekActiveLlmSpan() ?? Laminar.getCurrentSpan();\n\n    // Hash the verbatim LanguageModel-level prompt (system messages excluded)\n    // through the SAME serializer the v7 integration used to record\n    // `gen_ai.input.messages`, so the SDK and server key the cache identically.\n    // A null/empty result means we could not serialize the prompt at all (a\n    // stringify/JSON.parse failure, or an empty prompt). Hashing that would key\n    // the lookup off the wrong bytes and force a spurious MISS, which would\n    // wrongly latch live mode for the whole replay — so degrade to a live call\n    // WITHOUT latching, exactly like a transport error in the lookup.\n    const messages = verbatimPromptMessages(\n      (options as { prompt: unknown }).prompt,\n    );\n    if (messages === null || messages.length === 0) {\n      return originalFn(options);\n    }\n    const inputHash = debugInputHash(messages);\n    const outcome = (await getRuntime()?.lookupCache(inputHash)) ?? {\n      kind: \"live\" as const,\n    };\n\n    switch (outcome.kind) {\n      case \"hit\":\n        markSpanCached(spanToMark);\n        return buildFromCached(outcome.cached);\n      case \"miss\":\n        // First MISS latches live mode for the rest of the process, so later\n        // calls skip the lookup entirely and run live.\n        Laminar.debugRunLive = true;\n        return originalFn(options);\n      case \"live\":\n      default:\n        return originalFn(options);\n    }\n  }\n\n  private cachedDoGenerate(cached: CachedSpan): {\n    content: Array<\n      LanguageModelV2Content | LanguageModelV3Content | LanguageModelV4Content\n    >;\n    finishReason:\n      | LanguageModelV2FinishReason\n      | LanguageModelV3FinishReason\n      | LanguageModelV4FinishReason;\n    usage: LanguageModelV2Usage | LanguageModelV3Usage | LanguageModelV4Usage;\n    warnings: Array<\n      LanguageModelV2CallWarning | SharedV3Warning | SharedV4Warning\n    >;\n  } {\n    return {\n      ...this.parseCachedSpan(cached),\n      warnings: [],\n    };\n  }\n\n  private cachedDoStream(cached: CachedSpan): { stream: ReadableStream<any> } {\n    const parsed = this.parseCachedSpan(cached);\n    const stream = this.createStreamFromCachedResponse(\n      parsed.content,\n      parsed.finishReason,\n      parsed.usage,\n    );\n    return { stream };\n  }\n\n  /**\n   * Reconstructs content blocks, usage, and finish reason from a cached span.\n   */\n  private parseCachedSpan(cached: CachedSpan): {\n    content: Array<\n      LanguageModelV2Content | LanguageModelV3Content | LanguageModelV4Content\n    >;\n    finishReason:\n      | LanguageModelV2FinishReason\n      | LanguageModelV3FinishReason\n      | LanguageModelV4FinishReason;\n    usage: LanguageModelV2Usage | LanguageModelV3Usage | LanguageModelV4Usage;\n  } {\n    let parsedOutput: string | CacheOutput = cached.output;\n    try {\n      parsedOutput = JSON.parse(cached.output);\n    } catch {\n      // Ignore - keep as string\n    }\n\n    const content = this.convertToContentBlocks(parsedOutput);\n    const usage = this.createUsageObject();\n    const finishReason =\n      cached.attributes[\"ai.response.finishReason\"] ?? \"stop\";\n\n    return { content, usage, finishReason };\n  }\n\n  /**\n   * Converts output from span to content blocks compatible with both V2 and V3\n   */\n  private convertToContentBlocks(\n    output: string | CacheOutput,\n  ): Array<\n    LanguageModelV4Content | LanguageModelV3Content | LanguageModelV2Content\n  > {\n    if (typeof output === \"string\") {\n      return [\n        {\n          type: \"text\",\n          text: output,\n        },\n      ];\n    }\n\n    // A JSON `null` / primitive payload has no content to replay and would crash\n    // the wrapper / unwrap logic below (`output.type` on null throws). The\n    // resource degrades a no-payload HIT to live, but parseCachedSpan can't —\n    // so guard here too and emit an empty content array rather than throwing.\n    if (output === null || typeof output !== \"object\") {\n      return [];\n    }\n\n    // Handles a single content part. Covers the verbatim v7 shape recorded on\n    // `gen_ai.output.messages` (`{type:\"text\"|\"reasoning\", text}` /\n    // `{type:\"tool-call\", toolCallId, toolName, input}` — `input` is usually\n    // already a JSON string, straight from `LanguageModelContent`), the older\n    // v7-hybrid part shape (`{type:\"text\"|\"thinking\", content}` /\n    // `{type:\"tool_call\", id, name, arguments}`), and the v6 legacy shape\n    // (`{type:\"text\", text}` / `{type:\"tool_call\", name, id, arguments}`), so\n    // `text` and `content` are both accepted for the textual fields.\n    //\n    // Parts already in the verbatim v7 shape are SPREAD through, not rebuilt\n    // field-by-field. The AI SDK echoes provider fields from the replayed\n    // content into the NEXT step's prompt (`toResponseMessages` copies\n    // `providerMetadata` onto every part as `providerOptions`; tool-results\n    // inherit the tool-call's providerMetadata), and the server hashed the\n    // record-run step-N input WITH those fields. Dropping `providerMetadata` /\n    // `providerExecuted` here makes the replayed step-(N+1) prompt hash to\n    // different bytes → spurious MISS → the whole run latches live. Legacy\n    // shapes must NOT be spread (their `id`/`name`/`arguments`/`content` keys\n    // would leak into the rebuilt part) — they keep the field-by-field rebuild.\n    const handleItem = (\n      item: Record<string, any>,\n    ): LanguageModelV3Content[] => {\n      if (item.type === \"text\") {\n        if (typeof item.text === \"string\") {\n          return [{ ...item, type: \"text\", text: item.text }];\n        }\n        return [\n          {\n            type: \"text\",\n            text: item.content ?? \"\",\n          },\n        ];\n      }\n      if (item.type === \"tool-call\") {\n        return [\n          {\n            ...item,\n            type: \"tool-call\",\n            toolCallId: item.toolCallId ?? item.id,\n            toolName: item.toolName ?? item.name,\n            // Verbatim v7 content carries `input` as an already-serialized JSON\n            // string — re-stringifying would double-encode it.\n            input:\n              typeof item.input === \"string\"\n                ? item.input\n                : JSON.stringify(item.input ?? item.arguments),\n          },\n        ];\n      }\n      if (item.type === \"tool_call\") {\n        const rawInput = item.input ?? item.arguments;\n        return [\n          {\n            type: \"tool-call\",\n            toolCallId: item.toolCallId ?? item.id,\n            toolName: item.toolName ?? item.name,\n            input:\n              typeof rawInput === \"string\"\n                ? rawInput\n                : JSON.stringify(rawInput),\n          },\n        ];\n      }\n      if (item.type === \"reasoning\") {\n        if (typeof item.text === \"string\") {\n          return [{ ...item, type: \"reasoning\", text: item.text }];\n        }\n        return [\n          {\n            type: \"reasoning\",\n            text: item.content ?? \"\",\n          },\n        ];\n      }\n      if (item.type === \"thinking\") {\n        return [\n          {\n            type: \"reasoning\",\n            text: item.text ?? item.content ?? \"\",\n          },\n        ];\n      }\n      return [\n        {\n          type: \"text\",\n          text: JSON.stringify(item),\n        },\n      ];\n    };\n\n    // The HIT payload shape is not frozen (see CacheOutput): a discriminated\n    // CacheResponse wrapper, a bare provider object, or a bare message array are\n    // all possible. Unwrap the wrapper when present; otherwise treat the payload\n    // itself as the content (array as-is, single object wrapped) so an unwrapped\n    // server response replays instead of dereferencing a missing `.messages` /\n    // `.response` and yielding `[undefined]`.\n    let outputContent: Record<string, any>[];\n    if (Array.isArray(output)) {\n      outputContent = output;\n    } else if (\n      output.type === \"genAi\" &&\n      Array.isArray((output as any).messages)\n    ) {\n      outputContent = (output as any).messages;\n    } else if (output.type === \"raw\" && \"response\" in output) {\n      outputContent = Array.isArray(output.response)\n        ? output.response\n        : [output.response];\n    } else {\n      outputContent = [output];\n    }\n    return outputContent.flatMap((item) => {\n      // Older v7-hybrid `gen_ai.output.messages` shape: `{role, parts:[...]}`\n      // (already an object array, never a JSON string). Map each part through\n      // handleItem.\n      if (item.role && Array.isArray(item.parts)) {\n        return item.parts.flatMap(handleItem);\n      }\n      // Verbatim v7 shape (`{role, content: LanguageModelContent[]}`) and the\n      // v6 legacy shape: `{role, content}` where content is either an array of\n      // parts or a JSON-encoded string of them.\n      if (item.role && item.content) {\n        let parsedContent: Record<string, any>[] = item.content;\n        if (typeof item.content === \"string\") {\n          try {\n            parsedContent = JSON.parse(item.content);\n          } catch {\n            return [\n              {\n                type: \"text\",\n                text: item.content,\n              },\n            ];\n          }\n        }\n        return parsedContent.flatMap(handleItem);\n      }\n      return handleItem(item);\n    });\n  }\n}\n","import {\n  type LanguageModelV2,\n  type LanguageModelV2CallOptions,\n  type LanguageModelV2CallWarning,\n  type LanguageModelV2Content,\n  type LanguageModelV2FinishReason,\n  type LanguageModelV2ResponseMetadata,\n  type LanguageModelV2StreamPart,\n  type LanguageModelV2Usage,\n  type SharedV2Headers,\n  type SharedV2ProviderMetadata,\n} from \"@ai-sdk/provider-v2\";\n\nimport { BaseLaminarLanguageModel } from \"./base-language-model\";\n\nexport class LaminarLanguageModelV2\n  extends BaseLaminarLanguageModel\n  implements LanguageModelV2\n{\n  readonly specificationVersion = \"v2\";\n\n  protected readonly innerLanguageModel: LanguageModelV2;\n\n  constructor(languageModel: LanguageModelV2) {\n    super(languageModel);\n    this.innerLanguageModel = languageModel;\n  }\n\n  protected createUsageObject(): LanguageModelV2Usage {\n    return {\n      inputTokens: 0,\n      outputTokens: 0,\n      totalTokens: 0,\n    };\n  }\n\n  doGenerate(options: LanguageModelV2CallOptions): PromiseLike<{\n    content: Array<LanguageModelV2Content>;\n    finishReason: LanguageModelV2FinishReason;\n    usage: LanguageModelV2Usage;\n    providerMetadata?: SharedV2ProviderMetadata;\n    request?: {\n      body?: unknown;\n    };\n    response?: LanguageModelV2ResponseMetadata & {\n      headers?: SharedV2Headers;\n      body?: unknown;\n    };\n    warnings: Array<LanguageModelV2CallWarning>;\n  }> {\n    return this.doGenerateWithCaching(options, (opts) =>\n      this.innerLanguageModel.doGenerate(opts),\n    );\n  }\n\n  doStream(options: LanguageModelV2CallOptions): PromiseLike<{\n    stream: ReadableStream<LanguageModelV2StreamPart>;\n    request?: {\n      body?: unknown;\n    };\n    response?: {\n      headers?: SharedV2Headers;\n    };\n  }> {\n    return this.doStreamWithCaching(options, (opts) =>\n      this.innerLanguageModel.doStream(opts),\n    );\n  }\n\n  protected createStreamFromCachedResponse(\n    content: Array<LanguageModelV2Content>,\n    finishReason: LanguageModelV2FinishReason,\n    usage: LanguageModelV2Usage,\n  ): ReadableStream<LanguageModelV2StreamPart> {\n    const parts: LanguageModelV2StreamPart[] = [];\n\n    // Stream start\n    parts.push({ type: \"stream-start\", warnings: [] });\n\n    // Process each content block\n    let textIndex = 0;\n    let toolIndex = 0;\n    let reasoningIndex = 0;\n\n    // `providerMetadata` (and `providerExecuted` on tool calls) must survive\n    // the rebuild: the AI SDK echoes these into the next step's prompt, and\n    // the replay cache hashes that prompt — dropping them causes a spurious\n    // MISS on the following step.\n    for (const block of content) {\n      if (block.type === \"text\") {\n        const id = `text-${textIndex++}`;\n        parts.push({\n          type: \"text-start\",\n          id,\n          providerMetadata: block.providerMetadata,\n        });\n        parts.push({ type: \"text-delta\", id, delta: block.text });\n        parts.push({ type: \"text-end\", id });\n      } else if (block.type === \"tool-call\") {\n        const id = `tool-${toolIndex++}`;\n        parts.push({\n          type: \"tool-input-start\",\n          id,\n          toolName: block.toolName,\n        });\n        parts.push({\n          type: \"tool-input-delta\",\n          id,\n          delta: block.input,\n        });\n        parts.push({ type: \"tool-input-end\", id });\n        parts.push({ ...block, type: \"tool-call\" });\n      } else if (block.type === \"reasoning\") {\n        const id = `reasoning-${reasoningIndex++}`;\n        parts.push({\n          type: \"reasoning-start\",\n          id,\n          providerMetadata: block.providerMetadata,\n        });\n        parts.push({ type: \"reasoning-delta\", id, delta: block.text });\n        parts.push({ type: \"reasoning-end\", id });\n      }\n    }\n\n    // Finish event\n    parts.push({ type: \"finish\", usage, finishReason });\n\n    // Create readable stream from the parts array\n    return new ReadableStream({\n      start(controller) {\n        for (const part of parts) {\n          controller.enqueue(part);\n        }\n        controller.close();\n      },\n    });\n  }\n}\n","import {\n  type LanguageModelV3,\n  type LanguageModelV3CallOptions,\n  type LanguageModelV3Content,\n  type LanguageModelV3FinishReason,\n  type LanguageModelV3ResponseMetadata,\n  type LanguageModelV3StreamPart,\n  type LanguageModelV3Usage,\n  type SharedV3Headers,\n  type SharedV3ProviderMetadata,\n  type SharedV3Warning,\n} from \"@ai-sdk/provider-v3\";\n\nimport { BaseLaminarLanguageModel } from \"./base-language-model\";\n\nexport class LaminarLanguageModelV3\n  extends BaseLaminarLanguageModel\n  implements LanguageModelV3\n{\n  readonly specificationVersion = \"v3\";\n\n  protected readonly innerLanguageModel: LanguageModelV3;\n\n  constructor(languageModel: LanguageModelV3) {\n    super(languageModel);\n    this.innerLanguageModel = languageModel;\n  }\n\n  protected createUsageObject(): LanguageModelV3Usage {\n    return {\n      inputTokens: {\n        total: 0,\n        noCache: 0,\n        cacheRead: 0,\n        cacheWrite: 0,\n      },\n      outputTokens: {\n        total: 0,\n        text: 0,\n        reasoning: 0,\n      },\n    };\n  }\n\n  doGenerate(options: LanguageModelV3CallOptions): PromiseLike<{\n    content: Array<LanguageModelV3Content>;\n    finishReason: LanguageModelV3FinishReason;\n    usage: LanguageModelV3Usage;\n    providerMetadata?: SharedV3ProviderMetadata;\n    request?: {\n      body?: unknown;\n    };\n    response?: LanguageModelV3ResponseMetadata & {\n      headers?: SharedV3Headers;\n      body?: unknown;\n    };\n    warnings: Array<SharedV3Warning>;\n  }> {\n    return this.doGenerateWithCaching(options, (opts) =>\n      this.innerLanguageModel.doGenerate(opts),\n    );\n  }\n\n  doStream(options: LanguageModelV3CallOptions): PromiseLike<{\n    stream: ReadableStream<LanguageModelV3StreamPart>;\n    request?: {\n      body?: unknown;\n    };\n    response?: {\n      headers?: SharedV3Headers;\n    };\n  }> {\n    return this.doStreamWithCaching(options, (opts) =>\n      this.innerLanguageModel.doStream(opts),\n    );\n  }\n\n  protected createStreamFromCachedResponse(\n    content: Array<LanguageModelV3Content>,\n    finishReason: LanguageModelV3FinishReason,\n    usage: LanguageModelV3Usage,\n  ): ReadableStream<LanguageModelV3StreamPart> {\n    const parts: LanguageModelV3StreamPart[] = [];\n\n    // Stream start\n    parts.push({ type: \"stream-start\", warnings: [] });\n\n    // Process each content block\n    let textIndex = 0;\n    let toolIndex = 0;\n    let reasoningIndex = 0;\n\n    // `providerMetadata` (and `providerExecuted` on tool calls) must survive\n    // the rebuild: the AI SDK echoes these into the next step's prompt, and\n    // the replay cache hashes that prompt — dropping them causes a spurious\n    // MISS on the following step.\n    for (const block of content) {\n      if (block.type === \"text\") {\n        const id = `text-${textIndex++}`;\n        parts.push({\n          type: \"text-start\",\n          id,\n          providerMetadata: block.providerMetadata,\n        });\n        parts.push({ type: \"text-delta\", id, delta: block.text });\n        parts.push({ type: \"text-end\", id });\n      } else if (block.type === \"tool-call\") {\n        const id = `tool-${toolIndex++}`;\n        parts.push({\n          type: \"tool-input-start\",\n          id,\n          toolName: block.toolName,\n        });\n        parts.push({\n          type: \"tool-input-delta\",\n          id,\n          delta: block.input,\n        });\n        parts.push({ type: \"tool-input-end\", id });\n        parts.push({ ...block, type: \"tool-call\" });\n      } else if (block.type === \"reasoning\") {\n        const id = `reasoning-${reasoningIndex++}`;\n        parts.push({\n          type: \"reasoning-start\",\n          id,\n          providerMetadata: block.providerMetadata,\n        });\n        parts.push({ type: \"reasoning-delta\", id, delta: block.text });\n        parts.push({ type: \"reasoning-end\", id });\n      }\n    }\n\n    // Finish event\n    parts.push({ type: \"finish\", usage, finishReason });\n\n    // Create readable stream from the parts array\n    return new ReadableStream({\n      start(controller) {\n        for (const part of parts) {\n          controller.enqueue(part);\n        }\n        controller.close();\n      },\n    });\n  }\n}\n","import {\n  type LanguageModelV4,\n  type LanguageModelV4CallOptions,\n  type LanguageModelV4Content,\n  type LanguageModelV4FinishReason,\n  type LanguageModelV4ResponseMetadata,\n  type LanguageModelV4StreamPart,\n  type LanguageModelV4Usage,\n  type SharedV4Headers,\n  type SharedV4ProviderMetadata,\n  type SharedV4Warning,\n} from \"@ai-sdk/provider\";\n\nimport { BaseLaminarLanguageModel } from \"./base-language-model\";\n\nexport class LaminarLanguageModelV4\n  extends BaseLaminarLanguageModel\n  implements LanguageModelV4\n{\n  readonly specificationVersion = \"v4\";\n\n  protected readonly innerLanguageModel: LanguageModelV4;\n\n  constructor(languageModel: LanguageModelV4) {\n    super(languageModel);\n    this.innerLanguageModel = languageModel;\n  }\n\n  protected createUsageObject(): LanguageModelV4Usage {\n    return {\n      inputTokens: {\n        total: 0,\n        noCache: 0,\n        cacheRead: 0,\n        cacheWrite: 0,\n      },\n      outputTokens: {\n        total: 0,\n        text: 0,\n        reasoning: 0,\n      },\n    };\n  }\n\n  doGenerate(options: LanguageModelV4CallOptions): PromiseLike<{\n    content: Array<LanguageModelV4Content>;\n    finishReason: LanguageModelV4FinishReason;\n    usage: LanguageModelV4Usage;\n    providerMetadata?: SharedV4ProviderMetadata;\n    request?: {\n      body?: unknown;\n    };\n    response?: LanguageModelV4ResponseMetadata & {\n      headers?: SharedV4Headers;\n      body?: unknown;\n    };\n    warnings: Array<SharedV4Warning>;\n  }> {\n    return this.doGenerateWithCaching(options, (opts) =>\n      this.innerLanguageModel.doGenerate(opts),\n    );\n  }\n\n  doStream(options: LanguageModelV4CallOptions): PromiseLike<{\n    stream: ReadableStream<LanguageModelV4StreamPart>;\n    request?: {\n      body?: unknown;\n    };\n    response?: {\n      headers?: SharedV4Headers;\n    };\n  }> {\n    return this.doStreamWithCaching(options, (opts) =>\n      this.innerLanguageModel.doStream(opts),\n    );\n  }\n\n  protected createStreamFromCachedResponse(\n    content: Array<LanguageModelV4Content>,\n    finishReason: LanguageModelV4FinishReason,\n    usage: LanguageModelV4Usage,\n  ): ReadableStream<LanguageModelV4StreamPart> {\n    const parts: LanguageModelV4StreamPart[] = [];\n\n    // Stream start\n    parts.push({ type: \"stream-start\", warnings: [] });\n\n    // Process each content block\n    let textIndex = 0;\n    let toolIndex = 0;\n    let reasoningIndex = 0;\n\n    // `providerMetadata` (and `providerExecuted` on tool calls) must survive\n    // the rebuild: the AI SDK echoes these into the next step's prompt, and\n    // the replay cache hashes that prompt — dropping them causes a spurious\n    // MISS on the following step.\n    for (const block of content) {\n      if (block.type === \"text\") {\n        const id = `text-${textIndex++}`;\n        parts.push({\n          type: \"text-start\",\n          id,\n          providerMetadata: block.providerMetadata,\n        });\n        parts.push({ type: \"text-delta\", id, delta: block.text });\n        parts.push({ type: \"text-end\", id });\n      } else if (block.type === \"tool-call\") {\n        const id = `tool-${toolIndex++}`;\n        parts.push({\n          type: \"tool-input-start\",\n          id,\n          toolName: block.toolName,\n        });\n        parts.push({\n          type: \"tool-input-delta\",\n          id,\n          delta: block.input,\n        });\n        parts.push({ type: \"tool-input-end\", id });\n        parts.push({ ...block, type: \"tool-call\" });\n      } else if (block.type === \"reasoning\") {\n        const id = `reasoning-${reasoningIndex++}`;\n        parts.push({\n          type: \"reasoning-start\",\n          id,\n          providerMetadata: block.providerMetadata,\n        });\n        parts.push({ type: \"reasoning-delta\", id, delta: block.text });\n        parts.push({ type: \"reasoning-end\", id });\n      }\n    }\n\n    // Finish event\n    parts.push({ type: \"finish\", usage, finishReason });\n\n    // Create readable stream from the parts array\n    return new ReadableStream({\n      start(controller) {\n        for (const part of parts) {\n          controller.enqueue(part);\n        }\n        controller.close();\n      },\n    });\n  }\n}\n","import { type LanguageModelV4 } from \"@ai-sdk/provider\";\nimport { type LanguageModelV2 } from \"@ai-sdk/provider-v2\";\nimport { type LanguageModelV3 } from \"@ai-sdk/provider-v3\";\nimport type * as AI from \"ai\";\n\nimport { initializeLogger } from \"../../../utils\";\nimport { getTracer } from \"../../tracing\";\nimport { LaminarLanguageModelV2 } from \"./v2\";\nimport { LaminarLanguageModelV3 } from \"./v3\";\nimport { LaminarLanguageModelV4 } from \"./v4\";\n\nconst AI_FUNCTIONS = [\n  \"generateText\",\n  \"generateObject\",\n  \"streamText\",\n  \"streamObject\",\n  \"embed\",\n  \"embedMany\",\n  \"rerank\",\n];\n\n/**\n * Detect AI SDK v7 by the presence of `registerTelemetry` (added only in v7).\n * On v7 the wrapper injects `integrations: [laminarTelemetry()]`; on v6 it\n * falls back to the older `experimental_telemetry: { tracer }` path.\n */\nconst isAISDKv7 = (ai: typeof AI): boolean =>\n  typeof (ai as any).registerTelemetry === \"function\";\n\nconst logger = initializeLogger();\nlet wrapAISDKv7WarnedOnce = false;\n\nexport const wrapAISDK = (ai: typeof AI): typeof AI => {\n  const wrapped: Record<string, any> = {};\n  const v7 = isAISDKv7(ai);\n\n  if (v7) {\n    if (!wrapAISDKv7WarnedOnce) {\n      wrapAISDKv7WarnedOnce = true;\n      logger.warn(\n        \"wrapAISDK() is not supported for AI SDK v7. \" +\n          \"Use LaminarAiSdkTelemetry instead:\\n\" +\n          \"  import { LaminarAiSdkTelemetry } from '@lmnr-ai/lmnr';\\n\" +\n          \"  import { registerTelemetry } from 'ai';\\n\" +\n          \"  registerTelemetry(new LaminarAiSdkTelemetry());\",\n      );\n    }\n    return ai;\n  }\n\n  Object.entries(ai).forEach(([key, value]) => {\n    if (typeof value === \"function\" && AI_FUNCTIONS.includes(key)) {\n      const originalFn = value as (...args: any[]) => any;\n      wrapped[key] = (...args: any[]) => {\n        if (args[0] && typeof args[0] === \"object\") {\n          const defaultTelemetry = {\n            isEnabled: true,\n            tracer: getTracer(),\n          };\n          args[0] = {\n            ...args[0],\n            experimental_telemetry: {\n              ...defaultTelemetry,\n              ...args[0].experimental_telemetry,\n            },\n          };\n        }\n        return originalFn(...args);\n      };\n    } else {\n      wrapped[key] = value;\n    }\n  });\n  return wrapped as typeof AI;\n};\n\nexport function wrapLanguageModel(\n  languageModel: LanguageModelV4,\n): LanguageModelV4;\nexport function wrapLanguageModel(\n  languageModel: LanguageModelV3,\n): LanguageModelV3;\nexport function wrapLanguageModel(\n  languageModel: LanguageModelV2,\n): LanguageModelV2;\nexport function wrapLanguageModel(\n  languageModel: LanguageModelV2 | LanguageModelV3 | LanguageModelV4,\n): LanguageModelV2 | LanguageModelV3 | LanguageModelV4 {\n  if (languageModel.specificationVersion === \"v4\") {\n    return new LaminarLanguageModelV4(languageModel);\n  }\n  if (languageModel.specificationVersion === \"v3\") {\n    return new LaminarLanguageModelV3(languageModel);\n  }\n  return new LaminarLanguageModelV2(languageModel);\n}\n","import { readdirSync } from \"node:fs\";\nimport { join, sep } from \"node:path\";\n\nimport {\n  SPAN_INSTRUMENTATION_SCOPE_NAME,\n  SPAN_INSTRUMENTATION_SCOPE_VERSION,\n} from \"../../../tracing/attributes\";\n\n/**\n * Installed versions of the `ai` package and any `@ai-sdk/*` packages\n * resolvable from the host application's `node_modules`. Best-effort: a\n * package that can't be resolved is simply omitted.\n */\nexport interface AiSdkPackageVersions {\n  aiVersion?: string;\n  aiSdkPackages: Record<string, string>;\n}\n\nlet cached: AiSdkPackageVersions | undefined;\n\nconst readPackageVersion = (specifier: string): string | undefined => {\n  try {\n    // biome-ignore lint/style/noCommonJs: dynamic package version resolution needs CJS resolve\n    const pkg = require(`${specifier}/package.json`);\n    return typeof pkg?.version === \"string\"\n      ? (pkg.version as string)\n      : undefined;\n  } catch {\n    return undefined;\n  }\n};\n\n/**\n * A `node_modules` search-path entry is a package-manager-internal virtual\n * store (pnpm's `.pnpm`, yarn's `.yarn`, etc.) if any path segment starts\n * with `.` — excluding the `.`/`..` relative-path segments themselves, which\n * are unrelated. Packages resolved from inside such a store are some\n * dependency's OWN transitive deps (e.g. `ai`'s `@ai-sdk/provider`), not\n * what the host project declared, so those entries must be skipped.\n */\nexport const isPackageManagerInternalPath = (path: string): boolean =>\n  path\n    .split(sep)\n    .some(\n      (segment) =>\n        segment.startsWith(\".\") && segment !== \".\" && segment !== \"..\",\n    );\n\n/**\n * Given the ordered `node_modules` search-path list Node would use to\n * resolve a module from this file's location, find the closest directory\n * that actually has an `@ai-sdk` scope — skipping package-manager-internal\n * stores — and return the packages listed under it. The first path with a\n * usable `@ai-sdk` directory wins; levels are not merged, so an unrelated\n * ancestor/monorepo-root's `@ai-sdk` scope is never mixed in once a closer\n * one has already matched.\n */\nexport const findAiSdkScopeEntries = (searchPaths: string[]): string[] => {\n  for (const path of searchPaths) {\n    if (isPackageManagerInternalPath(path)) continue;\n    try {\n      const entries = readdirSync(join(path, \"@ai-sdk\"));\n      if (entries.length > 0) return entries;\n    } catch {\n      // No @ai-sdk scope at this level — keep walking.\n    }\n  }\n  return [];\n};\n\nconst discoverAiSdkPackages = (): Record<string, string> => {\n  const packages: Record<string, string> = {};\n  let searchPaths: string[];\n  try {\n    searchPaths = require.resolve.paths(\"@ai-sdk/__probe__\") ?? [];\n  } catch {\n    searchPaths = [];\n  }\n\n  for (const entry of findAiSdkScopeEntries(searchPaths)) {\n    const specifier = `@ai-sdk/${entry}`;\n    const version = readPackageVersion(specifier);\n    if (version) packages[specifier] = version;\n  }\n  return packages;\n};\n\n/**\n * Reads installed `ai` / `@ai-sdk/*` package versions once and caches the\n * result for the lifetime of the process — this is expected to be called on\n * every span creation, so the actual `require`/`readdirSync` work must not\n * repeat.\n */\nexport const getAiSdkPackageVersions = (): AiSdkPackageVersions => {\n  if (cached) return cached;\n  try {\n    cached = {\n      aiVersion: readPackageVersion(\"ai\"),\n      aiSdkPackages: discoverAiSdkPackages(),\n    };\n  } catch {\n    cached = { aiSdkPackages: {} };\n  }\n  return cached;\n};\n\n/**\n * Flat span-attribute object for the `ai` package's instrumentation scope\n * plus one `lmnr.span.instrumentation.@ai-sdk/<pkg>.version` entry per\n * resolvable `@ai-sdk/*` package. Merge this into every span this\n * integration creates.\n */\nexport const buildAiSdkInstrumentationAttributes = (): Record<\n  string,\n  string\n> => {\n  const { aiVersion, aiSdkPackages } = getAiSdkPackageVersions();\n  const attributes: Record<string, string> = {\n    [SPAN_INSTRUMENTATION_SCOPE_NAME]: \"ai\",\n  };\n  if (aiVersion) attributes[SPAN_INSTRUMENTATION_SCOPE_VERSION] = aiVersion;\n  for (const [pkg, version] of Object.entries(aiSdkPackages)) {\n    attributes[`lmnr.span.instrumentation.${pkg}.version`] = version;\n  }\n  return attributes;\n};\n","import type { Context, Span } from \"@opentelemetry/api\";\n\nexport interface OperationState {\n  span: Span;\n  ctx: Context;\n  operationId?: string;\n  provider?: string;\n  modelId?: string;\n}\n\nexport interface StepState {\n  span: Span;\n  ctx: Context;\n  stepNumber: number;\n}\n\nexport interface LlmState {\n  span: Span;\n  textDeltas: string[];\n}\n\nexport interface ToolState {\n  span: Span;\n  ctx: Context;\n  callId: string;\n}\n\nexport const stepKey = (callId: string, stepNumber: number): string =>\n  `${callId}:${stepNumber}`;\n","// Vercel AI SDK v7 telemetry integration.\n//\n// v7 replaces the v6 `experimental_telemetry: { tracer }` OTel-span-based\n// design with a plain `Telemetry` interface — 16 optional lifecycle callbacks\n// plus an `executeTool` wrapper that lets integrations propagate context into\n// tool execution (required for sub-agent nesting).\n//\n// Span hierarchy we build:\n//   <generateText|streamText> (DEFAULT)\n//     ├─ <step 0>              (DEFAULT)\n//     │   ├─ <llm call>        (LLM)\n//     │   ├─ <tool: X>         (TOOL) — flat sibling, not a child of the LLM\n//     │   ├─ <tool: Y>         (TOOL)\n//     ├─ <step 1>\n//     │   ├─ <llm call>        (LLM)\n//     │   ...\n//\n// For embed / embedMany / rerank we create a single LLM span directly under\n// the operation span — there are no step or tool spans.\n//\n// Attribute strategy: verbatim. LLM spans carry `gen_ai.input.messages`\n// (the LanguageModel-level prompt through `stringifyPromptForTelemetry` —\n// the ONLY transformation is Uint8Array file data → base64) and\n// `gen_ai.output.messages` (`[{role:\"assistant\", content: event.content}]`,\n// the provider's LanguageModelContent array untouched). `ai.prompt.messages`\n// is NOT written on v7 LLM spans. Metadata attributes (model, usage,\n// finish reason) still use both `ai.*` and `gen_ai.*` families.\n//\n// Sub-agent nesting works because `executeTool` wraps the tool's execute in\n// an OTel context that has the tool span set as the active span. Nested\n// `generateText` calls pick that up via `LaminarContextManager.getContext()`\n// which falls through to `trace.getActiveSpan()` / the Laminar ALS stack.\n\nimport * as diagnosticsChannel from \"node:diagnostics_channel\";\n\nimport { errorMessage } from \"@lmnr-ai/types\";\nimport {\n  context as contextApi,\n  type HrTime,\n  SpanKind,\n  SpanStatusCode,\n  trace,\n} from \"@opentelemetry/api\";\n\nimport { Laminar, type LaminarInitializeProps } from \"../../../../laminar\";\nimport { initializeLogger, metadataToAttributes } from \"../../../../utils\";\nimport { getTracer } from \"../../../tracing\";\nimport {\n  ASSOCIATION_PROPERTIES,\n  LaminarAttributes,\n  SESSION_ID,\n  SPAN_INPUT,\n  SPAN_OUTPUT,\n  SPAN_TYPE,\n  USER_ID,\n} from \"../../../tracing/attributes\";\nimport { LaminarContextManager } from \"../../../tracing/context\";\nimport { pushActiveLlmSpan, removeActiveLlmSpan } from \"../active-llm-span\";\nimport { buildAiSdkInstrumentationAttributes } from \"./package-versions\";\nimport {\n  type LlmState,\n  type OperationState,\n  type StepState,\n  stepKey,\n  type ToolState,\n} from \"./types\";\nimport {\n  applyFinishReason,\n  applyRequestModelAttributes,\n  applyUsageToSpan,\n  buildTextOutputMessages,\n  buildVerbatimOutputMessages,\n  compareHrTime,\n  normalizeProvider,\n  readSpanEndTime,\n  serializeJSON,\n  verbatimPromptString,\n  verbatimStandardizedMessages,\n} from \"./utils\";\n\n/**\n * The AI SDK v7 diagnostics channel name. Every lifecycle event fires\n * `{ type, event }` through this channel.\n */\nexport const AI_SDK_TELEMETRY_DIAGNOSTIC_CHANNEL = \"aisdk:telemetry\";\n\nexport interface LaminarAiSdkTelemetryOptions {\n  /**\n   * When true, record prompt messages and response content on spans.\n   * Defaults to true.\n   */\n  recordInputs?: boolean;\n  recordOutputs?: boolean;\n  /**\n   * When true, create an `ai.step N` span for each step in a multi-step\n   * generation. Defaults to false.\n   */\n  createStepSpan?: boolean;\n  /**\n   * Options to pass to {@link Laminar.initialize}. If Laminar is already\n   * initialized, this is ignored. Allows all-in-one setup without a separate\n   * `Laminar.initialize()` call.\n   */\n  laminarOptions?: LaminarInitializeProps;\n}\n\n/**\n * Laminar's implementation of the AI SDK v7 `Telemetry` interface.\n *\n * Shape matches `ai`'s exported `Telemetry` (v7). Constructing this class\n * directly depends only on OTel and Laminar internals — we do NOT import the\n * `Telemetry` interface from `ai` so users can pick up the integration even\n * when they are on a narrower `ai` version that doesn't export it yet.\n */\nexport class LaminarAiSdkTelemetry {\n  private readonly recordInputs: boolean;\n  private readonly recordOutputs: boolean;\n  private readonly createStepSpan: boolean;\n\n  // Root operation span (one per generateText/streamText/generateObject/\n  // streamObject/embed/embedMany/rerank call), keyed by AI SDK `callId`.\n  private readonly operationByCallId = new Map<string, OperationState>();\n  // Step span (one per LLM invocation within a text-generation operation),\n  // keyed by `${callId}:${stepNumber}`.\n  private readonly stepByKey = new Map<string, StepState>();\n  // LLM child span under the step. Same key shape as stepByKey.\n  private readonly llmByKey = new Map<string, LlmState>();\n  // Tool spans keyed by toolCallId (AI SDK guarantees uniqueness per run).\n  private readonly toolByCallId = new Map<string, ToolState>();\n  // Active streaming step per callId, set by `ai.stream.firstChunk` and\n  // cleared by `ai.stream.finish`. Used to route `text-delta` chunks to the\n  // right LLM span — individual text-delta chunks don't carry callId or\n  // stepNumber themselves.\n  private readonly activeStreamStepByCallId = new Map<string, number>();\n  // Serialized verbatim LanguageModel-level prompt (`event.promptMessages`\n  // through `stringifyPromptForTelemetry`), stashed by onStepStart for the\n  // immediately-following LLM call. Keyed by callId ALONE — v7's\n  // languageModelCallStartEvent carries NO stepNumber (verified against\n  // ai@7.0.17), and steps within one call are strictly sequential with no\n  // await between onStepStart and onLanguageModelCallStart, so one slot per\n  // callId is unambiguous. Consumed by onLanguageModelCallStart; swept on\n  // llm-call end, step finish, and operation close. This is the SAME\n  // serialization the replay wrapper hashes, so recording level == replay\n  // level for the debugger cache.\n  private readonly promptByCallId = new Map<string, string>();\n\n  private readonly logger = initializeLogger();\n\n  constructor(options: LaminarAiSdkTelemetryOptions = {}) {\n    this.recordInputs = options.recordInputs ?? true;\n    this.recordOutputs = options.recordOutputs ?? true;\n    this.createStepSpan = options.createStepSpan ?? false;\n    if (!Laminar.initialized()) {\n      Laminar.initialize(options.laminarOptions ?? {});\n    }\n  }\n\n  // ------------------------------------------------------------------\n  // operation-level: generateText / streamText / generateObject / streamObject\n  // ------------------------------------------------------------------\n\n  onStart = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    const parentCtx = LaminarContextManager.getContext();\n    const tracer = getTracer();\n    let spanName = event.operationId ?? \"ai.operation\";\n    // If an explicit { telemetry: { functionId: \"...\" } } is passed\n    // rename the span to match the pre-v7 AI SDK behaviour\n    if (typeof event.functionId === \"string\") {\n      spanName += ` ${event.functionId}`;\n    }\n    const span = tracer.startSpan(\n      spanName,\n      {\n        kind: SpanKind.CLIENT,\n        attributes: {\n          [SPAN_TYPE]: \"DEFAULT\",\n          ...buildAiSdkInstrumentationAttributes(),\n          ...(typeof event.functionId === \"string\"\n            ? {\n                \"operation.name\": event.functionId,\n                // legacy, needed for older parsing at the backend to work\n                \"ai.prompt\": \"_\",\n              }\n            : {}),\n        },\n      },\n      parentCtx,\n    );\n    const spanCtx = trace.setSpan(parentCtx, span);\n\n    span.setAttribute(SPAN_TYPE, \"DEFAULT\");\n    if (typeof event.operationId === \"string\") {\n      span.setAttribute(\"ai.operation\", event.operationId);\n    }\n    if (typeof event.provider === \"string\") {\n      const provider = normalizeProvider(event.provider);\n      if (provider) span.setAttribute(LaminarAttributes.PROVIDER, provider);\n    }\n    if (typeof event.modelId === \"string\") {\n      span.setAttribute(LaminarAttributes.REQUEST_MODEL, event.modelId);\n      span.setAttribute(\"ai.model.id\", event.modelId);\n    }\n    if (typeof event.functionId === \"string\") {\n      span.setAttribute(\"ai.functionId\", event.functionId);\n    }\n\n    // Classify embed / embedMany / rerank as LLM spans directly, since there\n    // are no step or llm-call child spans for these.\n    const isEmbedOrRerank =\n      event.operationId === \"ai.embed\" ||\n      event.operationId === \"ai.embedMany\" ||\n      event.operationId === \"ai.rerank\";\n    if (isEmbedOrRerank) {\n      span.setAttribute(SPAN_TYPE, \"LLM\");\n    }\n\n    const allMetadata = {\n      ...(event.toolsContext ?? {}),\n      ...(event.runtimeContext ?? {}),\n    };\n    const { userId, sessionId, tags, ...metadata } = allMetadata;\n    if (sessionId) {\n      span.setAttribute(SESSION_ID, sessionId);\n    }\n    if (userId) {\n      span.setAttribute(USER_ID, userId);\n    }\n    if (\n      tags &&\n      Array.isArray(tags) &&\n      tags.every((tag) => typeof tag === \"string\")\n    ) {\n      span.setAttribute(`${ASSOCIATION_PROPERTIES}.tags`, tags);\n    }\n    span.setAttributes(metadataToAttributes(metadata));\n\n    if (this.recordInputs) {\n      // generate/stream variants carry StandardizedPrompt (system + messages);\n      // embed carries `value`; rerank carries `documents` + `query`.\n      if (\n        Array.isArray(event.messages) ||\n        event.system !== undefined ||\n        event.instructions !== undefined\n      ) {\n        const msgs = verbatimStandardizedMessages(event);\n        if (msgs.length > 0) {\n          span.setAttribute(SPAN_INPUT, serializeJSON(msgs));\n        }\n      } else if (event.value !== undefined) {\n        span.setAttribute(SPAN_INPUT, serializeJSON(event.value));\n      } else if (event.query !== undefined || event.documents !== undefined) {\n        span.setAttribute(\n          SPAN_INPUT,\n          serializeJSON({ query: event.query, documents: event.documents }),\n        );\n      }\n    }\n\n    this.operationByCallId.set(callId, {\n      span,\n      ctx: spanCtx,\n      operationId: event.operationId ?? \"unknown\",\n      provider: event.provider,\n      modelId: event.modelId,\n    });\n  };\n\n  onStepStart = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    const stepNumber: number = event?.stepNumber ?? 0;\n    if (!callId) return;\n\n    // ALWAYS stash the verbatim LanguageModel-level prompt for the LLM call\n    // that follows this step start (same callId, no await in between) — even\n    // when step spans are disabled. onLanguageModelCallStart only carries the\n    // ModelMessage-level `instructions`+`messages`, not the provider prompt,\n    // so this stash is the ONLY source for verbatim `gen_ai.input.messages`\n    // on the LLM span.\n    if (Array.isArray(event?.promptMessages)) {\n      const serialized = verbatimPromptString(event.promptMessages);\n      if (serialized !== null) {\n        this.promptByCallId.set(callId, serialized);\n      }\n    }\n\n    if (!this.createStepSpan) return;\n    const op = this.operationByCallId.get(callId);\n    if (!op) return;\n    const tracer = getTracer();\n    const span = tracer.startSpan(`ai.step`, { kind: SpanKind.CLIENT }, op.ctx);\n    const spanCtx = trace.setSpan(op.ctx, span);\n    span.setAttribute(SPAN_TYPE, \"DEFAULT\");\n    span.setAttributes(buildAiSdkInstrumentationAttributes());\n    span.setAttribute(\"ai.step.number\", stepNumber);\n\n    if (this.recordInputs) {\n      const msgs = verbatimStandardizedMessages(event);\n      if (msgs.length > 0) {\n        span.setAttribute(SPAN_INPUT, serializeJSON(msgs));\n      }\n    }\n\n    this.stepByKey.set(stepKey(callId, stepNumber), {\n      span,\n      ctx: spanCtx,\n      stepNumber,\n    });\n  };\n\n  onLanguageModelCallStart = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    // When createStepSpan is true, LLM calls attach to the latest open step\n    // span; its stepNumber keys llmByKey. When false (no step spans\n    // registered), fall back to event.stepNumber — v7's\n    // languageModelCallStartEvent does NOT carry it (verified against\n    // ai@7.0.17) so this usually resolves to 0, which is still safe: LLM\n    // calls within one callId are strictly sequential, so at most one entry\n    // is live per callId at a time and start/end resolve the same key.\n    const step = this.findLatestStep(callId);\n    const stepNumber =\n      step?.stepNumber ?? (event?.stepNumber as number | undefined) ?? 0;\n    const parentCtx = step?.ctx ?? this.operationByCallId.get(callId)?.ctx;\n    if (!parentCtx) return;\n\n    const tracer = getTracer();\n    const span = tracer.startSpan(\n      `ai.llm ${event.provider ?? \"\"}:${event.modelId ?? \"\"}`,\n      { kind: SpanKind.CLIENT },\n      parentCtx,\n    );\n    span.setAttribute(SPAN_TYPE, \"LLM\");\n    span.setAttributes(buildAiSdkInstrumentationAttributes());\n    applyRequestModelAttributes(span, event);\n    if (this.recordInputs) {\n      if (event.tools) {\n        try {\n          span.setAttribute(\n            \"gen_ai.tool.definitions\",\n            JSON.stringify(event.tools),\n          );\n        } catch (e) {\n          this.logger.debug(\n            `Failed to record span tool definitions: ${errorMessage(e)}`,\n          );\n        }\n      }\n      // Verbatim LanguageModel-level prompt, stashed by onStepStart. This is\n      // the exact serialization the replay wrapper hashes, so the server-side\n      // debugger cache keys match at record and replay time. There is NO\n      // fallback to this event's ModelMessage-level `instructions`+`messages`:\n      // those bytes differ structurally from `options.prompt` (e.g. a raw\n      // string user message stays a string at ModelMessage level but is a\n      // `[{type:\"text\",text}]` parts array at LanguageModel level), so a\n      // fallback-recorded input can never hash-match at replay time — a wrong\n      // cache key silently degrades the whole debug run to live. Omitting the\n      // attribute is the safer failure mode.\n      const serialized = this.promptByCallId.get(callId);\n      if (serialized !== undefined) {\n        span.setAttribute(\"gen_ai.input.messages\", serialized);\n      }\n    }\n\n    this.llmByKey.set(stepKey(callId, stepNumber), {\n      span,\n      textDeltas: [],\n    });\n    // Publish to the replay wrapper so a cache HIT marks THIS span CACHED, not\n    // the on-context operation span (the parked llm span never enters context).\n    pushActiveLlmSpan(span);\n  };\n\n  onLanguageModelCallEnd = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    const step = this.findLatestStep(callId);\n    const stepNumber =\n      step?.stepNumber ?? (event?.stepNumber as number | undefined) ?? 0;\n    const llm = this.llmByKey.get(stepKey(callId, stepNumber));\n    if (!llm) return;\n\n    const span = llm.span;\n    if (typeof event.provider === \"string\") {\n      const provider = normalizeProvider(event.provider);\n      if (provider) span.setAttribute(LaminarAttributes.PROVIDER, provider);\n    }\n    if (typeof event.modelId === \"string\") {\n      span.setAttribute(LaminarAttributes.RESPONSE_MODEL, event.modelId);\n    }\n    if (typeof event.finishReason === \"string\") {\n      applyFinishReason(span, event.finishReason);\n    }\n    if (typeof event.responseId === \"string\") {\n      span.setAttribute(\"gen_ai.response.id\", event.responseId);\n    }\n    applyUsageToSpan(span, event.usage);\n\n    if (this.recordOutputs) {\n      // Verbatim provider content: `event.content` is the LanguageModelContent\n      // array exactly as returned, wrapped in one assistant message.\n      const outputMessages = buildVerbatimOutputMessages(\n        Array.isArray(event.content) ? (event.content as any[]) : undefined,\n      );\n      if (outputMessages) {\n        span.setAttribute(\"gen_ai.output.messages\", outputMessages);\n      }\n    }\n\n    span.setStatus({ code: SpanStatusCode.OK });\n    span.end();\n    removeActiveLlmSpan(span);\n    this.llmByKey.delete(stepKey(callId, stepNumber));\n    this.promptByCallId.delete(callId);\n  };\n\n  onChunk = (event: any): void => {\n    const chunk = event?.chunk;\n    if (!chunk || typeof chunk !== \"object\") return;\n    // Only the lifecycle markers `ai.stream.firstChunk` / `ai.stream.finish`\n    // carry `callId` + `stepNumber`; regular content chunks (`text-delta`,\n    // `tool-call`, etc.) do not — they are plain `TextStreamPart` objects.\n    // See AI SDK source `packages/ai/src/generate-text/stream-text.ts` for\n    // the publish points. We therefore latch the active streaming step when\n    // `firstChunk` fires and route subsequent text-delta chunks to it until\n    // `finish` arrives.\n    if (chunk.type === \"ai.stream.firstChunk\") {\n      if (\n        typeof chunk.callId === \"string\" &&\n        typeof chunk.stepNumber === \"number\"\n      ) {\n        this.activeStreamStepByCallId.set(chunk.callId, chunk.stepNumber);\n      }\n      return;\n    }\n    if (chunk.type === \"ai.stream.finish\") {\n      if (typeof chunk.callId === \"string\") {\n        this.activeStreamStepByCallId.delete(chunk.callId);\n      }\n      return;\n    }\n    if (chunk.type !== \"text-delta\") return;\n    if (typeof chunk.text !== \"string\" || chunk.text.length === 0) return;\n    // Content chunks carry no callId. When exactly one stream is active we\n    // can route the delta unambiguously; with 2+ concurrent streams sharing\n    // the same LaminarTelemetry instance the owner is ambiguous and naive\n    // LIFO would misattribute A's chunks to B after B's firstChunk. In that\n    // case skip accumulation — the buffered-deltas path is only a fallback\n    // for when onLanguageModelCallEnd doesn't fire; on the normal path we\n    // read text from `event.content` which is correctly scoped per call.\n    if (this.activeStreamStepByCallId.size !== 1) return;\n    const [callId, stepNumber] = this.activeStreamStepByCallId.entries().next()\n      .value!;\n    const llm = this.llmByKey.get(stepKey(callId, stepNumber));\n    if (!llm) return;\n    llm.textDeltas.push(chunk.text);\n  };\n\n  onStepFinish = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    const stepNumber: number = event?.stepNumber ?? 0;\n    if (!callId) return;\n    const key = stepKey(callId, stepNumber);\n\n    // Ensure the LLM span for this step is closed, even if the provider\n    // skipped `onLanguageModelCallEnd` (e.g. an error surfaced via onError).\n    const llm = this.llmByKey.get(key);\n    if (llm) {\n      // Flush any buffered stream deltas as the text output if we haven't\n      // already set one via onLanguageModelCallEnd. Use the same verbatim\n      // gen_ai.output.messages shape that path emits (a single text part), so\n      // the backend stores one consistent output format and the debugger can\n      // replay it.\n      if (this.recordOutputs && llm.textDeltas.length > 0) {\n        const outputMessages = buildTextOutputMessages(llm.textDeltas.join(\"\"));\n        if (outputMessages) {\n          llm.span.setAttribute(\"gen_ai.output.messages\", outputMessages);\n        }\n      }\n      // onLanguageModelCallEnd never fired (it deletes the key on the normal\n      // path), so it never stamped usage on this LLM span. Record the step\n      // usage here so interrupted / errored flows still report cost. Safe to\n      // write on the LLM leaf — it has no children, so no double counting.\n      applyUsageToSpan(llm.span, event.usage);\n      llm.span.end();\n      removeActiveLlmSpan(llm.span);\n      this.llmByKey.delete(key);\n    }\n    this.promptByCallId.delete(callId);\n\n    const step = this.stepByKey.get(key);\n    if (!step) return;\n\n    // Emit finish reason on the step span. Do NOT write token usage here: the\n    // step span is DEFAULT-typed and the backend computes cost from\n    // gen_ai.usage.* on ANY span carrying them, so usage on the step would be\n    // summed on top of its LLM-leaf children (double counting). Usage lives on\n    // the LLM leaf spans only.\n    if (typeof event.finishReason === \"string\") {\n      applyFinishReason(step.span, event.finishReason);\n    }\n    if (this.recordOutputs) {\n      // Verbatim step content (StepResult.content — the same parts the LLM\n      // span records), wrapped in one assistant message.\n      const outputMessages = buildVerbatimOutputMessages(\n        Array.isArray(event.content) ? (event.content as any[]) : undefined,\n      );\n      if (outputMessages) {\n        step.span.setAttribute(SPAN_OUTPUT, outputMessages);\n      }\n    }\n\n    step.span.setStatus({ code: SpanStatusCode.OK });\n    step.span.end();\n    this.stepByKey.delete(key);\n  };\n\n  // ------------------------------------------------------------------\n  // object-generation (generateObject / streamObject)\n  //\n  // These callbacks fire ONLY from generateObject / streamObject (which call\n  // model.doGenerate / doStream directly) — they do NOT overlap with\n  // onLanguageModelCall* (which fire only from generateText / streamText via\n  // stream-language-model-call.ts). So keying the LLM span under\n  // stepKey(callId, 0) is safe — there is no onLanguageModelCallStart/End pair\n  // for the same callId that would collide on the same map entry.\n  // ------------------------------------------------------------------\n\n  onObjectStepStart = (event: any): void => {\n    // generateObject/streamObject emit step 0 with no StandardizedPrompt at\n    // step-start time — just map to an LLM span directly under the operation.\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    const op = this.operationByCallId.get(callId);\n    if (!op) return;\n    const tracer = getTracer();\n    const span = tracer.startSpan(\n      `ai.llm ${event.provider ?? \"\"}:${event.modelId ?? \"\"}`,\n      { kind: SpanKind.CLIENT },\n      op.ctx,\n    );\n    span.setAttribute(SPAN_TYPE, \"LLM\");\n    span.setAttributes(buildAiSdkInstrumentationAttributes());\n    applyRequestModelAttributes(span, event);\n    if (this.recordInputs && Array.isArray(event?.promptMessages)) {\n      // Same verbatim serialization the replay wrapper hashes — see\n      // onLanguageModelCallStart.\n      const serialized = verbatimPromptString(event.promptMessages);\n      if (serialized !== null) {\n        span.setAttribute(\"gen_ai.input.messages\", serialized);\n      }\n    }\n    this.llmByKey.set(stepKey(callId, 0), { span, textDeltas: [] });\n    pushActiveLlmSpan(span);\n  };\n\n  onObjectStepFinish = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    const llm = this.llmByKey.get(stepKey(callId, 0));\n    if (!llm) return;\n    if (typeof event.finishReason === \"string\") {\n      applyFinishReason(llm.span, event.finishReason);\n    }\n    // GenerateObjectStepEndEvent.response carries { id, modelId, ... } — mirror\n    // onLanguageModelCallEnd by emitting gen_ai.response.model +\n    // gen_ai.response.id so model-routing / cost dashboards see the actual\n    // response model for object-gen calls too.\n    const response = event?.response;\n    if (response && typeof response === \"object\") {\n      if (typeof response.modelId === \"string\") {\n        llm.span.setAttribute(\n          LaminarAttributes.RESPONSE_MODEL,\n          response.modelId,\n        );\n      }\n      if (typeof response.id === \"string\") {\n        llm.span.setAttribute(\"gen_ai.response.id\", response.id);\n      }\n    }\n    applyUsageToSpan(llm.span, event.usage);\n    if (this.recordOutputs && typeof event.objectText === \"string\") {\n      const outputMessages = buildTextOutputMessages(event.objectText);\n      if (outputMessages) {\n        llm.span.setAttribute(\"gen_ai.output.messages\", outputMessages);\n      }\n    }\n    llm.span.setStatus({ code: SpanStatusCode.OK });\n    llm.span.end();\n    removeActiveLlmSpan(llm.span);\n    this.llmByKey.delete(stepKey(callId, 0));\n  };\n\n  // ------------------------------------------------------------------\n  // tool execution — spans are flat siblings of the LLM span under the step\n  // ------------------------------------------------------------------\n\n  onToolExecutionStart = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    const toolCall = event?.toolCall;\n    const toolCallId: string | undefined = toolCall?.toolCallId;\n    const toolName: string | undefined = toolCall?.toolName;\n    if (!callId || !toolCallId) return;\n\n    // Parent the tool span under the current step, not the LLM span. LLM and\n    // tool spans are flat siblings under the step.\n    const step = this.findLatestStep(callId);\n    const parentCtx = step?.ctx ?? this.operationByCallId.get(callId)?.ctx;\n    if (!parentCtx) return;\n\n    const tracer = getTracer();\n    const span = tracer.startSpan(\n      `ai.tool ${toolName ?? \"unknown\"}`,\n      { kind: SpanKind.CLIENT },\n      parentCtx,\n    );\n    const spanCtx = trace.setSpan(parentCtx, span);\n    span.setAttribute(SPAN_TYPE, \"TOOL\");\n    span.setAttributes(buildAiSdkInstrumentationAttributes());\n    if (toolName) span.setAttribute(\"ai.toolCall.name\", toolName);\n    span.setAttribute(\"ai.toolCall.id\", toolCallId);\n    if (this.recordInputs && toolCall?.input !== undefined) {\n      const serialized = serializeJSON(toolCall.input);\n      span.setAttribute(\"ai.toolCall.args\", serialized);\n      span.setAttribute(SPAN_INPUT, serialized);\n    }\n    this.toolByCallId.set(toolCallId, { span, ctx: spanCtx, callId });\n  };\n\n  onToolExecutionEnd = (event: any): void => {\n    const toolCallId: string | undefined = event?.toolCall?.toolCallId;\n    if (!toolCallId) return;\n    const tool = this.toolByCallId.get(toolCallId);\n    if (!tool) return;\n\n    if (typeof event.durationMs === \"number\") {\n      tool.span.setAttribute(\"ai.toolCall.durationMs\", event.durationMs);\n    }\n\n    const output = event?.toolOutput;\n    if (output && typeof output === \"object\") {\n      if (output.type === \"tool-error\") {\n        const err = output.error;\n        const message =\n          err instanceof Error\n            ? err.message\n            : typeof err === \"string\"\n              ? err\n              : serializeJSON(err);\n        tool.span.recordException(\n          err instanceof Error ? err : new Error(message),\n        );\n        tool.span.setStatus({ code: SpanStatusCode.ERROR, message });\n        if (this.recordOutputs) {\n          tool.span.setAttribute(SPAN_OUTPUT, message);\n          tool.span.setAttribute(\"ai.toolCall.error\", message);\n        }\n      } else if (output.type === \"tool-result\") {\n        if (this.recordOutputs && output.output !== undefined) {\n          const serialized = serializeJSON(output.output);\n          tool.span.setAttribute(\"ai.toolCall.result\", serialized);\n          tool.span.setAttribute(SPAN_OUTPUT, serialized);\n        }\n        tool.span.setStatus({ code: SpanStatusCode.OK });\n      }\n    } else {\n      tool.span.setStatus({ code: SpanStatusCode.OK });\n    }\n\n    tool.span.end();\n    this.toolByCallId.delete(toolCallId);\n  };\n\n  /**\n   * `executeTool` is v7's context-propagation hook. The AI SDK runs the\n   * tool's `execute` function inside whatever we return, so by entering a\n   * context that has the tool span set as the active span, any nested\n   * `generateText`/`streamText` call inside the tool will be reparented\n   * under the TOOL span (sub-agent nesting).\n   */\n  executeTool = <T>(options: {\n    callId: string;\n    toolCallId: string;\n    execute: () => PromiseLike<T>;\n  }): PromiseLike<T> => {\n    const tool = this.toolByCallId.get(options.toolCallId);\n    if (!tool) return options.execute();\n    // Push onto both the OTel active context AND the Laminar ALS stack so\n    // *any* child — standard OTel instrumentation (`trace.getActiveSpan`) and\n    // Laminar-aware calls (`LaminarContextManager.getContext`) — can see it.\n    return contextApi.with(tool.ctx, () => {\n      const currentStack = LaminarContextManager.getContextStack();\n      return LaminarContextManager.runWithIsolatedContext(\n        [...currentStack, tool.ctx],\n        () => options.execute(),\n      );\n    });\n  };\n\n  // ------------------------------------------------------------------\n  // embed / rerank — single LLM span, closed directly on finish\n  // ------------------------------------------------------------------\n\n  onEmbedStart = (event: any): void => {\n    // Individual doEmbed invocation — we don't create a separate span for\n    // each, the operation-level `onStart` already created an LLM span.\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    const op = this.operationByCallId.get(callId);\n    if (!op) return;\n    if (typeof event.modelId === \"string\") {\n      op.span.setAttribute(LaminarAttributes.REQUEST_MODEL, event.modelId);\n    }\n  };\n\n  onEmbedEnd = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    const op = this.operationByCallId.get(callId);\n    if (!op) return;\n    applyUsageToSpan(op.span, event.usage);\n  };\n\n  onRerankStart = (): void => {\n    // onStart already created the LLM span for ai.rerank. Nothing to do —\n    // documents/query are already recorded.\n  };\n\n  onRerankEnd = (): void => {\n    // End-of-rerank data lands via onFinish which carries the full event.\n  };\n\n  // ------------------------------------------------------------------\n  // operation finish / error\n  // ------------------------------------------------------------------\n\n  onEnd = (event: any): void => {\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    const op = this.operationByCallId.get(callId);\n    if (!op) return;\n\n    // Metadata (finish reason, aggregated token usage) is recorded regardless\n    // of recordOutputs — it's not user-content and is what analytics / cost\n    // dashboards read off the top-level span.\n    if (typeof event.finishReason === \"string\") {\n      applyFinishReason(op.span, event.finishReason);\n    }\n    // Only write token usage on embed / embedMany / rerank operation spans —\n    // those are classified LLM in onStart and have no LLM-leaf children, so\n    // the cost belongs on them. For generateText / streamText / generateObject\n    // / streamObject the operation span is DEFAULT and its children (the LLM\n    // leaf / object-gen spans) already carry usage; the backend computes cost\n    // from gen_ai.usage.* on ANY span, so stamping the already-aggregated\n    // totalUsage here would double-count it on top of the children.\n    const isEmbedOrRerank =\n      op.operationId === \"ai.embed\" ||\n      op.operationId === \"ai.embedMany\" ||\n      op.operationId === \"ai.rerank\";\n    if (isEmbedOrRerank) {\n      applyUsageToSpan(op.span, event.totalUsage ?? event.usage);\n    }\n\n    // Write final output content onto the operation span.\n    if (this.recordOutputs) {\n      // Text generation: verbatim content across all steps (StepResult parts\n      // exactly as the provider returned them), wrapped in one assistant\n      // message — the same shape the LLM / step spans record.\n      const outputMessages = buildVerbatimOutputMessages(\n        Array.isArray(event.content) ? (event.content as any[]) : undefined,\n      );\n      if (outputMessages) {\n        op.span.setAttribute(SPAN_OUTPUT, outputMessages);\n      }\n\n      // Embed: final embedding(s).\n      if (event.embedding !== undefined) {\n        // Avoid writing the raw vectors — just record shape.\n        const emb = event.embedding;\n        if (Array.isArray(emb) && Array.isArray(emb[0])) {\n          op.span.setAttribute(\"ai.embed.count\", emb.length);\n        } else if (Array.isArray(emb)) {\n          op.span.setAttribute(\"ai.embed.count\", 1);\n        }\n      }\n      // Rerank: ranking array is small enough to serialize.\n      if (Array.isArray(event.ranking)) {\n        op.span.setAttribute(\"ai.rerank.ranking\", serializeJSON(event.ranking));\n        op.span.setAttribute(SPAN_OUTPUT, serializeJSON(event.ranking));\n      }\n    }\n\n    // v7 FinishReason includes `\"error\"` — if the SDK surfaces the failure\n    // via onFinish (rather than onError), honor it instead of stamping OK.\n    if (event.finishReason === \"error\") {\n      op.span.setStatus({ code: SpanStatusCode.ERROR });\n    } else {\n      op.span.setStatus({ code: SpanStatusCode.OK });\n    }\n\n    this.closeOperation(callId, op);\n  };\n\n  onError = (event: any): void => {\n    // v7 passes either a structured `{ callId?, error }` payload or a raw\n    // error value. Try to scope the error to a single operation — blindly\n    // flagging every in-flight op would mark unrelated concurrent\n    // generateText / streamText calls as errored.\n    const rawError =\n      event && typeof event === \"object\" && \"error\" in event\n        ? event.error\n        : event;\n    const err =\n      rawError instanceof Error\n        ? rawError\n        : new Error(\n            typeof rawError === \"string\" ? rawError : serializeJSON(rawError),\n          );\n    const eventCallId: string | undefined =\n      event && typeof event === \"object\" && typeof event.callId === \"string\"\n        ? event.callId\n        : undefined;\n\n    // Resolve the target operation:\n    //  - explicit callId  → that one (if still open)\n    //  - single in-flight → that one\n    //  - otherwise        → skip; do NOT flag unrelated concurrent ops.\n    let targetCallId: string | undefined;\n    let targetOp: OperationState | undefined;\n    if (eventCallId) {\n      const op = this.operationByCallId.get(eventCallId);\n      if (op) {\n        targetCallId = eventCallId;\n        targetOp = op;\n      }\n    } else if (this.operationByCallId.size === 1) {\n      const [k, op] = this.operationByCallId.entries().next().value!;\n      targetCallId = k;\n      targetOp = op;\n    }\n    if (!targetOp || !targetCallId) return;\n\n    targetOp.span.recordException(err);\n    targetOp.span.setStatus({\n      code: SpanStatusCode.ERROR,\n      message: err.message,\n    });\n\n    // End child spans + the operation span tied to this callId so we don't\n    // leak if `onError` is terminal (no subsequent `onFinish`). If `onFinish`\n    // does fire afterwards, its `operationByCallId.get(callId)` returns\n    // undefined and it early-returns.\n    this.closeOperation(targetCallId, targetOp);\n  };\n\n  onAbort = (event: any): void => {\n    // Fired when a streaming text generation is aborted (its AbortSignal\n    // fired) before it could finish — so onEnd never arrives and the\n    // operation + child spans would otherwise leak. An abort is a deliberate\n    // cancellation, NOT a failure: the event carries `{ callId, steps,\n    // reason? }` with no error/finishReason, so we leave span status UNSET\n    // (neither OK nor ERROR) and just record an abort marker.\n    const callId: string | undefined = event?.callId;\n    if (!callId) return;\n    const op = this.operationByCallId.get(callId);\n    if (!op) return;\n\n    op.span.setAttribute(\"ai.response.aborted\", true);\n    op.span.addEvent(\"abort\");\n    // The AbortSignal reason is free-form (often a DOMException or string).\n    // Record it as an attribute when present so the cancellation cause is\n    // visible without implying an error status.\n    if (event?.reason !== undefined) {\n      const reason = event.reason;\n      const reasonStr =\n        reason instanceof Error\n          ? reason.message\n          : typeof reason === \"string\"\n            ? reason\n            : serializeJSON(reason);\n      if (reasonStr.length > 0) {\n        op.span.setAttribute(\"ai.response.abortReason\", reasonStr);\n      }\n    }\n\n    // Close orphan child spans (llm / step / tool — flushing any buffered\n    // stream deltas) BEFORE the operation span so children never end after\n    // their parent, then clamp the op endTime to the latest child endTime.\n    this.closeOperation(callId, op);\n  };\n\n  // ------------------------------------------------------------------\n  // helpers\n  // ------------------------------------------------------------------\n\n  /** End child spans, end the operation span, and clean up both maps. */\n  private closeOperation(callId: string, op: OperationState): void {\n    const latestChildEnd = this.endOrphanChildSpansForCallId(callId);\n    op.span.end(latestChildEnd);\n    this.operationByCallId.delete(callId);\n    this.activeStreamStepByCallId.delete(callId);\n  }\n\n  /** Latest (highest-stepNumber) open step for a given callId. */\n  private findLatestStep(callId: string): StepState | undefined {\n    let best: StepState | undefined;\n    const prefix = `${callId}:`;\n    for (const [key, step] of this.stepByKey) {\n      if (!key.startsWith(prefix)) continue;\n      if (!best || step.stepNumber > best.stepNumber) best = step;\n    }\n    return best;\n  }\n\n  /**\n   * End any still-open child spans owned by `callId` so the parent operation\n   * span always has the latest endTime in its subtree — a degenerate provider\n   * that skipped lang-model-call-end / step-finish / tool-end would otherwise\n   * leave children ending after the operation and break trace hierarchy\n   * semantics. Callers MUST invoke this BEFORE ending the operation span.\n   *\n   * Sweep order is llm + tool (leaves under step) → step. Tool spans are\n   * children of step spans (see `onToolExecutionStart` where\n   * `parentCtx = step?.ctx ?? op.ctx`), so step must end AFTER tool.\n   *\n   * Returns the latest endTime observed across ended children, or undefined\n   * if no child was ended. Callers use this to clamp the operation span's\n   * endTime so it is guaranteed ≥ every child's endTime — the default\n   * `span.end()` reads a fresh hrtime each call, and four rapid synchronous\n   * ends can land within the same sub-microsecond tick where the hrtime\n   * source is not strictly monotonic across consecutive readings, making the\n   * resulting ordering flaky.\n   */\n  private endOrphanChildSpansForCallId(callId: string): HrTime | undefined {\n    const prefix = `${callId}:`;\n    let latest: HrTime | undefined;\n    const bump = (endTime: HrTime | undefined): void => {\n      if (!endTime) return;\n      if (!latest || compareHrTime(endTime, latest) > 0) latest = endTime;\n    };\n    for (const [key, llm] of this.llmByKey) {\n      if (key.startsWith(prefix)) {\n        // Flush any buffered stream deltas as the text output before force-\n        // closing. This is the only place the buffered-deltas fallback is\n        // consumed for aborted / errored streams where onLanguageModelCallEnd\n        // never fired (see onChunk). Use the same verbatim\n        // gen_ai.output.messages shape as onStepFinish /\n        // onLanguageModelCallEnd so partial output still renders and the\n        // debugger can replay it.\n        if (this.recordOutputs && llm.textDeltas.length > 0) {\n          const outputMessages = buildTextOutputMessages(\n            llm.textDeltas.join(\"\"),\n          );\n          if (outputMessages) {\n            llm.span.setAttribute(\"gen_ai.output.messages\", outputMessages);\n          }\n        }\n        llm.span.end();\n        removeActiveLlmSpan(llm.span);\n        bump(readSpanEndTime(llm.span));\n      }\n    }\n    for (const tool of this.toolByCallId.values()) {\n      if (tool.callId === callId) {\n        tool.span.end();\n        bump(readSpanEndTime(tool.span));\n      }\n    }\n    // Steps are ancestors of the already-ended llm / tool spans — clamp each\n    // step's endTime to be ≥ the latest child endTime observed so far, so the\n    // \"step ends after its tool/llm children\" invariant holds deterministically\n    // even when the underlying hrtime source has sub-microsecond collisions\n    // across the rapid synchronous `end()` chain.\n    for (const [key, step] of this.stepByKey) {\n      if (key.startsWith(prefix)) {\n        step.span.end(latest);\n        bump(readSpanEndTime(step.span));\n      }\n    }\n    // Clean up maps only after all ends have fired, so we don't lose the span\n    // references we use to read endTime.\n    for (const key of this.llmByKey.keys()) {\n      if (key.startsWith(prefix)) this.llmByKey.delete(key);\n    }\n    for (const [toolCallId, tool] of this.toolByCallId) {\n      if (tool.callId === callId) this.toolByCallId.delete(toolCallId);\n    }\n    for (const key of this.stepByKey.keys()) {\n      if (key.startsWith(prefix)) this.stepByKey.delete(key);\n    }\n    this.promptByCallId.delete(callId);\n    return latest;\n  }\n}\n\n/**\n * Returns a Laminar `Telemetry` integration instance. Pass it to\n * `experimental_telemetry.integrations` on any AI SDK v7 generate/stream/\n * embed/rerank call, or via `registerLaminarTelemetry()` for global opt-in.\n *\n * @example\n * ```ts\n * import { generateText } from \"ai\";\n * import { laminarTelemetry } from \"@lmnr-ai/lmnr\";\n *\n * await generateText({\n *   model: openai(\"gpt-4o\"),\n *   prompt: \"hi\",\n *   experimental_telemetry: {\n *     isEnabled: true,\n *     integrations: laminarTelemetry(),\n *   },\n * });\n * ```\n */\nexport const aiSdkTelemetry = (\n  options?: LaminarAiSdkTelemetryOptions,\n): LaminarAiSdkTelemetry => new LaminarAiSdkTelemetry(options);\n\n/**\n * Registers a Laminar `Telemetry` integration as a global receiver for every\n * AI SDK v7 call that has telemetry enabled.\n *\n * Mirrors `registerTelemetry(...)` from `ai` (which writes\n * `globalThis.AI_SDK_TELEMETRY_INTEGRATIONS`), but avoids a runtime import\n * of `ai` — callers often want to register telemetry before the first\n * provider call and must not pay the cost of eagerly loading the AI SDK.\n */\nexport const registerAiSdkTelemetry = (\n  options?: LaminarAiSdkTelemetryOptions,\n): LaminarAiSdkTelemetry => {\n  const integration = new LaminarAiSdkTelemetry(options);\n  const g = globalThis as unknown as {\n    AI_SDK_TELEMETRY_INTEGRATIONS?: unknown[];\n  };\n  if (!Array.isArray(g.AI_SDK_TELEMETRY_INTEGRATIONS)) {\n    g.AI_SDK_TELEMETRY_INTEGRATIONS = [];\n  }\n  g.AI_SDK_TELEMETRY_INTEGRATIONS.push(integration);\n  return integration;\n};\n\n/**\n * Subscribes a pino-style logger to AI SDK v7's `diagnostics_channel`, which\n * fires every lifecycle event as `{ type, event }`. Use this for debugging\n * why a span didn't appear or what attributes are on the wire.\n *\n * Returns an unsubscribe function.\n */\nexport const enableAiSdkTelemetryDebug = (\n  log: (entry: { type: string; event: unknown }) => void = (e) =>\n    console.log(\"[aisdk:telemetry]\", e.type, e.event),\n): (() => void) => {\n  const channel = diagnosticsChannel.channel(\n    AI_SDK_TELEMETRY_DIAGNOSTIC_CHANNEL,\n  );\n  const handler = (message: unknown) =>\n    log(message as { type: string; event: unknown });\n  channel.subscribe(handler);\n  return () => channel.unsubscribe(handler);\n};\n","// Narrow structural types for Mastra's observability contract. Declared\n// locally to avoid a hard runtime/peer dep on @mastra/core. Also includes\n// the slice of AI SDK message shape we serialize into `ai.prompt.messages`.\n\nexport type LaminarSpanType = \"LLM\" | \"TOOL\" | \"DEFAULT\";\n\n// Mirror of the subset of `@mastra/core`'s `SpanType` enum we care about.\n// Declared locally so the exporter has no peer dep on Mastra. Mastra may\n// emit other span types we don't branch on — `MastraExportedSpan.type` stays\n// `string` to keep forward-compat, but every comparison in the exporter\n// should use this constant so the set of consumed types is centralized.\n//\n// Defined as a `const` object (not a TS `enum`) so equality checks against\n// `MastraExportedSpan.type: string` don't trip `no-unsafe-enum-comparison`.\nexport const MastraSpanType = {\n  MODEL_GENERATION: \"model_generation\",\n  MODEL_STEP: \"model_step\",\n  MODEL_CHUNK: \"model_chunk\",\n  TOOL_CALL: \"tool_call\",\n  MCP_TOOL_CALL: \"mcp_tool_call\",\n} as const;\nexport type MastraSpanType =\n  (typeof MastraSpanType)[keyof typeof MastraSpanType];\n\nexport interface MastraUsageStats {\n  inputTokens?: number;\n  outputTokens?: number;\n  inputDetails?: {\n    cacheRead?: number;\n    cacheWrite?: number;\n  };\n  outputDetails?: {\n    reasoning?: number;\n  };\n}\n\nexport interface MastraSpanErrorInfo {\n  message: string;\n  name?: string;\n  stack?: string;\n  details?: Record<string, unknown>;\n}\n\nexport interface MastraExportedSpan {\n  id: string;\n  traceId: string;\n  parentSpanId?: string;\n  name: string;\n  type: string;\n  startTime: Date;\n  endTime?: Date;\n  attributes?: Record<string, any>;\n  metadata?: Record<string, any>;\n  tags?: string[];\n  input?: unknown;\n  output?: unknown;\n  errorInfo?: MastraSpanErrorInfo;\n  isEvent: boolean;\n  isRootSpan: boolean;\n}\n\nexport interface MastraTracingEvent {\n  type: \"span_started\" | \"span_updated\" | \"span_ended\";\n  exportedSpan: MastraExportedSpan;\n}\n\nexport interface MastraExporterOptions {\n  /**\n   * Flush the underlying span processor after every span end. Useful for\n   * short-lived processes that exit before the batch processor would drain\n   * on its own.\n   */\n  realtime?: boolean;\n  /**\n   * When true (default), reparent Mastra traces under the caller's active\n   * OpenTelemetry span if one exists. This lets `observe()`-wrapped code that\n   * calls a Mastra agent produce a single unified trace instead of two\n   * disconnected ones (user's OTel trace + Mastra's own trace).\n   *\n   * Mastra does not propagate OTel context into its event bus, so without\n   * this we'd emit under Mastra's self-assigned trace id with no parent.\n   * Set to false to preserve Mastra's original trace id even when nested\n   * inside `observe()`.\n   */\n  linkToActiveContext?: boolean;\n}\n\nexport interface AISdkContentPart {\n  type: string;\n  text?: string;\n  toolCallId?: string;\n  toolName?: string;\n  input?: unknown;\n  output?: unknown;\n}\n\nexport interface AISdkMessage {\n  role: string;\n  content: string | AISdkContentPart[];\n  tool_call_id?: string;\n}\n","import { HrTime } from \"@opentelemetry/api\";\n\nimport { LaminarAttributes } from \"../../tracing/attributes\";\nimport {\n  AISdkContentPart,\n  AISdkMessage,\n  LaminarSpanType,\n  MastraExportedSpan,\n  MastraSpanType,\n  MastraUsageStats,\n} from \"./types\";\n\nexport const dateToHrTime = (date: Date): HrTime => {\n  const ms = date.getTime();\n  const seconds = Math.floor(ms / 1e3);\n  const nanoseconds = (ms % 1e3) * 1e6;\n  return [seconds, nanoseconds];\n};\n\nexport const normalizeProvider = (provider: string): string =>\n  provider.split(\".\").shift()?.toLowerCase().trim() ||\n  provider.toLowerCase().trim();\n\n// `model_step` is Laminar's atomic LLM call. `model_generation` wraps the\n// whole agent-to-LLM flow (which may include multiple steps + tool calls),\n// so it stays DEFAULT.\nexport const mapLaminarSpanType = (spanType: string): LaminarSpanType => {\n  switch (spanType) {\n    case MastraSpanType.MODEL_STEP:\n      return \"LLM\";\n    case MastraSpanType.TOOL_CALL:\n    case MastraSpanType.MCP_TOOL_CALL:\n      return \"TOOL\";\n    default:\n      return \"DEFAULT\";\n  }\n};\n\nexport const serializeJSON = (value: unknown): string => {\n  if (typeof value === \"string\") return value;\n  try {\n    return JSON.stringify(value);\n  } catch {\n    return \"[unserializable]\";\n  }\n};\n\ntype AttrPrimitive = string | number | boolean;\nexport const toAttributeValue = (\n  value: unknown,\n): AttrPrimitive | AttrPrimitive[] | undefined => {\n  if (value === undefined || value === null) return undefined;\n  if (\n    typeof value === \"string\" ||\n    typeof value === \"number\" ||\n    typeof value === \"boolean\"\n  ) {\n    return value;\n  }\n  if (Array.isArray(value)) {\n    if (value.every((v) => typeof v === \"string\")) return value;\n    if (value.every((v) => typeof v === \"number\")) return value;\n    if (value.every((v) => typeof v === \"boolean\")) return value;\n  }\n  return serializeJSON(value);\n};\n\nexport const extractMessages = (input: unknown): unknown[] | undefined => {\n  if (!input) return undefined;\n  if (Array.isArray(input)) return input as unknown[];\n  if (typeof input === \"object\") {\n    const asObj = input as Record<string, unknown>;\n    if (Array.isArray(asObj.messages)) return asObj.messages as unknown[];\n    if (Array.isArray(asObj.prompt)) return asObj.prompt as unknown[];\n    if (Array.isArray(asObj.input)) return asObj.input as unknown[];\n  }\n  return undefined;\n};\n\n// `MODEL_GENERATION.input` is the messages array the user passed into\n// `agent.generate(...)`, forwarded by Mastra to the AI SDK unchanged. It's\n// already in AI SDK shape by construction — the AI SDK would have rejected\n// it before observability fired otherwise. Just coerce non-object items to\n// a string user message so `ai.prompt.messages` always serializes as a\n// well-formed message list.\nexport const normalizeInputMessages = (raw: unknown[]): AISdkMessage[] => {\n  const out: AISdkMessage[] = [];\n  for (const m of raw) {\n    if (m == null) continue;\n    if (typeof m === \"object\") {\n      out.push(m as AISdkMessage);\n      continue;\n    }\n    out.push({\n      role: \"user\",\n      content: typeof m === \"string\" ? m : serializeJSON(m),\n    });\n  }\n  return out;\n};\n\n// Synthesizes the assistant turn cached on the surrounding MODEL_GENERATION\n// and replayed in the next step's `ai.prompt.messages`. Reasoning text is\n// intentionally omitted — providers don't re-send it in subsequent turns.\nexport const buildAssistantMessageFromStepOutput = (\n  output: unknown,\n): AISdkMessage | null => {\n  if (!output || typeof output !== \"object\") return null;\n  const outObj = output as Record<string, unknown>;\n  const parts: AISdkContentPart[] = [];\n  if (typeof outObj.text === \"string\" && outObj.text.length > 0) {\n    parts.push({ type: \"text\", text: outObj.text });\n  }\n  if (Array.isArray(outObj.toolCalls)) {\n    for (const tc of outObj.toolCalls as Array<Record<string, unknown>>) {\n      if (!tc) continue;\n      parts.push({\n        type: \"tool-call\",\n        toolCallId: tc.toolCallId as string | undefined,\n        toolName: tc.toolName as string | undefined,\n        // `args` is the legacy AI SDK v4 name, `input` is v5+; keep both\n        // until we drop v4 support.\n        input: tc.input ?? tc.args,\n      });\n    }\n  }\n  if (parts.length === 0) return null;\n  return { role: \"assistant\", content: parts };\n};\n\nexport const extractToolCallId = (\n  span: MastraExportedSpan,\n): string | undefined => {\n  const v = span.attributes?.toolCallId;\n  return typeof v === \"string\" ? v : undefined;\n};\n\n// Mastra names tool spans like `tool: 'myToolId'` or, for MCP tools,\n// `mcp_tool: 'toolId' on 'serverName'` (see @mastra/core buildSpanName).\n// Strip that prefix + quotes (and the trailing ` on '<server>'` for MCP) so\n// both the TOOL span's `ai.toolCall.name` and the tool-result message's\n// `toolName` agree on the raw tool id.\nexport const cleanMastraToolName = (\n  name: string | undefined,\n): string | undefined =>\n  name?.replace(/^(?:mcp_tool|tool):\\s*'?(.*?)'?(?:\\s+on\\s+'[^']*')?$/, \"$1\");\n\n// Tool-call args are sometimes a string (already-serialized JSON), sometimes\n// an object — stringify the latter so `ai.response.toolCalls` is always a\n// JSON-string at the AI SDK boundary. Mirror `serializeJSON`'s guard so\n// unserializable inputs (BigInt, circular refs) degrade the arg payload\n// rather than bubbling up and causing the caller's outer catch to drop the\n// whole LLM span.\nexport const stringifyArgs = (raw: unknown): string | undefined => {\n  if (raw === undefined) return undefined;\n  if (typeof raw === \"string\") return raw;\n  try {\n    return JSON.stringify(raw);\n  } catch {\n    return \"[unserializable]\";\n  }\n};\n\nexport const formatUsage = (\n  usage?: MastraUsageStats,\n): Record<string, number> => {\n  if (!usage) return {};\n  const out: Record<string, number> = {};\n  if (typeof usage.inputTokens === \"number\") {\n    out[LaminarAttributes.INPUT_TOKEN_COUNT] = usage.inputTokens;\n  }\n  if (typeof usage.outputTokens === \"number\") {\n    out[LaminarAttributes.OUTPUT_TOKEN_COUNT] = usage.outputTokens;\n  }\n  const total = (usage.inputTokens ?? 0) + (usage.outputTokens ?? 0);\n  if (total > 0) {\n    out[LaminarAttributes.TOTAL_TOKEN_COUNT] = total;\n  }\n  if (typeof usage.inputDetails?.cacheWrite === \"number\") {\n    out[\"gen_ai.usage.cache_creation_input_tokens\"] =\n      usage.inputDetails.cacheWrite;\n  }\n  if (typeof usage.inputDetails?.cacheRead === \"number\") {\n    out[\"gen_ai.usage.cache_read_input_tokens\"] = usage.inputDetails.cacheRead;\n  }\n  if (typeof usage.outputDetails?.reasoning === \"number\") {\n    out[\"gen_ai.usage.reasoning_tokens\"] = usage.outputDetails.reasoning;\n  }\n  return out;\n};\n","import { errorMessage } from \"@lmnr-ai/types\";\nimport {\n  Context,\n  context as contextApi,\n  Span,\n  SpanContext,\n  SpanKind,\n  SpanStatusCode,\n  TraceFlags,\n  trace,\n} from \"@opentelemetry/api\";\n\nimport { version as SDK_VERSION } from \"../../../../package.json\";\nimport {\n  initializeLogger,\n  normalizeOtelSpanId,\n  normalizeOtelTraceId,\n  otelSpanIdToUUID,\n} from \"../../../utils\";\nimport { getLangVersion } from \"../../../version\";\nimport {\n  ASSOCIATION_PROPERTIES,\n  LaminarAttributes,\n  SESSION_ID,\n  SPAN_IDS_PATH,\n  SPAN_INPUT,\n  SPAN_INSTRUMENTATION_SOURCE,\n  SPAN_LANGUAGE_VERSION,\n  SPAN_OUTPUT,\n  SPAN_PATH,\n  SPAN_SDK_VERSION,\n  SPAN_TYPE,\n  USER_ID,\n} from \"../../tracing/attributes\";\nimport { LaminarContextManager } from \"../../tracing/context\";\nimport { getSpanProcessor, getTracerProvider } from \"../../tracing/index\";\nimport {\n  AISdkMessage,\n  MastraExportedSpan,\n  MastraExporterOptions,\n  MastraSpanType,\n  MastraTracingEvent,\n  MastraUsageStats,\n} from \"./types\";\nimport {\n  buildAssistantMessageFromStepOutput,\n  cleanMastraToolName,\n  dateToHrTime,\n  extractMessages,\n  extractToolCallId,\n  formatUsage,\n  mapLaminarSpanType,\n  normalizeInputMessages,\n  normalizeProvider,\n  serializeJSON,\n  stringifyArgs,\n  toAttributeValue,\n} from \"./utils\";\n\nconst logger = initializeLogger();\n\ninterface TraceState {\n  spanPathById: Map<string, string[]>;\n  spanIdsPathById: Map<string, string[]>;\n  activeSpanIds: Set<string>;\n  // When the first event for this Mastra trace arrived inside an active OTel\n  // span (e.g. a user's `observe()` wrapper), we rewrite outgoing spans onto\n  // that OTel trace so the whole thing renders as a single trace. Stored\n  // once, at first-event time, and reused for every span in the trace.\n  otelTraceId?: string;\n  otelRootParentSpanId?: string;\n  // Outer span's SPAN_PATH / SPAN_IDS_PATH, captured from the active\n  // LaminarSpan's attributes at first-event time. Prepended to every Mastra\n  // span's path so Laminar's UI (which builds its hierarchy from\n  // `lmnr.span.ids_path`, NOT OTel parent-span relationships) renders the\n  // Mastra subtree nested under the outer `observe()` span rather than as a\n  // sibling on the same trace.\n  otelParentSpanPath?: string[];\n  otelParentSpanIdsPath?: string[];\n}\n\ninterface ToolCallChild {\n  // Tool-call identifier extracted from the tool_call span (attributes/input)\n  // when available. Used to pair results with the step's declared toolCalls\n  // by id — necessary when tools execute in parallel and finish out of\n  // declaration order. Falls back to arrival-order pairing when absent.\n  toolCallId?: string;\n  toolName: string;\n  input: unknown;\n  output: unknown;\n}\n\ninterface GenerationState {\n  // Messages as originally passed into the generation (system + user).\n  baseMessages: AISdkMessage[];\n  // Per-step conversation turn (assistant message + tool-result messages).\n  // Assembled at step-end, keyed by stepIndex so we can replay history for\n  // step N as [baseMessages, ...turns in order].\n  turnsByStepIndex: Map<number, AISdkMessage[]>;\n  // Ordered tool_call children per step — collected as they end (always\n  // before their parent MODEL_STEP ends) so we can pair them by arrival\n  // order with the step's declared `toolCalls` when the step itself ends.\n  toolCallChildrenByStepIndex: Map<number, ToolCallChild[]>;\n  // Accumulated reasoning text per step, built up from MODEL_CHUNK children\n  // with `chunkType: \"reasoning\"`. Mastra drops reasoning from\n  // `MODEL_STEP.output`/`attributes` entirely (see `#endStepSpan` in\n  // `@mastra/observability/dist/index.js`), and `MODEL_GENERATION.output`\n  // only carries a flat cross-step `reasoningText` string — neither preserves\n  // per-step boundaries. Reasoning chunks DO, and they end before the parent\n  // MODEL_STEP ends, so accumulating from them is the only way to surface\n  // thinking tokens on the step's LLM span.\n  reasoningTextByStepIndex: Map<number, string>;\n}\n\n/**\n * Bridges Mastra's ObservabilityExporter contract to Laminar's OTLP ingestion.\n *\n * Span-type mapping:\n * - `model_step` → LLM (atomic LLM call; rendered with message history).\n * - `tool_call`, `mcp_tool_call` → TOOL.\n * - `model_chunk` → dropped (per-delta, noise).\n * - everything else → DEFAULT.\n *\n * Tool-call reconstruction: Mastra's `extractStepInput` collapses prior tool\n * calls/results into empty user messages on MODEL_STEP inputs, so we\n * reconstruct the full conversation by accumulating (baseMessages → step0's\n * assistant message → tool-result message(s) → step1's assistant message →\n * …) using the parent MODEL_GENERATION's input and the children TOOL_CALL\n * spans paired by arrival order with each step's declared toolCalls.\n *\n * For LLM spans we emit `ai.prompt.messages` (stringified AI SDK messages\n * with tool-call / tool-result content parts) and `ai.response.text` +\n * `ai.response.toolCalls` so Laminar's backend parser threads them into\n * the LLM message history view.\n */\nexport class MastraExporter {\n  public readonly name = \"laminar\";\n\n  private readonly config: {\n    realtime: boolean;\n    linkToActiveContext: boolean;\n  };\n\n  private readonly traceMap: Map<string, TraceState> = new Map();\n  private readonly generationStateById: Map<string, GenerationState> =\n    new Map();\n  private readonly generationAttrsById: Map<string, Record<string, unknown>> =\n    new Map();\n  private readonly generationIdByStepId: Map<string, string> = new Map();\n  // Remember step index per step span so tool_call children can look up which\n  // step they belong to (fan-in by arrival order).\n  private readonly stepIndexBySpanId: Map<string, number> = new Map();\n  // Live OTel spans created via `tracer.startSpan` at span_started time, held\n  // until span_ended. Lookups by Mastra span id let us:\n  //   - apply attributes / status / exception on the live span at end-time;\n  //   - resolve a Mastra child's parent context to the *mutated* live span,\n  //     so the SDK threads parent linkage with our Mastra-derived ids.\n  private readonly liveOtelSpanByMastraId: Map<string, Span> = new Map();\n\n  private warnedNotInitialized = false;\n\n  constructor(options: MastraExporterOptions = {}) {\n    this.config = {\n      realtime: options.realtime ?? false,\n      linkToActiveContext: options.linkToActiveContext ?? true,\n    };\n  }\n\n  // Mastra calls `init({ config: { serviceName } })` on registration. We rely\n  // on Laminar's tracer provider (set by `Laminar.initialize()`) for span\n  // creation and export, so this is a no-op kept only for API compatibility\n  // with Mastra's exporter contract.\n  init(_options?: unknown): void {\n    /* intentional no-op */\n  }\n\n  async exportTracingEvent(event: MastraTracingEvent): Promise<void> {\n    const span = event.exportedSpan;\n    // Point-in-time event spans have no start/end pair and don't map cleanly\n    // onto our span-tree model — drop them regardless of phase. The guard must\n    // cover span_ended too: otherwise an isEvent span arriving on that phase\n    // slips through to handleSpanEnded and gets exported as a real span.\n    if (span.isEvent) return;\n\n    // Always remember generation attributes so children can resolve them\n    // regardless of event ordering. Merge (not overwrite) so a span_updated\n    // event carrying only a delta (e.g. just `usage`) can't clobber keys\n    // set earlier at span_started (e.g. `provider`, `model`). MODEL_STEP\n    // children end before MODEL_GENERATION's span_ended restores the full\n    // set, so applyLlmAttributes would otherwise read a partial snapshot.\n    if (span.type === MastraSpanType.MODEL_GENERATION && span.attributes) {\n      const existing = this.generationAttrsById.get(span.id);\n      // Always spread into a fresh object (even on first insert): Mastra\n      // owns `span.attributes` and could reuse or mutate it between events,\n      // which would silently corrupt the stored snapshot children read at\n      // `applyLlmAttributes` time.\n      this.generationAttrsById.set(\n        span.id,\n        existing ? { ...existing, ...span.attributes } : { ...span.attributes },\n      );\n    }\n\n    if (event.type === \"span_started\") {\n      this.handleSpanStarted(span);\n      return;\n    }\n    if (event.type !== \"span_ended\") return;\n    await this.handleSpanEnded(span);\n  }\n\n  async onTracingEvent(event: MastraTracingEvent): Promise<void> {\n    await this.exportTracingEvent(event);\n  }\n\n  async flush(): Promise<void> {\n    // Flush Laminar's span processor — the only pipeline our spans flow\n    // through. No-op when Laminar isn't initialized.\n    const processor = getSpanProcessor();\n    if (!processor) return;\n    try {\n      await processor.forceFlush();\n    } catch (err) {\n      logger.error(`[MastraExporter] forceFlush failed: ${errorMessage(err)}`);\n    }\n  }\n\n  shutdown(): Promise<void> {\n    // Don't tear down Laminar's pipeline here — it may still be needed by\n    // other instrumentations. Just drop our per-trace bookkeeping.\n    this.traceMap.clear();\n    this.generationStateById.clear();\n    this.generationAttrsById.clear();\n    this.generationIdByStepId.clear();\n    this.stepIndexBySpanId.clear();\n    this.liveOtelSpanByMastraId.clear();\n    return Promise.resolve();\n  }\n\n  private handleSpanStarted(span: MastraExportedSpan): void {\n    if (span.type === MastraSpanType.MODEL_CHUNK) return;\n\n    const traceState = this.getOrCreateTraceState(span.traceId);\n    const parentId = span.parentSpanId;\n\n    this.recordSpanPath(span, traceState);\n    traceState.activeSpanIds.add(span.id);\n\n    if (span.type === MastraSpanType.MODEL_GENERATION) {\n      this.initGenerationState(span);\n    } else if (span.type === MastraSpanType.MODEL_STEP && parentId) {\n      this.generationIdByStepId.set(span.id, parentId);\n      const stepIndex =\n        typeof span.attributes?.stepIndex === \"number\"\n          ? span.attributes.stepIndex\n          : 0;\n      this.stepIndexBySpanId.set(span.id, stepIndex);\n    }\n\n    this.startOtelSpan(span, traceState);\n  }\n\n  // Build `spanPath` / `spanIdsPath` for a Mastra span and store them on the\n  // trace state. For Mastra roots we seed from the captured outer observe()\n  // path so Laminar's UI nests the subtree underneath; for Mastra descendants\n  // we reuse the parent Mastra span's stored path (already has the outer\n  // path prepended).\n  private recordSpanPath(\n    span: MastraExportedSpan,\n    traceState: TraceState,\n  ): void {\n    const parentId = span.parentSpanId;\n    const parentPath = parentId\n      ? traceState.spanPathById.get(parentId)\n      : traceState.otelParentSpanPath;\n    const parentIdsPath = parentId\n      ? traceState.spanIdsPathById.get(parentId)\n      : traceState.otelParentSpanIdsPath;\n\n    // Derive the UUID from the normalized (16-hex-char) span id so this\n    // path entry agrees with what `convertSpanToOtel` produces via\n    // `normalizeOtelSpanId` → OTel span id. Mastra occasionally emits span ids\n    // longer than 16 hex chars; passing the raw value here would truncate\n    // differently from the exported id and Laminar's UI (which threads\n    // nesting on `lmnr.span.ids_path`) would render the Mastra subtree flat.\n    const spanUuid = otelSpanIdToUUID(normalizeOtelSpanId(span.id));\n    const spanPath = parentPath ? [...parentPath, span.name] : [span.name];\n    const spanIdsPath = parentIdsPath\n      ? [...parentIdsPath, spanUuid]\n      : [spanUuid];\n\n    traceState.spanPathById.set(span.id, spanPath);\n    traceState.spanIdsPathById.set(span.id, spanIdsPath);\n  }\n\n  private async handleSpanEnded(span: MastraExportedSpan): Promise<void> {\n    if (span.type === MastraSpanType.MODEL_CHUNK) {\n      // MODEL_CHUNK spans are streaming noise as far as trace output goes\n      // (dropped below), but reasoning chunks carry the thinking text for\n      // their parent MODEL_STEP — accumulate before dropping. Mastra emits\n      // these as `attributes.chunkType: \"reasoning\"` with `output.text` =\n      // the delta text accumulated by its own chunk-span transform, and\n      // the chunk ends BEFORE its parent MODEL_STEP ends, so the reasoning\n      // is available when we build the step's LLM attributes.\n      this.captureReasoningChunk(span);\n      return;\n    }\n\n    const traceState = this.getOrCreateTraceState(span.traceId);\n\n    try {\n      // Backfill path/state when SPAN_STARTED was missed (e.g. exporter\n      // registered mid-trace, the global SDK was unrecording at start time).\n      // Inside the try so a throw here still runs cleanup.\n      if (!traceState.spanPathById.has(span.id)) {\n        this.recordSpanPath(span, traceState);\n        // Mirror handleSpanStarted: register the span as active so the\n        // finally block's `activeSpanIds.delete` is balanced.\n        traceState.activeSpanIds.add(span.id);\n      }\n      if (\n        span.type === MastraSpanType.MODEL_GENERATION &&\n        !this.generationStateById.has(span.id)\n      ) {\n        this.initGenerationState(span);\n      }\n      if (\n        span.type === MastraSpanType.MODEL_STEP &&\n        !this.generationIdByStepId.has(span.id) &&\n        span.parentSpanId\n      ) {\n        this.generationIdByStepId.set(span.id, span.parentSpanId);\n      }\n      if (!this.liveOtelSpanByMastraId.has(span.id)) {\n        // Span_ended without a prior span_started, or the SDK was a\n        // NonRecording proxy at start time and we couldn't keep a live\n        // reference. Create the live span now (zero-duration if Mastra\n        // didn't carry startTime).\n        this.startOtelSpan(span, traceState);\n      }\n\n      // Record state transitions BEFORE applying attrs; LLM attribute\n      // construction reads the accumulated step turn history.\n      this.updateGenerationStateOnSpanEnd(span);\n\n      const otelSpan = this.liveOtelSpanByMastraId.get(span.id);\n      if (!otelSpan) {\n        // `Laminar.initialize()` wasn't called, so the tracer was a noop\n        // and `startOtelSpan` couldn't keep a recording span. Skip silently\n        // — `startOtelSpan` already logged a one-time warning.\n        return;\n      }\n\n      this.applyEndAttributes(span, otelSpan, traceState);\n\n      if (span.errorInfo) {\n        otelSpan.setStatus({\n          code: SpanStatusCode.ERROR,\n          message: span.errorInfo.message,\n        });\n        otelSpan.recordException({\n          name: span.errorInfo.name ?? \"Error\",\n          message: span.errorInfo.message,\n          stack: span.errorInfo.stack,\n        });\n      }\n\n      const endTime = span.endTime\n        ? dateToHrTime(span.endTime)\n        : dateToHrTime(span.startTime);\n      otelSpan.end(endTime);\n\n      // `Span.end()` synchronously fanned out to every processor on\n      // Laminar's tracer provider. No manual onEnd push needed.\n      if (this.config.realtime) {\n        await getSpanProcessor()?.forceFlush();\n      }\n    } catch (err) {\n      logger.error(\n        `[MastraExporter] failed to export span ${span.id}: ${errorMessage(err)}`,\n      );\n    } finally {\n      traceState.activeSpanIds.delete(span.id);\n      if (traceState.activeSpanIds.size === 0) {\n        this.traceMap.delete(span.traceId);\n      }\n      if (span.type === MastraSpanType.MODEL_GENERATION) {\n        this.generationStateById.delete(span.id);\n        this.generationAttrsById.delete(span.id);\n      }\n      if (span.type === MastraSpanType.MODEL_STEP) {\n        this.generationIdByStepId.delete(span.id);\n        this.stepIndexBySpanId.delete(span.id);\n      }\n      this.liveOtelSpanByMastraId.delete(span.id);\n    }\n  }\n\n  private initGenerationState(span: MastraExportedSpan): void {\n    const rawMessages = extractMessages(span.input);\n    const baseMessages = rawMessages ? normalizeInputMessages(rawMessages) : [];\n    this.generationStateById.set(span.id, {\n      baseMessages,\n      turnsByStepIndex: new Map(),\n      toolCallChildrenByStepIndex: new Map(),\n      reasoningTextByStepIndex: new Map(),\n    });\n  }\n\n  // Accumulate reasoning text from a MODEL_CHUNK into its parent MODEL_STEP's\n  // slot on the surrounding MODEL_GENERATION. Chunks' `parentSpanId` is the\n  // step span's id, and the step span was registered in `stepIndexBySpanId` /\n  // `generationIdByStepId` at span_started, so we can resolve the slot\n  // without any extra bookkeeping.\n  //\n  // When a step produces multiple separate reasoning blocks (reasoning-start\n  // / reasoning-end fires more than once inside one step — Mastra starts a\n  // new chunk span each time), we concatenate their texts in arrival order\n  // to mirror Mastra's own `#bufferedReasoning` behavior.\n  private captureReasoningChunk(span: MastraExportedSpan): void {\n    const attrs = span.attributes ?? {};\n    if (attrs.chunkType !== \"reasoning\") return;\n    const output = span.output;\n    if (!output || typeof output !== \"object\") return;\n    const text = (output as Record<string, unknown>).text;\n    if (typeof text !== \"string\" || text.length === 0) return;\n\n    const stepSpanId = span.parentSpanId;\n    if (!stepSpanId) return;\n    const generationId = this.generationIdByStepId.get(stepSpanId);\n    if (!generationId) return;\n    const gen = this.generationStateById.get(generationId);\n    if (!gen) return;\n    const stepIndex = this.stepIndexBySpanId.get(stepSpanId);\n    if (stepIndex === undefined) return;\n\n    const existing = gen.reasoningTextByStepIndex.get(stepIndex);\n    gen.reasoningTextByStepIndex.set(\n      stepIndex,\n      existing ? existing + text : text,\n    );\n  }\n\n  private updateGenerationStateOnSpanEnd(span: MastraExportedSpan): void {\n    if (span.type === MastraSpanType.MODEL_STEP) {\n      const generationId = this.generationIdByStepId.get(span.id);\n      if (!generationId) return;\n      const gen = this.generationStateById.get(generationId);\n      if (!gen) return;\n      const stepIndex =\n        this.stepIndexBySpanId.get(span.id) ??\n        (typeof span.attributes?.stepIndex === \"number\"\n          ? span.attributes.stepIndex\n          : 0);\n      this.stepIndexBySpanId.set(span.id, stepIndex);\n\n      // Pair the declared `toolCalls` with tool_call children. Prefer id-based\n      // pairing when children carry a toolCallId (parallel tool execution can\n      // finish out of declaration order, so array-index pairing would\n      // mis-attribute outputs). Fall back to arrival-order pairing among\n      // unclaimed children when ids aren't available on the child spans.\n      const output = span.output as Record<string, unknown> | undefined;\n      const declaredToolCalls = Array.isArray(output?.toolCalls)\n        ? (output.toolCalls as Array<Record<string, unknown>>)\n        : [];\n      const children = gen.toolCallChildrenByStepIndex.get(stepIndex) ?? [];\n      const childrenById = new Map<string, ToolCallChild>();\n      for (const c of children) {\n        if (c.toolCallId) childrenById.set(c.toolCallId, c);\n      }\n      // Track already-paired children so the arrival-order fallback can't\n      // re-pick a child that was already claimed by an id-based match.\n      const consumed = new Set<ToolCallChild>();\n\n      const turnMessages: AISdkMessage[] = [];\n      const assistantMsg = buildAssistantMessageFromStepOutput(output);\n      if (assistantMsg) turnMessages.push(assistantMsg);\n\n      for (const dec of declaredToolCalls) {\n        const toolCallId =\n          (dec?.toolCallId as string | undefined) ??\n          (dec?.id as string | undefined);\n        // Don't skip declarations with a missing id:\n        // `buildAssistantMessageFromStepOutput` still emitted a `tool-call`\n        // part for this declaration, so we must emit a matching tool-result\n        // or subsequent steps will see a broken history (assistant calls a\n        // tool, no result follows). Fall through to arrival-order pairing in\n        // that case, using whatever id the child span carries (may be\n        // undefined).\n        let child = toolCallId ? childrenById.get(toolCallId) : undefined;\n        if (child && consumed.has(child)) child = undefined;\n        if (!child) {\n          // Fallback: first unconsumed child in arrival order.\n          child = children.find((c) => !consumed.has(c));\n        }\n        if (!child) continue;\n        consumed.add(child);\n        const resolvedToolCallId = toolCallId ?? child.toolCallId;\n        const toolName =\n          (dec?.toolName as string | undefined) ??\n          (dec?.name as string | undefined) ??\n          child.toolName;\n        turnMessages.push({\n          role: \"tool\",\n          tool_call_id: resolvedToolCallId,\n          content: [\n            {\n              type: \"tool-result\",\n              toolCallId: resolvedToolCallId,\n              toolName,\n              output: child.output,\n            },\n          ],\n        });\n      }\n\n      gen.turnsByStepIndex.set(stepIndex, turnMessages);\n    } else if (\n      span.type === MastraSpanType.TOOL_CALL ||\n      span.type === MastraSpanType.MCP_TOOL_CALL\n    ) {\n      // Record the tool_call child under its step so the step-end handler\n      // can pair it with the declared toolCalls. Tool spans always end\n      // before their parent MODEL_STEP ends, so the parent's stepIndex is\n      // still in `stepIndexBySpanId` here.\n      const parentId = span.parentSpanId;\n      if (!parentId) return;\n      const generationId = this.generationIdByStepId.get(parentId);\n      if (!generationId) return;\n      const gen = this.generationStateById.get(generationId);\n      if (!gen) return;\n      const stepIndex = this.stepIndexBySpanId.get(parentId);\n      if (stepIndex === undefined) return;\n      const list = gen.toolCallChildrenByStepIndex.get(stepIndex) ?? [];\n      list.push({\n        toolCallId: extractToolCallId(span),\n        toolName: cleanMastraToolName(span.name) || \"tool\",\n        input: span.input,\n        output: span.output,\n      });\n      gen.toolCallChildrenByStepIndex.set(stepIndex, list);\n    }\n  }\n\n  private getOrCreateTraceState(traceId: string): TraceState {\n    const existing = this.traceMap.get(traceId);\n    if (existing) return existing;\n    const created: TraceState = {\n      spanPathById: new Map(),\n      spanIdsPathById: new Map(),\n      activeSpanIds: new Set(),\n    };\n    // Capture the caller's active span synchronously, at the moment the\n    // first event for this Mastra trace arrives — Mastra invokes exporter\n    // handlers within the originating async context (see\n    // `@mastra/observability` routeToHandler), so the caller's wrapper\n    // span is still active here. Any later reads would be outside that\n    // context (Mastra's event bus schedules handlers).\n    //\n    // Two stacks to consult, in order:\n    //  1. Laminar's own context manager — the only place spans started via\n    //     `Laminar.startActiveSpan()` are tracked. That helper writes onto\n    //     a separate AsyncLocalStorage instance and never touches OTel's\n    //     standard context, so step (2) alone wouldn't see them.\n    //  2. OTel's standard active span — set by `observe()` via\n    //     `context.with(...)` and by any other OTel-aware instrumentation.\n    if (this.config?.linkToActiveContext) {\n      const activeSpan =\n        trace.getSpan(LaminarContextManager.getContext()) ??\n        trace.getActiveSpan();\n      const ctx = activeSpan?.spanContext();\n      if (ctx && ctx.traceId && ctx.spanId) {\n        created.otelTraceId = normalizeOtelTraceId(ctx.traceId);\n        created.otelRootParentSpanId = normalizeOtelSpanId(ctx.spanId);\n        // Also capture SPAN_PATH / SPAN_IDS_PATH so we can prepend them to\n        // every Mastra span's path. Laminar's backend/UI threads the span\n        // tree on `lmnr.span.ids_path` — sharing the traceId alone isn't\n        // enough to make the Mastra subtree render under `observe()`.\n        const attrs = (\n          activeSpan as unknown as { attributes?: Record<string, unknown> }\n        ).attributes;\n        if (attrs) {\n          const parentPath = attrs[SPAN_PATH];\n          if (\n            Array.isArray(parentPath) &&\n            parentPath.every((p) => typeof p === \"string\")\n          ) {\n            created.otelParentSpanPath = parentPath;\n          }\n          const parentIdsPath = attrs[SPAN_IDS_PATH];\n          if (\n            Array.isArray(parentIdsPath) &&\n            parentIdsPath.every((p) => typeof p === \"string\")\n          ) {\n            created.otelParentSpanIdsPath = parentIdsPath;\n          }\n        }\n      }\n    }\n    this.traceMap.set(traceId, created);\n    return created;\n  }\n\n  // Create a real OTel span via Laminar's tracer, then mutate its ids /\n  // parent references so they line up with Mastra's. We use a real span (not\n  // a manually-constructed ReadableSpan) so the registered LaminarSpanProcessor\n  // sees it on `onStart` and can attach association properties from the\n  // active context.\n  private startOtelSpan(\n    span: MastraExportedSpan,\n    traceState: TraceState,\n  ): void {\n    // `Laminar.initialize()` is expected to have set up the tracer provider.\n    // If it wasn't called, `getTracerProvider()` falls back to the global\n    // OTel API which is a NoopTracerProvider, and `tracer.startSpan` will\n    // return a NonRecordingSpan — caught below.\n    const tracer = getTracerProvider().getTracer(\"@lmnr-ai/lmnr\", SDK_VERSION);\n    const parentCtx = this.buildParentContext(span, traceState);\n\n    const otelSpan = tracer.startSpan(\n      span.name,\n      {\n        startTime: dateToHrTime(span.startTime),\n        kind: SpanKind.INTERNAL,\n      },\n      parentCtx,\n    );\n\n    if (!otelSpan.isRecording()) {\n      this.warnNotInitializedOnce();\n      return;\n    }\n\n    // Capture the SDK-allocated span id before we overwrite it.\n    // `LaminarSpanProcessor.onStart` already fired synchronously inside\n    // `tracer.startSpan` and keyed its `_spanIdToPath` / `_spanIdLists`\n    // entries under this id — without dropping them below, `onEnd` (which\n    // reads the post-mutation Mastra id) would delete nothing and both maps\n    // would grow unboundedly.\n    const sdkAllocatedSpanId = otelSpan.spanContext().spanId;\n\n    // Stamp Mastra-derived ids over the SDK's auto-generated ones. Mutates\n    // the SpanContext object the SDK holds internally — `spanContext()`\n    // returns the same reference each call.\n    const mastraSpanId = normalizeOtelSpanId(span.id);\n    const mastraTraceId =\n      traceState.otelTraceId ?? normalizeOtelTraceId(span.traceId);\n    Object.assign(otelSpan.spanContext(), {\n      traceId: mastraTraceId,\n      spanId: mastraSpanId,\n    });\n\n    // Drop the orphaned path entry the processor cached under the original\n    // SDK-allocated id. Safe no-op if the id happened to match the Mastra id\n    // (unlikely but possible).\n    if (sdkAllocatedSpanId !== mastraSpanId) {\n      getSpanProcessor()?.dropPathInfo(sdkAllocatedSpanId);\n    }\n\n    // Patch parent references. We set both `parentSpanContext` (SDK v2) and\n    // `parentSpanId` (SDK v1 alias) so this works across SDK versions.\n    const parentSpanIdNormalized = span.parentSpanId\n      ? normalizeOtelSpanId(span.parentSpanId)\n      : traceState.otelRootParentSpanId;\n    if (parentSpanIdNormalized) {\n      const parentSpanContext: SpanContext = {\n        traceId: mastraTraceId,\n        spanId: parentSpanIdNormalized,\n        traceFlags: TraceFlags.SAMPLED,\n        isRemote: false,\n      };\n      Object.assign(otelSpan, {\n        parentSpanId: parentSpanIdNormalized,\n        parentSpanContext,\n      });\n    } else {\n      // Mastra root with no captured outer span — clear whatever parent the\n      // SDK inferred from `parentCtx` so the exported span reads as a root.\n      Object.assign(otelSpan, {\n        parentSpanId: undefined,\n        parentSpanContext: undefined,\n      });\n    }\n\n    // Globally-registered processors (e.g. LaminarSpanProcessor) wrote\n    // `lmnr.span.path` / `lmnr.span.ids_path` during their `onStart` hook\n    // using the SDK's auto-generated span id — overwrite with our\n    // Mastra-derived versions so Laminar's UI nests the subtree correctly.\n    const spanPath = traceState.spanPathById.get(span.id);\n    const spanIdsPath = traceState.spanIdsPathById.get(span.id);\n    if (spanPath) otelSpan.setAttribute(SPAN_PATH, spanPath);\n    if (spanIdsPath) otelSpan.setAttribute(SPAN_IDS_PATH, spanIdsPath);\n\n    this.liveOtelSpanByMastraId.set(span.id, otelSpan);\n  }\n\n  private warnNotInitializedOnce(): void {\n    if (this.warnedNotInitialized) return;\n    this.warnedNotInitialized = true;\n    logger.warn(\n      \"[MastraExporter] Laminar tracer is not initialized — Mastra spans \" +\n        \"will be dropped. Call `Laminar.initialize({ projectApiKey: ... })` \" +\n        \"before constructing `MastraExporter`.\",\n    );\n  }\n\n  // Pick the OTel context whose active span will become the new Mastra\n  // span's parent. Resolution order:\n  //   1. Mastra child? Use the *live* (mutated) parent span we already\n  //      created — its spanContext exposes the Mastra-derived parent ids.\n  //   2. Mastra root? Use the outer `observe()` / `Laminar.startActiveSpan()`\n  //      span captured at first-event time (if linking is enabled).\n  //   3. Otherwise the bare context (Laminar's first, OTel's as fallback).\n  private buildParentContext(\n    span: MastraExportedSpan,\n    traceState: TraceState,\n  ): Context {\n    const baseCtx = LaminarContextManager.getContext() ?? contextApi.active();\n\n    if (span.parentSpanId) {\n      const parentLive = this.liveOtelSpanByMastraId.get(span.parentSpanId);\n      if (parentLive) return trace.setSpan(baseCtx, parentLive);\n    }\n\n    if (traceState.otelTraceId && traceState.otelRootParentSpanId) {\n      const wrapped = trace.wrapSpanContext({\n        traceId: traceState.otelTraceId,\n        spanId: traceState.otelRootParentSpanId,\n        traceFlags: TraceFlags.SAMPLED,\n        isRemote: false,\n      });\n      return trace.setSpan(baseCtx, wrapped);\n    }\n\n    return baseCtx;\n  }\n\n  private applyEndAttributes(\n    span: MastraExportedSpan,\n    otelSpan: Span,\n    traceState: TraceState,\n  ): void {\n    const attributes = this.buildLaminarAttributes(span, traceState);\n    // Path attrs were already written in `startOtelSpan`. Skip them on the\n    // bulk re-apply both to avoid pointless setAttribute churn and to keep\n    // the path values stable if some upstream processor mutated them.\n    delete attributes[SPAN_PATH];\n    delete attributes[SPAN_IDS_PATH];\n    otelSpan.setAttributes(attributes);\n  }\n\n  private buildLaminarAttributes(\n    span: MastraExportedSpan,\n    traceState: TraceState,\n  ): Record<string, any> {\n    const attributes: Record<string, any> = {};\n\n    const spanPath = traceState.spanPathById.get(span.id);\n    const spanIdsPath = traceState.spanIdsPathById.get(span.id);\n    if (spanPath) attributes[SPAN_PATH] = spanPath;\n    if (spanIdsPath) attributes[SPAN_IDS_PATH] = spanIdsPath;\n\n    const laminarSpanType = mapLaminarSpanType(span.type);\n    attributes[SPAN_TYPE] = laminarSpanType;\n    attributes[SPAN_INSTRUMENTATION_SOURCE] = \"javascript\";\n    attributes[SPAN_SDK_VERSION] = SDK_VERSION;\n    const langVersion = getLangVersion();\n    if (langVersion) attributes[SPAN_LANGUAGE_VERSION] = langVersion;\n\n    // Preserve the original Mastra span type so e.g. agent_run vs\n    // model_generation (both DEFAULT) can be told apart downstream.\n    attributes[\"lmnr.internal.mastra.span_type\"] = span.type;\n\n    const metadata = span.metadata ?? {};\n    const sessionId = metadata.sessionId ?? metadata.session_id;\n    if (typeof sessionId === \"string\" && sessionId.length > 0) {\n      attributes[SESSION_ID] = sessionId;\n    }\n    const userId = metadata.userId ?? metadata.user_id;\n    if (typeof userId === \"string\" && userId.length > 0) {\n      attributes[USER_ID] = userId;\n    }\n    for (const [key, value] of Object.entries(metadata)) {\n      if (\n        key === \"sessionId\" ||\n        key === \"session_id\" ||\n        key === \"userId\" ||\n        key === \"user_id\" ||\n        value === undefined ||\n        value === null\n      ) {\n        continue;\n      }\n      const av = toAttributeValue(value);\n      if (av !== undefined) {\n        attributes[`${ASSOCIATION_PROPERTIES}.metadata.${key}`] = av;\n      }\n    }\n    if (span.isRootSpan && span.tags?.length) {\n      attributes[`${ASSOCIATION_PROPERTIES}.tags`] = span.tags;\n    }\n\n    if (laminarSpanType === \"LLM\") {\n      this.applyLlmAttributes(span, attributes);\n    } else if (laminarSpanType === \"TOOL\") {\n      this.applyToolAttributes(span, attributes);\n    } else {\n      if (span.input !== undefined) {\n        attributes[SPAN_INPUT] = serializeJSON(span.input);\n      }\n      if (span.output !== undefined) {\n        attributes[SPAN_OUTPUT] = serializeJSON(span.output);\n      }\n    }\n\n    return attributes;\n  }\n\n  private applyLlmAttributes(\n    span: MastraExportedSpan,\n    attributes: Record<string, any>,\n  ): void {\n    const generationId =\n      this.generationIdByStepId.get(span.id) ?? span.parentSpanId;\n    const gen = generationId\n      ? this.generationStateById.get(generationId)\n      : undefined;\n    const generationAttrs = generationId\n      ? this.generationAttrsById.get(generationId)\n      : undefined;\n\n    const stepAttrs = span.attributes ?? {};\n    const stepIndex =\n      this.stepIndexBySpanId.get(span.id) ??\n      (typeof stepAttrs.stepIndex === \"number\" ? stepAttrs.stepIndex : 0);\n\n    const provider = generationAttrs?.provider as string | undefined;\n    const model = generationAttrs?.model as string | undefined;\n    const responseModel = generationAttrs?.responseModel as string | undefined;\n    if (provider)\n      attributes[LaminarAttributes.PROVIDER] = normalizeProvider(provider);\n    if (model) attributes[LaminarAttributes.REQUEST_MODEL] = model;\n    if (responseModel)\n      attributes[LaminarAttributes.RESPONSE_MODEL] = responseModel;\n    else if (model) attributes[LaminarAttributes.RESPONSE_MODEL] = model;\n\n    const usage = (stepAttrs.usage ?? generationAttrs?.usage) as\n      | MastraUsageStats\n      | undefined;\n    Object.assign(attributes, formatUsage(usage));\n\n    if (typeof stepAttrs.finishReason === \"string\") {\n      attributes[\"gen_ai.response.finish_reason\"] = stepAttrs.finishReason;\n      attributes[\"ai.response.finishReason\"] = stepAttrs.finishReason;\n    }\n\n    // Build the full message history for this step: base + every turn with\n    // stepIndex < current stepIndex, flattened.\n    const messages: AISdkMessage[] = gen ? [...gen.baseMessages] : [];\n    if (gen) {\n      for (let i = 0; i < stepIndex; i++) {\n        const turn = gen.turnsByStepIndex.get(i);\n        if (turn) messages.push(...turn);\n      }\n    }\n\n    if (messages.length > 0) {\n      attributes[\"ai.prompt.messages\"] = serializeJSON(messages);\n    } else if (span.input !== undefined) {\n      attributes[SPAN_INPUT] = serializeJSON(span.input);\n    }\n\n    const out = span.output;\n    const reasoningText = gen?.reasoningTextByStepIndex.get(stepIndex);\n    if (out && typeof out === \"object\") {\n      const outObj = out as Record<string, unknown>;\n      if (typeof outObj.text === \"string\" && outObj.text.length > 0) {\n        attributes[\"ai.response.text\"] = outObj.text;\n      }\n      const normalizedToolCalls =\n        Array.isArray(outObj.toolCalls) && outObj.toolCalls.length > 0\n          ? (outObj.toolCalls as Array<Record<string, unknown>>).map((tc) => ({\n              toolCallType: tc.toolCallType ?? \"function\",\n              toolCallId: tc.toolCallId,\n              toolName: tc.toolName,\n              args: stringifyArgs(tc.args ?? tc.input),\n            }))\n          : [];\n      if (normalizedToolCalls.length > 0) {\n        attributes[\"ai.response.toolCalls\"] =\n          JSON.stringify(normalizedToolCalls);\n      }\n      // Emit OTel GenAI semconv `gen_ai.output.messages` with a `thinking`\n      // part when this step had reasoning chunks. Laminar's backend\n      // preserves this attribute verbatim on `self.output` and the frontend\n      // GenAI parser maps `thinking` → ModelMessage `reasoning`, rendered\n      // with a \"Thinking\" label in the trace UI.\n      if (typeof reasoningText === \"string\" && reasoningText.length > 0) {\n        const parts: Array<Record<string, unknown>> = [\n          { type: \"thinking\", content: reasoningText },\n        ];\n        if (typeof outObj.text === \"string\" && outObj.text.length > 0) {\n          parts.push({ type: \"text\", content: outObj.text });\n        }\n        for (const tc of normalizedToolCalls) {\n          let argsObj: unknown = tc.args;\n          if (typeof argsObj === \"string\") {\n            try {\n              argsObj = JSON.parse(argsObj);\n            } catch {\n              // leave as string; backend still accepts it\n            }\n          }\n          parts.push({\n            type: \"tool_call\",\n            id: tc.toolCallId,\n            name: tc.toolName,\n            arguments: argsObj,\n          });\n        }\n        attributes[\"gen_ai.output.messages\"] = JSON.stringify([\n          { role: \"assistant\", parts },\n        ]);\n      }\n    } else if (out !== undefined) {\n      attributes[SPAN_OUTPUT] = serializeJSON(out);\n    }\n  }\n\n  private applyToolAttributes(\n    span: MastraExportedSpan,\n    attributes: Record<string, any>,\n  ): void {\n    if (span.input !== undefined) {\n      attributes[SPAN_INPUT] = serializeJSON(span.input);\n    }\n    if (span.output !== undefined) {\n      attributes[SPAN_OUTPUT] = serializeJSON(span.output);\n    }\n    const toolAttrs = span.attributes ?? {};\n    // Strip the `tool: 'x'` prefix Mastra prepends so the displayed name is\n    // just the tool id.\n    const cleanedName = cleanMastraToolName(span.name) || span.name;\n    if (cleanedName) attributes[\"ai.toolCall.name\"] = cleanedName;\n    if (typeof toolAttrs.toolType === \"string\") {\n      attributes[\"ai.toolCall.type\"] = toolAttrs.toolType;\n    }\n    if (typeof toolAttrs.mcpServer === \"string\") {\n      attributes[\"mcp.server\"] = toolAttrs.mcpServer;\n    }\n  }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;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