byok-config.ts 21 KB

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