local-model-provider-write.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. import { randomBytes } from 'node:crypto';
  2. import fs, { existsSync, readFileSync } from 'node:fs';
  3. import { dirname, join } from 'node:path';
  4. import yaml from 'js-yaml';
  5. import lockfile from 'proper-lockfile';
  6. import {
  7. getConfig,
  8. getConfigPath,
  9. MINIMAX_API_MODEL_CATALOG,
  10. resetConfig,
  11. type Config,
  12. } from './config.js';
  13. import { MANAGED_MINIMAX_PROVIDER_ID, MINIMAX_API_PROVIDER_ID } from './model-availability.js';
  14. const LOCAL_CONFIG_FILE_MODE = 0o600;
  15. const DANGEROUS_CONFIG_PATH_SEGMENTS = new Set(['__proto__', 'prototype', 'constructor']);
  16. const LOCAL_BYOK_CONFIG_ROOTS = ['minimax_api', 'custom_provider'] as const;
  17. export interface LocalByokConfigDraft {
  18. minimax_api?: Record<string, unknown>;
  19. custom_provider?: Record<string, unknown>;
  20. minimaxModelSource?: 'token_plan' | 'minimax_api_key';
  21. defaultModel?: string;
  22. defaultModelVariant?: string;
  23. }
  24. export interface LocalModelSelectionWriteInput {
  25. readonly modelKey: string;
  26. readonly variant?: string;
  27. readonly thinking?: { readonly effort?: string };
  28. readonly contextLimit?: number;
  29. }
  30. export interface ManagedMinimaxProviderSnapshot {
  31. readonly api?: string;
  32. readonly name?: string;
  33. readonly options?: unknown;
  34. readonly models: Record<string, unknown>;
  35. readonly model_order?: readonly string[];
  36. }
  37. /** Remove one legacy `provider.*` entry after its OAuth config moved to `custom_provider`. */
  38. export async function removeLocalProviderConfig(
  39. providerId: string,
  40. ): Promise<{ readonly config: Config }> {
  41. const normalized = providerId.trim();
  42. if (!normalized || normalized.includes('.') || DANGEROUS_CONFIG_PATH_SEGMENTS.has(normalized)) {
  43. throw new LocalModelProviderConfigValidationError('Invalid provider id');
  44. }
  45. return withLockedConfig(async (raw) => {
  46. if (isPlainRecord(raw.provider)) delete raw.provider[normalized];
  47. return { write: true, value: undefined };
  48. }).then(({ config }) => ({ config }));
  49. }
  50. /** Replace the official MiniMax snapshot without taking ownership of BYOK roots. */
  51. export async function replaceLocalManagedMinimaxProvider(
  52. provider: ManagedMinimaxProviderSnapshot,
  53. ): Promise<{ readonly config: Config }> {
  54. if (!isPlainRecord(provider) || !isPlainRecord(provider.models)) {
  55. throw new LocalModelProviderConfigValidationError('Invalid managed MiniMax provider snapshot');
  56. }
  57. assertSafeConfigRecord(provider);
  58. return withLockedConfig(async (raw) => {
  59. raw.provider = {
  60. ...(isPlainRecord(raw.provider) ? raw.provider : {}),
  61. [MANAGED_MINIMAX_PROVIDER_ID]: structuredClone(provider),
  62. };
  63. return { write: true, value: undefined };
  64. }).then(({ config }) => ({ config }));
  65. }
  66. export interface LocalModelContextCompareAndSetResult {
  67. readonly config: Config;
  68. readonly updated: boolean;
  69. }
  70. class LocalModelProviderConfigValidationError extends Error {
  71. override name = 'LocalModelProviderConfigValidationError';
  72. }
  73. class LocalModelProviderConfigWriteError extends Error {
  74. override name = 'LocalModelProviderConfigWriteError';
  75. constructor() {
  76. super('Local runtime failed to update config file');
  77. }
  78. }
  79. /**
  80. * Lock-protected write path for the secret-bearing BYOK trees. The generic
  81. * config update API deliberately cannot reach these roots.
  82. */
  83. export async function updateLocalByokConfig(
  84. mutate: (draft: LocalByokConfigDraft, currentConfig: Config) => void | Promise<void>,
  85. ): Promise<{ readonly config: Config }> {
  86. return withLockedConfig(async (raw, currentConfig) => {
  87. const draft: LocalByokConfigDraft = {
  88. minimax_api: isPlainRecord(raw.minimax_api) ? raw.minimax_api : undefined,
  89. custom_provider: withoutEmptyEntries(
  90. isPlainRecord(raw.custom_provider) ? raw.custom_provider : undefined,
  91. ),
  92. minimaxModelSource:
  93. typeof raw.minimaxModelSource === 'string'
  94. ? (raw.minimaxModelSource as 'token_plan' | 'minimax_api_key')
  95. : undefined,
  96. defaultModel: typeof raw.defaultModel === 'string' ? raw.defaultModel : undefined,
  97. defaultModelVariant:
  98. typeof raw.defaultModelVariant === 'string' ? raw.defaultModelVariant : undefined,
  99. };
  100. await mutate(draft, currentConfig);
  101. for (const root of LOCAL_BYOK_CONFIG_ROOTS) {
  102. const value = draft[root];
  103. if (value === undefined) {
  104. delete raw[root];
  105. continue;
  106. }
  107. if (!isPlainRecord(value)) {
  108. throw new LocalModelProviderConfigValidationError(`Invalid BYOK config subtree "${root}"`);
  109. }
  110. assertSafeConfigRecord(value);
  111. raw[root] = value;
  112. }
  113. setOptionalString(raw, 'minimaxModelSource', draft.minimaxModelSource);
  114. if (raw.defaultModel !== draft.defaultModel) {
  115. delete raw.defaultModelThinking;
  116. delete raw.defaultModelContextWindow;
  117. }
  118. setOptionalString(raw, 'defaultModel', draft.defaultModel);
  119. setOptionalString(raw, 'defaultModelVariant', draft.defaultModelVariant);
  120. return { write: true, value: undefined };
  121. }).then(({ config }) => ({ config }));
  122. }
  123. /** Atomically persist the default model and its optional variant. */
  124. export async function updateLocalModelSelection(
  125. input: LocalModelSelectionWriteInput,
  126. ): Promise<{ readonly config: Config }> {
  127. const modelKey = input.modelKey.trim();
  128. if (!modelKey) {
  129. throw new LocalModelProviderConfigValidationError('Default model must not be empty');
  130. }
  131. if (
  132. input.contextLimit !== undefined &&
  133. (!Number.isSafeInteger(input.contextLimit) ||
  134. input.contextLimit <= 0 ||
  135. input.contextLimit > 2_147_483_647)
  136. )
  137. throw new LocalModelProviderConfigValidationError('Invalid default context');
  138. if (
  139. input.thinking?.effort !== undefined &&
  140. (typeof input.thinking.effort !== 'string' || !input.thinking.effort.trim())
  141. )
  142. throw new LocalModelProviderConfigValidationError('Invalid default effort');
  143. return withLockedConfig(async (raw) => {
  144. raw.defaultModel = modelKey;
  145. if (input.contextLimit === undefined) delete raw.defaultModelContextWindow;
  146. else raw.defaultModelContextWindow = input.contextLimit;
  147. if (input.thinking?.effort === undefined) delete raw.defaultModelThinking;
  148. else raw.defaultModelThinking = { effort: input.thinking.effort };
  149. if (input.variant === undefined) delete raw.defaultModelVariant;
  150. else raw.defaultModelVariant = input.variant;
  151. return { write: true, value: undefined };
  152. }).then(({ config }) => ({ config }));
  153. }
  154. /** Compare, remote-test, and persist a managed MiniMax model Context under one config lock. */
  155. export async function compareAndSetLocalModelContext(
  156. input: {
  157. readonly providerId: string;
  158. readonly modelId: string;
  159. readonly expectedContextLimit: number;
  160. readonly contextLimit: number;
  161. },
  162. beforeCommit: (currentConfig: Config) => Promise<boolean>,
  163. ): Promise<LocalModelContextCompareAndSetResult> {
  164. const modelId = input.modelId.trim();
  165. if (
  166. (input.providerId !== MANAGED_MINIMAX_PROVIDER_ID &&
  167. input.providerId !== MINIMAX_API_PROVIDER_ID) ||
  168. !modelId ||
  169. DANGEROUS_CONFIG_PATH_SEGMENTS.has(modelId)
  170. ) {
  171. throw new LocalModelProviderConfigValidationError('Invalid MiniMax model context target');
  172. }
  173. if (input.providerId === MINIMAX_API_PROVIDER_ID) {
  174. const options = MINIMAX_API_MODEL_CATALOG[modelId]?.contextWindowOptions;
  175. if (!options?.includes(input.contextLimit)) {
  176. throw new LocalModelProviderConfigValidationError('Invalid MiniMax API context limit');
  177. }
  178. }
  179. const outcome = await withLockedConfig(async (raw, currentConfig) => {
  180. const currentContext =
  181. input.providerId === MANAGED_MINIMAX_PROVIDER_ID
  182. ? currentConfig.provider?.[input.providerId]?.models?.[modelId]?.limit?.context
  183. : currentMinimaxApiContext(currentConfig, modelId);
  184. if (currentContext !== input.expectedContextLimit) {
  185. return { write: false, value: false };
  186. }
  187. if (!(await beforeCommit(currentConfig))) return { write: false, value: false };
  188. const path =
  189. input.providerId === MANAGED_MINIMAX_PROVIDER_ID
  190. ? ['minimaxModelContextLimits', modelId]
  191. : ['minimax_api', 'modelContextLimits', modelId];
  192. setNestedValue(raw, path, input.contextLimit);
  193. return { write: true, value: true };
  194. });
  195. return { config: outcome.config, updated: outcome.value };
  196. }
  197. function currentMinimaxApiContext(config: Config, modelId: string): number | undefined {
  198. const model = MINIMAX_API_MODEL_CATALOG[modelId];
  199. const override = config.minimax_api?.modelContextLimits?.[modelId];
  200. return override !== undefined && model?.contextWindowOptions?.includes(override)
  201. ? override
  202. : model?.limit?.context;
  203. }
  204. async function withLockedConfig<T>(
  205. operation: (
  206. raw: Record<string, unknown>,
  207. currentConfig: Config,
  208. ) => Promise<{ readonly write: boolean; readonly value: T }>,
  209. ): Promise<{ readonly config: Config; readonly value: T }> {
  210. const configPath = getConfigPath();
  211. let release: (() => Promise<void>) | undefined;
  212. try {
  213. await fs.promises.mkdir(dirname(configPath), { recursive: true });
  214. await fs.promises.writeFile(configPath, '', { flag: 'a', mode: LOCAL_CONFIG_FILE_MODE });
  215. await fs.promises.chmod(configPath, LOCAL_CONFIG_FILE_MODE);
  216. release = await lockfile.lock(configPath, {
  217. stale: 10_000,
  218. retries: { retries: 20, factor: 1, minTimeout: 5, maxTimeout: 25 },
  219. });
  220. const raw = readLocalRawConfig(configPath);
  221. resetConfig();
  222. const outcome = await operation(raw, getConfig());
  223. if (outcome.write) {
  224. assertSafeConfigRecord(raw);
  225. await atomicWriteFile(configPath, yaml.dump(raw, { indent: 2, lineWidth: -1, noRefs: true }));
  226. resetConfig();
  227. }
  228. return { config: getConfig(), value: outcome.value };
  229. } catch (error) {
  230. if (
  231. error instanceof LocalModelProviderConfigValidationError ||
  232. error instanceof LocalModelProviderConfigWriteError
  233. ) {
  234. throw error;
  235. }
  236. throw new LocalModelProviderConfigWriteError();
  237. } finally {
  238. await release?.().catch(() => undefined);
  239. }
  240. }
  241. async function atomicWriteFile(filePath: string, content: string): Promise<void> {
  242. const tmpPath = join(dirname(filePath), `.config-tmp-${randomBytes(6).toString('hex')}`);
  243. let created = false;
  244. try {
  245. const mode = LOCAL_CONFIG_FILE_MODE;
  246. const temporary = await fs.promises.open(tmpPath, 'wx', mode);
  247. created = true;
  248. try {
  249. await temporary.writeFile(content, 'utf-8');
  250. await temporary.chmod(mode);
  251. } finally {
  252. await temporary.close();
  253. }
  254. await fs.promises.rename(tmpPath, filePath);
  255. } catch {
  256. if (created) await fs.promises.unlink(tmpPath).catch(() => undefined);
  257. throw new LocalModelProviderConfigWriteError();
  258. }
  259. }
  260. function readLocalRawConfig(configPath: string): Record<string, unknown> {
  261. if (!existsSync(configPath)) return {};
  262. try {
  263. const parsed = yaml.load(readFileSync(configPath, 'utf-8'));
  264. return isPlainRecord(parsed) ? parsed : {};
  265. } catch {
  266. return {};
  267. }
  268. }
  269. function withoutEmptyEntries(
  270. subtree: Record<string, unknown> | undefined,
  271. ): Record<string, unknown> | undefined {
  272. if (!subtree) return undefined;
  273. return Object.fromEntries(Object.entries(subtree).filter(([, value]) => isPlainRecord(value)));
  274. }
  275. function setOptionalString(
  276. raw: Record<string, unknown>,
  277. key: 'minimaxModelSource' | 'defaultModel' | 'defaultModelVariant',
  278. value: string | undefined,
  279. ): void {
  280. if (value === undefined) delete raw[key];
  281. else raw[key] = value;
  282. }
  283. function setNestedValue(
  284. root: Record<string, unknown>,
  285. path: readonly string[],
  286. value: unknown,
  287. ): void {
  288. const key = path.at(-1);
  289. if (!key) throw new LocalModelProviderConfigValidationError('Invalid config path');
  290. let target = root;
  291. for (const segment of path.slice(0, -1)) {
  292. if (!segment || DANGEROUS_CONFIG_PATH_SEGMENTS.has(segment)) {
  293. throw new LocalModelProviderConfigValidationError('Invalid config path');
  294. }
  295. const current = target[segment];
  296. if (isPlainRecord(current)) target = current;
  297. else {
  298. const child: Record<string, unknown> = {};
  299. target[segment] = child;
  300. target = child;
  301. }
  302. }
  303. target[key] = value;
  304. }
  305. function assertSafeConfigRecord(record: Record<string, unknown>): void {
  306. for (const [key, value] of Object.entries(record)) {
  307. if (!key || DANGEROUS_CONFIG_PATH_SEGMENTS.has(key)) {
  308. throw new LocalModelProviderConfigValidationError(
  309. `Local runtime cannot update config field segment "${key}"`,
  310. );
  311. }
  312. if (isPlainRecord(value)) assertSafeConfigRecord(value);
  313. }
  314. }
  315. function isPlainRecord(value: unknown): value is Record<string, unknown> {
  316. return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
  317. }