Skip to content

Add capabilities

Browser tools

Use WebSearch.native({ tool }) to put a provider’s hosted search tool in the agent’s own model call. For a known page, a capture returns one bounded result; a browser session keeps a live page for navigation and input. Your application owns destination access, credentials, and cleanup.

Need Capability Host setup
Render content, links, or selector groups PageCapture with Quick Actions Cloudflare browser binding
Capture a page from Node or a Worker PageCapture with REST Account ID, redacted token, Effect HttpClient
Take an ephemeral PNG screenshot PageScreenshot with Quick Actions Cloudflare browser binding
Let an agent navigate and interact with websites BrowserUse + Code Mode + Browser Sessions Worker Loader, browser binding, private lifecycle credentials
import {
class CapturePageMarkdown

Return the rendered page converted to Markdown.

CapturePageMarkdown
,
class PageCapture

Stateless page-capture port. One capture is one pass: the adapter owns no session, replay, approval, or Thread semantics, identifies its isolation posture honestly (CAP-010), enforces or rejects every requested limit and policy, and returns exactly one bounded output. Capture results are untrusted input to whatever reads them.

PageCapture
,
class PageCaptureLimits

Limits an adapter must either enforce or reject. Bytes are UTF-8 encoded.

PageCaptureLimits
,
class PageCaptureRequest

Schema-first page capture request: one target, one action, one output.

PageCaptureRequest
,
class PageResourcePolicy

Request egress policy for the render. Rejected resource types are never fetched; when request patterns are given, only matching navigation, redirect, and subresource requests are allowed. Calling capabilities own the capture-target allowlist and project it into this policy so rendered JavaScript cannot escape the same construction-time authority.

PageResourcePolicy
,
class PageUrlTarget

Capture a URL after a full render, the common case.

PageUrlTarget
,
} from "@yielded/agent/page-capture";
import {
import Effect
Effect
} from "effect";
const
const readPage: Effect.Effect<PageCaptureResult, PageCaptureRateLimitedError | PageCaptureNavigationError | PageCaptureUnsupportedError | PageCaptureOutputLimitError | PageCaptureProtocolError, PageCapture>
readPage
=
import Effect
Effect
.
const gen: <Effect.Effect<PageCaptureResult, PageCaptureRateLimitedError | PageCaptureNavigationError | PageCaptureUnsupportedError | PageCaptureOutputLimitError | PageCaptureProtocolError, never> | Effect.Effect<{
readonly capture: (request: PageCaptureRequest) => Effect.Effect<PageCaptureResult, PageCaptureError>;
}, never, PageCapture>, PageCaptureResult>(f: () => Generator<...>) => Effect.Effect<...> (+1 overload)

Provides a way to write effectful code using generator functions, simplifying control flow and error handling.

When to use

Use when you want to write effectful code that looks and behaves like synchronous code, while still handling asynchronous tasks, errors, and complex control flow such as loops and conditions.

Generator functions work similarly to async/await but keep errors, requirements, and interruption in the Effect type. You can yield* values from effects and return the final result at the end.

Example (Sequencing effects with generators)

import { Data, Effect } from "effect"
class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
const addServiceCharge = (amount: number) => amount + 1
const applyDiscount = (
total: number,
discountRate: number
): Effect.Effect<number, DiscountRateError> =>
discountRate === 0
? Effect.fail(new DiscountRateError())
: Effect.succeed(total - (total * discountRate) / 100)
const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
const fetchDiscountRate = Effect.promise(() => Promise.resolve(5))
export const program = Effect.gen(function*() {
const transactionAmount = yield* fetchTransactionAmount
const discountRate = yield* fetchDiscountRate
const discountedAmount = yield* applyDiscount(
transactionAmount,
discountRate
)
const finalAmount = addServiceCharge(discountedAmount)
return `Final amount to charge: ${finalAmount}`
})
await Effect.runPromise(program) // => "Final amount to charge: 96"

@stability ― stable

@category ― constructors

@since ― 2.0.0

