import { basename } from 'node:path'; import { runBoundedProcess } from './boundedProcess.js'; declare const __GREEN_BUILD_VERSION__: string | undefined; const compiled = typeof __GREEN_BUILD_VERSION__ === 'string' || import.meta.url.includes('/$bunfs/'); /** Explicit runtime override, development interpreter, then verified PATH runtime. * Never invoke a compiled application as though it were a JS interpreter. */ export async function resolveScriptRuntime(options: { env?: NodeJS.ProcessEnv; signal?: AbortSignal; timeoutMs?: number; host?: { compiled: boolean; execPath: string }; } = {}): Promise { const env = options.env ?? process.env; const host = options.host ?? { compiled, execPath: process.execPath }; const override = env.MINIMAL_AGENT_SCRIPT_RUNTIME?.trim(); if (!override && !host.compiled && /^(node|bun)(\.exe)?$/i.test(basename(host.execPath))) return host.execPath; const candidates = override ? [override] : ['node', 'bun']; const started = Date.now(); const errors: string[] = []; for (const candidate of candidates) { options.signal?.throwIfAborted(); const remaining = (options.timeoutMs ?? 10000) - (Date.now() - started); if (remaining <= 0) break; try { const result = await runBoundedProcess(candidate, ['--eval', 'process.stdout.write("minimal-script-runtime:" + process.versions.node)'], { env, signal: options.signal, timeoutMs: Math.min(3000, remaining), }); if (result.exitCode === 0 && /^minimal-script-runtime:\d+\./.test(result.stdout.trim())) { const major = Number(result.stdout.trim().split(':')[1]?.split('.')[0]); if (major >= 20) return candidate; } errors.push(`${candidate}: incompatible or unavailable`); } catch (error) { options.signal?.throwIfAborted(); errors.push(`${candidate}: ${error instanceof Error ? error.message : String(error)}`); } } throw Object.assign(new Error(`未找到可用的 Node >=20/Bun 脚本解释器。请安装运行时或设置 MINIMAL_AGENT_SCRIPT_RUNTIME 为解释器路径。${errors.join('; ')}`), { code: 'SCRIPT_RUNTIME_UNAVAILABLE' }); }