Agents
An agent is an isolated execution environment — a microVM with its own kernel, browser, code runtime, and filesystem. Agents are created inside a session, run one or more tasks, and are destroyed when done (or paused and snapshotted for later resumption).
One-shot convenience
session.run() is the fastest way to run a task. It creates an agent, runs the task, waits for the result, and destroys the agent — all in one call.
const result = await session.run(class="cb-str">'researcher', class="cb-str">'analyze competitor pricing for SaaS tools')
console.log(result.output) class="cb-cmt">// Full text output from the agent
console.log(result.artifacts) class="cb-cmt">// ['/workspace/report.pdf', '/workspace/data.csv']
console.log(result.cost) class="cb-cmt">// { amount: 47, currency: 'usd' }
console.log(result.duration) class="cb-cmt">// 38412 (milliseconds)
console.log(result.toolCalls) class="cb-cmt">// [{ name: 'web_search', input: {...}, output: {...} }, ...]Explicit creation
Use session.agents.create() for full control over compute, model, tools, and guardrails. The agent is long-lived — you can run multiple tasks and interact with it before terminating.
const agent = await session.agents.create({
class="cb-cmt">// Compute override (uses session/platform default if omitted)
compute: {
provider: class="cb-str">'e2b',
credentials: { apiKey: process.env.E2B_API_KEY! },
},
class="cb-cmt">// Browser context
browser: true, class="cb-cmt">// provision a Chrome instance
class="cb-cmt">// Model
model: class="cb-str">'claude-3-5-sonnet-20241022',
class="cb-cmt">// System instructions
instructions: class="cb-str">'You are a research analyst. Be concise and cite sources.',
class="cb-cmt">// Built-in + custom tools to enable
tools: [class="cb-str">'web_search', class="cb-str">'write_file', class="cb-str">'screenshot'],
class="cb-cmt">// Hard limits for this agent
timeout: 300_000, class="cb-cmt">// 5 minutes in ms
costCap: { amount: class="cb-num">200, currency: class="cb-str">'usd' }, class="cb-cmt">// $2.00 hard cap
class="cb-cmt">// Require human approval before these tools fire
approvals: {
tools: [class="cb-str">'http_request'],
},
class="cb-cmt">// Knowledge bases to attach
knowledge: [class="cb-str">'kb_product_docs', class="cb-str">'kb_competitor_intel'],
class="cb-cmt">// Content guardrails
guardrails: {
blockPii: true,
allowedDomains: [class="cb-str">'*.wikipedia.org', class="cb-str">'*.github.com'],
},
})Running tasks
agent.run(task)
Run a task to completion and return a RunResult. This is a blocking call — it resolves when the agent finishes or hits its timeout.
const result = await agent.run(
class="cb-str">'Scrape the pricing pages of Vercel, Render, and Railway. ' +
class="cb-str">'Produce a comparison table and save it to /workspace/pricing.md'
)
// RunResult shape
console.log(result.output) class="cb-cmt">// string — final text output
console.log(result.artifacts) class="cb-cmt">// string[] — absolute paths to generated files
console.log(result.cost) class="cb-cmt">// { amount: 83, currency: 'usd' }
console.log(result.duration) class="cb-cmt">// number (ms)
console.log(result.toolCalls) class="cb-cmt">// ToolCall[] — full tool call logagent.stream(task)
Stream task progress in real time. Returns an AsyncIterable<StreamEvent>. Ideal for displaying live output in a UI.
const stream = agent.stream(class="cb-str">'Write a market analysis report')
for await (const event of stream) {
switch (event.type) {
case class="cb-str">'text':
process.stdout.write(event.delta) class="cb-cmt">// incremental text chunk
break
case class="cb-str">'tool_call':
console.log(class="cb-str">'calling:', event.name, event.input)
break
case class="cb-str">'tool_result':
console.log(class="cb-str">'result:', event.name, event.output)
break
case class="cb-str">'progress':
console.log(event.message) class="cb-cmt">// 'Searching the web...'
break
case class="cb-str">'done':
console.log(class="cb-str">'cost:', event.result.cost) class="cb-cmt">// { amount: 61, currency: 'usd' }
break
}
}Code execution (infra-only mode)
agent.exec() runs code directly inside the sandbox without an LLM. This is the entry point for infra-only customers using their own orchestration (LangGraph, CrewAI, custom loops). The agent acts as a pure compute sandbox.
// Execute Python inside the agent's sandbox
const result = await agent.exec(class="cb-str">'python', `
import json
import httpx
r = httpx.get(class="cb-str">'https://api.github.com/repos/vercel/next.js'repos/vercel/next.js')
data = r.json()
print(json.dumps({
class="cb-str">'stars': data[class="cb-str">'stargazers_count'],
class="cb-str">'forks': data[class="cb-str">'forks_count'],
}))
`)
console.log(result.stdout) class="cb-cmt">// '{"stars": 128043, "forks": 27185}'
console.log(result.stderr) class="cb-cmt">// ''
console.log(result.exitCode) class="cb-cmt">// 0agent.exec() is synchronous with a 120-second timeout. For long-running code, use agent.run() with the Theazo orchestrator, or stream output with agent.stream().File system
Each agent has an isolated filesystem. Use the agent.files namespace to read, write, and list files. Files persist for the lifetime of the agent and are included in snapshots.
// Write a file into the agent's workspace
await agent.files.write(class="cb-str">'/workspace/input.json', JSON.stringify({ query: class="cb-str">'hello' }))
// Read a file back (returns Buffer)
const buf = await agent.files.read(class="cb-str">'/workspace/output.md')
console.log(buf.toString(class="cb-str">'utf8'))
// List directory contents
const entries = await agent.files.list(class="cb-str">'/workspace')
// [{ name: 'input.json', size: 24, isDirectory: false }, ...]Exposed ports
Agents can expose ports to the public internet. Theazo provisions a unique HTTPS URL per port. Useful for running local dev servers, Jupyter notebooks, or internal APIs that other services need to reach.
// Start a server inside the agent first, then expose it
await agent.exec(class="cb-str">'bash', class="cb-str">'python -m http.server 8080 &')
const url = await agent.ports.expose(class="cb-num">8080)
console.log(url) class="cb-cmt">// 'https://agent-abc123-8080.sandbox.theazo.com'
// The URL is valid for the agent's lifetimeLifecycle management
agent.status()
const status = await agent.status()
console.log(status.state) class="cb-cmt">// 'running' | 'idle' | 'paused' | 'completed' | 'failed' | 'terminated'
console.log(status.cost) class="cb-cmt">// { amount: 34, currency: 'usd' }
console.log(status.computeMinutes) class="cb-cmt">// 12
console.log(status.startedAt) class="cb-cmt">// Datepause() and resume()
Pausing snapshots the entire agent state — memory, filesystem, browser tabs. Compute billing stops. Resuming restores from the snapshot exactly where it left off.
// Pause — creates a snapshot, stops billing
const snapshot = await agent.pause()
console.log(snapshot.id) class="cb-cmt">// 'snap_...'
console.log(snapshot.size) class="cb-cmt">// bytes
// Resume later — restores state from the snapshot
await agent.resume()
// Resume from a specific snapshot (cross-session restore)
await agent.resume({ snapshotId: class="cb-str">'snap_...' })agent.retry()
Re-run the last task from scratch with a fresh agent. Useful when an agent fails due to a transient error.
// Agent failed — retry the same task
const result = await agent.retry()agent.terminate()
// Destroy the agent immediately, release compute
await agent.terminate()terminate() is irreversible. Create a snapshot with agent.pause() first if you need to preserve state.Method reference
session.run(agentType, task)Promise<RunResult>One-shot: create agent, run task, destroy. Fastest path to a result.session.agents.create(opts)Promise<Agent>Create a long-lived agent with full option control.agent.run(task)Promise<RunResult>Run a task to completion. Returns output, artifacts, cost, duration, toolCalls.agent.stream(task)AsyncIterable<StreamEvent>Stream task events: text | tool_call | tool_result | progress | done.agent.exec(lang, code)Promise<ExecResult>Execute code directly (infra-only mode). Returns stdout, stderr, exitCode.agent.files.write(path, data)Promise<void>Write a file into the agent's isolated filesystem.agent.files.read(path)Promise<Buffer>Read a file from the agent's filesystem.agent.files.list(dir)Promise<FileEntry[]>List directory contents. Returns name, size, isDirectory per entry.agent.ports.expose(port)Promise<string>Expose a port to the public internet. Returns an HTTPS URL.agent.status()Promise<AgentStatus>Current state, cost, computeMinutes, and timing information.agent.pause()Promise<Snapshot>Snapshot agent state and stop compute billing. Returns Snapshot with id and size.agent.resume(opts?)Promise<void>Restore from the latest snapshot, or a specific snapshotId.agent.retry()Promise<RunResult>Re-run the last task from scratch on a fresh agent.agent.terminate()Promise<void>Permanently destroy the agent and release compute. Irreversible.