gen
(function* () {
const
const capture: {
readonly capture: (request: PageCaptureRequest) => Effect.Effect<PageCaptureResult, PageCaptureError>;
}
capture
= yield*
class PageCapture

Stateless page-capture port. One capture is one pass: the adapter owns no session, replay, approval, or Thread semantics, identifies its isolation posture honestly (CAP-010), enforces or rejects every requested limit and policy, and returns exactly one bounded output. Capture results are untrusted input to whatever reads them.

PageCapture
;
return yield*
const capture: {
readonly capture: (request: PageCaptureRequest) => Effect.Effect<PageCaptureResult, PageCaptureError>;
}
capture
.
capture: (request: PageCaptureRequest) => Effect.Effect<PageCaptureResult, PageCaptureError>
capture
(
class PageCaptureRequest

Schema-first page capture request: one target, one action, one output.

PageCaptureRequest
.
BottomWithoutNew<unknown, unknown, unknown, unknown, Declaration, decodeTo<declareConstructor<PageCaptureRequest, { readonly engine: "chromium" | "kitesurf"; readonly action: { readonly _tag: "CapturePageMarkdown"; } | { ...; } | { ...; } | { ...; }; ... 4 more ...; readonly resourcePolicy?: { ...; } | undefined; }, readonly [...], { ...; }>, Struct<...>, never, never>, ... 8 more ..., "required">.make(input: {
readonly engine: "chromium" | "kitesurf";
readonly action: CapturePageMarkdown | CapturePageContent | CapturePageLinks | CapturePageScrape;
readonly target: PageUrlTarget | PageHtmlTarget;
readonly limits: PageCaptureLimits;
readonly navigation?: PageNavigationOptions | undefined;
readonly viewport?: PageViewport | undefined;
readonly resourcePolicy?: PageResourcePolicy | undefined;
}, options?: MakeOptions): PageCaptureRequest

Constructs a value from the make input representation synchronously.

When to use

Use when constructor input is trusted or when validation failure should abort with a thrown Error.

Details

Applies constructor defaults and type-side validation according to MakeOptions.

Gotchas

Throws an Error with the schema issue in its cause when validation fails. Schema validation failures use the generic message "Schema validation failed"; format the cause explicitly with SchemaIssue.makeFormatterDefault() when human-readable details are needed. Causes that contain defects, interruptions, or other non-schema reasons throw with the underlying Cause attached instead.

@see ― BottomWithoutNew.makeOption — construct synchronously and discard validation details

@see ― BottomWithoutNew.makeEffect — construct through Effect when validation failure should stay in the error channel

make
({
target: PageUrlTarget | PageHtmlTarget
target
:
class PageUrlTarget

Capture a URL after a full render, the common case.

PageUrlTarget
.
BottomWithoutNew<unknown, unknown, unknown, unknown, Declaration, decodeTo<declareConstructor<PageUrlTarget, { readonly _tag: "PageUrlTarget"; readonly url: string; }, readonly [TaggedStruct<"PageUrlTarget", { readonly url: NonEmptyString; }>], { ...; }>, TaggedStruct<...>, never, never>, ... 8 more ..., "required">.make(input: {
readonly url: string;
readonly _tag?: "PageUrlTarget" | undefined;
}, options?: MakeOptions): PageUrlTarget

Constructs a value from the make input representation synchronously.

When to use

Use when constructor input is trusted or when validation failure should abort with a thrown Error.

Details

Applies constructor defaults and type-side validation according to MakeOptions.

Gotchas

Throws an Error with the schema issue in its cause when validation fails. Schema validation failures use the generic message "Schema validation failed"; format the cause explicitly with SchemaIssue.makeFormatterDefault() when human-readable details are needed. Causes that contain defects, interruptions, or other non-schema reasons throw with the underlying Cause attached instead.

@see ― BottomWithoutNew.makeOption — construct synchronously and discard validation details

@see ― BottomWithoutNew.makeEffect — construct through Effect when validation failure should stay in the error channel

make
({
url: string
url
: "https://example.com/" }),
action: CapturePageMarkdown | CapturePageContent | CapturePageLinks | CapturePageScrape
action
:
class CapturePageMarkdown

Return the rendered page converted to Markdown.

CapturePageMarkdown
.
BottomWithoutNew<unknown, unknown, unknown, unknown, Declaration, decodeTo<declareConstructor<CapturePageMarkdown, { readonly _tag: "CapturePageMarkdown"; }, readonly [TaggedStruct<"CapturePageMarkdown", {}>], { ...; }>, TaggedStruct<...>, never, never>, ... 8 more ..., "required">.make(input: void | {
readonly _tag?: "CapturePageMarkdown" | undefined;
}, options?: MakeOptions): CapturePageMarkdown

Constructs a value from the make input representation synchronously.

When to use

Use when constructor input is trusted or when validation failure should abort with a thrown Error.

Details

Applies constructor defaults and type-side validation according to MakeOptions.

Gotchas

Throws an Error with the schema issue in its cause when validation fails. Schema validation failures use the generic message "Schema validation failed"; format the cause explicitly with SchemaIssue.makeFormatterDefault() when human-readable details are needed. Causes that contain defects, interruptions, or other non-schema reasons throw with the underlying Cause attached instead.

@see ― BottomWithoutNew.makeOption — construct synchronously and discard validation details

@see ― BottomWithoutNew.makeEffect — construct through Effect when validation failure should stay in the error channel

make
({}),
engine: "chromium" | "kitesurf"
engine
: "chromium",
limits: PageCaptureLimits
limits
:
class PageCaptureLimits

Limits an adapter must either enforce or reject. Bytes are UTF-8 encoded.

PageCaptureLimits
.
BottomWithoutNew<unknown, unknown, unknown, unknown, Declaration, decodeTo<declareConstructor<PageCaptureLimits, { readonly maxOutputBytes: number; }, readonly [Struct<{ readonly maxOutputBytes: Int; }>], { ...; }>, Struct<...>, never, never>, ... 8 more ..., "required">.make(input: {
readonly maxOutputBytes: number;
}, options?: MakeOptions): PageCaptureLimits

Constructs a value from the make input representation synchronously.

When to use

Use when constructor input is trusted or when validation failure should abort with a thrown Error.

Details

Applies constructor defaults and type-side validation according to MakeOptions.

Gotchas

Throws an Error with the schema issue in its cause when validation fails. Schema validation failures use the generic message "Schema validation failed"; format the cause explicitly with SchemaIssue.makeFormatterDefault() when human-readable details are needed. Causes that contain defects, interruptions, or other non-schema reasons throw with the underlying Cause attached instead.

@see ― BottomWithoutNew.makeOption — construct synchronously and discard validation details

@see ― BottomWithoutNew.makeEffect — construct through Effect when validation failure should stay in the error channel

make
({
maxOutputBytes: number
maxOutputBytes
: 256 * 1024 }),
resourcePolicy?: PageResourcePolicy | undefined
resourcePolicy
:
class PageResourcePolicy

Request egress policy for the render. Rejected resource types are never fetched; when request patterns are given, only matching navigation, redirect, and subresource requests are allowed. Calling capabilities own the capture-target allowlist and project it into this policy so rendered JavaScript cannot escape the same construction-time authority.

PageResourcePolicy
.
BottomWithoutNew<unknown, unknown, unknown, unknown, Declaration, decodeTo<declareConstructor<PageResourcePolicy, { readonly rejectResourceTypes?: readonly ("document" | "stylesheet" | "image" | "media" | "font" | "script" | ... 6 more ... | "other")[] | undefined; readonly allowRequestPatterns?: readonly string[] | undefined; }, readonly [...], { ...; }>, Struct<...>, never, never>, ... 8 more ..., "required">.make(input: void | {
readonly rejectResourceTypes?: readonly ("document" | "stylesheet" | "image" | "media" | "font" | "script" | "texttrack" | "xhr" | "fetch" | "eventsource" | "websocket" | "manifest" | "other")[] | undefined;
readonly allowRequestPatterns?: readonly string[] | undefined;
}, options?: MakeOptions): PageResourcePolicy

Constructs a value from the make input representation synchronously.

When to use

Use when constructor input is trusted or when validation failure should abort with a thrown Error.

Details

Applies constructor defaults and type-side validation according to MakeOptions.

Gotchas

Throws an Error with the schema issue in its cause when validation fails. Schema validation failures use the generic message "Schema validation failed"; format the cause explicitly with SchemaIssue.makeFormatterDefault() when human-readable details are needed. Causes that contain defects, interruptions, or other non-schema reasons throw with the underlying Cause attached instead.

@see ― BottomWithoutNew.makeOption — construct synchronously and discard validation details

@see ― BottomWithoutNew.makeEffect — construct through Effect when validation failure should stay in the error channel

make
({
allowRequestPatterns?: readonly string[] | undefined
allowRequestPatterns
: ["^https://example\\.com(?:[/?#]|$)"],
}),
}),
);
});

