Blog

AI Agent Sandbox: Build a Controlled Agent Workspace

An AI agent sandbox gives a software agent isolated files, processes, network rules, and reviewable output. Learn how to test the workspace with a real task.

Drew Stone
agentssandboxinfrastructure
An editorial still life about describing and running an agent task

A coding agent is asked to upgrade one dependency and open a review. It edits the manifest, installs packages, runs the test suite, sees a failure, changes an import, and runs the tests again. The final patch is useful only if the reviewer can also see which files changed, which commands ran, and whether the agent ever reached outside the project.

An AI agent sandbox is an isolated workspace for that loop. It gives an agent files, processes, packages, and sometimes a browser or GPU while placing boundaries around the host machine, network, credentials, lifetime, and evidence. The sandbox does not make the model correct. It gives the model a place where a wrong action has a smaller blast radius and a run can leave inspectable results.

Tangle Sandbox’s public TypeScript SDK creates a workspace, waits for it to become usable, executes commands, supports sessions and snapshots, and deletes the temporary machine when the work is finished. The design decision is easy to state and easy to miss: the workspace must outlive an individual prompt, while the evidence must outlive the temporary machine.

The workspace is part of the agent

A chat response can be wrong without changing anything outside the response. A coding agent changes state as it works. It needs a directory to inspect, a process to run tests, a package manager to install dependencies, and enough time to recover from a failed attempt.

Running that loop directly on a developer laptop gives the agent access to unrelated files, credentials, processes, and network destinations. Running every command in a fresh one-shot function removes the state the agent needs to diagnose its own failure.

The sandbox sits between those two extremes. It makes the working directory explicit, limits the resources and lifetime, and gives the application a place to capture the side effects. The prompt explains the task. The sandbox controls where the task can act.

What the sandbox boundary must answer

Before an agent receives a repository or a secret, the workspace contract should answer six questions.

QuestionConcrete answer
What can the agent read and write?Named workspace paths and file permissions
Which processes may run?An image, command policy, timeout, and resource budget
Where may data go?An egress policy that names allowed network destinations
What survives a reconnect?A session identifier, snapshot, or durable artifact
What can a reviewer inspect?Changed files, output, errors, screenshots, and run metadata
When does the workspace end?An explicit stop, expiry, idle timeout, or deletion event

The word runtime means the software and machine that execute an agent’s actions. The sandbox is one runtime boundary inside a larger product that may also provide model calls, browser control, approvals, and result evaluation.

A policy is the set of rules that decides whether an action is allowed. The model may propose npm install, but the process enforcing the policy must decide which packages, network hosts, and write paths are permitted. A sentence in a prompt is guidance. An enforcement service is a control.

An agent profile is a versioned bundle of model settings, tools, permissions, resource limits, and budget for one kind of run. For a dependency-upgrade agent, the profile might allow package installation and tests inside a disposable workspace while forbidding access to production credentials. Changing the profile changes the experiment, so its identity belongs in the run record.

Start with the public contract

Tangle publishes a Sandbox manifest with the package name, API-key environment variable, safe discovery calls, and authenticated calls. The Sandbox documentation describes the product as an isolated computer with a shell, filesystem, ports, snapshots, optional GPU, and durable sessions.

The first checks should be read-only:

npm install @tangle-network/sandbox
curl -fsS https://sandbox.tangle.tools/health
curl -fsS https://sandbox.tangle.tools/.well-known/tangle-agent.json
curl -fsS https://sandbox.tangle.tools/v1/public-templates

The health call checks whether the public service answers. The manifest tells a caller which package and authentication variable to use. The template call exposes a public catalog without creating an account-owned workspace.

Those calls do not prove that your API key is valid, that a requested environment can be provisioned, or that your command will pass. They separate capability discovery from a real workload test.

The package’s public README contains the current SDK examples and entry points. Use the live README and manifest when version-specific options matter because the service surface can change.

Create, run, inspect, and delete

The smallest useful SDK loop is a dependency check inside a disposable workspace. This example uses the public Sandbox class and keeps the API key on the server. Set both TANGLE_API_KEY and SANDBOX_BASE_URL in the server environment before running it.

import { Sandbox } from '@tangle-network/sandbox'

const client = new Sandbox({
  apiKey: process.env.TANGLE_API_KEY!,
  baseUrl: process.env.SANDBOX_BASE_URL!,
})

const box = await client.create({
  name: 'dependency-review',
  environment: 'universal',
  resources: {
    cpuCores: 2,
    memoryMB: 4096,
    diskGB: 20,
  },
})

try {
  await box.waitFor('running')

  const result = await box.exec('node --version && npm --version')
  if (result.exitCode !== 0) {
    throw new Error(result.stderr)
  }

  console.log({ stdout: result.stdout, timing: result.timing })
} finally {
  await box.delete()
}

