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.

feat(ego-browser): add error_code abstraction and branch on stable codes

0x0e60a9ea6773a
diff --git a/package/ego-browser/src/ego-errors.test.mjs b/package/ego-browser/src/ego-errors.test.mjs
new file mode 100644
index 0000000..417ade9
--- /dev/null
+++ b/package/ego-browser/src/ego-errors.test.mjs
@@ -0,0 +1,112 @@
+import test from "node:test";
+import assert from "node:assert/strict";
+
+import {
+ assertNoEgoError,
+ egoErrorCode,
+ isEgoErrorCode,
+ isEgoUserControlError,
+ resolveEgoError,
+} from "../dist/src/ego-errors.js";
+
+test("egoErrorCode extracts the code from every error shape", () => {
+ // resolved { error, error_code } object
+ assert.equal(
+ egoErrorCode({ error: "nope", error_code: "EGO_BROWSER_UNAVAILABLE" }),
+ "EGO_BROWSER_UNAVAILABLE",
+ );
+ // rejected / thrown Error carrying .error_code
+ const err = Object.assign(new Error("boom"), {
+ error_code: "EGO_SNAPSHOT_FAILED",
+ });
+ assert.equal(egoErrorCode(err), "EGO_SNAPSHOT_FAILED");
+ // bare known code string (e.g. onSendCDPMessageError second arg)
+ assert.equal(
+ egoErrorCode("EGO_TASK_SPACE_USER_IN_CONTROL"),
+ "EGO_TASK_SPACE_USER_IN_CONTROL",
+ );
+ // future code this build does not know about is still returned
+ assert.equal(
+ egoErrorCode({ error_code: "EGO_FUTURE_CODE" }),
+ "EGO_FUTURE_CODE",
+ );
+ // no code present
+ assert.equal(egoErrorCode({ error: "plain message" }), undefined);
+ assert.equal(egoErrorCode("plain message"), undefined);
+});
+
+test("isEgoErrorCode narrows to known codes only", () => {
+ assert.equal(isEgoErrorCode("EGO_TASK_SPACE_NOT_FOUND"), true);
+ assert.equal(isEgoErrorCode("EGO_FUTURE_CODE"), false);
+ assert.equal(isEgoErrorCode(undefined), false);
+});
+
+test("resolveEgoError prefers the live browser text", () => {
+ const resolved = resolveEgoError({
+ error: "Task space not found: 7",
+ error_code: "EGO_TASK_SPACE_NOT_FOUND",
+ });
+ assert.deepEqual(resolved, {
+ code: "EGO_TASK_SPACE_NOT_FOUND",
+ message: "Task space not found: 7",
+ });
+});
+
+test("resolveEgoError falls back to the ego-browser message for a bare code", () => {
+ assert.deepEqual(resolveEgoError("EGO_TASK_SPACE_USER_IN_CONTROL"), {
+ code: "EGO_TASK_SPACE_USER_IN_CONTROL",
+ message: "The task is under user control.",
+ });
+});
+
+test("resolveEgoError falls back to the raw code, then a generic message", () => {
+ assert.deepEqual(resolveEgoError({ error_code: "EGO_FUTURE_CODE" }), {
+ code: "EGO_FUTURE_CODE",
+ message: "EGO_FUTURE_CODE",
+ });
+ assert.deepEqual(resolveEgoError({}), {
+ code: undefined,
+ message: "Unknown ego error",
+ });
+});
+
+test("isEgoUserControlError keys on the stable code, not wording", () => {
+ assert.equal(
+ isEgoUserControlError(
+ Object.assign(new Error("anything at all"), {
+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",
+ }),
+ ),
+ true,
+ );
+ // wording that mentions user control but lacks the code is not a match
+ assert.equal(
+ isEgoUserControlError(new Error("the user is controlling this")),
+ false,
+ );
+ assert.equal(
+ isEgoUserControlError({ error_code: "EGO_SNAPSHOT_FAILED" }),
+ false,
+ );
+});
+
+test("assertNoEgoError preserves the message and attaches error_code", () => {
+ try {
+ assertNoEgoError(
+ {
+ error: "The task is under user control",
+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",
+ },
+ "listTabs",
+ );
+ assert.fail("expected assertNoEgoError to throw");
+ } catch (err) {
+ assert.equal(err.message, "listTabs: The task is under user control");
+ assert.equal(err.error_code, "EGO_TASK_SPACE_USER_IN_CONTROL");
+ }
+});
+
+test("assertNoEgoError passes through results with no error", () => {
+ const ok = { tabs: [] };
+ assert.equal(assertNoEgoError(ok, "listTabs"), ok);
+});
diff --git a/package/ego-browser/src/ego-errors.ts b/package/ego-browser/src/ego-errors.ts
index 7bfa168..8812b4f 100644
--- a/package/ego-browser/src/ego-errors.ts
+++ b/package/ego-browser/src/ego-errors.ts
@@ -1,8 +1,114 @@
/**
- * Shared handling for `{ error: ... }` result objects returned by ego bindings.
- * Single source of truth — previously duplicated in helpers.ts and driver/nav.ts.
+ * Shared handling for ego-binding errors.
+ *
+ * Browser-side failures expose two signals (see the EgoBindings JS API):
+ * - human-readable text (`error` on resolved results, `message` on rejected
+ * Errors), and
+ * - a stable `error_code` such as EGO_TASK_SPACE_USER_IN_CONTROL.
+ *
+ * The code is the durable contract; the wording can drift between builds. Branch
+ * on the code (isEgoUserControlError), not on the message. EGO_ERROR_MESSAGES is
+ * the seam where ego-browser owns its own wording per code — today it only
+ * supplies a fallback when the browser sent no text, but it is the place to
+ * customize how each failure reads going forward.
+ *
+ * Single source of truth — error handling was previously duplicated across
+ * helpers.ts and driver/nav.ts.
*/
+/** Stable error codes emitted by the native ego bindings. */
+export const EGO_ERROR_CODES = [
+ "EGO_BROWSER_UNAVAILABLE",
+ "EGO_CDP_CHANNEL_UNAVAILABLE",
+ "EGO_CDP_SEND_FAILED",
+ "EGO_INVALID_ARGUMENT",
+ "EGO_INVALID_RESULT_PAYLOAD",
+ "EGO_OPERATION_FAILED",
+ "EGO_RESULT_CONVERSION_FAILED",
+ "EGO_SNAPSHOT_FAILED",
+ "EGO_TASK_HOST_DISCONNECTED",
+ "EGO_TASK_SPACE_INACTIVE",
+ "EGO_TASK_SPACE_NOT_FOUND",
+ "EGO_TASK_SPACE_NOT_SELECTED",
+ "EGO_TASK_SPACE_UNAVAILABLE",
+ "EGO_TASK_SPACE_USER_IN_CONTROL",
+ "EGO_WEB_CONTENTS_UNAVAILABLE",
+] as const;
+
+export type EgoErrorCode = (typeof EGO_ERROR_CODES)[number];
+
+/**
+ * ego-browser-owned message for each stable code. Used only as a fallback when
+ * the browser side supplied no human-readable text; customize wording here.
+ */
+const EGO_ERROR_MESSAGES: Record<EgoErrorCode, string> = {
+ EGO_BROWSER_UNAVAILABLE: "No active browser.",
+ EGO_CDP_CHANNEL_UNAVAILABLE: "The CDP channel is not connected.",
+ EGO_CDP_SEND_FAILED: "Failed to send the CDP message.",
+ EGO_INVALID_ARGUMENT: "Invalid argument.",
+ EGO_INVALID_RESULT_PAYLOAD: "The browser returned an invalid result payload.",
+ EGO_OPERATION_FAILED: "The browser operation failed.",
+ EGO_RESULT_CONVERSION_FAILED: "Failed to convert the browser result.",
+ EGO_SNAPSHOT_FAILED: "Failed to capture the page snapshot.",
+ EGO_TASK_HOST_DISCONNECTED: "The task host is no longer available.",
+ EGO_TASK_SPACE_INACTIVE: "The task space is inactive.",
+ EGO_TASK_SPACE_NOT_FOUND: "Task space not found.",
+ EGO_TASK_SPACE_NOT_SELECTED: "Task space not selected.",
+ EGO_TASK_SPACE_UNAVAILABLE: "The task space is unavailable.",
+ EGO_TASK_SPACE_USER_IN_CONTROL: "The task is under user control.",
+ EGO_WEB_CONTENTS_UNAVAILABLE: "The page contents are unavailable.",
+};
+
+/** Type guard for codes this build knows about. */
+export function isEgoErrorCode(value: unknown): value is EgoErrorCode {
+ return (
+ typeof value === "string" &&
+ (EGO_ERROR_CODES as readonly string[]).includes(value)
+ );
+}
+
+/**
+ * Pull the stable error_code out of any ego error shape: resolved
+ * `{ error, error_code }` objects, rejected/thrown Errors carrying `.error_code`,
+ * or a bare known code string. Returns the raw code (which may be one this build
+ * does not know about yet) or undefined when none is present.
+ */
+export function egoErrorCode(err: unknown): string | undefined {
+ if (typeof err === "string") {
+ return isEgoErrorCode(err) ? err : undefined;
+ }
+ if (err && typeof err === "object") {
+ const code = (err as Record<string, unknown>).error_code;
+ if (typeof code === "string" && code) return code;
+ }
+ return undefined;
+}
+
+/**
+ * Resolve any ego error into a stable `{ code, message }` pair.
+ *
+ * `message` prefers the live human-readable text the browser supplied, then the
+ * ego-browser-owned message for the code, then the bare code, then a generic
+ * string. `code` is the stable classifier and may be undefined.
+ */
+export function resolveEgoError(err: unknown): {
+ code?: string;
+ message: string;
+} {
+ const code = egoErrorCode(err);
+ const message =
+ liveErrorText(err) ??
+ (isEgoErrorCode(code) ? EGO_ERROR_MESSAGES[code] : undefined) ??
+ code ??
+ "Unknown ego error";
+ return { code, message };
+}
+
+/** Whether an ego error means the task is currently under user control. */
+export function isEgoUserControlError(err: unknown): boolean {
+ return egoErrorCode(err) === "EGO_TASK_SPACE_USER_IN_CONTROL";
+}
+
export function assertNoEgoError(result, op: string) {
if (
result &&
@@ -10,11 +116,29 @@ export function assertNoEgoError(result, op: string) {
"error" in result &&
result.error != null
) {
- throw new Error(`${op}: ${formatEgoError(result.error)}`);
+ const { code, message } = resolveEgoError(result);
+ const error: Error & { error_code?: string } = new Error(
+ `${op}: ${message}`,
+ );
+ if (code) error.error_code = code;
+ throw error;
}
return result;
}
+/** Human-readable text from any ego error shape, ignoring bare codes. */
+function liveErrorText(err: unknown): string | undefined {
+ if (typeof err === "string") {
+ return isEgoErrorCode(err) ? undefined : err;
+ }
+ if (err && typeof err === "object") {
+ const obj = err as Record<string, unknown>;
+ if (obj.error != null) return formatEgoError(obj.error);
+ if (typeof obj.message === "string" && obj.message) return obj.message;
+ }
+ return undefined;
+}
+
export function formatEgoError(err: unknown): string {
if (err == null) return String(err);
if (typeof err === "string") return err;
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index 5187d7b..192aa15 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -10,6 +10,7 @@ import {
listTaskSpaces,
useOrCreateTaskSpace,
switchTaskSpace,
+ waitForAgentControl,
} from "../dist/src/helpers.js";
function withEgo(ego, fn) {
@@ -693,3 +694,63 @@ test("useOrCreateTaskSpace rejects unknown ownership", async () => {
},
);
});
+
+// The probe in waitForAgentControl keys on ego.snapshot()'s rejection carrying
+// error_code === EGO_TASK_SPACE_USER_IN_CONTROL (the documented contract), not on
+// message wording. These tests pin that contract so a runtime that stops setting
+// the code surfaces as a failing test rather than a silent regression.
+function taskSpaceEgo(snapshot) {
+ return {
+ async listTaskSpaces() {
+ return {
+ taskSpaces: [{ taskId: "t", id: 1, name: "t", ownership: "agent" }],
+ };
+ },
+ async useTaskSpace() {
+ return 1;
+ },
+ snapshot,
+ };
+}
+
+test("waitForAgentControl retries while snapshot reports user control", async () => {
+ const restore = helperExports.__testing.setOverrides({
+ sleep: () => Promise.resolve(),
+ });
+ let calls = 0;
+ try {
+ await withEgo(
+ taskSpaceEgo(async () => {
+ calls += 1;
+ if (calls < 3) {
+ throw Object.assign(new Error("anything at all"), {
+ error_code: "EGO_TASK_SPACE_USER_IN_CONTROL",
+ });
+ }
+ return { content: "" };
+ }),
+ async () => {
+ await waitForAgentControl("t", { interval: 0, timeout: 5 });
+ },
+ );
+ } finally {
+ restore();
+ }
+ assert.equal(calls, 3);
+});
+
+test("waitForAgentControl propagates non-user-control snapshot errors", async () => {
+ await withEgo(
+ taskSpaceEgo(async () => {
+ throw Object.assign(new Error("snapshot failed"), {
+ error_code: "EGO_SNAPSHOT_FAILED",
+ });
+ }),
+ async () => {
+ await assert.rejects(
+ () => waitForAgentControl("t", { interval: 0, timeout: 5 }),
+ /snapshot failed/,
+ );
+ },
+ );
+});
diff --git a/package/ego-browser/src/helpers.ts b/package/ego-browser/src/helpers.ts
index 5146731..f62afee 100644
--- a/package/ego-browser/src/helpers.ts
+++ b/package/ego-browser/src/helpers.ts
@@ -3,7 +3,7 @@ import { join } from "node:path";
import { pathToFileURL } from "node:url";
import { setOverrides, state } from "./state.js";
-import { assertNoEgoError } from "./ego-errors.js";
+import { assertNoEgoError, isEgoUserControlError } from "./ego-errors.js";
import { help as helpRuntime, formatHelp } from "./help-runtime.js";
import { cdp, decodeUnserializableJsValue, js } from "./cdp-eval.js";
import * as pointer from "./driver/pointer.js";
@@ -303,11 +303,6 @@ export async function takeOverTaskSpace(nameOrId?: string | number) {
assertNoEgoError(await ego.takeOverTaskSpace(), "takeOverTaskSpace");
}
-function isUserControlError(err: unknown) {
- const message = err instanceof Error ? err.message : String(err ?? "");
- return /user control|user is controlling/i.test(message);
-}
-
/**
* Probe whether the agent currently holds control of the active task space.
* Module-private; used by waitForAgentControl. Uses ego.snapshot, which
@@ -323,7 +318,7 @@ async function probeAgentControl() {
await ego.snapshot({ maxResultLength: 1 });
return true;
} catch (err) {
- if (isUserControlError(err)) return false;
+ if (isEgoUserControlError(err)) return false;
throw err;
}
}