Supply browserQuickActionCaptureLayer with BrowserQuickActionBrowserBinding.layer({ browser }) in a Worker, or use browserRestCaptureLayer({ accountId, apiToken }) with an Effect HTTP client. Applications compose their own native Effect AI tools over this port; the sandbox example shows read, scrape, and screenshot tools.

Set the target, action, engine, resource policy, and response byte limit before dispatch. PageCapture returns rendered HTML, Markdown, links, or grouped selector scrape results. Choose an engine per operation; unsupported choices fail explicitly. There is no automatic engine fallback. A resource URL allowlist does not provide connection-time private-network isolation. For already approved HTML, use PageHtmlTarget and deny browser subrequests when the workload requires no further egress.

The capture byte limit is separate from the Agent’s 50 KiB default tool-result budget. Use saved tool outputs for follow-up reads of larger captures. For multiple pages, the application owns traversal and its host authorization, page/depth limits, total bytes, and deadline.

For rendered pages, use a finite waitForSelector for the content you need. Navigation completion alone may return only a loading shell. Treat rendered text as untrusted, and distinguish missing content from evidence that something is absent.

PageScreenshot returns PNG bytes from a separate ephemeral pass. Its request fixes the engine, viewport, resource policy, navigation options, and byte limit. Authorize the URL before capture and recheck authority before publishing the result. Interrupting local waiting for a Quick Action does not confirm termination of its unresolved remote browser request.

