{"version":3,"sources":["../src/shape/blocks.ts","../src/shape/citations.ts","../src/shape/echo.ts","../src/shape/usage.ts","../src/shape/request.ts","../src/shape/events.ts","../src/shape/errors.ts","../src/shape/helpers.ts","../src/shape/json-schema-shape.ts","../src/shape/json-schema.ts","../src/shape/index.ts","../src/shape/thinking.ts","../src/providers/errors.ts","../src/providers/echo.ts","../src/providers/anthropic/request.ts","../src/providers/anthropic/models.ts","../src/providers/tool-input.ts","../src/providers/anthropic/response.ts","../src/providers/anthropic/stream.ts","../src/client/abort.ts","../src/providers/anthropic.ts","../src/providers/blocks.ts","../src/providers/openai/request.ts","../src/providers/openai/responses-request.ts","../src/providers/openai/api.ts","../src/providers/openai/models.ts","../src/providers/openai/response.ts","../src/providers/openai/responses-response.ts","../src/providers/openai/stream.ts","../src/providers/openai/responses-stream.ts","../src/providers/openai.ts","../src/providers/google/request.ts","../src/providers/google/models.ts","../src/providers/google/response.ts","../src/providers/google/stream.ts","../src/providers/google.ts","../src/index.ts","../src/client/init.ts","../src/shape/capabilities.ts","../src/catalog/index.ts","../src/catalog/anthropic.ts","../src/shape/pricing.ts","../src/catalog/openai.ts","../src/catalog/google.ts","../src/client/keys.ts","../src/providers/registry.ts","../src/client/capacity.ts","../src/client/telemetry.ts","../src/catalog/pricing.ts","../src/client/stream.ts","../src/shape/superpowers.ts","../src/providers/discovery.ts","../src/agent/loop.ts","../src/agent/tools.ts","../src/agent/skill.ts","../src/agent/taint.ts","../src/agent/compaction.ts","../src/agent/tool-turn.ts","../src/agent/memory.ts","../src/harness/spec.ts","../src/harness/resolve.ts","../src/harness/verify.ts","../src/eval/harness.ts","../src/eval/graders.ts","../src/store/schema.ts","../src/store/memory.ts","../src/store/runs.ts","../src/store/keys.ts","../src/store/platform.ts","../src/store/hosted-provider.ts","../src/store/provision.ts","../src/store/crud.ts"],"sourcesContent":["// Content blocks and messages — the multi-modal building blocks of a request.\n// Zero runtime; pure type contract.\n\n// ----- Providers -----\n\n/** Every provider odla-ai can route to. Apps should not branch on this for\n *  portability, but it is carried on responses/events for observability. */\nexport type ProviderId = \"anthropic\" | \"openai\" | \"google\";\n\n// ----- Content blocks -----\n\nexport interface TextBlock {\n  type: \"text\";\n  text: string;\n  /** Anthropic prompt-caching marker. Other providers ignore it. */\n  cacheControl?: { type: \"ephemeral\" };\n  /** Gemini thought signature attached to this part. Opaque; carried so a\n   *  later turn can hand it back, which Gemini 3 requires. Other providers\n   *  ignore it. */\n  thoughtSignature?: string;\n}\n\nexport type ImageMediaType = \"image/jpeg\" | \"image/png\" | \"image/gif\" | \"image/webp\";\n\nexport type ImageSource =\n  | { type: \"base64\"; mediaType: ImageMediaType; data: string }\n  | { type: \"url\"; url: string };\n\nexport interface ImageBlock {\n  type: \"image\";\n  source: ImageSource;\n}\n\nexport type AudioMediaType =\n  | \"audio/wav\"\n  | \"audio/mp3\"\n  | \"audio/mpeg\"\n  | \"audio/ogg\"\n  | \"audio/flac\"\n  | \"audio/aac\"\n  | \"audio/webm\";\n\nexport type AudioSource =\n  | { type: \"base64\"; mediaType: AudioMediaType; data: string }\n  | { type: \"url\"; url: string };\n\n/** Audio input. Supported by OpenAI (audio models) and Google (Gemini); NOT by\n *  Anthropic — a request carrying an AudioBlock to a Claude model is rejected up\n *  front by capability validation, never sent. */\nexport interface AudioBlock {\n  type: \"audio\";\n  source: AudioSource;\n}\n\nexport type DocumentSource =\n  | { type: \"base64\"; mediaType: \"application/pdf\"; data: string }\n  | { type: \"url\"; url: string };\n\n/** A document (PDF) input. Supported by Anthropic and Google. */\nexport interface DocumentBlock {\n  type: \"document\";\n  source: DocumentSource;\n}\n\nexport interface ToolUseBlock {\n  type: \"tool_use\";\n  /** Correlates a `tool_result` with this call. Translated from OpenAI's\n   *  `tool_calls[].id` by the openai adapter. */\n  id: string;\n  name: string;\n  /** Already-parsed object. OpenAI's JSON-string `arguments` is parsed before it\n   *  reaches this shape — callers never JSON.parse a tool's arguments. */\n  input: Record<string, unknown>;\n  /** Gemini thought signature on the function-call part. Gemini 3 validates\n   *  that a function call echoed back carries the signature it was issued\n   *  with and rejects the request otherwise, so the adapter keeps it here and\n   *  the agent loop replays it unchanged. Other providers ignore it. */\n  thoughtSignature?: string;\n}\n\nexport interface ToolResultBlock {\n  type: \"tool_result\";\n  toolUseId: string;\n  /** String for plain-text results (most tools); a content-block array for tools\n   *  that return structured / multi-modal content. */\n  content: string | OracleContentBlock[];\n  isError?: boolean;\n}\n\nexport interface ThinkingBlock {\n  type: \"thinking\";\n  /** Extended-thinking text (Anthropic). Empty when `display` is omitted. */\n  thinking: string;\n  signature?: string;\n}\n\nexport type OracleContentBlock =\n  | TextBlock\n  | ImageBlock\n  | AudioBlock\n  | DocumentBlock\n  | ToolUseBlock\n  | ToolResultBlock\n  | ThinkingBlock;\n\n// ----- Messages -----\n\nexport type OracleRole = \"user\" | \"assistant\";\n\nexport interface OracleMessage {\n  role: OracleRole;\n  /** A plain string (shorthand for a single TextBlock) or an explicit array for\n   *  multi-modal / tool turns. */\n  content: string | OracleContentBlock[];\n}\n","// Web-search citations — the sources a provider attributed while answering with\n// its server-side search tool. The per-provider parsing lives in each adapter's\n// response mapper; this module owns the canonical shape and the merge rule.\n\n/**\n * One source a provider attributed while answering a web-search request.\n *\n * Two strengths of evidence share this shape. A citation carrying `citedText`\n * or a `startIndex`/`endIndex` span was attributed **inline** against a specific\n * claim. One carrying only a `url` was merely **consulted** — the provider\n * listed it as a search result without tying it to any sentence, which is much\n * weaker evidence that the answer actually came from there.\n */\nexport interface SearchCitation {\n  /**\n   * The source URL exactly as the provider reported it.\n   *\n   * Not always the publisher's URL: Gemini reports grounding chunks as\n   * `vertexaisearch.cloud.google.com/grounding-api-redirect/…` links that\n   * resolve to the real page only when followed. Compare hosts across providers\n   * only after resolving those redirects.\n   */\n  url: string;\n  /** Source title, when the provider reports one. */\n  title?: string;\n  /** The passage the provider says this source supports, when it attributes one. */\n  citedText?: string;\n  /** Start offset into the answer text this citation supports, when reported. */\n  startIndex?: number;\n  /** End offset (exclusive) into the answer text this citation supports. */\n  endIndex?: number;\n}\n\n/** Whether a citation was attributed to a specific claim rather than merely consulted. */\nfunction isAttributed(c: SearchCitation): boolean {\n  return c.citedText !== undefined || c.startIndex !== undefined || c.endIndex !== undefined;\n}\n\n/**\n * Normalize a provider's raw citations into the reported set.\n *\n * Drops entries without a URL, collapses exact duplicates, and — when a source\n * was attributed to at least one claim — drops the redundant bare \"consulted\"\n * entry for that same URL, so a source appears either as the spans it supports\n * or as a single consulted-only record, never both.\n */\nexport function mergeCitations(citations: readonly SearchCitation[]): SearchCitation[] {\n  const attributed = new Set(citations.filter((c) => c.url && isAttributed(c)).map((c) => c.url));\n  const seen = new Set<string>();\n  const out: SearchCitation[] = [];\n  for (const c of citations) {\n    if (!c.url) continue;\n    if (!isAttributed(c) && attributed.has(c.url)) continue;\n    const key = `${c.url}\\u0000${c.startIndex ?? \"\"}\\u0000${c.endIndex ?? \"\"}\\u0000${c.citedText ?? \"\"}`;\n    if (seen.has(key)) continue;\n    seen.add(key);\n    out.push(c);\n  }\n  return out;\n}\n","// The resolved-request echo: what a provider adapter *actually sent*, read back\n// off the built native params rather than re-derived from the request.\n//\n// That distinction is the whole point. Re-deriving the mapping would only prove\n// intent equals intent. Reading the params the adapter is about to hand the SDK\n// makes a later intent-vs-reality comparison meaningful, which is what catches a\n// silent coercion — the class of bug where a request asks for one thing, the\n// adapter quietly sends another, and the response looks perfectly healthy.\n//\n// Consumers that compare many models against each other (evals, benchmarks)\n// need this: a cross-model comparison whose cells were silently coerced to\n// different reasoning settings is not a comparison.\n\nimport type { ProviderId } from \"./blocks\";\nimport type { NativeEffort } from \"./thinking\";\n\n/** What the adapter actually sent, read off the built native params. */\nexport interface RequestEcho {\n  /** The provider that built the params. */\n  provider: ProviderId;\n  /** The native model id in the sent params — not the canonical catalog id. */\n  nativeModel: string;\n  /**\n   * Whether reasoning is actually active for this call. When the adapter sends\n   * no explicit thinking parameter this reflects the model's *documented\n   * default* from the catalog descriptor, because the default is what the model\n   * will actually do — \"we sent nothing\" is not the same as \"it will not think\".\n   */\n  thinkingActive: boolean;\n  /** The native reasoning knob actually sent, absent when none was. */\n  nativeEffort?: NativeEffort;\n  /** Max output tokens actually sent. */\n  maxTokens?: number;\n  /** Temperature actually sent. Absent when the adapter dropped it — several\n   *  do on reasoning-tier models, which is exactly the kind of quiet\n   *  substitution this type exists to surface. */\n  temperature?: number;\n  /** Number of tools actually sent (client tools plus server tools). */\n  toolCount: number;\n}\n","// Token usage accounting. The one runtime island with no dependencies.\n\n/**\n * Token counts for one call, in the four disjoint classes Anthropic reports\n * (the shape every adapter normalises onto). Disjoint matters for cost: a\n * cache-read token is *not* also counted as an input token, so pricing sums the\n * classes at their own rates rather than double-charging.\n */\nexport interface OracleUsage {\n  /** Uncached prompt tokens, billed at the model's input rate. */\n  inputTokens: number;\n  /** Generated tokens, billed at the output rate. Thinking tokens bill here. */\n  outputTokens: number;\n  /** Tokens written into the prompt cache, billed at a premium over input. */\n  cacheCreationTokens?: number;\n  /** Tokens served from the prompt cache, billed well below input. */\n  cacheReadTokens?: number;\n}\n\n/** A fresh zeroed usage tally (0 input/output tokens, no cache fields) — the seed for accumulation. */\nexport function emptyUsage(): OracleUsage {\n  return { inputTokens: 0, outputTokens: 0 };\n}\n\n/** Accumulate `more` into `into`, in place. Cache fields sum when present. */\nexport function addUsage(into: OracleUsage, more: OracleUsage): void {\n  into.inputTokens += more.inputTokens;\n  into.outputTokens += more.outputTokens;\n  if (more.cacheCreationTokens !== undefined) {\n    into.cacheCreationTokens = (into.cacheCreationTokens ?? 0) + more.cacheCreationTokens;\n  }\n  if (more.cacheReadTokens !== undefined) {\n    into.cacheReadTokens = (into.cacheReadTokens ?? 0) + more.cacheReadTokens;\n  }\n}\n","// Request shape, reasoning/output controls, and the non-streaming response.\nimport type { OracleContentBlock, OracleMessage, ProviderId, TextBlock } from \"./blocks\";\nimport type { SearchCitation } from \"./citations\";\nimport type { RequestEcho } from \"./echo\";\nimport type { OracleUsage } from \"./usage\";\n\n// ----- Tools -----\n\nexport interface OracleTool {\n  name: string;\n  description: string;\n  /** JSON Schema for the tool's arguments. */\n  inputSchema: Record<string, unknown>;\n}\n\n/** How the model may use tools this turn. `{ type: \"tool\", name }` forces one\n *  specific tool — the mechanism behind `extract<T>()`. */\nexport type ToolChoice = \"auto\" | \"any\" | \"none\" | { type: \"tool\"; name: string };\n\n// ----- Reasoning / output controls -----\n\n/** Whether the model reasons before answering. Maps to Anthropic adaptive\n *  thinking; emulated or ignored on providers without a native equivalent. */\nexport type ThinkingMode = \"off\" | \"adaptive\";\n\n/** Reasoning/spend depth. Maps to Anthropic `output_config.effort`; the openai\n *  and google adapters map it to their nearest reasoning-effort knob. */\nexport type Effort = \"low\" | \"medium\" | \"high\" | \"xhigh\" | \"max\";\n\n/** Constrain the response to valid JSON matching a schema (structured output). */\nexport interface ResponseFormat {\n  type: \"json_schema\";\n  name?: string;\n  schema: Record<string, unknown>;\n}\n\n/** Low-cardinality OpenTelemetry attributes attached to one provider call. */\nexport type AiTelemetryAttributes = Record<string, string | number | boolean>;\n\n/** Optional attribution for the automatic provider-call span. This metadata is\n * consumed by the odla-ai facade and is never forwarded to a provider. */\nexport interface AiTelemetry {\n  /** Queryable feature name. Defaults to chat, stream, extract, or search. */\n  operation?: string;\n  /** Additional low-cardinality dimensions such as odla.app or odla.ai.surface. */\n  attributes?: AiTelemetryAttributes;\n}\n\n// ----- Request -----\n\nexport interface OracleRequest {\n  /** Canonical model id from the catalog; resolved to a provider + native id. */\n  model: string;\n  /** System prompt. Top-level for Anthropic/Google; the openai adapter folds it\n   *  into a leading system message. */\n  system?: string | TextBlock[];\n  messages: OracleMessage[];\n  tools?: OracleTool[];\n  toolChoice?: ToolChoice;\n  maxTokens: number;\n  temperature?: number;\n  stopSequences?: string[];\n  /** Reasoning mode. Only applied on models whose capabilities allow it. */\n  thinking?: ThinkingMode;\n  /** Reasoning/spend depth. Only applied on models whose capabilities allow it. */\n  effort?: Effort;\n  responseFormat?: ResponseFormat;\n  /** Enable the provider's server-side web-search tool for this request. */\n  webSearch?: boolean;\n  /** Provider-specific escape hatch, passed through opaquely. Using it gives up\n   *  portability across providers. */\n  providerExtras?: Record<string, unknown>;\n  /** Cancel the provider request. Adapters pass this to the vendor SDK rather\n   * than limiting cancellation to local tool handlers. */\n  signal?: AbortSignal;\n  /** Absolute Unix timestamp in milliseconds. The SDK combines this deadline\n   * with `signal`; whichever fires first cancels the provider request. */\n  deadline?: number;\n  /** Automatic provider-call telemetry. `false` suppresses the span for this\n   * call; metadata is never included in the provider-native request. */\n  telemetry?: AiTelemetry | false;\n}\n\n// ----- Response (non-streaming) -----\n\nexport type OracleStopReason =\n  | \"end_turn\"\n  | \"max_tokens\"\n  | \"stop_sequence\"\n  | \"tool_use\"\n  | \"pause_turn\"\n  | \"refusal\"\n  | \"error\";\n\nexport interface OracleResponse {\n  id: string;\n  model: string;\n  /** The provider that actually answered — for observability, not branching. */\n  provider: ProviderId;\n  role: \"assistant\";\n  content: OracleContentBlock[];\n  stopReason: OracleStopReason;\n  usage: OracleUsage;\n  /**\n   * Sources the provider attributed when `webSearch` was enabled — absent on\n   * ordinary calls, and absent from streamed responses (the stream event set\n   * carries no citation event yet).\n   */\n  citations?: SearchCitation[];\n  /**\n   * What the adapter actually sent, read off the built native params. Lets a\n   * caller prove the request was transmitted as specified rather than silently\n   * coerced — see `verifyEcho`. Absent on streamed responses.\n   */\n  echo?: RequestEcho;\n  /** Durable accounting receipt returned by platform-hosted JSON calls. */\n  receipt?: OracleReceipt;\n}\n\n/** Platform-hosted final accounting shared by JSON and SSE responses. */\nexport interface OracleReceipt {\n  usageId: string;\n  usage: OracleUsage;\n  costMicrousd: number | null;\n  queueWaitMs: number;\n  ttftMs: number | null;\n  providerLatencyMs: number;\n  totalLatencyMs: number;\n  status: \"success\" | \"error\";\n}\n","// Streaming events — one SSE vocabulary regardless of provider.\nimport type { OracleContentBlock, ProviderId } from \"./blocks\";\nimport type { OracleUsage } from \"./usage\";\nimport type { OracleReceipt, OracleStopReason } from \"./request\";\nimport type { OracleErrorShape } from \"./errors\";\n\n/** A discriminated union of SSE events with the same vocabulary regardless of\n *  provider. The anthropic adapter passes these through nearly 1:1; the openai\n *  and google adapters map their native streams onto this shape. */\nexport type OracleEvent =\n  | MessageStartEvent\n  | ContentBlockStartEvent\n  | ContentBlockDeltaEvent\n  | ContentBlockStopEvent\n  | MessageDeltaEvent\n  | MessageStopEvent\n  | OracleReceiptEvent\n  | OracleErrorEvent;\n\nexport interface MessageStartEvent {\n  type: \"message_start\";\n  message: {\n    id: string;\n    model: string;\n    provider: ProviderId;\n    role: \"assistant\";\n    content: [];\n    usage: OracleUsage;\n  };\n}\n\nexport interface ContentBlockStartEvent {\n  type: \"content_block_start\";\n  index: number;\n  contentBlock: OracleContentBlock;\n}\n\nexport type ContentBlockDelta =\n  | { type: \"text_delta\"; text: string }\n  | { type: \"thinking_delta\"; thinking: string }\n  | { type: \"input_json_delta\"; partialJson: string };\n\nexport interface ContentBlockDeltaEvent {\n  type: \"content_block_delta\";\n  index: number;\n  delta: ContentBlockDelta;\n}\n\nexport interface ContentBlockStopEvent {\n  type: \"content_block_stop\";\n  index: number;\n}\n\nexport interface MessageDeltaEvent {\n  type: \"message_delta\";\n  delta: { stopReason?: OracleStopReason };\n  usage: OracleUsage;\n}\n\nexport interface MessageStopEvent {\n  type: \"message_stop\";\n}\n\n/** Final accounting receipt emitted by platform-hosted SSE streams. Direct\n * provider streams omit it because they have no platform usage ledger. */\nexport interface OracleReceiptEvent {\n  type: \"receipt\";\n  receipt: OracleReceipt;\n}\n\nexport interface OracleErrorEvent {\n  type: \"error\";\n  error: OracleErrorShape;\n}\n","// The normalized error taxonomy and the class hierarchy every adapter throws.\nimport type { OracleUsage } from \"./usage\";\n\n/** The closed taxonomy of normalized error codes carried by every OdlaAIError\n *  and by the streaming `error` event. */\nexport type OracleErrorType =\n  | \"invalid_request\"\n  | \"auth\"\n  | \"rate_limit\"\n  | \"context_window\"\n  | \"cancelled\"\n  | \"deadline_exceeded\"\n  | \"tool_input_invalid\"\n  | \"capability_unsupported\"\n  | \"config\"\n  | \"provider_error\";\n\n/** The plain-data error shape used inside the streaming `error` event. */\nexport interface OracleErrorShape {\n  code: OracleErrorType;\n  message: string;\n  /** HTTP status from the upstream provider, when applicable. */\n  providerStatus?: number;\n  /** Seconds until a retry might succeed (rate limit / overload). */\n  retryAfter?: number;\n}\n\n/** Base class for every error odla-ai throws. Carries a stable string `code`\n *  (the odla ecosystem convention — see odla-db's AuthError/RuleError) so\n *  callers branch on `err.code`, never on message text. */\nexport class OdlaAIError extends Error {\n  readonly code: OracleErrorType;\n  readonly providerStatus?: number;\n  readonly retryAfter?: number;\n  /** Sanitized provider usage when a response was received before a later\n   * validation/tool-shape failure. Omitted when usage is genuinely unknown. */\n  readonly usage?: OracleUsage;\n\n  constructor(\n    code: OracleErrorType,\n    message: string,\n    opts?: { providerStatus?: number; retryAfter?: number; cause?: unknown; usage?: OracleUsage },\n  ) {\n    super(message, opts?.cause !== undefined ? { cause: opts.cause } : undefined);\n    this.name = new.target.name;\n    this.code = code;\n    this.providerStatus = opts?.providerStatus;\n    this.retryAfter = opts?.retryAfter;\n    this.usage = opts?.usage ? Object.freeze({ ...opts.usage }) : undefined;\n  }\n\n  toShape(): OracleErrorShape {\n    return {\n      code: this.code,\n      message: this.message,\n      providerStatus: this.providerStatus,\n      retryAfter: this.retryAfter,\n    };\n  }\n}\n\n/** A provider/model is not configured — e.g. no API key for its provider, or an\n *  unknown canonical model id. The library analog of odla-db's 501 gating. */\nexport class ConfigError extends OdlaAIError {\n  constructor(message: string) {\n    super(\"config\", message);\n  }\n}\n\n/** Authentication with the provider failed (bad/missing key). */\nexport class AuthError extends OdlaAIError {\n  constructor(message: string, opts?: { providerStatus?: number; cause?: unknown }) {\n    super(\"auth\", message, opts);\n  }\n}\n\n/** The provider rate-limited or is overloaded; check `retryAfter`. */\nexport class RateLimitError extends OdlaAIError {\n  constructor(message: string, opts?: { providerStatus?: number; retryAfter?: number; cause?: unknown }) {\n    super(\"rate_limit\", message, opts);\n  }\n}\n\n/** The request asked a model to do something it cannot — audio to Claude, tools\n *  to a text-only model, web search where unsupported, etc. Raised before any\n *  network call by `validateRequest`. */\nexport class CapabilityError extends OdlaAIError {\n  constructor(message: string) {\n    super(\"capability_unsupported\", message);\n  }\n}\n\n/** The request exceeded the model's context window. */\nexport class ContextWindowError extends OdlaAIError {\n  constructor(message: string, opts?: { providerStatus?: number; cause?: unknown }) {\n    super(\"context_window\", message, opts);\n  }\n}\n\n/** The request was malformed / rejected as invalid by the provider. */\nexport class InvalidRequestError extends OdlaAIError {\n  constructor(message: string, opts?: { providerStatus?: number; cause?: unknown }) {\n    super(\"invalid_request\", message, opts);\n  }\n}\n\n/** A provider returned tool arguments that are malformed or do not satisfy the\n * declared JSON Schema. Tool handlers are never invoked for this error. */\nexport class ToolInputError extends OdlaAIError {\n  readonly tool?: string;\n\n  constructor(message: string, opts?: { tool?: string; cause?: unknown; usage?: OracleUsage }) {\n    super(\"tool_input_invalid\", message, { cause: opts?.cause, usage: opts?.usage });\n    this.tool = opts?.tool;\n  }\n}\n\n/** The caller cancelled a request. This is not an upstream failure and should\n * not be retried unless the caller explicitly starts a new operation. */\nexport class CancelledError extends OdlaAIError {\n  constructor(message = \"AI request was cancelled.\", opts?: { cause?: unknown }) {\n    super(\"cancelled\", message, opts);\n  }\n}\n\n/** The request's absolute deadline elapsed. Callers may choose a new deadline,\n * but should not classify this as a provider outage. */\nexport class DeadlineExceededError extends OdlaAIError {\n  constructor(message = \"AI request deadline was exceeded.\", opts?: { cause?: unknown }) {\n    super(\"deadline_exceeded\", message, opts);\n  }\n}\n\n/** Any other upstream provider failure (5xx, transport, unexpected shape). */\nexport class ProviderError extends OdlaAIError {\n  constructor(message: string, opts?: { providerStatus?: number; cause?: unknown; usage?: OracleUsage }) {\n    super(\"provider_error\", message, opts);\n  }\n}\n","// Cheap, dependency-free helpers over content blocks.\nimport type {\n  AudioBlock,\n  DocumentBlock,\n  ImageBlock,\n  OracleContentBlock,\n  TextBlock,\n  ThinkingBlock,\n  ToolResultBlock,\n  ToolUseBlock,\n} from \"./blocks\";\n\n/** Type guard: narrows a content block to a `TextBlock` (`type: \"text\"`). */\nexport function isTextBlock(b: OracleContentBlock): b is TextBlock {\n  return b.type === \"text\";\n}\n/** Type guard: narrows a content block to an `ImageBlock` (`type: \"image\"`). */\nexport function isImageBlock(b: OracleContentBlock): b is ImageBlock {\n  return b.type === \"image\";\n}\n/** Type guard: narrows a content block to an `AudioBlock` (`type: \"audio\"`). */\nexport function isAudioBlock(b: OracleContentBlock): b is AudioBlock {\n  return b.type === \"audio\";\n}\n/** Type guard: narrows a content block to a `DocumentBlock` (`type: \"document\"`). */\nexport function isDocumentBlock(b: OracleContentBlock): b is DocumentBlock {\n  return b.type === \"document\";\n}\n/** Type guard: narrows a content block to a `ToolUseBlock` (`type: \"tool_use\"`). */\nexport function isToolUseBlock(b: OracleContentBlock): b is ToolUseBlock {\n  return b.type === \"tool_use\";\n}\n/** Type guard: narrows a content block to a `ToolResultBlock` (`type: \"tool_result\"`). */\nexport function isToolResultBlock(b: OracleContentBlock): b is ToolResultBlock {\n  return b.type === \"tool_result\";\n}\n/** Type guard: narrows a content block to a `ThinkingBlock` (`type: \"thinking\"`). */\nexport function isThinkingBlock(b: OracleContentBlock): b is ThinkingBlock {\n  return b.type === \"thinking\";\n}\n\n/** Normalize a message's `content` (string shorthand or block array) to blocks. */\nexport function blocksOf(content: string | OracleContentBlock[]): OracleContentBlock[] {\n  return typeof content === \"string\" ? [{ type: \"text\", text: content }] : content;\n}\n\n/** Concatenate the text of every TextBlock. Image/audio/tool/thinking ignored. */\nexport function extractText(content: OracleContentBlock[]): string {\n  return content.filter(isTextBlock).map((b) => b.text).join(\"\");\n}\n\n/** Collect every tool_use block from response or message content. */\nexport function extractToolUses(content: OracleContentBlock[]): ToolUseBlock[] {\n  return content.filter(isToolUseBlock);\n}\n","import type { JsonSchemaIssue } from \"./json-schema.js\";\n\nconst ANNOTATION_KEYS = new Set([\n  \"$schema\",\n  \"$id\",\n  \"$anchor\",\n  \"title\",\n  \"description\",\n  \"default\",\n  \"examples\",\n  \"deprecated\",\n  \"readOnly\",\n  \"writeOnly\",\n  \"format\",\n]);\n\nexport const SUPPORTED_KEYS = new Set([\n  ...ANNOTATION_KEYS,\n  \"$ref\",\n  \"$defs\",\n  \"definitions\",\n  \"type\",\n  \"enum\",\n  \"const\",\n  \"allOf\",\n  \"anyOf\",\n  \"oneOf\",\n  \"not\",\n  \"properties\",\n  \"required\",\n  \"additionalProperties\",\n  \"minProperties\",\n  \"maxProperties\",\n  \"items\",\n  \"minItems\",\n  \"maxItems\",\n  \"uniqueItems\",\n  \"minLength\",\n  \"maxLength\",\n  \"pattern\",\n  \"minimum\",\n  \"maximum\",\n  \"exclusiveMinimum\",\n  \"exclusiveMaximum\",\n  \"multipleOf\",\n]);\n\nconst ALLOWED_TYPES = new Set([\n  \"null\",\n  \"boolean\",\n  \"object\",\n  \"array\",\n  \"number\",\n  \"integer\",\n  \"string\",\n]);\n\nexport function validateSchemaShape(\n  schema: unknown,\n  path: string,\n  root: unknown,\n  issues: JsonSchemaIssue[],\n): void {\n  if (typeof schema === \"boolean\") return;\n  if (!isRecord(schema)) {\n    issue(issues, path, \"schema must be an object or boolean\");\n    return;\n  }\n  for (const key of Object.keys(schema)) {\n    if (!SUPPORTED_KEYS.has(key)) issue(issues, path, `schema uses unsupported keyword \"${key}\"`);\n  }\n  if (typeof schema.$ref === \"string\" && resolveLocalRef(root, schema.$ref) === undefined) {\n    issue(issues, path, `schema reference \"${schema.$ref}\" could not be resolved`);\n  } else if (schema.$ref !== undefined && typeof schema.$ref !== \"string\") {\n    issue(issues, path, \"schema $ref must be a string\");\n  }\n  const types = typeof schema.type === \"string\"\n    ? [schema.type]\n    : Array.isArray(schema.type)\n      ? schema.type\n      : [];\n  if (\n    schema.type !== undefined\n    && (types.length === 0 || !types.every((type) => typeof type === \"string\" && ALLOWED_TYPES.has(type)))\n  ) {\n    issue(issues, path, \"schema type contains an unsupported JSON type\");\n  }\n  if (schema.enum !== undefined && !Array.isArray(schema.enum)) {\n    issue(issues, path, \"schema enum must be an array\");\n  }\n  if (\n    schema.required !== undefined\n    && (!Array.isArray(schema.required) || !schema.required.every((key) => typeof key === \"string\"))\n  ) {\n    issue(issues, path, \"schema required must be a string array\");\n  }\n  validateConstraintShapes(schema, path, issues);\n  validateChildSchemas(schema, path, root, issues);\n}\n\nfunction validateChildSchemas(\n  schema: Record<string, unknown>,\n  path: string,\n  root: unknown,\n  issues: JsonSchemaIssue[],\n): void {\n  for (const key of [\"properties\", \"$defs\", \"definitions\"] as const) {\n    const group = schema[key];\n    if (group === undefined) continue;\n    if (!isRecord(group)) {\n      issue(issues, path, `schema ${key} must be an object`);\n      continue;\n    }\n    for (const [name, child] of Object.entries(group)) {\n      validateSchemaShape(child, `${path}.${key}.${name}`, root, issues);\n    }\n  }\n  for (const key of [\"allOf\", \"anyOf\", \"oneOf\"] as const) {\n    const group = schema[key];\n    if (group === undefined) continue;\n    if (!Array.isArray(group) || group.length === 0) {\n      issue(issues, path, `schema ${key} must be a non-empty array`);\n      continue;\n    }\n    group.forEach((child, index) => validateSchemaShape(child, `${path}.${key}[${index}]`, root, issues));\n  }\n  for (const key of [\"items\", \"not\", \"additionalProperties\"] as const) {\n    const child = schema[key];\n    if (child !== undefined) validateSchemaShape(child, `${path}.${key}`, root, issues);\n  }\n}\n\nfunction validateConstraintShapes(\n  schema: Record<string, unknown>,\n  path: string,\n  issues: JsonSchemaIssue[],\n): void {\n  for (const key of [\"minLength\", \"maxLength\", \"minItems\", \"maxItems\", \"minProperties\", \"maxProperties\"] as const) {\n    const value = schema[key];\n    if (value !== undefined && (!Number.isInteger(value) || (value as number) < 0)) {\n      issue(issues, path, `schema ${key} must be a non-negative integer`);\n    }\n  }\n  for (const key of [\"minimum\", \"maximum\", \"exclusiveMinimum\", \"exclusiveMaximum\"] as const) {\n    const value = schema[key];\n    if (value !== undefined && !isFiniteNumber(value)) {\n      issue(issues, path, `schema ${key} must be a finite number`);\n    }\n  }\n  if (schema.multipleOf !== undefined && (!isFiniteNumber(schema.multipleOf) || schema.multipleOf <= 0)) {\n    issue(issues, path, \"schema multipleOf must be a finite number greater than zero\");\n  }\n  if (schema.uniqueItems !== undefined && typeof schema.uniqueItems !== \"boolean\") {\n    issue(issues, path, \"schema uniqueItems must be a boolean\");\n  }\n  validatePatternShape(schema.pattern, path, issues);\n}\n\nfunction validatePatternShape(value: unknown, path: string, issues: JsonSchemaIssue[]): void {\n  if (value === undefined) return;\n  if (typeof value !== \"string\") {\n    issue(issues, path, \"schema pattern must be a string\");\n    return;\n  }\n  try {\n    new RegExp(value, \"u\");\n  } catch {\n    issue(issues, path, `schema pattern \"${value}\" is invalid`);\n  }\n}\n\nfunction resolveLocalRef(root: unknown, ref: string): unknown {\n  if (ref === \"#\") return root;\n  if (!ref.startsWith(\"#/\")) return undefined;\n  let current = root;\n  for (const raw of ref.slice(2).split(\"/\")) {\n    const key = raw.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n    if (!isRecord(current) || !Object.hasOwn(current, key)) return undefined;\n    current = current[key];\n  }\n  return current;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n  return typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction issue(issues: JsonSchemaIssue[], path: string, message: string): void {\n  issues.push({ path, message });\n}\n","// A deliberately small, dependency-free JSON Schema validator for tool inputs.\n// Tool schemas are a trust boundary: provider output must be checked before it\n// reaches application code. We support a documented provider-tool subset and\n// fail closed when any unknown or unsupported keyword is present instead of\n// silently pretending validation happened.\n\nimport { SUPPORTED_KEYS, validateSchemaShape } from \"./json-schema-shape.js\";\n\n/** One deterministic validation failure at a JSONPath-like location. */\nexport interface JsonSchemaIssue {\n  path: string;\n  message: string;\n}\n\n/** Complete supported-subset schema validation result; unknown keywords fail validation. */\nexport interface JsonSchemaValidation {\n  valid: boolean;\n  issues: JsonSchemaIssue[];\n}\n\n/** Validate a JSON-compatible value against the supported JSON Schema subset.\n * Unknown or unsupported keywords are validation failures, not ignored hints. */\nexport function validateJsonSchema(\n  schema: unknown,\n  value: unknown,\n): JsonSchemaValidation {\n  const issues: JsonSchemaIssue[] = [];\n  validateSchemaShape(schema, \"$\", schema, issues);\n  if (issues.length > 0) return { valid: false, issues };\n  visit(schema, value, \"$\", schema, issues, new Set());\n  return { valid: issues.length === 0, issues };\n}\n\nfunction visit(\n  schema: unknown,\n  value: unknown,\n  path: string,\n  root: unknown,\n  issues: JsonSchemaIssue[],\n  refs: Set<string>,\n): void {\n  if (schema === true) return;\n  if (schema === false) {\n    issue(issues, path, \"is rejected by the schema\");\n    return;\n  }\n  if (!isRecord(schema)) {\n    issue(issues, path, \"schema must be an object or boolean\");\n    return;\n  }\n\n  for (const key of Object.keys(schema)) {\n    if (!SUPPORTED_KEYS.has(key)) {\n      issue(issues, path, `schema uses unsupported keyword \"${key}\"`);\n      return;\n    }\n  }\n\n  if (typeof schema.$ref === \"string\") {\n    const target = resolveLocalRef(root, schema.$ref);\n    if (target === undefined) {\n      issue(issues, path, `schema reference \"${schema.$ref}\" could not be resolved`);\n      return;\n    }\n    if (refs.has(schema.$ref)) {\n      issue(issues, path, `cyclic schema reference \"${schema.$ref}\" is unsupported`);\n      return;\n    }\n    const nextRefs = new Set(refs);\n    nextRefs.add(schema.$ref);\n    visit(target, value, path, root, issues, nextRefs);\n  }\n\n  if (Array.isArray(schema.enum) && !schema.enum.some((candidate) => jsonEqual(candidate, value))) {\n    issue(issues, path, \"must equal one of the allowed enum values\");\n  }\n  if (Object.hasOwn(schema, \"const\") && !jsonEqual(schema.const, value)) {\n    issue(issues, path, \"must equal the constant value\");\n  }\n\n  if (Array.isArray(schema.allOf)) {\n    for (const child of schema.allOf) visit(child, value, path, root, issues, refs);\n  }\n  if (Array.isArray(schema.anyOf) && !schema.anyOf.some((child) => matches(child, value, root, refs))) {\n    issue(issues, path, \"must match at least one anyOf schema\");\n  }\n  if (Array.isArray(schema.oneOf)) {\n    const matchesCount = schema.oneOf.filter((child) => matches(child, value, root, refs)).length;\n    if (matchesCount !== 1) issue(issues, path, \"must match exactly one oneOf schema\");\n  }\n  if (schema.not !== undefined && matches(schema.not, value, root, refs)) {\n    issue(issues, path, \"must not match the forbidden schema\");\n  }\n\n  const types = typeof schema.type === \"string\"\n    ? [schema.type]\n    : Array.isArray(schema.type) && schema.type.every((t) => typeof t === \"string\")\n      ? schema.type\n      : undefined;\n  if (schema.type !== undefined && !types) {\n    issue(issues, path, \"schema type must be a string or string array\");\n    return;\n  }\n  if (types && !types.some((type) => isType(value, type))) {\n    issue(issues, path, `must be ${types.join(\" or \")}`);\n    return;\n  }\n\n  if (typeof value === \"string\") validateString(schema, value, path, issues);\n  if (typeof value === \"number\") validateNumber(schema, value, path, issues);\n  if (Array.isArray(value)) validateArray(schema, value, path, root, issues, refs);\n  if (isRecord(value)) validateObject(schema, value, path, root, issues, refs);\n}\n\nfunction validateString(schema: Record<string, unknown>, value: string, path: string, issues: JsonSchemaIssue[]): void {\n  if (isFiniteNumber(schema.minLength) && [...value].length < schema.minLength) issue(issues, path, `must have at least ${schema.minLength} characters`);\n  if (isFiniteNumber(schema.maxLength) && [...value].length > schema.maxLength) issue(issues, path, `must have at most ${schema.maxLength} characters`);\n  if (typeof schema.pattern === \"string\") {\n    try {\n      if (!new RegExp(schema.pattern, \"u\").test(value)) issue(issues, path, `must match pattern ${schema.pattern}`);\n    } catch {\n      issue(issues, path, `schema pattern \"${schema.pattern}\" is invalid`);\n    }\n  }\n}\n\nfunction validateNumber(schema: Record<string, unknown>, value: number, path: string, issues: JsonSchemaIssue[]): void {\n  if (!Number.isFinite(value)) {\n    issue(issues, path, \"must be a finite number\");\n    return;\n  }\n  if (isFiniteNumber(schema.minimum) && value < schema.minimum) issue(issues, path, `must be >= ${schema.minimum}`);\n  if (isFiniteNumber(schema.maximum) && value > schema.maximum) issue(issues, path, `must be <= ${schema.maximum}`);\n  if (isFiniteNumber(schema.exclusiveMinimum) && value <= schema.exclusiveMinimum) issue(issues, path, `must be > ${schema.exclusiveMinimum}`);\n  if (isFiniteNumber(schema.exclusiveMaximum) && value >= schema.exclusiveMaximum) issue(issues, path, `must be < ${schema.exclusiveMaximum}`);\n  if (isFiniteNumber(schema.multipleOf) && schema.multipleOf > 0) {\n    const quotient = value / schema.multipleOf;\n    if (Math.abs(quotient - Math.round(quotient)) > Number.EPSILON * Math.max(1, Math.abs(quotient))) {\n      issue(issues, path, `must be a multiple of ${schema.multipleOf}`);\n    }\n  }\n}\n\nfunction validateArray(\n  schema: Record<string, unknown>,\n  value: unknown[],\n  path: string,\n  root: unknown,\n  issues: JsonSchemaIssue[],\n  refs: Set<string>,\n): void {\n  if (isFiniteNumber(schema.minItems) && value.length < schema.minItems) issue(issues, path, `must contain at least ${schema.minItems} items`);\n  if (isFiniteNumber(schema.maxItems) && value.length > schema.maxItems) issue(issues, path, `must contain at most ${schema.maxItems} items`);\n  if (schema.uniqueItems === true) {\n    for (let i = 0; i < value.length; i++) {\n      if (value.slice(0, i).some((other) => jsonEqual(other, value[i]))) {\n        issue(issues, `${path}[${i}]`, \"must be unique\");\n        break;\n      }\n    }\n  }\n  if (schema.items !== undefined) {\n    for (let i = 0; i < value.length; i++) visit(schema.items, value[i], `${path}[${i}]`, root, issues, refs);\n  }\n}\n\nfunction validateObject(\n  schema: Record<string, unknown>,\n  value: Record<string, unknown>,\n  path: string,\n  root: unknown,\n  issues: JsonSchemaIssue[],\n  refs: Set<string>,\n): void {\n  const keys = Object.keys(value);\n  if (isFiniteNumber(schema.minProperties) && keys.length < schema.minProperties) issue(issues, path, `must contain at least ${schema.minProperties} properties`);\n  if (isFiniteNumber(schema.maxProperties) && keys.length > schema.maxProperties) issue(issues, path, `must contain at most ${schema.maxProperties} properties`);\n\n  if (schema.required !== undefined && (!Array.isArray(schema.required) || !schema.required.every((key) => typeof key === \"string\"))) {\n    issue(issues, path, \"schema required must be a string array\");\n    return;\n  }\n  for (const key of (schema.required as string[] | undefined) ?? []) {\n    if (!Object.hasOwn(value, key)) issue(issues, childPath(path, key), \"is required\");\n  }\n\n  const properties = isRecord(schema.properties) ? schema.properties : {};\n  for (const [key, child] of Object.entries(properties)) {\n    if (Object.hasOwn(value, key)) visit(child, value[key], childPath(path, key), root, issues, refs);\n  }\n\n  const extras = keys.filter((key) => !Object.hasOwn(properties, key));\n  if (schema.additionalProperties === false) {\n    for (const key of extras) issue(issues, childPath(path, key), \"is not an allowed property\");\n  } else if (schema.additionalProperties !== undefined && schema.additionalProperties !== true) {\n    for (const key of extras) visit(schema.additionalProperties, value[key], childPath(path, key), root, issues, refs);\n  }\n}\n\nfunction matches(schema: unknown, value: unknown, root: unknown, refs: Set<string>): boolean {\n  const nested: JsonSchemaIssue[] = [];\n  visit(schema, value, \"$\", root, nested, refs);\n  return nested.length === 0;\n}\n\nfunction resolveLocalRef(root: unknown, ref: string): unknown {\n  if (ref === \"#\") return root;\n  if (!ref.startsWith(\"#/\")) return undefined;\n  let current = root;\n  for (const raw of ref.slice(2).split(\"/\")) {\n    const key = raw.replace(/~1/g, \"/\").replace(/~0/g, \"~\");\n    if (!isRecord(current) || !Object.hasOwn(current, key)) return undefined;\n    current = current[key];\n  }\n  return current;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n  return value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n\nfunction isType(value: unknown, type: string): boolean {\n  switch (type) {\n    case \"null\": return value === null;\n    case \"boolean\": return typeof value === \"boolean\";\n    case \"object\": return isRecord(value);\n    case \"array\": return Array.isArray(value);\n    case \"number\": return typeof value === \"number\" && Number.isFinite(value);\n    case \"integer\": return typeof value === \"number\" && Number.isInteger(value);\n    case \"string\": return typeof value === \"string\";\n    default: return false;\n  }\n}\n\nfunction isFiniteNumber(value: unknown): value is number {\n  return typeof value === \"number\" && Number.isFinite(value);\n}\n\nfunction jsonEqual(a: unknown, b: unknown): boolean {\n  if (Object.is(a, b)) return true;\n  if (Array.isArray(a) && Array.isArray(b)) return a.length === b.length && a.every((v, i) => jsonEqual(v, b[i]));\n  if (isRecord(a) && isRecord(b)) {\n    const aKeys = Object.keys(a);\n    const bKeys = Object.keys(b);\n    return aKeys.length === bKeys.length && aKeys.every((key) => Object.hasOwn(b, key) && jsonEqual(a[key], b[key]));\n  }\n  return false;\n}\n\nfunction childPath(path: string, key: string): string {\n  return /^[A-Za-z_$][\\w$]*$/.test(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`;\n}\n\nfunction issue(issues: JsonSchemaIssue[], path: string, message: string): void {\n  issues.push({ path, message });\n}\n","// The canonical request / response / event types for talking to any LLM\n// provider through odla-ai. One shape regardless of which vendor answers.\n//\n// Modeled after Anthropic's content-block shape because: (a) odla is\n// Claude-native in spirit, (b) Anthropic's tool-use is cleaner (object `input`\n// instead of a JSON-string `arguments`, structured content blocks, tool_result\n// as a content block), and (c) translating OpenAI/Google → Anthropic loses less\n// fidelity than the reverse. Forked and generalized from odla-ai-old's\n// `@odla-ai/oracle-shape`: this version adds Google as a first-class provider,\n// adds audio (and PDF document) input, replaces two-provider hardcoding with an\n// open provider union, and generalizes reasoning controls.\n//\n// This module has ZERO runtime dependencies beyond the small usage/error/helper\n// islands. It is the load-bearing contract the adapters, the client facade, the\n// agent loop, and the eval harness all speak; provider SDK types never leak past\n// the adapters. Split by concern; this barrel is the flat surface they import.\n\nexport * from \"./blocks\";\nexport * from \"./citations\";\nexport * from \"./echo\";\nexport * from \"./usage\";\nexport * from \"./request\";\nexport * from \"./events\";\nexport * from \"./errors\";\nexport * from \"./helpers\";\nexport * from \"./json-schema\";\n","// Per-model reasoning descriptor: how a model's thinking toggle behaves and how\n// the unified cross-provider effort ladder maps to that model's native knob.\n// This replaces the old lossy adapter heuristics (OpenAI silently collapsing\n// high/xhigh/max → \"high\"; Gemini ignoring effort entirely) with explicit,\n// per-model data that validateRequest can enforce.\n\nimport type { ProviderId } from \"./blocks\";\nimport type { Effort } from \"./request\";\nimport type { ModelSpec } from \"./capabilities\";\n\n/** How a model's `thinking` request field behaves. Describes the request\n *  toggle, not whether the model reasons internally. */\nexport type ThinkingControl =\n  /** No native thinking toggle; `thinking: \"adaptive\"` is rejected. */\n  | \"none\"\n  /** Thinking cannot be disabled; `thinking: \"off\"` is rejected. */\n  | \"always-on\"\n  /** Off unless the request sets `thinking: \"adaptive\"`. */\n  | \"opt-in\"\n  /** Adaptive unless the request sets `thinking: \"off\"`. */\n  | \"on-by-default\"\n  /** Legacy token-budget style; `\"adaptive\"` maps to a budget_tokens value. */\n  | \"budget\";\n\n/** The provider-native knob one unified `Effort` level maps to. The `param`\n *  discriminant lets each adapter assert the variant it expects and fail loudly\n *  on a mis-authored catalog entry. */\nexport type NativeEffort =\n  /** Anthropic `output_config.effort`. */\n  | { param: \"outputConfigEffort\"; value: Effort }\n  /** OpenAI `reasoning_effort`. */\n  | { param: \"reasoningEffort\"; value: string }\n  /** Google `thinkingConfig.thinkingBudget` (-1 = dynamic). */\n  | { param: \"thinkingBudget\"; value: number }\n  /** Google `thinkingConfig.thinkingLevel` (Gemini 3.x generation). */\n  | { param: \"thinkingLevel\"; value: \"minimal\" | \"low\" | \"medium\" | \"high\" };\n\n/** A model's reasoning descriptor: the effort-ladder levels it actually\n *  supports and how each maps to the provider-native knob. */\nexport interface ThinkingSupport {\n  control: ThinkingControl;\n  /** Ladder levels the model accepts, ascending. Omitted/empty = no effort knob. */\n  effortLevels?: Effort[];\n  /** Native mapping per supported level; keys must equal `effortLevels`. */\n  effortMap?: Partial<Record<Effort, NativeEffort>>;\n  /** `control: \"budget\"` only — the budget_tokens sent when a request asks for\n   *  `thinking: \"adaptive\"` (clamped below maxTokens by the adapter). */\n  defaultBudgetTokens?: number;\n  /** The native effort value to send when the request carries FUNCTION TOOLS.\n   *\n   *  Some reasoning models refuse tools while any reasoning is in play on the\n   *  provider's chat endpoint, and reason by default when the parameter is\n   *  omitted — so sending nothing is what fails. OpenAI's gpt-5.6 line says so\n   *  outright: \"Function tools with reasoning_effort are not supported … use\n   *  /v1/responses or set reasoning_effort to 'none'\".\n   *\n   *  Set it and the adapter sends this value for tool-carrying requests instead\n   *  of leaving the model on its default. Requesting an explicit `effort`\n   *  alongside tools on such a model is a CapabilityError, not a silent\n   *  downgrade — the caller asked for depth the endpoint cannot give. */\n  toolsEffort?: NativeEffort;\n}\n\n/** The full unified effort ladder, ascending. */\nexport const EFFORT_LEVELS: readonly Effort[] = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\n/** Resolve the provider-native mapping for an effort level on a model, or\n *  undefined when the model does not map that level. */\nexport function nativeEffort(spec: ModelSpec, effort: Effort): NativeEffort | undefined {\n  return spec.thinking?.effortMap?.[effort];\n}\n\n/** The effort levels a spec supports — descriptor first; specs authored before\n *  the descriptor existed fall back to the legacy capability boolean (all\n *  levels when `capabilities.effort` is true). */\nexport function supportedEffortLevels(spec: ModelSpec): Effort[] {\n  if (spec.thinking) return spec.thinking.effortLevels ?? [];\n  return spec.capabilities.effort ? [...EFFORT_LEVELS] : [];\n}\n\n/** Generic Gemini thinkingBudget ladder used when no hand-tuned map exists. */\nconst GOOGLE_BUDGETS: Record<Effort, number> = {\n  low: 1_024,\n  medium: 4_096,\n  high: 8_192,\n  xhigh: 16_384,\n  max: 24_576,\n};\n\n/**\n * Derive a sensible per-provider `effortMap` for a set of levels: identity\n * maps for Anthropic (`output_config.effort`) and OpenAI (`reasoning_effort`),\n * a generic token-budget ladder for Google. Used by callers (e.g. the odla\n * platform's catalog editor) that know a model's levels but not its native\n * knob values; hand-tuned catalog entries override this.\n */\nexport function defaultEffortMap(\n  provider: ProviderId,\n  levels: Effort[],\n  nativeId?: string,\n): Partial<Record<Effort, NativeEffort>> {\n  const out: Partial<Record<Effort, NativeEffort>> = {};\n  for (const level of levels) {\n    if (provider === \"google\" && nativeId?.startsWith(\"gemini-3\")) {\n      if (level === \"low\" || level === \"medium\" || level === \"high\") {\n        out[level] = { param: \"thinkingLevel\", value: level };\n      }\n    } else if (provider === \"google\") out[level] = { param: \"thinkingBudget\", value: GOOGLE_BUDGETS[level] };\n    else if (provider === \"openai\") out[level] = { param: \"reasoningEffort\", value: level };\n    else out[level] = { param: \"outputConfigEffort\", value: level };\n  }\n  return out;\n}\n","// Normalize a thrown provider-SDK error into the odla-ai error taxonomy. Kept\n// dependency-light: it duck-types the HTTP status / retry-after off the error\n// object rather than importing each SDK's error classes, so it works uniformly\n// across @anthropic-ai/sdk, openai, and @google/genai.\n\nimport {\n  AuthError,\n  CancelledError,\n  ContextWindowError,\n  DeadlineExceededError,\n  InvalidRequestError,\n  OdlaAIError,\n  ProviderError,\n  RateLimitError,\n  type ProviderId,\n} from \"../shape/index\";\n\nfunction statusOf(err: unknown): number | undefined {\n  if (err && typeof err === \"object\") {\n    const rec = err as Record<string, unknown>;\n    for (const k of [\"status\", \"statusCode\", \"code\"]) {\n      const v = rec[k];\n      if (typeof v === \"number\") return v;\n    }\n  }\n  return undefined;\n}\n\nfunction retryAfterOf(err: unknown): number | undefined {\n  if (!err || typeof err !== \"object\") return undefined;\n  const headers = (err as { headers?: unknown }).headers;\n  if (!headers || typeof headers !== \"object\") return undefined;\n\n  // The OpenAI and Anthropic SDKs expose a web `Headers` instance. Some\n  // custom transports expose a plain object instead, occasionally preserving\n  // the provider's original header casing. Support both without importing an\n  // SDK-specific error type.\n  const header = (name: string): unknown => {\n    const get = (headers as { get?: unknown }).get;\n    if (typeof get === \"function\") return get.call(headers, name);\n    const entry = Object.entries(headers as Record<string, unknown>)\n      .find(([key]) => key.toLowerCase() === name);\n    return entry?.[1];\n  };\n\n  const milliseconds = numericHeader(header(\"retry-after-ms\"));\n  if (milliseconds !== undefined) return milliseconds / 1_000;\n\n  const raw = header(\"retry-after\");\n  const seconds = numericHeader(raw);\n  if (seconds !== undefined) return seconds;\n  if (typeof raw !== \"string\") return undefined;\n  const timestamp = Date.parse(raw);\n  if (!Number.isFinite(timestamp)) return undefined;\n  return Math.max(0, (timestamp - Date.now()) / 1_000);\n}\n\nfunction numericHeader(value: unknown): number | undefined {\n  const parsed = typeof value === \"number\" ? value : typeof value === \"string\" && value.trim() ? Number(value) : NaN;\n  return Number.isFinite(parsed) && parsed >= 0 ? parsed : undefined;\n}\n\nfunction messageOf(err: unknown): string {\n  if (err instanceof Error) return err.message;\n  if (typeof err === \"string\") return err;\n  return \"unknown provider error\";\n}\n\n/** Map any provider error to an OdlaAIError, returning it (does not throw).\n *  Re-returns an OdlaAIError unchanged (already normalized). */\nexport function normalizeError(err: unknown, provider: ProviderId, signal?: AbortSignal): OdlaAIError {\n  if (err instanceof OdlaAIError) return err;\n  const cancellation = cancellationError(signal?.aborted ? signal.reason : err);\n  if (signal?.aborted || cancellation) return cancellation ?? new CancelledError(undefined, { cause: err });\n\n  const status = statusOf(err);\n  const message = messageOf(err);\n  const tagged = `[${provider}] ${message}`;\n\n  if (status === 401 || status === 403) return new AuthError(tagged, { providerStatus: status, cause: err });\n  if (status === 429) {\n    return new RateLimitError(tagged, { providerStatus: status, retryAfter: retryAfterOf(err), cause: err });\n  }\n  if (status === 400 || status === 422) {\n    if (/context|token limit|too long|maximum context/i.test(message)) {\n      return new ContextWindowError(tagged, { providerStatus: status, cause: err });\n    }\n    return new InvalidRequestError(tagged, { providerStatus: status, cause: err });\n  }\n  return new ProviderError(tagged, { providerStatus: status, cause: err });\n}\n\n/**\n * Normalize and throw. The `never` return lets call sites write\n * `catch (e) { mapProviderError(e, id); }` with no fallthrough.\n */\nexport function mapProviderError(err: unknown, provider: ProviderId, signal?: AbortSignal): never {\n  throw normalizeError(err, provider, signal);\n}\n\nfunction cancellationError(reason: unknown): CancelledError | DeadlineExceededError | undefined {\n  if (reason instanceof DeadlineExceededError || reason instanceof CancelledError) return reason;\n  if (!reason || typeof reason !== \"object\") return undefined;\n  const rec = reason as { name?: unknown; code?: unknown; message?: unknown };\n  if (rec.name === \"TimeoutError\") return new DeadlineExceededError(undefined, { cause: reason });\n  if (rec.name === \"AbortError\" || rec.name === \"APIUserAbortError\" || rec.code === \"ABORT_ERR\") {\n    return new CancelledError(undefined, { cause: reason });\n  }\n  return undefined;\n}\n","// Derive a RequestEcho from each provider's built native params. Every function\n// here reads the params object the adapter is about to send — never the\n// OracleRequest — so the echo reports reality rather than restating intent.\n\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport type { RequestEcho } from \"../shape/echo\";\n\n/**\n * Whether the model reasons when no explicit thinking parameter is sent.\n *\n * `ThinkingControl` describes the request *toggle*, not whether the model\n * reasons internally, so \"none\" cannot be read as \"does not reason\". Every\n * OpenAI reasoning model is `control: \"none\"` with a populated effort ladder:\n * there is no on/off switch, you only choose the depth, and omitting the\n * parameter gets the provider's own reasoning default. A \"none\" model with an\n * empty ladder (gpt-4o, gemini-2.0-flash) is the genuinely non-reasoning case.\n *\n * Descriptor-less specs — the shape discovery hands back — report inactive,\n * because \"we cannot tell\" must not read as a claim that the model reasons.\n */\nfunction defaultThinkingActive(spec: ModelSpec): boolean {\n  const control = spec.thinking?.control;\n  if (!control) return false;\n  if (control === \"always-on\" || control === \"on-by-default\") return true;\n  return control === \"none\" && (spec.thinking?.effortLevels?.length ?? 0) > 0;\n}\n\nfunction toolCountOf(params: Record<string, unknown>): number {\n  const tools = params.tools;\n  return Array.isArray(tools) ? tools.length : 0;\n}\n\n/** Echo for the Anthropic adapter's params (see providers/anthropic/request). */\nexport function echoFromAnthropic(spec: ModelSpec, params: Record<string, unknown>): RequestEcho {\n  const thinking = params.thinking as { type?: string } | undefined;\n  const outputConfig = params.output_config as { effort?: string } | undefined;\n  const echo: RequestEcho = {\n    provider: \"anthropic\",\n    nativeModel: String(params.model ?? spec.nativeId),\n    thinkingActive: thinking\n      ? thinking.type === \"adaptive\" || thinking.type === \"enabled\"\n      : defaultThinkingActive(spec),\n    toolCount: toolCountOf(params),\n  };\n  if (outputConfig?.effort !== undefined) {\n    echo.nativeEffort = { param: \"outputConfigEffort\", value: outputConfig.effort as never };\n  }\n  if (typeof params.max_tokens === \"number\") echo.maxTokens = params.max_tokens;\n  if (typeof params.temperature === \"number\") echo.temperature = params.temperature;\n  return echo;\n}\n\n/** Echo for the OpenAI adapter's params (see providers/openai/request). */\nexport function echoFromOpenAI(spec: ModelSpec, params: Record<string, unknown>): RequestEcho {\n  const effort = params.reasoning_effort;\n  const echo: RequestEcho = {\n    provider: \"openai\",\n    nativeModel: String(params.model ?? spec.nativeId),\n    // \"none\" is a real, sent value meaning reasoning is off — distinct from the\n    // parameter being absent, where the model's own default governs.\n    thinkingActive: effort === undefined ? defaultThinkingActive(spec) : effort !== \"none\",\n    toolCount: toolCountOf(params),\n  };\n  if (effort !== undefined) echo.nativeEffort = { param: \"reasoningEffort\", value: String(effort) };\n  if (typeof params.max_completion_tokens === \"number\") echo.maxTokens = params.max_completion_tokens;\n  if (typeof params.temperature === \"number\") echo.temperature = params.temperature;\n  return echo;\n}\n\n/** Echo for the OpenAI Responses adapter's params (see\n *  providers/openai/responses-request). Reasoning lives under `reasoning.effort`\n *  rather than a flat field, and `\"none\"` is a real sent value meaning reasoning\n *  is off — distinct from the object being absent. */\nexport function echoFromOpenAIResponses(spec: ModelSpec, params: Record<string, unknown>): RequestEcho {\n  const effort = (params.reasoning as { effort?: unknown } | undefined)?.effort;\n  const echo: RequestEcho = {\n    provider: \"openai\",\n    nativeModel: String(params.model ?? spec.nativeId),\n    thinkingActive: effort === undefined ? defaultThinkingActive(spec) : effort !== \"none\",\n    toolCount: toolCountOf(params),\n  };\n  if (effort !== undefined) echo.nativeEffort = { param: \"reasoningEffort\", value: String(effort) };\n  if (typeof params.max_output_tokens === \"number\") echo.maxTokens = params.max_output_tokens;\n  if (typeof params.temperature === \"number\") echo.temperature = params.temperature;\n  return echo;\n}\n\n/** Echo for the Google adapter's params (see providers/google/request). Gemini\n *  nests everything under `config`, and tools arrive as a single entry carrying\n *  many `functionDeclarations`, so the tool count is summed rather than the\n *  array length. */\nexport function echoFromGoogle(spec: ModelSpec, params: Record<string, unknown>): RequestEcho {\n  const config = (params.config ?? {}) as Record<string, unknown>;\n  const thinkingConfig = config.thinkingConfig as\n    | { thinkingBudget?: number; thinkingLevel?: string }\n    | undefined;\n\n  let thinkingActive = defaultThinkingActive(spec);\n  const echo: RequestEcho = {\n    provider: \"google\",\n    nativeModel: String(params.model ?? spec.nativeId),\n    thinkingActive,\n    toolCount: googleToolCount(config.tools),\n  };\n  if (thinkingConfig?.thinkingBudget !== undefined) {\n    const budget = thinkingConfig.thinkingBudget;\n    echo.nativeEffort = { param: \"thinkingBudget\", value: budget };\n    thinkingActive = budget !== 0; // 0 = disabled, -1 = dynamic\n  } else if (thinkingConfig?.thinkingLevel !== undefined) {\n    echo.nativeEffort = { param: \"thinkingLevel\", value: thinkingConfig.thinkingLevel as never };\n    thinkingActive = true;\n  }\n  echo.thinkingActive = thinkingActive;\n\n  if (typeof config.maxOutputTokens === \"number\") echo.maxTokens = config.maxOutputTokens;\n  if (typeof config.temperature === \"number\") echo.temperature = config.temperature;\n  return echo;\n}\n\nfunction googleToolCount(tools: unknown): number {\n  if (!Array.isArray(tools)) return 0;\n  let count = 0;\n  for (const entry of tools) {\n    const decls = (entry as { functionDeclarations?: unknown }).functionDeclarations;\n    count += Array.isArray(decls) ? decls.length : 1; // googleSearch etc. count as one\n  }\n  return count;\n}\n","// Anthropic request mapping. The canonical shape is Anthropic-flavored, so this\n// is the lowest-translation adapter.\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type { ModelSpec } from \"../../shape/capabilities\";\nimport { nativeEffort } from \"../../shape/thinking\";\nimport {\n  CapabilityError,\n  ConfigError,\n  type OracleContentBlock,\n  type OracleRequest,\n  type TextBlock,\n  type ToolChoice,\n} from \"../../shape/index\";\n\nexport function buildParams(\n  spec: ModelSpec,\n  req: OracleRequest,\n  messages: Anthropic.MessageParam[],\n): Record<string, unknown> {\n  const params: Record<string, unknown> = {\n    model: spec.nativeId,\n    max_tokens: req.maxTokens,\n    messages,\n  };\n\n  const system = toAnthropicSystem(req.system);\n  if (system !== undefined) params.system = system;\n\n  const tools = buildTools(spec, req);\n  if (tools) params.tools = tools;\n\n  const toolChoice = mapToolChoice(req.toolChoice);\n  if (toolChoice) params.tool_choice = toolChoice;\n\n  if (req.stopSequences && req.stopSequences.length > 0) params.stop_sequences = req.stopSequences;\n\n  // Sampling params are rejected on the frontier models (they carry effort);\n  // only the non-effort tier (Haiku) accepts temperature.\n  if (req.temperature !== undefined && !spec.capabilities.effort) params.temperature = req.temperature;\n\n  applyThinking(params, spec, req);\n\n  const outputConfig: Record<string, unknown> = {};\n  if (req.effort) {\n    const mapped = nativeEffort(spec, req.effort);\n    if (mapped) {\n      if (mapped.param !== \"outputConfigEffort\") {\n        throw new ConfigError(\n          `Model \"${spec.id}\" maps effort \"${req.effort}\" to \"${mapped.param}\" — not an Anthropic knob (mis-authored catalog entry).`,\n        );\n      }\n      outputConfig.effort = mapped.value;\n    } else if (!spec.thinking && spec.capabilities.effort) {\n      outputConfig.effort = req.effort; // legacy descriptor-less spec\n    }\n  }\n  if (req.responseFormat && spec.capabilities.structuredOutput) {\n    outputConfig.format = { type: \"json_schema\", schema: req.responseFormat.schema };\n  }\n  if (Object.keys(outputConfig).length > 0) params.output_config = outputConfig;\n\n  if (req.providerExtras) Object.assign(params, req.providerExtras);\n  return params;\n}\n\n/** Map the canonical thinking toggle onto Anthropic's per-model request shape:\n *  always-on models take no `thinking` param at all (an explicit config would\n *  400); on-by-default models take `{type:\"disabled\"}` to turn it off; opt-in\n *  models take `{type:\"adaptive\"}`; budget-era models (Haiku) take\n *  `{type:\"enabled\", budget_tokens}`. */\nfunction applyThinking(params: Record<string, unknown>, spec: ModelSpec, req: OracleRequest): void {\n  const descriptor = spec.thinking;\n  if (!descriptor) {\n    if (req.thinking === \"adaptive\" && spec.capabilities.thinking) params.thinking = { type: \"adaptive\" };\n    return;\n  }\n  switch (descriptor.control) {\n    case \"on-by-default\":\n      if (req.thinking === \"off\") params.thinking = { type: \"disabled\" };\n      return;\n    case \"opt-in\":\n      if (req.thinking === \"adaptive\") params.thinking = { type: \"adaptive\" };\n      return;\n    case \"budget\": {\n      if (req.thinking !== \"adaptive\") return;\n      // budget_tokens must be >= 1024 and < max_tokens, and the answer still\n      // needs room after thinking — so require maxTokens >= 2048.\n      const budget = Math.min(descriptor.defaultBudgetTokens ?? 8_192, req.maxTokens - 1_024);\n      if (budget < 1_024) {\n        throw new CapabilityError(\n          `Model \"${spec.id}\" needs maxTokens >= 2048 to think (budget_tokens is >= 1024 and must leave output room); got ${req.maxTokens}.`,\n        );\n      }\n      params.thinking = { type: \"enabled\", budget_tokens: budget };\n      return;\n    }\n    default:\n      return; // \"always-on\": omit the param entirely; \"none\": nothing to send\n  }\n}\n\nfunction toAnthropicSystem(system: OracleRequest[\"system\"]): string | Anthropic.TextBlockParam[] | undefined {\n  if (system === undefined) return undefined;\n  if (typeof system === \"string\") return system;\n  return system.map((b: TextBlock) => ({\n    type: \"text\" as const,\n    text: b.text,\n    ...(b.cacheControl ? { cache_control: { type: \"ephemeral\" as const } } : {}),\n  }));\n}\n\nexport function toAnthropicMessages(req: OracleRequest): Anthropic.MessageParam[] {\n  return req.messages.map((m) => ({\n    role: m.role,\n    content: typeof m.content === \"string\" ? m.content : m.content.map(anthropicBlock),\n  }));\n}\n\nfunction anthropicBlock(b: OracleContentBlock): Anthropic.ContentBlockParam {\n  switch (b.type) {\n    case \"text\":\n      return {\n        type: \"text\",\n        text: b.text,\n        ...(b.cacheControl ? { cache_control: { type: \"ephemeral\" } } : {}),\n      };\n    case \"image\":\n      return {\n        type: \"image\",\n        source:\n          b.source.type === \"base64\"\n            ? { type: \"base64\", media_type: b.source.mediaType, data: b.source.data }\n            : { type: \"url\", url: b.source.url },\n      } as Anthropic.ContentBlockParam;\n    case \"document\":\n      return {\n        type: \"document\",\n        source:\n          b.source.type === \"base64\"\n            ? { type: \"base64\", media_type: \"application/pdf\", data: b.source.data }\n            : { type: \"url\", url: b.source.url },\n      } as Anthropic.ContentBlockParam;\n    case \"tool_use\":\n      return { type: \"tool_use\", id: b.id, name: b.name, input: b.input };\n    case \"tool_result\":\n      return {\n        type: \"tool_result\",\n        tool_use_id: b.toolUseId,\n        content:\n          typeof b.content === \"string\"\n            ? b.content\n            : (b.content.map(anthropicBlock) as Anthropic.ToolResultBlockParam[\"content\"]),\n        ...(b.isError ? { is_error: true } : {}),\n      };\n    case \"thinking\":\n      return { type: \"thinking\", thinking: b.thinking, signature: b.signature ?? \"\" };\n    case \"audio\":\n      // Guarded by validateRequest; defensive in case validation is bypassed.\n      throw new Error(\"Anthropic does not support audio input\");\n  }\n}\n\nfunction buildTools(spec: ModelSpec, req: OracleRequest): unknown[] | undefined {\n  const tools: unknown[] = [];\n  for (const t of req.tools ?? []) {\n    tools.push({ name: t.name, description: t.description, input_schema: t.inputSchema });\n  }\n  if (req.webSearch) {\n    const power = spec.superpowers?.webSearch;\n    const toolType = power?.type === \"anthropic-web-search\" ? power.toolType : \"web_search_20260209\";\n    tools.push({ type: toolType, name: \"web_search\" });\n  }\n  return tools.length > 0 ? tools : undefined;\n}\n\nfunction mapToolChoice(tc: ToolChoice | undefined): unknown | undefined {\n  if (tc === undefined) return undefined;\n  if (tc === \"auto\") return { type: \"auto\" };\n  if (tc === \"any\") return { type: \"any\" };\n  if (tc === \"none\") return { type: \"none\" };\n  return { type: \"tool\", name: tc.name };\n}\n","// Anthropic list-models mapping. The Models API (GET /v1/models) returns, since\n// Mar 2026, `max_input_tokens`, `max_tokens`, and a `capabilities` tree with\n// `supported` leaves — none of which the installed @anthropic-ai/sdk (0.70.x)\n// types yet, so this reads them off the raw payload with defensive guards.\n\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport { EFFORT_LEVELS } from \"../../shape/thinking\";\nimport type { Effort } from \"../../shape/index\";\nimport type { DiscoveredModel, DiscoveryHints } from \"../types\";\nimport { mapProviderError } from \"../errors\";\n\nexport async function listAnthropicModels(\n  client: Anthropic,\n  opts?: { signal?: AbortSignal },\n): Promise<DiscoveredModel[]> {\n  try {\n    const out: DiscoveredModel[] = [];\n    // Anthropic's Models API supports up to 1,000 records per page. The SDK\n    // iterator still follows any subsequent page, while the explicit limit\n    // avoids a tiny default page making refreshes look incomplete.\n    for await (const info of client.models.list({ limit: 1_000 }, { signal: opts?.signal })) {\n      out.push(mapAnthropicModel(info as unknown as Record<string, unknown>));\n    }\n    return out;\n  } catch (err) {\n    mapProviderError(err, \"anthropic\", opts?.signal);\n  }\n}\n\n/** Normalize one raw Models-API entry. Exported for fixture tests. */\nexport function mapAnthropicModel(raw: Record<string, unknown>): DiscoveredModel {\n  const model: DiscoveredModel = { provider: \"anthropic\", nativeId: String(raw.id ?? \"\"), raw };\n  if (typeof raw.display_name === \"string\") model.displayName = raw.display_name;\n  if (typeof raw.max_input_tokens === \"number\") model.contextWindow = raw.max_input_tokens;\n  if (typeof raw.max_tokens === \"number\") model.maxOutput = raw.max_tokens;\n  const hints = capabilityHints(raw.capabilities);\n  if (hints) model.hints = hints;\n  return model;\n}\n\nfunction capabilityHints(capabilities: unknown): DiscoveryHints | undefined {\n  if (!capabilities || typeof capabilities !== \"object\") return undefined;\n  const caps = capabilities as Record<string, unknown>;\n  const hints: DiscoveryHints = {};\n\n  const imageIn = supported(caps.image_input);\n  if (imageIn !== undefined) hints.imageIn = imageIn;\n  const structured = supported(caps.structured_outputs);\n  if (structured !== undefined) hints.structuredOutput = structured;\n  const documentIn = firstDefined(supported(caps.pdf_input), supported(caps.document_input));\n  if (documentIn !== undefined) hints.documentIn = documentIn;\n  // As of 2026-08-11 the Models API advertises no server-tool support at all,\n  // so this stays `undefined` for every Claude model and the platform derives\n  // web search from its own table. Probed anyway: if Anthropic starts\n  // publishing it, discovery picks it up with no code change.\n  const webSearch = firstDefined(\n    supported(caps.web_search),\n    supported(caps.web_search_tool),\n    supported(leaf(caps.server_tools, \"web_search\")),\n  );\n  if (webSearch !== undefined) hints.webSearch = webSearch;\n\n  // `thinking.supported` says the model reasons; the `types` leaves say *how*.\n  // Conflating the two marks every budget-style model (Haiku 4.5, the dated\n  // 4.5 line) as having no thinking at all.\n  const thinks = supported(caps.thinking);\n  if (thinks !== undefined) hints.thinking = thinks;\n  const adaptive = supported(leaf(caps.thinking, \"types\", \"adaptive\"));\n  if (adaptive !== undefined) hints.adaptiveThinking = adaptive;\n  const budget = supported(leaf(caps.thinking, \"types\", \"enabled\"));\n  if (budget !== undefined) hints.budgetThinking = budget;\n\n  if (caps.effort && typeof caps.effort === \"object\") {\n    const effort = caps.effort as Record<string, unknown>;\n    const levels = EFFORT_LEVELS.filter((level: Effort) => supported(effort[level]) === true);\n    if (levels.length > 0) hints.effortLevels = levels;\n  }\n\n  return Object.keys(hints).length > 0 ? hints : undefined;\n}\n\nfunction leaf(node: unknown, ...path: string[]): unknown {\n  let current = node;\n  for (const key of path) {\n    if (!current || typeof current !== \"object\") return undefined;\n    current = (current as Record<string, unknown>)[key];\n  }\n  return current;\n}\n\nfunction supported(node: unknown): boolean | undefined {\n  if (!node || typeof node !== \"object\") return undefined;\n  const value = (node as Record<string, unknown>).supported;\n  return typeof value === \"boolean\" ? value : undefined;\n}\n\nfunction firstDefined(...values: Array<boolean | undefined>): boolean | undefined {\n  return values.find((value) => value !== undefined);\n}\n","import { ToolInputError, type ProviderId } from \"../shape/index\";\n\n/** Normalize a provider's decoded function arguments without manufacturing an\n * empty object from malformed data. Schema validation happens at the facade or\n * agent boundary, but structural corruption fails here. */\nexport function toolInput(value: unknown, provider: ProviderId, name: string): Record<string, unknown> {\n  if (value !== null && typeof value === \"object\" && !Array.isArray(value)) {\n    return value as Record<string, unknown>;\n  }\n  throw new ToolInputError(`[${provider}] tool \"${name}\" returned arguments that are not a JSON object.`, { tool: name });\n}\n","// Anthropic response mapping. mapUsage / mapStop are also used by the stream\n// mapper (kept here so the entry ↔ stream edge stays one-directional).\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type { OracleContentBlock, OracleStopReason, OracleUsage, SearchCitation } from \"../../shape/index\";\nimport { toolInput } from \"../tool-input\";\n\nexport function mapContent(blocks: Anthropic.ContentBlock[]): OracleContentBlock[] {\n  const out: OracleContentBlock[] = [];\n  for (const b of blocks) {\n    if (b.type === \"text\") out.push({ type: \"text\", text: b.text });\n    else if (b.type === \"tool_use\") {\n      out.push({ type: \"tool_use\", id: b.id, name: b.name, input: toolInput(b.input ?? {}, \"anthropic\", b.name) });\n    } else if (b.type === \"thinking\") {\n      out.push({ type: \"thinking\", thinking: b.thinking, signature: b.signature });\n    }\n    // server_tool_use / web_search_tool_result blocks carry no answer text; their\n    // sources are read separately by mapCitations.\n  }\n  return out;\n}\n\n/**\n * Read web-search sources out of a response's blocks: the result set carried by\n * `web_search_tool_result`, plus the per-sentence `citations` Anthropic stamps\n * onto text blocks. Search blocks are untyped in the installed SDK, so they are\n * narrowed structurally — a search error returns an object instead of a result\n * array and contributes nothing.\n */\nexport function mapCitations(blocks: Anthropic.ContentBlock[]): SearchCitation[] {\n  const out: SearchCitation[] = [];\n  for (const b of blocks as unknown as Record<string, unknown>[]) {\n    if (b.type === \"web_search_tool_result\" && Array.isArray(b.content)) {\n      for (const r of b.content as Record<string, unknown>[]) {\n        if (r?.type === \"web_search_result\" && typeof r.url === \"string\") {\n          out.push(citation(r.url, r.title));\n        }\n      }\n    } else if (b.type === \"text\" && Array.isArray(b.citations)) {\n      for (const c of b.citations as Record<string, unknown>[]) {\n        if (typeof c?.url !== \"string\") continue;\n        const cited = typeof c.cited_text === \"string\" ? c.cited_text : undefined;\n        out.push({ ...citation(c.url, c.title), ...(cited ? { citedText: cited } : {}) });\n      }\n    }\n  }\n  return out;\n}\n\nfunction citation(url: string, title: unknown): SearchCitation {\n  return { url, ...(typeof title === \"string\" && title ? { title } : {}) };\n}\n\nexport function mapUsage(u: Anthropic.Usage): OracleUsage {\n  const usage: OracleUsage = { inputTokens: u.input_tokens ?? 0, outputTokens: u.output_tokens ?? 0 };\n  if (u.cache_creation_input_tokens != null) usage.cacheCreationTokens = u.cache_creation_input_tokens;\n  if (u.cache_read_input_tokens != null) usage.cacheReadTokens = u.cache_read_input_tokens;\n  return usage;\n}\n\nexport function mapStop(reason: string | null | undefined): OracleStopReason {\n  switch (reason) {\n    case \"end_turn\":\n    case \"max_tokens\":\n    case \"stop_sequence\":\n    case \"tool_use\":\n    case \"pause_turn\":\n    case \"refusal\":\n      return reason;\n    default:\n      return \"end_turn\";\n  }\n}\n","// Anthropic stream mapping. The SDK's raw events pass through nearly 1:1.\nimport type Anthropic from \"@anthropic-ai/sdk\";\nimport type { OracleContentBlock, OracleEvent, OracleRequest } from \"../../shape/index\";\nimport { mapStop, mapUsage } from \"./response\";\n\nexport function mapStreamEvent(raw: Anthropic.RawMessageStreamEvent, req: OracleRequest): OracleEvent | undefined {\n  switch (raw.type) {\n    case \"message_start\":\n      return {\n        type: \"message_start\",\n        message: {\n          id: raw.message.id,\n          model: req.model,\n          provider: \"anthropic\",\n          role: \"assistant\",\n          content: [],\n          usage: mapUsage(raw.message.usage),\n        },\n      };\n    case \"content_block_start\": {\n      const block = mapStartBlock(raw.content_block);\n      return block ? { type: \"content_block_start\", index: raw.index, contentBlock: block } : undefined;\n    }\n    case \"content_block_delta\": {\n      const d = raw.delta;\n      if (d.type === \"text_delta\") return { type: \"content_block_delta\", index: raw.index, delta: { type: \"text_delta\", text: d.text } };\n      if (d.type === \"thinking_delta\") return { type: \"content_block_delta\", index: raw.index, delta: { type: \"thinking_delta\", thinking: d.thinking } };\n      if (d.type === \"input_json_delta\") return { type: \"content_block_delta\", index: raw.index, delta: { type: \"input_json_delta\", partialJson: d.partial_json } };\n      return undefined;\n    }\n    case \"content_block_stop\":\n      return { type: \"content_block_stop\", index: raw.index };\n    case \"message_delta\":\n      return { type: \"message_delta\", delta: { stopReason: mapStop(raw.delta.stop_reason) }, usage: mapUsage(raw.usage as Anthropic.Usage) };\n    case \"message_stop\":\n      return { type: \"message_stop\" };\n    default:\n      return undefined;\n  }\n}\n\nfunction mapStartBlock(cb: Anthropic.ContentBlock): OracleContentBlock | undefined {\n  if (cb.type === \"text\") return { type: \"text\", text: cb.text };\n  if (cb.type === \"tool_use\") return { type: \"tool_use\", id: cb.id, name: cb.name, input: {} };\n  if (cb.type === \"thinking\") return { type: \"thinking\", thinking: cb.thinking, signature: cb.signature };\n  return undefined;\n}\n","import { CancelledError, ConfigError, DeadlineExceededError } from \"../shape/errors\";\n\n/** Combine a caller signal with an absolute deadline. Kept provider-neutral so\n * every adapter and the agent loop observes the same cancellation contract. */\nexport function signalWithDeadline(signal?: AbortSignal, deadline?: number): AbortSignal | undefined {\n  if (deadline === undefined) return signal;\n  if (!Number.isSafeInteger(deadline)) throw new ConfigError(\"deadline must be a finite integer Unix timestamp in milliseconds.\");\n  const remaining = deadline - Date.now();\n  if (remaining <= 0) {\n    const expired = new AbortController();\n    expired.abort(new DeadlineExceededError());\n    return signal ? AbortSignal.any([signal, expired.signal]) : expired.signal;\n  }\n  const timeout = AbortSignal.timeout(remaining);\n  return signal ? AbortSignal.any([signal, timeout]) : timeout;\n}\n\n/** Fail synchronously before beginning a local side effect when a run was\n * cancelled or its deadline elapsed. Handlers must still observe the signal\n * while in flight; this closes the already-aborted race at invocation time. */\nexport function throwIfAborted(signal?: AbortSignal): void {\n  if (!signal?.aborted) return;\n  const reason = signal.reason;\n  if (reason instanceof DeadlineExceededError || reason instanceof CancelledError) throw reason;\n  if (reason && typeof reason === \"object\" && (reason as { name?: unknown }).name === \"TimeoutError\") {\n    throw new DeadlineExceededError(undefined, { cause: reason });\n  }\n  throw new CancelledError(undefined, { cause: reason });\n}\n","// Anthropic (Claude) adapter. The canonical shape is Anthropic-flavored, so this\n// is the lowest-translation adapter. Ported from odla-kg's claude.ts patterns:\n// forced tool-call via tool_choice, web_search_20260209 with pause_turn\n// continuation, adaptive thinking + output_config.effort (never budget_tokens).\n//\n// The installed @anthropic-ai/sdk (0.70.x) doesn't yet type adaptive thinking,\n// output_config, or web_search_20260209 — those newer request fields are built\n// into a loose params object in ./anthropic/request and cast at the call site\n// (the wire accepts them), exactly as odla-kg does for the web-search tool literal.\n\nimport Anthropic from \"@anthropic-ai/sdk\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport type { Provider } from \"./types\";\nimport { mapProviderError, normalizeError } from \"./errors\";\nimport { addUsage, emptyUsage, mergeCitations, type OracleContentBlock, type OracleEvent, type OracleRequest, type OracleResponse, type OracleStopReason, type RequestEcho, type SearchCitation } from \"../shape/index\";\nimport { echoFromAnthropic } from \"./echo\";\nimport { buildParams, toAnthropicMessages } from \"./anthropic/request\";\nimport { listAnthropicModels } from \"./anthropic/models\";\nimport { mapCitations, mapContent, mapStop, mapUsage } from \"./anthropic/response\";\nimport { mapStreamEvent } from \"./anthropic/stream\";\nimport { signalWithDeadline } from \"../client/abort\";\n\nexport class AnthropicProvider implements Provider {\n  readonly id = \"anthropic\" as const;\n  private client: Anthropic;\n\n  /** `client` may be injected (tests, custom transport); otherwise built from key. */\n  constructor(apiKey: string, client?: Anthropic) {\n    this.client = client ?? new Anthropic({ apiKey });\n  }\n\n  async create(spec: ModelSpec, req: OracleRequest): Promise<OracleResponse> {\n    const signal = signalWithDeadline(req.signal, req.deadline);\n    try {\n      let messages = toAnthropicMessages(req);\n      const content: OracleContentBlock[] = [];\n      const cites: SearchCitation[] = [];\n      const usage = emptyUsage();\n      let stopReason: OracleStopReason = \"end_turn\";\n      let id = \"\";\n      let echo: RequestEcho | undefined;\n\n      // Loop only to resolve server-side tools (pause_turn), max 8 hops. Client\n      // tool_use / end_turn / etc. return immediately.\n      for (let i = 0; i < 8; i++) {\n        const params = buildParams(spec, req, messages);\n        // Read the echo off the first hop's params: later pause_turn hops carry\n        // the same knobs and only differ in accumulated messages.\n        echo ??= echoFromAnthropic(spec, params);\n        const res = await this.client.messages.create(\n          params as unknown as Anthropic.MessageCreateParamsNonStreaming,\n          { signal },\n        );\n        id = res.id;\n        addUsage(usage, mapUsage(res.usage));\n        content.push(...mapContent(res.content));\n        cites.push(...mapCitations(res.content));\n        stopReason = mapStop(res.stop_reason);\n        if (res.stop_reason === \"pause_turn\") {\n          messages = [...messages, { role: \"assistant\", content: res.content }];\n          continue;\n        }\n        break;\n      }\n\n      const citations = mergeCitations(cites);\n      return { id, model: req.model, provider: \"anthropic\", role: \"assistant\", content, stopReason, usage, ...(citations.length ? { citations } : {}), ...(echo ? { echo } : {}) };\n    } catch (err) {\n      mapProviderError(err, \"anthropic\", signal);\n    }\n  }\n\n  async *stream(spec: ModelSpec, req: OracleRequest): AsyncIterable<OracleEvent> {\n    const signal = signalWithDeadline(req.signal, req.deadline);\n    try {\n      let messages = toAnthropicMessages(req);\n      const usage = emptyUsage();\n      let contentOffset = 0;\n      let emittedStart = false;\n      for (let hop = 0; hop < 8; hop++) {\n        const events = this.client.messages.stream(\n          buildParams(spec, req, messages) as unknown as Anthropic.MessageStreamParams,\n          { signal },\n        );\n        for await (const raw of events) {\n          // A pause_turn continuation is one logical Oracle stream. Suppress\n          // each hop's terminal envelope, emit one start, and offset later\n          // content blocks so callers see a single contiguous message.\n          if (raw.type === \"message_delta\" || raw.type === \"message_stop\") continue;\n          if (raw.type === \"message_start\" && emittedStart) continue;\n          const ev = mapStreamEvent(raw, req);\n          if (!ev) continue;\n          if (ev.type === \"message_start\") emittedStart = true;\n          if (\"index\" in ev) yield { ...ev, index: ev.index + contentOffset } as OracleEvent;\n          else yield ev;\n        }\n        const final = await events.finalMessage();\n        addUsage(usage, mapUsage(final.usage));\n        if (final.stop_reason === \"pause_turn\") {\n          messages = [...messages, { role: \"assistant\", content: final.content }];\n          contentOffset += final.content.length;\n          continue;\n        }\n        yield { type: \"message_delta\", delta: { stopReason: mapStop(final.stop_reason) }, usage };\n        yield { type: \"message_stop\" };\n        return;\n      }\n      yield { type: \"message_delta\", delta: { stopReason: \"pause_turn\" }, usage };\n      yield { type: \"message_stop\" };\n    } catch (err) {\n      yield { type: \"error\", error: normalizeError(err, \"anthropic\", signal).toShape() };\n    }\n  }\n\n  listModels(opts?: { signal?: AbortSignal }) {\n    return listAnthropicModels(this.client, opts);\n  }\n}\n","import type { OracleContentBlock } from \"../shape/index\";\n\n/** Render content blocks to a plain string for providers/fields that only accept\n * text: text blocks pass through, everything else becomes a `[type]` placeholder.\n * Shared by the openai and google request mappers (tool_result fallback). */\nexport function stringifyBlocks(blocks: OracleContentBlock[]): string {\n  return blocks.map((b) => (b.type === \"text\" ? b.text : `[${b.type}]`)).join(\"\");\n}\n","// OpenAI request mapping: canonical shape → Chat Completions params.\nimport type OpenAI from \"openai\";\nimport type { ModelSpec } from \"../../shape/capabilities\";\nimport { nativeEffort, type NativeEffort } from \"../../shape/thinking\";\nimport {\n  CapabilityError,\n  ConfigError,\n  type AudioMediaType,\n  type Effort,\n  type OracleContentBlock,\n  type OracleRequest,\n  type ToolChoice,\n} from \"../../shape/index\";\nimport { stringifyBlocks } from \"../blocks\";\n\ntype ChatMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam;\n\n/** Native ids that refuse function tools while any reasoning is in play on\n *  /v1/chat/completions, and reason by DEFAULT when the parameter is omitted —\n *  so sending nothing is what fails. The gpt-5.6 generation, in its own words:\n *\n *    400 Function tools with reasoning_effort are not supported for\n *    gpt-5.6-terra in /v1/chat/completions. To use function tools, use\n *    /v1/responses or set reasoning_effort to 'none'.\n *\n *  Matched by id because these models arrive from discovery with no catalog\n *  metadata at all — the registry's overlay knows their ids and nothing else,\n *  which is precisely when a tool-using agent goes silently dead. A spec that\n *  DOES declare `thinking.toolsEffort` wins over this list. */\nconst TOOLS_NEED_REASONING_OFF: RegExp[] = [/^gpt-5\\.6(?:[-.]|$)/];\n\n/** The native effort to send for a tool-carrying request, if this model needs\n *  one: the spec's own declaration first, else the known-lineup fallback. */\nexport function toolsEffortFor(spec: ModelSpec): NativeEffort | undefined {\n  if (spec.thinking?.toolsEffort) return spec.thinking.toolsEffort;\n  return TOOLS_NEED_REASONING_OFF.some((pattern) => pattern.test(spec.nativeId))\n    ? { param: \"reasoningEffort\", value: \"none\" }\n    : undefined;\n}\n\nexport function buildParams(spec: ModelSpec, req: OracleRequest, stream: boolean): Record<string, unknown> {\n  const params: Record<string, unknown> = {\n    model: spec.nativeId,\n    messages: toOpenAIMessages(req),\n    max_completion_tokens: req.maxTokens,\n  };\n\n  const tools = buildTools(req);\n  if (tools) params.tools = tools;\n\n  const toolChoice = mapToolChoice(req.toolChoice);\n  if (toolChoice !== undefined) params.tool_choice = toolChoice;\n\n  if (req.stopSequences && req.stopSequences.length > 0) params.stop = req.stopSequences;\n\n  // Reasoning (effort) models reject a custom temperature; only send it elsewhere.\n  if (req.temperature !== undefined && !spec.capabilities.effort) params.temperature = req.temperature;\n\n  // Reasoning models that refuse function tools while reasoning is on: send the\n  // model's declared tools-value rather than leaving it on a default that will\n  // be rejected. The whole point is that omitting the parameter is NOT neutral.\n  const toolsEffort = tools ? toolsEffortFor(spec) : undefined;\n  if (toolsEffort && req.effort) {\n    throw new CapabilityError(\n      `Model \"${spec.id}\" cannot combine function tools with an effort level on chat completions. ` +\n        \"Omit `effort` (the adapter disables reasoning for tool calls) or choose a model that supports both.\",\n    );\n  }\n  if (toolsEffort) {\n    if (toolsEffort.param !== \"reasoningEffort\") {\n      throw new ConfigError(\n        `Model \"${spec.id}\" maps its tools effort to \"${toolsEffort.param}\" — not an OpenAI knob (mis-authored catalog entry).`,\n      );\n    }\n    params.reasoning_effort = toolsEffort.value;\n  }\n  if (req.effort) {\n    const mapped = nativeEffort(spec, req.effort);\n    if (mapped) {\n      if (mapped.param !== \"reasoningEffort\") {\n        throw new ConfigError(\n          `Model \"${spec.id}\" maps effort \"${req.effort}\" to \"${mapped.param}\" — not an OpenAI knob (mis-authored catalog entry).`,\n        );\n      }\n      params.reasoning_effort = mapped.value;\n    } else if (!spec.thinking && spec.capabilities.effort) {\n      params.reasoning_effort = legacyReasoningEffort(req.effort);\n    }\n  }\n\n  if (req.responseFormat && spec.capabilities.structuredOutput) {\n    params.response_format = {\n      type: \"json_schema\",\n      json_schema: { name: req.responseFormat.name ?? \"response\", schema: req.responseFormat.schema },\n    };\n  }\n\n  // Search-capable chat models (e.g. gpt-5-search-api) take web_search_options;\n  // the capability gate keeps this off models without webSearch.\n  if (req.webSearch) {\n    const power = spec.superpowers?.webSearch;\n    const size = power?.type === \"openai-web-search\" ? (power.contextSize ?? \"medium\") : \"medium\";\n    params.web_search_options = { search_context_size: size };\n  }\n\n  if (stream) {\n    params.stream = true;\n    params.stream_options = { include_usage: true };\n  }\n\n  if (req.providerExtras) Object.assign(params, req.providerExtras);\n  return params;\n}\n\n/** Expand canonical messages into OpenAI's flat message list: system folded to a\n *  leading message, tool_result blocks lifted to role:\"tool\" messages, tool_use\n *  blocks emitted as assistant tool_calls. */\nexport function toOpenAIMessages(req: OracleRequest): ChatMessage[] {\n  const out: ChatMessage[] = [];\n\n  if (req.system !== undefined) {\n    const text = typeof req.system === \"string\" ? req.system : req.system.map((b) => b.text).join(\"\");\n    out.push({ role: \"system\", content: text });\n  }\n\n  for (const msg of req.messages) {\n    const blocks = typeof msg.content === \"string\" ? [{ type: \"text\" as const, text: msg.content }] : msg.content;\n\n    if (msg.role === \"assistant\") {\n      const textParts: string[] = [];\n      const toolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];\n      for (const b of blocks) {\n        if (b.type === \"text\") textParts.push(b.text);\n        else if (b.type === \"tool_use\") {\n          toolCalls.push({\n            id: b.id,\n            type: \"function\",\n            function: { name: b.name, arguments: JSON.stringify(b.input) },\n          } as OpenAI.Chat.Completions.ChatCompletionMessageToolCall);\n        }\n        // thinking blocks are dropped — OpenAI has no thinking input channel.\n      }\n      const assistant: Record<string, unknown> = { role: \"assistant\", content: textParts.join(\"\") || null };\n      if (toolCalls.length > 0) assistant.tool_calls = toolCalls;\n      out.push(assistant as unknown as ChatMessage);\n      continue;\n    }\n\n    // user turn: tool_result blocks become tool messages; the rest becomes one\n    // user message with multimodal content parts.\n    const toolResults = blocks.filter((b) => b.type === \"tool_result\");\n    for (const b of toolResults) {\n      if (b.type !== \"tool_result\") continue;\n      out.push({\n        role: \"tool\",\n        tool_call_id: b.toolUseId,\n        content: typeof b.content === \"string\" ? b.content : stringifyBlocks(b.content),\n      });\n    }\n    const rest = blocks.filter((b) => b.type !== \"tool_result\");\n    if (rest.length > 0) out.push({ role: \"user\", content: rest.map(userPart) });\n  }\n\n  return out;\n}\n\ntype UserPart = OpenAI.Chat.Completions.ChatCompletionContentPart;\n\nfunction userPart(b: OracleContentBlock): UserPart {\n  switch (b.type) {\n    case \"text\":\n      return { type: \"text\", text: b.text };\n    case \"image\":\n      return {\n        type: \"image_url\",\n        image_url: {\n          url: b.source.type === \"url\" ? b.source.url : `data:${b.source.mediaType};base64,${b.source.data}`,\n        },\n      };\n    case \"audio\": {\n      if (b.source.type !== \"base64\") {\n        throw new CapabilityError(\"OpenAI audio input requires base64 data, not a URL.\");\n      }\n      return {\n        type: \"input_audio\",\n        input_audio: { data: b.source.data, format: audioFormat(b.source.mediaType) },\n      } as UserPart;\n    }\n    default:\n      // document/tool_* are excluded from OpenAI user content (documents are\n      // gated off by capabilities; tool_result handled separately).\n      return { type: \"text\", text: stringifyBlocks([b]) };\n  }\n}\n\nfunction audioFormat(m: AudioMediaType): \"wav\" | \"mp3\" {\n  if (m === \"audio/wav\") return \"wav\";\n  if (m === \"audio/mp3\" || m === \"audio/mpeg\") return \"mp3\";\n  throw new CapabilityError(`OpenAI audio input supports wav and mp3, not \"${m}\".`);\n}\n\nfunction buildTools(req: OracleRequest): unknown[] | undefined {\n  if (!req.tools || req.tools.length === 0) return undefined;\n  return req.tools.map((t) => ({\n    type: \"function\",\n    function: { name: t.name, description: t.description, parameters: t.inputSchema },\n  }));\n}\n\nfunction mapToolChoice(tc: ToolChoice | undefined): unknown | undefined {\n  if (tc === undefined) return undefined;\n  if (tc === \"auto\") return \"auto\";\n  if (tc === \"none\") return \"none\";\n  if (tc === \"any\") return \"required\";\n  return { type: \"function\", function: { name: tc.name } };\n}\n\n/** Pre-descriptor fallback for custom specs authored before ThinkingSupport:\n *  the historical lossy collapse. Catalog models never hit this — their\n *  per-model effortMap governs, and out-of-ladder levels fail validation. */\nfunction legacyReasoningEffort(e: Effort): \"low\" | \"medium\" | \"high\" {\n  if (e === \"low\") return \"low\";\n  if (e === \"medium\") return \"medium\";\n  return \"high\"; // high / xhigh / max → high\n}\n","// OpenAI Responses request mapping: canonical shape → /v1/responses params.\n//\n// Structurally different from Chat Completions in three ways that matter:\n// the system prompt is `instructions` rather than a leading message; the\n// conversation is a flat `input` item list where tool calls and their results\n// are items in their own right rather than a message plus a role:\"tool\" reply;\n// and reasoning is `reasoning.effort` rather than `reasoning_effort`.\n\nimport type { ModelSpec } from \"../../shape/capabilities\";\nimport { nativeEffort } from \"../../shape/thinking\";\nimport {\n  CapabilityError,\n  ConfigError,\n  type AudioMediaType,\n  type OracleContentBlock,\n  type OracleRequest,\n  type ToolChoice,\n} from \"../../shape/index\";\nimport { stringifyBlocks } from \"../blocks\";\n\n/** Build the `/v1/responses` params for one request. */\nexport function buildResponsesParams(\n  spec: ModelSpec,\n  req: OracleRequest,\n  stream: boolean,\n): Record<string, unknown> {\n  const params: Record<string, unknown> = {\n    model: spec.nativeId,\n    input: toResponsesInput(req),\n    max_output_tokens: req.maxTokens,\n    // odla keeps no server-side conversation state; every turn is sent in full.\n    store: false,\n  };\n\n  if (req.system !== undefined) {\n    params.instructions = typeof req.system === \"string\" ? req.system : req.system.map((b) => b.text).join(\"\");\n  }\n\n  const tools = buildResponsesTools(req);\n  if (tools) {\n    params.tools = tools;\n    // The Code harness can overlap explicitly read-only calls while preserving\n    // output order and treating every effect as an exclusive barrier.\n    params.parallel_tool_calls = true;\n  }\n\n  const toolChoice = mapResponsesToolChoice(req.toolChoice);\n  if (toolChoice !== undefined) params.tool_choice = toolChoice;\n\n  // Unlike Chat Completions, reasoning models here accept temperature alongside\n  // an effort level, so it is passed through rather than dropped.\n  if (req.temperature !== undefined) params.temperature = req.temperature;\n\n  applyReasoning(params, spec, req);\n\n  if (req.responseFormat && spec.capabilities.structuredOutput) {\n    params.text = {\n      format: {\n        type: \"json_schema\",\n        name: req.responseFormat.name ?? \"response\",\n        schema: req.responseFormat.schema,\n      },\n    };\n  }\n\n  if (req.webSearch) params.tools = [...((params.tools as unknown[]) ?? []), { type: \"web_search\" }];\n\n  if (stream) params.stream = true;\n  if (req.providerExtras) Object.assign(params, req.providerExtras);\n  return params;\n}\n\n/** Map the unified effort ladder onto `reasoning.effort`. `thinking: \"off\"`\n *  sends the explicit `\"none\"` this endpoint understands — the whole reason it\n *  can carry tools and reasoning in the same request. */\nfunction applyReasoning(params: Record<string, unknown>, spec: ModelSpec, req: OracleRequest): void {\n  if (req.effort) {\n    const mapped = nativeEffort(spec, req.effort);\n    if (mapped) {\n      if (mapped.param !== \"reasoningEffort\") {\n        throw new ConfigError(\n          `Model \"${spec.id}\" maps effort \"${req.effort}\" to \"${mapped.param}\" — not an OpenAI knob (mis-authored catalog entry).`,\n        );\n      }\n      params.reasoning = { effort: mapped.value };\n      return;\n    }\n    if (!spec.thinking && spec.capabilities.effort) params.reasoning = { effort: req.effort };\n    return;\n  }\n  if (req.thinking === \"off\") params.reasoning = { effort: \"none\" };\n}\n\n/** Flatten the canonical conversation into the Responses `input` item list. */\nexport function toResponsesInput(req: OracleRequest): unknown[] {\n  const out: unknown[] = [];\n\n  for (const msg of req.messages) {\n    const blocks = typeof msg.content === \"string\" ? [{ type: \"text\" as const, text: msg.content }] : msg.content;\n\n    if (msg.role === \"assistant\") {\n      const text: string[] = [];\n      const calls: unknown[] = [];\n      for (const b of blocks) {\n        if (b.type === \"text\") text.push(b.text);\n        else if (b.type === \"tool_use\") {\n          calls.push({ type: \"function_call\", call_id: b.id, name: b.name, arguments: JSON.stringify(b.input) });\n        }\n        // thinking blocks are dropped — there is no reasoning input channel.\n      }\n      // The message precedes the tool calls it accompanies; an assistant turn\n      // that is purely tool calls contributes no message item at all.\n      if (text.join(\"\")) out.push({ role: \"assistant\", content: text.join(\"\") });\n      out.push(...calls);\n      continue;\n    }\n\n    // A user turn: tool results become their own items, everything else becomes\n    // one message with typed content parts.\n    for (const b of blocks) {\n      if (b.type !== \"tool_result\") continue;\n      out.push({\n        type: \"function_call_output\",\n        call_id: b.toolUseId,\n        output: typeof b.content === \"string\" ? b.content : stringifyBlocks(b.content),\n      });\n    }\n    const rest = blocks.filter((b) => b.type !== \"tool_result\");\n    if (rest.length > 0) out.push({ role: \"user\", content: rest.map(inputPart) });\n  }\n\n  return out;\n}\n\nfunction inputPart(b: OracleContentBlock): Record<string, unknown> {\n  switch (b.type) {\n    case \"text\":\n      return { type: \"input_text\", text: b.text };\n    case \"image\":\n      return {\n        type: \"input_image\",\n        detail: \"auto\",\n        image_url: b.source.type === \"url\" ? b.source.url : `data:${b.source.mediaType};base64,${b.source.data}`,\n      };\n    case \"audio\": {\n      if (b.source.type !== \"base64\") {\n        throw new CapabilityError(\"OpenAI audio input requires base64 data, not a URL.\");\n      }\n      return { type: \"input_audio\", input_audio: { data: b.source.data, format: audioFormat(b.source.mediaType) } };\n    }\n    default:\n      return { type: \"input_text\", text: stringifyBlocks([b]) };\n  }\n}\n\nfunction audioFormat(m: AudioMediaType): \"wav\" | \"mp3\" {\n  if (m === \"audio/wav\") return \"wav\";\n  if (m === \"audio/mp3\" || m === \"audio/mpeg\") return \"mp3\";\n  throw new CapabilityError(`OpenAI audio input supports wav and mp3, not \"${m}\".`);\n}\n\n/** Responses tools are flat — no nested `function` envelope. */\nfunction buildResponsesTools(req: OracleRequest): unknown[] | undefined {\n  if (!req.tools || req.tools.length === 0) return undefined;\n  return req.tools.map((t) => ({\n    type: \"function\",\n    name: t.name,\n    description: t.description,\n    parameters: t.inputSchema,\n    strict: false,\n  }));\n}\n\nfunction mapResponsesToolChoice(tc: ToolChoice | undefined): unknown | undefined {\n  if (tc === undefined) return undefined;\n  if (tc === \"auto\") return \"auto\";\n  if (tc === \"none\") return \"none\";\n  if (tc === \"any\") return \"required\";\n  return { type: \"function\", name: tc.name };\n}\n","// Which OpenAI endpoint a model is called on.\n//\n// Chat Completions cannot combine function tools with reasoning on the gpt-5.6\n// generation — the API says so itself:\n//\n//   400 Function tools with reasoning_effort are not supported for\n//   gpt-5.6-terra in /v1/chat/completions. To use function tools, use\n//   /v1/responses or set reasoning_effort to 'none'.\n//\n// The adapter used to take the second branch, disabling reasoning so tools kept\n// working. That is a real capability loss, applied silently, on the strongest\n// models — and for anything comparing models against each other it is worse than\n// an error, because it still returns a plausible answer.\n//\n// This takes the first branch. On `/v1/responses` reasoning and function tools\n// coexist, and the native effort vocabulary is wider (it has `xhigh` and `max`,\n// which Chat Completions lacks), so the unified ladder maps onto it without loss.\n\nimport type { ModelSpec } from \"../../shape/capabilities\";\n\n/** The OpenAI endpoints this adapter can speak. */\nexport type OpenAIApi = \"chat\" | \"responses\";\n\n/** Native ids that must use `/v1/responses` to keep reasoning while calling\n *  function tools. Matched by id because these models arrive from discovery\n *  with no catalog metadata at all — which is exactly when a tool-using agent\n *  would otherwise go quietly non-reasoning. A spec that declares `api` wins. */\nconst NEEDS_RESPONSES: RegExp[] = [/^gpt-5\\.6(?:[-.]|$)/];\n\n/**\n * Decide which endpoint to call `spec` on: the spec's own `api` declaration\n * when it has one, otherwise `\"responses\"` for models that need it to keep\n * reasoning alongside tools, otherwise `\"chat\"`.\n *\n * Defaulting to `\"chat\"` is deliberate. Chat Completions is the path every\n * catalog model is already tested against, so models move to Responses by\n * explicit declaration rather than by a wholesale switch nobody asked for.\n */\nexport function openaiApiFor(spec: ModelSpec): OpenAIApi {\n  if (spec.api) return spec.api;\n  return NEEDS_RESPONSES.some((pattern) => pattern.test(spec.nativeId)) ? \"responses\" : \"chat\";\n}\n","// OpenAI list-models mapping. GET /v1/models returns only bare records\n// ({id, created, owned_by}) — no limits, no capabilities — so discovery from\n// OpenAI is existence-only; metadata comes from curation.\n\nimport type OpenAI from \"openai\";\nimport type { DiscoveredModel } from \"../types\";\nimport { mapProviderError } from \"../errors\";\n\nexport async function listOpenAIModels(\n  client: OpenAI,\n  opts?: { signal?: AbortSignal },\n): Promise<DiscoveredModel[]> {\n  try {\n    const out: DiscoveredModel[] = [];\n    for await (const model of client.models.list({ signal: opts?.signal })) {\n      out.push(mapOpenAIModel(model as unknown as Record<string, unknown>));\n    }\n    return out;\n  } catch (err) {\n    mapProviderError(err, \"openai\", opts?.signal);\n  }\n}\n\n/** Normalize one raw /v1/models entry. Exported for fixture tests. */\nexport function mapOpenAIModel(raw: Record<string, unknown>): DiscoveredModel {\n  return { provider: \"openai\", nativeId: String(raw.id ?? \"\"), raw };\n}\n","// OpenAI response mapping: Chat Completion → canonical response. mapFinish /\n// mapUsage are also consumed by the stream mapper (kept here, not in the entry,\n// so the entry ↔ stream dependency stays one-directional — no import cycle).\nimport type OpenAI from \"openai\";\nimport {\n  type OracleContentBlock,\n  type OracleRequest,\n  type OracleResponse,\n  type OracleStopReason,\n  type OracleUsage,\n  type SearchCitation,\n} from \"../../shape/index\";\nimport { mergeCitations, ToolInputError } from \"../../shape/index\";\nimport { toolInput } from \"../tool-input\";\n\nexport function mapResponse(res: OpenAI.Chat.Completions.ChatCompletion, req: OracleRequest): OracleResponse {\n  const choice = res.choices[0];\n  const content: OracleContentBlock[] = [];\n  const message = choice?.message;\n\n  if (message?.content) content.push({ type: \"text\", text: message.content });\n  for (const call of message?.tool_calls ?? []) {\n    if (call.type !== \"function\") continue;\n    content.push({ type: \"tool_use\", id: call.id, name: call.function.name, input: parseArgs(call.function.arguments) });\n  }\n\n  const citations = mergeCitations(mapCitations(message?.annotations));\n  return {\n    id: res.id,\n    model: req.model,\n    provider: \"openai\",\n    role: \"assistant\",\n    content,\n    stopReason: mapFinish(choice?.finish_reason),\n    usage: mapUsage(res.usage),\n    ...(citations.length ? { citations } : {}),\n  };\n}\n\n/**\n * Read web-search sources out of a message's annotations. OpenAI reports each\n * one as a `url_citation` carrying the offsets into the answer text it supports,\n * so every citation here is claim-attributed rather than merely consulted.\n */\nexport function mapCitations(annotations: unknown): SearchCitation[] {\n  if (!Array.isArray(annotations)) return [];\n  const out: SearchCitation[] = [];\n  for (const a of annotations as Record<string, unknown>[]) {\n    if (a?.type !== \"url_citation\") continue;\n    const c = a.url_citation as Record<string, unknown> | undefined;\n    if (typeof c?.url !== \"string\") continue;\n    out.push({\n      url: c.url,\n      ...(typeof c.title === \"string\" && c.title ? { title: c.title } : {}),\n      ...(typeof c.start_index === \"number\" ? { startIndex: c.start_index } : {}),\n      ...(typeof c.end_index === \"number\" ? { endIndex: c.end_index } : {}),\n    });\n  }\n  return out;\n}\n\n/** OpenAI hands tool arguments back as a JSON *string*; malformed JSON fails\n * closed so a tool handler never receives invented empty arguments. */\nexport function parseArgs(raw: string | undefined): Record<string, unknown> {\n  if (!raw) return {};\n  try {\n    const parsed = JSON.parse(raw);\n    return toolInput(parsed, \"openai\", \"function\");\n  } catch (error) {\n    if (error instanceof ToolInputError) throw error;\n    throw new ToolInputError(\"[openai] tool returned malformed JSON arguments.\", { cause: error });\n  }\n}\n\nexport function mapFinish(reason: string | null | undefined): OracleStopReason {\n  switch (reason) {\n    case \"stop\":\n      return \"end_turn\";\n    case \"length\":\n      return \"max_tokens\";\n    case \"tool_calls\":\n    case \"function_call\":\n      return \"tool_use\";\n    case \"content_filter\":\n      return \"refusal\";\n    default:\n      return \"end_turn\";\n  }\n}\n\nexport function mapUsage(u: OpenAI.Completions.CompletionUsage | undefined): OracleUsage {\n  const usage: OracleUsage = { inputTokens: u?.prompt_tokens ?? 0, outputTokens: u?.completion_tokens ?? 0 };\n  const cached = u?.prompt_tokens_details?.cached_tokens;\n  if (cached != null) usage.cacheReadTokens = cached;\n  return usage;\n}\n","// OpenAI Responses response mapping: /v1/responses Response → canonical shape.\n//\n// The payload is a flat `output` item list rather than one message with side\n// channels, so text, tool calls, and reasoning summaries all arrive as siblings\n// and are mapped in the order the model emitted them.\n\nimport {\n  mergeCitations,\n  type OracleContentBlock,\n  type OracleRequest,\n  type OracleResponse,\n  type OracleStopReason,\n  type OracleUsage,\n  type SearchCitation,\n} from \"../../shape/index\";\nimport { parseArgs } from \"./response\";\n\ninterface OutputItem {\n  type?: string;\n  id?: string;\n  call_id?: string;\n  name?: string;\n  arguments?: string;\n  content?: unknown;\n  summary?: unknown;\n}\n\n/** Map a `/v1/responses` payload onto the canonical response. */\nexport function mapResponsesResponse(res: Record<string, unknown>, req: OracleRequest): OracleResponse {\n  const items = Array.isArray(res.output) ? (res.output as OutputItem[]) : [];\n  const content: OracleContentBlock[] = [];\n  const cites: SearchCitation[] = [];\n  let sawToolCall = false;\n  let refused = false;\n\n  for (const item of items) {\n    if (item.type === \"message\") {\n      for (const part of asArray(item.content)) {\n        const p = part as Record<string, unknown>;\n        if (p.type === \"output_text\" && typeof p.text === \"string\") {\n          content.push({ type: \"text\", text: p.text });\n          cites.push(...mapResponsesCitations(p.annotations));\n        } else if (p.type === \"refusal\") {\n          refused = true;\n          if (typeof p.refusal === \"string\") content.push({ type: \"text\", text: p.refusal });\n        }\n      }\n    } else if (item.type === \"function_call\") {\n      sawToolCall = true;\n      content.push({\n        type: \"tool_use\",\n        // `call_id` is the correlation key the API expects back on the result;\n        // `id` identifies the output item itself and is not interchangeable.\n        id: String(item.call_id ?? item.id ?? \"\"),\n        name: String(item.name ?? \"\"),\n        input: parseArgs(item.arguments),\n      });\n    } else if (item.type === \"reasoning\") {\n      const summary = asArray(item.summary)\n        .map((s) => (s as Record<string, unknown>)?.text)\n        .filter((t): t is string => typeof t === \"string\")\n        .join(\"\\n\");\n      if (summary) content.push({ type: \"thinking\", thinking: summary });\n    }\n  }\n\n  const citations = mergeCitations(cites);\n  return {\n    id: String(res.id ?? \"\"),\n    model: req.model,\n    provider: \"openai\",\n    role: \"assistant\",\n    content,\n    stopReason: mapResponsesStop(res, sawToolCall, refused),\n    usage: mapResponsesUsage(res.usage as Record<string, unknown> | undefined),\n    ...(citations.length ? { citations } : {}),\n  };\n}\n\n/** Sources attributed to the answer text, from `output_text` annotations. */\nexport function mapResponsesCitations(annotations: unknown): SearchCitation[] {\n  const out: SearchCitation[] = [];\n  for (const a of asArray(annotations)) {\n    const ann = a as Record<string, unknown>;\n    if (ann?.type !== \"url_citation\" || typeof ann.url !== \"string\") continue;\n    out.push({\n      url: ann.url,\n      ...(typeof ann.title === \"string\" && ann.title ? { title: ann.title } : {}),\n      ...(typeof ann.start_index === \"number\" ? { startIndex: ann.start_index } : {}),\n      ...(typeof ann.end_index === \"number\" ? { endIndex: ann.end_index } : {}),\n    });\n  }\n  return out;\n}\n\n/** Derive the canonical stop reason. A tool call outranks a plain completion,\n *  because the loop must keep going; truncation is reported by\n *  `incomplete_details.reason` rather than a finish string. */\nexport function mapResponsesStop(\n  res: Record<string, unknown>,\n  sawToolCall: boolean,\n  refused: boolean,\n): OracleStopReason {\n  if (refused) return \"refusal\";\n  const incomplete = res.incomplete_details as { reason?: string } | null | undefined;\n  if (incomplete?.reason === \"max_output_tokens\") return \"max_tokens\";\n  if (incomplete?.reason === \"content_filter\") return \"refusal\";\n  if (sawToolCall) return \"tool_use\";\n  if (res.status === \"failed\" || res.error) return \"error\";\n  if (res.status === \"incomplete\") return \"max_tokens\";\n  return \"end_turn\";\n}\n\n/** Responses reports token counts under different names than Chat Completions,\n *  and bills reasoning tokens inside `output_tokens`. */\nexport function mapResponsesUsage(u: Record<string, unknown> | undefined): OracleUsage {\n  const usage: OracleUsage = {\n    inputTokens: numberOr(u?.input_tokens, 0),\n    outputTokens: numberOr(u?.output_tokens, 0),\n  };\n  const cached = (u?.input_tokens_details as Record<string, unknown> | undefined)?.cached_tokens;\n  if (typeof cached === \"number\") usage.cacheReadTokens = cached;\n  return usage;\n}\n\nfunction asArray(v: unknown): unknown[] {\n  return Array.isArray(v) ? v : [];\n}\n\nfunction numberOr(v: unknown, fallback: number): number {\n  return typeof v === \"number\" ? v : fallback;\n}\n","// OpenAI stream mapping onto the canonical event vocabulary.\nimport type OpenAI from \"openai\";\nimport { addUsage, emptyUsage, type OracleEvent, type OracleRequest, type OracleStopReason } from \"../../shape/index\";\nimport { mapFinish, mapUsage } from \"./response\";\n\n/** Map an OpenAI chat stream onto the canonical event vocabulary. OpenAI has no\n *  explicit block start/stop, so we synthesize them: a text channel (index 0) and\n *  one channel per tool_call index, opened lazily and closed at finish. */\nexport async function* mapStream(\n  stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>,\n  req: OracleRequest,\n): AsyncIterable<OracleEvent> {\n  let started = false;\n  let textOpen = false;\n  const toolIndex = new Map<number, number>(); // openai tool_call index → our block index\n  let nextBlockIndex = 1; // 0 reserved for text\n  let stopReason: OracleStopReason = \"end_turn\";\n  const usage = emptyUsage();\n\n  for await (const chunk of stream) {\n    if (!started) {\n      started = true;\n      yield {\n        type: \"message_start\",\n        message: { id: chunk.id, model: req.model, provider: \"openai\", role: \"assistant\", content: [], usage: emptyUsage() },\n      };\n    }\n\n    if (chunk.usage) addUsage(usage, mapUsage(chunk.usage));\n\n    const choice = chunk.choices[0];\n    const delta = choice?.delta;\n\n    if (delta?.content) {\n      if (!textOpen) {\n        textOpen = true;\n        yield { type: \"content_block_start\", index: 0, contentBlock: { type: \"text\", text: \"\" } };\n      }\n      yield { type: \"content_block_delta\", index: 0, delta: { type: \"text_delta\", text: delta.content } };\n    }\n\n    for (const tc of delta?.tool_calls ?? []) {\n      let blockIndex = toolIndex.get(tc.index);\n      if (blockIndex === undefined) {\n        blockIndex = nextBlockIndex++;\n        toolIndex.set(tc.index, blockIndex);\n        yield {\n          type: \"content_block_start\",\n          index: blockIndex,\n          contentBlock: { type: \"tool_use\", id: tc.id ?? \"\", name: tc.function?.name ?? \"\", input: {} },\n        };\n      }\n      if (tc.function?.arguments) {\n        yield { type: \"content_block_delta\", index: blockIndex, delta: { type: \"input_json_delta\", partialJson: tc.function.arguments } };\n      }\n    }\n\n    if (choice?.finish_reason) stopReason = mapFinish(choice.finish_reason);\n  }\n\n  if (textOpen) yield { type: \"content_block_stop\", index: 0 };\n  for (const blockIndex of toolIndex.values()) yield { type: \"content_block_stop\", index: blockIndex };\n  yield { type: \"message_delta\", delta: { stopReason }, usage };\n  yield { type: \"message_stop\" };\n}\n","// OpenAI Responses stream mapping: semantic response.* events → canonical events.\n//\n// Easier to map than the Chat Completions delta stream: output items are opened\n// and closed explicitly, so block indices come from the API instead of being\n// reconstructed from the shape of successive deltas.\n\nimport { emptyUsage, type OracleEvent, type OracleRequest } from \"../../shape/index\";\nimport { mapResponsesUsage } from \"./responses-response\";\n\ninterface StreamEvent {\n  type?: string;\n  output_index?: number;\n  delta?: string;\n  item?: { type?: string; id?: string; call_id?: string; name?: string };\n  response?: Record<string, unknown>;\n}\n\n/** Translate the `/v1/responses` event stream into canonical events. */\nexport async function* mapResponsesStream(\n  stream: AsyncIterable<unknown>,\n  req: OracleRequest,\n): AsyncIterable<OracleEvent> {\n  let started = false;\n  // Output indices we actually opened a canonical block for. Reasoning items\n  // get their own added/done pair and map to no block, so closing on every\n  // `done` would emit a stop for a block that was never started — which is\n  // what a live gpt-5.6 stream does on its very first item.\n  const open = new Set<number>();\n\n  for await (const raw of stream) {\n    const ev = raw as StreamEvent;\n    const index = ev.output_index ?? 0;\n\n    switch (ev.type) {\n      case \"response.created\": {\n        if (started) break;\n        started = true;\n        yield {\n          type: \"message_start\",\n          message: {\n            id: String(ev.response?.id ?? \"\"),\n            model: req.model,\n            provider: \"openai\",\n            role: \"assistant\",\n            content: [],\n            usage: emptyUsage(),\n          },\n        };\n        break;\n      }\n\n      case \"response.output_item.added\": {\n        if (ev.item?.type === \"function_call\") {\n          open.add(index);\n          yield {\n            type: \"content_block_start\",\n            index,\n            contentBlock: {\n              type: \"tool_use\",\n              id: String(ev.item.call_id ?? ev.item.id ?? \"\"),\n              name: String(ev.item.name ?? \"\"),\n              input: {},\n            },\n          };\n        } else if (ev.item?.type === \"message\") {\n          open.add(index);\n          yield { type: \"content_block_start\", index, contentBlock: { type: \"text\", text: \"\" } };\n        }\n        break;\n      }\n\n      case \"response.output_text.delta\": {\n        if (typeof ev.delta === \"string\") {\n          yield { type: \"content_block_delta\", index, delta: { type: \"text_delta\", text: ev.delta } };\n        }\n        break;\n      }\n\n      case \"response.function_call_arguments.delta\": {\n        if (typeof ev.delta === \"string\") {\n          yield { type: \"content_block_delta\", index, delta: { type: \"input_json_delta\", partialJson: ev.delta } };\n        }\n        break;\n      }\n\n      case \"response.output_item.done\": {\n        if (!open.delete(index)) break; // never opened (e.g. a reasoning item)\n        yield { type: \"content_block_stop\", index };\n        break;\n      }\n\n      case \"response.completed\":\n      case \"response.incomplete\": {\n        const res = ev.response ?? {};\n        const items = Array.isArray(res.output) ? (res.output as { type?: string }[]) : [];\n        const sawToolCall = items.some((i) => i.type === \"function_call\");\n        const incomplete = res.incomplete_details as { reason?: string } | null | undefined;\n        yield {\n          type: \"message_delta\",\n          delta: {\n            stopReason: incomplete?.reason === \"max_output_tokens\" ? \"max_tokens\" : sawToolCall ? \"tool_use\" : \"end_turn\",\n          },\n          usage: mapResponsesUsage(res.usage as Record<string, unknown> | undefined),\n        };\n        yield { type: \"message_stop\" };\n        break;\n      }\n\n      case \"response.failed\": {\n        const err = (ev.response?.error ?? {}) as { message?: string };\n        yield {\n          type: \"error\",\n          error: { code: \"provider_error\", message: err.message ?? \"OpenAI response failed.\" },\n        };\n        break;\n      }\n    }\n  }\n}\n","// OpenAI adapter, speaking either Chat Completions or /v1/responses depending on\n// the model (see ./openai/api). The interesting translations — system folded\n// into a leading message or `instructions`, JSON-string tool `arguments` parsed\n// to an object, and tool results re-emitted as role:\"tool\" messages or\n// `function_call_output` items — happen in ./openai/request and\n// ./openai/responses-request so the rest of odla-ai only ever sees the\n// canonical shape.\n\nimport OpenAI from \"openai\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport type { Provider } from \"./types\";\nimport { normalizeError, mapProviderError } from \"./errors\";\nimport type { OracleEvent, OracleRequest, OracleResponse } from \"../shape/index\";\nimport { echoFromOpenAI, echoFromOpenAIResponses } from \"./echo\";\nimport { buildParams, toOpenAIMessages } from \"./openai/request\";\nimport { buildResponsesParams } from \"./openai/responses-request\";\nimport { openaiApiFor } from \"./openai/api\";\nimport { listOpenAIModels } from \"./openai/models\";\nimport { mapResponse, parseArgs } from \"./openai/response\";\nimport { mapResponsesResponse } from \"./openai/responses-response\";\nimport { mapStream } from \"./openai/stream\";\nimport { mapResponsesStream } from \"./openai/responses-stream\";\nimport { signalWithDeadline } from \"../client/abort\";\n\ntype ChatParams = OpenAI.Chat.Completions.ChatCompletionCreateParams;\n\nexport class OpenAIProvider implements Provider {\n  readonly id = \"openai\" as const;\n  private client: OpenAI;\n\n  constructor(apiKey: string, client?: OpenAI) {\n    this.client = client ?? new OpenAI({ apiKey });\n  }\n\n  async create(spec: ModelSpec, req: OracleRequest): Promise<OracleResponse> {\n    const signal = signalWithDeadline(req.signal, req.deadline);\n    try {\n      if (openaiApiFor(spec) === \"responses\") {\n        const params = buildResponsesParams(spec, req, false);\n        const res = (await this.client.responses.create(params as never, { signal })) as unknown as Record<\n          string,\n          unknown\n        >;\n        return { ...mapResponsesResponse(res, req), echo: echoFromOpenAIResponses(spec, params) };\n      }\n      const params = buildParams(spec, req, false);\n      const res = (await this.client.chat.completions.create(\n        params as unknown as ChatParams,\n        { signal },\n      )) as OpenAI.Chat.Completions.ChatCompletion;\n      return { ...mapResponse(res, req), echo: echoFromOpenAI(spec, params) };\n    } catch (err) {\n      mapProviderError(err, \"openai\", signal);\n    }\n  }\n\n  async *stream(spec: ModelSpec, req: OracleRequest): AsyncIterable<OracleEvent> {\n    const signal = signalWithDeadline(req.signal, req.deadline);\n    try {\n      if (openaiApiFor(spec) === \"responses\") {\n        const events = (await this.client.responses.create(\n          buildResponsesParams(spec, req, true) as never,\n          { signal },\n        )) as unknown as AsyncIterable<unknown>;\n        yield* mapResponsesStream(events, req);\n        return;\n      }\n      const stream = (await this.client.chat.completions.create(\n        buildParams(spec, req, true) as unknown as ChatParams,\n        { signal },\n      )) as unknown as AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>;\n      yield* mapStream(stream, req);\n    } catch (err) {\n      yield { type: \"error\", error: normalizeError(err, \"openai\", signal).toShape() };\n    }\n  }\n\n  listModels(opts?: { signal?: AbortSignal }) {\n    return listOpenAIModels(this.client, opts);\n  }\n}\n\n// Re-exported for the test suite (test/adapters.test.ts) and callers that pinned\n// these helpers when they lived in this file.\nexport { toOpenAIMessages, mapResponse, parseArgs };\n","// Google (Gemini) request mapping: canonical shape → generateContent params.\nimport { FunctionCallingConfigMode } from \"@google/genai\";\nimport type { Content, GenerateContentParameters, Part } from \"@google/genai\";\nimport type { ModelSpec } from \"../../shape/capabilities\";\nimport { nativeEffort } from \"../../shape/thinking\";\nimport {\n  CapabilityError,\n  ConfigError,\n  type OracleContentBlock,\n  type OracleRequest,\n  type ToolChoice,\n} from \"../../shape/index\";\nimport { stringifyBlocks } from \"../blocks\";\n\nexport function buildParams(spec: ModelSpec, req: OracleRequest): GenerateContentParameters {\n  const config: Record<string, unknown> = { maxOutputTokens: req.maxTokens };\n\n  if (req.system !== undefined) {\n    config.systemInstruction = typeof req.system === \"string\" ? req.system : req.system.map((b) => b.text).join(\"\");\n  }\n  if (req.temperature !== undefined) config.temperature = req.temperature;\n  if (req.stopSequences && req.stopSequences.length > 0) config.stopSequences = req.stopSequences;\n\n  const tools = buildTools(req);\n  if (tools) config.tools = tools;\n\n  const toolConfig = mapToolChoice(req.toolChoice);\n  if (toolConfig) config.toolConfig = toolConfig;\n\n  // Effort (when mapped for this model) is the concrete knob and wins; a bare\n  // thinking:\"adaptive\" keeps the dynamic budget; thinking:\"off\" disables\n  // thinking on models that run it by default (budget 0 = off).\n  const mapped = req.effort ? nativeEffort(spec, req.effort) : undefined;\n  if (mapped) {\n    if (mapped.param === \"thinkingBudget\") config.thinkingConfig = { thinkingBudget: mapped.value };\n    else if (mapped.param === \"thinkingLevel\") config.thinkingConfig = { thinkingLevel: mapped.value };\n    else {\n      throw new ConfigError(\n        `Model \"${spec.id}\" maps effort \"${req.effort}\" to \"${mapped.param}\" — not a Gemini knob (mis-authored catalog entry).`,\n      );\n    }\n  } else if (req.thinking === \"adaptive\" && thinkingOn(spec)) {\n    config.thinkingConfig = { thinkingBudget: -1 }; // -1 = dynamic (\"let the model decide\")\n  } else if (req.thinking === \"off\" && spec.thinking?.control === \"on-by-default\") {\n    config.thinkingConfig = { thinkingBudget: 0 }; // 0 = disabled\n  }\n\n  if (req.responseFormat && spec.capabilities.structuredOutput) {\n    config.responseMimeType = \"application/json\";\n    config.responseSchema = req.responseFormat.schema;\n  }\n\n  if (req.providerExtras) Object.assign(config, req.providerExtras);\n\n  return { model: spec.nativeId, contents: toContents(req), config } as unknown as GenerateContentParameters;\n}\n\nexport function toContents(req: OracleRequest): Content[] {\n  // Gemini correlates a functionResponse by function NAME, and the canonical\n  // tool_result carries only the call's id. The two coincide when Gemini issued\n  // no id, and differ when it did, so the name is looked up from the call.\n  const names = new Map<string, string>();\n  for (const m of req.messages) {\n    if (typeof m.content === \"string\") continue;\n    for (const b of m.content) if (b.type === \"tool_use\") names.set(b.id, b.name);\n  }\n  return req.messages.map((m) => ({\n    role: m.role === \"assistant\" ? \"model\" : \"user\",\n    parts: (typeof m.content === \"string\" ? [{ type: \"text\" as const, text: m.content }] : m.content)\n      .map((b) => toPart(b, names))\n      .filter((part): part is Part => part !== null),\n  }));\n}\n\nconst signed = (b: { thoughtSignature?: string }): { thoughtSignature?: string } =>\n  b.thoughtSignature ? { thoughtSignature: b.thoughtSignature } : {};\n\nfunction toPart(b: OracleContentBlock, names: ReadonlyMap<string, string>): Part | null {\n  switch (b.type) {\n    case \"text\":\n      return { text: b.text, ...signed(b) };\n    case \"image\":\n      if (b.source.type !== \"base64\") throw new CapabilityError(\"Google image input requires base64 data, not a URL.\");\n      return { inlineData: { mimeType: b.source.mediaType, data: b.source.data } };\n    case \"audio\":\n      if (b.source.type !== \"base64\") throw new CapabilityError(\"Google audio input requires base64 data, not a URL.\");\n      return { inlineData: { mimeType: b.source.mediaType, data: b.source.data } };\n    case \"document\":\n      if (b.source.type !== \"base64\") throw new CapabilityError(\"Google document input requires base64 data, not a URL.\");\n      return { inlineData: { mimeType: \"application/pdf\", data: b.source.data } };\n    case \"tool_use\":\n      // A Gemini 3 function call is echoed back with the signature it was\n      // issued with; a call replayed without one is rejected with HTTP 400,\n      // which is how a session died on its first tool result.\n      return {\n        functionCall: { name: b.name, args: b.input, ...(b.id !== b.name ? { id: b.id } : {}) },\n        ...signed(b),\n      };\n    case \"tool_result\": {\n      const name = names.get(b.toolUseId) ?? b.toolUseId;\n      return {\n        functionResponse: {\n          name,\n          ...(b.toolUseId !== name ? { id: b.toolUseId } : {}),\n          response: { result: typeof b.content === \"string\" ? b.content : stringifyBlocks(b.content) },\n        },\n      };\n    }\n    case \"thinking\":\n      // No thinking input channel, and an empty text part is an invalid part\n      // rather than a harmless one: the block is dropped, not blanked.\n      return null;\n  }\n}\n\nfunction thinkingOn(spec: ModelSpec): boolean {\n  return spec.thinking ? spec.thinking.control !== \"none\" : spec.capabilities.thinking;\n}\n\nfunction buildTools(req: OracleRequest): unknown[] | undefined {\n  const tools: unknown[] = [];\n  if (req.tools && req.tools.length > 0) {\n    tools.push({\n      functionDeclarations: req.tools.map((t) => ({\n        name: t.name,\n        description: t.description,\n        // `parametersJsonSchema`, NOT `parameters`. They are mutually exclusive\n        // and they take different things: `parameters` is Gemini's own OpenAPI\n        // 3.0 `Schema`, whose field list has no `additionalProperties` and whose\n        // `type` is the uppercase `Type` enum, while `parametersJsonSchema`\n        // takes ordinary JSON Schema — the SDK's own MCP bridge maps a tool's\n        // `inputSchema` to exactly this field.\n        //\n        // A tool schema is JSON Schema, so assigning it to `parameters` sent\n        // Gemini a payload with an unknown field in it and the request failed\n        // with HTTP 400 before the model saw anything. Anthropic and OpenAI\n        // accept the same schema, so this failed on one provider only: every\n        // odla Code tool declares `additionalProperties: false`, which meant a\n        // Code session routed to a Gemini model could not make a single call.\n        parametersJsonSchema: t.inputSchema,\n      })),\n    });\n  }\n  if (req.webSearch) tools.push({ googleSearch: {} });\n  return tools.length > 0 ? tools : undefined;\n}\n\nfunction mapToolChoice(tc: ToolChoice | undefined): unknown | undefined {\n  if (tc === undefined || tc === \"auto\") return undefined;\n  if (tc === \"none\") return { functionCallingConfig: { mode: FunctionCallingConfigMode.NONE } };\n  if (tc === \"any\") return { functionCallingConfig: { mode: FunctionCallingConfigMode.ANY } };\n  return { functionCallingConfig: { mode: FunctionCallingConfigMode.ANY, allowedFunctionNames: [tc.name] } };\n}\n","// Google (Gemini) list-models mapping. models.list returns resource names with\n// a \"models/\" prefix (stripped here), display names, token limits, supported\n// actions (e.g. \"generateContent\"), and a thinking flag on current SDKs.\n\nimport type { GoogleGenAI } from \"@google/genai\";\nimport type { DiscoveredModel, DiscoveryHints } from \"../types\";\nimport { mapProviderError } from \"../errors\";\n\nexport async function listGoogleModels(\n  client: GoogleGenAI,\n  opts?: { signal?: AbortSignal },\n): Promise<DiscoveredModel[]> {\n  try {\n    const out: DiscoveredModel[] = [];\n    const pager = await client.models.list({ config: { abortSignal: opts?.signal } });\n    for await (const model of pager) {\n      out.push(mapGoogleModel(model as unknown as Record<string, unknown>));\n    }\n    return out;\n  } catch (err) {\n    mapProviderError(err, \"google\", opts?.signal);\n  }\n}\n\n/** Normalize one raw models.list entry. Exported for fixture tests. */\nexport function mapGoogleModel(raw: Record<string, unknown>): DiscoveredModel {\n  const name = String(raw.name ?? \"\");\n  const model: DiscoveredModel = {\n    provider: \"google\",\n    nativeId: name.startsWith(\"models/\") ? name.slice(\"models/\".length) : name,\n    raw,\n  };\n  if (typeof raw.displayName === \"string\") model.displayName = raw.displayName;\n  if (typeof raw.inputTokenLimit === \"number\") model.contextWindow = raw.inputTokenLimit;\n  if (typeof raw.outputTokenLimit === \"number\") model.maxOutput = raw.outputTokenLimit;\n\n  const hints: DiscoveryHints = {};\n  if (typeof raw.thinking === \"boolean\") hints.thinking = raw.thinking;\n  const actions = raw.supportedActions ?? raw.supportedGenerationMethods;\n  if (Array.isArray(actions)) {\n    const methods = actions.filter((a): a is string => typeof a === \"string\");\n    if (methods.length > 0) hints.generationMethods = methods;\n  }\n  if (Object.keys(hints).length > 0) model.hints = hints;\n  return model;\n}\n","// Google (Gemini) response mapping. mapFinish / mapUsage are also used by the\n// stream mapper (kept here so the entry ↔ stream edge stays one-directional).\nimport type { GenerateContentResponse } from \"@google/genai\";\nimport type {\n  ImageBlock,\n  ImageMediaType,\n  OracleContentBlock,\n  OracleRequest,\n  OracleResponse,\n  OracleStopReason,\n  OracleUsage,\n  SearchCitation,\n} from \"../../shape/index\";\nimport { mergeCitations } from \"../../shape/index\";\nimport { toolInput } from \"../tool-input\";\n\nexport function mapResponse(res: GenerateContentResponse, req: OracleRequest): OracleResponse {\n  const candidate = res.candidates?.[0];\n  const parts = candidate?.content?.parts ?? [];\n  const content: OracleContentBlock[] = [];\n  let sawToolUse = false;\n\n  for (const p of parts) {\n    // A Gemini 3 model signs the part its reasoning produced; the signature\n    // has to travel with the block so the next request can hand it back.\n    const signed = signatureOf(p);\n    if (p.text) content.push({ type: \"text\", text: p.text, ...signed });\n    else if (p.inlineData) {\n      const image = imageBlockFromGooglePart(p);\n      if (image) content.push(image);\n    } else if (p.functionCall) {\n      sawToolUse = true;\n      const name = p.functionCall.name ?? \"\";\n      content.push({\n        type: \"tool_use\", id: p.functionCall.id ?? name, name,\n        input: toolInput(p.functionCall.args ?? {}, \"google\", name), ...signed,\n      });\n    }\n  }\n\n  const citations = mergeCitations(mapCitations(candidate?.groundingMetadata));\n  return {\n    id: res.responseId ?? \"\",\n    model: req.model,\n    provider: \"google\",\n    role: \"assistant\",\n    content,\n    stopReason: sawToolUse ? \"tool_use\" : mapFinish(candidate?.finishReason),\n    usage: mapUsage(res),\n    ...(citations.length ? { citations } : {}),\n  };\n}\n\n/** The thought signature on a part, as the optional block field, or nothing. */\nexport function signatureOf(part: unknown): { thoughtSignature?: string } {\n  const signature = (part as { thoughtSignature?: unknown } | null)?.thoughtSignature;\n  return typeof signature === \"string\" && signature.length > 0 ? { thoughtSignature: signature } : {};\n}\n\nconst IMAGE_MEDIA_TYPES = new Set<ImageMediaType>([\n  \"image/jpeg\",\n  \"image/png\",\n  \"image/gif\",\n  \"image/webp\",\n]);\n\n/** Preserve a Gemini inline image response without accepting arbitrary MIME\n * data into the canonical ImageBlock shape. Non-image and malformed parts are\n * ignored by the caller, matching the adapter's treatment of unknown parts. */\nexport function imageBlockFromGooglePart(part: unknown): ImageBlock | undefined {\n  if (!part || typeof part !== \"object\") return undefined;\n  const inlineData = (part as { inlineData?: unknown }).inlineData;\n  if (!inlineData || typeof inlineData !== \"object\") return undefined;\n  const { mimeType, data } = inlineData as { mimeType?: unknown; data?: unknown };\n  if (typeof mimeType !== \"string\" || !IMAGE_MEDIA_TYPES.has(mimeType as ImageMediaType)) return undefined;\n  if (typeof data !== \"string\" || data.length === 0) return undefined;\n  return {\n    type: \"image\",\n    source: { type: \"base64\", mediaType: mimeType as ImageMediaType, data },\n  };\n}\n\n/**\n * Read grounding sources out of a candidate's `groundingMetadata`. Gemini splits\n * them in two: `groundingChunks` is the source list, and `groundingSupports`\n * ties an answer-text span to the chunks backing it. Supported spans become\n * attributed citations; chunks no support references stay consulted-only.\n *\n * Chunk URIs are Vertex `grounding-api-redirect` links, not publisher URLs —\n * see {@link SearchCitation.url}.\n */\nexport function mapCitations(metadata: unknown): SearchCitation[] {\n  const meta = metadata as Record<string, unknown> | undefined;\n  const chunks = Array.isArray(meta?.groundingChunks) ? (meta.groundingChunks as Record<string, unknown>[]) : [];\n  const sources = chunks.map((c) => {\n    const web = c?.web as Record<string, unknown> | undefined;\n    if (typeof web?.uri !== \"string\") return null;\n    return { url: web.uri, ...(typeof web.title === \"string\" && web.title ? { title: web.title } : {}) } as SearchCitation;\n  });\n\n  const out: SearchCitation[] = [];\n  const supports = Array.isArray(meta?.groundingSupports) ? (meta.groundingSupports as Record<string, unknown>[]) : [];\n  for (const s of supports) {\n    const segment = s?.segment as Record<string, unknown> | undefined;\n    const indices = Array.isArray(s?.groundingChunkIndices) ? (s.groundingChunkIndices as unknown[]) : [];\n    for (const i of indices) {\n      const source = typeof i === \"number\" ? sources[i] : null;\n      if (!source) continue;\n      out.push({\n        ...source,\n        ...(typeof segment?.startIndex === \"number\" ? { startIndex: segment.startIndex } : {}),\n        ...(typeof segment?.endIndex === \"number\" ? { endIndex: segment.endIndex } : {}),\n        ...(typeof segment?.text === \"string\" && segment.text ? { citedText: segment.text } : {}),\n      });\n    }\n  }\n  for (const source of sources) if (source) out.push(source);\n  return out;\n}\n\nexport function mapFinish(reason: string | null | undefined): OracleStopReason {\n  switch (reason) {\n    case \"STOP\":\n      return \"end_turn\";\n    case \"MAX_TOKENS\":\n      return \"max_tokens\";\n    case \"SAFETY\":\n    case \"RECITATION\":\n    case \"BLOCKLIST\":\n    case \"PROHIBITED_CONTENT\":\n    case \"SPII\":\n      return \"refusal\";\n    default:\n      return \"end_turn\";\n  }\n}\n\nexport function mapUsage(res: GenerateContentResponse): OracleUsage {\n  const u = res.usageMetadata;\n  const usage: OracleUsage = {\n    inputTokens: u?.promptTokenCount ?? 0,\n    outputTokens: u?.candidatesTokenCount ?? 0,\n  };\n  if (u?.cachedContentTokenCount != null) usage.cacheReadTokens = u.cachedContentTokenCount;\n  return usage;\n}\n","// Google (Gemini) stream mapping onto the canonical event vocabulary.\nimport type { GenerateContentResponse } from \"@google/genai\";\nimport { emptyUsage, type OracleEvent, type OracleRequest, type OracleStopReason } from \"../../shape/index\";\nimport { imageBlockFromGooglePart, mapFinish, mapUsage, signatureOf } from \"./response\";\n\nexport async function* mapStream(iter: AsyncIterable<GenerateContentResponse>, req: OracleRequest): AsyncIterable<OracleEvent> {\n  let started = false;\n  let textOpen = false;\n  let nextBlockIndex = 1;\n  let stopReason: OracleStopReason = \"end_turn\";\n  const usage = emptyUsage();\n\n  for await (const chunk of iter) {\n    if (!started) {\n      started = true;\n      yield {\n        type: \"message_start\",\n        message: { id: chunk.responseId ?? \"\", model: req.model, provider: \"google\", role: \"assistant\", content: [], usage: emptyUsage() },\n      };\n    }\n\n    const candidate = chunk.candidates?.[0];\n    for (const p of candidate?.content?.parts ?? []) {\n      if (p.text) {\n        if (!textOpen) {\n          textOpen = true;\n          yield { type: \"content_block_start\", index: 0, contentBlock: { type: \"text\", text: \"\", ...signatureOf(p) } };\n        }\n        yield { type: \"content_block_delta\", index: 0, delta: { type: \"text_delta\", text: p.text } };\n      } else if (p.inlineData) {\n        const image = imageBlockFromGooglePart(p);\n        if (!image) continue;\n        const idx = nextBlockIndex++;\n        yield { type: \"content_block_start\", index: idx, contentBlock: image };\n        yield { type: \"content_block_stop\", index: idx };\n      } else if (p.functionCall) {\n        const idx = nextBlockIndex++;\n        const name = p.functionCall.name ?? \"\";\n        yield { type: \"content_block_start\", index: idx, contentBlock: {\n          type: \"tool_use\", id: p.functionCall.id ?? name, name, input: {}, ...signatureOf(p),\n        } };\n        yield { type: \"content_block_delta\", index: idx, delta: { type: \"input_json_delta\", partialJson: JSON.stringify(p.functionCall.args ?? {}) } };\n        yield { type: \"content_block_stop\", index: idx };\n        stopReason = \"tool_use\";\n      }\n    }\n\n    if (chunk.usageMetadata) {\n      const u = mapUsage(chunk);\n      usage.inputTokens = u.inputTokens; // Gemini reports cumulative counts\n      usage.outputTokens = u.outputTokens;\n      if (u.cacheReadTokens != null) usage.cacheReadTokens = u.cacheReadTokens;\n    }\n    if (candidate?.finishReason && stopReason !== \"tool_use\") stopReason = mapFinish(candidate.finishReason);\n  }\n\n  if (textOpen) yield { type: \"content_block_stop\", index: 0 };\n  yield { type: \"message_delta\", delta: { stopReason }, usage };\n  yield { type: \"message_stop\" };\n}\n","// Google (Gemini) adapter, on @google/genai's models.generateContent /\n// generateContentStream. Gemini is natively multimodal (text + image + audio +\n// PDF), so most translation is structural: canonical messages → Gemini\n// `contents` (role \"assistant\" → \"model\"), tools → functionDeclarations,\n// system → config.systemInstruction, tool_use/tool_result → functionCall/\n// functionResponse (name-keyed). The translations live in ./google/request.\n\nimport { GoogleGenAI } from \"@google/genai\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport type { Provider } from \"./types\";\nimport { mapProviderError, normalizeError } from \"./errors\";\nimport type { OracleEvent, OracleRequest, OracleResponse } from \"../shape/index\";\nimport { echoFromGoogle } from \"./echo\";\nimport { buildParams, toContents } from \"./google/request\";\nimport { listGoogleModels } from \"./google/models\";\nimport { mapResponse } from \"./google/response\";\nimport { mapStream } from \"./google/stream\";\nimport { signalWithDeadline } from \"../client/abort\";\n\nexport class GoogleProvider implements Provider {\n  readonly id = \"google\" as const;\n  private client: GoogleGenAI;\n\n  constructor(apiKey: string, client?: GoogleGenAI) {\n    this.client = client ?? new GoogleGenAI({ apiKey });\n  }\n\n  async create(spec: ModelSpec, req: OracleRequest): Promise<OracleResponse> {\n    const signal = signalWithDeadline(req.signal, req.deadline);\n    try {\n      const params = buildParams(spec, req);\n      // Echo before the signal is folded in — abortSignal is transport, not a\n      // model knob, and does not belong in a record of what was requested.\n      const echo = echoFromGoogle(spec, params as unknown as Record<string, unknown>);\n      params.config = { ...params.config, abortSignal: signal };\n      const res = await this.client.models.generateContent(params);\n      return { ...mapResponse(res, req), echo };\n    } catch (err) {\n      mapProviderError(err, \"google\", signal);\n    }\n  }\n\n  async *stream(spec: ModelSpec, req: OracleRequest): AsyncIterable<OracleEvent> {\n    const signal = signalWithDeadline(req.signal, req.deadline);\n    try {\n      const params = buildParams(spec, req);\n      params.config = { ...params.config, abortSignal: signal };\n      const iter = await this.client.models.generateContentStream(params);\n      yield* mapStream(iter, req);\n    } catch (err) {\n      yield { type: \"error\", error: normalizeError(err, \"google\", signal).toShape() };\n    }\n  }\n\n  listModels(opts?: { signal?: AbortSignal }) {\n    return listGoogleModels(this.client, opts);\n  }\n}\n\n// Re-exported for the test suite (test/adapters.test.ts) and callers that pinned\n// these helpers when they lived in this file.\nexport { toContents, mapResponse };\n","// @odla-ai/ai — one general-purpose interface for AI inference across\n// Anthropic (Claude), OpenAI, and Google (Gemini), plus a tool-use agent engine\n// and an eval harness. Library-only: import it in-process and bring your own keys.\n//\n//   import { init } from \"@odla-ai/ai\";\n//   const ai = init({ keys: { anthropic: process.env.ANTHROPIC_API_KEY } });\n//   const res = await ai.chat({ model: \"claude-opus-4-8\", messages: [{ role: \"user\", content: \"hi\" }], maxTokens: 256 });\n\n// ----- client facade -----\nexport { init } from \"./client/init\";\nexport type { Ai, Inference, InitOptions, ChatInput, ExtractCall, ExtractTool, SearchCall } from \"./client/init\";\nexport { redact, looksLikeKey, fingerprintCredential } from \"./client/keys\";\nexport type { KeyMap, KeyResolver, KeyOptions } from \"./client/keys\";\nexport {\n  createCapacityScheduler,\n  defaultCapacityScheduler,\n  estimateRequestTokens,\n  totalUsageTokens,\n} from \"./client/capacity\";\nexport type {\n  AiCapacityOptions,\n  CapacityAdmissionRequest,\n  CapacityEvent,\n  CapacityLease,\n  CapacityPoolIdentity,\n  CapacityScheduler,\n  CapacitySchedulerOptions,\n  ModelCapacityLimits,\n} from \"./client/capacity\";\n\n// ----- canonical shape -----\nexport {\n  emptyUsage,\n  addUsage,\n  blocksOf,\n  extractText,\n  extractToolUses,\n  isTextBlock,\n  isImageBlock,\n  isAudioBlock,\n  isDocumentBlock,\n  isToolUseBlock,\n  isToolResultBlock,\n  isThinkingBlock,\n  OdlaAIError,\n  ConfigError,\n  AuthError,\n  RateLimitError,\n  CapabilityError,\n  ContextWindowError,\n  CancelledError,\n  DeadlineExceededError,\n  InvalidRequestError,\n  ToolInputError,\n  ProviderError,\n  validateJsonSchema,\n  mergeCitations,\n} from \"./shape/index\";\nexport type {\n  ProviderId,\n  TextBlock,\n  ImageBlock,\n  ImageSource,\n  ImageMediaType,\n  AudioBlock,\n  AudioSource,\n  AudioMediaType,\n  DocumentBlock,\n  DocumentSource,\n  ToolUseBlock,\n  ToolResultBlock,\n  ThinkingBlock,\n  SearchCitation,\n  OracleContentBlock,\n  OracleRole,\n  OracleMessage,\n  OracleTool,\n  ToolChoice,\n  ThinkingMode,\n  Effort,\n  ResponseFormat,\n  AiTelemetry,\n  AiTelemetryAttributes,\n  OracleRequest,\n  OracleUsage,\n  OracleStopReason,\n  OracleResponse,\n  OracleReceipt,\n  RequestEcho,\n  OracleEvent,\n  MessageStartEvent,\n  ContentBlockStartEvent,\n  ContentBlockDeltaEvent,\n  ContentBlockDelta,\n  ContentBlockStopEvent,\n  MessageDeltaEvent,\n  MessageStopEvent,\n  OracleReceiptEvent,\n  OracleErrorEvent,\n  OracleErrorShape,\n  OracleErrorType,\n  JsonSchemaIssue,\n  JsonSchemaValidation,\n} from \"./shape/index\";\n\n// ----- capabilities + catalog -----\nexport { chatCapabilities, validateRequest } from \"./shape/capabilities\";\nexport type { ModelKind, Capabilities, ModelSpec } from \"./shape/capabilities\";\nexport { costUsd, promptTokens, ratesForPrompt, scaleLongContext } from \"./shape/pricing\";\nexport type { LongContextPricing, ModelPricing, TokenRates } from \"./shape/pricing\";\nexport { modelPricing, priceCall, pricedModels } from \"./catalog/pricing\";\nexport { EFFORT_LEVELS, nativeEffort, supportedEffortLevels, defaultEffortMap } from \"./shape/thinking\";\nexport type { ThinkingControl, NativeEffort, ThinkingSupport } from \"./shape/thinking\";\nexport { defaultWebSearchPower } from \"./shape/superpowers\";\nexport type { Superpowers, WebSearchPower, CodeExecutionPower } from \"./shape/superpowers\";\nexport {\n  DEFAULT_CATALOG,\n  buildCatalog,\n  resolveModel,\n  providersInCatalog,\n  ANTHROPIC_MODELS,\n  OPENAI_MODELS,\n  GOOGLE_MODELS,\n} from \"./catalog/index\";\nexport type { Catalog } from \"./catalog/index\";\n\n// ----- providers (adapter seam) -----\nexport { getProvider, registerProvider, clearProviderCache } from \"./providers/registry\";\nexport { listModels } from \"./providers/discovery\";\nexport { normalizeError } from \"./providers/errors\";\nexport type { Provider, ProviderFactory, DiscoveredModel, DiscoveryHints } from \"./providers/types\";\n\n// ----- agent engine -----\nexport {\n  runAgent,\n  assertCompacted,\n  keepRecentExchanges,\n  composeSkills,\n  toOracleTool,\n  InMemoryScope,\n  taint,\n  assertSinkAcceptsTaint,\n  TaintError,\n} from \"./agent/index\";\nexport type {\n  Persona,\n  Skill,\n  ComposedPersona,\n  AgentRun,\n  AgentRunInput,\n  AgentRunBudget,\n  CompactionInput,\n  CompactionPolicy,\n  CompactionRecord,\n  KeepRecentOptions,\n  StepRecord,\n  ToolCallRecord,\n  StoppedReason,\n  ToolDef,\n  ToolHandler,\n  ToolContext,\n  ToolOutput,\n  MemoryScope,\n  TaintLabel,\n  TaintSet,\n} from \"./agent/index\";\n\n// ----- harness (agent config as data + fidelity checks) -----\nexport { toPersona, resolveHarness, verifyEcho, isFaithful } from \"./harness/index\";\nexport type {\n  HarnessSpec,\n  ToolsetRegistry,\n  HarnessResolution,\n  HarnessRejection,\n  ResolveHarnessOptions,\n  EchoMismatch,\n} from \"./harness/index\";\n\n// ----- eval harness -----\nexport { evaluate, exactMatch, includes, structuredMatch, llmJudge } from \"./eval/index\";\nexport type { EvaluateOptions, EvalReport, EvalResult, EvalCase, Grader, GradeContext, GradeResult } from \"./eval/index\";\n\n// ----- odla-db storage integration (opt-in; core stays zero-runtime-dep) -----\nexport {\n  NS,\n  AGENT_SCHEMA,\n  OdlaDbMemory,\n  persistRun,\n  queryRuns,\n  odlaDbKeyResolver,\n  DEFAULT_SECRET_NAMES,\n  initFromPlatform,\n  clearPlatformAiCache,\n  createApp,\n  mintAppKey,\n  pushAgentSchema,\n  putSecret,\n  provisionAgentApp,\n  entityCrudSkill,\n} from \"./store/index\";\nexport type {\n  OdlaDbMemoryOptions,\n  PersistRunOptions,\n  QueryRunsOptions,\n  OdlaDbKeyResolverOptions,\n  InitFromPlatformOptions,\n  PlatformAi,\n  ProvisionContext,\n  ProvisionAgentAppOptions,\n  ProvisionedApp,\n  EntityCrudSkillOptions,\n  OdlaDbClient,\n  OdlaOp,\n  OdlaLookup,\n  OdlaEntityRef,\n  OdlaScalar,\n  OdlaQuery,\n} from \"./store/index\";\n","// The client facade. `init()` returns an `Ai` object (the odla convention —\n// init-returns-a-facade, cf. odla-db's `init()` → Db/AdminDb). It owns model\n// resolution (canonical id → provider), BYO key resolution, capability gating,\n// and the two convenience calls (`extract`, `search`) built generically on top\n// of the normalized `create` — so they work for any provider.\n\nimport {\n  CapabilityError,\n  ConfigError,\n  OdlaAIError,\n  ProviderError,\n  ToolInputError,\n  extractText,\n  validateJsonSchema,\n  type OracleContentBlock,\n  type OracleEvent,\n  type OracleRequest,\n  type OracleResponse,\n  type OracleUsage,\n  type AiTelemetry,\n  type AiTelemetryAttributes,\n  type ProviderId,\n  type SearchCitation,\n  type TextBlock,\n} from \"../shape/index\";\nimport { validateRequest, type ModelSpec } from \"../shape/capabilities\";\nimport { DEFAULT_CATALOG, resolveModel, type Catalog } from \"../catalog/index\";\nimport { getProvider } from \"../providers/registry\";\nimport type { Provider } from \"../providers/types\";\nimport { fingerprintCredential, resolveApiKey, type KeyMap, type KeyResolver } from \"./keys\";\nimport {\n  defaultCapacityScheduler,\n  estimateRequestTokens,\n  totalUsageTokens,\n  type AiCapacityOptions,\n  type CapacityLease,\n  type CapacityPoolIdentity,\n} from \"./capacity\";\nimport { inProviderSpan, startProviderCallSpan, type TelemetryDefaults } from \"./telemetry\";\nimport { streamProviderCall } from \"./stream\";\n\nexport interface InitOptions {\n  /** Static per-provider API keys (BYO). */\n  keys?: KeyMap;\n  /** Dynamic per-provider key lookup (multi-tenant / per-call). Consulted first. */\n  resolveKey?: KeyResolver;\n  /** Model used when a call omits `model`. */\n  defaultModel?: string;\n  /** Override / extend the built-in model catalog. */\n  catalog?: Catalog;\n  /** Inject provider adapters directly (tests, custom transports). When present\n   *  for a provider, it is used verbatim and no key is required. */\n  providers?: Partial<Record<ProviderId, Provider>>;\n  /** Optional provider-account capacity control. Pools are isolated by\n   * credential fingerprint and provider-native model id. */\n  capacity?: AiCapacityOptions;\n  /** Automatic OpenTelemetry provider-call spans. Enabled by default and a\n   * no-op until the host app configures an OTel tracer provider. */\n  telemetry?: false | { operation?: string; attributes?: AiTelemetryAttributes };\n}\n\n/** Any turn's input — a canonical request with `model` optional (defaultModel fills). */\nexport type ChatInput = Omit<OracleRequest, \"model\"> & { model?: string };\n\nexport interface ExtractTool {\n  name: string;\n  description?: string;\n  /** JSON Schema for the forced tool's arguments. */\n  parameters: Record<string, unknown>;\n}\n\n/** A forced structured extraction: schema in, validated object out. */\nexport interface ExtractCall {\n  model?: string;\n  system?: string | TextBlock[];\n  user: string | OracleContentBlock[];\n  tool: ExtractTool;\n  maxTokens?: number;\n  signal?: AbortSignal;\n  deadline?: number;\n  telemetry?: AiTelemetry | false;\n}\n\n/** A web-search-enabled call: the model searches and returns prose. */\nexport interface SearchCall {\n  model?: string;\n  system?: string | TextBlock[];\n  user: string | OracleContentBlock[];\n  maxTokens?: number;\n  signal?: AbortSignal;\n  deadline?: number;\n  telemetry?: AiTelemetry | false;\n}\n\nexport interface Ai {\n  /** The active model catalog. */\n  readonly catalog: Catalog;\n  /** One assistant turn (non-streaming). */\n  chat(input: ChatInput): Promise<OracleResponse>;\n  /** One assistant turn as a stream of normalized OracleEvents. */\n  stream(input: ChatInput): AsyncIterable<OracleEvent>;\n  /** Forced single-tool extraction → validated object. */\n  extract<T = unknown>(c: ExtractCall): Promise<{ value: T; usage: OracleUsage }>;\n  /**\n   * Web-search-grounded prose answer, plus the sources the provider attributed.\n   * `citations` is empty when the provider reported none — never assume a\n   * grounded-looking answer carries evidence.\n   */\n  search(c: SearchCall): Promise<{ text: string; usage: OracleUsage; citations: SearchCitation[] }>;\n}\n\n/** The minimal inference surface the agent loop and eval harness depend on. */\nexport type Inference = Pick<Ai, \"chat\" | \"stream\" | \"catalog\">;\n\n/**\n * Build the `Ai` facade (bring-your-own-keys). Resolves a canonical model id to\n * its provider, supplies keys statically (`keys`) or dynamically (`resolveKey`),\n * validates each request against the model's capabilities, and exposes\n * `chat`/`stream`/`extract`/`search` plus the active `catalog`. Only the SDK of a\n * provider you actually call is loaded (via the lazy provider registry).\n */\nexport function init(opts: InitOptions = {}): Ai {\n  const catalog = opts.catalog ?? DEFAULT_CATALOG;\n\n  const pickModel = (model?: string): string => {\n    const chosen = model ?? opts.defaultModel;\n    if (!chosen) throw new ConfigError(\"No model specified and no defaultModel set in init().\");\n    return chosen;\n  };\n\n  const resolveProviderFor = async (model: string): Promise<{ spec: ModelSpec; provider: Provider; credential: string }> => {\n    const spec = resolveModel(catalog, model);\n    const injected = opts.providers?.[spec.provider];\n    if (injected) {\n      const configured = opts.capacity?.injectedCredentialId;\n      const credential = typeof configured === \"function\"\n        ? configured(spec.provider)\n        : configured ?? `injected:${spec.provider}`;\n      return { spec, provider: injected, credential };\n    }\n    const key = await resolveApiKey(spec.provider, opts, model);\n    const provider = await getProvider(spec.provider, key);\n    return { spec, provider, credential: await fingerprintCredential(key) };\n  };\n\n  const acquire = async (\n    spec: ModelSpec,\n    credential: string,\n    req: OracleRequest,\n  ): Promise<CapacityLease | undefined> => {\n    if (!opts.capacity) return undefined;\n    const pool: CapacityPoolIdentity = { provider: spec.provider, credential, model: spec.nativeId };\n    const limits = typeof opts.capacity.limits === \"function\"\n      ? await opts.capacity.limits(pool)\n      : opts.capacity.limits;\n    if (!limits) return undefined;\n    return (opts.capacity.scheduler ?? defaultCapacityScheduler).acquire({\n      pool,\n      limits,\n      estimatedTokens: opts.capacity.estimateTokens?.(req) ?? estimateRequestTokens(req),\n      signal: req.signal,\n      deadline: req.deadline,\n    });\n  };\n\n  const telemetryDefaults: TelemetryDefaults | false = opts.telemetry === false\n    ? false\n    : { operation: opts.telemetry?.operation, attributes: opts.telemetry?.attributes };\n\n  const create = async (\n    model: string,\n    req: OracleRequest,\n    defaultOperation: \"chat\" | \"extract\" | \"search\" = \"chat\",\n  ): Promise<OracleResponse> => {\n    const { spec, provider, credential } = await resolveProviderFor(model);\n    validateRequest(spec, req);\n    const lease = await acquire(spec, credential, req);\n    const callSpan = startProviderCallSpan({\n      catalog,\n      model,\n      spec,\n      defaultOperation,\n      telemetry: req.telemetry,\n      defaults: telemetryDefaults,\n    });\n    try {\n      const response = await inProviderSpan(callSpan, () => provider.create(spec, req));\n      await lease?.settle(totalUsageTokens(response.usage));\n      callSpan?.succeed(response.usage, response.model);\n      return response;\n    } catch (error) {\n      const usage = error instanceof OdlaAIError ? error.usage : undefined;\n      await lease?.settle(totalUsageTokens(usage));\n      callSpan?.fail(error, usage);\n      throw error;\n    }\n  };\n\n  const chat: Ai[\"chat\"] = async (input) => {\n    const model = pickModel(input.model);\n    const req: OracleRequest = { ...input, model };\n    return create(model, req);\n  };\n\n  async function* stream(input: ChatInput): AsyncIterable<OracleEvent> {\n    const model = pickModel(input.model);\n    const req: OracleRequest = { ...input, model };\n    const { spec, provider, credential } = await resolveProviderFor(model);\n    if (!spec.capabilities.streaming) {\n      throw new CapabilityError(`Model \"${model}\" (${spec.provider}) does not support streaming.`);\n    }\n    validateRequest(spec, req);\n    const lease = await acquire(spec, credential, req);\n    const callSpan = startProviderCallSpan({\n      catalog,\n      model,\n      spec,\n      defaultOperation: \"stream\",\n      telemetry: req.telemetry,\n      defaults: telemetryDefaults,\n    });\n    yield* streamProviderCall({ provider, spec, request: req, lease, callSpan });\n  }\n\n  const extract: Ai[\"extract\"] = async <T = unknown>(c: ExtractCall) => {\n    const model = pickModel(c.model);\n    const req: OracleRequest = {\n      model,\n      system: c.system,\n      messages: [{ role: \"user\", content: c.user }],\n      tools: [{ name: c.tool.name, description: c.tool.description ?? \"\", inputSchema: c.tool.parameters }],\n      toolChoice: { type: \"tool\", name: c.tool.name },\n      maxTokens: c.maxTokens ?? 4096,\n      signal: c.signal,\n      deadline: c.deadline,\n      telemetry: c.telemetry,\n    };\n    const res = await create(model, req, \"extract\");\n    const block = res.content.find((b) => b.type === \"tool_use\" && b.name === c.tool.name);\n    if (!block || block.type !== \"tool_use\") {\n      throw new ProviderError(`Model \"${model}\" did not return the forced tool call \"${c.tool.name}\".`, { usage: res.usage });\n    }\n    const validation = validateJsonSchema(c.tool.parameters, block.input);\n    if (!validation.valid) {\n      const detail = validation.issues.slice(0, 5).map((i) => `${i.path} ${i.message}`).join(\"; \");\n      throw new ToolInputError(`Tool \"${c.tool.name}\" returned invalid input: ${detail}`, { tool: c.tool.name, usage: res.usage });\n    }\n    return { value: block.input as T, usage: res.usage };\n  };\n\n  const search: Ai[\"search\"] = async (c) => {\n    const model = pickModel(c.model);\n    const req: OracleRequest = {\n      model,\n      system: c.system,\n      messages: [{ role: \"user\", content: c.user }],\n      webSearch: true,\n      maxTokens: c.maxTokens ?? 8192,\n      signal: c.signal,\n      deadline: c.deadline,\n      telemetry: c.telemetry,\n    };\n    const res = await create(model, req, \"search\");\n    return { text: extractText(res.content), usage: res.usage, citations: res.citations ?? [] };\n  };\n\n  return { catalog, chat, stream, extract, search };\n}\n","// Model capabilities + request validation. This is the \"config is data\"\n// doctrine from odla-kg: what a model can do is a data descriptor, and every\n// request is checked against it *before* dispatch so a mismatch fails fast with\n// a clear CapabilityError instead of a confusing provider 400 (the canonical\n// example: audio input to a Claude model — Claude has no audio input).\n\nimport {\n  CapabilityError,\n  blocksOf,\n  type OracleRequest,\n  type ProviderId,\n} from \"./index\";\nimport type { ModelPricing } from \"./pricing\";\nimport type { Superpowers } from \"./superpowers\";\nimport type { ThinkingSupport } from \"./thinking\";\n\n/** The kind of model — chat/multimodal is the v1 focus; the others are modeled\n *  so embeddings, transcription, TTS, and image generation slot in later. */\nexport type ModelKind = \"chat\" | \"embed\" | \"transcribe\" | \"tts\" | \"image\";\n\nexport interface Capabilities {\n  kind: ModelKind;\n  /** Accepts text input. */\n  textIn: boolean;\n  /** Accepts image input (ImageBlock). */\n  imageIn: boolean;\n  /** Accepts audio input (AudioBlock). */\n  audioIn: boolean;\n  /** Accepts document/PDF input (DocumentBlock). */\n  documentIn: boolean;\n  /** Supports tool / function calling. */\n  toolUse: boolean;\n  /** Supports a native reasoning/thinking mode. */\n  thinking: boolean;\n  /** Supports an effort/reasoning-depth knob. */\n  effort: boolean;\n  /** Supports streaming responses. */\n  streaming: boolean;\n  /** Supports constrained JSON / structured output. */\n  structuredOutput: boolean;\n  /** Supports a provider server-side web-search tool. */\n  webSearch: boolean;\n  /** Tool results may carry content blocks natively (image/document blocks\n   *  inside a `tool_result`). When absent or false, the provider adapter\n   *  degrades non-text blocks in tool results to `[type]` text placeholders —\n   *  a lossy but non-fatal fallback, so this flag is discovery metadata for\n   *  consumers (e.g. vision-feeding tools) rather than a validation gate. */\n  toolResultBlocks?: boolean;\n}\n\n/** A catalog entry: a canonical model id mapped to a provider, that provider's\n *  native model id, and what the model can do. */\nexport interface ModelSpec {\n  /** Canonical id used across odla-ai (e.g. \"claude-opus-4-8\", \"gpt-5\"). */\n  id: string;\n  provider: ProviderId;\n  /** The id passed to the provider SDK. Often equal to `id`. */\n  nativeId: string;\n  capabilities: Capabilities;\n  contextWindow?: number;\n  maxOutput?: number;\n  /** Provider display name, for catalog/dashboard rendering. */\n  displayName?: string;\n  /** USD pricing per MTok; absent means unknown — never assume free. */\n  pricing?: ModelPricing;\n  /** Reasoning descriptor (thinking control + effort ladder). Authoritative\n   *  over the `capabilities.thinking`/`effort` booleans when present. */\n  thinking?: ThinkingSupport;\n  /** Provider server-side capabilities (web search, grounding, …) with typed\n   *  per-provider config. */\n  superpowers?: Superpowers;\n  /** Which of the provider's endpoints to call. OpenAI only today: `\"chat\"` is\n   *  Chat Completions, `\"responses\"` is `/v1/responses` — the only OpenAI\n   *  endpoint where reasoning and function tools coexist. Omit to let the\n   *  adapter choose (see `openaiApiFor`). */\n  api?: \"chat\" | \"responses\";\n}\n\n/** Sensible chat/multimodal defaults; per-model tables override what differs. */\nexport function chatCapabilities(overrides: Partial<Capabilities> = {}): Capabilities {\n  return {\n    kind: \"chat\",\n    textIn: true,\n    imageIn: true,\n    audioIn: false,\n    documentIn: false,\n    toolUse: true,\n    thinking: false,\n    effort: false,\n    streaming: true,\n    structuredOutput: true,\n    webSearch: false,\n    toolResultBlocks: false,\n    ...overrides,\n  };\n}\n\n/**\n * Validate a request against a model's capabilities. Throws CapabilityError on\n * the first violation. Runs before any provider call — the single choke point\n * that turns \"audio to Claude\" from an opaque upstream 400 into a clear error.\n */\nexport function validateRequest(spec: ModelSpec, req: OracleRequest): void {\n  const caps = spec.capabilities;\n  const fail = (what: string): never => {\n    throw new CapabilityError(\n      `Model \"${spec.id}\" (${spec.provider}) does not support ${what}.`,\n    );\n  };\n\n  if (caps.kind !== \"chat\") fail(`chat requests (it is a \"${caps.kind}\" model)`);\n\n  for (const msg of req.messages) {\n    for (const block of blocksOf(msg.content)) {\n      if (block.type === \"image\" && !caps.imageIn) fail(\"image input\");\n      if (block.type === \"audio\" && !caps.audioIn) fail(\"audio input\");\n      if (block.type === \"document\" && !caps.documentIn) fail(\"document (PDF) input\");\n    }\n  }\n\n  if (req.tools && req.tools.length > 0 && !caps.toolUse) fail(\"tool use\");\n  if (req.webSearch && !caps.webSearch && !spec.superpowers?.webSearch) fail(\"web search\");\n  if (req.responseFormat && !caps.structuredOutput) fail(\"structured output\");\n\n  const descriptor = spec.thinking;\n  if (descriptor) {\n    // Descriptor-aware gating: the per-model ThinkingSupport is authoritative.\n    if (req.thinking === \"off\" && descriptor.control === \"always-on\") {\n      fail(\"disabling thinking (thinking is always on for this model)\");\n    }\n    if (req.thinking === \"adaptive\" && descriptor.control === \"none\") fail(\"thinking\");\n    if (req.effort) {\n      const levels = descriptor.effortLevels ?? [];\n      if (!levels.includes(req.effort)) {\n        throw new CapabilityError(\n          `Model \"${spec.id}\" (${spec.provider}) does not support effort \"${req.effort}\". ` +\n            `Supported levels: ${levels.join(\", \") || \"(none)\"}.`,\n        );\n      }\n    }\n  } else {\n    // Legacy boolean fallback for specs authored before ThinkingSupport existed.\n    if (req.effort && !caps.effort) fail(\"the effort parameter\");\n    if (req.thinking === \"adaptive\" && !caps.thinking) fail(\"thinking\");\n  }\n}\n","// The model catalog: canonical model id → ModelSpec (provider, native id,\n// capabilities). The default catalog merges the three per-provider tables;\n// init() accepts a custom or extended catalog so apps can add/override models\n// without waiting on a release.\n\nimport { ConfigError, type ProviderId } from \"../shape/index\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport { ANTHROPIC_MODELS } from \"./anthropic\";\nimport { OPENAI_MODELS } from \"./openai\";\nimport { GOOGLE_MODELS } from \"./google\";\n\n/** Canonical id → spec. */\nexport type Catalog = Record<string, ModelSpec>;\n\nfunction index(specs: ModelSpec[]): Catalog {\n  const out: Catalog = {};\n  for (const spec of specs) out[spec.id] = spec;\n  return out;\n}\n\n/** The built-in catalog across Anthropic, OpenAI, and Google. */\nexport const DEFAULT_CATALOG: Catalog = index([\n  ...ANTHROPIC_MODELS,\n  ...OPENAI_MODELS,\n  ...GOOGLE_MODELS,\n]);\n\n/** Merge extra specs over a base catalog (later entries win by id). */\nexport function buildCatalog(base: Catalog, extra: ModelSpec[] = []): Catalog {\n  return { ...base, ...index(extra) };\n}\n\n/** Look up a model, throwing a ConfigError (with the known ids) if unknown. */\nexport function resolveModel(catalog: Catalog, id: string): ModelSpec {\n  const spec = catalog[id];\n  if (!spec) {\n    const known = Object.keys(catalog).sort().join(\", \");\n    throw new ConfigError(`Unknown model \"${id}\". Known models: ${known || \"(none)\"}.`);\n  }\n  return spec;\n}\n\n/** List every provider the catalog can route to. */\nexport function providersInCatalog(catalog: Catalog): ProviderId[] {\n  const set = new Set<ProviderId>();\n  for (const spec of Object.values(catalog)) set.add(spec.provider);\n  return [...set];\n}\n\nexport { ANTHROPIC_MODELS, OPENAI_MODELS, GOOGLE_MODELS };\n","// Anthropic (Claude) model catalog — config as data.\n//\n// VERIFIED 2026-07-15 against the live Models API (GET /v1/models via\n// listModels() with a real key): ids, display names, context windows, max\n// output, adaptive-thinking support, and per-model effort ladders all come\n// from the listing (opus-4-6/sonnet-4-6 have no \"xhigh\"; haiku-4-5 has no\n// adaptive thinking — it is budget_tokens-style). Pricing from the Anthropic\n// docs the same day (cache rates from the documented multipliers: read 0.1×,\n// default-TTL write 1.25×). web_search_20260209 verified with a live call on\n// claude-fable-5. Re-verify via listModels() before shipping if time has\n// passed — never hardcode model ids from memory.\n//\n// 2026-10-09, from Anthropic's models overview, the Haiku 5.5 model page and\n// migration guide, the programmatic tool calling page and the pricing page\n// (docs, not a Models API listing): Claude Haiku 5.5 added, the first model\n// here priced by prompt length; Sonnet 5's $2/$10 \"intro\" price is now its\n// standard price; Haiku 4.5 is a legacy model.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\nimport type { ModelPricing, TokenRates } from \"../shape/pricing\";\nimport type { Effort } from \"../shape/request\";\nimport type { Superpowers } from \"../shape/superpowers\";\nimport { defaultEffortMap, type ThinkingControl, type ThinkingSupport } from \"../shape/thinking\";\n\nconst FRONTIER = () =>\n  chatCapabilities({\n    documentIn: true, // PDF\n    thinking: true, // adaptive\n    effort: true, // output_config.effort\n    webSearch: true, // web_search_20260209\n    audioIn: false, // Claude has no audio input\n    toolResultBlocks: true, // adapter maps image/document blocks inside tool_result\n  });\n\nconst WEB_SEARCH: Superpowers = {\n  webSearch: { type: \"anthropic-web-search\", toolType: \"web_search_20260209\" },\n};\n\nconst FIVE: Effort[] = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\nconst FOUR: Effort[] = [\"low\", \"medium\", \"high\", \"max\"]; // 4.6 tier: no xhigh\n\nconst thinking = (control: ThinkingControl, levels: Effort[]): ThinkingSupport => ({\n  control,\n  effortLevels: levels,\n  effortMap: defaultEffortMap(\"anthropic\", levels),\n});\n\nconst rates = (inputPerMTok: number, outputPerMTok: number): TokenRates => ({\n  inputPerMTok,\n  outputPerMTok,\n  cacheReadPerMTok: inputPerMTok * 0.1,\n  cacheWritePerMTok: inputPerMTok * 1.25,\n});\n\nconst price = (inputPerMTok: number, outputPerMTok: number, note?: string): ModelPricing => ({\n  ...rates(inputPerMTok, outputPerMTok),\n  ...(note ? { note } : {}),\n});\n\n/** Built-in Anthropic (Claude) catalog: one `ModelSpec` per model (canonical id, native id, capabilities, limits, pricing, thinking descriptor). */\nexport const ANTHROPIC_MODELS: ModelSpec[] = [\n  {\n    id: \"claude-opus-5\",\n    provider: \"anthropic\",\n    nativeId: \"claude-opus-5\",\n    displayName: \"Claude Opus 5\",\n    capabilities: FRONTIER(),\n    contextWindow: 1_000_000,\n    maxOutput: 128_000,\n    pricing: price(5, 25),\n    thinking: thinking(\"on-by-default\", FIVE),\n    superpowers: WEB_SEARCH,\n  },\n  {\n    id: \"claude-opus-4-8\",\n    provider: \"anthropic\",\n    nativeId: \"claude-opus-4-8\",\n    displayName: \"Claude Opus 4.8\",\n    capabilities: FRONTIER(),\n    contextWindow: 1_000_000,\n    maxOutput: 128_000,\n    pricing: price(5, 25),\n    thinking: thinking(\"opt-in\", FIVE),\n    superpowers: WEB_SEARCH,\n  },\n  {\n    id: \"claude-opus-4-7\",\n    provider: \"anthropic\",\n    nativeId: \"claude-opus-4-7\",\n    displayName: \"Claude Opus 4.7\",\n    capabilities: FRONTIER(),\n    contextWindow: 1_000_000,\n    maxOutput: 128_000,\n    pricing: price(5, 25),\n    thinking: thinking(\"opt-in\", FIVE),\n    superpowers: WEB_SEARCH,\n  },\n  {\n    id: \"claude-opus-4-6\",\n    provider: \"anthropic\",\n    nativeId: \"claude-opus-4-6\",\n    displayName: \"Claude Opus 4.6\",\n    capabilities: FRONTIER(),\n    contextWindow: 1_000_000,\n    maxOutput: 128_000,\n    pricing: price(5, 25),\n    thinking: thinking(\"opt-in\", FOUR),\n    superpowers: WEB_SEARCH,\n  },\n  {\n    // Thinking is always on for Fable 5 — thinking:\"off\" is rejected.\n    id: \"claude-fable-5\",\n    provider: \"anthropic\",\n    nativeId: \"claude-fable-5\",\n    displayName: \"Claude Fable 5\",\n    capabilities: FRONTIER(),\n    contextWindow: 1_000_000,\n    maxOutput: 128_000,\n    pricing: price(10, 50),\n    thinking: thinking(\"always-on\", FIVE),\n    superpowers: WEB_SEARCH,\n  },\n  {\n    // Sonnet 5 runs adaptive thinking unless the request turns it off.\n    id: \"claude-sonnet-5\",\n    provider: \"anthropic\",\n    nativeId: \"claude-sonnet-5\",\n    displayName: \"Claude Sonnet 5\",\n    capabilities: FRONTIER(),\n    contextWindow: 1_000_000,\n    maxOutput: 128_000,\n    pricing: price(2, 10),\n    thinking: thinking(\"on-by-default\", FIVE),\n    superpowers: WEB_SEARCH,\n  },\n  {\n    id: \"claude-sonnet-4-6\",\n    provider: \"anthropic\",\n    nativeId: \"claude-sonnet-4-6\",\n    displayName: \"Claude Sonnet 4.6\",\n    capabilities: FRONTIER(),\n    contextWindow: 1_000_000,\n    maxOutput: 128_000,\n    pricing: price(3, 15),\n    thinking: thinking(\"opt-in\", FOUR),\n    superpowers: WEB_SEARCH,\n  },\n  {\n    // Haiku 5.5 is the first Haiku on the frontier request shape: adaptive\n    // thinking on unless the request turns it off, the full effort ladder, no\n    // sampling params. Unlike Haiku 4.5 it supports programmatic tool calling,\n    // which web_search_20260209's dynamic filtering runs through, so it takes\n    // the same web search the frontier tier does. It is also priced by prompt\n    // length — a request whose prompt is over 100K tokens pays five times as\n    // much on every token, cache reads and writes included.\n    id: \"claude-haiku-5-5\",\n    provider: \"anthropic\",\n    nativeId: \"claude-haiku-5-5\",\n    displayName: \"Claude Haiku 5.5\",\n    capabilities: FRONTIER(),\n    contextWindow: 1_000_000,\n    maxOutput: 128_000,\n    pricing: { ...price(0.1, 0.5), longContext: { aboveTokens: 100_000, ...rates(0.5, 2.5) } },\n    thinking: thinking(\"on-by-default\", FIVE),\n    superpowers: WEB_SEARCH,\n  },\n  {\n    // Haiku 4.5 (legacy since Haiku 5.5, which costs a tenth as much up to\n    // 100K prompt tokens): no effort param, no adaptive thinking (budget_tokens\n    // style), web search needs Sonnet-4.6+ — all reflected below.\n    id: \"claude-haiku-4-5\",\n    provider: \"anthropic\",\n    // The convenient canonical id routes to Anthropic's pinned dated model.\n    nativeId: \"claude-haiku-4-5-20251001\",\n    displayName: \"Claude Haiku 4.5\",\n    capabilities: chatCapabilities({\n      documentIn: true,\n      thinking: true, // budget-style thinking (mapped to budget_tokens)\n      effort: false,\n      webSearch: false,\n      audioIn: false,\n      toolResultBlocks: true, // same messages API + adapter mapping as the frontier tier\n    }),\n    contextWindow: 200_000,\n    maxOutput: 64_000,\n    pricing: price(1, 5),\n    thinking: { control: \"budget\", defaultBudgetTokens: 8_192 },\n  },\n];\n","// Model pricing — USD per million tokens, carried on the catalog's ModelSpec.\n// Field names deliberately mirror @odla/o11y-core's ModelPrice so a spec's\n// pricing can back its costUsd() override without adaptation.\n\nimport type { OracleUsage } from \"./usage\";\n\n/** The four per-token rates one request is billed at. */\nexport interface TokenRates {\n  /** USD per MTok of input. */\n  inputPerMTok: number;\n  /** USD per MTok of output (thinking tokens bill as output). */\n  outputPerMTok: number;\n  /** USD per MTok read from the prompt cache. Falls back to `inputPerMTok`. */\n  cacheReadPerMTok?: number;\n  /** USD per MTok written to the prompt cache (default-TTL tier). Falls back to\n   *  `inputPerMTok`. */\n  cacheWritePerMTok?: number;\n}\n\n/**\n * The rates a model charges once a request's prompt is longer than a\n * threshold. Every provider that prices this way replaces the rate of the\n * WHOLE request, not of the tokens past the threshold, so one extra prompt\n * token can multiply the bill. Cache rates left out here fall back to this\n * tier's `inputPerMTok`, never to the base tier's cheaper cache rates.\n */\nexport interface LongContextPricing extends TokenRates {\n  /** Prompt length in tokens. A request whose prompt is longer than this pays\n   *  these rates; a prompt of exactly this length still pays the base rates. */\n  aboveTokens: number;\n}\n\n/** USD prices per million tokens (MTok) for one model. Absent pricing means\n *  \"unknown\" — never assume free. */\nexport interface ModelPricing extends TokenRates {\n  /** Rates for requests whose prompt exceeds a length threshold. Absent means\n   *  the model charges one rate at every prompt length. */\n  longContext?: LongContextPricing;\n  /** Free-text qualifier, e.g. \"intro $2/$10 per MTok through 2026-08-31\". */\n  note?: string;\n}\n\n/**\n * The prompt length of one request: every token the model read, however it was\n * billed. The token classes in `OracleUsage` are disjoint, so a prompt served\n * mostly from the cache is still as long as the three classes summed — and it\n * is that length, not the uncached part, that selects a long-context rate.\n */\nexport function promptTokens(usage: OracleUsage): number {\n  return usage.inputTokens + (usage.cacheReadTokens ?? 0) + (usage.cacheCreationTokens ?? 0);\n}\n\n/**\n * The rates a request with a prompt of `prompt` tokens is billed at: the\n * long-context tier when the model has one and the prompt is over its\n * threshold, the base rates otherwise.\n */\nexport function ratesForPrompt(pricing: ModelPricing, prompt: number): TokenRates {\n  const long = pricing.longContext;\n  return long && prompt > long.aboveTokens ? long : pricing;\n}\n\n/**\n * Build a long-context tier from multipliers over a model's base rates — the\n * way OpenAI states it (\"2x input and 1.5x output\"). The input multiplier\n * covers every prompt-side rate: input, cache read, and cache write. A cache\n * rate the base does not carry stays absent, so it falls back to the tier's\n * input rate rather than inventing a discount.\n */\nexport function scaleLongContext(\n  base: TokenRates,\n  aboveTokens: number,\n  inputFactor: number,\n  outputFactor: number,\n): LongContextPricing {\n  return {\n    aboveTokens,\n    inputPerMTok: base.inputPerMTok * inputFactor,\n    outputPerMTok: base.outputPerMTok * outputFactor,\n    ...(base.cacheReadPerMTok === undefined ? {} : { cacheReadPerMTok: base.cacheReadPerMTok * inputFactor }),\n    ...(base.cacheWritePerMTok === undefined ? {} : { cacheWritePerMTok: base.cacheWritePerMTok * inputFactor }),\n  };\n}\n\n/**\n * Compute the USD cost of one request from its token usage. The four token\n * classes in `OracleUsage` are disjoint (Anthropic semantics, which the shape\n * mirrors), so each is priced at its own rate and summed. Callers must check\n * that pricing exists first — unknown pricing is \"no number\", never $0.\n *\n * `usage` must be ONE request's usage. A long-context tier is chosen by that\n * request's prompt length, so pricing a sum of several requests would bill\n * short prompts at the long rate; price each request, then add the dollars.\n */\nexport function costUsd(pricing: ModelPricing, usage: OracleUsage): number {\n  const rates = ratesForPrompt(pricing, promptTokens(usage));\n  const cacheRead = rates.cacheReadPerMTok ?? rates.inputPerMTok;\n  const cacheWrite = rates.cacheWritePerMTok ?? rates.inputPerMTok;\n  return (\n    (usage.inputTokens / 1e6) * rates.inputPerMTok +\n    (usage.outputTokens / 1e6) * rates.outputPerMTok +\n    ((usage.cacheReadTokens ?? 0) / 1e6) * cacheRead +\n    ((usage.cacheCreationTokens ?? 0) / 1e6) * cacheWrite\n  );\n}\n","// OpenAI model catalog — config as data.\n//\n// VERIFIED 2026-08-30 against the account's live /v1/models list (via\n// listModels() with a real key) and the official model/pricing pages\n// (developers.openai.com). reasoning_effort ladders verified EMPIRICALLY with\n// live calls per model: the gpt-5.4/5.5 generation accepts low/medium/high/\n// xhigh (plus \"none\", not part of the unified ladder — reachable via\n// providerExtras); the gpt-5 generation accepts low/medium/high only; search/\n// audio/4o lines reject reasoning_effort outright. OpenAI now publishes full\n// limits, modalities, effort ladders, tools, and token/cache prices for the\n// gpt-5.6 Sol/Terra/Luna family, so those stable ids are authoritative builtins\n// rather than mutable provider-discovery imports. Re-verify via listModels()\n// and the official model pages as the lineup drifts; do NOT trust ids from\n// memory. Pass a custom catalog to init() to add models without a release.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\nimport { scaleLongContext, type ModelPricing } from \"../shape/pricing\";\nimport type { Effort } from \"../shape/request\";\nimport { defaultEffortMap, type ThinkingSupport } from \"../shape/thinking\";\n\nconst LADDER_54: Effort[] = [\"low\", \"medium\", \"high\", \"xhigh\"];\nconst LADDER_5: Effort[] = [\"low\", \"medium\", \"high\"];\nconst LADDER_56: Effort[] = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n\n// OpenAI reasoning models have no thinking on/off toggle in the canonical\n// shape (control:\"none\"); depth is driven purely by the effort ladder.\nconst reasoning = (levels: Effort[]): ThinkingSupport => ({\n  control: \"none\",\n  effortLevels: levels,\n  effortMap: defaultEffortMap(\"openai\", levels),\n});\n\n// GPT-5.6 reasons at medium by default and accepts `none` as the native off\n// value. The canonical toggle therefore starts on while the explicit effort\n// ladder remains low..max.\nconst reasoning56 = (): ThinkingSupport => ({\n  control: \"on-by-default\",\n  effortLevels: LADDER_56,\n  effortMap: defaultEffortMap(\"openai\", LADDER_56),\n});\n\nconst price = (\n  inputPerMTok: number,\n  outputPerMTok: number,\n  cacheReadPerMTok: number,\n  note?: string,\n): ModelPricing => ({ inputPerMTok, outputPerMTok, cacheReadPerMTok, ...(note ? { note } : {}) });\n\n/** OpenAI's long-context rule, verified against its pricing page 2026-10-09:\n *  a prompt over 272K input tokens bills the whole request at 2× on every\n *  prompt-side rate (input, cached input, cache writes) and 1.5× on output. */\nconst longContext = (base: ModelPricing): ModelPricing => ({\n  ...base,\n  longContext: scaleLongContext(base, 272_000, 2, 1.5),\n});\n\nconst price56 = (\n  inputPerMTok: number,\n  outputPerMTok: number,\n  cacheReadPerMTok: number,\n  note?: string,\n): ModelPricing => longContext({\n  inputPerMTok,\n  outputPerMTok,\n  cacheReadPerMTok,\n  cacheWritePerMTok: inputPerMTok * 1.25,\n  ...(note ? { note } : {}),\n});\n\n/** Built-in OpenAI catalog: one `ModelSpec` per model (canonical id == native id, capabilities, limits, pricing, thinking descriptor). */\nexport const OPENAI_MODELS: ModelSpec[] = [\n  {\n    id: \"gpt-5.6-sol\",\n    provider: \"openai\",\n    nativeId: \"gpt-5.6-sol\",\n    displayName: \"GPT-5.6 Sol\",\n    capabilities: chatCapabilities({ thinking: true, effort: true, webSearch: true }),\n    contextWindow: 1_050_000,\n    maxOutput: 128_000,\n    pricing: price56(4, 20, 0.4, \"promotional pricing through at least 2026-11-21\"),\n    thinking: reasoning56(),\n    superpowers: { webSearch: { type: \"openai-web-search\", contextSize: \"medium\" } },\n    api: \"responses\",\n  },\n  {\n    id: \"gpt-5.6-terra\",\n    provider: \"openai\",\n    nativeId: \"gpt-5.6-terra\",\n    displayName: \"GPT-5.6 Terra\",\n    capabilities: chatCapabilities({ thinking: true, effort: true, webSearch: true }),\n    contextWindow: 1_050_000,\n    maxOutput: 128_000,\n    pricing: price56(2, 12, 0.2),\n    thinking: reasoning56(),\n    superpowers: { webSearch: { type: \"openai-web-search\", contextSize: \"medium\" } },\n    api: \"responses\",\n  },\n  {\n    id: \"gpt-5.6-luna\",\n    provider: \"openai\",\n    nativeId: \"gpt-5.6-luna\",\n    displayName: \"GPT-5.6 Luna\",\n    capabilities: chatCapabilities({ thinking: true, effort: true, webSearch: true }),\n    contextWindow: 1_050_000,\n    maxOutput: 128_000,\n    pricing: price56(0.2, 1.2, 0.02),\n    thinking: reasoning56(),\n    superpowers: { webSearch: { type: \"openai-web-search\", contextSize: \"medium\" } },\n    api: \"responses\",\n  },\n  {\n    id: \"gpt-5.5\",\n    provider: \"openai\",\n    nativeId: \"gpt-5.5\",\n    displayName: \"GPT-5.5\",\n    capabilities: chatCapabilities({ effort: true }),\n    contextWindow: 1_050_000,\n    maxOutput: 128_000,\n    pricing: longContext(price(5, 30, 0.5)),\n    thinking: reasoning(LADDER_54),\n  },\n  {\n    id: \"gpt-5.4\",\n    provider: \"openai\",\n    nativeId: \"gpt-5.4\",\n    displayName: \"GPT-5.4\",\n    capabilities: chatCapabilities({ effort: true }),\n    contextWindow: 1_050_000,\n    maxOutput: 128_000,\n    pricing: longContext(price(2.5, 15, 0.25)),\n    thinking: reasoning(LADDER_54),\n  },\n  {\n    // Compact GPT-5.4 reasoning model. The default for odla-o11y AI triage.\n    id: \"gpt-5.4-mini\",\n    provider: \"openai\",\n    nativeId: \"gpt-5.4-mini\",\n    displayName: \"GPT-5.4 mini\",\n    capabilities: chatCapabilities({ effort: true }),\n    contextWindow: 400_000,\n    maxOutput: 128_000,\n    pricing: price(0.75, 4.5, 0.075),\n    thinking: reasoning(LADDER_54),\n  },\n  {\n    id: \"gpt-5.4-nano\",\n    provider: \"openai\",\n    nativeId: \"gpt-5.4-nano\",\n    displayName: \"GPT-5.4 nano\",\n    capabilities: chatCapabilities({ effort: true }),\n    contextWindow: 400_000,\n    maxOutput: 128_000,\n    pricing: price(0.2, 1.25, 0.02),\n    thinking: reasoning(LADDER_54),\n  },\n  {\n    id: \"gpt-5\",\n    provider: \"openai\",\n    nativeId: \"gpt-5\",\n    displayName: \"GPT-5\",\n    capabilities: chatCapabilities({ effort: true }),\n    contextWindow: 400_000,\n    maxOutput: 128_000,\n    pricing: price(1.25, 10, 0.125),\n    thinking: reasoning(LADDER_5),\n  },\n  {\n    id: \"gpt-5-mini\",\n    provider: \"openai\",\n    nativeId: \"gpt-5-mini\",\n    displayName: \"GPT-5 mini\",\n    capabilities: chatCapabilities({ effort: true }),\n    contextWindow: 400_000,\n    maxOutput: 128_000,\n    pricing: price(0.25, 2, 0.025),\n    thinking: reasoning(LADDER_5),\n  },\n  {\n    id: \"gpt-5-nano\",\n    provider: \"openai\",\n    nativeId: \"gpt-5-nano\",\n    displayName: \"GPT-5 nano\",\n    capabilities: chatCapabilities({ effort: true }),\n    contextWindow: 400_000,\n    maxOutput: 128_000,\n    pricing: price(0.05, 0.4, 0.005),\n    thinking: reasoning(LADDER_5),\n  },\n  {\n    // Search-tuned chat model: the adapter sends web_search_options when a\n    // request sets webSearch. No reasoning-effort knob (verified: 400).\n    id: \"gpt-5-search-api\",\n    provider: \"openai\",\n    nativeId: \"gpt-5-search-api\",\n    displayName: \"GPT-5 Search API\",\n    capabilities: chatCapabilities({ webSearch: true }),\n    contextWindow: 400_000,\n    maxOutput: 128_000,\n    pricing: price(1.25, 10, 0.125, \"plus per-search-call tool fees\"),\n    thinking: { control: \"none\" },\n    superpowers: { webSearch: { type: \"openai-web-search\", contextSize: \"medium\" } },\n  },\n  {\n    // Non-reasoning multimodal chat (image input, no effort knob).\n    id: \"gpt-4o\",\n    provider: \"openai\",\n    nativeId: \"gpt-4o\",\n    displayName: \"GPT-4o\",\n    capabilities: chatCapabilities(),\n    contextWindow: 128_000,\n    maxOutput: 16_384,\n    pricing: price(2.5, 10, 1.25),\n    thinking: { control: \"none\" },\n  },\n  {\n    // Audio-input model line — accepts audio, not images.\n    id: \"gpt-audio\",\n    provider: \"openai\",\n    nativeId: \"gpt-audio\",\n    displayName: \"GPT Audio\",\n    capabilities: chatCapabilities({ imageIn: false, audioIn: true }),\n    contextWindow: 128_000,\n    maxOutput: 16_384,\n    pricing: price(2.5, 10, 0.25, \"text tokens; audio tokens bill separately\"),\n    thinking: { control: \"none\" },\n  },\n];\n","// Google (Gemini) model catalog — config as data.\n//\n// VERIFIED 2026-07-15 against the live models.list (via listModels() with a\n// real key) and ai.google.dev pricing. Thinking knobs verified EMPIRICALLY per\n// model: the Gemini 3.x generation takes thinkingConfig.thinkingLevel\n// (minimal/low/medium/high — pro rejects minimal) and still accepts budgets;\n// the 2.5 generation takes thinkingBudget only (pro: 128–32768, cannot\n// disable; flash: 0–24576, 0 = off); 2.0-flash has no thinking. Note\n// gemini-3-pro-preview was RETIRED upstream (404) — hence its absence.\n// Re-verify via listModels() before shipping; do NOT trust ids from memory.\n//\n// Gemini is natively multimodal: text + image + audio + PDF input, tool\n// calling via functionDeclarations, structured output via responseSchema, and\n// web grounding via the googleSearch tool — hence the broad default caps.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\nimport type { ModelPricing } from \"../shape/pricing\";\nimport type { Effort } from \"../shape/request\";\nimport type { Superpowers } from \"../shape/superpowers\";\nimport type { NativeEffort, ThinkingControl, ThinkingSupport } from \"../shape/thinking\";\n\nconst GEMINI = (over: { thinking?: boolean; effort?: boolean } = {}) =>\n  chatCapabilities({\n    audioIn: true,\n    documentIn: true,\n    thinking: over.thinking ?? true,\n    effort: over.effort ?? true,\n    webSearch: true, // googleSearch grounding\n  });\n\nconst GROUNDING: Superpowers = { webSearch: { type: \"google-search-grounding\" } };\n\n// Gemini 3.x: unified ladder → thinkingConfig.thinkingLevel (identity).\nconst levels = (control: ThinkingControl): ThinkingSupport => ({\n  control,\n  effortLevels: [\"low\", \"medium\", \"high\"],\n  effortMap: {\n    low: { param: \"thinkingLevel\", value: \"low\" },\n    medium: { param: \"thinkingLevel\", value: \"medium\" },\n    high: { param: \"thinkingLevel\", value: \"high\" },\n  },\n});\n\n// Gemini 2.5: unified ladder → thinkingConfig.thinkingBudget token values.\nconst budgets = (control: ThinkingControl, values: [number, number, number, number, number]): ThinkingSupport => {\n  const ladder: Effort[] = [\"low\", \"medium\", \"high\", \"xhigh\", \"max\"];\n  const effortMap: Partial<Record<Effort, NativeEffort>> = {};\n  ladder.forEach((level, i) => {\n    effortMap[level] = { param: \"thinkingBudget\", value: values[i]! };\n  });\n  return { control, effortLevels: ladder, effortMap };\n};\n\nconst price = (\n  inputPerMTok: number,\n  outputPerMTok: number,\n  cacheReadPerMTok: number,\n  note?: string,\n): ModelPricing => ({ inputPerMTok, outputPerMTok, cacheReadPerMTok, ...(note ? { note } : {}) });\n\n/** A Gemini Pro price with its second rate card: a prompt over 200K tokens\n *  bills the whole request at the higher rates. Verified against\n *  ai.google.dev/gemini-api/docs/pricing on 2026-10-09. */\nconst tiered = (base: ModelPricing, input: number, output: number, cacheRead: number): ModelPricing => ({\n  ...base,\n  longContext: { aboveTokens: 200_000, inputPerMTok: input, outputPerMTok: output, cacheReadPerMTok: cacheRead },\n});\n\n/** Built-in Google (Gemini) catalog: one `ModelSpec` per model (canonical id == native id, capabilities, limits, pricing, thinking descriptor). */\nexport const GOOGLE_MODELS: ModelSpec[] = [\n  {\n    // Stable model and limits verified 2026-08-29 against Google's model and\n    // pricing pages. The single output price is intentionally the conservative\n    // image-token rate; text/thinking output is cheaper, as the note records.\n    id: \"gemini-3.1-flash-lite-image\",\n    provider: \"google\",\n    nativeId: \"gemini-3.1-flash-lite-image\",\n    displayName: \"Nano Banana 2 Lite\",\n    capabilities: chatCapabilities({\n      audioIn: false,\n      documentIn: false,\n      thinking: true,\n      effort: true,\n      structuredOutput: false,\n      webSearch: false,\n    }),\n    contextWindow: 65_536,\n    maxOutput: 4_096,\n    pricing: {\n      inputPerMTok: 0.25,\n      outputPerMTok: 30,\n      note: \"image output; text/thinking output is $1.50/MTok; one 1K image is 1,120 tokens ($0.0336)\",\n    },\n    thinking: {\n      control: \"always-on\",\n      effortLevels: [\"low\", \"high\"],\n      effortMap: {\n        low: { param: \"thinkingLevel\", value: \"minimal\" },\n        high: { param: \"thinkingLevel\", value: \"high\" },\n      },\n    },\n  },\n  {\n    // Stable identity, limits, capabilities, and paid standard pricing\n    // verified 2026-08-30 against Google's model, image-generation, and\n    // pricing pages. Image output is the conservative catalog rate.\n    id: \"gemini-3.1-flash-image\",\n    provider: \"google\",\n    nativeId: \"gemini-3.1-flash-image\",\n    displayName: \"Nano Banana 2\",\n    capabilities: chatCapabilities({\n      audioIn: false,\n      documentIn: true,\n      toolUse: false,\n      thinking: true,\n      effort: true,\n      structuredOutput: false,\n      webSearch: true,\n    }),\n    contextWindow: 131_072,\n    maxOutput: 32_768,\n    pricing: {\n      inputPerMTok: 0.5,\n      outputPerMTok: 60,\n      note: \"image output; text/thinking output is $3/MTok; 0.5K/1K/2K/4K images cost $0.045/$0.067/$0.101/$0.151\",\n    },\n    thinking: {\n      control: \"always-on\",\n      effortLevels: [\"low\", \"high\"],\n      effortMap: {\n        low: { param: \"thinkingLevel\", value: \"minimal\" },\n        high: { param: \"thinkingLevel\", value: \"high\" },\n      },\n    },\n    superpowers: GROUNDING,\n  },\n  {\n    id: \"gemini-3-pro-image\",\n    provider: \"google\",\n    nativeId: \"gemini-3-pro-image\",\n    displayName: \"Nano Banana Pro\",\n    capabilities: chatCapabilities({\n      audioIn: false,\n      documentIn: false,\n      toolUse: false,\n      thinking: true,\n      effort: false,\n      structuredOutput: false,\n      webSearch: true,\n    }),\n    contextWindow: 65_536,\n    maxOutput: 32_768,\n    pricing: {\n      inputPerMTok: 2,\n      outputPerMTok: 120,\n      note: \"image output; text/thinking output is $12/MTok; 1K/2K images cost $0.134 and 4K images cost $0.24\",\n    },\n    thinking: { control: \"always-on\" },\n    superpowers: GROUNDING,\n  },\n  {\n    id: \"gemini-3.5-flash\",\n    provider: \"google\",\n    nativeId: \"gemini-3.5-flash\",\n    displayName: \"Gemini 3.5 Flash\",\n    capabilities: GEMINI(),\n    contextWindow: 1_048_576,\n    maxOutput: 65_536,\n    pricing: price(1.5, 9, 0.15),\n    thinking: levels(\"on-by-default\"),\n    superpowers: GROUNDING,\n  },\n  {\n    id: \"gemini-3.1-pro-preview\",\n    provider: \"google\",\n    nativeId: \"gemini-3.1-pro-preview\",\n    displayName: \"Gemini 3.1 Pro Preview\",\n    capabilities: GEMINI(),\n    contextWindow: 1_048_576,\n    maxOutput: 65_536,\n    pricing: tiered(price(2, 12, 0.2), 4, 18, 0.4),\n    thinking: levels(\"always-on\"),\n    superpowers: GROUNDING,\n  },\n  {\n    id: \"gemini-3-flash-preview\",\n    provider: \"google\",\n    nativeId: \"gemini-3-flash-preview\",\n    displayName: \"Gemini 3 Flash Preview\",\n    capabilities: GEMINI(),\n    contextWindow: 1_048_576,\n    maxOutput: 65_536,\n    pricing: price(0.5, 3, 0.05),\n    thinking: levels(\"on-by-default\"),\n    superpowers: GROUNDING,\n  },\n  {\n    // 2.5 Pro only works in thinking mode (budget 0 rejected upstream).\n    id: \"gemini-2.5-pro\",\n    provider: \"google\",\n    nativeId: \"gemini-2.5-pro\",\n    displayName: \"Gemini 2.5 Pro\",\n    capabilities: GEMINI(),\n    contextWindow: 1_048_576,\n    maxOutput: 65_536,\n    pricing: tiered(price(1.25, 10, 0.125), 2.5, 15, 0.25),\n    thinking: budgets(\"always-on\", [2_048, 8_192, 16_384, 24_576, 32_768]),\n    superpowers: GROUNDING,\n  },\n  {\n    id: \"gemini-2.5-flash\",\n    provider: \"google\",\n    nativeId: \"gemini-2.5-flash\",\n    displayName: \"Gemini 2.5 Flash\",\n    capabilities: GEMINI(),\n    contextWindow: 1_048_576,\n    maxOutput: 65_536,\n    pricing: price(0.3, 2.5, 0.03),\n    thinking: budgets(\"on-by-default\", [1_024, 4_096, 8_192, 16_384, 24_576]),\n    superpowers: GROUNDING,\n  },\n  {\n    id: \"gemini-2.5-flash-image\",\n    provider: \"google\",\n    nativeId: \"gemini-2.5-flash-image\",\n    displayName: \"Nano Banana\",\n    capabilities: chatCapabilities({\n      audioIn: false,\n      documentIn: false,\n      toolUse: false,\n      thinking: false,\n      effort: false,\n      structuredOutput: true,\n      webSearch: false,\n    }),\n    contextWindow: 65_536,\n    maxOutput: 32_768,\n    pricing: {\n      inputPerMTok: 0.3,\n      outputPerMTok: 30,\n      note: \"image output; text output is $2.50/MTok; one 1K image is 1,290 tokens ($0.039)\",\n    },\n    thinking: { control: \"none\" },\n  },\n  {\n    id: \"gemini-2.0-flash\",\n    provider: \"google\",\n    nativeId: \"gemini-2.0-flash\",\n    displayName: \"Gemini 2.0 Flash\",\n    capabilities: GEMINI({ thinking: false, effort: false }),\n    contextWindow: 1_048_576,\n    maxOutput: 8_192,\n    pricing: price(0.1, 0.4, 0.025),\n    thinking: { control: \"none\" },\n    superpowers: GROUNDING,\n  },\n];\n","// API-key resolution + redaction. Keys are BYO (caller-supplied): a static map\n// per provider and/or a dynamic resolver (for multi-tenant / per-call selection).\n// A provider with no resolvable key is simply unavailable — requesting one of its\n// models throws a ConfigError, the library analog of odla-db's config-presence\n// gating. Redaction patterns are lifted from odla-ai-old's publish-safety scanner.\n\nimport { ConfigError, type ProviderId } from \"../shape/index\";\n\n/** Static per-provider keys. */\nexport type KeyMap = Partial<Record<ProviderId, string>>;\n\n/** Dynamic key lookup — return undefined to signal \"no key for this provider\". */\nexport type KeyResolver = (provider: ProviderId) => string | undefined | Promise<string | undefined>;\n\nexport interface KeyOptions {\n  keys?: KeyMap;\n  /** Consulted first; falls back to `keys` when it returns undefined. */\n  resolveKey?: KeyResolver;\n}\n\n/** Resolve the API key for a provider, or throw a ConfigError naming it. */\nexport async function resolveApiKey(\n  provider: ProviderId,\n  opts: KeyOptions,\n  forModel: string,\n): Promise<string> {\n  let key: string | undefined;\n  if (opts.resolveKey) key = await opts.resolveKey(provider);\n  if (!key) key = opts.keys?.[provider];\n  if (!key) {\n    throw new ConfigError(\n      `No API key configured for provider \"${provider}\" (required by model \"${forModel}\"). ` +\n        `Pass keys: { ${provider}: \"...\" } or a resolveKey() to init().`,\n    );\n  }\n  return key;\n}\n\n/** Best-effort key-shape check (used by smoke/diagnostics, never for gating —\n *  formats drift). */\nexport function looksLikeKey(provider: ProviderId, key: string): boolean {\n  switch (provider) {\n    case \"anthropic\":\n      return /^sk-ant-[a-zA-Z0-9_-]{20,}/.test(key);\n    case \"openai\":\n      return /^sk-(?!ant-)(?:proj-)?[a-zA-Z0-9_-]{20,}/.test(key);\n    case \"google\":\n      return /^AIza[0-9A-Za-z_-]{35}$/.test(key) || key.length >= 20;\n  }\n}\n\n/** Redact anything that looks like a provider secret from a string (logs/errors). */\nexport function redact(text: string): string {\n  return text\n    .replace(/sk-ant-[a-zA-Z0-9_-]{6,}/g, \"sk-ant-…\")\n    .replace(/sk-(?!ant-)(?:proj-)?[a-zA-Z0-9_-]{10,}/g, \"sk-…\")\n    .replace(/\\bAIza[0-9A-Za-z_-]{6,}/g, \"AIza…\");\n}\n\n/** Return a stable SHA-256 credential fingerprint suitable for cache and\n * capacity-pool identities. The raw key is never retained in the result. */\nexport async function fingerprintCredential(apiKey: string): Promise<string> {\n  const digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(apiKey));\n  return [...new Uint8Array(digest)].map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\");\n}\n","// Provider registry. `getProvider` lazy-`import()`s the adapter module — and,\n// transitively, only that provider's SDK — so a Claude-only consumer never loads\n// `openai` or `@google/genai` at runtime. At most one short-lived client is kept\n// per provider. Cache keys are SHA-256 fingerprints, never raw credentials.\n\nimport type { ProviderId } from \"../shape/index\";\nimport type { Provider } from \"./types\";\nimport { fingerprintCredential } from \"../client/keys\";\n\ninterface CacheEntry {\n  fingerprint: string;\n  provider: Provider;\n  expiresAt: number;\n}\n\nconst CLIENT_TTL_MS = 60_000;\nconst cache = new Map<ProviderId, CacheEntry>();\nconst inflight = new Map<ProviderId, { fingerprint: string; promise: Promise<Provider> }>();\n// Synchronous test-only overrides preserve the existing registerProvider seam.\n// Production-created clients always use the fingerprinted cache above.\nconst overrides = new Map<ProviderId, { apiKey: string; provider: Provider }>();\n\n/**\n * Resolve the adapter for a provider, lazy-`import()`ing its module (and only\n * that provider's SDK) on first use and caching the instance per (provider, key)\n * so repeated calls reuse one SDK client.\n */\nexport async function getProvider(id: ProviderId, apiKey: string): Promise<Provider> {\n  const override = overrides.get(id);\n  if (override?.apiKey === apiKey) return override.provider;\n\n  const fingerprint = await fingerprintCredential(apiKey);\n  const existing = cache.get(id);\n  if (existing?.fingerprint === fingerprint && existing.expiresAt > Date.now()) return existing.provider;\n  if (existing) cache.delete(id); // rotation/expiry releases the prior SDK client + key\n\n  const pending = inflight.get(id);\n  if (pending?.fingerprint === fingerprint) return pending.promise;\n\n  const promise = createProvider(id, apiKey).then((provider) => {\n    cache.set(id, { fingerprint, provider, expiresAt: Date.now() + CLIENT_TTL_MS });\n    return provider;\n  }).finally(() => {\n    if (inflight.get(id)?.promise === promise) inflight.delete(id);\n  });\n  inflight.set(id, { fingerprint, promise });\n  return promise;\n}\n\nasync function createProvider(id: ProviderId, apiKey: string): Promise<Provider> {\n  let provider: Provider;\n  switch (id) {\n    case \"anthropic\": {\n      const { AnthropicProvider } = await import(\"./anthropic\");\n      provider = new AnthropicProvider(apiKey);\n      break;\n    }\n    case \"openai\": {\n      const { OpenAIProvider } = await import(\"./openai\");\n      provider = new OpenAIProvider(apiKey);\n      break;\n    }\n    case \"google\": {\n      const { GoogleProvider } = await import(\"./google\");\n      provider = new GoogleProvider(apiKey);\n      break;\n    }\n  }\n  return provider;\n}\n\n/** Test seam: register a provider instance directly (used to inject mocks). */\nexport function registerProvider(id: ProviderId, apiKey: string, provider: Provider): void {\n  overrides.set(id, { apiKey, provider });\n}\n\n/** Test seam: clear the adapter cache. */\nexport function clearProviderCache(): void {\n  cache.clear();\n  inflight.clear();\n  overrides.clear();\n}\n","import { CancelledError, DeadlineExceededError, type OracleRequest, type OracleUsage } from \"../shape/index\";\n\nconst MINUTE_MS = 60_000;\nconst DAY_MS = 24 * 60 * MINUTE_MS;\n\n/** Provider-account limits for one native model. Rate limits are interpreted\n * with `headroom` reserved; concurrency is an explicit hard ceiling. */\nexport interface ModelCapacityLimits {\n  /** Provider tokens per minute. */\n  tokensPerMinute?: number;\n  /** Provider requests per minute. */\n  requestsPerMinute?: number;\n  /** Provider tokens per day. */\n  tokensPerDay?: number;\n  /** Maximum requests simultaneously in flight. */\n  maxParallelRequests?: number;\n  /** Fraction of provider rate budgets held back. Defaults to 0.20. */\n  headroom?: number;\n}\n\n/** Stable, secret-free identity for a provider credential and native model. */\nexport interface CapacityPoolIdentity {\n  provider: string;\n  credential: string;\n  model: string;\n}\n\n/** One queued admission request. Deadlines include time spent waiting. */\nexport interface CapacityAdmissionRequest {\n  pool: CapacityPoolIdentity;\n  limits: ModelCapacityLimits;\n  estimatedTokens: number;\n  signal?: AbortSignal;\n  deadline?: number;\n}\n\n/** A granted capacity slot. Settle it exactly once after provider I/O ends. */\nexport interface CapacityLease {\n  readonly queuedMs: number;\n  readonly startedAt: number;\n  settle(actualTokens?: number): void | Promise<void>;\n}\n\n/** Observable scheduler state transitions. Pool identities contain only a\n * credential fingerprint, never the provider key. */\nexport interface CapacityEvent {\n  type: \"queued\" | \"started\" | \"settled\";\n  pool: CapacityPoolIdentity;\n  at: number;\n  estimatedTokens: number;\n  actualTokens?: number;\n  queuedMs?: number;\n  queueDepth: number;\n  activeRequests: number;\n}\n\n/** Options for the in-memory scheduler. */\nexport interface CapacitySchedulerOptions {\n  onEvent?: (event: CapacityEvent) => void;\n}\n\n/** FIFO admission controller shared by every `init()` using it. */\nexport interface CapacityScheduler {\n  acquire(request: CapacityAdmissionRequest): Promise<CapacityLease>;\n}\n\ninterface Waiter extends CapacityAdmissionRequest {\n  queuedAt: number;\n  resolve: (lease: CapacityLease) => void;\n  reject: (error: unknown) => void;\n  cancelled: boolean;\n  removeAbort?: () => void;\n}\n\ninterface PoolState {\n  active: number;\n  nextStartAt: number;\n  queue: Waiter[];\n  timer?: ReturnType<typeof setTimeout>;\n}\n\n/** Create a simple FIFO scheduler. Estimated usage advances the next-start\n * clock at admission; only positive actual-token excess advances it again. */\nexport function createCapacityScheduler(options: CapacitySchedulerOptions = {}): CapacityScheduler {\n  const pools = new Map<string, PoolState>();\n\n  const emit = (event: CapacityEvent) => {\n    try { options.onEvent?.(event); } catch { /* Observability cannot break admission. */ }\n  };\n\n  const drain = (key: string, state: PoolState): void => {\n    if (state.timer) {\n      clearTimeout(state.timer);\n      state.timer = undefined;\n    }\n    while (state.queue.length) {\n      const waiter = state.queue[0]!;\n      if (waiter.cancelled) {\n        state.queue.shift();\n        continue;\n      }\n      const now = Date.now();\n      if (waiter.deadline !== undefined && now >= waiter.deadline) {\n        state.queue.shift();\n        waiter.removeAbort?.();\n        waiter.reject(new DeadlineExceededError(\"AI request deadline elapsed while waiting for model capacity.\"));\n        continue;\n      }\n      const parallel = positiveInteger(waiter.limits.maxParallelRequests) ?? Number.POSITIVE_INFINITY;\n      if (state.active >= parallel) {\n        if (waiter.deadline !== undefined) {\n          state.timer = setTimeout(() => drain(key, state), Math.max(1, waiter.deadline - now));\n        }\n        return;\n      }\n      const eligibleAt = Math.max(now, state.nextStartAt);\n      if (waiter.deadline !== undefined && eligibleAt >= waiter.deadline) {\n        state.queue.shift();\n        waiter.removeAbort?.();\n        waiter.reject(new DeadlineExceededError(\"AI request deadline would elapse before model capacity is available.\"));\n        continue;\n      }\n      if (eligibleAt > now) {\n        state.timer = setTimeout(() => drain(key, state), eligibleAt - now);\n        return;\n      }\n\n      state.queue.shift();\n      waiter.removeAbort?.();\n      state.active += 1;\n      const startedAt = now;\n      state.nextStartAt = startedAt + requestSpacingMs(waiter.estimatedTokens, waiter.limits);\n      emit({\n        type: \"started\", pool: waiter.pool, at: startedAt,\n        estimatedTokens: waiter.estimatedTokens, queuedMs: startedAt - waiter.queuedAt,\n        queueDepth: state.queue.length, activeRequests: state.active,\n      });\n      let settled = false;\n      waiter.resolve({\n        queuedMs: startedAt - waiter.queuedAt,\n        startedAt,\n        settle(actualTokens = waiter.estimatedTokens) {\n          if (settled) return;\n          settled = true;\n          const finishedAt = Date.now();\n          state.active = Math.max(0, state.active - 1);\n          const actual = tokenCount(actualTokens);\n          const excess = Math.max(0, actual - tokenCount(waiter.estimatedTokens));\n          if (excess) {\n            state.nextStartAt = Math.max(state.nextStartAt, finishedAt) + tokenSpacingMs(excess, waiter.limits);\n          }\n          emit({\n            type: \"settled\", pool: waiter.pool, at: finishedAt,\n            estimatedTokens: waiter.estimatedTokens, actualTokens: actual,\n            queueDepth: state.queue.length, activeRequests: state.active,\n          });\n          drain(key, state);\n        },\n      });\n    }\n    if (state.active === 0) {\n      const remaining = state.nextStartAt - Date.now();\n      if (remaining <= 0) pools.delete(key);\n      else state.timer = setTimeout(() => {\n        state.timer = undefined;\n        if (state.active === 0 && state.queue.length === 0 && state.nextStartAt <= Date.now()) pools.delete(key);\n      }, remaining);\n    }\n  };\n\n  return {\n    acquire(request) {\n      const queuedAt = Date.now();\n      if (request.signal?.aborted) return Promise.reject(new CancelledError());\n      if (request.deadline !== undefined && queuedAt >= request.deadline) {\n        return Promise.reject(new DeadlineExceededError());\n      }\n      validateLimits(request.limits);\n      const normalized = { ...request, estimatedTokens: tokenCount(request.estimatedTokens) };\n      const key = poolKey(request.pool);\n      const state = pools.get(key) ?? { active: 0, nextStartAt: 0, queue: [] };\n      pools.set(key, state);\n      return new Promise<CapacityLease>((resolve, reject) => {\n        const waiter: Waiter = { ...normalized, queuedAt, resolve, reject, cancelled: false };\n        if (request.signal) {\n          const onAbort = () => {\n            if (waiter.cancelled) return;\n            waiter.cancelled = true;\n            reject(new CancelledError());\n            drain(key, state);\n          };\n          request.signal.addEventListener(\"abort\", onAbort, { once: true });\n          waiter.removeAbort = () => request.signal?.removeEventListener(\"abort\", onAbort);\n        }\n        state.queue.push(waiter);\n        emit({\n          type: \"queued\", pool: request.pool, at: queuedAt,\n          estimatedTokens: normalized.estimatedTokens,\n          queueDepth: state.queue.length, activeRequests: state.active,\n        });\n        drain(key, state);\n      });\n    },\n  };\n}\n\n/** Capacity configuration applied by an `Ai` facade. */\nexport interface AiCapacityOptions {\n  /** Limits or a resolver for a credential-model pool. Returning undefined\n   * bypasses scheduling for that call. */\n  limits: ModelCapacityLimits | ((pool: CapacityPoolIdentity) => ModelCapacityLimits | undefined | Promise<ModelCapacityLimits | undefined>);\n  /** Shared scheduler. Omit to use the process-wide scheduler. */\n  scheduler?: CapacityScheduler;\n  /** Stable credential identity for injected providers. Key-backed providers\n   * are fingerprinted automatically. */\n  injectedCredentialId?: string | ((provider: string) => string);\n  /** Override the conservative request token estimator. */\n  estimateTokens?: (request: OracleRequest) => number;\n}\n\n/** Count all disjoint provider token classes for capacity reconciliation. */\nexport function totalUsageTokens(usage: OracleUsage | undefined): number {\n  if (!usage) return 0;\n  return tokenCount(usage.inputTokens) + tokenCount(usage.outputTokens)\n    + tokenCount(usage.cacheCreationTokens) + tokenCount(usage.cacheReadTokens);\n}\n\n/** Estimate request tokens without provider-specific tokenizers. Output is not\n * added: the default 20% headroom reserves response uncertainty. */\nexport function estimateRequestTokens(request: OracleRequest): number {\n  const value = {\n    system: request.system,\n    messages: request.messages,\n    tools: request.tools,\n    responseFormat: request.responseFormat,\n  };\n  return Math.max(1, Math.ceil(new TextEncoder().encode(JSON.stringify(value)).byteLength / 4));\n}\n\n/** Process-wide scheduler used unless a caller supplies an isolated one. */\nexport const defaultCapacityScheduler = createCapacityScheduler();\n\nfunction requestSpacingMs(tokens: number, limits: ModelCapacityLimits): number {\n  const effective = effectiveLimits(limits);\n  return Math.ceil(Math.max(\n    effective.tokensPerMinute ? tokens / effective.tokensPerMinute * MINUTE_MS : 0,\n    effective.tokensPerDay ? tokens / effective.tokensPerDay * DAY_MS : 0,\n    effective.requestsPerMinute ? MINUTE_MS / effective.requestsPerMinute : 0,\n  ));\n}\n\nfunction tokenSpacingMs(tokens: number, limits: ModelCapacityLimits): number {\n  const effective = effectiveLimits(limits);\n  return Math.ceil(Math.max(\n    effective.tokensPerMinute ? tokens / effective.tokensPerMinute * MINUTE_MS : 0,\n    effective.tokensPerDay ? tokens / effective.tokensPerDay * DAY_MS : 0,\n  ));\n}\n\nfunction effectiveLimits(limits: ModelCapacityLimits): ModelCapacityLimits {\n  const headroom = limits.headroom ?? 0.2;\n  const usable = 1 - headroom;\n  return {\n    tokensPerMinute: limits.tokensPerMinute === undefined ? undefined : limits.tokensPerMinute * usable,\n    requestsPerMinute: limits.requestsPerMinute === undefined ? undefined : limits.requestsPerMinute * usable,\n    tokensPerDay: limits.tokensPerDay === undefined ? undefined : limits.tokensPerDay * usable,\n  };\n}\n\nfunction validateLimits(limits: ModelCapacityLimits): void {\n  const numeric = [limits.tokensPerMinute, limits.requestsPerMinute, limits.tokensPerDay];\n  if (numeric.some((value) => value !== undefined && (!Number.isFinite(value) || value <= 0))) {\n    throw new TypeError(\"model capacity rate limits must be positive finite numbers\");\n  }\n  if (limits.maxParallelRequests !== undefined && positiveInteger(limits.maxParallelRequests) === undefined) {\n    throw new TypeError(\"model capacity maxParallelRequests must be a positive integer\");\n  }\n  if (limits.headroom !== undefined && (!Number.isFinite(limits.headroom) || limits.headroom < 0 || limits.headroom >= 1)) {\n    throw new TypeError(\"model capacity headroom must be at least 0 and less than 1\");\n  }\n}\n\nfunction poolKey(pool: CapacityPoolIdentity): string {\n  return `${pool.provider}\\u0000${pool.credential}\\u0000${pool.model}`;\n}\n\nfunction positiveInteger(value: unknown): number | undefined {\n  return Number.isSafeInteger(value) && Number(value) > 0 ? Number(value) : undefined;\n}\n\nfunction tokenCount(value: unknown): number {\n  return Number.isFinite(value) && Number(value) > 0 ? Math.ceil(Number(value)) : 0;\n}\n","import {\n  SpanKind,\n  SpanStatusCode,\n  context,\n  trace,\n  type Attributes,\n  type Context,\n  type Span,\n} from \"@opentelemetry/api\";\nimport { priceCall } from \"../catalog/pricing\";\nimport type { Catalog } from \"../catalog/index\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport type { AiTelemetry, AiTelemetryAttributes } from \"../shape/request\";\nimport type { OracleUsage } from \"../shape/usage\";\nimport { OdlaAIError } from \"../shape/errors\";\n\nconst tracer = trace.getTracer(\"@odla-ai/ai\");\n\nexport interface TelemetryDefaults {\n  operation?: string;\n  attributes?: AiTelemetryAttributes;\n}\n\nexport interface ProviderCallSpan {\n  readonly span: Span;\n  readonly context: Context;\n  firstToken(): void;\n  succeed(usage: OracleUsage, responseModel?: string): void;\n  fail(error: unknown, usage?: OracleUsage): void;\n}\n\n/** Start one CLIENT span for one actual provider request. The OTel API's global\n * no-op provider makes this effectively free when an app has not configured\n * observability. */\nexport function startProviderCallSpan(input: {\n  catalog: Catalog;\n  model: string;\n  spec: ModelSpec;\n  defaultOperation: \"chat\" | \"stream\" | \"extract\" | \"search\";\n  telemetry?: AiTelemetry | false;\n  defaults?: TelemetryDefaults | false;\n}): ProviderCallSpan | undefined {\n  if (input.defaults === false || input.telemetry === false) return undefined;\n  const operation = input.telemetry?.operation || input.defaults?.operation || input.defaultOperation;\n  const startedAt = Date.now();\n  const attributes: Attributes = {\n    ...(input.defaults?.attributes ?? {}),\n    ...(input.telemetry?.attributes ?? {}),\n    \"gen_ai.operation.name\": operation,\n    \"gen_ai.provider.name\": input.spec.provider,\n    \"gen_ai.request.model\": input.model,\n    \"odla.llm.calls\": 1,\n  };\n  const span = tracer.startSpan(`gen_ai.${operation} ${input.model}`, {\n    kind: SpanKind.CLIENT,\n    attributes,\n  });\n  const spanContext = trace.setSpan(context.active(), span);\n  let ttftMs: number | undefined;\n  let ended = false;\n\n  const finish = (\n    status: { code: SpanStatusCode; message?: string },\n    usage?: OracleUsage,\n    responseModel?: string,\n    error?: unknown,\n  ): void => {\n    if (ended) return;\n    ended = true;\n    const latencyMs = Math.max(0, Date.now() - startedAt);\n    span.setAttribute(\"odla.llm.latency_ms\", latencyMs);\n    if (ttftMs !== undefined) span.setAttribute(\"odla.llm.ttft_ms\", ttftMs);\n    if (responseModel) span.setAttribute(\"gen_ai.response.model\", responseModel);\n    if (usage) {\n      span.setAttributes({\n        \"gen_ai.usage.input_tokens\": usage.inputTokens,\n        \"gen_ai.usage.output_tokens\": usage.outputTokens,\n        ...(usage.cacheReadTokens !== undefined\n          ? { \"gen_ai.usage.cache_read_tokens\": usage.cacheReadTokens }\n          : {}),\n        ...(usage.cacheCreationTokens !== undefined\n          ? { \"gen_ai.usage.cache_creation_tokens\": usage.cacheCreationTokens }\n          : {}),\n      });\n      const cost = priceCall(input.model, usage, input.catalog);\n      span.setAttribute(\"odla.llm.cost.priced\", cost !== undefined);\n      if (cost !== undefined) span.setAttribute(\"odla.llm.cost.usd\", cost);\n    } else {\n      span.setAttribute(\"odla.llm.cost.priced\", false);\n    }\n    if (error !== undefined) {\n      const errorCode = error instanceof OdlaAIError\n        ? error.code\n        : error instanceof Error\n          ? error.name\n          : \"unknown\";\n      span.setAttribute(\"error.type\", errorCode);\n      span.recordException(error instanceof Error ? error : String(error));\n    }\n    span.setStatus(status);\n    span.end();\n  };\n\n  return {\n    span,\n    context: spanContext,\n    firstToken() {\n      if (ttftMs === undefined) ttftMs = Math.max(0, Date.now() - startedAt);\n    },\n    succeed(usage, responseModel) {\n      finish({ code: SpanStatusCode.OK }, usage, responseModel);\n    },\n    fail(error, usage) {\n      finish({ code: SpanStatusCode.ERROR }, usage, undefined, error);\n    },\n  };\n}\n\n/** Run provider adapter work with the provider-call span active, allowing any\n * vendor HTTP instrumentation to become its child. */\nexport function inProviderSpan<T>(call: ProviderCallSpan | undefined, fn: () => T): T {\n  return call ? context.with(call.context, fn) : fn();\n}\n","// Catalog-backed pricing lookup. The catalog already carries per-model\n// `ModelPricing`; this is the seam that lets a cost-accounting consumer price a\n// call from a model id alone, without holding a Catalog or an Ai client.\n//\n// Deliberately free of provider-SDK imports (the whole `catalog/` + `shape/`\n// subtree is), so `@odla-ai/ai/pricing` stays a few KB in a Worker bundle.\n\nimport { costUsd, type ModelPricing } from \"../shape/pricing\";\nimport type { OracleUsage } from \"../shape/usage\";\nimport { DEFAULT_CATALOG, type Catalog } from \"./index\";\n\n/**\n * Look up a model's USD pricing by canonical id.\n *\n * Returns `undefined` for an unknown model *and* for a known model whose spec\n * carries no `pricing` — the two are the same answer to the only question that\n * matters downstream: \"can this call be priced?\". Unlike `resolveModel`, an\n * unknown id is not an error, because a cost path must degrade to \"unpriced\"\n * rather than throw inside telemetry.\n *\n * @param id Canonical model id, e.g. `\"claude-opus-4-8\"`.\n * @param catalog Catalog to read; defaults to the built-in `DEFAULT_CATALOG`.\n */\nexport function modelPricing(id: string, catalog: Catalog = DEFAULT_CATALOG): ModelPricing | undefined {\n  return catalog[id]?.pricing;\n}\n\n/**\n * Price one call from a model id and its token usage.\n *\n * Returns `undefined` when the model has no known pricing, so a caller can\n * never mistake missing catalog data for a free call. Cache-read and\n * cache-write tokens are priced at their own rates when the spec declares them\n * and fall back to the input rate otherwise (see `costUsd`).\n *\n * @param id Canonical model id, e.g. `\"gpt-5\"`.\n * @param usage Token counts for the call.\n * @param catalog Catalog to read; defaults to the built-in `DEFAULT_CATALOG`.\n */\nexport function priceCall(id: string, usage: OracleUsage, catalog: Catalog = DEFAULT_CATALOG): number | undefined {\n  const pricing = modelPricing(id, catalog);\n  return pricing ? costUsd(pricing, usage) : undefined;\n}\n\n/**\n * The canonical ids of every model in `catalog` that carries pricing, sorted.\n * Useful for a coverage assertion (\"does our catalog price everything we\n * route to?\") and for rendering a pricing table.\n *\n * @param catalog Catalog to read; defaults to the built-in `DEFAULT_CATALOG`.\n */\nexport function pricedModels(catalog: Catalog = DEFAULT_CATALOG): string[] {\n  return Object.keys(catalog)\n    .filter((id) => catalog[id]?.pricing !== undefined)\n    .sort();\n}\n","import { OdlaAIError, type OracleEvent, type OracleRequest, type OracleUsage } from \"../shape/index\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport type { Provider } from \"../providers/types\";\nimport { totalUsageTokens, type CapacityLease } from \"./capacity\";\nimport { inProviderSpan, type ProviderCallSpan } from \"./telemetry\";\n\n/** Run one provider stream and close its capacity lease and telemetry span even\n * when the consumer cancels iteration before the provider finishes. */\nexport async function* streamProviderCall(input: {\n  provider: Provider;\n  spec: ModelSpec;\n  request: OracleRequest;\n  lease?: CapacityLease;\n  callSpan?: ProviderCallSpan;\n}): AsyncIterable<OracleEvent> {\n  const { provider, spec, request, lease, callSpan } = input;\n  let usage: OracleUsage | undefined;\n  let responseModel: string | undefined;\n  let failure: unknown;\n  let completed = false;\n  const iterator = inProviderSpan(callSpan, () => provider.stream(spec, request)[Symbol.asyncIterator]());\n  try {\n    while (true) {\n      const next = await inProviderSpan(callSpan, () => iterator.next());\n      if (next.done) {\n        completed = true;\n        break;\n      }\n      const event = next.value;\n      if (event.type === \"message_start\") {\n        usage = event.message.usage;\n        responseModel = event.message.model;\n      }\n      if (event.type === \"error\") {\n        const streamError = new Error(\"AI provider stream reported an error.\");\n        streamError.name = event.error.code;\n        failure = streamError;\n      }\n      if (event.type === \"content_block_start\" || event.type === \"content_block_delta\") callSpan?.firstToken();\n      if (event.type === \"message_delta\") usage = event.usage;\n      yield event;\n    }\n  } catch (error) {\n    failure = error;\n    throw error;\n  } finally {\n    if (!completed && failure === undefined) {\n      const cancelled = new Error(\"AI stream consumer stopped before completion.\");\n      cancelled.name = \"cancelled\";\n      failure = cancelled;\n    }\n    if (!completed && iterator.return) {\n      try {\n        await inProviderSpan(callSpan, () => iterator.return!());\n      } catch (error) {\n        failure ??= error;\n      }\n    }\n    await lease?.settle(totalUsageTokens(usage));\n    if (failure !== undefined) callSpan?.fail(failure, failure instanceof OdlaAIError ? failure.usage : undefined);\n    else if (usage) callSpan?.succeed(usage, responseModel);\n    else callSpan?.fail(new Error(\"AI stream ended without usage.\"));\n  }\n}\n","// Provider \"superpowers\" — server-side capabilities beyond plain chat (web\n// search, search grounding, code execution), with typed per-provider config.\n// Carried on ModelSpec so the catalog can describe, display, and diff them;\n// adapters read the config instead of hardcoding tool literals.\n\n/** A model's server-side web-search capability and its provider-native config. */\nexport type WebSearchPower =\n  /** Anthropic web_search server tool; `toolType` is the versioned tool type\n   *  (e.g. \"web_search_20260209\"). */\n  | { type: \"anthropic-web-search\"; toolType: string }\n  /** OpenAI `web_search_options` on search-capable chat models. */\n  | { type: \"openai-web-search\"; contextSize?: \"low\" | \"medium\" | \"high\" }\n  /** Gemini `googleSearch` grounding. */\n  | { type: \"google-search-grounding\" };\n\n/** A model's server-side code-execution capability. Represented for catalog\n *  display/diffing; no request plumbing yet. */\nexport type CodeExecutionPower =\n  | { type: \"anthropic-code-execution\"; toolType: string }\n  | { type: \"google-code-execution\" };\n\n/** Provider server-side capabilities, keyed for ergonomic lookup. Extending\n *  the surface means adding a key here plus a typed per-provider union. */\nexport interface Superpowers {\n  webSearch?: WebSearchPower;\n  codeExecution?: CodeExecutionPower;\n}\n\n/** Provider-native default for the generic `webSearch` capability. */\nexport function defaultWebSearchPower(provider: \"anthropic\" | \"openai\" | \"google\"): WebSearchPower {\n  if (provider === \"anthropic\") return { type: \"anthropic-web-search\", toolType: \"web_search_20260209\" };\n  if (provider === \"openai\") return { type: \"openai-web-search\", contextSize: \"medium\" };\n  return { type: \"google-search-grounding\" };\n}\n","// Live model discovery. A thin top-level entry point over the provider\n// registry: lazy-loads only the requested provider's SDK, reuses its cached\n// client, and returns normalized DiscoveredModel records for catalog diffing.\n\nimport { ConfigError, type ProviderId } from \"../shape/index\";\nimport { getProvider } from \"./registry\";\nimport type { DiscoveredModel } from \"./types\";\n\n/**\n * List a provider's live models via its list-models API, normalized for\n * diffing against a Catalog (join on provider + nativeId). Note that provider\n * listings never include pricing. Throws ConfigError if the resolved provider\n * (e.g. an injected custom adapter) does not implement discovery.\n */\nexport async function listModels(\n  provider: ProviderId,\n  apiKey: string,\n  opts?: { signal?: AbortSignal },\n): Promise<DiscoveredModel[]> {\n  const adapter = await getProvider(provider, apiKey);\n  if (!adapter.listModels) {\n    throw new ConfigError(`Provider \"${provider}\" does not support model discovery (no listModels).`);\n  }\n  return adapter.listModels(opts);\n}\n","// The tool-use agent loop — the \"running\" half of the engine. Given a Persona\n// and an input, it drives model turn → tool execution → model turn until the\n// model stops asking for tools (or a step/refusal limit is hit), and returns the\n// full conversation, an accumulated usage tally, and a trace of tool calls.\n//\n// Provider-agnostic: it speaks only the canonical shape via the Inference facade,\n// so the same persona runs on Claude, GPT, or Gemini unchanged.\n\nimport {\n  addUsage,\n  ConfigError,\n  emptyUsage,\n  extractText,\n  extractToolUses,\n  type OracleContentBlock,\n  type OracleMessage,\n  type OracleResponse,\n  type OracleStopReason,\n  type OracleUsage,\n  type RequestEcho,\n  type ToolResultBlock,\n  type ToolUseBlock,\n} from \"../shape/index\";\nimport { costUsd, type ModelPricing } from \"../shape/pricing\";\nimport type { Inference } from \"../client/init\";\nimport { signalWithDeadline } from \"../client/abort\";\nimport type { Persona } from \"./persona\";\nimport type { ToolDef, ToolOutput } from \"./tools\";\nimport { toOracleTool } from \"./tools\";\nimport { composeSkills } from \"./skill\";\nimport { type TaintLabel, type TaintSet } from \"./taint\";\nimport { applyCompaction, type CompactionPolicy, type CompactionRecord } from \"./compaction\";\nimport { runToolTurn } from \"./tool-turn\";\n\n/** One resolved tool call within a run. */\nexport interface ToolCallRecord {\n  toolUse: ToolUseBlock;\n  output: ToolOutput;\n}\n\nexport interface AgentRunInput {\n  /** A single user turn (convenience). */\n  input?: string | OracleContentBlock[];\n  /** Or an explicit list of messages (takes precedence when both are given). */\n  messages?: OracleMessage[];\n  signal?: AbortSignal;\n  /** Absolute Unix timestamp in milliseconds for model requests and tools. */\n  deadline?: number;\n  /** Run-wide limits. Token limits are evaluated after each provider response;\n   * output allowance also caps the next request's maxTokens. */\n  budget?: AgentRunBudget;\n  /** Clock for per-step timing. Defaults to `Date.now`; inject a fake so a test\n   * can assert exact durations. */\n  now?: () => number;\n  /**\n   * Shorten the conversation when it gets expensive.\n   *\n   * Without one, a run re-sends its whole history every turn, so input cost\n   * grows with the square of its length — which is what stops a long-horizon\n   * goal, not the step limit. See {@link keepRecentExchanges} for a default.\n   */\n  compaction?: CompactionPolicy;\n}\n\n/** Run-wide limits: tool calls stop before effects; token usage stops later turns after provider reporting. */\nexport interface AgentRunBudget {\n  maxInputTokens?: number;\n  maxOutputTokens?: number;\n  maxTotalTokens?: number;\n  maxToolCalls?: number;\n}\n\nexport type StoppedReason = \"end_turn\" | \"max_steps\" | \"refusal\" | \"budget_exhausted\";\n\n\n\n/**\n * One model turn within a run. The aggregate `usage` on `AgentRun` says what a\n * run cost in total; this says where it went — which turn was expensive, which\n * was slow, how many turns it really took, and what the adapter actually sent\n * each time.\n *\n * That last part is why the echo is per-step rather than only on the final\n * response: a run whose third turn quietly lost its reasoning setting is\n * exactly the case `verifyEcho` exists to catch, and a final-turn-only echo\n * cannot see it.\n */\nexport interface StepRecord {\n  /** 1-based turn number; the last one equals `AgentRun.steps`. */\n  index: number;\n  /** Usage for this turn alone, not cumulative. */\n  usage: OracleUsage;\n  /** USD cost of this turn. Absent when the model's pricing is unknown —\n   *  never zero, since unknown pricing is not free. */\n  costUsd?: number;\n  /** Wall-clock milliseconds spent in the provider call. */\n  durationMs: number;\n  /** The provider's stop reason for this turn. */\n  stopReason: OracleStopReason;\n  /** What the adapter actually sent for this turn, when it reported it. */\n  echo?: RequestEcho;\n  /** Tool calls executed in response to this turn, in order. */\n  toolCalls: ToolCallRecord[];\n}\n\nexport interface AgentRun {\n  /** Concatenated text of the final assistant turn. */\n  finalText: string;\n  /** The last assistant response. */\n  response: OracleResponse;\n  /** The full conversation (loaded memory + input + assistant/tool turns). */\n  messages: OracleMessage[];\n  /** Accumulated usage across every model turn. */\n  usage: OracleUsage;\n  /** Number of model turns taken. */\n  steps: number;\n  /** Per-turn breakdown, one entry per model turn, in order. `steps` is its\n   *  length; this is where the cost and time actually went. */\n  trace: StepRecord[];\n  /** Every tool call executed, in order. */\n  toolCalls: ToolCallRecord[];\n  /** Conversation shortenings, in order. Empty when none were needed — which\n   *  is also what it says when no policy was supplied. */\n  compactions: CompactionRecord[];\n  stoppedReason: StoppedReason;\n}\n\n/**\n * Run the tool-use agent loop: model turn → execute requested tools → model turn,\n * until the model stops asking for tools (`end_turn`), refuses (`refusal`), or\n * `persona.maxSteps` (default 8) is hit (`max_steps`). Composes the persona's\n * skills into its tools/system prompt, enforces per-tool taint allowlists, and\n * loads/appends `persona.memory` when set. Returns `{ finalText, response,\n * messages, usage, steps, toolCalls, stoppedReason }`.\n */\nexport async function runAgent(inference: Inference, persona: Persona, input: AgentRunInput): Promise<AgentRun> {\n  validateRunLimits(persona.maxSteps, input.budget);\n  // Fold attached skills into the tool list + system prompt.\n  const { system, tools } = composeSkills(persona.system, persona.tools, persona.skills);\n  const handlerByName = new Map<string, ToolDef>();\n  for (const t of tools) if (t.handler) handlerByName.set(t.name, t);\n\n  // Assemble the starting conversation: memory, then the caller's input.\n  const priorFromMemory = persona.memory ? await persona.memory.load() : [];\n  const startingInput: OracleMessage[] = input.messages\n    ? input.messages\n    : input.input !== undefined\n      ? [{ role: \"user\", content: input.input }]\n      : [];\n  const messages: OracleMessage[] = [...priorFromMemory, ...startingInput];\n  const runStartIndex = messages.length - startingInput.length; // memory boundary for append()\n\n  const usage = emptyUsage();\n  const toolCalls: ToolCallRecord[] = [];\n  const trace: StepRecord[] = [];\n  const compactions: CompactionRecord[] = [];\n  const accumulatedTaint: TaintSet = new Set<TaintLabel>([\"llm_inherited\"]);\n  const maxSteps = persona.maxSteps ?? 8;\n  const runSignal = signalWithDeadline(input.signal, input.deadline);\n  const now = input.now ?? Date.now;\n  const pricing = pricingFor(inference, persona.model);\n\n  let response: OracleResponse | undefined;\n  let stoppedReason: StoppedReason = \"max_steps\";\n  let steps = 0;\n  let attemptedToolCalls = 0;\n\n  while (steps < maxSteps) {\n    steps++;\n    const remainingOutput = remainingOutputTokens(usage, input.budget);\n    const startedAt = now();\n    response = await inference.chat({\n      model: persona.model,\n      system,\n      messages,\n      tools: tools.length > 0 ? tools.map(toOracleTool) : undefined,\n      maxTokens: Math.min(persona.maxTokens ?? 4096, remainingOutput ?? Number.POSITIVE_INFINITY),\n      effort: persona.effort,\n      thinking: persona.thinking,\n      temperature: persona.temperature,\n      webSearch: persona.webSearch,\n      signal: runSignal,\n      deadline: input.deadline,\n    });\n    addUsage(usage, response.usage);\n    // Opened now and mutated as this turn's tools run, so a `break` below still\n    // leaves a complete record for the turn that caused it.\n    const step: StepRecord = {\n      index: steps,\n      usage: response.usage,\n      durationMs: now() - startedAt,\n      stopReason: response.stopReason,\n      ...(pricing ? { costUsd: costUsd(pricing, response.usage) } : {}),\n      ...(response.echo ? { echo: response.echo } : {}),\n      toolCalls: [],\n    };\n    trace.push(step);\n    messages.push({ role: \"assistant\", content: response.content });\n\n    if (response.stopReason === \"refusal\") {\n      stoppedReason = \"refusal\";\n      break;\n    }\n\n    const toolUses = extractToolUses(response.content);\n    if (toolUses.length === 0) {\n      stoppedReason = \"end_turn\";\n      break;\n    }\n    if (budgetExceeded(usage, input.budget)) {\n      stoppedReason = \"budget_exhausted\";\n      messages.push({\n        role: \"user\",\n        content: toolUses.map((toolUse) => errorResult(toolUse.id, \"Run budget exhausted before tool execution.\")),\n      });\n      break;\n    }\n\n    const toolTurn = await runToolTurn({\n      toolUses, handlerByName, accumulatedTaint, signal: runSignal,\n      maxToolCalls: input.budget?.maxToolCalls, attemptedToolCalls,\n    });\n    attemptedToolCalls = toolTurn.attemptedToolCalls;\n    for (const record of toolTurn.records) {\n      toolCalls.push(record);\n      step.toolCalls.push(record); // same object; the per-step view is a slice, not a copy\n    }\n    messages.push({ role: \"user\", content: toolTurn.resultBlocks });\n    if (toolTurn.budgetExhausted) {\n      stoppedReason = \"budget_exhausted\";\n      break;\n    }\n\n    // After the results are appended, not before: the turn that tripped the\n    // limit is the one whose tool output is usually responsible for it, and\n    // compacting first would leave that output to be re-sent anyway.\n    const record = await applyCompaction(messages, input.compaction, steps, response.usage.inputTokens);\n    if (record) compactions.push(record);\n  }\n\n  if (!response) throw new Error(\"runAgent: maxSteps must be at least 1\");\n\n  if (persona.memory) await persona.memory.append(messages.slice(runStartIndex));\n\n  return {\n    finalText: extractText(response.content),\n    response,\n    messages,\n    usage,\n    steps,\n    trace,\n    toolCalls,\n    compactions,\n    stoppedReason,\n  };\n}\n\n/**\n * Pricing for the run's model, for per-step cost — or undefined when it cannot\n * be had.\n *\n * An `Inference` is not obliged to offer a catalog, and at least one real\n * implementation refuses loudly rather than degrade: `@odla/chat-agent`'s\n * brokered inference throws on `catalog` because a worker with no credential\n * has no catalog to offer. Cost is optional trace metadata, so it must never\n * be the reason a run fails — this swallows that refusal and reports no cost,\n * which the trace already models as \"unknown\", never as zero.\n */\nfunction pricingFor(inference: Inference, model: string): ModelPricing | undefined {\n  try {\n    return inference.catalog[model]?.pricing;\n  } catch {\n    return undefined;\n  }\n}\n\nfunction budgetExceeded(usage: OracleUsage, budget: AgentRunBudget | undefined): boolean {\n  if (!budget) return false;\n  if (budget.maxInputTokens !== undefined && usage.inputTokens >= budget.maxInputTokens) return true;\n  if (budget.maxOutputTokens !== undefined && usage.outputTokens >= budget.maxOutputTokens) return true;\n  if (budget.maxTotalTokens !== undefined && usage.inputTokens + usage.outputTokens >= budget.maxTotalTokens) return true;\n  return false;\n}\n\nfunction remainingOutputTokens(usage: OracleUsage, budget: AgentRunBudget | undefined): number | undefined {\n  if (!budget) return undefined;\n  const remaining = [\n    budget.maxOutputTokens === undefined ? undefined : budget.maxOutputTokens - usage.outputTokens,\n    budget.maxTotalTokens === undefined ? undefined : budget.maxTotalTokens - usage.inputTokens - usage.outputTokens,\n  ].filter((value): value is number => value !== undefined);\n  return remaining.length === 0 ? undefined : Math.max(1, Math.min(...remaining));\n}\n\nfunction validateRunLimits(maxSteps: number | undefined, budget: AgentRunBudget | undefined): void {\n  if (maxSteps !== undefined && (!Number.isInteger(maxSteps) || maxSteps < 1)) {\n    throw new ConfigError(\"persona.maxSteps must be a positive integer.\");\n  }\n  if (!budget) return;\n  for (const key of [\"maxInputTokens\", \"maxOutputTokens\", \"maxTotalTokens\"] as const) {\n    const value = budget[key];\n    if (value !== undefined && (!Number.isInteger(value) || value < 1)) {\n      throw new ConfigError(`budget.${key} must be a positive integer.`);\n    }\n  }\n  if (budget.maxToolCalls !== undefined && (!Number.isInteger(budget.maxToolCalls) || budget.maxToolCalls < 0)) {\n    throw new ConfigError(\"budget.maxToolCalls must be a non-negative integer.\");\n  }\n}\n\nfunction errorResult(toolUseId: string, message: string): ToolResultBlock {\n  return { type: \"tool_result\", toolUseId, content: message, isError: true };\n}\n","// Tool definitions for the agent loop. A ToolDef is config-as-data: a name, a\n// description, a JSON-Schema for its input, and an optional local `handler`. A\n// tool without a handler is a provider server tool (e.g. web search) that\n// resolves inside the adapter; a tool with a handler is executed in-process by\n// the loop.\n\nimport type { OracleContentBlock, OracleTool } from \"../shape/index\";\nimport type { TaintLabel, TaintSet } from \"./taint\";\n\n/** What a tool returns after running. */\nexport interface ToolOutput {\n  content: string | OracleContentBlock[];\n  isError?: boolean;\n}\n\n/** Context handed to a tool handler when it runs. */\nexport interface ToolContext {\n  /**\n   * Stable provider-issued identity for this exact tool invocation.\n   *\n   * Agent runs always populate this from the matching `tool_use` block. It is\n   * optional only so existing direct handler callers remain source-compatible;\n   * handlers that use it as an idempotency key should fail closed when absent.\n   */\n  toolCallId?: string;\n  /** The taint currently on the conversation feeding this call. */\n  taint: TaintSet;\n  /** Optional cancellation signal, threaded from the run. */\n  signal?: AbortSignal;\n}\n\nexport type ToolHandler = (\n  input: Record<string, unknown>,\n  ctx: ToolContext,\n) => Promise<ToolOutput> | ToolOutput;\n\nexport interface ToolDef {\n  name: string;\n  description: string;\n  /** JSON Schema for the tool arguments. */\n  inputSchema: Record<string, unknown>;\n  /** Local executor. Omit for provider server tools resolved inside the adapter. */\n  handler?: ToolHandler;\n  /**\n   * Opt in to concurrent execution with adjacent tool calls carrying the same\n   * marker. Omit for effects and for handlers whose ordering is significant.\n   * Results are still returned to the model in request order, and any\n   * unmarked call is an exclusive barrier before and after its execution.\n   */\n  concurrency?: \"parallel\";\n  /** Taint labels this tool's output introduces into the conversation. */\n  outputTaint?: TaintLabel[];\n  /** If set, the tool only runs when the conversation taint ⊆ this allowlist. */\n  acceptsTaint?: TaintLabel[];\n}\n\n/** Project a ToolDef to the wire-level OracleTool the model sees. */\nexport function toOracleTool(t: ToolDef): OracleTool {\n  return { name: t.name, description: t.description, inputSchema: t.inputSchema };\n}\n","// A Skill is a named, reusable bundle of tools plus the instructions that tell a\n// persona how and when to use them. Attaching a skill to a persona is how you\n// \"add a skill and call it as tools\": the skill's tools are merged into the\n// model's tool list, and its instructions are appended to the system prompt.\n// A skill whose tool handlers write to odla-db is how an agent changes data.\n\nimport type { ToolDef } from \"./tools\";\n\nexport interface Skill {\n  /** Skill name — used as the heading for its instructions in the system prompt. */\n  name: string;\n  /** Guidance appended to the persona's system prompt (when/how to use the tools). */\n  instructions?: string;\n  /** The tools this skill contributes to the agent. */\n  tools: ToolDef[];\n}\n\nexport interface ComposedPersona {\n  system: string | undefined;\n  tools: ToolDef[];\n}\n\n/** Merge a persona's own tools/system with its attached skills: skill tools are\n *  appended to the tool list, and each skill's instructions become a titled\n *  section of the system prompt. Order is preserved (persona first, then skills). */\nexport function composeSkills(\n  system: string | undefined,\n  tools: ToolDef[] | undefined,\n  skills: Skill[] | undefined,\n): ComposedPersona {\n  const composedTools: ToolDef[] = [...(tools ?? [])];\n  const sections: string[] = system ? [system] : [];\n  for (const skill of skills ?? []) {\n    composedTools.push(...skill.tools);\n    if (skill.instructions) sections.push(`## ${skill.name}\\n${skill.instructions}`);\n  }\n  return { system: sections.length > 0 ? sections.join(\"\\n\\n\") : undefined, tools: composedTools };\n}\n","// A lightweight CaMeL-style taint layer (after arXiv:2503.18813, the model used\n// by odla-ai-old's chat-engine). Values that entered the conversation from an\n// untrusted source carry a label; a privileged tool (\"sink\") declares which\n// taints it will accept, and the agent loop refuses to run it when the current\n// conversation taint is not a subset of that allowlist. This is the seed of a\n// prompt-injection defense — deliberately minimal in v1 (label + assert), not a\n// full information-flow tracker.\n\nimport { OdlaAIError } from \"../shape/index\";\n\nexport type TaintLabel =\n  | \"web_untrusted\"\n  | \"operator_pasted_untrusted\"\n  | \"llm_inherited\"\n  | `tool_untrusted:${string}`;\n\nexport type TaintSet = Set<TaintLabel>;\n\n/** Build a `TaintSet` from labels — the CaMeL-style taint carried through a run and checked against each tool's allowlist. */\nexport function taint(...labels: TaintLabel[]): TaintSet {\n  return new Set(labels);\n}\n\n/** Raised when a tool's taint allowlist doesn't cover the conversation's taint.\n * Carries the sink, the label it met, and the allowlist, so a caller can say\n * something other than the diagnostic sentence. */\nexport class TaintError extends OdlaAIError {\n  readonly sink: string;\n  readonly label: string;\n  readonly allowed: readonly string[];\n  constructor(input: { sink: string; label: string; allowed: readonly string[] } | string) {\n    const fields = typeof input === \"string\" ? { sink: \"\", label: \"\", allowed: [] as string[] } : input;\n    super(\"invalid_request\", typeof input === \"string\" ? input\n      : `Tool \"${fields.sink}\" refused: conversation carries taint \"${fields.label}\" which is not in its allowlist [${fields.allowed.join(\", \")}].`);\n    this.sink = fields.sink; this.label = fields.label; this.allowed = fields.allowed;\n  }\n}\n\n/** What the model is told when a sink refuses the conversation's taint.\n *\n * Not the diagnostic sentence: a result that says \"refused\" is mirrored by the\n * model as a refusal of the whole task, which the provider then flags as a\n * refusal stop, and the harness ends the session on the second one (Factory\n * card 880bb33a, 2026-09-05, lost fifty-six tool calls of work that way). The\n * model is told the tool is unavailable, why, and what to do instead. */\nexport function taintUnavailableForModel(error: TaintError): string {\n  const accepts = error.allowed.length ? error.allowed.join(\", \") : \"nothing untrusted\";\n  return `Tool \"${error.sink}\" is unavailable for the rest of this conversation: the conversation has read \"${error.label}\" content, which ${error.sink} does not accept (it accepts: ${accepts}). Do not call ${error.sink} again. Continue the task with the tools that remain and put what you meant to send in your closing report.`;\n}\n\n/**\n * Throw unless every label currently on the conversation is in the sink's\n * allowlist. `llm_inherited` is intentionally excludable: a tool that lists it as\n * *not* accepted is one where model-derived instructions must never reach the\n * sink (the classic injected-instruction propagation case).\n */\nexport function assertSinkAcceptsTaint(sink: string, allowed: TaintLabel[], actual: TaintSet): void {\n  const allow = new Set(allowed);\n  for (const label of actual) {\n    if (!allow.has(label)) {\n      throw new TaintError({ sink, label, allowed });\n    }\n  }\n}\n","// Keeping a long run's conversation from becoming its own cost.\n//\n// `runAgent` appends every turn and every tool result to one array and re-sends\n// the whole thing each time, so a run's input cost grows with the SQUARE of its\n// length. Measured on a real repository: one workspace listing returned ~44k\n// tokens and was re-sent on all thirteen remaining turns, against 413 tokens of\n// actual output. A goal that re-attempts twenty times cannot work this way.\n//\n// The loop cannot decide what to drop — only the application knows which tool\n// results still matter — so the policy is injected. What the loop DOES enforce\n// is the invariant a naive policy breaks: every `tool_use` must still be\n// answered by a matching `tool_result`, or the next provider call is a 400.\n\nimport { ConfigError } from \"../shape/index\";\nimport type { OracleContentBlock, OracleMessage } from \"../shape/index\";\n\n/** What the policy is given when the conversation has grown too large. */\nexport interface CompactionInput {\n  /** The conversation as it stands, including the turn that tripped the limit. */\n  messages: OracleMessage[];\n  /** Model turns taken so far. */\n  steps: number;\n  /** Input tokens the provider reported for the most recent turn. */\n  inputTokens: number;\n}\n\n/** How a run shortens its own conversation when it gets expensive. */\nexport interface CompactionPolicy {\n  /**\n   * Compact once a turn's reported input tokens reach this.\n   *\n   * Measured against the provider's report rather than an estimate, because the\n   * number that matters is the one being billed.\n   */\n  whenInputTokensExceed: number;\n  /**\n   * Return a shorter conversation, or `null` when nothing can safely be\n   * dropped.\n   *\n   * `null` rather than a throw: a threshold set below the size of a single\n   * exchange is an ordinary misconfiguration, and it should cost the run its\n   * compaction, not its life.\n   */\n  compact(input: CompactionInput): OracleMessage[] | null | Promise<OracleMessage[] | null>;\n}\n\nconst blocks = (message: OracleMessage): OracleContentBlock[] =>\n  Array.isArray(message.content) ? message.content : [];\n\nconst toolUseIds = (message: OracleMessage): string[] =>\n  blocks(message).flatMap((block) => block.type === \"tool_use\" ? [block.id] : []);\n\nconst toolResultIds = (message: OracleMessage): string[] =>\n  blocks(message).flatMap((block) => block.type === \"tool_result\" ? [block.toolUseId] : []);\n\n/**\n * Reject a compaction that would make the next request invalid.\n *\n * Three ways a policy goes wrong, all of which fail far from here if allowed\n * through: dropping a tool_result but keeping its tool_use (a provider 400),\n * returning nothing (a request with no messages), and returning something no\n * shorter (an infinite compaction loop, since the trigger would still be met).\n */\nexport function assertCompacted(before: OracleMessage[], after: OracleMessage[]): void {\n  if (after.length === 0) throw new ConfigError(\"compaction returned an empty conversation.\");\n  if (after.length >= before.length) {\n    throw new ConfigError(\n      `compaction must shorten the conversation (${before.length} in, ${after.length} out).`,\n    );\n  }\n  const answered = new Set(after.flatMap(toolResultIds));\n  const orphans = after.flatMap(toolUseIds).filter((id) => !answered.has(id));\n  if (orphans.length > 0) {\n    throw new ConfigError(\n      `compaction left ${orphans.length} tool call(s) without a result: ${orphans.slice(0, 3).join(\", \")}.`,\n    );\n  }\n}\n\n/** One conversation-shortening, for the run's own record of what it dropped. */\nexport interface CompactionRecord {\n  /** The turn after which it happened. */\n  afterStep: number;\n  /** Input tokens reported for that turn — what tripped the policy. */\n  inputTokens: number;\n  messagesBefore: number;\n  messagesAfter: number;\n}\n\n/**\n * Shorten `messages` in place when the policy says to, and report what changed.\n *\n * Mutates rather than returns because the loop holds one array across turns and\n * the memory boundary is an index into it; replacing the reference would leave\n * `persona.memory` appending the wrong slice.\n */\nexport async function applyCompaction(\n  messages: OracleMessage[],\n  policy: CompactionPolicy | undefined,\n  steps: number,\n  inputTokens: number,\n): Promise<CompactionRecord | null> {\n  if (!policy || inputTokens < policy.whenInputTokensExceed) return null;\n  const messagesBefore = messages.length;\n  const compacted = await policy.compact({ messages: messages.slice(), steps, inputTokens });\n  // `null` means the policy found nothing safe to drop, which is a normal\n  // answer early in a run. Only a returned conversation is checked.\n  if (!compacted) return null;\n  assertCompacted(messages, compacted);\n  messages.length = 0;\n  messages.push(...compacted);\n  return { afterStep: steps, inputTokens, messagesBefore, messagesAfter: messages.length };\n}\n\n/** An assistant turn and the user turn answering its tool calls, as one unit. */\ninterface Exchange {\n  start: number;\n  end: number;\n  tools: string[];\n}\n\n/**\n * Group the conversation into indivisible exchanges.\n *\n * An assistant turn that asked for tools and the user turn that answered them\n * are one unit: keeping either alone is what produces an orphan.\n */\nfunction exchanges(messages: OracleMessage[], from: number): Exchange[] {\n  const found: Exchange[] = [];\n  for (let index = from; index < messages.length; index++) {\n    const uses = toolUseIds(messages[index]!);\n    if (!uses.length) continue;\n    const next = messages[index + 1];\n    const answers = next ? toolResultIds(next) : [];\n    const paired = uses.every((id) => answers.includes(id));\n    found.push({\n      start: index,\n      end: paired ? index + 1 : index,\n      tools: blocks(messages[index]!).flatMap((b) => b.type === \"tool_use\" ? [b.name] : []),\n    });\n    if (paired) index++;\n  }\n  return found;\n}\n\n/** Options for {@link keepRecentExchanges}. */\nexport interface KeepRecentOptions {\n  /** Trigger, in input tokens reported for one turn. */\n  whenInputTokensExceed: number;\n  /** How many of the most recent tool exchanges to keep in full. Default 3. */\n  keep?: number;\n  /**\n   * How many leading messages are the task itself and must never be dropped.\n   * Default 1 — the user turn that started the run.\n   */\n  preserveLeading?: number;\n}\n\n/**\n * The default policy: keep the task and the most recent exchanges, replace the\n * rest with a note saying what was done.\n *\n * The note is derived, not generated. Summarizing with a model would add a\n * request, a cost, and a failure mode to the very operation whose job is to\n * reduce all three — and for a coding agent the useful content is mechanical\n * anyway: which tools already ran, so the agent does not re-read what it read.\n */\nexport function keepRecentExchanges(options: KeepRecentOptions): CompactionPolicy {\n  const keep = options.keep ?? 3;\n  const preserveLeading = options.preserveLeading ?? 1;\n  if (!Number.isInteger(keep) || keep < 1) throw new ConfigError(\"keep must be a positive integer.\");\n  if (!Number.isInteger(preserveLeading) || preserveLeading < 1) {\n    throw new ConfigError(\"preserveLeading must be a positive integer.\");\n  }\n  return {\n    whenInputTokensExceed: options.whenInputTokensExceed,\n    compact({ messages }) {\n      const all = exchanges(messages, preserveLeading);\n      const dropped = all.slice(0, Math.max(0, all.length - keep));\n      // Fewer exchanges than `keep`, so every one of them is protected. Common\n      // when the threshold is lower than a single tool result — the run carries\n      // on at full size rather than dying over a tuning value.\n      if (!dropped.length) return null;\n      const cut = new Set<number>();\n      const names: string[] = [];\n      for (const exchange of dropped) {\n        for (let index = exchange.start; index <= exchange.end; index++) cut.add(index);\n        names.push(...exchange.tools);\n      }\n      const tally = [...names.reduce(\n        (counts, name) => counts.set(name, (counts.get(name) ?? 0) + 1),\n        new Map<string, number>(),\n      )].map(([name, count]) => (count > 1 ? `${name} ×${count}` : name));\n      const summary: OracleMessage = {\n        role: \"user\",\n        content: [{\n          type: \"text\",\n          text: `[Earlier work in this run was summarized to save context. ${dropped.length} exchange(s) were removed. Tools already run: ${tally.join(\", \")}. Their results are no longer in the conversation — re-run a tool if you need its output again.]`,\n        }],\n      };\n      const kept = messages.filter((_message, index) => !cut.has(index));\n      // Placed where the removed span was, so the surviving tail still reads in\n      // order and the model is told about the gap before it sees what follows.\n      kept.splice(preserveLeading, 0, summary);\n      return kept;\n    },\n  };\n}\n","import {\n  CancelledError,\n  DeadlineExceededError,\n  validateJsonSchema,\n  type ToolResultBlock,\n  type ToolUseBlock,\n} from \"../shape/index\";\nimport { throwIfAborted } from \"../client/abort\";\nimport { assertSinkAcceptsTaint, TaintError, taintUnavailableForModel, type TaintSet } from \"./taint\";\nimport type { ToolDef, ToolOutput } from \"./tools\";\n\ninterface PreparedToolCall {\n  toolUse: ToolUseBlock;\n  def?: ToolDef;\n  output?: ToolOutput;\n}\n\nexport interface ToolTurnRecord {\n  toolUse: ToolUseBlock;\n  output: ToolOutput;\n}\n\nexport interface ToolTurnResult {\n  resultBlocks: ToolResultBlock[];\n  records: ToolTurnRecord[];\n  attemptedToolCalls: number;\n  budgetExhausted: boolean;\n}\n\n/** Execute one model turn's tool calls in ordered, explicitly concurrent waves. */\nexport async function runToolTurn(input: {\n  toolUses: ToolUseBlock[];\n  handlerByName: ReadonlyMap<string, ToolDef>;\n  accumulatedTaint: TaintSet;\n  signal?: AbortSignal;\n  maxToolCalls?: number;\n  attemptedToolCalls: number;\n}): Promise<ToolTurnResult> {\n  let attemptedToolCalls = input.attemptedToolCalls;\n  let budgetExhausted = false;\n  const prepare = (toolUse: ToolUseBlock): PreparedToolCall => {\n    if (input.maxToolCalls !== undefined && attemptedToolCalls >= input.maxToolCalls) {\n      budgetExhausted = true;\n      return { toolUse, output: { content: \"Run tool-call budget exhausted before execution.\", isError: true } };\n    }\n    attemptedToolCalls++;\n    const def = input.handlerByName.get(toolUse.name);\n    if (!def?.handler) {\n      return { toolUse, output: { content: `No local handler for tool \"${toolUse.name}\".`, isError: true } };\n    }\n    const validation = validateJsonSchema(def.inputSchema, toolUse.input);\n    if (validation.valid) return { toolUse, def };\n    const detail = validation.issues.slice(0, 5).map((issue) => `${issue.path} ${issue.message}`).join(\"; \");\n    return {\n      toolUse, def,\n      output: { content: `Tool \"${toolUse.name}\" input is invalid: ${detail}`, isError: true },\n    };\n  };\n\n  const execute = async (call: PreparedToolCall, taint: TaintSet): Promise<ToolOutput> => {\n    if (call.output) return call.output;\n    const def = call.def!;\n    // A refused sink is an ANSWER, not a fault. The point of a capability\n    // system is that the action is denied and the agent carries on with what it\n    // still holds — this module's own contract says the loop \"refuses to run\n    // it\", meaning the tool, not the run.\n    //\n    // Throwing here instead killed whole agents. A Factory sub-agent read its\n    // own task's comments, reached for `move_task`, and lost twenty-six tool\n    // calls and its checkpoint — while the refusal had already prevented\n    // everything it was there to prevent. The kill bought no safety: the taint\n    // does not decay, so every other privileged sink would have refused the\n    // same agent for the same reason. It only destroyed legitimate work.\n    //\n    // The message is ours, not the provider's — it names the tool, the label\n    // and the allowlist and nothing else — so it is safe to hand to the model,\n    // and it is the only way the agent learns to stop trying and report instead.\n    if (def.acceptsTaint) {\n      try { assertSinkAcceptsTaint(def.name, def.acceptsTaint, taint); }\n      catch (error) {\n        if (!(error instanceof TaintError)) throw error;\n        return { content: taintUnavailableForModel(error), isError: true };\n      }\n    }\n    throwIfAborted(input.signal);\n    try {\n      return await def.handler!(call.toolUse.input, {\n        toolCallId: call.toolUse.id,\n        taint: new Set(taint),\n        signal: input.signal,\n      });\n    } catch (error) {\n      if (error instanceof CancelledError || error instanceof DeadlineExceededError) throw error;\n      throwIfAborted(input.signal);\n      // Handler messages can contain credentials or upstream payloads. The\n      // model gets a stable sanitized error; private diagnostics stay local.\n      return { content: `Tool \"${call.toolUse.name}\" failed.`, isError: true };\n    }\n  };\n\n  const resultBlocks: ToolResultBlock[] = [];\n  const records: ToolTurnRecord[] = [];\n  const append = (call: PreparedToolCall, output: ToolOutput): void => {\n    if (call.def) records.push({ toolUse: call.toolUse, output });\n    resultBlocks.push({\n      type: \"tool_result\", toolUseId: call.toolUse.id,\n      content: output.content, isError: output.isError,\n    });\n    for (const label of call.def?.outputTaint ?? []) input.accumulatedTaint.add(label);\n  };\n\n  for (let index = 0; index < input.toolUses.length;) {\n    const first = prepare(input.toolUses[index]!);\n    if (first.output || first.def?.concurrency !== \"parallel\") {\n      append(first, await execute(first, input.accumulatedTaint));\n      index += 1;\n      continue;\n    }\n\n    // Adjacent marked calls overlap. An unmarked call is the exclusive barrier\n    // between this settled wave and the next one.\n    const batch = [first];\n    let next = index + 1;\n    while (next < input.toolUses.length) {\n      const candidate = input.handlerByName.get(input.toolUses[next]!.name);\n      if (candidate?.concurrency !== \"parallel\") break;\n      batch.push(prepare(input.toolUses[next]!));\n      next += 1;\n    }\n    const taint = new Set(input.accumulatedTaint);\n    const outputs = await Promise.all(batch.map((call) => execute(call, taint)));\n    for (let offset = 0; offset < batch.length; offset += 1) append(batch[offset]!, outputs[offset]!);\n    index = next;\n  }\n\n  return { resultBlocks, records, attemptedToolCalls, budgetExhausted };\n}\n","// Pluggable persona memory. A MemoryScope supplies prior conversation context\n// before a run and receives the new turns after it. The default is in-process;\n// an app that wants durable memory (e.g. persisted to odla-db) implements this\n// interface — deliberately kept out of the core so the library has no infra deps.\n\nimport type { OracleMessage } from \"../shape/index\";\n\nexport interface MemoryScope {\n  /** Messages to prepend before this run's input. */\n  load(): Promise<OracleMessage[]> | OracleMessage[];\n  /** Persist the messages produced during this run (excludes what load() returned). */\n  append(messages: OracleMessage[]): Promise<void> | void;\n}\n\n/** A simple process-lifetime memory scope. */\nexport class InMemoryScope implements MemoryScope {\n  private messages: OracleMessage[] = [];\n\n  load(): OracleMessage[] {\n    return [...this.messages];\n  }\n\n  append(messages: OracleMessage[]): void {\n    this.messages.push(...messages);\n  }\n\n  clear(): void {\n    this.messages = [];\n  }\n}\n","// HarnessSpec — a Persona's configuration as *plain serializable data*.\n//\n// A Persona carries `tools: ToolDef[]`, and a ToolDef carries a live `handler`\n// function. That makes a Persona perfectly good to write in TypeScript and\n// impossible to write in YAML, store in a database row, or record in a run\n// trace. Anything that wants to treat \"which harness did this run under?\" as\n// data — a benchmark matrix, a stored experiment, an agent authoring configs —\n// needs the config and the code separated.\n//\n// So: the spec names a toolset, a registry maps names to real ToolDefs, and\n// `toPersona` joins them. Code stays code; configuration stays data.\n\nimport { ConfigError } from \"../shape/index\";\nimport type { Effort, ThinkingMode } from \"../shape/index\";\nimport type { AgentRunBudget } from \"../agent/loop\";\nimport type { Persona } from \"../agent/persona\";\nimport type { ToolDef } from \"../agent/tools\";\n\n/** A fully data-describable agent configuration. Every field is JSON-safe. */\nexport interface HarnessSpec {\n  /** Stable identifier for this configuration (used as the persona name). */\n  id?: string;\n  /** Canonical model id from the catalog. */\n  model: string;\n  system?: string;\n  /** Name of a toolset in the `ToolsetRegistry`. Omit for a tool-less harness. */\n  toolset?: string;\n  /** Enable the provider's server-side web-search tool. */\n  webSearch?: boolean;\n  /** Max model turns before the loop stops. */\n  maxSteps?: number;\n  effort?: Effort;\n  thinking?: ThinkingMode;\n  temperature?: number;\n  /** Max output tokens per model turn. */\n  maxTokens?: number;\n  /** Run-wide token and tool-call limits. */\n  budget?: AgentRunBudget;\n}\n\n/** Named sets of real tools, supplied by the host. The registry is the code\n *  half of the split — it never travels with the spec. */\nexport type ToolsetRegistry = Record<string, ToolDef[]>;\n\n/**\n * Join a `HarnessSpec` to real tools, producing a runnable `Persona`.\n *\n * Throws `ConfigError` when the spec names a toolset the registry does not\n * have. That is deliberate: silently producing a tool-less persona would run\n * happily and score differently, so a typo'd toolset name would corrupt a\n * comparison rather than fail it.\n */\nexport function toPersona(spec: HarnessSpec, registry: ToolsetRegistry = {}): Persona {\n  let tools: ToolDef[] | undefined;\n  if (spec.toolset !== undefined) {\n    const found = registry[spec.toolset];\n    if (!found) {\n      const known = Object.keys(registry).sort().join(\", \") || \"(registry is empty)\";\n      throw new ConfigError(\n        `HarnessSpec names toolset \"${spec.toolset}\", which is not in the registry. Known toolsets: ${known}.`,\n      );\n    }\n    tools = found;\n  }\n\n  const persona: Persona = { name: spec.id ?? spec.model, model: spec.model };\n  if (spec.system !== undefined) persona.system = spec.system;\n  if (tools) persona.tools = tools;\n  if (spec.webSearch !== undefined) persona.webSearch = spec.webSearch;\n  if (spec.maxSteps !== undefined) persona.maxSteps = spec.maxSteps;\n  if (spec.effort !== undefined) persona.effort = spec.effort;\n  if (spec.thinking !== undefined) persona.thinking = spec.thinking;\n  if (spec.temperature !== undefined) persona.temperature = spec.temperature;\n  if (spec.maxTokens !== undefined) persona.maxTokens = spec.maxTokens;\n  return persona;\n}\n","// resolveHarness — ask \"can this model actually run this configuration?\" and\n// get an answer instead of an exception.\n//\n// `validateRequest` already gates capabilities, but it *throws*, which forces a\n// caller planning a large matrix to wrap every combination in try/catch and\n// makes \"unsupported\" indistinguishable from \"bug\". This returns a discriminated\n// union so a planner can mark a cell skipped, with a machine-readable reason,\n// before spending anything.\n//\n// There is deliberately no third \"resolved with adjustments\" variant. A harness\n// either runs as specified or does not run: an adapter that wants to quietly\n// substitute a nearby legal value has nowhere to record that here, and a matrix\n// whose cells were silently adjusted is not a comparison. This is stricter than\n// the SDK's own tolerance on purpose — see `temperature_ignored` below, which\n// the adapters accept and drop, and which callers that care about fidelity need\n// surfaced rather than swallowed.\n\nimport type { Catalog } from \"../catalog/index\";\nimport { DEFAULT_CATALOG } from \"../catalog/index\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport { supportedEffortLevels } from \"../shape/thinking\";\nimport { toolsEffortFor } from \"../providers/openai/request\";\nimport { openaiApiFor } from \"../providers/openai/api\";\nimport type { HarnessSpec } from \"./spec\";\n\n/** Why a harness cannot run as specified. */\nexport type HarnessRejection =\n  /** The catalog has no such model. */\n  | \"unknown_model\"\n  /** The model has no thinking toggle, but the spec asks for `adaptive`. */\n  | \"thinking_unsupported\"\n  /** The model always reasons, but the spec asks for `off`. */\n  | \"thinking_not_disableable\"\n  /** The model does not offer the requested effort level. */\n  | \"effort_unsupported\"\n  /** The spec wants tools; the model cannot call them. */\n  | \"tools_unsupported\"\n  /** The spec wants server-side web search; the model has none. */\n  | \"web_search_unsupported\"\n  /** The model cannot combine function tools with an explicit effort level. */\n  | \"effort_conflicts_with_tools\"\n  /** The adapter would drop the requested temperature on this reasoning model. */\n  | \"temperature_ignored\";\n\n/**\n * The result of `resolveHarness`: either the resolved catalog entry, or a\n * machine-readable `code` plus a human-readable `reason`. There is deliberately\n * no \"resolved with adjustments\" variant — a harness runs as specified or it\n * does not run, so nothing here can express a silent substitution.\n */\nexport type HarnessResolution =\n  | { ok: true; spec: ModelSpec }\n  | { ok: false; code: HarnessRejection; reason: string };\n\n/** Options for `resolveHarness`. */\nexport interface ResolveHarnessOptions {\n  catalog?: Catalog;\n  /** How many tools the harness will send. Defaults to 1 when the spec names a\n   *  toolset, since tool presence changes what some models accept. */\n  toolCount?: number;\n}\n\n/**\n * Decide whether `harness` can run as literally specified on its model.\n *\n * Returns `{ ok: true, spec }` with the resolved catalog entry, or\n * `{ ok: false, code, reason }` naming the incompatibility. Never throws for an\n * unsupported combination — an unknown model is a rejection, not an error — so\n * a planner can enumerate a full matrix and skip the illegal cells loudly.\n */\nexport function resolveHarness(\n  harness: HarnessSpec,\n  opts: ResolveHarnessOptions = {},\n): HarnessResolution {\n  const catalog = opts.catalog ?? DEFAULT_CATALOG;\n  const spec = catalog[harness.model];\n  if (!spec) {\n    return {\n      ok: false,\n      code: \"unknown_model\",\n      reason: `Unknown model \"${harness.model}\".`,\n    };\n  }\n\n  const toolCount = opts.toolCount ?? (harness.toolset !== undefined ? 1 : 0);\n  const caps = spec.capabilities;\n  const control = spec.thinking?.control;\n  const at = `Model \"${spec.id}\" (${spec.provider})`;\n\n  if (toolCount > 0 && !caps.toolUse) {\n    return { ok: false, code: \"tools_unsupported\", reason: `${at} does not support tool use.` };\n  }\n  if (harness.webSearch && !caps.webSearch && !spec.superpowers?.webSearch) {\n    return { ok: false, code: \"web_search_unsupported\", reason: `${at} has no server-side web search.` };\n  }\n\n  if (harness.thinking === \"adaptive\" && (control === \"none\" || (!control && !caps.thinking))) {\n    return { ok: false, code: \"thinking_unsupported\", reason: `${at} has no thinking mode.` };\n  }\n  if (harness.thinking === \"off\" && control === \"always-on\") {\n    return {\n      ok: false,\n      code: \"thinking_not_disableable\",\n      reason: `${at} always reasons; thinking cannot be turned off.`,\n    };\n  }\n\n  if (harness.effort !== undefined) {\n    const levels = supportedEffortLevels(spec);\n    if (!levels.includes(harness.effort)) {\n      return {\n        ok: false,\n        code: \"effort_unsupported\",\n        reason: `${at} does not support effort \"${harness.effort}\". Supported: ${levels.join(\", \") || \"(none)\"}.`,\n      };\n    }\n    // Chat Completions rejects function tools whenever any reasoning effort is\n    // in play on some OpenAI models. Models routed to /v1/responses are exempt:\n    // that endpoint carries both, which is the reason they are routed there.\n    if (\n      toolCount > 0 &&\n      spec.provider === \"openai\" &&\n      openaiApiFor(spec) === \"chat\" &&\n      toolsEffortFor(spec)\n    ) {\n      return {\n        ok: false,\n        code: \"effort_conflicts_with_tools\",\n        reason: `${at} cannot combine function tools with an explicit effort level on chat completions.`,\n      };\n    }\n  }\n\n  // Reasoning-tier models reject sampling params on Chat Completions, so the\n  // Anthropic and OpenAI adapters drop temperature rather than fail. Harmless\n  // for ordinary calls, but a caller that set a temperature and got the model's\n  // default instead is measuring something it did not ask for. Gemini and the\n  // OpenAI Responses endpoint both accept temperature alongside reasoning, so\n  // neither is affected.\n  const dropsTemperature =\n    spec.provider === \"anthropic\" || (spec.provider === \"openai\" && openaiApiFor(spec) === \"chat\");\n  if (harness.temperature !== undefined && caps.effort && dropsTemperature) {\n    return {\n      ok: false,\n      code: \"temperature_ignored\",\n      reason: `${at} is a reasoning-tier model; the adapter drops temperature, so it would not take effect.`,\n    };\n  }\n\n  return { ok: true, spec };\n}\n","// verifyEcho — the differential check: compare what a harness *asked for*\n// against what the adapter *actually sent*.\n//\n// This is the layer that upfront validation cannot replace. `resolveHarness`\n// runs before dispatch and only knows what should happen; the echo is read off\n// the built params and knows what did. Only comparing the two catches a silent\n// substitution introduced below the caller — inside an adapter, or inside a\n// vendor SDK — which is precisely the shape of the bug that had gpt-5.6\n// reasoning by default and quietly breaking every tool-using agent.\n//\n// A run whose echo does not match its intent is not a failed run. It is a run\n// that measured something other than what was requested, which for a comparison\n// is worse: it still produces a plausible number.\n\nimport { nativeEffort as mappedEffort } from \"../shape/thinking\";\nimport type { NativeEffort } from \"../shape/thinking\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport type { RequestEcho } from \"../shape/echo\";\nimport type { HarnessSpec } from \"./spec\";\n\n/** One field where intent and reality disagree. */\nexport interface EchoMismatch {\n  field: \"model\" | \"thinking\" | \"effort\" | \"temperature\" | \"maxTokens\" | \"tools\";\n  /** What the harness asked for, rendered for a human. */\n  intended: string;\n  /** What the adapter actually sent. */\n  actual: string;\n  detail: string;\n}\n\nfunction render(effort: NativeEffort | undefined): string {\n  return effort ? `${effort.param}=${String(effort.value)}` : \"(none sent)\";\n}\n\nfunction sameEffort(a: NativeEffort | undefined, b: NativeEffort | undefined): boolean {\n  if (!a || !b) return a === b;\n  return a.param === b.param && a.value === b.value;\n}\n\n/**\n * Compare a `HarnessSpec` against the `RequestEcho` of the call it produced.\n * Returns every field where the adapter sent something other than what was\n * asked for — an empty array means the request was transmitted faithfully.\n *\n * Fields the harness left unset are not checked, with one exception: an effort\n * knob the harness never requested but the adapter sent anyway is reported,\n * because a cell running with reasoning explicitly disabled is not comparable\n * to cells running on their model's default.\n */\nexport function verifyEcho(\n  harness: HarnessSpec,\n  spec: ModelSpec,\n  echo: RequestEcho,\n): EchoMismatch[] {\n  const out: EchoMismatch[] = [];\n\n  if (echo.nativeModel !== spec.nativeId) {\n    out.push({\n      field: \"model\",\n      intended: spec.nativeId,\n      actual: echo.nativeModel,\n      detail: `Catalog entry \"${spec.id}\" maps to native id \"${spec.nativeId}\", but \"${echo.nativeModel}\" was sent.`,\n    });\n  }\n\n  if (harness.thinking !== undefined) {\n    const wanted = harness.thinking === \"adaptive\";\n    if (echo.thinkingActive !== wanted) {\n      out.push({\n        field: \"thinking\",\n        intended: harness.thinking,\n        actual: echo.thinkingActive ? \"active\" : \"inactive\",\n        detail: `Harness asked for thinking \"${harness.thinking}\" but reasoning was ${echo.thinkingActive ? \"on\" : \"off\"} for this call.`,\n      });\n    }\n  }\n\n  const wantedEffort = harness.effort ? mappedEffort(spec, harness.effort) : undefined;\n  if (harness.effort !== undefined) {\n    if (!sameEffort(wantedEffort, echo.nativeEffort)) {\n      out.push({\n        field: \"effort\",\n        intended: `${harness.effort} → ${render(wantedEffort)}`,\n        actual: render(echo.nativeEffort),\n        detail: `Effort \"${harness.effort}\" should map to ${render(wantedEffort)} on \"${spec.id}\".`,\n      });\n    }\n  } else if (echo.nativeEffort) {\n    out.push({\n      field: \"effort\",\n      intended: \"(model default)\",\n      actual: render(echo.nativeEffort),\n      detail:\n        `The harness requested no effort, but the adapter sent ${render(echo.nativeEffort)}. ` +\n        \"This cell did not run on the model's default and is not comparable to cells that did.\",\n    });\n  }\n\n  if (harness.temperature !== undefined && echo.temperature !== harness.temperature) {\n    out.push({\n      field: \"temperature\",\n      intended: String(harness.temperature),\n      actual: echo.temperature === undefined ? \"(dropped)\" : String(echo.temperature),\n      detail: `Temperature ${harness.temperature} was not applied to this call.`,\n    });\n  }\n\n  // The agent loop legitimately clamps maxTokens down to the remaining output\n  // allowance, so this is only a mismatch when no run budget could have.\n  if (harness.maxTokens !== undefined && harness.budget === undefined && echo.maxTokens !== harness.maxTokens) {\n    out.push({\n      field: \"maxTokens\",\n      intended: String(harness.maxTokens),\n      actual: echo.maxTokens === undefined ? \"(none sent)\" : String(echo.maxTokens),\n      detail: `Harness set maxTokens ${harness.maxTokens}; ${echo.maxTokens ?? \"nothing\"} was sent.`,\n    });\n  }\n\n  if (harness.toolset !== undefined && echo.toolCount === 0) {\n    out.push({\n      field: \"tools\",\n      intended: `toolset \"${harness.toolset}\"`,\n      actual: \"0 tools\",\n      detail: `Harness named a toolset but no tools reached the provider.`,\n    });\n  }\n\n  return out;\n}\n\n/** True when the adapter transmitted the harness faithfully. */\nexport function isFaithful(mismatches: EchoMismatch[]): boolean {\n  return mismatches.length === 0;\n}\n","// The eval harness: run a set of cases through either a Persona (via the agent\n// loop) or a plain model chat, grade each with a Grader, and return a report.\n// A thin, honest harness — run → grade → report — that is the seed of a real\n// conformance/eval suite, not a full framework.\n\nimport {\n  addUsage,\n  emptyUsage,\n  extractText,\n  type OracleContentBlock,\n  type OracleMessage,\n  type OracleResponse,\n  type OracleUsage,\n} from \"../shape/index\";\nimport type { Inference } from \"../client/init\";\nimport { runAgent } from \"../agent/loop\";\nimport type { Persona } from \"../agent/persona\";\nimport type { EvalCase, GradeResult, Grader } from \"./types\";\n\nexport interface EvalResult {\n  case: EvalCase;\n  output: string;\n  grade: GradeResult;\n  response: OracleResponse;\n  usage: OracleUsage;\n}\n\nexport interface EvalReport {\n  total: number;\n  passed: number;\n  failed: number;\n  passRate: number;\n  results: EvalResult[];\n  usage: OracleUsage;\n}\n\nexport interface EvaluateOptions {\n  inference: Inference;\n  cases: EvalCase[];\n  grader: Grader;\n  /** Run each case through this persona (agent loop). Mutually exclusive with model. */\n  persona?: Persona;\n  /** Or run each case as a single chat with this model + system. */\n  model?: string;\n  system?: string;\n  maxTokens?: number;\n  /** Max cases run concurrently (default 5). */\n  concurrency?: number;\n}\n\n/**\n * Eval harness: run each case through a `persona` (agent loop) or a plain `model`\n * chat, grade it with `grader`, and return an `EvalReport` (per-case results,\n * pass/fail counts, passRate, summed usage). Cases run concurrently up to\n * `concurrency` (default 5); throws if neither `persona` nor `model` is given.\n */\nexport async function evaluate(opts: EvaluateOptions): Promise<EvalReport> {\n  if (!opts.persona && !opts.model) {\n    throw new Error(\"evaluate() requires either a persona or a model.\");\n  }\n  const results = await runPool(opts.cases, opts.concurrency ?? 5, (c) => runCase(opts, c));\n\n  const usage = emptyUsage();\n  let passed = 0;\n  for (const r of results) {\n    addUsage(usage, r.usage);\n    if (r.grade.pass) passed++;\n  }\n  const total = results.length;\n  return { total, passed, failed: total - passed, passRate: total ? passed / total : 0, results, usage };\n}\n\nasync function runCase(opts: EvaluateOptions, c: EvalCase): Promise<EvalResult> {\n  const messages = toMessages(c.input);\n\n  let output: string;\n  let response: OracleResponse;\n  let usage: OracleUsage;\n\n  if (opts.persona) {\n    const run = await runAgent(opts.inference, opts.persona, { messages });\n    output = run.finalText;\n    response = run.response;\n    usage = run.usage;\n  } else {\n    response = await opts.inference.chat({\n      model: opts.model!,\n      system: opts.system,\n      messages,\n      maxTokens: opts.maxTokens ?? 1024,\n    });\n    output = extractText(response.content);\n    usage = response.usage;\n  }\n\n  const grade = await opts.grader({ case: c, output, response });\n  return { case: c, output, grade, response, usage };\n}\n\nfunction toMessages(input: EvalCase[\"input\"]): OracleMessage[] {\n  if (Array.isArray(input) && input.length > 0 && \"role\" in (input[0] as object)) {\n    return input as OracleMessage[];\n  }\n  return [{ role: \"user\", content: input as string | OracleContentBlock[] }];\n}\n\n/** Run `fn` over `items` with at most `limit` in flight, preserving input order. */\nasync function runPool<T, R>(items: T[], limit: number, fn: (item: T) => Promise<R>): Promise<R[]> {\n  const results = new Array<R>(items.length);\n  let next = 0;\n  const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {\n    for (;;) {\n      const i = next++;\n      if (i >= items.length) return;\n      results[i] = await fn(items[i]!);\n    }\n  });\n  await Promise.all(workers);\n  return results;\n}\n","// Built-in graders. `exactMatch` / `includes` / `structuredMatch` are pure and\n// offline; `llmJudge` dogfoods the inference core (an Inference facade) to grade\n// open-ended output against `case.expected` treated as a rubric.\n\nimport { extractText } from \"../shape/index\";\nimport type { Inference } from \"../client/init\";\nimport type { Grader } from \"./types\";\n\n/** Pass when trimmed output equals `case.expected` (stringified). */\nexport function exactMatch(): Grader {\n  return ({ case: c, output }) => {\n    const expected = String(c.expected ?? \"\").trim();\n    const pass = output.trim() === expected;\n    return { pass, reason: pass ? \"exact match\" : `expected \"${expected}\", got \"${output.trim()}\"` };\n  };\n}\n\n/** Pass when output contains `case.expected` (case-insensitive by default). */\nexport function includes(opts: { caseInsensitive?: boolean } = {}): Grader {\n  const ci = opts.caseInsensitive ?? true;\n  return ({ case: c, output }) => {\n    const needle = String(c.expected ?? \"\");\n    const hay = ci ? output.toLowerCase() : output;\n    const pass = hay.includes(ci ? needle.toLowerCase() : needle);\n    return { pass, reason: pass ? `contains \"${needle}\"` : `missing \"${needle}\"` };\n  };\n}\n\n/** Pass when output parses as JSON and contains every key/value in\n *  `case.expected` (a recursive subset match). */\nexport function structuredMatch(): Grader {\n  return ({ case: c, output }) => {\n    let actual: unknown;\n    try {\n      actual = JSON.parse(stripFences(output));\n    } catch {\n      return { pass: false, reason: \"output is not valid JSON\" };\n    }\n    const ok = subset(c.expected, actual);\n    return { pass: ok, reason: ok ? \"structural subset match\" : \"output is missing expected fields/values\" };\n  };\n}\n\n/** Grade open-ended output with a judge model. `case.expected` is the rubric.\n *  The judge is asked to return a strict JSON verdict which is tolerantly parsed. */\nexport function llmJudge(opts: { inference: Inference; model: string; extraGuidance?: string }): Grader {\n  return async ({ case: c, output }) => {\n    const rubric = typeof c.expected === \"string\" ? c.expected : JSON.stringify(c.expected);\n    const system =\n      \"You are a strict evaluation judge. Decide whether the CANDIDATE output satisfies the RUBRIC. \" +\n      \"Respond with ONLY a JSON object: {\\\"pass\\\": boolean, \\\"reason\\\": string}. No prose, no code fences.\" +\n      (opts.extraGuidance ? ` ${opts.extraGuidance}` : \"\");\n    const user = `RUBRIC:\\n${rubric}\\n\\nCANDIDATE:\\n${output}`;\n    const res = await opts.inference.chat({\n      model: opts.model,\n      system,\n      messages: [{ role: \"user\", content: user }],\n      maxTokens: 512,\n    });\n    const text = extractText(res.content);\n    try {\n      const verdict = JSON.parse(stripFences(text)) as { pass?: unknown; reason?: unknown };\n      return { pass: Boolean(verdict.pass), reason: typeof verdict.reason === \"string\" ? verdict.reason : undefined };\n    } catch {\n      // Fall back to a lenient keyword read if the judge didn't return clean JSON.\n      const pass = /\\bpass(ed)?\\b|\\btrue\\b|\\byes\\b/i.test(text) && !/\\bfail(ed)?\\b|\\bfalse\\b|\\bno\\b/i.test(text);\n      return { pass, reason: `unparseable judge output: ${text.slice(0, 200)}` };\n    }\n  };\n}\n\nfunction stripFences(s: string): string {\n  return s.replace(/^\\s*```(?:json)?\\s*/i, \"\").replace(/\\s*```\\s*$/i, \"\").trim();\n}\n\n/** Recursive \"is `expected` a subset of `actual`\" check. */\nfunction subset(expected: unknown, actual: unknown): boolean {\n  if (expected === null || typeof expected !== \"object\") return expected === actual;\n  if (Array.isArray(expected)) {\n    if (!Array.isArray(actual) || actual.length < expected.length) return false;\n    return expected.every((e, i) => subset(e, actual[i]));\n  }\n  if (actual === null || typeof actual !== \"object\" || Array.isArray(actual)) return false;\n  const a = actual as Record<string, unknown>;\n  return Object.entries(expected as Record<string, unknown>).every(([k, v]) => subset(v, a[k]));\n}\n","// The odla-db schema odla-ai persists into: three flat, natural-key-keyed\n// entities for conversation memory and agent-run traces. odla-db is\n// schema-optional (attrs are auto-created on write), but pushing this schema\n// makes the `key` attr `unique` so `Lookup` upserts bind to exactly one row.\n//\n// AGENT_SCHEMA is the already-serialized wire shape (generated with @odla-ai/db's\n// `i.schema(...).serialize()`), embedded so provisioning can push it without the\n// consumer needing the schema builder.\n\n/** Entity namespaces odla-ai owns in odla-db (all non-`$`, so no platform clash). */\nexport const NS = {\n  conversation: \"agent_conversation\",\n  message: \"agent_message\",\n  run: \"agent_run\",\n} as const;\n\n/** Serialized odla-db schema (POST to `/app/:id/schema` as `{ schema: AGENT_SCHEMA }`). */\nexport const AGENT_SCHEMA = {\n  entities: {\n    agent_conversation: {\n      attrs: {\n        key: { type: \"string\", unique: true, indexed: true, optional: false },\n        sessionId: { type: \"string\", unique: false, indexed: true, optional: false },\n        title: { type: \"string\", unique: false, indexed: false, optional: true },\n        createdAt: { type: \"date\", unique: false, indexed: true, optional: false },\n        updatedAt: { type: \"date\", unique: false, indexed: true, optional: false },\n      },\n    },\n    agent_message: {\n      attrs: {\n        key: { type: \"string\", unique: true, indexed: true, optional: false },\n        sessionId: { type: \"string\", unique: false, indexed: true, optional: false },\n        seq: { type: \"number\", unique: false, indexed: true, optional: false },\n        role: { type: \"string\", unique: false, indexed: false, optional: false },\n        content: { type: \"string\", unique: false, indexed: false, optional: false },\n        createdAt: { type: \"date\", unique: false, indexed: true, optional: false },\n      },\n    },\n    agent_run: {\n      attrs: {\n        key: { type: \"string\", unique: true, indexed: true, optional: false },\n        sessionId: { type: \"string\", unique: false, indexed: true, optional: false },\n        persona: { type: \"string\", unique: false, indexed: false, optional: true },\n        status: { type: \"string\", unique: false, indexed: true, optional: false },\n        steps: { type: \"number\", unique: false, indexed: false, optional: false },\n        inputTokens: { type: \"number\", unique: false, indexed: false, optional: false },\n        outputTokens: { type: \"number\", unique: false, indexed: false, optional: false },\n        finalText: { type: \"string\", unique: false, indexed: false, optional: true },\n        trace: { type: \"json\", unique: false, indexed: false, optional: false },\n        createdAt: { type: \"date\", unique: false, indexed: true, optional: false },\n      },\n    },\n  },\n  links: {},\n} as const;\n","// An odla-db-backed MemoryScope: persona conversation memory persisted as\n// odla-db records. load() replays prior turns for a session; append() upserts\n// the run's new turns by natural key with a deterministic mutationId (so a\n// retried run doesn't duplicate). Injected with an odla-db client — odla-ai keeps\n// zero runtime dependency on @odla-ai/db.\n\nimport type { OracleMessage, OracleRole } from \"../shape/index\";\nimport type { MemoryScope } from \"../agent/memory\";\nimport type { OdlaDbClient, OdlaOp } from \"./types\";\nimport { NS } from \"./schema\";\n\nexport interface OdlaDbMemoryOptions {\n  db: OdlaDbClient;\n  /** Groups a conversation's turns; stable across runs to accumulate history. */\n  sessionId: string;\n  /** Optional human-readable title stored on the conversation node. */\n  title?: string;\n  /** Override entity namespaces (default NS.message / NS.conversation). */\n  namespaces?: { message?: string; conversation?: string };\n}\n\n/**\n * A `MemoryScope` backed by odla-db. `load()` replays a session's prior turns\n * (ordered by `seq`); `append()` upserts new turns by natural key under a\n * deterministic `mutationId`, so a retried run never duplicates. Takes an\n * injected odla-db client — odla-ai keeps zero runtime dependency on @odla-ai/db.\n */\nexport class OdlaDbMemory implements MemoryScope {\n  private readonly db: OdlaDbClient;\n  private readonly sessionId: string;\n  private readonly title: string | undefined;\n  private readonly msgNs: string;\n  private readonly convNs: string;\n  private loadedCount = 0;\n\n  constructor(opts: OdlaDbMemoryOptions) {\n    this.db = opts.db;\n    this.sessionId = opts.sessionId;\n    this.title = opts.title;\n    this.msgNs = opts.namespaces?.message ?? NS.message;\n    this.convNs = opts.namespaces?.conversation ?? NS.conversation;\n  }\n\n  async load(): Promise<OracleMessage[]> {\n    const res = await this.db.query({\n      [this.msgNs]: { $: { where: { sessionId: this.sessionId }, order: { seq: \"asc\" }, limit: 100_000 } },\n    });\n    const rows = (res[this.msgNs] ?? []) as { seq?: number; role?: string; content?: string }[];\n    this.loadedCount = rows.length;\n    return rows.map((r) => ({ role: (r.role ?? \"user\") as OracleRole, content: parseContent(r.content) }));\n  }\n\n  async append(messages: OracleMessage[]): Promise<void> {\n    if (messages.length === 0) return;\n    const base = this.loadedCount;\n    const now = Date.now();\n\n    const ops: OdlaOp[] = [\n      {\n        t: \"update\",\n        ns: this.convNs,\n        id: { ns: this.convNs, attr: \"key\", value: this.sessionId },\n        attrs: {\n          key: this.sessionId,\n          sessionId: this.sessionId,\n          ...(this.title ? { title: this.title } : {}),\n          ...(base === 0 ? { createdAt: now } : {}),\n          updatedAt: now,\n        },\n      },\n    ];\n\n    messages.forEach((m, i) => {\n      const seq = base + i;\n      const key = `${this.sessionId}:${seq}`;\n      ops.push({\n        t: \"update\",\n        ns: this.msgNs,\n        id: { ns: this.msgNs, attr: \"key\", value: key },\n        attrs: { key, sessionId: this.sessionId, seq, role: m.role, content: JSON.stringify(m.content), createdAt: now },\n      });\n    });\n\n    await this.db.transact(ops, {\n      mutationId: `${this.sessionId}:append:${base}:${base + messages.length}`,\n    });\n    this.loadedCount += messages.length;\n  }\n}\n\n/** Message content was stored as JSON (string | OracleContentBlock[]); restore it. */\nfunction parseContent(raw: string | undefined): OracleMessage[\"content\"] {\n  if (raw === undefined) return \"\";\n  try {\n    return JSON.parse(raw) as OracleMessage[\"content\"];\n  } catch {\n    return raw; // tolerate a plain string that wasn't JSON-encoded\n  }\n}\n","// Persist agent-run traces to odla-db for observability. Each run becomes one\n// `agent_run` record (status, steps, usage, final text, and a JSON trace of tool\n// calls + full message log), upserted by a natural key so a retried write is\n// idempotent.\n\nimport type { AgentRun } from \"../agent/loop\";\nimport type { OdlaDbClient } from \"./types\";\nimport { NS } from \"./schema\";\n\nexport interface PersistRunOptions {\n  db: OdlaDbClient;\n  /** Groups runs (typically the same session as the memory scope). */\n  sessionId: string;\n  personaName?: string;\n  /** Stable id for exactly-once persistence; defaults to `${sessionId}:${now}`. */\n  runId?: string;\n  namespace?: string;\n}\n\n/** Write a run trace; returns the record key. */\nexport async function persistRun(run: AgentRun, opts: PersistRunOptions): Promise<string> {\n  const ns = opts.namespace ?? NS.run;\n  const key = opts.runId ?? `${opts.sessionId}:${Date.now()}`;\n  await opts.db.transact(\n    [\n      {\n        t: \"update\",\n        ns,\n        id: { ns, attr: \"key\", value: key },\n        attrs: {\n          key,\n          sessionId: opts.sessionId,\n          ...(opts.personaName ? { persona: opts.personaName } : {}),\n          status: run.stoppedReason,\n          steps: run.steps,\n          inputTokens: run.usage.inputTokens,\n          outputTokens: run.usage.outputTokens,\n          finalText: run.finalText,\n          trace: {\n            toolCalls: run.toolCalls.map((t) => ({ name: t.toolUse.name, input: t.toolUse.input, output: t.output })),\n            messages: run.messages,\n          },\n          createdAt: Date.now(),\n        },\n      },\n    ],\n    { mutationId: `run:${key}` },\n  );\n  return key;\n}\n\nexport interface QueryRunsOptions {\n  db: OdlaDbClient;\n  sessionId: string;\n  limit?: number;\n  namespace?: string;\n}\n\n/** Read persisted runs for a session, newest first. */\nexport async function queryRuns(opts: QueryRunsOptions): Promise<Record<string, unknown>[]> {\n  const ns = opts.namespace ?? NS.run;\n  const res = await opts.db.query({\n    [ns]: { $: { where: { sessionId: opts.sessionId }, order: { createdAt: \"desc\" }, limit: opts.limit ?? 50 } },\n  });\n  return res[ns] ?? [];\n}\n","// An odla-db-secrets-backed key resolver. BYO provider keys are stored as odla-db\n// secrets (AES-GCM-encrypted at rest, never returned to browser clients) and read\n// at request time with the app key via the read-only `secrets.get`. Wire it in\n// with `init({ resolveKey: odlaDbKeyResolver(db) })`.\n//\n// Storing the keys is a separate, privileged step (an operator/dev token, not the\n// app key) — see `provisionAgentApp` / `putSecret` in ./provision.\n\nimport type { ProviderId } from \"../shape/index\";\nimport type { KeyResolver } from \"../client/keys\";\nimport type { OdlaDbClient } from \"./types\";\n\n/** Default secret name per provider. */\nexport const DEFAULT_SECRET_NAMES: Record<ProviderId, string> = {\n  anthropic: \"anthropic_api_key\",\n  openai: \"openai_api_key\",\n  google: \"google_api_key\",\n};\n\nexport interface OdlaDbKeyResolverOptions {\n  /** Map a provider to its secret name (default `<provider>_api_key`). Use this\n   *  to scope per-end-user keys, e.g. `(p) => \\`${p}_api_key__${userSub}\\``. */\n  secretName?: (provider: ProviderId) => string;\n  /** Cache resolved keys in memory (default true). */\n  cache?: boolean;\n  /** Maximum age for a cached secret (default 60 seconds; 0 disables caching).\n   * This bounds provider-key rotation propagation in warm isolates. */\n  ttlMs?: number;\n  /** Version included in the cache key. Change it to invalidate a known key\n   * generation immediately without waiting for the TTL. */\n  cacheVersion?: string | ((provider: ProviderId) => string);\n}\n\n/** Build a KeyResolver that reads provider keys from odla-db secrets. A missing\n *  secret resolves to `undefined` (→ that provider is simply unavailable, and\n *  odla-ai throws its own ConfigError) rather than surfacing odla-db's 404. */\nexport function odlaDbKeyResolver(db: OdlaDbClient, opts: OdlaDbKeyResolverOptions = {}): KeyResolver {\n  const nameFor = opts.secretName ?? ((p: ProviderId) => DEFAULT_SECRET_NAMES[p]);\n  const ttlMs = opts.cache === false ? 0 : Math.max(0, opts.ttlMs ?? 60_000);\n  const cache = new Map<ProviderId, { version: string; value: string; expiresAt: number }>();\n\n  return async (provider: ProviderId): Promise<string | undefined> => {\n    const version = typeof opts.cacheVersion === \"function\" ? opts.cacheVersion(provider) : (opts.cacheVersion ?? \"\");\n    if (ttlMs > 0) {\n      const hit = cache.get(provider);\n      if (hit?.version === version && hit.expiresAt > Date.now()) return hit.value;\n      cache.delete(provider); // expiry/version change releases the prior secret\n    }\n    try {\n      const key = await db.secrets.get(nameFor(provider));\n      if (ttlMs > 0) cache.set(provider, { version, value: key, expiresAt: Date.now() + ttlMs });\n      return key;\n    } catch (error) {\n      if (isMissingSecret(error)) return undefined;\n      throw error;\n    }\n  };\n}\n\n/** Only absence maps to \"provider unavailable\". Auth, transport, and server\n * failures must remain visible instead of being misreported as missing config. */\nfunction isMissingSecret(error: unknown): boolean {\n  if (!error || typeof error !== \"object\") return false;\n  const rec = error as Record<string, unknown>;\n  if (rec.status === 404 || rec.statusCode === 404 || rec.code === \"not_found\") return true;\n  const message = error instanceof Error ? error.message : \"\";\n  return /\\b404\\b/.test(message);\n}\n","// Platform wiring for both platform-hosted inference and legacy BYOK apps.\n// Public config chooses the mode and model catalog. Hosted calls authenticate\n// with the app's existing backend key; BYOK calls resolve provider secrets from\n// the app's odla-db tenant as before.\n\nimport { ConfigError, ProviderError, type ProviderId } from \"../shape/index\";\nimport { init, type Ai, type InitOptions } from \"../client/init\";\nimport { DEFAULT_CATALOG, resolveModel, type Catalog } from \"../catalog/index\";\nimport { odlaDbKeyResolver, DEFAULT_SECRET_NAMES, type OdlaDbKeyResolverOptions } from \"./keys\";\nimport { HostedProvider } from \"./hosted-provider\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport type { OdlaDbClient } from \"./types\";\n\nexport interface InitFromPlatformOptions {\n  /** Platform base URL (e.g. \"https://odla.ai\"). */\n  platform: string;\n  /** The Registry app id, not the environment's database tenant id. */\n  appId: string;\n  /** Which environment's config to use (\"dev\", \"prod\", ...). */\n  env: string;\n  /** Existing backend app key. Required only for hosted mode. */\n  appKey?: string;\n  /** Tenant client used to resolve provider secrets in BYOK mode. */\n  db?: OdlaDbClient;\n  /** Transport override (tests / non-global fetch). */\n  fetch?: typeof fetch;\n  /** public-config cache TTL in ms (default 60s; 0 disables caching). */\n  ttlMs?: number;\n  /** Extra init() options. Platform routing still owns the active catalog and\n   * hosted provider transports. */\n  initOptions?: Omit<InitOptions, \"resolveKey\">;\n  /** BYOK secret resolver cache controls. */\n  keyResolverOptions?: OdlaDbKeyResolverOptions;\n}\n\nexport interface PlatformAi {\n  ai: Ai;\n  mode: \"hosted\" | \"byok\";\n  provider: ProviderId;\n  model?: string;\n  /** Registry service-config revision selecting this mode/model. */\n  revision: number;\n  /** Hosted model-policy revision, when hosted mode is active. */\n  policyRevision?: number;\n}\n\ninterface ByokConfig {\n  mode: \"byok\";\n  provider: ProviderId;\n  model?: string;\n  revision: number;\n}\n\ninterface HostedConfig {\n  mode: \"hosted\";\n  model?: string;\n  revision: number;\n  policyRevision: number;\n  models: ModelSpec[];\n}\n\ntype PlatformConfig = ByokConfig | HostedConfig;\ninterface CacheEntry { value: PlatformConfig; expiresAt: number }\nconst cache = new Map<string, CacheEntry>();\n\n/** Drop all cached platform configs (tests, or to force an immediate refetch). */\nexport function clearPlatformAiCache(): void {\n  cache.clear();\n}\n\ninterface PublicConfig {\n  ai?: {\n    mode?: unknown;\n    enabled?: unknown;\n    provider?: unknown;\n    model?: unknown;\n    models?: unknown;\n    revision?: unknown;\n    policyRevision?: unknown;\n  } | null;\n}\n\nasync function fetchAiConfig(opts: InitFromPlatformOptions): Promise<PlatformConfig> {\n  const doFetch = opts.fetch ?? fetch;\n  const base = opts.platform.replace(/\\/$/, \"\");\n  const url = `${base}/registry/apps/${encodeURIComponent(opts.appId)}/public-config?env=${encodeURIComponent(opts.env)}`;\n  const res = await doFetch(url);\n  if (!res.ok) throw new ProviderError(`platform public-config fetch failed: ${res.status} for ${opts.appId}/${opts.env}`);\n  const cfg = (await res.json()) as PublicConfig;\n  const ai = cfg.ai;\n  if (!ai) throw notConfigured(opts);\n  const revision = validRevision(ai.revision, \"service\", opts);\n  if (ai.mode === \"hosted\") {\n    if (ai.enabled !== true) throw new ConfigError(`hosted ai is disabled for \"${opts.appId}\" (${opts.env}).`);\n    if (!Array.isArray(ai.models) || !ai.models.every(isModelSpec)) {\n      throw new ConfigError(`platform hosted ai catalog is invalid for \"${opts.appId}\" (${opts.env}).`);\n    }\n    const policyRevision = validRevision(ai.policyRevision, \"policy\", opts);\n    const model = typeof ai.model === \"string\" && ai.model ? ai.model : undefined;\n    return { mode: \"hosted\", models: ai.models, revision, policyRevision, ...(model ? { model } : {}) };\n  }\n  // No mode is the backwards-compatible BYOK public shape.\n  if (ai.mode !== undefined && ai.mode !== \"byok\") throw notConfigured(opts);\n  if (typeof ai.provider !== \"string\" || !(ai.provider in DEFAULT_SECRET_NAMES)) {\n    throw new ConfigError(`platform ai config names unknown provider \"${String(ai.provider)}\" for \"${opts.appId}\" (${opts.env}).`);\n  }\n  const model = typeof ai.model === \"string\" && ai.model ? ai.model : undefined;\n  return { mode: \"byok\", provider: ai.provider as ProviderId, revision, ...(model ? { model } : {}) };\n}\n\n/** Build an `Ai` from the app's attested platform configuration. */\nexport async function initFromPlatform(opts: InitFromPlatformOptions): Promise<PlatformAi> {\n  const ttl = opts.ttlMs ?? 60_000;\n  const key = `${opts.platform}|${opts.appId}|${opts.env}`;\n  const now = Date.now();\n  const hit = ttl > 0 ? cache.get(key) : undefined;\n  const config = hit && hit.expiresAt > now ? hit.value : await fetchAiConfig(opts);\n  if (ttl > 0 && (!hit || hit.expiresAt <= now)) cache.set(key, { value: config, expiresAt: now + ttl });\n\n  if (config.mode === \"hosted\") return initHosted(opts, config);\n  if (!opts.db) throw new ConfigError(`platform BYOK ai requires a tenant db client for \"${opts.appId}\" (${opts.env}).`);\n  const sourceCatalog = opts.initOptions?.catalog ?? DEFAULT_CATALOG;\n  const catalog: Catalog = Object.fromEntries(\n    Object.entries(sourceCatalog).filter(([, spec]) => spec.provider === config.provider),\n  );\n  const defaultModel = config.model ?? opts.initOptions?.defaultModel;\n  if (defaultModel) resolveModel(catalog, defaultModel);\n  return {\n    ai: init({\n      ...opts.initOptions,\n      catalog,\n      resolveKey: odlaDbKeyResolver(opts.db, opts.keyResolverOptions),\n      defaultModel,\n    }),\n    mode: \"byok\",\n    provider: config.provider,\n    ...(config.model ? { model: config.model } : {}),\n    revision: config.revision,\n  };\n}\n\nfunction initHosted(opts: InitFromPlatformOptions, config: HostedConfig): PlatformAi {\n  if (!opts.appKey?.startsWith(\"odla_sk_\")) {\n    throw new ConfigError(`platform hosted ai requires the app's backend key for \"${opts.appId}\" (${opts.env}).`);\n  }\n  const catalog: Catalog = Object.fromEntries(config.models.map((model) => [model.id, model]));\n  const defaultModel = config.model ?? opts.initOptions?.defaultModel;\n  if (!defaultModel) {\n    throw new ConfigError(`platform hosted ai has no default model for \"${opts.appId}\" (${opts.env}).`);\n  }\n  const defaultSpec = resolveModel(catalog, defaultModel);\n  // Bind the default: a bare `fetch` reference handed to another object is one\n  // property call away from losing its receiver (see HostedProvider.request).\n  const doFetch = opts.fetch ?? globalThis.fetch.bind(globalThis);\n  const providers = Object.fromEntries(\n    [...new Set(config.models.map((model) => model.provider))].map((provider) => [\n      provider,\n      new HostedProvider({\n        platform: opts.platform,\n        appId: opts.appId,\n        env: opts.env,\n        appKey: opts.appKey!,\n        fetch: doFetch,\n        provider,\n      }),\n    ]),\n  );\n  return {\n    ai: init({ ...opts.initOptions, catalog, providers, defaultModel }),\n    mode: \"hosted\",\n    provider: defaultSpec.provider,\n    ...(config.model ? { model: config.model } : {}),\n    revision: config.revision,\n    policyRevision: config.policyRevision,\n  };\n}\n\nfunction validRevision(value: unknown, name: string, opts: InitFromPlatformOptions): number {\n  if (!Number.isSafeInteger(value) || Number(value) < 0) {\n    throw new ConfigError(`platform ai config has no valid ${name} revision for \"${opts.appId}\" (${opts.env}).`);\n  }\n  return Number(value);\n}\n\nfunction isModelSpec(value: unknown): value is ModelSpec {\n  if (!value || typeof value !== \"object\" || Array.isArray(value)) return false;\n  const model = value as Partial<ModelSpec>;\n  return typeof model.id === \"string\" && Boolean(model.id)\n    && typeof model.nativeId === \"string\" && Boolean(model.nativeId)\n    && (model.provider === \"openai\" || model.provider === \"anthropic\" || model.provider === \"google\")\n    && Boolean(model.capabilities) && typeof model.capabilities === \"object\";\n}\n\nfunction notConfigured(opts: InitFromPlatformOptions): ConfigError {\n  return new ConfigError(\n    `ai service is not enabled/configured for \"${opts.appId}\" (${opts.env}) — enable it in Studio or via @odla-ai/apps setAi().`,\n  );\n}\n","import { signalWithDeadline } from \"../client/abort\";\nimport type { ModelSpec } from \"../shape/capabilities\";\nimport {\n  CancelledError,\n  ConfigError,\n  DeadlineExceededError,\n  OdlaAIError,\n  ProviderError,\n  type OracleErrorType,\n  type OracleErrorShape,\n  type OracleEvent,\n  type OracleRequest,\n  type OracleResponse,\n  type ProviderId,\n} from \"../shape/index\";\nimport type { Provider } from \"../providers/types\";\n\nconst RETRYABLE_STATUS = new Set([502, 503, 504]);\nconst MAX_EVENT_BYTES = 1024 * 1024;\n\nexport interface HostedProviderOptions {\n  platform: string;\n  appId: string;\n  env: string;\n  appKey: string;\n  fetch: typeof fetch;\n  provider: ProviderId;\n}\n\n/** Provider adapter backed by the Registry's app-key-authenticated broker. */\nexport class HostedProvider implements Provider {\n  readonly id: ProviderId;\n\n  constructor(private readonly opts: HostedProviderOptions) {\n    this.id = opts.provider;\n  }\n\n  async create(_spec: ModelSpec, req: OracleRequest): Promise<OracleResponse> {\n    const response = await this.request(\"chat\", req);\n    return await response.json() as OracleResponse;\n  }\n\n  async *stream(_spec: ModelSpec, req: OracleRequest): AsyncIterable<OracleEvent> {\n    const response = await this.request(\"stream\", req);\n    if (!response.body) throw new ProviderError(\"hosted AI stream returned no response body.\");\n    const reader = response.body.getReader();\n    const decoder = new TextDecoder();\n    let pending = \"\";\n    const isSse = response.headers.get(\"content-type\")?.includes(\"text/event-stream\") === true;\n    while (true) {\n      const part = await reader.read();\n      pending += decoder.decode(part.value, { stream: !part.done });\n      if (new TextEncoder().encode(pending).byteLength > MAX_EVENT_BYTES && !pending.includes(\"\\n\")) {\n        await reader.cancel();\n        throw new ProviderError(\"hosted AI stream event exceeded the SDK limit.\");\n      }\n      if (isSse) {\n        const frames = pending.split(/\\r?\\n\\r?\\n/);\n        pending = frames.pop() ?? \"\";\n        for (const frame of frames) {\n          const event = parseSseEvent(frame);\n          if (event) yield event;\n        }\n      } else {\n        const lines = pending.split(\"\\n\");\n        pending = lines.pop() ?? \"\";\n        for (const line of lines) {\n          if (line.trim()) yield parseEvent(line);\n        }\n      }\n      if (part.done) break;\n    }\n    if (pending.trim()) {\n      const event = isSse ? parseSseEvent(pending) : parseEvent(pending);\n      if (event) yield event;\n    }\n  }\n\n  private async request(operation: \"chat\" | \"stream\", req: OracleRequest): Promise<Response> {\n    if (req.providerExtras !== undefined) {\n      throw new ConfigError(\"providerExtras is unavailable with platform-hosted AI.\");\n    }\n    const signal = signalWithDeadline(req.signal, req.deadline);\n    const call = { ...req } as Record<string, unknown>;\n    delete call.signal;\n    delete call.deadline;\n    const idempotencyKey = `odla:${operation}:${crypto.randomUUID()}`;\n    const url = `${this.opts.platform.replace(/\\/$/, \"\")}/registry/apps/${encodeURIComponent(this.opts.appId)}/ai/${operation}?env=${encodeURIComponent(this.opts.env)}`;\n    let response: Response | undefined;\n    for (let attempt = 0; attempt < 2; attempt += 1) {\n      try {\n        // Called through a local, never as `this.opts.fetch(...)`. A property\n        // call sets the receiver to the options object, and Cloudflare's global\n        // fetch refuses a foreign receiver with \"Illegal invocation\" — thrown\n        // before any request, so hosted init looks healthy and the first\n        // inference dies. Binding at the seam is not enough on its own: a\n        // caller may pass an unbound function in.\n        const send = this.opts.fetch;\n        response = await send(url, {\n          method: \"POST\",\n          headers: {\n            authorization: `Bearer ${this.opts.appKey}`,\n            \"content-type\": \"application/json\",\n            \"idempotency-key\": idempotencyKey,\n            ...(operation === \"stream\" ? { accept: \"text/event-stream\" } : {}),\n          },\n          body: JSON.stringify(call),\n          signal,\n        });\n      } catch (error) {\n        if (attempt === 0 && !signal?.aborted) continue;\n        throw transportError(error, signal, req.deadline);\n      }\n      if (!RETRYABLE_STATUS.has(response.status) || attempt === 1) break;\n    }\n    if (!response) throw new ProviderError(\"hosted AI request returned no response.\");\n    if (!response.ok) throw await responseError(response);\n    return response;\n  }\n}\n\nfunction parseSseEvent(frame: string): OracleEvent | undefined {\n  const lines = frame.split(/\\r?\\n/);\n  const name = lines.find((line) => line.startsWith(\"event:\"))?.slice(6).trim() ?? \"message\";\n  const data = lines.filter((line) => line.startsWith(\"data:\"))\n    .map((line) => line.slice(5).trimStart()).join(\"\\n\");\n  if (!data) return undefined;\n  if (name === \"receipt\") {\n    try {\n      return { type: \"receipt\", receipt: JSON.parse(data) } as OracleEvent;\n    } catch (error) {\n      throw new ProviderError(\"hosted AI stream returned an invalid receipt event.\", { cause: error });\n    }\n  }\n  if (name === \"oracle\") return parseEvent(data);\n  if (name === \"error\") {\n    try {\n      return { type: \"error\", error: JSON.parse(data) as OracleErrorShape };\n    } catch (error) {\n      throw new ProviderError(\"hosted AI stream returned an invalid error event.\", { cause: error });\n    }\n  }\n  throw new ProviderError(`hosted AI stream returned unsupported SSE event \"${name}\".`);\n}\n\nfunction parseEvent(line: string): OracleEvent {\n  try {\n    const value = JSON.parse(line) as OracleEvent;\n    if (!value || typeof value !== \"object\" || typeof value.type !== \"string\") throw new Error(\"invalid event\");\n    return value;\n  } catch (error) {\n    throw new ProviderError(\"hosted AI stream returned an invalid event.\", { cause: error });\n  }\n}\n\nasync function responseError(response: Response): Promise<OdlaAIError> {\n  const body = await response.json().catch(() => null) as { error?: { code?: unknown; message?: unknown } } | null;\n  const code = typeof body?.error?.code === \"string\" ? body.error.code : \"hosted_ai_failed\";\n  const message = typeof body?.error?.message === \"string\" ? body.error.message : `hosted AI returned ${response.status}.`;\n  const retryAfter = Number(response.headers.get(\"retry-after\"));\n  const type: OracleErrorType = response.status === 401\n    ? \"auth\"\n    : response.status === 429\n      ? \"rate_limit\"\n      : response.status === 400 || response.status === 413\n        ? \"invalid_request\"\n        : response.status === 403 || response.status === 409\n          ? \"config\"\n          : \"provider_error\";\n  return new OdlaAIError(type, `${code}: ${message}`, {\n    providerStatus: response.status,\n    ...(Number.isFinite(retryAfter) && retryAfter > 0 ? { retryAfter } : {}),\n  });\n}\n\nfunction transportError(error: unknown, signal: AbortSignal | undefined, deadline: number | undefined): OdlaAIError {\n  if (signal?.aborted) {\n    return deadline !== undefined && Date.now() >= deadline\n      ? new DeadlineExceededError(undefined, { cause: error })\n      : new CancelledError(undefined, { cause: error });\n  }\n  return error instanceof ConfigError || error instanceof OdlaAIError\n    ? error\n    : new ProviderError(\"hosted AI transport failed.\", { cause: error });\n}\n","// Provisioning helpers — the \"stand up a new agent app\" flow, mirroring odla-db's\n// handshake model. These are plain `fetch` calls (no @odla-ai/db dependency)\n// against a human-supplied odla platform endpoint that proxies the db operator\n// routes, authenticated with an **operator or developer token** (the platform\n// `ADMIN_SECRET`, or an `odla_dev_...` token from\n// `@odla-ai/db`'s `requestToken(...)` device handshake) — NOT an app key.\n//\n// The typical agent flow:\n//   1. `const { token } = await requestToken({ endpoint, email, onCode })`  // from @odla-ai/db\n//   2. `const { appId, appKey } = await provisionAgentApp({ endpoint, token, providerKeys })`\n//   3. `const db = init({ appId, adminToken: appKey, endpoint })`      // @odla-ai/db client\n//   4. `const ai = init({ resolveKey: odlaDbKeyResolver(db) })`        // keys from secrets\n//      `persona.memory = new OdlaDbMemory({ db, sessionId })`\n//\n// Storing a secret needs the operator/dev token; reading it back at request time\n// needs only the app key (via odlaDbKeyResolver).\n\nimport { AuthError, ConfigError, ProviderError, type ProviderId } from \"../shape/index\";\nimport { redact } from \"../client/keys\";\nimport { AGENT_SCHEMA } from \"./schema\";\nimport { DEFAULT_SECRET_NAMES } from \"./keys\";\n\ntype FetchLike = typeof fetch;\n\nexport interface ProvisionContext {\n  /** Platform origin exposing the proxied db operator routes, normally https://odla.ai. */\n  endpoint: string;\n  /** Operator `ADMIN_SECRET` or an `odla_dev_...` developer token (owns the app). */\n  token: string;\n  fetch?: FetchLike;\n}\n\nasync function post(ctx: ProvisionContext, path: string, body: unknown): Promise<Record<string, unknown>> {\n  const f = ctx.fetch ?? fetch;\n  const res = await f(`${ctx.endpoint.replace(/\\/$/, \"\")}${path}`, {\n    method: \"POST\",\n    headers: { authorization: `Bearer ${ctx.token}`, \"content-type\": \"application/json\" },\n    body: JSON.stringify(body),\n  });\n  if (!res.ok) throw errorFor(res.status, await safeText(res), path);\n  return (await res.json().catch(() => ({}))) as Record<string, unknown>;\n}\n\nasync function postWithKey(ctx: { endpoint: string; fetch?: FetchLike }, path: string, appKey: string, body: unknown): Promise<Record<string, unknown>> {\n  const f = ctx.fetch ?? fetch;\n  const res = await f(`${ctx.endpoint.replace(/\\/$/, \"\")}${path}`, {\n    method: \"POST\",\n    headers: { authorization: `Bearer ${appKey}`, \"content-type\": \"application/json\" },\n    body: JSON.stringify(body),\n  });\n  if (!res.ok) throw errorFor(res.status, await safeText(res), path);\n  return (await res.json().catch(() => ({}))) as Record<string, unknown>;\n}\n\n/** Create an app (owned by the token's developer). Returns its id. */\nexport async function createApp(ctx: ProvisionContext, opts: { appId?: string; name?: string } = {}): Promise<string> {\n  const body: Record<string, unknown> = {};\n  if (opts.appId) body.appId = opts.appId;\n  if (opts.name) body.name = opts.name;\n  const json = await post(ctx, \"/admin/apps\", body);\n  const appId = (json.appId ?? json.id ?? (json.app as { appId?: string } | undefined)?.appId ?? opts.appId) as string | undefined;\n  if (!appId) throw new ProviderError(\"[odla-db] createApp: response did not include an appId\");\n  return appId;\n}\n\n/** Mint a per-app `odla_sk_...` key (shown once). */\nexport async function mintAppKey(ctx: ProvisionContext, appId: string): Promise<string> {\n  const json = await post(ctx, `/admin/apps/${encodeURIComponent(appId)}/keys`, {});\n  const key = json.key as string | undefined;\n  if (!key) throw new ProviderError(\"[odla-db] mintAppKey: response did not include a key\");\n  return key;\n}\n\n/** Push odla-ai's agent memory/run schema (authenticated with the app key). */\nexport async function pushAgentSchema(ctx: { endpoint: string; fetch?: FetchLike }, appId: string, appKey: string): Promise<void> {\n  await postWithKey(ctx, `/app/${encodeURIComponent(appId)}/schema`, appKey, { schema: AGENT_SCHEMA });\n}\n\n/** Store a named secret (operator/dev token). Value must be a non-`$` string. */\nexport async function putSecret(ctx: ProvisionContext, appId: string, name: string, value: string): Promise<void> {\n  await post(ctx, `/admin/apps/${encodeURIComponent(appId)}/secrets`, { name, value });\n}\n\n/** Per-namespace CEL permission rules (odla-db is DEFAULT-DENY: end-users can't\n * read or write any namespace until its rules are set; the app key bypasses\n * rules, so agent-only apps work without them). */\nexport type AppRules = Record<string, { view?: string; create?: string; update?: string; delete?: string }>;\n\n/** Install permission rules (operator/dev token). Replaces the app's rule set. */\nexport async function putRules(ctx: ProvisionContext, appId: string, rules: AppRules): Promise<void> {\n  await post(ctx, `/app/${encodeURIComponent(appId)}/admin/rules`, rules);\n}\n\nexport interface ProvisionAgentAppOptions extends ProvisionContext {\n  appId?: string;\n  appName?: string;\n  /** Provider keys to store as odla-db secrets (read later via odlaDbKeyResolver). */\n  providerKeys?: Partial<Record<ProviderId, string>>;\n  /** Map a provider to its secret name (default `<provider>_api_key`). */\n  secretName?: (provider: ProviderId) => string;\n  /** Push the agent schema (default true). */\n  pushSchema?: boolean;\n  /** Permission rules to install. odla-db is default-deny, so set these for any\n   * namespace end-users should reach (e.g. own-rows-only:\n   * `{ todos: { view: \"auth.id == data.ownerId\", create: \"auth.id == data.ownerId\" } }`).\n   * Omit for agent-only apps — the app key bypasses rules. */\n  rules?: AppRules;\n}\n\nexport interface ProvisionedApp {\n  appId: string;\n  /** The minted `odla_sk_...` app key — pass as `adminToken` to `@odla-ai/db`'s init. */\n  appKey: string;\n}\n\n/** One call to stand up an agent app: create → mint key → push schema → store\n *  provider keys as secrets. Returns the appId + app key for the runtime client. */\nexport async function provisionAgentApp(opts: ProvisionAgentAppOptions): Promise<ProvisionedApp> {\n  const ctx: ProvisionContext = { endpoint: opts.endpoint, token: opts.token, fetch: opts.fetch };\n  const appId = await createApp(ctx, { appId: opts.appId, name: opts.appName });\n  const appKey = await mintAppKey(ctx, appId);\n\n  if (opts.pushSchema !== false) {\n    await pushAgentSchema({ endpoint: opts.endpoint, fetch: opts.fetch }, appId, appKey);\n  }\n\n  if (opts.rules) {\n    await putRules(ctx, appId, opts.rules);\n  }\n\n  const nameFor = opts.secretName ?? ((p: ProviderId) => DEFAULT_SECRET_NAMES[p]);\n  for (const [provider, value] of Object.entries(opts.providerKeys ?? {})) {\n    if (!value) continue;\n    await putSecret(ctx, appId, nameFor(provider as ProviderId), value);\n  }\n\n  return { appId, appKey };\n}\n\nfunction errorFor(status: number, text: string, path: string): Error {\n  const msg = redact(`[odla-db] ${path} → ${status} ${text}`.trim());\n  if (status === 401 || status === 403) return new AuthError(msg, { providerStatus: status });\n  if (status === 501) return new ConfigError(`${msg} (secrets/feature not enabled on the odla-db worker)`);\n  if (status === 400) return new ConfigError(msg);\n  return new ProviderError(msg, { providerStatus: status });\n}\n\nasync function safeText(res: Response): Promise<string> {\n  try {\n    return (await res.text()).slice(0, 300);\n  } catch {\n    return \"\";\n  }\n}\n","// Turn any odla-db entity into an agent Skill: list / create / update / delete\n// tools whose handlers call db.query / db.transact. This is the ergonomic hook\n// for \"add a skill and call it as tools that change data in odla-db\" — a todos\n// skill is a few lines (see the example at the bottom of this file's doc).\n//\n// Generic over the entity and its fields; the tool JSON-Schemas are built from\n// the `fields` you declare, so the model gets a precise contract.\n\nimport type { Skill } from \"../agent/skill\";\nimport type { ToolDef, ToolOutput } from \"../agent/tools\";\nimport type { OdlaDbClient, OdlaOp } from \"./types\";\n\nexport interface EntityCrudSkillOptions {\n  /** The injected odla-db client (from @odla-ai/db's init). */\n  db: OdlaDbClient;\n  /** Entity namespace, e.g. \"todos\". */\n  entity: string;\n  /** JSON-Schema `properties` for the create/update fields (e.g. { text: { type: \"string\" }, done: { type: \"boolean\" } }). */\n  fields: Record<string, unknown>;\n  /** Field names required to create (default: none). */\n  required?: string[];\n  /** Skill name (default `${entity} management`). */\n  name?: string;\n  /** Extra instructions appended to the generated guidance. */\n  instructions?: string;\n  /** Singular noun for tool names (default: `entity` with a trailing \"s\" stripped). */\n  singular?: string;\n  /** Plural noun for the list tool (default: `entity`). */\n  plural?: string;\n  /** Input field carrying the entity id in update/delete (default \"id\"). */\n  idField?: string;\n  /** Generate a new id on create (default crypto.randomUUID). */\n  genId?: () => string;\n  /** Attr stamped with Date.now() on create; pass false to disable (default \"createdAt\"). */\n  stampCreatedAt?: string | false;\n  /** Default ordering for the list tool (default { createdAt: \"asc\" }). */\n  order?: Record<string, \"asc\" | \"desc\">;\n}\n\n/** Build a CRUD Skill for one odla-db entity. */\nexport function entityCrudSkill(opts: EntityCrudSkillOptions): Skill {\n  const { db, entity, fields } = opts;\n  const singular = opts.singular ?? entity.replace(/s$/, \"\");\n  const plural = opts.plural ?? entity;\n  const idField = opts.idField ?? \"id\";\n  const genId = opts.genId ?? (() => globalThis.crypto.randomUUID());\n  const stampAttr = opts.stampCreatedAt === undefined ? \"createdAt\" : opts.stampCreatedAt;\n  const order = opts.order ?? { createdAt: \"asc\" };\n  const fieldNames = Object.keys(fields);\n\n  const pickFields = (input: Record<string, unknown>): Record<string, unknown> => {\n    const out: Record<string, unknown> = {};\n    for (const k of fieldNames) if (k in input && input[k] !== undefined) out[k] = input[k];\n    return out;\n  };\n  const ok = (obj: Record<string, unknown>): ToolOutput => ({ content: JSON.stringify(obj) });\n\n  // odla-db's `update` op is an UPSERT (creates the entity if the id is missing),\n  // so update/delete must verify the id exists first — otherwise a model that\n  // passes a wrong/hallucinated id silently spawns a phantom empty row instead of\n  // failing. Membership is checked client-side (rows carry `id`), which works the\n  // same on the real client and on test doubles.\n  const existsById = async (id: string): Promise<boolean> => {\n    const res = await db.query({ [entity]: { $: {} } });\n    return (res[entity] ?? []).some((r) => String(r.id ?? \"\") === id);\n  };\n\n  const listTool: ToolDef = {\n    name: `list_${plural}`,\n    description: `List ${plural}. Optionally filter by exact field values and/or limit the count.`,\n    inputSchema: {\n      type: \"object\",\n      properties: {\n        filter: { type: \"object\", description: `Exact-match filters, e.g. { \"done\": false }`, additionalProperties: true },\n        limit: { type: \"number\", description: \"Max rows to return.\" },\n      },\n    },\n    handler: async (input) => {\n      const filter = (input.filter as Record<string, unknown> | undefined) ?? undefined;\n      const limit = typeof input.limit === \"number\" ? input.limit : undefined;\n      const $: Record<string, unknown> = { order };\n      if (filter && Object.keys(filter).length > 0) $.where = filter;\n      if (limit !== undefined) $.limit = limit;\n      const res = await db.query({ [entity]: { $ } });\n      return ok({ [plural]: res[entity] ?? [] });\n    },\n  };\n\n  const createTool: ToolDef = {\n    name: `create_${singular}`,\n    description: `Create a new ${singular}.`,\n    inputSchema: { type: \"object\", properties: fields, ...(opts.required ? { required: opts.required } : {}) },\n    handler: async (input) => {\n      for (const req of opts.required ?? []) {\n        const v = input[req];\n        if (v === undefined || v === null || v === \"\") {\n          return { content: `Cannot create ${singular}: field \"${req}\" is required.`, isError: true };\n        }\n      }\n      const id = genId();\n      const attrs: Record<string, unknown> = pickFields(input);\n      if (stampAttr) attrs[stampAttr] = Date.now();\n      await db.transact([{ t: \"update\", ns: entity, id, attrs }]);\n      return ok({ id, created: true });\n    },\n  };\n\n  const updateTool: ToolDef = {\n    name: `update_${singular}`,\n    description: `Update fields of an existing ${singular} by ${idField}. Only the fields you pass change.`,\n    inputSchema: {\n      type: \"object\",\n      properties: {\n        [idField]: { type: \"string\", description: `The exact ${idField} string from list_${plural} — NOT the item's position in a numbered list.` },\n        ...fields,\n      },\n      required: [idField],\n    },\n    handler: async (input) => {\n      const id = String(input[idField] ?? \"\");\n      if (!id) return { content: `Missing \"${idField}\".`, isError: true };\n      const attrs = pickFields(input);\n      if (Object.keys(attrs).length === 0) return { content: \"No fields to update.\", isError: true };\n      if (!(await existsById(id))) {\n        return { content: `No ${singular} with ${idField} \"${id}\". Call list_${plural} for valid ids, then retry.`, isError: true };\n      }\n      await db.transact([{ t: \"update\", ns: entity, id, attrs }]);\n      return ok({ id, updated: true });\n    },\n  };\n\n  const deleteTool: ToolDef = {\n    name: `delete_${singular}`,\n    description: `Delete a ${singular} by ${idField}.`,\n    inputSchema: {\n      type: \"object\",\n      properties: { [idField]: { type: \"string\", description: `The exact ${idField} string from list_${plural} — NOT the item's position in a numbered list.` } },\n      required: [idField],\n    },\n    handler: async (input) => {\n      const id = String(input[idField] ?? \"\");\n      if (!id) return { content: `Missing \"${idField}\".`, isError: true };\n      if (!(await existsById(id))) {\n        return { content: `No ${singular} with ${idField} \"${id}\". Call list_${plural} for valid ids.`, isError: true };\n      }\n      const op: OdlaOp = { t: \"delete\", ns: entity, id };\n      await db.transact([op]);\n      return ok({ id, deleted: true });\n    },\n  };\n\n  const guidance =\n    `Manage ${plural} in the database. Use list_${plural} to read (optionally filtered), ` +\n    `create_${singular} to add, update_${singular} to change fields (e.g. mark done), and ` +\n    `delete_${singular} to remove. Always confirm the current list with list_${plural} before ` +\n    `updating or deleting so you use the right id.` +\n    (opts.instructions ? `\\n${opts.instructions}` : \"\");\n\n  return {\n    name: opts.name ?? `${entity} management`,\n    instructions: guidance,\n    tools: [listTool, createTool, updateTool, deleteTool],\n  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AU,IAAI,QAAQ,IAAI,MAAM,CAAC,CAAC;AAC1D,aAAO,GAAG,EAAE,IAAI,SAAS,KAAK,CAAC;AAAA,IACjC;AAAA,EACF;AAEA,QAAM,aAAsB;AAAA,IAC1B,MAAM,UAAU,QAAQ;AAAA,IACxB,aAAa,YAAY,QAAQ,OAAO,OAAO;AAAA,IAC/C,aAAa;AAAA,MACX,MAAM;AAAA,MACN,YAAY,EAAE,CAAC,OAAO,GAAG,EAAE,MAAM,UAAU,aAAa,aAAa,OAAO,qBAAqB,MAAM,sDAAiD,EAAE;AAAA,MAC1J,UAAU,CAAC,OAAO;AAAA,IACpB;AAAA,IACA,SAAS,OAAO,UAAU;AACxB,YAAM,KAAK,OAAO,MAAM,OAAO,KAAK,EAAE;AACtC,UAAI,CAAC,GAAI,QAAO,EAAE,SAAS,YAAY,OAAO,MAAM,SAAS,KAAK;AAClE,UAAI,CAAE,MAAM,WAAW,EAAE,GAAI;AAC3B,eAAO,EAAE,SAAS,MAAM,QAAQ,SAAS,OAAO,KAAK,EAAE,gBAAgB,MAAM,mBAAmB,SAAS,KAAK;AAAA,MAChH;AACA,YAAM,KAAa,EAAE,GAAG,UAAU,IAAI,QAAQ,GAAG;AACjD,YAAM,GAAG,SAAS,CAAC,EAAE,CAAC;AACtB,aAAO,GAAG,EAAE,IAAI,SAAS,KAAK,CAAC;AAAA,IACjC;AAAA,EACF;AAEA,QAAM,WACJ,UAAU,MAAM,8BAA8B,MAAM,0CAC1C,QAAQ,mBAAmB,QAAQ,kDACnC,QAAQ,yDAAyD,MAAM,2DAEhF,KAAK,eAAe;AAAA,EAAK,KAAK,YAAY,KAAK;AAElD,SAAO;AAAA,IACL,MAAM,KAAK,QAAQ,GAAG,MAAM;AAAA,IAC5B,cAAc;AAAA,IACd,OAAO,CAAC,UAAU,YAAY,YAAY,UAAU;AAAA,EACtD;AACF;","names":["index","issue","isRecord","resolveLocalRef","isFiniteNumber","levels","init_errors","thinking","init_echo","init_request","levels","init_errors","blocks","init_errors","init_echo","init_request","Anthropic","blocks","init_blocks","buildParams","buildTools","mapToolChoice","blocks","init_request","init_blocks","blocks","audioFormat","init_blocks","init_models","init_errors","mapCitations","mapUsage","init_response","init_response","mapUsage","init_stream","init_response","index","import_openai","init_errors","init_echo","init_request","init_models","init_response","init_stream","OpenAI","params","res","buildParams","buildParams","buildTools","mapToolChoice","init_request","init_blocks","init_models","init_errors","mapResponse","signed","mapCitations","mapFinish","mapUsage","init_response","mapStream","mapUsage","mapFinish","init_stream","init_response","mapResponse","import_genai","init_errors","init_echo","init_request","init_models","init_response","init_stream","buildParams","mapStream","overrides","levels","levels","rates","levels","price","price","AnthropicProvider","OpenAIProvider","GoogleProvider","import_api","init_errors","index","issue","taint","index","trace","record","init_request","levels","cache","cache","model"]}