byok-config.ts 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. // BYOK config parsing + required provider overrides.
  2. //
  3. // Split out of config.ts (2000-line layout budget). Types stay in config.ts
  4. // (they are part of the Config surface); the back edge here is type-only, so
  5. // there is no runtime import cycle.
  6. import { createHash, randomUUID } from 'node:crypto';
  7. import fs from 'node:fs';
  8. import path from 'node:path';
  9. import yaml from 'js-yaml';
  10. import { restrictConfigFileSync, writePrivateConfigFileSync } from './private-config-file.js';
  11. import type {
  12. CustomProvidersConfig,
  13. MinimaxApiConfig,
  14. ModelsConfig,
  15. ProviderConfig,
  16. } from './config.js';
  17. export function parseMinimaxApiConfig(raw: unknown): MinimaxApiConfig | undefined {
  18. if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
  19. const obj = raw as Record<string, unknown>;
  20. const parsed: MinimaxApiConfig = {};
  21. if (typeof obj.apiKey === 'string') parsed.apiKey = obj.apiKey;
  22. if (typeof obj.baseURL === 'string') parsed.baseURL = obj.baseURL;
  23. if (isPlainRecord(obj.headers)) {
  24. const entries = Object.entries(obj.headers).filter(
  25. (entry): entry is [string, string] => entry[0].length > 0 && typeof entry[1] === 'string',
  26. );
  27. if (entries.length > 0) parsed.headers = Object.fromEntries(entries);
  28. }
  29. const modelContextLimits = parseModelContextLimits(obj.modelContextLimits);
  30. if (modelContextLimits) parsed.modelContextLimits = modelContextLimits;
  31. return Object.keys(parsed).length > 0 ? parsed : undefined;
  32. }
  33. export function parseModelContextLimits(raw: unknown): Record<string, number> | undefined {
  34. if (!isPlainRecord(raw)) return undefined;
  35. const entries = Object.entries(raw).filter(
  36. (entry): entry is [string, number] =>
  37. entry[0].length > 0 && Number.isSafeInteger(entry[1]) && (entry[1] as number) > 0,
  38. );
  39. return entries.length > 0 ? Object.fromEntries(entries) : undefined;
  40. }
  41. /** Apply user-owned managed Context selections without mutating the official snapshot. */
  42. export function applyManagedMinimaxContextLimits(
  43. provider: ModelsConfig,
  44. contextLimits: Record<string, number> | undefined,
  45. ): ModelsConfig {
  46. const minimax = provider.minimax;
  47. if (!minimax?.models || !contextLimits) return provider;
  48. let changed = false;
  49. const models = Object.fromEntries(
  50. Object.entries(minimax.models).map(([modelId, model]) => {
  51. const context = contextLimits[modelId];
  52. if (
  53. context === undefined ||
  54. !model.contextWindowOptions?.includes(context) ||
  55. model.limit?.context === context
  56. ) {
  57. return [modelId, model];
  58. }
  59. changed = true;
  60. return [modelId, { ...model, limit: { ...model.limit, context } }];
  61. }),
  62. );
  63. return changed ? { ...provider, minimax: { ...minimax, models } } : provider;
  64. }
  65. export function parseCustomProvidersConfig(raw: unknown): CustomProvidersConfig | undefined {
  66. if (raw == null || typeof raw !== 'object' || Array.isArray(raw)) return undefined;
  67. const entries = Object.entries(raw as Record<string, unknown>).filter(
  68. ([, value]) => value != null && typeof value === 'object' && !Array.isArray(value),
  69. );
  70. if (entries.length === 0) return undefined;
  71. return Object.fromEntries(
  72. entries.map(([providerKey, provider]) => [
  73. providerKey,
  74. normalizeLegacyThinkingEffort(provider as Record<string, unknown>),
  75. ]),
  76. ) as CustomProvidersConfig;
  77. }
  78. export function normalizeLegacyThinkingEfforts(config: ModelsConfig): ModelsConfig {
  79. return Object.fromEntries(
  80. Object.entries(config).map(([providerKey, provider]) => [
  81. providerKey,
  82. isPlainRecord(provider)
  83. ? normalizeLegacyThinkingEffort(provider as Record<string, unknown>)
  84. : provider,
  85. ]),
  86. ) as ModelsConfig;
  87. }
  88. function normalizeLegacyThinkingEffort(provider: Record<string, unknown>): Record<string, unknown> {
  89. if (!isPlainRecord(provider.models)) return provider;
  90. let changed = false;
  91. const models = Object.fromEntries(
  92. Object.entries(provider.models).map(([modelId, value]) => {
  93. if (!isPlainRecord(value) || !isPlainRecord(value.thinking)) return [modelId, value];
  94. const legacyEffort =
  95. typeof value.thinking.effort === 'string' ? value.thinking.effort.trim() : '';
  96. const configuredDefaultEffort =
  97. typeof value.thinking.defaultEffort === 'string' ? value.thinking.defaultEffort.trim() : '';
  98. if (
  99. !Object.hasOwn(value.thinking, 'effort') &&
  100. !Object.hasOwn(value.thinking, 'defaultEffort')
  101. ) {
  102. return [modelId, value];
  103. }
  104. const effortOptions: string[] = [];
  105. const seen = new Set<string>();
  106. if (Array.isArray(value.thinking.effortOptions)) {
  107. for (const option of value.thinking.effortOptions) {
  108. if (typeof option !== 'string') continue;
  109. const normalized = option.trim();
  110. if (!normalized || seen.has(normalized)) continue;
  111. seen.add(normalized);
  112. effortOptions.push(normalized);
  113. }
  114. }
  115. if (legacyEffort && !seen.has(legacyEffort)) {
  116. seen.add(legacyEffort);
  117. effortOptions.push(legacyEffort);
  118. }
  119. if (configuredDefaultEffort && !seen.has(configuredDefaultEffort)) {
  120. seen.add(configuredDefaultEffort);
  121. effortOptions.push(configuredDefaultEffort);
  122. }
  123. const thinkingRest = { ...value.thinking };
  124. delete thinkingRest.effort;
  125. delete thinkingRest.effortOptions;
  126. delete thinkingRest.defaultEffort;
  127. const thinking = {
  128. ...thinkingRest,
  129. ...(effortOptions.length > 0 ? { effortOptions } : {}),
  130. ...(configuredDefaultEffort ? { defaultEffort: configuredDefaultEffort } : {}),
  131. };
  132. const model = { ...value };
  133. if (Object.keys(thinking).length > 0) model.thinking = thinking;
  134. else delete model.thinking;
  135. changed = true;
  136. return [modelId, model];
  137. }),
  138. );
  139. return changed ? { ...provider, models } : provider;
  140. }
  141. export interface RequiredProviderOverrideDeps {
  142. isManagedRuntime(): boolean;
  143. shouldEnforceManagedProviderProtection(): boolean;
  144. getManagedPreset(): { provider: ModelsConfig; defaultModel: string };
  145. isManagedPresetBaseUrl(baseURL: string): boolean;
  146. }
  147. export interface LegacyByokProviderMigrationResult {
  148. migrated: boolean;
  149. migratedProviders: Record<string, string>;
  150. backupPath?: string;
  151. }
  152. const LEGACY_BYOK_MIGRATION_KEY = 'byok_legacy_provider_to_custom_provider_v1';
  153. const LEGACY_BYOK_BACKUP_PREFIX = 'config.yaml.bak.byok-legacy-provider.';
  154. const RESERVED_CUSTOM_PROVIDER_KEYS = new Set([
  155. 'minimax',
  156. 'minimax_api',
  157. 'provider',
  158. 'custom_provider',
  159. ]);
  160. const SIMPLE_ASCII_NAME = /^[A-Za-z0-9 _-]+$/;
  161. /**
  162. * Feature-branch dogfood builds allowed BYOK-like providers to be hand-written
  163. * under `provider.*`. New builds keep `provider` as the managed/builtin tree,
  164. * so legacy user-owned entries are moved into `custom_provider` before the
  165. * config is parsed. Classification is intentionally conservative: eligible
  166. * legacy entries always become custom providers, never `minimax_api`.
  167. */
  168. export function migrateLegacyByokProvidersOnDisk(
  169. configPath: string,
  170. deps: RequiredProviderOverrideDeps,
  171. ): LegacyByokProviderMigrationResult {
  172. const empty = { migrated: false, migratedProviders: {} };
  173. if (!deps.isManagedRuntime()) return empty;
  174. if (!fs.existsSync(configPath)) return empty;
  175. const raw = readRawConfigForMigration(configPath);
  176. if (!isPlainRecord(raw.provider)) return empty;
  177. const provider = raw.provider;
  178. const customProvider = isPlainRecord(raw.custom_provider) ? raw.custom_provider : {};
  179. const marker = readLegacyMigrationMarker(raw);
  180. const migratedProviders: Record<string, string> = {};
  181. const nextCustomProvider: Record<string, unknown> = { ...customProvider };
  182. const existingKeys = new Set(Object.keys(nextCustomProvider));
  183. let changed = false;
  184. const managedProvider = deps.getManagedPreset().provider;
  185. for (const [providerId, providerConfig] of Object.entries(provider)) {
  186. if (!shouldMigrateLegacyProvider(providerId, providerConfig, managedProvider)) {
  187. continue;
  188. }
  189. const recordedKey = marker.providers[providerId];
  190. if (
  191. recordedKey &&
  192. !RESERVED_CUSTOM_PROVIDER_KEYS.has(recordedKey) &&
  193. !isPlainRecord(nextCustomProvider[recordedKey])
  194. ) {
  195. delete provider[providerId];
  196. changed = true;
  197. continue;
  198. }
  199. const customKey =
  200. recordedKey && !RESERVED_CUSTOM_PROVIDER_KEYS.has(recordedKey)
  201. ? recordedKey
  202. : generateLegacyCustomProviderKey(providerId, providerConfig, existingKeys);
  203. migratedProviders[providerId] = customKey;
  204. if (!isPlainRecord(nextCustomProvider[customKey])) {
  205. nextCustomProvider[customKey] = toMigratedCustomProvider(providerConfig);
  206. existingKeys.add(customKey);
  207. changed = true;
  208. }
  209. if (marker.providers[providerId] !== customKey) {
  210. marker.providers[providerId] = customKey;
  211. changed = true;
  212. }
  213. delete provider[providerId];
  214. changed = true;
  215. }
  216. if (!changed && Object.keys(migratedProviders).length === 0) return empty;
  217. changed = rewriteModelRefField(raw, 'defaultModel', migratedProviders) || changed;
  218. changed = rewriteModelRefField(raw, 'defaultLightModel', migratedProviders) || changed;
  219. changed = rewriteNexusModelProvider(raw, migratedProviders) || changed;
  220. if (!changed) return { migrated: false, migratedProviders };
  221. if (Object.keys(nextCustomProvider).length > 0) raw.custom_provider = nextCustomProvider;
  222. else delete raw.custom_provider;
  223. writeLegacyMigrationMarker(raw, marker);
  224. try {
  225. const backupPath = backupConfigForMigration(configPath);
  226. writePrivateConfigFileSync(
  227. configPath,
  228. yaml.dump(raw, { indent: 2, lineWidth: -1, noRefs: true }),
  229. );
  230. return { migrated: true, migratedProviders, backupPath };
  231. } catch (err) {
  232. console.warn(`[config] legacy BYOK provider migration skipped: ${formatMigrationError(err)}`);
  233. return { migrated: false, migratedProviders };
  234. }
  235. }
  236. // config.yaml lives in the user-writable dataDir, so the provider tree cannot
  237. // be trusted as-is: the builtin managed provider may be deleted or hand-edited.
  238. // In managed runtime every read restores a usable `provider.minimax`: a missing
  239. // or gutted entry is rebuilt from the current preset and missing models/npm are
  240. // backfilled. Protected builds additionally force `baseURL` and `authMode` back
  241. // to the current preset with managed-login. Test builds deliberately preserve
  242. // existing connection fields so developers can route the builtin provider
  243. // through a local fault-injection proxy. In non-managed dev/runtime, an existing
  244. // `provider.minimax` that explicitly points at a managed preset gateway still
  245. // gets the built-in model table only when its managed snapshot is absent, but
  246. // custom endpoints are left untouched. `provider.minimax` remains the builtin managed provider; user
  247. // BYOK for protected builds lives exclusively in the `minimax_api` /
  248. // `custom_provider` trees. The result is never written back to disk, and
  249. // user-owned trees (`minimax_api`, `custom_provider`) are never touched.
  250. // Selection fallback for a dangling defaultModel is owned by the models/select
  251. // layer, not by this read path.
  252. //
  253. // `minimax_api` is additionally a reserved provider id: the resolver matches
  254. // it before falling back to the legacy provider map, so a hand-written
  255. // `provider.minimax_api` entry would be permanently shadowed. It is dropped
  256. // from the effective view with a warning (in every runtime mode).
  257. export function applyRequiredProviderOverrides(
  258. input: { provider: ModelsConfig; defaultModel?: string },
  259. deps: RequiredProviderOverrideDeps,
  260. ): { provider: ModelsConfig; defaultModel?: string } {
  261. let provider = input.provider;
  262. const defaultModel = input.defaultModel;
  263. if (Object.prototype.hasOwnProperty.call(provider, 'minimax_api')) {
  264. const { minimax_api: _shadowed, ...rest } = provider;
  265. provider = rest;
  266. console.warn(
  267. '[config] "minimax_api" is a reserved provider id; ignoring provider.minimax_api from config.yaml',
  268. );
  269. }
  270. const preset = deps.getManagedPreset();
  271. const presetProvider = preset.provider.minimax as ProviderConfig;
  272. const existing = provider.minimax;
  273. const managedRuntime = deps.isManagedRuntime();
  274. const shouldBackfillManagedMinimax =
  275. managedRuntime || isManagedOriginMinimaxProvider(existing, deps);
  276. if (!shouldBackfillManagedMinimax) return { provider, defaultModel };
  277. const existingOptions = existing?.options;
  278. const enforceProtection = managedRuntime && deps.shouldEnforceManagedProviderProtection();
  279. // A persisted managed snapshot is the complete model catalog. The built-in
  280. // preset is used only before the first valid remote snapshot is available.
  281. // The on-disk config.yaml is never rewritten by this read-time protection.
  282. const models = mergeManagedModelTables(presetProvider.models, existing?.models);
  283. // The on-disk apiKey is paired with the on-disk endpoint. When the override
  284. // discards a non-managed endpoint, the paired key is meaningless against
  285. // the managed gateway (stable 401) and, worse, a real key bypasses the
  286. // managed-login "auth token is not synced" sentinel (which only fires on
  287. // the placeholder). Reset it to the preset placeholder so the sentinel
  288. // works again. Keys stored alongside a managed-origin endpoint (legacy
  289. // gateway-key flow) stay valid for the gateway and are preserved.
  290. const existingBaseURL =
  291. typeof existingOptions?.baseURL === 'string' && existingOptions.baseURL.length > 0
  292. ? existingOptions.baseURL
  293. : undefined;
  294. const dropPairedApiKey =
  295. enforceProtection && existingBaseURL != null && !deps.isManagedPresetBaseUrl(existingBaseURL);
  296. provider = {
  297. ...provider,
  298. minimax: {
  299. ...presetProvider,
  300. ...(existing ?? {}),
  301. npm: existing?.npm ?? presetProvider.npm,
  302. models,
  303. options: {
  304. ...(presetProvider.options ?? {}),
  305. ...(existingOptions ?? {}),
  306. ...(dropPairedApiKey ? { apiKey: presetProvider.options?.apiKey } : {}),
  307. ...(enforceProtection
  308. ? { authMode: 'managed-login', baseURL: presetProvider.options?.baseURL }
  309. : {}),
  310. },
  311. },
  312. };
  313. return { provider, defaultModel };
  314. }
  315. function isManagedOriginMinimaxProvider(
  316. provider: ProviderConfig | undefined,
  317. deps: RequiredProviderOverrideDeps,
  318. ): boolean {
  319. const options = provider?.options;
  320. if (options?.authMode === 'managed-login') return true;
  321. return typeof options?.baseURL === 'string' && deps.isManagedPresetBaseUrl(options.baseURL);
  322. }
  323. function mergeManagedModelTables(
  324. presetModels: ProviderConfig['models'] | undefined,
  325. existingModels: ProviderConfig['models'] | undefined,
  326. ): ProviderConfig['models'] {
  327. return existingModels && Object.keys(existingModels).length > 0
  328. ? existingModels
  329. : (presetModels ?? {});
  330. }
  331. function readRawConfigForMigration(configPath: string): Record<string, unknown> {
  332. try {
  333. const parsed = yaml.load(fs.readFileSync(configPath, 'utf-8'));
  334. return isPlainRecord(parsed) ? parsed : {};
  335. } catch {
  336. return {};
  337. }
  338. }
  339. function shouldMigrateLegacyProvider(
  340. providerId: string,
  341. providerConfig: unknown,
  342. managedProvider: ModelsConfig,
  343. ): providerConfig is Record<string, unknown> {
  344. // Builtin identity is stable even when old config contains a proxy endpoint.
  345. // Never turn an official Session choice into an API-key provider alias.
  346. if (providerId === 'minimax' || providerId === 'minimax_api') return false;
  347. if (!isProviderLikeRecord(providerConfig)) return false;
  348. if (!hasLegacyByokProviderShape(providerConfig)) return false;
  349. return !Object.prototype.hasOwnProperty.call(managedProvider, providerId);
  350. }
  351. function hasLegacyByokProviderShape(providerConfig: Record<string, unknown>): boolean {
  352. const options = isPlainRecord(providerConfig.options) ? providerConfig.options : undefined;
  353. return (
  354. typeof options?.apiKey === 'string' &&
  355. options.apiKey.trim().length > 0 &&
  356. typeof options.baseURL === 'string' &&
  357. options.baseURL.trim().length > 0 &&
  358. isPlainRecord(providerConfig.models)
  359. );
  360. }
  361. function toMigratedCustomProvider(
  362. providerConfig: Record<string, unknown>,
  363. ): Record<string, unknown> {
  364. const options = isPlainRecord(providerConfig.options) ? providerConfig.options : {};
  365. return {
  366. ...providerConfig,
  367. kind: 'custom',
  368. enabled: providerConfig.enabled !== false,
  369. options: {
  370. ...options,
  371. authMode: 'api-key',
  372. },
  373. };
  374. }
  375. function generateLegacyCustomProviderKey(
  376. providerId: string,
  377. providerConfig: unknown,
  378. existingKeys: Set<string>,
  379. ): string {
  380. const record = isPlainRecord(providerConfig) ? providerConfig : {};
  381. const name = typeof record.name === 'string' ? record.name : undefined;
  382. const fallback = `provider-${stableHash(providerId)}`;
  383. const base = slugify(providerId) ?? slugify(name) ?? fallback;
  384. for (let suffix = 0; ; suffix += 1) {
  385. const candidate = suffix === 0 ? base : `${base}-${suffix + 1}`;
  386. if (!existingKeys.has(candidate) && !RESERVED_CUSTOM_PROVIDER_KEYS.has(candidate)) {
  387. return candidate;
  388. }
  389. }
  390. }
  391. function slugify(value: string | undefined): string | undefined {
  392. const trimmed = value?.trim();
  393. if (!trimmed || !SIMPLE_ASCII_NAME.test(trimmed)) return undefined;
  394. const slug = trimmed
  395. .toLowerCase()
  396. .replace(/[\s_-]+/g, '-')
  397. .replace(/^-+|-+$/g, '');
  398. return slug || undefined;
  399. }
  400. function stableHash(value: string): string {
  401. return createHash('sha256').update(value).digest('hex').slice(0, 8);
  402. }
  403. function rewriteModelRefField(
  404. raw: Record<string, unknown>,
  405. field: 'defaultModel' | 'defaultLightModel',
  406. migratedProviders: Record<string, string>,
  407. ): boolean {
  408. const value = raw[field];
  409. if (typeof value !== 'string') return false;
  410. const next = rewriteModelRef(value, migratedProviders);
  411. if (next === value) return false;
  412. raw[field] = next;
  413. return true;
  414. }
  415. function rewriteModelRef(value: string, migratedProviders: Record<string, string>): string {
  416. const slash = value.indexOf('/');
  417. if (slash <= 0 || slash === value.length - 1) return value;
  418. const providerId = value.slice(0, slash);
  419. const customKey = migratedProviders[providerId];
  420. if (!customKey) return value;
  421. return `custom_provider:${customKey}/${value.slice(slash + 1)}`;
  422. }
  423. function rewriteNexusModelProvider(
  424. raw: Record<string, unknown>,
  425. migratedProviders: Record<string, string>,
  426. ): boolean {
  427. if (!isPlainRecord(raw.nexus) || !isPlainRecord(raw.nexus.model)) return false;
  428. const providerID = raw.nexus.model.providerID;
  429. if (typeof providerID !== 'string') return false;
  430. const customKey = migratedProviders[providerID];
  431. if (!customKey) return false;
  432. raw.nexus.model.providerID = `custom_provider:${customKey}`;
  433. return true;
  434. }
  435. /** Repair old backups without making archival maintenance a config-load dependency. */
  436. export function restrictLegacyByokBackups(configPath: string): void {
  437. if (process.platform === 'win32') return;
  438. const directory = path.dirname(configPath);
  439. let entries: fs.Dirent[];
  440. try {
  441. entries = fs.readdirSync(directory, { withFileTypes: true });
  442. } catch {
  443. console.warn(
  444. `[config] Could not inspect legacy BYOK backups in ${JSON.stringify(directory)}. ` +
  445. 'Backup permissions were not verified; check directory access and restrict backup permissions manually.',
  446. );
  447. return;
  448. }
  449. for (const entry of entries) {
  450. if (entry.isFile() && entry.name.startsWith(LEGACY_BYOK_BACKUP_PREFIX)) {
  451. const backupPath = path.join(directory, entry.name);
  452. try {
  453. restrictConfigFileSync(backupPath);
  454. } catch {
  455. // Do not expose arbitrary error messages that could contain config content.
  456. console.warn(
  457. `[config] Could not restrict legacy BYOK backup ${JSON.stringify(backupPath)}. ` +
  458. 'It may still be readable by other users; restrict its permissions manually.',
  459. );
  460. }
  461. }
  462. }
  463. }
  464. function backupConfigForMigration(configPath: string): string {
  465. const backupPath = path.join(
  466. path.dirname(configPath),
  467. `${LEGACY_BYOK_BACKUP_PREFIX}${Date.now()}.${randomUUID()}`,
  468. );
  469. restrictConfigFileSync(configPath);
  470. writePrivateConfigFileSync(backupPath, fs.readFileSync(configPath), true);
  471. return backupPath;
  472. }
  473. function readLegacyMigrationMarker(raw: Record<string, unknown>): {
  474. providers: Record<string, string>;
  475. } {
  476. const migrations = isPlainRecord(raw.migrations) ? raw.migrations : undefined;
  477. const marker = migrations?.[LEGACY_BYOK_MIGRATION_KEY];
  478. const providers =
  479. isPlainRecord(marker) && isPlainRecord(marker.providers)
  480. ? Object.fromEntries(
  481. Object.entries(marker.providers).filter(
  482. (entry): entry is [string, string] => typeof entry[1] === 'string',
  483. ),
  484. )
  485. : {};
  486. return { providers };
  487. }
  488. function writeLegacyMigrationMarker(
  489. raw: Record<string, unknown>,
  490. marker: { providers: Record<string, string> },
  491. ): void {
  492. const migrations = isPlainRecord(raw.migrations) ? raw.migrations : {};
  493. migrations[LEGACY_BYOK_MIGRATION_KEY] = {
  494. version: 1,
  495. providers: marker.providers,
  496. };
  497. raw.migrations = migrations;
  498. }
  499. function isProviderLikeRecord(value: unknown): value is Record<string, unknown> {
  500. if (!isPlainRecord(value)) return false;
  501. return (
  502. typeof value.name === 'string' ||
  503. typeof value.npm === 'string' ||
  504. typeof value.api === 'string' ||
  505. isPlainRecord(value.options) ||
  506. isPlainRecord(value.models)
  507. );
  508. }
  509. function isPlainRecord(value: unknown): value is Record<string, unknown> {
  510. return value != null && typeof value === 'object' && !Array.isArray(value);
  511. }
  512. function formatMigrationError(err: unknown): string {
  513. if (err instanceof Error) return err.message;
  514. return String(err);
  515. }