/** Signal handlers only request cancellation. The owning turn saves and exits. */ export function createCliLifecycle() { const controller = new AbortController(); let exitCode: number | undefined; const interrupt = () => { exitCode ??= 130; controller.abort(new DOMException('Interrupted', 'AbortError')); }; const terminate = () => { exitCode ??= 143; controller.abort(new DOMException('Terminated', 'AbortError')); }; const outputError = (error: NodeJS.ErrnoException) => { exitCode ??= 1; controller.abort(error); }; process.on('SIGINT', interrupt); process.on('SIGTERM', terminate); process.stdout.on('error', outputError); process.stderr.on('error', outputError); return { signal: controller.signal, fail(error: Error) { exitCode ??= 1; controller.abort(error); }, get exitCode() { return exitCode; }, dispose() { process.removeListener('SIGINT', interrupt); process.removeListener('SIGTERM', terminate); process.stdout.removeListener('error', outputError); process.stderr.removeListener('error', outputError); }, }; } /** Wait for queued protocol output before removing error handlers or exiting. */ export async function flushCliOutput(): Promise { await Promise.all( [process.stdout, process.stderr].map( (stream) => new Promise((resolve) => { if ( stream.destroyed || !stream.writable || stream.writableLength === 0 ) return resolve(); try { stream.write('', () => resolve()); } catch { resolve(); } }), ), ); }