Cloudflare Workers
Since 0.2.0, the TypeScript SDK runs inside a Cloudflare Worker. Your agent can launch a browser with Browser Run (formerly Browser Rendering), hit a CAPTCHA or a login, and hand the page to a person.
What works
- Workers, including Durable Objects and the Agents SDK.
- Browser Run (formerly Browser Rendering), through
@cloudflare/puppeteer. Pass thepageas it is. - Deno and Bun, with the same package. They load the Node entry, so binary mode works there as on Node. On Deno and Bun, opt in with
mode: 'in-process'(it needs a relay, as below). - No Node compatibility flag for Unstuck itself.
@cloudflare/puppeteerdoes neednodejs_compat, so keep it on, as Cloudflare's Browser Run guide says. Unstuck adds about 0.5 MB to the bundle (measured by our release dry run).
Deployable examples, each with a Deploy to Cloudflare button: a Durable Object (the pattern below, with /start and /status) and an Agents SDK agent.
A Worker has no local machine, so there is no local link. Takeovers always go through a relay: Unstuck Cloud (one API key) or your own.
Set up
npm install @velmlabs/unstuck @cloudflare/puppeteer
npx wrangler secret put UNSTUCK_API_KEYCreate the key on your dashboard. A Worker has no process.env, so pass the key to new Unstuck() as an option.
wrangler.toml: a browser binding, a Durable Object, and more CPU time (see Timeouts and CPU below):
name = "my-agent"
main = "src/index.ts"
compatibility_date = "2026-11-01"
compatibility_flags = ["nodejs_compat"] # for @cloudflare/puppeteer
[browser]
binding = "BROWSER"
[[durable_objects.bindings]]
name = "PORTAL_AGENT"
class_name = "PortalAgent"
[[migrations]]
tag = "v1"
new_sqlite_classes = ["PortalAgent"]
[limits]
cpu_ms = 300000limits.cpu_ms above the default needs the Workers Paid plan.
Run a takeover in a Durable Object
A takeover can take minutes, so don't hold the caller's request open. Start the work, answer at once, and let the caller ask for the result later. The object stores the outcome (never the link) in its own storage.
import puppeteer from '@cloudflare/puppeteer';
import { Unstuck } from '@velmlabs/unstuck';
import { DurableObject } from 'cloudflare:workers';
interface Env {
BROWSER: Fetcher;
PORTAL_AGENT: DurableObjectNamespace<PortalAgent>;
UNSTUCK_API_KEY: string;
}
type State = { status: 'idle' } | { status: 'running'; startedAt: number } | { status: string; detail?: string };
const TIMEOUT_S = 900;
/** A run older than this was cut short (the object was evicted mid-run and never reached `finally`): start again. */
const STALE_MS = (TIMEOUT_S + 120) * 1000;
export class PortalAgent extends DurableObject<Env> {
async fetch(req: Request): Promise<Response> {
const { pathname } = new URL(req.url);
const state = (await this.ctx.storage.get<State>('state')) ?? { status: 'idle' };
if (req.method === 'POST' && pathname === '/start') {
const running = state.status === 'running' && 'startedAt' in state && Date.now() - state.startedAt < STALE_MS;
if (!running) {
await this.ctx.storage.put('state', { status: 'running', startedAt: Date.now() });
this.ctx.waitUntil(this.run());
return Response.json({ status: 'running' }, { status: 202 });
}
return Response.json(state, { status: 202 }); // already running: don't start a second browser
}
if (req.method === 'GET' && pathname === '/status') return Response.json(state);
return new Response('not found', { status: 404 });
}
async run(): Promise<void> {
let outcome: State = { status: 'failed', detail: 'error' };
let browser: Awaited<ReturnType<typeof puppeteer.launch>> | undefined;
try {
// keep_alive (ms) is Browser Run's inactivity timeout; see Timeouts and CPU below.
browser = await puppeteer.launch(this.env.BROWSER, { keep_alive: 1_200_000 });
const page = await browser.newPage();
await page.goto('https://portal.example.com/login');
const unstuck = new Unstuck({ apiKey: this.env.UNSTUCK_API_KEY });
const result = await unstuck.takeover(page, {
reason: 'Log in with your 2FA code',
timeoutS: TIMEOUT_S,
alerts: 'required', // fail at once if Unstuck Cloud can't accept the link for at least one paired phone
});
outcome = { status: result.status, detail: result.detail };
if (result.status === 'resolved') {
// Carry on in the same page: it has the person's login. Do your work here.
}
} finally {
await this.ctx.storage.put('state', outcome);
await browser?.close();
// Or call a webhook with `outcome` here, so the caller doesn't have to poll.
}
}
}
export default {
async fetch(req: Request, env: Env): Promise<Response> {
return env.PORTAL_AGENT.get(env.PORTAL_AGENT.idFromName('portal-check')).fetch(req);
},
};Call POST /start, then GET /status until it is no longer running.
A Durable Object stays alive while the takeover holds its sockets open; ctx.waitUntil is there for clarity, and an alarm is a sturdier trigger if you need retries.
The link goes to your paired phones (see Phone alerts below). To send it somewhere else as well, pass an onLink handler. Without one, Unstuck logs with console.log, which ends up in Workers Logs, so it keeps the link out of the log when it can:
- If at least one paired phone got the link, it logs
Unstuck: a human is needed (<reason>), link sent to <N> paired phone(s) (session <id>), with no link in it. - If no phone got it, it logs the full link as the fallback. With
alerts: 'required'the takeover has already failed withalert_failed, so nothing is logged. - With your own relay, or
alerts: false, the log is the only channel, so the full link is logged at once.
Workers Logs come too late for the link. Workers Logs and wrangler tail show a Durable Object's logs only when the invocation that wrote them ends. For a takeover started as above (a request with ctx.waitUntil, or an alarm), that is after the takeover, so a logged link reaches you once it is no use. Rely on phone alerts (Unstuck Cloud), or pass an onLink that sends the link at once, for example to an incoming webhook. The examples do this with an optional LINK_WEBHOOK_URL secret. With a self-hosted relay, which sends no phone alerts, use the webhook.
If your onLink throws (or, when it is async, rejects), Unstuck logs one line with console.error (without the link) and the takeover goes on.
With the Agents SDK, put the body of run() in a method of your agent and start it with this.schedule(0, 'run'). A Workflow step works too (below).
Don't await unstuck.close() inside onLink. close() waits for running takeovers, including the one that called it.
Your own relay
Pass relay and agentKey instead of apiKey:
const unstuck = new Unstuck({ relay: this.env.UNSTUCK_RELAY_URL, agentKey: this.env.UNSTUCK_AGENT_KEY });UNSTUCK_RELAY_URL is the wss:// address of your relay (ws:// is accepted only for localhost). The relay on Cloudflare Workers can run on the same Cloudflare account: use its workers.dev address as a plain wss:// URL, and add global_fetch_strictly_public to your agent's compatibility_flags. Without it, Cloudflare refuses the Worker-to-Worker request with error 1042 and the relay never sees the agent. Service bindings are not supported yet. A self-hosted relay sends no phone alerts, so alerts: 'required' throws UnstuckConfigError there; send the link with your own onLink instead (see the note on Workers Logs above).
Session memory in a Worker
Unstuck Browser can remember a site a person got past, so the next request goes straight through. A Worker has no file system, so give wrap a store in the Durable Object's own storage. It survives requests and restarts of the object, and the hourly limit of person-checks is kept there too:
import { siteOf, type SessionStore, type SiteRecord, type StoredCookie } from '@velmlabs/unstuck';
const RATE_WINDOW_MS = 60 * 60 * 1000;
const live = (c: StoredCookie, now: number) => !(c.expires > 0 && c.expires * 1000 <= now);
const cookieKey = (c: StoredCookie) => `${c.name}\u0000${c.domain}\u0000${c.path}`;
type Stored = Omit<SiteRecord, 'site'>;
/** Sites live under `site:<site>`, the hourly rescue times under `rescues`. */
export function durableObjectSessionStore(storage: DurableObjectStorage, o: { now?: () => number } = {}): SessionStore {
const now = o.now ?? Date.now;
return {
async load(site) {
const s = siteOf(site);
const rec = await storage.get<Stored>(`site:${s}`);
const cookies = (rec?.cookies ?? []).filter((c) => live(c, now()));
return rec && cookies.length > 0 ? { site: s, userAgent: rec.userAgent, solvedAt: rec.solvedAt, cookies } : null;
},
async save(site, cookies, userAgent) {
const key = `site:${siteOf(site)}`;
await storage.transaction(async (txn) => {
const merged = new Map(((await txn.get<Stored>(key))?.cookies ?? []).map((c) => [cookieKey(c), c]));
for (const c of cookies) merged.set(cookieKey(c), c);
const kept = [...merged.values()].filter((c) => live(c, now()));
if (kept.length > 0) await txn.put(key, { userAgent, solvedAt: now(), cookies: kept } satisfies Stored);
else await txn.delete(key);
});
},
async forget(site) {
await storage.delete(`site:${siteOf(site)}`);
},
async forgetAll() {
const keys = [...(await storage.list({ prefix: 'site:' })).keys()];
if (keys.length > 0) await storage.delete(keys);
},
updateRescues: (fn) =>
storage.transaction(async (txn) => {
const recent = ((await txn.get<number[]>('rescues')) ?? []).filter((t) => t > now() - RATE_WINDOW_MS);
const next = fn(recent);
await txn.put('rescues', next);
return [...next];
}),
};
}const page = unstuck.wrap(await browser.newPage(), { remember: true, store: durableObjectSessionStore(this.ctx.storage) });Without a store, the Worker entry keeps remembered sites in memory, for the life of the Unstuck client.
Where to run it
Use a Durable Object. A takeover keeps a WebSocket to the relay and a connection to the browser open while a person works, and that can take minutes. A Durable Object can hold them. The Agents SDK is built on Durable Objects, so an agent that extends Agent can call takeover() the same way. Start it without holding a request open, as in the example.
Workflows work too. One user runs takeovers inside a Workflow step. Three settings matter:
const result = await step.do(
'read page',
{ timeout: '20 minutes', retries: { limit: 0, delay: 0 } },
async () => {
// launch, goto, takeover, read, close (as above); return only what you need
},
);- Set
timeoutyourself. The default step timeout is 10 minutes, shorter than a long takeover. - Set
retries: { limit: 0 }. A retry would start a second takeover and ping the person twice. - Use a new instance id for every launch (for example
crypto.randomUUID()). A job that runs again after a takeover can't reuse its earlier id.
This pattern comes from a user's report. We haven't run it in our own tests.
A plain fetch handler is not a good home for a multi-minute wait. Start the work in a Durable Object or a Workflow instead.
Timeouts and CPU
Two timers run during a takeover:
- The takeover's timeout:
timeoutS, 600 seconds by default. When it passes,takeover()returnstimed_out. - Browser Run's
keep_alive: an inactivity timeout (60 seconds by default, up to 20 minutes at the time of writing: check Cloudflare's limits page). If it passes, Browser Run closes the browser and the takeover ends withpage_closed.
In a Worker, Unstuck pings the page every 60 seconds for the whole takeover, so the session stays active while a person works. That means timeoutS may be longer than keep_alive. We still suggest a generous keep_alive, because the ping needs the Worker to stay running.
CPU time. Streaming the screen and encrypting each frame use CPU inside your Worker. For a takeover that lasts minutes, raise limits.cpu_ms (the example above uses the 5-minute maximum). We haven't published measurements of how much CPU a takeover uses. Start high, then lower it once you've seen your own numbers.
Phone alerts
With an apiKey, the link is also sent to your paired phones, as on any other runtime. See Phone alerts to pair a phone and turn alerts on for the key.
For an agent that runs with nobody watching, pass alerts: 'required'. If Unstuck Cloud can't accept the link for at least one paired phone, the takeover ends at once as failed with detail alert_failed, instead of waiting for its timeout. That happens when:
- alerts are not enabled for the key;
- no phone is paired;
- the link could not be sealed for any phone;
- Unstuck Cloud answered with an error, or didn't answer within 10 seconds.
It does not fire once a person has already joined through a link your own onLink sent.
Pass alerts: false to skip the alert for one takeover. The default is to send it when the key allows alerts.
If your code intercepts requests
If you call page.setRequestInterception(true), it works alongside Unstuck's page lock. Both use the DevTools Fetch domain, each on its own session. We checked this with a local Chromium. We haven't checked it on Browser Run yet.
Options and results
Pass options to new Unstuck({ … }). The most used:
| Option | Meaning |
|---|---|
apiKey |
Unstuck Cloud API key |
relay, agentKey |
Your own relay and its key. Not combinable with apiKey |
cloudRelay, cloudApi |
Override Cloud's relay and API addresses. Only with apiKey |
viewerUrl |
Override the viewer address in takeover links (https://) |
timeoutS |
Default takeover timeout, in seconds (default 600) |
requireCode |
Also ask for a 6-digit code. Needs an onLink that sends it by another channel |
onLink |
Called with the link when a person is needed. Default: see above |
mode |
'in-process' on Node, Deno or Bun, to use this mode there. Workers use it already ('binary' there throws) |
takeover(page, { reason, timeoutS, alerts, allowedSites, requireCode }) resolves with a status and sometimes a detail:
status |
detail |
Meaning |
|---|---|---|
resolved |
The person tapped Done | |
cancelled |
cant_solve, or their note |
The person tapped Can't solve |
cancelled |
engine_closed |
You called close() |
timed_out |
Nobody finished in time | |
failed |
page_closed |
The page closed, or Browser Run dropped the connection |
failed |
alert_failed |
alerts: 'required', and Unstuck Cloud couldn't accept the link for any paired phone |
failed |
relay_unauthorized |
The relay refused the key |
failed |
internal_error: … |
An unexpected engine error; please report it |
takeover() rejects only for setup mistakes: UnstuckConfigError when the options don't fit together (for example apiKey with relay, no relay at all, mode: 'binary' in a Worker, or a relay that isn't wss://), and TypeError for requireCode without an onLink handler. The whole option list and every error message: the SDK README.
Troubleshooting
in a Worker, Unstuck needs a relay: set apiKey or relay + agentKey. No relay was configured. A Worker does not read environment variables, so pass apiKey, or relay and agentKey, to new Unstuck(). Check that the secret is bound to the Worker (wrangler secret put).
relay_unauthorized. The relay refused your key. Check the key on your dashboard, or the agent key on your own relay.
alert_failed. You asked for alerts: 'required' and Unstuck Cloud couldn't accept the link for any paired phone. Pair a phone and turn on Can alert my phones for the key (Phone alerts). Or drop 'required'.
The viewer shows "Waiting for the page…" and never a picture. The agent sends a screenshot as the first frame, so this usually clears in a second or two. If it stays, check that the browser is still open.
A black screen on 0.1.x. If you built on @velmlabs/unstuck-core 0.1.x yourself, the viewer could stay black in a Worker. Upgrade to 0.2.0 and use the SDK.
page_closed after a few minutes. Browser Run closed the browser. Raise keep_alive, and check that the Worker was still running.