Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.
fix(wizard): shared readline that rejects on EOF; crash handlers before configure(); .env is 0600 (#64)
Salman Qureshi6a6691ed6e12
diff --git a/src/cli/ask.test.ts b/src/cli/ask.test.tsnew file mode 100644index 00000000..2505c280--- /dev/null+++ b/src/cli/ask.test.ts@@ -0,0 +1,85 @@+import { describe, expect, it } from 'vitest';+import { PassThrough } from 'node:stream';+import { createPrompter, InputClosedError } from './ask.js';++/**+ * Wizard input contract (#64): a closed stdin must fail the pending+ * question loudly — never hang, never let the process exit 0 as if setup+ * had completed — and the shared interface must not pin stdin open once+ * no question is waiting.+ */++function io() {+ const input = new PassThrough();+ const output = new PassThrough();+ let written = '';+ output.on('data', (chunk) => { written += String(chunk); });+ return { input, output, prompter: createPrompter({ input, output }), written: () => written };+}++const tick = () => new Promise<void>((resolve) => setImmediate(resolve));++describe('ask()', () => {+ it('answers consecutive questions from one input stream and trims the answers', async () => {+ const { input, prompter, written } = io();+ const first = prompter.ask('Name: ');+ input.write(' Jane \n');+ expect(await first).toBe('Jane');+ const second = prompter.ask('Agent: ');+ input.write('Mercury\n');+ expect(await second).toBe('Mercury');+ expect(written()).toContain('Name: ');+ expect(written()).toContain('Agent: ');+ prompter.close();+ });++ it('rejects the pending question with InputClosedError when stdin hits EOF', async () => {+ const { input, prompter } = io();+ const pending = prompter.ask('Token: ');+ input.end(); // EOF with no answer — the silent-exit case+ await expect(pending).rejects.toBeInstanceOf(InputClosedError);+ await expect(pending).rejects.toThrow(/stdin reached EOF/);+ });++ it('rejects every later question immediately once input has ended (no hang)', async () => {+ const { input, prompter } = io();+ const pending = prompter.ask('A: ');+ input.end();+ await expect(pending).rejects.toBeInstanceOf(InputClosedError);+ // A fresh interface on an ended stream would wait forever; we must not.+ await expect(prompter.ask('B: ')).rejects.toBeInstanceOf(InputClosedError);+ });++ it('rejects when input ended before the first question', async () => {+ const { input, prompter } = io();+ input.end();+ await expect(prompter.ask('A: ')).rejects.toBeInstanceOf(InputClosedError);+ });++ it('releases the readline interface when no question is pending, so the process can exit', async () => {+ const { input, prompter } = io();+ const q = prompter.ask('A: ');+ expect(input.listenerCount('data')).toBeGreaterThan(0);+ input.write('x\n');+ await q;+ await tick();+ await tick();+ // readline detached its data listener; only our own `end` hook remains.+ expect(input.listenerCount('data')).toBe(0);+ expect(input.listenerCount('keypress')).toBe(0);+ // Reuse after release still works.+ const q2 = prompter.ask('B: ');+ input.write('y\n');+ expect(await q2).toBe('y');+ prompter.close();+ });++ it('refuses overlapping questions instead of silently queueing them', async () => {+ const { input, prompter } = io();+ const q = prompter.ask('A: ');+ await expect(prompter.ask('B: ')).rejects.toThrow(/still waiting/);+ input.write('a\n');+ expect(await q).toBe('a');+ prompter.close();+ });+});diff --git a/src/cli/ask.ts b/src/cli/ask.tsnew file mode 100644index 00000000..f3c07971--- /dev/null+++ b/src/cli/ask.ts@@ -0,0 +1,119 @@+import readline from 'node:readline';++/**+ * Interactive prompt for the setup wizard and the `mercury <channel>`+ * pairing commands.+ *+ * One shared readline interface serves every consecutive question (#64).+ * The previous per-question interface had no `close` handler: when stdin+ * reached EOF (piped input, closed terminal, Ctrl+D) the pending question+ * never resolved, the event loop drained, and the process exited 0 as if+ * setup had finished. Now:+ * - a `close` while a question is pending rejects it with+ * `InputClosedError`, so the caller fails loudly (exit 1);+ * - once stdin has ended, every later `ask()` rejects immediately instead+ * of hanging on a stream that will never emit another line;+ * - the interface is released as soon as no question is pending (after+ * the current tick), so a command that asked one question still exits,+ * and the Ink TUI that boots after the wizard gets a free stdin.+ */+export class InputClosedError extends Error {+ constructor(message = 'Input closed before the question was answered (stdin reached EOF). Run this command from an interactive terminal.') {+ super(message);+ this.name = 'InputClosedError';+ }+}++export interface AskIO {+ input: NodeJS.ReadableStream;+ output: NodeJS.WritableStream;+}++interface Prompter {+ ask(prompt: string): Promise<string>;+ close(): void;+}++export function createPrompter(io: AskIO): Prompter {+ let rl: readline.Interface | null = null;+ let inputEnded = false;+ let pending: { reject: (err: Error) => void } | null = null;+ let release: NodeJS.Immediate | null = null;+ let endHooked = false;++ const onInputEnd = () => { inputEnded = true; };++ function open(): readline.Interface {+ if (rl) return rl;+ if (!endHooked) {+ // readline removes its own listeners on close(); keep ours so an EOF+ // that lands between two questions is still remembered.+ io.input.once('end', onInputEnd);+ endHooked = true;+ }+ const iface = readline.createInterface({ input: io.input, output: io.output });+ iface.on('close', () => {+ if (rl !== iface) return; // our own release, already detached+ rl = null;+ if (pending) {+ // Closed by EOF / Ctrl+D while waiting: this is the silent-exit bug.+ inputEnded = true;+ const p = pending;+ pending = null;+ p.reject(new InputClosedError());+ }+ });+ rl = iface;+ return iface;+ }++ function close(): void {+ if (release) { clearImmediate(release); release = null; }+ const iface = rl;+ rl = null;+ iface?.close();+ }++ function scheduleRelease(): void {+ if (release) clearImmediate(release);+ release = setImmediate(() => {+ release = null;+ if (!pending) close();+ });+ }++ return {+ ask(prompt: string): Promise<string> {+ if (inputEnded) return Promise.reject(new InputClosedError());+ if (pending) return Promise.reject(new Error('ask(): a previous question is still waiting for an answer'));+ if (release) { clearImmediate(release); release = null; }+ const iface = open();+ return new Promise<string>((resolve, reject) => {+ pending = { reject };+ iface.question(prompt, (answer) => {+ pending = null;+ scheduleRelease();+ resolve(answer.trim());+ });+ });+ },+ close,+ };+}++let stdPrompter: Prompter | null = null;++function std(): Prompter {+ if (!stdPrompter) stdPrompter = createPrompter({ input: process.stdin, output: process.stdout });+ return stdPrompter;+}++/** Ask one question on the process terminal; see module docs for EOF rules. */+export function ask(prompt: string): Promise<string> {+ return std().ask(prompt);+}++/** Release the terminal readline (idempotent; normally automatic). */+export function closeAsk(): void {+ stdPrompter?.close();+}diff --git a/src/index.ts b/src/index.tsindex 40a0e883..bfdda0a8 100644--- a/src/index.ts+++ b/src/index.ts@@ -1,8 +1,7 @@-import { readFileSync, writeFileSync, existsSync, statSync } from 'node:fs';+import { readFileSync, writeFileSync, existsSync, statSync, chmodSync } from 'node:fs';import { fileURLToPath } from 'node:url';import { dirname, join, resolve as pathResolve } from 'node:path';import { Command } from 'commander';-import readline from 'node:readline';import chalk from 'chalk';import {@@ -72,6 +71,7 @@ import { SkillLoader } from './skills/loader.js';import { registerSkillsCommand } from './skills/cli.js';import { registerBotsCommand } from './bots/cli.js';import { getManual } from './utils/manual.js';+import { ask, InputClosedError } from './cli/ask.js';import { startBackground, stopDaemon, showLogs, getDaemonStatus, registerRuntimeProcess, releaseRuntimeProcess, restartDaemon, tryAutoDaemonize, isStandaloneBinary, getForegroundRuntimeStatus, stopForegroundRuntime } from './cli/daemon.js';import { runUninstall } from './cli/uninstall.js';import { runAttach } from './cli/attach.js';@@ -150,16 +150,6 @@ function splashScreen() {console.log('');}-async function ask(prompt: string): Promise<string> {- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });- return new Promise((resolve) => {- rl.question(prompt, (answer) => {- rl.close();- resolve(answer.trim());- });- });-}-function maskKey(key: string): string {if (!key) return '';if (key.length <= 8) return '••••••••';@@ -729,7 +719,11 @@ function appendToEnv(key: string, value: string): void {}const lines = envContent.split('\n').filter((l: string) => !l.startsWith(`${key}=`) && l.trim() !== '');lines.push(`${key}=${value}`);- writeFileSync(envPath, lines.join('\n') + '\n', 'utf-8');+ // Holds API keys and bot tokens: owner-only, like config.yaml and the web+ // credential files. `mode` only applies on create, so chmod repairs a+ // file an older version wrote with the default umask (0644).+ writeFileSync(envPath, lines.join('\n') + '\n', { encoding: 'utf-8', mode: 0o600 });+ try { chmodSync(envPath, 0o600); } catch { /* best effort (Windows ACLs) */ }process.env[key] = value;}@@ -2341,6 +2335,7 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {const { appendFileSync } = await import('node:fs');const dumpFile = join(getMercuryHome(), 'crash-report.log');const line = (m: string) => appendFileSync(dumpFile, `[${new Date().toISOString()}] ${m}\n`);+ removeBootCrashHandlers();Error.stackTraceLimit = 50;if (typeof (process as any).report !== 'undefined') {try { (process as any).report.uncaughtException = true; } catch { /* unsupported */ }@@ -3712,6 +3707,42 @@ async function runAgent(isDaemon: boolean = false): Promise<void> {}}+/**+ * Boot-time crash handlers (#64). Installed before any command runs — in+ * particular before the setup wizard — so a failure there is loud and+ * exits 1. Without them, web/server.ts's import-time `unhandledRejection`+ * listener disables Node's default throw-on-rejection, and a rejected+ * `configure()` (e.g. stdin closed mid-wizard) ended the process with+ * exit code 0 and no message. runAgent() swaps these for its forensics+ * handlers (crash-report.log) once the runtime boots.+ */+function describeBootError(err: unknown): string {+ if (err instanceof Error) {+ return process.env.MERCURY_DEBUG && err.stack ? err.stack : err.message;+ }+ return String(err);+}+function bootUncaughtException(err: unknown): void {+ try { process.stderr.write(`\n✗ Mercury hit an unexpected error: ${describeBootError(err)}\n`); } catch { /* stderr gone */ }+ process.exit(1);+}+function bootUnhandledRejection(reason: unknown): void {+ if (reason instanceof InputClosedError) {+ try { process.stderr.write(`\n✗ ${reason.message}\n`); } catch { /* stderr gone */ }+ process.exit(1);+ }+ bootUncaughtException(reason);+}+function installBootCrashHandlers(): void {+ process.on('uncaughtException', bootUncaughtException);+ process.on('unhandledRejection', bootUnhandledRejection);+}+function removeBootCrashHandlers(): void {+ process.off('uncaughtException', bootUncaughtException);+ process.off('unhandledRejection', bootUnhandledRejection);+}+installBootCrashHandlers();+const program = new Command();program