InteractiveBrowser owns one bounded pass. Its immutable network policy makes the distinction explicit: ExactHosts is a URL allowlist, not connection-time private-network isolation. PublicWeb requires that isolation and is unsupported by the Cloudflare adapter. Unrestricted opts out of both host and private-network containment; only trusted host code should select it.

BrowserUse gives the model one Code Mode tool. The model writes JavaScript for the website it actually encounters, using Chrome DevTools Protocol (CDP) to inspect the DOM, evaluate page JavaScript, navigate, or send native input. There is no framework classifier deciding which elements are actionable.

import {
import BrowserUse
BrowserUse
} from "@yielded/agent";
import {
import Toolkit
Toolkit
} from "effect/ai";
const
const browser: CodeModeDefinition<"browser_execute", {
cdp: {
send: Tool<"browser_cdp_send", {
readonly parameters: Struct<{
readonly method: String;
readonly params: optionalKey<$Record<String, Codec<Json, Json, never, never>>>;
readonly targetId: optionalKey<NonEmptyString>;
readonly frameId: optionalKey<NonEmptyString>;
}>;
readonly success: Codec<Json, Json, never, never>;
readonly failure: Union<readonly [typeof BrowserUse.BrowserUseError, typeof BrowserUse.BrowserUsePolicyError]>;
readonly failureMode: "return";
}, never>;
tabs: Tool<...>;
frames: Tool<...>;
newTab: Tool<...>;
closeTab: Tool<...>;
};
}, never>
browser
=
import BrowserUse
BrowserUse
.
const make: (options?: {
readonly limits?: CodeExecutionLimits;
readonly maxEgressBytes?: number;
}) => CodeModeDefinition<"browser_execute", {
cdp: {
send: Tool<"browser_cdp_send", {
readonly parameters: Struct<{
readonly method: String;
readonly params: optionalKey<$Record<String, Codec<Json, Json, never, never>>>;
readonly targetId: optionalKey<NonEmptyString>;
readonly frameId: optionalKey<NonEmptyString>;
}>;
readonly success: Codec<...>;
readonly failure: Union<...>;
readonly failureMode: "return";
}, never>;
tabs: Tool<...>;
frames: Tool<...>;
newTab: Tool<...>;
closeTab: Tool<...>;
};
}, never>