The lifecycle has five observable moments:

  1. create requests a named environment with explicit resources.
  2. waitFor('running') prevents the client from sending work to a machine that is still provisioning.
  3. exec returns an exit code, standard output, standard error, and timing data.
  4. The application copies any patch, report, or log that must survive the run.
  5. delete releases temporary state even when the command throws.

The finally block is part of the example’s correctness. A timeout or failed command must not turn a temporary workspace into an abandoned bill or an untracked machine. If the next run needs the same files, create a snapshot or use a durable session instead of silently skipping cleanup.

A failed test is a useful result

Consider a package upgrade that produces this sequence:

EventEvidenceWhat it says
Workspace readySandbox ID, environment, resource requestThe runtime accepted the create request
Install startedCommand, working directory, start timeThe agent attempted the dependency change
Install failedNon-zero exit code and error textThe first attempt did not complete
File changedDiff or file hashThe agent changed a specific artifact
Tests rerunCommand and exit codeRecovery was attempted and observed
Cleanup completedDelete result or expiry stateTemporary execution ended

The final answer can summarize that sequence, but the sequence itself is the evidence. A trace is the structured record of the run’s inputs, actions, outputs, errors, identifiers, and artifacts. It lets a reviewer distinguish “the agent fixed the dependency” from “the agent claimed it fixed the dependency after a test command failed.”

Tangle’s public Sandbox docs describe durable sessions that can reconnect after a client crash, deployment, or browser reload. That matters when the command continues after the user interface disconnects. The session ID is the handle for the work, while the trace and artifacts are the record of what the work did.

Keep state across attempts without keeping authority forever

A retry should see the files it needs, but it should not inherit permissions accidentally. The application should make those two decisions separately.

The SDK supports snapshots for preserving filesystem state and sessions for continuing a conversation with an agent backend. The following example shows the snapshot shape documented by the public package:

const snapshot = await box.snapshot({
  tags: ['dependency-baseline'],
})

const restored = await client.create({
  fromSnapshot: snapshot.snapshotId,
})

try {
  await restored.waitFor('running')
  const result = await restored.exec('npm test', {
    timeoutMs: 10 * 60 * 1000,
  })
  console.log(result.exitCode, result.stdout, result.stderr)
} finally {
  await restored.delete()
}

Use the same idempotencyKey only when retrying the same logical create request. An idempotency key is a caller-chosen identifier that lets a service recognize a retry rather than provisioning a second copy of the same request. It does not mean that every command inside the workspace is idempotent.

For longer agent sessions, the application should retain both the session ID and the execution ID returned by the SDK. Those identifiers make it possible to reconnect to the exact run instead of accidentally appending a new turn or replaying a completed action.

Network access deserves its own test

Many coding tasks need a package registry or a public documentation site. They rarely need every destination on the internet.

Start with the narrowest network policy that can complete the task. Record whether a request was allowed, denied, or failed for another reason. Treat a denied request as evidence about policy, not as proof that the model made a bad decision.

Credentials need the same care. Inject a short-lived, task-scoped secret only when the job needs it. Do not mount a developer’s general-purpose credential directory into a workspace that can read arbitrary files or send network requests. If the model needs a GitHub connection, expose the smallest operation set that satisfies the task and keep writes disabled until a reviewer approves them.

The public Sandbox package exposes capability clients for files, processes, network, egress, previews, backends, and related resources. Unsupported capabilities should fail as typed SDK errors rather than being silently treated as available. The exact option names belong in the live SDK documentation, not in an agent’s guess.

Prove the boundary with a canary task

An isolation claim becomes useful only when a small test can try the boundary and record the result. Use a harmless canary project before giving the workspace customer data or production credentials.

Canary stepExpected observationWhat a failure means
Write a file under the workspace rootThe file exists in the workspace and appears in the artifact listThe file or artifact boundary is unclear
Request a path outside the workspaceThe operation is denied or the path is absentThe host and workspace boundaries need review
Call an allowed package registryThe request succeeds and the destination is recordedThe network policy is too narrow for the task
Call an unapproved destinationThe request is denied with an attributable policy resultEgress enforcement is missing or opaque
Kill the client during a commandThe session or execution can be found again without a duplicate runReconnection semantics are incomplete
Delete the workspaceTemporary files disappear while copied artifacts remainCleanup or retention is not doing what the product promises

This canary is not a substitute for a security review. This canary connects the policy a team wrote to the behavior the runtime enforced. Run it with the same image, credentials, network rules, and cleanup policy used by the real agent. If the production profile differs, the canary is testing a different environment.

Container, microVM, or TEE

