← Blog

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.

The OpenAI Agents SDK for TypeScript 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 and the @openai/agents 0.22 type definitions as of November 2026. Sandscale calls are from the TypeScript SDK reference. 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, 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

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 and 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 for when each makes sense.

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

Keep reading