One Code Mode tool. Generated code chooses how to inspect and operate each website.

make
();
const
const tools: Toolkit.Toolkit<{
readonly browser_execute: CodeModeTool<"browser_execute">;
}>
tools
=
import Toolkit
Toolkit
.
const make: <[CodeModeTool<"browser_execute">]>(tools_0: CodeModeTool<"browser_execute">) => Toolkit.Toolkit<{
readonly browser_execute: CodeModeTool<"browser_execute">;
}>

Creates a new toolkit from the specified tools.

Details

This is the primary constructor for creating toolkits. It accepts multiple tools and organizes them into a toolkit that can be provided to AI language models.

Example (Creating a toolkit)

import { Effect, Schema } from "effect"
import { Tool, Toolkit } from "effect/ai"
const GetCurrentTime = Tool.make("GetCurrentTime", {
description: "Get the current timestamp",
success: Schema.Number
})
const GetWeather = Tool.make("get_weather", {
description: "Get weather information",
parameters: Schema.Struct({ location: Schema.String }),
success: Schema.Struct({
temperature: Schema.Number,
condition: Schema.String
})
})
const toolkit = Toolkit.make(GetCurrentTime, GetWeather)
const ready = toolkit.pipe(Effect.provide(toolkit.toLayer({
GetCurrentTime: () => Effect.succeed(0),
get_weather: () => Effect.succeed({ temperature: 20, condition: "clear" })
})))
Object.keys((await Effect.runPromise(ready)).tools) // => ["GetCurrentTime", "get_weather"]

@stability ― unstable

@category ― constructors

@since ― 4.0.0

make
(
const browser: CodeModeDefinition<"browser_execute", {
cdp: {
send: Tool<"browser_cdp_send", {
readonly parameters: Struct<{
readonly method: String;
readonly params: optionalKey<$Record<String, Codec<Json, Json, never, never>>>;
readonly targetId: optionalKey<NonEmptyString>;
readonly frameId: optionalKey<NonEmptyString>;
}>;
readonly success: Codec<Json, Json, never, never>;
readonly failure: Union<readonly [typeof BrowserUse.BrowserUseError, typeof BrowserUse.BrowserUsePolicyError]>;
readonly failureMode: "return";
}, never>;
tabs: Tool<...>;
frames: Tool<...>;
newTab: Tool<...>;
closeTab: Tool<...>;
};
}, never>
browser
.
CodeModeDefinition<"browser_execute", { cdp: { send: Tool<"browser_cdp_send", { readonly parameters: Struct<{ readonly method: String; readonly params: optionalKey<$Record<String, Codec<Json, Json, never, never>>>; readonly targetId: optionalKey<...>; readonly frameId: optionalKey<...>; }>; readonly success: Codec<...>; readonly failure: Union<...>; readonly failureMode: "return"; }, never>; tabs: Tool<...>; frames: Tool<...>; newTab: Tool<...>; closeTab: Tool<...>; }; }, never>.tool: CodeModeTool<"browser_execute">

The ordinary Effect AI Tool to include in the model-facing Toolkit.

tool
);

Provide BrowserUse.layer with the scoped adapter from @yielded/agent-platform-cloudflare/browser-use, then pass those handlers to CloudflareCodeMode.layer(browser, { loader, handlers }). The adapter borrows an existing BrowserSession; the executor runs each program in a fresh Worker with no ambient network, bindings, or secrets. The browser remains attached across programs.

