ctx.browser opens a web page in a headless browser, runs its scripts, and reads the page once it loads. Use it for pages that fetch can’t read well: pages that build their content with JavaScript, pages that need a signed-in session, or pages you want to keep as a screenshot or PDF.
The sandbox never reaches the browser directly. Each action is a request to Forge, which opens the page in a headless browser that Kernel runs and answers with what the page shows. Kernel sees the pages you open and the credentials a connection places in them. A local development stage opens pages in a headless Chrome on your machine instead.
ctx.browser is available in two places:
- A tool’s
ctx.browser. - A workflow step’s
s.browser, insidestep.do(name, async (s) => ...).
Actions
Every action takes an options object with a url, an http: or https: URL, and returns a promise:
| Action | Answers | Extra options |
|---|---|---|
markdown({ url }) |
{ url, status, markdown, truncated }: the page as Markdown, with links and images as absolute URLs |
None |
links({ url }) |
{ url, status, links, truncated }: the page’s distinct http: and https: links, as absolute URLs, in document order |
None |
content({ url }) |
{ url, status, html, truncated }: the page’s HTML once it loaded, as its scripts left it |
None |
screenshot({ url, filename }) |
An attachment: see Screenshots and PDFs | fullPage, format, viewport |
pdf({ url, filename }) |
An attachment: see Screenshots and PDFs | format, landscape |
Every answer carries these fields:
url: The URL the page ended at, after redirects.status: The HTTP status the page answered with, ornullwhen the browser got no response.
Every action also accepts connection, a bound connection whose credentials the page gets. See Signed-in pages.
import { array, defineExtension, object, string, tool } from "@buildr/sdk";
const readSpec = tool(
{
description: "Reads a manufacturer's product page",
input: object({ url: string() }),
output: object({ markdown: string(), datasheets: array(string()) }),
},
async (ctx, { url }) => {
const page = await ctx.browser.markdown({ url });
if (page.status !== 200) throw new Error(`${page.url} answered ${page.status}`);
const { links } = await ctx.browser.links({ url });
return { markdown: page.markdown, datasheets: links.filter((link) => link.endsWith(".pdf")) };
},
);
export default defineExtension({}, { tools: { readSpec } });Truncated answers
A large page is answered cut to a limit, with truncated set to true:
| Answer | Limit |
|---|---|
| HTML read from the page | 2,000,000 characters |
markdown |
1,000,000 characters |
links |
1,000 links |
markdown and links read the page’s first 2,000,000 characters of HTML, so either can be truncated because the page was cut before it was converted.
Screenshots and PDFs
screenshot and pdf never return the file’s bytes. The browser saves the file as an attachment in the repo that the call acts on, created as the caller, as forge attachment-blobs upload creates one. In a workflow step, the caller is the member who started the run. The action answers the attachment:
{ url, status, attachmentBlobId, filename, contentType, size }To attach the file to a record, write attachmentBlobId in an attachment field:
const capture = tool(
{ description: "Keeps a copy of a page", input: object({ url: string() }) },
async (ctx, { url }) => {
const shot = await ctx.browser.screenshot({ url, filename: "page.png", fullPage: true });
await ctx.forge.customRecords.createRepoCustomRecord({
repo_id: ctx.repo.id,
branch: ctx.branch,
model_api_name: "capture",
body: { fields: { page: { id: shot.attachmentBlobId } } },
});
return { attachmentBlobId: shot.attachmentBlobId };
},
);Both actions take a filename, which must not be empty, and these options:
| Action | Option | Default | Values |
|---|---|---|---|
screenshot |
fullPage |
false |
true captures the whole page rather than the viewport |
screenshot |
format |
"png" |
"png" or "jpeg" |
screenshot |
viewport |
The browser’s | { width, height } in CSS pixels, each from 1 to 2048 |
pdf |
format |
"letter" |
"letter", "legal", "tabloid", "a3", "a4", or "a5" |
pdf |
landscape |
false |
true prints in landscape |
A file must fit in 16 MiB. A screenshot is refused before it’s taken when it would hold more than about 4.2 million device pixels (16 MiB at 4 bytes a pixel), and a PDF as soon as it passes 16 MiB. Every call runs in a repo, and the attachment goes there:
- A call on a branch saves into the branch’s repo, the repo that defines the extension.
- A call on an installation, and a workflow step, save into the installing repo,
ctx.repo.id.
Signed-in pages
To open a page with a connection’s credentials, pass the connection from ctx.org.connections or ctx.user.connections (or s.org.connections in a workflow step) as connection:
import { cookie, defineExtension, defineProvider, object, secrets, string, tool } from "@buildr/sdk";
const portal = defineProvider({
name: "Portal",
hosts: ["portal.example.com"],
auth: {
session: secrets({
label: "Session key",
fields: object({ key: string() }),
request: ({ key }) => cookie("session", key),
}),
},
});
const timecards = tool(
{ description: "Reads this week's timecards", input: object({}) },
async (ctx) => {
const page = await ctx.browser.markdown({
url: "https://portal.example.com/timecards",
connection: ctx.org.connections.portal,
});
return page.markdown;
},
);
export default defineExtension({ org: { connections: { portal } } }, { tools: { timecards } });The credentials stay on the provider’s hosts, as they do for fetch:
- The page’s URL must be on one of the provider’s
hosts, over HTTPS. Otherwise the action rejects withNetworkRefused, status 421. - Header placements, such as
bearer(...)andheader(...), go only with the page’s requests to the provider’s hosts. Its requests to other hosts, such as a CDN, go without them. - Cookie placements become cookies of the page’s browser context, for each of the provider’s hosts that the page requests: host-only,
HttpOnly,Secure, andSameSite=Strict. The page’s scripts can’t read them, and the browser never sends them to another host. A cookie belongs to a host, not to a port. The browser refuses the page’s requests to a port of the host that the provider doesn’t declare, but it can’t see a WebSocket, so a WebSocket that the page opens to another port of the host carries the cookie. - A method that places a credential in the URL’s query, with
query(...), can’t open a page, because the page’s scripts could read the URL. The action rejects withNetworkRefusedand the reasoncredential_query. Read such a service withfetchand the connection’surl()instead. - When a page refuses an OAuth connection’s access token, answering
401, or403witherror="invalid_token"in a Bearer challenge inWWW-Authenticate, Forge renews the token and loads the page once more. When the token can’t be renewed, the refusing page is the answer. - A connection’s secret that a
markdown,links, orcontentanswer shows comes back as its sealed handle: as the page received it, percent-encoded in a URL, escaped in a JSON string, as an API that echoes it writes it, or escaped in the page’s HTML. A secret that the page changes in any other way, such as encoding it in base64, comes back as the page shows it. A screenshot or PDF shows the page as it is, so it can hold any secret the page displays.
Actions with connections run side by side with the call’s other actions. Each page gets only its own connection’s credentials, and its popups, frames, and workers get them as it does.
Sites that sign in with a password
For a walkthrough of a whole extension that reads such a site, see Signed-in sites.
A connection whose method declares signIn signs in to its site, and an action passes it as connection like any other:
const purchases = tool(
{ description: "Reads this year's purchases", input: object({}) },
async (ctx) => {
const page = await ctx.browser.content({
url: "https://portal.example.com/api/purchases?year=2026",
connection: ctx.user.connections.portal,
});
return JSON.parse(page.html);
},
);A JSON API that the session opens doesn’t need a page: fetch sends the same session with the connection’s headers(). See Signed-in sessions on fetch.
Forge keeps the session that a sign-in leaves, so most calls don’t sign in at all:
- Connecting signs in first, as the person submits the connect form, and keeps the cookies that the sign-in left for the provider’s sites. Forge saves them with the connection, encrypted like its credentials. A sign-in that fails saves nothing, and the form shows why. A sign-in that leaves no cookie fails too, because there’s no session to keep.
- Each later action, in the same call or a later one, restores those cookies, as the site set them, into its page’s context before the page loads.
- When a page with a restored session answers
401, or the site sends it to the sign-in page, Forge signs in again once, saves the new session, and loads the page once more. - When a sign-in fails, the connection reads as unhealthy, with the failure’s message, until a sign-in works again.
- When the site refuses the username and password, as after someone changes the password on the site, that call and every later one answer with the refusal without trying the password again, so the site never locks the account for it. Connect again with the right password, and bind the new connection in place of the old one.
A site’s cookies can reach every host of its registrable domain, the domain one registers, such as example.com for www.example.com, and every port of those hosts. So while Forge signs in, and on every page with a restored session, the browser refuses the page’s requests to any host of those domains, or port of one, that the provider doesn’t declare. While it signs in, it also refuses any request but GET, and any navigation, off the provider’s hosts, so the password goes nowhere else. Requests to other sites, such as a CDN on another domain, go on without the session. A signed-in page that loads its scripts or styles from another subdomain of its own site needs that host, or *.example.com, in the provider’s hosts.
Extension code never sees the password or the session’s cookies. A session cookie’s value that a markdown, links, or content answer shows comes back as [signed-in session]. As with other connections, a screenshot or PDF shows the page as it is.
A sign-in counts against the call’s time like any page load. When it fails, the action rejects with ConnectionSignInFailed. Its reason is credentials_refused when the site didn’t accept the username and password, and sign_in_unusable otherwise, and its message says what happened: the site didn’t accept the username and password, the sign-in page has no form that Forge fills, the form asks for a new password, the sign-in went to a host that the provider doesn’t declare, or the sign-in left no cookie. A message names a page by its address without the query, where a form may have put what it sent.
Sessions
An action opens its page, reads it, and closes it. A session keeps one page open across steps, so that a tool can fill a search form, page through the results, and read each page. ctx.browser.session() opens one and answers a BrowserSession:
import { defineExtension, object, string, tool } from "@buildr/sdk";
const searchOrders = tool(
{ description: "Searches the portal's orders", input: object({ q: string() }) },
async (ctx, { q }) => {
const session = await ctx.browser.session({ connection: ctx.user.connections.portal });
await session.goto("https://portal.example.com/orders");
await session.fill("input[name=q]", q);
await session.click("button[type=submit]", { navigation: true });
const pages = [];
for (;;) {
pages.push((await session.markdown()).markdown);
const { outline } = await session.snapshot(); // - button "Next page" [ref=e14]
const next = /button "Next page" \[ref=(e\d+)\]/.exec(outline)?.[1];
if (next === undefined) break;
await session.click(next, { navigation: true });
}
await session.close();
return pages;
},
);session() takes these options, both optional:
| Option | What it does |
|---|---|
connection |
A bound connection whose credentials or signed-in session the page gets, as an action’s page does. See Signed-in pages. |
viewport |
The viewport’s size, { width, height } in CSS pixels, each from 1 to 2048. |
A session’s page has a browser context of its own, so no cookie or storage reaches it from the call’s actions or other sessions. The session closes when you call close(), or when the call ends. A call holds at most four open sessions. A session with a connection that signs in signs in, or restores the connection’s session, as session() opens it.
Steps
Each step acts on the page as it stands, and the session takes one step at a time. A step that names an element takes a target: a ref from the latest snapshot, such as e14, or a CSS selector. Puppeteer’s ::-p-text(...) and ::-p-aria(...) selectors work too.
| Step | What it does | Answers |
|---|---|---|
goto(url) |
Loads the page, which has 20 seconds to load. | { url, status } |
snapshot() |
Reads the page as an outline of roles and names. See Snapshots and refs. | { url, status, outline, truncated } |
click(target, { navigation? }) |
Clicks the element. With navigation: true, it waits up to 20 seconds for the page that the click loads. |
{ url, status } |
fill(target, text) |
Types plain text into a text field or an editable element, replacing what it held. | { url, status } |
select(target, ...values) |
Selects a <select> element’s options by their values. |
{ url, status } |
press(key) |
Presses Enter, Tab, Escape, ArrowUp, or ArrowDown in the focused element. |
{ url, status } |
waitFor(condition, { timeoutMs? }) |
Waits for { selector, state? }, an element that matches the CSS selector, to be "attached" (the default), "visible", or "hidden", or for { url }, the page’s URL to match a pattern in which * matches any characters. It waits 5 seconds by default, and at most 20 seconds. |
{ url, status } |
markdown(), links(), content() |
Read the page as the actions of the same names do. | As the actions answer |
screenshot({ filename, fullPage?, format? }), pdf({ filename, format?, landscape? }) |
Save the page as an attachment, as the actions of the same names do. | An attachment |
close() |
Closes the session. | Nothing |
In every answer, url is the URL that the page is at, and status is the HTTP status that its last navigation answered, or null before the first one.
A step that names an element waits up to 5 seconds for a CSS selector to match. To wait longer, call waitFor first. fill types only plain text. A connection’s sealed handle anywhere in text rejects with NetworkRefused and the reason credential_placement, so a password goes into a site only through the connection’s sign-in.
The session keeps the page to itself. A popup that the page opens closes at once, and a JavaScript dialog, such as alert or confirm, is dismissed.
Snapshots and refs
snapshot() reads the page’s accessibility tree and answers it as an outline, one element a line, indented by depth. Each element that a step acts on, such as a link, a button, or a text field, gets a ref, and a field shows its value:
- heading "Orders"
- StaticText "Search orders"
- searchbox "Search orders" [ref=e1]: "tent"
- button "Search" [ref=e2]
- StaticText "order-1: Two-person tent, $289.00"
- StaticText "order-3: Tent footprint, $39.95"
- StaticText "Page 1 of 2"
- button "Next page" [ref=e3]A ref names its element until the next snapshot or navigation. A step that names a ref from before then rejects with BrowserElementNotFound, so take a new snapshot after the page changes. A snapshot is redacted as a markdown answer is, and is cut at 1,000,000 characters, with truncated set.
Requests, limits, and connections
A session follows the rules of the actions:
- Opening a session and each step, other than
close(), count as one of the call’s requests. - Opening a session, each
goto, and each click withnavigation: truecount against the org’s rate limit, as a page that an action opens does. - Every step answers within the call’s time, as an action does.
gotorefuses a URL that an action refuses. With a connection, the URL must be on the provider’shosts, as an action’s page must be. A page that a restored session sends to the sign-in page, or that answers401, signs in again once ongoto, as an action’s page does.
Isolation and limits
A call’s first action starts a browser for that call alone, and the browser ends when the call ends, so nothing one call’s pages leave running reaches another call. Each action opens its page in a fresh incognito browser context and closes it when the action ends, so no cookie or storage carries over from one action to the next. A call runs up to four actions or session steps at once, and the rest wait their turn.
The browser follows these rules:
- Addresses: A page and every request it makes reach only
http:andhttps:URLs of public addresses. The browser refuseslocalhost, and loopback, private, link-local, and unspecified IP addresses. A check inside the page also refuses a WebSocket to them, but a page’s own scripts can get around it; don’t rely on it to keep a page off private addresses. A name that resolves to a private address is refused too. A local development stage allows private addresses, so that you can open pages served on your machine. - No host allowlist: Unlike
fetch, which reaches only the hosts of the call’s connections, the browser opens any public URL. - Request budget: Each action counts as one of the call’s requests. A tool call makes up to 50
fetchrequests and, separately, up to 50 browser actions. A workflow step’sfetchrequests and browser actions share one budget of 50. Past the budget, an action rejects with aTypeError. - Rate limit: An org’s extensions open at most 60 pages a minute between them. Past that, an action rejects with
BrowserRateLimited. Forge also runs a limited number of browsers at once across every org, and a call that starts one while all are in use rejects withBrowserRateLimitedtoo. - Time: A page has 20 seconds to load, and a screenshot or PDF 10 seconds to render. All of it counts against the call’s 30 seconds, or a workflow step’s
timeout: an action rejects withBrowserFailedat least 2 seconds before the call’s time ends, so your code can still answer, and a page that the call has too little time left to load and read gets less than 20 seconds. Pages of up to about 16 MB of HTML load in about 10 seconds.
Refusals
An action or a session’s step that the browser refuses or can’t finish rejects with a ForgeError, as a ctx.forge call does. Its operation names the action or step, such as browser.markdown or browser.session.click, and status and error carry the refusal:
error._tag |
Status | Cause |
|---|---|---|
BrowserUrlRefused |
400 | The URL isn’t a URL, isn’t http: or https:, or names a private address. url names it, which can be a redirect’s target. When the page’s name resolves to a private address, url names the URL that the browser refused, which can also be a redirect’s target. |
BrowserAttachmentNeedsRepo |
400 | screenshot or pdf ran in a call that runs in no repo, so the file has no repo to be an attachment in. |
AiBrowserLimitReached |
402 | The org has spent its plan’s included monthly AI and browser budget. plan, included_microdollars, resets_at, and message describe the limit. |
BrowserElementNotFound |
404 | A session’s step found no element for its target: no element matched the CSS selector in time, the ref isn’t one of the latest snapshot’s, or the element is gone. Also when the element can’t take the step: fill on what isn’t a text field, select on what isn’t a <select>, or a click on a hidden element. target names the target, and message says why. |
BrowserWaitTimedOut |
408 | A session’s waitFor, or a click’s navigation, didn’t happen in time. message says what it waited for. |
BrowserAttachmentTooLarge |
413 | The screenshot or PDF would be, or came out, larger than 16 MiB. bytes and max_bytes give the sizes. |
ConnectionSignInFailed |
409 | The connection’s sign-in failed, or the site refused its username and password before. connection_id names the connection, reason is credentials_refused or sign_in_unusable, and message says why. |
NetworkRefused |
421 | The connection’s credentials can’t go to the page. refusal.reason says why, as for fetch. |
BrowserRateLimited |
429 | The org’s extensions opened pages too fast, or Forge runs as many browsers as it may at once. A later try succeeds. |
BrowserFailed |
502 | No browser was available, the page’s host couldn’t be reached, the page didn’t load in time, the call ran out of time, or the browser couldn’t read the page or store its file. message says which. When a host can’t be reached, because its name doesn’t resolve, its TLS fails, or it never answers, message names the host. |
screenshot and pdf also reject with the API’s own error when the caller can’t add files to the repo.
An action rejects with a TypeError for options it can’t use, such as a missing url or filename, an object passed as connection that isn’t a bound connection, a call past the request budget, or a call after its workflow step ended. A session rejects with a TypeError too when the call already holds four open sessions, and a step does when its session is closed.
A page that loads with an error status, such as 404 or 500, isn’t a refusal. The action answers the page, and status carries the error. When the error’s response has no body, Chrome shows an error page of its own. The answer’s url is then the URL that answered, and its HTML, Markdown, and links are empty.