@theokit/sdk 4.22.0 → 4.24.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.
Files changed (63) hide show
  1. package/dist/auth/index.cjs +29 -5
  2. package/dist/auth/index.cjs.map +1 -1
  3. package/dist/auth/index.js +29 -5
  4. package/dist/auth/index.js.map +1 -1
  5. package/dist/compaction.cjs +31 -0
  6. package/dist/compaction.cjs.map +1 -1
  7. package/dist/compaction.d.cts +79 -0
  8. package/dist/compaction.d.ts +79 -0
  9. package/dist/compaction.js +28 -1
  10. package/dist/compaction.js.map +1 -1
  11. package/dist/{cron-Bhdyjl0B.d.ts → cron-B_NkE_VM.d.ts} +15 -1
  12. package/dist/{cron-M2Xz7lq2.d.cts → cron-x3muPNgg.d.cts} +15 -1
  13. package/dist/cron.cjs +467 -337
  14. package/dist/cron.cjs.map +1 -1
  15. package/dist/cron.d.cts +2 -2
  16. package/dist/cron.d.ts +2 -2
  17. package/dist/cron.js +467 -337
  18. package/dist/cron.js.map +1 -1
  19. package/dist/{errors-gE8612p9.d.cts → errors-BdL-buYn.d.cts} +1 -1
  20. package/dist/{errors-CG2RpeW-.d.ts → errors-DHZtSNnj.d.ts} +1 -1
  21. package/dist/errors.d.cts +2 -2
  22. package/dist/eval.cjs +467 -337
  23. package/dist/eval.cjs.map +1 -1
  24. package/dist/eval.js +467 -337
  25. package/dist/eval.js.map +1 -1
  26. package/dist/index.cjs +640 -508
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +21 -12
  29. package/dist/index.d.ts +21 -12
  30. package/dist/index.js +640 -508
  31. package/dist/index.js.map +1 -1
  32. package/dist/internal/auth/credential-store.d.ts +20 -3
  33. package/dist/internal/global-singleton.d.ts +13 -0
  34. package/dist/internal/llm/openai-messages.d.ts +2 -0
  35. package/dist/internal/local-agent/mcp-pool.d.ts +41 -0
  36. package/dist/internal/local-agent/real-local-run.d.ts +2 -0
  37. package/dist/internal/persistence/index.cjs +3 -1
  38. package/dist/internal/persistence/index.cjs.map +1 -1
  39. package/dist/internal/persistence/index.js +3 -1
  40. package/dist/internal/persistence/index.js.map +1 -1
  41. package/dist/internal/providers/registry.d.ts +1 -0
  42. package/dist/internal/runtime/lifecycle/context-budget-event.d.ts +25 -0
  43. package/dist/internal/runtime/lifecycle/goal-marker.d.ts +13 -0
  44. package/dist/internal/runtime/lifecycle/run-until.d.ts +0 -1
  45. package/dist/internal/session/agent-session.d.ts +1 -1
  46. package/dist/internal/session/session-cache.d.ts +20 -0
  47. package/dist/models.cjs +22 -20
  48. package/dist/models.cjs.map +1 -1
  49. package/dist/models.js +22 -20
  50. package/dist/models.js.map +1 -1
  51. package/dist/persistence.cjs +3 -1
  52. package/dist/persistence.cjs.map +1 -1
  53. package/dist/persistence.js +3 -1
  54. package/dist/persistence.js.map +1 -1
  55. package/dist/provider-catalog.json +144 -469
  56. package/dist/{run-DFM1H2jW.d.cts → run-OJbGyweZ.d.cts} +20 -1
  57. package/dist/{run-DFM1H2jW.d.ts → run-OJbGyweZ.d.ts} +20 -1
  58. package/dist/types/agent.d.ts +14 -0
  59. package/dist/types/run-events.d.ts +20 -1
  60. package/dist/workflow.cjs.map +1 -1
  61. package/dist/workflow.js.map +1 -1
  62. package/package.json +2 -2
  63. package/dist/goal-loop.d.ts +0 -35