Inside a program, cdp.send({ method, params, targetId?, frameId? }) sends a CDP command. cdp.tabs({}) discovers pages in the session’s context, cdp.newTab({}) opens a blank page, and cdp.closeTab({ targetId }) closes a secondary page. Omit targetId to address the original page. Browser and Target protocol domains are reserved for the host. Use cdp.frames({ targetId? }) to discover frames, including cross-origin frames, and frameId to route commands to a frame’s session. Page.createIsolatedWorld supplies an execution context for evaluating JavaScript in that frame.

Successful responses retain the CDP shape: Runtime.evaluate with returnByValue: true returns the value at response.result.value, and Runtime.getExceptionDetails returns its diagnostic metadata unchanged. Page execution exceptions reject cdp.send with BrowserUseError code evaluation, carrying the page diagnostic into Code Mode’s failure report unless the program catches it. An evaluation may have changed the page before throwing; inspect current state before further actions. The default tool guidance asks the model to correct inspection errors with a smaller program and continue authorized work.

For example, the model can inspect a page with:

async () => {
const response = await cdp.send({
method: "Runtime.evaluate",
params: {
expression: "document.body.innerText.slice(0, 6000)",
returnByValue: true,
awaitPromise: true,
},
});
return response;
};

The host authorizes every command with current page and target metadata and sets command, tab, and result limits. Set the adapter’s maxCommands: null to let the host-owned session lifetime bound work without an additional command-count cutoff. Code Mode adds execution and aggregate output limits. A result limit does not bound the upstream CDP transfer; programs should request small results. CDP events are not streamed to the program; inspect state or use bounded page-side conditions.

Arbitrary page JavaScript is a broad capability: a URL check or a tool named “read” cannot guarantee read-only behavior, recipient restrictions, or safe checkout. Enforce network access outside generated code and authorize the task’s actual capabilities. Page content remains untrusted. A completed command does not prove the website accepted an order, login, or upload; verify the site’s outcome independently. Never replay uncertain input automatically.

BrowserSessions keeps a private reference to one exact browser, context, and page while Attempts borrow scoped attachments. The owner serializes attachments and retains responsibility for closing the browser at completion, cancellation, or expiry. Disconnecting an attachment preserves the remote session; a reference cannot recreate an expired page.

Creation option Default Meaning
maxElapsedMillis Required positive safe integer Fixed session expiry
keepAliveMillis 600_000 Provider idle allowance; maximum 600_000
commandTimeoutMillis 30_000 Command limit, also bounded by remaining session lifetime

Keep session references and Live View URLs private. Human takeover requires exclusive control; read-only viewers can still see page data. Expiry of a viewing URL limits new connections, not already connected viewers.

BrowserSessionError.cause and BrowserUseError.cause retain original native failures for trusted in-process inspection. These properties are non-enumerable and excluded from error Schemas and JSON. Use FailureDiagnostic.capture(error) before crossing a transport boundary to retain a bounded private diagnostic; keep that diagnostic out of model responses and public logs.

session.fillCredential resolves host-owned material through BrowserCredentialAccess, then fills supported native controls without submitting the form. The host authorizes the actual page, frame, and form-recipient origins. Authorize filling itself: input handlers may send data immediately.

For private user entry, prepare the form before showing it to the user:

const binding = yield * session.prepareCredential(form);
// Retain only form, binding, expiry, and a one-use request ID.
// After private submission, atomically consume the request before filling.
const result = yield * session.fillCredential({ ...form, credential: requestId, binding });

Accept values through a separate authenticated endpoint and supply an invocation-scoped BrowserCredentialAccess Layer there. Its resolver can use the submitted values instead of a vault. Keep material out of conversation input, history, checkpoints, and telemetry. The binding pins the page, document, form, and controls across attachments; a changed target requires a fresh request. The host owns request expiry and one-use consumption. Retain only the outcome after filling; process loss or an uncertain result never permits replaying the values.

Credentials stay out of the fill API’s results and telemetry, but generated page JavaScript can read filled fields and the website may echo values in later observations or screenshots. CDP also has access to browser cookies. Your disclosure policy must cover those outputs. Uncertain fills or actions must not be blindly retried; confirmed browser cleanup does not undo website effects.

The browser-speed example shows a runnable interactive application. Consult the session API for attachment and cleanup details.