# LangGraph.js agents with a Sandscale sandbox per thread

> Give a LangGraph.js agent shell and file tools that run in a Firecracker sandbox: tools from @langchain/core, a StateGraph with ToolNode, the sandbox id passed through configurable, and cleanup that always runs. Type-checked against current packages.

Give a LangGraph.js agent shell and file tools that run in a Firecracker sandbox: tools from @langchain/core, a StateGraph with ToolNode, the sandbox id passed through configurable, and cleanup that always runs. Type-checked against current packages.

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

LangGraph gives you an agent loop you can see: a model node, a tools node, and edges between them. What it does not give you is somewhere safe for those tools to run. If a tool calls `child_process.exec`, the model’s commands run on your server. This guide puts the tools in a [Sandscale sandbox](https://sandscale.dev/sandboxes) instead, one per graph run, using LangGraph.js and the Sandscale TypeScript SDK.

The code below was type-checked with `tsc --strict` against `@langchain/langgraph` 1.7, `@langchain/core` 1.5, `@langchain/openai` 1.8, `zod` 4 and `@sandscale/sdk` 1.0. The Sandscale calls are the ones in the [TypeScript SDK reference](https://sandscale.dev/docs/sdks/typescript): `sandboxes.create`, `run`, `writeFile` and `stop`.

## Install

```bash
npm install @langchain/langgraph @langchain/core @langchain/openai zod @sandscale/sdk
export SANDSCALE_API_KEY=...   # a key with permission to create and use sandboxes
export OPENAI_API_KEY=...
```

## The code

```ts
import { tool } from '@langchain/core/tools';
import type { RunnableConfig } from '@langchain/core/runnables';
import { HumanMessage } from '@langchain/core/messages';
import { ChatOpenAI } from '@langchain/openai';
import { StateGraph, MessagesAnnotation, START } from '@langchain/langgraph';
import { ToolNode, toolsCondition } from '@langchain/langgraph/prebuilt';
import { z } from 'zod';
import { Sandscale } from '@sandscale/sdk';

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

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

function box(config: RunnableConfig) {
  const sandboxId = config.configurable?.sandboxId as string | undefined;
  const region = config.configurable?.region as string | undefined;
  if (!sandboxId) throw new Error('configurable.sandboxId is required');
  return { sandboxId, region };
}

const runShell = tool(
  async ({ command, timeout_seconds }, config) => {
    const { sandboxId, region } = box(config);
    const r = await sandscale.sandboxes.run(sandboxId, ['bash', '-lc', command], {
      region,
      workdir: '/workspace',
      timeoutSeconds: timeout_seconds,
    });
    return JSON.stringify({
      exit_code: r.exitCode,
      timed_out: r.timedOut,
      oom_killed: r.oomKilled,
      stdout: clip(r.stdout),
      stderr: clip(r.stderr),
    });
  },
  {
    name: 'run_shell',
    description:
      'Run a bash command in an isolated Linux sandbox, in /workspace. Files persist for this thread. ' +
      'There is no network access. Output over 8,000 characters is cut.',
    schema: z.object({
      command: z.string().max(4_000),
      timeout_seconds: z.number().int().min(1).max(300),
    }),
  },
);

const writeFile = tool(
  async ({ path, content }, config) => {
    const { sandboxId, region } = box(config);
    if (!path.startsWith('/workspace/')) return 'error: path must be under /workspace/';
    await sandscale.sandboxes.writeFile(sandboxId, path, content, { region });
    return `wrote ${content.length} characters to ${path}`;
  },
  {
    name: 'write_file',
    description: 'Write a text file in the sandbox. The path must be under /workspace/.',
    schema: z.object({ path: z.string(), content: z.string().max(200_000) }),
  },
);

const tools = [runShell, writeFile];
const model = new ChatOpenAI({ model: 'gpt-4.1' }).bindTools(tools);

async function callModel(state: typeof MessagesAnnotation.State) {
  const reply = await model.invoke(state.messages);
  return { messages: [reply] };
}

const graph = new StateGraph(MessagesAnnotation)
  .addNode('agent', callModel)
  .addNode('tools', new ToolNode(tools))
  .addEdge(START, 'agent')
  .addConditionalEdges('agent', toolsCondition)
  .addEdge('tools', 'agent')
  .compile();

export async function solve(task: string) {
  const sb = await sandscale.sandboxes.create({
    template: 'builtin:python',
    timeoutSeconds: 1800,
    labels: { app: 'langgraph-agent' },
  });
  try {
    const result = await graph.invoke(
      { messages: [new HumanMessage(task)] },
      { configurable: { sandboxId: sb.id, region: sb.region }, recursionLimit: 40 },
    );
    return result.messages.at(-1)?.content;
  } finally {
    await sandscale.sandboxes.stop(sb.id, { region: sb.region });
  }
}
```

## How it fits together

**The graph is the standard tool loop.** `StateGraph(MessagesAnnotation)` keeps the message list. The `agent` node calls the model with the tools bound; `toolsCondition` sends the run to the `tools` node when the model asked for a tool and ends it otherwise; `ToolNode` runs the requested tools and appends their results. Nothing here is specific to Sandscale, which is the point: the sandbox lives entirely inside the tool functions.

**The sandbox id travels in `configurable`.** LangChain passes the run’s config to each tool as its second argument, so `solve` puts `sandboxId` and `region` in `configurable` and the tools read them back with `box(config)`. The graph itself is compiled once and shared; each invocation gets its own sandbox. Two concurrent `solve` calls never touch each other’s files, because each box is its own Firecracker microVM with its own kernel and disk.

**Errors stay inside the conversation.** `run_shell` returns the exit code, `timed_out` and `oom_killed` alongside the output as JSON. A failing test or a killed process is something the model should see and react to, not an exception that ends the graph. Only infrastructure failures, such as an API error from Sandscale, throw.

**Output is clipped.** Test runners and package managers print a lot. The tool cuts each stream at 8,000 characters and says how much it cut, so one noisy command cannot fill the context window. [Truncating tool output for LLMs](https://sandscale.dev/blog/truncating-tool-output-for-llms) goes further.

**The tool descriptions match the box.** The sandbox is created without a `network` option, and the SDK’s default is `none`, so the description tells the model there is no network. If you create the box with `network: 'allowlist'`, where your plan includes it, change the description to say what it can reach.

**Cleanup is in `finally`.** `sandboxes.stop` runs however the graph ends, including when it hits `recursionLimit`. Stopping deletes the sandbox’s disk. `timeoutSeconds: 1800` is the backstop: if your process dies before `finally` runs, the sandbox stops when its time is up.

## Variations

**Keep state across turns.** For a chat UI where each user message is a new graph invocation, create the sandbox when the conversation starts, store its id with the conversation (or in a LangGraph checkpointer’s thread metadata), and pass the same id in `configurable` on every turn. Between turns, `sandboxes.pause` keeps memory and disk without the box staying awake, and `sandboxes.resume` brings it back. [A code interpreter for a chat product](https://sandscale.dev/blog/use-case-chat-code-interpreter) walks through that lifecycle.

**Start from a prepared project.** If every run needs the same repository with dependencies installed, set it up once, call `sandboxes.snapshot`, and create each run’s sandbox with `snapshotId` instead of a template. A snapshot is an archive of `/workspace`.

**Put a person in the loop.** LangGraph’s `interrupt` can pause before the `tools` node for commands you want reviewed. Sandscale’s own [approvals](https://sandscale.dev/security/approvals) and [agent policy](https://sandscale.dev/security/agent-policy) apply on the server side too, so a blocked action stays blocked even if the graph’s check is skipped.

**Label for traceability.** `labels: { app: 'langgraph-agent' }` is stored with the sandbox, so you can tell which agent started a box when you list them. Add a user or thread id if you need per-user traces; see [labels and run records](https://sandscale.dev/blog/labels-and-run-records-for-traceability).

## Cost

Each sandbox uses awake vCPU-hours while it runs: 100 a month on the Free plan, 1,500 on Pro and 2,000 per member pooled on Team. The [plans reference](https://sandscale.dev/docs/reference/plans) says a box counts only while it is awake, so stopping or pausing promptly is what keeps usage down.

**On this page**

1. Install
2. The code
3. How it fits together
4. Variations
5. Cost

**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/langgraph-js-agent-with-sandscale
