DEV Community

Sandscale
Sandscale

Posted on Originally published at sandscale.dev

LangGraph.js agents with a Sandscale sandbox per thread

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 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: sandboxes.create, run, writeFile and stop.

Install

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=...
Enter fullscreen mode Exit fullscreen mode

The code

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 });
  }
}
Enter fullscreen mode Exit fullscreen mode

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 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 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 and 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.

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 says a box counts only while it is awake, so stopping or pausing promptly is what keeps usage down.

Originally published on the Sandscale blog.

Top comments (0)