Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(cli): graceful Node < 22 message on every Node version

Salman Qureshiaa7a9e9669ca
diff --git a/scripts/build-bin.cjs b/scripts/build-bin.cjs
index 1853fbde..4a86b038 100644
--- a/scripts/build-bin.cjs
+++ b/scripts/build-bin.cjs
@@ -54,7 +54,9 @@ const os = require('node:os');
const root = path.join(__dirname, '..');
const releaseRoot = path.join(root, 'release');
-const entry = path.join(root, 'dist', 'index.js');
+// The bundle itself; dist/index.js is only the Node version launcher, and
+// Bun binaries carry their own runtime.
+const entry = path.join(root, 'dist', 'mercury.js');
function copyDirSync(src, dest) {
fs.mkdirSync(dest, { recursive: true });
diff --git a/scripts/post-build.cjs b/scripts/post-build.cjs
index b57ba1fb..38e07703 100644
--- a/scripts/post-build.cjs
+++ b/scripts/post-build.cjs
@@ -24,9 +24,9 @@ function copyDirSync(src, dest) {
// and silently lose every fix (Static.itemKey, freeze gate, live-region
// guard, hardware cursor).
{
- const bundle = fs.readFileSync(path.join(__dirname, '..', 'dist', 'index.js'), 'utf8');
+ const bundle = fs.readFileSync(path.join(__dirname, '..', 'dist', 'mercury.js'), 'utf8');
const problems = [];
- if (/(?:from|import\()\s*["']ink["']/.test(bundle)) problems.push('dist/index.js imports "ink" at runtime (tsup alias/noExternal missing)');
+ if (/(?:from|import\()\s*["']ink["']/.test(bundle)) problems.push('dist/mercury.js imports "ink" at runtime (tsup alias/noExternal missing)');
for (const marker of ['__mercuryFrameGate', '__mercuryCursorAnchor', 'maxLiveRows', 'setCommitTick', 'vendored: true']) {
if (!bundle.includes(marker)) problems.push(`vendored ink marker missing from the bundle: ${marker}`);
}
diff --git a/scripts/verify-package.cjs b/scripts/verify-package.cjs
index 7912c676..fa2b5a89 100755
--- a/scripts/verify-package.cjs
+++ b/scripts/verify-package.cjs
@@ -54,6 +54,19 @@ check('shebang present', () => {
if (!head.includes('node')) throw new Error('no #!/usr/bin/env node shebang');
});
+check('dist/index.js is the Node version launcher, dist/mercury.js the bundle', () => {
+ if (!existsSync(join(modDir, 'dist', 'mercury.js'))) throw new Error('missing dist/mercury.js');
+ const launcher = readFileSync(join(modDir, 'dist', 'index.js'), 'utf-8');
+ // The check must run before any dependency loads: no static imports
+ // other than node builtins, and the gate before the bundle import.
+ const staticImports = [...launcher.matchAll(/^import .* from ["']([^"']+)["'];?$/gm)].map((m) => m[1]);
+ const foreign = staticImports.filter((s) => !s.startsWith('node:'));
+ if (foreign.length) throw new Error(`launcher has static imports that load before the version check: ${foreign.join(', ')}`);
+ const gate = launcher.indexOf('Mercury needs Node.js 22 or newer');
+ const load = launcher.indexOf('./mercury.js');
+ if (gate < 0 || load < 0 || gate > load) throw new Error('launcher must check the Node version before loading ./mercury.js');
+});
+
check('no dangling script references', () => {
const pkg = JSON.parse(readFileSync(join(modDir, 'package.json'), 'utf-8'));
const scripts = pkg.scripts || {};
@@ -74,10 +87,11 @@ check('no dangling script references', () => {
});
check('patched ink is bundled into dist (ADR-017, no postinstall)', () => {
- const bundle = readFileSync(join(modDir, 'dist', 'index.js'), 'utf-8');
- if (/(?:from|import\()\s*["']ink["']/.test(bundle)) throw new Error('dist/index.js imports "ink" at runtime — the vendored build is not bundled');
- for (const marker of ['__mercuryFrameGate', '__mercuryCursorAnchor', '__mercuryInkYogaHygiene', 'vendored: true']) {
- if (!bundle.includes(marker)) throw new Error(`vendored ink marker missing from dist/index.js: ${marker}`);
+ const bundle = readFileSync(join(modDir, 'dist', 'mercury.js'), 'utf-8');
+ if (/(?:from|import\()\s*["']ink["']/.test(bundle)) throw new Error('dist/mercury.js imports "ink" at runtime — the vendored build is not bundled');
+ // Same markers as scripts/post-build.cjs (ink 8 patch set, ADR-019).
+ for (const marker of ['__mercuryFrameGate', '__mercuryCursorAnchor', 'maxLiveRows', 'setCommitTick', 'vendored: true']) {
+ if (!bundle.includes(marker)) throw new Error(`vendored ink marker missing from dist/mercury.js: ${marker}`);
}
const pkg = JSON.parse(readFileSync(join(modDir, 'package.json'), 'utf-8'));
if (pkg.scripts && pkg.scripts.postinstall) throw new Error(`postinstall must not be needed any more (got: ${pkg.scripts.postinstall})`);
diff --git a/src/cli/service.test.ts b/src/cli/service.test.ts
index 2ab21abc..14e1f4fa 100644
--- a/src/cli/service.test.ts
+++ b/src/cli/service.test.ts
@@ -169,12 +169,16 @@ describe('resolveDistPath', () => {
expect(resolved).not.toContain(join('npm', '..', 'lib'));
});
- it('falls back to the module location when argv[1] is not a real file (bun-virtual path)', () => {
+ it('falls back to the launcher next to the bundle when argv[1] is not a real file (bun-virtual path)', () => {
+ // The bundle is dist/mercury.js; services must launch dist/index.js, the
+ // launcher that checks the Node version before loading the bundle.
root = mkdtempSync(join(tmpdir(), 'mercury-dist-self-'));
- const self = join(root, 'dist', 'index.js');
mkdirSync(join(root, 'dist'));
- writeFileSync(self, '// bundle');
- expect(resolveDistPath('/$bunfs/root/mercury', pathToFileURL(self).href)).toBe(self);
+ const bundle = join(root, 'dist', 'mercury.js');
+ const launcher = join(root, 'dist', 'index.js');
+ writeFileSync(bundle, '// bundle');
+ writeFileSync(launcher, '// launcher');
+ expect(resolveDistPath('/$bunfs/root/mercury', pathToFileURL(bundle).href)).toBe(launcher);
});
it('falls back to the nvm guess when nothing else resolves', () => {
diff --git a/src/cli/service.ts b/src/cli/service.ts
index df6dcfd6..f5698611 100644
--- a/src/cli/service.ts
+++ b/src/cli/service.ts
@@ -83,8 +83,8 @@ function getNodeBinPath(): string {
* index.js`), on Windows npm installs the `.cmd` shim already hands node the
* real `%APPDATA%\npm\node_modules\...\dist\index.js`. `realpathSync` folds
* both into the real file, so no layout assumption (`bin/../lib/...`) is
- * needed. Fallbacks: this module's own location (the bundle IS dist/index.js),
- * then the legacy nvm guess.
+ * needed. Fallbacks: the launcher next to this bundle (`dist/mercury.js` →
+ * `dist/index.js`), then the legacy nvm guess.
*/
export function resolveDistPath(
argv1: string | undefined,
@@ -100,7 +100,10 @@ export function resolveDistPath(
}
try {
const self = fileURLToPath(moduleUrl);
- if (/[\\/]dist[\\/]index\.(?:m?js|cjs)$/i.test(self) && existsSync(self)) return self;
+ if (/[\\/]dist[\\/](?:index|mercury)\.(?:m?js|cjs)$/i.test(self)) {
+ const launcher = join(dirname(self), 'index.js');
+ if (existsSync(launcher)) return launcher;
+ }
} catch {
// not a file: URL (unusual bundler) — fall through.
}
diff --git a/src/launcher.ts b/src/launcher.ts
new file mode 100644
index 00000000..9df191f8
--- /dev/null
+++ b/src/launcher.ts
@@ -0,0 +1,10 @@
+/**
+ * Mercury's entry point — `dist/index.js`, what the `mercury` bin, service
+ * files and the daemon re-spawn all run. Deliberately tiny with no static
+ * imports: Node evaluates every static import of a module before the
+ * module's first line, so a version check inside the main bundle runs too
+ * late on Node 16/18 (a dependency throws while loading, before Mercury can
+ * say anything useful). The tsup banner puts the Node 22 check (ADR-019) at
+ * the top of this file; only then is the real bundle loaded.
+ */
+await import(new URL('./mercury.js', import.meta.url).href);
diff --git a/tsup.config.ts b/tsup.config.ts
index ea73a30c..eaa4423c 100644
--- a/tsup.config.ts
+++ b/tsup.config.ts
@@ -22,7 +22,9 @@ const channelVersion = process.env.MERCURY_CHANNEL_VERSION || pkg.version;
const channelStamp = process.env.MERCURY_CHANNEL_VERSION || '';
export default defineConfig({
- entry: ["src/index.ts"],
+ // dist/index.js is the launcher (see src/launcher.ts); dist/mercury.js is
+ // the real bundle it loads once the Node version check has passed.
+ entry: { index: "src/launcher.ts", mercury: "src/index.ts" },
format: ["esm"],
target: "node22",
outDir: "dist",
@@ -39,10 +41,12 @@ export default defineConfig({
"#!/usr/bin/env node",
'import { createRequire as __mercuryCreateRequire } from "node:module";',
"const require = __mercuryCreateRequire(import.meta.url);",
- // ink 8 (the TUI renderer) needs Node 22 (Promise.withResolvers and
- // friends). Say so up front instead of crashing at the first render.
- // Bun reports its own Node-compat version, so it is exempt.
- 'if (!process.versions.bun && Number(process.versions.node.split(".")[0]) < 22) { console.error("Mercury needs Node.js 22 or newer (found " + process.version + "). Upgrade Node, e.g. `nvm install 22`."); process.exit(1); }',
+ // Node 22 is required (ADR-019: ink 8). Say so in plain words instead
+ // of crashing. Bun reports its own Node-compat version and is exempt.
+ // Under a service manager (`--daemon`), exit 0: launchd and systemd
+ // restart a daemon that exits non-zero, which would loop forever;
+ // the message still lands in the daemon log.
+ 'if (!process.versions.bun && Number(process.versions.node.split(".")[0]) < 22) { console.error("Mercury needs Node.js 22 or newer — this is Node " + process.version + ".\\n Upgrade Node: nvm install 22 && nvm alias default 22 (or https://nodejs.org)\\n Then reinstall Mercury with that Node: npm install -g @cosmicstack/mercury-agent"); process.exit(process.argv.includes("--daemon") ? 0 : 1); }',
].join("\n"),
},
// Inject the version so standalone binaries (Bun --compile) can read it