@@ -1 +1 @@
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/builtin/anthropic.ts","../src/internal/providers/builtin/bedrock.ts","../src/internal/providers/builtin/openai-compatible.ts","../src/internal/providers/builtin/cerebras.ts","../src/internal/providers/builtin/cohere.ts","../src/internal/providers/builtin/deepinfra.ts","../src/internal/providers/builtin/gemini.ts","../src/internal/providers/builtin/google.ts","../src/internal/providers/builtin/groq.ts","../src/internal/providers/builtin/llamacpp.ts","../src/internal/providers/builtin/lmstudio.ts","../src/internal/providers/builtin/mistral.ts","../src/internal/providers/builtin/ollama.ts","../src/internal/providers/builtin/openai.ts","../src/internal/auth/credential-store.ts","../src/server/auth/errors.ts","../src/internal/auth/oauth-engine.ts","../src/internal/auth/resolve-credential.ts","../src/internal/providers/builtin/openai-chatgpt.ts","../src/internal/providers/builtin/openrouter.ts","../src/internal/providers/builtin/perplexity.ts","../src/internal/providers/builtin/together.ts","../src/internal/providers/builtin/vertex.ts","../src/internal/providers/builtin/xai.ts","../src/internal/providers/builtin/index.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":["z","dirname","fileURLToPath","globalSingleton","join","readFileSync","statSync","mkdirSync","chmodSync","randomBytes","openSync","writeFileSync","fsyncSync","closeSync","renameSync","unlinkSync","fresh","homedir","createHash","path"],"mappings":";;;;;;;;;;;AAeO,IAAM,aAAa,CAAC,MAAA,EAAQ,OAAA,EAAS,OAAA,EAAS,SAAS,KAAK,CAAA;AAGnE,IAAM,UAAA,GAAaA,MAChB,MAAA,CAAO;AAAA;AAAA,EAEN,KAAA,EAAOA,KAAA,CAAE,MAAA,EAAO,CAAE,WAAA,EAAY;AAAA,EAC9B,MAAA,EAAQA,KAAA,CAAE,MAAA,EAAO,CAAE,WAAA,EAAY;AAAA,EAC/B,YAAYA,KAAA,CAAE,MAAA,EAAO,CAAE,WAAA,GAAc,QAAA,EAAS;AAAA,EAC9C,aAAaA,KAAA,CAAE,MAAA,EAAO,CAAE,WAAA,GAAc,QAAA;AACxC,CAAC,EACA,KAAA,EAAM;AAET,IAAM,WAAA,GAAcA,MACjB,MAAA,CAAO;AAAA,EACN,OAAA,EAASA,KAAA,CAAE,MAAA,EAAO,CAAE,QAAA,EAAS;AAAA,EAC7B,OAAOA,KAAA,CAAE,MAAA,EAAO,CAAE,QAAA,GAAW,QAAA,EAAS;AAAA,EACtC,QAAQA,KAAA,CAAE,MAAA,EAAO,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\"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\n/**\n * M44 B1 fix — the registry state lives on `globalThis` keyed by `Symbol.for`, so EVERY bundle copy of this\n * module (tsup bundles each entry separately with `splitting: false` — `dist/index.js` and `dist/models.js`\n * each embed their own copy) shares the SAME maps. Without this, `@theokit/sdk/models`'s\n * `refreshModelCatalog` saw an eternally-empty registry and its patches were invisible to the core bundle's\n * capability/pricing lookups (state duplication made load-bearing by M44).\n */\nfunction globalSingleton<T>(key: string, create: () => T): T {\n const g = globalThis as unknown as Record<symbol, T>;\n const sym = Symbol.for(key);\n if (g[sym] === undefined) g[sym] = create();\n return g[sym];\n}\n\nconst REGISTRY = globalSingleton(\n \"theokit-sdk.providers.registry\",\n () => new Map<string, ProviderProfile>(),\n);\nconst ALIASES = globalSingleton(\"theokit-sdk.providers.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 */\n// M44 B1 fix — index state on globalThis (Symbol.for) so every bundle copy shares the SAME maps (see the\n// identical pattern + rationale in registry.ts).\nfunction globalSingleton<T>(key: string, create: () => T): T {\n const g = globalThis as unknown as Record<symbol, T>;\n const sym = Symbol.for(key);\n if (g[sym] === undefined) g[sym] = create();\n return g[sym];\n}\n\nconst modelInfoIndex = globalSingleton(\n \"theokit-sdk.providers.model-info-index\",\n () => new Map<string, CatalogModel>(),\n);\n/** M44 M5 fix — keys patched by the live models-dev source (honest pricing provenance). */\nconst patchedModelKeys = globalSingleton(\n \"theokit-sdk.providers.model-info-patched\",\n () => new Set<string>(),\n);\nconst indexState = globalSingleton(\"theokit-sdk.providers.model-info-loaded\", () => ({\n loaded: false,\n}));\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/** Was this key patched by the LIVE models-dev source (vs the vendored catalog)? @internal */\nexport function isPatchedModelKey(key: string): boolean {\n return patchedModelKeys.has(key);\n}\n\n/**\n * Patch the index with fresher per-model data (the models-dev source). M44 H2 fix — a per-FIELD shallow\n * MERGE, not a wholesale replace: models.dev can never supply the theokit extension fields\n * (`cache_control`, `structured_output` overlays), so a replace would wipe them and silently flip\n * capability answers. Incoming fields win; existing fields survive when the patch omits them.\n * @internal\n */\nexport function patchModelInfo(key: string, model: CatalogModel): void {\n ensureModelIndexLoaded();\n const existing = modelInfoIndex.get(key);\n modelInfoIndex.set(key, existing === undefined ? model : { ...existing, ...model });\n patchedModelKeys.add(key);\n}\n\n/** All indexed `provider/model` keys (for maintenance/tests). @internal */\nexport function listModelInfoKeys(): string[] {\n ensureModelIndexLoaded();\n return [...modelInfoIndex.keys()];\n}\n\nfunction ensureModelIndexLoaded(): void {\n if (indexState.loaded) return;\n indexState.loaded = true;\n // M44 L9 fix — never throw from a capability/pricing lookup: a missing/corrupt vendored catalog degrades\n // to conservative defaults with a WARN (the deleted EXACT map could never throw; keep that property).\n try {\n const catalog = loadProviderCatalog();\n for (const entry of Object.values(catalog)) {\n indexEntryModels(entry);\n }\n } catch (err) {\n process.stderr.write(\n `[theokit-sdk] WARN: provider catalog unavailable (${(err as Error).message}) — per-model data disabled\\n`,\n );\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 patchedModelKeys.clear();\n indexState.loaded = 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 // M45 review L4 — alias keys too (e.g. entry `google-gemini` alias `google`), consistent with the\n // model-info index's alias-keyed convention.\n for (const alias of entry.aliases ?? []) {\n if (_capabilitiesCache[alias] === undefined) _capabilitiesCache[alias] = entry.capabilities;\n }\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 type { ProviderProfile } from \"../types.js\";\n\nexport const ANTHROPIC: ProviderProfile = {\n name: \"anthropic\",\n apiMode: \"anthropic_messages\",\n envVars: [\"ANTHROPIC_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.anthropic.com\",\n modelsUrl: \"https://api.anthropic.com/v1/models\",\n hostname: \"api.anthropic.com\",\n fallbackModels: [\"claude-opus-4-7\", \"claude-sonnet-4-6\", \"claude-haiku-4-5-20251001\"],\n // M45 — the Anthropic beta-features header (interleaved thinking + fine-grained tool streaming). An\n // Anthropic API constant, adapted verbatim from OpenCode's anthropic plugin (MIT © 2025 opencode). The\n // SANCTIONED behavior delta of M45 (ADR D4) — consumed by the anthropic transport's extraHeaders wiring.\n extraHeaders: {\n \"anthropic-beta\": \"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14\",\n },\n};\n","/**\n * AWS Bedrock profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Bearer-only auth via `AWS_BEARER_TOKEN_BEDROCK` env (GA Sep 2025).\n * Optional `@aws/bedrock-token-generator` peer dep auto-refreshes short-term\n * tokens (D287). Transport via native `fetch`; no `@aws-sdk/*` dependency.\n *\n * Model IDs follow the `bedrock/{aws-id}` convention so the router can\n * infer the provider via prefix routing (D186). The client strips the\n * `bedrock/` prefix before building the URL.\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const BEDROCK: ProviderProfile = {\n name: \"bedrock\",\n apiMode: \"bedrock_anthropic\",\n envVars: [\"AWS_BEARER_TOKEN_BEDROCK\"],\n authType: \"aws_bearer\",\n baseUrl: \"https://bedrock-runtime.us-east-1.amazonaws.com\",\n modelsUrl: undefined,\n hostname: \"bedrock-runtime.amazonaws.com\",\n fallbackModels: [\n \"bedrock/us.anthropic.claude-sonnet-4-5-v1:0\",\n \"bedrock/us.anthropic.claude-opus-4-7-v1:0\",\n \"bedrock/global.anthropic.claude-haiku-4-5-v1:0\",\n ],\n};\n\n/** Strip `\"bedrock/\"` prefix so the raw AWS model id is used in the URL. */\nexport function stripBedrockPrefix(modelId: string): string {\n return modelId.replace(/^bedrock\\//, \"\");\n}\n\n/**\n * Infer AWS region from a Bedrock model id prefix (D290).\n *\n * `global.*` routes via `us-east-1` (AWS default entrypoint for global\n * inference profiles).\n */\nexport function inferRegionFromModelId(modelId: string): string | undefined {\n const id = stripBedrockPrefix(modelId);\n if (id.startsWith(\"global.\")) return \"us-east-1\";\n if (id.startsWith(\"us.\")) return process.env.AWS_REGION ?? \"us-east-1\";\n if (id.startsWith(\"eu.\")) return process.env.AWS_REGION ?? \"eu-west-1\";\n if (id.startsWith(\"apac.\")) return process.env.AWS_REGION ?? \"ap-southeast-1\";\n if (id.startsWith(\"jp.\")) return \"ap-northeast-1\";\n return undefined;\n}\n\n/** Resolve baseUrl from model id; falls back to `AWS_REGION` env or `us-east-1`. */\nexport function resolveBedrockBaseUrl(modelId: string): string {\n const region = inferRegionFromModelId(modelId) ?? process.env.AWS_REGION ?? \"us-east-1\";\n return `https://bedrock-runtime.${region}.amazonaws.com`;\n}\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * M45 — the data-only base for OpenAI-compatible chat_completions providers. OpenCode's\n * `openai-compatible-profile` pattern (MIT © 2025 opencode — `packages/llm/src/providers/`) flattened to\n * theokit's data model: leaves declare name/baseUrl/envVars (+ overrides) in ~10 lines; the router's\n * URL-join rule (version-segment detection + `chatCompletionsPath` escape) derives the endpoint.\n *\n * @internal\n */\nexport function openAiCompatibleProfile(\n p: { name: string; baseUrl: string; envVars: readonly string[] } & Partial<ProviderProfile>,\n): ProviderProfile {\n return {\n apiMode: \"chat_completions\",\n authType: \"api_key\",\n fallbackModels: [],\n ...p,\n };\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cerebras. Integration header adapted from OpenCode's `cerebras.ts` (MIT — value changed to\n * `theokit`, never `opencode`: the header attributes TRAFFIC). Models per models.dev (2026-07 snapshot).\n */\nexport const CEREBRAS = openAiCompatibleProfile({\n name: \"cerebras\",\n baseUrl: \"https://api.cerebras.ai/v1\",\n envVars: [\"CEREBRAS_API_KEY\"],\n fallbackModels: [\"gpt-oss-120b\", \"zai-glm-4.7\"],\n extraHeaders: { \"X-Cerebras-3rd-Party-Integration\": \"theokit\" },\n hostname: \"api.cerebras.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cohere via its OpenAI-compatibility surface (`api.cohere.ai/compatibility/v1` — the native v2 API\n * is NOT chat_completions; the discovery flagged the old catalog baseUrl as doubly wrong). Models per\n * models.dev `cohere` (2026-07 snapshot). SOURCE NOTE (review L2): the compatibility endpoint + `CO_API_KEY`\n * come from Cohere's own docs/python-SDK convention (not vendored in this repo's references) — verify with a\n * live smoke when a key is available.\n */\nexport const COHERE = openAiCompatibleProfile({\n name: \"cohere\",\n baseUrl: \"https://api.cohere.ai/compatibility/v1\",\n envVars: [\"COHERE_API_KEY\", \"CO_API_KEY\"],\n fallbackModels: [\"command-a-03-2025\"],\n hostname: \"api.cohere.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — DeepInfra. OpenAI-compat surface under /v1/openai (models.dev `deepinfra`, OpenCode profile map). */\nexport const DEEPINFRA = openAiCompatibleProfile({\n name: \"deepinfra\",\n baseUrl: \"https://api.deepinfra.com/v1/openai\",\n envVars: [\"DEEPINFRA_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen3-32B\"],\n hostname: \"api.deepinfra.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Gemini via OpenRouter passthrough. Direct Gemini API uses a different\n * dialect (`generateContent`); SDK currently routes through OpenRouter's\n * OpenAI-compatible endpoint so the chat_completions transport works.\n *\n * A future plugin `@theokit-provider-gemini-direct` can override this with\n * `apiMode: \"gemini_generate_content\"` once that transport ships.\n */\nexport const GEMINI: ProviderProfile = {\n name: \"gemini\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENROUTER_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n hostname: \"openrouter.ai\",\n fallbackModels: [\"google/gemini-2.0-flash-001\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Google Gemini via the DIRECT OpenAI-compat endpoint (a Google API key, not OpenRouter). Distinct\n * from the `gemini` builtin (an OpenRouter passthrough) by ADR D3 — two routes, two names. Endpoint + env\n * vars per Google's OpenAI-compatibility docs (mirrored by models.dev `google` + the M44 catalog entry).\n */\nexport const GOOGLE = openAiCompatibleProfile({\n name: \"google\",\n baseUrl: \"https://generativelanguage.googleapis.com/v1beta/openai\",\n envVars: [\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\", \"GOOGLE_GENERATIVE_AI_API_KEY\"],\n fallbackModels: [\"gemini-2.5-pro\", \"gemini-2.5-flash\"],\n hostname: \"generativelanguage.googleapis.com\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Groq. Values per models.dev `groq` (2026-07 snapshot); OpenAI-compat surface under /openai/v1. */\nexport const GROQ = openAiCompatibleProfile({\n name: \"groq\",\n baseUrl: \"https://api.groq.com/openai/v1\",\n envVars: [\"GROQ_API_KEY\"],\n fallbackModels: [\"llama-3.3-70b-versatile\", \"llama-3.1-8b-instant\"],\n hostname: \"api.groq.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * llama.cpp server provider profile (T7.2, ADR D189).\n *\n * llama.cpp ships a HTTP server binary (`./server` since b1500+) that\n * implements the OpenAI-compatible `/v1/chat/completions` endpoint on\n * `http://localhost:8080` by default. Inherits `authType: \"none\"` from\n * D182 — no API key required for local use.\n *\n * llama.cpp idiosyncrasies:\n * - Server loads a single GGUF model at startup via `--model` CLI\n * flag. The `model` field in the chat-completions request is\n * cosmetic — any string works; the response comes from the loaded\n * model regardless. This is documented in\n * `.claude/knowledge-base/reviews/edge-case/ollama-integration-edge-cases-2026-05-21.md`\n * as EC-O.\n * - Tool calling support depends entirely on the underlying model.\n *\n * Override the default URL with `LLAMACPP_HOST`.\n *\n * @internal\n */\nexport const LLAMACPP: ProviderProfile = {\n name: \"llamacpp\",\n aliases: [\"llama-cpp\", \"llama.cpp\"],\n apiMode: \"chat_completions\",\n envVars: [\"LLAMACPP_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:8080\",\n modelsUrl: \"http://localhost:8080/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * LM Studio provider profile (T7.1, ADR D188).\n *\n * LM Studio exposes an OpenAI-compatible `/v1/chat/completions` endpoint\n * on `http://localhost:1234` by default (configurable via the LM Studio\n * UI under \"Local Server\"). Inherits the `authType: \"none\"` primitive\n * from D182 — no API key required for local use.\n *\n * LM Studio idiosyncrasies:\n * - Loads ONE model at a time via the desktop UI. The `model` field in\n * the chat-completions request is informational only — LM Studio\n * serves whatever model is currently loaded.\n * - `/v1/models` returns a single entry pointing to the loaded model.\n * - Tool calling depends on the underlying model.\n *\n * Override the default URL with `LMSTUDIO_HOST` (mirrors `OLLAMA_HOST`).\n *\n * @internal\n */\nexport const LMSTUDIO: ProviderProfile = {\n name: \"lmstudio\",\n aliases: [\"lm-studio\", \"lm_studio\"],\n apiMode: \"chat_completions\",\n envVars: [\"LMSTUDIO_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:1234\",\n modelsUrl: \"http://localhost:1234/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Mistral (La Plateforme). Values per models.dev `mistral` (2026-07 snapshot). */\nexport const MISTRAL = openAiCompatibleProfile({\n name: \"mistral\",\n baseUrl: \"https://api.mistral.ai/v1\",\n envVars: [\"MISTRAL_API_KEY\"],\n fallbackModels: [\"mistral-large-latest\", \"codestral-latest\"],\n hostname: \"api.mistral.ai\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Ollama — local-first LLM runtime (ADR D182).\n *\n * Ships as a builtin so `Agent.create({ model: \"ollama/llama3.2\" })` works\n * with zero configuration when `ollama serve` is running on the default\n * port. `authType: \"none\"` signals the router to skip env-key resolution\n * and use a placeholder credential (Ollama ignores Authorization headers\n * on local installs).\n *\n * Overrides:\n * - `OLLAMA_HOST` — replaces the default `http://localhost:11434` baseUrl\n * (advanced users running Ollama on a remote machine).\n * - `OLLAMA_API_KEY` — replaces the placeholder when Ollama is behind a\n * reverse-proxy with auth or when using Ollama Cloud (paid tier).\n */\nexport const OLLAMA: ProviderProfile = {\n name: \"ollama\",\n apiMode: \"chat_completions\",\n envVars: [\"OLLAMA_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:11434\",\n modelsUrl: \"http://localhost:11434/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"llama3.2\", \"qwen2.5\", \"mistral\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENAI: ProviderProfile = {\n name: \"openai\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.openai.com\",\n modelsUrl: \"https://api.openai.com/v1/models\",\n hostname: \"api.openai.com\",\n fallbackModels: [\"gpt-4o\", \"gpt-4o-mini\"],\n};\n","import { randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { z } from \"zod\";\n\n/**\n * M42 — the SDK credential store. Promoted DOWN from agent-builder's hardened `agents/lib/credentials.ts`\n * (M37), generalized from a closed `openrouter|anthropic|openai` union to an open `provider: string` and\n * driven by a caller-supplied {@link CredentialStoreConfig} (no hardcoded `.agent-builder`/`auth.json` /\n * `AGENT_BUILDER_HOME`). The security-critical file mechanics are ported VERBATIM (ADR D3 of the M42 plan):\n * atomic O_EXCL + rename + fsync write, 0700/0600 mode gates, `env` is always a PARAMETER (never an ambient\n * `process.env` read). Contract SHAPE adapted from OpenCode's provider `auth.loader` (MIT © 2025 opencode).\n *\n * The env-precedence + key-prefix-inference + declared-provider rungs of the agent-builder resolver are\n * APP POLICY and deliberately stay UP in the consumer; this module owns only the on-disk store + the\n * `api|oauth` discriminated union. See {@link resolveCredential} (SDK) for the store-read + refresh path.\n *\n * @internal\n */\nimport type {\n CredentialStoreConfig,\n StoredCredential,\n StoredOAuthCredential,\n} from \"./auth-types.js\";\n\n/** The store directory, honoring an optional `homeEnvVar` override. */\nexport function credentialHome(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const override = config.homeEnvVar !== undefined ? env[config.homeEnvVar]?.trim() : undefined;\n return override !== undefined && override.length > 0\n ? override\n : join(config.home, config.dirName);\n}\n\n/** The credential file path inside the (possibly overridden) store directory. */\nexport function authFilePath(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return join(credentialHome(config, env), config.fileName);\n}\n\n/** A credential problem the caller can act on. Never carries the key value. */\nexport class CredentialError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"CredentialError\";\n }\n}\n\n/**\n * The on-disk store — a discriminated union on `type` (OpenCode `Info` shape). A legacy file with NO\n * `type` (or `type: 'api'`) is the API-key variant — read unchanged, no migration. The `oauth` variant\n * carries the token pair + expiry.\n */\nconst apiFileSchema = z\n .object({\n type: z.literal(\"api\").optional(),\n provider: z.string().min(1).optional(),\n api_key: z.string(),\n })\n .strict();\n\nconst oauthFileSchema = z\n .object({\n type: z.literal(\"oauth\"),\n provider: z.string().min(1),\n access: z.string().min(1),\n refresh: z.string().min(1),\n expires: z.number(),\n account_id: z.string().optional(),\n })\n .strict();\n\n// oauth first (it requires `type: 'oauth'`); a legacy `{provider?, api_key}` falls through to api.\nconst fileSchema = z.union([oauthFileSchema, apiFileSchema]);\n\n/**\n * Read the credential file. Absent ⇒ `undefined` (the normal case). Present-but-wrong is a typed error\n * naming the file: a malformed credential store must not surface as a raw parse crash. Enforces the\n * 0700 dir / 0600 file mode gates (ported verbatim — a writable dir lets an attacker swap the file for a\n * symlink to their own account).\n */\n/**\n * The 0700-dir / 0600-file mode gates (ported verbatim). The DIRECTORY matters as much as the file:\n * `mkdirSync(mode)` applies only at creation, so a pre-existing store dir keeps whatever mode it had, and a\n * writable dir lets an attacker replace the credential file with a symlink to their own 0600 file — the\n * agent then runs on THEIR account.\n */\nfunction assertSecureModes(dirPath: string, path: string): void {\n const dirMode = statSync(dirPath).mode & 0o777;\n if ((dirMode & 0o022) !== 0) {\n throw new CredentialError(\n `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file ` +\n `inside it can be replaced. Fix it with: chmod 700 ${dirPath}`,\n );\n }\n const mode = statSync(path).mode & 0o777;\n if ((mode & 0o077) !== 0) {\n throw new CredentialError(\n `${path} is readable by other users (mode ${mode.toString(8)}). ` +\n `A credential file must not be. Fix it with: chmod 600 ${path}`,\n );\n }\n}\n\n/**\n * A `z.union` reports a generic \"Invalid input\" at the root, hiding WHAT is wrong. Pick the sub-schema the\n * file was CLEARLY aiming at (by its `type` discriminant) and surface that schema's specific issue.\n */\nfunction describeUnionError(parsed: unknown, err: unknown, path: string): CredentialError {\n const looksOAuth =\n typeof parsed === \"object\" &&\n parsed !== null &&\n (parsed as { type?: unknown }).type === \"oauth\";\n const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);\n let issue: z.ZodIssue | undefined;\n if (!specific.success) {\n issue = specific.error.issues[0];\n } else if (err instanceof z.ZodError) {\n issue = err.issues[0];\n }\n return new CredentialError(\n `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(\".\") || \"root\"}]`,\n );\n}\n\n/** Parse the raw file into the store union, surfacing the SPECIFIC sub-schema issue (not a generic union error). */\nfunction parseStoredFile(raw: string, path: string): StoredCredential {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // The parser's message embeds a snippet of the INPUT — up to the raw key when a user pastes the bare\n // key instead of JSON. The position is not actionable anyway, so the expected shape is more useful.\n throw new CredentialError(\n `${path} is not valid JSON. Expected: {\"provider\": \"<name>\", \"api_key\": \"...\"}`,\n );\n }\n try {\n return fileSchema.parse(parsed);\n } catch (err) {\n throw describeUnionError(parsed, err, path);\n }\n}\n\nexport function readAuthFile(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredCredential | undefined {\n const path = authFilePath(config, env);\n\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new CredentialError(`cannot read ${path}: ${(err as Error).message}`);\n }\n\n assertSecureModes(credentialHome(config, env), path);\n return parseStoredFile(raw, path);\n}\n\n/**\n * Read the stored OAuth credential (with its refresh token), or `undefined` when the store is absent or\n * holds an api credential. The oauth engine needs the refresh token, which the resolved bearer does not\n * carry. Enforces the same 0600/0700 gates as every other read.\n */\nexport function readStoredOAuth(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredOAuthCredential | undefined {\n const stored = readAuthFile(config, env);\n return stored !== undefined && stored.type === \"oauth\" ? stored : undefined;\n}\n\n/** Narrows a writable credential to the oauth variant. */\nfunction isOAuthWrite(\n c: { provider: string; apiKey: string } | StoredOAuthCredential,\n): c is StoredOAuthCredential {\n return \"type\" in c && c.type === \"oauth\";\n}\n\n/**\n * Persist a credential atomically at mode `0600`. Ported VERBATIM (ADR D3): write to a random-named temp\n * file in the same directory with `wx` (O_EXCL), fsync, close, chmod, then `rename` (atomic on POSIX) —\n * so a crash mid-write leaves whatever was there untouched, and a pre-planted symlink cannot capture the\n * key. The api variant persists the unchanged `{provider, api_key}` (back-compat, no `type` key); the\n * oauth variant persists `{type:'oauth', provider, access, refresh, expires, account_id?}`.\n */\n/** Build the on-disk JSON payload for the credential variant, validating non-empty tokens. */\nfunction buildStorePayload(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n): Record<string, unknown> {\n if (isOAuthWrite(cred)) {\n if (cred.access.length === 0 || cred.refresh.length === 0) {\n throw new CredentialError(\n \"refusing to write an oauth credential with an empty access/refresh token\",\n );\n }\n return {\n type: \"oauth\",\n provider: cred.provider,\n access: cred.access,\n refresh: cred.refresh,\n expires: cred.expires,\n ...(cred.account_id !== undefined ? { account_id: cred.account_id } : {}),\n };\n }\n if (typeof cred.apiKey !== \"string\" || cred.apiKey.length === 0) {\n throw new CredentialError(\"refusing to write an empty API key\");\n }\n return { provider: cred.provider, api_key: cred.apiKey };\n}\n\nexport function writeCredential(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const payload = buildStorePayload(cred);\n\n const dir = credentialHome(config, env);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700); // unconditional: mkdirSync's mode applies only at creation\n\n const path = authFilePath(config, env);\n // RANDOM name + `wx` (O_EXCL): a predictable temp name with a plain write follows a pre-planted SYMLINK,\n // landing the key in an attacker's file while reporting success. O_EXCL refuses any pre-existing file or\n // link; the random suffix also removes the pid collision two containers sharing a bind-mounted home make.\n const tmp = `${path}.tmp-${randomBytes(8).toString(\"hex\")}`;\n try {\n const fd = openSync(tmp, \"wx\", 0o600);\n try {\n writeFileSync(fd, `${JSON.stringify(payload, null, 2)}\\n`);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n chmodSync(tmp, 0o600); // explicit: the mode argument is subject to umask\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // the temp file may not exist; its absence is not a failure of the write\n }\n throw new CredentialError(`cannot write ${path}: ${(err as Error).message}`);\n }\n return path;\n}\n","/**\n * @theokit/sdk/server/auth — typed error classes\n *\n * Plan T1.2 + v1.1 EC-1 (AuthCancelledError for OAuth provider error response RFC 6749 §4.1.2.1).\n */\n\n/**\n * Thrown at `defineAuth()` time when configuration is invalid\n * (e.g., duplicate provider name, invalid email shape per EC-V1-12).\n */\nexport class AuthConfigError extends Error {\n override readonly name = \"AuthConfigError\";\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(`[${code}] ${message}`);\n this.code = code;\n }\n}\n\n/**\n * Thrown at `startSignIn(providerName, ...)` or `finishSignIn(providerName, ...)`\n * when the named provider is not registered in `providers[]`.\n */\nexport class AuthProviderNotFoundError extends Error {\n override readonly name = \"AuthProviderNotFoundError\";\n readonly providerName: string;\n\n constructor(providerName: string) {\n super(\n `Auth provider not found: '${providerName}'. Register it in defineAuth({ providers: [...] }).`,\n );\n this.providerName = providerName;\n }\n}\n\n/**\n * Thrown during OAuth callback handling for state mismatches, expired\n * transactions, missing query params, or provider 4xx/5xx errors.\n *\n * Typed `code` field lets consumers branch on cause:\n * - 'oauth_transaction_expired' — cookie tx > 10min old (per ADR D5)\n * - 'oauth_state_mismatch' — query state ≠ cookie state (CSRF defense per RFC 6749 §10.12)\n * - 'oauth_provider_error' — non-access_denied error in callback URL\n * - 'oauth_token_exchange_failed' — provider rejected code-for-tokens swap\n * - 'oauth_userinfo_failed' — userinfo endpoint returned error\n * - 'oauth_missing_code_or_state' — required query params absent\n */\nexport class AuthCallbackError extends Error {\n override readonly name: string = \"AuthCallbackError\";\n readonly code: string;\n\n constructor(code: string, message?: string) {\n super(message ?? `OAuth callback error: ${code}`);\n this.code = code;\n }\n}\n\n/**\n * Per v1.1 EC-1 MUST FIX — typed subclass of AuthCallbackError for the\n * specific case where user declined consent at provider screen.\n *\n * OAuth 2.0 RFC 6749 §4.1.2.1: provider redirects with `?error=access_denied`.\n * Apps can catch this distinctly from network/server errors to render\n * \"Login cancelled — try again\" UX instead of opaque \"callback failed\".\n */\nexport class AuthCancelledError extends AuthCallbackError {\n override readonly name: string = \"AuthCancelledError\";\n readonly errorDescription?: string;\n\n constructor(errorDescription?: string) {\n super(\"user_declined_consent\", errorDescription ?? \"User declined consent at provider\");\n this.errorDescription = errorDescription;\n }\n}\n","/**\n * M42 — the SDK OAuth engine. Promoted DOWN from agent-builder's hardened `agents/lib/oauth.ts` +\n * `oauth-device.ts` (M37), generalized to `provider: string` + a caller-supplied {@link CredentialStoreConfig}\n * (no hardcoded client IDs — the caller declares its provider's endpoints). Ported VERBATIM (ADR D3): the\n * refresh coalescing lock, the no-token-in-error discipline, and the RFC 8628 device grant.\n *\n * Reuses the SDK's typed error taxonomy (`AuthCallbackError` from `server/auth`) for exchange/refresh\n * failures. All network I/O + clock + sleep are INJECTED so the flow is deterministic.\n *\n * ─── ADAPTED FROM OpenCode (MIT License, Copyright (c) 2025 opencode — https://github.com/sst/opencode) ───\n * - the device-grant poll loop (device_code → authorization_pending / slow_down) is adapted from\n * `packages/opencode/src/plugin/github-copilot/copilot.ts`;\n * - the JWT-claim / account-id extraction + the OpenAI two-step headless flow are adapted from\n * `packages/opencode/src/plugin/openai/codex.ts`.\n * The MIT license permits this reuse with attribution; this notice + the NOTICE file are that attribution.\n *\n * @internal\n */\nimport { AuthCallbackError } from \"../../server/auth/errors.js\";\n\nimport type {\n CredentialStoreConfig,\n HttpDeps,\n OAuthProviderConfig,\n OAuthTokens,\n ResolvedCredential,\n} from \"./auth-types.js\";\nimport { authFilePath, readStoredOAuth, writeCredential } from \"./credential-store.js\";\n\n/** Refresh a token this many ms BEFORE it actually expires (avoid a last-second, mid-request expiry). */\nconst REFRESH_SKEW_MS = 60_000;\n\n/** Parse an OAuth token endpoint response into our token triple. Throws a typed error on a bad shape. */\nfunction parseTokenResponse(body: unknown, now: number): OAuthTokens {\n const b = body as {\n access_token?: unknown;\n refresh_token?: unknown;\n expires_in?: unknown;\n account_id?: unknown;\n };\n if (typeof b.access_token !== \"string\" || b.access_token.length === 0) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"token response had no access_token\",\n );\n }\n if (typeof b.refresh_token !== \"string\" || b.refresh_token.length === 0) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"token response had no refresh_token\",\n );\n }\n const expiresIn = typeof b.expires_in === \"number\" ? b.expires_in : 3600;\n return {\n access: b.access_token,\n refresh: b.refresh_token,\n expires: now + expiresIn * 1000,\n ...(typeof b.account_id === \"string\" ? { accountId: b.account_id } : {}),\n };\n}\n\n/** POST a form-encoded grant to the token endpoint; return the parsed JSON or throw a typed error. */\nasync function postGrant(\n config: OAuthProviderConfig,\n form: Record<string, string>,\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n let res: Response;\n try {\n res = await deps.fetch(config.tokenEndpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\", accept: \"application/json\" },\n body: new URLSearchParams(form).toString(),\n });\n } catch (err) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n `token endpoint request failed: ${(err as Error).message}`,\n );\n }\n if (!res.ok) {\n // The body may carry an OAuth `error` code, but never echo it verbatim — it can contain a token in\n // some providers' error payloads. Report the status only.\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n `token endpoint returned HTTP ${res.status}`,\n );\n }\n let json: unknown;\n try {\n json = await res.json();\n } catch {\n // Do NOT echo the parser message — on a 200 non-JSON body it embeds a snippet of the response, which\n // in a token context can contain access/refresh material.\n throw new AuthCallbackError(\"oauth_token_exchange_failed\", \"token response was not valid JSON\");\n }\n return parseTokenResponse(json, deps.now());\n}\n\n/** Exchange an authorization `code` (+ PKCE verifier) for the token pair. */\nexport function exchangeCode(\n config: OAuthProviderConfig,\n input: { code: string; verifier: string },\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n return postGrant(\n config,\n {\n grant_type: \"authorization_code\",\n code: input.code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: input.verifier,\n },\n deps,\n );\n}\n\n/** Swap a refresh token for a fresh access (and possibly rotated refresh) token. */\nexport function refreshOAuthTokens(\n config: OAuthProviderConfig,\n refresh: string,\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n return postGrant(\n config,\n { grant_type: \"refresh_token\", refresh_token: refresh, client_id: config.clientId },\n deps,\n );\n}\n\n/** Persist a token triple to the store's oauth variant through the hardened 0600 writer. */\nexport function persistOAuthTokens(\n provider: string,\n tokens: OAuthTokens,\n store: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return writeCredential(\n {\n type: \"oauth\",\n provider,\n access: tokens.access,\n refresh: tokens.refresh,\n expires: tokens.expires,\n ...(tokens.accountId !== undefined ? { account_id: tokens.accountId } : {}),\n },\n store,\n env,\n );\n}\n\n/**\n * In-flight refreshes, keyed by the auth-file path. Refresh tokens ROTATE (single-use) on many providers,\n * so two concurrent turns must NOT both POST the same refresh token — the second would present an\n * already-consumed token and fail. This coalesces concurrent refreshes of the same store onto one promise.\n * Process-local — the single-credential store is per-user; a cross-process lock would be over-engineering.\n */\nconst inFlightRefresh = new Map<string, Promise<OAuthTokens>>();\n\n/**\n * Return a credential guaranteed fresh enough to use. An `api` credential passes through untouched. An\n * `oauth` credential still valid (beyond the skew window) passes through; an expired one is refreshed,\n * re-persisted 0600, and returned with the new access token. Concurrent refreshes of the same store are\n * coalesced (single-use refresh tokens); the rejected promise is evicted so a failure is not cached-poison.\n */\nexport async function ensureFreshCredential(\n resolved: ResolvedCredential,\n opts: {\n config: OAuthProviderConfig;\n store: CredentialStoreConfig;\n env?: Record<string, string | undefined>;\n },\n deps: HttpDeps,\n): Promise<ResolvedCredential> {\n if (resolved.kind !== \"oauth\") return resolved;\n\n const now = deps.now();\n if (resolved.expiresAt !== undefined && resolved.expiresAt > now + REFRESH_SKEW_MS) {\n return resolved; // still valid — no network, no rewrite\n }\n\n const env = opts.env ?? {};\n const path = authFilePath(opts.store, env);\n let refresh = inFlightRefresh.get(path);\n if (refresh === undefined) {\n refresh = (async (): Promise<OAuthTokens> => {\n const stored = readStoredOAuth(opts.store, env);\n if (stored === undefined) {\n // The resolved credential said oauth but the store no longer holds it — do not fabricate; surface it.\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"no stored oauth credential to refresh\",\n );\n }\n const fresh = await refreshOAuthTokens(opts.config, stored.refresh, deps);\n // M43 D4 fix #1 — the OAuth refresh response returns JWTs, not a top-level `account_id`, so\n // `parseTokenResponse` leaves `fresh.accountId` undefined. Prefer a freshly-derived id, else PRESERVE\n // the stored one (account_id is stable) — otherwise the Codex `ChatGPT-Account-Id` header empties after\n // the first refresh and the backend 401/403s.\n const merged: OAuthTokens = {\n ...fresh,\n accountId: fresh.accountId ?? stored.account_id,\n };\n persistOAuthTokens(resolved.provider, merged, opts.store, env);\n return merged;\n })();\n inFlightRefresh.set(path, refresh);\n refresh.finally(() => inFlightRefresh.delete(path)).catch(() => {});\n }\n\n const fresh = await refresh;\n return {\n kind: \"oauth\",\n provider: resolved.provider,\n apiKey: fresh.access,\n source: resolved.source,\n inferred: false,\n expiresAt: fresh.expires,\n };\n}\n","/**\n * M42 — `resolveCredential`: the public composition entrypoint over the credential store + oauth engine.\n * Given a provider name + a {@link CredentialStoreConfig} (and, for oauth, an {@link OAuthProviderConfig}),\n * read the store and return a FRESH `ResolvedCredential` — an api credential passes through by identity; an\n * oauth credential is transparently refreshed when its access token is within the skew window. Returns\n * `undefined` when the store holds no credential for `provider` (the caller then falls back to env / apiKeys).\n *\n * Mirrors agent-builder's `resolveFreshCredential` composition (store read → oauth → ensureFreshCredential),\n * defaulting `fetch`/`now` to globals. This is the async surface an oauth provider's M41 `transform.fetch`\n * calls at stream time, so a mid-turn token expiry refreshes without rebuilding the agent.\n *\n * @internal (re-exported from the package barrel as public)\n */\nimport type {\n CredentialStoreConfig,\n HttpDeps,\n OAuthProviderConfig,\n ResolvedCredential,\n} from \"./auth-types.js\";\nimport { authFilePath, readAuthFile } from \"./credential-store.js\";\nimport { ensureFreshCredential } from \"./oauth-engine.js\";\n\nexport interface ResolveCredentialOptions {\n /** The provider whose stored credential to resolve. */\n provider: string;\n /** Where the credential store lives. */\n store: CredentialStoreConfig;\n /** Env for the store's optional `homeEnvVar` override. Never an ambient read. */\n env?: Record<string, string | undefined>;\n /** Required to refresh an oauth credential; omit for an api-only store. */\n oauth?: OAuthProviderConfig;\n /** Injected HTTP + clock for deterministic tests; default globals. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * Resolve a fresh credential for `provider` from the store, or `undefined` if the store holds none for it.\n * oauth credentials are auto-refreshed when `opts.oauth` is supplied; api credentials pass through.\n */\n/** Resolve (and, when a config is supplied, refresh) the oauth variant for the requested provider. */\nasync function resolveOAuth(\n stored: { provider: string; access: string; expires: number },\n path: string,\n opts: ResolveCredentialOptions,\n env: Record<string, string | undefined>,\n): Promise<ResolvedCredential | undefined> {\n if (stored.provider !== opts.provider) return undefined;\n const base: ResolvedCredential = {\n kind: \"oauth\",\n provider: opts.provider,\n apiKey: stored.access,\n source: path,\n inferred: false,\n expiresAt: stored.expires,\n };\n if (opts.oauth === undefined) return base; // no config to refresh with — return the stored access token\n const deps: HttpDeps = {\n fetch: opts.deps?.fetch ?? fetch,\n now: opts.deps?.now ?? (() => Date.now()),\n };\n return ensureFreshCredential(base, { config: opts.oauth, store: opts.store, env }, deps);\n}\n\nexport async function resolveCredential(\n opts: ResolveCredentialOptions,\n): Promise<ResolvedCredential | undefined> {\n const env = opts.env ?? {};\n const stored = readAuthFile(opts.store, env);\n if (stored === undefined) return undefined;\n\n const path = authFilePath(opts.store, env);\n\n if (stored.type === \"oauth\") {\n return resolveOAuth(stored, path, opts, env);\n }\n\n // api variant: require the stored `provider` to MATCH the requested provider (M42 review MEDIUM-2).\n // The generic SDK cannot infer a provider from a key prefix (that was agent-builder app policy), so a\n // provider-less or mismatched stored key is NOT attributed to the requested provider — otherwise a legacy\n // `{api_key:\"sk-ant-…\"}` file could be POSTed to the wrong vendor's endpoint (cross-vendor key exposure).\n // Fail-closed, mirroring OpenCode, whose credential resolution never attributes a key across providers.\n if (stored.api_key.length === 0) return undefined;\n if (stored.provider !== opts.provider) return undefined;\n return {\n kind: \"api\",\n provider: opts.provider,\n apiKey: stored.api_key,\n source: path,\n inferred: false,\n };\n}\n","import { homedir } from \"node:os\";\n\nimport type { CredentialStoreConfig, OAuthProviderConfig } from \"../../auth/auth-types.js\";\nimport { readStoredOAuth } from \"../../auth/credential-store.js\";\nimport { resolveCredential } from \"../../auth/resolve-credential.js\";\nimport type { ProviderProfile } from \"../types.js\";\n\n/**\n * M43 — the ChatGPT \"Codex\" backend as a first-class builtin `ProviderProfile`. Migrated from the\n * agent-builder M40 workaround; the SDK now owns the provider, so a consumer only selects\n * `openai-chatgpt/<model>` and logs in — ZERO provider logic in the consumer.\n *\n * Grounded 100% in OpenCode's provider-auth model (see the codex-provider-in-sdk blueprint):\n * - static profile + a `transform.fetch` that resolves the LIVE credential per HTTP request (fresh Bearer +\n * dynamic `ChatGPT-Account-Id`), so a mid-turn expiry refreshes transparently with NO agent rebuild;\n * - the protocol values (endpoint, models, oauth config, `originator` header) are SDK-owned constants,\n * adapted from OpenCode's `openai.ts` (MIT © 2025 opencode — see NOTICE).\n *\n * @internal\n */\n\n/**\n * The SDK-owned ambient credential store the transform reads. Defaults to `~/.theokit/auth.json`. A consumer\n * points it at its existing store dir via the DEDICATED `THEOKIT_AUTH_HOME` env var (NOT `THEOKIT_HOME` — that\n * is the SDK's whole home directory for personality/credential-pool/profiles; overloading it would redirect\n * the entire runtime). The OpenCode \"ambient credential Service\" analog.\n */\nconst DEFAULT_STORE: CredentialStoreConfig = {\n home: homedir(),\n dirName: \".theokit\",\n fileName: \"auth.json\",\n homeEnvVar: \"THEOKIT_AUTH_HOME\",\n};\n\n/**\n * The OpenAI OAuth config the transform resolves + refreshes against. `provider: \"openai\"` is the STORE\n * provider (what `/login` persists), deliberately distinct from this profile's routing name `openai-chatgpt`\n * — the two-namespace split (integration id vs routed provider) mirrors OpenCode. Endpoints/clientId/scopes\n * adapted from OpenCode `openai.ts`.\n */\nconst OPENAI_OAUTH_CONFIG: OAuthProviderConfig = {\n provider: \"openai\",\n authorizeEndpoint: \"https://auth.openai.com/oauth/authorize\",\n tokenEndpoint: \"https://auth.openai.com/oauth/token\",\n clientId: \"app_EMoamEEZ73f0CkXaXp7hrann\",\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n redirectUri: \"https://auth.openai.com/deviceauth/callback\",\n};\n\n/**\n * Build the per-request fetch: resolve a FRESH (refreshed) Bearer + the LIVE account-id from the ambient\n * store, and inject them as headers. Re-resolves on EVERY call → mid-turn refresh with no rebuild. A\n * `Headers` object is used so `authorization` is set case-insensitively (never doubled). If no credential is\n * logged in, throw a clear error rather than putting the router's `__oauth_lazy_token__` placeholder on the\n * wire (fail-closed — the OpenCode `MissingCredentialError` semantics).\n */\nfunction codexFetch(): typeof fetch {\n return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n const env = process.env as Record<string, string | undefined>;\n const resolved = await resolveCredential({\n provider: \"openai\",\n store: DEFAULT_STORE,\n oauth: OPENAI_OAUTH_CONFIG,\n env,\n });\n if (resolved === undefined) {\n throw new Error(\n 'openai-chatgpt: no ChatGPT credential found — run the OpenAI device login (e.g. \"/login openai\") first.',\n );\n }\n const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;\n const headers = new Headers(init?.headers);\n headers.set(\"authorization\", `Bearer ${resolved.apiKey}`);\n if (accountId !== undefined) headers.set(\"ChatGPT-Account-Id\", accountId);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport const OPENAI_CHATGPT: ProviderProfile = {\n name: \"openai-chatgpt\",\n apiMode: \"responses_api\",\n authType: \"oauth_device_code\",\n baseUrl: \"https://chatgpt.com/backend-api/codex\",\n envVars: [],\n fallbackModels: [\n \"openai-chatgpt/gpt-5.4\",\n \"openai-chatgpt/gpt-5.4-mini\",\n \"openai-chatgpt/gpt-5.5\",\n ],\n extraHeaders: { originator: \"codex_cli_rs\" },\n transform: {\n // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.\n fetch: () => codexFetch(),\n },\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENROUTER: ProviderProfile = {\n name: \"openrouter\",\n apiMode: \"chat_completions\",\n aliases: [\"or\"],\n // Ordered fallback (EC-10): OPENROUTER_API_KEY preferred, OPENAI_API_KEY as compat.\n envVars: [\"OPENROUTER_API_KEY\", \"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n modelsUrl: \"https://openrouter.ai/api/v1/models\",\n hostname: \"openrouter.ai\",\n // M45 — models refreshed (claude-3-haiku retired upstream).\n fallbackModels: [\"openai/gpt-4o-mini\", \"anthropic/claude-haiku-4-5\"],\n // M45 — OpenRouter app-attribution headers (mechanism from OpenCode's openrouter plugin, MIT; VALUES are\n // theokit's own — copying another app's referer would misattribute traffic).\n extraHeaders: { \"HTTP-Referer\": \"https://usetheo.dev\", \"X-Title\": \"theokit\" },\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Perplexity. Its endpoint is UNVERSIONED (`/chat/completions`) — the explicit `chatCompletionsPath`\n * escape expresses it (the sonar-online model family was retired; models per models.dev `perplexity`).\n */\nexport const PERPLEXITY = openAiCompatibleProfile({\n name: \"perplexity\",\n baseUrl: \"https://api.perplexity.ai\",\n chatCompletionsPath: \"/chat/completions\",\n envVars: [\"PERPLEXITY_API_KEY\"],\n fallbackModels: [\"sonar-pro\", \"sonar\"],\n hostname: \"api.perplexity.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Together AI (models.dev id `togetherai` — kept as an alias). Values per the 2026-07 snapshot. */\nexport const TOGETHER = openAiCompatibleProfile({\n name: \"together\",\n aliases: [\"togetherai\"],\n baseUrl: \"https://api.together.xyz/v1\",\n envVars: [\"TOGETHER_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen2.5-7B-Instruct-Turbo\"],\n hostname: \"api.together.xyz\",\n});\n","/**\n * GCP Vertex AI profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Required peer dep: `google-auth-library` (D288). Resolves access tokens\n * via ADC (env → gcloud → metadata server → WIF).\n *\n * Model IDs follow the convention `vertex/{dialect}/{model}`:\n * - `vertex/google/gemini-2.0-flash-001` → OpenAI-compat endpoint (D291)\n * - `vertex/anthropic/claude-sonnet-4-5@20250929` → :rawPredict (D292)\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const VERTEX: ProviderProfile = {\n name: \"vertex\",\n apiMode: \"anthropic_messages\", // sub-dispatched in selectTransport by profile.name\n envVars: [\"GOOGLE_APPLICATION_CREDENTIALS\"],\n authType: \"gcp_oauth\",\n baseUrl: \"https://us-central1-aiplatform.googleapis.com\",\n modelsUrl: undefined,\n hostname: \"aiplatform.googleapis.com\",\n fallbackModels: [\n \"vertex/anthropic/claude-sonnet-4-5@20250929\",\n \"vertex/google/gemini-2.0-flash-001\",\n ],\n};\n\n/**\n * D293 absorbed: when location === \"global\", use `aiplatform.googleapis.com`\n * (no `global-` prefix) — known bug `streamRawPredict` 404 at\n * `global-aiplatform.googleapis.com` (a peer#10287).\n */\nexport function resolveVertexBaseUrl(opts: {\n projectId: string;\n location: string;\n modelDialect: \"anthropic\" | \"gemini\";\n}): string {\n const host =\n opts.location === \"global\"\n ? \"aiplatform.googleapis.com\"\n : `${opts.location}-aiplatform.googleapis.com`;\n if (opts.modelDialect === \"gemini\") {\n // OpenAI-compat endpoint (D291) — the client appends `/chat/completions`.\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/endpoints/openapi`;\n }\n // Anthropic — base URL up to `/publishers/anthropic` (model id appended by client).\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/publishers/anthropic`;\n}\n\n/** Detect dialect from a `vertex/{dialect}/{model}` id. Default: gemini. */\nexport function inferModelDialect(modelId: string): \"anthropic\" | \"gemini\" {\n if (modelId.includes(\"/anthropic/\")) return \"anthropic\";\n if (modelId.includes(\"/google/\")) return \"gemini\";\n return \"gemini\";\n}\n\n/** Strip the `vertex/{dialect}/` prefix so the raw model id is used in the URL. */\nexport function stripVertexPrefix(modelId: string): string {\n return modelId.replace(/^vertex\\/(anthropic|google)\\//, \"\");\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — xAI (Grok). Values per models.dev `xai` (2026-07 snapshot; grok-2 retired). */\nexport const XAI = openAiCompatibleProfile({\n name: \"xai\",\n aliases: [\"grok\"],\n baseUrl: \"https://api.x.ai/v1\",\n envVars: [\"XAI_API_KEY\"],\n fallbackModels: [\"grok-4.5\", \"grok-4.3\"],\n hostname: \"api.x.ai\",\n});\n","/**\n * Eager registration of builtin providers (T3.3). Side-effect import:\n * importing this module registers the 4 builtins with the registry.\n *\n * Lazy user-plugin discovery is handled by `discovery.ts` (T3.4).\n *\n * @internal\n */\n\nimport { registerCatalogProviders } from \"../catalog-loader.js\";\nimport { registerProvider } from \"../registry.js\";\nimport { ANTHROPIC } from \"./anthropic.js\";\nimport { BEDROCK } from \"./bedrock.js\";\nimport { CEREBRAS } from \"./cerebras.js\";\nimport { COHERE } from \"./cohere.js\";\nimport { DEEPINFRA } from \"./deepinfra.js\";\nimport { GEMINI } from \"./gemini.js\";\nimport { GOOGLE } from \"./google.js\";\nimport { GROQ } from \"./groq.js\";\nimport { LLAMACPP } from \"./llamacpp.js\";\nimport { LMSTUDIO } from \"./lmstudio.js\";\nimport { MISTRAL } from \"./mistral.js\";\nimport { OLLAMA } from \"./ollama.js\";\nimport { OPENAI } from \"./openai.js\";\nimport { OPENAI_CHATGPT } from \"./openai-chatgpt.js\";\nimport { OPENROUTER } from \"./openrouter.js\";\nimport { PERPLEXITY } from \"./perplexity.js\";\nimport { TOGETHER } from \"./together.js\";\nimport { VERTEX } from \"./vertex.js\";\nimport { XAI } from \"./xai.js\";\n\n// M45 review M2 — the guard lives on globalThis like the registry itself (M44 B1): a process importing both\n// bundle copies (`@theokit/sdk` + `@theokit/sdk/models`) must not re-register 19 builtins with bogus\n// \"overridden by user plugin\" WARNs.\nconst _registeredState = ((): { done: boolean } => {\n const g = globalThis as unknown as Record<symbol, { done: boolean }>;\n const sym = Symbol.for(\"theokit-sdk.providers.builtins-registered\");\n if (g[sym] === undefined) g[sym] = { done: false };\n return g[sym];\n})();\n\nexport function registerBuiltins(): void {\n if (_registeredState.done) return;\n _registeredState.done = true;\n // First-party builtins (take priority — registered first)\n registerProvider(ANTHROPIC);\n registerProvider(OPENAI);\n registerProvider(OPENAI_CHATGPT);\n registerProvider(OPENROUTER);\n registerProvider(GEMINI);\n registerProvider(OLLAMA);\n registerProvider(LMSTUDIO);\n registerProvider(LLAMACPP);\n registerProvider(BEDROCK);\n registerProvider(VERTEX);\n // M45 — the data-provider fleet (one file each on the openai-compatible base).\n registerProvider(GOOGLE);\n registerProvider(MISTRAL);\n registerProvider(GROQ);\n registerProvider(COHERE);\n registerProvider(DEEPINFRA);\n registerProvider(TOGETHER);\n registerProvider(XAI);\n registerProvider(PERPLEXITY);\n registerProvider(CEREBRAS);\n // Dynamic catalog — 40+ providers from JSON (T10.1, ADR D447)\n registerCatalogProviders();\n}\n\n/** Test-only reset. @internal */\nexport function _resetBuiltinsRegistered(): void {\n _registeredState.done = false;\n}\n\nexport {\n ANTHROPIC,\n BEDROCK,\n GEMINI,\n LLAMACPP,\n LMSTUDIO,\n OLLAMA,\n OPENAI,\n OPENAI_CHATGPT,\n OPENROUTER,\n VERTEX,\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 { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, 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 // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"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/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\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 — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\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 for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n process.stderr.write(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\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 let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog (OpenCode's delete-and-fall-through).\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\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 try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n process.stderr.write(\n `[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`,\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 // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works standalone\n // (without the consumer having built an Agent first).\n registerBuiltins();\n // M44 L11 fix — presence-based would treat \"0\"/\"false\"/\"\" as disabled; only truthy values disable.\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n if (kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\") {\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 try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n process.stderr.write(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\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"]}
1
+ {"version":3,"sources":["../src/internal/global-singleton.ts","../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/builtin/anthropic.ts","../src/internal/providers/builtin/bedrock.ts","../src/internal/providers/builtin/openai-compatible.ts","../src/internal/providers/builtin/cerebras.ts","../src/internal/providers/builtin/cohere.ts","../src/internal/providers/builtin/deepinfra.ts","../src/internal/providers/builtin/gemini.ts","../src/internal/providers/builtin/google.ts","../src/internal/providers/builtin/groq.ts","../src/internal/providers/builtin/llamacpp.ts","../src/internal/providers/builtin/lmstudio.ts","../src/internal/providers/builtin/mistral.ts","../src/internal/providers/builtin/ollama.ts","../src/internal/providers/builtin/openai.ts","../src/internal/auth/credential-store.ts","../src/server/auth/errors.ts","../src/internal/auth/oauth-engine.ts","../src/internal/auth/resolve-credential.ts","../src/internal/providers/builtin/openai-chatgpt.ts","../src/internal/providers/builtin/openrouter.ts","../src/internal/providers/builtin/perplexity.ts","../src/internal/providers/builtin/together.ts","../src/internal/providers/builtin/vertex.ts","../src/internal/providers/builtin/xai.ts","../src/internal/providers/builtin/index.ts","../src/internal/providers/catalog-source-models-dev.ts"],"names":["z","dirname","fileURLToPath","join","readFileSync","statSync","mkdirSync","chmodSync","randomBytes","openSync","writeFileSync","fsyncSync","closeSync","renameSync","unlinkSync","fresh","homedir","createHash","path"],"mappings":";;;;;;;;;;;;;AAYO,SAAS,eAAA,CAAmB,KAAa,MAAA,EAAoB;AAClE,EAAA,MAAM,CAAA,GAAI,UAAA;AACV,EAAA,MAAM,GAAA,GAAM,MAAA,CAAO,GAAA,CAAI,GAAG,CAAA;AAC1B,EAAA,IAAI,EAAE,GAAG,CAAA,KAAM,QAAW,CAAA,CAAE,GAAG,IAAI,MAAA,EAAO;AAC1C,EAAA,OAAO,EAAE,GAAG,CAAA;AACd;ACFO,IAAM,aAAa,CAAC,MAAA,EAAQ,OAAA,EAAS,OAAA,EAAS,SAAS,KAAK,CAAA;AAGnE,IAAM,UAAA,GAAaA,MAChB,MAAA,CAAO;AAAA;AAAA,EAEN,KAAA,EAAOA,KAAA,CAAE,MAAA,EAAO,CAAE,WAAA,EAAY;AAAA,EAC9B,MAAA,EAAQA,KAAA,CAAE,MAAA,EAAO,CAAE,WAAA,EAAY;AAAA,EAC/B,YAAYA,KAAA,CAAE,MAAA,EAAO,CAA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acote pode ser carregado mais de uma vez no mesmo processo (duas cópias em\n * `node_modules`, ESM e CJS lado a lado, monorepo com versões distintas) — e aí `const x = new Map()`\n * a nível de módulo produz DUAS caches que não se enxergam. `Symbol.for` usa o registro global de\n * símbolos, que é do realm e não do módulo, então todas as cópias convergem para a mesma instância.\n *\n * Estava copiado verbatim em `providers/discovery.ts` e `providers/catalog-loader.ts`. Isso é\n * duplicação de CONHECIMENTO, não coincidência de forma: as duas cópias precisam concordar sobre o\n * mecanismo, e uma corrigida sem a outra produz exatamente o bug que a função existe para evitar.\n */\nexport function globalSingleton<T>(key: string, create: () => T): T {\n const g = globalThis as unknown as Record<symbol, T>;\n const sym = Symbol.for(key);\n if (g[sym] === undefined) g[sym] = create();\n return g[sym];\n}\n","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 { globalSingleton } from \"../global-singleton.js\";\nimport type { ProviderProfile } from \"./types.js\";\n\n/**\n * M44 B1 fix — the registry state lives on `globalThis` keyed by `Symbol.for`, so EVERY bundle copy of this\n * module (tsup bundles each entry separately with `splitting: false` — `dist/index.js` and `dist/models.js`\n * each embed their own copy) shares the SAME maps. Without this, `@theokit/sdk/models`'s\n * `refreshModelCatalog` saw an eternally-empty registry and its patches were invisible to the core bundle's\n * capability/pricing lookups (state duplication made load-bearing by M44).\n */\nconst REGISTRY = globalSingleton(\n \"theokit-sdk.providers.registry\",\n () => new Map<string, ProviderProfile>(),\n);\nconst ALIASES = globalSingleton(\"theokit-sdk.providers.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 { globalSingleton } from \"../global-singleton.js\";\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 */\n// M44 B1 fix — index state on globalThis (Symbol.for) so every bundle copy shares the SAME maps (see the\n// identical pattern + rationale in registry.ts).\nconst modelInfoIndex = globalSingleton(\n \"theokit-sdk.providers.model-info-index\",\n () => new Map<string, CatalogModel>(),\n);\n/** M44 M5 fix — keys patched by the live models-dev source (honest pricing provenance). */\nconst patchedModelKeys = globalSingleton(\n \"theokit-sdk.providers.model-info-patched\",\n () => new Set<string>(),\n);\nconst indexState = globalSingleton(\"theokit-sdk.providers.model-info-loaded\", () => ({\n loaded: false,\n}));\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/** Was this key patched by the LIVE models-dev source (vs the vendored catalog)? @internal */\nexport function isPatchedModelKey(key: string): boolean {\n return patchedModelKeys.has(key);\n}\n\n/**\n * Patch the index with fresher per-model data (the models-dev source). M44 H2 fix — a per-FIELD shallow\n * MERGE, not a wholesale replace: models.dev can never supply the theokit extension fields\n * (`cache_control`, `structured_output` overlays), so a replace would wipe them and silently flip\n * capability answers. Incoming fields win; existing fields survive when the patch omits them.\n * @internal\n */\nexport function patchModelInfo(key: string, model: CatalogModel): void {\n ensureModelIndexLoaded();\n const existing = modelInfoIndex.get(key);\n modelInfoIndex.set(key, existing === undefined ? model : { ...existing, ...model });\n patchedModelKeys.add(key);\n}\n\n/** All indexed `provider/model` keys (for maintenance/tests). @internal */\nexport function listModelInfoKeys(): string[] {\n ensureModelIndexLoaded();\n return [...modelInfoIndex.keys()];\n}\n\nfunction ensureModelIndexLoaded(): void {\n if (indexState.loaded) return;\n indexState.loaded = true;\n // M44 L9 fix — never throw from a capability/pricing lookup: a missing/corrupt vendored catalog degrades\n // to conservative defaults with a WARN (the deleted EXACT map could never throw; keep that property).\n try {\n const catalog = loadProviderCatalog();\n for (const entry of Object.values(catalog)) {\n indexEntryModels(entry);\n }\n } catch (err) {\n process.stderr.write(\n `[theokit-sdk] WARN: provider catalog unavailable (${(err as Error).message}) — per-model data disabled\\n`,\n );\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 */\n// Divida PRE-EXISTENTE, exposta quando o M75 consertou a config Biome que abortava antes\n// de varrer estes arquivos (raiz aninhada em refactor/). Nao e codigo novo e nao foi tocado\n// pelo M75; refatorar internals do SDK sem revisao trocaria um problema visivel por um diff\n// arriscado. Rastreado em usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ver a razao logo acima\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 patchedModelKeys.clear();\n indexState.loaded = 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\n// Divida PRE-EXISTENTE, exposta quando o M75 consertou a config Biome que abortava antes\n// de varrer estes arquivos (raiz aninhada em refactor/). Nao e codigo novo e nao foi tocado\n// pelo M75; refatorar internals do SDK sem revisao trocaria um problema visivel por um diff\n// arriscado. Rastreado em usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ver a razao logo acima\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 // M45 review L4 — alias keys too (e.g. entry `google-gemini` alias `google`), consistent with the\n // model-info index's alias-keyed convention.\n for (const alias of entry.aliases ?? []) {\n if (_capabilitiesCache[alias] === undefined) _capabilitiesCache[alias] = entry.capabilities;\n }\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 type { ProviderProfile } from \"../types.js\";\n\nexport const ANTHROPIC: ProviderProfile = {\n name: \"anthropic\",\n apiMode: \"anthropic_messages\",\n envVars: [\"ANTHROPIC_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.anthropic.com\",\n modelsUrl: \"https://api.anthropic.com/v1/models\",\n hostname: \"api.anthropic.com\",\n fallbackModels: [\"claude-opus-4-7\", \"claude-sonnet-4-6\", \"claude-haiku-4-5-20251001\"],\n // M45 — the Anthropic beta-features header (interleaved thinking + fine-grained tool streaming). An\n // Anthropic API constant, adapted verbatim from OpenCode's anthropic plugin (MIT © 2025 opencode). The\n // SANCTIONED behavior delta of M45 (ADR D4) — consumed by the anthropic transport's extraHeaders wiring.\n extraHeaders: {\n \"anthropic-beta\": \"interleaved-thinking-2025-05-14,fine-grained-tool-streaming-2025-05-14\",\n },\n};\n","/**\n * AWS Bedrock profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Bearer-only auth via `AWS_BEARER_TOKEN_BEDROCK` env (GA Sep 2025).\n * Optional `@aws/bedrock-token-generator` peer dep auto-refreshes short-term\n * tokens (D287). Transport via native `fetch`; no `@aws-sdk/*` dependency.\n *\n * Model IDs follow the `bedrock/{aws-id}` convention so the router can\n * infer the provider via prefix routing (D186). The client strips the\n * `bedrock/` prefix before building the URL.\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const BEDROCK: ProviderProfile = {\n name: \"bedrock\",\n apiMode: \"bedrock_anthropic\",\n envVars: [\"AWS_BEARER_TOKEN_BEDROCK\"],\n authType: \"aws_bearer\",\n baseUrl: \"https://bedrock-runtime.us-east-1.amazonaws.com\",\n modelsUrl: undefined,\n hostname: \"bedrock-runtime.amazonaws.com\",\n fallbackModels: [\n \"bedrock/us.anthropic.claude-sonnet-4-5-v1:0\",\n \"bedrock/us.anthropic.claude-opus-4-7-v1:0\",\n \"bedrock/global.anthropic.claude-haiku-4-5-v1:0\",\n ],\n};\n\n/** Strip `\"bedrock/\"` prefix so the raw AWS model id is used in the URL. */\nexport function stripBedrockPrefix(modelId: string): string {\n return modelId.replace(/^bedrock\\//, \"\");\n}\n\n/**\n * Infer AWS region from a Bedrock model id prefix (D290).\n *\n * `global.*` routes via `us-east-1` (AWS default entrypoint for global\n * inference profiles).\n */\nexport function inferRegionFromModelId(modelId: string): string | undefined {\n const id = stripBedrockPrefix(modelId);\n if (id.startsWith(\"global.\")) return \"us-east-1\";\n if (id.startsWith(\"us.\")) return process.env.AWS_REGION ?? \"us-east-1\";\n if (id.startsWith(\"eu.\")) return process.env.AWS_REGION ?? \"eu-west-1\";\n if (id.startsWith(\"apac.\")) return process.env.AWS_REGION ?? \"ap-southeast-1\";\n if (id.startsWith(\"jp.\")) return \"ap-northeast-1\";\n return undefined;\n}\n\n/** Resolve baseUrl from model id; falls back to `AWS_REGION` env or `us-east-1`. */\nexport function resolveBedrockBaseUrl(modelId: string): string {\n const region = inferRegionFromModelId(modelId) ?? process.env.AWS_REGION ?? \"us-east-1\";\n return `https://bedrock-runtime.${region}.amazonaws.com`;\n}\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * M45 — the data-only base for OpenAI-compatible chat_completions providers. OpenCode's\n * `openai-compatible-profile` pattern (MIT © 2025 opencode — `packages/llm/src/providers/`) flattened to\n * theokit's data model: leaves declare name/baseUrl/envVars (+ overrides) in ~10 lines; the router's\n * URL-join rule (version-segment detection + `chatCompletionsPath` escape) derives the endpoint.\n *\n * @internal\n */\nexport function openAiCompatibleProfile(\n p: { name: string; baseUrl: string; envVars: readonly string[] } & Partial<ProviderProfile>,\n): ProviderProfile {\n return {\n apiMode: \"chat_completions\",\n authType: \"api_key\",\n fallbackModels: [],\n ...p,\n };\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cerebras. Integration header adapted from OpenCode's `cerebras.ts` (MIT — value changed to\n * `theokit`, never `opencode`: the header attributes TRAFFIC). Models per models.dev (2026-07 snapshot).\n */\nexport const CEREBRAS = openAiCompatibleProfile({\n name: \"cerebras\",\n baseUrl: \"https://api.cerebras.ai/v1\",\n envVars: [\"CEREBRAS_API_KEY\"],\n fallbackModels: [\"gpt-oss-120b\", \"zai-glm-4.7\"],\n extraHeaders: { \"X-Cerebras-3rd-Party-Integration\": \"theokit\" },\n hostname: \"api.cerebras.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Cohere via its OpenAI-compatibility surface (`api.cohere.ai/compatibility/v1` — the native v2 API\n * is NOT chat_completions; the discovery flagged the old catalog baseUrl as doubly wrong). Models per\n * models.dev `cohere` (2026-07 snapshot). SOURCE NOTE (review L2): the compatibility endpoint + `CO_API_KEY`\n * come from Cohere's own docs/python-SDK convention (not vendored in this repo's references) — verify with a\n * live smoke when a key is available.\n */\nexport const COHERE = openAiCompatibleProfile({\n name: \"cohere\",\n baseUrl: \"https://api.cohere.ai/compatibility/v1\",\n envVars: [\"COHERE_API_KEY\", \"CO_API_KEY\"],\n fallbackModels: [\"command-a-03-2025\"],\n hostname: \"api.cohere.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — DeepInfra. OpenAI-compat surface under /v1/openai (models.dev `deepinfra`, OpenCode profile map). */\nexport const DEEPINFRA = openAiCompatibleProfile({\n name: \"deepinfra\",\n baseUrl: \"https://api.deepinfra.com/v1/openai\",\n envVars: [\"DEEPINFRA_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen3-32B\"],\n hostname: \"api.deepinfra.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Gemini via OpenRouter passthrough. Direct Gemini API uses a different\n * dialect (`generateContent`); SDK currently routes through OpenRouter's\n * OpenAI-compatible endpoint so the chat_completions transport works.\n *\n * A future plugin `@theokit-provider-gemini-direct` can override this with\n * `apiMode: \"gemini_generate_content\"` once that transport ships.\n */\nexport const GEMINI: ProviderProfile = {\n name: \"gemini\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENROUTER_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n hostname: \"openrouter.ai\",\n fallbackModels: [\"google/gemini-2.0-flash-001\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Google Gemini via the DIRECT OpenAI-compat endpoint (a Google API key, not OpenRouter). Distinct\n * from the `gemini` builtin (an OpenRouter passthrough) by ADR D3 — two routes, two names. Endpoint + env\n * vars per Google's OpenAI-compatibility docs (mirrored by models.dev `google` + the M44 catalog entry).\n */\nexport const GOOGLE = openAiCompatibleProfile({\n name: \"google\",\n baseUrl: \"https://generativelanguage.googleapis.com/v1beta/openai\",\n envVars: [\"GOOGLE_API_KEY\", \"GEMINI_API_KEY\", \"GOOGLE_GENERATIVE_AI_API_KEY\"],\n fallbackModels: [\"gemini-2.5-pro\", \"gemini-2.5-flash\"],\n hostname: \"generativelanguage.googleapis.com\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Groq. Values per models.dev `groq` (2026-07 snapshot); OpenAI-compat surface under /openai/v1. */\nexport const GROQ = openAiCompatibleProfile({\n name: \"groq\",\n baseUrl: \"https://api.groq.com/openai/v1\",\n envVars: [\"GROQ_API_KEY\"],\n fallbackModels: [\"llama-3.3-70b-versatile\", \"llama-3.1-8b-instant\"],\n hostname: \"api.groq.com\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * llama.cpp server provider profile (T7.2, ADR D189).\n *\n * llama.cpp ships a HTTP server binary (`./server` since b1500+) that\n * implements the OpenAI-compatible `/v1/chat/completions` endpoint on\n * `http://localhost:8080` by default. Inherits `authType: \"none\"` from\n * D182 — no API key required for local use.\n *\n * llama.cpp idiosyncrasies:\n * - Server loads a single GGUF model at startup via `--model` CLI\n * flag. The `model` field in the chat-completions request is\n * cosmetic — any string works; the response comes from the loaded\n * model regardless. This is documented in\n * `.claude/knowledge-base/reviews/edge-case/ollama-integration-edge-cases-2026-05-21.md`\n * as EC-O.\n * - Tool calling support depends entirely on the underlying model.\n *\n * Override the default URL with `LLAMACPP_HOST`.\n *\n * @internal\n */\nexport const LLAMACPP: ProviderProfile = {\n name: \"llamacpp\",\n aliases: [\"llama-cpp\", \"llama.cpp\"],\n apiMode: \"chat_completions\",\n envVars: [\"LLAMACPP_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:8080\",\n modelsUrl: \"http://localhost:8080/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * LM Studio provider profile (T7.1, ADR D188).\n *\n * LM Studio exposes an OpenAI-compatible `/v1/chat/completions` endpoint\n * on `http://localhost:1234` by default (configurable via the LM Studio\n * UI under \"Local Server\"). Inherits the `authType: \"none\"` primitive\n * from D182 — no API key required for local use.\n *\n * LM Studio idiosyncrasies:\n * - Loads ONE model at a time via the desktop UI. The `model` field in\n * the chat-completions request is informational only — LM Studio\n * serves whatever model is currently loaded.\n * - `/v1/models` returns a single entry pointing to the loaded model.\n * - Tool calling depends on the underlying model.\n *\n * Override the default URL with `LMSTUDIO_HOST` (mirrors `OLLAMA_HOST`).\n *\n * @internal\n */\nexport const LMSTUDIO: ProviderProfile = {\n name: \"lmstudio\",\n aliases: [\"lm-studio\", \"lm_studio\"],\n apiMode: \"chat_completions\",\n envVars: [\"LMSTUDIO_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:1234\",\n modelsUrl: \"http://localhost:1234/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"loaded-model\"],\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Mistral (La Plateforme). Values per models.dev `mistral` (2026-07 snapshot). */\nexport const MISTRAL = openAiCompatibleProfile({\n name: \"mistral\",\n baseUrl: \"https://api.mistral.ai/v1\",\n envVars: [\"MISTRAL_API_KEY\"],\n fallbackModels: [\"mistral-large-latest\", \"codestral-latest\"],\n hostname: \"api.mistral.ai\",\n});\n","import type { ProviderProfile } from \"../types.js\";\n\n/**\n * Ollama — local-first LLM runtime (ADR D182).\n *\n * Ships as a builtin so `Agent.create({ model: \"ollama/llama3.2\" })` works\n * with zero configuration when `ollama serve` is running on the default\n * port. `authType: \"none\"` signals the router to skip env-key resolution\n * and use a placeholder credential (Ollama ignores Authorization headers\n * on local installs).\n *\n * Overrides:\n * - `OLLAMA_HOST` — replaces the default `http://localhost:11434` baseUrl\n * (advanced users running Ollama on a remote machine).\n * - `OLLAMA_API_KEY` — replaces the placeholder when Ollama is behind a\n * reverse-proxy with auth or when using Ollama Cloud (paid tier).\n */\nexport const OLLAMA: ProviderProfile = {\n name: \"ollama\",\n apiMode: \"chat_completions\",\n envVars: [\"OLLAMA_API_KEY\"],\n authType: \"none\",\n baseUrl: \"http://localhost:11434\",\n modelsUrl: \"http://localhost:11434/v1/models\",\n hostname: \"localhost\",\n fallbackModels: [\"llama3.2\", \"qwen2.5\", \"mistral\"],\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENAI: ProviderProfile = {\n name: \"openai\",\n apiMode: \"chat_completions\",\n envVars: [\"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://api.openai.com\",\n modelsUrl: \"https://api.openai.com/v1/models\",\n hostname: \"api.openai.com\",\n fallbackModels: [\"gpt-4o\", \"gpt-4o-mini\"],\n};\n","import { randomBytes } from \"node:crypto\";\nimport {\n chmodSync,\n closeSync,\n fsyncSync,\n mkdirSync,\n openSync,\n readFileSync,\n renameSync,\n statSync,\n unlinkSync,\n writeFileSync,\n} from \"node:fs\";\nimport { join } from \"node:path\";\n\nimport { z } from \"zod\";\n\nimport { AuthenticationError } from \"../../errors.js\";\n\n/**\n * M42 — the SDK credential store. Promoted DOWN from agent-builder's hardened `agents/lib/credentials.ts`\n * (M37), generalized from a closed `openrouter|anthropic|openai` union to an open `provider: string` and\n * driven by a caller-supplied {@link CredentialStoreConfig} (no hardcoded `.agent-builder`/`auth.json` /\n * `AGENT_BUILDER_HOME`). The security-critical file mechanics are ported VERBATIM (ADR D3 of the M42 plan):\n * atomic O_EXCL + rename + fsync write, 0700/0600 mode gates, `env` is always a PARAMETER (never an ambient\n * `process.env` read). Contract SHAPE adapted from OpenCode's provider `auth.loader` (MIT © 2025 opencode).\n *\n * The env-precedence + key-prefix-inference + declared-provider rungs of the agent-builder resolver are\n * APP POLICY and deliberately stay UP in the consumer; this module owns only the on-disk store + the\n * `api|oauth` discriminated union. See {@link resolveCredential} (SDK) for the store-read + refresh path.\n *\n * @internal\n */\nimport type {\n CredentialStoreConfig,\n StoredCredential,\n StoredOAuthCredential,\n} from \"./auth-types.js\";\n\n/** The store directory, honoring an optional `homeEnvVar` override. */\nexport function credentialHome(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const override = config.homeEnvVar !== undefined ? env[config.homeEnvVar]?.trim() : undefined;\n return override !== undefined && override.length > 0\n ? override\n : join(config.home, config.dirName);\n}\n\n/** The credential file path inside the (possibly overridden) store directory. */\nexport function authFilePath(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return join(credentialHome(config, env), config.fileName);\n}\n\n/**\n * A credential problem the caller can act on. Never carries the key value.\n *\n * M78 — this used to extend bare `Error`, which quietly disabled classification for the entire auth\n * path: `isTransientError` is `err instanceof TheokitAgentError && err.isRetryable === true`\n * (`errors.ts:443`), so a credential failure could never be judged transient OR permanent. The\n * predicate was not \"forgotten\" downstream — it was unusable there by construction.\n *\n * Extending `AuthenticationError` is ADDITIVE: the class still exists, still reports\n * `name: \"CredentialError\"`, and every existing `instanceof CredentialError` stays true. It only\n * gains ancestors. `AuthenticationError` pins `isRetryable: false`, so gaining the ability to be\n * classified does NOT turn a revoked credential into a retry loop.\n *\n * The single reference does the same thing with one root type: Codex routes every domain failure\n * through `CodexErr` with `is_retryable()` as a method (`protocol/src/error.rs:176`), rather than\n * parallel classes extending the language's `Error`.\n */\nexport class CredentialError extends AuthenticationError {\n // Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`\n // (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the\n // suite was green with the broken assignment because the transpiler strips the type.\n override readonly name: string = \"CredentialError\";\n}\n\n/**\n * The on-disk store — a discriminated union on `type` (OpenCode `Info` shape). A legacy file with NO\n * `type` (or `type: 'api'`) is the API-key variant — read unchanged, no migration. The `oauth` variant\n * carries the token pair + expiry.\n */\nconst apiFileSchema = z\n .object({\n type: z.literal(\"api\").optional(),\n provider: z.string().min(1).optional(),\n api_key: z.string(),\n })\n .strict();\n\nconst oauthFileSchema = z\n .object({\n type: z.literal(\"oauth\"),\n provider: z.string().min(1),\n access: z.string().min(1),\n refresh: z.string().min(1),\n expires: z.number(),\n account_id: z.string().optional(),\n })\n .strict();\n\n// oauth first (it requires `type: 'oauth'`); a legacy `{provider?, api_key}` falls through to api.\nconst fileSchema = z.union([oauthFileSchema, apiFileSchema]);\n\n/**\n * Read the credential file. Absent ⇒ `undefined` (the normal case). Present-but-wrong is a typed error\n * naming the file: a malformed credential store must not surface as a raw parse crash. Enforces the\n * 0700 dir / 0600 file mode gates (ported verbatim — a writable dir lets an attacker swap the file for a\n * symlink to their own account).\n */\n/**\n * The 0700-dir / 0600-file mode gates (ported verbatim). The DIRECTORY matters as much as the file:\n * `mkdirSync(mode)` applies only at creation, so a pre-existing store dir keeps whatever mode it had, and a\n * writable dir lets an attacker replace the credential file with a symlink to their own 0600 file — the\n * agent then runs on THEIR account.\n */\nfunction assertSecureModes(dirPath: string, path: string): void {\n const dirMode = statSync(dirPath).mode & 0o777;\n if ((dirMode & 0o022) !== 0) {\n throw new CredentialError(\n `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file ` +\n `inside it can be replaced. Fix it with: chmod 700 ${dirPath}`,\n );\n }\n const mode = statSync(path).mode & 0o777;\n if ((mode & 0o077) !== 0) {\n throw new CredentialError(\n `${path} is readable by other users (mode ${mode.toString(8)}). ` +\n `A credential file must not be. Fix it with: chmod 600 ${path}`,\n );\n }\n}\n\n/**\n * A `z.union` reports a generic \"Invalid input\" at the root, hiding WHAT is wrong. Pick the sub-schema the\n * file was CLEARLY aiming at (by its `type` discriminant) and surface that schema's specific issue.\n */\nfunction describeUnionError(parsed: unknown, err: unknown, path: string): CredentialError {\n const looksOAuth =\n typeof parsed === \"object\" &&\n parsed !== null &&\n (parsed as { type?: unknown }).type === \"oauth\";\n const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);\n let issue: z.ZodIssue | undefined;\n if (!specific.success) {\n issue = specific.error.issues[0];\n } else if (err instanceof z.ZodError) {\n issue = err.issues[0];\n }\n return new CredentialError(\n `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(\".\") || \"root\"}]`,\n );\n}\n\n/** Parse the raw file into the store union, surfacing the SPECIFIC sub-schema issue (not a generic union error). */\nfunction parseStoredFile(raw: string, path: string): StoredCredential {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n // The parser's message embeds a snippet of the INPUT — up to the raw key when a user pastes the bare\n // key instead of JSON. The position is not actionable anyway, so the expected shape is more useful.\n throw new CredentialError(\n `${path} is not valid JSON. Expected: {\"provider\": \"<name>\", \"api_key\": \"...\"}`,\n );\n }\n try {\n return fileSchema.parse(parsed);\n } catch (err) {\n throw describeUnionError(parsed, err, path);\n }\n}\n\nexport function readAuthFile(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredCredential | undefined {\n const path = authFilePath(config, env);\n\n let raw: string;\n try {\n raw = readFileSync(path, \"utf8\");\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === \"ENOENT\") return undefined;\n throw new CredentialError(`cannot read ${path}: ${(err as Error).message}`);\n }\n\n assertSecureModes(credentialHome(config, env), path);\n return parseStoredFile(raw, path);\n}\n\n/**\n * Read the stored OAuth credential (with its refresh token), or `undefined` when the store is absent or\n * holds an api credential. The oauth engine needs the refresh token, which the resolved bearer does not\n * carry. Enforces the same 0600/0700 gates as every other read.\n */\nexport function readStoredOAuth(\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): StoredOAuthCredential | undefined {\n const stored = readAuthFile(config, env);\n return stored !== undefined && stored.type === \"oauth\" ? stored : undefined;\n}\n\n/** Narrows a writable credential to the oauth variant. */\nfunction isOAuthWrite(\n c: { provider: string; apiKey: string } | StoredOAuthCredential,\n): c is StoredOAuthCredential {\n return \"type\" in c && c.type === \"oauth\";\n}\n\n/**\n * Persist a credential atomically at mode `0600`. Ported VERBATIM (ADR D3): write to a random-named temp\n * file in the same directory with `wx` (O_EXCL), fsync, close, chmod, then `rename` (atomic on POSIX) —\n * so a crash mid-write leaves whatever was there untouched, and a pre-planted symlink cannot capture the\n * key. The api variant persists the unchanged `{provider, api_key}` (back-compat, no `type` key); the\n * oauth variant persists `{type:'oauth', provider, access, refresh, expires, account_id?}`.\n */\n/** Build the on-disk JSON payload for the credential variant, validating non-empty tokens. */\nfunction buildStorePayload(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n): Record<string, unknown> {\n if (isOAuthWrite(cred)) {\n if (cred.access.length === 0 || cred.refresh.length === 0) {\n throw new CredentialError(\n \"refusing to write an oauth credential with an empty access/refresh token\",\n );\n }\n return {\n type: \"oauth\",\n provider: cred.provider,\n access: cred.access,\n refresh: cred.refresh,\n expires: cred.expires,\n ...(cred.account_id !== undefined ? { account_id: cred.account_id } : {}),\n };\n }\n if (typeof cred.apiKey !== \"string\" || cred.apiKey.length === 0) {\n throw new CredentialError(\"refusing to write an empty API key\");\n }\n return { provider: cred.provider, api_key: cred.apiKey };\n}\n\nexport function writeCredential(\n cred: { provider: string; apiKey: string } | StoredOAuthCredential,\n config: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n const payload = buildStorePayload(cred);\n\n const dir = credentialHome(config, env);\n mkdirSync(dir, { recursive: true, mode: 0o700 });\n chmodSync(dir, 0o700); // unconditional: mkdirSync's mode applies only at creation\n\n const path = authFilePath(config, env);\n // RANDOM name + `wx` (O_EXCL): a predictable temp name with a plain write follows a pre-planted SYMLINK,\n // landing the key in an attacker's file while reporting success. O_EXCL refuses any pre-existing file or\n // link; the random suffix also removes the pid collision two containers sharing a bind-mounted home make.\n const tmp = `${path}.tmp-${randomBytes(8).toString(\"hex\")}`;\n try {\n const fd = openSync(tmp, \"wx\", 0o600);\n try {\n writeFileSync(fd, `${JSON.stringify(payload, null, 2)}\\n`);\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n chmodSync(tmp, 0o600); // explicit: the mode argument is subject to umask\n renameSync(tmp, path);\n } catch (err) {\n try {\n unlinkSync(tmp);\n } catch {\n // the temp file may not exist; its absence is not a failure of the write\n }\n throw new CredentialError(`cannot write ${path}: ${(err as Error).message}`);\n }\n return path;\n}\n","/**\n * @theokit/sdk/server/auth — typed error classes\n *\n * Plan T1.2 + v1.1 EC-1 (AuthCancelledError for OAuth provider error response RFC 6749 §4.1.2.1).\n */\n\n/**\n * Thrown at `defineAuth()` time when configuration is invalid\n * (e.g., duplicate provider name, invalid email shape per EC-V1-12).\n */\nexport class AuthConfigError extends Error {\n override readonly name = \"AuthConfigError\";\n readonly code: string;\n\n constructor(code: string, message: string) {\n super(`[${code}] ${message}`);\n this.code = code;\n }\n}\n\n/**\n * Thrown at `startSignIn(providerName, ...)` or `finishSignIn(providerName, ...)`\n * when the named provider is not registered in `providers[]`.\n */\nexport class AuthProviderNotFoundError extends Error {\n override readonly name = \"AuthProviderNotFoundError\";\n readonly providerName: string;\n\n constructor(providerName: string) {\n super(\n `Auth provider not found: '${providerName}'. Register it in defineAuth({ providers: [...] }).`,\n );\n this.providerName = providerName;\n }\n}\n\n/**\n * Thrown during OAuth callback handling for state mismatches, expired\n * transactions, missing query params, or provider 4xx/5xx errors.\n *\n * Typed `code` field lets consumers branch on cause:\n * - 'oauth_transaction_expired' — cookie tx > 10min old (per ADR D5)\n * - 'oauth_state_mismatch' — query state ≠ cookie state (CSRF defense per RFC 6749 §10.12)\n * - 'oauth_provider_error' — non-access_denied error in callback URL\n * - 'oauth_token_exchange_failed' — provider rejected code-for-tokens swap\n * - 'oauth_userinfo_failed' — userinfo endpoint returned error\n * - 'oauth_missing_code_or_state' — required query params absent\n */\nexport class AuthCallbackError extends Error {\n override readonly name: string = \"AuthCallbackError\";\n readonly code: string;\n\n constructor(code: string, message?: string) {\n super(message ?? `OAuth callback error: ${code}`);\n this.code = code;\n }\n}\n\n/**\n * Per v1.1 EC-1 MUST FIX — typed subclass of AuthCallbackError for the\n * specific case where user declined consent at provider screen.\n *\n * OAuth 2.0 RFC 6749 §4.1.2.1: provider redirects with `?error=access_denied`.\n * Apps can catch this distinctly from network/server errors to render\n * \"Login cancelled — try again\" UX instead of opaque \"callback failed\".\n */\nexport class AuthCancelledError extends AuthCallbackError {\n override readonly name: string = \"AuthCancelledError\";\n readonly errorDescription?: string;\n\n constructor(errorDescription?: string) {\n super(\"user_declined_consent\", errorDescription ?? \"User declined consent at provider\");\n this.errorDescription = errorDescription;\n }\n}\n","/**\n * M42 — the SDK OAuth engine. Promoted DOWN from agent-builder's hardened `agents/lib/oauth.ts` +\n * `oauth-device.ts` (M37), generalized to `provider: string` + a caller-supplied {@link CredentialStoreConfig}\n * (no hardcoded client IDs — the caller declares its provider's endpoints). Ported VERBATIM (ADR D3): the\n * refresh coalescing lock, the no-token-in-error discipline, and the RFC 8628 device grant.\n *\n * Reuses the SDK's typed error taxonomy (`AuthCallbackError` from `server/auth`) for exchange/refresh\n * failures. All network I/O + clock + sleep are INJECTED so the flow is deterministic.\n *\n * ─── ADAPTED FROM OpenCode (MIT License, Copyright (c) 2025 opencode — https://github.com/sst/opencode) ───\n * - the device-grant poll loop (device_code → authorization_pending / slow_down) is adapted from\n * `packages/opencode/src/plugin/github-copilot/copilot.ts`;\n * - the JWT-claim / account-id extraction + the OpenAI two-step headless flow are adapted from\n * `packages/opencode/src/plugin/openai/codex.ts`.\n * The MIT license permits this reuse with attribution; this notice + the NOTICE file are that attribution.\n *\n * @internal\n */\nimport { AuthCallbackError } from \"../../server/auth/errors.js\";\n\nimport type {\n CredentialStoreConfig,\n HttpDeps,\n OAuthProviderConfig,\n OAuthTokens,\n ResolvedCredential,\n} from \"./auth-types.js\";\nimport { authFilePath, readStoredOAuth, writeCredential } from \"./credential-store.js\";\n\n/** Refresh a token this many ms BEFORE it actually expires (avoid a last-second, mid-request expiry). */\nconst REFRESH_SKEW_MS = 60_000;\n\n/** Parse an OAuth token endpoint response into our token triple. Throws a typed error on a bad shape. */\nfunction parseTokenResponse(body: unknown, now: number): OAuthTokens {\n const b = body as {\n access_token?: unknown;\n refresh_token?: unknown;\n expires_in?: unknown;\n account_id?: unknown;\n };\n if (typeof b.access_token !== \"string\" || b.access_token.length === 0) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"token response had no access_token\",\n );\n }\n if (typeof b.refresh_token !== \"string\" || b.refresh_token.length === 0) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"token response had no refresh_token\",\n );\n }\n const expiresIn = typeof b.expires_in === \"number\" ? b.expires_in : 3600;\n return {\n access: b.access_token,\n refresh: b.refresh_token,\n expires: now + expiresIn * 1000,\n ...(typeof b.account_id === \"string\" ? { accountId: b.account_id } : {}),\n };\n}\n\n/** POST a form-encoded grant to the token endpoint; return the parsed JSON or throw a typed error. */\nasync function postGrant(\n config: OAuthProviderConfig,\n form: Record<string, string>,\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n let res: Response;\n try {\n res = await deps.fetch(config.tokenEndpoint, {\n method: \"POST\",\n headers: { \"content-type\": \"application/x-www-form-urlencoded\", accept: \"application/json\" },\n body: new URLSearchParams(form).toString(),\n });\n } catch (err) {\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n `token endpoint request failed: ${(err as Error).message}`,\n );\n }\n if (!res.ok) {\n // The body may carry an OAuth `error` code, but never echo it verbatim — it can contain a token in\n // some providers' error payloads. Report the status only.\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n `token endpoint returned HTTP ${res.status}`,\n );\n }\n let json: unknown;\n try {\n json = await res.json();\n } catch {\n // Do NOT echo the parser message — on a 200 non-JSON body it embeds a snippet of the response, which\n // in a token context can contain access/refresh material.\n throw new AuthCallbackError(\"oauth_token_exchange_failed\", \"token response was not valid JSON\");\n }\n return parseTokenResponse(json, deps.now());\n}\n\n/** Exchange an authorization `code` (+ PKCE verifier) for the token pair. */\nexport function exchangeCode(\n config: OAuthProviderConfig,\n input: { code: string; verifier: string },\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n return postGrant(\n config,\n {\n grant_type: \"authorization_code\",\n code: input.code,\n redirect_uri: config.redirectUri,\n client_id: config.clientId,\n code_verifier: input.verifier,\n },\n deps,\n );\n}\n\n/** Swap a refresh token for a fresh access (and possibly rotated refresh) token. */\nexport function refreshOAuthTokens(\n config: OAuthProviderConfig,\n refresh: string,\n deps: HttpDeps,\n): Promise<OAuthTokens> {\n return postGrant(\n config,\n { grant_type: \"refresh_token\", refresh_token: refresh, client_id: config.clientId },\n deps,\n );\n}\n\n/** Persist a token triple to the store's oauth variant through the hardened 0600 writer. */\nexport function persistOAuthTokens(\n provider: string,\n tokens: OAuthTokens,\n store: CredentialStoreConfig,\n env: Record<string, string | undefined> = {},\n): string {\n return writeCredential(\n {\n type: \"oauth\",\n provider,\n access: tokens.access,\n refresh: tokens.refresh,\n expires: tokens.expires,\n ...(tokens.accountId !== undefined ? { account_id: tokens.accountId } : {}),\n },\n store,\n env,\n );\n}\n\n/**\n * In-flight refreshes, keyed by the auth-file path. Refresh tokens ROTATE (single-use) on many providers,\n * so two concurrent turns must NOT both POST the same refresh token — the second would present an\n * already-consumed token and fail. This coalesces concurrent refreshes of the same store onto one promise.\n * Process-local — the single-credential store is per-user; a cross-process lock would be over-engineering.\n */\nconst inFlightRefresh = new Map<string, Promise<OAuthTokens>>();\n\n/**\n * Return a credential guaranteed fresh enough to use. An `api` credential passes through untouched. An\n * `oauth` credential still valid (beyond the skew window) passes through; an expired one is refreshed,\n * re-persisted 0600, and returned with the new access token. Concurrent refreshes of the same store are\n * coalesced (single-use refresh tokens); the rejected promise is evicted so a failure is not cached-poison.\n */\nexport async function ensureFreshCredential(\n resolved: ResolvedCredential,\n opts: {\n config: OAuthProviderConfig;\n store: CredentialStoreConfig;\n env?: Record<string, string | undefined>;\n },\n deps: HttpDeps,\n): Promise<ResolvedCredential> {\n if (resolved.kind !== \"oauth\") return resolved;\n\n const now = deps.now();\n if (resolved.expiresAt !== undefined && resolved.expiresAt > now + REFRESH_SKEW_MS) {\n return resolved; // still valid — no network, no rewrite\n }\n\n const env = opts.env ?? {};\n const path = authFilePath(opts.store, env);\n let refresh = inFlightRefresh.get(path);\n if (refresh === undefined) {\n refresh = (async (): Promise<OAuthTokens> => {\n const stored = readStoredOAuth(opts.store, env);\n if (stored === undefined) {\n // The resolved credential said oauth but the store no longer holds it — do not fabricate; surface it.\n throw new AuthCallbackError(\n \"oauth_token_exchange_failed\",\n \"no stored oauth credential to refresh\",\n );\n }\n const fresh = await refreshOAuthTokens(opts.config, stored.refresh, deps);\n // M43 D4 fix #1 — the OAuth refresh response returns JWTs, not a top-level `account_id`, so\n // `parseTokenResponse` leaves `fresh.accountId` undefined. Prefer a freshly-derived id, else PRESERVE\n // the stored one (account_id is stable) — otherwise the Codex `ChatGPT-Account-Id` header empties after\n // the first refresh and the backend 401/403s.\n const merged: OAuthTokens = {\n ...fresh,\n accountId: fresh.accountId ?? stored.account_id,\n };\n persistOAuthTokens(resolved.provider, merged, opts.store, env);\n return merged;\n })();\n inFlightRefresh.set(path, refresh);\n refresh.finally(() => inFlightRefresh.delete(path)).catch(() => {});\n }\n\n const fresh = await refresh;\n return {\n kind: \"oauth\",\n provider: resolved.provider,\n apiKey: fresh.access,\n source: resolved.source,\n inferred: false,\n expiresAt: fresh.expires,\n };\n}\n","/**\n * M42 — `resolveCredential`: the public composition entrypoint over the credential store + oauth engine.\n * Given a provider name + a {@link CredentialStoreConfig} (and, for oauth, an {@link OAuthProviderConfig}),\n * read the store and return a FRESH `ResolvedCredential` — an api credential passes through by identity; an\n * oauth credential is transparently refreshed when its access token is within the skew window. Returns\n * `undefined` when the store holds no credential for `provider` (the caller then falls back to env / apiKeys).\n *\n * Mirrors agent-builder's `resolveFreshCredential` composition (store read → oauth → ensureFreshCredential),\n * defaulting `fetch`/`now` to globals. This is the async surface an oauth provider's M41 `transform.fetch`\n * calls at stream time, so a mid-turn token expiry refreshes without rebuilding the agent.\n *\n * @internal (re-exported from the package barrel as public)\n */\nimport type {\n CredentialStoreConfig,\n HttpDeps,\n OAuthProviderConfig,\n ResolvedCredential,\n} from \"./auth-types.js\";\nimport { authFilePath, readAuthFile } from \"./credential-store.js\";\nimport { ensureFreshCredential } from \"./oauth-engine.js\";\n\nexport interface ResolveCredentialOptions {\n /** The provider whose stored credential to resolve. */\n provider: string;\n /** Where the credential store lives. */\n store: CredentialStoreConfig;\n /** Env for the store's optional `homeEnvVar` override. Never an ambient read. */\n env?: Record<string, string | undefined>;\n /** Required to refresh an oauth credential; omit for an api-only store. */\n oauth?: OAuthProviderConfig;\n /** Injected HTTP + clock for deterministic tests; default globals. */\n deps?: { fetch?: typeof fetch; now?: () => number };\n}\n\n/**\n * Resolve a fresh credential for `provider` from the store, or `undefined` if the store holds none for it.\n * oauth credentials are auto-refreshed when `opts.oauth` is supplied; api credentials pass through.\n */\n/** Resolve (and, when a config is supplied, refresh) the oauth variant for the requested provider. */\nasync function resolveOAuth(\n stored: { provider: string; access: string; expires: number },\n path: string,\n opts: ResolveCredentialOptions,\n env: Record<string, string | undefined>,\n): Promise<ResolvedCredential | undefined> {\n if (stored.provider !== opts.provider) return undefined;\n const base: ResolvedCredential = {\n kind: \"oauth\",\n provider: opts.provider,\n apiKey: stored.access,\n source: path,\n inferred: false,\n expiresAt: stored.expires,\n };\n if (opts.oauth === undefined) return base; // no config to refresh with — return the stored access token\n const deps: HttpDeps = {\n fetch: opts.deps?.fetch ?? fetch,\n now: opts.deps?.now ?? (() => Date.now()),\n };\n return ensureFreshCredential(base, { config: opts.oauth, store: opts.store, env }, deps);\n}\n\nexport async function resolveCredential(\n opts: ResolveCredentialOptions,\n): Promise<ResolvedCredential | undefined> {\n const env = opts.env ?? {};\n const stored = readAuthFile(opts.store, env);\n if (stored === undefined) return undefined;\n\n const path = authFilePath(opts.store, env);\n\n if (stored.type === \"oauth\") {\n return resolveOAuth(stored, path, opts, env);\n }\n\n // api variant: require the stored `provider` to MATCH the requested provider (M42 review MEDIUM-2).\n // The generic SDK cannot infer a provider from a key prefix (that was agent-builder app policy), so a\n // provider-less or mismatched stored key is NOT attributed to the requested provider — otherwise a legacy\n // `{api_key:\"sk-ant-…\"}` file could be POSTed to the wrong vendor's endpoint (cross-vendor key exposure).\n // Fail-closed, mirroring OpenCode, whose credential resolution never attributes a key across providers.\n if (stored.api_key.length === 0) return undefined;\n if (stored.provider !== opts.provider) return undefined;\n return {\n kind: \"api\",\n provider: opts.provider,\n apiKey: stored.api_key,\n source: path,\n inferred: false,\n };\n}\n","import { homedir } from \"node:os\";\n\nimport type { CredentialStoreConfig, OAuthProviderConfig } from \"../../auth/auth-types.js\";\nimport { readStoredOAuth } from \"../../auth/credential-store.js\";\nimport { resolveCredential } from \"../../auth/resolve-credential.js\";\nimport type { ProviderProfile } from \"../types.js\";\n\n/**\n * M43 — the ChatGPT \"Codex\" backend as a first-class builtin `ProviderProfile`. Migrated from the\n * agent-builder M40 workaround; the SDK now owns the provider, so a consumer only selects\n * `openai-chatgpt/<model>` and logs in — ZERO provider logic in the consumer.\n *\n * Grounded 100% in OpenCode's provider-auth model (see the codex-provider-in-sdk blueprint):\n * - static profile + a `transform.fetch` that resolves the LIVE credential per HTTP request (fresh Bearer +\n * dynamic `ChatGPT-Account-Id`), so a mid-turn expiry refreshes transparently with NO agent rebuild;\n * - the protocol values (endpoint, models, oauth config, `originator` header) are SDK-owned constants,\n * adapted from OpenCode's `openai.ts` (MIT © 2025 opencode — see NOTICE).\n *\n * @internal\n */\n\n/**\n * The SDK-owned ambient credential store the transform reads. Defaults to `~/.theokit/auth.json`. A consumer\n * points it at its existing store dir via the DEDICATED `THEOKIT_AUTH_HOME` env var (NOT `THEOKIT_HOME` — that\n * is the SDK's whole home directory for personality/credential-pool/profiles; overloading it would redirect\n * the entire runtime). The OpenCode \"ambient credential Service\" analog.\n */\nconst DEFAULT_STORE: CredentialStoreConfig = {\n home: homedir(),\n dirName: \".theokit\",\n fileName: \"auth.json\",\n homeEnvVar: \"THEOKIT_AUTH_HOME\",\n};\n\n/**\n * The OpenAI OAuth config the transform resolves + refreshes against. `provider: \"openai\"` is the STORE\n * provider (what `/login` persists), deliberately distinct from this profile's routing name `openai-chatgpt`\n * — the two-namespace split (integration id vs routed provider) mirrors OpenCode. Endpoints/clientId/scopes\n * adapted from OpenCode `openai.ts`.\n */\nconst OPENAI_OAUTH_CONFIG: OAuthProviderConfig = {\n provider: \"openai\",\n authorizeEndpoint: \"https://auth.openai.com/oauth/authorize\",\n tokenEndpoint: \"https://auth.openai.com/oauth/token\",\n clientId: \"app_EMoamEEZ73f0CkXaXp7hrann\",\n scopes: [\"openid\", \"profile\", \"email\", \"offline_access\"],\n redirectUri: \"https://auth.openai.com/deviceauth/callback\",\n};\n\n/**\n * Build the per-request fetch: resolve a FRESH (refreshed) Bearer + the LIVE account-id from the ambient\n * store, and inject them as headers. Re-resolves on EVERY call → mid-turn refresh with no rebuild. A\n * `Headers` object is used so `authorization` is set case-insensitively (never doubled). If no credential is\n * logged in, throw a clear error rather than putting the router's `__oauth_lazy_token__` placeholder on the\n * wire (fail-closed — the OpenCode `MissingCredentialError` semantics).\n */\nfunction codexFetch(): typeof fetch {\n return (async (input: Parameters<typeof fetch>[0], init?: Parameters<typeof fetch>[1]) => {\n const env = process.env as Record<string, string | undefined>;\n const resolved = await resolveCredential({\n provider: \"openai\",\n store: DEFAULT_STORE,\n oauth: OPENAI_OAUTH_CONFIG,\n env,\n });\n if (resolved === undefined) {\n throw new Error(\n 'openai-chatgpt: no ChatGPT credential found — run the OpenAI device login (e.g. \"/login openai\") first.',\n );\n }\n const accountId = readStoredOAuth(DEFAULT_STORE, env)?.account_id;\n const headers = new Headers(init?.headers);\n headers.set(\"authorization\", `Bearer ${resolved.apiKey}`);\n if (accountId !== undefined) headers.set(\"ChatGPT-Account-Id\", accountId);\n return fetch(input, { ...init, headers });\n }) as typeof fetch;\n}\n\nexport const OPENAI_CHATGPT: ProviderProfile = {\n name: \"openai-chatgpt\",\n apiMode: \"responses_api\",\n authType: \"oauth_device_code\",\n baseUrl: \"https://chatgpt.com/backend-api/codex\",\n envVars: [],\n fallbackModels: [\n \"openai-chatgpt/gpt-5.4\",\n \"openai-chatgpt/gpt-5.4-mini\",\n \"openai-chatgpt/gpt-5.5\",\n ],\n extraHeaders: { originator: \"codex_cli_rs\" },\n transform: {\n // Only `fetch` (async) can await the credential refresh; `headers` is sync and cannot.\n fetch: () => codexFetch(),\n },\n};\n","import type { ProviderProfile } from \"../types.js\";\n\nexport const OPENROUTER: ProviderProfile = {\n name: \"openrouter\",\n apiMode: \"chat_completions\",\n aliases: [\"or\"],\n // Ordered fallback (EC-10): OPENROUTER_API_KEY preferred, OPENAI_API_KEY as compat.\n envVars: [\"OPENROUTER_API_KEY\", \"OPENAI_API_KEY\"],\n authType: \"api_key\",\n baseUrl: \"https://openrouter.ai/api\",\n modelsUrl: \"https://openrouter.ai/api/v1/models\",\n hostname: \"openrouter.ai\",\n // M45 — models refreshed (claude-3-haiku retired upstream).\n fallbackModels: [\"openai/gpt-4o-mini\", \"anthropic/claude-haiku-4-5\"],\n // M45 — OpenRouter app-attribution headers (mechanism from OpenCode's openrouter plugin, MIT; VALUES are\n // theokit's own — copying another app's referer would misattribute traffic).\n extraHeaders: { \"HTTP-Referer\": \"https://usetheo.dev\", \"X-Title\": \"theokit\" },\n};\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/**\n * M45 — Perplexity. Its endpoint is UNVERSIONED (`/chat/completions`) — the explicit `chatCompletionsPath`\n * escape expresses it (the sonar-online model family was retired; models per models.dev `perplexity`).\n */\nexport const PERPLEXITY = openAiCompatibleProfile({\n name: \"perplexity\",\n baseUrl: \"https://api.perplexity.ai\",\n chatCompletionsPath: \"/chat/completions\",\n envVars: [\"PERPLEXITY_API_KEY\"],\n fallbackModels: [\"sonar-pro\", \"sonar\"],\n hostname: \"api.perplexity.ai\",\n});\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — Together AI (models.dev id `togetherai` — kept as an alias). Values per the 2026-07 snapshot. */\nexport const TOGETHER = openAiCompatibleProfile({\n name: \"together\",\n aliases: [\"togetherai\"],\n baseUrl: \"https://api.together.xyz/v1\",\n envVars: [\"TOGETHER_API_KEY\"],\n fallbackModels: [\"Qwen/Qwen2.5-7B-Instruct-Turbo\"],\n hostname: \"api.together.xyz\",\n});\n","/**\n * GCP Vertex AI profile (Adoption Roadmap #8; ADRs D286-D302).\n *\n * Required peer dep: `google-auth-library` (D288). Resolves access tokens\n * via ADC (env → gcloud → metadata server → WIF).\n *\n * Model IDs follow the convention `vertex/{dialect}/{model}`:\n * - `vertex/google/gemini-2.0-flash-001` → OpenAI-compat endpoint (D291)\n * - `vertex/anthropic/claude-sonnet-4-5@20250929` → :rawPredict (D292)\n *\n * @internal\n */\n\nimport type { ProviderProfile } from \"../types.js\";\n\nexport const VERTEX: ProviderProfile = {\n name: \"vertex\",\n apiMode: \"anthropic_messages\", // sub-dispatched in selectTransport by profile.name\n envVars: [\"GOOGLE_APPLICATION_CREDENTIALS\"],\n authType: \"gcp_oauth\",\n baseUrl: \"https://us-central1-aiplatform.googleapis.com\",\n modelsUrl: undefined,\n hostname: \"aiplatform.googleapis.com\",\n fallbackModels: [\n \"vertex/anthropic/claude-sonnet-4-5@20250929\",\n \"vertex/google/gemini-2.0-flash-001\",\n ],\n};\n\n/**\n * D293 absorbed: when location === \"global\", use `aiplatform.googleapis.com`\n * (no `global-` prefix) — known bug `streamRawPredict` 404 at\n * `global-aiplatform.googleapis.com` (a peer#10287).\n */\nexport function resolveVertexBaseUrl(opts: {\n projectId: string;\n location: string;\n modelDialect: \"anthropic\" | \"gemini\";\n}): string {\n const host =\n opts.location === \"global\"\n ? \"aiplatform.googleapis.com\"\n : `${opts.location}-aiplatform.googleapis.com`;\n if (opts.modelDialect === \"gemini\") {\n // OpenAI-compat endpoint (D291) — the client appends `/chat/completions`.\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/endpoints/openapi`;\n }\n // Anthropic — base URL up to `/publishers/anthropic` (model id appended by client).\n return `https://${host}/v1/projects/${opts.projectId}/locations/${opts.location}/publishers/anthropic`;\n}\n\n/** Detect dialect from a `vertex/{dialect}/{model}` id. Default: gemini. */\nexport function inferModelDialect(modelId: string): \"anthropic\" | \"gemini\" {\n if (modelId.includes(\"/anthropic/\")) return \"anthropic\";\n if (modelId.includes(\"/google/\")) return \"gemini\";\n return \"gemini\";\n}\n\n/** Strip the `vertex/{dialect}/` prefix so the raw model id is used in the URL. */\nexport function stripVertexPrefix(modelId: string): string {\n return modelId.replace(/^vertex\\/(anthropic|google)\\//, \"\");\n}\n","import { openAiCompatibleProfile } from \"./openai-compatible.js\";\n\n/** M45 — xAI (Grok). Values per models.dev `xai` (2026-07 snapshot; grok-2 retired). */\nexport const XAI = openAiCompatibleProfile({\n name: \"xai\",\n aliases: [\"grok\"],\n baseUrl: \"https://api.x.ai/v1\",\n envVars: [\"XAI_API_KEY\"],\n fallbackModels: [\"grok-4.5\", \"grok-4.3\"],\n hostname: \"api.x.ai\",\n});\n","/**\n * Eager registration of builtin providers (T3.3). Side-effect import:\n * importing this module registers the 4 builtins with the registry.\n *\n * Lazy user-plugin discovery is handled by `discovery.ts` (T3.4).\n *\n * @internal\n */\n\nimport { registerCatalogProviders } from \"../catalog-loader.js\";\nimport { registerProvider } from \"../registry.js\";\nimport { ANTHROPIC } from \"./anthropic.js\";\nimport { BEDROCK } from \"./bedrock.js\";\nimport { CEREBRAS } from \"./cerebras.js\";\nimport { COHERE } from \"./cohere.js\";\nimport { DEEPINFRA } from \"./deepinfra.js\";\nimport { GEMINI } from \"./gemini.js\";\nimport { GOOGLE } from \"./google.js\";\nimport { GROQ } from \"./groq.js\";\nimport { LLAMACPP } from \"./llamacpp.js\";\nimport { LMSTUDIO } from \"./lmstudio.js\";\nimport { MISTRAL } from \"./mistral.js\";\nimport { OLLAMA } from \"./ollama.js\";\nimport { OPENAI } from \"./openai.js\";\nimport { OPENAI_CHATGPT } from \"./openai-chatgpt.js\";\nimport { OPENROUTER } from \"./openrouter.js\";\nimport { PERPLEXITY } from \"./perplexity.js\";\nimport { TOGETHER } from \"./together.js\";\nimport { VERTEX } from \"./vertex.js\";\nimport { XAI } from \"./xai.js\";\n\n// M45 review M2 — the guard lives on globalThis like the registry itself (M44 B1): a process importing both\n// bundle copies (`@theokit/sdk` + `@theokit/sdk/models`) must not re-register 19 builtins with bogus\n// \"overridden by user plugin\" WARNs.\nconst _registeredState = ((): { done: boolean } => {\n const g = globalThis as unknown as Record<symbol, { done: boolean }>;\n const sym = Symbol.for(\"theokit-sdk.providers.builtins-registered\");\n if (g[sym] === undefined) g[sym] = { done: false };\n return g[sym];\n})();\n\nexport function registerBuiltins(): void {\n if (_registeredState.done) return;\n _registeredState.done = true;\n // First-party builtins (take priority — registered first)\n registerProvider(ANTHROPIC);\n registerProvider(OPENAI);\n registerProvider(OPENAI_CHATGPT);\n registerProvider(OPENROUTER);\n registerProvider(GEMINI);\n registerProvider(OLLAMA);\n registerProvider(LMSTUDIO);\n registerProvider(LLAMACPP);\n registerProvider(BEDROCK);\n registerProvider(VERTEX);\n // M45 — the data-provider fleet (one file each on the openai-compatible base).\n registerProvider(GOOGLE);\n registerProvider(MISTRAL);\n registerProvider(GROQ);\n registerProvider(COHERE);\n registerProvider(DEEPINFRA);\n registerProvider(TOGETHER);\n registerProvider(XAI);\n registerProvider(PERPLEXITY);\n registerProvider(CEREBRAS);\n // Dynamic catalog — 40+ providers from JSON (T10.1, ADR D447)\n registerCatalogProviders();\n}\n\n/** Test-only reset. @internal */\nexport function _resetBuiltinsRegistered(): void {\n _registeredState.done = false;\n}\n\nexport {\n ANTHROPIC,\n BEDROCK,\n GEMINI,\n LLAMACPP,\n LMSTUDIO,\n OLLAMA,\n OPENAI,\n OPENAI_CHATGPT,\n OPENROUTER,\n VERTEX,\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 { registerBuiltins } from \"./builtin/index.js\";\nimport { getCatalogModelInfo, loadProviderCatalog, 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 // M44 L8 fix — honor the SDK home override so tests and multi-home setups never touch the real ~/.theokit.\n const base = process.env.THEOKIT_HOME?.trim() || join(homedir(), \".theokit\");\n const dir = join(base, \"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/**\n * M44 H3 fix — models.dev provider ids ≠ theokit ids (google↔google-gemini, zai↔zhipu, togetherai↔together,\n * fireworks-ai↔fireworks, amazon-bedrock↔bedrock, google-vertex↔vertex). The RUNTIME mapping mirrors the\n * maintenance script's table; targets resolve against the CATALOG entries (id + aliases — the same namespace\n * the vendored index uses) first, then the registry.\n */\nconst MODELS_DEV_ID_MAP: Record<string, string> = {\n google: \"google-gemini\",\n zai: \"zhipu\",\n togetherai: \"together\",\n \"fireworks-ai\": \"fireworks\",\n \"amazon-bedrock\": \"bedrock\",\n \"google-vertex\": \"vertex\",\n};\n\nlet _catalogTargets: Map<string, { keys: string[] }> | undefined;\n/** external-id → the index keys (entry id + aliases) its models patch under. Lazy; catalog-first. */\nfunction catalogTargets(): Map<string, { keys: string[] }> {\n if (_catalogTargets !== undefined) return _catalogTargets;\n _catalogTargets = new Map();\n try {\n for (const entry of Object.values(loadProviderCatalog())) {\n const keys = [entry.id, ...(entry.aliases ?? [])];\n for (const k of keys) {\n if (!_catalogTargets.has(k)) _catalogTargets.set(k, { keys });\n }\n }\n } catch {\n // catalog unavailable — registry fallback below still works\n }\n return _catalogTargets;\n}\n\nfunction resolvePatchKeys(externalId: string): string[] | undefined {\n const mapped = MODELS_DEV_ID_MAP[externalId] ?? externalId;\n const fromCatalog = catalogTargets().get(mapped);\n if (fromCatalog !== undefined) return fromCatalog.keys;\n const profile = getProviderProfile(mapped);\n if (profile !== undefined) return [profile.name, ...(profile.aliases ?? [])];\n return undefined;\n}\n\n/** Parse + patch the index from an api.json payload. Unknown providers are skipped with WARN (once each). */\n// Divida PRE-EXISTENTE, exposta quando o M75 consertou a config Biome que abortava antes\n// de varrer estes arquivos (raiz aninhada em refactor/). Nao e codigo novo e nao foi tocado\n// pelo M75; refatorar internals do SDK sem revisao trocaria um problema visivel por um diff\n// arriscado. Rastreado em usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ver a razao logo acima\nfunction patchIndexFromApiJson(raw: unknown): number {\n if (typeof raw !== \"object\" || raw === null) return 0;\n let patched = 0;\n const skipped: string[] = [];\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 — models.dev's npm/api fields cannot be mapped to a theokit\n // apiMode/authType safely, so unknown providers are data we cannot route.\n const keys = resolvePatchKeys(providerId);\n if (keys === undefined) {\n skipped.push(providerId);\n continue;\n }\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 for (const key of keys) patchModelInfo(`${key}/${modelId}`, parsed.data);\n patched++;\n }\n }\n if (skipped.length > 0) {\n process.stderr.write(\n `[theokit-sdk] WARN: models-dev refresh skipped ${skipped.length} unknown provider(s) (e.g. ${skipped.slice(0, 3).join(\", \")})\\n`,\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 let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n // corrupt cache: delete and fall through to the vendored catalog (OpenCode's delete-and-fall-through).\n // M44 L9 fix — only a PARSE failure is cache corruption; a patch error must never delete a valid cache.\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 try {\n return patchIndexFromApiJson(parsed);\n } catch (err) {\n process.stderr.write(\n `[theokit-sdk] WARN: models-dev cache patch failed (${(err as Error).message})\\n`,\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 */\n// Divida PRE-EXISTENTE, exposta quando o M75 consertou a config Biome que abortava antes\n// de varrer estes arquivos (raiz aninhada em refactor/). Nao e codigo novo e nao foi tocado\n// pelo M75; refatorar internals do SDK sem revisao trocaria um problema visivel por um diff\n// arriscado. Rastreado em usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: ver a razao logo acima\nexport async function refreshModelCatalog(\n opts: RefreshModelCatalogOptions = {},\n): Promise<RefreshModelCatalogResult> {\n // M44 M4 fix — self-initialize provider registration so the `@theokit/sdk/models` subpath works standalone\n // (without the consumer having built an Agent first).\n registerBuiltins();\n // M44 L11 fix — presence-based would treat \"0\"/\"false\"/\"\" as disabled; only truthy values disable.\n const kill = process.env.THEOKIT_DISABLE_MODELS_FETCH;\n if (kill !== undefined && kill !== \"\" && kill !== \"0\" && kill.toLowerCase() !== \"false\") {\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 try {\n return { source: \"network\", models: patchIndexFromApiJson(JSON.parse(body)) };\n } catch (err) {\n process.stderr.write(\n `[theokit-sdk] WARN: models-dev patch failed (${(err as Error).message}) — serving existing data\\n`,\n );\n return { source: \"cache\", models: 0 };\n }\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"]}