> ## Documentation Index
> Fetch the complete documentation index at: https://docs.restate.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Sandboxes

> Give an agent's tools a sandbox to run commands and edit files in, and keep the sandbox's files across the requests of a session.

Restate Harness doesn't provide sandboxes for commands and files. Your handler connects to a sandbox at a provider, such as Modal, and passes a client for it to the tools in the [run context](https://docs.restate.dev/harness/tools.md#run-context).
The handler wraps each lifecycle call to the provider in `restate.run`, so a replay reuses the journaled sandbox reference instead of creating another sandbox.

## Connect to a sandbox

The examples on this page use a small provider interface. Implement it with your provider's SDK:

```typescript {"CODE_LOAD::harness/src/sandboxes.ts#provider"}  theme={null}
/** Identifies a sandbox at your provider. Extend it with what your provider needs, such as a compute ID. */
export type SandboxRef = {id: string};

export interface SandboxProvider {
  /** Creates a sandbox. A retry after a failure must reuse a sandbox that the failed attempt created. */
  provision(key: string): Promise<SandboxRef>;
  /** Starts compute for the sandbox's files, or reuses compute that still runs. */
  resume(ref: SandboxRef): Promise<SandboxRef>;
  /** Stops the compute and keeps the files. */
  suspend(ref: SandboxRef): Promise<SandboxRef>;
  /** Deletes the sandbox and its files. */
  destroy(ref: SandboxRef): Promise<void>;
  /** Builds a client for the sandbox, without I/O. */
  connect(ref: SandboxRef): SandboxClient;
}

export interface SandboxClient {
  readFile(path: string): Promise<string>;
  writeFile(path: string, content: string): Promise<void>;
  exec(command: string): Promise<{exitCode: number; output: string}>;
}
```

* **Store only the reference.** State and the journal hold `SandboxRef`, the data that identifies the sandbox. `connect` builds a client from it in each attempt, without I/O, also when another process continues the request.
* **Make the lifecycle calls safe to repeat.** If an attempt fails after the provider completed a call, but before Restate journaled the result, Restate calls it again. For example, name the sandbox after its key, and reuse a sandbox with that name in `provision`.
* **Keep credentials out of the sandbox.** A command that the model runs can print environment variables and files into the conversation and the journal.

## Keep files across requests

A [Virtual Object](https://docs.restate.dev/foundations/services.md#virtual-object) keeps one sandbox per session. The first request provisions the sandbox. Each later request resumes it, and each request suspends it when the run ends, which stops the compute and keeps the files:

```typescript {"CODE_LOAD::harness/src/sandboxes.ts#session"}  theme={null}
type SandboxContext = {sandbox: SandboxClient};

const coder = agent<SandboxContext>({
  model,
  instructions: "You are a coding agent. Work in the sandbox, where your files stay between requests.",
  tools: {
    readFile: asyncTool({
      description: "Read a file in the sandbox.",
      input: z.object({path: z.string()}),
      execute: ({path}, {context}) => context.sandbox.readFile(path),
    }),
    writeFile: asyncTool({
      description: "Create or replace a file in the sandbox.",
      input: z.object({path: z.string(), content: z.string()}),
      async execute({path, content}, {context}) {
        await context.sandbox.writeFile(path, content);
        return {path};
      },
    }),
    runCommand: asyncTool({
      description: "Run a shell command in the sandbox.",
      input: z.object({command: z.string()}),
      // A command isn't safe to repeat, so a failure goes to the model instead of a retry
      retry: {maxAttempts: 1},
      execute: ({command}, {context}) => context.sandbox.exec(command),
    }),
  },
});

export const codingSession = restate.object({
  name: "CodingSession",
  handlers: {
    *chat(message: string) {
      const ref = yield* openSandbox();
      try {
        const result = yield* coder.run(message, {
          conversation: new Conversation(),
          context: {sandbox: provider.connect(ref)},
        });
        if (result.status !== "completed") return result.output ?? result.reason;
        return result.output;
      } finally {
        const suspended = yield* restate.run(() => provider.suspend(ref), {name: "Suspend sandbox"});
        restate.state().set("sandbox", suspended);
      }
    },
    *close() {
      const ref = yield* restate.state().get<SandboxRef>("sandbox");
      if (ref) yield* restate.run(() => provider.destroy(ref), {name: "Destroy sandbox"});
      // Deletes the conversation and the sandbox reference
      restate.state().clearAll();
    },
  },
});

/** Resumes the session's sandbox, or provisions one on the first request. */
function* openSandbox(): restate.Operation<SandboxRef> {
  const key = restate.handlerRequest().key!;
  const stored = yield* restate.state().get<SandboxRef>("sandbox");
  const ref = stored
    ? yield* restate.run(() => provider.resume(stored), {name: "Resume sandbox"})
    : yield* restate.run(() => provider.provision(key), {name: "Provision sandbox"});
  // Store the reference right away, so that the next request finds the sandbox even if this one fails
  restate.state().set("sandbox", ref);
  return ref;
}
```

* **One run at a time.** Restate runs one exclusive handler per key at a time, so only one run uses the sandbox at a time, without a lock of your own.
* **The reference in state.** The handler stores the reference as soon as it has one, so the next request finds the sandbox even if this request fails. The `finally` block suspends the sandbox when the run completes, fails with a terminal error, or is cancelled. If you [kill](https://docs.restate.dev/services/invocation/managing-invocations.md#kill) the invocation, `finally` doesn't run and the compute keeps running, so the next `resume` reuses it or starts new compute. Set a timeout at your provider, so that the provider stops compute that no request suspends.
* **No retries for commands.** After a failed command, the model receives the error and can inspect the sandbox. A crash before the result is journaled still runs the command again.
* **Files, not processes.** Suspending stops the processes in the sandbox. Start long-running processes again in a later request.

To provision the sandbox only for runs that use it, acquire it in the first sandbox tool call instead of at the start of the request. The [reference architecture](https://docs.restate.dev/ai/reference-architecture.md) does this, and lets parallel tool calls wait for one acquisition.

## One sandbox per request

For a self-contained task, run the agent in a service. Provision a sandbox at the start of the request, and destroy it in `finally`. The [coding agent lesson](https://github.com/restatedev/ai-examples/blob/main/restate-harness/examples/src/lessons/11_coding_agent.ts) does this with a Modal sandbox.

A request that provisions its own sandbox shouldn't use a [conversation](https://docs.restate.dev/harness/sessions.md): the history of a later request would refer to files in a sandbox that no longer exists.

## Providers

The reference architecture implements this lifecycle for Modal. A Modal Volume per agent keeps the files, and each run that uses the sandbox mounts the Volume in new Sandbox compute. See its [Modal provider](https://github.com/restatedev/ai-examples/blob/main/restate-harness/reference-architecture/packages/libs/core/src/sandbox/modal-provider.ts) and its [sandbox documentation](https://github.com/restatedev/ai-examples/blob/main/restate-harness/reference-architecture/docs/sandboxes.md), which covers retries, cancellation, and how to add a provider.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.