Skip to content

The fastest browser for AI agents to run browser automation, built for sharing your logged-in browser state with your AI agents, like Codex or Claude Code, without disturbing you. Zero cost, zero config.

fix(ego-browser): collapse swallowed hard-stop errors to a single message

0x0964aceb192c8
diff --git a/package/ego-browser/src/ego-errors.ts b/package/ego-browser/src/ego-errors.ts
index 6d95900..c85b404 100644
--- a/package/ego-browser/src/ego-errors.ts
+++ b/package/ego-browser/src/ego-errors.ts
@@ -15,6 +15,8 @@
* helpers.ts and driver/nav.ts.
*/
+import { markHardStop } from "./output-sink.js";
+
/** Stable error codes emitted by the native ego bindings. */
export const EGO_ERROR_CODES = [
"EGO_BROWSER_UNAVAILABLE",
@@ -113,6 +115,23 @@ export function isEgoUserControlError(err: unknown): boolean {
return egoErrorCode(err) === "EGO_TASK_SPACE_USER_IN_CONTROL";
}
+/**
+ * Codes that halt the whole agent task rather than mark a routable obstacle: a task
+ * space the user has taken back, or one that is inactive / not assigned to this agent.
+ * Both require the user to explicitly hand control back before work can resume.
+ */
+function isEgoHardStopCode(code: string | undefined): boolean {
+ return (
+ code === "EGO_TASK_SPACE_USER_IN_CONTROL" ||
+ code === "EGO_TASK_SPACE_INACTIVE"
+ );
+}
+
+/** Whether an ego error is a hard stop the agent must not retry or route around. */
+export function isEgoHardStopError(err: unknown): boolean {
+ return isEgoHardStopCode(egoErrorCode(err));
+}
+
/**
* Build an Error carrying the resolved message and stable error_code from any ego
* error shape. `op`, when given, prefixes the message with the failing operation.
@@ -125,6 +144,14 @@ export function buildEgoError(
op?: string,
): Error & { error_code?: string } {
const { code, message } = resolveEgoError(err);
+ if (isEgoHardStopCode(code)) {
+ // buildEgoError is the single birthplace of every ego error — assertNoEgoError and
+ // the CDP-send failure path both route through it — so recording the hard stop here
+ // catches it even when the agent's own try/catch later swallows the thrown Error.
+ // The op-less owned message is the one the agent should see, regardless of which
+ // operation surfaced it.
+ markHardStop(message);
+ }
const error: Error & { error_code?: string } = new Error(
op ? `${op}: ${message}` : message,
);
diff --git a/package/ego-browser/src/index.ts b/package/ego-browser/src/index.ts
index 73319ce..25e970d 100644
--- a/package/ego-browser/src/index.ts
+++ b/package/ego-browser/src/index.ts
@@ -8,6 +8,11 @@ import {
setPreferredTarget,
} from "./browser-runtime.js";
import { formatCliLogValue } from "./format.js";
+import {
+ bufferOutput,
+ installLifecycleFlush,
+ resetSink,
+} from "./output-sink.js";
import { runMain } from "./run.js";
type HelperFunction = (...args: unknown[]) => unknown;
@@ -67,6 +72,7 @@ export function installEgoSdk(
});
installed[name] = exposed as HelperFunction;
}
+ const usingDefaultCliLog = !options.cliLog;
const cliLogFn = options.cliLog || createCliLog();
Object.defineProperty(target, "cliLog", {
value: cliLogFn,
@@ -75,6 +81,12 @@ export function installEgoSdk(
enumerable: false,
});
installed.cliLog = cliLogFn;
+ if (usingDefaultCliLog) {
+ // SDK path: the host runs each heredoc in a fresh short-lived process and never
+ // calls execute(), so reset the per-run sink and flush it on process teardown.
+ resetSink();
+ installLifecycleFlush(process.stdout);
+ }
if (target.ego && typeof target.ego === "object") {
target.ego.helpers = installed;
target.ego.learnings = {};
@@ -107,11 +119,11 @@ if (isDirectCli()) {
installEgoSdk();
}
-function createCliLog(
- stream: { write(chunk: string): unknown } = process.stdout,
-) {
+function createCliLog() {
return (...args: unknown[]) => {
- stream.write(`${args.map(formatCliLogValue).join(" ")}\n`);
+ // Buffer instead of writing through: a hard stop later in the run must be able to
+ // discard everything logged so far. The buffer is flushed on process teardown.
+ bufferOutput(`${args.map(formatCliLogValue).join(" ")}\n`);
};
}
diff --git a/package/ego-browser/src/output-sink.test.mjs b/package/ego-browser/src/output-sink.test.mjs
new file mode 100644
index 0000000..8959d95
--- /dev/null
+++ b/package/ego-browser/src/output-sink.test.mjs
@@ -0,0 +1,74 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ bufferOutput,
+ flushSink,
+ markHardStop,
+ resetSink,
+} from "../dist/src/output-sink.js";
+
+function fakeStream() {
+ const chunks = [];
+ return {
+ write(chunk) {
+ chunks.push(String(chunk));
+ },
+ text() {
+ return chunks.join("");
+ },
+ };
+}
+
+test("flushSink writes buffered output verbatim on a clean run", () => {
+ resetSink();
+ bufferOutput("a\n");
+ bufferOutput("b\n");
+ const out = fakeStream();
+ flushSink(out, false);
+ assert.equal(out.text(), "a\nb\n");
+});
+
+test("a swallowed hard stop discards the buffer and prints the owned message once", () => {
+ resetSink();
+ bufferOutput("visiting\n");
+ markHardStop("HARD STOP MESSAGE");
+ markHardStop("a later re-report that must be ignored");
+ const out = fakeStream();
+ flushSink(out, false);
+ assert.equal(out.text(), "HARD STOP MESSAGE\n");
+});
+
+test("a thrown hard stop stays silent so the propagating error is not echoed twice", () => {
+ resetSink();
+ bufferOutput("visiting\n");
+ markHardStop("HARD STOP MESSAGE");
+ const out = fakeStream();
+ flushSink(out, true);
+ assert.equal(out.text(), "");
+});
+
+test("an ordinary thrown error still flushes what was logged before it", () => {
+ resetSink();
+ bufferOutput("partial\n");
+ const out = fakeStream();
+ flushSink(out, true);
+ assert.equal(out.text(), "partial\n");
+});
+
+test("flushSink runs at most once", () => {
+ resetSink();
+ bufferOutput("x\n");
+ const out = fakeStream();
+ flushSink(out, false);
+ flushSink(out, false);
+ assert.equal(out.text(), "x\n");
+});
+
+test("a message that already ends in a newline is not double-terminated", () => {
+ resetSink();
+ markHardStop("already terminated\n");
+ const out = fakeStream();
+ flushSink(out, false);
+ assert.equal(out.text(), "already terminated\n");
+});
diff --git a/package/ego-browser/src/output-sink.ts b/package/ego-browser/src/output-sink.ts
new file mode 100644
index 0000000..06b09c7
--- /dev/null
+++ b/package/ego-browser/src/output-sink.ts
@@ -0,0 +1,94 @@
+/**
+ * Output sink for the agent-facing heredoc runtime.
+ *
+ * `cliLog` is the only channel an agent reads. A single user takeover turns that
+ * channel into noise: while the user holds control, every browser command re-reports
+ * the same hard-stop error, so a script that loops over work and swallows each error
+ * (try/catch, `.catch()`) prints the same guidance on every iteration, buried under
+ * its own business logging and success rows.
+ *
+ * To collapse that to one clean line we buffer cliLog output instead of writing it
+ * straight through. When a hard-stop error is born (see `buildEgoError`) we record its
+ * owned message once. At the end of the run we either:
+ * - a hard stop occurred -> discard the whole buffer and emit the owned message once
+ * - otherwise -> flush the buffered output verbatim
+ *
+ * Buffering is the price of discarding pre-stop output: bytes already written cannot be
+ * recalled, so nothing may be written until we know the run did not hard-stop. Each
+ * heredoc runs in its own short-lived process, so this module state is per-run and needs
+ * no cross-round reset; `resetSink()` exists only so in-process tests can reuse the run.
+ */
+
+type WritableLike = { write(chunk: string): unknown };
+
+let buffer: string[] = [];
+let hardStopMessage: string | null = null;
+let flushed = false;
+let lifecycleHooked = false;
+
+/** Buffer one already-formatted cliLog chunk (the trailing newline is included). */
+export function bufferOutput(chunk: string): void {
+ buffer.push(chunk);
+}
+
+/**
+ * Record the owned message of the first hard-stop error seen this run. Later hard stops
+ * — the same error re-reported on each loop iteration — are ignored so the agent sees
+ * the guidance exactly once.
+ */
+export function markHardStop(message: string): void {
+ if (hardStopMessage === null) {
+ hardStopMessage = message;
+ }
+}
+
+/**
+ * Emit the run's output exactly once.
+ *
+ * `thrown` separates a completed script from one ending on an uncaught error. On a clean
+ * finish we are the only writer, so a hard stop must print its message here. On an
+ * uncaught error the propagating Error already surfaces the message (the host prints it),
+ * so we stay silent and only drop the buffer. Non-hard-stop output is flushed either way,
+ * so an ordinary failure still shows what the script logged before it threw.
+ */
+export function flushSink(stream: WritableLike, thrown: boolean): void {
+ if (flushed) return;
+ flushed = true;
+ if (hardStopMessage !== null) {
+ // Drop every buffered line — business logs, success rows, and the repeated error
+ // echoes — so the owned guidance is all that remains.
+ if (!thrown) {
+ stream.write(
+ hardStopMessage.endsWith("\n")
+ ? hardStopMessage
+ : `${hardStopMessage}\n`,
+ );
+ }
+ } else {
+ for (const chunk of buffer) stream.write(chunk);
+ }
+ buffer = [];
+}
+
+/** Clear sink state. Real runs get a fresh process; this is only for in-process tests. */
+export function resetSink(): void {
+ buffer = [];
+ hardStopMessage = null;
+ flushed = false;
+}
+
+/**
+ * Flush on process teardown for the SDK path, where the host runs each heredoc directly
+ * and never calls the CLI `execute()` wrapper, so lifecycle events are our only hook.
+ *
+ * A clean finish drains the event loop and reaches `beforeExit`; an uncaught async
+ * rejection skips `beforeExit` but still reaches `exit` (`thrown: true`, so a hard stop
+ * stays silent and lets the propagating Error surface the message). The stream still
+ * accepts writes in both events, so the same `stream` serves both. Registered once.
+ */
+export function installLifecycleFlush(stream: WritableLike): void {
+ if (lifecycleHooked) return;
+ lifecycleHooked = true;
+ process.on("beforeExit", () => flushSink(stream, false));
+ process.on("exit", () => flushSink(stream, true));
+}
diff --git a/package/ego-browser/src/run-output-sink.test.mjs b/package/ego-browser/src/run-output-sink.test.mjs
new file mode 100644
index 0000000..2d29eeb
--- /dev/null
+++ b/package/ego-browser/src/run-output-sink.test.mjs
@@ -0,0 +1,147 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import { runMain } from "../dist/src/run.js";
+
+// A minimal native ego whose only method reports a hard stop, the same shape the real
+// bindings return when the user holds (or has not handed over) the task space. The
+// `listTaskSpaces` helper lifts it through assertNoEgoError -> buildEgoError, which is
+// where the sink is told a hard stop occurred.
+function hardStopEgo(error_code) {
+ return {
+ calls: 0,
+ async listTaskSpaces() {
+ this.calls += 1;
+ return {
+ error: "native wording that should never reach the agent",
+ error_code,
+ };
+ },
+ };
+}
+
+function captureStream() {
+ const chunks = [];
+ return {
+ write(chunk) {
+ chunks.push(String(chunk));
+ },
+ text() {
+ return chunks.join("");
+ },
+ };
+}
+
+async function runScript(code, ego) {
+ const previous = globalThis.ego;
+ if (ego === undefined) {
+ delete globalThis.ego;
+ } else {
+ globalThis.ego = ego;
+ }
+ const stdout = captureStream();
+ const stderr = captureStream();
+ let exitCode = null;
+ let error = null;
+ try {
+ exitCode = await runMain({
+ argv: [],
+ stdinText: code,
+ stdout,
+ stderr,
+ services: { printUpdateBanner() {} },
+ });
+ } catch (err) {
+ error = err;
+ } finally {
+ if (previous === undefined) {
+ delete globalThis.ego;
+ } else {
+ globalThis.ego = previous;
+ }
+ }
+ return { exitCode, error, stdout: stdout.text(), stderr: stderr.text() };
+}
+
+test("a clean run flushes buffered cliLog output in order", async () => {
+ const result = await runScript(`cliLog("one"); cliLog("two");`);
+ assert.equal(result.exitCode, 0);
+ assert.equal(result.stdout, "one\ntwo\n");
+});
+
+test("a swallowed user-control hard stop discards all output and prints the guidance once", async () => {
+ const ego = hardStopEgo("EGO_TASK_SPACE_USER_IN_CONTROL");
+ const result = await runScript(
+ `
+ for (const site of ["a", "b", "c"]) {
+ cliLog("visiting " + site);
+ try {
+ await listTaskSpaces();
+ cliLog("ok " + site);
+ } catch (e) {
+ cliLog("failed " + site + ": " + e.message);
+ }
+ }
+ cliLog("summary: done");
+ `,
+ ego,
+ );
+
+ assert.equal(result.exitCode, 0);
+ // Only the owned guidance survives — none of the script's own logging.
+ assert.match(result.stdout, /taken control of this task space/);
+ assert.match(result.stdout, /takeOverTaskSpace\(\)/);
+ assert.doesNotMatch(result.stdout, /visiting|failed|ok |summary/);
+ // Printed exactly once, even though every loop iteration re-reported the hard stop.
+ assert.equal(result.stdout.match(/takeOverTaskSpace\(\)/g).length, 1);
+ assert.ok(ego.calls >= 3, "every iteration should have hit the hard stop");
+});
+
+test("an inactive / unassigned task space is also a hard stop", async () => {
+ const ego = hardStopEgo("EGO_TASK_SPACE_INACTIVE");
+ const result = await runScript(
+ `
+ try {
+ await listTaskSpaces();
+ } catch (e) {
+ cliLog("swallowed: " + e.message);
+ }
+ cliLog("more business output");
+ `,
+ ego,
+ );
+
+ assert.equal(result.exitCode, 0);
+ assert.match(result.stdout, /no longer assigned to the agent/);
+ assert.match(result.stdout, /claimTaskSpace\(id\)/);
+ assert.doesNotMatch(result.stdout, /swallowed|business/);
+});
+
+test("an uncaught hard stop discards output without double-printing the message", async () => {
+ const ego = hardStopEgo("EGO_TASK_SPACE_USER_IN_CONTROL");
+ const result = await runScript(
+ `
+ cliLog("before");
+ await listTaskSpaces();
+ cliLog("after");
+ `,
+ ego,
+ );
+
+ // The thrown Error already surfaces the message (the host prints it), so the sink
+ // discards the buffer and stays silent rather than printing the guidance a second time.
+ assert.ok(result.error, "expected runMain to reject");
+ assert.match(result.error.message, /taken control of this task space/);
+ assert.equal(result.stdout, "");
+});
+
+test("an ordinary uncaught error still flushes the output logged before it", async () => {
+ const result = await runScript(`
+ cliLog("partial result");
+ throw new Error("boom");
+ `);
+
+ assert.ok(result.error, "expected runMain to reject");
+ assert.equal(result.error.message, "boom");
+ assert.equal(result.stdout, "partial result\n");
+});
diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.ts
index 1746995..df026c6 100644
--- a/package/ego-browser/src/run.ts
+++ b/package/ego-browser/src/run.ts
@@ -6,6 +6,7 @@ import {
import { formatCliLogValue } from "./format.js";
import * as helpers from "./helpers.js";
+import { bufferOutput, flushSink, resetSink } from "./output-sink.js";
type WritableLike = {
write(chunk: string): unknown;
@@ -105,23 +106,34 @@ export async function runMain(options: RunMainOptions = {}) {
}
async function execute(code: string, stdout: WritableLike) {
- const context = await executionContext(stdout);
+ resetSink();
+ const context = await executionContext();
Object.assign(globalThis, context);
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const names = Object.keys(context);
const values = Object.values(context);
const fn = new AsyncFunction(...names, `"use strict";\n${code}`);
- await fn(...values);
+ try {
+ await fn(...values);
+ } catch (error) {
+ // The thrown Error surfaces the hard-stop message on its own, so flush as a thrown
+ // completion (drop the buffer, stay silent) and let it propagate.
+ flushSink(stdout, true);
+ throw error;
+ }
+ flushSink(stdout, false);
}
-export async function executionContext(stdout: WritableLike = processStdout) {
+export async function executionContext() {
const agentHelpers = await helpers.loadAgentHelpers();
// Single source of truth for the agent-facing surface: the same helperContext()
// that installEgoSdk() exposes in the browser runtime, so the CLI and SDK paths
// cannot drift apart (and `help` exists in both).
const context: Record<string, any> = helpers.helperContext(agentHelpers);
context.cliLog = (...args: unknown[]) => {
- write(stdout, `${args.map(formatCliLogValue).join(" ")}\n`);
+ // Buffer rather than write through; execute() flushes (or discards on hard stop)
+ // once the script settles. Keeps the CLI path identical to the SDK path.
+ bufferOutput(`${args.map(formatCliLogValue).join(" ")}\n`);
};
return context;
}