Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(interaction): A5 bounded stdin reads, EOF-safe prompts, forced-non-interactive notice

garrytan4ac480250327
diff --git a/docs/architecture/key-files/core-services-2.md b/docs/architecture/key-files/core-services-2.md
index e784a2e7a0..5b9e8d2ce1 100644
--- a/docs/architecture/key-files/core-services-2.md
+++ b/docs/architecture/key-files/core-services-2.md
@@ -20,6 +20,8 @@ Current behavior and load-bearing invariants; history belongs in Git and CHANGEL
- `src/core/facts/write-single.ts` — `writeSingleFact(fact, ctx)`: the zero-LLM single-fact seam behind `remember`. `runFactsPipeline` is extraction-first (LLM-gated) and cannot back a pre-formed fact; this reuses the pipeline's post-extraction stages directly: resolve → embedding-cosine dedup (same 0.95 threshold) → fence-first write with the same legacy DB-only fallbacks (thin-client, unparented, stub-guard). Supersession: deterministic rule — same entity_slug + same kind + similarity ≥ threshold + DIFFERENT text ⇒ the new fact supersedes (fence path: append new + `forgetFactInFence(old, { supersededBy })`, which strikes the old row with a page-local `#N` supersession reference and records no withdrawal, + superseded_by link; DB path: engine insertFact supersedeId). Pinned by `test/facts-supersede-not-withdrawal.test.ts`. Provenance lands on NewFact.source verbatim (no FactsBackstopCtx). No embedding provider ⇒ `degraded_dedup: true` (near-duplicates may insert — documented). `isNullLikeEntity(entity)` (exported) normalizes null-like entity tokens (`"null"`, `"undefined"`, `"none"`, `"n/a"`, `"nil"`, `"-"`, empty/whitespace) to ABSENT before resolution — applied here rather than only at the verb boundary so EVERY writeSingleFact caller gets the guard and the `resolved?.slug ?? entityRef` fallback can never adopt `"null"` as a slug. On a managed brain, after the withdrawal check and embedding, the fact publishes through `publishManagedEntityFacts` (`src/core/facts/managed-fact-write.ts`, the `managed_facts_entity` intent: fence row, index row and file together, dedup at publication, and the same-kind near-duplicate supersession rule via the intent's `supersede` flag, which strikes the old fence row and expires and links the old fact in the same transaction; an explicit per-fact context is kept; an entity without a live page lands database-only on `memory/unattributed` and, through the intent's opt-in `attribute_fallback` flag, which only writeSingleFact sets, keeps the resolver's fallback slug as `entity_slug` with no row number, so dedup and withdrawal checks stay per entity; the facts backstop never sets it and keeps those rows unattributed). `writeFactsToFence` (`fence-write.ts`) takes the same path on a managed brain, after dropping withdrawn claims.
- `src/core/facts/managed-fact-write.ts` — `publishManagedEntityFacts(engine, sourceId, entity, facts)` builds one managed facts session per visibility (request identity derived from the write, so a retried job replays its receipt; `attributeFallback` sets the intent's `attribute_fallback`), keeps a caller's vector only when it matches the brain's facts embedding signature, and returns ids in input order; `managedFactWritePreflight` runs the same session checks before a caller's model call.
+- `src/core/interaction.ts` — the one interaction primitive (agent operator wave A5). `isInteractive(probe?)` needs two TTYs and no `GBRAIN_NON_INTERACTIVE`, `CI` or agent-process marker (`agentProcessMarker()`: `CLAUDECODE`, `CLAUDE_CODE_ENTRYPOINT`, `CODEX_SANDBOX`, `CODEX_CI`, `OPENCODE`, `OPENCODE_PID`; never `CODEX_HOME`); `GBRAIN_INTERACTIVE=1` overrides on two TTYs only, and a marker or `CI` forcing prompts off prints one stderr line per process naming it and the override. Neither variable implies consent. `readLine` is the prompt read (stderr prompt; EOF/timeout = decline; `{kind:'eof'}` without reading when non-interactive; bytes after the newline are pushed back for the next prompt). `readStdinBounded` is the payload read: 30 s first-byte deadline (`GBRAIN_STDIN_TIMEOUT_MS` overrides; stderr notice at 5 s), 60 s inactivity reset per chunk, no total cap, 5 MB default byte cap; `data`/`empty`/`timeout{phase}`/`cancelled`/`error` are distinct and partial input is never `data`. Every reader removes its listeners and pauses the stream so the process can exit; a failed read of process stdin also destroys it. Also hosts the legacy `promptLine` (now `''` on EOF), `promptLineStderr` and `promptYesNo`, re-exported by `cli-util.ts` / `confirm-prompt.ts` for one release; `src/cli.ts` keeps a legacy `readStdinBounded(): string | null` shim. Pinned by `test/interaction.test.ts` (decision table, injected streams) and `test/interaction-stdin.serial.test.ts` (real stdin, PTY, natural exit).
+
- `src/core/ops/` — the operations contract's module directory (the meat behind the `operations.ts` façade). `contract.ts` is the foundation contract: the error envelope (`ErrorCode`/`OperationError`/`verbError`), the shared param/logger/auth/context types, and the `Operation` interface — re-exported wholesale by the façade. `context.ts` carries the context validators + scope resolvers: the upload/slug/filename validators, the subagent and bound-client slug fences, and the source-scope resolution ladder (some internal helpers are exported only here and deliberately NOT re-exported from the façade — import those from `context.ts` directly). The remaining modules are one-per-op-domain (`pages.ts`, `search.ts`, `takes.ts`, `tags.ts`, `links.ts`, `timeline.ts`, `admin.ts`, `skills-catalog.ts`, `sync-status.ts`, `raw-data.ts`, `chunks.ts`, `ingest-log.ts`, `files.ts`, `jobs.ts`, `orphans.ts`, `calibration.ts`, `salience.ts`, `facts.ts`, `sources.ts`, `transcripts.ts`, `insights.ts`, `image.ts`, `extraction.ts`, `code-intel.ts`, `chronicle.ts`, `embedding-migration.ts`, `request-tools.ts`, `schema-packs.ts`, `skillopt.ts`), each exporting a `<domain>Operations` map that the façade spreads into the single `operations` export. Add a new op in the matching domain module — an existing domain needs no façade change; a brand-new domain module gets one spread line in `operations.ts`. `facadeExpansion` in `scripts/generate-flag-registry.ts` maps the façade to this whole directory so every module's `--flag` text stays on the command flag-scan surface.
- `src/core/ops/admin.ts` — the admin/diagnostics domain module (`get_stats`, `get_health`, `get_brain_identity`, …). `get_health` adds `embedding_column`, the registry-active vector column its coverage counts were measured on (legacy `embedding` when the registry is unreadable), on both engines (`test/get-health-embedding-column.test.ts` + its Postgres arm). `get_versions` reads an explicit column list (`PAGE_VERSION_COLUMNS` in `engine-sql/pages.ts`), so the write attribution columns never reach a plain `read` caller; trusted local callers and `admin` holders (`canReadWriteAttribution`) also get `written_by` and `archived_by` from `attributeVersions`. It filters protected facts/takes from both canonical body and timeline, preserves legacy missing timeline fields, and retains engine-side current/historical page privacy predicates for every snapshot field. All three aggregate ops confine remote callers via the same ladder reads use: `ctx.remote === false` keeps the trusted brain-wide view; every other caller gets `sourceScopeOpts(ctx)` (federated array > scalar > the unmatchable `__all__` sentinel, which fail-closes to zeros) threaded into `engine.getStats(scope)`/`getHealth(scope)` — aggregates leak by subtraction, so they scope exactly like reads, and read-scope `get_brain_identity` is confined the same way. `get_health`'s `migrations {pending, partial, wedged, skipped_future}` block stays GLOBAL for scoped callers by decision: it is a host filesystem ledger with no per-source semantics, a wedged host migration is exactly what a remote agent needs to see to explain degraded behavior, and it is composed at the op layer (not in `BrainEngine.getHealth` — growing the engine interface would force both engines to duplicate a file read). `get_health` serves repeat calls from `src/core/health-memo.ts` and returns `computed_at`, the time its counters were read.
diff --git a/scripts/serial-weights.json b/scripts/serial-weights.json
index 85c89e694e..806cdf316a 100644
--- a/scripts/serial-weights.json
+++ b/scripts/serial-weights.json
@@ -145,6 +145,7 @@
"test/import-signature-stamp.serial.test.ts": 6,
"test/import-source-cr-mode.serial.test.ts": 4,
"test/init-picker-pty.serial.test.ts": 14,
+ "test/interaction-stdin.serial.test.ts": 12,
"test/jobs-autopilot-cycle-braindir.serial.test.ts": 4,
"test/jobs-embed-background-dryrun.serial.test.ts": 3,
"test/jobs-embed-background-parity.serial.test.ts": 11,
diff --git a/scripts/test-weights.json b/scripts/test-weights.json
index 9f3185387e..59c79f477e 100644
--- a/scripts/test-weights.json
+++ b/scripts/test-weights.json
@@ -999,6 +999,7 @@
"test/integrations.test.ts": 30,
"test/integrity.test.ts": 2493,
"test/intent-weights.test.ts": 14,
+ "test/interaction.test.ts": 1,
"test/job-isolation-allow-shell-jobs.test.ts": 4,
"test/job-isolation-protocol.test.ts": 100,
"test/job-pull-policy.test.ts": 21,
diff --git a/scripts/ubicloud/weights.json b/scripts/ubicloud/weights.json
index 48b9ecad00..74426dc719 100644
--- a/scripts/ubicloud/weights.json
+++ b/scripts/ubicloud/weights.json
@@ -430,6 +430,7 @@
"serial:test/import-signature-stamp.serial.test.ts": 2228,
"serial:test/import-source-cr-mode.serial.test.ts": 1649,
"serial:test/init-picker-pty.serial.test.ts": 8243,
+ "serial:test/interaction-stdin.serial.test.ts": 12000,
"serial:test/jobs-autopilot-cycle-braindir.serial.test.ts": 1494,
"serial:test/jobs-child-readiness.serial.test.ts": 1246,
"serial:test/jobs-embed-background-dryrun.serial.test.ts": 2053,
@@ -1554,6 +1555,7 @@
"unit:test/integrations.test.ts": 211,
"unit:test/integrity.test.ts": 5391,
"unit:test/intent-weights.test.ts": 236,
+ "unit:test/interaction.test.ts": 1100,
"unit:test/job-isolation-allow-shell-jobs.test.ts": 357,
"unit:test/job-isolation-protocol.test.ts": 457,
"unit:test/job-pull-policy.test.ts": 644,
diff --git a/src/core/interaction.ts b/src/core/interaction.ts
index b1979a161e..ec4d65f302 100644
--- a/src/core/interaction.ts
+++ b/src/core/interaction.ts
@@ -3,8 +3,15 @@
* answer a prompt, prompt reads that treat EOF/timeout as a decline, and
* bounded payload reads from stdin. Neither GBRAIN_INTERACTIVE nor
* GBRAIN_NON_INTERACTIVE implies consent.
+ *
+ * Also the one home of the legacy prompt helpers (`promptLine`,
+ * `promptLineStderr`, `promptYesNo`); `src/core/cli-util.ts` and
+ * `src/core/confirm-prompt.ts` re-export them for one release.
*/
+import { fstatSync, readFileSync } from 'node:fs';
+import { createInterface } from 'node:readline';
+
export interface InteractiveProbe {
env?: NodeJS.ProcessEnv;
stdinIsTTY?: boolean; stdoutIsTTY?: boolean;
@@ -21,6 +28,18 @@ export function agentProcessMarker(env: NodeJS.ProcessEnv = process.env): string
const truthy = (v: string | undefined) => v !== undefined && v !== '' && v !== '0' && v.toLowerCase() !== 'false';
+let forcedNoticePrinted = false;
+
+/** One stderr line per process when an agent marker or CI turns off prompts on two TTYs. */
+function noteForcedNonInteractive(cause: string): void {
+ if (forcedNoticePrinted) return;
+ forcedNoticePrinted = true;
+ process.stderr.write(
+ `[gbrain] prompts are off: ${cause} is set, so confirmations decline by default. ` +
+ `A human at this terminal can set GBRAIN_INTERACTIVE=1 to answer prompts.\n`,
+ );
+}
+
export function isInteractive(probe: InteractiveProbe = {}): boolean {
const env = probe.env ?? process.env;
const stdinTTY = probe.stdinIsTTY ?? process.stdin.isTTY === true;
@@ -28,38 +47,125 @@ export function isInteractive(probe: InteractiveProbe = {}): boolean {
if (!stdinTTY || !stdoutTTY) return false;
if (truthy(env.GBRAIN_INTERACTIVE)) return true;
if (truthy(env.GBRAIN_NON_INTERACTIVE)) return false;
- if (truthy(env.CI)) return false;
- return agentProcessMarker(env) === null;
+ const cause = truthy(env.CI) ? 'CI' : agentProcessMarker(env);
+ if (cause === null) return true;
+ noteForcedNonInteractive(cause);
+ return false;
}
export type LineRead = { kind: 'line'; text: string } | { kind: 'eof' } | { kind: 'timeout' };
-/** Prompt read: stderr prompt; EOF/timeout = decline. Returns {kind:'eof'} at once when !isInteractive(). */
-export async function readLine(opts: { prompt: string; timeoutMs?: number }): Promise<LineRead> {
- if (!isInteractive()) return { kind: 'eof' };
- const timeoutMs = opts.timeoutMs ?? 300_000;
+interface LineSource {
+ prompt: string;
+ timeoutMs?: number;
+ input?: NodeJS.ReadableStream;
+ output?: NodeJS.WritableStream;
+}
+
+/** An earlier reader already saw EOF (or the stream was destroyed): 'end' will never fire again. */
+function streamFinished(stream: NodeJS.ReadableStream): boolean {
+ const r = stream as NodeJS.ReadableStream & { readableEnded?: boolean; destroyed?: boolean };
+ return r.readableEnded === true || r.destroyed === true;
+}
+
+/**
+ * Read one line (trimmed) from `input`. EOF without a newline yields the
+ * buffered text as the line, or `eof` when nothing arrived. Bytes after the
+ * newline are pushed back so the next prompt sees them. Always removes its
+ * listeners and pauses the stream, so the process can exit afterwards.
+ */
+function readLineFrom(src: LineSource): Promise<LineRead> {
+ const input = (src.input ?? process.stdin) as NodeJS.ReadableStream & { unshift?(chunk: Buffer): void };
+ const timeoutMs = src.timeoutMs ?? 300_000;
+ (src.output ?? process.stderr).write(src.prompt);
+ if (streamFinished(input)) return Promise.resolve({ kind: 'eof' });
return new Promise(resolve => {
- process.stderr.write(opts.prompt);
- process.stdin.setEncoding('utf-8');
- let buf = '';
+ let buf = Buffer.alloc(0);
let timer: ReturnType<typeof setTimeout> | null = null;
- const done = (r: LineRead) => {
- process.stdin.removeListener('data', onData);
- process.stdin.removeListener('end', onEnd);
+ let settled = false;
+ const done = (r: LineRead, rest?: Buffer) => {
+ if (settled) return;
+ settled = true;
+ input.removeListener('data', onData);
+ input.removeListener('end', onEnd);
+ input.removeListener('error', onEnd);
if (timer) clearTimeout(timer);
- process.stdin.pause();
+ input.pause();
+ if (rest?.length) { try { input.unshift?.(rest); } catch { /* best effort */ } }
resolve(r);
};
const onData = (chunk: string | Buffer) => {
- buf += chunk.toString();
- const nl = buf.indexOf('\n');
- if (nl >= 0) done({ kind: 'line', text: buf.slice(0, nl).replace(/\r$/, '').trim() });
+ buf = Buffer.concat([buf, typeof chunk === 'string' ? Buffer.from(chunk) : chunk]);
+ const nl = buf.indexOf(0x0a);
+ if (nl >= 0) done({ kind: 'line', text: buf.subarray(0, nl).toString('utf8').trim() }, buf.subarray(nl + 1));
};
- const onEnd = () => done(buf ? { kind: 'line', text: buf.trim() } : { kind: 'eof' });
+ const onEnd = () => done(buf.length ? { kind: 'line', text: buf.toString('utf8').trim() } : { kind: 'eof' });
if (timeoutMs > 0) timer = setTimeout(() => done({ kind: 'timeout' }), timeoutMs);
- process.stdin.on('data', onData);
- process.stdin.once('end', onEnd);
- process.stdin.resume();
+ input.on('data', onData);
+ input.once('end', onEnd);
+ input.once('error', onEnd);
+ input.resume();
+ });
+}
+
+/**
+ * Prompt read: stderr prompt; EOF/timeout = decline. Returns {kind:'eof'} at once when !isInteractive().
+ * `input`/`output`/`probe` are injection seams for tests and embedders; the default is process stdin/stderr.
+ */
+export async function readLine(
+ opts: { prompt: string; timeoutMs?: number; input?: NodeJS.ReadableStream; output?: NodeJS.WritableStream; probe?: InteractiveProbe },
+): Promise<LineRead> {
+ if (!isInteractive(opts.probe)) return { kind: 'eof' };
+ return readLineFrom(opts);
+}
+
+/**
+ * Legacy prompt (stdout prompt, no interactivity gate). Resolves the trimmed
+ * line; '' on EOF or timeout (it used to hang forever on a closed stdin).
+ * @deprecated use readLine.
+ */
+export async function promptLine(prompt: string): Promise<string> {
+ const r = await readLineFrom({ prompt, output: process.stdout });
+ return r.kind === 'line' ? r.text : '';
+}
+
+/**
+ * Legacy prompt that keeps stdout clean (stderr prompt, no interactivity
+ * gate). Resolves the trimmed line, or `null` on EOF or after `timeoutMs`
+ * (default 5 minutes). `null` is NOT the empty string ('' = user pressed Enter).
+ * @deprecated use readLine.
+ */
+export async function promptLineStderr(prompt: string, opts: { timeoutMs?: number } = {}): Promise<string | null> {
+ const r = await readLineFrom({ prompt, timeoutMs: opts.timeoutMs, output: process.stderr });
+ return r.kind === 'line' ? r.text : null;
+}
+
+export interface ConfirmStreams {
+ input?: NodeJS.ReadableStream;
+ output?: NodeJS.WritableStream;
+}
+
+/**
+ * Interactive [y/N] prompt. Resolves true on y/yes; false on anything else or EOF.
+ * #4318: resolve the ANSWER first, then close the interface; the 'close'
+ * listener declines only when no answer arrived (true EOF / Ctrl-D).
+ */
+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);
+ });
});
}
@@ -70,10 +176,123 @@ export type StdinRead =
| { kind: 'cancelled'; bytes: number }
| { kind: 'error'; error: Error; bytes: number };
-/** Payload read: first-byte timeout 30 s (stderr notice at 5 s), 60 s inactivity reset on progress, no total time cap. */
-export async function readStdinBounded(opts: { firstByteMs?: number; inactivityMs?: number; maxBytes?: number; signal?: AbortSignal } = {}): Promise<StdinRead> {
- const chunks: Buffer[] = [];
- for await (const chunk of process.stdin) chunks.push(Buffer.from(chunk as Buffer));
- const text = Buffer.concat(chunks).toString('utf8');
- return text.length ? { kind: 'data', text } : { kind: 'empty' };
+export interface StdinReadOptions {
+ /** First-byte deadline. Default: GBRAIN_STDIN_TIMEOUT_MS, else 30 s. */
+ firstByteMs?: number;
+ /** Silence allowed between chunks once data flows; reset on every chunk. Default 60 s. */
+ inactivityMs?: number;
+ /** Byte cap; more input is an error, never a truncated success. Default 5 MB. */
+ maxBytes?: number;
+ signal?: AbortSignal;
+ /** Injection seam (tests, embedders). Default: process.stdin, with a direct read for files and /dev/null. */
+ stream?: NodeJS.ReadableStream;
+}
+
+const DEFAULT_FIRST_BYTE_MS = 30_000;
+const FIRST_BYTE_NOTICE_MS = 5_000;
+const DEFAULT_INACTIVITY_MS = 60_000;
+export const DEFAULT_STDIN_MAX_BYTES = 5_000_000;
+
+function firstByteDeadlineMs(explicit: number | undefined): number {
+ if (explicit !== undefined) return explicit;
+ const n = Number(process.env.GBRAIN_STDIN_TIMEOUT_MS);
+ return Number.isFinite(n) && n > 0 ? n : DEFAULT_FIRST_BYTE_MS;
+}
+
+const tooLarge = (maxBytes: number, bytes: number): StdinRead =>
+ ({ kind: 'error', error: new Error(`stdin exceeds ${maxBytes} bytes; split the input into smaller pieces`), bytes });
+
+/**
+ * fd 0 as a regular file or a non-TTY character device (`< file`, `< /dev/null`)
+ * never blocks, so read it directly. Returns null when fd 0 needs the stream path.
+ */
+function readStdinFd(maxBytes: number): StdinRead | null {
+ try {
+ const st = fstatSync(0);
+ if (st.isFIFO() || st.isSocket() || process.stdin.isTTY) return null;
+ if (st.isFile() && st.size > maxBytes) return tooLarge(maxBytes, 0);
+ const text = readFileSync(0, 'utf-8');
+ const bytes = Buffer.byteLength(text, 'utf-8');
+ if (bytes > maxBytes) return tooLarge(maxBytes, bytes);
+ return bytes ? { kind: 'data', text } : { kind: 'empty' };
+ } catch (e) {
+ return { kind: 'error', error: e instanceof Error ? e : new Error(String(e)), bytes: 0 };
+ }
+}
+
+/**
+ * Payload read: first-byte timeout 30 s (stderr notice at 5 s), 60 s inactivity reset on progress, no total time cap.
+ * EOF, timeout, cancellation and stream error are distinct results; partial input is never returned as data.
+ */
+export async function readStdinBounded(opts: StdinReadOptions = {}): Promise<StdinRead> {
+ const maxBytes = opts.maxBytes ?? DEFAULT_STDIN_MAX_BYTES;
+ if (opts.signal?.aborted) return { kind: 'cancelled', bytes: 0 };
+ if (!opts.stream) {
+ const direct = readStdinFd(maxBytes);
+ if (direct) return direct;
+ }
+ const ownsStdin = !opts.stream;
+ const stream: NodeJS.ReadableStream = opts.stream ?? process.stdin;
+ if (streamFinished(stream)) return { kind: 'error', error: new Error('stdin was already consumed or closed'), bytes: 0 };
+ const firstByteMs = firstByteDeadlineMs(opts.firstByteMs);
+ const inactivityMs = opts.inactivityMs ?? DEFAULT_INACTIVITY_MS;
+ const armed = (ms: number) => Number.isFinite(ms) && ms > 0;
+
+ return new Promise<StdinRead>(resolve => {
+ const chunks: Buffer[] = [];
+ let bytes = 0;
+ let settled = false;
+ let deadline: ReturnType<typeof setTimeout> | null = null;
+ let notice: ReturnType<typeof setTimeout> | null = null;
+
+ const finish = (r: StdinRead) => {
+ if (settled) return;
+ settled = true;
+ if (deadline) clearTimeout(deadline);
+ if (notice) clearTimeout(notice);
+ stream.removeListener('data', onData);
+ stream.removeListener('end', onEnd);
+ stream.removeListener('error', onError);
+ stream.removeListener('close', onClose);
+ opts.signal?.removeEventListener('abort', onAbort);
+ stream.pause();
+ // A still-open process stdin would keep the event loop alive after a failed read.
+ if (ownsStdin && r.kind !== 'data' && r.kind !== 'empty') process.stdin.destroy();
+ resolve(r);
+ };
+ const arm = (phase: 'first_byte' | 'inactivity', ms: number) => {
+ if (deadline) clearTimeout(deadline);
+ deadline = armed(ms) ? setTimeout(() => finish({ kind: 'timeout', phase, bytes }), ms) : null;
+ };
+ const onData = (chunk: string | Buffer) => {
+ const b = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
+ if (b.length === 0) return;
+ if (bytes === 0 && notice) { clearTimeout(notice); notice = null; }
+ bytes += b.length;
+ if (bytes > maxBytes) return finish(tooLarge(maxBytes, bytes));
+ chunks.push(b);
+ arm('inactivity', inactivityMs);
+ };
+ const onEnd = () => finish(bytes ? { kind: 'data', text: Buffer.concat(chunks).toString('utf8') } : { kind: 'empty' });
+ const onError = (e: unknown) => finish({ kind: 'error', error: e instanceof Error ? e : new Error(String(e)), bytes });
+ const onClose = () => finish({ kind: 'error', error: new Error('stdin closed before end of input'), bytes });
+ const onAbort = () => finish({ kind: 'cancelled', bytes });
+
+ arm('first_byte', firstByteMs);
+ if (armed(firstByteMs) && firstByteMs > FIRST_BYTE_NOTICE_MS) {
+ notice = setTimeout(() => {
+ notice = null;
+ process.stderr.write(
+ `[gbrain] waiting for stdin: no input after ${FIRST_BYTE_NOTICE_MS / 1000}s; giving up after ${Math.round(firstByteMs / 1000)}s. ` +
+ `Pipe the payload or close stdin; set GBRAIN_STDIN_TIMEOUT_MS=<ms> to wait longer for the first byte.\n`,
+ );
+ }, FIRST_BYTE_NOTICE_MS);
+ }
+ opts.signal?.addEventListener('abort', onAbort, { once: true });
+ stream.on('data', onData);
+ stream.once('end', onEnd);
+ stream.once('error', onError);
+ stream.once('close', onClose);
+ stream.resume();
+ });
}
diff --git a/test/interaction-stdin.serial.test.ts b/test/interaction-stdin.serial.test.ts
new file mode 100644
index 0000000000..9dc8904774
--- /dev/null
+++ b/test/interaction-stdin.serial.test.ts
@@ -0,0 +1,234 @@
+/**
+ * A5 interaction primitive (src/core/interaction.ts) against a REAL process
+ * stdin: each case runs a child `bun -e` driver whose fd 0 is a pipe, a file,
+ * /dev/null or a pseudo-terminal. The driver never calls process.exit, so
+ * every case also proves the reader leaves no stdin listener or ref behind:
+ * the child must exit on its own while its stdin pipe is still held open.
+ *
+ * Serial lane: concurrent subprocess spawns (one of them sleeps 8 s to pin the
+ * slow-first-byte contract) and PTY sessions, same rationale as
+ * test/cli-stdin-hang.test.ts and test/init-picker-pty.serial.test.ts.
+ * The in-process half (decision table, injected streams) is
+ * test/interaction.test.ts.
+ */
+import { afterAll, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { launchTty, ptySupported } from './helpers/tty-harness.ts';
+
+const REPO = join(import.meta.dir, '..');
+const MOD = join(REPO, 'src', 'core', 'interaction.ts');
+const MARKERS = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'OPENCODE', 'OPENCODE_PID'];
+const TMP = mkdtempSync(join(tmpdir(), 'gbrain-interaction-'));
+afterAll(() => rmSync(TMP, { recursive: true, force: true }));
+
+const DRIVER = `
+const m = await import(${JSON.stringify(MOD)});
+const mode = process.env.MODE;
+const opts = JSON.parse(process.env.OPTS || '{}');
+let r;
+if (mode === 'payload') r = await m.readStdinBounded(opts);
+if (mode === 'cancel') {
+ const ac = new AbortController();
+ setTimeout(() => ac.abort(), 200);
+ r = await m.readStdinBounded({ ...opts, signal: ac.signal });
+}
+if (mode === 'readline') r = await m.readLine({ prompt: 'PROMPT> ', ...opts });
+if (mode === 'readline2') r = [await m.readLine({ prompt: 'ONE> ' }), await m.readLine({ prompt: 'TWO> ' })];
+if (mode === 'probe') {
+ const probe = { env: opts.env, stdinIsTTY: true, stdoutIsTTY: true };
+ r = [m.isInteractive(probe), m.isInteractive(probe)];
+}
+if (r && r.kind === 'error') r = { ...r, error: r.error.message };
+console.log('__RESULT__' + JSON.stringify(r));
+`;
+
+type Stdin = 'hold-open' | 'closed-empty' | { file: string } | { chunks: Array<{ afterMs: number; data: string }>; thenEnd: boolean };
+
+interface Run { exitedOnItsOwn: boolean; result: unknown; stderr: string; elapsedMs: number }
+
+/** Parent env minus anything that changes the decision under test. */
+function cleanEnv(extra: Record<string, string>): Record<string, string> {
+ const env: Record<string, string> = {};
+ for (const [k, v] of Object.entries(process.env)) if (v !== undefined) env[k] = v;
+ for (const k of ['GBRAIN_STDIN_TIMEOUT_MS', 'GBRAIN_INTERACTIVE', 'GBRAIN_NON_INTERACTIVE', 'CI', ...MARKERS]) delete env[k];
+ return { ...env, ...extra };
+}
+
+async function runDriver(mode: string, stdin: Stdin, opts: { env?: Record<string, string>; driverOpts?: unknown; windowMs?: number } = {}): Promise<Run> {
+ const started = Date.now();
+ const proc = Bun.spawn(['bun', '-e', DRIVER], {
+ cwd: REPO,
+ env: cleanEnv({ MODE: mode, OPTS: JSON.stringify(opts.driverOpts ?? {}), ...opts.env }),
+ stdin: typeof stdin === 'object' && 'file' in stdin ? Bun.file(stdin.file) : 'pipe',
+ stdout: 'pipe',
+ stderr: 'pipe',
+ });
+ const sink = typeof proc.stdin === 'object' && proc.stdin !== null ? proc.stdin : null;
+ let exitedOnItsOwn = true;
+ const killer = setTimeout(() => {
+ exitedOnItsOwn = false;
+ try { proc.kill('SIGKILL'); } catch { /* gone */ }
+ }, opts.windowMs ?? 20_000);
+ const feed = (async () => {
+ if (!sink) return;
+ if (stdin === 'closed-empty') return void (await sink.end());
+ if (typeof stdin === 'object' && 'chunks' in stdin) {
+ for (const c of stdin.chunks) {
+ await Bun.sleep(c.afterMs);
+ try { sink.write(c.data); await sink.flush(); } catch { /* child gone */ }
+ }
+ if (stdin.thenEnd) try { await sink.end(); } catch { /* child gone */ }
+ }
+ })();
+ const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
+ clearTimeout(killer);
+ await feed.catch(() => {});
+ try { sink?.end(); } catch { /* hold-open cleanup */ }
+ const m = stdout.match(/__RESULT__(.*)/);
+ return { exitedOnItsOwn, result: m ? JSON.parse(m[1]) : undefined, stderr, elapsedMs: Date.now() - started };
+}
+
+describe('readStdinBounded on a real process stdin', () => {
+ test('slow first byte (8 s) succeeds, with the 5 s notice naming GBRAIN_STDIN_TIMEOUT_MS', async () => {
+ const run = await runDriver('payload', { chunks: [{ afterMs: 8000, data: 'late payload' }], thenEnd: true }, { windowMs: 25_000 });
+ expect(run.exitedOnItsOwn).toBe(true);
+ expect(run.result).toEqual({ kind: 'data', text: 'late payload' });
+ expect(run.stderr).toContain('waiting for stdin');
+ expect(run.stderr).toContain('GBRAIN_STDIN_TIMEOUT_MS');
+ expect(run.stderr.match(/waiting for stdin/g)?.length).toBe(1);
+ }, 30_000);
+
+ test('an open silent pipe times out at GBRAIN_STDIN_TIMEOUT_MS and the process exits with the pipe still open', async () => {
+ const run = await runDriver('payload', 'hold-open', { env: { GBRAIN_STDIN_TIMEOUT_MS: '300' } });
+ expect(run.exitedOnItsOwn).toBe(true);
+ expect(run.result).toEqual({ kind: 'timeout', phase: 'first_byte', bytes: 0 });
+ expect(run.stderr).not.toContain('waiting for stdin');
+ }, 30_000);
+
+ test('one byte then a stall times out in the inactivity phase; the partial byte is not returned', async () => {
+ const run = await runDriver('payload', { chunks: [{ afterMs: 0, data: 'x' }], thenEnd: false }, { driverOpts: { inactivityMs: 300 } });
+ expect(run.exitedOnItsOwn).toBe(true);
+ expect(run.result).toEqual({ kind: 'timeout', phase: 'inactivity', bytes: 1 });
+ }, 30_000);
+
+ test('cancellation on a silent pipe is cancelled and the process exits', async () => {
+ const run = await runDriver('cancel', 'hold-open');
+ expect(run.exitedOnItsOwn).toBe(true);
+ expect(run.result).toEqual({ kind: 'cancelled', bytes: 0 });
+ }, 30_000);
+
+ test('an empty pipe that closes at once is empty', async () => {
+ const run = await runDriver('payload', 'closed-empty');
+ expect(run.result).toEqual({ kind: 'empty' });
+ }, 30_000);
+
+ test('/dev/null is empty without waiting', async () => {
+ const run = await runDriver('payload', { file: '/dev/null' });
+ expect(run.result).toEqual({ kind: 'empty' });
+ }, 30_000);
+
+ test('a regular file is read whole; past maxBytes it is an error', async () => {
+ const f = join(TMP, 'payload.md');
+ writeFileSync(f, '# title\nbody\n');
+ expect((await runDriver('payload', { file: f })).result).toEqual({ kind: 'data', text: '# title\nbody\n' });
+ const big = await runDriver('payload', { file: f }, { driverOpts: { maxBytes: 4 } });
+ expect((big.result as { kind: string }).kind).toBe('error');
+ }, 30_000);
+
+ test('multiple chunks then EOF are returned whole', async () => {
+ const run = await runDriver('payload', { chunks: [{ afterMs: 0, data: 'a' }, { afterMs: 100, data: 'b' }, { afterMs: 100, data: 'c' }], thenEnd: true });
+ expect(run.result).toEqual({ kind: 'data', text: 'abc' });
+ }, 30_000);
+});
+
+describe('readLine and the interactivity notice', () => {
+ test('non-interactive readLine returns eof at once without prompting, even on an open pipe', async () => {
+ const run = await runDriver('readline', 'hold-open');
+ expect(run.exitedOnItsOwn).toBe(true);
+ expect(run.result).toEqual({ kind: 'eof' });
+ expect(run.stderr).not.toContain('PROMPT>');
+ expect(run.elapsedMs).toBeLessThan(10_000);
+ }, 30_000);
+
+ for (const cause of ['CLAUDECODE', 'CODEX_CI', 'CI']) {
+ test(`${cause} on two TTYs prints ONE stderr line per process naming it and GBRAIN_INTERACTIVE=1`, async () => {
+ const run = await runDriver('probe', 'closed-empty', { driverOpts: { env: { [cause]: '1' } } });
+ expect(run.result).toEqual([false, false]);
+ const lines = run.stderr.split('\n').filter(l => l.includes('prompts are off'));
+ expect(lines.length).toBe(1);
+ expect(lines[0]).toContain(cause);
+ expect(lines[0]).toContain('GBRAIN_INTERACTIVE=1');
+ }, 30_000);
+ }
+
+ test('no notice for a human (CODEX_HOME only), GBRAIN_NON_INTERACTIVE, or the override', async () => {
+ for (const [env, want] of [
+ [{ CODEX_HOME: '/home/u/.codex' }, [true, true]],
+ [{ GBRAIN_NON_INTERACTIVE: '1', CLAUDECODE: '1' }, [false, false]],
+ [{ GBRAIN_INTERACTIVE: '1', CLAUDECODE: '1' }, [true, true]],
+ ] as const) {
+ const run = await runDriver('probe', 'closed-empty', { driverOpts: { env } });
+ expect(run.result).toEqual(want);
+ expect(run.stderr).not.toContain('prompts are off');
+ }
+ }, 30_000);
+});
+
+describe('readLine under a real pseudo-terminal', () => {
+ if (process.env.CI) {
+ test('PTY support is mandatory on CI', () => expect(ptySupported()).toBe(true));
+ }
+ const ptyTest = ptySupported() ? test : test.skip;
+ const ptyEnv = (extra: Record<string, string>) => ({ MODE: 'readline2', HOME: TMP, GBRAIN_HOME: join(TMP, '.gbrain'), ...extra });
+
+ async function drive(extra: Record<string, string>, steps: (s: ReturnType<typeof launchTty>) => Promise<void>): Promise<string> {
+ const s = launchTty(['bun', '-e', DRIVER], { cwd: REPO, env: ptyEnv(extra), dropEnv: ['CI', 'GBRAIN_INTERACTIVE', 'GBRAIN_NON_INTERACTIVE', ...MARKERS].filter(k => !(k in extra)), timeoutMs: 30_000 });
+ try {
+ await steps(s);
+ expect(await s.waitForExit(10_000)).toBe(0);
+ return s.visible();
+ } finally {
+ await s.close();
+ }
+ }
+
+ ptyTest('a human types two answers: both lines read, and the process exits on its own', async () => {
+ const out = await drive({}, async s => {
+ await s.waitFor('ONE> ', { timeoutMs: 10_000 });
+ s.send('first answer\r');
+ await s.waitFor('TWO> ', { timeoutMs: 10_000 });
+ s.send(' second \r');
+ });
+ expect(out).toContain('__RESULT__[{"kind":"line","text":"first answer"},{"kind":"line","text":"second"}]');
+ }, 40_000);
+
+ ptyTest('Ctrl-D at the prompt is eof (a decline)', async () => {
+ const out = await drive({}, async s => {
+ await s.waitFor('ONE> ', { timeoutMs: 10_000 });
+ s.send('\x04');
+ await s.waitFor('TWO> ', { timeoutMs: 10_000 });
+ });
+ expect(out).toContain('__RESULT__[{"kind":"eof"},{"kind":"eof"}]');
+ }, 40_000);
+
+ ptyTest('an agent marker on a real terminal: no prompt, eof, one notice line naming the override', async () => {
+ const out = await drive({ CLAUDECODE: '1' }, async s => { await s.waitFor('__RESULT__', { timeoutMs: 10_000 }); });
+ expect(out).toContain('__RESULT__[{"kind":"eof"},{"kind":"eof"}]');
+ expect(out).not.toContain('ONE> ');
+ expect(out.match(/prompts are off: CLAUDECODE/g)?.length).toBe(1);
+ expect(out).toContain('GBRAIN_INTERACTIVE=1');
+ }, 40_000);
+
+ ptyTest('GBRAIN_INTERACTIVE=1 lets a human behind an agent marker answer', async () => {
+ const out = await drive({ CLAUDECODE: '1', GBRAIN_INTERACTIVE: '1' }, async s => {
+ await s.waitFor('ONE> ', { timeoutMs: 10_000 });
+ s.send('y\r');
+ await s.waitFor('TWO> ', { timeoutMs: 10_000 });
+ s.send('n\r');
+ });
+ expect(out).toContain('__RESULT__[{"kind":"line","text":"y"},{"kind":"line","text":"n"}]');
+ expect(out).not.toContain('prompts are off');
+ }, 40_000);
+});
diff --git a/test/interaction.test.ts b/test/interaction.test.ts
new file mode 100644
index 0000000000..5025cb7189
--- /dev/null
+++ b/test/interaction.test.ts
@@ -0,0 +1,241 @@
+/**
+ * A5 interaction primitive (src/core/interaction.ts), in-process half: the
+ * isInteractive decision table, agentProcessMarker, and readLine /
+ * readStdinBounded against injected streams with short timeouts. The real
+ * process-stdin cases (natural exit, 8 s slow first byte, /dev/null, the
+ * one-per-process stderr line) live in test/interaction-stdin.serial.test.ts.
+ */
+import { describe, expect, test } from 'bun:test';
+import { PassThrough, Readable } from 'node:stream';
+import {
+ agentProcessMarker,
+ isInteractive,
+ readLine,
+ readStdinBounded,
+ type StdinRead,
+} from '../src/core/interaction.ts';
+
+const TTY = { stdinIsTTY: true, stdoutIsTTY: true } as const;
+const MARKERS = ['CLAUDECODE', 'CLAUDE_CODE_ENTRYPOINT', 'CODEX_SANDBOX', 'CODEX_CI', 'OPENCODE', 'OPENCODE_PID'];
+
+describe('isInteractive decision table', () => {
+ const rows: Array<[string, NodeJS.ProcessEnv, { stdinIsTTY: boolean; stdoutIsTTY: boolean }, boolean]> = [
+ ['a human on two TTYs', {}, TTY, true],
+ ['a human with only CODEX_HOME keeps prompts', { CODEX_HOME: '/home/u/.codex' }, TTY, true],
+ ['stdin not a TTY', {}, { stdinIsTTY: false, stdoutIsTTY: true }, false],
+ ['stdout not a TTY', {}, { stdinIsTTY: true, stdoutIsTTY: false }, false],
+ ['CI=true', { CI: 'true' }, TTY, false],
+ ['CI=1', { CI: '1' }, TTY, false],
+ ['CI=false is not CI', { CI: 'false' }, TTY, true],
+ ['CI=0 is not CI', { CI: '0' }, TTY, true],
+ ['GBRAIN_NON_INTERACTIVE=1', { GBRAIN_NON_INTERACTIVE: '1' }, TTY, false],
+ ['GBRAIN_INTERACTIVE=1 overrides an agent marker', { CLAUDECODE: '1', GBRAIN_INTERACTIVE: '1' }, TTY, true],
+ ['GBRAIN_INTERACTIVE=1 overrides CI', { CI: 'true', GBRAIN_INTERACTIVE: '1' }, TTY, true],
+ ['GBRAIN_INTERACTIVE=1 overrides GBRAIN_NON_INTERACTIVE', { GBRAIN_NON_INTERACTIVE: '1', GBRAIN_INTERACTIVE: '1' }, TTY, true],
+ ['GBRAIN_INTERACTIVE=1 cannot conjure a TTY', { GBRAIN_INTERACTIVE: '1' }, { stdinIsTTY: false, stdoutIsTTY: true }, false],
+ ['GBRAIN_INTERACTIVE=0 is not an override', { CLAUDECODE: '1', GBRAIN_INTERACTIVE: '0' }, TTY, false],
+ ...MARKERS.map((m): [string, NodeJS.ProcessEnv, typeof TTY, boolean] => [`agent marker ${m}`, { [m]: '1' }, TTY, false]),
+ ];
+ for (const [name, env, ttys, want] of rows) {
+ test(name, () => {
+ expect(isInteractive({ env, ...ttys })).toBe(want);
+ });
+ }
+});
+
+describe('agentProcessMarker', () => {
+ test('names each process-scoped marker', () => {
+ for (const m of MARKERS) expect(agentProcessMarker({ [m]: '1' })).toBe(m);
+ });
+ test('never CODEX_HOME; empty values do not count', () => {
+ expect(agentProcessMarker({ CODEX_HOME: '/x' })).toBeNull();
+ expect(agentProcessMarker({ CLAUDECODE: '' })).toBeNull();
+ expect(agentProcessMarker({})).toBeNull();
+ });
+});
+
+function sink(): { stream: PassThrough; text: () => string } {
+ const stream = new PassThrough();
+ const parts: string[] = [];
+ stream.on('data', c => parts.push(c.toString()));
+ return { stream, text: () => parts.join('') };
+}
+
+const listenerTotal = (s: NodeJS.ReadableStream) =>
+ ['data', 'end', 'error', 'close'].reduce((n, e) => n + s.listenerCount(e), 0);
+
+describe('readLine', () => {
+ test('non-interactive returns eof at once without prompting or reading', async () => {
+ const input = new PassThrough();
+ const out = sink();
+ const started = Date.now();
+ const r = await readLine({ prompt: 'Proceed? ', input, output: out.stream, probe: { env: {}, stdinIsTTY: false, stdoutIsTTY: true } });
+ expect(r).toEqual({ kind: 'eof' });
+ expect(Date.now() - started).toBeLessThan(100);
+ expect(out.text()).toBe('');
+ expect(listenerTotal(input)).toBe(0);
+ });
+
+ test('an agent marker on two TTYs is non-interactive: eof without reading', async () => {
+ const input = new PassThrough();
+ const r = await readLine({ prompt: 'Q ', input, output: sink().stream, probe: { env: { CODEX_SANDBOX: 'seatbelt' }, ...TTY } });
+ expect(r).toEqual({ kind: 'eof' });
+ });
+
+ const human = { env: {}, ...TTY };
+
+ test('reads one trimmed line; prompt goes to the output stream; listeners removed', async () => {
+ const input = new PassThrough();
+ const out = sink();
+ const p = readLine({ prompt: 'Name? ', input, output: out.stream, probe: human });
+ input.write(' Ada \r\n');
+ expect(await p).toEqual({ kind: 'line', text: 'Ada' });
+ expect(out.text()).toBe('Name? ');
+ expect(listenerTotal(input)).toBe(0);
+ });
+
+ test('bytes after the newline stay for the next read', async () => {
+ const input = new PassThrough();
+ const p1 = readLine({ prompt: '', input, output: sink().stream, probe: human });
+ input.write('one\ntwo\n');
+ expect(await p1).toEqual({ kind: 'line', text: 'one' });
+ const p2 = readLine({ prompt: '', input, output: sink().stream, probe: human });
+ expect(await p2).toEqual({ kind: 'line', text: 'two' });
+ });
+
+ test('EOF with nothing typed is eof (a decline); an ended stream stays eof', async () => {
+ const input = new PassThrough();
+ const p = readLine({ prompt: '', input, output: sink().stream, probe: human });
+ input.end();
+ expect(await p).toEqual({ kind: 'eof' });
+ expect(await readLine({ prompt: '', input, output: sink().stream, probe: human })).toEqual({ kind: 'eof' });
+ });
+
+ test('EOF after a partial line returns the text', async () => {
+ const input = new PassThrough();
+ const p = readLine({ prompt: '', input, output: sink().stream, probe: human });
+ input.end('y');
+ expect(await p).toEqual({ kind: 'line', text: 'y' });
+ });
+
+ test('timeout is its own result (a decline) and cleans up', async () => {
+ const input = new PassThrough();
+ const r = await readLine({ prompt: '', timeoutMs: 50, input, output: sink().stream, probe: human });
+ expect(r).toEqual({ kind: 'timeout' });
+ expect(listenerTotal(input)).toBe(0);
+ });
+});
+
+describe('readStdinBounded (injected stream)', () => {
+ const read = (stream: NodeJS.ReadableStream, extra: Parameters<typeof readStdinBounded>[0] = {}) =>
+ readStdinBounded({ firstByteMs: 2000, inactivityMs: 2000, ...extra, stream });
+
+ test('data then EOF is data', async () => {
+ const s = new PassThrough();
+ const p = read(s);
+ s.write('hello ');
+ s.end('world');
+ expect(await p).toEqual({ kind: 'data', text: 'hello world' });
+ expect(listenerTotal(s)).toBe(0);
+ });
+
+ test('zero bytes then EOF is empty', async () => {
+ const s = new PassThrough();
+ const p = read(s);
+ s.end();
+ expect(await p).toEqual({ kind: 'empty' });
+ });
+
+ test('an open silent stream times out in the first_byte phase', async () => {
+ const s = new PassThrough();
+ expect(await read(s, { firstByteMs: 50 })).toEqual({ kind: 'timeout', phase: 'first_byte', bytes: 0 });
+ expect(listenerTotal(s)).toBe(0);
+ });
+
+ test('one byte then a stall times out in the inactivity phase; the partial byte is not returned', async () => {
+ const s = new PassThrough();
+ const p = read(s, { inactivityMs: 80 });
+ s.write('x');
+ const r = await p;
+ expect(r).toEqual({ kind: 'timeout', phase: 'inactivity', bytes: 1 });
+ expect('text' in r).toBe(false);
+ });
+
+ test('inactivity resets on every chunk: no total time cap', async () => {
+ const s = new PassThrough();
+ const p = read(s, { firstByteMs: 200, inactivityMs: 120 });
+ for (let i = 0; i < 8; i++) {
+ s.write(String(i));
+ await Bun.sleep(50);
+ }
+ s.end();
+ expect(await p).toEqual({ kind: 'data', text: '01234567' });
+ });
+
+ test('partial then a stream error is an error carrying the byte count, never data', async () => {
+ const s = new PassThrough();
+ const p = read(s);
+ s.write('abc');
+ await Bun.sleep(5);
+ s.destroy(new Error('EPIPE-ish'));
+ const r = await p;
+ expect(r.kind).toBe('error');
+ expect((r as Extract<StdinRead, { kind: 'error' }>).bytes).toBe(3);
+ expect((r as Extract<StdinRead, { kind: 'error' }>).error.message).toBe('EPIPE-ish');
+ });
+
+ test('close without end is an error, not a short success', async () => {
+ const s = new PassThrough();
+ const p = read(s);
+ s.write('ab');
+ await Bun.sleep(5);
+ s.destroy();
+ const r = await p;
+ expect(r.kind).toBe('error');
+ expect((r as Extract<StdinRead, { kind: 'error' }>).bytes).toBe(2);
+ });
+
+ test('cancellation mid-read is cancelled with the byte count', async () => {
+ const s = new PassThrough();
+ const ac = new AbortController();
+ const p = read(s, { signal: ac.signal });
+ s.write('abcd');
+ await Bun.sleep(5);
+ ac.abort();
+ expect(await p).toEqual({ kind: 'cancelled', bytes: 4 });
+ expect(listenerTotal(s)).toBe(0);
+ });
+
+ test('an already-aborted signal returns cancelled without reading', async () => {
+ const s = new PassThrough();
+ const ac = new AbortController();
+ ac.abort();
+ expect(await read(s, { signal: ac.signal })).toEqual({ kind: 'cancelled', bytes: 0 });
+ expect(listenerTotal(s)).toBe(0);
+ });
+
+ test('input past maxBytes is an error, never truncated data', async () => {
+ const s = new PassThrough();
+ const p = read(s, { maxBytes: 4 });
+ s.write('abc');
+ s.write('de');
+ const r = await p;
+ expect(r.kind).toBe('error');
+ expect((r as Extract<StdinRead, { kind: 'error' }>).error.message).toContain('exceeds 4 bytes');
+ });
+
+ test('string chunks and multi-byte UTF-8 split across chunks decode intact', async () => {
+ const bytes = Buffer.from('héllo ✓');
+ const s = Readable.from([bytes.subarray(0, 2), bytes.subarray(2, 9), bytes.subarray(9)]);
+ expect(await read(s)).toEqual({ kind: 'data', text: 'héllo ✓' });
+ });
+
+ test('an already-consumed stream is an error', async () => {
+ const s = new PassThrough();
+ const p = read(s);
+ s.end();
+ await p;
+ const r = await read(s);
+ expect(r.kind).toBe('error');
+ });
+});