Get Started

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.

one-shot.ts
const result = await session.run('researcher', 'analyze competitor pricing for SaaS tools')

console.log(result.output)      // Full text output from the agent
console.log(result.artifacts)   // ['/workspace/report.pdf', '/workspace/data.csv']
console.log(result.cost)        // { amount: 47, currency: 'usd' }
console.log(result.duration)    // 38412  (milliseconds)
console.log(result.toolCalls)   // [{ 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.

create-agent.ts
const agent = await session.agents.create({
  // Compute override (uses session/platform default if omitted)
  compute: {
    provider: 'e2b',
    credentialRef: 'e2b_key',  // references secret stored in vault
  },

  // Browser context
  browser: true,          // provision a Chrome instance

  // Model
  model: 'claude-3-5-sonnet-20241022',

  // System instructions
  instructions: 'You are a research analyst. Be concise and cite sources.',

  // Built-in + custom tools to enable
  tools: ['web_search', 'write_file', 'screenshot'],

  // Hard limits for this agent
  timeout: 300_000,        // 5 minutes in ms
  costCap: { amount: 200, currency: 'usd' },   // $2.00 hard cap

  // Require human approval before these tools fire
  approvals: {
    tools: ['http_request'],
  },

  // Knowledge bases to attach
  knowledge: ['kb_product_docs', 'kb_competitor_intel'],

  // Content guardrails
  guardrails: {
    blockPii: true,
    allowedDomains: ['*.wikipedia.org', '*.github.com'],
  },
})

Agent Definitions

Instead of passing compute, model, tools, and instructions inline every time, you can save a reusable configuration in the Agent Store and reference it by name with the definition param.

definition.ts
// Load everything from a stored definition
const agent = await session.agents.create({
  definition: 'researcher',
})

// The 'researcher' definition in Agent Store might include:
//   compute:      { provider: 'e2b' }
//   model:        'anthropic/claude-sonnet'
//   tools:        ['web_search', 'write_file', 'screenshot']
//   instructions: 'You are a research analyst. Be concise and cite sources.'
//   timeout:      300_000
//   costCap:      { amount: 200, currency: 'usd' }

You can override specific fields from the definition at creation time. Overrides are merged on top of the stored config — everything else comes from the definition.

definition-override.ts
// Load definition but override model and timeout
const agent = await session.agents.create({
  definition: 'researcher',
  model: 'anthropic/claude-opus',     // override model only
  timeout: 600_000,                    // extend timeout to 10 minutes
})

// compute, tools, instructions, costCap, guardrails — all from the definition
Manage definitions in the Agent Store docs — create, update, version, and delete reusable agent configs.

Per-agent model override

The model field accepts a string shorthand or a full AgentModelConfig object. Model resolution follows a 3-level override chain: platform default → session default → per-agent override.

String shorthand

Pass a model identifier as a string. The platform's default credentials are used automatically.

model-string.ts
const agent = await session.agents.create({
  model: 'anthropic/claude-sonnet',   // uses platform default Anthropic credentials
})

Direct BYOI (bring your own inference)

Pass an object to use your own provider credentials directly. Credentials are stored in the secrets vault and referenced by name — never hardcoded.

model-byoi-direct.ts
const agent = await session.agents.create({
  model: {
    provider: 'anthropic',
    credentialRef: 'my_anthropic_key',   // references a secret in the vault
  },
})

Gateway BYOI

Route through an inference gateway (OpenRouter, LiteLLM, etc.) by providing a baseUrl and model name.

model-byoi-gateway.ts
const agent = await session.agents.create({
  model: {
    baseUrl: 'https://openrouter.ai/api/v1',
    credentialRef: 'openrouter_key',
    name: 'gpt-4o',
  },
})

Override chain

Model resolution walks three levels. The most specific override wins:

model-override-chain.ts
// Level 1: Platform default (set in dashboard → Settings → Models)
//   → applies to all sessions and agents unless overridden

// Level 2: Session default (set at session creation)
const session = await theazo.sessions.create({
  userId: 'user_123',
  model: 'anthropic/claude-sonnet',   // all agents in this session use Sonnet
})

// Level 3: Per-agent override (set at agent creation)
const agent = await session.agents.create({
  model: 'anthropic/claude-opus',     // this agent uses Opus, overriding session default
})
Credential references (credentialRef) point to secrets in the encrypted vault. See Secrets & Credentials for how to store and manage provider keys.

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.

run.ts
const result = await agent.run(
  'Scrape the pricing pages of Vercel, Render, and Railway. ' +
  'Produce a comparison table and save it to /workspace/pricing.md'
)

// RunResult shape
console.log(result.output)     // string — final text output
console.log(result.artifacts)  // string[] — absolute paths to generated files
console.log(result.cost)       // { amount: 83, currency: 'usd' }
console.log(result.duration)   // number (ms)
console.log(result.toolCalls)  // ToolCall[] — full tool call log

agent.stream(task)

Stream task progress in real time. Returns an AsyncIterable<StreamEvent>. Ideal for displaying live output in a UI.

stream.ts
const stream = agent.stream('Write a market analysis report')

for await (const event of stream) {
  switch (event.type) {
    case 'text':
      process.stdout.write(event.delta)   // incremental text chunk
      break

    case 'tool_call':
      console.log('calling:', event.name, event.input)
      break

    case 'tool_result':
      console.log('result:', event.name, event.output)
      break

    case 'progress':
      console.log(event.message)           // 'Searching the web...'
      break

    case 'done':
      console.log('cost:', event.result.cost)   // { 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.

exec.ts
// Execute Python inside the agent's sandbox
const result = await agent.exec('python', `
import json
import httpx

r = httpx.get('https://api.github.com/repos/vercel/next.js')
data = r.json()
print(json.dumps({
    'stars': data['stargazers_count'],
    'forks': data['forks_count'],
}))
`)

console.log(result.stdout)    // '{"stars": 128043, "forks": 27185}'
console.log(result.stderr)    // ''
console.log(result.exitCode)  // 0
agent.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.

files.ts
// Write a file into the agent's workspace
await agent.files.write('/workspace/input.json', JSON.stringify({ query: 'hello' }))

// Read a file back (returns Buffer)
const buf = await agent.files.read('/workspace/output.md')
console.log(buf.toString('utf8'))

// List directory contents
const entries = await agent.files.list('/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.

ports.ts
// Start a server inside the agent first, then expose it
await agent.exec('bash', 'python -m http.server 8080 &')

const url = await agent.ports.expose(8080)
console.log(url) // 'https://agent-abc123-8080.sandbox.theazo.com'

// The URL is valid for the agent's lifetime

Lifecycle management

agent.status()

status.ts
const status = await agent.status()

console.log(status.state)          // 'running' | 'idle' | 'paused' | 'completed' | 'failed' | 'terminated'
console.log(status.cost)           // { amount: 34, currency: 'usd' }
console.log(status.computeMinutes) // 12
console.log(status.startedAt)      // Date

pause() 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-resume.ts
// Pause — creates a snapshot, stops billing
const snapshot = await agent.pause()
console.log(snapshot.id)   // 'snap_...'
console.log(snapshot.size) // bytes

// Resume later — restores state from the snapshot
await agent.resume()

// Resume from a specific snapshot (cross-session restore)
await agent.resume({ snapshotId: 'snap_...' })

agent.retry()

Re-run the last task from scratch with a fresh agent. Useful when an agent fails due to a transient error.

retry.ts
// Agent failed — retry the same task
const result = await agent.retry()

agent.terminate()

terminate.ts
// 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.
Was this page helpful?
Ask anything...⌘I