AI agents and automation
An agent stuck on Cloudflare Turnstile
Turnstile often shows nothing more than a small box that spins, so a browsing agent waits, clicks it, waits again and never moves on. This guide shows how to recognize the widget in agent snapshots and replace the waiting with one API call at $0.84 per 1,000.
What the agent is actually looking at
Most browsing agents do not read raw HTML. They receive a simplified view: an accessibility tree, a list of interactive elements with numbers, or a screenshot with labels. In those views Cloudflare Turnstile is easy to miss. It lives in a cross origin iframe from challenges.cloudflare.com, so the agent sees one opaque frame element, sometimes with a title along the lines of "Widget containing a Cloudflare security challenge", and perhaps a checkbox it cannot reach inside the frame.
The model then does what a reasonable person would: it clicks the box, waits, sees the form still blocked, and tries again. Each loop costs model tokens and time. Since the widget's real decision is made from background signals, the agent's clicks rarely change the outcome.
Recognize Turnstile reliably
Do the recognition in code that runs after every page change, and report the result to the model in plain words. Three markers cover nearly every page:
- An element with class
cf-turnstileand adata-sitekeythat starts with0x4. - A hidden input named
cf-turnstile-responseinside the form. - An iframe whose
srcpoints atchallenges.cloudflare.com, used when the site renders the widget from JavaScript.
The script below checks them in that order and also collects data-action and data-cdata, which some sites set and which the task needs when they exist. When the widget was rendered by code and the key is not in the DOM, the guide to finding Turnstile parameters shows how to read it from the render call.
// turnstile-probe.js, evaluated in the page after each navigation
() => {
const host = document.querySelector('.cf-turnstile[data-sitekey]');
const input = document.querySelector('input[name="cf-turnstile-response"]');
const frame = document.querySelector('iframe[src*="challenges.cloudflare.com"]');
if (!host && !input && !frame) return { present: false };
return {
present: true,
sitekey: host?.dataset.sitekey ?? null,
action: host?.dataset.action ?? null,
cdata: host?.dataset.cdata ?? null,
alreadyFilled: Boolean(input?.value),
};
}
The alreadyFilled flag matters. Turnstile often passes silently for visitors with good signals, and when the hidden input already has a value there is nothing to do. Solving anyway wastes a task.
Tell the model, then let a tool do the work
Append a short line to the snapshot the agent receives, such as "Cloudflare Turnstile present and unsolved; call solve_turnstile before submitting." Then expose a tool with that name. The model only decides when to call it. The tool runs the probe again, creates the task and fills the field.
// solve-turnstile-tool.mjs (Node.js 18+, Playwright page passed in)
const API = 'https://gatesolver.com';
const nap = (ms) => new Promise(function (wake) { setTimeout(wake, ms); });
async function callApi(route, payload) {
const res = await fetch(`${API}/${route}`, {
method: 'POST',
headers: { 'content-type': 'application/json' }, // createTask and getTaskResult take JSON
body: JSON.stringify({ clientKey: process.env.GATESOLVER_KEY, ...payload }),
});
return res.json();
}
export async function solveTurnstileTool(page, probe) {
const task = { type: 'AntiTurnstileTaskProxyLess', websiteURL: page.url(),
websiteKey: probe.sitekey };
if (probe.action || probe.cdata) task.metadata = { action: probe.action, cdata: probe.cdata };
const started = await callApi('createTask', { task });
if (started.errorId) return `Turnstile solve refused: ${started.errorCode}`;
for (let i = 0; i < 40; i++) {
await nap(3000);
const poll = await callApi('getTaskResult', { taskId: started.taskId });
if (poll.status === 'ready') {
await page.evaluate((freshToken) => {
for (const el of document.querySelectorAll('[name="cf-turnstile-response"]')) el.value = freshToken;
}, poll.solution.token);
return 'Turnstile solved; the form can be submitted now.';
}
if (poll.status === 'failed' || poll.errorId) return 'Turnstile solve failed (not charged). Stop here.';
}
return 'No Turnstile answer in two minutes. Stop here.';
}
Fill the field the site reads
Most forms submit the cf-turnstile-response input with the other fields, and filling it is enough. Some sites instead pass the token to a callback given in data-callback, which then enables the submit button or sends an XHR. If the button stays disabled after the tool returns, read that attribute and call the function with the token in the same page.evaluate. A few single page apps also keep the token in their own state; in that case, watch the network tab for the request that carries it and add the token there.
Resume without starting over
Because the tool changes the live page, the agent's next step is simply the submit it planned. Do not reload the page between solving and submitting: a reload renders a fresh widget and the filled token disappears. The token is also single use and short lived, so solve right before the submit rather than when the page first loads.
If the agent runs a long multi page flow, it may meet Turnstile more than once. That is fine. Each widget needs its own token, and the probe will report the new one after the navigation.
When the problem is not the widget
A full page "Just a moment" screen is not Turnstile in a form. It is the Cloudflare challenge page, and it needs a cf_clearance cookie earned from the same IP the agent uses. That is a different task type, AntiCloudflareTask, with a required proxy. Our guide on diagnosing blocks in a Browser Use agent has a table for telling the two apart.
Limits that keep runs predictable
- Allow at most two solves per page and return a stop message after that.
- Skip the solve when
alreadyFilledis true. - Log the task id with the page URL so a refused submit can be traced.
- Keep the API key in the environment; it never belongs in a prompt.
Turnstile tokens usually come back under 3 seconds, so the pause in the agent run is short. Failed tasks and error replies are free. The Cloudflare Turnstile page lists every field, including metadata.
Wiring the probe into an agent framework
Where the probe runs depends on the framework, but the idea is the same everywhere: after any action that navigates or submits, evaluate the probe and attach the result to the next observation. In a hand written loop that is one line after page.waitForLoadState(). In a framework with custom tools, wrap the framework's navigation tool so it returns the page text plus a status line. Either way, the model reads a fact ("Turnstile present, unsolved") rather than a hint it might overlook.
Keep the status line identical every time. Models pick up a fixed phrase reliably, and a fixed phrase is also easy to search for in logs when you want to know how often the agent met Turnstile on a given site.
Testing before the agent sees it
Run the tool from a small script against a page you control that embeds a Turnstile widget with your own site key. Cloudflare also publishes test site keys that always pass or always fail, which are handy for checking that your field filling and form logic behave, although they do not exercise a real solve. Once the script path works, connect the agent.
Common questions
Why does my agent keep clicking the Turnstile box?
The decision happens from background signals inside a cross origin frame, so clicking from the agent rarely changes it. A token from the API replaces the click.
Does the agent need a proxy to get a Turnstile token?
No. AntiTurnstileTaskProxyLess is solved without one, and the token is placed in your agent page afterwards.
What are data-action and data-cdata for?
They are optional values some sites bind to the widget. When present, send them in the task metadata so the token matches.
The input already has a value. Should I still solve?
No. Turnstile passed on its own for that visit, so the form can be submitted as it is.
Can the same token be used for two submits?
No. Each Turnstile token is valid once and for a short time, so request a new one for each form.
Keep reading
- Cloudflare Turnstile solver$0.84 per 1,000 tasks, answers under 3 seconds.
- Find Turnstile site key, action and cDataWhere Turnstile keeps its site key, action and cData: widget attributes, turnstile.render options and explicit rendering setups.
- Cloudflare TurnstileThe Turnstile widget from Cloudflare, its managed, non-interactive and invisible modes, and the cf-turnstile-response token field.
- How do I give an AI agent a CAPTCHA tool?Wrap createTask and getTaskResult in one function with a clear schema, register it as a tool, and let the agent call it.