@theokit/sdk 4.12.2 → 4.13.0
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/CHANGELOG.md +6 -0
- package/dist/cron.cjs +164 -78
- package/dist/cron.cjs.map +1 -1
- package/dist/cron.js +164 -78
- package/dist/cron.js.map +1 -1
- package/dist/eval.cjs +164 -78
- package/dist/eval.cjs.map +1 -1
- package/dist/eval.js +164 -78
- package/dist/eval.js.map +1 -1
- package/dist/index.cjs +178 -92
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +178 -92
- package/dist/index.js.map +1 -1
- package/dist/internal/providers/catalog-loader.d.ts +8 -0
- package/dist/internal/providers/catalog-schema.d.ts +53 -0
- package/dist/internal/providers/catalog-source-models-dev.d.ts +33 -0
- package/dist/models.cjs +332 -257
- package/dist/models.cjs.map +1 -1
- package/dist/models.d.cts +2 -0
- package/dist/models.d.ts +2 -0
- package/dist/models.js +330 -258
- package/dist/models.js.map +1 -1
- package/dist/provider-catalog.json +571 -5
- package/package.json +1 -1
package/dist/models.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/internal/llm/model-capabilities.ts","../src/internal/llm/model-identifier.ts","../src/internal/llm/model-option.ts"],"names":[],"mappings":";AAgCA,IAAM,qBAAA,GAA2C;AAAA,EAC/C,cAAA,EAAgB,KAAA;AAAA,EAChB,wBAAA,EAA0B,KAAA;AAAA,EAC1B,eAAA,EAAiB,KAAA;AAAA,EACjB,oBAAA,EAAsB,KAAA;AAAA,EACtB,gBAAA,EAAkB,IAAA;AAAA,EAClB,eAAA,EAAiB;AACnB,CAAA;AAGA,IAAM,KAAA,uBAAoD,GAAA,CAAI;AAAA;AAAA,EAE5D;AAAA,IACE,eAAA;AAAA,IACA;AAAA,MACE,cAAA,EAAgB,IAAA;AAAA,MAChB,wBAAA,EAA0B,IAAA;AAAA,MAC1B,eAAA,EAAiB,IAAA;AAAA,MACjB,oBAAA,E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AK,WAAA,CAAY,GAAG,CAAA;AACtC,EAAA,MAAM,OAAO,SAAA,IAAa,CAAA,GAAI,KAAK,KAAA,CAAM,SAAA,GAAY,CAAC,CAAA,GAAI,IAAA;AAC1D,EAAA,MAAM,QAAQ,IAAA,CACX,KAAA,CAAM,UAAU,CAAA,CAChB,OAAO,CAAC,CAAA,KAAM,CAAA,CAAE,MAAA,GAAS,CAAC,CAAA,CAC1B,GAAA,CAAI,WAAW,CAAA,CACf,KAAK,GAAG,CAAA;AACX,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,OAAA;AAC/B,EAAA,OAAO,QAAQ,MAAA,GAAS,CAAA,GAAI,GAAG,KAAK,CAAA,EAAA,EAAK,OAAO,CAAA,CAAA,CAAA,GAAM,KAAA;AACxD;AAUO,SAAS,cAAc,OAAA,EAA8B;AAC1D,EAAA,OAAO;AAAA,IACL,KAAA,EAAO,OAAA;AAAA,IACP,KAAA,EAAO,kBAAkB,OAAO,CAAA;AAAA,IAChC,QAAA,EAAU,YAAA,CAAa,OAAO,CAAA,CAAE;AAAA,GAClC;AACF","file":"models.js","sourcesContent":["/**\n * T3.10c — Model capability registry (DR3 #17).\n *\n * Typed per-model flags that let the SDK gate features at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Exact-match capability entries. Keys are `vendor/model` (no routing prefix). */\nconst EXACT: ReadonlyMap<string, ModelCapabilities> = new Map([\n // OpenAI family\n [\n \"openai/gpt-4o\",\n {\n supportsVision: true,\n supportsStructuredOutput: true,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 128_000,\n maxOutputTokens: 16_384,\n },\n ],\n [\n \"openai/gpt-4o-mini\",\n {\n supportsVision: true,\n supportsStructuredOutput: true,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 128_000,\n maxOutputTokens: 16_384,\n },\n ],\n [\n \"openai/gpt-4-turbo\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 128_000,\n maxOutputTokens: 4096,\n },\n ],\n [\n \"openai/o1\",\n {\n supportsVision: false,\n supportsStructuredOutput: true,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 200_000,\n maxOutputTokens: 100_000,\n },\n ],\n [\n \"openai/o3\",\n {\n supportsVision: false,\n supportsStructuredOutput: true,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 200_000,\n maxOutputTokens: 100_000,\n },\n ],\n [\n // GPT-4.1 — 1M-context flagship; multimodal + structured output (RADAR #92.a).\n \"openai/gpt-4.1\",\n {\n supportsVision: true,\n supportsStructuredOutput: true,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 1_047_576,\n maxOutputTokens: 32_768,\n },\n ],\n // Anthropic family\n [\n \"anthropic/claude-opus-4\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 32_000,\n },\n ],\n [\n \"anthropic/claude-sonnet-4\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 16_000,\n },\n ],\n [\n \"anthropic/claude-3-5-sonnet\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 8192,\n },\n ],\n [\n \"anthropic/claude-3-5-sonnet-latest\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 8192,\n },\n ],\n [\n \"anthropic/claude-3-5-haiku-latest\",\n {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 8192,\n },\n ],\n [\n \"anthropic/claude-3-haiku\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 4096,\n },\n ],\n [\n \"anthropic/claude-3-opus\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 4096,\n },\n ],\n // Dot-form OpenRouter slugs theocode uses (RADAR #92.a). These are the same\n // models as their dash-form siblings above; capability parity is intentional.\n // Without these entries the dotted slugs fall through to the 4096 default\n // (`anthropic/claude-3.5-sonnet` ≠ `anthropic/claude-3-5-sonnet`).\n [\n \"anthropic/claude-opus-4.1\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 32_000,\n },\n ],\n [\n \"anthropic/claude-sonnet-4.5\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 16_000,\n },\n ],\n [\n \"anthropic/claude-3.5-sonnet\",\n {\n supportsVision: true,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: true,\n maxContextTokens: 200_000,\n maxOutputTokens: 8192,\n },\n ],\n // Cheap OpenRouter slugs (RADAR #92.a) — previously fell to the 4096\n // CONSERVATIVE default. toolUse on; vision/structuredOutput only for Gemini.\n [\n \"qwen/qwen3-coder-30b-a3b-instruct\",\n {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 160_000,\n maxOutputTokens: 8000,\n },\n ],\n [\n \"deepseek/deepseek-v4-flash\",\n {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 1_048_576,\n maxOutputTokens: 8000,\n },\n ],\n [\n \"deepseek/deepseek-v3.2\",\n {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 131_072,\n maxOutputTokens: 8000,\n },\n ],\n [\n \"z-ai/glm-4.7-flash\",\n {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 202_752,\n maxOutputTokens: 8000,\n },\n ],\n [\n \"google/gemini-2.5-flash-lite\",\n {\n supportsVision: true,\n supportsStructuredOutput: true,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 1_048_576,\n maxOutputTokens: 8000,\n },\n ],\n [\n \"google/gemini-2.5-pro\",\n {\n supportsVision: true,\n supportsStructuredOutput: true,\n supportsToolUse: true,\n supportsCacheControl: false,\n maxContextTokens: 1_048_576,\n maxOutputTokens: 8000,\n },\n ],\n]);\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n const exact = EXACT.get(bare);\n if (exact !== undefined) return exact;\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = EXACT.get(withVendor);\n if (vendored !== undefined) return vendored;\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n","/**\n * Model identifier parsing (T1.2 follow-up, ADR D182 zero-config UX).\n *\n * SDK callers pass model strings like:\n * - `\"ollama/llama3.2:3b\"` → provider=\"ollama\", name=\"llama3.2:3b\"\n * - `\"anthropic/claude-3-5-sonnet\"` → provider=\"anthropic\", name=\"claude-3-5-sonnet\"\n * - `\"openrouter/meta-llama/llama-3\"` → provider=\"openrouter\", name=\"meta-llama/llama-3\"\n * - `\"claude-sonnet-4-6\"` → provider=undefined, name=\"claude-sonnet-4-6\"\n *\n * The first `/` separates the provider from the rest. Models with embedded\n * slashes (e.g. OpenRouter routing) keep the remainder intact. Tag suffixes\n * (`:latest`, `:3b`) are preserved as part of the name — Ollama expects them.\n *\n * **Returns `undefined` provider** when no `/` is present so callers can\n * fall back to env-var detection. Empty/whitespace components are treated\n * as no-prefix.\n *\n * Aligned with peer-project `extensions/ollama/src/discovery-shared.ts`\n * (`OLLAMA_PROVIDER_ID = \"ollama\"`) and Hermes `hermes_cli/providers.py`\n * (ALIASES table, `normalize_provider`).\n *\n * Public via `@theokit/sdk/models` (M5-8).\n *\n * @public\n */\n\nexport interface ParsedModelId {\n /** Provider name extracted from the prefix (lowercase), or undefined. */\n provider: string | undefined;\n /** Model name to send to the provider — prefix stripped. */\n name: string;\n}\n\n/** Provider aliases mirrored from Hermes `hermes_cli/providers.py` ALIASES. */\nconst PROVIDER_ALIASES: Readonly<Record<string, string>> = {\n \"llama-cpp\": \"llamacpp\",\n \"llama.cpp\": \"llamacpp\",\n \"lm-studio\": \"lmstudio\",\n lm_studio: \"lmstudio\",\n};\n\nexport function parseModelId(modelId: string | undefined): ParsedModelId {\n if (modelId === undefined || modelId.length === 0) {\n return { provider: undefined, name: \"\" };\n }\n const slash = modelId.indexOf(\"/\");\n if (slash <= 0 || slash === modelId.length - 1) {\n return { provider: undefined, name: modelId };\n }\n const rawProvider = modelId.slice(0, slash).trim().toLowerCase();\n const name = modelId.slice(slash + 1).trim();\n if (rawProvider.length === 0 || name.length === 0) {\n return { provider: undefined, name: modelId };\n }\n const canonical = PROVIDER_ALIASES[rawProvider] ?? rawProvider;\n return { provider: canonical, name };\n}\n","import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n const base = (colon >= 0 ? name.slice(0, colon) : name).replace(/\\/+$/, \"\");\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/internal/providers/catalog-schema.ts","../src/internal/providers/registry.ts","../src/internal/providers/catalog-loader.ts","../src/internal/llm/model-capabilities.ts","../src/internal/llm/model-identifier.ts","../src/internal/llm/model-option.ts","../src/errors.ts","../src/internal/runtime/retry/with-retry.ts","../src/retry.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":["join","dirname","readFileSync"],"mappings":";;;;;;;;AAeO,IAAM,aAAa,CAAC,MAAA,EAAQ,OAAA,EAAS,OAAA,EAAS,SAAS,KAAK,CAAA;AAGnE,IAAM,UAAA,GAAa,EAChB,MAAA,CAAO;AAAA;AAAA,EAEN,KAAA,EAAO,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,EAAY;AAAA,EAC9B,MAAA,EAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,EAAY;AAAA,EAC/B,YAAY,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,GAAc,QAAA,EAAS;AAAA,EAC9C,aAAa,CAAA,CAAE,MAAA,EAAO,CAAE,WAAA,GAAc,QAAA;AACxC,CAAC,EACA,KAAA,EAAM;AAET,IAAM,WAAA,GAAc,EACjB,MAAA,CAAO;AAAA,EACN,OAAA,EAAS,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC7B,OAAO,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,GAAW,QAAA,EAAS;AAAA,EACtC,QAAQ,CAAA,CAAE,MAAA,EAAO,CAAE,QAAA,GAAW,QAAA;AAChC,CAAC,EACA,KAAA,EAAM;AAET,IAAM,gBAAA,GAAmB,EACtB,MAAA,CAAO;AAAA,EACN,KAAA,EAAO,EAAE,KAAA,CAAM,CAAA,CAAE,KAAK,UAAU,CAAC,EAAE,QAAA,EAA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,MAAM,IAAI,KAAA,CAAM,CAAA,KAAA,EAAQ,CAAA,CAAE,MAAM,CAAA,CAAE,CAAA;AAC7C,QAAA,OAAO,CAAA;AAAA,MACT,CAAA;AAAA;AAAA;AAAA,MAGA,EAAE,OAAA,EAAS,CAAA,EAAG,aAAa,MAAM,IAAA,EAAM,gBAAgB,GAAA;AAAI,KAC7D;AACA,IAAA,IAAA,GAAO,MAAM,IAAI,IAAA,EAAK;AACtB,IAAA,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACjB,SAAS,GAAA,EAAK;AACZ,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,MACb,CAAA,+CAAA,EAAmD,IAAc,OAAO,CAAA;AAAA;AAAA,KAC1E;AAEA,IAAA,OAAO,EAAE,MAAA,EAAQ,OAAA,EAAS,MAAA,EAAQ,kBAAA,CAAmB,GAAG,CAAA,EAAE;AAAA,EAC5D;AAEA,EAAA,IAAI;AACF,IAAA,gBAAA,CAAiB,MAAM,IAAI,CAAA;AAAA,EAC7B,SAAS,GAAA,EAAK;AACZ,IAAA,OAAA,CAAQ,MAAA,CAAO,KAAA;AAAA,MACb,CAAA,mDAAA,EAAuD,IAAc,OAAO,CAAA;AAAA;AAAA,KAC9E;AAAA,EACF;AACA,EAAA,OAAO,EAAE,QAAQ,SAAA,EAAW,MAAA,EAAQ,sBAAsB,IAAA,CAAK,KAAA,CAAM,IAAI,CAAC,CAAA,EAAE;AAC9E;AAGO,SAAS,aAAa,OAAA,EAAyD;AACpF,EAAA,OAAO,oBAAoB,OAAO,CAAA;AACpC","file":"models.js","sourcesContent":["import { z } from \"zod\";\n\n/**\n * M44 — the per-model catalog sub-schema. Field names mirror models.dev VERBATIM (snake_case) so\n * `scripts/refresh-catalog.mjs` regenerates the vendored data mechanically from `api.json` with zero\n * renaming (ADR D1; OpenCode keeps the raw shape on disk and maps at load — `core/src/models-dev.ts`).\n * TOLERANT by design: every field optional, unknown keys ignored — models.dev adds fields over time and\n * additive drift must never break the loader (Blueprint §6.4).\n *\n * theokit extensions beyond models.dev: `structured_output` / `cache_control` (both already exist on the\n * SDK's `ModelCapabilities`; models.dev has no such flags).\n *\n * @internal\n */\n\nexport const MODALITIES = [\"text\", \"audio\", \"image\", \"video\", \"pdf\"] as const;\nexport type Modality = (typeof MODALITIES)[number];\n\nconst costSchema = z\n .object({\n /** USD per 1M tokens (models.dev convention). */\n input: z.number().nonnegative(),\n output: z.number().nonnegative(),\n cache_read: z.number().nonnegative().optional(),\n cache_write: z.number().nonnegative().optional(),\n })\n .loose();\n\nconst limitSchema = z\n .object({\n context: z.number().positive(),\n input: z.number().positive().optional(),\n output: z.number().positive().optional(),\n })\n .loose();\n\nconst modalitiesSchema = z\n .object({\n input: z.array(z.enum(MODALITIES)).optional(),\n output: z.array(z.enum(MODALITIES)).optional(),\n })\n .loose();\n\nexport const catalogModelSchema = z\n .object({\n name: z.string().optional(),\n release_date: z.string().optional(),\n attachment: z.boolean().optional(),\n reasoning: z.boolean().optional(),\n temperature: z.boolean().optional(),\n tool_call: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsStructuredOutput. */\n structured_output: z.boolean().optional(),\n /** theokit extension — maps to ModelCapabilities.supportsCacheControl. */\n cache_control: z.boolean().optional(),\n cost: costSchema.optional(),\n limit: limitSchema.optional(),\n modalities: modalitiesSchema.optional(),\n status: z.enum([\"alpha\", \"beta\", \"deprecated\"]).optional(),\n })\n .loose();\n\nexport type CatalogModel = z.infer<typeof catalogModelSchema>;\nexport type CatalogModelCost = z.infer<typeof costSchema>;\n","/**\n * Provider registry (T3.2, ADR D107).\n *\n * `registerProvider` is idempotent and surface-warning: re-registering\n * a `name` logs to stderr (D107 last-writer-wins with WARN). Alias\n * collisions also warn (EC-5).\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"./types.js\";\n\nconst REGISTRY = new Map<string, ProviderProfile>();\nconst ALIASES = new Map<string, string>();\n\nexport function registerProvider(profile: ProviderProfile): void {\n if (REGISTRY.has(profile.name)) {\n process.stderr.write(`[theokit-sdk] Provider \"${profile.name}\" overridden by user plugin.\\n`);\n }\n REGISTRY.set(profile.name, profile);\n for (const alias of profile.aliases ?? []) {\n // EC-5: surface alias collision so operators notice mis-routing.\n const previous = ALIASES.get(alias);\n if (previous !== undefined && previous !== profile.name) {\n process.stderr.write(\n `[theokit-sdk] Alias \"${alias}\" collision: was \"${previous}\", now \"${profile.name}\".\\n`,\n );\n }\n ALIASES.set(alias, profile.name);\n }\n}\n\nexport function getProviderProfile(name: string): ProviderProfile | undefined {\n const canonical = ALIASES.get(name) ?? name;\n return REGISTRY.get(canonical);\n}\n\nexport function listProviders(): ProviderProfile[] {\n return Array.from(REGISTRY.values());\n}\n\n/** Test-only reset. @internal */\nexport function _resetProvidersForTests(): void {\n REGISTRY.clear();\n ALIASES.clear();\n}\n","/**\n * Dynamic provider catalog loader (T10.1, ADR D447).\n *\n * Loads provider metadata from `provider-catalog.json` at runtime.\n * Malformed entries are skipped with WARN (EC-1) — never crash.\n *\n * @internal\n */\n\nimport { readFileSync } from \"node:fs\";\nimport { dirname, join } from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { type CatalogModel, catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile, registerProvider } from \"./registry.js\";\nimport type { ApiMode, AuthType, ProviderProfile } from \"./types.js\";\n\nconst __dirname_resolved = dirname(fileURLToPath(import.meta.url));\n\nexport interface ProviderCapabilities {\n supportsToolUse: boolean;\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsStreaming: boolean;\n supportsCacheControl: boolean;\n maxContextTokens?: number;\n maxOutputTokens?: number;\n}\n\nexport interface CatalogEntry {\n id: string;\n displayName: string;\n apiMode: ApiMode;\n authType: AuthType;\n baseUrl: string;\n envVars: string[];\n fallbackModels: string[];\n capabilities: ProviderCapabilities;\n aliases?: string[];\n modelsUrl?: string;\n hostname?: string;\n extraHeaders?: Record<string, string>;\n /**\n * M44 — OPTIONAL per-model data (models.dev shape, snake_case — see `catalog-schema.ts`), keyed by the\n * BARE model id. Additive: entries without it behave byte-identically to before. The loader indexes this\n * into the model-info index (`getCatalogModelInfo`) rather than onto `ProviderProfile` (ADR D2 — the\n * builtins-first registration skip means profile-attached data would never reach builtin providers).\n */\n models?: Record<string, CatalogModel>;\n}\n\n/**\n * M44 — the model-info index: `provider/model` → per-model catalog data (the EXACT-map key convention).\n * Populated by the vendored catalog load AND patched by the optional models-dev source (cache entries win\n * per model). The single lookup surface for capability / cost / limit enrichment.\n */\nconst modelInfoIndex = new Map<string, CatalogModel>();\n\n/** Look up per-model catalog data by `provider/model` key. @internal */\nexport function getCatalogModelInfo(key: string): CatalogModel | undefined {\n ensureModelIndexLoaded();\n return modelInfoIndex.get(key);\n}\n\n/**\n * Patch the index with fresher per-model data (the models-dev source). A patched entry wins over the\n * vendored one for that model (shallow per-model replace — mirrors OpenCode's `catalog.model.update`).\n * @internal\n */\nexport function patchModelInfo(key: string, model: CatalogModel): void {\n ensureModelIndexLoaded();\n modelInfoIndex.set(key, model);\n}\n\n/** All indexed `provider/model` keys (for maintenance/tests). @internal */\nexport function listModelInfoKeys(): string[] {\n ensureModelIndexLoaded();\n return [...modelInfoIndex.keys()];\n}\n\nlet _modelIndexLoaded = false;\nfunction ensureModelIndexLoaded(): void {\n if (_modelIndexLoaded) return;\n _modelIndexLoaded = true;\n const catalog = loadProviderCatalog();\n for (const entry of Object.values(catalog)) {\n indexEntryModels(entry);\n }\n}\n\n/**\n * Index an entry's `models` block. Runs for EVERY catalog entry — including those whose PROVIDER\n * registration is skipped builtins-first — so builtin providers still get their per-model data (ADR D2).\n * A malformed model sub-entry drops THAT MODEL with WARN and keeps the provider (EC-1 philosophy extended).\n */\nfunction indexEntryModels(entry: CatalogEntry): void {\n if (entry.models === undefined || typeof entry.models !== \"object\") return;\n for (const [modelId, raw] of Object.entries(entry.models)) {\n const parsed = catalogModelSchema.safeParse(raw);\n if (!parsed.success) {\n process.stderr.write(\n `[theokit-sdk] WARN: Skipping malformed catalog model \"${entry.id}/${modelId}\": ` +\n `${parsed.error.issues[0]?.message ?? \"invalid\"}\\n`,\n );\n continue;\n }\n // Index under the entry id AND every alias — capability lookups are VENDOR-keyed (e.g.\n // `google/gemini-2.5-pro` while the entry id is `google-gemini` with alias `google`), so alias keys are\n // what make the vendor-keyed convention resolve without a second mapping table.\n modelInfoIndex.set(`${entry.id}/${modelId}`, parsed.data);\n for (const alias of entry.aliases ?? []) {\n const key = `${alias}/${modelId}`;\n if (!modelInfoIndex.has(key)) modelInfoIndex.set(key, parsed.data);\n }\n }\n}\n\n/** Test-only reset for the model-info index. @internal */\nexport function _resetModelInfoIndexForTests(): void {\n modelInfoIndex.clear();\n _modelIndexLoaded = false;\n}\n\ninterface LoadOptions {\n _testInjectMalformed?: boolean;\n}\n\nfunction validateEntry(raw: Record<string, unknown>): CatalogEntry | null {\n if (\n typeof raw.id !== \"string\" ||\n typeof raw.displayName !== \"string\" ||\n typeof raw.apiMode !== \"string\" ||\n typeof raw.authType !== \"string\" ||\n typeof raw.baseUrl !== \"string\" ||\n !Array.isArray(raw.envVars) ||\n !Array.isArray(raw.fallbackModels) ||\n raw.capabilities == null ||\n typeof raw.capabilities !== \"object\"\n ) {\n return null;\n }\n return raw as unknown as CatalogEntry;\n}\n\nexport function loadProviderCatalog(opts?: LoadOptions): Record<string, CatalogEntry> {\n const catalogPath = join(__dirname_resolved, \"provider-catalog.json\");\n const rawText = readFileSync(catalogPath, \"utf-8\");\n let entries: Record<string, unknown>[] = JSON.parse(rawText);\n\n if (opts?._testInjectMalformed) {\n entries = [\n ...entries,\n { id: \"malformed-provider\", displayName: \"Bad\" } as Record<string, unknown>,\n ];\n }\n\n const result: Record<string, CatalogEntry> = {};\n for (const raw of entries) {\n const validated = validateEntry(raw as Record<string, unknown>);\n if (validated === null) {\n process.stderr.write(\n `[theokit-sdk] WARN: Skipping malformed catalog entry: ${JSON.stringify(raw).slice(0, 100)}\\n`,\n );\n continue;\n }\n result[validated.id] = validated;\n }\n return result;\n}\n\nlet _capabilitiesCache: Record<string, ProviderCapabilities> | null = null;\n\nexport function getCatalogCapabilities(providerId: string): ProviderCapabilities | undefined {\n if (_capabilitiesCache === null) {\n const catalog = loadProviderCatalog();\n _capabilitiesCache = {};\n for (const entry of Object.values(catalog)) {\n _capabilitiesCache[entry.id] = entry.capabilities;\n }\n }\n return _capabilitiesCache[providerId];\n}\n\nexport function registerCatalogProviders(opts?: LoadOptions): void {\n const catalog = loadProviderCatalog(opts);\n for (const entry of Object.values(catalog)) {\n // Skip catalog entries that would overwrite first-party builtins.\n // Builtins have richer env-var handling and are registered first.\n // Also skip if any alias collides with an existing provider name.\n if (getProviderProfile(entry.id) !== undefined) continue;\n if (entry.aliases?.some((a) => getProviderProfile(a) !== undefined)) continue;\n\n const profile: ProviderProfile = {\n name: entry.id,\n apiMode: entry.apiMode,\n authType: entry.authType,\n baseUrl: entry.baseUrl,\n envVars: entry.envVars,\n fallbackModels: entry.fallbackModels,\n displayName: entry.displayName,\n aliases: entry.aliases,\n modelsUrl: entry.modelsUrl,\n hostname: entry.hostname,\n extraHeaders: entry.extraHeaders,\n };\n registerProvider(profile);\n }\n}\n","/**\n * T3.10c — Model capability registry (DR3 #17).\n *\n * Typed per-model flags that let the SDK gate features at the boundary\n * (before hitting the provider) instead of letting opaque 400s surface.\n *\n * Resolution algorithm:\n * 1. Strip routing prefixes (openrouter/, vertex/, bedrock/) AND the\n * OpenRouter `:variant` suffix (:free/:nitro/…) to find the bare vendor id.\n * 2. Exact match in the `EXACT` catalog → return entry.\n * 3. Vendor inference (e.g., `claude-*` → `anthropic/claude-*`) → return entry.\n * 4. No match → conservative defaults (all false, minimum tokens).\n *\n * Module is internal, but `ModelCapabilities` + `resolveModelCapabilities` are\n * re-exported publicly via the `@theokit/sdk/models` subpath (see their @public tags).\n */\n\n/**\n * Per-model capability shape. Consumers use this to gate features at\n * the SDK boundary (before request construction, not after 400).\n *\n * @public\n */\nexport interface ModelCapabilities {\n supportsVision: boolean;\n supportsStructuredOutput: boolean;\n supportsToolUse: boolean;\n supportsCacheControl: boolean;\n maxContextTokens: number;\n maxOutputTokens: number;\n}\n\nconst CONSERVATIVE_DEFAULTS: ModelCapabilities = {\n supportsVision: false,\n supportsStructuredOutput: false,\n supportsToolUse: false,\n supportsCacheControl: false,\n maxContextTokens: 4096,\n maxOutputTokens: 4096,\n};\n\n/** Routing prefixes to strip to find the underlying vendor model. */\nconst ROUTING_PREFIXES = [\"openrouter/\", \"vertex/\", \"bedrock/\"] as const;\n\nimport { getCatalogModelInfo } from \"../providers/catalog-loader.js\";\nimport type { CatalogModel } from \"../providers/catalog-schema.js\";\n\n/** Map a catalog model block (models.dev shape) to the SDK's ModelCapabilities (M44 — catalog-backed). */\nfunction capsFromCatalog(m: CatalogModel): ModelCapabilities {\n return {\n supportsVision: m.modalities?.input?.includes(\"image\") ?? m.attachment ?? false,\n supportsStructuredOutput: m.structured_output ?? false,\n supportsToolUse: m.tool_call ?? false,\n supportsCacheControl: (m as { cache_control?: boolean }).cache_control ?? false,\n maxContextTokens: m.limit?.context ?? CONSERVATIVE_DEFAULTS.maxContextTokens,\n maxOutputTokens: m.limit?.output ?? CONSERVATIVE_DEFAULTS.maxOutputTokens,\n };\n}\n\n/**\n * Resolve per-model capability flags (vision/structured-output/tool-use/cache +\n * `maxContextTokens`/`maxOutputTokens`) for a model id. Pure, sync, offline (a\n * static catalog — no network). Strips routing prefixes (`openrouter/`/`vertex/`/\n * `bedrock/`) and OpenRouter `:variant` suffixes before lookup; unknown models get\n * conservative defaults. Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function resolveModelCapabilities(modelId: string): ModelCapabilities {\n const bare = stripVariantSuffix(stripRoutingPrefix(modelId));\n // M44 — the catalog model-info index replaced the hand-curated EXACT map (single source of truth; the\n // vendored provider-catalog.json carries the migrated data — parity-tested against the old map snapshot).\n const fromIndex = getCatalogModelInfo(bare);\n if (fromIndex !== undefined) return capsFromCatalog(fromIndex);\n // Routing-prefixed models (vertex/claude-3-5-sonnet) strip to bare\n // model name without vendor. Try inferring the vendor from the name.\n const withVendor = inferVendorPrefix(bare);\n if (withVendor !== bare) {\n const vendored = getCatalogModelInfo(withVendor);\n if (vendored !== undefined) return capsFromCatalog(vendored);\n }\n return CONSERVATIVE_DEFAULTS;\n}\n\nfunction stripRoutingPrefix(modelId: string): string {\n for (const prefix of ROUTING_PREFIXES) {\n if (modelId.startsWith(prefix)) return modelId.slice(prefix.length);\n }\n return modelId;\n}\n\n/**\n * Strip an OpenRouter variant suffix (`:free`/`:nitro`/`:floor`/`:beta`/…) so the\n * catalog lookup hits the underlying model. Model slugs contain no `:` except the\n * variant separator, so cutting at the first `:` is safe.\n */\nfunction stripVariantSuffix(modelId: string): string {\n const i = modelId.indexOf(\":\");\n return i >= 0 ? modelId.slice(0, i) : modelId;\n}\n\n/** Infer vendor prefix from bare model name for routing-prefixed lookups. */\nfunction inferVendorPrefix(bare: string): string {\n if (bare.startsWith(\"claude\")) return `anthropic/${bare}`;\n if (bare.startsWith(\"gpt-\") || bare.startsWith(\"o1\") || bare.startsWith(\"o3\"))\n return `openai/${bare}`;\n if (bare.startsWith(\"gemini\")) return `google/${bare}`;\n return bare;\n}\n","/**\n * Model identifier parsing (T1.2 follow-up, ADR D182 zero-config UX).\n *\n * SDK callers pass model strings like:\n * - `\"ollama/llama3.2:3b\"` → provider=\"ollama\", name=\"llama3.2:3b\"\n * - `\"anthropic/claude-3-5-sonnet\"` → provider=\"anthropic\", name=\"claude-3-5-sonnet\"\n * - `\"openrouter/meta-llama/llama-3\"` → provider=\"openrouter\", name=\"meta-llama/llama-3\"\n * - `\"claude-sonnet-4-6\"` → provider=undefined, name=\"claude-sonnet-4-6\"\n *\n * The first `/` separates the provider from the rest. Models with embedded\n * slashes (e.g. OpenRouter routing) keep the remainder intact. Tag suffixes\n * (`:latest`, `:3b`) are preserved as part of the name — Ollama expects them.\n *\n * **Returns `undefined` provider** when no `/` is present so callers can\n * fall back to env-var detection. Empty/whitespace components are treated\n * as no-prefix.\n *\n * Aligned with peer-project `extensions/ollama/src/discovery-shared.ts`\n * (`OLLAMA_PROVIDER_ID = \"ollama\"`) and Hermes `hermes_cli/providers.py`\n * (ALIASES table, `normalize_provider`).\n *\n * Public via `@theokit/sdk/models` (M5-8).\n *\n * @public\n */\n\nexport interface ParsedModelId {\n /** Provider name extracted from the prefix (lowercase), or undefined. */\n provider: string | undefined;\n /** Model name to send to the provider — prefix stripped. */\n name: string;\n}\n\n/** Provider aliases mirrored from Hermes `hermes_cli/providers.py` ALIASES. */\nconst PROVIDER_ALIASES: Readonly<Record<string, string>> = {\n \"llama-cpp\": \"llamacpp\",\n \"llama.cpp\": \"llamacpp\",\n \"lm-studio\": \"lmstudio\",\n lm_studio: \"lmstudio\",\n};\n\nexport function parseModelId(modelId: string | undefined): ParsedModelId {\n if (modelId === undefined || modelId.length === 0) {\n return { provider: undefined, name: \"\" };\n }\n const slash = modelId.indexOf(\"/\");\n if (slash <= 0 || slash === modelId.length - 1) {\n return { provider: undefined, name: modelId };\n }\n const rawProvider = modelId.slice(0, slash).trim().toLowerCase();\n const name = modelId.slice(slash + 1).trim();\n if (rawProvider.length === 0 || name.length === 0) {\n return { provider: undefined, name: modelId };\n }\n const canonical = PROVIDER_ALIASES[rawProvider] ?? rawProvider;\n return { provider: canonical, name };\n}\n","import { parseModelId } from \"./model-identifier.js\";\n\n/**\n * A UI-friendly model option — the shape a `<select>`/dropdown consumes.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport interface ModelOption {\n /** The original model id (what you pass back to the SDK). */\n value: string;\n /** Best-effort human label (see {@link humanizeModelName}). */\n label: string;\n /** Provider from the slug prefix, or `undefined` when none. */\n provider: string | undefined;\n}\n\n/** Tokens rendered upper-case rather than title-case. */\nconst ACRONYMS = new Set([\"gpt\", \"ai\", \"hd\", \"ui\", \"api\", \"sdk\", \"llm\", \"xl\"]);\n\nfunction prettyToken(token: string): string {\n if (ACRONYMS.has(token.toLowerCase())) return token.toUpperCase();\n return token.charAt(0).toUpperCase() + token.slice(1);\n}\n\n/**\n * Turn a model id into a best-effort human label: strip the routing/vendor\n * prefix to the core model segment, split on `-`/`_`/`.`/whitespace, title-case\n * each token (known acronyms upper-cased), and append an OpenRouter `:variant`\n * in parentheses. Deterministic, pure, dependency-free.\n *\n * Best-effort, NOT vendor-canonical: `\"anthropic/claude-3-5-sonnet\"` →\n * `\"Claude 3 5 Sonnet\"`. A UI wanting exact marketing names overrides per id.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function humanizeModelName(modelId: string): string {\n const { name } = parseModelId(modelId);\n if (name.length === 0) return \"\";\n const colon = name.indexOf(\":\");\n // Strip a trailing slash so a typo'd `gpt-4o/` keeps its name (not lost to an\n // empty last segment).\n const base = (colon >= 0 ? name.slice(0, colon) : name).replace(/\\/+$/, \"\");\n const variant = colon >= 0 ? name.slice(colon + 1) : \"\";\n const lastSlash = base.lastIndexOf(\"/\");\n const core = lastSlash >= 0 ? base.slice(lastSlash + 1) : base;\n const label = core\n .split(/[-_.\\s]+/)\n .filter((t) => t.length > 0)\n .map(prettyToken)\n .join(\" \");\n if (label.length === 0) return variant; // no base label (e.g. \":free\") → bare variant\n return variant.length > 0 ? `${label} (${variant})` : label;\n}\n\n/**\n * Build a {@link ModelOption} (`{ value, label, provider }`) for a model id —\n * a dropdown-ready entry composing {@link humanizeModelName} + `parseModelId`.\n *\n * Public via `@theokit/sdk/models`.\n *\n * @public\n */\nexport function toModelOption(modelId: string): ModelOption {\n return {\n value: modelId,\n label: humanizeModelName(modelId),\n provider: parseModelId(modelId).provider,\n };\n}\n","import { defaultRetriableForCode } from \"./internal/runtime/retry/default-retriable.js\";\nimport { redactSecrets } from \"./internal/security/redact.js\";\nimport type { RunOperation } from \"./types/run.js\";\n\n/**\n * Finite, machine-readable error codes for provider-originated errors\n * (ADR D66). Consumers can `switch (err.metadata?.code)` exhaustively\n * — adding a new variant is an explicit decision + test coverage.\n *\n * @public\n */\nexport type ErrorCode =\n | \"rate_limit\"\n | \"auth_failed\"\n | \"invalid_request\"\n | \"timeout\"\n | \"server_error\"\n | \"context_too_long\"\n | \"content_filtered\"\n | \"model_unavailable\"\n | \"network\"\n | \"quota_exceeded\"\n | \"unknown\";\n\n/**\n * Codes used by {@link AgentRunError} (Production-Readiness #3, ADR D311).\n *\n * Superset of {@link ErrorCode} extended with codes that do NOT originate\n * from a provider HTTP response:\n *\n * - `quota_exceeded` — billing limit hit (provider 402 or signalled error)\n * - `tool_runtime_error` — custom tool handler threw inside dispatch\n * - `aborted` — caller's `AbortSignal` fired (Phase 4)\n * - `invalid_model` — model id rejected by provider (400 \"model not found\")\n * - `safety_blocked` — provider safety filter blocked req or resp\n * - `provider_unreachable` — DNS/TCP/timeout/5xx at transport boundary\n *\n * The `& {}` tail keeps the literal-union ergonomics (autocomplete) while\n * accepting any string for forward compatibility with constructor calls\n * that pass arbitrary code values (legacy callers).\n *\n * @public\n */\n/**\n * T1.1 — closed literal union for `AgentRunError.code`. The previous\n * `(string & {})` escape hatch let arbitrary strings slip into the type\n * surface and defeated exhaustive `switch (code)` discrimination. This is\n * the canonical closed form. `AgentRunErrorCode` is re-aliased below for\n * source-level back-compat.\n *\n * Adding a new code: append the literal here AND audit every `switch (err.code)`\n * in callers. Type-checker enforces the audit via the `default: assertNever(code)`\n * convention.\n *\n * @public\n */\nexport type KnownAgentRunErrorCode =\n | ErrorCode\n | \"quota_exceeded\"\n | \"tool_runtime_error\"\n | \"aborted\"\n | \"invalid_model\"\n | \"safety_blocked\"\n | \"provider_unreachable\";\n\n/**\n * Back-compat alias of {@link KnownAgentRunErrorCode}. Pre-T1.1 callers that\n * imported `AgentRunErrorCode` keep working; new code SHOULD prefer\n * `KnownAgentRunErrorCode` to make the closed-union intent explicit.\n *\n * @public\n */\nexport type AgentRunErrorCode = KnownAgentRunErrorCode;\n\n/** Snapshot of every known code at runtime — used by the boundary coercer. */\nconst KNOWN_AGENT_RUN_ERROR_CODES = new Set<string>([\n \"rate_limit\",\n \"auth_failed\",\n \"invalid_request\",\n \"timeout\",\n \"server_error\",\n \"context_too_long\",\n \"content_filtered\",\n \"model_unavailable\",\n \"network\",\n \"unknown\",\n \"quota_exceeded\",\n \"tool_runtime_error\",\n \"aborted\",\n \"invalid_model\",\n \"safety_blocked\",\n \"provider_unreachable\",\n]);\n\n/**\n * T1.1 boundary helper — coerce an arbitrary string (typically arriving from\n * a downstream `RunErrorDetail.code` or a deserialized cloud response) into a\n * `KnownAgentRunErrorCode`. Unknown strings collapse to `\"unknown\"` so the\n * closed type contract holds without forcing every caller to switch.\n *\n * @internal\n */\nexport function coerceToKnownAgentRunErrorCode(code: string | undefined): KnownAgentRunErrorCode {\n if (code !== undefined && KNOWN_AGENT_RUN_ERROR_CODES.has(code)) {\n return code as KnownAgentRunErrorCode;\n }\n return \"unknown\";\n}\n\n/**\n * Structured context for errors that originated from a provider HTTP\n * call (ADR D65). Lets callers retry with the right backoff (`retryAfter`),\n * surface actionable diagnostics (`provider`, `endpoint`), and inspect the\n * raw response body when needed (`raw`, capped at ~2KB by the mapper).\n *\n * @public\n */\nexport interface ErrorMetadata {\n /** Provider canonical name (e.g., `\"anthropic\"`, `\"openai\"`, `\"openrouter\"`, `\"gemini\"`). */\n provider: string;\n /** HTTP endpoint that failed (e.g., `\"/v1/messages\"`, `\"/v1/chat/completions\"`). */\n endpoint: string;\n /** Machine-readable error code (finite enum). */\n code: ErrorCode;\n /** HTTP status code if applicable. */\n statusCode?: number;\n /** Seconds to wait before retry, per provider's `retry-after` header (numeric form only). */\n retryAfter?: number;\n /** Raw response body for debugging (truncated to ~2KB by the mapper). */\n raw?: unknown;\n}\n\n/**\n * Base class for all errors thrown by `@theokit/sdk`.\n *\n * Use `isRetryable` to drive retry/backoff logic. `code` and `protoErrorCode`\n * are populated for server-originated errors when available. `metadata`\n * (ADR D65) carries structured `{ provider, endpoint, code, ... }` when\n * the error originated from a provider HTTP call.\n *\n * @public\n */\nexport class TheokitAgentError extends Error {\n override readonly name: string = \"TheokitAgentError\";\n readonly isRetryable: boolean;\n readonly code?: string;\n readonly protoErrorCode?: string;\n readonly metadata?: ErrorMetadata;\n\n constructor(\n message: string,\n options: {\n isRetryable?: boolean;\n code?: string;\n protoErrorCode?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n } = {},\n ) {\n super(message, options.cause !== undefined ? { cause: options.cause } : undefined);\n this.isRetryable = options.isRetryable ?? false;\n if (options.code !== undefined) this.code = options.code;\n if (options.protoErrorCode !== undefined) this.protoErrorCode = options.protoErrorCode;\n if (options.metadata !== undefined) this.metadata = options.metadata;\n }\n}\n\n/**\n * Invalid API key, not logged in, insufficient permissions.\n *\n * @public\n */\nexport class AuthenticationError extends TheokitAgentError {\n override readonly name: string = \"AuthenticationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Too many requests or usage limits exceeded.\n *\n * @public\n */\nexport class RateLimitError extends TheokitAgentError {\n override readonly name: string = \"RateLimitError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Invalid model, bad request parameters, malformed options.\n *\n * @public\n */\nexport class ConfigurationError extends TheokitAgentError {\n override readonly name: string = \"ConfigurationError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown when creating a cloud agent for a repo whose SCM provider is not\n * connected. Use `helpUrl` to point the user at the right reconnect flow.\n *\n * @public\n */\nexport class IntegrationNotConnectedError extends ConfigurationError {\n override readonly name: string = \"IntegrationNotConnectedError\";\n readonly provider: string;\n readonly helpUrl: string;\n\n constructor(\n message: string,\n options: {\n provider: string;\n helpUrl: string;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, options);\n this.provider = options.provider;\n this.helpUrl = options.helpUrl;\n }\n}\n\n/**\n * Service unavailable, timeout, transport-level failure.\n *\n * @public\n */\nexport class NetworkError extends TheokitAgentError {\n override readonly name: string = \"NetworkError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: true });\n }\n}\n\n/**\n * Catch-all for unclassified server or runtime errors.\n *\n * @public\n */\nexport class UnknownAgentError extends TheokitAgentError {\n override readonly name: string = \"UnknownAgentError\";\n\n constructor(\n message: string,\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(message, { ...options, isRetryable: false });\n }\n}\n\n/**\n * Thrown by `Agent.prompt` (and helpers that go through `run.wait()`) when\n * the option `{ throwOnError: true }` is set and the run terminates with\n * `status: 'error'`. Carries the structured `RunResult.error` fields so\n * callers can `catch` once and branch on `code` / `provider` instead of\n * unwrapping the run.\n *\n * Extends {@link TheokitAgentError} per ADR D65 — no new hierarchy.\n *\n * @example\n * try {\n * await Agent.prompt(msg, { apiKey, model, throwOnError: true });\n * } catch (err) {\n * if (err instanceof AgentRunError && err.code === 'auth_failed') {\n * // bad key\n * }\n * }\n *\n * @public\n */\nexport class AgentRunError extends TheokitAgentError {\n override readonly name: string = \"AgentRunError\";\n readonly provider?: string;\n readonly raw?: string;\n /** Provider's request id (`x-request-id` / `request-id` header). Useful for support tickets. */\n readonly requestId?: string;\n /** SDK conversation id this error was raised inside. */\n readonly conversationId?: string;\n\n constructor(\n message: string,\n options: {\n code: AgentRunErrorCode;\n provider?: string;\n raw?: string;\n requestId?: string;\n conversationId?: string;\n retriable?: boolean;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n code: options.code,\n cause: options.cause,\n metadata: options.metadata,\n // D311: most AgentRunErrors are not retriable (auth, validation, abort).\n // Provider mappers (D314) override per-status — explicit `retriable` wins\n // over the implicit default when supplied.\n isRetryable: options.retriable ?? defaultRetriableForCode(options.code),\n });\n if (options.provider !== undefined) this.provider = options.provider;\n if (options.raw !== undefined) this.raw = options.raw;\n if (options.requestId !== undefined) this.requestId = options.requestId;\n if (options.conversationId !== undefined) this.conversationId = options.conversationId;\n }\n\n /**\n * Production-Readiness #3 (ADR D311): alias for `isRetryable` exposed as\n * `retriable` to match the handoff contract. Future v2 will deprecate\n * `isRetryable` in favor of this.\n */\n get retriable(): boolean {\n return this.isRetryable;\n }\n\n /**\n * D312: provider's `Retry-After` header in **milliseconds**. Mappers store\n * the header value (seconds) in `metadata.retryAfter`; this getter\n * multiplies by 1000 so the result composes with `Date.now()`/`setTimeout`.\n *\n * Returns `undefined` when no hint was provided. `0` is a legitimate value\n * — use `=== undefined` check rather than truthy check.\n */\n get retryAfterMs(): number | undefined {\n if (this.metadata?.retryAfter === undefined) return undefined;\n return this.metadata.retryAfter * 1000;\n }\n\n /**\n * D313 + T1.5: alias for `metadata.raw`. Provider response body for\n * debugging. T1.5 wraps the value in `redactSecrets` at the getter\n * boundary so secret-shaped substrings (`sk-...`, Bearer JWTs, etc.) are\n * stripped before reaching the caller. Available but NEVER serialized\n * into `.message` (anti-leak invariant).\n */\n get providerError(): unknown {\n const raw = this.metadata?.raw;\n if (raw === undefined) return undefined;\n if (typeof raw === \"string\") return redactSecrets(raw);\n // Non-string raw (object/buffer) — stringify then redact.\n try {\n return redactSecrets(JSON.stringify(raw));\n } catch {\n return redactSecrets(String(raw));\n }\n }\n\n /**\n * T1.5 — sanitized JSON form. `metadata.raw` is OMITTED by default; opt\n * in via `THEOKIT_DEBUG_RAW_ERRORS=1` to surface the (redacted) raw\n * payload for diagnostics. Every other field stays accessible.\n *\n * The single env-var gate is read each call so operators can toggle at\n * runtime without restarting the process.\n */\n toJSON(): Record<string, unknown> {\n const json: Record<string, unknown> = {\n name: this.name,\n message: this.message,\n isRetryable: this.isRetryable,\n };\n addOptionalFields(json, this);\n const safeMeta = sanitizeMetadata(this.metadata);\n if (safeMeta !== undefined) json.metadata = safeMeta;\n return json;\n }\n}\n\nfunction addOptionalFields(json: Record<string, unknown>, err: AgentRunError): void {\n if (err.code !== undefined) json.code = err.code;\n if (err.provider !== undefined) json.provider = err.provider;\n if (err.requestId !== undefined) json.requestId = err.requestId;\n if (err.conversationId !== undefined) json.conversationId = err.conversationId;\n if (err.raw !== undefined) json.raw = redactSecrets(err.raw);\n}\n\nfunction sanitizeMetadata(meta: ErrorMetadata | undefined): ErrorMetadata | undefined {\n if (meta === undefined) return undefined;\n const { raw, ...rest } = meta;\n const debugRaw = process.env.THEOKIT_DEBUG_RAW_ERRORS === \"1\";\n if (debugRaw && raw !== undefined) {\n const redactedRaw =\n typeof raw === \"string\" ? redactSecrets(raw) : redactSecrets(safeStringify(raw));\n return { ...rest, raw: redactedRaw } as ErrorMetadata;\n }\n return rest as ErrorMetadata;\n}\n\nfunction safeStringify(value: unknown): string {\n try {\n return JSON.stringify(value);\n } catch {\n return String(value);\n }\n}\n\n/**\n * Is this error transient (worth retrying)?\n *\n * Returns the SDK's own retryability verdict: every {@link TheokitAgentError}\n * subclass computes `isRetryable` at construction (rate-limit / network /\n * credential-pool-exhausted are retryable; auth / configuration / unsupported\n * are not), so this predicate is a single source of truth rather than a\n * re-derivation. Non-SDK errors return `false` conservatively — wrap a foreign\n * error in the appropriate SDK error first if you want it considered transient.\n * It never inspects `err.message`.\n *\n * @example\n * try {\n * await agent.send(message, { throwOnError: true });\n * } catch (err) {\n * if (isTransientError(err)) return retryWithBackoff();\n * throw err;\n * }\n *\n * @public\n */\nexport function isTransientError(err: unknown): boolean {\n return err instanceof TheokitAgentError && err.isRetryable === true;\n}\n\n/**\n * Thrown when a {@link Run} or agent operation is not available on the current\n * runtime. Check first with `run.supports(operation)`.\n *\n * Extends {@link TheokitAgentError} (so error-catching code that branches on\n * `instanceof TheokitAgentError` continues to work) but is never retryable —\n * an unsupported operation will not become supported on retry.\n *\n * @public\n */\nexport class UnsupportedRunOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedRunOperationError\";\n readonly operation: RunOperation;\n\n constructor(\n message: string,\n operation: RunOperation,\n options: { code?: string; cause?: unknown } = {},\n ) {\n super(message, {\n ...options,\n isRetryable: false,\n code: options.code ?? \"unsupported_run_operation\",\n });\n this.operation = operation;\n }\n}\n\n/**\n * Thrown when every credential in a per-provider pool is in cooldown\n * and no healthy key is available (ADR D133). The caller's\n * {@link import(\"./internal/llm/fallback-client.js\").FallbackLlmClient}\n * catches this and tries the next provider in the fallback chain.\n *\n * `metadata.nextRetryAt` (epoch ms) tells callers when the soonest\n * pool entry resumes — useful for manual retry scheduling.\n *\n * @public\n */\nexport class CredentialPoolExhaustedError extends TheokitAgentError {\n override readonly name: string = \"CredentialPoolExhaustedError\";\n readonly provider: string;\n readonly nextRetryAt: number | undefined;\n\n constructor(\n message: string,\n options: {\n provider: string;\n nextRetryAt?: number;\n code?: string;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n ...options,\n isRetryable: true,\n code: options.code ?? \"credential_pool_exhausted\",\n });\n this.provider = options.provider;\n this.nextRetryAt = options.nextRetryAt;\n }\n}\n\n/**\n * Finite error codes specific to memory adapter operations (ADR D141).\n *\n * @public\n */\nexport type MemoryAdapterErrorCode =\n | \"auth_failed\"\n | \"rate_limited\"\n | \"not_found\"\n | \"network\"\n | \"invalid_input\"\n | \"unknown\";\n\n/**\n * Error raised by `@theokit-memory-*` adapters. Carries `adapterId`\n * so callers can branch on which provider failed (ADR D141).\n *\n * @public\n */\nexport class MemoryAdapterError extends TheokitAgentError {\n override readonly name: string = \"MemoryAdapterError\";\n readonly adapterId: string;\n\n constructor(\n message: string,\n options: {\n adapterId: string;\n code: MemoryAdapterErrorCode;\n cause?: unknown;\n metadata?: ErrorMetadata;\n },\n ) {\n super(message, {\n isRetryable: options.code === \"rate_limited\" || options.code === \"network\",\n code: options.code,\n ...(options.cause !== undefined ? { cause: options.cause } : {}),\n ...(options.metadata !== undefined ? { metadata: options.metadata } : {}),\n });\n this.adapterId = options.adapterId;\n }\n}\n\n/**\n * Thrown when a user-supplied task ID violates the grammar\n * `^[a-z0-9][a-z0-9_-]*$` (D368) OR starts with a reserved adapter\n * prefix (`wf-` / `b-` / `cron-`, EC-5).\n *\n * @public\n */\nexport class InvalidTaskIdError extends TheokitAgentError {\n override readonly name: string = \"InvalidTaskIdError\";\n readonly taskId: string;\n\n constructor(message: string, taskId: string, options: { cause?: unknown } = {}) {\n super(message, {\n ...options,\n isRetryable: false,\n code: \"invalid_task_id\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `Task.subscribe(id)` is called for a task that has been\n * evicted, never submitted, or evicted after retention (D373).\n *\n * @public\n */\nexport class TaskNotFoundError extends TheokitAgentError {\n override readonly name: string = \"TaskNotFoundError\";\n readonly taskId: string;\n\n constructor(taskId: string, options: { cause?: unknown } = {}) {\n super(`Task not found: ${taskId}`, {\n ...options,\n isRetryable: false,\n code: \"task_not_found\",\n });\n this.taskId = taskId;\n }\n}\n\n/**\n * Thrown when `CloudAgent` is asked to wrap a task (D370). Cloud\n * task observability is deferred until Theo PaaS GA.\n *\n * @public\n */\nexport class UnsupportedTaskOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedTaskOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Task operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D370)`,\n {\n ...options,\n isRetryable: false,\n code: \"task_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n\n/**\n * Thrown by `Budget` enforcement (ADR D386) when a `mode: \"block\"`\n * budget would be exceeded by the upcoming LLM call. Caller pega\n * tipado para retry-after-window-reset or surface to the user.\n *\n * @public\n */\nexport class BudgetExceededError extends TheokitAgentError {\n override readonly name: string = \"BudgetExceededError\";\n readonly budgetName: string;\n readonly window: import(\"./types/budget.js\").BudgetWindow;\n readonly spentUsd: number;\n readonly limitUsd: number;\n readonly mode: import(\"./types/budget.js\").BudgetMode;\n\n constructor(args: {\n budgetName: string;\n window: import(\"./types/budget.js\").BudgetWindow;\n spentUsd: number;\n limitUsd: number;\n mode: import(\"./types/budget.js\").BudgetMode;\n cause?: unknown;\n }) {\n super(\n `Budget \"${args.budgetName}\" exceeded for window ${args.window}: spent $${args.spentUsd.toFixed(4)} > limit $${args.limitUsd.toFixed(4)}`,\n {\n ...(args.cause !== undefined ? { cause: args.cause } : {}),\n isRetryable: false,\n code: \"budget_exceeded\",\n },\n );\n this.budgetName = args.budgetName;\n this.window = args.window;\n this.spentUsd = args.spentUsd;\n this.limitUsd = args.limitUsd;\n this.mode = args.mode;\n }\n}\n\n/**\n * Thrown when `CloudAgent.send({ budget })` is invoked (D388). Cloud\n * budget surface waits for Theo PaaS GA.\n *\n * @public\n */\n/**\n * T1.6 — Thrown when a consumer calls `agent.send()` or any method\n * on an agent that has already been `dispose()`d. Pre-T1.6 this was\n * a generic `new Error(\"Agent has been disposed\")` — consumers\n * couldn't catch it without string-matching the message.\n *\n * @public\n */\nexport class AgentDisposedError extends TheokitAgentError {\n override readonly name: string = \"AgentDisposedError\";\n readonly agentId: string;\n\n constructor(agentId: string) {\n super(`Agent \"${agentId}\" has been disposed. Create a new agent or use Agent.resume().`, {\n isRetryable: false,\n code: \"agent_disposed\",\n });\n this.agentId = agentId;\n }\n}\n\nexport class UnsupportedBudgetOperationError extends TheokitAgentError {\n override readonly name: string = \"UnsupportedBudgetOperationError\";\n readonly operation: string;\n\n constructor(operation: string, options: { cause?: unknown } = {}) {\n super(\n `Budget operation \"${operation}\" is not supported on CloudAgent (pre-release; see ADR D388)`,\n {\n ...options,\n isRetryable: false,\n code: \"budget_op_unsupported\",\n },\n );\n this.operation = operation;\n }\n}\n","/**\n * Generic retry wrapper (plan m0-foundation-expose-primitives, M0-3).\n *\n * Exponential backoff with full jitter, deterministically testable via an\n * injectable `sleep` and `rng` (no real timers in unit tests, per the repo\n * testing rule). The default `isRetryable` predicate is {@link isTransientError}\n * so SDK errors retry exactly as the SDK classifies them. The workflow-internal\n * `withRetry` (RetryPolicy-coupled) is intentionally separate (ADR-M0-3).\n *\n * @internal — public via `@theokit/sdk/retry`\n */\n\nimport { ConfigurationError, isTransientError } from \"../../../errors.js\";\n\n/** Options for {@link withRetry}. All fields optional; sensible defaults applied. */\nexport interface RetryOptions {\n /** Number of retries after the first attempt (total attempts = retries + 1). Default 3. */\n retries?: number;\n /** Predicate deciding whether a thrown error is worth retrying. Default {@link isTransientError}. */\n isRetryable?: (err: unknown) => boolean;\n /** Base backoff in ms for the first retry. Default 100. */\n initialDelayMs?: number;\n /** Upper bound for a single backoff sleep. Default 30_000. */\n maxDelayMs?: number;\n /** Exponential multiplier applied per retry. Default 2. */\n backoffMultiplier?: number;\n /** [0, 1) source for full-jitter. Default `Math.random`. Inject for deterministic tests. */\n rng?: () => number;\n /** Sleep function. Default a `setTimeout`-based abortable sleep. Inject for deterministic tests. */\n sleep?: (ms: number, signal?: AbortSignal) => Promise<void>;\n /** Abort signal; once aborted, the abortable default sleep rejects and the loop stops. */\n signal?: AbortSignal;\n}\n\nfunction defaultSleep(ms: number, signal?: AbortSignal): Promise<void> {\n return new Promise<void>((resolve, reject) => {\n if (signal?.aborted) {\n reject(signal.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n return;\n }\n const timer = setTimeout(() => {\n signal?.removeEventListener(\"abort\", onAbort);\n resolve();\n }, ms);\n function onAbort(): void {\n clearTimeout(timer);\n reject(signal?.reason instanceof Error ? signal.reason : new Error(\"withRetry: aborted\"));\n }\n signal?.addEventListener(\"abort\", onAbort, { once: true });\n });\n}\n\ninterface ResolvedRetry {\n retries: number;\n isRetryable: (err: unknown) => boolean;\n initialDelayMs: number;\n maxDelayMs: number;\n backoffMultiplier: number;\n rng: () => number;\n sleep: (ms: number, signal?: AbortSignal) => Promise<void>;\n signal?: AbortSignal;\n}\n\nfunction resolveRetryOptions(options?: RetryOptions): ResolvedRetry {\n const retries = options?.retries ?? 3;\n if (!Number.isInteger(retries) || retries < 0) {\n throw new ConfigurationError(\n `withRetry: retries must be a non-negative integer, got ${retries}`,\n { code: \"invalid_retry_config\" },\n );\n }\n return {\n retries,\n isRetryable: options?.isRetryable ?? isTransientError,\n initialDelayMs: options?.initialDelayMs ?? 100,\n maxDelayMs: options?.maxDelayMs ?? 30_000,\n backoffMultiplier: options?.backoffMultiplier ?? 2,\n rng: options?.rng ?? Math.random,\n sleep: options?.sleep ?? defaultSleep,\n signal: options?.signal,\n };\n}\n\n/** Full-jitter backoff for the given (0-indexed) retry attempt. */\nfunction backoffMs(cfg: ResolvedRetry, attempt: number): number {\n const ceiling = Math.min(cfg.maxDelayMs, cfg.initialDelayMs * cfg.backoffMultiplier ** attempt);\n return Math.floor(cfg.rng() * ceiling);\n}\n\n/**\n * Run `fn`, retrying transient failures with exponential backoff + full jitter.\n *\n * @returns the resolved value of the first successful `fn()` call\n * @throws the last error when retries are exhausted or the error is not retryable\n *\n * @example\n * const data = await withRetry(() => fetchJson(url)); // retries rate-limit/network\n */\nexport async function withRetry<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n const cfg = resolveRetryOptions(options);\n let attempt = 0;\n for (;;) {\n try {\n return await fn();\n } catch (err) {\n if (attempt >= cfg.retries || !cfg.isRetryable(err)) throw err;\n await cfg.sleep(backoffMs(cfg, attempt), cfg.signal);\n attempt += 1;\n }\n }\n}\n","/**\n * Public generic retry primitive (plan m0-foundation-expose-primitives, M0-3).\n *\n * Split into its own top-level module so `tsup` builds a dedicated\n * `@theokit/sdk/retry` sub-path entry, mirroring the `path-safety` pattern.\n * The default retry predicate is `isTransientError`, so retries follow the\n * SDK's own error classification.\n */\n\nimport { type RetryOptions, withRetry } from \"./internal/runtime/retry/with-retry.js\";\n\nexport type { RetryOptions };\n\n/**\n * SE36 — `Retry.create` replaces `withRetry` (ADR 0015 / ADR-P2). NOTE: `withRetry` is an\n * EXECUTOR, not a constructor — `Retry.create(fn, opts)` RUNS `fn` with retry and resolves to\n * its result (`Promise<T>`), not a `Retry` instance. The `.create` name is the uniformity\n * mandate; the executor semantics are the documented, accepted awkwardness. @public\n */\nexport class Retry {\n private constructor() {}\n static create<T>(fn: () => Promise<T>, options?: RetryOptions): Promise<T> {\n return withRetry(fn, options);\n }\n}\n","import { createHash, randomBytes } from \"node:crypto\";\nimport { mkdirSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync } from \"node:fs\";\nimport { homedir } from \"node:os\";\nimport { dirname, join } from \"node:path\";\n\nimport { Retry } from \"../../retry.js\";\nimport { getCatalogModelInfo, patchModelInfo } from \"./catalog-loader.js\";\nimport { catalogModelSchema } from \"./catalog-schema.js\";\nimport { getProviderProfile } from \"./registry.js\";\n\n/**\n * M44 — the OPTIONAL models.dev catalog source. Explicit opt-in ONLY (`refreshModelCatalog()`): the SDK\n * NEVER fetches at startup or per-request — the vendored catalog + any existing disk cache are the offline\n * base, and every failure mode fails CLOSED back to them (ROADMAP constraint: no runtime hard network dep).\n *\n * Mechanism adapted from OpenCode's models.dev consumption (MIT © 2025 opencode — `core/src/models-dev.ts`):\n * disk cache with mtime TTL, atomic tempfile+rename write, corrupt-cache delete-and-fall-through, kill-switch\n * env. Library adaptations: NO background refresh loop (a consumer composes refresh with the SDK's cron);\n * TTL 1h (not 5min — no background refresher to keep it warm); no cross-process flock v1 (atomic rename +\n * idempotent upstream content — at most one wasted fetch).\n *\n * @internal (the public surface is `refreshModelCatalog` re-exported via `@theokit/sdk/models`)\n */\n\nconst DEFAULT_URL = \"https://models.dev/api.json\";\nconst TTL_MS = 60 * 60 * 1000; // 1 hour\nconst FETCH_TIMEOUT_MS = 10_000;\n\nexport interface RefreshModelCatalogOptions {\n /** Override the source URL (`THEOKIT_MODELS_URL` env also honored). */\n url?: string;\n /** Bypass the TTL freshness gate. */\n force?: boolean;\n /** Injected for tests. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\nexport interface RefreshModelCatalogResult {\n /** Where the data came from: a fresh network fetch, the still-fresh disk cache, or skipped entirely. */\n source: \"network\" | \"cache\" | \"skipped\";\n /** How many models were patched into the index. */\n models: number;\n}\n\n/** The cache file for a source URL (custom URLs get a hash-suffixed name, mirroring OpenCode). */\nexport function cachePathFor(url: string): string {\n const dir = join(homedir(), \".theokit\", \"cache\", \"models-dev\");\n if (url === DEFAULT_URL) return join(dir, \"api.json\");\n const hash = createHash(\"sha256\").update(url).digest(\"hex\").slice(0, 12);\n return join(dir, `api-${hash}.json`);\n}\n\n/** Atomic write: temp file + rename (crash mid-write never leaves a partial cache). */\nfunction writeCacheAtomic(path: string, body: string): void {\n mkdirSync(dirname(path), { recursive: true });\n const tmp = `${path}.tmp-${randomBytes(6).toString(\"hex\")}`;\n try {\n writeFileSync(tmp, body);\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // best effort\n }\n throw err;\n }\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN. */\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n for (const [providerId, provider] of Object.entries(raw as Record<string, unknown>)) {\n const models = (provider as { models?: Record<string, unknown> })?.models;\n if (models === undefined || typeof models !== \"object\") continue;\n // Enrich ONLY providers the SDK knows (id or alias) — models.dev's npm/api fields cannot be mapped to a\n // theokit apiMode/authType safely, so unknown providers are data we cannot route (skip with WARN).\n const profile = getProviderProfile(providerId);\n if (profile === undefined) continue;\n for (const [modelId, rawModel] of Object.entries(models)) {\n const parsed = catalogModelSchema.safeParse(rawModel);\n if (!parsed.success) continue; // malformed model — drop silently (live data, additive drift expected)\n patchModelInfo(`${profile.name}/${modelId}`, parsed.data);\n patched++;\n }\n }\n return patched;\n}\n\n/**\n * Load an existing disk cache into the index (called by refresh when fresh, or opportunistically by a\n * consumer at startup — NEVER fetches). Corrupt cache → delete + fall through to vendored data.\n */\nexport function loadCacheIntoIndex(url: string = DEFAULT_URL): number {\n const path = cachePathFor(url);\n let body: string;\n try {\n body = readFileSync(path, \"utf-8\");\n } catch {\n return 0; // no cache — vendored data only\n }\n try {\n return patchIndexFromApiJson(JSON.parse(body));\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog (OpenCode's delete-and-fall-through)\n try {\n unlinkSync(path);\n } catch {\n // best effort\n }\n process.stderr.write(`[theokit-sdk] WARN: corrupt models-dev cache deleted (${path})\\n`);\n return 0;\n }\n}\n\n/**\n * Explicitly refresh the model catalog from models.dev (the ONLY network trigger in the subsystem).\n * Fail-closed: any failure keeps serving the current index (cache or vendored). Kill-switch:\n * `THEOKIT_DISABLE_MODELS_FETCH`.\n */\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n if (process.env.THEOKIT_DISABLE_MODELS_FETCH !== undefined) {\n return { source: \"skipped\", models: 0 };\n }\n const url = opts.url ?? process.env.THEOKIT_MODELS_URL ?? DEFAULT_URL;\n const path = cachePathFor(url);\n const now = opts.deps?.now ?? (() => Date.now());\n\n // TTL gate: a fresh cache serves without network (mtime freshness, OpenCode's gate).\n if (opts.force !== true) {\n try {\n const age = now() - statSync(path).mtimeMs;\n if (age < TTL_MS) {\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n }\n } catch {\n // no cache — proceed to fetch\n }\n }\n\n const fetchImpl = opts.deps?.fetch ?? fetch;\n let body: string;\n try {\n const res = await Retry.create(\n async () => {\n const r = await fetchImpl(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });\n if (!r.ok) throw new Error(`HTTP ${r.status}`);\n return r;\n },\n // 2 transient retries with backoff (OpenCode does the same); every error here is worth one more try —\n // the whole call is already fail-closed at the caller.\n { retries: 2, isRetryable: () => true, initialDelayMs: 200 },\n );\n body = await res.text();\n JSON.parse(body); // validate before persisting — never cache garbage\n } catch (err) {\n process.stderr.write(\n `[theokit-sdk] WARN: models-dev refresh failed (${(err as Error).message}) — serving existing data\\n`,\n );\n // fail-closed: serve whatever we already have (stale cache if present, else vendored)\n return { source: \"cache\", models: loadCacheIntoIndex(url) };\n }\n\n try {\n writeCacheAtomic(path, body);\n } catch (err) {\n process.stderr.write(\n `[theokit-sdk] WARN: models-dev cache write failed (${(err as Error).message})\\n`,\n );\n }\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n}\n\n/** The enriched per-model view (public via `@theokit/sdk/models`): index lookup by (possibly prefixed) id. */\nexport function getModelInfo(modelId: string): ReturnType<typeof getCatalogModelInfo> {\n return getCatalogModelInfo(modelId);\n}\n"]}
|