Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

refactor(interaction): route legacy prompt and stdin helpers through interaction.ts

garrytana299e6aeae03
diff --git a/scripts/check-orphan-modules.mjs b/scripts/check-orphan-modules.mjs
index 52011d6e06..c2c6af9562 100644
--- a/scripts/check-orphan-modules.mjs
+++ b/scripts/check-orphan-modules.mjs
@@ -81,7 +81,6 @@ const PERMITTED_TEST_ONLY = [
{ path: 'src/core/ingestion/sources/gstack-learnings.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision' },
{ path: 'src/core/ingestion/sources/inbox-folder.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/guides/data-ingestion.md promises the inbox folder)' },
{ path: 'src/core/consent.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (C1/C2 command handlers) land on the collector' },
- { path: 'src/core/interaction.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (A5 prompt shims, C5 readers) land on the collector' },
{ path: 'src/core/ops/callable.ts', reason: 'held: agent operator wave A0 freeze; tools/list + dispatch wiring lands in A2 on the collector' },
{ path: 'src/core/readiness.ts', reason: 'held: agent operator wave A0 freeze; runtime consumers (E/F readiness producers) land on the collector' },
{ path: 'src/core/ingestion/sources/markdown-greenfield.ts', reason: 'held: ingestion cluster awaits a wire-up vs delete product decision (docs/migrations/v0.41.2-markdown-greenfield.md)' },
diff --git a/src/cli.ts b/src/cli.ts
index 77feb9d737..c9ce6eaebf 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -6,7 +6,8 @@ import { installSigchldHandler } from './core/zombie-reap.ts';
installSigchldHandler();
import { installCleanupSignalHandlers } from './core/serve-invocation.ts';
-import { readFileSync, existsSync, unlinkSync, fstatSync } from 'fs';
+import { readFileSync, existsSync, unlinkSync } from 'fs';
+import { readStdinBounded as readStdinPayload } from './core/interaction.ts';
import { spawn } from 'child_process';
import {
readUpdateCache,
@@ -1121,13 +1122,14 @@ export function parseOpArgs(op: Operation, args: string[]): Record<string, unkno
* returns without blocking (`gbrain put x < file`, `< /dev/null` → '').
* - FIFO/socket: stream-read with a deadline on the FIRST byte only. A real
* pipe (`echo foo | gbrain put x`, heredocs) delivers its first byte
- * within milliseconds; once any data arrives the deadline is lifted and
- * we read to EOF like readFileSync did (slow producers stay supported).
+ * within milliseconds; once data flows only a 60s inactivity timeout
+ * applies, reset on every chunk (slow producers stay supported).
* An empty-but-closed pipe (`: | gbrain put x`) EOFs immediately → ''.
* A pipe that never delivers a byte times out → param stays unset, so
* the existing required-param usage error fires (fail fast, exit 1).
*
- * GBRAIN_STDIN_TIMEOUT_MS overrides the first-byte deadline (default 5000).
+ * GBRAIN_STDIN_TIMEOUT_MS overrides the first-byte deadline (default 30s,
+ * stderr notice at 5s). The reader is interaction.ts readStdinBounded (A5).
* Exported for tests; called by the op dispatch right after parseOpArgs.
*/
export async function applyStdinParam(
@@ -1155,56 +1157,15 @@ export async function applyStdinParam(
}
}
-/** First-byte deadline for pipe/socket stdin (#3513). Env-overridable escape hatch. */
-function stdinFirstByteTimeoutMs(): number {
- const n = Number(process.env.GBRAIN_STDIN_TIMEOUT_MS);
- return Number.isFinite(n) && n > 0 ? n : 5000;
-}
-
/**
- * Returns the full stdin content, '' for a readable-but-empty stdin, or
- * null when stdin is a pipe/socket that never delivered a byte within the
- * first-byte deadline (or the fd is closed/unreadable).
+ * Legacy-signature shim over interaction.ts readStdinBounded (A5): the full
+ * stdin content, '' for a readable-but-empty stdin, or null for anything else
+ * (first-byte or inactivity timeout, stream error, closed fd). No byte cap
+ * here: applyStdinParam keeps its own 5MB check and message.
*/
export async function readStdinBounded(): Promise<string | null> {
- let isPipeOrSocket: boolean;
- try {
- const st = fstatSync(0);
- isPipeOrSocket = st.isFIFO() || st.isSocket();
- } catch {
- return null; // closed/invalid fd — treat as no input
- }
- if (!isPipeOrSocket) {
- // Regular file redirect, /dev/null, etc. — read returns without blocking.
- try {
- return readFileSync(0, 'utf-8');
- } catch {
- return null;
- }
- }
- return await new Promise<string | null>((resolve) => {
- const chunks: Buffer[] = [];
- let gotData = false;
- const timer = setTimeout(() => {
- if (!gotData) {
- process.stdin.destroy();
- resolve(null);
- }
- }, stdinFirstByteTimeoutMs());
- const finish = () => {
- clearTimeout(timer);
- resolve(Buffer.concat(chunks).toString('utf-8'));
- };
- process.stdin.on('data', (c: Buffer) => {
- if (!gotData) {
- gotData = true;
- clearTimeout(timer); // deadline applies to the FIRST byte only
- }
- chunks.push(c);
- });
- process.stdin.once('end', finish);
- process.stdin.once('error', finish);
- });
+ const r = await readStdinPayload({ maxBytes: Infinity });
+ return r.kind === 'data' ? r.text : r.kind === 'empty' ? '' : null;
}
/**
diff --git a/src/commands/reinit-pglite.ts b/src/commands/reinit-pglite.ts
index cf124b774e..085ef7493c 100644
--- a/src/commands/reinit-pglite.ts
+++ b/src/commands/reinit-pglite.ts
@@ -23,6 +23,7 @@ import { assertManagedFilesystemWrite } from '../core/persistence/filesystem-gua
import { existsSync, statSync, rmSync } from 'fs';
import { dirname } from 'path';
import { loadConfig, loadConfigFileOnly, gbrainPath } from '../core/config.ts';
+import { promptYesNo } from '../core/interaction.ts';
interface ReinitOpts {
embeddingModel: string;
@@ -96,7 +97,11 @@ export async function runReinitPglite(args: string[]): Promise<void> {
'Non-TTY environment requires --yes to confirm destruction.',
);
}
- const confirmed = await promptYesNo('Wipe and reinit?');
+ // Defense in depth behind the non-TTY refusal above: a non-TTY stdin declines
+ // instead of reading. The shared prompt treats EOF as a decline and writes to
+ // stderr so stdout stays clean for --json payloads.
+ const confirmed = process.stdin.isTTY === true
+ && await promptYesNo('Wipe and reinit? (y/N): ', { output: process.stderr });
if (!confirmed) {
if (opts.jsonOutput) {
console.log(JSON.stringify({ status: 'aborted', reason: 'user_declined' }));
@@ -333,31 +338,3 @@ function fail(jsonOutput: boolean, reason: string, message: string): never {
}
process.exit(1);
}
-
-async function promptYesNo(question: string): Promise<boolean> {
- // W0 fix-wave (Tier-1 #15): non-interactive stdin (CI, pipes, spawned
- // agents) resolves to the safe default instead of hanging — this prompt
- // had no TTY guard and no end/EOF path, so a closed stdin parked the
- // process permanently. This command wipes the store; decline-by-default
- // is the only safe non-interactive answer (--yes stays the escape hatch).
- if (!process.stdin.isTTY) return false;
- // Prompt on stderr so stdout stays clean for --json payloads.
- process.stderr.write(`${question} (y/N): `);
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- const stdin = process.stdin as any;
- stdin.setEncoding?.('utf8');
- return new Promise<boolean>((resolve) => {
- const cleanup = () => {
- stdin.off?.('data', onData);
- stdin.off?.('end', onEnd);
- };
- const onEnd = () => { cleanup(); resolve(false); }; // EOF = decline
- const onData = (chunk: string) => {
- const answer = chunk.trim().toLowerCase();
- cleanup();
- resolve(answer === 'y' || answer === 'yes');
- };
- stdin.on?.('data', onData);
- stdin.on?.('end', onEnd);
- });
-}
diff --git a/src/core/cli-util.ts b/src/core/cli-util.ts
index 9778be17d5..358e47edda 100644
--- a/src/core/cli-util.ts
+++ b/src/core/cli-util.ts
@@ -1,72 +1,9 @@
/**
- * Prompt on stdout, read one line from stdin, return trimmed string.
- * Shared helper used by interactive CLI flows (init, apply-migrations, etc.).
+ * Legacy home of the shared prompt helpers. They live in
+ * `src/core/interaction.ts` now (agent operator wave A5); these re-exports
+ * stay for one release with unchanged return contracts:
+ * - promptLine(prompt): string (trimmed line; '' on EOF/timeout, no longer hangs)
+ * - promptLineStderr(prompt, {timeoutMs}): string | null (null on EOF/timeout)
+ * New code: use readLine() from interaction.ts.
*/
-export function promptLine(prompt: string): Promise<string> {
- return new Promise((resolve) => {
- process.stdout.write(prompt);
- process.stdin.setEncoding('utf-8');
- process.stdin.once('data', (chunk) => {
- const data = chunk.toString().trim();
- process.stdin.pause();
- resolve(data);
- });
- process.stdin.resume();
- });
-}
-
-/**
- * Same as promptLine, but writes the prompt to stderr instead of stdout AND
- * resolves to `null` on stdin EOF or after `timeoutMs` (default 5 minutes)
- * instead of hanging forever. Used when the surrounding command must keep
- * stdout clean for machine-readable output (JSON, piped data); the thin-client
- * upgrade prompt fires before any routed command runs and would otherwise
- * pollute `gbrain query > out.json`.
- *
- * Return contract:
- * - resolves to a `string` (trimmed) on the first stdin data event
- * - resolves to `null` on stdin 'end' (parent shell closed, /dev/null piped
- * past the TTY check, etc.) or after `timeoutMs` elapses
- * - never rejects
- *
- * Callers MUST handle null explicitly — it is NOT the same as an empty string
- * (which means "user pressed Enter").
- */
-export function promptLineStderr(prompt: string, opts: { timeoutMs?: number } = {}): Promise<string | null> {
- const timeoutMs = opts.timeoutMs ?? 300_000;
- return new Promise((resolve) => {
- process.stderr.write(prompt);
- process.stdin.setEncoding('utf-8');
- let settled = false;
- let timer: ReturnType<typeof setTimeout> | null = null;
- const cleanup = () => {
- process.stdin.removeListener('data', onData);
- process.stdin.removeListener('end', onEnd);
- if (timer !== null) clearTimeout(timer);
- process.stdin.pause();
- };
- const onData = (chunk: Buffer | string) => {
- if (settled) return;
- settled = true;
- cleanup();
- resolve(chunk.toString().trim());
- };
- const onEnd = () => {
- if (settled) return;
- settled = true;
- cleanup();
- resolve(null);
- };
- if (timeoutMs > 0) {
- timer = setTimeout(() => {
- if (settled) return;
- settled = true;
- cleanup();
- resolve(null);
- }, timeoutMs);
- }
- process.stdin.once('data', onData);
- process.stdin.once('end', onEnd);
- process.stdin.resume();
- });
-}
+export { promptLine, promptLineStderr } from './interaction.ts';
diff --git a/src/core/confirm-prompt.ts b/src/core/confirm-prompt.ts
index 5f10940072..c18bae2865 100644
--- a/src/core/confirm-prompt.ts
+++ b/src/core/confirm-prompt.ts
@@ -1,42 +1,7 @@
/**
- * #4318 — shared interactive [y/N] confirm.
- *
- * The old inline twins (sync-cost-gate.ts, reindex-code.ts) called
- * `rl.close()` BEFORE resolving the answer, and their unguarded
- * `rl.on('close', () => resolve(false))` listener fired synchronously during
- * that close — so the promise settled `false` before the real answer's
- * resolve ran and a typed "y" was read as a decline (the cost gate refused
- * every interactive approval).
- *
- * Rules pinned here (test/confirm-prompt.test.ts):
- * - resolve the ANSWER first, then close the interface;
- * - the 'close' listener resolves(false) ONLY when no answer arrived
- * (true EOF / Ctrl-D — decline, matching the [y/N] default).
+ * #4318 — shared interactive [y/N] confirm. Lives in
+ * `src/core/interaction.ts` now (agent operator wave A5); this re-export stays
+ * for one release with the same contract: true on y/yes, false on anything
+ * else or EOF. The close-race rules are pinned by test/confirm-prompt.test.ts.
*/
-
-import { createInterface } from 'node:readline';
-
-export interface ConfirmStreams {
- input?: NodeJS.ReadableStream;
- output?: NodeJS.WritableStream;
-}
-
-/** Interactive [y/N] prompt. Resolves true on y/yes; false on anything else or EOF. */
-export async function promptYesNo(question: string, streams: ConfirmStreams = {}): Promise<boolean> {
- return new Promise((resolve) => {
- const rl = createInterface({
- input: streams.input ?? process.stdin,
- output: streams.output ?? process.stdout,
- });
- let answered = false;
- rl.question(question, (answer) => {
- answered = true;
- const a = answer.trim().toLowerCase();
- resolve(a === 'y' || a === 'yes');
- rl.close();
- });
- rl.on('close', () => {
- if (!answered) resolve(false);
- });
- });
-}
+export { promptYesNo, type ConfirmStreams } from './interaction.ts';
diff --git a/src/core/progressive-batch/orchestrator.ts b/src/core/progressive-batch/orchestrator.ts
index 7003539b63..b28ac08440 100644
--- a/src/core/progressive-batch/orchestrator.ts
+++ b/src/core/progressive-batch/orchestrator.ts
@@ -42,6 +42,7 @@
import { getCurrentBudgetTracker } from '../ai/gateway.ts';
import type { BudgetTracker } from '../budget/budget-tracker.ts';
+import { isInteractive } from '../interaction.ts';
import { logProgressiveBatchEvent } from './audit.ts';
import { defaultStageReport } from './stage-report.ts';
import type {
@@ -163,17 +164,6 @@ function trackerHeadroom(tracker: BudgetTracker): number | null {
return Math.max(0, snapshot.maxCostUsd - snapshot.cumulativeCostUsd);
}
-/**
- * Detect TTY for interactive grace. Skips when stdin OR stdout is
- * not a TTY (e.g. piped output, cron, launchd, Minion workers).
- *
- * GBRAIN_PROGRESSIVE_BATCH_AUTO=1 forces non-interactive.
- */
-function isInteractive(): boolean {
- if (process.env.GBRAIN_PROGRESSIVE_BATCH_AUTO === '1') return false;
- return Boolean(process.stdin.isTTY && process.stderr.isTTY);
-}
-
/**
* Wait up to `ms` for a Ctrl-C (SIGINT). Resolves to `true` if
* SIGINT was received (caller should abort). Resolves to `false`
@@ -488,7 +478,7 @@ export async function runProgressiveBatch<T>(
const stagesCompleted: Stage[] = [];
const interactiveMs = policy.interactiveAbortMs ?? 0;
- const interactiveOn = interactiveMs > 0 && isInteractive() && !disabled;
+ const interactiveOn = interactiveMs > 0 && process.env.GBRAIN_PROGRESSIVE_BATCH_AUTO !== '1' && isInteractive() && !disabled;
const maxErrorRate = policy.maxErrorRate ?? 0.02;
for (let i = 0; i < stageSequence.length; i++) {
diff --git a/test/cli-util-prompt.serial.test.ts b/test/cli-util-prompt.serial.test.ts
index eb46559eb8..15c37809cf 100644
--- a/test/cli-util-prompt.serial.test.ts
+++ b/test/cli-util-prompt.serial.test.ts
@@ -14,9 +14,11 @@
* that checks truthiness instead of `=== null` conflates "user pressed
* Enter" (empty string) with "stdin closed / timed out" (null). Both sides
* of that boundary are pinned below.
- * - `promptLine` (the stdout variant) has NO EOF handling: on a closed stdin
- * it never resolves. Callers must TTY-gate before using it; the EOF-safe
- * contract belongs to `promptLineStderr` alone.
+ * - `promptLine` (the stdout variant) resolves '' on a closed stdin. It
+ * used to have no EOF handling and hung forever; agent operator wave A5
+ * (docs/designs/AGENT_OPERATOR_WAVE.md) moved both helpers into
+ * src/core/interaction.ts, where EOF is a decline. cli-util.ts re-exports
+ * them for one release.
* - Neither helper checks `isTTY` — piped (non-TTY) stdin is read normally.
* The TTY gate lives at call sites, not in the util.
* - `promptLineStderr` writes its prompt to stderr (stdout stays clean for
@@ -136,23 +138,25 @@ process.exit(0);
expect(r.stdout).toContain('NAME> ');
}, 15_000);
- test('EOF reality pin: promptLine NEVER resolves on closed stdin (no end handler — callers must TTY-gate)', () => {
- // Race promptLine against a 1.5s timer on an immediately-EOF stdin. The
- // timer winning pins that promptLine has no EOF path: it would hang a
- // non-interactive caller forever. If this test ever flips to 'resolved',
- // promptLine grew EOF handling — update the contract docs and call sites.
+ test('EOF resolves the empty string instead of hanging (A5 contract change; was a never-resolves pin)', () => {
+ // Race promptLine against a 5s timer on an immediately-EOF stdin, twice
+ // in a row: the second call sees an already-ended stream and must not
+ // hang either.
const script = `
const { promptLine } = await import(${JSON.stringify(UTIL_PATH)});
-const winner = await Promise.race([
+const race = () => Promise.race([
promptLine('Q> ').then((v) => ({ kind: 'resolved', v })),
- new Promise((r) => setTimeout(() => r({ kind: 'hang' }), 1500)),
+ new Promise((r) => setTimeout(() => r({ kind: 'hang' }), 5000)),
]);
-console.log('__RESULT__' + JSON.stringify(winner));
+const first = await race();
+const second = await race();
+console.log('__RESULT__' + JSON.stringify({ first, second }));
process.exit(0);
`;
const r = runChild(script, '');
expect(r.status).toBe(0);
const res = parseResult(r.stdout);
- expect(res.kind).toBe('hang');
+ expect(res.first).toEqual({ kind: 'resolved', v: '' });
+ expect(res.second).toEqual({ kind: 'resolved', v: '' });
}, 15_000);
});
diff --git a/test/cycle/regression-pr-wave-r1-r2-r4.test.ts b/test/cycle/regression-pr-wave-r1-r2-r4.test.ts
index 009da8d29d..12f2225f72 100644
--- a/test/cycle/regression-pr-wave-r1-r2-r4.test.ts
+++ b/test/cycle/regression-pr-wave-r1-r2-r4.test.ts
@@ -111,12 +111,15 @@ describe('R2 — put_page schema content stays required: true', () => {
});
describe('R4 — cross-platform stdin via fd 0 (PR #1325 regression pin)', () => {
- test('R4 source-grep: src/cli.ts uses readFileSync(0, ...) not readFileSync("/dev/stdin", ...)', () => {
+ test('R4 source-grep: the stdin reader uses readFileSync(0, ...) not readFileSync("/dev/stdin", ...)', () => {
// Belt-and-suspenders source-grep guard. The behavior of fd 0 is OS-level
// and hard to unit-test deterministically across platforms; this guard
- // catches a future contributor reverting the cross-platform fix.
- const path = join(import.meta.dir ?? '.', '..', '..', 'src', 'cli.ts');
- const src = readFileSync(path, 'utf-8');
+ // catches a future contributor reverting the cross-platform fix. The
+ // reader moved from src/cli.ts to src/core/interaction.ts (agent operator
+ // wave A5); cli.ts keeps a legacy-signature shim, so both are checked.
+ const root = join(import.meta.dir ?? '.', '..', '..', 'src');
+ const src = readFileSync(join(root, 'core', 'interaction.ts'), 'utf-8');
+ expect(readFileSync(join(root, 'cli.ts'), 'utf-8')).not.toMatch(/readFileSync\(\s*['"]\/dev\/stdin['"]/);
// The exact pattern the PR replaced. If anyone reintroduces it, R4 fires.
// Look for `'/dev/stdin'` with surrounding quote so we don't false-fire