Skip to content

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

fix(ego-browser): require absolute paths for screenshot and fetch saveAs

Zhuowei Wang26b64be706b2
diff --git a/package/ego-browser/src/page-model.test.mjs b/package/ego-browser/src/page-model.test.mjs
index f7f8eb0..3646caf 100644
--- a/package/ego-browser/src/page-model.test.mjs
+++ b/package/ego-browser/src/page-model.test.mjs
@@ -2531,6 +2531,19 @@ test("metadata reads stay target-scoped while evaluate and screenshot activate t
() => first.screenshot("/tmp/legacy.png"),
/options must be an object/,
);
+ for (const path of ["./step1-initial.png", "shots/before.png", ""]) {
+ await assert.rejects(
+ () => first.screenshot({ path }),
+ /page\.screenshot path must be an absolute file path/,
+ `page.screenshot must reject the relative path ${JSON.stringify(path)}`,
+ );
+ }
+ assert(
+ !fixture.calls.some(
+ ([kind, path]) => kind === "screenshot" && !path.startsWith("/"),
+ ),
+ "relative screenshot paths must be rejected before capture",
+ );
assert.equal(
fixture.activeTarget(),
"target-1",
@@ -3018,6 +3031,18 @@ test("Page fetch saves a binary response without converting it to text", async (
});
});
+test("Page fetch rejects a relative saveAs path before requesting", async () => {
+ await withFixture(async (fixture) => {
+ const task = taskForRound(fixture, "round-a");
+ const page = await openTestPage(task, "https://example.test/fetch");
+
+ await assert.rejects(
+ () => page.fetch("/image.png", { saveAs: "./image.png" }),
+ /page\.fetch saveAs must be an absolute file path/,
+ );
+ });
+});
+
test("Page click fails closed when native mouse dispatch times out", async () => {
await withFixture(async (fixture) => {
fixture.tabs.set("target-user", {
diff --git a/package/ego-browser/src/page-model.ts b/package/ego-browser/src/page-model.ts
index 90a30c3..1e4d4c3 100644
--- a/package/ego-browser/src/page-model.ts
+++ b/package/ego-browser/src/page-model.ts
@@ -1,5 +1,5 @@
import { mkdir, writeFile } from "node:fs/promises";
-import { dirname } from "node:path";
+import { dirname, isAbsolute } from "node:path";
import {
browserCdp,
@@ -2134,8 +2134,8 @@ class Page {
async screenshot(options: PageScreenshotOptions = {}): Promise<string> {
validatePublicApiOptions("Page.screenshot", options);
const { path, fullPage, ...captureOptions } = options;
- if (path !== undefined && (typeof path !== "string" || path.length === 0)) {
- throw new TypeError("page.screenshot path must be a non-empty string");
+ if (path !== undefined) {
+ assertAbsoluteFilePath(path, "page.screenshot path");
}
const page = await this.#resolve();
return this.#services.gate.withPage(page, async ({ sessionId }) => {
@@ -3340,12 +3340,25 @@ function serializeJsonValue(value: unknown, message: string): unknown {
}
}
+// The script does not run in the caller's shell working directory: the host
+// starts the Node context from the application's own directory, which is not
+// writable on Windows. Reject relative paths up front instead of surfacing a
+// confusing EPERM from that directory.
+function assertAbsoluteFilePath(path: unknown, label: string): void {
+ if (typeof path !== "string" || path.length === 0 || !isAbsolute(path)) {
+ throw new TypeError(`${label} must be an absolute file path`);
+ }
+}
+
function pageFetchPayload(
url: string,
options: PageFetchOptions,
): { payload: PageFetchPayload; saveAs?: string } {
validatePublicApiOptions("Page.fetch", options);
const { timeout = 20_000, saveAs, ...requestOptions } = options;
+ if (saveAs !== undefined) {
+ assertAbsoluteFilePath(saveAs, "page.fetch saveAs");
+ }
return {
payload: {
url,
diff --git a/package/ego-browser/src/public-api-schema.ts b/package/ego-browser/src/public-api-schema.ts
index 6c999f5..0f2b4df 100644
--- a/package/ego-browser/src/public-api-schema.ts
+++ b/package/ego-browser/src/public-api-schema.ts
@@ -258,7 +258,7 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
options: {
path: option(
"string",
- "Output path; missing parent directories are created.",
+ "Absolute output path; missing parent directories are created. Omit to write into the system temporary directory.",
),
fullPage: option("boolean", "Capture the full scrollable page."),
clip: option("clip", "CSS-pixel clipping rectangle."),
@@ -387,7 +387,7 @@ export const PUBLIC_API_SCHEMA: readonly PublicApiEntry[] = [
timeout,
saveAs: option(
"nonEmptyString",
- "Write the response body to this path without text conversion.",
+ "Write the response body to this absolute path without text conversion.",
),
method: option("string", "HTTP method."),
headers: option("stringRecord", "Request headers."),
diff --git a/skills/ego-browser/SKILL.md b/skills/ego-browser/SKILL.md
index 2759213..efd7f53 100644
--- a/skills/ego-browser/SKILL.md
+++ b/skills/ego-browser/SKILL.md
@@ -48,7 +48,9 @@ Node.js APIs belong in the script; Page globals such as `window`, `document`,
`page.evaluate()`. Do not import Playwright or launch another browser.
The Node.js runtime uses ESM. When a script needs local files, load built-ins
-with dynamic imports such as `await import("node:fs/promises")`.
+with dynamic imports such as `await import("node:fs/promises")`. The script
+does not run in your shell's working directory, so use absolute paths for every
+file it reads or writes.
Ego-browser deliberately exposes a small custom API. It is not Playwright, even
where method names and options look similar. Use only the TaskSpace, Page,
@@ -270,6 +272,12 @@ await page.keyboard.paste("hello\tworld");
console.log({ screenshot: path });
```
+`path` must be absolute; relative paths are rejected. Omit `path` to write
+into the system temporary directory and use the returned file path. On
+Windows, write paths with forward slashes, such as
+`C:/Users/<name>/ego-shots/before.png`, because backslashes are escape
+characters inside JavaScript strings.
+
Inspect the screenshot with an image-viewing tool. Coordinates use CSS pixels;
keyboard names and `+`-separated chords follow Playwright syntax. Use
`ControlOrMeta` for portable shortcuts and verify the resulting page state.
diff --git a/skills/ego-browser/references/api.md b/skills/ego-browser/references/api.md
index 0e67b60..7d050c0 100644
--- a/skills/ego-browser/references/api.md
+++ b/skills/ego-browser/references/api.md
@@ -43,42 +43,42 @@ Selectors accept refs, Ego locators, XPath, and raw CSS. A small compatibility s
## Page
-| API | Options | Purpose |
-| ----------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| `page.label` | — | Durable Page label used to restore the tab across rounds. |
-| `page.spaceId` | — | Numeric identifier of the Page's task space. |
-| `page.openedBy` | — | Conservative origin attribution for this Page. |
-| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |
-| `await page.goto(url, { referer?, timeout?, waitUntil? })` | `referer` — HTTP Referer header for the navigation.<br>`timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Navigate this Page in place. Timeout errors report whether the new document committed, plus its URL and readyState when available. |
-| `await page.reload({ timeout?, waitUntil? })` | `timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Reload this Page and wait for the selected navigation state. |
-| `await page.snapshot({ scope?, root?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport, subtree) — Snapshot scope; defaults to only_within_viewport, including visible iframe content returned by the browser. Use subtree with an iframe root ref to focus on that frame.<br>`root` — Valid Page snapshot ref such as @21; required only when scope is subtree. Partial snapshots preserve existing node identities.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport, full Page, or one snapshot-ref subtree with Page provenance. |
-| `await page.screenshot({ path?, fullPage?, clip?, scale?, raw? })` | `path` — Output path; missing parent directories are created.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`scale` (css) — Output scale mode; css uses CSS-pixel sizing and is the default.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |
-| `await page.url()` | — | Read this Page's current URL. |
-| `await page.waitForURL(urlMatcher, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL, Playwright-style glob, RegExp, or synchronous predicate receiving a URL object. |
-| `await page.waitForEvent(event, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for this Page's next "popup" or "download"; arm the promise before the triggering action. |
-| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |
-| `await page.title()` | — | Read this Page's current title. |
-| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |
-| `await page.acceptDialog(promptText?)` | — | Accept this Page's JavaScript dialog, optionally supplying prompt text; return false when none is open. |
-| `await page.dismissDialog()` | — | Dismiss this Page's JavaScript dialog; return false when none is open. |
-| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables. Safety-timeout errors report executionStopped, pageResponsive, and mayHaveLateEffects. |
-| `await page.waitForFunction(fnOrString, argument?, { timeout?, polling? })` | `timeout` — Maximum duration in milliseconds.<br>`polling` — Polling interval in milliseconds; defaults to 100. | Wait until a Page function or expression returns a truthy value. |
-| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`saveAs` — Write the response body to this path without text conversion.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page, obey browser CORS, and return a structured response. |
-| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |
-| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |
-| `await page.waitForLoadState(state?, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state; no state defaults to load. |
-| `await page.events()` | — | Read and clear CDP events buffered for this Page. |
-| `await page.click(selector, { button?, clickCount?, delay?, position?, force?, timeout?, label? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000.<br>`label` — Concise user-visible action description shown with the native mouse highlight. | Click an element with native CDP input. |
-| `await page.dblclick(selector, { button?, delay?, position?, force?, timeout?, label? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000.<br>`label` — Concise user-visible action description shown with the native mouse highlight. | Double-click an element with native CDP input. |
-| `await page.hover(selector, { position?, force?, timeout?, label? })` | `position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000.<br>`label` — Concise user-visible action description shown with the native mouse highlight. | Move the mouse over an element. |
-| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition?, force?, timeout?, label? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000.<br>`label` — Concise user-visible action description shown with the native mouse highlight. | Drag from one element to another. |
-| `await page.fill(selector, value, { clearFirst?, timeout? })` | `clearFirst` — Clear the current value before filling.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Fill the selected field, its editing host, or its unique fillable descendant, then confirm editing took effect. |
-| `await page.selectOption(selector, valueOrValues, { timeout? })` | `timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Select by a value-or-label string or { value?, label?, index? }; arrays select multiple options, while null or [] clears the selection. The select must be enabled, but disabled options remain programmatically selectable. |
-| `await page.focus(selector, { timeout? })` | `timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Focus the element, its nearest interactive ancestor, or its unique editable descendant. |
-| `await page.press(selector, chord, { delay?, timeout? })` | `delay` — Input delay in milliseconds.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Focus one element and press a key or shortcut chord. Named keys are case-insensitive; single-character keys preserve case. |
-| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input resolved from the input, its label, or a unique descendant. |
-| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |
-| `await page.close()` | — | Close this Page after confirming its tab disappeared. |
+| API | Options | Purpose |
+| ----------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `page.label` | — | Durable Page label used to restore the tab across rounds. |
+| `page.spaceId` | — | Numeric identifier of the Page's task space. |
+| `page.openedBy` | — | Conservative origin attribution for this Page. |
+| `page.targetId` | — | Internal browser target identifier for advanced Target-domain CDP only. |
+| `await page.goto(url, { referer?, timeout?, waitUntil? })` | `referer` — HTTP Referer header for the navigation.<br>`timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Navigate this Page in place. Timeout errors report whether the new document committed, plus its URL and readyState when available. |
+| `await page.reload({ timeout?, waitUntil? })` | `timeout` — Maximum duration in milliseconds.<br>`waitUntil` (commit, domcontentloaded, load, networkidle) — Completion state; defaults to load. networkidle requires 500ms without network activity. | Reload this Page and wait for the selected navigation state. |
+| `await page.snapshot({ scope?, root?, includeActionMarks?, includeStableLocator? })` | `scope` (full_page, only_within_viewport, subtree) — Snapshot scope; defaults to only_within_viewport, including visible iframe content returned by the browser. Use subtree with an iframe root ref to focus on that frame.<br>`root` — Valid Page snapshot ref such as @21; required only when scope is subtree. Partial snapshots preserve existing node identities.<br>`includeActionMarks` — Include action marks.<br>`includeStableLocator` — Include stable locators. | Return a semantic snapshot of the current viewport, full Page, or one snapshot-ref subtree with Page provenance. |
+| `await page.screenshot({ path?, fullPage?, clip?, scale?, raw? })` | `path` — Absolute output path; missing parent directories are created. Omit to write into the system temporary directory.<br>`fullPage` — Capture the full scrollable page.<br>`clip` — CSS-pixel clipping rectangle.<br>`scale` (css) — Output scale mode; css uses CSS-pixel sizing and is the default.<br>`raw` — Bypass device-pixel-ratio correction. | Capture this Page to a PNG file. |
+| `await page.url()` | — | Read this Page's current URL. |
+| `await page.waitForURL(urlMatcher, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for an exact URL, Playwright-style glob, RegExp, or synchronous predicate receiving a URL object. |
+| `await page.waitForEvent(event, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for this Page's next "popup" or "download"; arm the promise before the triggering action. |
+| `await page.waitForTimeout(timeout)` | — | Wait a fixed number of milliseconds without activating this Page. |
+| `await page.title()` | — | Read this Page's current title. |
+| `await page.info()` | — | Read URL, title, viewport, scroll, and dialog state. |
+| `await page.acceptDialog(promptText?)` | — | Accept this Page's JavaScript dialog, optionally supplying prompt text; return false when none is open. |
+| `await page.dismissDialog()` | — | Dismiss this Page's JavaScript dialog; return false when none is open. |
+| `await page.evaluate(fnOrString, argument?)` | — | Run JavaScript in this Page; callbacks receive JSON data but cannot capture Node.js variables. Safety-timeout errors report executionStopped, pageResponsive, and mayHaveLateEffects. |
+| `await page.waitForFunction(fnOrString, argument?, { timeout?, polling? })` | `timeout` — Maximum duration in milliseconds.<br>`polling` — Polling interval in milliseconds; defaults to 100. | Wait until a Page function or expression returns a truthy value. |
+| `await page.fetch(url, options?)` | `timeout` — Maximum duration in milliseconds.<br>`saveAs` — Write the response body to this absolute path without text conversion.<br>`method` — HTTP method.<br>`headers` — Request headers.<br>`body` — Request body.<br>`cache` (default, no-store, reload, no-cache, force-cache, only-if-cached) — Fetch cache mode.<br>`credentials` (omit, same-origin, include) — Fetch credentials mode.<br>`integrity` — Subresource integrity value.<br>`keepalive` — Allow the request to outlive the page.<br>`mode` (cors, no-cors, same-origin) — Fetch request mode.<br>`redirect` (follow, error, manual) — Redirect handling mode.<br>`referrer` — Request referrer.<br>`referrerPolicy` — Request referrer policy. | Run window.fetch in this Page, obey browser CORS, and return a structured response. |
+| `await page.cdp(method, params?, { timeout? })` | `timeout` — Maximum duration in milliseconds. | Send a CDP command through this Page's target session. |
+| `await page.waitForSelector(selector, { timeout?, state? })` | `timeout` — Maximum duration in milliseconds.<br>`state` (attached, detached, visible, hidden) — Required element state. | Wait for an element state in this Page. |
+| `await page.waitForLoadState(state?, { timeout?, idleMs? })` | `timeout` — Maximum duration in milliseconds.<br>`idleMs` — Required network-idle window in milliseconds. | Wait for DOM content, load, or network-idle state; no state defaults to load. |
+| `await page.events()` | — | Read and clear CDP events buffered for this Page. |
+| `await page.click(selector, { button?, clickCount?, delay?, position?, force?, timeout?, label? })` | `button` (left, middle, right) — Mouse button.<br>`clickCount` — Number of clicks.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000.<br>`label` — Concise user-visible action description shown with the native mouse highlight. | Click an element with native CDP input. |
+| `await page.dblclick(selector, { button?, delay?, position?, force?, timeout?, label? })` | `button` (left, middle, right) — Mouse button.<br>`delay` — Input delay in milliseconds.<br>`position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000.<br>`label` — Concise user-visible action description shown with the native mouse highlight. | Double-click an element with native CDP input. |
+| `await page.hover(selector, { position?, force?, timeout?, label? })` | `position` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000.<br>`label` — Concise user-visible action description shown with the native mouse highlight. | Move the mouse over an element. |
+| `await page.dragAndDrop(source, target, { button?, sourcePosition?, targetPosition?, force?, timeout?, label? })` | `button` (left, middle, right) — Mouse button.<br>`sourcePosition` — CSS-pixel offset from the element's top-left corner.<br>`targetPosition` — CSS-pixel offset from the element's top-left corner.<br>`force` — Bypass pointer interception checks.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000.<br>`label` — Concise user-visible action description shown with the native mouse highlight. | Drag from one element to another. |
+| `await page.fill(selector, value, { clearFirst?, timeout? })` | `clearFirst` — Clear the current value before filling.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Fill the selected field, its editing host, or its unique fillable descendant, then confirm editing took effect. |
+| `await page.selectOption(selector, valueOrValues, { timeout? })` | `timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Select by a value-or-label string or { value?, label?, index? }; arrays select multiple options, while null or [] clears the selection. The select must be enabled, but disabled options remain programmatically selectable. |
+| `await page.focus(selector, { timeout? })` | `timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Focus the element, its nearest interactive ancestor, or its unique editable descendant. |
+| `await page.press(selector, chord, { delay?, timeout? })` | `delay` — Input delay in milliseconds.<br>`timeout` — Maximum wait for the element to become usable in milliseconds; defaults to 3000. | Focus one element and press a key or shortcut chord. Named keys are case-insensitive; single-character keys preserve case. |
+| `await page.setInputFiles(selector, pathOrPaths)` | — | Set files on a file input resolved from the input, its label, or a unique descendant. |
+| `page.waitForFileChooser({ timeout? })` | `timeout` — Maximum duration in milliseconds. | Wait for a dynamically created file chooser. |
+| `await page.close()` | — | Close this Page after confirming its tab disappeared. |
## Download