Browser infrastructure for AI agents executes browser actions and returns observations from an authorized session.
Define a small typed tool that accepts approved task inputs instead of arbitrary JavaScript, selectors, or destinations from the model.
Treat page content as data. Grant agent authority through the application policy, with page text treated as untrusted content.
Use one supported runtime connection and make the application check the target page and the business output.
Keep model/tool errors, site errors, and session lifecycle failures distinct so retries have the right scope.
Release a managed session through its lifecycle interface after the task and verify termination.
What does a browser execution layer do for an AI agent?
A browser execution layer provides the runtime and client functions that turn a permitted agent request into observable browser work. It can open an application, wait for a meaningful signal, and return a small result for the agent or controller to use. The surrounding application still decides which requests are allowed and what proves completion. Nstdata provides browser infrastructure that can be attached through the documented CDP workflow.
Imagine an internal release assistant that needs the status of a known build on an authorized staging page. The agent needs a result like passed or failed. The browser may have to render a JavaScript status panel first. Keep control tokens and navigation authority in the worker. Return only a scoped, verified observation to the model. A narrow function can perform the task with an explicit destination and return only the verified status. The cloud browser and Crawl API comparison explains the boundary between interactive execution and URL-driven content acquisition.
Which components should your application own?
Your application should own the task contract, action authorization, acceptance checks, and stop decision. The browser client interprets the allowed call and performs the selected UI action. The provider owns documented parts of runtime provisioning and observes its own lifecycle. A useful boundary starts at the worker, before it creates channels for arbitrary model outputs.
Check identity, allowed target, and permitted action
Accept or reject with a safe reason
Browser worker
Load the expected page and run the bounded operation
A verified page marker or categorized error
Application validator
Check the data and its association with the job
Accepted outcome or reconciliation
Lifecycle owner
Stop the managed browser and reconcile usage
Terminal session state
Keep the allowlist scoped to tools the application actually needs. Avoid adding unrestricted browsing to fill gaps in tool design. If the requested operation falls outside the approved scope, return a safe rejection or send the job for authorized human review. See OWASP guidance on excessive agency.
How do you build a bounded browser tool for one task?
Build a tool that accepts one authorized action, validates its work item, and returns a structured observation. The example reads a synthetic build status from a fixture and rejects a submit request. It requires Node.js 22, playwright-core@1.65.1, and the accompanying files. Start node fixture.mjs for a local run and install Chromium with npx playwright-core install chromium. A managed run requires an authorized workspace, a ready session, and an equivalent approved fixture reachable by the managed browser.
Step 1. Define the allowed request
Give the caller a small request shape, such as { action: "readBuildStatus", build: "fixture-42" }. Validate the operation and reject extra fields at the boundary. Derive the destination from application configuration and the operation itself. For a production integration with more than one allowed build, look up authorized build IDs before constructing a route.
Step 2. Prepare a browser attachment
Set the controller's approved target origin and connect through the documented client interface. For a managed run, set NSTDATA_API_KEY, NSTDATA_SESSION_ID, and NSTDATA_TEAM_ID if your team context requires it. The connection helper checks that the session is ready and attaches with the returned credential. The local example can launch an isolated Chromium directly. The live service branch requires workspace authorization. The core task was verified on local Chromium and a temporary local CDP runtime.
const root ='https://api.nstdata.io/api/v1/cloud-browser';exportasyncfunctionapi(method, path, body){const key = process.env.NSTDATA_API_KEY;if(!key)thrownewError('Set NSTDATA_API_KEY');const headers ={'x-api-key': key };if(process.env.NSTDATA_TEAM_ID) headers['x-team-id']= process.env.NSTDATA_TEAM_ID;if(body) headers['content-type']='application/json';let response;try{ response =awaitfetch(root + path,{ method, headers,redirect:'error',body: body ?JSON.stringify(body):undefined,signal:AbortSignal.timeout(20_000),});}catch{throwObject.assign(newError('API transport failed; reconcile the original operation'),{retryable:true});}const retryable = response.status===429|| response.status>=500;let result;try{ result =await response.json();}catch{throwObject.assign(newError('Invalid API JSON'),{ retryable });}if(!response.ok|| result.err===true|| result.success===false){throwObject.assign(newError(`Cloud Browser API HTTP ${response.status}`),{ retryable });}if(!result.data)thrownewError('Missing API data');return result.data;}exportasyncfunctionconnection(id){if(!id)thrownewError('Set NSTDATA_SESSION_ID');const path =`/sessions/${encodeURIComponent(id)}`;const session =awaitapi('GET', path);if(session.state!=='ready')thrownewError(`Session is ${session.state}, not ready`);const c =awaitapi('POST', path +'/automation-credentials');if(c.sessionId!== id ||!c.headerName||!c.accessToken||!(Date.parse(c.expiresAt)>Date.now())||newURL(c.cdpUrl).protocol!=='wss:'){thrownewError('Invalid or expired CDP credentials');}return{endpoint: c.cdpUrl,headers:{[c.headerName]: c.headerName.toLowerCase()==='authorization'?`Bearer ${c.accessToken}`: c.accessToken},};}exportasyncfunctionendpoint(){// An isolated local CDP endpoint can test the client without managed credentials.if(process.env.LOCAL_CDP_URL){const url =newURL(process.env.LOCAL_CDP_URL);if(!['127.0.0.1','localhost','[::1]'].includes(url.hostname)){thrownewError('LOCAL_CDP_URL must use loopback');}return{endpoint: url.href,headers:{}};}returnconnection(process.env.NSTDATA_SESSION_ID);}
import{ chromium }from'playwright-core';import{ endpoint }from'./cloud-api.mjs';exportasyncfunctionwithPage(task){const origin =newURL(process.env.APP_ORIGIN??'http://127.0.0.1:4173');const remote =Boolean(process.env.LOCAL_CDP_URL|| process.env.NSTDATA_SESSION_ID);if(!remote && origin.hostname!=='127.0.0.1')throwError('Use the local fixture for local runs');const connection = remote ?awaitendpoint():null;const browser = connection
?await chromium.connectOverCDP(connection.endpoint,{headers: connection.headers,timeout:15_000}):await chromium.launch({args:['--no-proxy-server']});let page;try{const context = remote ? browser.contexts()[0]:await browser.newContext();if(!context)throwError('Expected a browser context'); page =await context.newPage(); page.setDefaultTimeout(8_000); page.setDefaultNavigationTimeout(10_000);returnawaittask(page, origin);}finally{try{await page?.close();}finally{await browser.close();}}}
Step 3. Execute the card-sized operation
Save the task module as agent.mjs. Run node agent.mjs against the local fixture. The script compares the actual page URL with the selected fixture route, checks the heading and task marker, and returns only one recognized value. The rejected operation returns rejected_action without directing the browser to a new page. Use the Playwright BrowserType reference for connection limits and the Locator reference for selecting the result.
Treat the exact URL comparison as a verification check for this fixed fixture. Production jobs need the network and navigation policy enforced at the appropriate execution boundary, including redirect behavior and any downstream subrequests the app depends on. A post-navigation assertion alone cannot enforce egress. Keep the example on the fixed test origin for which it was designed.
Step 4. Record and close the job
Record the action name, validated build reference, category of outcome, and runtime identifier. Keep connection credentials and arbitrary page text out of generalized model context and logs. Close any page that the worker created. The controller stops the managed browser and verifies its terminal state. Cloud Browser session lifecycle.
How do you prevent page content from extending an agent's authority?
Prevent page content from extending authority by enforcing policies in the application and limiting what the browser tool accepts. A banner or instruction inside a site can describe how to use a page. An external upload, a new destination, or additional account access requires application-level authorization. The app should choose the allowed destination and permitted operations before a page is loaded.
Return structured output to the model whenever the action allows it. For a status tool, return the known job ID, legal status values, and a safe failure reason. For a task that needs text, keep its provenance and treat it as a document to interpret. If a task genuinely needs a side effect, define a separate typed operation and authorize it explicitly. An internal test fixture and synthetic data make boundary checks discrete enough to repeat.
The operator handoff guide gives a pattern for pausing at a real workflow boundary. Once an authorized person finishes, validate the expected page state before resuming automation. Keep the controller that owns termination available even if the agent stops responding.
How does Nstdata Cloud Browser fit the agent stack?
Nstdata Cloud Browser provides managed cloud browsers for browser automation and AI agents. Your application can attach Playwright to an owned session while retaining tool permission checks and its own progress state. Live View can be useful in an approved workflow that requires a person to inspect or continue a page. Available diagnostics can help separate browser attachment from page or application failures. For tasks that require public URL content for ingestion tasks, evaluate Nstdata Crawl, a Web Crawling API for LLM-ready data.
Documented attachment. Use the business API to prepare an owned session and give the worker the correct short-lived connection credential.
Human inspection. Grant an authorized operator only the access necessary to check or resolve the task, then verify a checkpoint on return.
Runtime lifecycle. Keep the stop and verification steps with the controller so agent exceptions do not leave a browser untracked.
Separate evidence. Correlate permitted diagnostic events with the app's task ID, and keep protected artifacts outside routine model context.
What should you ship before adding more agent actions?
Ship one narrow action with two clear outcomes and a repeatable end-to-end test. Demonstrate that the service can report the expected build state, reject a different operation, and recover from a known page failure without reissuing broader access. Extend the tool vocabulary only when the next operation has its own identity, permission, receipt, and cleanup rule.
Measure the share of proposed calls that pass policy, the share that produce an accepted observation, and the share that reach verified browser shutdown. If a workflow fails before it produces evidence, use the browser automation debugging guide to determine which layer should report the failure.
Q: Does an agent always need full browser control?
Many agent tasks need only one structured read or approved operation. A narrow browser tool can cover those tasks with less authority and less data exposure.
Q: Should a model get the CDP endpoint and token?
Keep the control credentials inside the authorized worker. Return a safe result or allowed job reference to the caller.
Q: How can an agent recognize completion?
Have the application confirm the expected page, read an independent task marker, and validate the returned value. Track browser termination separately.
Q: Can an agent retry rejected or failed actions automatically?
Retry only classified transient errors with a bounded policy. Rejected requests need a new valid task, and uncertain writes need reconciliation before a retry.
Q: Is the example using a live model?
The example exercises the browser tool with explicit fixture requests. It demonstrates the execution contract that a model integration can call.
Marcus Chen
Nov. 20th 2026
Launch cloud browsers on demand
Handle fingerprints and CAPTCHAs
Automate workflows and power AI agents
From web scraping and testing to AI-driven automation, run it all in the cloud.