# OpenAI Agents SDK for TypeScript with a Sandscale sandbox: context, tools and approvals

> An integration guide that keeps one sandbox per agent run in the Agents SDK's run context, runs model-written Python in it, and puts package installs behind needsApproval with the interruptions loop.

An integration guide that keeps one sandbox per agent run in the Agents SDK's run context, runs model-written Python in it, and puts package installs behind needsApproval with the interruptions loop.

November 27, 2026 · 5 min read · The Sandscale team

The [OpenAI Agents SDK for TypeScript](https://openai.github.io/openai-agents-js/) gives you agents, tools, a run loop and a human-in-the-loop flow. It does not decide where a tool’s code runs. For a data-analysis agent that writes Python, that should be somewhere other than your server. This guide connects the Agents SDK to a Sandscale sandbox: one Firecracker microVM per run, held in the SDK’s run context, with package installs gated behind a person’s approval.

Agents SDK details come from its [human-in-the-loop guide](https://openai.github.io/openai-agents-js/guides/human-in-the-loop/) and the `@openai/agents` 0.22 type definitions as of November 2026. Sandscale calls are from the [TypeScript SDK reference](https://sandscale.dev/docs/sdks/typescript). The code type-checks against both.

## The design

- **The sandbox lives in the run context.** The Agents SDK passes a `RunContext` to every tool’s `execute`. Putting the sandbox id and region there means tools do not need globals, and two runs in the same process each get their own box.
- **Two tools with different risk.** `run_python` runs code inside the sandbox; that is what the box is for, so it runs without asking. `pip_install` pulls code from the network into the box, which is a [supply-chain decision](https://sandscale.dev/blog/supply-chain-risk-when-agents-install-packages), so it has `needsApproval: true`.
- **The interruptions loop.** When a tool needs approval, the SDK pauses the run and returns `interruptions`. You approve or reject each one on `result.state` and run again from that state.
- **A guaranteed stop.** The sandbox is stopped in `finally`, and its `timeoutSeconds` stops it anyway if the process dies first.

## The code

```ts
import { Agent, run, tool, RunContext } from '@openai/agents';
import { z } from 'zod';
import { Sandscale } from '@sandscale/sdk';
import * as readline from 'node:readline/promises';

const sandscale = new Sandscale(); // reads SANDSCALE_API_KEY

interface BoxContext {
  sandboxId: string;
  region?: string;
}

const clip = (s: string, n = 8_000) => (s.length > n ? s.slice(0, n) + `\n[cut ${s.length - n} chars]` : s);

const runPython = tool({
  name: 'run_python',
  description:
    'Run a Python 3 script in an isolated sandbox. Files you write persist for this session ' +
    'under /workspace. Network is limited to the organization allowlist. Output over 8,000 characters is cut.',
  parameters: z.object({
    code: z.string().max(20_000),
    timeout_seconds: z.number().int().min(1).max(120),
  }),
  execute: async ({ code, timeout_seconds }, ctx?: RunContext<BoxContext>) => {
    const { sandboxId, region } = ctx!.context;
    await sandscale.sandboxes.writeFile(sandboxId, '/workspace/main.py', code, { region });
    const r = await sandscale.sandboxes.run(sandboxId, ['python3', '/workspace/main.py'], {
      region,
      timeoutSeconds: timeout_seconds,
    });
    return JSON.stringify({
      exit_code: r.exitCode,
      timed_out: r.timedOut,
      stdout: clip(r.stdout),
      stderr: clip(r.stderr),
    });
  },
});

const pipInstall = tool({
  name: 'pip_install',
  description: 'Install Python packages into the sandbox. A person approves each request.',
  parameters: z.object({
    packages: z.array(z.string().regex(/^[A-Za-z0-9_.\-]+(==[A-Za-z0-9_.\-]+)?$/)).min(1).max(10),
  }),
  needsApproval: true,
  execute: async ({ packages }, ctx?: RunContext<BoxContext>) => {
    const { sandboxId, region } = ctx!.context;
    const r = await sandscale.sandboxes.run(sandboxId, ['pip', 'install', '--no-input', ...packages], {
      region,
      timeoutSeconds: 300,
    });
    return JSON.stringify({ exit_code: r.exitCode, stderr: clip(r.stderr, 2_000) });
  },
});

const analyst = new Agent<BoxContext>({
  name: 'Data analyst',
  instructions:
    'Answer questions about the CSV at /workspace/data.csv by writing and running Python. ' +
    'Use the standard library where you can. Ask for packages only when you need them.',
  tools: [runPython, pipInstall],
});

export async function analyse(question: string, csv: string) {
  const box = await sandscale.sandboxes.create({
    template: 'builtin:python',
    network: 'allowlist', // pip needs the package index on your organization's allowlist
    timeoutSeconds: 1800,
    labels: { app: 'agents-sdk-analyst' },
  });
  const context: BoxContext = { sandboxId: box.id, region: box.region };
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });

  try {
    await sandscale.sandboxes.writeFile(box.id, '/workspace/data.csv', csv, { region: box.region });
    let result = await run(analyst, question, { context });

    while (result.interruptions.length > 0) {
      for (const item of result.interruptions) {
        const answer = await rl.question(`Allow ${item.name} with ${item.arguments}? [y/N] `);
        if (answer.trim().toLowerCase() === 'y') result.state.approve(item);
        else result.state.reject(item);
      }
      result = await run(analyst, result.state, { context });
    }
    return result.finalOutput;
  } finally {
    rl.close();
    await sandscale.sandboxes.stop(box.id, { region: box.region });
  }
}
```

## Notes on the choices

**Network is decided when the sandbox starts, not per call.** Sandscale sandboxes start with `network: 'none'` unless you ask for `allowlist`, which uses your organization’s egress allowlist and is not on every plan. Here the box needs the Python package index reachable for `pip_install`, so it starts with `allowlist`. The model cannot widen that from a tool call; only your code chooses the mode. If you do not need installs, drop `pip_install` and start with `none`.

**The approval shows the real arguments.** `item.arguments` is the JSON the model produced. The person sees exactly which packages and versions will be installed. The schema’s regex limits names to plain package specifiers, so a request cannot smuggle in a URL or a shell fragment, and `--no-input` keeps pip from waiting for a prompt that will never come.

**Rejected is a normal outcome.** When you call `result.state.reject(item)`, the SDK tells the model the call was refused and the run continues. A good agent then tries the standard library, which is what the instructions ask for.

**Results are strings.** The tool returns `JSON.stringify` of the exit code, a timeout flag and capped output. Keeping it structured lets the model distinguish a Python error from a timeout without parsing prose.

**Approvals and Sandscale’s own approvals are different layers.** The Agents SDK approval is your app asking a person before a tool runs. Sandscale also has [approvals](https://sandscale.dev/security/approvals) and [agent policy](https://sandscale.dev/security/agent-policy) on the platform side, which apply to every client, not only this app. Use the SDK’s for per-app interaction and the platform’s for rules that must hold everywhere.

## Durable approvals

The run state can be serialized, which the Agents SDK guide covers. That lets you store a paused run, show the approval in a web UI, and resume hours later. If you do that, keep the sandbox’s `timeoutSeconds` longer than the approval wait, or pause the sandbox with `sandboxes.pause` while the run waits and `sandboxes.resume` it after. Pause keeps memory and disk; see [pause, resume or stop](https://sandscale.dev/blog/pause-resume-or-stop-agent-sandboxes) for when each makes sense.

## Where to go next

- [Designing a run_code tool schema](https://sandscale.dev/blog/designing-a-run-code-tool-schema) covers descriptions, limits and result shapes in more depth.
- [Safe data analysis with LLM-generated Python](https://sandscale.dev/blog/safe-data-analysis-with-llm-generated-python) covers the data side: what to put in the box and what to keep out.
- [Human approvals for agent tool calls](https://sandscale.dev/blog/human-approvals-for-agent-tool-calls) covers which calls deserve a person at all.

**On this page**

1. The design
2. The code
3. Notes on the choices
4. Durable approvals
5. Where to go next

**Run your agents in a box of their own**

Each sandbox is a Firecracker microVM. Free includes 100 awake vCPU-hours a month.

[Start free](https://cloud.sandscale.dev/auth/signup)

## Keep reading

- [November 27, 2026 · **A LlamaIndex.TS data agent that runs its Python in a Sandscale sandbox** · Use LlamaIndex.TS's agent workflow with tools that write and run Python in a Firecracker sandbox, built per sandbox so a run can only reach its own box. Upload data files, answer with the numbers, clean up. Type-checked.](https://sandscale.dev/blog/llamaindex-ts-agent-with-sandscale)
- [November 27, 2026 · **Adding the Sandscale MCP server to Codex: config.toml, OAuth login and approval modes** · Configure the remote or local Sandscale MCP server in OpenAI Codex, sign in with codex mcp login, and use enabled_tools, approval modes and tool timeouts to match what each tool does.](https://sandscale.dev/blog/sandscale-mcp-server-in-codex)

---
Source: https://sandscale.dev/blog/openai-agents-sdk-with-sandscale
