prefix-update.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872
  1. import { createHash, randomUUID } from 'node:crypto';
  2. import {
  3. cpSync,
  4. existsSync,
  5. mkdirSync,
  6. readdirSync,
  7. readFileSync,
  8. renameSync,
  9. rmSync,
  10. writeFileSync,
  11. } from 'node:fs';
  12. import path from 'node:path';
  13. import spawn from 'cross-spawn';
  14. import { resolveMcodeNpmPrefixInstall, type McodeNpmPackageName } from './install-source.js';
  15. const PENDING_UPDATE_FILE = '.mcode-update-pending.json';
  16. const ACTIVE_PROCESS_DIRECTORY = '.mcode-active';
  17. const ACTIVATOR_LEASE_FILE = '.mcode-update-activator.json';
  18. const ACTIVATION_STATUS_FILE = '.mcode-update-activation-status.json';
  19. const PENDING_UPDATE_SCHEMA_VERSION = 1;
  20. const ACTIVATOR_LEASE_SCHEMA_VERSION = 1;
  21. const ACTIVATION_STATUS_SCHEMA_VERSION = 1;
  22. const RESTART_PARENT_WAIT_TIMEOUT_MS = 30_000;
  23. export const MCODE_UPDATE_PARENT_PID_ENV = 'MCODE_UPDATE_PARENT_PID';
  24. type McodePlatformPath = typeof path.posix | typeof path.win32;
  25. export interface McodePrefixPackageMetadata {
  26. readonly packageRoot: string;
  27. readonly version: string;
  28. readonly binEntry: string;
  29. readonly mcodeToolsBinEntry: string;
  30. }
  31. export interface McodePrefixLauncherPair {
  32. readonly activePath: string;
  33. readonly stagedPath: string;
  34. readonly backupPath: string;
  35. }
  36. export interface McodePrefixUpdateActivation {
  37. readonly stagingPrefix: string;
  38. readonly activePrefix: string;
  39. readonly activeModulesRoot: string;
  40. readonly stagedModulesRoot: string;
  41. readonly backupModulesRoot: string;
  42. readonly packageName: McodeNpmPackageName;
  43. readonly expectedVersion: string;
  44. readonly launchers: readonly McodePrefixLauncherPair[];
  45. }
  46. export function createMcodePrefixUpdateStagingPrefix(
  47. activePrefix: string,
  48. version: string,
  49. platform: NodeJS.Platform = process.platform,
  50. ): string {
  51. const platformPath = platformPathFor(platform);
  52. return platformPath.join(
  53. platformPath.dirname(activePrefix),
  54. `.${platformPath.basename(activePrefix)}.update-${version}-${process.pid}-${randomUUID()}`,
  55. );
  56. }
  57. export function resolveMcodePrefixModulesRoot(
  58. prefix: string,
  59. platform: NodeJS.Platform = process.platform,
  60. ): string {
  61. const platformPath = platformPathFor(platform);
  62. return platform === 'win32'
  63. ? platformPath.join(prefix, 'node_modules')
  64. : platformPath.join(prefix, 'lib', 'node_modules');
  65. }
  66. export function resolveMcodePrefixPackageRoot(
  67. prefix: string,
  68. packageName: McodeNpmPackageName,
  69. platform: NodeJS.Platform = process.platform,
  70. ): string {
  71. const platformPath = platformPathFor(platform);
  72. return platformPath.join(
  73. resolveMcodePrefixModulesRoot(prefix, platform),
  74. ...packageName.split('/'),
  75. );
  76. }
  77. export function resolveMcodePrefixLauncherPairs(
  78. activePrefix: string,
  79. stagingPrefix: string,
  80. platform: NodeJS.Platform = process.platform,
  81. ): readonly McodePrefixLauncherPair[] {
  82. const platformPath = platformPathFor(platform);
  83. const names = platform === 'win32' ? ['mcode.cmd', 'mcode.ps1'] : ['mcode'];
  84. const directory = platform === 'win32' ? '' : 'bin';
  85. return names.map((name) => {
  86. const activePath = platformPath.join(activePrefix, directory, name);
  87. return {
  88. activePath,
  89. stagedPath: platformPath.join(stagingPrefix, directory, name),
  90. backupPath: `${activePath}.mcode-update-backup`,
  91. };
  92. });
  93. }
  94. export function prepareMcodePrefixUpdateStaging(
  95. activePrefix: string,
  96. stagingPrefix: string,
  97. platform: NodeJS.Platform = process.platform,
  98. ): void {
  99. const activeModulesRoot = resolveMcodePrefixModulesRoot(activePrefix, platform);
  100. const stagedModulesRoot = resolveMcodePrefixModulesRoot(stagingPrefix, platform);
  101. if (!existsSync(activeModulesRoot)) {
  102. throw new Error(`Active MCode modules directory is missing: ${activeModulesRoot}`);
  103. }
  104. cpSync(activeModulesRoot, stagedModulesRoot, { recursive: true, dereference: false });
  105. for (const launcher of resolveMcodePrefixLauncherPairs(activePrefix, stagingPrefix, platform)) {
  106. if (!existsSync(launcher.activePath)) continue;
  107. mkdirSync(path.dirname(launcher.stagedPath), { recursive: true });
  108. cpSync(launcher.activePath, launcher.stagedPath, { dereference: false, force: true });
  109. }
  110. }
  111. export function readMcodePrefixPackageMetadata(
  112. prefix: string,
  113. packageName: McodeNpmPackageName,
  114. platform: NodeJS.Platform = process.platform,
  115. ): McodePrefixPackageMetadata {
  116. const packageRoot = resolveMcodePrefixPackageRoot(prefix, packageName, platform);
  117. const manifestFile = path.join(packageRoot, 'package.json');
  118. const manifest = JSON.parse(readFileSync(manifestFile, 'utf8')) as {
  119. name?: unknown;
  120. version?: unknown;
  121. bin?: unknown;
  122. };
  123. const binEntry = readMcodeBinEntry(manifest.bin, 'mcode');
  124. const mcodeToolsBinEntry = readMcodeBinEntry(manifest.bin, 'mcode-tools');
  125. if (
  126. manifest.name !== packageName ||
  127. typeof manifest.version !== 'string' ||
  128. !binEntry ||
  129. !mcodeToolsBinEntry
  130. ) {
  131. throw new Error(`MCode package metadata is invalid at ${manifestFile}.`);
  132. }
  133. return { packageRoot, version: manifest.version, binEntry, mcodeToolsBinEntry };
  134. }
  135. export async function validateMcodePrefixPackage(
  136. prefix: string,
  137. metadata: McodePrefixPackageMetadata,
  138. runtimeExecutable: string,
  139. expectedVersion: string,
  140. ): Promise<void> {
  141. await validateMcodePrefixEntry(
  142. prefix,
  143. runtimeExecutable,
  144. [path.join(metadata.packageRoot, ...metadata.binEntry.split('/')), '--version'],
  145. 'MCode',
  146. (output) => output === expectedVersion,
  147. );
  148. await validateMcodePrefixEntry(
  149. prefix,
  150. runtimeExecutable,
  151. [path.join(metadata.packageRoot, ...metadata.mcodeToolsBinEntry.split('/')), '--version'],
  152. 'mcode-tools',
  153. (output) => output.length > 0,
  154. );
  155. // --version does not load the native runtime. Validate it with the exact Node
  156. // executable that the new release launcher will use, independently of npm's Node.
  157. await validateMcodePrefixEntry(
  158. prefix,
  159. runtimeExecutable,
  160. [
  161. '--input-type=module',
  162. '--eval',
  163. `
  164. import { createRequire } from 'node:module';
  165. const require = createRequire(process.argv[1]);
  166. const Database = require('better-sqlite3');
  167. const database = new Database(':memory:');
  168. try {
  169. if (database.prepare('SELECT 1 AS value').get()?.value !== 1) {
  170. throw new Error('SQLite validation returned an unexpected result.');
  171. }
  172. } finally { database.close(); }
  173. `,
  174. path.join(metadata.packageRoot, 'package.json'),
  175. ],
  176. 'SQLite',
  177. () => true,
  178. );
  179. }
  180. function validateMcodePrefixEntry(
  181. prefix: string,
  182. runtimeExecutable: string,
  183. args: readonly string[],
  184. commandName: 'MCode' | 'mcode-tools' | 'SQLite',
  185. outputIsValid: (output: string) => boolean,
  186. ): Promise<void> {
  187. return new Promise((resolve, reject) => {
  188. const child = spawn(runtimeExecutable, [...args], {
  189. cwd: prefix,
  190. env: process.env,
  191. stdio: ['ignore', 'pipe', 'pipe'],
  192. windowsHide: true,
  193. timeout: 30_000,
  194. killSignal: 'SIGKILL',
  195. });
  196. const stdout: Buffer[] = [];
  197. const stderr: Buffer[] = [];
  198. child.stdout?.on('data', (chunk: Buffer) => stdout.push(chunk));
  199. child.stderr?.on('data', (chunk: Buffer) => stderr.push(chunk));
  200. child.once('error', reject);
  201. child.once('close', (code, signal) => {
  202. const output = Buffer.concat(stdout).toString('utf8').trim();
  203. if (code === 0 && outputIsValid(output)) return resolve();
  204. const details = Buffer.concat(stderr).toString('utf8').trim() || output;
  205. reject(
  206. new Error(
  207. `Staged ${commandName} validation failed (${signal ? `signal ${signal}` : `exit ${String(code)}`})` +
  208. `${details ? `: ${details}` : ''}`,
  209. ),
  210. );
  211. });
  212. });
  213. }
  214. export function writeMcodePrefixUpdatePending(activation: McodePrefixUpdateActivation): string {
  215. const pendingFile = path.join(activation.activePrefix, PENDING_UPDATE_FILE);
  216. const temporaryFile = `${pendingFile}.tmp-${process.pid}-${randomUUID()}`;
  217. const contents = `${JSON.stringify(
  218. { schemaVersion: PENDING_UPDATE_SCHEMA_VERSION, ...activation, createdAtMs: Date.now() },
  219. null,
  220. 2,
  221. )}\n`;
  222. try {
  223. writeFileSync(temporaryFile, contents, { mode: 0o600 });
  224. renameSync(temporaryFile, pendingFile);
  225. } catch (error) {
  226. rmSync(temporaryFile, { force: true });
  227. throw error;
  228. }
  229. return pendingFile;
  230. }
  231. export async function scheduleMcodePrefixUpdate(
  232. pendingFile: string,
  233. runtimeExecutable = process.execPath,
  234. parentPid = process.pid,
  235. restartArgs: readonly string[] = [],
  236. environment: NodeJS.ProcessEnv = process.env,
  237. restartCwd = process.cwd(),
  238. ): Promise<void> {
  239. const { contents: pendingContents, pending } = readPendingUpdateFile(pendingFile);
  240. if (path.resolve(pendingFile) !== path.resolve(pending.activePrefix, PENDING_UPDATE_FILE)) {
  241. throw new Error(`MCode pending update file is outside its active prefix: ${pendingFile}`);
  242. }
  243. const pendingDigest = createHash('sha256').update(pendingContents).digest('hex');
  244. const leaseFile = path.join(pending.activePrefix, ACTIVATOR_LEASE_FILE);
  245. if (!acquireMcodePrefixActivatorLease(leaseFile, pendingDigest)) return;
  246. const helperFile = path.join(pending.activePrefix, '.mcode-update-activator.cjs');
  247. try {
  248. writeMcodePrefixActivationStatus(pending.activePrefix, pendingDigest, 'scheduled');
  249. writeFileSync(helperFile, prefixActivatorSource(), { mode: 0o700 });
  250. const child = spawn(
  251. runtimeExecutable,
  252. [helperFile, pendingFile, pendingDigest, String(parentPid), restartCwd, ...restartArgs],
  253. {
  254. cwd: pending.activePrefix,
  255. env: environment,
  256. detached: true,
  257. stdio: restartArgs.length > 0 ? 'inherit' : 'ignore',
  258. windowsHide: true,
  259. },
  260. );
  261. await new Promise<void>((resolve, reject) => {
  262. child.once('error', reject);
  263. child.once('spawn', resolve);
  264. });
  265. child.unref();
  266. } catch (error) {
  267. try {
  268. writeMcodePrefixActivationStatus(pending.activePrefix, pendingDigest, 'failed', error);
  269. } catch {
  270. // Preserve the scheduling failure when its diagnostic sidecar cannot be written.
  271. }
  272. removeMcodePrefixActivatorLease(leaseFile, pendingDigest, process.pid);
  273. throw error;
  274. }
  275. }
  276. export async function schedulePendingMcodePrefixUpdate(
  277. entryFile = process.argv[1],
  278. runtimeExecutable = process.execPath,
  279. parentPid = process.pid,
  280. restartArgs: readonly string[] = [],
  281. environment: NodeJS.ProcessEnv = process.env,
  282. ): Promise<boolean> {
  283. const prefix = resolvePrefixFromEntryFile(entryFile);
  284. if (!prefix) return false;
  285. const pendingFile = path.join(prefix, PENDING_UPDATE_FILE);
  286. if (!existsSync(pendingFile)) return false;
  287. await scheduleMcodePrefixUpdate(
  288. pendingFile,
  289. runtimeExecutable,
  290. parentPid,
  291. restartArgs,
  292. environment,
  293. );
  294. return true;
  295. }
  296. export function removeMcodePrefixUpdatePending(pendingFile: string): void {
  297. rmSync(pendingFile, { force: true });
  298. }
  299. export function removeMcodePrefixUpdateStaging(stagingPrefix: string): void {
  300. rmSync(stagingPrefix, { recursive: true, force: true, maxRetries: 4, retryDelay: 50 });
  301. }
  302. export interface McodePendingPrefixUpdateInspection {
  303. readonly pendingFile: string;
  304. readonly activation: McodePrefixUpdateActivation;
  305. readonly state: 'staged' | 'activated';
  306. }
  307. export function inspectPendingMcodePrefixUpdate(
  308. entryFile = process.argv[1],
  309. ): McodePendingPrefixUpdateInspection | undefined {
  310. const prefix = resolvePrefixFromEntryFile(entryFile);
  311. if (!prefix) return undefined;
  312. const pendingFile = path.join(prefix, PENDING_UPDATE_FILE);
  313. if (!existsSync(pendingFile)) return undefined;
  314. const { pending } = readPendingUpdateFile(pendingFile);
  315. if (path.resolve(pendingFile) !== path.resolve(pending.activePrefix, PENDING_UPDATE_FILE)) {
  316. throw new Error(`MCode pending update file is outside its active prefix: ${pendingFile}`);
  317. }
  318. const state = classifyRecoverableMcodePrefixUpdateArtifacts(pending);
  319. if (!state) {
  320. throw new Error(`MCode pending update artifacts are incomplete at ${pendingFile}.`);
  321. }
  322. return {
  323. pendingFile,
  324. activation: pending,
  325. state,
  326. };
  327. }
  328. function classifyRecoverableMcodePrefixUpdateArtifacts(
  329. pending: McodePrefixUpdateActivation,
  330. ): 'staged' | 'activated' | undefined {
  331. if (pending.launchers.length === 0) return undefined;
  332. const activeMatches = pendingPackageMatches(
  333. pending.activeModulesRoot,
  334. pending.packageName,
  335. pending.expectedVersion,
  336. );
  337. if (
  338. activeMatches &&
  339. pending.launchers.every(
  340. (launcher) => existsSync(launcher.activePath) || existsSync(launcher.stagedPath),
  341. )
  342. ) {
  343. return 'activated';
  344. }
  345. const stagedMatches = pendingPackageMatches(
  346. pending.stagedModulesRoot,
  347. pending.packageName,
  348. pending.expectedVersion,
  349. );
  350. if (!stagedMatches) return undefined;
  351. const backupExists = existsSync(pending.backupModulesRoot);
  352. return pending.launchers.every(
  353. (launcher) =>
  354. existsSync(launcher.stagedPath) ||
  355. (backupExists && existsSync(launcher.activePath) && existsSync(launcher.backupPath)),
  356. )
  357. ? 'staged'
  358. : undefined;
  359. }
  360. function pendingPackageMatches(
  361. modulesRoot: string,
  362. packageName: McodeNpmPackageName,
  363. expectedVersion: string,
  364. ): boolean {
  365. try {
  366. const manifest = JSON.parse(
  367. readFileSync(path.join(modulesRoot, ...packageName.split('/'), 'package.json'), 'utf8'),
  368. ) as { name?: unknown; version?: unknown };
  369. return manifest.name === packageName && manifest.version === expectedVersion;
  370. } catch {
  371. return false;
  372. }
  373. }
  374. export interface McodePrefixProcessPreparation {
  375. readonly remove: () => void;
  376. }
  377. export async function prepareMcodePrefixProcess(
  378. entryFile = process.argv[1],
  379. environment: NodeJS.ProcessEnv = process.env,
  380. ): Promise<McodePrefixProcessPreparation> {
  381. const parentPid = Number(environment[MCODE_UPDATE_PARENT_PID_ENV]);
  382. if (Number.isSafeInteger(parentPid) && parentPid > 0) await waitForProcessExit(parentPid);
  383. return {
  384. remove: registerMcodePrefixProcess(entryFile) ?? (() => undefined),
  385. };
  386. }
  387. async function waitForProcessExit(pid: number): Promise<void> {
  388. const deadline = Date.now() + RESTART_PARENT_WAIT_TIMEOUT_MS;
  389. while (isProcessAlive(pid)) {
  390. if (Date.now() >= deadline) {
  391. throw new Error(`MCode restart waited too long for parent process ${pid} to exit.`);
  392. }
  393. await new Promise((resolve) => setTimeout(resolve, 100));
  394. }
  395. }
  396. function isProcessAlive(pid: number): boolean {
  397. try {
  398. process.kill(pid, 0);
  399. return true;
  400. } catch (error) {
  401. return (error as NodeJS.ErrnoException).code === 'EPERM';
  402. }
  403. }
  404. interface McodePrefixActivatorLease {
  405. readonly schemaVersion: number;
  406. readonly journalDigest: string;
  407. readonly pid: number;
  408. readonly startedAtMs: number;
  409. }
  410. function acquireMcodePrefixActivatorLease(leaseFile: string, journalDigest: string): boolean {
  411. for (let attempt = 0; attempt < 3; attempt += 1) {
  412. const lease: McodePrefixActivatorLease = {
  413. schemaVersion: ACTIVATOR_LEASE_SCHEMA_VERSION,
  414. journalDigest,
  415. pid: process.pid,
  416. startedAtMs: Date.now(),
  417. };
  418. try {
  419. writeFileSync(leaseFile, `${JSON.stringify(lease)}\n`, { flag: 'wx', mode: 0o600 });
  420. return true;
  421. } catch (error) {
  422. if ((error as NodeJS.ErrnoException).code !== 'EEXIST') throw error;
  423. }
  424. const existing = readMcodePrefixActivatorLease(leaseFile);
  425. if (existing && isProcessAlive(existing.pid)) {
  426. if (existing.journalDigest === journalDigest) return false;
  427. throw new Error('Another MCode prefix activator is running for a different journal.');
  428. }
  429. rmSync(leaseFile, { force: true });
  430. }
  431. throw new Error(`MCode prefix activator lease could not be acquired at ${leaseFile}.`);
  432. }
  433. function readMcodePrefixActivatorLease(leaseFile: string): McodePrefixActivatorLease | undefined {
  434. try {
  435. const value = JSON.parse(readFileSync(leaseFile, 'utf8')) as Partial<McodePrefixActivatorLease>;
  436. if (
  437. value.schemaVersion !== ACTIVATOR_LEASE_SCHEMA_VERSION ||
  438. typeof value.journalDigest !== 'string' ||
  439. !Number.isSafeInteger(value.pid) ||
  440. (value.pid ?? 0) <= 0 ||
  441. typeof value.startedAtMs !== 'number'
  442. ) {
  443. return undefined;
  444. }
  445. return value as McodePrefixActivatorLease;
  446. } catch {
  447. return undefined;
  448. }
  449. }
  450. function removeMcodePrefixActivatorLease(
  451. leaseFile: string,
  452. journalDigest: string,
  453. pid: number,
  454. ): void {
  455. const lease = readMcodePrefixActivatorLease(leaseFile);
  456. if (lease?.journalDigest !== journalDigest || lease.pid !== pid) return;
  457. rmSync(leaseFile, { force: true });
  458. }
  459. function writeMcodePrefixActivationStatus(
  460. activePrefix: string,
  461. journalDigest: string,
  462. state: 'scheduled' | 'failed',
  463. error?: unknown,
  464. ): void {
  465. const statusFile = path.join(activePrefix, ACTIVATION_STATUS_FILE);
  466. const temporaryFile = `${statusFile}.tmp-${process.pid}-${randomUUID()}`;
  467. const errorMessage =
  468. error instanceof Error ? error.message : error === undefined ? undefined : String(error);
  469. const status = {
  470. schemaVersion: ACTIVATION_STATUS_SCHEMA_VERSION,
  471. journalDigest,
  472. state,
  473. updatedAtMs: Date.now(),
  474. ...(errorMessage ? { error: errorMessage.slice(0, 2_000) } : {}),
  475. };
  476. try {
  477. writeFileSync(temporaryFile, `${JSON.stringify(status)}\n`, { mode: 0o600 });
  478. rmSync(statusFile, { force: true });
  479. renameSync(temporaryFile, statusFile);
  480. } catch (statusError) {
  481. rmSync(temporaryFile, { force: true });
  482. throw statusError;
  483. }
  484. }
  485. export function registerMcodePrefixProcess(entryFile = process.argv[1]): (() => void) | undefined {
  486. const prefix = resolvePrefixFromEntryFile(entryFile);
  487. if (!prefix) return undefined;
  488. const directory = path.join(prefix, ACTIVE_PROCESS_DIRECTORY);
  489. mkdirSync(directory, { recursive: true, mode: 0o700 });
  490. const marker = path.join(directory, `${process.pid}.json`);
  491. let removed = false;
  492. const removeOnExit = () => rmSync(marker, { force: true });
  493. const remove = () => {
  494. if (removed) return;
  495. removed = true;
  496. process.off('exit', removeOnExit);
  497. rmSync(marker, { force: true });
  498. };
  499. writeFileSync(marker, `${JSON.stringify({ pid: process.pid, startedAtMs: Date.now() })}\n`, {
  500. mode: 0o600,
  501. });
  502. process.once('exit', removeOnExit);
  503. return remove;
  504. }
  505. export function countMcodePrefixUpdateBlockers(
  506. activePrefix: string,
  507. currentPid = process.pid,
  508. ): number | undefined {
  509. const directory = path.join(activePrefix, ACTIVE_PROCESS_DIRECTORY);
  510. if (!existsSync(directory)) return 0;
  511. let markerNames: string[];
  512. try {
  513. markerNames = readdirSync(directory);
  514. } catch {
  515. return undefined;
  516. }
  517. let blockers = 0;
  518. for (const name of markerNames) {
  519. if (!name.endsWith('.json')) continue;
  520. const pid = Number(name.slice(0, -5));
  521. if (!Number.isSafeInteger(pid) || pid <= 0 || pid === currentPid) continue;
  522. if (isProcessAlive(pid)) {
  523. blockers += 1;
  524. continue;
  525. }
  526. try {
  527. rmSync(path.join(directory, name), { force: true });
  528. } catch {
  529. // A stale marker does not block activation; the detached helper also retries cleanup.
  530. }
  531. }
  532. return blockers;
  533. }
  534. function resolvePrefixFromEntryFile(entryFile: string | undefined): string | undefined {
  535. if (!entryFile) return undefined;
  536. try {
  537. const detected = resolveMcodeNpmPrefixInstall(entryFile);
  538. if (detected) return detected.prefix;
  539. } catch {
  540. // Fall through to pending-journal recovery for legacy prefixes whose receipt is missing.
  541. }
  542. let current = path.dirname(entryFile);
  543. for (;;) {
  544. const receiptFile = path.join(current, 'install.json');
  545. if (existsSync(receiptFile)) {
  546. try {
  547. const receipt = JSON.parse(readFileSync(receiptFile, 'utf8')) as {
  548. updateOwner?: unknown;
  549. prefix?: unknown;
  550. };
  551. if (receipt.updateOwner === 'npm-prefix' && typeof receipt.prefix === 'string') {
  552. return receipt.prefix;
  553. }
  554. } catch {
  555. return undefined;
  556. }
  557. }
  558. const pendingFile = path.join(current, PENDING_UPDATE_FILE);
  559. if (existsSync(pendingFile)) {
  560. try {
  561. const pending = readPendingUpdate(pendingFile);
  562. return path.resolve(pending.activePrefix) === path.resolve(current)
  563. ? pending.activePrefix
  564. : undefined;
  565. } catch {
  566. return undefined;
  567. }
  568. }
  569. const parent = path.dirname(current);
  570. if (parent === current) return undefined;
  571. current = parent;
  572. }
  573. }
  574. function readPendingUpdate(file: string): McodePrefixUpdateActivation & { schemaVersion: number } {
  575. return readPendingUpdateFile(file).pending;
  576. }
  577. function readPendingUpdateFile(file: string): {
  578. readonly contents: string;
  579. readonly pending: McodePrefixUpdateActivation & { schemaVersion: number };
  580. } {
  581. const contents = readFileSync(file, 'utf8');
  582. const value = JSON.parse(contents) as Partial<
  583. McodePrefixUpdateActivation & { schemaVersion: number }
  584. >;
  585. if (
  586. value.schemaVersion !== PENDING_UPDATE_SCHEMA_VERSION ||
  587. typeof value.activePrefix !== 'string' ||
  588. typeof value.stagingPrefix !== 'string' ||
  589. typeof value.activeModulesRoot !== 'string' ||
  590. typeof value.stagedModulesRoot !== 'string' ||
  591. typeof value.backupModulesRoot !== 'string' ||
  592. (value.packageName !== '@minimax/code' && value.packageName !== '@minimax-ai/code') ||
  593. typeof value.expectedVersion !== 'string' ||
  594. !Array.isArray(value.launchers) ||
  595. !value.launchers.every(
  596. (launcher) =>
  597. launcher !== null &&
  598. typeof launcher === 'object' &&
  599. 'activePath' in launcher &&
  600. typeof launcher.activePath === 'string' &&
  601. 'stagedPath' in launcher &&
  602. typeof launcher.stagedPath === 'string' &&
  603. 'backupPath' in launcher &&
  604. typeof launcher.backupPath === 'string',
  605. )
  606. ) {
  607. throw new Error(`MCode pending update metadata is invalid at ${file}.`);
  608. }
  609. const pending = value as McodePrefixUpdateActivation & { schemaVersion: number };
  610. const expectedActiveModulesRoot = resolveMcodePrefixModulesRoot(
  611. pending.activePrefix,
  612. process.platform,
  613. );
  614. const expectedStagedModulesRoot = resolveMcodePrefixModulesRoot(
  615. pending.stagingPrefix,
  616. process.platform,
  617. );
  618. const expectedLaunchers = resolveMcodePrefixLauncherPairs(
  619. pending.activePrefix,
  620. pending.stagingPrefix,
  621. process.platform,
  622. );
  623. if (
  624. path.resolve(pending.activePrefix) === path.resolve(pending.stagingPrefix) ||
  625. !sameResolvedPath(pending.activeModulesRoot, expectedActiveModulesRoot) ||
  626. !sameResolvedPath(pending.stagedModulesRoot, expectedStagedModulesRoot) ||
  627. !sameResolvedPath(
  628. pending.backupModulesRoot,
  629. `${expectedActiveModulesRoot}.mcode-update-backup`,
  630. ) ||
  631. pending.launchers.length !== expectedLaunchers.length ||
  632. pending.launchers.some((launcher, index) => {
  633. const expected = expectedLaunchers[index];
  634. return (
  635. !expected ||
  636. !sameResolvedPath(launcher.activePath, expected.activePath) ||
  637. !sameResolvedPath(launcher.stagedPath, expected.stagedPath) ||
  638. !sameResolvedPath(launcher.backupPath, expected.backupPath)
  639. );
  640. }) ||
  641. !isPathInside(pending.activePrefix, pending.activeModulesRoot) ||
  642. !isPathInside(pending.activePrefix, pending.backupModulesRoot) ||
  643. !isPathInside(pending.stagingPrefix, pending.stagedModulesRoot) ||
  644. pending.launchers.some(
  645. (launcher) =>
  646. !isPathInside(pending.activePrefix, launcher.activePath) ||
  647. !isPathInside(pending.activePrefix, launcher.backupPath) ||
  648. !isPathInside(pending.stagingPrefix, launcher.stagedPath),
  649. )
  650. ) {
  651. throw new Error(`MCode pending update paths are invalid at ${file}.`);
  652. }
  653. return { contents, pending };
  654. }
  655. function isPathInside(root: string, candidate: string): boolean {
  656. const relative = path.relative(path.resolve(root), path.resolve(candidate));
  657. return relative !== '' && !relative.startsWith('..') && !path.isAbsolute(relative);
  658. }
  659. function sameResolvedPath(left: string, right: string): boolean {
  660. return path.resolve(left) === path.resolve(right);
  661. }
  662. function platformPathFor(platform: NodeJS.Platform): McodePlatformPath {
  663. return platform === 'win32' ? path.win32 : path.posix;
  664. }
  665. function readMcodeBinEntry(value: unknown, name: 'mcode' | 'mcode-tools'): string | undefined {
  666. const entry =
  667. typeof value === 'string' && name === 'mcode'
  668. ? value
  669. : value && typeof value === 'object' && name in value
  670. ? (value as Record<string, unknown>)[name]
  671. : undefined;
  672. if (typeof entry !== 'string' || !entry.trim()) return undefined;
  673. const normalized = entry.replaceAll('\\', '/').replace(/^\.\//u, '');
  674. if (normalized.startsWith('/') || normalized.split('/').some((segment) => segment === '..'))
  675. return undefined;
  676. return normalized;
  677. }
  678. function prefixActivatorSource(): string {
  679. return String.raw`'use strict';
  680. const fs = require('node:fs');
  681. const path = require('node:path');
  682. const cp = require('node:child_process');
  683. const crypto = require('node:crypto');
  684. const pendingFile = process.argv[2];
  685. const pendingDigest = process.argv[3];
  686. const parentPid = Number(process.argv[4]);
  687. const restartCwd = process.argv[5];
  688. const restartArgs = process.argv.slice(6);
  689. const pendingContents = fs.readFileSync(pendingFile, 'utf8');
  690. if (crypto.createHash('sha256').update(pendingContents).digest('hex') !== pendingDigest) throw new Error('MCode pending update journal changed after scheduling.');
  691. const pending = JSON.parse(pendingContents);
  692. const leaseFile = path.join(pending.activePrefix, '.mcode-update-activator.json');
  693. const statusFile = path.join(pending.activePrefix, '.mcode-update-activation-status.json');
  694. fs.writeFileSync(leaseFile, JSON.stringify({ schemaVersion: 1, journalDigest: pendingDigest, pid: process.pid, startedAtMs: Date.now() }) + '\n', { mode: 0o600 });
  695. const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
  696. const alive = (pid) => { try { process.kill(pid, 0); return true; } catch (error) { return error && error.code === 'EPERM'; } };
  697. const remove = (target) => { try { fs.rmSync(target, { recursive: true, force: true, maxRetries: 8, retryDelay: 100 }); } catch {} };
  698. const writeStatus = (state, error) => {
  699. const temporaryFile = statusFile + '.tmp-' + process.pid;
  700. const errorMessage = error === undefined ? undefined : String(error && error.message || error).slice(0, 2000);
  701. try {
  702. fs.writeFileSync(temporaryFile, JSON.stringify({ schemaVersion: 1, journalDigest: pendingDigest, state, updatedAtMs: Date.now(), ...(errorMessage ? { error: errorMessage } : {}) }) + '\n', { mode: 0o600 });
  703. fs.rmSync(statusFile, { force: true });
  704. fs.renameSync(temporaryFile, statusFile);
  705. } catch {
  706. remove(temporaryFile);
  707. }
  708. };
  709. // The pending journal is durable. Keep the detached handoff alive until every process using the
  710. // old prefix exits; a TUI-owned Runtime or another MCode session may legitimately take over 30s.
  711. async function waitForExit(pid) {
  712. while (alive(pid)) await sleep(100);
  713. }
  714. async function waitForMarkers() {
  715. const directory = path.join(pending.activePrefix, '.mcode-active');
  716. for (;;) {
  717. const blockers = fs.existsSync(directory) ? fs.readdirSync(directory).filter((name) => name.endsWith('.json')).filter((name) => {
  718. const pid = Number(name.slice(0, -5));
  719. if (!Number.isSafeInteger(pid) || pid <= 0 || pid === process.pid) return false;
  720. if (alive(pid)) return true;
  721. try { fs.rmSync(path.join(directory, name), { force: true }); } catch {}
  722. return false;
  723. }) : [];
  724. if (blockers.length === 0) return;
  725. await sleep(100);
  726. }
  727. }
  728. async function recoverInterrupted() {
  729. const activeVersion = (() => {
  730. try {
  731. return JSON.parse(fs.readFileSync(path.join(pending.activeModulesRoot, ...pending.packageName.split('/'), 'package.json'), 'utf8')).version;
  732. } catch { return undefined; }
  733. })();
  734. if (activeVersion === pending.expectedVersion) {
  735. const launchers = pending.launchers || [];
  736. const canCompleteLaunchers = launchers.every((launcher) => fs.existsSync(launcher.activePath) || fs.existsSync(launcher.stagedPath));
  737. if (canCompleteLaunchers) {
  738. for (const launcher of launchers) {
  739. if (!fs.existsSync(launcher.activePath)) fs.renameSync(launcher.stagedPath, launcher.activePath);
  740. }
  741. return true;
  742. }
  743. }
  744. if (!fs.existsSync(pending.backupModulesRoot)) return false;
  745. if (fs.existsSync(pending.activeModulesRoot)) {
  746. if (!fs.existsSync(pending.stagedModulesRoot)) fs.renameSync(pending.activeModulesRoot, pending.stagedModulesRoot);
  747. else remove(pending.activeModulesRoot);
  748. }
  749. fs.renameSync(pending.backupModulesRoot, pending.activeModulesRoot);
  750. for (const launcher of pending.launchers || []) {
  751. if (!fs.existsSync(launcher.backupPath)) continue;
  752. if (fs.existsSync(launcher.activePath)) {
  753. if (!fs.existsSync(launcher.stagedPath)) fs.renameSync(launcher.activePath, launcher.stagedPath);
  754. else remove(launcher.activePath);
  755. }
  756. fs.renameSync(launcher.backupPath, launcher.activePath);
  757. }
  758. return false;
  759. }
  760. function cleanup() {
  761. remove(pending.backupModulesRoot);
  762. for (const launcher of pending.launchers || []) remove(launcher.backupPath);
  763. fs.rmSync(pendingFile, { force: true });
  764. remove(pending.stagingPrefix);
  765. remove(path.join(pending.activePrefix, '.mcode-update-activator.cjs'));
  766. remove(leaseFile);
  767. }
  768. async function activate() {
  769. const alreadyActivated = await recoverInterrupted();
  770. const restart = (args) => new Promise((resolve, reject) => {
  771. if (args.length === 0) return resolve();
  772. const child = cp.spawn(process.execPath, args, {
  773. cwd: restartCwd, env: process.env, detached: true, stdio: 'inherit', windowsHide: false,
  774. });
  775. child.once('error', reject);
  776. child.once('spawn', () => { child.unref(); resolve(); });
  777. });
  778. if (alreadyActivated) {
  779. await restart(restartArgs);
  780. writeStatus('completed');
  781. cleanup();
  782. return;
  783. }
  784. const launchers = pending.launchers || [];
  785. let modulesMoved = false;
  786. const moved = [];
  787. const installed = [];
  788. try {
  789. const stagedManifest = JSON.parse(fs.readFileSync(path.join(pending.stagedModulesRoot, ...pending.packageName.split('/'), 'package.json'), 'utf8'));
  790. if (stagedManifest.name !== pending.packageName || stagedManifest.version !== pending.expectedVersion) throw new Error('Staged MCode package identity or version is invalid.');
  791. if (launchers.some((launcher) => !fs.existsSync(launcher.stagedPath))) throw new Error('Staged MCode launcher is missing.');
  792. fs.renameSync(pending.activeModulesRoot, pending.backupModulesRoot);
  793. modulesMoved = true;
  794. for (const launcher of launchers) { if (fs.existsSync(launcher.activePath)) { fs.renameSync(launcher.activePath, launcher.backupPath); moved.push(launcher); } }
  795. fs.renameSync(pending.stagedModulesRoot, pending.activeModulesRoot);
  796. for (const launcher of launchers) { if (fs.existsSync(launcher.stagedPath)) { fs.renameSync(launcher.stagedPath, launcher.activePath); installed.push(launcher); } }
  797. const manifest = JSON.parse(fs.readFileSync(path.join(pending.activeModulesRoot, ...pending.packageName.split('/'), 'package.json'), 'utf8'));
  798. if (manifest.name !== pending.packageName || manifest.version !== pending.expectedVersion) throw new Error('Activated MCode package identity or version is invalid.');
  799. await restart(restartArgs);
  800. writeStatus('completed');
  801. cleanup();
  802. } catch (error) {
  803. try {
  804. if (modulesMoved) {
  805. if (fs.existsSync(pending.activeModulesRoot)) {
  806. if (!fs.existsSync(pending.stagedModulesRoot)) fs.renameSync(pending.activeModulesRoot, pending.stagedModulesRoot);
  807. else remove(pending.activeModulesRoot);
  808. }
  809. if (fs.existsSync(pending.backupModulesRoot)) fs.renameSync(pending.backupModulesRoot, pending.activeModulesRoot);
  810. }
  811. for (const launcher of installed) { if (fs.existsSync(launcher.activePath)) { if (!fs.existsSync(launcher.stagedPath)) fs.renameSync(launcher.activePath, launcher.stagedPath); else remove(launcher.activePath); } }
  812. for (const launcher of moved) if (fs.existsSync(launcher.backupPath)) fs.renameSync(launcher.backupPath, launcher.activePath);
  813. } catch (rollbackError) {
  814. process.stderr.write(String(rollbackError && rollbackError.stack || rollbackError) + '\\n');
  815. }
  816. writeStatus('failed', error);
  817. process.stderr.write(String(error && error.stack || error) + '\\n');
  818. }
  819. }
  820. (async () => {
  821. writeStatus('waiting-parent');
  822. await waitForExit(parentPid);
  823. writeStatus('waiting-processes');
  824. await waitForMarkers();
  825. writeStatus('activating');
  826. await activate();
  827. })().catch((error) => { writeStatus('failed', error); process.stderr.write(String(error && error.stack || error) + '\n'); process.exitCode = 1; });
  828. `;
  829. }