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.

add page feedback and buffered console

Aute386c08eca8d7
diff --git a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
index 583d5ec..95e8c99 100644
--- a/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
+++ b/package/ego-browser/scripts/real-browser-e2e/cases/page-labels.mjs
@@ -217,6 +217,18 @@ export function pageBasicOperationsCase() {
assertIncludes(info.url, "page-api=first", "page.info reads its own URL");
assert(info.w > 0 && info.h > 0, "page.info reports a usable viewport");
assertEqual((await currentTab()).targetId, second.targetId, "metadata reads do not activate their page");
+ const baselineSnapshot = await first.snapshot({ diff: true });
+ assertIncludes(baselineSnapshot, 'page-api-first', "snapshot identifies its source Page");
+ assertIncludes(baselineSnapshot, 'space "' + taskName + '"', "snapshot identifies its task space");
+ assertIncludes(baselineSnapshot, "diff: full (baseline unavailable)", "first diff snapshot reports its full fallback");
+ await first.evaluate(() => {
+ const marker = document.createElement("p");
+ marker.textContent = "Snapshot diff marker";
+ document.body.append(marker);
+ });
+ const changedSnapshot = await first.snapshot({ diff: true });
+ assertIncludes(changedSnapshot, "diff: changes from previous snapshot", "second diff snapshot reports its baseline");
+ assertIncludes(changedSnapshot, "Snapshot diff marker", "snapshot diff contains the new page content");
assertEqual(
await first.evaluate("document.querySelector('h1').textContent"),
"Helper e2e fixture",
@@ -316,6 +328,11 @@ export function pageBasicOperationsCase() {
"page.screenshot activates the page it captures"
);
+ const navigationReceipt = await first.click("#nav-link");
+ assertIncludes(navigationReceipt.navigation.from, "page-api=first", "click receipt reports the source URL");
+ assertIncludes(navigationReceipt.navigation.to, "/nav-target", "click receipt reports the destination URL");
+ assertEqual(navigationReceipt.domChanged, true, "navigation is reported as a document change");
+
await first.close();
await second.close();
`;
@@ -342,7 +359,9 @@ export function pageActionsAndPopupCase() {
});
assertEqual((await currentTab()).targetId, budgetFiller.targetId, "the budget page starts active");
- assertEqual(await source.fill("#text-input", "page-filled").then(() => source.evaluate("document.querySelector('#text-input').value")), "page-filled", "page.fill writes into the addressed page");
+ const fillReceipt = await source.fill("#text-input", "page-filled");
+ assertEqual(fillReceipt.domChanged, true, "page.fill reports its form-state change");
+ assertEqual(await source.evaluate("document.querySelector('#text-input').value"), "page-filled", "page.fill writes into the addressed page");
assertEqual((await currentTab()).targetId, source.targetId, "page.fill activates and keeps its page current");
await source.evaluate((popupUrl) => {
diff --git a/package/ego-browser/src/index.ts b/package/ego-browser/src/index.ts
index d327879..989f660 100644
--- a/package/ego-browser/src/index.ts
+++ b/package/ego-browser/src/index.ts
@@ -10,6 +10,7 @@ import {
import { formatCliLogValue } from "./format.js";
import {
bufferOutput,
+ createRoundConsole,
installLifecycleFlush,
resetSink,
} from "./output-sink.js";
@@ -81,6 +82,16 @@ export function installEgoSdk(
enumerable: false,
});
installed.cliLog = cliLogFn;
+ Object.defineProperty(target, "console", {
+ value: createRoundConsole(
+ usingDefaultCliLog
+ ? undefined
+ : (line) => cliLogFn(line.endsWith("\n") ? line.slice(0, -1) : line),
+ ),
+ writable: true,
+ configurable: true,
+ enumerable: false,
+ });
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.
diff --git a/package/ego-browser/src/output-sink.ts b/package/ego-browser/src/output-sink.ts
index 06b09c7..b85496c 100644
--- a/package/ego-browser/src/output-sink.ts
+++ b/package/ego-browser/src/output-sink.ts
@@ -1,3 +1,5 @@
+import { formatCliLogValue } from "./format.js";
+
/**
* Output sink for the agent-facing heredoc runtime.
*
@@ -21,6 +23,8 @@
type WritableLike = { write(chunk: string): unknown };
+export type RoundConsole = Pick<Console, "log" | "info" | "warn" | "error">;
+
let buffer: string[] = [];
let hardStopMessage: string | null = null;
let flushed = false;
@@ -31,6 +35,22 @@ export function bufferOutput(chunk: string): void {
buffer.push(chunk);
}
+/** Create the console object injected into one agent round. */
+export function createRoundConsole(
+ writeLine: (line: string) => void = bufferOutput,
+): RoundConsole {
+ const append = (prefix: string, args: unknown[]) => {
+ const body = args.map(formatCliLogValue).join(" ");
+ writeLine(`${prefix}${body}\n`);
+ };
+ return Object.freeze({
+ log: (...args: unknown[]) => append("", args),
+ info: (...args: unknown[]) => append("", args),
+ warn: (...args: unknown[]) => append("[warn] ", args),
+ error: (...args: unknown[]) => append("[error] ", args),
+ });
+}
+
/**
* 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
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index 66ffe94..232bbb6 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -27,9 +27,11 @@ function createFixture(rootDir) {
let popupOnNextClick = null;
let timeoutNextMouseDispatch = false;
let rejectNextClickPoint = false;
+ let navigateOnNextClickUrl = null;
let nowMs = 1_000;
const pageEvents = new Map();
const networkSessions = new Set();
+ const snapshotOptions = [];
function openPendingPopup() {
if (!popupOnNextClick) return;
@@ -57,6 +59,7 @@ function createFixture(rootDir) {
const services = {
gate,
pageRefs: new PageRefRegistry(),
+ snapshotBaselines: new Map(),
async createTab(url) {
assert.equal(selectedSpace, 7);
const targetId = `target-${nextTarget++}`;
@@ -85,6 +88,19 @@ function createFixture(rootDir) {
if (method === "Runtime.evaluate") {
const targetId = sessionId?.slice("session:".length);
const tab = tabs.get(targetId);
+ if (params.expression.includes("__egoBrowserActionProbes")) {
+ return {
+ result: {
+ type: "object",
+ value: {
+ url: tab.url,
+ documentToken: `document:${tab.url}`,
+ controlHash: "controls",
+ mutations: 0,
+ },
+ },
+ };
+ }
if (params.expression === "globalThis") {
return {
result: {
@@ -233,7 +249,15 @@ function createFixture(rootDir) {
timeoutNextMouseDispatch = false;
throw new Error("CDP request timed out: Input.dispatchMouseEvent");
}
- if (params.type === "mouseReleased") openPendingPopup();
+ if (params.type === "mouseReleased") {
+ if (navigateOnNextClickUrl) {
+ const targetId = sessionId.slice("session:".length);
+ tabs.get(targetId).url = navigateOnNextClickUrl;
+ tabs.get(targetId).title = navigateOnNextClickUrl;
+ navigateOnNextClickUrl = null;
+ }
+ openPendingPopup();
+ }
return {};
}
if (method === "Target.activateTarget") {
@@ -247,9 +271,10 @@ function createFixture(rootDir) {
}
throw new Error(`unexpected CDP method ${method}`);
},
- async snapshot() {
+ async snapshot(options = {}) {
const tab = tabs.get(activeTarget);
calls.push(["snapshot", activeTarget]);
+ snapshotOptions.push(options);
return {
content: `snapshot:${tab?.url}`,
refs: [
@@ -294,6 +319,7 @@ function createFixture(rootDir) {
gate,
rootDir,
services,
+ snapshotOptions,
tabs,
openPopupOnNextClick(url) {
popupOnNextClick = url;
@@ -304,6 +330,9 @@ function createFixture(rootDir) {
rejectNextClickPoint() {
rejectNextClickPoint = true;
},
+ navigateOnNextClick(url) {
+ navigateOnNextClickUrl = url;
+ },
emitPageEvent(targetId, method, params = {}) {
const sessionId = `session:${targetId}`;
const events = pageEvents.get(sessionId) || [];
@@ -337,7 +366,7 @@ test("a page label restores in a new round and goto reuses its target", async ()
const secondRound = taskForRound(fixture, "round-b");
const restored = secondRound.page("p1");
- await restored.goto("https://example.test/second");
+ const receipt = await restored.goto("https://example.test/second");
assert.equal(restored.targetId, "target-1");
assert.equal(fixture.tabs.size, 1, "goto must not create a second tab");
@@ -345,9 +374,16 @@ test("a page label restores in a new round and goto reuses its target", async ()
fixture.tabs.get("target-1").url,
"https://example.test/second",
);
- assert.equal(
+ assert.deepEqual(receipt, {
+ navigation: {
+ from: "https://example.test/first",
+ to: "https://example.test/second",
+ },
+ domChanged: true,
+ });
+ assert.match(
await restored.snapshot(),
- "snapshot:https://example.test/second",
+ /\[p1 .*space "research"\(7\).*\]\nsnapshot:https:\/\/example\.test\/second/,
);
});
});
@@ -411,11 +447,36 @@ test("snapshot activates the addressed page, not whichever tab was current", asy
await task.newPage("https://example.test/second");
assert.equal(fixture.activeTarget(), "target-2");
- assert.equal(await first.snapshot(), "snapshot:https://example.test/first");
+ assert.match(
+ await first.snapshot(),
+ /\[p1 .*space "research"\(7\).*\]\nsnapshot:https:\/\/example\.test\/first/,
+ );
assert.equal(fixture.activeTarget(), "target-1");
});
});
+test("snapshot reports its source and returns a line diff after the baseline", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.newPage("https://example.test/before");
+
+ const first = await page.snapshot({ diff: true });
+ assert.match(first, /diff: full \(baseline unavailable\)/);
+ assert.match(first, /snapshot:https:\/\/example\.test\/before/);
+
+ await page.goto("https://example.test/after");
+ const second = await page.snapshot({ diff: true });
+ assert.match(second, /diff: changes from previous snapshot/);
+ assert.match(second, /-snapshot:https:\/\/example\.test\/before/);
+ assert.match(second, /\+snapshot:https:\/\/example\.test\/after/);
+ assert.equal(
+ Object.hasOwn(fixture.snapshotOptions.at(-1), "diff"),
+ false,
+ "diff is a JS option and must not leak into the native snapshot call",
+ );
+ });
+});
+
test("metadata reads stay target-scoped while evaluate and screenshot activate their Page", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -672,6 +733,22 @@ test("Page fill uses its target session and reports no popup when none opened",
});
});
+test("Page action receipts report navigation and obvious document changes", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await task.newPage("https://example.test/before");
+ fixture.navigateOnNextClick("https://example.test/after");
+
+ assert.deepEqual(await page.click("#navigate"), {
+ navigation: {
+ from: "https://example.test/before",
+ to: "https://example.test/after",
+ },
+ domChanged: true,
+ });
+ });
+});
+
test("Page pointer methods dispatch through the addressed target session", async () => {
await withFixture(async (fixture) => {
const task = taskForRound(fixture, "round-a");
@@ -1145,9 +1222,9 @@ test("adopt turns a live untracked page into a managed page", async () => {
assert.equal(adopted.label, "notes");
assert.equal(adopted.targetId, "target-user");
assert.equal(adopted.openedBy, "unknown");
- assert.equal(
+ assert.match(
await adopted.snapshot(),
- "snapshot:https://example.test/user",
+ /\[notes .*space "research"\(7\).*\]\nsnapshot:https:\/\/example\.test\/user/,
);
assert.deepEqual(
(await task.listPages()).map(({ label, openedBy }) => ({
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 406f853..6bf75ef 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -78,6 +78,10 @@ type PageGotoOptions = {
timeout?: number;
};
+type PageSnapshotOptions = Record<string, unknown> & {
+ diff?: boolean;
+};
+
type CdpOptions = {
timeout?: number;
};
@@ -139,6 +143,7 @@ type OperationGate = {
};
type LedgerPort = {
+ read(spaceId: number): Promise<PageLedger>;
addPage(
spaceId: number,
targetId: string,
@@ -163,6 +168,7 @@ type RuntimeTab = {
type PageModelServices = {
ledger: LedgerPort;
pageRefs: PageRefRegistry;
+ snapshotBaselines: Map<string, string>;
gate: OperationGate;
createTab(url: string): Promise<string>;
listTabs(): Promise<RuntimeTab[]>;
@@ -201,6 +207,8 @@ export type PageInventoryItem = {
export type PageActionReceipt = {
popups?: Array<{ label: string; targetId: string }>;
+ navigation?: { from: string; to: string };
+ domChanged?: true;
};
type MouseActionRunner = (
@@ -341,6 +349,7 @@ export class PageBudgetError extends Error {
let defaultLedger: PageLedgerStore | undefined;
const defaultPageRefs = new PageRefRegistry();
+const defaultSnapshotBaselines = new Map<string, string>();
const unmanagedPageConstructorToken = Symbol("UnmanagedPage");
const defaultGate: OperationGate = {
@@ -351,6 +360,7 @@ const defaultGate: OperationGate = {
const baseDefaultServices: Omit<PageModelServices, "ledger" | "pageBudget"> = {
gate: defaultGate,
pageRefs: defaultPageRefs,
+ snapshotBaselines: defaultSnapshotBaselines,
async createTab(url) {
const result = assertNoEgoError(
await browserEgo().createTab(url),
@@ -633,6 +643,7 @@ export class Page {
readonly mouse: PageMouse;
readonly keyboard: PageKeyboard;
readonly #services: PageModelServices;
+ readonly #spaceName: string;
#targetId?: string;
#openedBy?: PageOrigin;
#closed = false;
@@ -645,6 +656,7 @@ export class Page {
) {
this.label = label;
this.spaceId = task.id;
+ this.#spaceName = task.name;
this.#services = services;
this.#targetId = entry?.targetId;
this.#openedBy = entry?.openedBy;
@@ -669,13 +681,17 @@ export class Page {
return this.#openedBy;
}
- async goto(url: string, options: PageGotoOptions = {}): Promise<any> {
+ async goto(
+ url: string,
+ options: PageGotoOptions = {},
+ ): Promise<PageActionReceipt> {
assertUrl(url);
const timeoutMs = options.timeout ?? 15_000;
assertTimeout(timeoutMs);
const page = await this.#resolve();
- return this.#services.gate.withPage(page, async ({ sessionId }) => {
- try {
+ const { receipt } = await this.#runActionBoundary(
+ page,
+ async (sessionId) => {
const navigation = await this.#services.cdp(
"Page.navigate",
{ url },
@@ -686,14 +702,19 @@ export class Page {
throw new Error(`page.goto failed: ${navigation.errorText}`);
}
await waitForReadyState(this.#services, sessionId, timeoutMs);
- return navigation;
- } finally {
- this.#services.pageRefs.clear(page.targetId);
- }
- });
+ },
+ );
+ return receipt;
}
- async snapshot(options: Record<string, unknown> = {}): Promise<string> {
+ async snapshot(options: PageSnapshotOptions = {}): Promise<string> {
+ if (!options || typeof options !== "object" || Array.isArray(options)) {
+ throw new TypeError("page.snapshot options must be an object");
+ }
+ const { diff = false, ...nativeOptions } = options;
+ if (typeof diff !== "boolean") {
+ throw new TypeError("page.snapshot diff must be a boolean");
+ }
const page = await this.#resolve();
return this.#services.gate.withPage(page, async () => {
await this.#activate(page.targetId);
@@ -701,10 +722,23 @@ export class Page {
scope: "full_page",
includeActionMarks: true,
includeStableLocator: true,
- ...options,
+ ...nativeOptions,
});
this.#services.pageRefs.replace(page.targetId, result?.refs || []);
- return result?.content || "";
+ const content = result?.content || "";
+ const previous = this.#services.snapshotBaselines.get(page.targetId);
+ this.#services.snapshotBaselines.set(page.targetId, content);
+ const projection =
+ diff && previous !== undefined
+ ? snapshotLineDiff(previous, content)
+ : content;
+ const diffStatus = !diff
+ ? undefined
+ : previous === undefined
+ ? "full (baseline unavailable)"
+ : "changes from previous snapshot";
+ const header = await this.#snapshotHeader(page, diffStatus);
+ return `${header}\n${projection}`;
});
}
@@ -956,6 +990,7 @@ export class Page {
if (!live) {
await this.#services.ledger.closePage(this.spaceId, this.label);
this.#services.pageRefs.clear(page.targetId);
+ this.#services.snapshotBaselines.delete(page.targetId);
this.#closed = true;
throw new Error(`page ${this.label} was closed`);
}
@@ -970,6 +1005,7 @@ export class Page {
}
this.#services.invalidateSession(page.targetId);
this.#services.pageRefs.clear(page.targetId);
+ this.#services.snapshotBaselines.delete(page.targetId);
await this.#services.ledger.closePage(this.spaceId, this.label);
this.#closed = true;
});
@@ -1053,6 +1089,10 @@ export class Page {
const before = new Set(
(await this.#services.listTabs()).map((tab) => tab.targetId),
);
+ const observation = await startActionObservation(
+ this.#services,
+ sessionId,
+ );
let actionError: unknown;
let value: T | undefined;
try {
@@ -1065,6 +1105,11 @@ export class Page {
// settle covers native tab-list propagation without turning this into a
// navigation wait or silently changing the page's active state.
await this.#services.sleep(50);
+ const observedAfter = await finishActionObservation(
+ this.#services,
+ sessionId,
+ observation,
+ );
let popupError: unknown;
const popups: Array<{ label: string; targetId: string }> = [];
try {
@@ -1086,7 +1131,7 @@ export class Page {
if (popupError) throw popupError;
return {
value: value as T,
- receipt: popups.length > 0 ? { popups } : {},
+ receipt: actionReceipt(observation, observedAfter, popups),
};
} finally {
this.#services.pageRefs.clear(page.targetId);
@@ -1114,12 +1159,241 @@ export class Page {
return refs;
}
+ async #snapshotHeader(
+ page: PageTarget,
+ diffStatus?: string,
+ ): Promise<string> {
+ try {
+ const [tabs, ledger] = await Promise.all([
+ this.#services.listTabs(),
+ this.#services.ledger.read(this.spaceId),
+ ]);
+ return snapshotSourceHeader({
+ currentLabel: this.label,
+ currentTargetId: page.targetId,
+ diffStatus,
+ ledger,
+ pageBudget: this.#services.pageBudget,
+ spaceId: this.spaceId,
+ spaceName: this.#spaceName,
+ tabs,
+ });
+ } catch {
+ const diffPart = diffStatus ? ` | diff: ${diffStatus}` : "";
+ return `[${this.label} | space ${JSON.stringify(this.#spaceName)}(${this.spaceId})${diffPart}]`;
+ }
+ }
+
async #activate(targetId: string): Promise<void> {
await this.#services.cdp("Target.activateTarget", { targetId });
this.#services.setPreferredTarget(targetId);
}
}
+type ActionObservation = {
+ id: string;
+ url: string;
+ documentToken: string;
+ controlHash: number;
+ mutations?: number;
+};
+
+async function startActionObservation(
+ services: PageModelServices,
+ sessionId: string,
+): Promise<ActionObservation | undefined> {
+ const id = `action_${services.now()}_${Math.random().toString(16).slice(2)}`;
+ try {
+ const response = await services.cdp(
+ "Runtime.evaluate",
+ {
+ expression: `(() => {
+ const id = ${JSON.stringify(id)};
+ const hashControls = () => {
+ let hash = 2166136261;
+ const values = Array.from(document.querySelectorAll('input,textarea,select'))
+ .map((element) => [element.value, element.checked, element.selectedIndex].join(':'))
+ .join('|');
+ for (let index = 0; index < values.length; index += 1) {
+ hash = Math.imul(hash ^ values.charCodeAt(index), 16777619);
+ }
+ return hash >>> 0;
+ };
+ const probe = { mutations: 0 };
+ probe.observer = new MutationObserver((records) => {
+ probe.mutations += records.length;
+ });
+ if (document.documentElement) {
+ probe.observer.observe(document.documentElement, {
+ attributes: true,
+ childList: true,
+ characterData: true,
+ subtree: true,
+ });
+ }
+ globalThis.__egoBrowserActionProbes ||= Object.create(null);
+ globalThis.__egoBrowserActionProbes[id] = probe;
+ return {
+ url: location.href,
+ documentToken: String(performance.timeOrigin),
+ controlHash: hashControls(),
+ };
+ })()`,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
+ const value = response?.result?.value;
+ if (!value || typeof value.url !== "string") return undefined;
+ return { id, ...value };
+ } catch {
+ // Receipts are feedback only. A page that blocks observation must not make
+ // the requested action fail.
+ return undefined;
+ }
+}
+
+async function finishActionObservation(
+ services: PageModelServices,
+ sessionId: string,
+ before: ActionObservation | undefined,
+): Promise<ActionObservation | undefined> {
+ if (!before) return undefined;
+ try {
+ const response = await services.cdp(
+ "Runtime.evaluate",
+ {
+ expression: `(() => {
+ const id = ${JSON.stringify(before.id)};
+ const hashControls = () => {
+ let hash = 2166136261;
+ const values = Array.from(document.querySelectorAll('input,textarea,select'))
+ .map((element) => [element.value, element.checked, element.selectedIndex].join(':'))
+ .join('|');
+ for (let index = 0; index < values.length; index += 1) {
+ hash = Math.imul(hash ^ values.charCodeAt(index), 16777619);
+ }
+ return hash >>> 0;
+ };
+ const probes = globalThis.__egoBrowserActionProbes;
+ const probe = probes?.[id];
+ let mutations = 0;
+ if (probe) {
+ mutations = probe.mutations + probe.observer.takeRecords().length;
+ probe.observer.disconnect();
+ delete probes[id];
+ }
+ return {
+ url: location.href,
+ documentToken: String(performance.timeOrigin),
+ controlHash: hashControls(),
+ mutations,
+ };
+ })()`,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
+ const value = response?.result?.value;
+ if (!value || typeof value.url !== "string") return undefined;
+ return { id: before.id, ...value };
+ } catch {
+ return undefined;
+ }
+}
+
+function actionReceipt(
+ before: ActionObservation | undefined,
+ after: ActionObservation | undefined,
+ popups: Array<{ label: string; targetId: string }>,
+): PageActionReceipt {
+ const receipt: PageActionReceipt = {};
+ if (before && after) {
+ const navigated =
+ before.url !== after.url || before.documentToken !== after.documentToken;
+ if (navigated) {
+ receipt.navigation = { from: before.url, to: after.url };
+ }
+ if (
+ navigated ||
+ (after.mutations ?? 0) > 0 ||
+ before.controlHash !== after.controlHash
+ ) {
+ receipt.domChanged = true;
+ }
+ }
+ if (popups.length > 0) receipt.popups = popups;
+ return receipt;
+}
+
+function snapshotSourceHeader(input: {
+ currentLabel: string;
+ currentTargetId: string;
+ diffStatus?: string;
+ ledger: PageLedger;
+ pageBudget: number;
+ spaceId: number;
+ spaceName: string;
+ tabs: RuntimeTab[];
+}): string {
+ const tabsByTarget = new Map(input.tabs.map((tab) => [tab.targetId, tab]));
+ const managedTargets = new Set(
+ Object.values(input.ledger.pages).map((page) => page.targetId),
+ );
+ const current = tabsByTarget.get(input.currentTargetId);
+ const currentTitle = compactPageTitle(
+ current?.title || current?.url || "untitled",
+ );
+ const pages = Object.entries(input.ledger.pages).map(([label, page]) => {
+ const tab = tabsByTarget.get(page.targetId);
+ const title = compactPageTitle(tab?.title || tab?.url || "untitled");
+ return `${label}${page.targetId === input.currentTargetId ? "*" : ""} ${JSON.stringify(title)}`;
+ });
+ const untracked = input.tabs.filter(
+ (tab) => !managedTargets.has(tab.targetId),
+ ).length;
+ const managed = pages.length;
+ const budget =
+ managed >= input.pageBudget - 1
+ ? ` | budget ${managed}/${input.pageBudget}`
+ : "";
+ const diff = input.diffStatus ? ` | diff: ${input.diffStatus}` : "";
+ const inventory = pages.length > 0 ? ` — ${pages.join(", ")}` : "";
+ return `[${input.currentLabel} ${JSON.stringify(currentTitle)} | space ${JSON.stringify(input.spaceName)}(${input.spaceId}): ${managed} managed, ${untracked} untracked${inventory}${budget}${diff}]`;
+}
+
+function snapshotLineDiff(previous: string, current: string): string {
+ if (previous === current) return "[no snapshot changes]";
+ const oldLines = previous.split("\n");
+ const newLines = current.split("\n");
+ let prefix = 0;
+ while (
+ prefix < oldLines.length &&
+ prefix < newLines.length &&
+ oldLines[prefix] === newLines[prefix]
+ ) {
+ prefix += 1;
+ }
+ let suffix = 0;
+ while (
+ suffix < oldLines.length - prefix &&
+ suffix < newLines.length - prefix &&
+ oldLines[oldLines.length - 1 - suffix] ===
+ newLines[newLines.length - 1 - suffix]
+ ) {
+ suffix += 1;
+ }
+ const removed = oldLines.slice(prefix, oldLines.length - suffix);
+ const added = newLines.slice(prefix, newLines.length - suffix);
+ return [
+ `@@ line ${prefix + 1} @@`,
+ ...removed.map((line) => `-${line}`),
+ ...added.map((line) => `+${line}`),
+ ].join("\n");
+}
+
async function evaluateInSession<T>(
services: PageModelServices,
sessionId: string,
diff --git a/package/ego-browser/src/run-output-sink.test.mjs b/package/ego-browser/src/run-output-sink.test.mjs
index 97d83d9..28d9276 100644
--- a/package/ego-browser/src/run-output-sink.test.mjs
+++ b/package/ego-browser/src/run-output-sink.test.mjs
@@ -85,6 +85,37 @@ test("a clean run flushes buffered cliLog output in order", async () => {
assert.equal(result.stdout, "one\ntwo\n");
});
+test("round console methods share the buffered output channel", async () => {
+ const result = await runScript(`
+ console.log("plain", { value: 1 });
+ console.info("info");
+ console.warn("careful");
+ console.error("broken");
+ cliLog("legacy");
+ `);
+
+ assert.equal(result.exitCode, 0);
+ assert.equal(
+ result.stdout,
+ 'plain {"value":1}\ninfo\n[warn] careful\n[error] broken\nlegacy\n',
+ );
+});
+
+test("a hard stop discards console output together with cliLog output", async () => {
+ const ego = hardStopEgo("EGO_TASK_SPACE_USER_IN_CONTROL");
+ const result = await runScript(
+ `
+ console.log("before");
+ try { await listTaskSpaces(); } catch {}
+ console.warn("after");
+ `,
+ ego,
+ );
+
+ assert.match(result.stdout, /taken control of this task space/);
+ assert.doesNotMatch(result.stdout, /before|after/);
+});
+
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(
diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.ts
index df026c6..21bce66 100644
--- a/package/ego-browser/src/run.ts
+++ b/package/ego-browser/src/run.ts
@@ -6,7 +6,12 @@ import {
import { formatCliLogValue } from "./format.js";
import * as helpers from "./helpers.js";
-import { bufferOutput, flushSink, resetSink } from "./output-sink.js";
+import {
+ bufferOutput,
+ createRoundConsole,
+ flushSink,
+ resetSink,
+} from "./output-sink.js";
type WritableLike = {
write(chunk: string): unknown;
@@ -108,7 +113,11 @@ export async function runMain(options: RunMainOptions = {}) {
async function execute(code: string, stdout: WritableLike) {
resetSink();
const context = await executionContext();
- Object.assign(globalThis, context);
+ // Helpers remain globally visible for loaded agent modules, but console is a
+ // lexical round parameter so the CLI never replaces Node's process console.
+ const globalHelpers = { ...context };
+ delete globalHelpers.console;
+ Object.assign(globalThis, globalHelpers);
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
const names = Object.keys(context);
const values = Object.values(context);
@@ -135,6 +144,8 @@ export async function executionContext() {
// once the script settles. Keeps the CLI path identical to the SDK path.
bufferOutput(`${args.map(formatCliLogValue).join(" ")}\n`);
};
+ // A lexical parameter shadows Node's global console without mutating it.
+ context.console = createRoundConsole();
return context;
}