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.

style: format ego-browser sources with Prettier

0x0fccd624688cb
diff --git a/package/ego-browser/src/browser-runtime.ts b/package/ego-browser/src/browser-runtime.ts
index d5feefc..afa1f89 100644
--- a/package/ego-browser/src/browser-runtime.ts
+++ b/package/ego-browser/src/browser-runtime.ts
@@ -5,15 +5,19 @@ const SESSION_TTL_MS = 2000;
// Upper bound for buffered CDP events. The runtime can be long-lived (installEgoSdk
// inside the browser); without a cap, undrained events grow without bound.
const MAX_BUFFERED_EVENTS = 10000;
-const SESSION_LOST = /Session (?:with given id )?not found|Target closed|No session/i;
-const BROWSER_LEVEL = (method) => method.startsWith("Target.") || method.startsWith("Browser.");
+const SESSION_LOST =
+ /Session (?:with given id )?not found|Target closed|No session/i;
+const BROWSER_LEVEL = (method) =>
+ method.startsWith("Target.") || method.startsWith("Browser.");
let nextMessageId = 1;
const pending = new Map();
const events = [];
const pageEnabledSessions = new Set();
const pendingDialogs = new Map();
export function isBrowserRuntime() {
- return Boolean(globalThis.ego && typeof globalThis.ego.sendCDPMessage === "function");
+ return Boolean(
+ globalThis.ego && typeof globalThis.ego.sendCDPMessage === "function",
+ );
}
export function browserEgo() {
@@ -23,11 +27,21 @@ export function browserEgo() {
return globalThis.ego;
}
-function rawCdp(method, params: any = {}, sessionId = undefined, timeoutMs = RESPONSE_TIMEOUT_MS) {
+function rawCdp(
+ method,
+ params: any = {},
+ sessionId = undefined,
+ timeoutMs = RESPONSE_TIMEOUT_MS,
+) {
const runtime = browserEgo();
runtime.onCDPMessage = handleMessage;
const id = nextMessageId++;
- const payload = JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) });
+ const payload = JSON.stringify({
+ id,
+ method,
+ params,
+ ...(sessionId ? { sessionId } : {}),
+ });
return new Promise<any>((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
@@ -41,7 +55,7 @@ function rawCdp(method, params: any = {}, sessionId = undefined, timeoutMs = RES
reject: (error) => {
clearTimeout(timer);
reject(error);
- }
+ },
});
try {
runtime.sendCDPMessage(payload);
@@ -53,7 +67,12 @@ function rawCdp(method, params: any = {}, sessionId = undefined, timeoutMs = RES
});
}
-export async function browserCdp(method, params: any = {}, sessionId = undefined, timeoutMs = RESPONSE_TIMEOUT_MS) {
+export async function browserCdp(
+ method,
+ params: any = {},
+ sessionId = undefined,
+ timeoutMs = RESPONSE_TIMEOUT_MS,
+) {
// Test mock: cdpOverride bypasses everything including session injection.
if (state.cdpOverride) {
return state.cdpOverride(method, params, sessionId);
@@ -93,13 +112,18 @@ export async function ensureSession() {
const preferred = state.preferredTargetId
? tabs.find((t) => t.targetId === state.preferredTargetId)
: null;
- const active = preferred || tabs.find((t) => t.active) || tabs[tabs.length - 1];
+ const active =
+ preferred || tabs.find((t) => t.active) || tabs[tabs.length - 1];
if (!active) {
throw new Error("no active tab to attach session");
}
const targetId = active.targetId;
if (targetId !== state.sessionTargetId || !state.sessionId) {
- const attached = await rawCdp("Target.attachToTarget", { targetId, flatten: true }, undefined);
+ const attached = await rawCdp(
+ "Target.attachToTarget",
+ { targetId, flatten: true },
+ undefined,
+ );
state.sessionId = attached.result?.sessionId || attached.sessionId;
state.sessionTargetId = targetId;
}
@@ -176,7 +200,10 @@ function handleMessage(message) {
entry.resolve(data);
return;
}
- if (data.method === "Target.detachedFromTarget" || data.method === "Target.targetDestroyed") {
+ if (
+ data.method === "Target.detachedFromTarget" ||
+ data.method === "Target.targetDestroyed"
+ ) {
const sessionId = data.params?.sessionId || data.sessionId;
if (sessionId) {
pageEnabledSessions.delete(sessionId);
@@ -213,6 +240,12 @@ export function browserSnapshotRefsToRefMap(refMap, refs = []) {
if (ref.backendNodeId === undefined || ref.backendNodeId === null) {
continue;
}
- refMap.add(String(ref.backendNodeId), ref.backendNodeId, ref.role, ref.name, undefined);
+ refMap.add(
+ String(ref.backendNodeId),
+ ref.backendNodeId,
+ ref.role,
+ ref.name,
+ undefined,
+ );
}
}
diff --git a/package/ego-browser/src/cdp-eval.ts b/package/ego-browser/src/cdp-eval.ts
index 9b50659..141d730 100644
--- a/package/ego-browser/src/cdp-eval.ts
+++ b/package/ego-browser/src/cdp-eval.ts
@@ -15,7 +15,10 @@ export async function cdp(method, params: any = {}, sessionId = undefined) {
const result = state.cdpOverride
? await state.cdpOverride(method, params, sessionId)
: (await send({ method, params, session_id: sessionId })).result || {};
- if (!sessionId && (method === "Network.enable" || method === "Network.disable")) {
+ if (
+ !sessionId &&
+ (method === "Network.enable" || method === "Network.disable")
+ ) {
// Mirror the default session's Network domain state so helpers like
// waitForNetworkIdle can restore it instead of tearing down a domain
// the caller still relies on for drainEvents().
@@ -39,20 +42,23 @@ export async function js(expression, targetId = undefined) {
hasWarnedAboutFunctionJs = true;
process.stderr.write(
`[ego-browser] js() received a function and auto-wrapped it (${jsSnippet(source, 80)}).\n` +
- ` js() is a thin wrapper over CDP Runtime.evaluate; it takes a string expression,\n` +
- ` not a Puppeteer/Playwright-style callable. Auto-wrap does NOT capture closure\n` +
- ` variables and has NO args channel.\n` +
- ` Prefer:\n` +
- ` js(\`<expression>\`) // pure expression or explicit IIFE\n`
+ ` js() is a thin wrapper over CDP Runtime.evaluate; it takes a string expression,\n` +
+ ` not a Puppeteer/Playwright-style callable. Auto-wrap does NOT capture closure\n` +
+ ` variables and has NO args channel.\n` +
+ ` Prefer:\n` +
+ ` js(\`<expression>\`) // pure expression or explicit IIFE\n`,
);
}
expression = `(${source})()`;
} else if (typeof expression !== "string") {
throw new TypeError(
- `js() expects a string expression or function, got ${expression === null ? "null" : typeof expression}`
+ `js() expects a string expression or function, got ${expression === null ? "null" : typeof expression}`,
);
}
- const sessionId = targetId ? (await cdp("Target.attachToTarget", { targetId, flatten: true })).sessionId : undefined;
+ const sessionId = targetId
+ ? (await cdp("Target.attachToTarget", { targetId, flatten: true }))
+ .sessionId
+ : undefined;
let finalExpression = expression;
if (hasReturnStatement(expression) && !expression.trim().startsWith("(")) {
finalExpression = `(function(){${expression}})()`;
@@ -60,17 +66,30 @@ export async function js(expression, targetId = undefined) {
return runtimeEvaluate(finalExpression, sessionId, true);
}
-async function runtimeEvaluate(expression, sessionId = undefined, awaitPromise = false) {
+async function runtimeEvaluate(
+ expression,
+ sessionId = undefined,
+ awaitPromise = false,
+) {
try {
- const response = await cdp("Runtime.evaluate", {
- expression,
- returnByValue: true,
- awaitPromise
- }, sessionId);
+ const response = await cdp(
+ "Runtime.evaluate",
+ {
+ expression,
+ returnByValue: true,
+ awaitPromise,
+ },
+ sessionId,
+ );
return runtimeValue(response, expression);
} catch (error) {
- if (error instanceof TimeoutError || /timed out/i.test(error?.message || "")) {
- throw new Error(`Runtime.evaluate timed out; expression: ${jsSnippet(expression)}`);
+ if (
+ error instanceof TimeoutError ||
+ /timed out/i.test(error?.message || "")
+ ) {
+ throw new Error(
+ `Runtime.evaluate timed out; expression: ${jsSnippet(expression)}`,
+ );
}
throw error;
}
@@ -81,10 +100,13 @@ export function runtimeValue(response, expression) {
const details = response.exceptionDetails;
if (details || result.subtype === "error") {
const desc = jsExceptionDescription(result, details);
- const loc = details?.lineNumber !== undefined && details?.columnNumber !== undefined
- ? ` at line ${details.lineNumber}, column ${details.columnNumber}`
- : "";
- throw new Error(`JavaScript evaluation failed${loc}: ${desc}; expression: ${jsSnippet(expression)}`);
+ const loc =
+ details?.lineNumber !== undefined && details?.columnNumber !== undefined
+ ? ` at line ${details.lineNumber}, column ${details.columnNumber}`
+ : "";
+ throw new Error(
+ `JavaScript evaluation failed${loc}: ${desc}; expression: ${jsSnippet(expression)}`,
+ );
}
if (Object.hasOwn(result, "value")) {
return result.value;
@@ -142,7 +164,7 @@ export function hasReturnStatement(expression) {
const ch = expression[i];
const next = expression[i + 1] || "";
if (stateName === "code") {
- if (ch === "'" || ch === "\"" || ch === "`") {
+ if (ch === "'" || ch === '"' || ch === "`") {
stateName = "string";
quote = ch;
i += 1;
diff --git a/package/ego-browser/src/driver/nav.test.mjs b/package/ego-browser/src/driver/nav.test.mjs
index c12f20a..7da2ed9 100644
--- a/package/ego-browser/src/driver/nav.test.mjs
+++ b/package/ego-browser/src/driver/nav.test.mjs
@@ -1,8 +1,17 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { browserCdp, invalidateSession, pendingDialog } from "../../dist/src/browser-runtime.js";
-import { listTabs, newTab, pageInfo, closeTab } from "../../dist/src/driver/nav.js";
+import {
+ browserCdp,
+ invalidateSession,
+ pendingDialog,
+} from "../../dist/src/browser-runtime.js";
+import {
+ listTabs,
+ newTab,
+ pageInfo,
+ closeTab,
+} from "../../dist/src/driver/nav.js";
import { setOverrides, state } from "../../dist/src/state.js";
function withEgo(ego, fn) {
@@ -26,8 +35,13 @@ function withCdpRuntime(fn) {
async listTabs() {
return {
tabs: [
- { targetId: "target-1", active: true, title: "Example", url: "https://example.com/" }
- ]
+ {
+ targetId: "target-1",
+ active: true,
+ title: "Example",
+ url: "https://example.com/",
+ },
+ ],
};
},
sendCDPMessage(payload) {
@@ -47,16 +61,20 @@ function withCdpRuntime(fn) {
sx: 0,
sy: 0,
pw: 800,
- ph: 1200
- })
- }
+ ph: 1200,
+ }),
+ },
};
}
- queueMicrotask(() => runtime.onCDPMessage(JSON.stringify({ id: request.id, result })));
+ queueMicrotask(() =>
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result })),
+ );
},
emit(method, params) {
- runtime.onCDPMessage(JSON.stringify({ sessionId: "session-1", method, params }));
- }
+ runtime.onCDPMessage(
+ JSON.stringify({ sessionId: "session-1", method, params }),
+ );
+ },
};
globalThis.ego = runtime;
invalidateSession();
@@ -73,42 +91,51 @@ function withCdpRuntime(fn) {
}
test("listTabs throws on ego binding error objects", async () => {
- await withEgo({
- async listTabs() {
- return { error: "The task is under user control" };
- }
- }, async () => {
- await assert.rejects(
- () => listTabs(),
- /listTabs: The task is under user control/
- );
- });
+ await withEgo(
+ {
+ async listTabs() {
+ return { error: "The task is under user control" };
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => listTabs(),
+ /listTabs: The task is under user control/,
+ );
+ },
+ );
});
test("newTab throws on ego binding error objects", async () => {
- await withEgo({
- async createTab() {
- return { error: "The task is under user control" };
- }
- }, async () => {
- await assert.rejects(
- () => newTab("https://example.com/"),
- /newTab: The task is under user control/
- );
- });
+ await withEgo(
+ {
+ async createTab() {
+ return { error: "The task is under user control" };
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => newTab("https://example.com/"),
+ /newTab: The task is under user control/,
+ );
+ },
+ );
});
test("newTab throws when the binding returns no targetId", async () => {
- await withEgo({
- async createTab() {
- return {};
- }
- }, async () => {
- await assert.rejects(
- () => newTab("https://example.com/"),
- /newTab returned no targetId/
- );
- });
+ await withEgo(
+ {
+ async createTab() {
+ return {};
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => newTab("https://example.com/"),
+ /newTab returned no targetId/,
+ );
+ },
+ );
});
test("closeTab closes an explicit target and returns its id", async () => {
@@ -117,7 +144,7 @@ test("closeTab closes an explicit target and returns its id", async () => {
cdpOverride(method, params, sessionId) {
calls.push({ method, params, sessionId });
return { success: true };
- }
+ },
});
try {
assert.equal(await closeTab("target-2"), "target-2");
@@ -129,48 +156,56 @@ test("closeTab closes an explicit target and returns its id", async () => {
{
method: "Target.closeTarget",
params: { targetId: "target-2" },
- sessionId: undefined
- }
+ sessionId: undefined,
+ },
]);
});
test("closeTab closes the current tab and invalidates matching session state", async () => {
const calls = [];
- await withEgo({
- async listTabs() {
- return {
- tabs: [
- { targetId: "target-1", active: true, title: "Example", url: "https://example.com/" }
- ]
- };
- }
- }, async () => {
- const restore = setOverrides({
- cdpOverride(method, params, sessionId) {
- calls.push({ method, params, sessionId });
- return { success: true };
+ await withEgo(
+ {
+ async listTabs() {
+ return {
+ tabs: [
+ {
+ targetId: "target-1",
+ active: true,
+ title: "Example",
+ url: "https://example.com/",
+ },
+ ],
+ };
},
- sessionId: "session-1",
- sessionTargetId: "target-1",
- sessionAt: Date.now(),
- preferredTargetId: "target-1"
- });
- try {
- assert.equal(await closeTab(), "target-1");
- assert.equal(state.sessionId, null);
- assert.equal(state.sessionTargetId, null);
- assert.equal(state.preferredTargetId, null);
- } finally {
- restore();
- }
- });
+ },
+ async () => {
+ const restore = setOverrides({
+ cdpOverride(method, params, sessionId) {
+ calls.push({ method, params, sessionId });
+ return { success: true };
+ },
+ sessionId: "session-1",
+ sessionTargetId: "target-1",
+ sessionAt: Date.now(),
+ preferredTargetId: "target-1",
+ });
+ try {
+ assert.equal(await closeTab(), "target-1");
+ assert.equal(state.sessionId, null);
+ assert.equal(state.sessionTargetId, null);
+ assert.equal(state.preferredTargetId, null);
+ } finally {
+ restore();
+ }
+ },
+ );
assert.deepEqual(calls, [
{
method: "Target.closeTarget",
params: { targetId: "target-1" },
- sessionId: undefined
- }
+ sessionId: undefined,
+ },
]);
});
@@ -178,22 +213,21 @@ test("browser runtime enables Page events and tracks pending native dialogs", as
await withCdpRuntime(async ({ runtime, sent }) => {
await browserCdp("Runtime.evaluate", { expression: "document.title" });
- assert.deepEqual(sent.map((request) => request.method), [
- "Target.attachToTarget",
- "Page.enable",
- "Runtime.evaluate"
- ]);
+ assert.deepEqual(
+ sent.map((request) => request.method),
+ ["Target.attachToTarget", "Page.enable", "Runtime.evaluate"],
+ );
assert.equal(sent[1].sessionId, "session-1");
runtime.emit("Page.javascriptDialogOpening", {
type: "alert",
message: "Confirm action",
- url: "https://example.com/"
+ url: "https://example.com/",
});
assert.deepEqual(pendingDialog(), {
type: "alert",
message: "Confirm action",
- url: "https://example.com/"
+ url: "https://example.com/",
});
runtime.emit("Page.javascriptDialogClosed", { result: true });
@@ -209,16 +243,19 @@ test("pageInfo returns pending dialog without evaluating frozen page JavaScript"
runtime.emit("Page.javascriptDialogOpening", {
type: "confirm",
message: "Leave page?",
- url: "https://example.com/"
+ url: "https://example.com/",
});
assert.deepEqual(await pageInfo(), {
dialog: {
type: "confirm",
message: "Leave page?",
- url: "https://example.com/"
- }
+ url: "https://example.com/",
+ },
});
- assert.equal(sent.some((request) => request.method === "Runtime.evaluate"), false);
+ assert.equal(
+ sent.some((request) => request.method === "Runtime.evaluate"),
+ false,
+ );
});
});
diff --git a/package/ego-browser/src/driver/nav.ts b/package/ego-browser/src/driver/nav.ts
index 3e005d8..eba53a0 100644
--- a/package/ego-browser/src/driver/nav.ts
+++ b/package/ego-browser/src/driver/nav.ts
@@ -1,10 +1,24 @@
-import { browserEgo, clearPreferredTarget, ensureSession, invalidateSession, isBrowserRuntime, pendingDialog, setPreferredTarget } from "../browser-runtime.js";
+import {
+ browserEgo,
+ clearPreferredTarget,
+ ensureSession,
+ invalidateSession,
+ isBrowserRuntime,
+ pendingDialog,
+ setPreferredTarget,
+} from "../browser-runtime.js";
import { cdp, js } from "../cdp-eval.js";
import { assertNoEgoError } from "../ego-errors.js";
import { state } from "../state.js";
import { waitForDocumentLoad } from "./load.js";
-export const INTERNAL_URL_PREFIXES = ["chrome://", "chrome-untrusted://", "devtools://", "chrome-extension://", "about:"];
+export const INTERNAL_URL_PREFIXES = [
+ "chrome://",
+ "chrome-untrusted://",
+ "devtools://",
+ "chrome-extension://",
+ "about:",
+];
type TabInfo = {
targetId: string;
@@ -50,9 +64,15 @@ export async function gotoUrl(url) {
* @param {{timeout?: number, settle?: number, wait?: boolean}} [options]
* @returns {Promise<{navigation: object, loaded: boolean}>}
*/
-export async function gotoAndWait(url: string, options: GotoAndWaitOptions = {}) {
+export async function gotoAndWait(
+ url: string,
+ options: GotoAndWaitOptions = {},
+) {
const navigation = await gotoUrl(url);
- const loaded = options.wait === false ? false : await waitForDocumentLoad({ timeout: options.timeout ?? 20 });
+ const loaded =
+ options.wait === false
+ ? false
+ : await waitForDocumentLoad({ timeout: options.timeout ?? 20 });
const settle = Number(options.settle ?? 0);
if (settle > 0) {
await state.sleep(settle * 1000);
@@ -72,7 +92,8 @@ export async function pageInfo() {
return { dialog };
}
}
- const expression = "JSON.stringify({url:location.href,title:document.title,w:innerWidth,h:innerHeight,sx:scrollX,sy:scrollY,pw:document.documentElement.scrollWidth,ph:document.documentElement.scrollHeight})";
+ const expression =
+ "JSON.stringify({url:location.href,title:document.title,w:innerWidth,h:innerHeight,sx:scrollX,sy:scrollY,pw:document.documentElement.scrollWidth,ph:document.documentElement.scrollHeight})";
return JSON.parse(await js(expression));
}
@@ -81,13 +102,27 @@ export async function pageInfo() {
* @param {{includeChrome?: boolean}} [options]
* @returns {Promise<Array<{targetId:string,title:string,url:string}>>}
*/
-export async function listTabs(options: ListTabsOptions = {}): Promise<TabInfo[]> {
+export async function listTabs(
+ options: ListTabsOptions = {},
+): Promise<TabInfo[]> {
const includeChrome = options.includeChrome ?? true;
const result = assertNoEgoError(await browserEgo().listTabs(), "listTabs");
const tabs = result.tabs || [];
return tabs
- .filter((tab) => includeChrome || !INTERNAL_URL_PREFIXES.some((prefix) => (tab.url || "").startsWith(prefix)))
- .map((tab) => ({ targetId: tab.targetId, title: tab.title || "", url: tab.url || "", active: Boolean(tab.active), index: tab.index }));
+ .filter(
+ (tab) =>
+ includeChrome ||
+ !INTERNAL_URL_PREFIXES.some((prefix) =>
+ (tab.url || "").startsWith(prefix),
+ ),
+ )
+ .map((tab) => ({
+ targetId: tab.targetId,
+ title: tab.title || "",
+ url: tab.url || "",
+ active: Boolean(tab.active),
+ index: tab.index,
+ }));
}
/**
@@ -135,7 +170,10 @@ export async function newTab(url = "about:blank") {
* @param {{match?: "exact"|"origin"|"origin+path"|"includes", wait?: boolean, timeout?: number, settle?: number}} [options]
* @returns {Promise<{targetId:string,url:string,title:string,active:boolean,index?:number,reused:boolean}>}
*/
-export async function openOrReuseTab(url: string, options: OpenOrReuseTabOptions = {}) {
+export async function openOrReuseTab(
+ url: string,
+ options: OpenOrReuseTabOptions = {},
+) {
const tabs = await listTabs({ includeChrome: false });
const match = options.match || "exact";
const existing = tabs.find((tab) => tabMatchesUrl(tab.url, url, match));
@@ -167,9 +205,12 @@ export async function openOrReuseTab(url: string, options: OpenOrReuseTabOptions
* @returns {Promise<string>} Closed target id.
*/
export async function closeTab(target: TabTarget | undefined = undefined) {
- const targetId = target === undefined
- ? (await currentTab()).targetId
- : typeof target === "object" ? target.targetId : target;
+ const targetId =
+ target === undefined
+ ? (await currentTab()).targetId
+ : typeof target === "object"
+ ? target.targetId
+ : target;
if (!targetId) {
throw new Error("closeTab requires a targetId");
}
@@ -191,7 +232,10 @@ export async function ensureRealTab() {
return null;
}
const current = await currentTab().catch(() => null);
- if (current?.url && !INTERNAL_URL_PREFIXES.some((prefix) => current.url.startsWith(prefix))) {
+ if (
+ current?.url &&
+ !INTERNAL_URL_PREFIXES.some((prefix) => current.url.startsWith(prefix))
+ ) {
return current;
}
await switchTab(tabs[0].targetId);
@@ -205,7 +249,12 @@ export async function ensureRealTab() {
*/
export async function iframeTarget(urlSubstring) {
const targets = (await cdp("Target.getTargets")).targetInfos || [];
- return targets.find((target) => target.type === "iframe" && (target.url || "").includes(urlSubstring))?.targetId || null;
+ return (
+ targets.find(
+ (target) =>
+ target.type === "iframe" && (target.url || "").includes(urlSubstring),
+ )?.targetId || null
+ );
}
function tabMatchesUrl(tabUrl: string, wantedUrl: string, match: UrlMatchMode) {
@@ -227,7 +276,10 @@ function tabMatchesUrl(tabUrl: string, wantedUrl: string, match: UrlMatchMode) {
return tab.origin === wanted.origin;
}
if (match === "origin+path") {
- return tab.origin === wanted.origin && trimSlash(tab.pathname) === trimSlash(wanted.pathname);
+ return (
+ tab.origin === wanted.origin &&
+ trimSlash(tab.pathname) === trimSlash(wanted.pathname)
+ );
}
return tab.href === wanted.href;
}
diff --git a/package/ego-browser/src/driver/observe.test.mjs b/package/ego-browser/src/driver/observe.test.mjs
index 38a4a26..7bc9837 100644
--- a/package/ego-browser/src/driver/observe.test.mjs
+++ b/package/ego-browser/src/driver/observe.test.mjs
@@ -1,7 +1,10 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { browserCdp, invalidateSession } from "../../dist/src/browser-runtime.js";
+import {
+ browserCdp,
+ invalidateSession,
+} from "../../dist/src/browser-runtime.js";
import { captureScreenshot } from "../../dist/src/driver/observe.js";
import { setOverrides } from "../../dist/src/state.js";
@@ -12,8 +15,13 @@ function withCdpRuntime(fn) {
async listTabs() {
return {
tabs: [
- { targetId: "target-1", active: true, title: "Example", url: "https://example.com/" }
- ]
+ {
+ targetId: "target-1",
+ active: true,
+ title: "Example",
+ url: "https://example.com/",
+ },
+ ],
};
},
sendCDPMessage(payload) {
@@ -27,11 +35,15 @@ function withCdpRuntime(fn) {
} else if (request.method === "Runtime.evaluate") {
result = { result: { value: "1" } };
}
- queueMicrotask(() => runtime.onCDPMessage(JSON.stringify({ id: request.id, result })));
+ queueMicrotask(() =>
+ runtime.onCDPMessage(JSON.stringify({ id: request.id, result })),
+ );
},
emit(method, params) {
- runtime.onCDPMessage(JSON.stringify({ sessionId: "session-1", method, params }));
- }
+ runtime.onCDPMessage(
+ JSON.stringify({ sessionId: "session-1", method, params }),
+ );
+ },
};
globalThis.ego = runtime;
invalidateSession();
@@ -52,7 +64,7 @@ test("captureScreenshot skips page metric JavaScript while a native dialog is pe
const restore = setOverrides({
async writeFile(path, data) {
writes.push({ path, data });
- }
+ },
});
try {
await withCdpRuntime(async ({ runtime, sent }) => {
@@ -60,17 +72,22 @@ test("captureScreenshot skips page metric JavaScript while a native dialog is pe
runtime.emit("Page.javascriptDialogOpening", {
type: "alert",
message: "Blocked",
- url: "https://example.com/"
+ url: "https://example.com/",
});
sent.length = 0;
await captureScreenshot("/tmp/ego-browser-dialog-shot.png");
- assert.equal(sent.some((request) => request.method === "Runtime.evaluate"), false);
- const screenshot = sent.find((request) => request.method === "Page.captureScreenshot");
+ assert.equal(
+ sent.some((request) => request.method === "Runtime.evaluate"),
+ false,
+ );
+ const screenshot = sent.find(
+ (request) => request.method === "Page.captureScreenshot",
+ );
assert.deepEqual(screenshot.params, {
format: "png",
- captureBeyondViewport: false
+ captureBeyondViewport: false,
});
});
} finally {
diff --git a/package/ego-browser/src/driver/observe.ts b/package/ego-browser/src/driver/observe.ts
index cdf76e2..bb52fe5 100644
--- a/package/ego-browser/src/driver/observe.ts
+++ b/package/ego-browser/src/driver/observe.ts
@@ -4,9 +4,20 @@ import { tmpdir } from "node:os";
import { state } from "../state.js";
import { cdp, js } from "../cdp-eval.js";
import { pageInfo } from "./nav.js";
-import { browserEgo, browserSnapshotRefsToRefMap, drainBrowserEvents, ensureSession, isBrowserRuntime, pendingDialog } from "../browser-runtime.js";
+import {
+ browserEgo,
+ browserSnapshotRefsToRefMap,
+ drainBrowserEvents,
+ ensureSession,
+ isBrowserRuntime,
+ pendingDialog,
+} from "../browser-runtime.js";
import { resolveElementCenter } from "../element-resolver.js";
-import { browserRefMap, ensureRefMapForRef, registerSnapshotForRefRefresh } from "../ref-state.js";
+import {
+ browserRefMap,
+ ensureRefMapForRef,
+ registerSnapshotForRefRefresh,
+} from "../ref-state.js";
type SnapshotOptions = {
scope?: "only_within_viewport" | "full_page";
@@ -51,14 +62,19 @@ export async function snapshotText(options: SnapshotOptions = {}) {
const result = await snapshot({
scope: options.scope ?? "full_page",
includeActionMarks: options.includeActionMarks ?? true,
- includeStableLocator: options.includeStableLocator ?? true
+ includeStableLocator: options.includeStableLocator ?? true,
});
return result.content || "";
}
export async function elementCenter(selectorOrRef) {
await ensureRefMapForRef(selectorOrRef);
- return resolveElementCenter({ sendRaw: cdp }, undefined, browserRefMap, selectorOrRef);
+ return resolveElementCenter(
+ { sendRaw: cdp },
+ undefined,
+ browserRefMap,
+ selectorOrRef,
+ );
}
// Sequence number for default screenshot file names. Combined with the pid it
@@ -66,12 +82,18 @@ export async function elementCenter(selectorOrRef) {
// other's shots in the shared tmpdir, and successive shots in one run distinct.
let screenshotSeq = 0;
-export async function captureScreenshot(path = join(tmpdir(), `ego-browser-shot-${process.pid}-${++screenshotSeq}.png`), options: CaptureScreenshotOptions = {}) {
+export async function captureScreenshot(
+ path = join(
+ tmpdir(),
+ `ego-browser-shot-${process.pid}-${++screenshotSeq}.png`,
+ ),
+ options: CaptureScreenshotOptions = {},
+) {
const full = options.full ?? false;
const raw = options.raw ?? false;
const params: any = {
format: "png",
- captureBeyondViewport: full
+ captureBeyondViewport: full,
};
if (raw) {
if (options.clip) {
@@ -96,7 +118,7 @@ export async function captureScreenshot(path = join(tmpdir(), `ego-browser-shot-
y: 0,
width: full ? info.pw : info.w,
height: full ? info.ph : info.h,
- scale: cssScale
+ scale: cssScale,
};
}
}
diff --git a/package/ego-browser/src/driver/pointer.test.mjs b/package/ego-browser/src/driver/pointer.test.mjs
index ee6ba82..1a4839d 100644
--- a/package/ego-browser/src/driver/pointer.test.mjs
+++ b/package/ego-browser/src/driver/pointer.test.mjs
@@ -9,7 +9,10 @@ test("click resolves selector offsets without the public elementEval helper", as
const restore = setOverrides({
cdpOverride(method, params, sessionId) {
calls.push({ method, params, sessionId });
- if (method === "Runtime.evaluate" && params.objectGroup === "ego-browser") {
+ if (
+ method === "Runtime.evaluate" &&
+ params.objectGroup === "ego-browser"
+ ) {
return { result: { objectId: "object-1" } };
}
if (method === "Runtime.evaluate") {
@@ -19,7 +22,7 @@ test("click resolves selector offsets without the public elementEval helper", as
return { result: { value: { x: 100, y: 200 } } };
}
return {};
- }
+ },
});
try {
await click({ selector: "#target", x: 12, y: 8 });
@@ -27,21 +30,37 @@ test("click resolves selector offsets without the public elementEval helper", as
restore();
}
- const callFunction = calls.find((call) => call.method === "Runtime.callFunctionOn");
+ const callFunction = calls.find(
+ (call) => call.method === "Runtime.callFunctionOn",
+ );
assert.equal(callFunction.params.objectId, "object-1");
- assert.match(callFunction.params.functionDeclaration, /getBoundingClientRect/);
+ assert.match(
+ callFunction.params.functionDeclaration,
+ /getBoundingClientRect/,
+ );
- assert.ok(calls.some((call) => call.method === "Runtime.releaseObject" && call.params.objectId === "object-1"));
+ assert.ok(
+ calls.some(
+ (call) =>
+ call.method === "Runtime.releaseObject" &&
+ call.params.objectId === "object-1",
+ ),
+ );
- const mouseEvents = calls.filter((call) => call.method === "Input.dispatchMouseEvent");
- assert.deepEqual(mouseEvents.map((call) => ({
- type: call.params.type,
- x: call.params.x,
- y: call.params.y
- })), [
- { type: "mousePressed", x: 112, y: 208 },
- { type: "mouseReleased", x: 112, y: 208 }
- ]);
+ const mouseEvents = calls.filter(
+ (call) => call.method === "Input.dispatchMouseEvent",
+ );
+ assert.deepEqual(
+ mouseEvents.map((call) => ({
+ type: call.params.type,
+ x: call.params.x,
+ y: call.params.y,
+ })),
+ [
+ { type: "mousePressed", x: 112, y: 208 },
+ { type: "mouseReleased", x: 112, y: 208 },
+ ],
+ );
});
test("scroll defaults to scrolling down (positive deltaY, DOM wheel convention)", async () => {
@@ -54,7 +73,7 @@ test("scroll defaults to scrolling down (positive deltaY, DOM wheel convention)"
cdpOverride(method, params) {
calls.push({ method, params });
return {};
- }
+ },
});
try {
await scroll();
@@ -79,7 +98,7 @@ test("scroll falls back to DOM scrolling only when wheel dispatch is unsupported
return { result: { value: { x: 0, y: 450 } } };
}
return {};
- }
+ },
});
try {
const result = await scroll({ x: 50, y: 60, dx: 10, dy: 450 });
@@ -94,7 +113,7 @@ test("scroll falls back to DOM scrolling only when wheel dispatch is unsupported
x: 50,
y: 60,
deltaX: 10,
- deltaY: 450
+ deltaY: 450,
});
assert.equal(calls[1].method, "Runtime.evaluate");
assert.match(calls[1].params.expression, /window\.scrollBy/);
@@ -112,7 +131,7 @@ test("scroll propagates wheel dispatch timeouts instead of silently degrading",
throw new Error("CDP request timed out: Input.dispatchMouseEvent");
}
return {};
- }
+ },
});
try {
await assert.rejects(() => scroll({ dy: 450 }), /timed out/);
@@ -129,7 +148,7 @@ test("scroll propagates user-control errors from wheel dispatch", async () => {
throw new Error("user is controlling this task space");
}
return {};
- }
+ },
});
try {
await assert.rejects(() => scroll(), /user is controlling/);
diff --git a/package/ego-browser/src/driver/pointer.ts b/package/ego-browser/src/driver/pointer.ts
index c1f736d..a47a8b6 100644
--- a/package/ego-browser/src/driver/pointer.ts
+++ b/package/ego-browser/src/driver/pointer.ts
@@ -56,7 +56,10 @@ type ScrollUntilOptions = {
waitSeconds?: number;
stallLimit?: number;
};
-type ScrollUntilCondition = ((state: ScrollState) => boolean | Promise<boolean>) | string | null;
+type ScrollUntilCondition =
+ | ((state: ScrollState) => boolean | Promise<boolean>)
+ | string
+ | null;
type MouseEventOptions = Record<string, unknown>;
/**
@@ -83,8 +86,16 @@ export async function click(target: MouseTarget, options: ClickOptions = {}) {
const button = options.button || "left";
const clickCount = options.clickCount ?? options.clicks ?? 1;
maybeHighlight(point, options.label);
- await dispatchMouse(point, "mousePressed", { button, buttons: pressedButtons(button), clickCount });
- await dispatchMouse(point, "mouseReleased", { button, buttons: 0, clickCount });
+ await dispatchMouse(point, "mousePressed", {
+ button,
+ buttons: pressedButtons(button),
+ clickCount,
+ });
+ await dispatchMouse(point, "mouseReleased", {
+ button,
+ buttons: 0,
+ clickCount,
+ });
}
/**
@@ -93,7 +104,10 @@ export async function click(target: MouseTarget, options: ClickOptions = {}) {
* @param {{button?: "left"|"middle"|"right", label?: string}} [options]
* @returns {Promise<void>}
*/
-export async function doubleClick(target: MouseTarget, options: ClickOptions = {}) {
+export async function doubleClick(
+ target: MouseTarget,
+ options: ClickOptions = {},
+) {
await click(target, { ...options, clickCount: 2 });
}
@@ -106,12 +120,16 @@ export async function doubleClick(target: MouseTarget, options: ClickOptions = {
export async function hover(target: MouseTarget, options: HoverOptions = {}) {
const point = await resolveMouseTarget(target);
maybeHighlight(point, options.label);
- await cdp("Input.dispatchMouseEvent", {
- type: "mouseMoved",
- x: point.x,
- y: point.y,
- buttons: 0
- }, point.sessionId);
+ await cdp(
+ "Input.dispatchMouseEvent",
+ {
+ type: "mouseMoved",
+ x: point.x,
+ y: point.y,
+ buttons: 0,
+ },
+ point.sessionId,
+ );
}
/**
@@ -120,7 +138,10 @@ export async function hover(target: MouseTarget, options: HoverOptions = {}) {
* @param {{button?: "left"|"middle"|"right", delayMs?: number, label?: string}} [options]
* @returns {Promise<void>}
*/
-export async function dragMouse(points: MouseTarget[], options: DragMouseOptions = {}) {
+export async function dragMouse(
+ points: MouseTarget[],
+ options: DragMouseOptions = {},
+) {
if (!Array.isArray(points) || points.length < 2) {
throw new Error("dragMouse requires at least two points");
}
@@ -133,35 +154,47 @@ export async function dragMouse(points: MouseTarget[], options: DragMouseOptions
const first = resolved[0];
const last = resolved.at(-1);
maybeHighlight(first, options.label);
- await cdp("Input.dispatchMouseEvent", {
- type: "mousePressed",
- x: first.x,
- y: first.y,
- button,
- buttons,
- clickCount: 1
- }, first.sessionId);
+ await cdp(
+ "Input.dispatchMouseEvent",
+ {
+ type: "mousePressed",
+ x: first.x,
+ y: first.y,
+ button,
+ buttons,
+ clickCount: 1,
+ },
+ first.sessionId,
+ );
for (let i = 1; i < resolved.length; i += 1) {
const point = resolved[i];
- await cdp("Input.dispatchMouseEvent", {
- type: "mouseMoved",
- x: point.x,
- y: point.y,
- button,
- buttons
- }, point.sessionId ?? first.sessionId);
+ await cdp(
+ "Input.dispatchMouseEvent",
+ {
+ type: "mouseMoved",
+ x: point.x,
+ y: point.y,
+ button,
+ buttons,
+ },
+ point.sessionId ?? first.sessionId,
+ );
if (options.delayMs > 0 && i < resolved.length - 1) {
await new Promise((resolve) => setTimeout(resolve, options.delayMs));
}
}
- await cdp("Input.dispatchMouseEvent", {
- type: "mouseReleased",
- x: last.x,
- y: last.y,
- button,
- buttons: 0,
- clickCount: 1
- }, last.sessionId ?? first.sessionId);
+ await cdp(
+ "Input.dispatchMouseEvent",
+ {
+ type: "mouseReleased",
+ x: last.x,
+ y: last.y,
+ button,
+ buttons: 0,
+ clickCount: 1,
+ },
+ last.sessionId ?? first.sessionId,
+ );
}
/**
@@ -175,7 +208,11 @@ export async function dragMouse(points: MouseTarget[], options: DragMouseOptions
* @param {{dx?: number, dy?: number}} [options] Deltas in CSS pixels; positive dy scrolls down.
* @returns {Promise<void>}
*/
-export async function scroll(x: number | ScrollOptions = 0, y: number | ScrollOptions = 0, options: ScrollOptions = {}) {
+export async function scroll(
+ x: number | ScrollOptions = 0,
+ y: number | ScrollOptions = 0,
+ options: ScrollOptions = {},
+) {
if (x && typeof x === "object" && !Array.isArray(x)) {
options = x;
y = options.y ?? 0;
@@ -189,7 +226,7 @@ export async function scroll(x: number | ScrollOptions = 0, y: number | ScrollOp
x: Number(x) || 0,
y: Number(y) || 0,
deltaX: options.dx ?? 0,
- deltaY: options.dy ?? 300
+ deltaY: options.dy ?? 300,
};
try {
await browserCdp("Input.dispatchMouseEvent", params, undefined, 1000);
@@ -207,7 +244,7 @@ export async function scroll(x: number | ScrollOptions = 0, y: number | ScrollOp
const message = error instanceof Error ? error.message : String(error);
process.stderr.write(
`[ego-browser] scroll(): wheel dispatch unsupported on this target (${message}); ` +
- `falling back to DOM scrollBy(). Wheel-only behaviors (virtualized lists, inner scroll panes) may not trigger.\n`
+ `falling back to DOM scrollBy(). Wheel-only behaviors (virtualized lists, inner scroll panes) may not trigger.\n`,
);
}
return scrollBy({ dx: params.deltaX, dy: params.deltaY });
@@ -218,7 +255,9 @@ let hasWarnedAboutWheelFallback = false;
function isWheelDispatchUnsupported(error: unknown) {
const message = error instanceof Error ? error.message : String(error ?? "");
- return /not (?:supported|implemented)|wasn't found|isn't found|unknown (?:method|command)|method not found/i.test(message);
+ return /not (?:supported|implemented)|wasn't found|isn't found|unknown (?:method|command)|method not found/i.test(
+ message,
+ );
}
/**
@@ -228,7 +267,10 @@ function isWheelDispatchUnsupported(error: unknown) {
* @param {{dx?:number,dy?:number,left?:number,top?:number,behavior?: ScrollBehavior}} [options]
* @returns {Promise<{x:number,y:number}>} New window scroll position.
*/
-export async function scrollBy(amount: number | ScrollByOptions = 900, options: ScrollByOptions = {}) {
+export async function scrollBy(
+ amount: number | ScrollByOptions = 900,
+ options: ScrollByOptions = {},
+) {
const params = scrollByParams(amount, options);
return js(`(() => {
window.scrollBy({
@@ -246,10 +288,16 @@ export async function scrollBy(amount: number | ScrollByOptions = 900, options:
* @param {{step?:number,dy?:number,maxSteps?:number,wait?:number,waitSeconds?:number,stallLimit?:number}} [options]
* @returns {Promise<{done:boolean,reason:string,steps:number,state:object}>}
*/
-export async function scrollToBottomUntil(condition: ScrollUntilCondition = null, options: ScrollUntilOptions = {}) {
+export async function scrollToBottomUntil(
+ condition: ScrollUntilCondition = null,
+ options: ScrollUntilOptions = {},
+) {
const step = numberValue(options.step ?? options.dy ?? 900);
const maxSteps = Math.max(0, Math.floor(numberValue(options.maxSteps ?? 30)));
- const stallLimit = Math.max(1, Math.floor(numberValue(options.stallLimit ?? 2)));
+ const stallLimit = Math.max(
+ 1,
+ Math.floor(numberValue(options.stallLimit ?? 2)),
+ );
const waitSeconds = numberValue(options.waitSeconds ?? options.wait ?? 0.5);
let previousY = -1;
let stalls = 0;
@@ -289,13 +337,21 @@ function maybeHighlight(point: Point, label?: string) {
}
}
-async function dispatchMouse(point: Point, type: string, options: MouseEventOptions = {}) {
- await cdp("Input.dispatchMouseEvent", {
- type,
- x: point.x,
- y: point.y,
- ...options
- }, point.sessionId);
+async function dispatchMouse(
+ point: Point,
+ type: string,
+ options: MouseEventOptions = {},
+) {
+ await cdp(
+ "Input.dispatchMouseEvent",
+ {
+ type,
+ x: point.x,
+ y: point.y,
+ ...options,
+ },
+ point.sessionId,
+ );
}
async function resolveMouseTarget(target: MouseTarget): Promise<Point> {
@@ -306,15 +362,22 @@ async function resolveMouseTarget(target: MouseTarget): Promise<Point> {
return pointFrom(target);
}
if (target && typeof target === "object") {
- if ("selector" in target && typeof target.selector === "string" && target.selector) {
+ if (
+ "selector" in target &&
+ typeof target.selector === "string" &&
+ target.selector
+ ) {
if (target.x === undefined && target.y === undefined) {
return elementCenter(target.selector);
}
- const [topLeft, center] = await Promise.all([elementTopLeft(target.selector), elementCenter(target.selector)]);
+ const [topLeft, center] = await Promise.all([
+ elementTopLeft(target.selector),
+ elementCenter(target.selector),
+ ]);
return {
x: topLeft.x + numberValue(target.x),
y: topLeft.y + numberValue(target.y),
- sessionId: center.sessionId
+ sessionId: center.sessionId,
};
}
if (target.x !== undefined || target.y !== undefined) {
@@ -327,7 +390,7 @@ async function resolveMouseTarget(target: MouseTarget): Promise<Point> {
async function elementTopLeft(selectorOrRef: string): Promise<Point> {
const { result } = await resolveAndCall(
selectorOrRef,
- "function(){const rect=this.getBoundingClientRect();return {x:rect.left,y:rect.top};}"
+ "function(){const rect=this.getBoundingClientRect();return {x:rect.left,y:rect.top};}",
);
const value = result.result?.value;
if (typeof value?.x !== "number" || typeof value?.y !== "number") {
@@ -353,15 +416,22 @@ function numberValue(value: unknown) {
return out;
}
-function scrollByParams(amount: number | ScrollByOptions, options: ScrollByOptions) {
- const input = amount && typeof amount === "object" && !Array.isArray(amount) ? amount : options;
- const top = amount && typeof amount === "object" && !Array.isArray(amount)
- ? input.top ?? input.dy ?? 900
- : input.top ?? input.dy ?? amount;
+function scrollByParams(
+ amount: number | ScrollByOptions,
+ options: ScrollByOptions,
+) {
+ const input =
+ amount && typeof amount === "object" && !Array.isArray(amount)
+ ? amount
+ : options;
+ const top =
+ amount && typeof amount === "object" && !Array.isArray(amount)
+ ? (input.top ?? input.dy ?? 900)
+ : (input.top ?? input.dy ?? amount);
return {
left: numberValue(input.left ?? input.dx ?? 0),
top: numberValue(top),
- behavior: input.behavior === "smooth" ? "smooth" : "instant"
+ behavior: input.behavior === "smooth" ? "smooth" : "instant",
};
}
@@ -387,7 +457,10 @@ async function scrollState(): Promise<ScrollState> {
})()`);
}
-async function conditionMet(condition: ScrollUntilCondition, state: ScrollState) {
+async function conditionMet(
+ condition: ScrollUntilCondition,
+ state: ScrollState,
+) {
if (!condition) {
return false;
}
@@ -397,7 +470,9 @@ async function conditionMet(condition: ScrollUntilCondition, state: ScrollState)
if (typeof condition === "string") {
return Boolean(await js(`Boolean(${condition})`));
}
- throw new TypeError(`scrollToBottomUntil condition must be a function or string, got ${typeof condition}`);
+ throw new TypeError(
+ `scrollToBottomUntil condition must be a function or string, got ${typeof condition}`,
+ );
}
function pressedButtons(button: MouseButton) {
diff --git a/package/ego-browser/src/driver/waits.test.mjs b/package/ego-browser/src/driver/waits.test.mjs
index 124f151..1336309 100644
--- a/package/ego-browser/src/driver/waits.test.mjs
+++ b/package/ego-browser/src/driver/waits.test.mjs
@@ -18,7 +18,7 @@ test("waitForNetworkIdle enables the Network domain and disables it afterwards",
now: () => t,
sleep: async (ms) => {
t += ms;
- }
+ },
});
try {
const result = await waitForNetworkIdle({ timeout: 5 });
@@ -26,8 +26,16 @@ test("waitForNetworkIdle enables the Network domain and disables it afterwards",
} finally {
restore();
}
- assert.equal(methods[0], "Network.enable", "must enable Network before observing");
- assert.equal(methods.at(-1), "Network.disable", "must disable Network when done");
+ assert.equal(
+ methods[0],
+ "Network.enable",
+ "must enable Network before observing",
+ );
+ assert.equal(
+ methods.at(-1),
+ "Network.disable",
+ "must disable Network when done",
+ );
});
test("waitForNetworkIdle leaves a caller-enabled Network domain enabled", async () => {
@@ -41,7 +49,7 @@ test("waitForNetworkIdle leaves a caller-enabled Network domain enabled", async
now: () => t,
sleep: async (ms) => {
t += ms;
- }
+ },
});
try {
await cdp("Network.enable"); // the caller owns the domain
@@ -53,7 +61,7 @@ test("waitForNetworkIdle leaves a caller-enabled Network domain enabled", async
}
assert.ok(
!methods.includes("Network.disable"),
- "must not tear down a Network domain the caller enabled"
+ "must not tear down a Network domain the caller enabled",
);
});
@@ -69,7 +77,7 @@ test("waitForNetworkIdle survives a bridge that rejects Network.enable", async (
now: () => t,
sleep: async (ms) => {
t += ms;
- }
+ },
});
try {
const result = await waitForNetworkIdle({ timeout: 5 });
diff --git a/package/ego-browser/src/driver/waits.ts b/package/ego-browser/src/driver/waits.ts
index 0ac486d..878c6f7 100644
--- a/package/ego-browser/src/driver/waits.ts
+++ b/package/ego-browser/src/driver/waits.ts
@@ -39,11 +39,15 @@ export async function waitForLoad(options: WaitForLoadOptions = {}) {
* @param {{timeout?: number, visible?: boolean}} [options]
* @returns {Promise<boolean>} True when found before timeout.
*/
-export async function waitForElement(selector: string, options: WaitForElementOptions = {}) {
+export async function waitForElement(
+ selector: string,
+ options: WaitForElementOptions = {},
+) {
const timeout = options.timeout ?? 10.0;
const visible = options.visible ?? false;
const deadline = state.now() + timeout * 1000;
- const visibilityFn = "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";
+ const visibilityFn =
+ "function(){if(typeof this.checkVisibility==='function')return this.checkVisibility({checkOpacity:true,checkVisibilityCSS:true});const s=getComputedStyle(this);return s.display!=='none'&&s.visibility!=='hidden'&&s.opacity!=='0';}";
while (state.now() < deadline) {
let handle;
try {
@@ -57,12 +61,16 @@ export async function waitForElement(selector: string, options: WaitForElementOp
}
try {
if (!visible) return true;
- const response = await cdp("Runtime.callFunctionOn", {
- functionDeclaration: visibilityFn,
- objectId: handle.objectId,
- returnByValue: true,
- awaitPromise: false
- }, handle.sessionId);
+ const response = await cdp(
+ "Runtime.callFunctionOn",
+ {
+ functionDeclaration: visibilityFn,
+ objectId: handle.objectId,
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ handle.sessionId,
+ );
if (response.result?.value) return true;
} catch {
// visibility check failed (element raced away); treat as not-ready, keep polling.
@@ -85,7 +93,9 @@ export async function waitForElement(selector: string, options: WaitForElementOp
* @param {{timeout?: number, idleMs?: number}} [options]
* @returns {Promise<boolean>} True when idle before timeout.
*/
-export async function waitForNetworkIdle(options: WaitForNetworkIdleOptions = {}) {
+export async function waitForNetworkIdle(
+ options: WaitForNetworkIdleOptions = {},
+) {
const timeout = options.timeout ?? 10.0;
const idleMs = options.idleMs ?? 500;
const deadline = state.now() + timeout * 1000;
@@ -103,7 +113,10 @@ export async function waitForNetworkIdle(options: WaitForNetworkIdleOptions = {}
if (method === "Network.requestWillBeSent") {
inflight.add(params.requestId);
lastActivity = state.now();
- } else if (method === "Network.loadingFinished" || method === "Network.loadingFailed") {
+ } else if (
+ method === "Network.loadingFinished" ||
+ method === "Network.loadingFailed"
+ ) {
inflight.delete(params.requestId);
lastActivity = state.now();
} else if (method.startsWith("Network.")) {
diff --git a/package/ego-browser/src/ego-errors.ts b/package/ego-browser/src/ego-errors.ts
index f29bbd2..7bfa168 100644
--- a/package/ego-browser/src/ego-errors.ts
+++ b/package/ego-browser/src/ego-errors.ts
@@ -4,7 +4,12 @@
*/
export function assertNoEgoError(result, op: string) {
- if (result && typeof result === "object" && "error" in result && result.error != null) {
+ if (
+ result &&
+ typeof result === "object" &&
+ "error" in result &&
+ result.error != null
+ ) {
throw new Error(`${op}: ${formatEgoError(result.error)}`);
}
return result;
diff --git a/package/ego-browser/src/element-resolver.test.mjs b/package/ego-browser/src/element-resolver.test.mjs
index 6c0e124..885cf76 100644
--- a/package/ego-browser/src/element-resolver.test.mjs
+++ b/package/ego-browser/src/element-resolver.test.mjs
@@ -1,7 +1,10 @@
import test from "node:test";
import assert from "node:assert/strict";
-import { resolveElementCenter, ElementResolutionError } from "../dist/src/element-resolver.js";
+import {
+ resolveElementCenter,
+ ElementResolutionError,
+} from "../dist/src/element-resolver.js";
import { RefMap } from "../dist/src/ref-map.js";
class FakeCDP {
@@ -18,8 +21,8 @@ class FakeCDP {
const AX_TREE = {
nodes: [
- { role: { value: "button" }, name: { value: "ok" }, backendDOMNodeId: 100 }
- ]
+ { role: { value: "button" }, name: { value: "ok" }, backendDOMNodeId: 100 },
+ ],
};
test("resolveElementCenter computes the center from a valid box model", async () => {
@@ -57,11 +60,11 @@ test("degenerate box model throws transient instead of returning (0,0)", async (
assert.equal(error.kind, "transient");
assert.match(error.message, /no box model/);
return true;
- }
+ },
);
assert.ok(
!cdp.calls.some(([method]) => method === "Accessibility.getFullAXTree"),
- "must not fall back to role/name lookup — it could match a different node with the same label"
+ "must not fall back to role/name lookup — it could match a different node with the same label",
);
});
@@ -87,7 +90,7 @@ test("stale backend node still falls back to role/name lookup", async () => {
assert.equal(point.y, 5);
assert.ok(
cdp.calls.some(([method]) => method === "Accessibility.getFullAXTree"),
- "a stale node must trigger the role/name fallback"
+ "a stale node must trigger the role/name fallback",
);
});
@@ -102,11 +105,17 @@ test("role locator with degenerate box model throws transient", async () => {
return {};
});
await assert.rejects(
- () => resolveElementCenter(cdp, undefined, new RefMap(), 'loc=role:button[name="ok"]'),
+ () =>
+ resolveElementCenter(
+ cdp,
+ undefined,
+ new RefMap(),
+ 'loc=role:button[name="ok"]',
+ ),
(error) => {
assert.ok(error instanceof ElementResolutionError);
assert.equal(error.kind, "transient");
return true;
- }
+ },
);
});
diff --git a/package/ego-browser/src/element-resolver.ts b/package/ego-browser/src/element-resolver.ts
index 9df21c0..cfebdcc 100644
--- a/package/ego-browser/src/element-resolver.ts
+++ b/package/ego-browser/src/element-resolver.ts
@@ -20,18 +20,36 @@ function matchCountKind(message: string): "transient" | "permanent" {
return n > 1 ? "permanent" : "transient";
}
-export async function resolveElementCenter(cdp, sessionId, refMap, selectorOrRef, iframeSessions = new Map()) {
+export async function resolveElementCenter(
+ cdp,
+ sessionId,
+ refMap,
+ selectorOrRef,
+ iframeSessions = new Map(),
+) {
const refId = parseRef(selectorOrRef);
if (refId) {
const entry = refMap.get(refId);
if (!entry) {
throw new ElementResolutionError(`Unknown ref: ${refId}`, "transient");
}
- const effectiveSessionId = resolveFrameSession(entry.frameId, sessionId, iframeSessions);
+ const effectiveSessionId = resolveFrameSession(
+ entry.frameId,
+ sessionId,
+ iframeSessions,
+ );
if (entry.backendNodeId !== undefined && entry.backendNodeId !== null) {
try {
- const result = await send(cdp, "DOM.getBoxModel", { backendNodeId: entry.backendNodeId }, effectiveSessionId);
- return { ...boxModelCenter(result.model), sessionId: effectiveSessionId };
+ const result = await send(
+ cdp,
+ "DOM.getBoxModel",
+ { backendNodeId: entry.backendNodeId },
+ effectiveSessionId,
+ );
+ return {
+ ...boxModelCenter(result.model),
+ sessionId: effectiveSessionId,
+ };
} catch (error) {
if (error instanceof ElementResolutionError) {
// The node resolved but has no usable box model (not rendered yet).
@@ -42,8 +60,21 @@ export async function resolveElementCenter(cdp, sessionId, refMap, selectorOrRef
// The backend node can become stale after DOM updates; fall back to role/name lookup below.
}
}
- const backendNodeId = await findBackendNodeIdByRoleName(cdp, sessionId, entry.role, entry.name, entry.nth, entry.frameId, iframeSessions);
- const result = await send(cdp, "DOM.getBoxModel", { backendNodeId }, effectiveSessionId);
+ const backendNodeId = await findBackendNodeIdByRoleName(
+ cdp,
+ sessionId,
+ entry.role,
+ entry.name,
+ entry.nth,
+ entry.frameId,
+ iframeSessions,
+ );
+ const result = await send(
+ cdp,
+ "DOM.getBoxModel",
+ { backendNodeId },
+ effectiveSessionId,
+ );
return { ...boxModelCenter(result.model), sessionId: effectiveSessionId };
}
@@ -52,35 +83,61 @@ export async function resolveElementCenter(cdp, sessionId, refMap, selectorOrRef
return resolveLocatorCenter(cdp, sessionId, locator);
}
- const result = await send(cdp, "Runtime.evaluate", {
- expression: buildSelectorCenterJs(selectorOrRef),
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
+ const result = await send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression: buildSelectorCenterJs(selectorOrRef),
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
if (result.exceptionDetails) {
- throw new ElementResolutionError(`Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`, "permanent");
+ throw new ElementResolutionError(
+ `Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`,
+ "permanent",
+ );
}
const value = result.result?.value;
if (typeof value?.x !== "number" || typeof value?.y !== "number") {
- throw new ElementResolutionError(`Element not found: ${selectorOrRef}`, "transient");
+ throw new ElementResolutionError(
+ `Element not found: ${selectorOrRef}`,
+ "transient",
+ );
}
return { x: value.x, y: value.y, sessionId };
}
-export async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrRef, iframeSessions = new Map()) {
+export async function resolveElementObjectId(
+ cdp,
+ sessionId,
+ refMap,
+ selectorOrRef,
+ iframeSessions = new Map(),
+) {
const refId = parseRef(selectorOrRef);
if (refId) {
const entry = refMap.get(refId);
if (!entry) {
throw new ElementResolutionError(`Unknown ref: ${refId}`, "transient");
}
- const effectiveSessionId = resolveFrameSession(entry.frameId, sessionId, iframeSessions);
+ const effectiveSessionId = resolveFrameSession(
+ entry.frameId,
+ sessionId,
+ iframeSessions,
+ );
if (entry.backendNodeId !== undefined && entry.backendNodeId !== null) {
try {
- const result = await send(cdp, "DOM.resolveNode", {
- backendNodeId: entry.backendNodeId,
- objectGroup: "ego-browser"
- }, effectiveSessionId);
+ const result = await send(
+ cdp,
+ "DOM.resolveNode",
+ {
+ backendNodeId: entry.backendNodeId,
+ objectGroup: "ego-browser",
+ },
+ effectiveSessionId,
+ );
const objectId = result.object?.objectId;
if (objectId) {
return { objectId, sessionId: effectiveSessionId };
@@ -89,11 +146,27 @@ export async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrR
// The backend node can become stale after DOM updates; fall back to role/name lookup below.
}
}
- const backendNodeId = await findBackendNodeIdByRoleName(cdp, sessionId, entry.role, entry.name, entry.nth, entry.frameId, iframeSessions);
- const result = await send(cdp, "DOM.resolveNode", { backendNodeId, objectGroup: "ego-browser" }, effectiveSessionId);
+ const backendNodeId = await findBackendNodeIdByRoleName(
+ cdp,
+ sessionId,
+ entry.role,
+ entry.name,
+ entry.nth,
+ entry.frameId,
+ iframeSessions,
+ );
+ const result = await send(
+ cdp,
+ "DOM.resolveNode",
+ { backendNodeId, objectGroup: "ego-browser" },
+ effectiveSessionId,
+ );
const objectId = result.object?.objectId;
if (!objectId) {
- throw new ElementResolutionError(`No objectId for ref ${refId}`, "permanent");
+ throw new ElementResolutionError(
+ `No objectId for ref ${refId}`,
+ "permanent",
+ );
}
return { objectId, sessionId: effectiveSessionId };
}
@@ -103,18 +176,29 @@ export async function resolveElementObjectId(cdp, sessionId, refMap, selectorOrR
return resolveLocatorObjectId(cdp, sessionId, locator);
}
- const result = await send(cdp, "Runtime.evaluate", {
- expression: buildFindElementJs(selectorOrRef),
- returnByValue: false,
- awaitPromise: false,
- objectGroup: "ego-browser"
- }, sessionId);
+ const result = await send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression: buildFindElementJs(selectorOrRef),
+ returnByValue: false,
+ awaitPromise: false,
+ objectGroup: "ego-browser",
+ },
+ sessionId,
+ );
if (result.exceptionDetails) {
- throw new ElementResolutionError(`Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`, "permanent");
+ throw new ElementResolutionError(
+ `Invalid selector: ${selectorOrRef}: ${exceptionText(result)}`,
+ "permanent",
+ );
}
const objectId = result.result?.objectId;
if (!objectId) {
- throw new ElementResolutionError(`Element not found: ${selectorOrRef}`, "transient");
+ throw new ElementResolutionError(
+ `Element not found: ${selectorOrRef}`,
+ "transient",
+ );
}
return { objectId, sessionId };
}
@@ -131,91 +215,176 @@ function resolveFrameSession(frameId, sessionId, iframeSessions) {
async function resolveLocatorCenter(cdp, sessionId, locator) {
if (locator.kind === "role") {
- const backendNodeId = await findUniqueBackendNodeIdByRoleName(cdp, sessionId, locator.role, locator.name);
- const result = await send(cdp, "DOM.getBoxModel", { backendNodeId }, sessionId);
+ const backendNodeId = await findUniqueBackendNodeIdByRoleName(
+ cdp,
+ sessionId,
+ locator.role,
+ locator.name,
+ );
+ const result = await send(
+ cdp,
+ "DOM.getBoxModel",
+ { backendNodeId },
+ sessionId,
+ );
return { ...boxModelCenter(result.model), sessionId };
}
- const result = await send(cdp, "Runtime.evaluate", {
- expression: buildLocatorCenterJs(locator),
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
+ const result = await send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression: buildLocatorCenterJs(locator),
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
if (result.exceptionDetails) {
- throw new ElementResolutionError(`Invalid selector: ${locator.raw}: ${exceptionText(result)}`, "permanent");
+ throw new ElementResolutionError(
+ `Invalid selector: ${locator.raw}: ${exceptionText(result)}`,
+ "permanent",
+ );
}
const value = result.result?.value;
if (value?.error) {
throw new ElementResolutionError(value.error, matchCountKind(value.error));
}
if (typeof value?.x !== "number" || typeof value?.y !== "number") {
- throw new ElementResolutionError(`Element not found: ${locator.raw}`, "transient");
+ throw new ElementResolutionError(
+ `Element not found: ${locator.raw}`,
+ "transient",
+ );
}
return { x: value.x, y: value.y, sessionId };
}
async function resolveLocatorObjectId(cdp, sessionId, locator) {
if (locator.kind === "role") {
- const backendNodeId = await findUniqueBackendNodeIdByRoleName(cdp, sessionId, locator.role, locator.name);
- const result = await send(cdp, "DOM.resolveNode", { backendNodeId, objectGroup: "ego-browser" }, sessionId);
+ const backendNodeId = await findUniqueBackendNodeIdByRoleName(
+ cdp,
+ sessionId,
+ locator.role,
+ locator.name,
+ );
+ const result = await send(
+ cdp,
+ "DOM.resolveNode",
+ { backendNodeId, objectGroup: "ego-browser" },
+ sessionId,
+ );
const objectId = result.object?.objectId;
if (!objectId) {
- throw new ElementResolutionError(`No objectId for locator ${locator.raw}`, "permanent");
+ throw new ElementResolutionError(
+ `No objectId for locator ${locator.raw}`,
+ "permanent",
+ );
}
return { objectId, sessionId };
}
const count = await locatorCount(cdp, sessionId, locator);
if (count === 0) {
- throw new ElementResolutionError(`Locator ${locator.raw} matched 0 elements`, "transient");
+ throw new ElementResolutionError(
+ `Locator ${locator.raw} matched 0 elements`,
+ "transient",
+ );
}
if (count > 1) {
- throw new ElementResolutionError(`Locator ${locator.raw} matched ${count} elements`, "permanent");
- }
- const result = await send(cdp, "Runtime.evaluate", {
- expression: buildLocatorFindJs(locator),
- returnByValue: false,
- awaitPromise: false,
- objectGroup: "ego-browser"
- }, sessionId);
+ throw new ElementResolutionError(
+ `Locator ${locator.raw} matched ${count} elements`,
+ "permanent",
+ );
+ }
+ const result = await send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression: buildLocatorFindJs(locator),
+ returnByValue: false,
+ awaitPromise: false,
+ objectGroup: "ego-browser",
+ },
+ sessionId,
+ );
const objectId = result.result?.objectId;
if (!objectId) {
- throw new ElementResolutionError(`Element not found: ${locator.raw}`, "transient");
+ throw new ElementResolutionError(
+ `Element not found: ${locator.raw}`,
+ "transient",
+ );
}
return { objectId, sessionId };
}
async function locatorCount(cdp, sessionId, locator) {
- const result = await send(cdp, "Runtime.evaluate", {
- expression: buildLocatorCountJs(locator),
- returnByValue: true,
- awaitPromise: false
- }, sessionId);
+ const result = await send(
+ cdp,
+ "Runtime.evaluate",
+ {
+ expression: buildLocatorCountJs(locator),
+ returnByValue: true,
+ awaitPromise: false,
+ },
+ sessionId,
+ );
if (result.exceptionDetails) {
- throw new ElementResolutionError(`Invalid selector: ${locator.raw}: ${exceptionText(result)}`, "permanent");
+ throw new ElementResolutionError(
+ `Invalid selector: ${locator.raw}: ${exceptionText(result)}`,
+ "permanent",
+ );
}
return Number(result.result?.value || 0);
}
-async function findBackendNodeIdByRoleName(cdp, sessionId, role, name, nth = undefined, frameId = undefined, iframeSessions = new Map()) {
- const [params, effectiveSessionId] = resolveAxSession(frameId, sessionId, iframeSessions);
- const result = await send(cdp, "Accessibility.getFullAXTree", params, effectiveSessionId);
+async function findBackendNodeIdByRoleName(
+ cdp,
+ sessionId,
+ role,
+ name,
+ nth = undefined,
+ frameId = undefined,
+ iframeSessions = new Map(),
+) {
+ const [params, effectiveSessionId] = resolveAxSession(
+ frameId,
+ sessionId,
+ iframeSessions,
+ );
+ const result = await send(
+ cdp,
+ "Accessibility.getFullAXTree",
+ params,
+ effectiveSessionId,
+ );
const nthIndex = nth ?? 0;
let matchCount = 0;
for (const node of result.nodes || []) {
if (node.ignored) {
continue;
}
- if (extractAxString(node.role) !== role || extractAxString(node.name) !== name) {
+ if (
+ extractAxString(node.role) !== role ||
+ extractAxString(node.name) !== name
+ ) {
continue;
}
if (matchCount === nthIndex) {
- if (node.backendDOMNodeId === undefined || node.backendDOMNodeId === null) {
- throw new ElementResolutionError(`AX node has no backendDOMNodeId for role=${role} name=${name}`, "permanent");
+ if (
+ node.backendDOMNodeId === undefined ||
+ node.backendDOMNodeId === null
+ ) {
+ throw new ElementResolutionError(
+ `AX node has no backendDOMNodeId for role=${role} name=${name}`,
+ "permanent",
+ );
}
return node.backendDOMNodeId;
}
matchCount += 1;
}
- throw new ElementResolutionError(`Could not locate element with role=${role} name=${name}`, "transient");
+ throw new ElementResolutionError(
+ `Could not locate element with role=${role} name=${name}`,
+ "transient",
+ );
}
async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {
@@ -225,19 +394,31 @@ async function findUniqueBackendNodeIdByRoleName(cdp, sessionId, role, name) {
if (node.ignored) {
continue;
}
- if (extractAxString(node.role) === role && extractAxString(node.name) === name) {
+ if (
+ extractAxString(node.role) === role &&
+ extractAxString(node.name) === name
+ ) {
matches.push(node);
}
}
if (matches.length === 0) {
- throw new ElementResolutionError(`Locator role:${role}[name=${JSON.stringify(name)}] matched 0 elements`, "transient");
+ throw new ElementResolutionError(
+ `Locator role:${role}[name=${JSON.stringify(name)}] matched 0 elements`,
+ "transient",
+ );
}
if (matches.length > 1) {
- throw new ElementResolutionError(`Locator role:${role}[name=${JSON.stringify(name)}] matched ${matches.length} elements`, "permanent");
+ throw new ElementResolutionError(
+ `Locator role:${role}[name=${JSON.stringify(name)}] matched ${matches.length} elements`,
+ "permanent",
+ );
}
const backendNodeId = matches[0].backendDOMNodeId;
if (backendNodeId === undefined || backendNodeId === null) {
- throw new ElementResolutionError(`AX node has no backendDOMNodeId for role=${role} name=${name}`, "permanent");
+ throw new ElementResolutionError(
+ `AX node has no backendDOMNodeId for role=${role} name=${name}`,
+ "permanent",
+ );
}
return backendNodeId;
}
@@ -246,7 +427,10 @@ function resolveAxSession(frameId, sessionId, iframeSessions) {
if (!frameId) {
return [{}, sessionId];
}
- const iframeSession = iframeSessions instanceof Map ? iframeSessions.get(frameId) : iframeSessions?.[frameId];
+ const iframeSession =
+ iframeSessions instanceof Map
+ ? iframeSessions.get(frameId)
+ : iframeSessions?.[frameId];
if (iframeSession) {
return [{}, iframeSession];
}
@@ -326,7 +510,7 @@ function parseLocator(input) {
kind: "role",
role: roleMatch[1],
name: parseLocatorName(roleMatch[2]),
- raw: value
+ raw: value,
};
}
return null;
@@ -334,7 +518,7 @@ function parseLocator(input) {
function parseLocatorName(raw) {
const trimmed = raw.trim();
- if (trimmed.startsWith("\"") && trimmed.endsWith("\"")) {
+ if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
try {
return JSON.parse(trimmed);
} catch {
@@ -353,11 +537,14 @@ function boxModelCenter(model: any = {}) {
// Returning a fake (0,0) here would silently click the viewport corner.
// Treat a missing/degenerate box model as "element not ready" so callers
// with retry semantics (waitForElement, ref fallback) can poll.
- throw new ElementResolutionError("Element has no box model (not rendered or zero-sized)", "transient");
+ throw new ElementResolutionError(
+ "Element has no box model (not rendered or zero-sized)",
+ "transient",
+ );
}
return {
x: (content[0] + content[2] + content[4] + content[6]) / 4,
- y: (content[1] + content[3] + content[5] + content[7]) / 4
+ y: (content[1] + content[3] + content[5] + content[7]) / 4,
};
}
diff --git a/package/ego-browser/src/helpers.test.mjs b/package/ego-browser/src/helpers.test.mjs
index c2e56bb..5187d7b 100644
--- a/package/ego-browser/src/helpers.test.mjs
+++ b/package/ego-browser/src/helpers.test.mjs
@@ -9,7 +9,7 @@ import {
helperContext,
listTaskSpaces,
useOrCreateTaskSpace,
- switchTaskSpace
+ switchTaskSpace,
} from "../dist/src/helpers.js";
function withEgo(ego, fn) {
@@ -27,59 +27,68 @@ function withEgo(ego, fn) {
}
test("listTaskSpaces normalizes the current taskSpaces binding shape", async () => {
- await withEgo({
- async listTaskSpaces() {
- return {
- taskSpaces: [
- {
- taskId: "checkout-flow",
- id: 7,
- name: "Checkout flow",
- createdBy: "agent",
- ownership: "agent",
- recentTabTitles: ["Checkout", "Cart"]
- }
- ]
- };
- }
- }, async () => {
- assert.deepEqual(await listTaskSpaces(), [
- {
- taskId: "checkout-flow",
- id: 7,
- name: "Checkout flow",
- createdBy: "agent",
- ownership: "agent",
- recentTabTitles: ["Checkout", "Cart"]
- }
- ]);
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "Checkout flow",
+ createdBy: "agent",
+ ownership: "agent",
+ recentTabTitles: ["Checkout", "Cart"],
+ },
+ ],
+ };
+ },
+ },
+ async () => {
+ assert.deepEqual(await listTaskSpaces(), [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "Checkout flow",
+ createdBy: "agent",
+ ownership: "agent",
+ recentTabTitles: ["Checkout", "Cart"],
+ },
+ ]);
+ },
+ );
});
test("listTaskSpaces rejects legacy taskIds results", async () => {
- await withEgo({
- async listTaskSpaces() {
- return { taskIds: ["checkout-flow", "research-session"] };
- }
- }, async () => {
- await assert.rejects(
- () => listTaskSpaces(),
- /listTaskSpaces expected \{ taskSpaces: \[\.\.\.\] \}/
- );
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return { taskIds: ["checkout-flow", "research-session"] };
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => listTaskSpaces(),
+ /listTaskSpaces expected \{ taskSpaces: \[\.\.\.\] \}/,
+ );
+ },
+ );
});
test("listTaskSpaces throws on binding error objects", async () => {
- await withEgo({
- async listTaskSpaces() {
- return { error: "The task is under user control" };
- }
- }, async () => {
- await assert.rejects(
- () => listTaskSpaces(),
- /listTaskSpaces: The task is under user control/
- );
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return { error: "The task is under user control" };
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => listTaskSpaces(),
+ /listTaskSpaces: The task is under user control/,
+ );
+ },
+ );
});
test("taskspace helper surface exposes public helpers without claimTaskSpace", () => {
@@ -101,467 +110,586 @@ test("taskspace helper surface exposes public helpers without claimTaskSpace", (
test("switchTaskSpace selects a matching task space", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "Checkout flow", ownership: "agent" }
- ]
- };
- },
- useTaskSpace(taskId) {
- calls.push(["useTaskSpace", taskId]);
- return taskId;
- }
- }, async () => {
- assert.deepEqual(await switchTaskSpace(7), {
- taskId: "checkout-flow",
- id: 7,
- name: "Checkout flow",
- ownership: "agent"
- });
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "Checkout flow",
+ ownership: "agent",
+ },
+ ],
+ };
+ },
+ useTaskSpace(taskId) {
+ calls.push(["useTaskSpace", taskId]);
+ return taskId;
+ },
+ },
+ async () => {
+ assert.deepEqual(await switchTaskSpace(7), {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "Checkout flow",
+ ownership: "agent",
+ });
+ },
+ );
assert.deepEqual(calls, [["useTaskSpace", 7]]);
});
test("switchTaskSpace rejects non-agent-owned task spaces", async () => {
- await withEgo({
- async listTaskSpaces() {
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "user" }
- ]
- };
- },
- useTaskSpace() {}
- }, async () => {
- await assert.rejects(
- () => switchTaskSpace("checkout-flow"),
- /switchTaskSpace requires an agent-owned task space/
- );
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "user",
+ },
+ ],
+ };
+ },
+ useTaskSpace() {},
+ },
+ async () => {
+ await assert.rejects(
+ () => switchTaskSpace("checkout-flow"),
+ /switchTaskSpace requires an agent-owned task space/,
+ );
+ },
+ );
});
test("switchTaskSpace awaits useTaskSpace binding errors", async () => {
- await withEgo({
- async listTaskSpaces() {
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "agent" }
- ]
- };
- },
- async useTaskSpace() {
- return { error: "Task space not selected" };
- }
- }, async () => {
- await assert.rejects(
- () => switchTaskSpace("checkout-flow"),
- /switchTaskSpace: Task space not selected/
- );
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ },
+ ],
+ };
+ },
+ async useTaskSpace() {
+ return { error: "Task space not selected" };
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => switchTaskSpace("checkout-flow"),
+ /switchTaskSpace: Task space not selected/,
+ );
+ },
+ );
});
test("newTaskSpace creates and selects an agent task space", async () => {
const calls = [];
- await withEgo({
- async createTaskSpace(name) {
- calls.push(["createTaskSpace", name]);
- return { taskId: name, id: 7, name, ownership: "agent" };
- },
- useTaskSpace(taskId) {
- calls.push(["useTaskSpace", taskId]);
- return taskId;
- }
- }, async () => {
- assert.deepEqual(await newTaskSpace("checkout-flow"), {
- taskId: "checkout-flow",
- id: 7,
- name: "checkout-flow",
- ownership: "agent"
- });
- });
+ await withEgo(
+ {
+ async createTaskSpace(name) {
+ calls.push(["createTaskSpace", name]);
+ return { taskId: name, id: 7, name, ownership: "agent" };
+ },
+ useTaskSpace(taskId) {
+ calls.push(["useTaskSpace", taskId]);
+ return taskId;
+ },
+ },
+ async () => {
+ assert.deepEqual(await newTaskSpace("checkout-flow"), {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ });
+ },
+ );
assert.deepEqual(calls, [
["createTaskSpace", "checkout-flow"],
- ["useTaskSpace", 7]
+ ["useTaskSpace", 7],
]);
});
test("newTaskSpace rejects results without a numeric id", async () => {
const calls = [];
- await withEgo({
- async createTaskSpace(name) {
- calls.push(["createTaskSpace", name]);
- return { taskId: name, id: name, name };
- },
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "agent" }
- ]
- };
- },
- useTaskSpace(id) {
- calls.push(["useTaskSpace", id]);
- }
- }, async () => {
- await assert.rejects(
- () => newTaskSpace("checkout-flow"),
- /newTaskSpace requires a numeric task space id/
- );
- });
+ await withEgo(
+ {
+ async createTaskSpace(name) {
+ calls.push(["createTaskSpace", name]);
+ return { taskId: name, id: name, name };
+ },
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ },
+ ],
+ };
+ },
+ useTaskSpace(id) {
+ calls.push(["useTaskSpace", id]);
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => newTaskSpace("checkout-flow"),
+ /newTaskSpace requires a numeric task space id/,
+ );
+ },
+ );
assert.deepEqual(calls, [["createTaskSpace", "checkout-flow"]]);
});
test("newTaskSpace throws on binding error objects", async () => {
- await withEgo({
- async createTaskSpace() {
- return { error: "Task space already exists: checkout-flow" };
- },
- useTaskSpace() {}
- }, async () => {
- await assert.rejects(
- () => newTaskSpace("checkout-flow"),
- /newTaskSpace: Task space already exists: checkout-flow/
- );
- });
+ await withEgo(
+ {
+ async createTaskSpace() {
+ return { error: "Task space already exists: checkout-flow" };
+ },
+ useTaskSpace() {},
+ },
+ async () => {
+ await assert.rejects(
+ () => newTaskSpace("checkout-flow"),
+ /newTaskSpace: Task space already exists: checkout-flow/,
+ );
+ },
+ );
});
test("useOrCreateTaskSpace reuses existing agent-owned spaces", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "agent" }
- ]
- };
- },
- useTaskSpace(taskId) {
- calls.push(["useTaskSpace", taskId]);
- return taskId;
- },
- async createTaskSpace(name) {
- calls.push(["createTaskSpace", name]);
- return { taskId: name, id: 8, name, ownership: "agent" };
- },
- async claimTaskSpace(id, name) {
- calls.push(["claimTaskSpace", id, name]);
- return { taskId: name, id, name, ownership: "agent" };
- }
- }, async () => {
- assert.deepEqual(await useOrCreateTaskSpace("checkout-flow"), {
- taskId: "checkout-flow",
- id: 7,
- name: "checkout-flow",
- ownership: "agent"
- });
- });
- assert.deepEqual(calls, [
- ["listTaskSpaces"],
- ["useTaskSpace", 7]
- ]);
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ },
+ ],
+ };
+ },
+ useTaskSpace(taskId) {
+ calls.push(["useTaskSpace", taskId]);
+ return taskId;
+ },
+ async createTaskSpace(name) {
+ calls.push(["createTaskSpace", name]);
+ return { taskId: name, id: 8, name, ownership: "agent" };
+ },
+ async claimTaskSpace(id, name) {
+ calls.push(["claimTaskSpace", id, name]);
+ return { taskId: name, id, name, ownership: "agent" };
+ },
+ },
+ async () => {
+ assert.deepEqual(await useOrCreateTaskSpace("checkout-flow"), {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ });
+ },
+ );
+ assert.deepEqual(calls, [["listTaskSpaces"], ["useTaskSpace", 7]]);
});
test("useOrCreateTaskSpace claims existing user-owned spaces", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "user" }
- ]
- };
- },
- async claimTaskSpace(id, name) {
- calls.push(["claimTaskSpace", id, name]);
- return { taskId: name, id, name, ownership: "agent" };
- },
- useTaskSpace(taskId) {
- calls.push(["useTaskSpace", taskId]);
- return taskId;
- }
- }, async () => {
- assert.deepEqual(await useOrCreateTaskSpace("checkout-flow"), {
- taskId: "checkout-flow",
- id: 7,
- name: "checkout-flow",
- ownership: "agent"
- });
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "user",
+ },
+ ],
+ };
+ },
+ async claimTaskSpace(id, name) {
+ calls.push(["claimTaskSpace", id, name]);
+ return { taskId: name, id, name, ownership: "agent" };
+ },
+ useTaskSpace(taskId) {
+ calls.push(["useTaskSpace", taskId]);
+ return taskId;
+ },
+ },
+ async () => {
+ assert.deepEqual(await useOrCreateTaskSpace("checkout-flow"), {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ });
+ },
+ );
assert.deepEqual(calls, [
["listTaskSpaces"],
["claimTaskSpace", 7, "checkout-flow"],
- ["useTaskSpace", 7]
+ ["useTaskSpace", 7],
]);
});
test("useOrCreateTaskSpace creates missing spaces", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return { taskSpaces: [] };
- },
- async createTaskSpace(name) {
- calls.push(["createTaskSpace", name]);
- return { taskId: name, id: 7, name, ownership: "agent" };
- },
- useTaskSpace(taskId) {
- calls.push(["useTaskSpace", taskId]);
- return taskId;
- }
- }, async () => {
- assert.deepEqual(await useOrCreateTaskSpace("checkout-flow"), {
- taskId: "checkout-flow",
- id: 7,
- name: "checkout-flow",
- ownership: "agent"
- });
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return { taskSpaces: [] };
+ },
+ async createTaskSpace(name) {
+ calls.push(["createTaskSpace", name]);
+ return { taskId: name, id: 7, name, ownership: "agent" };
+ },
+ useTaskSpace(taskId) {
+ calls.push(["useTaskSpace", taskId]);
+ return taskId;
+ },
+ },
+ async () => {
+ assert.deepEqual(await useOrCreateTaskSpace("checkout-flow"), {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ });
+ },
+ );
assert.deepEqual(calls, [
["listTaskSpaces"],
["createTaskSpace", "checkout-flow"],
- ["useTaskSpace", 7]
+ ["useTaskSpace", 7],
]);
});
test("useOrCreateTaskSpace resolves string names before numeric id strings", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "plain-seven", id: 7, name: "plain-seven", ownership: "agent" },
- { taskId: "7", id: 8, name: "7", ownership: "agent" }
- ]
- };
- },
- useTaskSpace(id) {
- calls.push(["useTaskSpace", id]);
- return id;
- }
- }, async () => {
- assert.deepEqual(await useOrCreateTaskSpace("7"), {
- taskId: "7",
- id: 8,
- name: "7",
- ownership: "agent"
- });
- });
- assert.deepEqual(calls, [
- ["listTaskSpaces"],
- ["useTaskSpace", 8]
- ]);
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "plain-seven",
+ id: 7,
+ name: "plain-seven",
+ ownership: "agent",
+ },
+ { taskId: "7", id: 8, name: "7", ownership: "agent" },
+ ],
+ };
+ },
+ useTaskSpace(id) {
+ calls.push(["useTaskSpace", id]);
+ return id;
+ },
+ },
+ async () => {
+ assert.deepEqual(await useOrCreateTaskSpace("7"), {
+ taskId: "7",
+ id: 8,
+ name: "7",
+ ownership: "agent",
+ });
+ },
+ );
+ assert.deepEqual(calls, [["listTaskSpaces"], ["useTaskSpace", 8]]);
});
test("useOrCreateTaskSpace rejects missing numeric ids instead of creating", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return { taskSpaces: [] };
- },
- async createTaskSpace(name) {
- calls.push(["createTaskSpace", name]);
- return { taskId: String(name), id: 7, name: String(name), ownership: "agent" };
- }
- }, async () => {
- await assert.rejects(
- () => useOrCreateTaskSpace(7),
- /task space not found: 7/
- );
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return { taskSpaces: [] };
+ },
+ async createTaskSpace(name) {
+ calls.push(["createTaskSpace", name]);
+ return {
+ taskId: String(name),
+ id: 7,
+ name: String(name),
+ ownership: "agent",
+ };
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => useOrCreateTaskSpace(7),
+ /task space not found: 7/,
+ );
+ },
+ );
assert.deepEqual(calls, [["listTaskSpaces"]]);
});
test("completeTaskSpace selects by numeric id before completing", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "agent" }
- ]
- };
- },
- useTaskSpace(id) {
- calls.push(["useTaskSpace", id]);
- return id;
- },
- async completeTaskSpace() {
- calls.push(["completeTaskSpace"]);
- return "7 task space completed.";
- }
- }, async () => {
- await completeTaskSpace("checkout-flow", { keep: true });
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ },
+ ],
+ };
+ },
+ useTaskSpace(id) {
+ calls.push(["useTaskSpace", id]);
+ return id;
+ },
+ async completeTaskSpace() {
+ calls.push(["completeTaskSpace"]);
+ return "7 task space completed.";
+ },
+ },
+ async () => {
+ await completeTaskSpace("checkout-flow", { keep: true });
+ },
+ );
assert.deepEqual(calls, [
["listTaskSpaces"],
["useTaskSpace", 7],
- ["completeTaskSpace"]
+ ["completeTaskSpace"],
]);
});
test("completeTaskSpace waits for async useTaskSpace before completing", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "agent" }
- ]
- };
- },
- async useTaskSpace(id) {
- calls.push(["useTaskSpace:start", id]);
- await new Promise((resolve) => setTimeout(resolve, 0));
- calls.push(["useTaskSpace:end", id]);
- },
- async completeTaskSpace() {
- calls.push(["completeTaskSpace"]);
- return "7 task space completed.";
- }
- }, async () => {
- await completeTaskSpace("checkout-flow", { keep: true });
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ },
+ ],
+ };
+ },
+ async useTaskSpace(id) {
+ calls.push(["useTaskSpace:start", id]);
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ calls.push(["useTaskSpace:end", id]);
+ },
+ async completeTaskSpace() {
+ calls.push(["completeTaskSpace"]);
+ return "7 task space completed.";
+ },
+ },
+ async () => {
+ await completeTaskSpace("checkout-flow", { keep: true });
+ },
+ );
assert.deepEqual(calls, [
["listTaskSpaces"],
["useTaskSpace:start", 7],
["useTaskSpace:end", 7],
- ["completeTaskSpace"]
+ ["completeTaskSpace"],
]);
});
test("completeTaskSpace claims user-owned spaces before closing", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "user" }
- ]
- };
- },
- async claimTaskSpace(id, name) {
- calls.push(["claimTaskSpace", id, name]);
- return { taskId: name, id, name, ownership: "agent" };
- },
- async useTaskSpace(id) {
- calls.push(["useTaskSpace", id]);
- return id;
- },
- async closeTaskSpace() {
- calls.push(["closeTaskSpace"]);
- return "7 task space closed.";
- }
- }, async () => {
- const result = await completeTaskSpace("checkout-flow", { keep: false });
- assert.deepEqual(result, { done: true });
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "user",
+ },
+ ],
+ };
+ },
+ async claimTaskSpace(id, name) {
+ calls.push(["claimTaskSpace", id, name]);
+ return { taskId: name, id, name, ownership: "agent" };
+ },
+ async useTaskSpace(id) {
+ calls.push(["useTaskSpace", id]);
+ return id;
+ },
+ async closeTaskSpace() {
+ calls.push(["closeTaskSpace"]);
+ return "7 task space closed.";
+ },
+ },
+ async () => {
+ const result = await completeTaskSpace("checkout-flow", { keep: false });
+ assert.deepEqual(result, { done: true });
+ },
+ );
assert.deepEqual(calls, [
["listTaskSpaces"],
["claimTaskSpace", 7, "checkout-flow"],
["useTaskSpace", 7],
- ["closeTaskSpace"]
+ ["closeTaskSpace"],
]);
});
test("completeTaskSpace keep true skips user-owned spaces and reports it", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "user" }
- ]
- };
- },
- async completeTaskSpace() {
- calls.push(["completeTaskSpace"]);
- }
- }, async () => {
- const result = await completeTaskSpace("checkout-flow", { keep: true });
- assert.deepEqual(result, { done: false, skipped: "user-owned" });
- });
- assert.deepEqual(calls, [
- ["listTaskSpaces"]
- ]);
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "user",
+ },
+ ],
+ };
+ },
+ async completeTaskSpace() {
+ calls.push(["completeTaskSpace"]);
+ },
+ },
+ async () => {
+ const result = await completeTaskSpace("checkout-flow", { keep: true });
+ assert.deepEqual(result, { done: false, skipped: "user-owned" });
+ },
+ );
+ assert.deepEqual(calls, [["listTaskSpaces"]]);
});
test("handOffTaskSpace skips user-owned spaces and reports it", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "user" }
- ]
- };
- },
- async handOffTaskSpace() {
- calls.push(["handOffTaskSpace"]);
- }
- }, async () => {
- const result = await handOffTaskSpace("checkout-flow");
- assert.deepEqual(result, { done: false, skipped: "user-owned" });
- });
- assert.deepEqual(calls, [
- ["listTaskSpaces"]
- ]);
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "user",
+ },
+ ],
+ };
+ },
+ async handOffTaskSpace() {
+ calls.push(["handOffTaskSpace"]);
+ },
+ },
+ async () => {
+ const result = await handOffTaskSpace("checkout-flow");
+ assert.deepEqual(result, { done: false, skipped: "user-owned" });
+ },
+ );
+ assert.deepEqual(calls, [["listTaskSpaces"]]);
});
test("handOffTaskSpace reports done for agent-owned spaces", async () => {
const calls = [];
- await withEgo({
- async listTaskSpaces() {
- calls.push(["listTaskSpaces"]);
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "agent" }
- ]
- };
- },
- async useTaskSpace(id) {
- calls.push(["useTaskSpace", id]);
- return id;
- },
- async handOffTaskSpace() {
- calls.push(["handOffTaskSpace"]);
- }
- }, async () => {
- const result = await handOffTaskSpace("checkout-flow");
- assert.deepEqual(result, { done: true });
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ calls.push(["listTaskSpaces"]);
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ },
+ ],
+ };
+ },
+ async useTaskSpace(id) {
+ calls.push(["useTaskSpace", id]);
+ return id;
+ },
+ async handOffTaskSpace() {
+ calls.push(["handOffTaskSpace"]);
+ },
+ },
+ async () => {
+ const result = await handOffTaskSpace("checkout-flow");
+ assert.deepEqual(result, { done: true });
+ },
+ );
assert.deepEqual(calls, [
["listTaskSpaces"],
["useTaskSpace", 7],
- ["handOffTaskSpace"]
+ ["handOffTaskSpace"],
]);
});
test("useOrCreateTaskSpace rejects unknown ownership", async () => {
- await withEgo({
- async listTaskSpaces() {
- return {
- taskSpaces: [
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "shared" }
- ]
- };
- }
- }, async () => {
- await assert.rejects(
- () => useOrCreateTaskSpace("checkout-flow"),
- /ownership "shared"/
- );
- });
+ await withEgo(
+ {
+ async listTaskSpaces() {
+ return {
+ taskSpaces: [
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "shared",
+ },
+ ],
+ };
+ },
+ },
+ async () => {
+ await assert.rejects(
+ () => useOrCreateTaskSpace("checkout-flow"),
+ /ownership "shared"/,
+ );
+ },
+ );
});
diff --git a/package/ego-browser/src/index.ts b/package/ego-browser/src/index.ts
index e296679..73319ce 100644
--- a/package/ego-browser/src/index.ts
+++ b/package/ego-browser/src/index.ts
@@ -2,7 +2,11 @@
import { pathToFileURL } from "node:url";
import * as helpers from "./helpers.js";
-import { clearPreferredTarget, invalidateSession, setPreferredTarget } from "./browser-runtime.js";
+import {
+ clearPreferredTarget,
+ invalidateSession,
+ setPreferredTarget,
+} from "./browser-runtime.js";
import { formatCliLogValue } from "./format.js";
import { runMain } from "./run.js";
@@ -28,7 +32,10 @@ const SYNC_HELPERS = new Set(["help"]);
// second installEgoSdk call cannot double-wrap createTab / task-space methods.
const EGO_WRAPPED = Symbol.for("egoBrowser.sdkWrapped");
-export function installEgoSdk(target: InstallTarget = globalThis, options: InstallEgoSdkOptions = {}) {
+export function installEgoSdk(
+ target: InstallTarget = globalThis,
+ options: InstallEgoSdkOptions = {},
+) {
if (!target || typeof target !== "object") {
return target;
}
@@ -43,26 +50,46 @@ export function installEgoSdk(target: InstallTarget = globalThis, options: Insta
if (typeof value !== "function") {
continue;
}
- const exposed = SYNC_HELPERS.has(name) ? value : async (...args: unknown[]) => {
- await readySignal;
- if (readyError) {
- throw readyError;
- }
- return value(...args);
- };
- Object.defineProperty(target, name, { value: exposed, writable: true, configurable: true, enumerable: false });
+ const exposed = SYNC_HELPERS.has(name)
+ ? value
+ : async (...args: unknown[]) => {
+ await readySignal;
+ if (readyError) {
+ throw readyError;
+ }
+ return value(...args);
+ };
+ Object.defineProperty(target, name, {
+ value: exposed,
+ writable: true,
+ configurable: true,
+ enumerable: false,
+ });
installed[name] = exposed as HelperFunction;
}
const cliLogFn = options.cliLog || createCliLog();
- Object.defineProperty(target, "cliLog", { value: cliLogFn, writable: true, configurable: true, enumerable: false });
+ Object.defineProperty(target, "cliLog", {
+ value: cliLogFn,
+ writable: true,
+ configurable: true,
+ enumerable: false,
+ });
installed.cliLog = cliLogFn;
if (target.ego && typeof target.ego === "object") {
target.ego.helpers = installed;
target.ego.learnings = {};
if (!(target.ego as Record<symbol, unknown>)[EGO_WRAPPED]) {
wrapCreateTab(target.ego);
- wrapInvalidating(target.ego, ["useTaskSpace", "closeTaskSpace", "createTaskSpace", "claimTaskSpace"]);
- Object.defineProperty(target.ego, EGO_WRAPPED, { value: true, enumerable: false });
+ wrapInvalidating(target.ego, [
+ "useTaskSpace",
+ "closeTaskSpace",
+ "createTaskSpace",
+ "claimTaskSpace",
+ ]);
+ Object.defineProperty(target.ego, EGO_WRAPPED, {
+ value: true,
+ enumerable: false,
+ });
}
exposeEgoMethods(target, target.ego);
}
@@ -80,14 +107,18 @@ if (isDirectCli()) {
installEgoSdk();
}
-function createCliLog(stream: { write(chunk: string): unknown } = process.stdout) {
+function createCliLog(
+ stream: { write(chunk: string): unknown } = process.stdout,
+) {
return (...args: unknown[]) => {
stream.write(`${args.map(formatCliLogValue).join(" ")}\n`);
};
}
function isDirectCli() {
- return process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url;
+ return (
+ process.argv[1] && pathToFileURL(process.argv[1]).href === import.meta.url
+ );
}
function wrapInvalidating(ego: EgoRuntime, methodNames: string[]) {
@@ -131,13 +162,25 @@ function wrapCreateTab(ego: EgoRuntime) {
}
function exposeEgoMethods(target: InstallTarget, ego: EgoRuntime) {
- const skip = new Set(["helpers", "learnings", "useTaskSpace", "createTaskSpace", "claimTaskSpace", "closeTaskSpace"]);
+ const skip = new Set([
+ "helpers",
+ "learnings",
+ "useTaskSpace",
+ "createTaskSpace",
+ "claimTaskSpace",
+ "closeTaskSpace",
+ ]);
for (const key of Object.keys(ego)) {
if (skip.has(key)) continue;
if (key in target) continue;
const value = ego[key];
if (typeof value !== "function") continue;
const bound = value.bind(ego);
- Object.defineProperty(target, key, { value: bound, writable: true, configurable: true, enumerable: false });
+ Object.defineProperty(target, key, {
+ value: bound,
+ writable: true,
+ configurable: true,
+ enumerable: false,
+ });
}
}
diff --git a/package/ego-browser/src/learning/check-domain-learning.ts b/package/ego-browser/src/learning/check-domain-learning.ts
index 6089c99..a8df146 100644
--- a/package/ego-browser/src/learning/check-domain-learning.ts
+++ b/package/ego-browser/src/learning/check-domain-learning.ts
@@ -69,20 +69,28 @@ export function learningsRoot(workspace = agentWorkspace()) {
export const siteSkillsRoot = learningsRoot;
-export async function checkDomainLearningExists(urlOrDomain: string, options: { root?: string; agentWorkspace?: string } = {}) {
+export async function checkDomainLearningExists(
+ urlOrDomain: string,
+ options: { root?: string; agentWorkspace?: string } = {},
+) {
const hostname = urlHostname(urlOrDomain);
- const root = options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
+ const root =
+ options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
const matches = hostname ? await siteSkillsForUrl(hostname, { root }) : [];
return {
exists: matches.length > 0,
hostname,
root,
- matches
+ matches,
};
}
-export async function checkLearningExists(siteId: string, options: { root?: string; agentWorkspace?: string } = {}) {
- const root = options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
+export async function checkLearningExists(
+ siteId: string,
+ options: { root?: string; agentWorkspace?: string } = {},
+) {
+ const root =
+ options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
const siteDir = join(root, siteId);
const manifestPath = join(siteDir, "manifest.json");
const exists = await pathExists(manifestPath);
@@ -90,7 +98,7 @@ export async function checkLearningExists(siteId: string, options: { root?: stri
exists,
root,
siteDir,
- manifestPath
+ manifestPath,
};
}
@@ -99,7 +107,8 @@ export async function siteSkillsForUrl(url, options: any = {}) {
if (!hostname) {
return [];
}
- const root = options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
+ const root =
+ options.root || learningsRoot(options.agentWorkspace || agentWorkspace());
const matches = [];
for (const siteDir of await iterLearningDirs(root)) {
let manifest;
@@ -109,7 +118,12 @@ export async function siteSkillsForUrl(url, options: any = {}) {
continue;
}
const domains = Array.isArray(manifest.domains) ? manifest.domains : [];
- if (domains.some((domain) => typeof domain === "string" && domainMatches(hostname, domain))) {
+ if (
+ domains.some(
+ (domain) =>
+ typeof domain === "string" && domainMatches(hostname, domain),
+ )
+ ) {
matches.push(learningEntry(siteDir, manifest));
}
}
@@ -129,20 +143,29 @@ export async function iterLearningDirs(root: string) {
.sort();
}
-export async function loadLearningManifest(siteDir: string): Promise<LearningManifest> {
+export async function loadLearningManifest(
+ siteDir: string,
+): Promise<LearningManifest> {
let parsed: unknown;
try {
parsed = JSON.parse(await readFile(join(siteDir, "manifest.json"), "utf8"));
} catch (error) {
- throw new Error(`site skill ${JSON.stringify(siteDir)} has invalid or missing manifest.json: ${error.message}`);
+ throw new Error(
+ `site skill ${JSON.stringify(siteDir)} has invalid or missing manifest.json: ${error.message}`,
+ );
}
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
- throw new Error(`site skill ${JSON.stringify(siteDir)} manifest must be an object`);
+ throw new Error(
+ `site skill ${JSON.stringify(siteDir)} manifest must be an object`,
+ );
}
return parsed as LearningManifest;
}
-export function learningEntry(siteDir: string, manifest: LearningManifest): LearningEntry {
+export function learningEntry(
+ siteDir: string,
+ manifest: LearningManifest,
+): LearningEntry {
const notes = Array.isArray(manifest.notes) ? manifest.notes : [];
return {
id: manifest.id || siteDir.split(/[\\/]/).at(-1),
@@ -151,7 +174,7 @@ export function learningEntry(siteDir: string, manifest: LearningManifest): Lear
domains: Array.isArray(manifest.domains) ? [...manifest.domains] : [],
notes: notes.map((note) => join(siteDir, note)),
nodeTools: toolSchemasNode(manifest),
- browserTools: toolSchemasBrowser(manifest)
+ browserTools: toolSchemasBrowser(manifest),
};
}
@@ -176,7 +199,9 @@ export function urlHostname(url) {
}
function domainMatches(hostname, pattern) {
- const normalized = String(pattern || "").toLowerCase().replace(/\.$/, "");
+ const normalized = String(pattern || "")
+ .toLowerCase()
+ .replace(/\.$/, "");
if (normalized.startsWith("*.")) {
const suffix = normalized.slice(2);
return hostname.endsWith(`.${suffix}`);
@@ -184,13 +209,17 @@ function domainMatches(hostname, pattern) {
return hostname === normalized;
}
-function toolSchemasNode(manifest: LearningManifest): Record<string, NodeToolSchema> {
+function toolSchemasNode(
+ manifest: LearningManifest,
+): Record<string, NodeToolSchema> {
const value = manifest.nodeTools;
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
return { ...value };
}
-function toolSchemasBrowser(manifest: LearningManifest): Record<string, ToolSchema> {
+function toolSchemasBrowser(
+ manifest: LearningManifest,
+): Record<string, ToolSchema> {
const value = manifest.browserTools;
if (!value || typeof value !== "object" || Array.isArray(value)) return {};
return { ...value };
diff --git a/package/ego-browser/src/learning/index.ts b/package/ego-browser/src/learning/index.ts
index 7b4da5d..ac7e47f 100644
--- a/package/ego-browser/src/learning/index.ts
+++ b/package/ego-browser/src/learning/index.ts
@@ -21,7 +21,7 @@ import {
import {
validateLearning,
validateLearnings,
- validateSiteSkills
+ validateSiteSkills,
} from "./validate-learning-format.js";
export {
@@ -31,19 +31,22 @@ export {
learningsRoot,
pathExists,
siteSkillsForUrl,
- siteSkillsRoot
+ siteSkillsRoot,
} from "./check-domain-learning.js";
export {
validateLearning,
validateLearnings,
- validateSiteSkills
+ validateSiteSkills,
} from "./validate-learning-format.js";
/**
* Load learned context for a given URL.
* Returns site knowledge (notes content, available tools, selector hints).
*/
-export async function loadLearnedContext(url: string, options: any = {}): Promise<LearnedContext> {
+export async function loadLearnedContext(
+ url: string,
+ options: any = {},
+): Promise<LearnedContext> {
const matches = await siteSkillsForUrl(url, options);
if (matches.length === 0) {
return {
@@ -115,13 +118,18 @@ export async function loadLearnedContext(url: string, options: any = {}): Promis
function isLearningNotePath(siteDir: string, notePath: string) {
const relativePath = relative(resolve(siteDir), resolve(notePath));
const parts = relativePath.split(/[\\/]/);
- return parts.length === 2
- && parts[0] === "notes"
- && parts[1].endsWith(".md")
- && parts.every((part) => part && part !== "." && part !== "..");
+ return (
+ parts.length === 2 &&
+ parts[0] === "notes" &&
+ parts[1].endsWith(".md") &&
+ parts.every((part) => part && part !== "." && part !== "..")
+ );
}
-export async function findSiteSkill(siteId: string, options: any = {}): Promise<{ siteDir: string; manifest: LearningManifest }> {
+export async function findSiteSkill(
+ siteId: string,
+ options: any = {},
+): Promise<{ siteDir: string; manifest: LearningManifest }> {
const root = options.root || siteSkillsRoot(options.agentWorkspace);
for (const siteDir of await iterLearningDirs(root)) {
const manifest = await loadLearningManifest(siteDir);
@@ -132,30 +140,50 @@ export async function findSiteSkill(siteId: string, options: any = {}): Promise<
throw siteSkillNotFoundError(siteId, root);
}
-export async function runNodeSiteTool(siteId, toolName, args: any = {}, ctx, options: any = {}) {
+export async function runNodeSiteTool(
+ siteId,
+ toolName,
+ args: any = {},
+ ctx,
+ options: any = {},
+) {
const { siteDir, manifest } = await findSiteSkill(siteId, options);
const schema = toolSchemas(manifest, "nodeTools")[toolName];
if (!schema || typeof schema !== "object") {
- throw new Error(`Node tool ${JSON.stringify(toolName)} is not declared by site skill ${JSON.stringify(siteId)}`);
+ throw new Error(
+ `Node tool ${JSON.stringify(toolName)} is not declared by site skill ${JSON.stringify(siteId)}`,
+ );
}
const toolPath = relativeSitePath(siteDir, schema.path, "Node tool");
- const module = await import(`${pathToFileURL(toolPath).href}?t=${Date.now()}`);
+ const module = await import(
+ `${pathToFileURL(toolPath).href}?t=${Date.now()}`
+ );
const callableName = schema.callable;
if (typeof callableName !== "string" || !callableName.trim()) {
- throw new Error(`Node tool ${JSON.stringify(toolName)} must declare a callable`);
+ throw new Error(
+ `Node tool ${JSON.stringify(toolName)} must declare a callable`,
+ );
}
const tool = module[callableName];
if (typeof tool !== "function") {
- throw new Error(`site skill ${JSON.stringify(siteId)} is missing Node callable ${JSON.stringify(callableName)}`);
+ throw new Error(
+ `site skill ${JSON.stringify(siteId)} is missing Node callable ${JSON.stringify(callableName)}`,
+ );
}
return tool(ctx, args || {});
}
-export async function loadBrowserToolSource(siteId, toolName, options: any = {}) {
+export async function loadBrowserToolSource(
+ siteId,
+ toolName,
+ options: any = {},
+) {
const { siteDir, manifest } = await findSiteSkill(siteId, options);
const schema = toolSchemas(manifest, "browserTools")[toolName];
if (!schema || typeof schema !== "object") {
- throw new Error(`browser tool ${JSON.stringify(toolName)} is not declared by site skill ${JSON.stringify(siteId)}`);
+ throw new Error(
+ `browser tool ${JSON.stringify(toolName)} is not declared by site skill ${JSON.stringify(siteId)}`,
+ );
}
const toolPath = relativeSitePath(siteDir, schema.path, "browser tool");
return readFile(toolPath, "utf8");
@@ -173,22 +201,30 @@ function siteSkillNotFoundError(siteId, searchedRoot) {
`site skill not found: ${JSON.stringify(siteId)}`,
` searched: ${searchedRoot}`,
` EGO_BROWSER_AGENT_WORKSPACE: ${workspace}`,
- ` hint: ensure your write path begins with the searched root above`
+ ` hint: ensure your write path begins with the searched root above`,
];
return new Error(lines.join("\n"));
}
function toolSchemas(manifest, key) {
const value = manifest[key] || {};
- return value && typeof value === "object" && !Array.isArray(value) ? { ...value } : {};
+ return value && typeof value === "object" && !Array.isArray(value)
+ ? { ...value }
+ : {};
}
function relativeSitePath(siteDir, manifestPath, label) {
if (typeof manifestPath !== "string" || !manifestPath.trim()) {
throw new Error(`${label} path must be a non-empty relative path`);
}
- if (manifestPath.includes("\\") || isAbsolute(manifestPath) || manifestPath.split("/").includes("..")) {
- throw new Error(`${label} path must be relative to the site skill directory`);
+ if (
+ manifestPath.includes("\\") ||
+ isAbsolute(manifestPath) ||
+ manifestPath.split("/").includes("..")
+ ) {
+ throw new Error(
+ `${label} path must be relative to the site skill directory`,
+ );
}
const resolved = resolve(siteDir, manifestPath);
const siteRoot = resolve(siteDir);
diff --git a/package/ego-browser/src/ref-map.ts b/package/ego-browser/src/ref-map.ts
index c5d7398..c5e17ab 100644
--- a/package/ego-browser/src/ref-map.ts
+++ b/package/ego-browser/src/ref-map.ts
@@ -9,14 +9,21 @@ export class RefMap {
this.addWithFrame(refId, backendNodeId, role, name, nth, undefined);
}
- addWithFrame(refId, backendNodeId, role, name, nth = undefined, frameId = undefined) {
+ addWithFrame(
+ refId,
+ backendNodeId,
+ role,
+ name,
+ nth = undefined,
+ frameId = undefined,
+ ) {
this.map.set(refId, {
backendNodeId,
role,
name,
nth,
selector: undefined,
- frameId
+ frameId,
});
}
@@ -38,7 +45,7 @@ export function parseRef(input) {
for (const candidate of [
trimmed.startsWith("@") ? trimmed.slice(1) : null,
trimmed.startsWith("ref=") ? trimmed.slice(4) : null,
- trimmed
+ trimmed,
]) {
if (candidate && /^\d+$/.test(candidate)) {
return candidate;
diff --git a/package/ego-browser/src/run.ts b/package/ego-browser/src/run.ts
index 918931e..1746995 100644
--- a/package/ego-browser/src/run.ts
+++ b/package/ego-browser/src/run.ts
@@ -1,4 +1,8 @@
-import { stdin as processStdin, stdout as processStdout, stderr as processStderr } from "node:process";
+import {
+ stdin as processStdin,
+ stdout as processStdout,
+ stderr as processStderr,
+} from "node:process";
import { formatCliLogValue } from "./format.js";
import * as helpers from "./helpers.js";
@@ -62,7 +66,7 @@ export async function runMain(options: RunMainOptions = {}) {
resetConnection: async () => {},
printUpdateBanner: () => {},
runDoctor: async () => 0,
- ...options.services
+ ...options.services,
};
if (argv[0] === "-h" || argv[0] === "--help") {
@@ -86,7 +90,10 @@ export async function runMain(options: RunMainOptions = {}) {
return 2;
}
- const code = options.stdinText !== undefined ? options.stdinText : await readAll(options.stdin || processStdin);
+ const code =
+ options.stdinText !== undefined
+ ? options.stdinText
+ : await readAll(options.stdin || processStdin);
if (!code.trim()) {
write(stderr, USAGE);
return 2;
diff --git a/package/ego-browser/src/state.ts b/package/ego-browser/src/state.ts
index 4b80a10..36c816b 100644
--- a/package/ego-browser/src/state.ts
+++ b/package/ego-browser/src/state.ts
@@ -9,9 +9,15 @@ export const NAME = process.env.EGO_BROWSER_NAME || "default";
async function defaultSend(req) {
if (!req || typeof req !== "object" || !req.method) {
- throw new Error(`unsupported browser runtime request: ${JSON.stringify(req)}`);
+ throw new Error(
+ `unsupported browser runtime request: ${JSON.stringify(req)}`,
+ );
}
- const response = await browserCdp(req.method, req.params || {}, req.session_id);
+ const response = await browserCdp(
+ req.method,
+ req.params || {},
+ req.session_id,
+ );
return { result: response.result || {} };
}
@@ -29,7 +35,7 @@ export const state = {
sessionInflight: null,
preferredTargetId: null,
// Last observed Network domain state on the default session (tracked in cdp()).
- networkDomainEnabled: false
+ networkDomainEnabled: false,
};
export async function send(req) {
diff --git a/package/ego-browser/src/taskspace-e2e.test.mjs b/package/ego-browser/src/taskspace-e2e.test.mjs
index c9b8314..fe7c90e 100644
--- a/package/ego-browser/src/taskspace-e2e.test.mjs
+++ b/package/ego-browser/src/taskspace-e2e.test.mjs
@@ -8,7 +8,13 @@ class FakeEgo {
this.taskSpaces = taskSpaces.map((space) => ({ ...space }));
this.calls = [];
this.selectedId = null;
- this.nextId = Math.max(0, ...this.taskSpaces.map((space) => typeof space.id === "number" ? space.id : 0)) + 1;
+ this.nextId =
+ Math.max(
+ 0,
+ ...this.taskSpaces.map((space) =>
+ typeof space.id === "number" ? space.id : 0,
+ ),
+ ) + 1;
}
async listTaskSpaces() {
@@ -27,10 +33,21 @@ class FakeEgo {
async createTaskSpace(name) {
this.calls.push(["createTaskSpace", name]);
- if (this.taskSpaces.some((space) => space.taskId === name || space.name === name)) {
+ if (
+ this.taskSpaces.some(
+ (space) => space.taskId === name || space.name === name,
+ )
+ ) {
return { error: `Task space already exists: ${name}` };
}
- const created = { taskId: name, id: this.nextId++, name, createdBy: "agent", ownership: "agent", recentTabTitles: [] };
+ const created = {
+ taskId: name,
+ id: this.nextId++,
+ name,
+ createdBy: "agent",
+ ownership: "agent",
+ recentTabTitles: [],
+ };
this.taskSpaces.push(created);
return { ...created };
}
@@ -65,7 +82,7 @@ async function runTaskspaceScript(ego, code) {
stdinText: code,
stdout,
stderr,
- services: { printUpdateBanner() {} }
+ services: { printUpdateBanner() {} },
});
return { exitCode, stdout: stdout.text(), stderr: stderr.text() };
} finally {
@@ -85,7 +102,7 @@ function captureStream() {
},
text() {
return chunks.join("");
- }
+ },
};
}
@@ -95,10 +112,13 @@ function firstJsonLine(output) {
test("taskspace e2e creates and selects a missing task space", async () => {
const ego = new FakeEgo();
- const result = await runTaskspaceScript(ego, `
+ const result = await runTaskspaceScript(
+ ego,
+ `
const task = await useOrCreateTaskSpace("checkout-flow");
cliLog(JSON.stringify({ task, selected: ego.selectedId }));
- `);
+ `,
+ );
assert.equal(result.exitCode, 0);
assert.deepEqual(firstJsonLine(result.stdout), {
@@ -108,81 +128,113 @@ test("taskspace e2e creates and selects a missing task space", async () => {
name: "checkout-flow",
createdBy: "agent",
ownership: "agent",
- recentTabTitles: []
+ recentTabTitles: [],
},
- selected: 1
+ selected: 1,
});
assert.deepEqual(ego.calls, [
["listTaskSpaces"],
["createTaskSpace", "checkout-flow"],
- ["useTaskSpace", 1]
+ ["useTaskSpace", 1],
]);
});
test("taskspace e2e reuses an existing agent-owned task space", async () => {
const ego = new FakeEgo([
- { taskId: "checkout-flow", id: 7, name: "Checkout flow", createdBy: "agent", ownership: "agent" }
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "Checkout flow",
+ createdBy: "agent",
+ ownership: "agent",
+ },
]);
- const result = await runTaskspaceScript(ego, `
+ const result = await runTaskspaceScript(
+ ego,
+ `
const task = await useOrCreateTaskSpace(7);
cliLog(JSON.stringify({ task, selected: ego.selectedId }));
- `);
+ `,
+ );
assert.equal(result.exitCode, 0);
assert.deepEqual(firstJsonLine(result.stdout), {
- task: { taskId: "checkout-flow", id: 7, name: "Checkout flow", createdBy: "agent", ownership: "agent" },
- selected: 7
+ task: {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "Checkout flow",
+ createdBy: "agent",
+ ownership: "agent",
+ },
+ selected: 7,
});
- assert.deepEqual(ego.calls, [
- ["listTaskSpaces"],
- ["useTaskSpace", 7]
- ]);
+ assert.deepEqual(ego.calls, [["listTaskSpaces"], ["useTaskSpace", 7]]);
});
test("taskspace e2e claims and selects an existing user-owned task space", async () => {
const ego = new FakeEgo([
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", createdBy: "user", ownership: "user" }
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ createdBy: "user",
+ ownership: "user",
+ },
]);
- const result = await runTaskspaceScript(ego, `
+ const result = await runTaskspaceScript(
+ ego,
+ `
const task = await useOrCreateTaskSpace("checkout-flow");
cliLog(JSON.stringify({ task, selected: ego.selectedId }));
- `);
+ `,
+ );
assert.equal(result.exitCode, 0);
assert.deepEqual(firstJsonLine(result.stdout), {
- task: { taskId: "checkout-flow", id: 7, name: "checkout-flow", createdBy: "agent", ownership: "agent" },
- selected: 7
+ task: {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ createdBy: "agent",
+ ownership: "agent",
+ },
+ selected: 7,
});
assert.deepEqual(ego.calls, [
["listTaskSpaces"],
["claimTaskSpace", 7, "checkout-flow"],
- ["useTaskSpace", 7]
+ ["useTaskSpace", 7],
]);
});
test("taskspace e2e exposes newTaskSpace but not claimTaskSpace as a helper", async () => {
const ego = new FakeEgo();
- const result = await runTaskspaceScript(ego, `
+ const result = await runTaskspaceScript(
+ ego,
+ `
cliLog(JSON.stringify({
newType: typeof newTaskSpace,
switchType: typeof switchTaskSpace,
claimType: typeof claimTaskSpace,
rawClaimType: typeof ego.claimTaskSpace
}));
- `);
+ `,
+ );
assert.equal(result.exitCode, 0);
assert.deepEqual(firstJsonLine(result.stdout), {
newType: "function",
switchType: "function",
claimType: "undefined",
- rawClaimType: "function"
+ rawClaimType: "function",
});
});
test("cli e2e exposes the unified helperContext surface (help present, internals hidden)", async () => {
const ego = new FakeEgo();
- const result = await runTaskspaceScript(ego, `
+ const result = await runTaskspaceScript(
+ ego,
+ `
cliLog(JSON.stringify({
helpType: typeof help,
helpResultType: typeof help("click"),
@@ -190,7 +242,8 @@ test("cli e2e exposes the unified helperContext surface (help present, internals
helperContextType: typeof helperContext,
loadAgentHelpersType: typeof loadAgentHelpers
}));
- `);
+ `,
+ );
assert.equal(result.exitCode, 0);
assert.deepEqual(firstJsonLine(result.stdout), {
@@ -198,42 +251,59 @@ test("cli e2e exposes the unified helperContext surface (help present, internals
helpResultType: "string",
newTabType: "undefined",
helperContextType: "undefined",
- loadAgentHelpersType: "undefined"
+ loadAgentHelpersType: "undefined",
});
});
test("taskspace e2e rejects explicit use of a user-owned task space", async () => {
const ego = new FakeEgo([
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", createdBy: "user", ownership: "user" }
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ createdBy: "user",
+ ownership: "user",
+ },
]);
await assert.rejects(
() => runTaskspaceScript(ego, `await switchTaskSpace("checkout-flow")`),
- /switchTaskSpace requires an agent-owned task space/
+ /switchTaskSpace requires an agent-owned task space/,
);
assert.deepEqual(ego.calls, [["listTaskSpaces"]]);
});
test("taskspace e2e rejects unknown task space ownership", async () => {
const ego = new FakeEgo([
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "shared" }
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "shared",
+ },
]);
await assert.rejects(
- () => runTaskspaceScript(ego, `await useOrCreateTaskSpace("checkout-flow")`),
- /ownership "shared"/
+ () =>
+ runTaskspaceScript(ego, `await useOrCreateTaskSpace("checkout-flow")`),
+ /ownership "shared"/,
);
assert.deepEqual(ego.calls, [["listTaskSpaces"]]);
});
test("taskspace e2e surfaces newTaskSpace binding errors", async () => {
const ego = new FakeEgo([
- { taskId: "checkout-flow", id: 7, name: "checkout-flow", ownership: "agent" }
+ {
+ taskId: "checkout-flow",
+ id: 7,
+ name: "checkout-flow",
+ ownership: "agent",
+ },
]);
await assert.rejects(
() => runTaskspaceScript(ego, `await newTaskSpace("checkout-flow")`),
- /newTaskSpace: Task space already exists: checkout-flow/
+ /newTaskSpace: Task space already exists: checkout-flow/,
);
assert.deepEqual(ego.calls, [["createTaskSpace", "checkout-flow"]]);
});