@theokit/sdk 4.52.1 → 4.53.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 (96) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/dist/{agent-U2R2R5JP.cjs → agent-JX5SBYDE.cjs} +13 -12
  3. package/dist/{agent-U2R2R5JP.cjs.map → agent-JX5SBYDE.cjs.map} +1 -1
  4. package/dist/{agent-RDHK6MVT.js → agent-ZAGG6ZBS.js} +12 -11
  5. package/dist/{agent-RDHK6MVT.js.map → agent-ZAGG6ZBS.js.map} +1 -1
  6. package/dist/auth/index.cjs +26 -25
  7. package/dist/auth/index.cjs.map +1 -1
  8. package/dist/auth/index.js +3 -2
  9. package/dist/auth/index.js.map +1 -1
  10. package/dist/chunk-23VZBRDQ.js +147 -0
  11. package/dist/chunk-23VZBRDQ.js.map +1 -0
  12. package/dist/{chunk-CY7MIMI4.cjs → chunk-2QMK627M.cjs} +3 -3
  13. package/dist/{chunk-CY7MIMI4.cjs.map → chunk-2QMK627M.cjs.map} +1 -1
  14. package/dist/{chunk-6GS7JI64.cjs → chunk-2VFZQEDW.cjs} +56 -56
  15. package/dist/{chunk-6GS7JI64.cjs.map → chunk-2VFZQEDW.cjs.map} +1 -1
  16. package/dist/{chunk-M5EK7N6R.js → chunk-2Y5NO2SY.js} +4 -4
  17. package/dist/{chunk-M5EK7N6R.js.map → chunk-2Y5NO2SY.js.map} +1 -1
  18. package/dist/{chunk-V2EJLKGA.js → chunk-2YWWPCGX.js} +4 -3
  19. package/dist/chunk-2YWWPCGX.js.map +1 -0
  20. package/dist/chunk-33L2NVTJ.cjs +177 -0
  21. package/dist/chunk-33L2NVTJ.cjs.map +1 -0
  22. package/dist/{chunk-GNPI5IWZ.js → chunk-3SHW7XKK.js} +3 -3
  23. package/dist/{chunk-GNPI5IWZ.js.map → chunk-3SHW7XKK.js.map} +1 -1
  24. package/dist/{chunk-J4RY5DTI.js → chunk-634YVZLU.js} +3 -3
  25. package/dist/{chunk-J4RY5DTI.js.map → chunk-634YVZLU.js.map} +1 -1
  26. package/dist/{chunk-T6ZCG5AP.cjs → chunk-BC5EUG7R.cjs} +7 -6
  27. package/dist/chunk-BC5EUG7R.cjs.map +1 -0
  28. package/dist/{chunk-WLESQ3ZQ.cjs → chunk-DM6Y5B2G.cjs} +21 -21
  29. package/dist/{chunk-WLESQ3ZQ.cjs.map → chunk-DM6Y5B2G.cjs.map} +1 -1
  30. package/dist/{chunk-NACDF3PK.js → chunk-HTK54K2J.js} +3 -3
  31. package/dist/{chunk-SDJYLCJK.cjs.map → chunk-HTK54K2J.js.map} +1 -1
  32. package/dist/{chunk-42PLABFU.js → chunk-I5OTK2RP.js} +3 -3
  33. package/dist/{chunk-42PLABFU.js.map → chunk-I5OTK2RP.js.map} +1 -1
  34. package/dist/chunk-NUEL6RCZ.cjs +155 -0
  35. package/dist/chunk-NUEL6RCZ.cjs.map +1 -0
  36. package/dist/{chunk-KELIQH7K.js → chunk-NZOR3N4E.js} +11 -11
  37. package/dist/{chunk-KELIQH7K.js.map → chunk-NZOR3N4E.js.map} +1 -1
  38. package/dist/{chunk-ZNEE4WWQ.cjs → chunk-QN5N3ZVT.cjs} +5 -5
  39. package/dist/{chunk-ZNEE4WWQ.cjs.map → chunk-QN5N3ZVT.cjs.map} +1 -1
  40. package/dist/{chunk-OI6RHLGC.cjs → chunk-T5ZWI3MC.cjs} +5 -5
  41. package/dist/{chunk-OI6RHLGC.cjs.map → chunk-T5ZWI3MC.cjs.map} +1 -1
  42. package/dist/{chunk-SDJYLCJK.cjs → chunk-TR4V2LHV.cjs} +3 -3
  43. package/dist/chunk-TR4V2LHV.cjs.map +1 -0
  44. package/dist/chunk-XRI6DXPZ.js +171 -0
  45. package/dist/chunk-XRI6DXPZ.js.map +1 -0
  46. package/dist/{compact-session-FBVWO6B3.cjs → compact-session-6GKIS4SD.cjs} +15 -14
  47. package/dist/{compact-session-FBVWO6B3.cjs.map → compact-session-6GKIS4SD.cjs.map} +1 -1
  48. package/dist/{compact-session-XLXC2CZN.js → compact-session-EJ36VH5I.js} +7 -6
  49. package/dist/{compact-session-XLXC2CZN.js.map → compact-session-EJ36VH5I.js.map} +1 -1
  50. package/dist/cron.cjs +12 -11
  51. package/dist/cron.js +11 -10
  52. package/dist/eval.cjs +15 -14
  53. package/dist/eval.cjs.map +1 -1
  54. package/dist/eval.js +11 -10
  55. package/dist/eval.js.map +1 -1
  56. package/dist/fs-session-store-LIKYT24K.js +10 -0
  57. package/dist/{fs-session-store-2TF3ZWMT.js.map → fs-session-store-LIKYT24K.js.map} +1 -1
  58. package/dist/{fs-session-store-TL4RJTXZ.cjs → fs-session-store-VXXDIBGM.cjs} +5 -5
  59. package/dist/{fs-session-store-TL4RJTXZ.cjs.map → fs-session-store-VXXDIBGM.cjs.map} +1 -1
  60. package/dist/index.cjs +42 -41
  61. package/dist/index.cjs.map +1 -1
  62. package/dist/index.js +13 -12
  63. package/dist/index.js.map +1 -1
  64. package/dist/{inject-session-UBAQ7I3G.cjs → inject-session-67SF65FC.cjs} +4 -4
  65. package/dist/{inject-session-UBAQ7I3G.cjs.map → inject-session-67SF65FC.cjs.map} +1 -1
  66. package/dist/{inject-session-UEH5MAKU.js → inject-session-HO7FYVCX.js} +3 -3
  67. package/dist/{inject-session-UEH5MAKU.js.map → inject-session-HO7FYVCX.js.map} +1 -1
  68. package/dist/internal/mcp/oauth.d.ts +1 -0
  69. package/dist/internal/mcp/token-storage.d.ts +1 -0
  70. package/dist/internal/persistence/index.cjs +6 -6
  71. package/dist/internal/persistence/index.js +1 -1
  72. package/dist/internal/persistence/transcript-ops.d.cts +6 -7
  73. package/dist/internal/persistence/transcript-ops.d.ts +6 -7
  74. package/dist/mcp-auth.cjs +299 -0
  75. package/dist/mcp-auth.cjs.map +1 -0
  76. package/dist/mcp-auth.d.cts +17 -0
  77. package/dist/mcp-auth.d.ts +17 -0
  78. package/dist/mcp-auth.js +292 -0
  79. package/dist/mcp-auth.js.map +1 -0
  80. package/dist/models.cjs +11 -10
  81. package/dist/models.cjs.map +1 -1
  82. package/dist/models.js +3 -2
  83. package/dist/models.js.map +1 -1
  84. package/dist/persistence.cjs +16 -7
  85. package/dist/persistence.cjs.map +1 -1
  86. package/dist/persistence.js +11 -2
  87. package/dist/persistence.js.map +1 -1
  88. package/package.json +11 -1
  89. package/dist/chunk-BKRTYDVN.js +0 -312
  90. package/dist/chunk-BKRTYDVN.js.map +0 -1
  91. package/dist/chunk-NACDF3PK.js.map +0 -1
  92. package/dist/chunk-T6ZCG5AP.cjs.map +0 -1
  93. package/dist/chunk-V2EJLKGA.js.map +0 -1
  94. package/dist/chunk-XK54DTRF.cjs +0 -325
  95. package/dist/chunk-XK54DTRF.cjs.map +0 -1
  96. package/dist/fs-session-store-2TF3ZWMT.js +0 -10
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/global-singleton.ts","../src/internal/providers/registry.ts","../src/internal/providers/catalog-schema.ts","../src/internal/providers/catalog-loader.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/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"],"names":[],"mappings":";;;;;;;;;AAYO,SAAS,eAAA,CAAmB,KAAa,MAAA,EAAoB;AAClE,EAAA,MAAM,CA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,2CAA2C,CAAA;AAClE,EAAA,IAAI,CAAA,CAAE,GAAG,CAAA,KAAM,MAAA,IAAa,GAAG,CAAA,GAAI,EAAE,IAAA,EAAM,KAAA,EAAM;AACjD,EAAA,OAAO,EAAE,GAAG,CAAA;AACd,CAAA,GAAG;AAEI,SAAS,gBAAA,GAAyB;AACvC,EAAA,IAAI,iBAAiB,IAAA,EAAM;AAC3B,EAAA,gBAAA,CAAiB,IAAA,GAAO,IAAA;AAExB,EAAA,gBAAA,CAAiB,SAAS,CAAA;AAC1B,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,cAAc,CAAA;AAC/B,EAAA,gBAAA,CAAiB,UAAU,CAAA;AAC3B,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,OAAO,CAAA;AACxB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AAEvB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,OAAO,CAAA;AACxB,EAAA,gBAAA,CAAiB,IAAI,CAAA;AACrB,EAAA,gBAAA,CAAiB,MAAM,CAAA;AACvB,EAAA,gBAAA,CAAiB,SAAS,CAAA;AAC1B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AACzB,EAAA,gBAAA,CAAiB,GAAG,CAAA;AACpB,EAAA,gBAAA,CAAiB,UAAU,CAAA;AAC3B,EAAA,gBAAA,CAAiB,QAAQ,CAAA;AAEzB,EAAA,wBAAA,EAAyB;AAC3B","file":"chunk-V2EJLKGA.js","sourcesContent":["/**\n * One singleton per realm, keyed by `Symbol.for`.\n *\n * It exists because a package can be loaded more than once in the same process (two copies in\n * `node_modules`, ESM and CJS side by side, a monorepo with distinct versions) — and then a module-level\n * `const x = new Map()` produces TWO caches that cannot see each other. `Symbol.for` uses the global\n * symbol registry, which belongs to the realm and not the module, so every copy converges on one instance.\n *\n * It was copied verbatim into `providers/discovery.ts` and `providers/catalog-loader.ts`. That is\n * duplicated KNOWLEDGE, not a coincidence of shape: the two copies have to agree on the\n * mechanism, and one fixed without the other produces exactly the bug the function exists to avoid.\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","/**\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 { diag } from \"../diagnostics.js\";\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 diag(`[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 diag(`[theokit-sdk] Alias \"${alias}\" collision: was \"${previous}\", now \"${profile.name}\".\\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","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 * 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 { diag } from \"../diagnostics.js\";\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 diag(\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// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\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 diag(\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 diag(\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// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\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","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 { 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 // #165 — this shipped as `codex_cli_rs`, which is the OFFICIAL Codex CLI's own value\n // (`codex-rs/login/src/auth/default_client.rs`, `DEFAULT_ORIGINATOR`). Claiming to be a different\n // vendor's client is a false statement of identity, and it diverged from the very prior art this\n // file is adapted from: OpenCode sends `originator: \"opencode\"` — its own name — against this same\n // endpoint, which also shows the route is not restricted to the official client.\n extraHeaders: { originator: \"theokit\" },\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"]}
@@ -1,325 +0,0 @@
1
- 'use strict';
2
-
3
- var chunkC6Y6CWYD_cjs = require('./chunk-C6Y6CWYD.cjs');
4
- var chunk2YGIBOUH_cjs = require('./chunk-2YGIBOUH.cjs');
5
- var crypto = require('crypto');
6
- var fs = require('fs');
7
- var path = require('path');
8
- var zod = require('zod');
9
-
10
- function credentialHome(config, env = {}) {
11
- const override = config.homeEnvVar !== void 0 ? env[config.homeEnvVar]?.trim() : void 0;
12
- return override !== void 0 && override.length > 0 ? override : path.join(config.home, config.dirName);
13
- }
14
- function authFilePath(config, env = {}) {
15
- return path.join(credentialHome(config, env), config.fileName);
16
- }
17
- var CredentialError = class extends chunk2YGIBOUH_cjs.AuthenticationError {
18
- // Field, not an assignment in the constructor: `AuthenticationError.name` is `override readonly`
19
- // (`errors.ts:174`), so `this.name = …` does not compile. Caught by `tsc`, not by vitest — the
20
- // suite was green with the broken assignment because the transpiler strips the type.
21
- name = "CredentialError";
22
- };
23
- var apiFileSchema = zod.z.object({
24
- type: zod.z.literal("api").optional(),
25
- provider: zod.z.string().min(1).optional(),
26
- api_key: zod.z.string()
27
- }).strict();
28
- var oauthFileSchema = zod.z.object({
29
- type: zod.z.literal("oauth"),
30
- provider: zod.z.string().min(1),
31
- access: zod.z.string().min(1),
32
- refresh: zod.z.string().min(1),
33
- expires: zod.z.number(),
34
- account_id: zod.z.string().optional()
35
- }).strict();
36
- var fileSchema = zod.z.union([oauthFileSchema, apiFileSchema]);
37
- function assertSecureModes(dirPath, path) {
38
- const dirMode = fs.statSync(dirPath).mode & 511;
39
- if ((dirMode & 18) !== 0) {
40
- throw new CredentialError(
41
- `${dirPath} is writable by other users (mode ${dirMode.toString(8)}), so the credential file inside it can be replaced. Fix it with: chmod 700 ${dirPath}`
42
- );
43
- }
44
- const mode = fs.statSync(path).mode & 511;
45
- if ((mode & 63) !== 0) {
46
- throw new CredentialError(
47
- `${path} is readable by other users (mode ${mode.toString(8)}). A credential file must not be. Fix it with: chmod 600 ${path}`
48
- );
49
- }
50
- }
51
- function describeUnionError(parsed, err, path) {
52
- const looksOAuth = typeof parsed === "object" && parsed !== null && parsed.type === "oauth";
53
- const specific = looksOAuth ? oauthFileSchema.safeParse(parsed) : apiFileSchema.safeParse(parsed);
54
- let issue;
55
- if (!specific.success) {
56
- issue = specific.error.issues[0];
57
- } else if (err instanceof zod.z.ZodError) {
58
- issue = err.issues[0];
59
- }
60
- return new CredentialError(
61
- `${path}: ${issue?.message ?? String(err)} [${issue?.path.join(".") || "root"}]`
62
- );
63
- }
64
- function parseStoredFile(raw, path) {
65
- let parsed;
66
- try {
67
- parsed = JSON.parse(raw);
68
- } catch {
69
- throw new CredentialError(
70
- `${path} is not valid JSON. Expected: {"provider": "<name>", "api_key": "..."}`
71
- );
72
- }
73
- try {
74
- return fileSchema.parse(parsed);
75
- } catch (err) {
76
- throw describeUnionError(parsed, err, path);
77
- }
78
- }
79
- function readAuthFile(config, env = {}) {
80
- const path = authFilePath(config, env);
81
- let raw;
82
- try {
83
- raw = fs.readFileSync(path, "utf8");
84
- } catch (err) {
85
- if (err.code === "ENOENT") return void 0;
86
- throw new CredentialError(`cannot read ${path}: ${err.message}`);
87
- }
88
- assertSecureModes(credentialHome(config, env), path);
89
- return parseStoredFile(raw, path);
90
- }
91
- function readStoredOAuth(config, env = {}) {
92
- const stored = readAuthFile(config, env);
93
- return stored !== void 0 && stored.type === "oauth" ? stored : void 0;
94
- }
95
- function isOAuthWrite(c) {
96
- return "type" in c && c.type === "oauth";
97
- }
98
- function buildStorePayload(cred) {
99
- if (isOAuthWrite(cred)) {
100
- if (cred.access.length === 0 || cred.refresh.length === 0) {
101
- throw new CredentialError(
102
- "refusing to write an oauth credential with an empty access/refresh token"
103
- );
104
- }
105
- return {
106
- type: "oauth",
107
- provider: cred.provider,
108
- access: cred.access,
109
- refresh: cred.refresh,
110
- expires: cred.expires,
111
- ...cred.account_id !== void 0 ? { account_id: cred.account_id } : {}
112
- };
113
- }
114
- if (typeof cred.apiKey !== "string" || cred.apiKey.length === 0) {
115
- throw new CredentialError("refusing to write an empty API key");
116
- }
117
- return { provider: cred.provider, api_key: cred.apiKey };
118
- }
119
- function writeCredential(cred, config, env = {}) {
120
- const payload = buildStorePayload(cred);
121
- const dir = credentialHome(config, env);
122
- fs.mkdirSync(dir, { recursive: true, mode: 448 });
123
- fs.chmodSync(dir, 448);
124
- const path = authFilePath(config, env);
125
- const tmp = `${path}.tmp-${crypto.randomBytes(8).toString("hex")}`;
126
- try {
127
- const fd = fs.openSync(tmp, "wx", 384);
128
- try {
129
- fs.writeFileSync(fd, `${JSON.stringify(payload, null, 2)}
130
- `);
131
- fs.fsyncSync(fd);
132
- } finally {
133
- fs.closeSync(fd);
134
- }
135
- fs.chmodSync(tmp, 384);
136
- fs.renameSync(tmp, path);
137
- } catch (err) {
138
- try {
139
- fs.unlinkSync(tmp);
140
- } catch {
141
- }
142
- throw new CredentialError(`cannot write ${path}: ${err.message}`);
143
- }
144
- return path;
145
- }
146
-
147
- // src/internal/auth/oauth-engine.ts
148
- var REFRESH_SKEW_MS = 6e4;
149
- function parseTokenResponse(body, now) {
150
- const b = body;
151
- if (typeof b.access_token !== "string" || b.access_token.length === 0) {
152
- throw new chunkC6Y6CWYD_cjs.AuthCallbackError(
153
- "oauth_token_exchange_failed",
154
- "token response had no access_token"
155
- );
156
- }
157
- if (typeof b.refresh_token !== "string" || b.refresh_token.length === 0) {
158
- throw new chunkC6Y6CWYD_cjs.AuthCallbackError(
159
- "oauth_token_exchange_failed",
160
- "token response had no refresh_token"
161
- );
162
- }
163
- const expiresIn = typeof b.expires_in === "number" ? b.expires_in : 3600;
164
- return {
165
- access: b.access_token,
166
- refresh: b.refresh_token,
167
- expires: now + expiresIn * 1e3,
168
- ...typeof b.account_id === "string" ? { accountId: b.account_id } : {}
169
- };
170
- }
171
- async function postGrant(config, form, deps) {
172
- let res;
173
- try {
174
- res = await deps.fetch(config.tokenEndpoint, {
175
- method: "POST",
176
- headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
177
- body: new URLSearchParams(form).toString()
178
- });
179
- } catch (err) {
180
- throw new chunkC6Y6CWYD_cjs.AuthCallbackError(
181
- "oauth_token_exchange_failed",
182
- `token endpoint request failed: ${err.message}`
183
- );
184
- }
185
- if (!res.ok) {
186
- throw new chunkC6Y6CWYD_cjs.AuthCallbackError(
187
- "oauth_token_exchange_failed",
188
- `token endpoint returned HTTP ${res.status}`
189
- );
190
- }
191
- let json;
192
- try {
193
- json = await res.json();
194
- } catch {
195
- throw new chunkC6Y6CWYD_cjs.AuthCallbackError("oauth_token_exchange_failed", "token response was not valid JSON");
196
- }
197
- return parseTokenResponse(json, deps.now());
198
- }
199
- function exchangeCode(config, input, deps) {
200
- return postGrant(
201
- config,
202
- {
203
- grant_type: "authorization_code",
204
- code: input.code,
205
- redirect_uri: config.redirectUri,
206
- client_id: config.clientId,
207
- code_verifier: input.verifier
208
- },
209
- deps
210
- );
211
- }
212
- function refreshOAuthTokens(config, refresh, deps) {
213
- return postGrant(
214
- config,
215
- { grant_type: "refresh_token", refresh_token: refresh, client_id: config.clientId },
216
- deps
217
- );
218
- }
219
- function persistOAuthTokens(provider, tokens, store, env = {}) {
220
- return writeCredential(
221
- {
222
- type: "oauth",
223
- provider,
224
- access: tokens.access,
225
- refresh: tokens.refresh,
226
- expires: tokens.expires,
227
- ...tokens.accountId !== void 0 ? { account_id: tokens.accountId } : {}
228
- },
229
- store,
230
- env
231
- );
232
- }
233
- var inFlightRefresh = /* @__PURE__ */ new Map();
234
- async function ensureFreshCredential(resolved, opts, deps) {
235
- if (resolved.kind !== "oauth") return resolved;
236
- const now = deps.now();
237
- if (resolved.expiresAt !== void 0 && resolved.expiresAt > now + REFRESH_SKEW_MS) {
238
- return resolved;
239
- }
240
- const env = opts.env ?? {};
241
- const path = authFilePath(opts.store, env);
242
- let refresh = inFlightRefresh.get(path);
243
- if (refresh === void 0) {
244
- refresh = (async () => {
245
- const stored = readStoredOAuth(opts.store, env);
246
- if (stored === void 0) {
247
- throw new chunkC6Y6CWYD_cjs.AuthCallbackError(
248
- "oauth_token_exchange_failed",
249
- "no stored oauth credential to refresh"
250
- );
251
- }
252
- const fresh2 = await refreshOAuthTokens(opts.config, stored.refresh, deps);
253
- const merged = {
254
- ...fresh2,
255
- accountId: fresh2.accountId ?? stored.account_id
256
- };
257
- persistOAuthTokens(resolved.provider, merged, opts.store, env);
258
- return merged;
259
- })();
260
- inFlightRefresh.set(path, refresh);
261
- refresh.finally(() => inFlightRefresh.delete(path)).catch(() => {
262
- });
263
- }
264
- const fresh = await refresh;
265
- return {
266
- kind: "oauth",
267
- provider: resolved.provider,
268
- apiKey: fresh.access,
269
- source: resolved.source,
270
- inferred: false,
271
- expiresAt: fresh.expires
272
- };
273
- }
274
-
275
- // src/internal/auth/resolve-credential.ts
276
- async function resolveOAuth(stored, path, opts, env) {
277
- if (stored.provider !== opts.provider) return void 0;
278
- const base = {
279
- kind: "oauth",
280
- provider: opts.provider,
281
- apiKey: stored.access,
282
- source: path,
283
- inferred: false,
284
- expiresAt: stored.expires
285
- };
286
- if (opts.oauth === void 0) return base;
287
- const deps = {
288
- fetch: opts.deps?.fetch ?? fetch,
289
- now: opts.deps?.now ?? (() => Date.now())
290
- };
291
- return ensureFreshCredential(base, { config: opts.oauth, store: opts.store, env }, deps);
292
- }
293
- async function resolveCredential(opts) {
294
- const env = opts.env ?? {};
295
- const stored = readAuthFile(opts.store, env);
296
- if (stored === void 0) return void 0;
297
- const path = authFilePath(opts.store, env);
298
- if (stored.type === "oauth") {
299
- return resolveOAuth(stored, path, opts, env);
300
- }
301
- if (stored.api_key.length === 0) return void 0;
302
- if (stored.provider !== opts.provider) return void 0;
303
- return {
304
- kind: "api",
305
- provider: opts.provider,
306
- apiKey: stored.api_key,
307
- source: path,
308
- inferred: false
309
- };
310
- }
311
-
312
- exports.CredentialError = CredentialError;
313
- exports.assertSecureModes = assertSecureModes;
314
- exports.authFilePath = authFilePath;
315
- exports.credentialHome = credentialHome;
316
- exports.ensureFreshCredential = ensureFreshCredential;
317
- exports.exchangeCode = exchangeCode;
318
- exports.persistOAuthTokens = persistOAuthTokens;
319
- exports.readAuthFile = readAuthFile;
320
- exports.readStoredOAuth = readStoredOAuth;
321
- exports.refreshOAuthTokens = refreshOAuthTokens;
322
- exports.resolveCredential = resolveCredential;
323
- exports.writeCredential = writeCredential;
324
- //# sourceMappingURL=chunk-XK54DTRF.cjs.map
325
- //# sourceMappingURL=chunk-XK54DTRF.cjs.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/internal/auth/credential-store.ts","../src/internal/auth/oauth-engine.ts","../src/internal/auth/resolve-credential.ts"],"names":["join","AuthenticationError","z","statSync","readFileSync","mkdirSync","chmodSync","randomBytes","openSync","writeFileSync","fsyncSync","closeSync","renameSync","unlinkSync","AuthCallbackError","fresh"],"mappings":";;;;;;;;;AAwCO,SAAS,cAAA,CACd,MAAA,EACA,GAAA,GAA0C,EAAC,EACnC;AACR,EAAA,MAAM,QAAA,GAAW,OAAO,UAAA,KAAe,MAAA,GAAY,IAAI,MAAA,CAAO,UAAU,CAAA,EAAG,IAAA,EAAK,GAAI,MAAA;AACpF,EAAA,OAAO,QAAA,KAAa,MAAA,IAAa,QAAA,CAAS,MAAA,GAAS,CAAA,GAC/C,WACAA,SAAA,CAAK,MAAA,CAAO,IAAA,EAAM,MAAA,CAAO,OAAO,CAAA;AACtC;AAGO,SAAS,YAAA,CACd,MAAA,EACA,GAAA,GAA0C,EAAC,EACnC;AACR,EAAA,OAAOA,UAAK,cAAA,CAAe,MAAA,EAAQ,GAAG,CAAA,EAAG,OAAO,QAAQ,CAAA;AAC1D;AAmBO,IAAM,eAAA,GAAN,cAA8BC,qCAAA,CAAoB;AAAA;AAAA;AAAA;AAAA,EAIrC,IAAA,GAAe,iBAAA;AACnC;AAOA,IAAM,aAAA,GAAgBC,MACnB,MAAA,CAAO;AAAA,EACN,IAAA,EAAMA,KAAA,CAAE,OAAA,CAAQ,KAAK,EAAE,QAAA,EAAS;AAAA,EAChC,UAAUA,KAAA,CAAE,MAAA,GAAS,GAAA,CAAI,CAAC,EAAE,QAAA,EAAS;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AA,IAAI,MAAA,CAAO,QAAA,KAAa,IAAA,CAAK,QAAA,EAAU,OAAO,MAAA;AAC9C,EAAA,OAAO;AAAA,IACL,IAAA,EAAM,KAAA;AAAA,IACN,UAAU,IAAA,CAAK,QAAA;AAAA,IACf,QAAQ,MAAA,CAAO,OAAA;AAAA,IACf,MAAA,EAAQ,IAAA;AAAA,IACR,QAAA,EAAU;AAAA,GACZ;AACF","file":"chunk-XK54DTRF.cjs","sourcesContent":["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 */\nexport function 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 * 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"]}
@@ -1,10 +0,0 @@
1
- export { FsSessionStore } from './chunk-J4RY5DTI.js';
2
- import './chunk-R7TKOQMJ.js';
3
- import './chunk-C4EU627W.js';
4
- import './chunk-NACDF3PK.js';
5
- import './chunk-2XLKLVVR.js';
6
- import './chunk-CHVSMEKM.js';
7
- import './chunk-HI4ZW62S.js';
8
- import './chunk-4X3SBHPK.js';
9
- //# sourceMappingURL=fs-session-store-2TF3ZWMT.js.map
10
- //# sourceMappingURL=fs-session-store-2TF3ZWMT.js.map