mcode-tools-artifact.mjs 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. import { createHash } from 'node:crypto';
  2. import { mkdir, readFile, writeFile } from 'node:fs/promises';
  3. import path from 'node:path';
  4. import { Readable } from 'node:stream';
  5. import { setTimeout as sleep } from 'node:timers/promises';
  6. import { Parser } from 'tar';
  7. export const MCODE_TOOLS_ARTIFACT = Object.freeze({
  8. url: 'https://registry.npmjs.org/@minimax-ai/code/-/code-0.3.11.tgz',
  9. integrity: 'sBOd8yvQRVuQNoGvzCDwXKaj5rQxLI3gKnojWS4+0wnMU9IXtxObSqbfBxz30Lze/zitRtSG2v76iJGHOmHRUA==',
  10. version: '0.0.4',
  11. sha256: 'e5a59ec5362e395b519317ad6fecd99f6e92308b9d985be44b64eb2f2b73a722',
  12. });
  13. // Extract unchanged artifacts from the public release package without running package scripts or extracting other files to disk.
  14. export async function extractMcodeToolsArtifact(bytes) {
  15. if (createHash('sha512').update(bytes).digest('base64') !== MCODE_TOOLS_ARTIFACT.integrity)
  16. throw new Error('Public MCode archive integrity mismatch.');
  17. const files = new Map();
  18. const prefix = 'package/embedded/mcode-tools/';
  19. await new Promise((resolve, reject) => {
  20. const parser = new Parser({
  21. strict: true,
  22. onReadEntry(entry) {
  23. if (![`${prefix}cli.mjs`, `${prefix}manifest.json`, 'package/THIRD_PARTY_NOTICES.md'].includes(entry.path)) {
  24. entry.resume();
  25. return;
  26. }
  27. if (entry.type !== 'File' || files.has(entry.path)) {
  28. reject(new Error('Unexpected mcode-tools archive entry.'));
  29. entry.resume();
  30. return;
  31. }
  32. const chunks = [];
  33. entry.on('data', chunk => chunks.push(chunk));
  34. entry.on('end', () => files.set(entry.path, Buffer.concat(chunks)));
  35. },
  36. });
  37. parser.on('error', reject);
  38. parser.on('end', resolve);
  39. Readable.from([bytes]).pipe(parser);
  40. });
  41. const cli = files.get(`${prefix}cli.mjs`);
  42. const manifestBytes = files.get(`${prefix}manifest.json`);
  43. const notices = files.get('package/THIRD_PARTY_NOTICES.md');
  44. if (!cli || !manifestBytes || !notices) throw new Error('Public archive is missing mcode-tools or its notices.');
  45. const manifest = JSON.parse(manifestBytes.toString('utf8'));
  46. if (manifest.version !== MCODE_TOOLS_ARTIFACT.version || manifest.buildEnv !== 'prod' ||
  47. manifest.entry !== 'cli.mjs' || manifest.packageName !== '@minimax/mcode-tools' ||
  48. createHash('sha256').update(cli).digest('hex') !== MCODE_TOOLS_ARTIFACT.sha256)
  49. throw new Error('Embedded mcode-tools manifest or entry integrity mismatch.');
  50. return { cli, manifest: manifestBytes, notices };
  51. }
  52. const transientNetworkCodes = new Set([
  53. 'ECONNRESET', 'ECONNREFUSED', 'EPIPE', 'ETIMEDOUT', 'EAI_AGAIN', 'ENETUNREACH',
  54. 'UND_ERR_CONNECT_TIMEOUT', 'UND_ERR_HEADERS_TIMEOUT', 'UND_ERR_BODY_TIMEOUT', 'UND_ERR_SOCKET',
  55. ]);
  56. const transientHttpStatuses = new Set([408, 429, 500, 502, 503, 504]);
  57. export async function downloadMcodeToolsArtifact(fetchImpl = fetch, { wait = sleep, warn = console.warn } = {}) {
  58. const attempts = 3;
  59. for (let attempt = 1; attempt <= attempts; attempt++) {
  60. let retryAfterMs = 0;
  61. try {
  62. // A new deadline covers both connection setup and the complete response body.
  63. const response = await fetchImpl(MCODE_TOOLS_ARTIFACT.url, { signal: AbortSignal.timeout(120_000) });
  64. if (!response.ok) {
  65. const retryAfter = response.headers.get('retry-after');
  66. if (retryAfter !== null) {
  67. const milliseconds = /^\d+$/.test(retryAfter) ? Number(retryAfter) * 1000 : Date.parse(retryAfter) - Date.now();
  68. if (!Number.isNaN(milliseconds)) retryAfterMs = Math.min(30_000, Math.max(0, milliseconds));
  69. }
  70. await response.body?.cancel().catch(() => {});
  71. const error = new Error(`Cannot download public mcode-tools artifact: HTTP ${response.status}`);
  72. error.status = response.status;
  73. throw error;
  74. }
  75. return Buffer.from(await response.arrayBuffer());
  76. } catch (error) {
  77. const code = error.cause?.code ?? error.code;
  78. const retryable = transientHttpStatuses.has(error.status) ||
  79. transientNetworkCodes.has(code) || error.name === 'TimeoutError';
  80. if (!retryable) throw error;
  81. if (attempt === attempts)
  82. throw new Error(`Cannot download public mcode-tools artifact after ${attempts} attempts`, { cause: error });
  83. const delayMs = Math.max(1000 * 2 ** (attempt - 1), retryAfterMs);
  84. warn(`[mcode-tools] Download attempt ${attempt}/${attempts} failed (${code ?? error.message}); retrying in ${delayMs} ms.`);
  85. await wait(delayMs);
  86. }
  87. }
  88. }
  89. export async function copyMcodeToolsArtifact(root, outdir, fetchImpl = fetch) {
  90. const cache = path.join(root, '.cache', 'artifacts', 'code-0.3.11.tgz');
  91. let bytes;
  92. try { bytes = await readFile(cache); }
  93. catch (error) {
  94. if (error.code !== 'ENOENT') throw error;
  95. bytes = await downloadMcodeToolsArtifact(fetchImpl);
  96. }
  97. const artifact = await extractMcodeToolsArtifact(bytes);
  98. await mkdir(path.dirname(cache), { recursive: true });
  99. await writeFile(cache, bytes);
  100. const destination = path.join(outdir, 'embedded', 'mcode-tools');
  101. await mkdir(destination, { recursive: true });
  102. await writeFile(path.join(destination, 'cli.mjs'), artifact.cli);
  103. await writeFile(path.join(destination, 'manifest.json'), artifact.manifest);
  104. await writeFile(path.join(outdir, 'MCODE_TOOLS_NOTICES.md'), artifact.notices);
  105. }