The word sandbox describes a boundary, not one implementation. A provider may use a container, a microvirtual machine, or another isolated execution driver. The useful properties are the ones a caller can test: separate filesystem state, process limits, network policy, cleanup, and evidence.

A TEE, or Trusted Execution Environment, is a hardware-backed execution boundary. An attestation is signed evidence about that boundary, such as a measurement of the code or environment that ran. Attestation can help a caller verify an execution claim when the measurement, verification policy, input, and output are bound together. It does not prove that the agent chose the right command or that the resulting patch is safe. Tangle’s attestation explanation makes the distinction explicit.

Choose a confidential runtime when the trust decision depends on protecting inputs or proving code identity. Choose an ordinary isolated workspace when the main requirement is containing filesystem and process side effects. In both cases, test the actual permissions and failure paths you plan to deploy.

Sandbox versus a one-shot code runner

The right boundary follows the workload.

WorkloadSmaller tool that may fitWhy an agent sandbox earns its cost
One calculation from fixed inputCode interpreter or function runnerUsually no persistent project state is needed
A public page checkBrowser automationThe browser owns the important state
A fixed batch transformServerless jobA single invocation can finish without interaction
Dependency upgrade and repairAgent sandboxThe agent needs files, packages, commands, retries, and a review record
Long-running coding sessionAgent sandbox with sessionsA client disconnect should not destroy the work
Parallel repository checksSandbox fleet or batch APIEach worker needs its own state and bounded resource policy

The Browser Agent driver can control a browser and capture page evidence. Sandbox can hold the test files, comparison scripts, and reports around that browser session. They solve different boundaries and can be combined when the task needs both. The browser automation guide shows how to keep the page evidence separate from the workspace evidence.

How to evaluate a sandbox workload

An evaluation, or eval, is a repeatable run over named cases with explicit success criteria. For a sandbox, the cases should cover more than a successful echo command.

Use one small project and test these cases:

  1. The agent creates a file inside the workspace and the host cannot see it through an unrelated path.
  2. A command fails and returns its exit code, output, and error.
  3. A permitted network request succeeds and a forbidden destination is denied.
  4. A second command sees the first attempt’s files and logs.
  5. A client reconnects to the same session without starting a duplicate run.
  6. A snapshot restores the expected state.
  7. Deletion removes temporary state while saved artifacts remain available.

The eval should store a trace for each case. It should also distinguish a provisioning failure, a policy denial, a command failure, and a wrong agent decision. Those failures require different fixes.

@tangle-network/agent-eval is a public package for running cases, applying judges or deterministic checks, comparing candidates, and preserving the data needed to explain a score. The agent-eval repository documents that evaluation path. You can use a simpler local test suite for a first sandbox, but keep the same separation between what the runtime observed and what the evaluator concluded.

What the sandbox does not prove

A successful create proves that a service accepted a provisioning request. A running state proves that the workspace reached a lifecycle state the service reports as usable. A zero exit code proves that one command returned success. A saved patch proves which files were captured.

None of those facts proves that the agent’s patch is correct, that every secret was handled safely, or that an untested network path is harmless. The application still needs code review, deterministic tests, credential policy, and a decision about which side effects require human approval.

The narrow promise is valuable. An agent receives a bounded place to work, and the rest of the system receives a durable record of what happened there.

The decision for builders

Use an AI agent sandbox when the job needs a live project directory, several commands, intermediate state, recovery, or a reviewable artifact. Start with the public health check, one authenticated create, one successful command, one deliberate failure, and cleanup.

Keep the task disposable until a reviewer can answer three questions from the trace: which files could the agent reach, which side effects did it attempt, and what remains after the workspace is deleted. If those answers are unclear, adding a larger model or more tools will increase uncertainty rather than remove it.

What is an AI agent sandbox?

An AI agent sandbox is an isolated workspace where an agent can read and write files, run processes, use approved tools, and preserve evidence without receiving direct control of the host machine.

Is a code interpreter the same as an agent sandbox?

Usually not. A code interpreter is optimized for a bounded execution request, while a sandbox keeps a project workspace alive for multi-step work, retries, and review.

Is an AI agent sandbox safe by default?

No. Safety depends on filesystem scope, network policy, credential scope, resource limits, timeouts, logging, cleanup, and the application’s approval rules. A sandbox reduces the area a mistake can affect, but it does not remove the need to test those controls.

When should I use Tangle Sandbox?

Use Tangle Sandbox when an agent needs a disposable or resumable development environment with files, processes, packages, sessions, snapshots, and inspectable results. Start from the public manifest and run one small workload before connecting a larger agent.

Does a TEE attestation prove that an agent did the right thing?

No. Attestation can describe the code and execution boundary that produced a result. Correctness still requires task-specific tests, result checks, or human review.