@odla-ai/ai 0.2.2 → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +71 -17
- package/dist/{anthropic-BIGCVQE4.js → anthropic-2NPMHJZT.js} +16 -8
- package/dist/anthropic-2NPMHJZT.js.map +1 -0
- package/dist/chunk-OX4TA4ZH.js +16 -0
- package/dist/chunk-OX4TA4ZH.js.map +1 -0
- package/dist/{chunk-QFT2DU2X.js → chunk-PXXCN2EU.js} +62 -5
- package/dist/chunk-PXXCN2EU.js.map +1 -0
- package/dist/{google-QY5B4T5O.js → google-3XV2VWVB.js} +18 -8
- package/dist/google-3XV2VWVB.js.map +1 -0
- package/dist/index.cjs +664 -66
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +120 -10
- package/dist/index.d.ts +120 -10
- package/dist/index.js +545 -50
- package/dist/index.js.map +1 -1
- package/dist/{openai-PTZPJYTT.js → openai-NTQCF577.js} +20 -10
- package/dist/openai-NTQCF577.js.map +1 -0
- package/llms.txt +34 -15
- package/package.json +12 -5
- package/dist/anthropic-BIGCVQE4.js.map +0 -1
- package/dist/chunk-QFT2DU2X.js.map +0 -1
- package/dist/google-QY5B4T5O.js.map +0 -1
- package/dist/openai-PTZPJYTT.js.map +0 -1
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/shape/blocks.ts","../src/shape/usage.ts","../src/shape/request.ts","../src/shape/events.ts","../src/shape/errors.ts","../src/shape/helpers.ts","../src/shape/index.ts","../src/providers/errors.ts","../src/providers/anthropic/request.ts","../src/providers/anthropic/response.ts","../src/providers/anthropic/stream.ts","../src/providers/anthropic.ts","../src/providers/blocks.ts","../src/providers/openai/request.ts","../src/providers/openai/response.ts","../src/providers/openai/stream.ts","../src/providers/openai.ts","../src/providers/google/request.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/catalog/openai.ts","../src/catalog/google.ts","../src/providers/registry.ts","../src/client/keys.ts","../src/doc/llms.ts","../src/agent/loop.ts","../src/agent/tools.ts","../src/agent/skill.ts","../src/agent/taint.ts","../src/agent/memory.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/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}\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}\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","// Token usage accounting. The one runtime island with no dependencies.\n\nexport interface OracleUsage {\n inputTokens: number;\n outputTokens: number;\n cacheCreationTokens?: number;\n cacheReadTokens?: number;\n}\n\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 { 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// ----- 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}\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","// Streaming events — one SSE vocabulary regardless of provider.\nimport type { OracleContentBlock, ProviderId } from \"./blocks\";\nimport type { OracleUsage } from \"./usage\";\nimport type { 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 | 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\nexport interface OracleErrorEvent {\n type: \"error\";\n error: OracleErrorShape;\n}\n","// The normalized error taxonomy and the class hierarchy every adapter throws.\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 | \"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\n constructor(\n code: OracleErrorType,\n message: string,\n opts?: { providerStatus?: number; retryAfter?: number; cause?: unknown },\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 }\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/** Any other upstream provider failure (5xx, transport, unexpected shape). */\nexport class ProviderError extends OdlaAIError {\n constructor(message: string, opts?: { providerStatus?: number; cause?: unknown }) {\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\nexport function isTextBlock(b: OracleContentBlock): b is TextBlock {\n return b.type === \"text\";\n}\nexport function isImageBlock(b: OracleContentBlock): b is ImageBlock {\n return b.type === \"image\";\n}\nexport function isAudioBlock(b: OracleContentBlock): b is AudioBlock {\n return b.type === \"audio\";\n}\nexport function isDocumentBlock(b: OracleContentBlock): b is DocumentBlock {\n return b.type === \"document\";\n}\nexport function isToolUseBlock(b: OracleContentBlock): b is ToolUseBlock {\n return b.type === \"tool_use\";\n}\nexport function isToolResultBlock(b: OracleContentBlock): b is ToolResultBlock {\n return b.type === \"tool_result\";\n}\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","// 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 \"./usage\";\nexport * from \"./request\";\nexport * from \"./events\";\nexport * from \"./errors\";\nexport * from \"./helpers\";\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 ContextWindowError,\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\") {\n const headers = (err as { headers?: unknown }).headers;\n if (headers && typeof headers === \"object\") {\n const raw = (headers as Record<string, unknown>)[\"retry-after\"];\n const n = typeof raw === \"string\" ? Number(raw) : typeof raw === \"number\" ? raw : NaN;\n if (Number.isFinite(n)) return n;\n }\n }\n return 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): OdlaAIError {\n if (err instanceof OdlaAIError) return 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): never {\n throw normalizeError(err, provider);\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 type { OracleContentBlock, OracleRequest, TextBlock, ToolChoice } 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(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 if (req.thinking === \"adaptive\" && spec.capabilities.thinking) params.thinking = { type: \"adaptive\" };\n\n const outputConfig: Record<string, unknown> = {};\n if (req.effort && spec.capabilities.effort) outputConfig.effort = req.effort;\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\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(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) tools.push({ type: \"web_search_20260209\", name: \"web_search\" });\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 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 } from \"../../shape/index\";\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: (b.input ?? {}) as Record<string, unknown> });\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 are dropped — the answer\n // text lives in text blocks.\n }\n return out;\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","// 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, type OracleContentBlock, type OracleEvent, type OracleRequest, type OracleResponse, type OracleStopReason } from \"../shape/index\";\nimport { buildParams, toAnthropicMessages } from \"./anthropic/request\";\nimport { mapContent, mapStop, mapUsage } from \"./anthropic/response\";\nimport { mapStreamEvent } from \"./anthropic/stream\";\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 try {\n let messages = toAnthropicMessages(req);\n const content: OracleContentBlock[] = [];\n const usage = emptyUsage();\n let stopReason: OracleStopReason = \"end_turn\";\n let id = \"\";\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 res = await this.client.messages.create(\n buildParams(spec, req, messages) as unknown as Anthropic.MessageCreateParamsNonStreaming,\n );\n id = res.id;\n addUsage(usage, mapUsage(res.usage));\n content.push(...mapContent(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 return { id, model: req.model, provider: \"anthropic\", role: \"assistant\", content, stopReason, usage };\n } catch (err) {\n mapProviderError(err, \"anthropic\");\n }\n }\n\n async *stream(spec: ModelSpec, req: OracleRequest): AsyncIterable<OracleEvent> {\n try {\n const events = this.client.messages.stream(\n buildParams(spec, req, toAnthropicMessages(req)) as unknown as Anthropic.MessageStreamParams,\n );\n for await (const raw of events) {\n const ev = mapStreamEvent(raw, req);\n if (ev) yield ev;\n }\n } catch (err) {\n yield { type: \"error\", error: normalizeError(err, \"anthropic\").toShape() };\n }\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 {\n CapabilityError,\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\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 if (req.effort && spec.capabilities.effort) params.reasoning_effort = reasoningEffort(req.effort);\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) params.web_search_options = { search_context_size: \"medium\" };\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\nfunction reasoningEffort(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 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} from \"../../shape/index\";\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 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 };\n}\n\n/** OpenAI hands tool arguments back as a JSON *string*; the canonical shape wants\n * a parsed object. Tolerant: malformed JSON becomes an empty object. */\nexport function parseArgs(raw: string | undefined): Record<string, unknown> {\n if (!raw) return {};\n try {\n const parsed = JSON.parse(raw);\n return parsed && typeof parsed === \"object\" ? (parsed as Record<string, unknown>) : {};\n } catch {\n return {};\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 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 adapter, on the Chat Completions API (stable across the current model\n// lineup, multimodal, tool calls, streaming). The interesting translations —\n// system folded into a leading message, JSON-string tool `arguments` parsed to an\n// object, and tool_result blocks re-emitted as role:\"tool\" messages — happen in\n// ./openai/request so the rest of odla-ai only ever sees the 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 { buildParams, toOpenAIMessages } from \"./openai/request\";\nimport { mapResponse, parseArgs } from \"./openai/response\";\nimport { mapStream } from \"./openai/stream\";\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 try {\n const res = (await this.client.chat.completions.create(\n buildParams(spec, req, false) as unknown as ChatParams,\n )) as OpenAI.Chat.Completions.ChatCompletion;\n return mapResponse(res, req);\n } catch (err) {\n mapProviderError(err, \"openai\");\n }\n }\n\n async *stream(spec: ModelSpec, req: OracleRequest): AsyncIterable<OracleEvent> {\n try {\n const stream = (await this.client.chat.completions.create(\n buildParams(spec, req, true) as unknown as ChatParams,\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\").toShape() };\n }\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 { CapabilityError, type OracleContentBlock, type OracleRequest, type ToolChoice } 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 if (req.thinking === \"adaptive\" && spec.capabilities.thinking) {\n config.thinkingConfig = { thinkingBudget: -1 }; // -1 = dynamic (\"let the model decide\")\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 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).map(toPart),\n }));\n}\n\nfunction toPart(b: OracleContentBlock): Part {\n switch (b.type) {\n case \"text\":\n return { text: b.text };\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 return { functionCall: { name: b.name, args: b.input } };\n case \"tool_result\":\n return {\n functionResponse: {\n // Gemini correlates by name; the canonical tool_use id is keyed to it.\n name: b.toolUseId,\n response: { result: typeof b.content === \"string\" ? b.content : stringifyBlocks(b.content) },\n },\n };\n case \"thinking\":\n return { text: \"\" }; // no thinking input channel; drop content\n }\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 parameters: 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) 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 { OracleContentBlock, OracleRequest, OracleResponse, OracleStopReason, OracleUsage } from \"../../shape/index\";\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 if (p.text) content.push({ type: \"text\", text: p.text });\n else if (p.functionCall) {\n sawToolUse = true;\n const name = p.functionCall.name ?? \"\";\n content.push({ type: \"tool_use\", id: p.functionCall.id ?? name, name, input: (p.functionCall.args ?? {}) as Record<string, unknown> });\n }\n }\n\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 };\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 { mapFinish, mapUsage } 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: \"\" } };\n }\n yield { type: \"content_block_delta\", index: 0, delta: { type: \"text_delta\", text: p.text } };\n } else if (p.functionCall) {\n const idx = nextBlockIndex++;\n const name = p.functionCall.name ?? \"\";\n yield { type: \"content_block_start\", index: idx, contentBlock: { type: \"tool_use\", id: p.functionCall.id ?? name, name, input: {} } };\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 { buildParams, toContents } from \"./google/request\";\nimport { mapResponse } from \"./google/response\";\nimport { mapStream } from \"./google/stream\";\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 try {\n const res = await this.client.models.generateContent(buildParams(spec, req));\n return mapResponse(res, req);\n } catch (err) {\n mapProviderError(err, \"google\");\n }\n }\n\n async *stream(spec: ModelSpec, req: OracleRequest): AsyncIterable<OracleEvent> {\n try {\n const iter = await this.client.models.generateContentStream(buildParams(spec, req));\n yield* mapStream(iter, req);\n } catch (err) {\n yield { type: \"error\", error: normalizeError(err, \"google\").toShape() };\n }\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 } from \"./client/keys\";\nexport type { KeyMap, KeyResolver, KeyOptions } from \"./client/keys\";\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 InvalidRequestError,\n ProviderError,\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 OracleContentBlock,\n OracleRole,\n OracleMessage,\n OracleTool,\n ToolChoice,\n ThinkingMode,\n Effort,\n ResponseFormat,\n OracleRequest,\n OracleUsage,\n OracleStopReason,\n OracleResponse,\n OracleEvent,\n MessageStartEvent,\n ContentBlockStartEvent,\n ContentBlockDeltaEvent,\n ContentBlockDelta,\n ContentBlockStopEvent,\n MessageDeltaEvent,\n MessageStopEvent,\n OracleErrorEvent,\n OracleErrorShape,\n OracleErrorType,\n} from \"./shape/index\";\n\n// ----- llms.txt codegen -----\nexport { generateLlmsTxt } from \"./doc/llms\";\n\n// ----- capabilities + catalog -----\nexport { chatCapabilities, validateRequest } from \"./shape/capabilities\";\nexport type { ModelKind, Capabilities, ModelSpec } from \"./shape/capabilities\";\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 { normalizeError } from \"./providers/errors\";\nexport type { Provider, ProviderFactory } from \"./providers/types\";\n\n// ----- agent engine -----\nexport {\n runAgent,\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 ToolCallRecord,\n StoppedReason,\n ToolDef,\n ToolHandler,\n ToolContext,\n ToolOutput,\n MemoryScope,\n TaintLabel,\n TaintSet,\n} from \"./agent/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 ProviderError,\n extractText,\n type OracleContentBlock,\n type OracleEvent,\n type OracleRequest,\n type OracleResponse,\n type OracleUsage,\n type ProviderId,\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 { resolveApiKey, type KeyMap, type KeyResolver } from \"./keys\";\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}\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}\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}\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 /** Web-search-grounded prose answer. */\n search(c: SearchCall): Promise<{ text: string; usage: OracleUsage }>;\n}\n\n/** The minimal inference surface the agent loop and eval harness depend on. */\nexport type Inference = Pick<Ai, \"chat\" | \"stream\" | \"catalog\">;\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 }> => {\n const spec = resolveModel(catalog, model);\n const injected = opts.providers?.[spec.provider];\n if (injected) return { spec, provider: injected };\n const key = await resolveApiKey(spec.provider, opts, model);\n const provider = await getProvider(spec.provider, key);\n return { spec, provider };\n };\n\n const chat: Ai[\"chat\"] = async (input) => {\n const model = pickModel(input.model);\n const req: OracleRequest = { ...input, model };\n const { spec, provider } = await resolveProviderFor(model);\n validateRequest(spec, req);\n return provider.create(spec, 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 } = 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 yield* provider.stream(spec, req);\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 };\n const { spec, provider } = await resolveProviderFor(model);\n validateRequest(spec, req);\n const res = await provider.create(spec, req);\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}\".`);\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 };\n const { spec, provider } = await resolveProviderFor(model);\n validateRequest(spec, req);\n const res = await provider.create(spec, req);\n return { text: extractText(res.content), usage: res.usage };\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\";\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}\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}\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 ...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) fail(\"web search\");\n if (req.responseFormat && !caps.structuredOutput) fail(\"structured output\");\n if (req.effort && !caps.effort) fail(\"the effort parameter\");\n if (req.thinking === \"adaptive\" && !caps.thinking) fail(\"thinking\");\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// Model ids + capabilities VERIFIED against the `claude-api` skill (this build):\n// current chat ids are claude-opus-4-8 (default), claude-sonnet-5,\n// claude-haiku-4-5, claude-fable-5; thinking is adaptive-only; forced tool-call\n// is tool_choice:{type:\"tool\"}; web search is web_search_20260209 and needs\n// Sonnet-4.6+/Opus (not Haiku); Claude has NO audio input.\n// Re-verify via the skill before shipping if time has passed — never hardcode\n// model ids from memory.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\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 });\n\nexport const ANTHROPIC_MODELS: ModelSpec[] = [\n {\n id: \"claude-opus-4-8\",\n provider: \"anthropic\",\n nativeId: \"claude-opus-4-8\",\n capabilities: FRONTIER(),\n contextWindow: 1_000_000,\n maxOutput: 128_000,\n },\n {\n id: \"claude-sonnet-5\",\n provider: \"anthropic\",\n nativeId: \"claude-sonnet-5\",\n capabilities: FRONTIER(),\n contextWindow: 1_000_000,\n maxOutput: 128_000,\n },\n {\n id: \"claude-fable-5\",\n provider: \"anthropic\",\n nativeId: \"claude-fable-5\",\n capabilities: FRONTIER(),\n contextWindow: 1_000_000,\n maxOutput: 128_000,\n },\n {\n // Haiku 4.5: no effort param (errors), web search needs Sonnet-4.6+, so both off.\n id: \"claude-haiku-4-5\",\n provider: \"anthropic\",\n nativeId: \"claude-haiku-4-5\",\n capabilities: chatCapabilities({\n documentIn: true,\n thinking: false,\n effort: false,\n webSearch: false,\n audioIn: false,\n }),\n contextWindow: 200_000,\n maxOutput: 64_000,\n },\n];\n","// OpenAI model catalog — config as data.\n//\n// Model ids VERIFIED against the account's live /v1/models list at build time\n// (2026-07). Canonical id == native id. The GPT-5 line are reasoning models\n// (reasoning-effort knob → effort: true) and take image but not audio input;\n// audio input is the separate `gpt-audio` line. Re-verify against /v1/models as\n// the lineup drifts — do NOT trust these from memory. Pass a custom catalog to\n// init() to add models without a release.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\n\nexport const OPENAI_MODELS: ModelSpec[] = [\n {\n id: \"gpt-5.5\",\n provider: \"openai\",\n nativeId: \"gpt-5.5\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n id: \"gpt-5\",\n provider: \"openai\",\n nativeId: \"gpt-5\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n id: \"gpt-5-mini\",\n provider: \"openai\",\n nativeId: \"gpt-5-mini\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n id: \"gpt-5-nano\",\n provider: \"openai\",\n nativeId: \"gpt-5-nano\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n // Search-tuned chat model: the adapter sends web_search_options when a\n // request sets webSearch. No reasoning-effort knob.\n id: \"gpt-5-search-api\",\n provider: \"openai\",\n nativeId: \"gpt-5-search-api\",\n capabilities: chatCapabilities({ webSearch: true }),\n contextWindow: 400_000,\n },\n {\n // Non-reasoning multimodal chat (image input, no effort knob).\n id: \"gpt-4o\",\n provider: \"openai\",\n nativeId: \"gpt-4o\",\n capabilities: chatCapabilities(),\n contextWindow: 128_000,\n },\n {\n // Audio-input model line — accepts audio, not images.\n id: \"gpt-audio\",\n provider: \"openai\",\n nativeId: \"gpt-audio\",\n capabilities: chatCapabilities({ imageIn: false, audioIn: true }),\n contextWindow: 128_000,\n },\n];\n","// Google (Gemini) model catalog — config as data.\n//\n// ⚠️ VERIFY these ids + capabilities against current Google GenAI docs before\n// shipping — do NOT trust them from memory. Canonical id == native id here.\n//\n// Gemini is natively multimodal: text + image + audio + PDF input on the current\n// generation, tool calling via functionDeclarations, thinking via thinkingConfig,\n// structured output via responseSchema, and web grounding via the googleSearch\n// tool — hence the broad default caps below.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\n\nconst GEMINI = () =>\n chatCapabilities({\n audioIn: true,\n documentIn: true,\n thinking: true,\n effort: true, // mapped onto thinkingConfig\n webSearch: true, // googleSearch grounding\n });\n\nexport const GOOGLE_MODELS: ModelSpec[] = [\n {\n id: \"gemini-2.5-pro\",\n provider: \"google\",\n nativeId: \"gemini-2.5-pro\",\n capabilities: GEMINI(),\n contextWindow: 1_000_000,\n },\n {\n id: \"gemini-2.5-flash\",\n provider: \"google\",\n nativeId: \"gemini-2.5-flash\",\n capabilities: GEMINI(),\n contextWindow: 1_000_000,\n },\n {\n id: \"gemini-2.0-flash\",\n provider: \"google\",\n nativeId: \"gemini-2.0-flash\",\n capabilities: chatCapabilities({\n audioIn: true,\n documentIn: true,\n thinking: false,\n effort: false,\n webSearch: true,\n }),\n contextWindow: 1_000_000,\n },\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. Adapters are cached per (provider, key)\n// so repeated calls reuse one SDK client.\n\nimport type { ProviderId } from \"../shape/index\";\nimport type { Provider } from \"./types\";\n\nconst cache = new Map<string, Provider>();\n\nexport async function getProvider(id: ProviderId, apiKey: string): Promise<Provider> {\n const cacheKey = `${id}:${apiKey}`;\n const existing = cache.get(cacheKey);\n if (existing) return existing;\n\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 cache.set(cacheKey, provider);\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 cache.set(`${id}:${apiKey}`, provider);\n}\n\n/** Test seam: clear the adapter cache. */\nexport function clearProviderCache(): void {\n cache.clear();\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","// Machine-readable context codegen — the odla-db pattern (generateLlmsTxt), but\n// for an inference/agent library the source is the model catalog rather than a\n// per-app schema. Emits an `llms.txt` giving an LLM everything it needs to build,\n// run, test, and persist agents with @odla-ai/ai, including the odla-db\n// handshake / storage / secrets flow. The shipped repo-root `llms.txt` is this\n// function's output over DEFAULT_CATALOG.\n\nimport { DEFAULT_CATALOG, type Catalog } from \"../catalog/index\";\nimport type { Capabilities } from \"../shape/capabilities\";\n\nfunction capsSummary(c: Capabilities): string {\n const flags: string[] = [\"text\"];\n if (c.imageIn) flags.push(\"image\");\n if (c.audioIn) flags.push(\"audio\");\n if (c.toolUse) flags.push(\"tools\");\n if (c.thinking) flags.push(\"thinking\");\n if (c.effort) flags.push(\"effort\");\n if (c.webSearch) flags.push(\"web-search\");\n if (c.structuredOutput) flags.push(\"structured\");\n return flags.join(\", \");\n}\n\n/** Generate the `llms.txt` context document for a given model catalog. */\nexport function generateLlmsTxt(catalog: Catalog = DEFAULT_CATALOG): string {\n const models = Object.values(catalog)\n .map((s) => `- \\`${s.id}\\` (${s.provider}) — ${capsSummary(s.capabilities)}`)\n .join(\"\\n\");\n\n return `# @odla-ai/ai — LLM context\n\n> EXPERIMENTAL — an agentic-coding experiment. This package is built and operated\n> by autonomous coding agents as an experiment in agentic loops. APIs change\n> without notice and nothing here is production-hardened. Use at your own risk.\n\nOne general-purpose interface for AI inference across Anthropic (Claude), OpenAI\n(GPT), and Google (Gemini) — text, image, and audio — plus a tool-use agent\nengine and an eval harness. Library-only: import in-process, bring your own keys.\nIsomorphic (Node 20+, Cloudflare Workers, browser). Provider SDKs are lazy-loaded.\n\n## Install\n\n npm i @odla-ai/ai\n # provider SDKs are peer-lazy-loaded; install those you use:\n # @anthropic-ai/sdk openai @google/genai\n # optional, for odla-db-backed storage + secrets:\n # @odla-ai/db\n\n## Core call\n\n import { init } from \"@odla-ai/ai\";\n const ai = init({ keys: { anthropic: KEY, openai: KEY, google: KEY }, defaultModel: \"claude-opus-4-8\" });\n const res = await ai.chat({ model: \"gpt-5\", messages: [{ role: \"user\", content: \"hi\" }], maxTokens: 256 });\n // res.content: OracleContentBlock[] (text/tool_use/thinking)\n\n- \\`ai.stream(input)\\` → async iterable of normalized events: message_start →\n content_block_start → content_block_delta {text_delta|thinking_delta|input_json_delta}\n → content_block_stop → message_delta → message_stop (plus \\`error\\`).\n- \\`ai.extract<T>({ model, user, tool })\\` → forced tool call; returns a parsed object.\n- \\`ai.search({ model, user })\\` → web-search-grounded prose.\n\n## Content blocks (multimodal)\n\ntext; image { source: base64|url }; audio { source: base64|url }; document (PDF);\ntool_use { id, name, input }; tool_result { toolUseId, content }; thinking.\nAudio input is accepted by OpenAI (\\`gpt-audio\\`) and Google, NOT by Claude — an\naudio block to a Claude model throws CapabilityError before any network call.\n\n## Agents\n\n import { runAgent, type Persona, type ToolDef } from \"@odla-ai/ai\";\n const add: ToolDef = { name: \"add\", description: \"add\", inputSchema: {...}, handler: (i) => ({ content: String(i.a + i.b) }) };\n const persona: Persona = { name: \"calc\", model: \"claude-opus-4-8\", system: \"...\", tools: [add], maxSteps: 4 };\n const run = await runAgent(ai, persona, { input: \"what is 21+21?\" });\n // run.finalText, run.toolCalls, run.usage, run.steps, run.stoppedReason\n\nTools may carry taint labels (outputTaint / acceptsTaint) for a CaMeL-style\nprompt-injection gate. Personas may carry a MemoryScope.\n\n## Skills\n\nA Skill = { name, instructions?, tools: ToolDef[] } is a bundle you attach to a\npersona (persona.skills); its tools merge into the model's tool list and its\ninstructions into the system prompt. Turn an odla-db entity into CRUD tools:\n\n import { entityCrudSkill } from \"@odla-ai/ai\";\n const todos = entityCrudSkill({ db, entity: \"todos\", fields: { text: { type: \"string\" }, done: { type: \"boolean\" } }, required: [\"text\"] });\n // → tools: list_todos, create_todo, update_todo (partial), delete_todo — handlers write to odla-db\n const run = await runAgent(ai, { name: \"todo-bot\", model: \"gpt-5\", skills: [todos] }, { input: \"add buy milk\" });\n\n## Evals\n\n import { evaluate, exactMatch, llmJudge } from \"@odla-ai/ai\";\n const report = await evaluate({ inference: ai, model: \"claude-opus-4-8\", grader: exactMatch(), cases: [{ input, expected }] });\n // graders: exactMatch, includes, structuredMatch, llmJudge; pass a persona to eval an agent.\n\n## Storage + BYO keys via odla-db (@odla-ai/db) — the handshake\n\nFollows odla-db's model. An agent never takes a platform secret; it does a\ndevice-authorization handshake for a scoped, revocable token, then provisions.\n\n import { requestToken, init as odlaInit } from \"@odla-ai/db\";\n import { provisionAgentApp, odlaDbKeyResolver, OdlaDbMemory, persistRun, init } from \"@odla-ai/ai\";\n\n // 1. Handshake: the human supplies the endpoint and approves a short code in odla-db Studio.\n const { token } = await requestToken({ endpoint: ODLA_URL, onCode: ({ userCode }) => show(userCode) });\n\n // 2. Provision: create app, mint app key, push agent schema, store BYO provider keys as secrets.\n const { appId, appKey } = await provisionAgentApp({ endpoint: ODLA_URL, token, providerKeys: { openai: OPENAI_KEY } });\n\n // 3. Runtime: read keys from odla-db secrets; persist memory + run traces.\n const db = odlaInit({ appId, adminToken: appKey, endpoint: ODLA_URL });\n const ai = init({ resolveKey: odlaDbKeyResolver(db) });\n const persona = { name: \"assistant\", model: \"gpt-5\", memory: new OdlaDbMemory({ db, sessionId: \"user-42\" }) };\n const run = await runAgent(ai, persona, { input: \"hello\" });\n await persistRun(run, { db, sessionId: \"user-42\" });\n\nSecrets are read-only from the app key (odlaDbKeyResolver → db.secrets.get); they\nare WRITTEN only with the operator/dev token via provisionAgentApp/putSecret. Keys\nare AES-GCM-encrypted at rest in odla-db and never returned to browser clients.\n\n## Platform wiring (odla.ai apps registry)\n\nApps registered on the odla platform get LLM access as an APP SETTING —\nnever put provider keys in your Worker's wrangler vars/secrets. Provider +\ndefault model are per-environment registry config (set in Studio's AI card\nor \\`@odla-ai/apps\\` setAi); the API key lives in the platform vault (the\nenv's odla-db tenant secrets, write-only for operators). One call reads both:\n\n import { initFromPlatform } from \"@odla-ai/ai\";\n import { init as odlaInit } from \"@odla-ai/db\";\n\n const db = odlaInit({ appId: TENANT, adminToken: env.ODLA_API_KEY, endpoint: \"https://db.odla.ai\" });\n const { ai, provider, model } = await initFromPlatform({\n platform: \"https://odla.ai\", appId: APP_ID, env: \"prod\", db });\n // ai.chat / ai.stream / ai.extract — provider/model from public-config\n // (cached ~60s, so Studio changes apply without redeploys); the key is\n // fetched from the vault at call time via odlaDbKeyResolver.\n\nThe only secret the Worker carries is its odla-db app key. Rotating the LLM\nkey = writing the secret again; switching provider/model = a Studio edit.\n\n## Errors\n\nEvery error is an OdlaAIError subclass with a stable \\`code\\` — branch on err.code:\nconfig, auth, rate_limit, capability_unsupported, context_window, invalid_request,\ntool_input_invalid, provider_error.\n\n## Models\n\n${models}\n\nModel ids live in a data catalog and drift — verify against provider docs; extend\nvia buildCatalog / init({ catalog }).\n`;\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 emptyUsage,\n extractText,\n extractToolUses,\n type OracleContentBlock,\n type OracleMessage,\n type OracleResponse,\n type OracleUsage,\n type ToolResultBlock,\n type ToolUseBlock,\n} from \"../shape/index\";\nimport type { Inference } from \"../client/init\";\nimport type { Persona } from \"./persona\";\nimport type { ToolDef, ToolOutput } from \"./tools\";\nimport { toOracleTool } from \"./tools\";\nimport { composeSkills } from \"./skill\";\nimport { assertSinkAcceptsTaint, type TaintLabel, type TaintSet } from \"./taint\";\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}\n\nexport type StoppedReason = \"end_turn\" | \"max_steps\" | \"refusal\";\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 /** Every tool call executed, in order. */\n toolCalls: ToolCallRecord[];\n stoppedReason: StoppedReason;\n}\n\nexport async function runAgent(inference: Inference, persona: Persona, input: AgentRunInput): Promise<AgentRun> {\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 accumulatedTaint: TaintSet = new Set<TaintLabel>([\"llm_inherited\"]);\n const maxSteps = persona.maxSteps ?? 8;\n\n let response: OracleResponse | undefined;\n let stoppedReason: StoppedReason = \"max_steps\";\n let steps = 0;\n\n while (steps < maxSteps) {\n steps++;\n response = await inference.chat({\n model: persona.model,\n system,\n messages,\n tools: tools.length > 0 ? tools.map(toOracleTool) : undefined,\n maxTokens: persona.maxTokens ?? 4096,\n effort: persona.effort,\n thinking: persona.thinking,\n temperature: persona.temperature,\n webSearch: persona.webSearch,\n });\n addUsage(usage, response.usage);\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\n const resultBlocks: ToolResultBlock[] = [];\n for (const toolUse of toolUses) {\n const def = handlerByName.get(toolUse.name);\n if (!def || !def.handler) {\n resultBlocks.push(errorResult(toolUse.id, `No local handler for tool \"${toolUse.name}\".`));\n continue;\n }\n if (def.acceptsTaint) assertSinkAcceptsTaint(def.name, def.acceptsTaint, accumulatedTaint);\n\n let output: ToolOutput;\n try {\n output = await def.handler(toolUse.input, { taint: new Set(accumulatedTaint), signal: input.signal });\n } catch (err) {\n output = { content: `Tool \"${toolUse.name}\" threw: ${(err as Error).message}`, isError: true };\n }\n toolCalls.push({ toolUse, output });\n resultBlocks.push({ type: \"tool_result\", toolUseId: toolUse.id, content: output.content, isError: output.isError });\n for (const label of def.outputTaint ?? []) accumulatedTaint.add(label);\n }\n messages.push({ role: \"user\", content: resultBlocks });\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 toolCalls,\n stoppedReason,\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 /** 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 /** 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\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. */\nexport class TaintError extends OdlaAIError {\n constructor(message: string) {\n super(\"invalid_request\", message);\n }\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(\n `Tool \"${sink}\" refused: conversation carries taint \"${label}\" which is not in its allowlist [${allowed.join(\", \")}].`,\n );\n }\n }\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","// 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\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\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}\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 useCache = opts.cache ?? true;\n const cache = new Map<ProviderId, string>();\n\n return async (provider: ProviderId): Promise<string | undefined> => {\n if (useCache) {\n const hit = cache.get(provider);\n if (hit !== undefined) return hit;\n }\n try {\n const key = await db.secrets.get(nameFor(provider));\n if (useCache) cache.set(provider, key);\n return key;\n } catch {\n return undefined; // absent secret → provider unavailable\n }\n };\n}\n","// Platform wiring: one call turns an odla.ai app registration into a ready\n// `Ai`. The NON-SECRET half ({provider, model?}) comes from the registry's\n// anonymous public-config endpoint — so switching provider/model in Studio\n// needs no redeploy; the SECRET half (the provider API key) never travels\n// through the registry at all: it is read from the app's own odla-db tenant\n// secrets at call time via `odlaDbKeyResolver`. The only credential the\n// caller holds is its odla-db app key (inside `db`).\n\nimport { ConfigError, ProviderError, type ProviderId } from \"../shape/index\";\nimport { init, type Ai, type InitOptions } from \"../client/init\";\nimport { odlaDbKeyResolver, DEFAULT_SECRET_NAMES } from \"./keys\";\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 env's tenant id. */\n appId: string;\n /** Which environment's config to use (\"dev\", \"prod\", …). */\n env: string;\n /** The app's own tenant client — key reads go through `db.secrets.get`. */\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 (catalog, injected providers, …). `resolveKey` is\n * owned by this helper; `defaultModel` is used only when the platform\n * config sets no model. */\n initOptions?: Omit<InitOptions, \"resolveKey\">;\n}\n\nexport interface PlatformAi {\n ai: Ai;\n provider: ProviderId;\n model?: string;\n}\n\ninterface CacheEntry {\n value: PlatformAi;\n expiresAt: number;\n}\n\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?: { provider?: unknown; model?: unknown } | null;\n}\n\nasync function fetchAiConfig(opts: InitFromPlatformOptions): Promise<{ provider: ProviderId; model?: string }> {\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 || typeof ai.provider !== \"string\") {\n throw new ConfigError(\n `ai service is not enabled/configured for \"${opts.appId}\" (${opts.env}) — ` +\n `enable it in Studio or via @odla-ai/apps setAi(appId, env, { provider }).`,\n );\n }\n if (!(ai.provider in DEFAULT_SECRET_NAMES)) {\n throw new ConfigError(`platform ai config names unknown provider \"${ai.provider}\" for \"${opts.appId}\" (${opts.env}).`);\n }\n const model = typeof ai.model === \"string\" && ai.model ? ai.model : undefined;\n return { provider: ai.provider as ProviderId, ...(model ? { model } : {}) };\n}\n\n/** Build an `Ai` from the app's platform registration: provider/model from\n * public-config (cached ~60s), API key from the tenant's odla-db secrets at\n * call time. On cache refresh the existing `Ai` (and its warm key-resolver\n * cache) is reused unless provider/model changed. Note the first call's\n * `db`/`initOptions` are captured for the cache entry's lifetime. */\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 if (hit && hit.expiresAt > now) return hit.value;\n\n const { provider, model } = await fetchAiConfig(opts);\n\n // Same config as the (expired) entry → keep the Ai and its warm key cache.\n if (hit && hit.value.provider === provider && hit.value.model === model) {\n hit.expiresAt = now + ttl;\n return hit.value;\n }\n\n const ai = init({\n ...opts.initOptions,\n resolveKey: odlaDbKeyResolver(opts.db),\n defaultModel: model ?? opts.initOptions?.defaultModel,\n });\n const value: PlatformAi = { ai, provider, ...(model ? { model } : {}) };\n if (ttl > 0) cache.set(key, { value, expiresAt: now + ttl });\n return value;\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-db endpoint, authenticated with an **operator or\n// developer token** (the platform `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, 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 /** The odla-db worker URL — always human-supplied, never hardcoded. */\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 };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACSO,SAAS,aAA0B;AACxC,SAAO,EAAE,aAAa,GAAG,cAAc,EAAE;AAC3C;AAGO,SAAS,SAAS,MAAmB,MAAyB;AACnE,OAAK,eAAe,KAAK;AACzB,OAAK,gBAAgB,KAAK;AAC1B,MAAI,KAAK,wBAAwB,QAAW;AAC1C,SAAK,uBAAuB,KAAK,uBAAuB,KAAK,KAAK;AAAA,EACpE;AACA,MAAI,KAAK,oBAAoB,QAAW;AACtC,SAAK,mBAAmB,KAAK,mBAAmB,KAAK,KAAK;AAAA,EAC5D;AACF;AAvBA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAA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1J,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":["init_errors","init_request","init_errors","init_request","Anthropic","init_blocks","buildParams","buildTools","mapToolChoice","init_request","init_blocks","mapUsage","init_response","mapUsage","init_stream","init_response","import_openai","init_errors","init_request","init_response","init_stream","OpenAI","buildParams","buildParams","buildTools","mapToolChoice","init_request","init_blocks","mapResponse","mapFinish","mapUsage","init_response","mapStream","mapUsage","mapFinish","init_stream","init_response","mapResponse","import_genai","init_errors","init_request","init_response","init_stream","buildParams","mapStream","AnthropicProvider","OpenAIProvider","GoogleProvider","init_errors","cache","cache"]}
|
|
1
|
+
{"version":3,"sources":["../src/shape/blocks.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/providers/errors.ts","../src/providers/anthropic/request.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/response.ts","../src/providers/openai/stream.ts","../src/providers/openai.ts","../src/providers/google/request.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/catalog/openai.ts","../src/catalog/google.ts","../src/providers/registry.ts","../src/client/keys.ts","../src/doc/llms.ts","../src/agent/loop.ts","../src/agent/tools.ts","../src/agent/skill.ts","../src/agent/taint.ts","../src/agent/memory.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/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}\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}\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","// Token usage accounting. The one runtime island with no dependencies.\n\nexport interface OracleUsage {\n inputTokens: number;\n outputTokens: number;\n cacheCreationTokens?: number;\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 { 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// ----- 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}\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","// Streaming events — one SSE vocabulary regardless of provider.\nimport type { OracleContentBlock, ProviderId } from \"./blocks\";\nimport type { OracleUsage } from \"./usage\";\nimport type { 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 | 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\nexport interface OracleErrorEvent {\n type: \"error\";\n error: OracleErrorShape;\n}\n","// The normalized error taxonomy and the class hierarchy every adapter throws.\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\n constructor(\n code: OracleErrorType,\n message: string,\n opts?: { providerStatus?: number; retryAfter?: number; cause?: unknown },\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 }\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 }) {\n super(\"tool_input_invalid\", message, { cause: opts?.cause });\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 }) {\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 \"./usage\";\nexport * from \"./request\";\nexport * from \"./events\";\nexport * from \"./errors\";\nexport * from \"./helpers\";\nexport * from \"./json-schema\";\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\") {\n const headers = (err as { headers?: unknown }).headers;\n if (headers && typeof headers === \"object\") {\n const raw = (headers as Record<string, unknown>)[\"retry-after\"];\n const n = typeof raw === \"string\" ? Number(raw) : typeof raw === \"number\" ? raw : NaN;\n if (Number.isFinite(n)) return n;\n }\n }\n return 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","// 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 type { OracleContentBlock, OracleRequest, TextBlock, ToolChoice } 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(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 if (req.thinking === \"adaptive\" && spec.capabilities.thinking) params.thinking = { type: \"adaptive\" };\n\n const outputConfig: Record<string, unknown> = {};\n if (req.effort && spec.capabilities.effort) outputConfig.effort = req.effort;\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\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(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) tools.push({ type: \"web_search_20260209\", name: \"web_search\" });\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","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 } 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 are dropped — the answer\n // text lives in text blocks.\n }\n return out;\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, type OracleContentBlock, type OracleEvent, type OracleRequest, type OracleResponse, type OracleStopReason } from \"../shape/index\";\nimport { buildParams, toAnthropicMessages } from \"./anthropic/request\";\nimport { 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 usage = emptyUsage();\n let stopReason: OracleStopReason = \"end_turn\";\n let id = \"\";\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 res = await this.client.messages.create(\n buildParams(spec, req, messages) 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 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 return { id, model: req.model, provider: \"anthropic\", role: \"assistant\", content, stopReason, usage };\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 const events = this.client.messages.stream(\n buildParams(spec, req, toAnthropicMessages(req)) as unknown as Anthropic.MessageStreamParams,\n { signal },\n );\n for await (const raw of events) {\n const ev = mapStreamEvent(raw, req);\n if (ev) yield ev;\n }\n } catch (err) {\n yield { type: \"error\", error: normalizeError(err, \"anthropic\", signal).toShape() };\n }\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 {\n CapabilityError,\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\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 if (req.effort && spec.capabilities.effort) params.reasoning_effort = reasoningEffort(req.effort);\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) params.web_search_options = { search_context_size: \"medium\" };\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\nfunction reasoningEffort(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 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} from \"../../shape/index\";\nimport { 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 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 };\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 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 adapter, on the Chat Completions API (stable across the current model\n// lineup, multimodal, tool calls, streaming). The interesting translations —\n// system folded into a leading message, JSON-string tool `arguments` parsed to an\n// object, and tool_result blocks re-emitted as role:\"tool\" messages — happen in\n// ./openai/request so the rest of odla-ai only ever sees the 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 { buildParams, toOpenAIMessages } from \"./openai/request\";\nimport { mapResponse, parseArgs } from \"./openai/response\";\nimport { mapStream } from \"./openai/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 const res = (await this.client.chat.completions.create(\n buildParams(spec, req, false) as unknown as ChatParams,\n { signal },\n )) as OpenAI.Chat.Completions.ChatCompletion;\n return mapResponse(res, req);\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 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\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 { CapabilityError, type OracleContentBlock, type OracleRequest, type ToolChoice } 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 if (req.thinking === \"adaptive\" && spec.capabilities.thinking) {\n config.thinkingConfig = { thinkingBudget: -1 }; // -1 = dynamic (\"let the model decide\")\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 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).map(toPart),\n }));\n}\n\nfunction toPart(b: OracleContentBlock): Part {\n switch (b.type) {\n case \"text\":\n return { text: b.text };\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 return { functionCall: { name: b.name, args: b.input } };\n case \"tool_result\":\n return {\n functionResponse: {\n // Gemini correlates by name; the canonical tool_use id is keyed to it.\n name: b.toolUseId,\n response: { result: typeof b.content === \"string\" ? b.content : stringifyBlocks(b.content) },\n },\n };\n case \"thinking\":\n return { text: \"\" }; // no thinking input channel; drop content\n }\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 parameters: 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) 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 { OracleContentBlock, OracleRequest, OracleResponse, OracleStopReason, OracleUsage } 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 if (p.text) content.push({ type: \"text\", text: p.text });\n else if (p.functionCall) {\n sawToolUse = true;\n const name = p.functionCall.name ?? \"\";\n content.push({ type: \"tool_use\", id: p.functionCall.id ?? name, name, input: toolInput(p.functionCall.args ?? {}, \"google\", name) });\n }\n }\n\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 };\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 { mapFinish, mapUsage } 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: \"\" } };\n }\n yield { type: \"content_block_delta\", index: 0, delta: { type: \"text_delta\", text: p.text } };\n } else if (p.functionCall) {\n const idx = nextBlockIndex++;\n const name = p.functionCall.name ?? \"\";\n yield { type: \"content_block_start\", index: idx, contentBlock: { type: \"tool_use\", id: p.functionCall.id ?? name, name, input: {} } };\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 { buildParams, toContents } from \"./google/request\";\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 params.config = { ...params.config, abortSignal: signal };\n const res = await this.client.models.generateContent(params);\n return mapResponse(res, req);\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\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 } from \"./client/keys\";\nexport type { KeyMap, KeyResolver, KeyOptions } from \"./client/keys\";\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} 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 OracleContentBlock,\n OracleRole,\n OracleMessage,\n OracleTool,\n ToolChoice,\n ThinkingMode,\n Effort,\n ResponseFormat,\n OracleRequest,\n OracleUsage,\n OracleStopReason,\n OracleResponse,\n OracleEvent,\n MessageStartEvent,\n ContentBlockStartEvent,\n ContentBlockDeltaEvent,\n ContentBlockDelta,\n ContentBlockStopEvent,\n MessageDeltaEvent,\n MessageStopEvent,\n OracleErrorEvent,\n OracleErrorShape,\n OracleErrorType,\n JsonSchemaIssue,\n JsonSchemaValidation,\n} from \"./shape/index\";\n\n// ----- llms.txt codegen -----\nexport { generateLlmsTxt } from \"./doc/llms\";\n\n// ----- capabilities + catalog -----\nexport { chatCapabilities, validateRequest } from \"./shape/capabilities\";\nexport type { ModelKind, Capabilities, ModelSpec } from \"./shape/capabilities\";\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 { normalizeError } from \"./providers/errors\";\nexport type { Provider, ProviderFactory } from \"./providers/types\";\n\n// ----- agent engine -----\nexport {\n runAgent,\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 ToolCallRecord,\n StoppedReason,\n ToolDef,\n ToolHandler,\n ToolContext,\n ToolOutput,\n MemoryScope,\n TaintLabel,\n TaintSet,\n} from \"./agent/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 ProviderError,\n ToolInputError,\n extractText,\n validateJsonSchema,\n type OracleContentBlock,\n type OracleEvent,\n type OracleRequest,\n type OracleResponse,\n type OracleUsage,\n type ProviderId,\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 { resolveApiKey, type KeyMap, type KeyResolver } from \"./keys\";\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}\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}\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}\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 /** Web-search-grounded prose answer. */\n search(c: SearchCall): Promise<{ text: string; usage: OracleUsage }>;\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 }> => {\n const spec = resolveModel(catalog, model);\n const injected = opts.providers?.[spec.provider];\n if (injected) return { spec, provider: injected };\n const key = await resolveApiKey(spec.provider, opts, model);\n const provider = await getProvider(spec.provider, key);\n return { spec, provider };\n };\n\n const chat: Ai[\"chat\"] = async (input) => {\n const model = pickModel(input.model);\n const req: OracleRequest = { ...input, model };\n const { spec, provider } = await resolveProviderFor(model);\n validateRequest(spec, req);\n return provider.create(spec, 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 } = 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 yield* provider.stream(spec, req);\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 };\n const { spec, provider } = await resolveProviderFor(model);\n validateRequest(spec, req);\n const res = await provider.create(spec, req);\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}\".`);\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 });\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 };\n const { spec, provider } = await resolveProviderFor(model);\n validateRequest(spec, req);\n const res = await provider.create(spec, req);\n return { text: extractText(res.content), usage: res.usage };\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\";\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}\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}\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 ...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) fail(\"web search\");\n if (req.responseFormat && !caps.structuredOutput) fail(\"structured output\");\n if (req.effort && !caps.effort) fail(\"the effort parameter\");\n if (req.thinking === \"adaptive\" && !caps.thinking) fail(\"thinking\");\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// Model ids + capabilities VERIFIED against the `claude-api` skill (this build):\n// current chat ids are claude-opus-4-8 (default), claude-sonnet-5,\n// claude-haiku-4-5, claude-fable-5; thinking is adaptive-only; forced tool-call\n// is tool_choice:{type:\"tool\"}; web search is web_search_20260209 and needs\n// Sonnet-4.6+/Opus (not Haiku); Claude has NO audio input.\n// Re-verify via the skill before shipping if time has passed — never hardcode\n// model ids from memory.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\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 });\n\n/** Built-in Anthropic (Claude) catalog: one `ModelSpec` per model (canonical id, native id, capabilities, limits). */\nexport const ANTHROPIC_MODELS: ModelSpec[] = [\n {\n id: \"claude-opus-4-8\",\n provider: \"anthropic\",\n nativeId: \"claude-opus-4-8\",\n capabilities: FRONTIER(),\n contextWindow: 1_000_000,\n maxOutput: 128_000,\n },\n {\n id: \"claude-sonnet-5\",\n provider: \"anthropic\",\n nativeId: \"claude-sonnet-5\",\n capabilities: FRONTIER(),\n contextWindow: 1_000_000,\n maxOutput: 128_000,\n },\n {\n id: \"claude-fable-5\",\n provider: \"anthropic\",\n nativeId: \"claude-fable-5\",\n capabilities: FRONTIER(),\n contextWindow: 1_000_000,\n maxOutput: 128_000,\n },\n {\n // Haiku 4.5: no effort param (errors), web search needs Sonnet-4.6+, so both off.\n id: \"claude-haiku-4-5\",\n provider: \"anthropic\",\n nativeId: \"claude-haiku-4-5\",\n capabilities: chatCapabilities({\n documentIn: true,\n thinking: false,\n effort: false,\n webSearch: false,\n audioIn: false,\n }),\n contextWindow: 200_000,\n maxOutput: 64_000,\n },\n];\n","// OpenAI model catalog — config as data.\n//\n// Most ids VERIFIED against the account's live /v1/models list at build time\n// (2026-07); `gpt-5.4-mini` was added by operator request and should be\n// re-verified against /v1/models. Canonical id == native id. The GPT-5 line are\n// reasoning models (reasoning-effort knob → effort: true) and take image but not\n// audio input; audio input is the separate `gpt-audio` line. Re-verify against\n// /v1/models as the lineup drifts — do NOT trust these from memory. Pass a custom\n// catalog to init() to add models without a release.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\n\n/** Built-in OpenAI catalog: one `ModelSpec` per model (canonical id == native id, capabilities, context window). */\nexport const OPENAI_MODELS: ModelSpec[] = [\n {\n id: \"gpt-5.5\",\n provider: \"openai\",\n nativeId: \"gpt-5.5\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n // Compact GPT-5.4 reasoning model (effort knob), same 400K context as the\n // rest of the GPT-5 line. The default for odla-o11y AI triage.\n id: \"gpt-5.4-mini\",\n provider: \"openai\",\n nativeId: \"gpt-5.4-mini\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n id: \"gpt-5\",\n provider: \"openai\",\n nativeId: \"gpt-5\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n id: \"gpt-5-mini\",\n provider: \"openai\",\n nativeId: \"gpt-5-mini\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n id: \"gpt-5-nano\",\n provider: \"openai\",\n nativeId: \"gpt-5-nano\",\n capabilities: chatCapabilities({ effort: true }),\n contextWindow: 400_000,\n },\n {\n // Search-tuned chat model: the adapter sends web_search_options when a\n // request sets webSearch. No reasoning-effort knob.\n id: \"gpt-5-search-api\",\n provider: \"openai\",\n nativeId: \"gpt-5-search-api\",\n capabilities: chatCapabilities({ webSearch: true }),\n contextWindow: 400_000,\n },\n {\n // Non-reasoning multimodal chat (image input, no effort knob).\n id: \"gpt-4o\",\n provider: \"openai\",\n nativeId: \"gpt-4o\",\n capabilities: chatCapabilities(),\n contextWindow: 128_000,\n },\n {\n // Audio-input model line — accepts audio, not images.\n id: \"gpt-audio\",\n provider: \"openai\",\n nativeId: \"gpt-audio\",\n capabilities: chatCapabilities({ imageIn: false, audioIn: true }),\n contextWindow: 128_000,\n },\n];\n","// Google (Gemini) model catalog — config as data.\n//\n// ⚠️ VERIFY these ids + capabilities against current Google GenAI docs before\n// shipping — do NOT trust them from memory. Canonical id == native id here.\n//\n// Gemini is natively multimodal: text + image + audio + PDF input on the current\n// generation, tool calling via functionDeclarations, thinking via thinkingConfig,\n// structured output via responseSchema, and web grounding via the googleSearch\n// tool — hence the broad default caps below.\n\nimport { chatCapabilities, type ModelSpec } from \"../shape/capabilities\";\n\nconst GEMINI = () =>\n chatCapabilities({\n audioIn: true,\n documentIn: true,\n thinking: true,\n effort: true, // mapped onto thinkingConfig\n webSearch: true, // googleSearch grounding\n });\n\n/** Built-in Google (Gemini) catalog: one `ModelSpec` per model (canonical id == native id, capabilities, context window). */\nexport const GOOGLE_MODELS: ModelSpec[] = [\n {\n id: \"gemini-2.5-pro\",\n provider: \"google\",\n nativeId: \"gemini-2.5-pro\",\n capabilities: GEMINI(),\n contextWindow: 1_000_000,\n },\n {\n id: \"gemini-2.5-flash\",\n provider: \"google\",\n nativeId: \"gemini-2.5-flash\",\n capabilities: GEMINI(),\n contextWindow: 1_000_000,\n },\n {\n id: \"gemini-2.0-flash\",\n provider: \"google\",\n nativeId: \"gemini-2.0-flash\",\n capabilities: chatCapabilities({\n audioIn: true,\n documentIn: true,\n thinking: false,\n effort: false,\n webSearch: true,\n }),\n contextWindow: 1_000_000,\n },\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\";\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 fingerprintKey(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\nasync function fingerprintKey(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\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","// 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","// Machine-readable context codegen — the odla-db pattern (generateLlmsTxt), but\n// for an inference/agent library the source is the model catalog rather than a\n// per-app schema. Emits an `llms.txt` giving an LLM everything it needs to build,\n// run, test, and persist agents with @odla-ai/ai, including the odla-db\n// handshake / storage / secrets flow. The shipped repo-root `llms.txt` is this\n// function's output over DEFAULT_CATALOG.\n\nimport { DEFAULT_CATALOG, type Catalog } from \"../catalog/index\";\nimport type { Capabilities } from \"../shape/capabilities\";\n\nfunction capsSummary(c: Capabilities): string {\n const flags: string[] = [\"text\"];\n if (c.imageIn) flags.push(\"image\");\n if (c.audioIn) flags.push(\"audio\");\n if (c.toolUse) flags.push(\"tools\");\n if (c.thinking) flags.push(\"thinking\");\n if (c.effort) flags.push(\"effort\");\n if (c.webSearch) flags.push(\"web-search\");\n if (c.structuredOutput) flags.push(\"structured\");\n return flags.join(\", \");\n}\n\n/** Generate the `llms.txt` context document for a given model catalog. */\nexport function generateLlmsTxt(catalog: Catalog = DEFAULT_CATALOG): string {\n const models = Object.values(catalog)\n .map((s) => `- \\`${s.id}\\` (${s.provider}) — ${capsSummary(s.capabilities)}`)\n .join(\"\\n\");\n\n return `# @odla-ai/ai — LLM context\n\n> EARLY ACCESS — pre-1.0. Agents work from bounded runbooks; humans approve\n> credentials, production changes, releases, and merges. APIs and exact package\n> availability can change. Review documented guarantees and limitations; this\n> software is MIT-licensed and provided without warranty.\n\nOne general-purpose interface for AI inference across Anthropic (Claude), OpenAI\n(GPT), and Google (Gemini) — text, image, and audio — plus a tool-use agent\nengine and an eval harness. Library-only: import in-process, bring your own keys.\nTargets Node 20+ and Cloudflare Workers. Provider adapters are runtime-lazy, but\nall provider SDKs are package dependencies. Never expose long-lived keys in a browser.\n\n## Install\n\n npm i @odla-ai/ai\n # optional, for odla-db-backed storage + secrets:\n # @odla-ai/db\n\n## Core call\n\n import { init } from \"@odla-ai/ai\";\n const ai = init({ keys: { anthropic: KEY, openai: KEY, google: KEY }, defaultModel: \"claude-opus-4-8\" });\n const res = await ai.chat({ model: \"gpt-5\", messages: [{ role: \"user\", content: \"hi\" }], maxTokens: 256 });\n // res.content: OracleContentBlock[] (text/tool_use/thinking)\n\n- \\`ai.stream(input)\\` → async iterable of normalized events: message_start →\n content_block_start → content_block_delta {text_delta|thinking_delta|input_json_delta}\n → content_block_stop → message_delta → message_stop (plus \\`error\\`).\n- \\`ai.extract<T>({ model, user, tool })\\` → forced tool call; returns an object\n validated against the declared JSON Schema. Unsupported assertions fail closed.\n- \\`ai.search({ model, user })\\` → web-search-grounded prose.\n\n## Content blocks (multimodal)\n\ntext; image { source: base64|url }; audio { source: base64|url }; document (PDF);\ntool_use { id, name, input }; tool_result { toolUseId, content }; thinking.\nAudio input is accepted by OpenAI (\\`gpt-audio\\`) and Google, NOT by Claude — an\naudio block to a Claude model throws CapabilityError before any network call.\n\n## Agents\n\n import { runAgent, type Persona, type ToolDef } from \"@odla-ai/ai\";\n const add: ToolDef = { name: \"add\", description: \"add\", inputSchema: {...}, handler: (i) => ({ content: String(i.a + i.b) }) };\n const persona: Persona = { name: \"calc\", model: \"claude-opus-4-8\", system: \"...\", tools: [add], maxSteps: 4 };\n const run = await runAgent(ai, persona, { input: \"what is 21+21?\" });\n // run.finalText, run.toolCalls, run.usage, run.steps, run.stoppedReason\n\nTools may carry taint labels (outputTaint / acceptsTaint) for a CaMeL-style\nprompt-injection gate. Personas may carry a MemoryScope. Tool inputs are schema-\nvalidated before handlers run. Pass signal/deadline and a run budget\n({maxInputTokens,maxOutputTokens,maxTotalTokens,maxToolCalls}) to bound follow-up\neffects and requested output. Input and total limits are post-turn ceilings:\nprovider usage is unavailable before the first response, so they cannot\ntokenizer-bound the first prompt. Output and remaining-total limits cap the next\nrequest's maxTokens. Token limits must be positive integers; maxToolCalls may be\nzero. Budget exits pair every requested tool_use with an error tool_result before\nmemory is persisted.\n\n## Skills\n\nA Skill = { name, instructions?, tools: ToolDef[] } is a bundle you attach to a\npersona (persona.skills); its tools merge into the model's tool list and its\ninstructions into the system prompt. Turn an odla-db entity into CRUD tools:\n\n import { entityCrudSkill } from \"@odla-ai/ai\";\n const todos = entityCrudSkill({ db, entity: \"todos\", fields: { text: { type: \"string\" }, done: { type: \"boolean\" } }, required: [\"text\"] });\n // → tools: list_todos, create_todo, update_todo (partial), delete_todo — handlers write to odla-db\n const run = await runAgent(ai, { name: \"todo-bot\", model: \"gpt-5\", skills: [todos] }, { input: \"add buy milk\" });\n\n## Evals\n\n import { evaluate, exactMatch, llmJudge } from \"@odla-ai/ai\";\n const report = await evaluate({ inference: ai, model: \"claude-opus-4-8\", grader: exactMatch(), cases: [{ input, expected }] });\n // graders: exactMatch, includes, structuredMatch, llmJudge; pass a persona to eval an agent.\n\n## Storage + BYO keys via odla-db (@odla-ai/db) — the handshake\n\nFollows odla-db's model. An agent never takes a platform secret; it does a\ndevice-authorization handshake for a scoped, revocable token, then provisions.\n\n import { requestToken, init as odlaInit } from \"@odla-ai/db\";\n import { provisionAgentApp, odlaDbKeyResolver, OdlaDbMemory, persistRun, init } from \"@odla-ai/ai\";\n\n const ODLA_PLATFORM = \"https://odla.ai\";\n const ODLA_DB_URL = \"https://db.odla.ai\";\n\n // 1. Handshake: the human approves a short code at odla.ai.\n const { token } = await requestToken({ endpoint: ODLA_PLATFORM, onCode: ({ userCode }) => show(userCode) });\n\n // 2. Provision: create app, mint app key, push agent schema, store BYO provider keys as secrets.\n const { appId, appKey } = await provisionAgentApp({ endpoint: ODLA_PLATFORM, token, providerKeys: { openai: OPENAI_KEY } });\n\n // 3. Runtime: read keys from odla-db secrets; persist memory + run traces.\n const db = odlaInit({ appId, adminToken: appKey, endpoint: ODLA_DB_URL });\n const ai = init({ resolveKey: odlaDbKeyResolver(db) });\n const persona = { name: \"assistant\", model: \"gpt-5\", memory: new OdlaDbMemory({ db, sessionId: \"user-42\" }) };\n const run = await runAgent(ai, persona, { input: \"hello\" });\n await persistRun(run, { db, sessionId: \"user-42\" });\n\nSecrets are read-only from the app key (odlaDbKeyResolver → db.secrets.get); they\nare WRITTEN only with the operator/dev token via provisionAgentApp/putSecret. Keys\nare AES-GCM-encrypted at rest in odla-db and never returned to browser clients.\n\n## Platform wiring (odla.ai apps registry)\n\nApps registered on the odla platform get LLM access as an APP SETTING —\nnever put provider keys in your Worker's wrangler vars/secrets. Provider +\ndefault model are per-environment registry config (set in Studio's AI card\nor \\`@odla-ai/apps\\` setAi); the API key lives in the platform vault (the\nenv's odla-db tenant secrets, write-only for operators). One call reads both:\n\n import { initFromPlatform } from \"@odla-ai/ai\";\n import { init as odlaInit } from \"@odla-ai/db\";\n\n const db = odlaInit({ appId: TENANT, adminToken: env.ODLA_API_KEY, endpoint: \"https://db.odla.ai\" });\n const { ai, provider, model } = await initFromPlatform({\n platform: \"https://odla.ai\", appId: APP_ID, env: \"prod\", db });\n // ai.chat / ai.stream / ai.extract — provider/model from public-config\n // (cached ~60s, so Studio changes apply without redeploys); the key is\n // fetched from the vault via a finite-TTL odlaDbKeyResolver.\n\nThe only secret the Worker carries is its odla-db app key. Rotating the LLM\nkey = writing the secret again; the default warm-isolate key TTL is 60 seconds\nand cacheVersion provides immediate invalidation. Provider SDK clients are\nfingerprinted, bounded to one generation per provider, and expire after 60\nseconds. The platform provider is enforced: models from other providers are\nabsent from the facade catalog. If no default model is configured, each call\nmust name a model for that provider. Only public config is shared; tenant-bound\nAi facades are not cached globally.\n\n## Errors\n\nEvery error is an OdlaAIError subclass with a stable \\`code\\` — branch on err.code:\nconfig, auth, rate_limit, capability_unsupported, context_window, invalid_request,\ntool_input_invalid, cancelled, deadline_exceeded, provider_error.\n\n## Models\n\n${models}\n\nModel ids live in a data catalog and drift — verify against provider docs; extend\nvia buildCatalog / init({ catalog }).\n`;\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 CancelledError,\n ConfigError,\n DeadlineExceededError,\n emptyUsage,\n extractText,\n extractToolUses,\n validateJsonSchema,\n type OracleContentBlock,\n type OracleMessage,\n type OracleResponse,\n type OracleUsage,\n type ToolResultBlock,\n type ToolUseBlock,\n} from \"../shape/index\";\nimport type { Inference } from \"../client/init\";\nimport { signalWithDeadline, throwIfAborted } from \"../client/abort\";\nimport type { Persona } from \"./persona\";\nimport type { ToolDef, ToolOutput } from \"./tools\";\nimport { toOracleTool } from \"./tools\";\nimport { composeSkills } from \"./skill\";\nimport { assertSinkAcceptsTaint, type TaintLabel, type TaintSet } from \"./taint\";\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}\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\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 /** Every tool call executed, in order. */\n toolCalls: ToolCallRecord[];\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 accumulatedTaint: TaintSet = new Set<TaintLabel>([\"llm_inherited\"]);\n const maxSteps = persona.maxSteps ?? 8;\n const runSignal = signalWithDeadline(input.signal, input.deadline);\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 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 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 resultBlocks: ToolResultBlock[] = [];\n for (const toolUse of toolUses) {\n if (input.budget?.maxToolCalls !== undefined && attemptedToolCalls >= input.budget.maxToolCalls) {\n stoppedReason = \"budget_exhausted\";\n resultBlocks.push(errorResult(toolUse.id, \"Run tool-call budget exhausted before execution.\"));\n continue;\n }\n attemptedToolCalls++;\n const def = handlerByName.get(toolUse.name);\n if (!def || !def.handler) {\n resultBlocks.push(errorResult(toolUse.id, `No local handler for tool \"${toolUse.name}\".`));\n continue;\n }\n if (def.acceptsTaint) assertSinkAcceptsTaint(def.name, def.acceptsTaint, accumulatedTaint);\n\n let output: ToolOutput;\n const validation = validateJsonSchema(def.inputSchema, toolUse.input);\n if (!validation.valid) {\n const detail = validation.issues.slice(0, 5).map((i) => `${i.path} ${i.message}`).join(\"; \");\n output = { content: `Tool \"${toolUse.name}\" input is invalid: ${detail}`, isError: true };\n } else {\n throwIfAborted(runSignal);\n try {\n output = await def.handler(toolUse.input, { taint: new Set(accumulatedTaint), signal: runSignal });\n } catch (error) {\n if (error instanceof CancelledError || error instanceof DeadlineExceededError) throw error;\n throwIfAborted(runSignal);\n // Handler messages can contain credentials or upstream payloads. The\n // model gets a stable sanitized error; applications can instrument\n // the handler itself when they need private diagnostics.\n output = { content: `Tool \"${toolUse.name}\" failed.`, isError: true };\n }\n }\n toolCalls.push({ toolUse, output });\n resultBlocks.push({ type: \"tool_result\", toolUseId: toolUse.id, content: output.content, isError: output.isError });\n for (const label of def.outputTaint ?? []) accumulatedTaint.add(label);\n }\n messages.push({ role: \"user\", content: resultBlocks });\n if (stoppedReason === \"budget_exhausted\") break;\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 toolCalls,\n stoppedReason,\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 /** 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 /** 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. */\nexport class TaintError extends OdlaAIError {\n constructor(message: string) {\n super(\"invalid_request\", message);\n }\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(\n `Tool \"${sink}\" refused: conversation carries taint \"${label}\" which is not in its allowlist [${allowed.join(\", \")}].`,\n );\n }\n }\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","// 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: one call turns an odla.ai app registration into a ready\n// `Ai`. The NON-SECRET half ({provider, model?}) comes from the registry's\n// anonymous public-config endpoint — so switching provider/model in Studio\n// needs no redeploy; the SECRET half (the provider API key) never travels\n// through the registry at all: it is read from the app's own odla-db tenant\n// secrets at call time via `odlaDbKeyResolver`. The only credential the\n// caller holds is its odla-db app key (inside `db`).\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 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 env's tenant id. */\n appId: string;\n /** Which environment's config to use (\"dev\", \"prod\", …). */\n env: string;\n /** The app's own tenant client — key reads go through `db.secrets.get`. */\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 (catalog, injected providers, …). `resolveKey` is\n * owned by this helper; `defaultModel` is used only when the platform\n * config sets no model. */\n initOptions?: Omit<InitOptions, \"resolveKey\">;\n /** Secret resolver cache controls. Defaults to a finite 60-second TTL. */\n keyResolverOptions?: OdlaDbKeyResolverOptions;\n}\n\nexport interface PlatformAi {\n ai: Ai;\n provider: ProviderId;\n model?: string;\n}\n\ninterface CacheEntry {\n value: { provider: ProviderId; model?: string };\n expiresAt: number;\n}\n\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?: { provider?: unknown; model?: unknown } | null;\n}\n\nasync function fetchAiConfig(opts: InitFromPlatformOptions): Promise<{ provider: ProviderId; model?: string }> {\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 || typeof ai.provider !== \"string\") {\n throw new ConfigError(\n `ai service is not enabled/configured for \"${opts.appId}\" (${opts.env}) — ` +\n `enable it in Studio or via @odla-ai/apps setAi(appId, env, { provider }).`,\n );\n }\n if (!(ai.provider in DEFAULT_SECRET_NAMES)) {\n throw new ConfigError(`platform ai config names unknown provider \"${ai.provider}\" for \"${opts.appId}\" (${opts.env}).`);\n }\n const model = typeof ai.model === \"string\" && ai.model ? ai.model : undefined;\n return { provider: ai.provider as ProviderId, ...(model ? { model } : {}) };\n}\n\n/** Build an `Ai` from the app's platform registration: provider/model from\n * public-config (cached ~60s), API key from the supplied tenant's odla-db\n * secrets at call time. Only public config is shared globally; every call\n * builds a facade bound to its own `db` and init options. */\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 const { provider, model } = config;\n if (ttl > 0 && (!hit || hit.expiresAt <= now)) cache.set(key, { value: config, expiresAt: now + ttl });\n\n // The platform provider is an isolation boundary, not merely a UI hint.\n // Calls may select any model for that provider, but cannot route around the\n // configured tenant credential by naming another provider's model.\n const sourceCatalog = opts.initOptions?.catalog ?? DEFAULT_CATALOG;\n const catalog: Catalog = Object.fromEntries(\n Object.entries(sourceCatalog).filter(([, spec]) => spec.provider === provider),\n );\n const defaultModel = model ?? opts.initOptions?.defaultModel;\n if (defaultModel) resolveModel(catalog, defaultModel);\n\n const ai = init({\n ...opts.initOptions,\n catalog,\n resolveKey: odlaDbKeyResolver(opts.db, opts.keyResolverOptions),\n defaultModel,\n });\n const value: PlatformAi = { ai, provider, ...(model ? { model } : {}) };\n return value;\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, 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 };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUO,SAAS,aAA0B;AACxC,SAAO,EAAE,aAAa,GAAG,cAAc,EAAE;AAC3C;AAGO,SAAS,SAAS,MAAmB,MAAyB;AACnE,OAAK,eAAe,KAAK;AACzB,OAAK,gBAAgB,KAAK;AAC1B,MAAI,KAAK,wBAAwB,QAAW;AAC1C,SAAK,uBAAuB,KAAK,uBAAuB,KAAK,KAAK;AAAA,EACpE;AACA,MAAI,KAAK,oBAAoB,QAAW;AACtC,SAAK,mBAAmB,KAAK,mBAAmB,KAAK,KAAK;AAAA,EAC5D;AACF;AAxBA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;;;ACAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,IA6Ba,aA6BA,aAOA,WAOA,gBASA,iBAOA,oBAOA,qBAQA,gBAWA,gBAQA,uBAOA;AAjIb;AAAA;AAAA;AA6BO,IAAM,cAAN,cA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init_request","init_errors","init_request","Anthropic","init_blocks","buildParams","buildTools","mapToolChoice","init_request","init_blocks","mapUsage","init_response","mapUsage","init_stream","init_response","import_openai","init_errors","init_request","init_response","init_stream","OpenAI","buildParams","buildParams","buildTools","mapToolChoice","init_request","init_blocks","mapResponse","mapFinish","mapUsage","init_response","mapStream","mapUsage","mapFinish","init_stream","init_response","mapResponse","import_genai","init_errors","init_request","init_response","init_stream","buildParams","mapStream","overrides","AnthropicProvider","OpenAIProvider","GoogleProvider","init_errors","cache","cache"]}
|