resource.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. import {
  2. chmodSync,
  3. existsSync,
  4. mkdirSync,
  5. readFileSync,
  6. renameSync,
  7. rmSync,
  8. writeFileSync,
  9. } from 'node:fs';
  10. import path from 'node:path';
  11. import {
  12. validateEmbeddedResourceFiles,
  13. validateEmbeddedResourceManifest,
  14. } from './resource-manifest.mjs';
  15. import {
  16. AUTH_LEASE_PROTOCOL_PACKAGE_NAME,
  17. AUTH_LEASE_PROTOCOL_PACKAGE_VERSION,
  18. AUTH_LEASE_PROTOCOL_VERSION,
  19. } from '@mavis/oauth-lease-protocol';
  20. export type McodeToolsBuildEnv = 'test' | 'staging' | 'prod';
  21. export type McodeToolsRegion = 'cn' | 'en';
  22. export interface McodeToolsManifest {
  23. schemaVersion: 3 | 4;
  24. packageName: string;
  25. version: string;
  26. gitSha: string;
  27. buildEnv: McodeToolsBuildEnv;
  28. bedrockLane: string;
  29. nodeRange: string;
  30. entry: 'cli.mjs';
  31. auth: {
  32. mode: 'shared-broker';
  33. protocol: {
  34. name: typeof AUTH_LEASE_PROTOCOL_PACKAGE_NAME;
  35. version: typeof AUTH_LEASE_PROTOCOL_PACKAGE_VERSION;
  36. wireVersion: typeof AUTH_LEASE_PROTOCOL_VERSION;
  37. };
  38. };
  39. nativePackages: { name: 'registry-js'; version: string; napiVersion: 3 }[];
  40. resources: [{ path: 'cli.mjs'; sha256: string }, ...{ path: string; sha256: string }[]];
  41. }
  42. export interface ValidatedMcodeToolsResource {
  43. rootDir: string;
  44. cliPath: string;
  45. manifest: McodeToolsManifest;
  46. }
  47. export function validateMcodeToolsResource(options: {
  48. resourceDir: string;
  49. expectedBuildEnv: McodeToolsBuildEnv;
  50. }): ValidatedMcodeToolsResource {
  51. const manifestPath = path.join(options.resourceDir, 'manifest.json');
  52. if (!existsSync(manifestPath)) throw new Error('mcode-tools manifest is missing');
  53. let value: unknown;
  54. try {
  55. value = JSON.parse(readFileSync(manifestPath, 'utf8'));
  56. } catch {
  57. throw new Error('mcode-tools manifest is not valid JSON');
  58. }
  59. const manifest = parseManifest(value);
  60. if (manifest.buildEnv !== options.expectedBuildEnv) {
  61. throw new Error(
  62. `mcode-tools build environment mismatch: expected ${options.expectedBuildEnv}, received ${manifest.buildEnv}`,
  63. );
  64. }
  65. const expectedPackageName = packageNameForBuildEnv(options.expectedBuildEnv);
  66. if (manifest.packageName !== expectedPackageName) {
  67. throw new Error(
  68. `mcode-tools package mismatch: expected ${expectedPackageName}, received ${manifest.packageName}`,
  69. );
  70. }
  71. const cliPath = path.join(options.resourceDir, manifest.entry);
  72. if (!existsSync(cliPath)) throw new Error('mcode-tools embedded cli is missing');
  73. validateEmbeddedResourceFiles(options.resourceDir, manifest);
  74. return { rootDir: options.resourceDir, cliPath, manifest };
  75. }
  76. export async function installMcodeToolsLauncher(options: {
  77. resourceDir: string;
  78. expectedBuildEnv: McodeToolsBuildEnv;
  79. dataDir: string;
  80. executable: string;
  81. platform: NodeJS.Platform;
  82. region: McodeToolsRegion;
  83. bedrockLane?: string;
  84. brokerEndpoint: string;
  85. brokerCapabilityFile: string;
  86. }): Promise<{
  87. launcherPath: string;
  88. regionalLauncherPath: string;
  89. resource: ValidatedMcodeToolsResource;
  90. }> {
  91. const resource = validateMcodeToolsResource(options);
  92. const binDir = path.join(options.dataDir, 'bin');
  93. const configDir = path.join(options.dataDir, 'integrations', 'mcode-tools', options.region);
  94. mkdirSync(binDir, { recursive: true, mode: 0o700 });
  95. mkdirSync(configDir, { recursive: true, mode: 0o700 });
  96. chmodSync(binDir, 0o700);
  97. chmodSync(configDir, 0o700);
  98. const isWindows = options.platform === 'win32';
  99. const launcherPath = path.join(binDir, isWindows ? 'mcode-tools.cmd' : 'mcode-tools');
  100. const regionLabel = options.region === 'cn' ? 'cn' : 'global';
  101. const regionalLauncherPath = path.join(
  102. binDir,
  103. isWindows ? `mcode-tools-${regionLabel}.cmd` : `mcode-tools-${regionLabel}`,
  104. );
  105. const staleLauncherPaths = isWindows
  106. ? ['mcode-tools', 'mcode-tools-cn', 'mcode-tools-global']
  107. : ['mcode-tools.cmd', 'mcode-tools-cn.cmd', 'mcode-tools-global.cmd'];
  108. const bedrockLane = resolveManagedBedrockLane(options.bedrockLane);
  109. const contents = isWindows
  110. ? renderWindowsLauncher({
  111. executable: options.executable,
  112. cliPath: resource.cliPath,
  113. configDir,
  114. region: options.region,
  115. ...(bedrockLane ? { bedrockLane } : {}),
  116. brokerEndpoint: options.brokerEndpoint,
  117. brokerCapabilityFile: options.brokerCapabilityFile,
  118. })
  119. : renderPosixLauncher({
  120. executable: options.executable,
  121. cliPath: resource.cliPath,
  122. configDir,
  123. region: options.region,
  124. ...(bedrockLane ? { bedrockLane } : {}),
  125. brokerEndpoint: options.brokerEndpoint,
  126. brokerCapabilityFile: options.brokerCapabilityFile,
  127. });
  128. const dispatcher = isWindows ? renderWindowsDispatcher() : renderPosixDispatcher();
  129. writeFileIfChanged(regionalLauncherPath, contents, isWindows ? 0o600 : 0o755);
  130. writeFileIfChanged(launcherPath, dispatcher, isWindows ? 0o600 : 0o755);
  131. for (const staleName of staleLauncherPaths) {
  132. rmSync(path.join(binDir, staleName), { force: true });
  133. }
  134. return { launcherPath, regionalLauncherPath, resource };
  135. }
  136. export function removeMcodeToolsLaunchers(dataDir: string, region?: McodeToolsRegion): void {
  137. const binDir = path.join(dataDir, 'bin');
  138. const regionLabels = region ? [region === 'cn' ? 'cn' : 'global'] : ['cn', 'global'];
  139. for (const name of regionLabels.flatMap((label) => [
  140. `mcode-tools-${label}`,
  141. `mcode-tools-${label}.cmd`,
  142. ])) {
  143. rmSync(path.join(binDir, name), { force: true });
  144. }
  145. const hasRegionalLauncher = ['cn', 'global'].some(
  146. (label) =>
  147. existsSync(path.join(binDir, `mcode-tools-${label}`)) ||
  148. existsSync(path.join(binDir, `mcode-tools-${label}.cmd`)),
  149. );
  150. if (!hasRegionalLauncher) {
  151. rmSync(path.join(binDir, 'mcode-tools'), { force: true });
  152. rmSync(path.join(binDir, 'mcode-tools.cmd'), { force: true });
  153. }
  154. }
  155. function renderPosixDispatcher(): string {
  156. return [
  157. '#!/bin/sh',
  158. 'mcode_tools_bin_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)',
  159. ['mcode_tools_region=$', '{MCODE_REGION:-$', '{MAVIS_REGION:-}}'].join(''),
  160. 'case "$mcode_tools_region" in',
  161. ' cn) mcode_tools_target="$mcode_tools_bin_dir/mcode-tools-cn" ;;',
  162. ' en|global) mcode_tools_target="$mcode_tools_bin_dir/mcode-tools-global" ;;',
  163. ' "")',
  164. ' if [ -x "$mcode_tools_bin_dir/mcode-tools-cn" ] && [ ! -x "$mcode_tools_bin_dir/mcode-tools-global" ]; then',
  165. ' mcode_tools_target="$mcode_tools_bin_dir/mcode-tools-cn"',
  166. ' elif [ -x "$mcode_tools_bin_dir/mcode-tools-global" ] && [ ! -x "$mcode_tools_bin_dir/mcode-tools-cn" ]; then',
  167. ' mcode_tools_target="$mcode_tools_bin_dir/mcode-tools-global"',
  168. ' else',
  169. ' echo "MCODE_REGION must be cn or global when both regional mcode-tools launchers are installed." >&2',
  170. ' exit 2',
  171. ' fi',
  172. ' ;;',
  173. ' *) echo "Invalid MCODE_REGION; expected cn or global." >&2; exit 2 ;;',
  174. 'esac',
  175. 'exec "$mcode_tools_target" "$@"',
  176. '',
  177. ].join('\n');
  178. }
  179. function renderWindowsDispatcher(): string {
  180. return [
  181. '@echo off',
  182. 'setlocal DisableDelayedExpansion',
  183. 'set "mcode_tools_region=%MCODE_REGION%"',
  184. 'if not defined mcode_tools_region set "mcode_tools_region=%MAVIS_REGION%"',
  185. 'if /i "%mcode_tools_region%"=="cn" goto mcode_tools_cn',
  186. 'if /i "%mcode_tools_region%"=="en" goto mcode_tools_global',
  187. 'if /i "%mcode_tools_region%"=="global" goto mcode_tools_global',
  188. 'if defined mcode_tools_region goto mcode_tools_invalid',
  189. 'if exist "%~dp0mcode-tools-cn.cmd" if not exist "%~dp0mcode-tools-global.cmd" goto mcode_tools_cn',
  190. 'if exist "%~dp0mcode-tools-global.cmd" if not exist "%~dp0mcode-tools-cn.cmd" goto mcode_tools_global',
  191. 'echo MCODE_REGION must be cn or global when both regional mcode-tools launchers are installed. 1>&2',
  192. 'exit /b 2',
  193. ':mcode_tools_cn',
  194. 'call "%~dp0mcode-tools-cn.cmd" %*',
  195. 'exit /b %ERRORLEVEL%',
  196. ':mcode_tools_global',
  197. 'call "%~dp0mcode-tools-global.cmd" %*',
  198. 'exit /b %ERRORLEVEL%',
  199. ':mcode_tools_invalid',
  200. 'echo Invalid MCODE_REGION; expected cn or global. 1>&2',
  201. 'exit /b 2',
  202. '',
  203. ].join('\r\n');
  204. }
  205. export function renderPosixLauncher(options: {
  206. executable: string;
  207. cliPath: string;
  208. configDir: string;
  209. region: McodeToolsRegion;
  210. bedrockLane?: string;
  211. brokerEndpoint: string;
  212. brokerCapabilityFile: string;
  213. }): string {
  214. const lines = [
  215. '#!/bin/sh',
  216. 'unset MAVIS_ACCESS_TOKEN MAVIS_DATA_DIR MINIMAX_DATA_DIR MAVIS_PORT MAVIS_PROFILE IS_SANDBOX MCODE_API_BASE_URL MCODE_AUTH_BASE_URL MCODE_CLIENT_ID MCODE_SCOPE MCODE_AUTH_PROVIDER MCODE_AUTH_BROKER_ENDPOINT MCODE_AUTH_BROKER_CAPABILITY_FILE MCODE_EXTRA_HEADERS',
  217. "for mcode_tools_name in $(env | sed -n 's/^\\([^=]*\\)=.*$/\\1/p'); do",
  218. ' case "$mcode_tools_name" in',
  219. ' __MAVIS_PARENT_*|__MAVIS_RUNTIME_*|AGENTARCHON_*|AGENT_ARCHON_*) unset "$mcode_tools_name" ;;',
  220. ' esac',
  221. 'done',
  222. 'unset mcode_tools_name',
  223. 'export ELECTRON_RUN_AS_NODE=1',
  224. `export MCODE_REGION=${quotePosix(options.region)}`,
  225. `export MCODE_CONFIG_DIR=${quotePosix(options.configDir)}`,
  226. ];
  227. lines.push(
  228. 'export MCODE_AUTH_PROVIDER=shared-broker',
  229. `export MCODE_AUTH_BROKER_ENDPOINT=${quotePosix(options.brokerEndpoint)}`,
  230. `export MCODE_AUTH_BROKER_CAPABILITY_FILE=${quotePosix(options.brokerCapabilityFile)}`,
  231. );
  232. if (options.bedrockLane) {
  233. lines.push(
  234. `export MCODE_EXTRA_HEADERS=${quotePosix(`bedrock_lane:${options.bedrockLane},bedrock-lane:${options.bedrockLane}`)}`,
  235. );
  236. }
  237. lines.push(`exec ${quotePosix(options.executable)} ${quotePosix(options.cliPath)} "$@"`, '');
  238. return lines.join('\n');
  239. }
  240. export function renderWindowsLauncher(options: {
  241. executable: string;
  242. cliPath: string;
  243. configDir: string;
  244. region: McodeToolsRegion;
  245. bedrockLane?: string;
  246. brokerEndpoint: string;
  247. brokerCapabilityFile: string;
  248. }): string {
  249. const lines = [
  250. '@echo off',
  251. 'setlocal DisableDelayedExpansion',
  252. 'set "MAVIS_ACCESS_TOKEN="',
  253. 'set "MAVIS_DATA_DIR="',
  254. 'set "MINIMAX_DATA_DIR="',
  255. 'set "MAVIS_PORT="',
  256. 'set "MAVIS_PROFILE="',
  257. 'set "IS_SANDBOX="',
  258. 'set "MCODE_API_BASE_URL="',
  259. 'set "MCODE_AUTH_BASE_URL="',
  260. 'set "MCODE_CLIENT_ID="',
  261. 'set "MCODE_SCOPE="',
  262. 'set "MCODE_AUTH_PROVIDER="',
  263. 'set "MCODE_AUTH_BROKER_ENDPOINT="',
  264. 'set "MCODE_AUTH_BROKER_CAPABILITY_FILE="',
  265. 'set "MCODE_EXTRA_HEADERS="',
  266. 'for /f "tokens=1 delims==" %%V in (\'set __MAVIS_PARENT_ 2^>nul\') do set "%%V="',
  267. 'for /f "tokens=1 delims==" %%V in (\'set __MAVIS_RUNTIME_ 2^>nul\') do set "%%V="',
  268. 'for /f "tokens=1 delims==" %%V in (\'set AGENTARCHON_ 2^>nul\') do set "%%V="',
  269. 'for /f "tokens=1 delims==" %%V in (\'set AGENT_ARCHON_ 2^>nul\') do set "%%V="',
  270. 'set "ELECTRON_RUN_AS_NODE=1"',
  271. `set "MCODE_REGION=${escapeWindowsBatchValue(options.region)}"`,
  272. `set "MCODE_CONFIG_DIR=${escapeWindowsBatchValue(options.configDir)}"`,
  273. ];
  274. lines.push(
  275. 'set "MCODE_AUTH_PROVIDER=shared-broker"',
  276. `set "MCODE_AUTH_BROKER_ENDPOINT=${escapeWindowsBatchValue(options.brokerEndpoint)}"`,
  277. `set "MCODE_AUTH_BROKER_CAPABILITY_FILE=${escapeWindowsBatchValue(options.brokerCapabilityFile)}"`,
  278. );
  279. if (options.bedrockLane) {
  280. lines.push(
  281. `set "MCODE_EXTRA_HEADERS=${escapeWindowsBatchValue(`bedrock_lane:${options.bedrockLane},bedrock-lane:${options.bedrockLane}`)}"`,
  282. );
  283. }
  284. lines.push(
  285. `"${escapeWindowsBatchValue(options.executable)}" "${escapeWindowsBatchValue(options.cliPath)}" %*`,
  286. 'exit /b %ERRORLEVEL%',
  287. '',
  288. );
  289. return lines.join('\r\n');
  290. }
  291. function parseManifest(value: unknown): McodeToolsManifest {
  292. if (!value || typeof value !== 'object') throw new Error('mcode-tools manifest is invalid');
  293. const input = value as Record<string, unknown>;
  294. const buildEnv = input.buildEnv;
  295. if (buildEnv !== 'test' && buildEnv !== 'staging' && buildEnv !== 'prod') {
  296. throw new Error('mcode-tools manifest buildEnv is invalid');
  297. }
  298. if (input.entry !== 'cli.mjs') throw new Error('mcode-tools manifest entry is invalid');
  299. for (const key of ['packageName', 'version', 'gitSha', 'nodeRange'] as const) {
  300. if (typeof input[key] !== 'string' || input[key].trim().length === 0) {
  301. throw new Error(`mcode-tools manifest ${key} is invalid`);
  302. }
  303. }
  304. if (typeof input.bedrockLane !== 'string') {
  305. throw new Error('mcode-tools manifest bedrockLane is invalid');
  306. }
  307. if (buildEnv !== 'test' && input.bedrockLane.trim().length > 0) {
  308. throw new Error('mcode-tools non-test manifest must not select a Bedrock lane');
  309. }
  310. const auth = input.auth as Record<string, unknown> | undefined;
  311. const protocol = auth?.protocol as Record<string, unknown> | undefined;
  312. if (
  313. (input.schemaVersion !== 3 && input.schemaVersion !== 4) ||
  314. auth?.mode !== 'shared-broker' ||
  315. protocol?.name !== AUTH_LEASE_PROTOCOL_PACKAGE_NAME ||
  316. protocol?.version !== AUTH_LEASE_PROTOCOL_PACKAGE_VERSION ||
  317. protocol?.wireVersion !== AUTH_LEASE_PROTOCOL_VERSION
  318. ) {
  319. throw new Error('mcode-tools shared-broker lease protocol manifest is incompatible');
  320. }
  321. if (hasOwn(input, 'sharedLocal') || hasOwn(input, 'platform') || hasOwn(input, 'arch')) {
  322. throw new Error(
  323. 'mcode-tools shared-broker manifest must not contain shared-local platform metadata',
  324. );
  325. }
  326. validateEmbeddedResourceManifest(input);
  327. return input as unknown as McodeToolsManifest;
  328. }
  329. function hasOwn(value: object, key: PropertyKey): boolean {
  330. return Object.prototype.hasOwnProperty.call(value, key);
  331. }
  332. function resolveManagedBedrockLane(value: string | undefined): string | undefined {
  333. if (value === undefined) return undefined;
  334. const lane = value.trim();
  335. if (!/^[A-Za-z0-9._-]+$/u.test(lane)) {
  336. throw new Error('mcode-tools Bedrock lane is invalid');
  337. }
  338. return lane;
  339. }
  340. function packageNameForBuildEnv(buildEnv: McodeToolsBuildEnv): string {
  341. if (buildEnv === 'test') return '@minimax/mcode-tools-test';
  342. if (buildEnv === 'staging') return '@minimax/mcode-tools-staging';
  343. return '@minimax/mcode-tools';
  344. }
  345. function quotePosix(value: string): string {
  346. if (/\r|\n|\0/u.test(value)) throw new Error('mcode-tools launcher path contains control data');
  347. return `'${value.replace(/'/gu, "'\\''")}'`;
  348. }
  349. function escapeWindowsBatchValue(value: string): string {
  350. if (/\r|\n|\0|"/u.test(value)) {
  351. throw new Error('mcode-tools launcher path contains unsupported characters');
  352. }
  353. return value.replace(/%/gu, '%%');
  354. }
  355. function writeFileIfChanged(file: string, contents: string, mode: number): void {
  356. if (existsSync(file) && readFileSync(file, 'utf8') === contents) {
  357. chmodSync(file, mode);
  358. return;
  359. }
  360. const temporary = `${file}.${process.pid}.${Date.now()}.tmp`;
  361. writeFileSync(temporary, contents, { mode });
  362. try {
  363. renameSync(temporary, file);
  364. } catch (error) {
  365. rmSync(temporary, { force: true });
  366. throw error;
  367. }
  368. chmodSync(file, mode);
  369. }