{"version":3,"sources":["../src/content/normalize.ts","../src/observability.ts","../src/budget/memory.ts","../src/errors.ts","../src/validation.ts","../src/utils/deprecation.ts","../src/registry/config.ts","../src/registry/cost-session.ts","../src/registry/registry.ts","../src/registry/tasks.ts","../src/budget/cost.ts","../src/retry.ts","../src/retry-emit.ts","../src/capabilities-learning.ts","../src/notify-learning.ts","../src/utils/wrap-provider-error.ts","../src/utils/stringify-content.ts","../src/utils/json.ts","../src/utils/usage.ts","../src/utils/repair-validation.ts","../src/utils/validate-image.ts","../src/utils/abort.ts","../src/utils/to-messages.ts","../src/utils/resolve-messages.ts","../src/observability-context.ts"],"names":["cutoff","current","spent","result"],"mappings":";;;AAUO,SAAS,gBAAgB,OAAA,EAA4C;AAC1E,EAAA,OAAO,OAAO,OAAA,KAAY,QAAA;AAC5B;AAGO,SAAS,SAAS,OAAA,EAAyC;AAChE,EAAA,IAAI,OAAO,YAAY,QAAA,EAAU;AAC/B,IAAA,OAAO,CAAC,EAAE,IAAA,EAAM,MAAA,EAAQ,IAAA,EAAM,SAAS,CAAA;AAAA,EACzC;AACA,EAAA,OAAO,OAAA;AACT;AAOO,SAAS,kBAAkB,MAAA,EAAuC;AACvE,EAAA,IAAI,MAAA,CAAO,MAAA,KAAW,CAAA,EAAG,OAAO,EAAA;AAChC,EAAA,IAAI,CAAC,OAAO,KAAA,CAAM,CAAC,MAAsB,CAAA,CAAE,IAAA,KAAS,MAAM,CAAA,EAAG,OAAO,IAAA;AACpE,EAAA,OAAO,MAAA,CAAO,IAAI,CAAC,CAAA,KAAM,EAAE,IAAI,CAAA,CAAE,KAAK,EAAE,CAAA;AAC1C;AAGO,SAAS,YAAY,OAAA,EAAiC;AAC3D,EAAA,OAAO,SAAS,OAAO,CAAA,CACpB,MAAA,CAAO,CAAC,MAAsB,CAAA,CAAE,IAAA,KAAS,MAAM,CAAA,CAC/C,IAAI,CAAC,CAAA,KAAM,EAAE,IAAI,CAAA,CACjB,KAAK,EAAE,CAAA;AACZ;;;AC2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AI,KAAA,CAAM,eAAA,KAAoB,MAAA,EAAW,MAAA,CAAO,kBAAkB,KAAA,CAAM,eAAA;AACxE,EAAA,IAAI,KAAA,CAAM,eAAA,KAAoB,MAAA,EAAW,MAAA,CAAO,kBAAkB,KAAA,CAAM,eAAA;AAExE,EAAA,IAAI,KAAA,CAAM,YAAY,MAAA,EAAW;AAC/B,IAAA,IAAI,IAAA,CAAK,YAAY,MAAA,EAAW;AAC9B,MAAA,MAAA,CAAO,OAAA,GAAU,CAAC,GAAG,KAAA,CAAM,OAAO,CAAA;AAAA,IACpC,CAAA,MAAO;AAEL,MAAA,MAAM,SAAA,GAAY,IAAI,GAAA,CAAI,KAAA,CAAM,OAAA,CAAQ,IAAI,CAAC,CAAA,KAAM,CAAA,CAAE,GAAG,CAAC,CAAA;AACzD,MAAA,MAAM,YAAA,GAAe,IAAA,CAAK,OAAA,CAAQ,MAAA,CAAO,CAAC,CAAA,KAAM,CAAC,SAAA,CAAU,GAAA,CAAI,CAAA,CAAE,GAAG,CAAC,CAAA;AACrE,MAAA,MAAA,CAAO,UAAU,CAAC,GAAG,YAAA,EAAc,GAAG,MAAM,OAAO,CAAA;AAAA,IACrD;AAAA,EACF;AAEA,EAAA,IAAI,KAAA,CAAM,eAAe,MAAA,EAAW;AAClC,IAAA,MAAA,CAAO,UAAA,GAAa,EAAE,GAAI,IAAA,CAAK,cAAc,EAAC,EAAI,GAAG,KAAA,CAAM,UAAA,EAAW;AAAA,EACxE;AAEA,EAAA,OAAO,MAAA;AACT","file":"index.mjs","sourcesContent":["/**\r\n * Helpers for normalizing between string and ContentBlock[] forms.\r\n *\r\n * Adapters use these to accept either input shape and emit the canonical\r\n * ContentBlock[] form that the rest of the system reasons about.\r\n */\r\n\r\nimport type { ContentBlock, MessageContent, TextBlock } from \"./blocks.js\";\r\n\r\n/** True if the value is the string-sugar form of MessageContent. */\r\nexport function isStringContent(content: MessageContent): content is string {\r\n  return typeof content === \"string\";\r\n}\r\n\r\n/** Convert any MessageContent to its canonical ContentBlock[] form. */\r\nexport function toBlocks(content: MessageContent): ContentBlock[] {\r\n  if (typeof content === \"string\") {\r\n    return [{ type: \"text\", text: content }];\r\n  }\r\n  return content;\r\n}\r\n\r\n/**\r\n * Collapse a ContentBlock[] to a single string if and only if every block is text.\r\n * Returns null if the content includes non-text blocks (caller must keep array form).\r\n * Useful for adapters whose underlying SDK wants `content: string` for text-only messages.\r\n */\r\nexport function tryCollapseToText(blocks: ContentBlock[]): string | null {\r\n  if (blocks.length === 0) return \"\";\r\n  if (!blocks.every((b): b is TextBlock => b.type === \"text\")) return null;\r\n  return blocks.map((b) => b.text).join(\"\");\r\n}\r\n\r\n/** Concatenate all text content from a MessageContent, ignoring non-text blocks. */\r\nexport function extractText(content: MessageContent): string {\r\n  return toBlocks(content)\r\n    .filter((b): b is TextBlock => b.type === \"text\")\r\n    .map((b) => b.text)\r\n    .join(\"\");\r\n}\r\n","/**\n * Cross-adapter observability hooks (alpha.21+).\n *\n * Five fire-and-forget hooks aligned with the OpenTelemetry `gen_ai.*`\n * semantic-conventions taxonomy so downstream pipelines (Honeycomb, Datadog,\n * OTel Collector, custom OTLP exporters) can map them onto spans + metrics\n * without re-deriving fields.\n *\n *   - onCost            : fires after every billable call with a cost breakdown\n *   - onTokenUsage      : fires after every billable call with token counts\n *   - onFallback        : fires when the Registry chain advances to the next provider\n *   - onValidationRetry : fires when retry-with-feedback round-trips on structured output\n *   - onCacheHit        : fires when the provider reports cache hits (cached_tokens > 0)\n *\n * All hooks are sync OR async, called fire-and-forget, with hook errors\n * swallowed. Same contract as the existing `OnRetry` hook (alpha.17+).\n *\n * Why these five hooks and not others?\n *\n *   - Cost and token usage answer \"what did this turn me?\" — the two most-\n *     asked-for observability signals in production LLM systems.\n *   - Fallback answers \"did my primary provider hold up?\" — the signal that\n *     drives chain reconfiguration and SLO regression alerts.\n *   - Validation retry answers \"was my schema healthy?\" — the signal that\n *     surfaces schema drift and provider degradation before cost spikes.\n *   - Cache hit answers \"did my prompt-engineering work?\" — the signal that\n *     tells you whether `cacheControl` / `prompt_cache_key` are actually firing.\n *\n * The existing `OnRetry` hook (transient-auth, capability-fallback,\n * reasoning-starvation, validation-feedback) stays as-is — it covers the\n * \"adapter decided to retry\" surface. The new hooks cover the \"Registry\n * decided to move on\" and \"call result is interesting\" surfaces, which\n * OnRetry doesn't observe.\n */\n\nimport type { ArtifactRef, TokenUsage, CostUsage } from \"./ports/llm-port.js\";\nimport type { BudgetScopeRef } from \"./budget/types.js\";\n\n/** Cause of a Registry-level fallback advancement. */\nexport type FallbackCause =\n  /** The primary provider raised an error (budget exhausted, 401, 5xx, transient). */\n  | \"provider-error\"\n  /** A budget gate (req/min, cost/day, etc.) denied the call on the primary. */\n  | \"budget-exhausted\"\n  /** Structured output validation exhausted retries; chain advances to a fallback model. */\n  | \"validation-exhausted\"\n  /** The primary returned an empty response after starvation retries gave up. */\n  | \"empty-response\"\n  /** The primary's circuit breaker is open. */\n  | \"circuit-open\";\n\n/** Trigger for `onValidationRetry`. */\nexport type ValidationRetryCause =\n  /** The model returned valid JSON that failed Zod validation. Retry with feedback. */\n  | \"schema-mismatch\"\n  /** The model returned non-JSON text. Retry with stricter prompt. */\n  | \"parse-error\";\n\n// ─── Event shapes ────────────────────────────────────────────────────\n\n/** OnCost event: per-call cost breakdown. */\nexport interface CostEvent {\n  /** USD spent on input tokens for this call. */\n  promptUsd: number;\n  /** USD spent on output tokens for this call. */\n  completionUsd: number;\n  /** USD spent on cache-read tokens (when the provider has a discounted tier). */\n  cacheReadUsd?: number;\n  /** USD spent on cache-write tokens (Anthropic-style explicit-cache providers). */\n  cacheWriteUsd?: number;\n  /** USD spent on reasoning tokens (hidden chain-of-thought billed separately). */\n  reasoningUsd?: number;\n  /** Total USD for this single call. */\n  totalUsd: number;\n  /** Model that produced the result (may differ from requested when the model serves under an alias). */\n  modelId: string;\n  /** Adapter alias used (the Registry-side name, e.g. `gptoss-cerebras`). */\n  providerAlias: string;\n  /** Operation kind. */\n  operation: \"generateText\" | \"generateStructured\" | \"streamText\" | \"streamStructured\" | \"runAgent\" | \"embed\" | \"rerank\";\n  /** Optional task-type tag from the call site. */\n  taskType?: string;\n  /** Optional scope hint passed by the caller for downstream attribution. */\n  budgetScope?: BudgetScopeRef;\n  /** Consumer-owned artifact reference tags passed on the call options; verbatim on the event. (alpha.25+) */\n  refs?: Record<string, ArtifactRef>;\n}\n\n/** OnTokenUsage event: per-call token counts (raw, before cost monetization). */\nexport interface TokenUsageEvent {\n  inputTokens: number;\n  outputTokens: number;\n  cachedInputTokens?: number;\n  cacheCreationTokens?: number;\n  reasoningTokens?: number;\n  totalTokens: number;\n  modelId: string;\n  providerAlias: string;\n  operation: CostEvent[\"operation\"];\n  taskType?: string;\n  budgetScope?: BudgetScopeRef;\n  /** Consumer-owned artifact reference tags passed on the call options; verbatim on the event. (alpha.25+) */\n  refs?: Record<string, ArtifactRef>;\n}\n\n/** OnFallback event: chain advanced to the next provider. */\nexport interface FallbackEvent {\n  /** The alias the call was originally routed to. */\n  fromAlias: string;\n  /** The alias the call was reassigned to. */\n  toAlias: string;\n  /** Why the chain advanced. */\n  cause: FallbackCause;\n  /** Operation kind. */\n  operation: CostEvent[\"operation\"];\n  /** Optional task type for grouping in observability stacks. */\n  taskType?: string;\n  /** The error or signal that triggered the advancement, when applicable. */\n  reason?: unknown;\n  /** Consumer-owned artifact reference tags passed on the call options; verbatim on the event. (alpha.25+) */\n  refs?: Record<string, ArtifactRef>;\n}\n\n/** OnValidationRetry event: retry-with-feedback round-trip on structured output. */\nexport interface ValidationRetryEvent {\n  /** 0-indexed retry number (0 = first retry after the initial call). */\n  attempt: number;\n  /** Maximum attempts the adapter is configured to make in total. */\n  maxAttempts: number;\n  modelId: string;\n  providerAlias: string;\n  /** Why this retry fired. */\n  cause: ValidationRetryCause;\n  /** Validation issues (Zod issues, parse error message, etc.). */\n  issues?: unknown;\n  /** Operation kind. */\n  operation: \"generateStructured\" | \"streamStructured\";\n  /** Consumer-owned artifact reference tags passed on the call options; verbatim on the event. (alpha.25+) */\n  refs?: Record<string, ArtifactRef>;\n}\n\n/** OnCacheHit event: provider reported cached prompt tokens. */\nexport interface CacheHitEvent {\n  /** Tokens served from cache (matches the provider's `cached_tokens` field). */\n  cachedTokens: number;\n  /** Total input tokens this call would have billed without the cache hit. */\n  inputTokensTotal: number;\n  /** Computed hit ratio = cachedTokens / inputTokensTotal. */\n  hitRatio: number;\n  /** USD saved by the cache hit. Only populated when the provider has a discounted cache-read tier. */\n  savingsUsd?: number;\n  modelId: string;\n  providerAlias: string;\n  operation: CostEvent[\"operation\"];\n  taskType?: string;\n  /** Consumer-owned artifact reference tags passed on the call options; verbatim on the event. (alpha.25+) */\n  refs?: Record<string, ArtifactRef>;\n}\n\n// ─── Hook function types ─────────────────────────────────────────────\n\n/** Fired after every billable call with cost breakdown. Fire-and-forget. */\nexport type OnCost = (event: CostEvent) => void | Promise<void>;\n\n/** Fired after every billable call with raw token counts. Fire-and-forget. */\nexport type OnTokenUsage = (event: TokenUsageEvent) => void | Promise<void>;\n\n/** Fired when the Registry's provider chain advances. Fire-and-forget. */\nexport type OnFallback = (event: FallbackEvent) => void | Promise<void>;\n\n/** Fired when retry-with-feedback round-trips on structured output. Fire-and-forget. */\nexport type OnValidationRetry = (event: ValidationRetryEvent) => void | Promise<void>;\n\n/** Fired when the provider reports cache hits. Fire-and-forget. */\nexport type OnCacheHit = (event: CacheHitEvent) => void | Promise<void>;\n\n/**\n * Bundle of optional observability hooks passed at Registry construction\n * (alpha.21+). Each field is independently optional; pass only the ones the\n * downstream pipeline needs.\n */\nexport interface ObservabilityHooks {\n  onCost?: OnCost;\n  onTokenUsage?: OnTokenUsage;\n  onFallback?: OnFallback;\n  onValidationRetry?: OnValidationRetry;\n  onCacheHit?: OnCacheHit;\n}\n\n// ─── Emit helpers ────────────────────────────────────────────────────\n//\n// Each emit helper is fire-and-forget with hook errors swallowed. Same\n// contract as `emitRetryEvent` in retry-emit.ts.\n\nfunction safeEmit<T>(hook: ((event: T) => void | Promise<void>) | undefined, event: T): void {\n  if (!hook) return;\n  try {\n    const result = hook(event);\n    if (result && typeof (result as Promise<void>).then === \"function\") {\n      (result as Promise<void>).catch(() => {\n        // Swallow async hook errors. Hooks are observability only;\n        // never let them break the call.\n      });\n    }\n  } catch {\n    // Swallow sync hook errors.\n  }\n}\n\nexport function emitCost(hook: OnCost | undefined, event: CostEvent): void {\n  safeEmit(hook, event);\n}\n\nexport function emitTokenUsage(hook: OnTokenUsage | undefined, event: TokenUsageEvent): void {\n  safeEmit(hook, event);\n}\n\nexport function emitFallback(hook: OnFallback | undefined, event: FallbackEvent): void {\n  safeEmit(hook, event);\n}\n\nexport function emitValidationRetry(hook: OnValidationRetry | undefined, event: ValidationRetryEvent): void {\n  safeEmit(hook, event);\n}\n\nexport function emitCacheHit(hook: OnCacheHit | undefined, event: CacheHitEvent): void {\n  safeEmit(hook, event);\n}\n\n/**\n * Derive a validation-retry event from an adapter-level `OnRetry` event.\n * (alpha.24+)\n *\n * The Registry-level `onValidationRetry` hook fires only for the\n * `validation-feedback` retry reason (structured-output schema mismatch).\n * Pass the result of this helper as the adapter's `onRetry` so each\n * adapter's retry events flow through to the Registry's observability\n * hooks AND any user-supplied adapter-level callback.\n *\n * @example\n *   import { createOpenAIAdapter } from \"@llm-ports/adapter-openai\";\n *   import { createRegistryFromEnv, deriveValidationRetryFromAdapterRetry } from \"@llm-ports/core\";\n *\n *   const registry = createRegistryFromEnv({\n *     // ...\n *     observability: {\n *       onValidationRetry: (e) => myMetrics.validationRetries.inc({ model: e.modelId }),\n *     },\n *   });\n *\n *   const adapter = createOpenAIAdapter({\n *     apiKey: process.env.OPENAI_API_KEY!,\n *     onRetry: deriveValidationRetryFromAdapterRetry(registry, {\n *       userOnRetry: (e) => myLogger.warn(\"retry\", e), // chain optional\n *     }),\n *   });\n *\n * **Caveats.** The adapter-level `RetryEvent` doesn't carry `maxAttempts`\n * or `operation`, so this helper:\n *   - Sets `maxAttempts` to `event.attempt + 1` (best-known lower bound)\n *   - Defaults `operation` to `\"generateStructured\"` (validation-feedback\n *     only fires from structured-output paths, so this is correct in\n *     practice)\n *   - Sets `cause` to `\"schema-mismatch\"` unconditionally (the adapter\n *     doesn't distinguish parse errors from schema errors today)\n *\n * If the user supplies an `OperationOverride`, that wins.\n */\nexport function deriveValidationRetryFromAdapterRetry(\n  registry: { observability: ObservabilityHooks },\n  opts?: {\n    /** Chain a user-supplied adapter-level onRetry. Errors swallowed. */\n    userOnRetry?: (event: import(\"./retry.js\").RetryEvent) => void | Promise<void>;\n    /** Override the operation discriminator. Default `\"generateStructured\"`. */\n    operation?: \"generateStructured\" | \"streamStructured\";\n  },\n): (event: import(\"./retry.js\").RetryEvent) => void {\n  const op = opts?.operation ?? \"generateStructured\";\n  return (event) => {\n    // Pass through to the user's adapter-level callback first, regardless of\n    // reason. Errors swallowed to match the standard `onRetry` contract.\n    if (opts?.userOnRetry) {\n      try {\n        const result = opts.userOnRetry(event);\n        if (result && typeof (result as Promise<void>).then === \"function\") {\n          (result as Promise<void>).catch(() => {/* swallow */});\n        }\n      } catch {\n        /* swallow */\n      }\n    }\n    // Only forward validation-feedback events to the Registry-level hook.\n    if (event.reason !== \"validation-feedback\") return;\n    const hook = registry.observability.onValidationRetry;\n    if (!hook) return;\n    emitValidationRetry(hook, {\n      attempt: event.attempt,\n      maxAttempts: event.attempt + 1,\n      modelId: event.modelId,\n      providerAlias: event.providerAlias,\n      cause: \"schema-mismatch\",\n      operation: op,\n      ...(event.cause !== undefined ? { issues: event.cause } : {}),\n    });\n  };\n}\n\n// ─── Streamed cost surfacing (alpha.25+) ─────────────────────────────\n\n/**\n * Internal contract between the Registry and an adapter for surfacing\n * stream-completion metadata (usage + cost + timing) back to the Registry's\n * observability hooks. (alpha.25+)\n *\n * The Registry attaches a `StreamCompleteCallback` to the options object\n * via `STREAM_COMPLETE_CALLBACK_KEY` before dispatching to the adapter. The\n * adapter reads it and calls it ONCE with the final metadata when the stream\n * completes naturally. The Registry then emits `onCost` + `onTokenUsage`\n * from the callback body, preserving `refs` and all other observability\n * plumbing.\n *\n * Semantics enforced by callers:\n *   - The callback is called AT MOST ONCE per call.\n *   - It is called only on natural stream completion. Mid-stream errors,\n *     consumer-cancelled streams, and empty streams do NOT invoke it.\n *   - Adapters that don't implement stream metadata (older adapter builds\n *     mixed with new core) just don't call the callback; the Registry\n *     falls back to zero-cost-recording behavior (matches alpha.24 for\n *     stream methods).\n *\n * This is an internal contract, not a public consumer API. Consumers set\n * observability hooks at Registry construction; the Symbol-keyed callback\n * is Registry-internal plumbing.\n */\nexport const STREAM_COMPLETE_CALLBACK_KEY = Symbol.for(\n  \"llm-ports.streamCompleteCallback\",\n);\n\n/** Payload the adapter passes when firing the stream-complete callback. */\nexport interface StreamCompleteMetadata {\n  usage: TokenUsage;\n  cost: CostUsage;\n  modelId: string;\n  providerAlias: string;\n  latencyMs: number;\n}\n\n/** Signature of the Registry-attached stream-complete callback. */\nexport type StreamCompleteCallback = (meta: StreamCompleteMetadata) => void;\n\n/**\n * Read the Registry-attached stream-complete callback from a call options\n * object. Adapters call this to retrieve the callback before entering their\n * stream loop; if a callback is present, the adapter fires it on natural\n * completion. Type-safe wrapper around the Symbol-keyed access.\n */\nexport function readStreamCompleteCallback(\n  options: object | undefined,\n): StreamCompleteCallback | undefined {\n  if (!options) return undefined;\n  const key = STREAM_COMPLETE_CALLBACK_KEY;\n  const value = (options as Record<symbol, unknown>)[key];\n  return typeof value === \"function\" ? (value as StreamCompleteCallback) : undefined;\n}\n\n/**\n * Attach a stream-complete callback to a call options object. The Registry\n * calls this before dispatching a stream call to an adapter that supports\n * completion metadata. Returns the mutated options (same reference).\n */\nexport function attachStreamCompleteCallback<T extends object>(\n  options: T,\n  callback: StreamCompleteCallback,\n): T {\n  (options as Record<symbol, unknown>)[STREAM_COMPLETE_CALLBACK_KEY] = callback;\n  return options;\n}\n\n/**\n * Compute cache-hit metadata from a TokenUsage. Returns null when the usage\n * has no cache hit to emit (cachedInputTokens missing or 0). Adapters call\n * this after a successful call to determine whether to emit `onCacheHit`.\n */\nexport function deriveCacheHit(usage: TokenUsage, cost: CostUsage | undefined): {\n  cachedTokens: number;\n  inputTokensTotal: number;\n  hitRatio: number;\n  savingsUsd?: number;\n} | null {\n  const cached = usage.cacheReadTokens ?? 0;\n  if (cached <= 0) return null;\n  const total = usage.inputTokens || 0;\n  const hitRatio = total > 0 ? cached / total : 0;\n  if (cost && cost.cacheSavingsUSD !== undefined) {\n    return {\n      cachedTokens: cached,\n      inputTokensTotal: total,\n      hitRatio,\n      savingsUsd: cost.cacheSavingsUSD,\n    };\n  }\n  return {\n    cachedTokens: cached,\n    inputTokensTotal: total,\n    hitRatio,\n  };\n}\n","/**\n * In-memory implementations of BudgetBackend and CostBackend.\n *\n * Default for development and single-process deployments. For multi-process\n * deployments, swap in a Redis-backed implementation (separate package).\n *\n * Storage keys are arbitrary strings — the Registry composes them as\n * `${alias}` or `${alias}|${scope}:${scopeId}` (alpha.20+) to make gating\n * per-alias or per-scope. The backends don't need to know the schema.\n */\n\nimport type {\n  BudgetBackend,\n  BudgetCheckResult,\n  BudgetLimit,\n  CostBackend,\n  CostCheckResult,\n  CostLimit,\n} from \"./types.js\";\n\nconst ONE_MINUTE_MS = 60 * 1000;\nconst ONE_HOUR_MS = 60 * ONE_MINUTE_MS;\nconst ONE_DAY_MS = 24 * ONE_HOUR_MS;\nconst ONE_MONTH_MS = 30 * ONE_DAY_MS;\n\n// ─── Budget backend (request count per window) ───────────────────────\n\n/**\n * In-memory implementation. Stores per-key arrays of request timestamps and\n * counts windowed views from them lazily. Supports per-minute, per-hour, and\n * legacy `requestsPerHour` (alpha.19 backwards compat).\n *\n * `perSession` from BudgetLimit is intentionally ignored here — session-scope\n * enforcement lives in CostSession (which is the only thing that knows\n * \"this is the same session\"). The backend exists for per-alias / per-scope\n * windowed enforcement.\n */\nexport class InMemoryBudget implements BudgetBackend {\n  private requests = new Map<string, number[]>();\n\n  async recordRequest(key: string): Promise<void> {\n    const arr = this.requests.get(key) ?? [];\n    arr.push(Date.now());\n    this.requests.set(key, arr);\n    this.prune(arr);\n  }\n\n  async check(key: string, limit: BudgetLimit): Promise<BudgetCheckResult> {\n    if (limit.kind === \"unlimited\") {\n      return { allowed: true, current: 0, limit: Infinity };\n    }\n    const arr = this.requests.get(key) ?? [];\n    const now = Date.now();\n\n    // Build the configured window ceilings. perSession is enforced by\n    // CostSession, not the windowed backend, so it's skipped here.\n    const ceilings: Array<{ windowMs: number; cap: number; label: string }> = [];\n    if (limit.perMinute !== undefined) {\n      ceilings.push({ windowMs: ONE_MINUTE_MS, cap: limit.perMinute, label: \"minute\" });\n    }\n    const perHour = limit.perHour ?? limit.requestsPerHour;\n    if (perHour !== undefined) {\n      ceilings.push({ windowMs: ONE_HOUR_MS, cap: perHour, label: \"hour\" });\n    }\n\n    for (const ceiling of ceilings) {\n      const cutoff = now - ceiling.windowMs;\n      const current = arr.reduce((n, t) => (t >= cutoff ? n + 1 : n), 0);\n      if (current >= ceiling.cap) {\n        return {\n          allowed: false,\n          current,\n          limit: ceiling.cap,\n          reason: `Request budget exceeded for \"${key}\": ${current} >= ${ceiling.cap}/${ceiling.label}`,\n        };\n      }\n    }\n\n    if (ceilings.length === 0) {\n      return { allowed: true, current: 0, limit: Infinity };\n    }\n    // Surface the tightest configured window's current usage for visibility.\n    const tightest = ceilings.reduce((a, b) => (a.cap < b.cap ? a : b));\n    const cutoff = now - tightest.windowMs;\n    const current = arr.reduce((n, t) => (t >= cutoff ? n + 1 : n), 0);\n    return { allowed: true, current, limit: tightest.cap };\n  }\n\n  private prune(arr: number[]): void {\n    // Keep at most the last hour of timestamps — adequate for hour-grained\n    // windowed checks, which is the longest window the backend enforces.\n    const cutoff = Date.now() - ONE_HOUR_MS;\n    while (arr.length > 0 && arr[0]! < cutoff) {\n      arr.shift();\n    }\n  }\n}\n\n// ─── Cost backend (USD per minute/hour/day/month) ────────────────────\n\ninterface CostEntry {\n  timestamp: number;\n  usd: number;\n}\n\nexport class InMemoryCost implements CostBackend {\n  private spends = new Map<string, CostEntry[]>();\n\n  async recordCost(key: string, usd: number): Promise<void> {\n    const arr = this.spends.get(key) ?? [];\n    arr.push({ timestamp: Date.now(), usd });\n    this.spends.set(key, arr);\n    this.prune(arr);\n  }\n\n  async check(key: string, limit: CostLimit): Promise<CostCheckResult> {\n    if (limit.kind === \"unlimited\") {\n      return { allowed: true, current: 0, limit: Infinity };\n    }\n    const arr = this.spends.get(key) ?? [];\n    const now = Date.now();\n    const ceilings: Array<{ windowMs: number; cap: number; label: string }> = [];\n    if (limit.perMinute !== undefined) ceilings.push({ windowMs: ONE_MINUTE_MS, cap: limit.perMinute, label: \"minute\" });\n    if (limit.perHour !== undefined) ceilings.push({ windowMs: ONE_HOUR_MS, cap: limit.perHour, label: \"hour\" });\n    if (limit.perDay !== undefined) ceilings.push({ windowMs: ONE_DAY_MS, cap: limit.perDay, label: \"day\" });\n    if (limit.perMonth !== undefined) ceilings.push({ windowMs: ONE_MONTH_MS, cap: limit.perMonth, label: \"month\" });\n    // perSession is enforced by CostSession; skipped here.\n\n    for (const ceiling of ceilings) {\n      const cutoff = now - ceiling.windowMs;\n      const spent = arr.reduce((sum, e) => (e.timestamp >= cutoff ? sum + e.usd : sum), 0);\n      if (spent >= ceiling.cap) {\n        return {\n          allowed: false,\n          current: spent,\n          limit: ceiling.cap,\n          reason: `Cost cap exceeded for \"${key}\" per ${ceiling.label}: $${spent.toFixed(4)} >= $${ceiling.cap}`,\n        };\n      }\n    }\n\n    if (ceilings.length === 0) {\n      return { allowed: true, current: 0, limit: Infinity };\n    }\n    const tightest = ceilings.reduce((a, b) => (a.cap < b.cap ? a : b));\n    const cutoff = now - tightest.windowMs;\n    const spent = arr.reduce((sum, e) => (e.timestamp >= cutoff ? sum + e.usd : sum), 0);\n    return { allowed: true, current: spent, limit: tightest.cap };\n  }\n\n  private prune(arr: CostEntry[]): void {\n    const cutoff = Date.now() - ONE_MONTH_MS;\n    while (arr.length > 0 && arr[0]!.timestamp < cutoff) {\n      arr.shift();\n    }\n  }\n}\n","/**\r\n * Typed error taxonomy for @llm-ports.\r\n *\r\n * Designed for typed-error-driven failover (alpha.18+). Consumers declare\r\n * which error classes route to which fallback chains rather than string-\r\n * matching error messages. The shape matches the field consensus that\r\n * emerged across LiteLLM, Pydantic AI, LangChain, Portkey, and Genkit;\r\n * LiteLLM's 11-class taxonomy is the closest analogue.\r\n *\r\n * Hierarchy (alpha.18):\r\n *\r\n *   LLMPortError                                  // common base for instanceof checks\r\n *   ├── BadRequestError                           // 400-class root (client-fixable)\r\n *   │   ├── ContextWindowExceededError            // prompt too long for model\r\n *   │   └── ContentPolicyViolationError           // content filter rejected the request\r\n *   ├── AuthenticationError                       // 401/403 (NOT retryable to same provider)\r\n *   ├── RateLimitError                            // 429 with optional retryAfterMs\r\n *   ├── BudgetExceededError                       // port-internal cap exhausted\r\n *   ├── SessionBudgetExceededError                // CostSession budget exhausted\r\n *   ├── ServiceUnavailableError                   // 503 root (transient)\r\n *   │   ├── ProviderUnavailableError              // SDK error or unreachable; route to fallback\r\n *   │   └── EmptyResponseError                    // model returned empty visible text\r\n *   ├── NoProvidersAvailableError                 // entire chain exhausted\r\n *   ├── ValidationError                           // structured-output Zod failure\r\n *   ├── ContentBlockUnsupportedError              // block kind unknown to adapter\r\n *   ├── ConfigError                               // env/config malformed\r\n *   ├── ImageTooLargeError                        // image over per-provider byte limit\r\n *   └── InvalidImageUrlError                      // image URL form invalid\r\n *\r\n * Breaking changes vs alpha.17:\r\n *\r\n *   - `ContextWindowExceededError` is NEW. Previously the underlying provider\r\n *     SDK threw a generic 400, which got wrapped as `ProviderUnavailableError`.\r\n *     With the new taxonomy it's parented under `BadRequestError`. Consumers\r\n *     branching on `instanceof ProviderUnavailableError` after a context-window\r\n *     overflow will need to add `instanceof BadRequestError` to their handlers.\r\n *\r\n *   - `ContentPolicyViolationError` is NEW. Same shape change.\r\n *\r\n *   - `ServiceUnavailableError` is NEW. `ProviderUnavailableError` and\r\n *     `EmptyResponseError` are reparented under it. Existing `instanceof\r\n *     ProviderUnavailableError` checks continue to work; new `instanceof\r\n *     ServiceUnavailableError` checks catch both.\r\n *\r\n *   - `AuthenticationError` is NEW. Previously 401/403 errors were wrapped as\r\n *     `ProviderUnavailableError`, which is wrong because they're not transient\r\n *     and shouldn't trigger same-provider retries.\r\n *\r\n *   - `RateLimitError` is NEW. Previously 429 errors were wrapped as\r\n *     `ProviderUnavailableError`, which lost the `retryAfterMs` information.\r\n *\r\n *   - `LLMPortError` is NEW. All errors thrown by this library extend it.\r\n *     Use `e instanceof LLMPortError` to catch any library error;\r\n *     `errorMatchers.all` does this for fallback predicates.\r\n */\r\n\r\nimport type { ZodIssue } from \"zod\";\r\n\r\n/**\r\n * Common base class for every error thrown by this library. Useful for\r\n * blanket catches: `try { ... } catch (e) { if (e instanceof LLMPortError)\r\n * { /* library error *\\/ } }`. Direct subclass of `Error`, so existing\r\n * `instanceof Error` checks continue to work.\r\n */\r\nexport class LLMPortError extends Error {\r\n  public override readonly name: string = \"LLMPortError\";\r\n}\r\n\r\n// ─── 400-class (client-fixable; do NOT retry the same request) ────────\r\n\r\n/**\r\n * 400-class root. Indicates the request itself is malformed, too large, or\r\n * policy-violating. Adapters should NOT include this in default fallback\r\n * chains: another provider will reject the same request the same way.\r\n *\r\n * Use `LiteLLM`-style explicit `context_window_fallbacks` /\r\n * `content_policy_fallbacks` chains to handle 400s by routing to a model\r\n * with a larger window or more permissive policy.\r\n */\r\nexport class BadRequestError extends LLMPortError {\r\n  public override readonly name: string = \"BadRequestError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    message: string,\r\n    public override readonly cause?: Error,\r\n  ) {\r\n    super(`Provider \"${alias}\": ${message}`);\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown when the prompt + tools + system content exceeds the model's\r\n * context window. Subclass of `BadRequestError`: fallback to another\r\n * provider with the same window will fail the same way. Route to a\r\n * larger-window model explicitly.\r\n */\r\nexport class ContextWindowExceededError extends BadRequestError {\r\n  public override readonly name: string = \"ContextWindowExceededError\";\r\n  constructor(\r\n    alias: string,\r\n    public readonly modelId: string,\r\n    public readonly contextLimit?: number,\r\n    public readonly observedTokens?: number,\r\n    cause?: Error,\r\n  ) {\r\n    const detail =\r\n      contextLimit !== undefined && observedTokens !== undefined\r\n        ? ` (~${observedTokens} tokens; model limit ${contextLimit})`\r\n        : \"\";\r\n    super(\r\n      alias,\r\n      `context window exceeded for model \"${modelId}\"${detail}`,\r\n      cause,\r\n    );\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown when the provider's content filter / safety classifier rejected\r\n * the request. Not retryable on the same provider's same policy; may\r\n * succeed on a provider with different policy thresholds.\r\n */\r\nexport class ContentPolicyViolationError extends BadRequestError {\r\n  public override readonly name: string = \"ContentPolicyViolationError\";\r\n  constructor(\r\n    alias: string,\r\n    public readonly modelId: string,\r\n    public readonly policyDetails?: string,\r\n    cause?: Error,\r\n  ) {\r\n    super(\r\n      alias,\r\n      policyDetails\r\n        ? `content policy violation on model \"${modelId}\": ${policyDetails}`\r\n        : `content policy violation on model \"${modelId}\"`,\r\n      cause,\r\n    );\r\n  }\r\n}\r\n\r\n// ─── 401/403 (NOT retryable to same provider) ─────────────────────────\r\n\r\n/**\r\n * Thrown when the provider rejected the request as unauthenticated or\r\n * forbidden. Not transient: retrying the same call against the same\r\n * provider with the same credential will fail again. Adapters should\r\n * NOT include this in default fallback chains; the credential needs to\r\n * be fixed externally.\r\n */\r\nexport class AuthenticationError extends LLMPortError {\r\n  public override readonly name: string = \"AuthenticationError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    message: string,\r\n    public override readonly cause?: Error,\r\n  ) {\r\n    super(`Provider \"${alias}\" auth failed: ${message}`);\r\n  }\r\n}\r\n\r\n// ─── 429 (rate limited; may be retryable after a delay) ───────────────\r\n\r\n/**\r\n * Thrown when the provider returned HTTP 429 (rate limited). When the\r\n * provider supplies a `Retry-After` or `retry-after-ms` header, the\r\n * adapter parses it and exposes it as `retryAfterMs`. Fallback chains\r\n * SHOULD honor this delay (planned for alpha.21+) and demote the alias\r\n * for exactly that duration rather than guessing with exponential\r\n * backoff.\r\n */\r\nexport class RateLimitError extends LLMPortError {\r\n  public override readonly name: string = \"RateLimitError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    message: string,\r\n    public readonly retryAfterMs?: number,\r\n    public override readonly cause?: Error,\r\n  ) {\r\n    super(`Provider \"${alias}\" rate limited: ${message}`);\r\n  }\r\n}\r\n\r\n// ─── Budget / session (port-internal, not provider-side) ──────────────\r\n\r\n/**\r\n * Thrown when a provider's request budget (count or USD) is exhausted.\r\n * Distinct from a provider-side 429: this is the local registry's\r\n * `cost:N/day` or `req:N/hour` gating, evaluated BEFORE the provider call.\r\n */\r\nexport class BudgetExceededError extends LLMPortError {\r\n  public override readonly name: string = \"BudgetExceededError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    public readonly limit: number,\r\n    public readonly current: number,\r\n    public readonly gatingKind: \"requests\" | \"cost\",\r\n  ) {\r\n    super(\r\n      `Budget exceeded for provider \"${alias}\" (${gatingKind}): ${current} > ${limit}`,\r\n    );\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown when an active CostSession exceeds its USD budget. Distinct from\r\n * `BudgetExceededError` (which gates per-provider hour/day/month) so call\r\n * sites can recover differently: typically by closing the session and\r\n * informing the user, not by routing to a fallback provider.\r\n *\r\n * Use case: continuous screen-capture loops where one stuck-open window\r\n * could otherwise burn arbitrary dollars overnight. The session-scoped\r\n * cap is a hard backstop independent of the per-provider gates.\r\n */\r\nexport class SessionBudgetExceededError extends LLMPortError {\r\n  public override readonly name: string = \"SessionBudgetExceededError\";\r\n  /**\r\n   * Optional reason tag distinguishing which session-grain cap tripped\r\n   * (e.g. `\"tokens (50000 >= 50000)\"`, `\"tool_calls (8 >= 8)\"`,\r\n   * `\"requests (100 >= 100)\"`). When undefined the default USD cap\r\n   * tripped. (alpha.20+)\r\n   */\r\n  public readonly grain?: string;\r\n  /**\r\n   * Backwards-compatible constructor. The first three args are the legacy\r\n   * USD-cap shape; pass a fourth `grain` string when the cap that tripped\r\n   * is one of the alpha.20+ token / tool_call / request session ceilings.\r\n   * `budgetUSD` and `spentUSD` are repurposed as `cap` and `current` in\r\n   * that case so the existing fields keep working for diagnostics.\r\n   */\r\n  constructor(\r\n    public readonly sessionId: string,\r\n    public readonly budgetUSD: number,\r\n    public readonly spentUSD: number,\r\n    grain?: string,\r\n  ) {\r\n    super(\r\n      grain\r\n        ? `Cost session \"${sessionId}\" exceeded its ${grain} cap`\r\n        : `Cost session \"${sessionId}\" exceeded its budget: $${spentUSD.toFixed(6)} > $${budgetUSD.toFixed(6)}`,\r\n    );\r\n    if (grain) this.grain = grain;\r\n  }\r\n}\r\n\r\n// ─── 503-class root (transient; safe to retry / failover) ─────────────\r\n\r\n/**\r\n * Root of the transient-failure tier (HTTP 502/503/504, network resets,\r\n * provider-side overload). Adapters should include this in default\r\n * fallback chains: another provider may serve the same request fine.\r\n */\r\nexport class ServiceUnavailableError extends LLMPortError {\r\n  public override readonly name: string = \"ServiceUnavailableError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    message: string,\r\n    public override readonly cause?: Error,\r\n  ) {\r\n    super(`Provider \"${alias}\" service unavailable: ${message}`);\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown when a configured provider is unreachable, returned a non-typed\r\n * error, or is misconfigured. Subclass of `ServiceUnavailableError` so\r\n * the default fallback predicate routes it to the next provider.\r\n *\r\n * Reparenting note: in alpha.17 this extended `Error` directly. In alpha.18\r\n * it extends `ServiceUnavailableError`. Existing `instanceof\r\n * ProviderUnavailableError` checks continue to work.\r\n */\r\nexport class ProviderUnavailableError extends ServiceUnavailableError {\r\n  public override readonly name: string = \"ProviderUnavailableError\";\r\n  constructor(\r\n    alias: string,\r\n    cause: Error,\r\n  ) {\r\n    super(alias, cause.message, cause);\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown by adapters when a model returns an empty/whitespace-only response\r\n * where one is structurally required (e.g. generateStructured needs JSON to\r\n * parse). Carries the model id + provider alias so the registry can route\r\n * to a fallback. Common cause: reasoning models that spent the entire output\r\n * budget on hidden reasoning tokens and produced no visible text.\r\n *\r\n * Reparenting note: in alpha.17 this extended `Error` directly. In alpha.18\r\n * it extends `ServiceUnavailableError` so fallback predicates treat it as\r\n * a transient failure.\r\n */\r\nexport class EmptyResponseError extends ServiceUnavailableError {\r\n  public override readonly name: string = \"EmptyResponseError\";\r\n  constructor(\r\n    alias: string,\r\n    public readonly modelId: string,\r\n    public readonly hint?: string,\r\n  ) {\r\n    const msg = hint\r\n      ? `empty response for model \"${modelId}\". ${hint}`\r\n      : `empty response for model \"${modelId}\".`;\r\n    super(alias, msg);\r\n  }\r\n}\r\n\r\n// ─── Chain-level + other typed errors ─────────────────────────────────\r\n\r\n/**\r\n * Thrown when every provider in the task's fallback chain has been attempted\r\n * and none succeeded (each either errored, was budget-blocked, or was missing).\r\n */\r\nexport class NoProvidersAvailableError extends LLMPortError {\r\n  public override readonly name: string = \"NoProvidersAvailableError\";\r\n  constructor(\r\n    public readonly taskType: string,\r\n    public readonly attempted: string[],\r\n    public readonly reasons: Record<string, string>,\r\n  ) {\r\n    super(\r\n      `No providers available for task \"${taskType}\". Attempted: ${attempted.join(\", \")}`,\r\n    );\r\n  }\r\n}\r\n\r\n/** Thrown by validation strategies when generated structured output fails schema. */\r\nexport class ValidationError extends LLMPortError {\r\n  public override readonly name: string = \"ValidationError\";\r\n  constructor(\r\n    public readonly issues: ZodIssue[],\r\n    public readonly attempts: number,\r\n  ) {\r\n    const summary = issues.map((i) => `${i.path.join(\".\") || \"<root>\"}: ${i.message}`).join(\"; \");\r\n    super(`Validation failed after ${attempts} attempt(s): ${summary}`);\r\n  }\r\n}\r\n\r\n/** Thrown when a content block kind is sent to an adapter that does not support it. */\r\nexport class ContentBlockUnsupportedError extends LLMPortError {\r\n  public override readonly name: string = \"ContentBlockUnsupportedError\";\r\n  constructor(\r\n    public readonly adapter: string,\r\n    public readonly blockType: string,\r\n  ) {\r\n    super(`Adapter \"${adapter}\" does not support content block type \"${blockType}\"`);\r\n  }\r\n}\r\n\r\n/** Thrown by the registry when env config is malformed. */\r\nexport class ConfigError extends LLMPortError {\r\n  public override readonly name: string = \"ConfigError\";\r\n  constructor(message: string) {\r\n    super(message);\r\n  }\r\n}\r\n\r\n// ─── alpha.26 messages-input errors ──────────────────────────────────\r\n\r\n/**\r\n * Thrown at Registry entry when a call is dispatched with neither `messages`\r\n * nor the legacy `prompt` set. Exactly one of the two must be supplied.\r\n * (alpha.26+)\r\n */\r\nexport class MessagesRequiredError extends LLMPortError {\r\n  public override readonly name: string = \"MessagesRequiredError\";\r\n  constructor(public readonly method: string) {\r\n    super(\r\n      `${method}: neither 'messages' nor 'prompt' was supplied. Use 'messages: LLMMessage[]' (recommended) or the legacy 'prompt' field.`,\r\n    );\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown at Registry entry when `messages` is supplied but empty. Every\r\n * provider requires at least one message. (alpha.26+)\r\n */\r\nexport class EmptyMessagesError extends LLMPortError {\r\n  public override readonly name: string = \"EmptyMessagesError\";\r\n  constructor(public readonly method: string) {\r\n    super(`${method}: 'messages' array is empty. At least one message is required.`);\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown by the `toMessages` helper when called without a `prompt`. The\r\n * helper is designed to migrate the legacy `{instructions, prompt}` shape;\r\n * calling it with no prompt is a caller bug. (alpha.26+)\r\n */\r\nexport class PromptRequiredError extends LLMPortError {\r\n  public override readonly name: string = \"PromptRequiredError\";\r\n  constructor() {\r\n    super(\r\n      \"toMessages: 'prompt' is required. Use 'sys()' + 'usr()' or object literals for other shapes.\",\r\n    );\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown at Registry entry when a caller mixes the alpha.26 canonical\r\n * `messages` shape with the deprecated `{instructions, prompt}` shape.\r\n * Ambiguity is a caller bug worth surfacing. Post-alpha.27 (which removes\r\n * the deprecated fields) this error is unreachable. (alpha.26+)\r\n */\r\nexport class MessagesConflictError extends LLMPortError {\r\n  public override readonly name: string = \"MessagesConflictError\";\r\n  constructor(public readonly method: string, public readonly conflictingFields: readonly string[]) {\r\n    super(\r\n      `${method}: cannot mix 'messages' with the deprecated legacy fields (${conflictingFields.join(\", \")}). Use 'messages' alone.`,\r\n    );\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown by adapters whose underlying provider does not structurally\r\n * support mid-conversation system-role messages. Anthropic's `system` is\r\n * a top-level request field distinct from `messages`; Google Gemini's\r\n * `systemInstruction` is similar. Both providers reject a `messages`\r\n * array that contains a system-role message after any user or assistant\r\n * message; the adapter surfaces this typed error at the boundary rather\r\n * than silent flattening or a confusing provider error.\r\n *\r\n * Adapters whose provider tolerates mid-conversation system messages\r\n * (OpenAI, Ollama, Vercel) pass them through inline and never throw\r\n * this error. See per-adapter docs for the policy.\r\n *\r\n * (alpha.27+)\r\n */\r\nexport class NonContiguousSystemError extends LLMPortError {\r\n  public override readonly name: string = \"NonContiguousSystemError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    public readonly method: string,\r\n    public readonly messageIndex: number,\r\n  ) {\r\n    super(\r\n      `Provider \"${alias}\" (${method}): system-role message at index ${messageIndex} appears mid-conversation. This provider structurally rejects non-leading system messages. Group all system-role messages at the start of the array, or fold their content into the leading system message.`,\r\n    );\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown by adapters when an image content block exceeds the provider's\r\n * per-image byte limit. Caught at the adapter boundary BEFORE the SDK call,\r\n * so the caller sees a typed error instead of an opaque 413/400 wrapped as\r\n * ProviderUnavailableError.\r\n *\r\n * Each adapter knows its own default limit (Anthropic 5MB, OpenAI 20MB,\r\n * Ollama model-dependent), and the limit can be overridden per-adapter at\r\n * port creation via `imageSizeLimitBytes`.\r\n *\r\n * `imageIndex` is the 0-indexed position of the offending image in the\r\n * caller's `prompt` ContentBlock[] array.\r\n */\r\nexport class ImageTooLargeError extends LLMPortError {\r\n  public override readonly name: string = \"ImageTooLargeError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    public readonly imageIndex: number,\r\n    public readonly byteSize: number,\r\n    public readonly limitBytes: number,\r\n  ) {\r\n    super(\r\n      `Image at index ${imageIndex} is ${byteSize} bytes; exceeds the ${limitBytes}-byte limit for provider \"${alias}\".`,\r\n    );\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown by adapters when an image content block's URL form is malformed:\r\n * `file://` scheme, `data:` URI passed as `kind: \"url\"` instead of base64,\r\n * or a URL with no scheme. Caught at the adapter boundary BEFORE the SDK call.\r\n */\r\nexport class InvalidImageUrlError extends LLMPortError {\r\n  public override readonly name: string = \"InvalidImageUrlError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    public readonly url: string,\r\n    public readonly reason: string,\r\n  ) {\r\n    super(`Invalid image URL for provider \"${alias}\": ${reason}. URL: ${url.slice(0, 100)}`);\r\n  }\r\n}\r\n\r\n// ─── alpha.28 new typed classes (cross-consumer review 2026-07-21) ────\r\n\r\n/**\r\n * Thrown when the provider's account or billing headroom is exhausted.\r\n * Distinct from `AuthenticationError` (which reflects a genuine wrong-key\r\n * or invalid-credential problem) because the credential is valid; the\r\n * account just has no billing headroom. Distinct from\r\n * `BudgetExceededError` (which is port-internal gating) because this\r\n * fires on the provider's side.\r\n *\r\n * Walk-worthy: a different vendor with a fresh billing state can succeed.\r\n * A single provider's credit-exhaustion surface today varies across\r\n * response shapes (401 with a credit-exhaustion body, 403, 429 with\r\n * \"credit_balance too low\", 400 with a \"your account has no credit\"\r\n * message). Adapters classify into this typed class using the same\r\n * message patterns collected in `AGGRESSIVE_CREDIT_EXHAUSTION_PATTERNS`.\r\n *\r\n * Added in alpha.28 pre-work (TD-LLMP-19). Prior to alpha.28, downstream\r\n * consumers walked on `AuthenticationError` as a proxy for this condition;\r\n * that over-walked on genuine wrong-key auth failures. Separating the\r\n * classes lets `defaultShouldFallback` walk on `CreditExhaustionError`\r\n * while aborting on true `AuthenticationError`.\r\n */\r\nexport class CreditExhaustionError extends LLMPortError {\r\n  public override readonly name: string = \"CreditExhaustionError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    message: string,\r\n    public override readonly cause?: Error,\r\n  ) {\r\n    super(`Provider \"${alias}\" credit exhausted: ${message}`);\r\n  }\r\n}\r\n\r\n/**\r\n * Thrown when a provider returns HTTP 400 with an empty or unparseable\r\n * body (no descriptive error body explaining what was malformed). This\r\n * condition surfaces on Cerebras when a structured-output request uses\r\n * a strict schema the provider cannot handle, and on some OpenAI-compat\r\n * providers when the payload triggers an upstream provider-side bug that\r\n * short-circuits before the descriptive error is emitted.\r\n *\r\n * Walk-worthy: another provider may accept the same request. Distinct\r\n * from generic `BadRequestError` (which is unclassified 400 and most\r\n * likely identical across providers) because this specific mode has an\r\n * observed pattern of provider-specific quirks that walking recovers\r\n * from.\r\n *\r\n * Added in alpha.28 pre-work (TD-LLMP-19). Prior to alpha.28, downstream\r\n * consumers walked on generic `BadRequestError` as a proxy for this\r\n * condition; that over-walked on genuine malformed requests that fail\r\n * identically on every provider. Separating the classes lets\r\n * `defaultShouldFallback` walk on `ProviderMalformed400Error` while\r\n * aborting on true generic `BadRequestError`.\r\n */\r\nexport class ProviderMalformed400Error extends BadRequestError {\r\n  public override readonly name: string = \"ProviderMalformed400Error\";\r\n}\r\n\r\n/**\r\n * Thrown when the adapter or registry code itself throws synchronously\r\n * (TypeError, ReferenceError, JS runtime bug, unchecked precondition\r\n * violation) BEFORE reaching the provider. Distinct from\r\n * `ServiceUnavailableError` (which reflects a provider-side failure)\r\n * because this is a bug in the port library, not a problem with the\r\n * provider.\r\n *\r\n * NOT walk-worthy: another provider will produce the same local error\r\n * at every hop. Walking the chain for a client-side bug multiplies\r\n * latency and cost, and misdirects operator diagnostic to provider\r\n * status pages when the fix is inside `@llm-ports`.\r\n *\r\n * Adapter code SHOULD wrap only the provider-call block (network call\r\n * plus immediate response handling) in the `errorMatchers` try/catch.\r\n * Local synchronous throws before the network call SHOULD propagate as\r\n * `AdapterInternalError` so the registry does not fail over on them.\r\n *\r\n * Added in alpha.28 pre-work (TD-LLMP-17). Prior to alpha.28, local\r\n * TypeErrors from adapter code were wrapped as `ServiceUnavailableError`\r\n * by `wrapProviderError`'s fallback branch, which then triggered futile\r\n * chain-wide failover with the same error re-thrown at every hop.\r\n */\r\nexport class AdapterInternalError extends LLMPortError {\r\n  public override readonly name: string = \"AdapterInternalError\";\r\n  constructor(\r\n    public readonly alias: string,\r\n    message: string,\r\n    public override readonly cause?: Error,\r\n  ) {\r\n    super(`Adapter \"${alias}\" internal error: ${message}`);\r\n  }\r\n}\r\n\r\n// ─── errorMatchers helper (typed-error-driven failover predicates) ────\r\n\r\n/**\r\n * Predicates for typed-error-driven fallback. Pass one of these as the\r\n * `shouldFallback` argument when configuring per-call or registry-level\r\n * `runtimeFallback` (planned alpha.21 surface) instead of writing inline\r\n * `instanceof` chains or string-match checks.\r\n *\r\n * Semantics:\r\n *   - `rateLimit`: true only for `RateLimitError`. Use when you want to\r\n *     fall back ONLY on 429.\r\n *   - `transient`: true for `RateLimitError` and any `ServiceUnavailableError`\r\n *     subclass (including `ProviderUnavailableError` and `EmptyResponseError`).\r\n *     Use for the conservative \"retry on network-level transients\" policy.\r\n *   - `default`: true for any `LLMPortError` EXCEPT `BadRequestError`\r\n *     subclasses (`ContextWindowExceededError`, `ContentPolicyViolationError`)\r\n *     and `AuthenticationError`. Use for the \"fall back on anything not\r\n *     client-fixable\" policy. This is the recommended default.\r\n *   - `all`: true for any `LLMPortError`. Use when you want to fall back\r\n *     on every library error, including client-fixable ones (rarely\r\n *     correct, but offered for completeness).\r\n */\r\nexport const errorMatchers = {\r\n  rateLimit: (e: unknown): boolean => e instanceof RateLimitError,\r\n  transient: (e: unknown): boolean =>\r\n    e instanceof RateLimitError || e instanceof ServiceUnavailableError,\r\n  default: (e: unknown): boolean =>\r\n    e instanceof LLMPortError &&\r\n    !(e instanceof BadRequestError) &&\r\n    !(e instanceof AuthenticationError),\r\n  all: (e: unknown): boolean => e instanceof LLMPortError,\r\n};\r\n\r\n// ─── Aggressive fallback classifier (alpha.25+, LP-REQ-01) ────────────\r\n\r\n/**\r\n * Body-pattern list for credit-exhaustion / account-issue 400s. Matched\r\n * case-insensitively against `error.message` on a `BadRequestError`.\r\n * Expanded conservatively: the intent is \"the account cannot serve ANY\r\n * call right now\"; genuinely malformed requests (invalid parameter,\r\n * schema failure) fail identically on every provider and MUST NOT walk\r\n * the chain.\r\n *\r\n * Exported so consumers who want to extend this list (uncommon) or run\r\n * the same matcher outside the fallback path can reuse the canonical\r\n * regex set.\r\n */\r\nexport const AGGRESSIVE_CREDIT_EXHAUSTION_PATTERNS: readonly RegExp[] = [\r\n  /credit balance is too low/i,\r\n  /insufficient (funds|credit|quota|balance)/i,\r\n  /account (disabled|suspended|deactivated|closed)/i,\r\n  /billing/i,\r\n  /exceeded your current quota/i,\r\n  /out of credits/i,\r\n  /payment required/i,\r\n  /organization has been (deactivated|disabled)/i,\r\n];\r\n\r\n/**\r\n * The opinionated classifier bundled with `RegistryOptions.runtimeFallback:\r\n * \"aggressive\"`. Walks the provider chain on any provider-side signal that\r\n * means \"try a different provider\" — not just the narrow default of\r\n * `ProviderUnavailableError`.\r\n *\r\n * Bundled empirically after BEPA (Plan 29), HomeSignal, and SalesCoach\r\n * (Plan 30 §R2 + §5.4) each rebuilt the same classifier by hand. The\r\n * common thread: the default `runtimeFallback: \"default\"` only walks on\r\n * `ProviderUnavailableError`, which let credit-exhaustion 400s and\r\n * empty-response 200s abort the chain in production and caused hours-long\r\n * outages before the consumer patched their own classifier.\r\n *\r\n * Walks on:\r\n *   1. `ProviderUnavailableError` — the default (5xx, network, generic).\r\n *   2. `RateLimitError` — try the next provider immediately, don't wait\r\n *      out the retry-after backoff on this one.\r\n *   3. `EmptyResponseError` — the adapter's own retries gave up; a\r\n *      different provider may not exhibit the pattern.\r\n *   4. `ContextWindowExceededError` — this provider can't handle the\r\n *      input; try a provider with a larger window.\r\n *   5. `BadRequestError` matching credit-exhaustion / account body\r\n *      patterns (see {@link AGGRESSIVE_CREDIT_EXHAUSTION_PATTERNS}).\r\n *   6. Any raw error with `status >= 500` (defensive for adapters that\r\n *      don't wrap 5xx as `ProviderUnavailableError`).\r\n *\r\n * Does NOT walk on:\r\n *   - `AuthenticationError` (401/403 — credential needs to be fixed).\r\n *   - Generic `BadRequestError` (malformed request — would fail everywhere).\r\n *   - `ContentPolicyViolationError` (content-filter — separate concern).\r\n *   - `BudgetExceededError` / `SessionBudgetExceededError` (port-internal\r\n *     gating; walking would defeat the gate).\r\n *   - `NoProvidersAvailableError` (chain-level; nothing more to try).\r\n *   - Errors that aren't `LLMPortError` and don't look like a 5xx.\r\n *\r\n * Composability: consumers who want everything this classifier does PLUS\r\n * one extra condition can wrap it inline (`(e) => aggressiveShouldFallback(e)\r\n * || myExtraCheck(e)`). Consumers who want to disable one of these\r\n * categories can wrap and short-circuit similarly.\r\n */\r\nexport function aggressiveShouldFallback(err: unknown): boolean {\r\n  // 1. Existing default (ProviderUnavailableError; covers 5xx via SDK wrap\r\n  //    and any other unknown-provider-error surface).\r\n  if (err instanceof ProviderUnavailableError) return true;\r\n\r\n  // 2. Rate limits — try the next provider rather than waiting out backoff.\r\n  if (err instanceof RateLimitError) return true;\r\n\r\n  // 3. Empty responses after starvation retries gave up.\r\n  if (err instanceof EmptyResponseError) return true;\r\n\r\n  // 4. Context window exceeded — try a larger-window provider.\r\n  if (err instanceof ContextWindowExceededError) return true;\r\n\r\n  // 5. Credit exhaustion / account-issue 400s. Match against the message\r\n  //    body patterns; genuine malformed-request 400s don't match and\r\n  //    correctly do NOT walk the chain.\r\n  if (err instanceof BadRequestError) {\r\n    // ContextWindowExceededError already handled in (4). This branch is\r\n    // for the OTHER BadRequestError shapes.\r\n    if (err instanceof ContextWindowExceededError) return true;\r\n    const message = String((err as Error).message ?? \"\");\r\n    for (const pattern of AGGRESSIVE_CREDIT_EXHAUSTION_PATTERNS) {\r\n      if (pattern.test(message)) return true;\r\n    }\r\n    return false;\r\n  }\r\n\r\n  // 6. Raw 5xx (defensive check for adapters that don't wrap 5xx as\r\n  //    ProviderUnavailableError). Guards against duck-typed status fields.\r\n  if (\r\n    typeof err === \"object\" &&\r\n    err !== null &&\r\n    \"status\" in err &&\r\n    typeof (err as { status: unknown }).status === \"number\" &&\r\n    (err as { status: number }).status >= 500\r\n  ) {\r\n    return true;\r\n  }\r\n\r\n  return false;\r\n}\r\n\r\n// ─── Canonical walk-table policy (alpha.28+, TD-LLMP-19) ──────────────\r\n\r\n/**\r\n * The canonical walk-table policy for `RegistryOptions.runtimeFallback:\r\n * \"default\"` starting alpha.28. Codifies the outcome of the 2026-07-21\r\n * cross-consumer review pass; supersedes hand-rolled per-consumer\r\n * classifiers (BEPA `src/ai/llm.ts:357-379`, ADW `registry.ts:170`, etc.)\r\n * that each mis-attributed one or more error classes.\r\n *\r\n * **Walks (transient / provider-varying):** the caller has a reasonable\r\n * chance of success on a different provider.\r\n *\r\n *   - `RateLimitError` — this provider's 429; another provider may have\r\n *     headroom.\r\n *   - `ServiceUnavailableError` (and subclasses `ProviderUnavailableError`,\r\n *     `EmptyResponseError`) — transient 5xx / SDK errors; walk.\r\n *   - `ContextWindowExceededError` — different providers have different\r\n *     context windows. A 150k-token request rejected by a 128k-window\r\n *     provider can succeed on a 400k-window provider.\r\n *   - `ContentPolicyViolationError` — different providers apply different\r\n *     content policies. Anthropic refuses some things OpenAI accepts and\r\n *     vice versa.\r\n *   - `ImageTooLargeError` — different attachment size limits per provider.\r\n *   - `ContentBlockUnsupportedError` — different multimodal capabilities.\r\n *   - `CreditExhaustionError` — this provider's billing headroom is spent;\r\n *     a different vendor's account is unaffected.\r\n *   - `ProviderMalformed400Error` — provider returned 400 with an empty\r\n *     or unparseable body (typically a provider-side bug on complex\r\n *     schemas); another provider may accept the same request.\r\n *\r\n * **Aborts (deterministic / same across providers):** walking wastes N\r\n * provider API calls with the same identical error at every hop.\r\n *\r\n *   - `AuthenticationError` — a truly wrong or expired credential does\r\n *     not fix on the next provider, and each hop leaks the failure across\r\n *     vendors.\r\n *   - Generic `BadRequestError` (unclassified 400) — most likely identical\r\n *     across providers (missing field, invalid JSON, malformed message\r\n *     role). Consumers who observe a specific provider-quirk 400 that\r\n *     walking recovers from should upgrade `wrapProviderError`'s\r\n *     classification to emit `ProviderMalformed400Error` (or another\r\n *     narrower typed class) instead of over-walking on the generic parent.\r\n *   - `MessagesRequiredError`, `EmptyMessagesError`, `MessagesConflictError`,\r\n *     `PromptRequiredError`, `NonContiguousSystemError` — contract-level\r\n *     violations. Deterministic. Walking is pure waste.\r\n *   - `InvalidImageUrlError` — universally invalid URL. Walking is waste.\r\n *   - `AdapterInternalError` — port library's own bug. Walking multiplies\r\n *     latency and cost, and misdirects operator diagnostic. The fix lives\r\n *     inside `@llm-ports`, not in another provider.\r\n *   - Unknown error classes — default is conservative: unclassified failures\r\n *     are, empirically, most likely identical across providers.\r\n *\r\n * Consumers wire this via `runtimeFallback: { shouldFallback:\r\n * defaultShouldFallback }` on `createRegistryFromEnv`. To extend (e.g. add\r\n * a consumer-specific typed class), wrap:\r\n *\r\n * ```ts\r\n * shouldFallback: (err) => defaultShouldFallback(err) || (err instanceof MyClass)\r\n * ```\r\n *\r\n * To narrow (e.g. abort on `ContentPolicyViolationError` because policy\r\n * variance is not useful for your workload), wrap:\r\n *\r\n * ```ts\r\n * shouldFallback: (err) =>\r\n *   err instanceof ContentPolicyViolationError\r\n *     ? false\r\n *     : defaultShouldFallback(err)\r\n * ```\r\n *\r\n * Distinct from `aggressiveShouldFallback` (bundled with\r\n * `runtimeFallback: \"aggressive\"`): the aggressive preset matches on\r\n * message-body patterns (via `AGGRESSIVE_CREDIT_EXHAUSTION_PATTERNS`)\r\n * rather than the typed `CreditExhaustionError` class; use aggressive when\r\n * an adapter has not yet upgraded to emit the typed class, and use\r\n * `defaultShouldFallback` when your adapter stack emits the typed classes\r\n * consistently.\r\n */\r\nexport function defaultShouldFallback(err: unknown): boolean {\r\n  // Fast pass-through for non-LLMPortError inputs: only walk on 5xx-shaped\r\n  // raw errors (defensive; adapters SHOULD have wrapped these already).\r\n  if (!(err instanceof LLMPortError)) {\r\n    if (\r\n      typeof err === \"object\" &&\r\n      err !== null &&\r\n      \"status\" in err &&\r\n      typeof (err as { status: unknown }).status === \"number\" &&\r\n      (err as { status: number }).status >= 500\r\n    ) {\r\n      return true;\r\n    }\r\n    return false;\r\n  }\r\n\r\n  // Walk-worthy classes.\r\n  if (err instanceof RateLimitError) return true;\r\n  if (err instanceof ServiceUnavailableError) return true;\r\n  if (err instanceof CreditExhaustionError) return true;\r\n  if (err instanceof ProviderMalformed400Error) return true;\r\n  if (err instanceof ContextWindowExceededError) return true;\r\n  if (err instanceof ContentPolicyViolationError) return true;\r\n  if (err instanceof ImageTooLargeError) return true;\r\n  if (err instanceof ContentBlockUnsupportedError) return true;\r\n\r\n  // Abort-worthy classes: explicit for readability + safety against\r\n  // future subclasses inheriting the wrong parent.\r\n  if (err instanceof AuthenticationError) return false;\r\n  if (err instanceof AdapterInternalError) return false;\r\n  if (err instanceof InvalidImageUrlError) return false;\r\n\r\n  // Contract-level errors (MessagesRequiredError, EmptyMessagesError,\r\n  // MessagesConflictError, PromptRequiredError, NonContiguousSystemError,\r\n  // ValidationError, ConfigError) all extend LLMPortError directly and\r\n  // fall through to the default-abort branch below.\r\n\r\n  // Any other LLMPortError (including generic BadRequestError that did not\r\n  // match a walk-worthy subclass above): abort.\r\n  return false;\r\n}\r\n","/**\r\n * Validation strategies for generateStructured() output that fails schema.\r\n *\r\n * The default is `retry-with-feedback` with maxAttempts=2: when validation\r\n * fails, the strategy injects the Zod errors into the next prompt and asks\r\n * the model to regenerate. In the originating production workflow, this\r\n * strategy achieves ~70% fix rate on the second attempt.\r\n *\r\n * See docs/concepts/validation-strategies for the full design rationale\r\n * and when to swap strategies.\r\n */\r\n\r\nimport type { z, ZodIssue } from \"zod\";\r\nimport { ValidationError } from \"./errors.js\";\r\n\r\n/**\r\n * Strategy applied when generated structured output fails schema validation.\r\n *\r\n * - `throw`:                     fail immediately with ValidationError.\r\n * - `retry-with-feedback`:       re-prompt the model with the Zod errors\r\n *                                injected into the next user message. Default.\r\n * - `fallback-to-next-provider`: skip to the next provider in the task chain\r\n *                                (the registry handles the actual fallback).\r\n * - `custom`:                    user-provided handler decides what to do.\r\n */\r\nexport type ValidationStrategy =\r\n  | { kind: \"throw\" }\r\n  | {\r\n      kind: \"retry-with-feedback\";\r\n      maxAttempts: number;\r\n      includeOriginalError: boolean;\r\n    }\r\n  | { kind: \"fallback-to-next-provider\" }\r\n  | {\r\n      kind: \"custom\";\r\n      handler: <T>(ctx: ValidationFailureContext<T>) => Promise<T>;\r\n    };\r\n\r\nexport interface ValidationFailureContext<T> {\r\n  attempt: number;\r\n  schema: z.ZodType<T>;\r\n  rawOutput: unknown;\r\n  issues: ZodIssue[];\r\n  /** Re-invoke the model with a (possibly modified) prompt. */\r\n  retry: (correctionMessage?: string) => Promise<T>;\r\n}\r\n\r\n/** Default strategy: retry twice with the validation errors fed back. */\r\nexport const DEFAULT_VALIDATION_STRATEGY: ValidationStrategy = {\r\n  kind: \"retry-with-feedback\",\r\n  maxAttempts: 2,\r\n  includeOriginalError: true,\r\n};\r\n\r\n/**\r\n * Build a correction prompt from Zod issues. Adapters call this when\r\n * implementing retry-with-feedback to construct the re-prompt.\r\n */\r\nexport function buildCorrectionPrompt(issues: ZodIssue[]): string {\r\n  const bullets = issues\r\n    .map((issue) => {\r\n      const path = issue.path.length === 0 ? \"<root>\" : issue.path.join(\".\");\r\n      return `- ${path}: ${issue.message}`;\r\n    })\r\n    .join(\"\\n\");\r\n  return `Your previous response failed validation:\\n${bullets}\\n\\nPlease regenerate the response with valid output that conforms to the schema.`;\r\n}\r\n\r\n/**\r\n * Helper for adapters: throw the canonical ValidationError when the strategy\r\n * has exhausted attempts or kind is \"throw\".\r\n */\r\nexport function failValidation(issues: ZodIssue[], attempts: number): never {\r\n  throw new ValidationError(issues, attempts);\r\n}\r\n","/**\r\n * Deprecation-warning emitter with dedup + suppression + custom handler.\r\n *\r\n * A generic surface consumers and library authors reuse whenever a\r\n * public field, method, or configuration is deprecated on an active\r\n * release line. Every unique deprecation \"where\" produces at most one\r\n * warning per Registry instance; suppression is per-Registry;\r\n * structured logging routes through the optional `handler`.\r\n *\r\n * Renamed and generalized in `0.1.0-alpha.27` from the field-specific\r\n * `warnDeprecatedLegacyInput(state, method)` shipped in alpha.26. The\r\n * runtime behavior (method-only dedup, suppression, handler routing)\r\n * is identical; the new signature accepts a details object instead of\r\n * just a method name.\r\n */\r\n\r\n/** Per-Registry deprecation-warning state. */\r\nexport interface WarningState {\r\n  /** When true, no warnings fire regardless of the dedup set. */\r\n  suppressed: boolean;\r\n  /** Set of `where` keys already warned for. */\r\n  warned: Set<string>;\r\n  /**\r\n   * Optional replacement for `console.warn`. Consumers wanting structured\r\n   * logging can supply a function that receives the warning message.\r\n   * Defaults to `console.warn`.\r\n   */\r\n  handler?: (message: string) => void;\r\n}\r\n\r\n/** Fresh warning state for a Registry instance. */\r\nexport function createWarningState(opts?: {\r\n  suppressed?: boolean;\r\n  handler?: (message: string) => void;\r\n}): WarningState {\r\n  const state: WarningState = {\r\n    suppressed: !!opts?.suppressed,\r\n    warned: new Set<string>(),\r\n  };\r\n  if (opts?.handler) state.handler = opts.handler;\r\n  return state;\r\n}\r\n\r\n/**\r\n * Descriptor for a deprecation warning. `where` is the dedup key; every\r\n * unique `where` produces at most one warning per WarningState. Consumers\r\n * of the library and library authors both use this surface.\r\n */\r\nexport interface DeprecationDetails {\r\n  /**\r\n   * Human-readable name of the deprecated surface. E.g.\r\n   * `\"'onMissing' as a function callback\"` or\r\n   * `\"'perAttemptTimeoutMs' option\"`.\r\n   */\r\n  what: string;\r\n  /**\r\n   * Dedup key AND display location. E.g. `\"createVersionedStore\"` or\r\n   * `\"streamText\"`. Every unique `where` value produces at most one\r\n   * warning per WarningState.\r\n   */\r\n  where: string;\r\n  /**\r\n   * Version the deprecated surface will be removed in. E.g.\r\n   * `\"alpha.35\"`. Optional but recommended for consumer planning.\r\n   */\r\n  removalVersion?: string;\r\n  /**\r\n   * URL to the migration guide for this specific deprecation. Optional\r\n   * but recommended.\r\n   */\r\n  migrationUrl?: string;\r\n}\r\n\r\n/**\r\n * Emit a deprecation warning through the shared WarningState. Cheap on\r\n * repeat calls: only the O(1) Set lookup runs after the first warning\r\n * per unique `where`. Respects `suppressed` and routes through the\r\n * optional `handler` (default `console.warn`).\r\n *\r\n * Consumers of `@llm-ports/core` who need to fire deprecation warnings\r\n * from custom code paths (adapter authors, downstream wrapper\r\n * libraries) can call this with a WarningState acquired from the\r\n * Registry: `warnDeprecated(registry.warningState, { what, where, ... })`.\r\n *\r\n * Generalized in `0.1.0-alpha.27` from the field-specific\r\n * `warnDeprecatedLegacyInput` that shipped in alpha.26.\r\n */\r\nexport function warnDeprecated(state: WarningState, details: DeprecationDetails): void {\r\n  if (state.suppressed) return;\r\n  if (state.warned.has(details.where)) return;\r\n  state.warned.add(details.where);\r\n  const parts = [`[llm-ports] DEPRECATED: ${details.what} on ${details.where}`];\r\n  if (details.removalVersion) {\r\n    parts.push(`will be removed in ${details.removalVersion}.`);\r\n  } else {\r\n    parts.push(`is deprecated.`);\r\n  }\r\n  if (details.migrationUrl) parts.push(`See ${details.migrationUrl}.`);\r\n  (state.handler ?? console.warn.bind(console))(parts.join(\" \"));\r\n}\r\n","/**\r\n * Env config parser for the registry.\r\n *\r\n * Reads `LLM_PROVIDER_*` and `LLM_TASK_ROUTE_*` entries from a record\r\n * (typically `process.env`) and returns a structured config the registry\r\n * uses for routing.\r\n *\r\n * Format:\r\n *   LLM_PROVIDER_<ALIAS>=<adapter>|<modelId>|<gating>[,<gating>...]\r\n *   LLM_TASK_ROUTE_<TASK>=<alias>[,<alias>...]\r\n *\r\n * Gating tokens (alpha.20):\r\n *   req:N/{minute|hour|session}                       -> request-count limit\r\n *   cost:N/{minute|hour|day|month|session}            -> USD limit\r\n *   total_tokens:N/session                            -> tokens per CostSession\r\n *   tool_calls:N/session                              -> tool calls per CostSession\r\n *   unlimited                                         -> no gating (useful for local Ollama)\r\n *\r\n * Backwards compatible: `req:N/hour` and `cost:N/{hour|day|month}` from\r\n * alpha.19 keep working unchanged. `req:N/hour` still writes the legacy\r\n * `requestsPerHour` field for backend backwards compat.\r\n *\r\n * See docs/concepts/task-routing for the full design rationale.\r\n */\r\n\r\nimport type { BudgetLimit, CostLimit, SessionGrainLimits } from \"../budget/types.js\";\r\nimport { ConfigError } from \"../errors.js\";\r\n\r\nexport interface ProviderEntry {\r\n  /** User-chosen alias (lowercase, derived from env var name). */\r\n  alias: string;\r\n  /** Which adapter implementation this alias uses (\"anthropic\", \"openai\", \"ollama\", \"vercel\"). */\r\n  adapter: string;\r\n  /** Provider-specific model id. */\r\n  modelId: string;\r\n  budgetLimit: BudgetLimit;\r\n  costLimit: CostLimit;\r\n  /** Session-grain limits (token + tool-call ceilings). Enforced by CostSession. (alpha.20+) */\r\n  sessionLimits?: SessionGrainLimits;\r\n}\r\n\r\nexport interface RegistryConfig {\r\n  providers: Record<string, ProviderEntry>;\r\n  /** Maps task type -> ordered fallback chain of provider aliases. */\r\n  taskRoutes: Record<string, string[]>;\r\n}\r\n\r\nexport interface ParseConfigOptions {\r\n  /** Env var prefix. Default: \"LLM_\". */\r\n  envPrefix?: string;\r\n  /** Source record. Default: process.env. */\r\n  env?: Record<string, string | undefined>;\r\n}\r\n\r\nexport function parseRegistryConfig(opts: ParseConfigOptions = {}): RegistryConfig {\r\n  const prefix = opts.envPrefix ?? \"LLM_\";\r\n  const env = opts.env ?? (typeof process !== \"undefined\" ? process.env : {});\r\n\r\n  const providers: Record<string, ProviderEntry> = {};\r\n  const taskRoutes: Record<string, string[]> = {};\r\n\r\n  for (const [key, rawValue] of Object.entries(env)) {\r\n    if (!rawValue) continue;\r\n    const value = rawValue.trim();\r\n\r\n    if (key.startsWith(`${prefix}PROVIDER_`)) {\r\n      const alias = key.slice(`${prefix}PROVIDER_`.length).toLowerCase().replace(/_/g, \"-\");\r\n      const parts = value.split(\"|\");\r\n      if (parts.length < 3) {\r\n        throw new ConfigError(\r\n          `Invalid ${key}: expected \"<adapter>|<modelId>|<gating>[,<gating>...]\", got \"${value}\"`,\r\n        );\r\n      }\r\n      const [adapter, modelId, gatingStr] = parts;\r\n      const { budgetLimit, costLimit, sessionLimits } = parseGating(gatingStr ?? \"unlimited\", key);\r\n      providers[alias] = {\r\n        alias,\r\n        adapter: adapter!.trim(),\r\n        modelId: modelId!.trim(),\r\n        budgetLimit,\r\n        costLimit,\r\n        ...(sessionLimits ? { sessionLimits } : {}),\r\n      };\r\n    } else if (key.startsWith(`${prefix}TASK_ROUTE_`)) {\r\n      const taskName = key.slice(`${prefix}TASK_ROUTE_`.length).toLowerCase().replace(/_/g, \"-\");\r\n      const chain = value\r\n        .split(\",\")\r\n        .map((s) => s.trim())\r\n        .filter((s) => s.length > 0);\r\n      if (chain.length === 0) {\r\n        throw new ConfigError(`Invalid ${key}: empty fallback chain`);\r\n      }\r\n      taskRoutes[taskName] = chain;\r\n    }\r\n  }\r\n\r\n  return { providers, taskRoutes };\r\n}\r\n\r\n/**\r\n * Parse a comma-separated gating string into BudgetLimit + CostLimit +\r\n * SessionGrainLimits. Examples:\r\n *\r\n *   \"req:200/hour\"                         -> request-only\r\n *   \"cost:100/day\"                         -> cost-only\r\n *   \"req:30/minute,cost:50/day\"            -> minute-grain rate limit + daily USD cap\r\n *   \"req:500/hour,cost:50/day\"             -> both apply (first to trip blocks)\r\n *   \"cost:1.00/session,total_tokens:50000/session,tool_calls:8/session\"\r\n *                                          -> session-grain ceilings (enforced by CostSession)\r\n *   \"unlimited\"                            -> no gating\r\n *\r\n * Backwards compatible: `req:N/hour` from alpha.19 still writes the legacy\r\n * `requestsPerHour` field so existing backend wiring keeps working.\r\n */\r\nfunction parseGating(input: string, envKey: string): {\r\n  budgetLimit: BudgetLimit;\r\n  costLimit: CostLimit;\r\n  sessionLimits?: SessionGrainLimits;\r\n} {\r\n  let budgetLimit: BudgetLimit = { kind: \"unlimited\" };\r\n  let costLimit: CostLimit = { kind: \"unlimited\" };\r\n  let sessionLimits: SessionGrainLimits | undefined;\r\n\r\n  if (input.trim() === \"unlimited\") {\r\n    return { budgetLimit, costLimit };\r\n  }\r\n\r\n  const tokens = input\r\n    .split(\",\")\r\n    .map((t) => t.trim())\r\n    .filter((t) => t.length > 0);\r\n\r\n  function ensureRequests(): Extract<BudgetLimit, { kind: \"requests\" }> {\r\n    if (budgetLimit.kind !== \"requests\") {\r\n      budgetLimit = { kind: \"requests\" };\r\n    }\r\n    return budgetLimit;\r\n  }\r\n\r\n  function ensureUsd(): Extract<CostLimit, { kind: \"usd\" }> {\r\n    if (costLimit.kind !== \"usd\") {\r\n      costLimit = { kind: \"usd\" };\r\n    }\r\n    return costLimit;\r\n  }\r\n\r\n  function ensureSession(): SessionGrainLimits {\r\n    if (!sessionLimits) sessionLimits = {};\r\n    return sessionLimits;\r\n  }\r\n\r\n  for (const token of tokens) {\r\n    if (token.startsWith(\"req:\")) {\r\n      const m = token.match(/^req:(\\d+)\\/(minute|hour|session)$/);\r\n      if (!m) {\r\n        throw new ConfigError(\r\n          `Invalid request gating in ${envKey}: \"${token}\" (expected req:N/{minute|hour|session})`,\r\n        );\r\n      }\r\n      const amount = parseInt(m[1]!, 10);\r\n      const window = m[2] as \"minute\" | \"hour\" | \"session\";\r\n      const next = ensureRequests();\r\n      if (window === \"minute\") next.perMinute = amount;\r\n      else if (window === \"hour\") {\r\n        next.perHour = amount;\r\n        // Backwards-compat: legacy field still populated so older backends\r\n        // that haven't been upgraded to read `perHour` keep working.\r\n        next.requestsPerHour = amount;\r\n      } else if (window === \"session\") next.perSession = amount;\r\n    } else if (token.startsWith(\"cost:\")) {\r\n      const m = token.match(/^cost:(\\d+(?:\\.\\d+)?)\\/(minute|hour|day|month|session)$/);\r\n      if (!m) {\r\n        throw new ConfigError(\r\n          `Invalid cost gating in ${envKey}: \"${token}\" (expected cost:N/{minute|hour|day|month|session})`,\r\n        );\r\n      }\r\n      const amount = parseFloat(m[1]!);\r\n      const window = m[2] as \"minute\" | \"hour\" | \"day\" | \"month\" | \"session\";\r\n      const next = ensureUsd();\r\n      if (window === \"minute\") next.perMinute = amount;\r\n      else if (window === \"hour\") next.perHour = amount;\r\n      else if (window === \"day\") next.perDay = amount;\r\n      else if (window === \"month\") next.perMonth = amount;\r\n      else if (window === \"session\") next.perSession = amount;\r\n    } else if (token.startsWith(\"total_tokens:\")) {\r\n      const m = token.match(/^total_tokens:(\\d+)\\/session$/);\r\n      if (!m) {\r\n        throw new ConfigError(\r\n          `Invalid session-grain gating in ${envKey}: \"${token}\" (expected total_tokens:N/session)`,\r\n        );\r\n      }\r\n      ensureSession().totalTokensPerSession = parseInt(m[1]!, 10);\r\n    } else if (token.startsWith(\"tool_calls:\")) {\r\n      const m = token.match(/^tool_calls:(\\d+)\\/session$/);\r\n      if (!m) {\r\n        throw new ConfigError(\r\n          `Invalid session-grain gating in ${envKey}: \"${token}\" (expected tool_calls:N/session)`,\r\n        );\r\n      }\r\n      ensureSession().toolCallsPerSession = parseInt(m[1]!, 10);\r\n    } else if (token === \"unlimited\") {\r\n      // explicit unlimited; do nothing\r\n    } else {\r\n      throw new ConfigError(`Unknown gating token in ${envKey}: \"${token}\"`);\r\n    }\r\n  }\r\n\r\n  return sessionLimits ? { budgetLimit, costLimit, sessionLimits } : { budgetLimit, costLimit };\r\n}\r\n","/**\n * Session-scoped cost gating.\n *\n * Wraps an LLMPort with session-level ceilings independent of the per-provider\n * windowed gates. Designed for continuous-call workloads (screen capture, OCR\n * loops, multi-step agents) where a single stuck-open session can burn\n * arbitrary dollars / tokens / tool calls.\n *\n * Usage:\n *\n *   const session = registry.openCostSession({ budgetUSD: 0.50 });\n *   const llm = session.getPort();\n *   try {\n *     for (const frame of screenCaptureFrames) {\n *       await llm.generateText({ taskType: \"screen_analyze\", prompt: [...] });\n *     }\n *   } finally {\n *     console.log(\"session spent:\", session.totalSpentUSD());\n *     session.close();\n *   }\n *\n * Throws `SessionBudgetExceededError` mid-loop when a cap is reached. The\n * per-provider windowed gates still apply on top — session ceilings are a\n * hard backstop, not a replacement.\n *\n * alpha.20 additions:\n *   - tokensUsed() / toolCallsMade() / requestsMade() helpers.\n *   - Optional `maxTokens`, `maxToolCalls`, `maxRequests` ceilings that mirror\n *     the env-driven `total_tokens:N/session`, `tool_calls:N/session`, and\n *     `req:N/session` gating tokens. The error thrown is still\n *     `SessionBudgetExceededError` so existing catch-blocks keep working;\n *     the `reason` field distinguishes which cap tripped.\n */\n\nimport type {\n  AgentResult,\n  GenerateStructuredOptions,\n  GenerateStructuredResult,\n  GenerateTextOptions,\n  GenerateTextResult,\n  LLMPort,\n  RunAgentOptions,\n  StreamStructuredOptions,\n  StreamTextOptions,\n} from \"../ports/llm-port.js\";\nimport { SessionBudgetExceededError } from \"../errors.js\";\n\nexport interface OpenCostSessionOptions {\n  /** Hard USD cap for this session. Required. */\n  budgetUSD: number;\n  /**\n   * Optional client-supplied session ID. If omitted, a timestamp-keyed id\n   * is generated. The ID appears in `SessionBudgetExceededError.sessionId`\n   * and is useful for log correlation across multi-step flows.\n   */\n  sessionId?: string;\n  /**\n   * Optional ceiling on total tokens used in this session (input + output,\n   * across every call). Maps to the `total_tokens:N/session` env gating\n   * token. Tripping this throws `SessionBudgetExceededError`. (alpha.20+)\n   */\n  maxTokens?: number;\n  /**\n   * Optional ceiling on tool / function calls made by `runAgent` in this\n   * session. Maps to the `tool_calls:N/session` env gating token. Tripping\n   * this throws `SessionBudgetExceededError`. (alpha.20+)\n   */\n  maxToolCalls?: number;\n  /**\n   * Optional ceiling on requests made in this session (every call counts,\n   * including streaming). Maps to the `req:N/session` env gating token.\n   * Tripping this throws `SessionBudgetExceededError`. (alpha.20+)\n   */\n  maxRequests?: number;\n}\n\n/**\n * Handle returned by `Registry.openCostSession`.\n */\nexport class CostSession {\n  public readonly id: string;\n  public readonly budgetUSD: number;\n  public readonly maxTokens?: number;\n  public readonly maxToolCalls?: number;\n  public readonly maxRequests?: number;\n  private spentUSD = 0;\n  private tokens = 0;\n  private toolCalls = 0;\n  private requests = 0;\n  private closed = false;\n\n  constructor(\n    private readonly underlying: LLMPort,\n    opts: OpenCostSessionOptions,\n  ) {\n    if (!Number.isFinite(opts.budgetUSD) || opts.budgetUSD <= 0) {\n      throw new Error(\n        `CostSession requires a positive finite budgetUSD; got ${opts.budgetUSD}`,\n      );\n    }\n    this.budgetUSD = opts.budgetUSD;\n    this.id = opts.sessionId ?? `cs-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;\n    if (opts.maxTokens !== undefined) this.maxTokens = opts.maxTokens;\n    if (opts.maxToolCalls !== undefined) this.maxToolCalls = opts.maxToolCalls;\n    if (opts.maxRequests !== undefined) this.maxRequests = opts.maxRequests;\n  }\n\n  totalSpentUSD(): number {\n    return this.spentUSD;\n  }\n\n  remainingUSD(): number {\n    return Math.max(0, this.budgetUSD - this.spentUSD);\n  }\n\n  /** Total tokens billed (input + output) across all calls. (alpha.20+) */\n  tokensUsed(): number {\n    return this.tokens;\n  }\n\n  /** Tool / function calls made by runAgent across the session. (alpha.20+) */\n  toolCallsMade(): number {\n    return this.toolCalls;\n  }\n\n  /** Total port calls made in this session. (alpha.20+) */\n  requestsMade(): number {\n    return this.requests;\n  }\n\n  /**\n   * Returns an LLMPort proxy that tracks every call's cost / tokens / tool\n   * calls / request count against this session. Before invoking the\n   * underlying port, the proxy checks every ceiling; the first one that\n   * would be exceeded throws `SessionBudgetExceededError`.\n   */\n  getPort(): LLMPort {\n    // eslint-disable-next-line @typescript-eslint/no-this-alias\n    const session = this;\n    const ensureOpen = (): void => {\n      if (session.closed) {\n        throw new Error(\n          `CostSession \"${session.id}\" is closed; cannot make further calls.`,\n        );\n      }\n    };\n    const checkBefore = (): void => {\n      ensureOpen();\n      if (session.spentUSD >= session.budgetUSD) {\n        throw new SessionBudgetExceededError(\n          session.id,\n          session.budgetUSD,\n          session.spentUSD,\n        );\n      }\n      if (session.maxTokens !== undefined && session.tokens >= session.maxTokens) {\n        throw new SessionBudgetExceededError(\n          session.id,\n          session.maxTokens,\n          session.tokens,\n          `tokens (${session.tokens} >= ${session.maxTokens})`,\n        );\n      }\n      if (\n        session.maxToolCalls !== undefined &&\n        session.toolCalls >= session.maxToolCalls\n      ) {\n        throw new SessionBudgetExceededError(\n          session.id,\n          session.maxToolCalls,\n          session.toolCalls,\n          `tool_calls (${session.toolCalls} >= ${session.maxToolCalls})`,\n        );\n      }\n      if (\n        session.maxRequests !== undefined &&\n        session.requests >= session.maxRequests\n      ) {\n        throw new SessionBudgetExceededError(\n          session.id,\n          session.maxRequests,\n          session.requests,\n          `requests (${session.requests} >= ${session.maxRequests})`,\n        );\n      }\n    };\n    const recordResult = (\n      cost: { totalUSD: number },\n      usage?: { totalTokens?: number },\n      toolCalls?: number,\n    ): void => {\n      session.spentUSD += cost.totalUSD;\n      session.requests += 1;\n      if (usage?.totalTokens !== undefined) session.tokens += usage.totalTokens;\n      if (toolCalls !== undefined) session.toolCalls += toolCalls;\n    };\n\n    return {\n      async generateText(options: GenerateTextOptions): Promise<GenerateTextResult> {\n        checkBefore();\n        const result = await session.underlying.generateText(options);\n        recordResult(result.cost, result.usage);\n        return result;\n      },\n      async generateStructured<T>(\n        options: GenerateStructuredOptions<T>,\n      ): Promise<GenerateStructuredResult<T>> {\n        checkBefore();\n        const result = await session.underlying.generateStructured(options);\n        recordResult(result.cost, result.usage);\n        return result;\n      },\n      async *streamText(options: StreamTextOptions): AsyncIterable<string> {\n        checkBefore();\n        // Streaming doesn't return aggregated cost/usage; the request counts\n        // toward perRequest gates but tokens / cost can't update mid-stream.\n        session.requests += 1;\n        yield* session.underlying.streamText(options);\n      },\n      async *streamStructured<T>(\n        options: StreamStructuredOptions<T>,\n      ): AsyncIterable<Partial<T>> {\n        checkBefore();\n        session.requests += 1;\n        yield* session.underlying.streamStructured(options);\n      },\n      async runAgent(options: RunAgentOptions): Promise<AgentResult> {\n        checkBefore();\n        const result = await session.underlying.runAgent(options);\n        recordResult(result.cost, result.usage, result.toolCalls.length);\n        return result;\n      },\n    };\n  }\n\n  /**\n   * Close the session. After `close()`, calls through any port previously\n   * returned by `getPort()` throw an error.\n   *\n   * Returns the total USD spent during the session — useful for logging\n   * or charging back to a tenant.\n   */\n  close(): number {\n    this.closed = true;\n    return this.spentUSD;\n  }\n}\n","/**\r\n * Registry — selects an adapter for a given task type, applies budget/cost gating,\r\n * walks fallback chains on failure, and exposes the unified LLMPort surface.\r\n *\r\n * This implementation is intentionally minimal in v0.1:\r\n *  - Adapters are registered by name (matching the env config's adapter token).\r\n *  - selectModel(taskType) walks the configured fallback chain and returns the\r\n *    first adapter whose budget allows the call.\r\n *  - getPort() returns an LLMPort proxy whose every method invokes selectModel.\r\n *  - The registry exposes both LLMPort and EmbeddingsPort (when supported by adapters).\r\n *\r\n * Note: this skeleton focuses on the routing/gating contract. Adapter implementations\r\n * land in their own packages (Week 2 onwards) and plug in here.\r\n */\r\n\r\nimport type {\r\n  AgentResult,\r\n  ArtifactRef,\r\n  GenerateStructuredOptions,\r\n  GenerateStructuredResult,\r\n  GenerateTextOptions,\r\n  GenerateTextResult,\r\n  LLMPort,\r\n  RunAgentOptions,\r\n  StreamStructuredOptions,\r\n  StreamTextOptions,\r\n} from \"../ports/llm-port.js\";\r\nimport {\r\n  attachStreamCompleteCallback,\r\n  deriveCacheHit,\r\n  emitCacheHit,\r\n  emitCost,\r\n  emitFallback,\r\n  emitTokenUsage,\r\n  type ObservabilityHooks,\r\n  type StreamCompleteCallback,\r\n} from \"../observability.js\";\r\nimport type {\r\n  BatchEmbeddingOptions,\r\n  BatchEmbeddingResult,\r\n  EmbeddingOptions,\r\n  EmbeddingResult,\r\n  EmbeddingsPort,\r\n} from \"../ports/embeddings-port.js\";\r\nimport type {\r\n  BudgetBackend,\r\n  BudgetScopeRef,\r\n  CostBackend,\r\n  ModelPricing,\r\n} from \"../budget/types.js\";\r\nimport { InMemoryBudget, InMemoryCost } from \"../budget/memory.js\";\r\nimport {\r\n  DEFAULT_VALIDATION_STRATEGY,\r\n  type ValidationStrategy,\r\n} from \"../validation.js\";\r\nimport {\r\n  aggressiveShouldFallback,\r\n  ConfigError,\r\n  EmptyMessagesError,\r\n  MessagesRequiredError,\r\n  NoProvidersAvailableError,\r\n  ProviderUnavailableError,\r\n} from \"../errors.js\";\r\nimport { createWarningState, type WarningState } from \"../utils/deprecation.js\";\r\nimport type { LLMMessage } from \"../ports/llm-port.js\";\r\nimport type { ProviderEntry, RegistryConfig } from \"./config.js\";\r\nimport { parseRegistryConfig } from \"./config.js\";\r\nimport { CostSession, type OpenCostSessionOptions } from \"./cost-session.js\";\r\n\r\n// ─── Adapter contract used internally by the registry ────────────────\r\n\r\n/**\r\n * What an adapter passes to the registry on registration. The adapter\r\n * provides factories that, given a model id, return a configured port instance.\r\n *\r\n * Why factories instead of pre-built ports: the registry knows the model id\r\n * per-call (from env config), so the adapter must defer instantiation until\r\n * model selection time.\r\n */\r\nexport interface AdapterRegistration {\r\n  /** Adapter name, must match the env config's `<adapter>` token. */\r\n  name: string;\r\n  /** Build an LLMPort for a specific model. Required for chat-capable adapters. */\r\n  createLLMPort?: (modelId: string, alias: string) => LLMPort;\r\n  /** Build an EmbeddingsPort for a specific model. Optional. */\r\n  createEmbeddingsPort?: (modelId: string, alias: string) => EmbeddingsPort;\r\n  /** Pricing table this adapter ships, keyed by modelId. */\r\n  pricing: Record<string, ModelPricing>;\r\n}\r\n\r\n// ─── Registry options ────────────────────────────────────────────────\r\n\r\nexport interface RegistryOptions {\r\n  envPrefix?: string;\r\n  env?: Record<string, string | undefined>;\r\n  /** Adapters keyed by their name (must match env config tokens). */\r\n  adapters: Record<string, AdapterRegistration>;\r\n  budget?: BudgetBackend;\r\n  cost?: CostBackend;\r\n  validationStrategy?: ValidationStrategy;\r\n  /** Override pricing for specific model ids (key = modelId). */\r\n  pricingOverrides?: Record<string, ModelPricing>;\r\n  /**\r\n   * Runtime-error fallback configuration. When a call to the first viable\r\n   * provider in a task's fallback chain throws an error matching `catchClass`,\r\n   * the registry walks to the next viable provider and retries — without the\r\n   * caller having to catch and re-route themselves.\r\n   *\r\n   * Default: walks on `ProviderUnavailableError` only (the safest class —\r\n   * covers 5xx, network errors, rate-limit-style 429s the SDK wraps).\r\n   *\r\n   * Set to `\"none\"` to disable runtime fallback entirely (v0.1 behavior;\r\n   * caller catches `ProviderUnavailableError` and routes manually).\r\n   *\r\n   * Set to a custom predicate for finer control (e.g. walk on\r\n   * `EmptyResponseError` too, or skip 429s and let the SDK's own backoff\r\n   * handle them).\r\n   *\r\n   * Added in `0.1.0-alpha.7`.\r\n   *\r\n   * The `\"aggressive\"` preset was added in `0.1.0-alpha.25` (LP-REQ-01).\r\n   * It bundles the opinionated classifier three consumers had rebuilt by\r\n   * hand (BEPA Plan 29, HomeSignal, SalesCoach Plan 30). See\r\n   * {@link aggressiveShouldFallback} for the full matrix; the summary is\r\n   * \"walk on RateLimitError, EmptyResponseError, ContextWindowExceededError,\r\n   * BadRequestError with credit-exhaustion body patterns, and raw 5xx status\r\n   * codes — in addition to the default ProviderUnavailableError\".\r\n   */\r\n  runtimeFallback?:\r\n    | \"default\" // walk on ProviderUnavailableError\r\n    | \"aggressive\" // walk on any provider-side signal (alpha.25+, LP-REQ-01)\r\n    | \"none\" // disable; caller handles errors\r\n    | { shouldFallback: (err: unknown) => boolean };\r\n  /**\r\n   * OTel-aligned observability hooks. Optional; each hook is independent.\r\n   * Hooks are fire-and-forget — errors thrown by hook callbacks are swallowed\r\n   * so observability instrumentation can't break inference.\r\n   *\r\n   * Coverage in this release (alpha.21):\r\n   *   - onCost / onTokenUsage / onCacheHit : emitted by the Registry on every\r\n   *     successful call against generateText, generateStructured, runAgent\r\n   *     (and on each cache-hit response). Streaming methods do not emit cost\r\n   *     yet (streamed cost surfacing is a follow-up, mirroring the alpha.7\r\n   *     `walkChain` \"no cost to record at stream-creation\" behavior).\r\n   *   - onFallback : emitted by the Registry's `walkChain` whenever it\r\n   *     advances from one provider alias to the next due to runtime error,\r\n   *     budget rejection, or empty response. Per-call only; not emitted for\r\n   *     the initial selection or for `forceProviderAlias` calls (which by\r\n   *     contract don't fall back).\r\n   *   - onValidationRetry : hook type defined but not Registry-emitted in\r\n   *     alpha.21. Consumers wanting validation-retry observability should\r\n   *     use the adapter's existing `onRetry` hook and filter on\r\n   *     `reason === \"validation-feedback\"`. Registry-level emission is the\r\n   *     alpha.22 follow-up.\r\n   *\r\n   * Added in 0.1.0-alpha.21. Aligned with OpenTelemetry's `gen_ai.*` semantic\r\n   * conventions where applicable; events are designed to map cleanly onto\r\n   * spans and metrics in a downstream OTel pipeline.\r\n   */\r\n  observability?: ObservabilityHooks;\r\n  /**\r\n   * Per-attempt timeout, in milliseconds. When set, every provider attempt\r\n   * within `walkChain` is wrapped in an `AbortController` that fires after\r\n   * this many milliseconds. The abort propagates to the adapter's HTTP\r\n   * client; the adapter throws `ProviderUnavailableError`; the Registry's\r\n   * `shouldFallback` predicate catches it and walks to the next provider\r\n   * with a fresh timer.\r\n   *\r\n   * Use case: a reasoning model that grinds on hidden chain-of-thought can\r\n   * otherwise hang for minutes before the AbortSignal is the only escape.\r\n   * Set a tight per-attempt cap (e.g. 30000) and let the chain fall back to\r\n   * a fast non-reasoning provider after the cap fires. Per-attempt, not\r\n   * chain-wide — each provider gets its own budget.\r\n   *\r\n   * Composes with a caller-supplied `signal` on the call options: BOTH the\r\n   * timeout and the caller's abort fire the same wrapped controller. The\r\n   * shorter trigger wins.\r\n   *\r\n   * Default: undefined (no timeout). When set, applies to `generateText`,\r\n   * `generateStructured`, and `runAgent` walkChain attempts. Stream methods\r\n   * use the same timeout for stream-creation only (not mid-stream — once a\r\n   * stream opens, mid-stream timeout is a per-chunk policy that lives in\r\n   * the consumer's `for await`).\r\n   *\r\n   * Added in 0.1.0-alpha.23.\r\n   */\r\n  perAttemptTimeoutMs?: number;\r\n  /**\r\n   * When true, suppress the alpha.26+ deprecation warnings that fire when a\r\n   * call uses the legacy `{instructions, prompt}` shape instead of the\r\n   * canonical `messages: LLMMessage[]`. The legacy path still works during\r\n   * the alpha.26 window; suppression is a per-Registry opt-out for\r\n   * consumers who have read the migration guide and are working through\r\n   * the migration incrementally.\r\n   *\r\n   * Removed in alpha.27, when the legacy fields go with it.\r\n   *\r\n   * Added in 0.1.0-alpha.26.\r\n   */\r\n  suppressDeprecationWarnings?: boolean;\r\n  /**\r\n   * Optional replacement for the deprecation warning's default emitter\r\n   * (`console.warn`). Consumers wanting structured logging can supply a\r\n   * function that receives the fully-formatted warning message. Removed\r\n   * in alpha.27.\r\n   *\r\n   * Added in 0.1.0-alpha.26.\r\n   */\r\n  deprecationWarningHandler?: (message: string) => void;\r\n}\r\n\r\n// ─── Selection result ────────────────────────────────────────────────\r\n\r\nexport interface ModelSelection {\r\n  alias: string;\r\n  adapter: AdapterRegistration;\r\n  modelId: string;\r\n  pricing: ModelPricing;\r\n  port?: LLMPort;\r\n  embeddingsPort?: EmbeddingsPort;\r\n}\r\n\r\n// ─── The registry ────────────────────────────────────────────────────\r\n\r\nexport class Registry {\r\n  public readonly config: RegistryConfig;\r\n  public readonly budget: BudgetBackend;\r\n  public readonly cost: CostBackend;\r\n  public readonly validationStrategy: ValidationStrategy;\r\n  /**\r\n   * Returns true if an error should cause the registry to walk to the next\r\n   * viable provider in the fallback chain. See `RegistryOptions.runtimeFallback`.\r\n   */\r\n  public readonly shouldFallback: (err: unknown) => boolean;\r\n  /** OTel-aligned observability hooks, set at construction. Read by `walkChain` + `RegistryPort`. */\r\n  public readonly observability: ObservabilityHooks;\r\n  /** Per-attempt timeout in ms, applied by `walkChain` to each provider attempt. (alpha.23+) */\r\n  public readonly perAttemptTimeoutMs: number | undefined;\r\n  /** Deprecation-warning dedup state for the alpha.26+ legacy `{instructions, prompt}` path. */\r\n  public readonly warningState: WarningState;\r\n  private readonly adapters: Record<string, AdapterRegistration>;\r\n  private readonly pricingOverrides: Record<string, ModelPricing>;\r\n\r\n  constructor(opts: RegistryOptions) {\r\n    this.config = parseRegistryConfig({ envPrefix: opts.envPrefix, env: opts.env });\r\n    this.adapters = opts.adapters;\r\n    this.budget = opts.budget ?? new InMemoryBudget();\r\n    this.cost = opts.cost ?? new InMemoryCost();\r\n    this.validationStrategy = opts.validationStrategy ?? DEFAULT_VALIDATION_STRATEGY;\r\n    this.pricingOverrides = opts.pricingOverrides ?? {};\r\n    this.shouldFallback = resolveRuntimeFallback(opts.runtimeFallback);\r\n    this.observability = opts.observability ?? {};\r\n    this.perAttemptTimeoutMs = opts.perAttemptTimeoutMs;\r\n    this.warningState = createWarningState({\r\n      suppressed: opts.suppressDeprecationWarnings ?? false,\r\n      ...(opts.deprecationWarningHandler ? { handler: opts.deprecationWarningHandler } : {}),\r\n    });\r\n    this.validateConfig();\r\n  }\r\n\r\n  /** Sanity-check that every provider's adapter exists and every task chain references real providers. */\r\n  private validateConfig(): void {\r\n    for (const [alias, entry] of Object.entries(this.config.providers)) {\r\n      if (!this.adapters[entry.adapter]) {\r\n        throw new ConfigError(\r\n          `Provider \"${alias}\" references adapter \"${entry.adapter}\" which is not registered. Available adapters: ${Object.keys(this.adapters).join(\", \") || \"(none)\"}`,\r\n        );\r\n      }\r\n    }\r\n    for (const [task, chain] of Object.entries(this.config.taskRoutes)) {\r\n      for (const alias of chain) {\r\n        if (!this.config.providers[alias]) {\r\n          throw new ConfigError(\r\n            `Task \"${task}\" references provider \"${alias}\" which is not configured.`,\r\n          );\r\n        }\r\n      }\r\n    }\r\n  }\r\n\r\n  /**\r\n   * Compose the gating storage key. When `budgetScope` is set, the backend\r\n   * sees `${alias}|${scope}:${scopeId}` so configured caps apply per-scope.\r\n   * Otherwise the key is just `${alias}` — backwards-compatible with every\r\n   * release up to alpha.19.1. (alpha.20+)\r\n   */\r\n  scopedKey(alias: string, budgetScope?: BudgetScopeRef): string {\r\n    if (!budgetScope) return alias;\r\n    return `${alias}|${budgetScope.scope}:${budgetScope.scopeId}`;\r\n  }\r\n\r\n  /** Resolve the first usable provider in the task's fallback chain. */\r\n  async selectModel(\r\n    taskType: string,\r\n    priority: 0 | 1 | 2 | 3 = 2,\r\n    budgetScope?: BudgetScopeRef,\r\n  ): Promise<ModelSelection> {\r\n    const chain = this.config.taskRoutes[taskType] ?? this.config.taskRoutes[\"general\"] ?? [];\r\n    if (chain.length === 0) {\r\n      throw new NoProvidersAvailableError(taskType, [], {\r\n        general: `No fallback chain configured for task \"${taskType}\" or \"general\"`,\r\n      });\r\n    }\r\n\r\n    const reasons: Record<string, string> = {};\r\n    for (const alias of chain) {\r\n      const entry = this.config.providers[alias];\r\n      if (!entry) {\r\n        reasons[alias] = \"provider not configured\";\r\n        continue;\r\n      }\r\n      const adapter = this.adapters[entry.adapter];\r\n      if (!adapter) {\r\n        reasons[alias] = `adapter \"${entry.adapter}\" not registered`;\r\n        continue;\r\n      }\r\n\r\n      // P0 bypasses budget gating.\r\n      if (priority > 0) {\r\n        const key = this.scopedKey(alias, budgetScope);\r\n        const budgetCheck = await this.budget.check(key, entry.budgetLimit);\r\n        if (!budgetCheck.allowed) {\r\n          reasons[alias] = budgetCheck.reason ?? \"budget exceeded\";\r\n          continue;\r\n        }\r\n        const costCheck = await this.cost.check(key, entry.costLimit);\r\n        if (!costCheck.allowed) {\r\n          reasons[alias] = costCheck.reason ?? \"cost cap exceeded\";\r\n          continue;\r\n        }\r\n      }\r\n\r\n      const pricing =\r\n        this.pricingOverrides[entry.modelId] ?? adapter.pricing[entry.modelId];\r\n      if (!pricing) {\r\n        reasons[alias] = `no pricing entry for model \"${entry.modelId}\"`;\r\n        continue;\r\n      }\r\n\r\n      return {\r\n        alias,\r\n        adapter,\r\n        modelId: entry.modelId,\r\n        pricing,\r\n        port: adapter.createLLMPort?.(entry.modelId, alias),\r\n        embeddingsPort: adapter.createEmbeddingsPort?.(entry.modelId, alias),\r\n      };\r\n    }\r\n\r\n    throw new NoProvidersAvailableError(taskType, chain, reasons);\r\n  }\r\n\r\n  /**\r\n   * Resolve a single provider by alias, bypassing the task-routing chain.\r\n   * Used by `forceProviderAlias` (alpha.7+). Per-provider budget gates still\r\n   * apply (P0 priority bypasses them, matching `selectModel`). Throws\r\n   * `NoProvidersAvailableError` if the alias is unconfigured or fails gating.\r\n   */\r\n  async selectByAlias(\r\n    alias: string,\r\n    priority: 0 | 1 | 2 | 3 = 2,\r\n    budgetScope?: BudgetScopeRef,\r\n  ): Promise<ModelSelection> {\r\n    const entry = this.config.providers[alias];\r\n    if (!entry) {\r\n      throw new NoProvidersAvailableError(`forced:${alias}`, [alias], {\r\n        [alias]: \"provider not configured\",\r\n      });\r\n    }\r\n    const adapter = this.adapters[entry.adapter];\r\n    if (!adapter) {\r\n      throw new NoProvidersAvailableError(`forced:${alias}`, [alias], {\r\n        [alias]: `adapter \"${entry.adapter}\" not registered`,\r\n      });\r\n    }\r\n    if (priority > 0) {\r\n      const key = this.scopedKey(alias, budgetScope);\r\n      const budgetCheck = await this.budget.check(key, entry.budgetLimit);\r\n      if (!budgetCheck.allowed) {\r\n        throw new NoProvidersAvailableError(`forced:${alias}`, [alias], {\r\n          [alias]: budgetCheck.reason ?? \"budget exceeded\",\r\n        });\r\n      }\r\n      const costCheck = await this.cost.check(key, entry.costLimit);\r\n      if (!costCheck.allowed) {\r\n        throw new NoProvidersAvailableError(`forced:${alias}`, [alias], {\r\n          [alias]: costCheck.reason ?? \"cost cap exceeded\",\r\n        });\r\n      }\r\n    }\r\n    const pricing =\r\n      this.pricingOverrides[entry.modelId] ?? adapter.pricing[entry.modelId];\r\n    if (!pricing) {\r\n      throw new NoProvidersAvailableError(`forced:${alias}`, [alias], {\r\n        [alias]: `no pricing entry for model \"${entry.modelId}\"`,\r\n      });\r\n    }\r\n    return {\r\n      alias,\r\n      adapter,\r\n      modelId: entry.modelId,\r\n      pricing,\r\n      port: adapter.createLLMPort?.(entry.modelId, alias),\r\n      embeddingsPort: adapter.createEmbeddingsPort?.(entry.modelId, alias),\r\n    };\r\n  }\r\n\r\n  /**\r\n   * Resolve EVERY usable provider in the task's fallback chain, in order.\r\n   * Used by the registry's port proxy to walk the chain on runtime errors\r\n   * (alpha.7+). The eligibility checks (provider configured, adapter\r\n   * registered, budget allows, cost cap allows, pricing exists) are the\r\n   * same as `selectModel`; the difference is this method returns the full\r\n   * viable list instead of just the first.\r\n   *\r\n   * Throws `NoProvidersAvailableError` if NO providers in the chain are\r\n   * viable. Returns at least one `ModelSelection` otherwise.\r\n   */\r\n  async selectViableChain(\r\n    taskType: string,\r\n    priority: 0 | 1 | 2 | 3 = 2,\r\n    budgetScope?: BudgetScopeRef,\r\n  ): Promise<ModelSelection[]> {\r\n    const chain = this.config.taskRoutes[taskType] ?? this.config.taskRoutes[\"general\"] ?? [];\r\n    if (chain.length === 0) {\r\n      throw new NoProvidersAvailableError(taskType, [], {\r\n        general: `No fallback chain configured for task \"${taskType}\" or \"general\"`,\r\n      });\r\n    }\r\n    const viable: ModelSelection[] = [];\r\n    const reasons: Record<string, string> = {};\r\n    for (const alias of chain) {\r\n      const entry = this.config.providers[alias];\r\n      if (!entry) {\r\n        reasons[alias] = \"provider not configured\";\r\n        continue;\r\n      }\r\n      const adapter = this.adapters[entry.adapter];\r\n      if (!adapter) {\r\n        reasons[alias] = `adapter \"${entry.adapter}\" not registered`;\r\n        continue;\r\n      }\r\n      if (priority > 0) {\r\n        const key = this.scopedKey(alias, budgetScope);\r\n        const budgetCheck = await this.budget.check(key, entry.budgetLimit);\r\n        if (!budgetCheck.allowed) {\r\n          reasons[alias] = budgetCheck.reason ?? \"budget exceeded\";\r\n          continue;\r\n        }\r\n        const costCheck = await this.cost.check(key, entry.costLimit);\r\n        if (!costCheck.allowed) {\r\n          reasons[alias] = costCheck.reason ?? \"cost cap exceeded\";\r\n          continue;\r\n        }\r\n      }\r\n      const pricing =\r\n        this.pricingOverrides[entry.modelId] ?? adapter.pricing[entry.modelId];\r\n      if (!pricing) {\r\n        reasons[alias] = `no pricing entry for model \"${entry.modelId}\"`;\r\n        continue;\r\n      }\r\n      viable.push({\r\n        alias,\r\n        adapter,\r\n        modelId: entry.modelId,\r\n        pricing,\r\n        port: adapter.createLLMPort?.(entry.modelId, alias),\r\n        embeddingsPort: adapter.createEmbeddingsPort?.(entry.modelId, alias),\r\n      });\r\n    }\r\n    if (viable.length === 0) {\r\n      throw new NoProvidersAvailableError(taskType, chain, reasons);\r\n    }\r\n    return viable;\r\n  }\r\n\r\n  /** Returns an LLMPort whose methods route to the selected adapter per call. */\r\n  getPort(): LLMPort {\r\n    return new RegistryPort(this);\r\n  }\r\n\r\n  /** Returns an EmbeddingsPort whose methods route to the selected adapter per call. */\r\n  getEmbeddingsPort(): EmbeddingsPort {\r\n    return new RegistryEmbeddingsPort(this);\r\n  }\r\n\r\n  /**\r\n   * Open a session-scoped cost gate. Returns a {@link CostSession} that\r\n   * wraps an LLMPort with a hard USD cap, independent of the per-provider\r\n   * hour/day/month gates. Throws `SessionBudgetExceededError` mid-loop\r\n   * when the cap is reached.\r\n   *\r\n   * Designed for continuous-call workloads (screen capture loops, OCR\r\n   * pipelines, multi-step agents) where a single stuck-open session can\r\n   * otherwise burn arbitrary dollars.\r\n   *\r\n   * The returned session has its own LLMPort via `session.getPort()`; the\r\n   * underlying registry's per-provider budget gates still apply on top.\r\n   */\r\n  openCostSession(opts: OpenCostSessionOptions): CostSession {\r\n    return new CostSession(this.getPort(), opts);\r\n  }\r\n\r\n  /** Introspection: list all provider aliases. */\r\n  listProviders(): ProviderEntry[] {\r\n    return Object.values(this.config.providers);\r\n  }\r\n\r\n  /** Introspection: list all configured task routes. */\r\n  listTasks(): Array<{ task: string; chain: string[] }> {\r\n    return Object.entries(this.config.taskRoutes).map(([task, chain]) => ({ task, chain }));\r\n  }\r\n\r\n  /**\r\n   * Compare bundled per-adapter pricing tables against each provider's live\r\n   * model catalog (via `LLMPort.listModels()`). Reports drift: models bundled\r\n   * but not exposed by the provider (deprecated), models exposed but not\r\n   * bundled (newly launched), and per-model rate divergence when the provider\r\n   * exposes pricing.\r\n   *\r\n   * Use as a CI / scheduled job to get a warning when a provider quietly\r\n   * changes its catalog. The bundled pricing tables remain the source of\r\n   * truth for cost computation; this method does NOT auto-update them.\r\n   *\r\n   * Adapters that don't implement `listModels()` (e.g. `adapter-vercel`)\r\n   * are skipped and reported under `skipped`.\r\n   *\r\n   * Added in `0.1.0-alpha.9`.\r\n   */\r\n  async checkPricingFreshness(): Promise<PricingFreshnessReport> {\r\n    const checked: PricingFreshnessAdapterReport[] = [];\r\n    const skipped: Array<{ adapter: string; reason: string }> = [];\r\n\r\n    // Group providers by adapter; only need to call listModels once per adapter.\r\n    const adapterToProviders = new Map<string, Array<{ alias: string; modelId: string }>>();\r\n    for (const [alias, entry] of Object.entries(this.config.providers)) {\r\n      const list = adapterToProviders.get(entry.adapter) ?? [];\r\n      list.push({ alias, modelId: entry.modelId });\r\n      adapterToProviders.set(entry.adapter, list);\r\n    }\r\n\r\n    for (const [adapterName, providers] of adapterToProviders) {\r\n      const adapter = this.adapters[adapterName];\r\n      if (!adapter) {\r\n        skipped.push({ adapter: adapterName, reason: \"adapter not registered\" });\r\n        continue;\r\n      }\r\n      const first = providers[0]!;\r\n      const port = adapter.createLLMPort?.(first.modelId, first.alias);\r\n      if (!port?.listModels) {\r\n        skipped.push({ adapter: adapterName, reason: \"adapter does not implement listModels()\" });\r\n        continue;\r\n      }\r\n      try {\r\n        const live = await port.listModels();\r\n        const liveIds = new Set(live.map((m) => m.id));\r\n        const bundledIds = new Set(Object.keys(adapter.pricing));\r\n\r\n        const removed = [...bundledIds].filter((id) => !liveIds.has(id));\r\n        const added = [...liveIds].filter((id) => !bundledIds.has(id));\r\n        const drift: Array<{\r\n          modelId: string;\r\n          bundledInputPer1M: number;\r\n          bundledOutputPer1M: number;\r\n          liveInputPer1M: number;\r\n          liveOutputPer1M: number;\r\n        }> = [];\r\n        for (const liveModel of live) {\r\n          if (liveModel.inputPer1M === undefined && liveModel.outputPer1M === undefined) continue;\r\n          const bundled = adapter.pricing[liveModel.id];\r\n          if (!bundled) continue;\r\n          if (\r\n            liveModel.inputPer1M !== undefined &&\r\n            liveModel.inputPer1M !== bundled.inputPer1M\r\n          ) {\r\n            drift.push({\r\n              modelId: liveModel.id,\r\n              bundledInputPer1M: bundled.inputPer1M,\r\n              bundledOutputPer1M: bundled.outputPer1M,\r\n              liveInputPer1M: liveModel.inputPer1M,\r\n              liveOutputPer1M: liveModel.outputPer1M ?? bundled.outputPer1M,\r\n            });\r\n          } else if (\r\n            liveModel.outputPer1M !== undefined &&\r\n            liveModel.outputPer1M !== bundled.outputPer1M\r\n          ) {\r\n            drift.push({\r\n              modelId: liveModel.id,\r\n              bundledInputPer1M: bundled.inputPer1M,\r\n              bundledOutputPer1M: bundled.outputPer1M,\r\n              liveInputPer1M: liveModel.inputPer1M ?? bundled.inputPer1M,\r\n              liveOutputPer1M: liveModel.outputPer1M,\r\n            });\r\n          }\r\n        }\r\n        checked.push({\r\n          adapter: adapterName,\r\n          liveModelCount: live.length,\r\n          bundledModelCount: bundledIds.size,\r\n          addedModels: added,\r\n          removedModels: removed,\r\n          priceDrift: drift,\r\n        });\r\n      } catch (err) {\r\n        skipped.push({\r\n          adapter: adapterName,\r\n          reason: `listModels failed: ${err instanceof Error ? err.message : String(err)}`,\r\n        });\r\n      }\r\n    }\r\n\r\n    return { checked, skipped };\r\n  }\r\n}\r\n\r\n/**\r\n * Output of {@link Registry.checkPricingFreshness}.\r\n *\r\n * `checked` has one entry per adapter that successfully reported its live\r\n * model catalog; `skipped` lists adapters that don't implement listModels()\r\n * or whose call failed.\r\n */\r\nexport interface PricingFreshnessReport {\r\n  checked: PricingFreshnessAdapterReport[];\r\n  skipped: Array<{ adapter: string; reason: string }>;\r\n}\r\n\r\nexport interface PricingFreshnessAdapterReport {\r\n  adapter: string;\r\n  liveModelCount: number;\r\n  bundledModelCount: number;\r\n  /** Models exposed by the provider but not in the bundled pricing table. */\r\n  addedModels: string[];\r\n  /** Models in the bundled pricing table but no longer exposed by the provider. */\r\n  removedModels: string[];\r\n  /** Models where bundled USD/1M differs from live USD/1M (when the API exposes pricing). */\r\n  priceDrift: Array<{\r\n    modelId: string;\r\n    bundledInputPer1M: number;\r\n    bundledOutputPer1M: number;\r\n    liveInputPer1M: number;\r\n    liveOutputPer1M: number;\r\n  }>;\r\n}\r\n\r\n/**\r\n * Convenience factory matching the public API surface advertised in the README.\r\n *\r\n *   const registry = createRegistryFromEnv({ adapters: { anthropic: ... } });\r\n *   const llm = registry.getPort();\r\n */\r\nexport function createRegistryFromEnv(opts: RegistryOptions): Registry {\r\n  return new Registry(opts);\r\n}\r\n\r\n// ─── Internal port proxies ───────────────────────────────────────────\r\n\r\n/**\r\n * Resolve the viable chain, filter to selections that actually have an\r\n * LLMPort, and walk through them attempting `attempt(sel)`. Walks on errors\r\n * matching `registry.shouldFallback`; surfaces other errors immediately.\r\n *\r\n * Records budget + cost ONLY on the successful attempt. If every viable\r\n * provider fails (or the chain is empty after filtering), throws a\r\n * `NoProvidersAvailableError` whose `reasons` map carries the per-alias\r\n * fallback error for diagnostics.\r\n */\r\nasync function walkChain<R>(\r\n  registry: Registry,\r\n  taskType: string,\r\n  priority: 0 | 1 | 2 | 3 | undefined,\r\n  attempt: (sel: ModelSelection) => Promise<R>,\r\n  recordCost: (sel: ModelSelection, result: R, key: string) => Promise<void>,\r\n  forceProviderAlias?: string,\r\n  budgetScope?: BudgetScopeRef,\r\n  operation:\r\n    | \"generateText\"\r\n    | \"generateStructured\"\r\n    | \"streamText\"\r\n    | \"streamStructured\"\r\n    | \"runAgent\" = \"generateText\",\r\n  refs?: Record<string, ArtifactRef>,\r\n): Promise<R> {\r\n  // forceProviderAlias short-circuit: bypass task routing entirely. Single-\r\n  // element chain. Runtime fallback does NOT engage — caller explicitly asked\r\n  // for this provider; falling back would defeat the point.\r\n  if (forceProviderAlias !== undefined) {\r\n    const sel = await registry.selectByAlias(forceProviderAlias, priority, budgetScope);\r\n    if (!sel.port) {\r\n      throw new NoProvidersAvailableError(`forced:${forceProviderAlias}`, [sel.alias], {\r\n        [sel.alias]: `adapter \"${sel.adapter.name}\" does not implement LLMPort`,\r\n      });\r\n    }\r\n    const result = await attempt(sel);\r\n    const key = registry.scopedKey(sel.alias, budgetScope);\r\n    await registry.budget.recordRequest(key);\r\n    await recordCost(sel, result, key);\r\n    return result;\r\n  }\r\n  const chain = await registry.selectViableChain(taskType, priority, budgetScope);\r\n  const reasons: Record<string, string> = {};\r\n  let lastErr: unknown;\r\n  let prevSelForFallback: ModelSelection | undefined;\r\n  for (const sel of chain) {\r\n    if (!sel.port) {\r\n      reasons[sel.alias] = `adapter \"${sel.adapter.name}\" does not implement LLMPort`;\r\n      continue;\r\n    }\r\n    // If a previous alias failed, this is a fallback advancement. Emit\r\n    // before we re-attempt so observers see the from→to transition in order.\r\n    if (prevSelForFallback) {\r\n      emitFallback(registry.observability.onFallback, {\r\n        fromAlias: prevSelForFallback.alias,\r\n        toAlias: sel.alias,\r\n        cause: \"provider-error\",\r\n        operation,\r\n        taskType,\r\n        reason: lastErr,\r\n        ...(refs ? { refs } : {}),\r\n      });\r\n    }\r\n    try {\r\n      const result = await attempt(sel);\r\n      const key = registry.scopedKey(sel.alias, budgetScope);\r\n      await registry.budget.recordRequest(key);\r\n      await recordCost(sel, result, key);\r\n      return result;\r\n    } catch (err) {\r\n      lastErr = err;\r\n      if (!registry.shouldFallback(err)) throw err;\r\n      const message =\r\n        err instanceof Error ? err.message : typeof err === \"string\" ? err : \"unknown error\";\r\n      reasons[sel.alias] = `runtime fallback: ${message}`;\r\n      prevSelForFallback = sel;\r\n      continue;\r\n    }\r\n  }\r\n  // Empty viable chain or every provider in the chain failed and fell through.\r\n  const attempted = chain.map((s) => s.alias);\r\n  if (lastErr instanceof Error && attempted.length > 0) {\r\n    // Surface the last error's message in the NoProviders summary so the\r\n    // caller doesn't have to dig through .reasons to see what actually failed.\r\n    throw new NoProvidersAvailableError(taskType, attempted, reasons);\r\n  }\r\n  throw new NoProvidersAvailableError(taskType, attempted, reasons);\r\n}\r\n\r\n/**\r\n * Normalize the alpha.25/alpha.26 dual-shape input into a `messages`\r\n * array + a \"messages-canonical\" options bag ready for adapter dispatch.\r\n * (alpha.26+)\r\n *\r\n * Semantics:\r\n *   - If `opts.messages` is set AND non-empty, use it verbatim. Also\r\n *     throws `MessagesConflictError` if any legacy field is co-set —\r\n *     ambiguity is a caller bug.\r\n *   - If `opts.messages` is set but empty, throws `EmptyMessagesError`.\r\n *   - If `opts.messages` is unset and `opts.prompt` is set, synthesize\r\n *     `messages = toMessages(instructions, prompt)`, emit the deduplicated\r\n *     deprecation warning, and dispatch.\r\n *   - If both are missing, throws `MessagesRequiredError`.\r\n *\r\n * Returns the resolved `messages` array. Callers replace the original\r\n * `messages` field on options with this value before adapter dispatch;\r\n * the legacy `instructions`/`prompt` fields stay on the options bag for\r\n * backwards-compat adapter reads during the alpha.26 window.\r\n */\r\nfunction normalizeMessagesOnOptions(\r\n  method: \"generateText\" | \"generateStructured\" | \"streamText\" | \"streamStructured\",\r\n  opts: {\r\n    messages?: LLMMessage[];\r\n  },\r\n): LLMMessage[] {\r\n  if (opts.messages === undefined) throw new MessagesRequiredError(method);\r\n  if (opts.messages.length === 0) throw new EmptyMessagesError(method);\r\n  return opts.messages;\r\n}\r\n\r\nclass RegistryPort implements LLMPort {\r\n  constructor(private readonly registry: Registry) {}\r\n\r\n  /**\r\n   * Emit OTel-aligned observability events for a completed result.\r\n   *\r\n   * Called from generateText, generateStructured, runAgent after walkChain\r\n   * returns the successful result. Stream methods do not call this — streamed\r\n   * cost surfacing is the alpha.22 follow-up. (alpha.21+)\r\n   */\r\n  private emitResultEvents(\r\n    result: { cost: { inputUSD: number; outputUSD: number; totalUSD: number; cacheSavingsUSD?: number }; usage: { inputTokens: number; outputTokens: number; totalTokens: number; cacheReadTokens?: number; cacheWriteTokens?: number; reasoningTokens?: number }; modelId: string; providerAlias: string },\r\n    operation: \"generateText\" | \"generateStructured\" | \"streamText\" | \"streamStructured\" | \"runAgent\" | \"embed\" | \"rerank\",\r\n    taskType: string | undefined,\r\n    budgetScope?: BudgetScopeRef,\r\n    refs?: Record<string, ArtifactRef>,\r\n  ): void {\r\n    const hooks = this.registry.observability;\r\n    if (hooks.onCost) {\r\n      emitCost(hooks.onCost, {\r\n        promptUsd: result.cost.inputUSD,\r\n        completionUsd: result.cost.outputUSD,\r\n        totalUsd: result.cost.totalUSD,\r\n        ...(result.cost.cacheSavingsUSD !== undefined ? { cacheReadUsd: result.cost.cacheSavingsUSD } : {}),\r\n        modelId: result.modelId,\r\n        providerAlias: result.providerAlias,\r\n        operation,\r\n        ...(taskType ? { taskType } : {}),\r\n        ...(budgetScope ? { budgetScope } : {}),\r\n        ...(refs ? { refs } : {}),\r\n      });\r\n    }\r\n    if (hooks.onTokenUsage) {\r\n      emitTokenUsage(hooks.onTokenUsage, {\r\n        inputTokens: result.usage.inputTokens,\r\n        outputTokens: result.usage.outputTokens,\r\n        totalTokens: result.usage.totalTokens,\r\n        ...(result.usage.cacheReadTokens !== undefined ? { cachedInputTokens: result.usage.cacheReadTokens } : {}),\r\n        ...(result.usage.cacheWriteTokens !== undefined ? { cacheCreationTokens: result.usage.cacheWriteTokens } : {}),\r\n        ...(result.usage.reasoningTokens !== undefined ? { reasoningTokens: result.usage.reasoningTokens } : {}),\r\n        modelId: result.modelId,\r\n        providerAlias: result.providerAlias,\r\n        operation,\r\n        ...(taskType ? { taskType } : {}),\r\n        ...(budgetScope ? { budgetScope } : {}),\r\n        ...(refs ? { refs } : {}),\r\n      });\r\n    }\r\n    if (hooks.onCacheHit) {\r\n      const hit = deriveCacheHit(result.usage, result.cost);\r\n      if (hit) {\r\n        emitCacheHit(hooks.onCacheHit, {\r\n          cachedTokens: hit.cachedTokens,\r\n          inputTokensTotal: hit.inputTokensTotal,\r\n          hitRatio: hit.hitRatio,\r\n          ...(hit.savingsUsd !== undefined ? { savingsUsd: hit.savingsUsd } : {}),\r\n          modelId: result.modelId,\r\n          providerAlias: result.providerAlias,\r\n          operation,\r\n          ...(taskType ? { taskType } : {}),\r\n          ...(refs ? { refs } : {}),\r\n        });\r\n      }\r\n    }\r\n  }\r\n\r\n  async generateText(options: GenerateTextOptions): Promise<GenerateTextResult> {\r\n    const messages = normalizeMessagesOnOptions(\"generateText\", options);\r\n    const normalizedOptions = { ...options, messages };\r\n    const result = await walkChain(\r\n      this.registry,\r\n      normalizedOptions.taskType,\r\n      normalizedOptions.priority,\r\n      (sel) =>\r\n        withPerAttemptTimeout(\r\n          this.registry.perAttemptTimeoutMs,\r\n          normalizedOptions.signal,\r\n          (signal) => sel.port!.generateText(signal ? { ...normalizedOptions, signal } : normalizedOptions),\r\n        ),\r\n      (_sel, result, key) => this.registry.cost.recordCost(key, result.cost.totalUSD),\r\n      normalizedOptions.forceProviderAlias,\r\n      normalizedOptions.budgetScope,\r\n      \"generateText\",\r\n      normalizedOptions.refs,\r\n    );\r\n    this.emitResultEvents(\r\n      result,\r\n      \"generateText\",\r\n      normalizedOptions.taskType,\r\n      normalizedOptions.budgetScope,\r\n      normalizedOptions.refs,\r\n    );\r\n    return result;\r\n  }\r\n\r\n  async generateStructured<T>(\r\n    options: GenerateStructuredOptions<T>,\r\n  ): Promise<GenerateStructuredResult<T>> {\r\n    const messages = normalizeMessagesOnOptions(\"generateStructured\", options);\r\n    const normalizedOptions = { ...options, messages };\r\n    const result = await walkChain(\r\n      this.registry,\r\n      normalizedOptions.taskType,\r\n      normalizedOptions.priority,\r\n      (sel) =>\r\n        withPerAttemptTimeout(\r\n          this.registry.perAttemptTimeoutMs,\r\n          normalizedOptions.signal,\r\n          (signal) => sel.port!.generateStructured(signal ? { ...normalizedOptions, signal } : normalizedOptions),\r\n        ),\r\n      (_sel, result, key) => this.registry.cost.recordCost(key, result.cost.totalUSD),\r\n      normalizedOptions.forceProviderAlias,\r\n      normalizedOptions.budgetScope,\r\n      \"generateStructured\",\r\n      normalizedOptions.refs,\r\n    );\r\n    this.emitResultEvents(\r\n      result,\r\n      \"generateStructured\",\r\n      normalizedOptions.taskType,\r\n      normalizedOptions.budgetScope,\r\n      normalizedOptions.refs,\r\n    );\r\n    return result;\r\n  }\r\n\r\n  /**\r\n   * Build a stream-complete callback that (a) emits `onCost` + `onTokenUsage`\r\n   * + `onCacheHit` from the completion metadata the adapter surfaces, and\r\n   * (b) records the streamed cost against the budget backend. (alpha.25+)\r\n   *\r\n   * The callback is attached to the caller's options object via\r\n   * {@link attachStreamCompleteCallback}; the adapter reads it and fires\r\n   * once at natural completion. Mid-stream errors and consumer aborts do\r\n   * NOT fire the callback, so no cost or observability events are emitted\r\n   * on failure paths (consistent with the alpha.24 non-streaming contract).\r\n   */\r\n  private buildStreamCompleteCallback(\r\n    operation: \"streamText\" | \"streamStructured\",\r\n    taskType: string | undefined,\r\n    budgetScope: BudgetScopeRef | undefined,\r\n    refs: Record<string, ArtifactRef> | undefined,\r\n  ): StreamCompleteCallback {\r\n    const registry = this.registry;\r\n    return (meta) => {\r\n      // 1. Emit observability events.\r\n      this.emitResultEvents(\r\n        { cost: meta.cost, usage: meta.usage, modelId: meta.modelId, providerAlias: meta.providerAlias },\r\n        operation,\r\n        taskType,\r\n        budgetScope,\r\n        refs,\r\n      );\r\n      // 2. Record streamed cost against the budget backend (fire-and-forget;\r\n      //    same swallow-error contract as the observability emits above).\r\n      const key = registry.scopedKey(meta.providerAlias, budgetScope);\r\n      Promise.resolve()\r\n        .then(() => registry.cost.recordCost(key, meta.cost.totalUSD))\r\n        .catch(() => {\r\n          // Budget backend errors on the streamed-cost path are not fatal\r\n          // to the caller; the stream already yielded. Observability hooks\r\n          // will still fire above.\r\n        });\r\n    };\r\n  }\r\n\r\n  async *streamText(options: StreamTextOptions): AsyncIterable<string> {\r\n    const messages = normalizeMessagesOnOptions(\"streamText\", options);\r\n    const normalizedOptions = { ...options, messages };\r\n    // Streaming runtime fallback is more nuanced — once we start yielding\r\n    // chunks, switching providers mid-stream would emit a confusing mix.\r\n    // For alpha.7 we walk the chain on the INITIAL `streamText()` call\r\n    // (most failures happen at stream-creation time anyway), then yield\r\n    // through whatever stream opened successfully. Mid-stream errors\r\n    // propagate as-is to the consumer; users handle them with a try/catch\r\n    // inside the for-await. Document this limit in the cancellation guide.\r\n    const completeCallback = this.buildStreamCompleteCallback(\r\n      \"streamText\",\r\n      normalizedOptions.taskType,\r\n      normalizedOptions.budgetScope,\r\n      normalizedOptions.refs,\r\n    );\r\n    const optionsWithCallback = attachStreamCompleteCallback({ ...normalizedOptions }, completeCallback);\r\n    const startStream = async (sel: ModelSelection): Promise<AsyncIterable<string>> => {\r\n      return sel.port!.streamText(optionsWithCallback);\r\n    };\r\n    const stream = await walkChain(\r\n      this.registry,\r\n      normalizedOptions.taskType,\r\n      normalizedOptions.priority,\r\n      startStream,\r\n      // No cost recording here — the stream-complete callback records cost\r\n      // when the stream naturally finishes. This preserves the alpha.7\r\n      // \"no cost at stream-creation\" behavior while adding the alpha.25\r\n      // \"cost at stream-completion\" surface.\r\n      async () => {\r\n        /* noop */\r\n      },\r\n      normalizedOptions.forceProviderAlias,\r\n      normalizedOptions.budgetScope,\r\n      \"streamText\",\r\n      normalizedOptions.refs,\r\n    );\r\n    yield* stream;\r\n  }\r\n\r\n  async *streamStructured<T>(options: StreamStructuredOptions<T>): AsyncIterable<Partial<T>> {\r\n    const messages = normalizeMessagesOnOptions(\"streamStructured\", options);\r\n    const normalizedOptions = { ...options, messages };\r\n    const completeCallback = this.buildStreamCompleteCallback(\r\n      \"streamStructured\",\r\n      normalizedOptions.taskType,\r\n      normalizedOptions.budgetScope,\r\n      normalizedOptions.refs,\r\n    );\r\n    const optionsWithCallback = attachStreamCompleteCallback({ ...normalizedOptions }, completeCallback);\r\n    const startStream = async (sel: ModelSelection): Promise<AsyncIterable<Partial<T>>> => {\r\n      return sel.port!.streamStructured(optionsWithCallback);\r\n    };\r\n    const stream = await walkChain(\r\n      this.registry,\r\n      normalizedOptions.taskType,\r\n      normalizedOptions.priority,\r\n      startStream,\r\n      async () => {\r\n        /* noop */\r\n      },\r\n      normalizedOptions.forceProviderAlias,\r\n      normalizedOptions.budgetScope,\r\n      \"streamStructured\",\r\n      normalizedOptions.refs,\r\n    );\r\n    yield* stream;\r\n  }\r\n\r\n  async runAgent(options: RunAgentOptions): Promise<AgentResult> {\r\n    const result = await walkChain(\r\n      this.registry,\r\n      options.taskType,\r\n      options.priority,\r\n      (sel) =>\r\n        withPerAttemptTimeout(\r\n          this.registry.perAttemptTimeoutMs,\r\n          options.signal,\r\n          (signal) => sel.port!.runAgent(signal ? { ...options, signal } : options),\r\n        ),\r\n      (_sel, result, key) => this.registry.cost.recordCost(key, result.cost.totalUSD),\r\n      options.forceProviderAlias,\r\n      options.budgetScope,\r\n      \"runAgent\",\r\n      options.refs,\r\n    );\r\n    this.emitResultEvents(\r\n      result,\r\n      \"runAgent\",\r\n      options.taskType,\r\n      options.budgetScope,\r\n      options.refs,\r\n    );\r\n    return result;\r\n  }\r\n}\r\n\r\n/**\r\n * Per-attempt timeout helper (alpha.23+).\r\n *\r\n * Composes a per-call timeout with a user-supplied AbortSignal. Both fire\r\n * the same wrapped controller; the shorter trigger wins. Called fresh per\r\n * provider attempt inside `walkChain` so each provider gets its own budget.\r\n *\r\n * When `timeoutMs` is undefined AND there's no user signal, the wrapper is\r\n * a pass-through (no AbortController created).\r\n */\r\nasync function withPerAttemptTimeout<R>(\r\n  timeoutMs: number | undefined,\r\n  userSignal: AbortSignal | undefined,\r\n  fn: (signal: AbortSignal | undefined) => Promise<R>,\r\n): Promise<R> {\r\n  if (timeoutMs === undefined && !userSignal) {\r\n    return fn(undefined);\r\n  }\r\n  const controller = new AbortController();\r\n  let timer: ReturnType<typeof setTimeout> | undefined;\r\n  if (timeoutMs !== undefined) {\r\n    timer = setTimeout(() => controller.abort(), timeoutMs);\r\n  }\r\n  let userListener: (() => void) | undefined;\r\n  if (userSignal) {\r\n    // If user signal already aborted, forward immediately.\r\n    if (userSignal.aborted) {\r\n      controller.abort();\r\n    } else {\r\n      userListener = () => controller.abort();\r\n      userSignal.addEventListener(\"abort\", userListener, { once: true });\r\n    }\r\n  }\r\n  try {\r\n    return await fn(controller.signal);\r\n  } finally {\r\n    if (timer !== undefined) clearTimeout(timer);\r\n    if (userListener && userSignal) userSignal.removeEventListener(\"abort\", userListener);\r\n  }\r\n}\r\n\r\nclass RegistryEmbeddingsPort implements EmbeddingsPort {\r\n  constructor(private readonly registry: Registry) {}\r\n\r\n  private async resolve(taskType: string, budgetScope?: BudgetScopeRef): Promise<ModelSelection> {\r\n    const sel = await this.registry.selectModel(taskType, 2, budgetScope);\r\n    if (!sel.embeddingsPort) {\r\n      throw new NoProvidersAvailableError(taskType, [sel.alias], {\r\n        [sel.alias]: `adapter \"${sel.adapter.name}\" does not implement EmbeddingsPort`,\r\n      });\r\n    }\r\n    return sel;\r\n  }\r\n\r\n  async generateEmbedding(options: EmbeddingOptions): Promise<EmbeddingResult> {\r\n    const sel = await this.resolve(options.taskType, options.budgetScope);\r\n    const result = await sel.embeddingsPort!.generateEmbedding(options);\r\n    const key = this.registry.scopedKey(sel.alias, options.budgetScope);\r\n    await this.registry.budget.recordRequest(key);\r\n    await this.registry.cost.recordCost(key, result.cost.totalUSD);\r\n    return result;\r\n  }\r\n\r\n  async generateEmbeddings(options: BatchEmbeddingOptions): Promise<BatchEmbeddingResult> {\r\n    const sel = await this.resolve(options.taskType, options.budgetScope);\r\n    const result = await sel.embeddingsPort!.generateEmbeddings(options);\r\n    const key = this.registry.scopedKey(sel.alias, options.budgetScope);\r\n    await this.registry.budget.recordRequest(key);\r\n    await this.registry.cost.recordCost(key, result.cost.totalUSD);\r\n    return result;\r\n  }\r\n}\r\n\r\n// ─── Runtime-fallback predicate resolution ───────────────────────────\r\n\r\n/**\r\n * Translate the user-friendly `runtimeFallback` config into a predicate\r\n * the registry uses to decide whether to walk the chain on an error.\r\n *\r\n *   - `\"default\"` (or undefined): walk on `ProviderUnavailableError` only.\r\n *   - `\"aggressive\"` (alpha.25+, LP-REQ-01): walk on any provider-side\r\n *     signal via {@link aggressiveShouldFallback}.\r\n *   - `\"none\"`: never walk — preserves v0.1 behavior.\r\n *   - `{ shouldFallback }`: caller-supplied predicate.\r\n */\r\nfunction resolveRuntimeFallback(\r\n  opt: RegistryOptions[\"runtimeFallback\"],\r\n): (err: unknown) => boolean {\r\n  if (opt === \"none\") return () => false;\r\n  if (opt === \"aggressive\") return aggressiveShouldFallback;\r\n  if (opt && typeof opt === \"object\" && \"shouldFallback\" in opt) {\r\n    return opt.shouldFallback;\r\n  }\r\n  // Default\r\n  return (err) => err instanceof ProviderUnavailableError;\r\n}\r\n","/**\r\n * declareTasks<T>() — opt-in type safety for task definitions.\r\n *\r\n * TaskType is intentionally `string` at the LLMPort surface so the library\r\n * does not constrain users' task vocabularies. The cost is loose typing at\r\n * call sites. declareTasks() recovers most of the safety with autocomplete\r\n * and typo protection.\r\n *\r\n * Stated as \"open with opt-in typing,\" not \"better than enum.\"\r\n *\r\n * See implementation plan v3 §6.4 and decision 17.\r\n */\r\n\r\nimport type { LLMPriority } from \"../ports/llm-port.js\";\r\n\r\nexport interface TaskConfig {\r\n  priority?: LLMPriority;\r\n  defaultTemperature?: number;\r\n  defaultMaxOutputTokens?: number;\r\n  description?: string;\r\n}\r\n\r\n/**\r\n * Returns a typed map of task-name keys to their literal-string task type.\r\n *\r\n * @example\r\n * const tasks = declareTasks({\r\n *   triage: { priority: 1, defaultTemperature: 0 },\r\n *   draft:  { priority: 2, defaultTemperature: 0.4 },\r\n * });\r\n *\r\n * llm.generateText({ taskType: tasks.triage, prompt: \"...\" });\r\n * //                          ^^^^^^^^^^^^^ autocomplete + typo-safe\r\n *\r\n * The runtime value of `tasks.triage` is the literal string \"triage\";\r\n * the type is also the literal \"triage\", not the wider `string`.\r\n */\r\nexport function declareTasks<T extends Record<string, TaskConfig>>(\r\n  config: T,\r\n): { [K in keyof T]: K & string } & { __meta: T } {\r\n  const result: Record<string, string> = {};\r\n  for (const key of Object.keys(config)) {\r\n    result[key] = key;\r\n  }\r\n  // Attach the original config under a metadata key so callers (e.g. registry)\r\n  // can read defaults without recomputing them.\r\n  Object.defineProperty(result, \"__meta\", {\r\n    value: config,\r\n    enumerable: false,\r\n    writable: false,\r\n  });\r\n  return result as { [K in keyof T]: K & string } & { __meta: T };\r\n}\r\n\r\n/** Read the original TaskConfig back from a declareTasks() result. */\r\nexport function getTaskConfig<T extends Record<string, TaskConfig>>(\r\n  declared: { [K in keyof T]: K & string } & { __meta: T },\r\n  taskName: keyof T,\r\n): TaskConfig | undefined {\r\n  return declared.__meta[taskName];\r\n}\r\n","/**\r\n * Cost computation: convert TokenUsage + ModelPricing → CostUsage.\r\n *\r\n * Adapters call this after every LLM request to compute the dollar cost\r\n * of the call from token counts and the model's pricing entry. The result\r\n * goes into both the result object (for caller observability) and the\r\n * CostBackend (for budget enforcement).\r\n */\r\n\r\nimport type { CostUsage, TokenUsage } from \"../ports/llm-port.js\";\r\nimport type { ModelPricing } from \"./types.js\";\r\n\r\nconst PER_1M = 1_000_000;\r\n\r\n/**\r\n * Compute USD cost for a chat/text completion call.\r\n * Cache reads (Anthropic feature) are billed at the discounted rate when present.\r\n */\r\nexport function computeChatCost(usage: TokenUsage, pricing: ModelPricing): CostUsage {\r\n  const cacheReadTokens = usage.cacheReadTokens ?? 0;\r\n  const cacheWriteTokens = usage.cacheWriteTokens ?? 0;\r\n  // Regular input tokens are total input minus what was satisfied from cache reads\r\n  // and what was committed as cache writes. Adapters typically already report this\r\n  // breakdown correctly; if not, regularInput falls back to inputTokens.\r\n  const regularInput = Math.max(0, usage.inputTokens - cacheReadTokens - cacheWriteTokens);\r\n\r\n  const inputUSD = (regularInput * pricing.inputPer1M) / PER_1M;\r\n  const outputUSD = (usage.outputTokens * pricing.outputPer1M) / PER_1M;\r\n  const cacheReadUSD = ((pricing.cacheReadPer1M ?? pricing.inputPer1M) * cacheReadTokens) / PER_1M;\r\n  const cacheWriteUSD = ((pricing.cacheWritePer1M ?? pricing.inputPer1M) * cacheWriteTokens) / PER_1M;\r\n\r\n  // Savings = what the caller saved by hitting cache vs paying full input rate.\r\n  // Renamed from cacheDiscountUSD in alpha.19 (BREAKING).\r\n  const cacheSavingsUSD =\r\n    cacheReadTokens > 0\r\n      ? (pricing.inputPer1M - (pricing.cacheReadPer1M ?? pricing.inputPer1M)) * (cacheReadTokens / PER_1M)\r\n      : undefined;\r\n\r\n  const totalUSD = inputUSD + outputUSD + cacheReadUSD + cacheWriteUSD;\r\n\r\n  return {\r\n    inputUSD: round6(inputUSD + cacheReadUSD + cacheWriteUSD),\r\n    outputUSD: round6(outputUSD),\r\n    totalUSD: round6(totalUSD),\r\n    ...(cacheSavingsUSD !== undefined ? { cacheSavingsUSD: round6(cacheSavingsUSD) } : {}),\r\n  };\r\n}\r\n\r\n/** Compute USD cost for an embedding call (input tokens only). */\r\nexport function computeEmbeddingCost(inputTokens: number, pricing: ModelPricing): CostUsage {\r\n  const ratePer1M = pricing.embeddingPer1M ?? pricing.inputPer1M;\r\n  const inputUSD = (inputTokens * ratePer1M) / PER_1M;\r\n  return {\r\n    inputUSD: round6(inputUSD),\r\n    outputUSD: 0,\r\n    totalUSD: round6(inputUSD),\r\n  };\r\n}\r\n\r\n/**\r\n * Round to 10 decimals (1/10,000,000,000 of a USD = $0.0000000001).\r\n *\r\n * Why 10 not 6: a single embedding of a few tokens at $0.02/1M costs around\r\n * $0.0000001, which would round to 0 at 6 decimals — making the cost field\r\n * useless for cost gating on embeddings or short prompts. 10 decimals\r\n * preserves precision for the smallest realistic per-call costs while\r\n * still being well within IEEE 754 double precision.\r\n *\r\n * The function is named round6 for backward source compatibility; the\r\n * actual rounding is at 10 decimals as of v0.1.\r\n */\r\nfunction round6(n: number): number {\r\n  return Math.round(n * 10_000_000_000) / 10_000_000_000;\r\n}\r\n","/**\r\n * Cross-adapter observability hook for transient retries.\r\n *\r\n * Adapters call `onRetry` when they decide to retry an in-flight request for\r\n * a known transient reason — burst-protection 401s, capability-rejection\r\n * fallback (drop temperature, drop json_object, drop system message),\r\n * reasoning-starved responses (model spent all tokens on hidden reasoning),\r\n * or schema-validation feedback retries.\r\n *\r\n * This is observability only. Adapters decide whether to retry; the hook just\r\n * gets told. Throwing from the hook does NOT cancel the retry — adapters call\r\n * the hook fire-and-forget.\r\n */\r\n\r\n/**\r\n * Discriminator for why the adapter retried. New reasons may be added in\r\n * minor releases; consumers should default to logging the event verbatim\r\n * rather than switching exhaustively.\r\n */\r\nexport type RetryReason =\r\n  /** Project-key burst-protection 401 from OpenAI. The key is valid; retry. */\r\n  | \"transient-auth\"\r\n  /** Model rejected an unsupported parameter (temperature, json_object, system). Drop and retry. */\r\n  | \"capability-fallback\"\r\n  /** Reasoning model spent its whole budget on hidden tokens. Retry with expanded budget. */\r\n  | \"reasoning-starvation\"\r\n  /** Structured-output response failed schema validation; retry with corrective feedback. */\r\n  | \"validation-feedback\"\r\n  /**\r\n   * Tool call was emitted in the harmony reasoning channel (`message.reasoning_content`)\r\n   * rather than the standard `message.tool_calls` array. The adapter extracted the\r\n   * harmony tool call and hoisted it into the executable path. No retry was performed\r\n   * — this is observability only, signaling that the response shape was non-standard\r\n   * but recoverable. (alpha.23+)\r\n   */\r\n  | \"harmony-tool-call-extracted\"\r\n  /**\r\n   * Model emitted prose without making any tool calls, despite the request providing\r\n   * a tools array. Retry with a corrective system message asking the model to use\r\n   * the standard `tool_calls` array. Single-shot retry. (alpha.23+)\r\n   */\r\n  | \"zero-tool-call-prose-retry\";\r\n\r\n/** What the adapter passes to `onRetry` each time it retries. */\r\nexport interface RetryEvent {\r\n  reason: RetryReason;\r\n  /** 0-indexed retry number (0 = first retry, after the original attempt failed). */\r\n  attempt: number;\r\n  modelId: string;\r\n  providerAlias: string;\r\n  /** Milliseconds slept before this retry. 0 when the retry fires immediately. */\r\n  delayMs: number;\r\n  /**\r\n   * The error that triggered the retry, when applicable. `undefined` for\r\n   * reasoning-starvation (which inspects a successful response, not an error)\r\n   * and may be undefined for validation-feedback if the adapter doesn't\r\n   * forward the Zod issues here.\r\n   */\r\n  cause?: unknown;\r\n  /**\r\n   * When `reason === \"capability-fallback\"`, names the specific capability\r\n   * the adapter learned about (e.g. `temperatureLocked`, `jsonModeUnsupported`,\r\n   * `systemMessageInUserOnly`). Lets observability stacks distinguish \"we\r\n   * stripped temperature\" from \"we stripped json_object\" from each other.\r\n   * Adapter authors should populate this whenever the retry was driven by a\r\n   * specific capability rejection. Omitted for other retry reasons.\r\n   */\r\n  capability?: string;\r\n}\r\n\r\n/**\r\n * Observability hook. Sync or async. Adapters call it fire-and-forget; they\r\n * do NOT await the returned promise and do NOT cancel the retry if the hook\r\n * throws. Use this to emit logs, metrics, or traces.\r\n */\r\nexport type OnRetry = (event: RetryEvent) => void | Promise<void>;\r\n\r\n/**\r\n * Jitter strategy for exponential backoff delays.\r\n *\r\n * Per the AWS Architecture Blog \"Exponential Backoff And Jitter\" (2015) and\r\n * subsequent industry consensus, decorrelated jitter is the recommended\r\n * default for high-concurrency clients because it preserves the average\r\n * backoff while breaking up retry storms most aggressively. \"Full\" matches\r\n * Genkit's default. \"Equal\" matches the classic Capacity-Random-Truncated\r\n * Binary Exponential Backoff. \"None\" disables jitter (use for tests).\r\n */\r\nexport type JitterStrategy = \"none\" | \"full\" | \"equal\" | \"decorrelated\";\r\n\r\n/**\r\n * Configurable jittered exponential backoff for adapter retry loops.\r\n *\r\n * Adapters consume this config when computing the delay before a retry.\r\n * The shape matches Genkit's middleware retry config so users migrating\r\n * from Genkit see a familiar API.\r\n *\r\n * Defaults (when fields are omitted):\r\n *   - initialDelayMs: 200\r\n *   - maxDelayMs:     10000\r\n *   - multiplier:     2\r\n *   - jitter:         \"decorrelated\"\r\n *\r\n * Pseudocode for delay computation:\r\n *\r\n *   baseDelay = min(initialDelayMs * multiplier^attempt, maxDelayMs)\r\n *   switch (jitter) {\r\n *     case \"none\":          return baseDelay\r\n *     case \"full\":          return random(0, baseDelay)\r\n *     case \"equal\":         return baseDelay/2 + random(0, baseDelay/2)\r\n *     case \"decorrelated\":  return min(maxDelayMs, random(initialDelayMs, prevDelay * 3))\r\n *   }\r\n *\r\n * Added in alpha.17. Adapters wire this in adapter-specific releases.\r\n */\r\nexport interface BackoffConfig {\r\n  /**\r\n   * Delay before the first retry, in milliseconds. The base from which\r\n   * subsequent attempts scale exponentially. Default: 200ms.\r\n   */\r\n  initialDelayMs?: number;\r\n\r\n  /**\r\n   * Hard ceiling on any single retry delay. Prevents runaway exponential\r\n   * growth. Default: 10000ms (10 seconds).\r\n   */\r\n  maxDelayMs?: number;\r\n\r\n  /**\r\n   * Exponential growth factor. Default: 2 (each attempt waits ~2x the\r\n   * previous one before jitter is applied).\r\n   */\r\n  multiplier?: number;\r\n\r\n  /** Jitter strategy. Default: \"decorrelated\". */\r\n  jitter?: JitterStrategy;\r\n}\r\n\r\n/**\r\n * Compute the delay (in ms) before the Nth retry attempt under a given\r\n * BackoffConfig. Pure function; useful for testing and for adapters that\r\n * want to apply uniform backoff semantics.\r\n *\r\n * @param attempt 0-indexed retry number (0 = before the first retry).\r\n * @param config  Backoff configuration. Missing fields filled with defaults.\r\n * @param prevDelay The previous attempt's computed delay; required for\r\n *   \"decorrelated\" jitter, ignored otherwise. Pass `initialDelayMs` for\r\n *   the first call.\r\n * @param rng A 0-1 uniform random function. Defaults to Math.random for\r\n *   production; tests should pass a deterministic function.\r\n */\r\nexport function computeBackoffDelay(\r\n  attempt: number,\r\n  config: BackoffConfig = {},\r\n  prevDelay?: number,\r\n  rng: () => number = Math.random,\r\n): number {\r\n  const initial = config.initialDelayMs ?? 200;\r\n  const max = config.maxDelayMs ?? 10000;\r\n  const multiplier = config.multiplier ?? 2;\r\n  const jitter = config.jitter ?? \"decorrelated\";\r\n\r\n  const baseDelay = Math.min(initial * Math.pow(multiplier, attempt), max);\r\n\r\n  switch (jitter) {\r\n    case \"none\":\r\n      return baseDelay;\r\n    case \"full\":\r\n      return rng() * baseDelay;\r\n    case \"equal\":\r\n      return baseDelay / 2 + rng() * (baseDelay / 2);\r\n    case \"decorrelated\": {\r\n      const prev = prevDelay ?? initial;\r\n      return Math.min(max, initial + rng() * (prev * 3 - initial));\r\n    }\r\n  }\r\n}\r\n","/**\r\n * Fire-and-forget invocation of the `onRetry` observability hook.\r\n *\r\n * Adapters fire this on every retry attempt for the reasons documented in\r\n * `RetryReason`. Hooks are called fire-and-forget: errors thrown synchronously\r\n * or rejected promises are swallowed silently so observability code can never\r\n * cancel a retry or crash the request.\r\n *\r\n * Hoisted from per-adapter copies in alpha.3 so every adapter shares the same\r\n * semantics. Adapters that wrote their own `emitRetry` (adapter-openai,\r\n * adapter-vercel) now import this instead.\r\n */\r\n\r\nimport type { OnRetry, RetryEvent } from \"./retry.js\";\r\n\r\n/**\r\n * Invoke `onRetry` with the given event, fire-and-forget.\r\n *\r\n * - If `onRetry` is undefined, returns immediately.\r\n * - If `onRetry` throws synchronously, the error is swallowed.\r\n * - If `onRetry` returns a rejected promise, the rejection is swallowed.\r\n *\r\n * Observability hooks are not allowed to affect retry behavior. This helper\r\n * enforces that invariant.\r\n */\r\nexport function emitRetryEvent(onRetry: OnRetry | undefined, event: RetryEvent): void {\r\n  if (!onRetry) return;\r\n  try {\r\n    const result = onRetry(event);\r\n    if (result && typeof (result as Promise<void>).then === \"function\") {\r\n      (result as Promise<void>).catch(() => {\r\n        /* swallow — hook is observability only */\r\n      });\r\n    }\r\n  } catch {\r\n    /* swallow — hook is observability only */\r\n  }\r\n}\r\n","/**\r\n * Runtime capability discovery utility — shared across all adapters.\r\n *\r\n * Providers don't expose programmatic capability discovery (no API endpoint\r\n * tells you \"this model rejects custom temperature\" or \"this model doesn't\r\n * support response_format: json_object\"). Hardcoded capability tables go\r\n * stale every time a new model ships.\r\n *\r\n * The pattern that works:\r\n *\r\n *   1. The adapter tries the call with the parameter included.\r\n *   2. If the provider returns a 400 matching a known \"deprecated parameter\"\r\n *      shape, the adapter calls `learner.remember(modelId, { ... })`.\r\n *   3. The adapter strips the parameter and retries the call.\r\n *   4. Every subsequent call in this process applies the learned constraint\r\n *      up front. No re-discovery.\r\n *\r\n * Each adapter contributes its own error classifiers (which provider error\r\n * shape signals which capability rejection) and its own static catalog of\r\n * known rejectors (so first-call discovery can be skipped for models we\r\n * already know reject the parameter). The pattern itself — the Map, the\r\n * accumulation, the user-override layering, the static-catalog seeding — is\r\n * what this module provides.\r\n *\r\n * Hoisted from adapter-openai's per-adapter copy in alpha.3 so every adapter\r\n * shares the same discovery machinery.\r\n */\r\n\r\nimport type { ModelCapabilities } from \"./budget/types.js\";\r\n\r\n/**\r\n * One entry in the static \"we already know this model rejects X\" catalog.\r\n *\r\n * Adapters maintain their own catalog (the exact model patterns are\r\n * provider-specific) and pass it to `learner.seedFromCatalog(modelId, catalog)`\r\n * at port creation time. Matching entries pre-seed the learned-constraint\r\n * Map so the first call skips the discovery round-trip.\r\n */\r\nexport interface KnownModelConstraint {\r\n  /** Regex matched against the model id, e.g. `/^claude-opus-4-5/`. */\r\n  pattern: RegExp;\r\n  /** The constraint to remember when the pattern matches. */\r\n  constraints: Partial<ModelCapabilities>;\r\n}\r\n\r\n/**\r\n * Per-process learner of per-model capability constraints. Each call to\r\n * `createCapabilityLearner()` returns a fresh learner with its own Map.\r\n *\r\n * Adapters create one learner per adapter context (typically per LLMPort\r\n * instance) and reference it in their retry loops. The learner is internal\r\n * state of the adapter; it's not part of any port's public surface.\r\n */\r\nexport interface CapabilityLearner {\r\n  /**\r\n   * Resolve the effective capabilities for a model. User-supplied\r\n   * capabilities (passed via `pricingOverrides[modelId].capabilities`)\r\n   * override learned ones; learned ones override defaults.\r\n   */\r\n  get(modelId: string, userSupplied?: ModelCapabilities): ModelCapabilities;\r\n\r\n  /**\r\n   * Record a discovered constraint after the provider returns an error that\r\n   * signals the capability rejection. Accumulates: subsequent calls add more\r\n   * constraints to the same model entry without losing prior ones.\r\n   */\r\n  remember(modelId: string, constraints: Partial<ModelCapabilities>): void;\r\n\r\n  /**\r\n   * Test-only: clear all learned state. Should not be used in production code.\r\n   */\r\n  _reset(): void;\r\n\r\n  /**\r\n   * Seed the learner with static \"we already know this model rejects X\"\r\n   * entries. Adapters call this at port creation with their per-provider\r\n   * catalog. Pre-seeding skips the first-call discovery round-trip.\r\n   *\r\n   * Idempotent: re-seeding the same catalog adds the same constraints. The\r\n   * underlying Map is set-based; duplicate entries are harmless.\r\n   */\r\n  seedFromCatalog(modelId: string, catalog: readonly KnownModelConstraint[]): void;\r\n\r\n  /**\r\n   * True if the learner has already learned (or been seeded with) a given\r\n   * capability flag for a model. Used by `emitFirstLearningWarning` to fire\r\n   * the click-to-file URL once per modelId per process.\r\n   */\r\n  hasLearned(modelId: string, capabilityFlag: keyof ModelCapabilities): boolean;\r\n}\r\n\r\n/** Factory: returns a fresh capability learner with no learned state. */\r\nexport function createCapabilityLearner(): CapabilityLearner {\r\n  const learnedConstraints = new Map<string, ModelCapabilities>();\r\n\r\n  return {\r\n    get(modelId, userSupplied) {\r\n      const learned = learnedConstraints.get(modelId) ?? {};\r\n      return { ...learned, ...userSupplied };\r\n    },\r\n\r\n    remember(modelId, constraints) {\r\n      const existing = learnedConstraints.get(modelId) ?? {};\r\n      learnedConstraints.set(modelId, { ...existing, ...constraints });\r\n    },\r\n\r\n    _reset() {\r\n      learnedConstraints.clear();\r\n    },\r\n\r\n    seedFromCatalog(modelId, catalog) {\r\n      for (const entry of catalog) {\r\n        if (entry.pattern.test(modelId)) {\r\n          this.remember(modelId, entry.constraints);\r\n        }\r\n      }\r\n    },\r\n\r\n    hasLearned(modelId, capabilityFlag) {\r\n      const learned = learnedConstraints.get(modelId);\r\n      if (!learned) return false;\r\n      return learned[capabilityFlag] !== undefined;\r\n    },\r\n  };\r\n}\r\n","/**\r\n * Notification mechanism for runtime-learned capability constraints.\r\n *\r\n * When an adapter discovers at runtime that a model rejects a parameter,\r\n * it builds a pre-filled GitHub New Issue URL and prints it via console.warn\r\n * once per modelId+capability per process. Users see the warning, can click\r\n * the URL, and submit a well-structured issue with model id + error message\r\n * + adapter version + SDK version already filled in.\r\n *\r\n * This is intentionally NOT telemetry: no automatic data exfiltration, no\r\n * phone-home endpoint, no opt-in flag. Maintainers see signal only when a\r\n * user takes an explicit action (clicking the URL). The pattern preserves\r\n * user privacy AND gives maintainers actionable signal when something new\r\n * shows up in the wild.\r\n */\r\n\r\n/**\r\n * Inputs for the click-to-file warning + URL builder.\r\n *\r\n * Adapters populate this at the moment they learn a new constraint. The\r\n * `packageName` field is what appears as a label and in the title; it MUST\r\n * be the npm package name (e.g. `@llm-ports/adapter-anthropic`), not a\r\n * short alias.\r\n *\r\n * The `capability` field is the constraint name that was learned (e.g.\r\n * `temperatureLocked`, `jsonModeUnsupported`). Adapters can also pass\r\n * a free-form string for capabilities not in the standard `ModelCapabilities`\r\n * enum — the URL builder treats it as opaque.\r\n */\r\nexport interface FirstLearningEvent {\r\n  /** Full npm package name, e.g. `@llm-ports/adapter-anthropic`. */\r\n  packageName: string;\r\n  /** Provider-side model id that exhibited the constraint, e.g. `claude-opus-4-5`. */\r\n  modelId: string;\r\n  /** Constraint name that was learned, e.g. `temperatureLocked`. */\r\n  capability: string;\r\n  /** The error message the provider returned (used to title the issue + verify). */\r\n  providerErrorMessage: string;\r\n  /** The installed adapter version, e.g. `0.1.0-alpha.3`. */\r\n  adapterVersion: string;\r\n  /** The installed SDK version (e.g. `@anthropic-ai/sdk` version). */\r\n  sdkVersion: string;\r\n  /**\r\n   * Base URL of the project's GitHub repository. The URL builder appends\r\n   * `/issues/new?title=...&body=...&labels=...` to this. Default in the\r\n   * builder is `https://github.com/baabakk/llm-ports`.\r\n   */\r\n  repoUrl?: string;\r\n}\r\n\r\n/**\r\n * Build a pre-filled GitHub New Issue URL for a runtime-learned constraint.\r\n *\r\n * The URL opens GitHub's New Issue form with title, body, and labels already\r\n * populated from the event. The user reviews + edits + submits in seconds.\r\n *\r\n * Exported for testing and for adapters that want to surface the URL in a\r\n * non-console channel (logger, Sentry custom event, etc.). The default\r\n * caller is `emitFirstLearningWarning` below which prints the URL via\r\n * `console.warn`.\r\n */\r\nexport function buildLearningIssueUrl(event: FirstLearningEvent): string {\r\n  const repoUrl = event.repoUrl ?? \"https://github.com/baabakk/llm-ports\";\r\n  const title = `Add ${event.modelId} to ${event.capability} catalog (${event.packageName})`;\r\n  const body = [\r\n    \"## Auto-generated by adapter runtime learning\",\r\n    \"\",\r\n    `**Model:** \\`${event.modelId}\\``,\r\n    `**Constraint learned at runtime:** \\`${event.capability}\\``,\r\n    `**Provider error message:** \\`${event.providerErrorMessage}\\``,\r\n    \"\",\r\n    \"**Versions:**\",\r\n    `- \\`${event.packageName}\\` v${event.adapterVersion}`,\r\n    `- SDK v${event.sdkVersion}`,\r\n    typeof process !== \"undefined\" ? `- Node.js ${process.version}` : \"\",\r\n    \"\",\r\n    \"The adapter learned this constraint at runtime and stripped the parameter\",\r\n    \"from subsequent calls automatically. Filing this issue lets us add the\",\r\n    \"model to the static catalog so other users skip the discovery round-trip.\",\r\n    \"\",\r\n    \"(Auto-prefilled. Please review and edit before submitting if anything\",\r\n    \"looks wrong, especially the model ID.)\",\r\n  ]\r\n    .filter((line) => line !== \"\")\r\n    .join(\"\\n\");\r\n\r\n  // Determine sensible labels. The package-specific area label (e.g.\r\n  // `area:adapter-anthropic`) is added when we can derive it from the\r\n  // package name.\r\n  const labels = [\"bug\", \"runtime-learned\"];\r\n  const areaLabel = derivePackageAreaLabel(event.packageName);\r\n  if (areaLabel) labels.push(areaLabel);\r\n\r\n  return (\r\n    `${repoUrl}/issues/new?` +\r\n    `title=${encodeURIComponent(title)}&` +\r\n    `body=${encodeURIComponent(body)}&` +\r\n    `labels=${encodeURIComponent(labels.join(\",\"))}`\r\n  );\r\n}\r\n\r\n/**\r\n * Per-process tracking of which (modelId, capability) pairs we've already\r\n * warned about. Ensures the console.warn fires once per pair per process,\r\n * not on every call.\r\n */\r\nconst warnedAlready = new Set<string>();\r\n\r\n/**\r\n * Emit a `console.warn` with the click-to-file URL for a runtime-learned\r\n * constraint. Fires exactly once per (modelId, capability) pair per process.\r\n *\r\n * Adapters call this from inside their `rememberConstraint`-equivalent path\r\n * the first time a specific constraint is learned. Subsequent calls to\r\n * `remember` the same constraint stay silent (the adapter's retry loop\r\n * still operates normally; only the warning is gated).\r\n */\r\nexport function emitFirstLearningWarning(event: FirstLearningEvent): void {\r\n  const key = `${event.modelId}::${event.capability}`;\r\n  if (warnedAlready.has(key)) return;\r\n  warnedAlready.add(key);\r\n\r\n  const url = buildLearningIssueUrl(event);\r\n  // Use the simplest form of console.warn to maximize compatibility with\r\n  // common log shippers (Vercel, Cloudflare Workers, AWS Lambda, etc.).\r\n  console.warn(\r\n    `[${event.packageName}] Model \"${event.modelId}\" rejected ${event.capability}. ` +\r\n      `Stripped for subsequent calls in this process.\\n\\n` +\r\n      `Help us improve the static catalog (one click, pre-filled): ${url}`,\r\n  );\r\n}\r\n\r\n/** Test-only: reset the per-process warning state. */\r\nexport function _resetWarnedState(): void {\r\n  warnedAlready.clear();\r\n}\r\n\r\n/**\r\n * Derive a sensible `area:adapter-<name>` label from a package name like\r\n * `@llm-ports/adapter-anthropic`. Returns null for packages outside that\r\n * pattern.\r\n */\r\nfunction derivePackageAreaLabel(packageName: string): string | null {\r\n  const match = /^@llm-ports\\/adapter-([a-z0-9-]+)$/i.exec(packageName);\r\n  if (!match) return null;\r\n  return `area:adapter-${match[1]}`;\r\n}\r\n","/**\n * Idempotent error-wrapping helper for adapter implementations.\n *\n * Every adapter's `messages.create` / `chat.completions.create` call wraps\n * the inner SDK call in try/catch and pipes the error through this helper\n * before throwing it out of the LLMPort method. The contract:\n *\n *   - Typed framework errors pass through unchanged. These are intentional\n *     signals from upstream code; double-wrapping them would hide their\n *     type from the caller's try/catch.\n *\n *   - HTTP-shaped SDK errors get classified into the new alpha.18 typed\n *     taxonomy: 400-context-window → ContextWindowExceededError; 400-policy\n *     → ContentPolicyViolationError; 401/403 → AuthenticationError; 429 →\n *     RateLimitError (with parsed retryAfterMs); 502/503/504 →\n *     ServiceUnavailableError; everything else → ProviderUnavailableError.\n *\n *   - Non-Error values (strings, undefined, primitives) are stringified\n *     into an Error first, then classified.\n *\n * Hoisted from per-adapter copies in alpha.3; HTTP classification added in\n * alpha.18 (TD-LLMPORTS-TYPED-ERRORS).\n */\n\nimport {\n  AdapterInternalError,\n  AuthenticationError,\n  BadRequestError,\n  ContentPolicyViolationError,\n  ContextWindowExceededError,\n  EmptyResponseError,\n  LLMPortError,\n  ProviderUnavailableError,\n  RateLimitError,\n  ServiceUnavailableError,\n} from \"../errors.js\";\n\n/**\n * Extract HTTP status code from an SDK error if present. Provider SDKs\n * (OpenAI, Anthropic, Google Gemini) all expose `.status` on their error\n * classes; fetch-based errors may put it on `.response.status`.\n */\nfunction extractStatus(err: Error): number | undefined {\n  const e = err as unknown as {\n    status?: number;\n    statusCode?: number;\n    response?: { status?: number };\n  };\n  return e.status ?? e.statusCode ?? e.response?.status;\n}\n\n/**\n * Parse a Retry-After header value (seconds or HTTP-date) or\n * retry-after-ms (milliseconds) into milliseconds. Returns undefined when\n * no usable value is present.\n */\nfunction extractRetryAfterMs(err: Error): number | undefined {\n  const e = err as unknown as {\n    headers?: Record<string, string | undefined>;\n    response?: { headers?: Record<string, string | undefined> };\n  };\n  const headers = e.headers ?? e.response?.headers;\n  if (!headers) return undefined;\n\n  // Anthropic exposes both retry-after-ms (preferred) and retry-after.\n  const ms = headers[\"retry-after-ms\"];\n  if (ms) {\n    const n = Number(ms);\n    if (Number.isFinite(n) && n >= 0) return n;\n  }\n  const after = headers[\"retry-after\"];\n  if (after) {\n    const n = Number(after);\n    if (Number.isFinite(n) && n >= 0) return n * 1000;\n    // HTTP-date form: parse and subtract now.\n    const dateMs = Date.parse(after);\n    if (Number.isFinite(dateMs)) {\n      return Math.max(0, dateMs - Date.now());\n    }\n  }\n  return undefined;\n}\n\n/**\n * Heuristic detector for the two BadRequestError subclasses. Provider error\n * messages are not standardized, but the patterns are well-known across\n * OpenAI, Anthropic, Google, and the OpenAI-compat providers.\n */\nfunction detectBadRequestKind(\n  message: string,\n): \"context-window\" | \"content-policy\" | undefined {\n  const m = message.toLowerCase();\n  if (\n    m.includes(\"context length\") ||\n    m.includes(\"context window\") ||\n    m.includes(\"maximum context\") ||\n    m.includes(\"tokens in the input\") ||\n    m.includes(\"prompt is too long\") ||\n    m.includes(\"requested tokens exceed\")\n  ) {\n    return \"context-window\";\n  }\n  if (\n    m.includes(\"content policy\") ||\n    m.includes(\"content_policy\") ||\n    m.includes(\"safety\") ||\n    m.includes(\"safety_classifier\") ||\n    m.includes(\"flagged by\") ||\n    m.includes(\"policy violation\")\n  ) {\n    return \"content-policy\";\n  }\n  return undefined;\n}\n\n/**\n * Wrap an unknown caught error as a typed framework error.\n *\n * Idempotent on every `LLMPortError` subclass (including subclasses added\n * in alpha.18: `BadRequestError`, `AuthenticationError`, `RateLimitError`,\n * `ServiceUnavailableError`, and their descendants).\n *\n * For raw SDK errors, classifies into the right typed class by HTTP status\n * + message pattern. For non-Error inputs, stringifies first.\n *\n * Adapter authors can opt into more precise typing by extracting their\n * SDK-specific error fields (e.g. OpenAI's `param`, Anthropic's\n * `error.type`) and constructing the typed error directly; this helper is\n * the catch-all fallback when adapters haven't customized.\n *\n * The optional `modelId` argument, added in alpha.28 pre-work (TD-LLMP-16),\n * is threaded into the `ContextWindowExceededError` and\n * `ContentPolicyViolationError` constructors so the resulting error carries\n * the model name that was in play at request-construction time. Adapter\n * authors should pass `req.modelId` (or equivalent) at every call site\n * inside a per-call code path; call sites outside a per-call path (e.g.\n * `listModels`) may omit it. When omitted, the error's `modelId` field\n * falls back to the legacy `\"(unknown)\"` placeholder for backwards compat.\n */\nexport function wrapProviderError(\n  alias: string,\n  err: unknown,\n  modelId?: string,\n): Error {\n  // Pass-through: any LLMPortError subclass is already typed.\n  if (err instanceof LLMPortError) return err;\n\n  // Pass-through: ValidationError predates LLMPortError extension; keep\n  // by-name check as a safety net for any code paths still constructing\n  // it without the base class.\n  if (err instanceof Error && err.name === \"ValidationError\") return err;\n\n  // Local JS runtime errors (TypeError, ReferenceError, SyntaxError) are\n  // almost always adapter or registry bugs, not provider-side failures.\n  // Wrap them as AdapterInternalError so the walk-table policy aborts\n  // rather than triggering futile chain-wide failover. Added in alpha.28\n  // pre-work (TD-LLMP-17). Prior to this fix, a local TypeError from\n  // adapter code was misclassified as ServiceUnavailableError, causing\n  // the registry to walk the entire chain re-throwing the same identical\n  // local error at every hop while operators saw \"service unavailable\"\n  // and checked the provider status page.\n  if (\n    err instanceof TypeError ||\n    err instanceof ReferenceError ||\n    err instanceof SyntaxError\n  ) {\n    return new AdapterInternalError(alias, err.message, err);\n  }\n\n  // Stringify non-Error inputs.\n  if (!(err instanceof Error)) {\n    return new ProviderUnavailableError(alias, new Error(String(err)));\n  }\n\n  // Classify by HTTP status when available.\n  const status = extractStatus(err);\n  const message = err.message ?? String(err);\n  const resolvedModelId = modelId ?? \"(unknown)\";\n\n  if (status === 400) {\n    const kind = detectBadRequestKind(message);\n    if (kind === \"context-window\") {\n      return new ContextWindowExceededError(\n        alias,\n        resolvedModelId,\n        undefined,\n        undefined,\n        err,\n      );\n    }\n    if (kind === \"content-policy\") {\n      return new ContentPolicyViolationError(\n        alias,\n        resolvedModelId,\n        message,\n        err,\n      );\n    }\n    // Generic 400 → BadRequest with raw message.\n    return new BadRequestError(alias, message, err);\n  }\n\n  if (status === 401 || status === 403) {\n    return new AuthenticationError(alias, message, err);\n  }\n\n  if (status === 429) {\n    const retryAfterMs = extractRetryAfterMs(err);\n    return new RateLimitError(alias, message, retryAfterMs, err);\n  }\n\n  if (status !== undefined && status >= 500 && status < 600) {\n    return new ServiceUnavailableError(alias, message, err);\n  }\n\n  // Unknown / no status → treat as provider unavailable (default behavior\n  // matching alpha.17 semantics).\n  return new ProviderUnavailableError(alias, err);\n}\n\n// Empty response is a typed signal, not an SDK error. Re-export for adapter\n// authors who construct it directly.\nexport { EmptyResponseError };\n","/**\r\n * Convert a `MessageContent` (either a plain string or an array of content\r\n * blocks) into a single string. Used by adapter implementations when they\r\n * need to log a prompt, fall back from rich content to plain text, or\r\n * inject a string-shaped prompt into a provider that doesn't accept block\r\n * arrays for a given message role.\r\n *\r\n * Non-text blocks (image, audio, tool_use, tool_result) are rendered as\r\n * `[block-type ...]` placeholders. This preserves the structural information\r\n * without producing garbage if the caller later logs the string.\r\n *\r\n * Hoisted from per-adapter copies in alpha.3. Every adapter that previously\r\n * wrote its own `stringifyPrompt(content)` now imports this.\r\n */\r\n\r\nimport type { MessageContent } from \"../content/blocks.js\";\r\n\r\n/**\r\n * Render `MessageContent` as a string. Text blocks contribute their text\r\n * verbatim; other block types contribute a `[type ...]` placeholder.\r\n */\r\nexport function stringifyContentBlocks(content: MessageContent): string {\r\n  if (typeof content === \"string\") return content;\r\n  return content\r\n    .map((block) => {\r\n      if (block.type === \"text\") return block.text;\r\n      if (block.type === \"image\") return \"[image content]\";\r\n      if (block.type === \"audio\") return \"[audio content]\";\r\n      if (block.type === \"tool_use\") return `[tool_use ${block.name}]`;\r\n      if (block.type === \"tool_result\") return `[tool_result for ${block.toolUseId}]`;\r\n      return \"[non-text block]\";\r\n    })\r\n    .join(\"\\n\");\r\n}\r\n","/**\r\n * JSON helpers used by adapters for structured-output and streaming-structured\r\n * paths.\r\n *\r\n *   - `extractJSON(raw)`: parses a string that may include markdown fences\r\n *     and surrounding prose into a JavaScript value. Throws on parse failure\r\n *     (callers handle the failure via the retry-with-feedback validation\r\n *     strategy upstream). Falls back to `jsonrepair` when plain JSON.parse\r\n *     fails, which catches trailing commas, single quotes, smart quotes,\r\n *     Python-style None/True/False, unquoted keys, comments, and most other\r\n *     LLM-quirk syntactic issues.\r\n *\r\n *   - `tryParsePartialJSON(buffer)`: best-effort parse of an in-progress\r\n *     streaming buffer. Returns `null` if no JSON can yet be recovered;\r\n *     returns the parsed value if balancing the buffer's open braces /\r\n *     brackets and trimming trailing commas produces a valid parse.\r\n *\r\n * Hoisted from per-adapter copies in alpha.3. jsonrepair fallback added in\r\n * alpha.5 to reduce retry-with-feedback round-trips on syntactic quirks.\r\n */\r\n\r\nimport { jsonrepair } from \"jsonrepair\";\r\n\r\n/**\r\n * Parse a JSON value out of a string that may be wrapped in markdown fences\r\n * or have leading/trailing prose. Throws on parse failure.\r\n *\r\n * Strategy:\r\n *   1. If wrapped in a ```json ... ``` or ``` ... ``` fence, extract the\r\n *      inner content.\r\n *   2. Find the first `{` and the last `}`. If both exist and `{` precedes\r\n *      `}`, parse the slice.\r\n *   3. If the parse fails, run the candidate through `jsonrepair` and try\r\n *      again. This catches trailing commas, smart quotes, single quotes,\r\n *      Python literals, unquoted keys, comments, and most syntactic LLM\r\n *      quirks before we waste a retry-with-feedback round-trip.\r\n *   4. If repair also fails, surface the underlying SyntaxError to the\r\n *      caller (validation strategy decides whether to retry against the LLM).\r\n */\r\nexport function extractJSON(raw: string): unknown {\r\n  const fenced = raw.match(/```(?:json)?\\s*([\\s\\S]*?)\\s*```/i);\r\n  const candidate = fenced?.[1] ?? raw;\r\n  const start = candidate.indexOf(\"{\");\r\n  const end = candidate.lastIndexOf(\"}\");\r\n  const sliced =\r\n    start === -1 || end === -1 || end <= start\r\n      ? candidate\r\n      : candidate.slice(start, end + 1);\r\n  try {\r\n    return JSON.parse(sliced);\r\n  } catch (parseErr) {\r\n    // Only fall back to jsonrepair when the input has structural JSON markers\r\n    // (a brace or bracket). Otherwise jsonrepair will happily wrap arbitrary\r\n    // prose like \"not even json\" in quotes and call it a valid JSON string —\r\n    // which silently breaks every caller that expected an object or array.\r\n    if (!sliced.includes(\"{\") && !sliced.includes(\"[\")) {\r\n      throw parseErr;\r\n    }\r\n    try {\r\n      return JSON.parse(jsonrepair(sliced));\r\n    } catch {\r\n      // Surface the ORIGINAL parse error, not the repair error — its message\r\n      // is the actually-useful diagnostic for retry-with-feedback.\r\n      throw parseErr;\r\n    }\r\n  }\r\n}\r\n\r\n/**\r\n * Best-effort parse of an in-progress streaming JSON buffer.\r\n *\r\n * Returns the parsed value if either:\r\n *   - The buffer is already complete and parses cleanly, OR\r\n *   - Balancing the buffer's open `{`/`[` against close `}`/`]` and trimming\r\n *     trailing commas produces a valid parse.\r\n *\r\n * Returns `null` if no `{` is present yet, or if no balancing strategy\r\n * recovers a valid JSON value. Adapters call this on every streaming chunk\r\n * append; the result is yielded as a `Partial<T>` to consumers.\r\n */\r\nexport function tryParsePartialJSON(buffer: string): unknown | null {\r\n  try {\r\n    const start = buffer.indexOf(\"{\");\r\n    if (start === -1) return null;\r\n    return JSON.parse(buffer.slice(start));\r\n  } catch {\r\n    // Build a stack of expected closing brackets while scanning, so we close\r\n    // in the correct reverse order. Track string boundaries so `{`/`[`/`}`/`]`\r\n    // inside a string literal don't perturb the stack.\r\n    //\r\n    // Note: this fix corrects a bug from the per-adapter implementations that\r\n    // simply counted braces and brackets independently and appended `}` then `]`.\r\n    // That broke on inputs like `{\"items\": [1, 2, 3` where the correct close\r\n    // order is `]` then `}`.\r\n    const stack: string[] = [];\r\n    let inString = false;\r\n    let escape = false;\r\n    for (const ch of buffer) {\r\n      if (escape) {\r\n        escape = false;\r\n        continue;\r\n      }\r\n      if (inString) {\r\n        if (ch === \"\\\\\") escape = true;\r\n        else if (ch === '\"') inString = false;\r\n        continue;\r\n      }\r\n      if (ch === '\"') inString = true;\r\n      else if (ch === \"{\") stack.push(\"}\");\r\n      else if (ch === \"[\") stack.push(\"]\");\r\n      else if (ch === \"}\" || ch === \"]\") stack.pop();\r\n    }\r\n\r\n    let attempt = buffer;\r\n    if (inString) attempt += '\"';\r\n    while (stack.length > 0) {\r\n      attempt += stack.pop();\r\n    }\r\n    attempt = attempt.replace(/,\\s*([}\\]])/g, \"$1\");\r\n\r\n    try {\r\n      const start = attempt.indexOf(\"{\");\r\n      if (start === -1) return null;\r\n      return JSON.parse(attempt.slice(start));\r\n    } catch {\r\n      return null;\r\n    }\r\n  }\r\n}\r\n","/**\r\n * Token-usage helpers shared across adapters.\r\n *\r\n * Each adapter has its own `parseUsage(response)` because provider response\r\n * shapes differ. But once parsed into a `TokenUsage` value, the math (adding\r\n * usage across multiple turns of an agent loop, or across multiple retries\r\n * of a structured-output call) is identical.\r\n *\r\n * Hoisted from per-adapter copies in alpha.3.\r\n */\r\n\r\nimport type { TokenUsage } from \"../ports/llm-port.js\";\r\n\r\n/**\r\n * Add two `TokenUsage` values. Preserves the optional `cacheReadTokens` and\r\n * `reasoningTokens` fields when at least one operand has them.\r\n *\r\n * Used by adapters in `runAgent` (each tool-use step contributes usage) and\r\n * in `generateStructured` (when retry-with-feedback fires; each attempt\r\n * contributes usage).\r\n */\r\nexport function mergeTokenUsage(a: TokenUsage, b: TokenUsage): TokenUsage {\r\n  const hasCacheRead = a.cacheReadTokens !== undefined || b.cacheReadTokens !== undefined;\r\n  const hasCacheWrite = a.cacheWriteTokens !== undefined || b.cacheWriteTokens !== undefined;\r\n  const hasReasoning = a.reasoningTokens !== undefined || b.reasoningTokens !== undefined;\r\n  return {\r\n    inputTokens: a.inputTokens + b.inputTokens,\r\n    outputTokens: a.outputTokens + b.outputTokens,\r\n    totalTokens: a.totalTokens + b.totalTokens,\r\n    ...(hasCacheRead\r\n      ? { cacheReadTokens: (a.cacheReadTokens ?? 0) + (b.cacheReadTokens ?? 0) }\r\n      : {}),\r\n    ...(hasCacheWrite\r\n      ? { cacheWriteTokens: (a.cacheWriteTokens ?? 0) + (b.cacheWriteTokens ?? 0) }\r\n      : {}),\r\n    ...(hasReasoning\r\n      ? { reasoningTokens: (a.reasoningTokens ?? 0) + (b.reasoningTokens ?? 0) }\r\n      : {}),\r\n  };\r\n}\r\n","/**\r\n * Deterministic programmatic repair for Zod validation failures.\r\n *\r\n * Inspects a `ZodError`'s issues and applies type-coercion / null-deletion\r\n * fixes BEFORE the validation-strategy fires a retry-with-feedback round-trip\r\n * against the LLM. Each repair pattern represents a known LLM quirk that an\r\n * LLM round-trip is overkill to fix.\r\n *\r\n * The 8 patterns this catches (each one avoids ~1 LLM retry):\r\n *\r\n *   1. `null` where a non-null type is expected → delete key\r\n *      (lets `.optional()` schemas accept the absence)\r\n *   2. string `\"9\"` where `number` is expected → `Number(\"9\")` → `9`\r\n *   3. string `\"true\"` / `\"false\"` where `boolean` is expected → real booleans\r\n *   4. number `9` where `string` is expected → `String(9)` → `\"9\"`\r\n *   5. enum value with case / whitespace / markdown drift\r\n *      (`\"HIGH\"`, `\"**low**\"`, `'\"medium\"'`, \"Low \") →\r\n *      strip wrappers + `.toLowerCase().trim()`\r\n *   6. `null` inside an optional union (`z.string().nullable().optional()`) →\r\n *      delete key\r\n *   7. (alpha.13+) stringified JSON where object/array expected:\r\n *      `'{\"a\":1}'` → `JSON.parse(...)` → `{a: 1}` when the string starts/ends\r\n *      with `{}` or `[]`. Catches the \"model double-encodes nested objects\"\r\n *      quirk seen on some compat providers (e.g. MiniMax returns\r\n *      `reasoning: \"{\\\"experience\\\": ...}\"` for an object-typed field).\r\n *   8. (alpha.13+) array where object expected with a single-element array\r\n *      containing an object: `[{...}]` → `{...}`. Catches \"model wrapped a\r\n *      singular field as an array\" misreads of the schema.\r\n *\r\n * Strategy:\r\n *\r\n *   1. Run `schema.safeParse(raw)`.\r\n *   2. If it fails, call `attemptRepair(raw, error)` to produce a repaired\r\n *      candidate (does NOT mutate the input).\r\n *   3. Re-run `schema.safeParse(repaired)`.\r\n *   4. If the second parse succeeds, return it. Saves an LLM round-trip.\r\n *   5. If the second parse still fails, hand off to the validation strategy\r\n *      (retry-with-feedback OR fallback-to-next-provider, configured at port\r\n *      creation).\r\n *\r\n * Ported from BEPA (Babak's Executive Personal Assistant) where this repair\r\n * has been running in production for ~6 months. The 6 patterns are exactly\r\n * the ones BEPA observed across millions of LLM calls against Claude,\r\n * GPT, GPT-OSS, Qwen, Cerebras gpt-oss, and Ollama models.\r\n *\r\n * Note on Zod compatibility: this code reads `issue.code` and `issue.expected`\r\n * which are stable across Zod v3 + v4. The `invalid_enum_value` code name\r\n * changed to `invalid_value` in Zod v4; we match both.\r\n */\r\n\r\nimport type { ZodError, ZodIssue } from \"zod\";\r\n\r\n/**\r\n * Apply deterministic repairs to `raw` based on a `ZodError`. Returns a\r\n * structurally-cloned, repaired copy. Does not mutate the input.\r\n *\r\n * Safe to call even if `raw` is not an object — non-object input is returned\r\n * as-is.\r\n */\r\nexport function attemptValidationRepair(raw: unknown, error: ZodError): unknown {\r\n  if (!raw || typeof raw !== \"object\") return raw;\r\n  const data = structuredClone(raw) as Record<string, unknown>;\r\n\r\n  for (const issue of error.issues) {\r\n    applyFix(data, issue);\r\n  }\r\n\r\n  return data;\r\n}\r\n\r\nfunction applyFix(root: Record<string, unknown>, issue: ZodIssue): void {\r\n  const path = issue.path;\r\n  if (path.length === 0) return;\r\n\r\n  const target = resolvePath(root, path.slice(0, -1));\r\n  if (!target || typeof target !== \"object\") return;\r\n\r\n  const key = String(path[path.length - 1]);\r\n  const obj = target as Record<string, unknown>;\r\n  const current = obj[key];\r\n\r\n  // Zod v4 changed the issue code for enum/literal mismatches from\r\n  // `invalid_enum_value` to `invalid_value`. Match both so this works\r\n  // across the peer-dependency range `zod >=3.24.0 <5`.\r\n  const code = issue.code as string;\r\n\r\n  switch (code) {\r\n    case \"invalid_type\": {\r\n      const expected = (issue as { expected?: unknown }).expected;\r\n      // null → undefined (delete key so .optional() works)\r\n      if (current === null && expected !== \"null\") {\r\n        delete obj[key];\r\n        break;\r\n      }\r\n      // string → number\r\n      if (expected === \"number\" && typeof current === \"string\") {\r\n        const num = Number(current);\r\n        if (!Number.isNaN(num)) obj[key] = num;\r\n        break;\r\n      }\r\n      // string → boolean\r\n      if (expected === \"boolean\" && typeof current === \"string\") {\r\n        if (current === \"true\") obj[key] = true;\r\n        else if (current === \"false\") obj[key] = false;\r\n        break;\r\n      }\r\n      // number → string\r\n      if (expected === \"string\" && typeof current === \"number\") {\r\n        obj[key] = String(current);\r\n        break;\r\n      }\r\n      // Pattern 7 (alpha.13): stringified JSON where object/array expected.\r\n      // Some compat providers double-encode nested fields; if the string\r\n      // looks like JSON (`{...}` or `[...]`), try parsing once. Only\r\n      // assign back if parse succeeds AND the parsed shape matches the\r\n      // expected category — otherwise we'd risk replacing a legitimate\r\n      // string with parsed junk.\r\n      if (\r\n        (expected === \"object\" || expected === \"array\") &&\r\n        typeof current === \"string\"\r\n      ) {\r\n        const trimmed = current.trim();\r\n        const looksLikeObject =\r\n          expected === \"object\" && trimmed.startsWith(\"{\") && trimmed.endsWith(\"}\");\r\n        const looksLikeArray =\r\n          expected === \"array\" && trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\");\r\n        if (looksLikeObject || looksLikeArray) {\r\n          try {\r\n            const parsed = JSON.parse(trimmed) as unknown;\r\n            const matchesShape =\r\n              (expected === \"object\" &&\r\n                parsed !== null &&\r\n                typeof parsed === \"object\" &&\r\n                !Array.isArray(parsed)) ||\r\n              (expected === \"array\" && Array.isArray(parsed));\r\n            if (matchesShape) {\r\n              obj[key] = parsed;\r\n            }\r\n          } catch {\r\n            // Not valid JSON; leave as-is so retry-with-feedback can ask\r\n            // the model to fix it.\r\n          }\r\n        }\r\n        break;\r\n      }\r\n      // Pattern 8 (alpha.13): array-with-single-object where object expected.\r\n      // Common when the model misreads the schema for a singular field and\r\n      // wraps the answer in an array.\r\n      if (\r\n        expected === \"object\" &&\r\n        Array.isArray(current) &&\r\n        current.length === 1 &&\r\n        current[0] !== null &&\r\n        typeof current[0] === \"object\" &&\r\n        !Array.isArray(current[0])\r\n      ) {\r\n        obj[key] = current[0];\r\n        break;\r\n      }\r\n      break;\r\n    }\r\n\r\n    case \"invalid_enum_value\":\r\n    case \"invalid_value\":\r\n      // Case + whitespace + markdown / quote-wrapper normalization for enum\r\n      // / literal mismatches. Catches:\r\n      //   \"HIGH\" / \"Low \" → \"high\" / \"low\"\r\n      //   \"**low**\"       → \"low\"  (markdown wrap)\r\n      //   '\"medium\"'      → \"medium\"  (model quoted the value)\r\n      //   \"`low`\"         → \"low\"  (model code-fenced it)\r\n      //   \"shared‑lib\"    → \"shared-lib\"  (U+2011 non-breaking hyphen → ASCII;\r\n      //                    added alpha.28 pre-work TD-LLMP-18)\r\n      if (typeof current === \"string\") {\r\n        obj[key] = stripEnumDecorators(normalizeUnicodeConfusables(current));\r\n      }\r\n      break;\r\n\r\n    case \"invalid_union\":\r\n      // null inside an optional union (e.g. `z.string().nullable().optional()`)\r\n      // → delete the key so the optional branch can succeed.\r\n      if (current === null) {\r\n        delete obj[key];\r\n      }\r\n      break;\r\n  }\r\n}\r\n\r\n/**\r\n * Normalize Unicode confusables of ASCII delimiter characters used in\r\n * enum literals. Models occasionally emit typographic variants\r\n * (U+2011 non-breaking hyphen instead of U+002D ASCII hyphen-minus,\r\n * curly quotes instead of straight, non-breaking spaces instead of\r\n * ASCII spaces, fullwidth punctuation on Chinese-tuned models) that\r\n * break Zod's byte-exact enum matching without any semantic\r\n * difference to the caller's intent.\r\n *\r\n * Content-preserving: only fires inside the `invalid_enum_value` /\r\n * `invalid_value` repair branch, so free-text `z.string()` fields\r\n * where an em dash or curly quote is deliberate are never touched.\r\n *\r\n * Added in alpha.28 pre-work (TD-LLMP-18) after ADW production\r\n * observed U+2011 non-breaking hyphen in `\"shared-lib\"` breaking\r\n * their guardrails Zod enum validation. BEPA has three parallel\r\n * exposures (venture / interaction-type / call-triage-category\r\n * enums with hyphenated values).\r\n */\r\nfunction normalizeUnicodeConfusables(s: string): string {\r\n  return s\r\n    // Hyphens / dashes: U+2010..U+2015 (hyphen through horizontal bar) +\r\n    // U+2212 minus sign + U+FF0D fullwidth hyphen-minus → ASCII '-'\r\n    .replace(/[‐‑‒–—―−－]/g, \"-\")\r\n    // Single quotes: U+2018 left / U+2019 right → ASCII apostrophe\r\n    .replace(/[‘’]/g, \"'\")\r\n    // Double quotes: U+201C left / U+201D right → ASCII quote\r\n    .replace(/[“”]/g, '\"')\r\n    // Spaces: U+00A0 non-breaking + U+2007 figure + U+2008 punctuation +\r\n    // U+2009 thin + U+202F narrow-no-break + U+205F medium-math + U+3000\r\n    // ideographic → ASCII space\r\n    .replace(/[      　]/g, \" \");\r\n}\r\n\r\n/**\r\n * Strip common LLM-output decorators from a candidate enum value before\r\n * normalizing. Loops the strip pipeline until no further changes, then\r\n * lowercases. Handles compound cases like `'**LOW**.'` (trailing punct\r\n * outside the markdown wrap) and `'\"**low**\"'` (quoted-then-bolded).\r\n */\r\nfunction stripEnumDecorators(s: string): string {\r\n  let v = s.trim();\r\n  for (let i = 0; i < 4; i++) {\r\n    const before = v;\r\n    // Strip trailing punctuation first so it doesn't block a wrapper match.\r\n    v = v.replace(/[.,;!?]+$/, \"\").trim();\r\n    // Strip surrounding markdown bold / italic\r\n    if (v.startsWith(\"**\") && v.endsWith(\"**\") && v.length >= 4) {\r\n      v = v.slice(2, -2);\r\n    } else if (v.startsWith(\"__\") && v.endsWith(\"__\") && v.length >= 4) {\r\n      v = v.slice(2, -2);\r\n    } else if (\r\n      (v.startsWith(\"*\") && v.endsWith(\"*\") && v.length >= 2) ||\r\n      (v.startsWith(\"_\") && v.endsWith(\"_\") && v.length >= 2)\r\n    ) {\r\n      v = v.slice(1, -1);\r\n    }\r\n    // Strip surrounding code-fence backticks\r\n    if (v.startsWith(\"`\") && v.endsWith(\"`\") && v.length >= 2) {\r\n      v = v.slice(1, -1);\r\n    }\r\n    // Strip surrounding quotes\r\n    if (\r\n      (v.startsWith('\"') && v.endsWith('\"') && v.length >= 2) ||\r\n      (v.startsWith(\"'\") && v.endsWith(\"'\") && v.length >= 2)\r\n    ) {\r\n      v = v.slice(1, -1);\r\n    }\r\n    v = v.trim();\r\n    if (v === before) break;\r\n  }\r\n  return v.toLowerCase();\r\n}\r\n\r\nfunction resolvePath(obj: unknown, path: ReadonlyArray<string | number>): unknown {\r\n  let current: unknown = obj;\r\n  for (const key of path) {\r\n    if (!current || typeof current !== \"object\") return null;\r\n    current = (current as Record<string, unknown>)[String(key)];\r\n  }\r\n  return current;\r\n}\r\n","/**\r\n * Adapter-boundary validation for `ImageBlock` content.\r\n *\r\n * Catches two classes of errors before the SDK call so the caller sees a\r\n * typed error instead of an opaque provider 4xx wrapped as\r\n * `ProviderUnavailableError`:\r\n *\r\n *   - **Size**: base64-encoded image exceeds the provider's documented limit.\r\n *     Throws `ImageTooLargeError` carrying the byte size + the limit.\r\n *\r\n *   - **URL shape**: URL-form image with a `file://`, `data:`, or\r\n *     no-scheme URL. Throws `InvalidImageUrlError` carrying the offending\r\n *     URL + reason.\r\n *\r\n * Each adapter calls `validateImageBlocks(blocks, opts)` on every outgoing\r\n * `ContentBlock[]` before constructing the provider-native payload.\r\n *\r\n * Limits and behavior are intentionally adapter-tunable: Anthropic ships\r\n * with a 5MB default, OpenAI with 20MB, Ollama with no enforced limit (model-\r\n * dependent; caller responsibility). Each adapter wires its own default\r\n * through `validateImageBlocks({ limitBytes })`.\r\n */\r\n\r\nimport type { ContentBlock } from \"../content/blocks.js\";\r\nimport { ImageTooLargeError, InvalidImageUrlError } from \"../errors.js\";\r\n\r\nexport interface ValidateImageOptions {\r\n  /** Provider alias for error messages. */\r\n  alias: string;\r\n  /**\r\n   * Maximum bytes per base64 image. If undefined, size validation is skipped\r\n   * (use this for Ollama where the limit is model-dependent).\r\n   */\r\n  limitBytes?: number;\r\n  /**\r\n   * Whether to allow `file://` URLs. Default false — file URLs almost always\r\n   * indicate a caller mistake (the file is on the caller's machine; the\r\n   * provider can't reach it).\r\n   */\r\n  allowFileUrl?: boolean;\r\n}\r\n\r\n/**\r\n * Validate every ImageBlock in a ContentBlock array. Throws on the first\r\n * violation with a typed error.\r\n *\r\n * Non-image blocks are skipped. Recursively descends into ToolResult blocks\r\n * since those can carry nested ImageBlocks.\r\n */\r\nexport function validateImageBlocks(\r\n  blocks: ReadonlyArray<ContentBlock>,\r\n  opts: ValidateImageOptions,\r\n): void {\r\n  blocks.forEach((block, index) => validateBlock(block, index, opts));\r\n}\r\n\r\nfunction validateBlock(\r\n  block: ContentBlock,\r\n  index: number,\r\n  opts: ValidateImageOptions,\r\n): void {\r\n  if (block.type === \"tool_result\") {\r\n    if (typeof block.content !== \"string\") {\r\n      validateImageBlocks(block.content, opts);\r\n    }\r\n    return;\r\n  }\r\n  if (block.type !== \"image\") return;\r\n\r\n  // URL-form validation\r\n  if (block.source.kind === \"url\") {\r\n    validateImageUrl(block.source.url, opts.alias, opts.allowFileUrl === true);\r\n    return;\r\n  }\r\n\r\n  // base64-form size validation\r\n  if (opts.limitBytes !== undefined) {\r\n    const byteSize = base64ByteSize(block.source.data);\r\n    if (byteSize > opts.limitBytes) {\r\n      throw new ImageTooLargeError(opts.alias, index, byteSize, opts.limitBytes);\r\n    }\r\n  }\r\n}\r\n\r\n/**\r\n * Validate an image URL's shape. Rejects `file://`, `data:`, and\r\n * no-scheme strings. Accepts `http://` and `https://`. Use `allowFileUrl`\r\n * to override (test environments may want it).\r\n */\r\nexport function validateImageUrl(\r\n  url: string,\r\n  alias: string,\r\n  allowFileUrl: boolean,\r\n): void {\r\n  const trimmed = url.trim();\r\n\r\n  if (trimmed.length === 0) {\r\n    throw new InvalidImageUrlError(alias, url, \"URL is empty\");\r\n  }\r\n\r\n  if (trimmed.startsWith(\"data:\")) {\r\n    throw new InvalidImageUrlError(\r\n      alias,\r\n      url,\r\n      \"data: URI passed as URL; use kind: 'base64' with the raw data + mediaType instead\",\r\n    );\r\n  }\r\n\r\n  if (trimmed.startsWith(\"file://\")) {\r\n    if (!allowFileUrl) {\r\n      throw new InvalidImageUrlError(\r\n        alias,\r\n        url,\r\n        \"file:// URLs are not fetchable by remote providers; pass the file contents as kind: 'base64' instead\",\r\n      );\r\n    }\r\n    return;\r\n  }\r\n\r\n  // Must have an http(s) scheme. Anything else (relative paths, ftp://, etc.)\r\n  // is almost certainly a caller mistake.\r\n  if (!trimmed.startsWith(\"http://\") && !trimmed.startsWith(\"https://\")) {\r\n    throw new InvalidImageUrlError(\r\n      alias,\r\n      url,\r\n      \"URL must start with http:// or https://\",\r\n    );\r\n  }\r\n}\r\n\r\n/**\r\n * Compute the byte size of a base64-encoded payload. Base64 encodes every 3\r\n * bytes as 4 chars, padded to a multiple of 4 with `=`. So decoded byte size\r\n * = ceil(len * 3 / 4) - padding. We approximate as `(len * 3) / 4` which is\r\n * accurate to within 2 bytes; close enough for provider-limit comparison.\r\n */\r\nfunction base64ByteSize(data: string): number {\r\n  return Math.floor((data.length * 3) / 4);\r\n}\r\n","/**\r\n * AbortSignal entry-time check helper for adapter port methods.\r\n *\r\n * Each adapter calls `throwIfAborted(signal)` at the top of every port\r\n * method that accepts a `signal?: AbortSignal`. This avoids the boilerplate\r\n * of \"if (signal?.aborted) throw signal.reason ?? new Error(...)\" repeated\r\n * at every entry, and ensures consistent error shape across adapters.\r\n *\r\n * When the signal is undefined or not yet aborted, this is a no-op.\r\n *\r\n * The mid-flight cancellation (the more important half of the contract)\r\n * happens by passing `signal` to the underlying SDK call. This helper only\r\n * covers the entry-time fast-path.\r\n */\r\n\r\n/**\r\n * Throw if the given AbortSignal has already been aborted. No-op when\r\n * `signal` is undefined or not yet aborted.\r\n *\r\n * Honors `signal.reason` when present (modern AbortController convention);\r\n * falls back to a generic `AbortError`-shaped error otherwise.\r\n */\r\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\r\n  if (signal?.aborted) {\r\n    // signal.reason was added to the spec in 2022; widely available in\r\n    // Node 18+ and all modern browsers. Fall back to a sane default if\r\n    // the runtime predates it.\r\n    const reason =\r\n      (signal as { reason?: unknown }).reason ??\r\n      new DOMException(\"The operation was aborted.\", \"AbortError\");\r\n    throw reason;\r\n  }\r\n}\r\n","/**\n * `toMessages`, `sys`, `usr` — migration + construction helpers for the\n * canonical `messages: LLMMessage[]` input introduced in alpha.26.\n *\n * `toMessages(instructions, prompt)` is the one-line migration shim from the\n * legacy `{instructions, prompt}` shape. `sys()` and `usr()` are idiomatic\n * message-array constructors for hand-written call sites.\n *\n * None of these helpers do runtime validation beyond what's needed for\n * shape correctness — they're primitives, not gate-keepers. Empty strings,\n * empty content blocks, and other edge cases pass through and let the\n * provider throw its native error.\n *\n * Added in `0.1.0-alpha.26` (issue #TBD).\n */\n\nimport { PromptRequiredError } from \"../errors.js\";\nimport type { LLMMessage } from \"../ports/llm-port.js\";\nimport type { MessageContent } from \"../content/blocks.js\";\n\n/**\n * Convert the legacy `{instructions, prompt}` shape into the canonical\n * `messages: LLMMessage[]` shape. The one-line migration shim for\n * consumers upgrading from alpha.25 or earlier.\n *\n * Semantics:\n *   - If `instructions` is a non-empty string, emits a system-role message\n *     with that content first.\n *   - Emits a user-role message with `prompt` as the content.\n *   - Throws `PromptRequiredError` if `prompt` is missing — the shim is\n *     designed for the migrate-single-turn-call use case, and a missing\n *     prompt is a caller bug.\n *\n * @example\n *   port.generateText({\n *     taskType: \"triage\",\n *     messages: toMessages(SYSTEM_PROMPT, userInput),\n *   });\n */\nexport function toMessages(\n  instructions: string | undefined,\n  prompt: MessageContent,\n): LLMMessage[] {\n  if (prompt === undefined || prompt === null) throw new PromptRequiredError();\n  const out: LLMMessage[] = [];\n  if (typeof instructions === \"string\" && instructions.length > 0) {\n    out.push({ role: \"system\", content: instructions });\n  }\n  out.push({ role: \"user\", content: prompt });\n  return out;\n}\n\n/**\n * Idiomatic system-role message constructor.\n *\n * Accepts a plain string only. System prompts are almost always text; the\n * rare multimodal-system case constructs via object literal\n * (`{ role: \"system\", content: [...] }`).\n *\n * @example\n *   port.generateText({\n *     taskType: \"triage\",\n *     messages: [sys(\"Classify the message urgency.\"), usr(rawEmailBody)],\n *   });\n */\nexport function sys(content: string): LLMMessage {\n  return { role: \"system\", content };\n}\n\n/**\n * Idiomatic user-role message constructor.\n *\n * Accepts either a plain string or a structured `MessageContent` array\n * (text + image + audio content blocks).\n *\n * @example\n *   port.generateText({\n *     taskType: \"describe\",\n *     messages: [\n *       sys(\"Describe the image concisely.\"),\n *       usr([{ type: \"text\", text: \"What's in this?\" }, imageBlock]),\n *     ],\n *   });\n */\nexport function usr(content: MessageContent): LLMMessage {\n  return { role: \"user\", content };\n}\n","/**\n * Shared adapter helper for resolving the canonical `messages` + `instructions`\n * pair from the alpha.26 dual-shape call options.\n *\n * The Registry normalizes `{ instructions, prompt }` into `messages` before\n * dispatch, so in practice this helper mostly reads `options.messages`.\n * When called directly (bypassing the Registry), the helper also honors\n * the legacy `{ instructions, prompt }` fields.\n *\n * Semantics:\n *   - If `options.messages` is set: extract the LEADING contiguous system-\n *     role messages into a concatenated `instructions` string (Anthropic\n *     + Google adapters use a separate system field; the OpenAI shape keeps\n *     system inline but the helper centralizes the transform for\n *     consistency). Remaining messages become the user-visible message\n *     content.\n *   - Non-contiguous system messages (system in the middle of a\n *     conversation) pass through inline unchanged.\n *   - If `options.messages` is unset, fall back to a single-user-message\n *     shape from `options.prompt` and `options.instructions`.\n *   - When `options.messages` fully consumes into system content (no user\n *     turn), returns an empty messages array — the caller adapter can\n *     decide to error or synthesize a placeholder.\n *\n * Added in `0.1.0-alpha.26`.\n */\n\nimport type { LLMMessage } from \"../ports/llm-port.js\";\nimport type { MessageContent } from \"../content/blocks.js\";\n\n/**\n * Return the \"user-facing\" message content when the caller uses the legacy\n * `{prompt}` shape. Returns `undefined` when `messages` is set — the caller\n * should use `messages` directly in that case.\n */\nexport function resolveCanonicalMessages(options: {\n  messages?: LLMMessage[];\n  instructions?: string;\n  prompt?: MessageContent;\n}): { messages: LLMMessage[]; instructions: string | undefined } {\n  if (options.messages !== undefined && options.messages.length > 0) {\n    const arr = options.messages;\n    const leadingSystem: string[] = [];\n    let i = 0;\n    while (i < arr.length && arr[i]!.role === \"system\") {\n      const content = arr[i]!.content;\n      if (typeof content === \"string\") {\n        leadingSystem.push(content);\n      } else {\n        // Multimodal system content: flatten text blocks; if any non-text\n        // blocks are present, abort concatenation and let the system\n        // message pass through inline unchanged.\n        const textFragments: string[] = [];\n        let hasNonText = false;\n        for (const block of content) {\n          if ((block as { type: string }).type === \"text\") {\n            textFragments.push((block as { text: string }).text);\n          } else {\n            hasNonText = true;\n          }\n        }\n        if (hasNonText) break;\n        leadingSystem.push(textFragments.join(\"\"));\n      }\n      i++;\n    }\n    const instructions =\n      leadingSystem.length > 0 ? leadingSystem.join(\"\\n\\n\") : options.instructions;\n    const remaining = arr.slice(i);\n    return { messages: remaining, instructions };\n  }\n  // Legacy shape: synthesize a single user message from prompt.\n  if (options.prompt === undefined) {\n    return { messages: [], instructions: options.instructions };\n  }\n  return {\n    messages: [{ role: \"user\", content: options.prompt }],\n    instructions: options.instructions,\n  };\n}\n","/**\n * `withObservabilityContext(port, context)` — the scoped-port wrapper\n * for caller-provided observability context, per Plan 58 v0.4 §4.2.\n *\n * The port's public interface (`LLMPort`) stays untouched. Consumers\n * who want to attach correlation, W3C Trace Context, Baggage,\n * attributes, or an HMAC fingerprint key to every call flowing through\n * a port wrap it once at the workflow root:\n *\n *   const scoped = withObservabilityContext(port, {\n *     operation_id: workflowOperationId,\n *     traceparent: incomingHeader,\n *     baggage: [{ key: \"tenant_id\", value: tenantId }],\n *     attributes: { region: \"us-west\" },\n *     fingerprint_key: process.env.OBS_HMAC_KEY,\n *   });\n *\n *   await scoped.generateText({...});\n *\n * At alpha.28 the wrapper's runtime behavior is minimal: it stores the\n * context in a WeakMap keyed by the returned port instance and forwards\n * every method call to the underlying port unchanged. `getObservabilityContext(port)`\n * retrieves the context for a wrapped port; the runtime instrumentation\n * that consumes it lands in alpha.29 (runtime instrumentation release).\n *\n * Why a WeakMap: consumers who pass wrapped ports around retain the\n * context association without leaking (once no reference to the wrapped\n * port survives, the context entry is garbage-collected). Alternative\n * of storing the context on the port object itself would mutate the\n * shape and clash with the \"no LLMPort interface change\" commitment.\n *\n * Why not AsyncLocalStorage (option (b) from the earlier design\n * decision): scoped-port wrapper is cross-runtime (works in every JS\n * runtime including workers where ALS is missing or partial); testable\n * without ambient state; explicit at the call site whether context is\n * scoped; subprocess callers can construct their own scoped emitter\n * from @llm-ports/observability-contract without needing a port.\n * ALS can be layered on top later as an opt-in propagator for Node-\n * only consumers who prefer ambient magic.\n */\n\nimport type { ObservabilityContext } from \"@llm-ports/observability-contract\";\n\nimport type { LLMPort } from \"./ports/llm-port.js\";\n\n/**\n * The WeakMap that associates each wrapped port with its context.\n * Keyed by the wrapped port instance (the return value of\n * withObservabilityContext); collected when no reference survives.\n */\nconst contextByPort = new WeakMap<LLMPort, ObservabilityContext>();\n\n/**\n * Wrap a port so that all calls through the returned port carry the\n * caller-provided `ObservabilityContext`. The returned port is\n * indistinguishable from the input at the public LLMPort interface;\n * consumers who need the context call `getObservabilityContext(port)`.\n *\n * Wrapping is composable: `withObservabilityContext(scoped, moreContext)`\n * merges `moreContext` over the previous scope. Fields present on\n * `moreContext` override; fields absent inherit. Baggage arrays are\n * concatenated (later entries win on duplicate keys).\n */\nexport function withObservabilityContext<T extends LLMPort>(\n  port: T,\n  context: ObservabilityContext,\n): T {\n  // Merge with any prior context on the input port (composition).\n  const prior = contextByPort.get(port);\n  const merged: ObservabilityContext = prior ? mergeContext(prior, context) : { ...context };\n\n  // Build a fresh proxy that forwards every method call to the\n  // underlying port. Using a Proxy (rather than a fresh object with\n  // explicit methods) preserves any optional or future methods on\n  // LLMPort without needing to enumerate them here.\n  const wrapped = new Proxy(port, {\n    get(target, prop, receiver) {\n      const value = Reflect.get(target, prop, receiver);\n      // Bind methods to the underlying port so `this` remains correct\n      // when the caller destructures methods off the wrapped port.\n      if (typeof value === \"function\") {\n        return value.bind(target);\n      }\n      return value;\n    },\n  }) as T;\n\n  contextByPort.set(wrapped, merged);\n  return wrapped;\n}\n\n/**\n * Retrieve the ObservabilityContext associated with a wrapped port.\n * Returns undefined for ports that were not wrapped via\n * `withObservabilityContext`.\n *\n * Alpha.28 exposes this as the low-level reader that alpha.29's runtime\n * instrumentation calls to stamp context onto emitted events.\n * Consumers writing their own emit paths (per §4.13 non-port callers)\n * also use this to read a context they scoped at a higher layer.\n */\nexport function getObservabilityContext(port: LLMPort): ObservabilityContext | undefined {\n  return contextByPort.get(port);\n}\n\n/**\n * Merge two ObservabilityContext values. `right` overrides `left` for\n * scalar fields; baggage arrays are concatenated (later entries win on\n * duplicate keys); attributes are merged (right overrides left per key).\n */\nfunction mergeContext(\n  left: ObservabilityContext,\n  right: ObservabilityContext,\n): ObservabilityContext {\n  const merged: ObservabilityContext = { ...left };\n\n  if (right.operation_id !== undefined) merged.operation_id = right.operation_id;\n  if (right.parent_operation_id !== undefined) {\n    merged.parent_operation_id = right.parent_operation_id;\n  }\n  if (right.traceparent !== undefined) merged.traceparent = right.traceparent;\n  if (right.tracestate !== undefined) merged.tracestate = right.tracestate;\n  if (right.fingerprint_key !== undefined) merged.fingerprint_key = right.fingerprint_key;\n  if (right.conversation_id !== undefined) merged.conversation_id = right.conversation_id;\n\n  if (right.baggage !== undefined) {\n    if (left.baggage === undefined) {\n      merged.baggage = [...right.baggage];\n    } else {\n      // Concatenate; dedupe on key with right winning.\n      const rightKeys = new Set(right.baggage.map((e) => e.key));\n      const leftFiltered = left.baggage.filter((e) => !rightKeys.has(e.key));\n      merged.baggage = [...leftFiltered, ...right.baggage];\n    }\n  }\n\n  if (right.attributes !== undefined) {\n    merged.attributes = { ...(left.attributes ?? {}), ...right.attributes };\n  }\n\n  return merged;\n}\n"]}