For translation, open lesson in new tab and use Chrome translate

Sandboxes and LocalShell

Lesson Video Walkthrough

The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.

The filesystem backends from the last lesson give the agent file tools: ls, read_file, write_file, edit_file, glob, grep. LocalShellBackend and sandbox backends add one more: execute, which runs shell commands.


graph TB Tools[Filesystem Tools] --> Backend[Backend] Backend --> LocalShell[Local Shell] Backend --> Sandbox[Sandbox Backend] LocalShell --> Execute["+ execute tool"] Sandbox --> Execute classDef trigger fill:#CCE9FF,stroke:#006DDD,stroke-width:2px,color:#030710 classDef hub fill:#7FC8FF,stroke:#006DDD,stroke-width:2px,color:#030710 classDef process fill:#E5F4FF,stroke:#006DDD,stroke-width:1px,color:#030710 classDef output fill:#030710,stroke:#030710,stroke-width:1px,color:#F2FAFF class Tools trigger class Backend hub class LocalShell,Sandbox process class Execute output

The execute tool

Shell-capable backends expose an execute(command) tool. The agent calls it to run scripts it has written, invoke CLI tools, and compile and test code. The combined command output, exit code, and execution metadata come back as a tool result on the next LLM call.


How do you choose?

Two shell-capable backends are available: LocalShellBackend and sandbox backends. The deciding factor is isolation.

LocalShellBackend runs code on the host; sandbox backends run code in an isolated container

Use a sandbox. Agent generated code and packages the agent may load are untrusted by nature. Use a sandbox to isolate that code from your infrastructure.

Use LocalShellBackend when building a local tool where the agent working directly on your machine is the point, such as a coding assistant or desktop agent. It is not appropriate for production or untrusted input.


Sandbox Backends

A sandbox is a temporary, isolated workspace containing a filesystem, command execution environment, and other resources. Sandbox backends run commands inside that workspace instead of on your host machine.

There are two models for using a sandbox with an agent:

Two sandbox models: agent in sandbox vs sandbox as a tool

Agent in Sandbox: The agent itself runs inside the sandbox. The LLM API key(s) live inside the sandbox. To update the agent, you must rebuild the sandbox image. This is useful when you want the execution environment to mirror your production infrastructure.

Sandbox as a Tool: The agent runs outside and calls the sandbox via execute and filesystem tools. The LLM API keys stay on your host, agent code is easy to update, and sandbox failures don't affect agent state. This is the model used in this course.

Managing credentials in a sandbox

Sandbox-as-a-tool keeps the LLM API key on the host, away from the untrusted code running in the sandbox. But an agent often needs other keys too, to reach services on the user's behalf. LangSmith Sandboxes can attach those keys to outgoing requests without exposing them to the code the agent runs. The slideshow below shows how:

The auth proxy pattern above is specific to LangSmith Sandboxes. The proxy sidecar holds the secrets inside the sandbox, but the code the agent writes and runs never sees them, so the code cannot exfiltrate them.


Configuring a LangSmith sandbox as a tool

Here's an example of a LangSmith sandbox being configured as a backend:

# python/m2/m2.3_sandbox_agent.py
from uuid import uuid4

from deepagents import create_deep_agent
from deepagents.backends.langsmith import LangSmithSandbox
from langsmith.sandbox import SandboxClient

client = SandboxClient()
ls_sandbox = client.create_sandbox(name=f"lca-deepagents-lab-{uuid4().hex[:8]}")
print(f"Sandbox: {ls_sandbox.name}  (id: {ls_sandbox.id})")
backend = LangSmithSandbox(sandbox=ls_sandbox)

agent = create_deep_agent(
    model=model,
    backend=backend,
)

try:
    result = agent.invoke({"messages": [{"role": "user", "content": "..."}]})
    print(result["messages"][-1].text)
finally:
    client.delete_sandbox(ls_sandbox.name)
// typescript/m2/m2.3_sandbox_agent.ts
import { randomUUID } from "node:crypto";

import { LangSmithSandbox, createDeepAgent } from "deepagents";
import { SandboxClient } from "langsmith/sandbox";

const client = new SandboxClient();
const ls_sandbox = await client.createSandbox({
  name: `lca-deepagents-lab-${randomUUID().slice(0, 8)}`,
});
console.log(`Sandbox: ${ls_sandbox.name}  (id: ${ls_sandbox.id})`);
const backend = new LangSmithSandbox({ sandbox: ls_sandbox });

const agent = createDeepAgent({
  model,
  backend,
});

try {
  const result = await agent.invoke({ messages: [{ role: "user", content: "..." }] });
  console.log(result.messages.at(-1)?.text);
} finally {
  await client.deleteSandbox(ls_sandbox.name);
}

The try/finally block ensures the sandbox is deleted even if the agent raises. Sandboxes are billed resources; always clean them up.

create_sandbox(...) provisions a fresh sandbox workspace. Files persist within that sandbox until it is deleted; a newly created sandbox starts empty unless you upload files first.

createSandbox(...) provisions a fresh sandbox workspace. Files persist within that sandbox until it is deleted; a newly created sandbox starts empty unless you upload files first.


LocalShellBackend

LocalShellBackend runs commands directly on the host machine. It can scope filesystem tools to a root_dir, but execute itself runs with host permissions; no process isolation is applied.

virtual_mode=True is the default: filesystem tools (ls, read_file, write_file, etc.) are path-scoped under root_dir, and paths resolving outside it are rejected. Pass virtual_mode=False to allow absolute host paths instead. Either way, root_dir does not restrict the execute tool. Shell commands run with host permissions and can access paths outside the filesystem-tool root. That's why LocalShellBackend is unsuitable for production or untrusted input.

LocalShellBackend runs commands directly on the host machine. It can scope filesystem tools to a rootDir, but execute itself runs with host permissions; no process isolation is applied.

In TypeScript, virtualMode defaults to false (unlike Python), so pass virtualMode: true explicitly: filesystem tools (ls, read_file, write_file, etc.) are then path-scoped under rootDir, and paths resolving outside it are rejected. With the default virtualMode: false, absolute host paths are allowed. Either way, rootDir does not restrict the execute tool. Shell commands run with host permissions and can access paths outside the filesystem-tool root. That's why LocalShellBackend is unsuitable for production or untrusted input.

⚠ Security Warning

This backend grants agents direct filesystem read/write access and unrestricted shell execution on your host. Use with extreme caution and only in appropriate environments.

Appropriate use cases:

  • Local development CLIs (coding assistants, development tools)
  • Personal development environments where you trust the agent's code
  • CI/CD pipelines with proper secret management

Inappropriate use cases:

  • Production environments (such as web servers, APIs, multi-tenant systems)
  • Processing untrusted user input or executing untrusted code

Security risks:

  • Agents can execute arbitrary shell commands with your user's permissions
  • Agents can read any accessible file, including secrets (API keys, credentials, .env files)
  • Secrets may be exposed
  • File modifications and command execution are permanent and irreversible
  • Commands run directly on your host system
  • Commands can consume unlimited CPU, memory, disk

Recommended safeguards:

  • Enable Human-in-the-Loop (HITL) middleware to review and approve operations before execution. This is strongly recommended.
  • Run in dedicated development environments only. Never use on shared or production systems.
  • Use a sandbox backend for production environments requiring shell execution.

Note: virtual_mode=TruevirtualMode: true provides no security with shell access enabled, since commands can access any path on the system.


Recap

Next

Complete the Labs and Quiz above, then continue to the next lesson on the interpreter and how the agent writes and executes code directly in the main loop.


References

Documentation:

Go deeper: read the source (optional)

The lesson shows how to use this. To see how it's implemented, start with these files:

Documentation:

Go deeper: read the source (optional)

The lesson shows how to use this. To see how it's implemented, start with these files:

Blog:

Lab 1: Sandbox Agent

Lab Video Walkthrough

The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.

Inspect your own run in LangSmith. Notice the write → execute sequence running as isolated tool calls inside the LangSmith sandbox.

LangSmith Video Walkthrough

Build an agent that writes a Python script to a sandbox, executes it, and reports the output. You will see the write → execute sequence in LangSmith as a chain of tool calls.

This lab uses LangSmithSandbox; commands run in an isolated LangSmith-managed environment, not on your local machine.

Note: Sandboxes are available on every LangSmith plan, including the free Developer tier, which comes with a monthly sandbox allowance. You can cap what you spend under Settings → Billing and Usage → Usage limits.

Before running it, make sure your model API key and LangSmith sandbox credentials from setup are available in the Python environment.

Code overview of the sandbox lab: a LangSmith sandbox created for the run, passed to the agent as its backend, and deleted in a finally block.


# python/m2/m2.3_sandbox_agent.py
from uuid import uuid4

from deepagents import create_deep_agent
from deepagents.backends.langsmith import LangSmithSandbox
from langsmith.sandbox import SandboxClient
from models import model

client = SandboxClient()
ls_sandbox = client.create_sandbox(name=f"lca-deepagents-lab-{uuid4().hex[:8]}")
print(f"Sandbox: {ls_sandbox.name}  (id: {ls_sandbox.id})")
backend = LangSmithSandbox(sandbox=ls_sandbox)

agent = create_deep_agent(
    model=model,
    backend=backend,
    system_prompt=(
        "You are a coding assistant. When asked to run code, write the script "
        "to a file first, then execute it. Show the output in your final answer."
    ),
)

try:
    result = agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": (
                        "Write a Python script that prints the first 15 Fibonacci numbers, "
                        "save it to fib.py, and run it."
                    ),
                }
            ]
        }
    )
    print(result["messages"][-1].text)
finally:
    client.delete_sandbox(ls_sandbox.name)

From the repo root:

cd python
uv run ./m2/m2.3_sandbox_agent.py

Before running it, make sure your model API key and LangSmith sandbox credentials from setup are available in the TypeScript environment.

Code overview of the sandbox lab: a LangSmith sandbox created for the run, passed to the agent as its backend, and deleted in a finally block.


// typescript/m2/m2.3_sandbox_agent.ts
import { randomUUID } from "node:crypto";

import { context } from "langchain";
import { LangSmithSandbox, createDeepAgent } from "deepagents";
import { SandboxClient } from "langsmith/sandbox";

import { model } from "../models.js";

const client = new SandboxClient();
const ls_sandbox = await client.createSandbox({
  name: `lca-deepagents-lab-${randomUUID().slice(0, 8)}`,
});
console.log(`Sandbox: ${ls_sandbox.name}  (id: ${ls_sandbox.id})`);
const backend = new LangSmithSandbox({ sandbox: ls_sandbox });

const agent = createDeepAgent({
  model,
  backend,
  systemPrompt: context`
    You are a coding assistant. When asked to run code, write the script
    to a file first, then execute it. Show the output in your final answer.`,
});

try {
  const result = await agent.invoke({
    messages: [
      {
        role: "user",
        content: context`
          Write a Python script that prints the first 15 Fibonacci numbers,
          save it to fib.py, and run it.`,
      },
    ],
  });
  console.log(result.messages.at(-1)?.text);
} finally {
  await client.deleteSandbox(ls_sandbox.name);
}

From the repo root:

cd typescript
pnpm tsx ./m2/m2.3_sandbox_agent.ts

What to check:

Open LangSmith and look at the tool call sequence:

  1. write_file: agent writes fib.py into the sandbox
  2. execute: agent runs python fib.py inside the sandbox
  3. The tool result carries the stdout back to the LLM
  4. The LLM includes the output in its final answer

If the script had an error, you will see the agent call edit_file to fix it and execute again. Shell execution enables this self-correction loop; the sandbox makes it safer to run.

Try a different task:

Lab 2: Sales Chart Agent

Lab Video Walkthrough

The video and the text below cover the same material, so pick whichever format you prefer. If they ever differ, the text is the most up-to-date version.

Inspect your own run in LangSmith. Notice the file upload to the sandbox, the query and chart-generation steps, and the file read back at the end.

LangSmith Video Walkthrough

Build an agent that queries the Chinook music store database inside a sandbox and generates a chart. The agent installs its own dependencies, writes and runs Python, and you retrieve the output file from the sandbox.

This lab introduces two new patterns: uploading files to a sandbox before the agent runs, and reading files back from the sandbox after it finishes.

Note: Sandboxes are available on every LangSmith plan, including the free Developer tier, which comes with a monthly sandbox allowance. You can cap what you spend under Settings → Billing and Usage → Usage limits.

⚠ Troubleshooting timeouts: raising the model's timeout= (set in models.py) won't help; it only bounds the LLM API call, not sandbox operations. Sandbox timing has separate knobs: This lab's pip install plus chart generation is the most likely to hit the idle timeout. Check the LangSmith trace for the specific error before assuming the model's timeout= is the cause.

Before running it, make sure your model API key and LangSmith sandbox credentials from setup are available in the Python environment.


# python/m2/m2.3_sales_agent.py
from pathlib import Path
from uuid import uuid4

from deepagents import create_deep_agent
from deepagents.backends.langsmith import LangSmithSandbox
from langsmith.sandbox import SandboxClient
from models import model

DB_PATH = Path(__file__).resolve().parent / "chinook.db"

client = SandboxClient()
ls_sandbox = client.create_sandbox(name=f"lca-deepagents-lab-{uuid4().hex[:8]}")
print(f"Sandbox: {ls_sandbox.name}  (id: {ls_sandbox.id})")

backend = LangSmithSandbox(sandbox=ls_sandbox)
with open(DB_PATH, "rb") as f:
    upload_results = backend.upload_files([("/chinook.db", f.read())])

for upload_result in upload_results:
    if upload_result.error:
        raise RuntimeError(f"Failed to upload {upload_result.path}: {upload_result.error}")

agent = create_deep_agent(
    model=model,
    backend=backend,
    system_prompt=(
        "You are a sales data analyst with access to the Chinook music store database "
        "at /chinook.db. Use sqlite3 and matplotlib to answer questions with charts. "
        "This sandbox Python is externally managed, so install packages with "
        "`pip install --break-system-packages <package>` (e.g. `pip install "
        "--break-system-packages matplotlib`). sqlite3 is stdlib, so do not install it. "
        "When asked to produce a chart, write a Python script, execute it, and confirm "
        "the output file was created."
    ),
)

try:
    result = agent.invoke(
        {
            "messages": [
                {
                    "role": "user",
                    "content": (
                        "Query the Chinook database at /chinook.db to get total revenue "
                        "by genre. Create a clean donut chart showing each genre's share "
                        "of total sales revenue. Group any genres that individually "
                        "account for less than 3% of total revenue into a single 'Other' "
                        "slice. Label each slice with the genre name and percentage. "
                        "Use a visually distinct color palette, leave a white center hole, "
                        "and make sure no labels overlap with each other or with the title. "
                        "Add enough top padding so the title is fully visible. "
                        "Save the chart to /genre_revenue.png."
                    ),
                }
            ]
        }
    )
    print(result["messages"][-1].text)

    png_bytes = ls_sandbox.read("/genre_revenue.png")
    out_path = Path(__file__).parent / "genre_revenue.png"
    out_path.write_bytes(png_bytes)
    print(f"Chart saved to {out_path}")

finally:
    client.delete_sandbox(ls_sandbox.name)

From the repo root:

cd python
uv run ./m2/m2.3_sales_agent.py
open m2/genre_revenue.png

Expected output:

Sandbox: lca-deepagents-lab  (id: 510c7cfa-7809-4317-a272-715c05221a24)
Done! I've successfully created your donut chart showing revenue by genre.

Data Summary:
- Total Revenue: $2,328.60
- Rock: 35.5% ($826.65)
- Latin: 16.4% ($382.14)
- Metal: 11.2% ($261.36)
- Alternative & Punk: 10.4% ($241.56)
- TV Shows: 4.0% ($93.53)
- Jazz: 3.4% ($79.20)
- Other (<3%): 19.1% ($444.16)

Chart saved to python/m2/genre_revenue.png

The chart is saved locally as genre_revenue.png. Open it with open m2/genre_revenue.png.

Before running it, make sure your model API key and LangSmith sandbox credentials from setup are available in the TypeScript environment.


// typescript/m2/m2.3_sales_agent.ts
import { randomUUID } from "node:crypto";
import { dirname, join } from "node:path";
import { writeFileSync } from "node:fs";
import { readFile } from "node:fs/promises";
import { fileURLToPath } from "node:url";

import { context } from "langchain";
import { LangSmithSandbox, createDeepAgent } from "deepagents";
import { SandboxClient } from "langsmith/sandbox";

import { model } from "../models.js";

const __dirname = dirname(fileURLToPath(import.meta.url));
const DB_PATH = join(__dirname, "chinook.db");

const client = new SandboxClient();
const ls_sandbox = await client.createSandbox({
  name: `lca-deepagents-lab-${randomUUID().slice(0, 8)}`,
});
console.log(`Sandbox: ${ls_sandbox.name}  (id: ${ls_sandbox.id})`);

const backend = new LangSmithSandbox({ sandbox: ls_sandbox });

// Upload the Chinook database into the sandbox.
const dbBytes = await readFile(DB_PATH);
const uploadResults = await backend.uploadFiles([["/chinook.db", dbBytes]]);

for (const result of uploadResults) {
  if (result.error) {
    throw new Error(`Failed to upload ${result.path}: ${result.error}`);
  }
}

const agent = createDeepAgent({
  model,
  backend,
  systemPrompt: context`
    You are a sales data analyst with access to the Chinook music store database
    at /chinook.db. Use sqlite3 and matplotlib to answer questions with charts.
    This sandbox Python is externally managed, so install packages with
    \`pip install --break-system-packages <package>\` (e.g. \`pip install
    --break-system-packages matplotlib\`). sqlite3 is stdlib, so do not install it.
    When asked to produce a chart, write a Python script, execute it, and confirm
    the output file was created.`,
});

try {
  const result = await agent.invoke({
    messages: [
      {
        role: "user",
        content: context`
          Query the Chinook database at /chinook.db to get total revenue
          by genre. Create a clean donut chart showing each genre's share
          of total sales revenue. Group any genres that individually
          account for less than 3% of total revenue into a single 'Other'
          slice. Label each slice with the genre name and percentage.
          Use a visually distinct color palette, leave a white center hole,
          and make sure no labels overlap with each other or with the title.
          Add enough top padding so the title is fully visible.
          Save the chart to /genre_revenue.png.`,
      },
    ],
  });
  console.log(result.messages.at(-1)?.text);

  const pngBytes = await ls_sandbox.read("/genre_revenue.png");
  const outPath = join(__dirname, "genre_revenue.png");
  writeFileSync(outPath, pngBytes);
  console.log(`Chart saved to ${outPath}`);
} finally {
  await client.deleteSandbox(ls_sandbox.name);
}

From the repo root:

cd typescript
pnpm tsx ./m2/m2.3_sales_agent.ts
open m2/genre_revenue.png

Expected output:

Sandbox: lca-deepagents-lab  (id: 510c7cfa-7809-4317-a272-715c05221a24)
Done! I've successfully created your donut chart showing revenue by genre.

Data Summary:
- Total Revenue: $2,328.60
- Rock: 35.5% ($826.65)
- Latin: 16.4% ($382.14)
- Metal: 11.2% ($261.36)
- Alternative & Punk: 10.4% ($241.56)
- TV Shows: 4.0% ($93.53)
- Jazz: 3.4% ($79.20)
- Other (<3%): 19.1% ($444.16)

Chart saved to typescript/m2/genre_revenue.png

The chart is saved locally as genre_revenue.png. Open it with open m2/genre_revenue.png.

Expected chart [click to expand]



Donut chart showing Chinook revenue by genre

Check your understanding

Question: The agent runs pytest through execute and one test fails. What does it get back to work with on its next model call?
A) Only a pass or fail flag, so it must rerun pytest with verbose flags
B) Only stdout, since stderr is written to a separate sandbox log file
C) The combined command output, along with the nonzero exit code
D) Nothing yet, until it calls read_file on the command output log
Question: You create LocalShellBackend(root_dir='/home/me/proj') with the default virtual_mode. The agent calls read_file on /etc/hosts, then execute('cat /etc/hosts'). What should you expect?
A) Both are blocked, since root_dir scopes every tool on this backend
B) read_file stays inside root_dir, but execute can print the host file
C) Both succeed, since root_dir only sets the starting working directory
D) read_file reaches the host file, but execute is blocked outside root_dir
Question: You create new LocalShellBackend({ rootDir: '/home/me/proj', virtualMode: true }). The agent calls read_file on /etc/hosts, then execute('cat /etc/hosts'). What should you expect?
A) Both are blocked, since rootDir scopes every tool on this backend
B) read_file stays inside rootDir, but execute can print the host file
C) Both succeed, since rootDir only sets the starting working directory
D) read_file reaches the host file, but execute is blocked outside rootDir
Question: This course runs the agent on your host and calls a LangSmith sandbox through execute and the file tools. What is one reason the lesson gives for this Sandbox as a Tool setup?
A) Commands run faster because the sandbox shares the host process space
B) Updating the agent does not require rebuilding a sandbox image
C) The agent state lives in the sandbox, so it survives host restarts
D) The sandbox can read your local files directly without any setup
Question: You create a fresh LangSmith sandbox and ask the agent to query chinook.db, which is on your laptop. The agent reports that the file does not exist. What does the lab do to fix this?
A) Calls backend.upload_files() with the file bytes before invoking the agent
B) Adds the laptop file path to the system prompt so the agent can find it
C) Sets root_dir to the laptop folder so the sandbox mounts that directory
D) Has the agent run execute to copy the file from your laptop to the sandbox
Question: You create a fresh LangSmith sandbox and ask the agent to query chinook.db, which is on your laptop. The agent reports that the file does not exist. What does the lab do to fix this?
A) Calls backend.uploadFiles() with the file bytes before invoking the agent
B) Adds the laptop file path to the system prompt so the agent can find it
C) Sets rootDir to the laptop folder so the sandbox mounts that directory
D) Has the agent run execute to copy the file from your laptop to the sandbox
Question: A teammate wants users to submit arbitrary scripts for the agent to run, and proposes LocalShellBackend with a scratch root directory and virtual mode on to keep it safe. What is the problem?
A) Virtual mode disables execute, so the submitted scripts cannot run
B) The root directory has no effect without FilesystemPermission rules
C) LocalShellBackend can only run shell builtins such as ls and cat
D) execute runs with host permissions; the root only limits file tools

Prove Persistence in Your Own Sandbox

Lab 1 ran one script in a sandbox. In this homework, you'll send two separate tasks to the same sandbox, one after the other, to prove that its filesystem persists between invoke() calls instead of resetting each time. Lab 2 relies on this too: it uploads a database before the agent runs and reads a chart back after it finishes.

Open python/m2/m2.3_homework.py.

  1. TODO 1: write a system prompt for your sandboxed agent. Give it any persona and working rules you like, as long as it tells the agent to:
    • write code to a file before running it, as in Lab 1
    • install packages with pip install --break-system-packages <package>, as in Lab 2, because this sandbox's Python is externally managed and matplotlib isn't preinstalled
    • use matplotlib when it needs to build a chart
  2. TODO 2: write two task messages for the same sandbox. TASK_ONE should have the agent generate or compute some numeric data and save it to a file. TASK_TWO must read that same file back, without regenerating the data, and turn it into a matplotlib chart saved at a path you choose; it only proves the sandbox persisted if it reuses TASK_ONE's file instead of recreating the data.
  3. TODO 3: point CHART_PATH at the exact path you told the agent to save the chart to in TASK_TWO, so the script can read the image back from the sandbox, the same way Lab 2 does.

Run it

cd python
uv run ./m2/m2.3_homework.py
open m2/homework_chart.png

Stuck, or want to see the finished shape before you start? m2.3_homework_filled.py is a reference copy with every TODO filled in (using a made-up monthly rainfall dataset charted as a bar chart, with a data-visualization-assistant persona); run it the same way to see what "done" looks like end to end.

Try to avoid peeking unless you're really stuck. You'll get more out of this by working through the TODOs yourself first.


Optional Extension: Want To Code From Scratch?

What you'll build: proof that root_dir/virtual_mode on LocalShellBackend restricts the filesystem tools but never execute, watched safely by gating execute behind your approval instead of letting it run unattended.

⚠ No sandbox here. Unlike Lab 1/2 and the homework above, this runs on LocalShellBackend, which executes directly on your own machine with no isolation. The approval step below is your only safeguard, so only approve a command you would be comfortable running yourself.

Requirements:

  • Write your own create_deep_agent(model=model, backend=LocalShellBackend(root_dir=..., virtual_mode=True), interrupt_on={"execute": {"allowed_decisions": ["approve", "reject"]}}, checkpointer=MemorySaver()) call from scratch, in a new file under python/m2/. Point root_dir at a fresh scratch directory you create just for this exercise, e.g. Path(__file__).parent / "sandbox_scratch". No file in this module uses LocalShellBackend directly, so check its own docstring for the exact root_dir/virtual_mode semantics rather than looking for a worked example nearby.
  • Reuse (or rewrite) the approve/reject review loop from the homework in the HITL lesson to handle the interrupt: it's what lets you see and vet a command before it runs.
  • Write a task that has the agent write a file with write_file inside the scratch directory (ungated, confined to root_dir).
  • Write a second task that has the agent use execute on a harmless, read-only target OUTSIDE root_dir (e.g. pwd, or listing your home directory). When the interrupt fires, read the exact command before approving it, then confirm it succeeds anyway, proving virtual_mode never scoped execute in the first place.
  • Try rejecting an execute call once and see the agent respond to your rejection message instead of the command's real output.

Prove Persistence in Your Own Sandbox

Lab 1 ran one script in a sandbox. In this homework, you'll send two separate tasks to the same sandbox, one after the other, to prove that its filesystem persists between invoke() calls instead of resetting each time. Lab 2 relies on this too: it uploads a database before the agent runs and reads a chart back after it finishes.

Open typescript/m2/m2.3_homework.ts.

  1. TODO 1: write a system prompt for your sandboxed agent. Give it any persona and working rules you like, as long as it tells the agent to:
    • write code to a file before running it, as in Lab 1
    • install packages with pip install --break-system-packages <package>, as in Lab 2, because this sandbox's Python is externally managed and matplotlib isn't preinstalled
    • use matplotlib when it needs to build a chart
  2. TODO 2: write two task messages for the same sandbox. TASK_ONE should have the agent generate or compute some numeric data and save it to a file. TASK_TWO must read that same file back, without regenerating the data, and turn it into a matplotlib chart saved at a path you choose; it only proves the sandbox persisted if it reuses TASK_ONE's file instead of recreating the data.
  3. TODO 3: point CHART_PATH at the exact path you told the agent to save the chart to in TASK_TWO, so the script can read the image back from the sandbox, the same way Lab 2 does.

Run it

cd typescript
pnpm tsx ./m2/m2.3_homework.ts
open m2/homework_chart.png

Stuck, or want to see the finished shape before you start? m2.3_homework_filled.ts is a reference copy with every TODO filled in (using a made-up monthly rainfall dataset charted as a bar chart, with a data-visualization-assistant persona); run it the same way to see what "done" looks like end to end.

Try to avoid peeking unless you're really stuck. You'll get more out of this by working through the TODOs yourself first.


Optional Extension: Want To Code From Scratch?

What you'll build: proof that rootDir/virtualMode on LocalShellBackend restricts the filesystem tools but never execute, watched safely by gating execute behind your approval instead of letting it run unattended.

⚠ No sandbox here. Unlike Lab 1/2 and the homework above, this runs on LocalShellBackend, which executes directly on your own machine with no isolation. The approval step below is your only safeguard, so only approve a command you would be comfortable running yourself.

Requirements:

  • Write your own createDeepAgent({ model, backend: new LocalShellBackend({ rootDir: ..., virtualMode: true }), interruptOn: { execute: { allowedDecisions: ["approve", "reject"] } }, checkpointer: new MemorySaver() }) call from scratch, in a new file under typescript/m2/. Point rootDir at a fresh scratch directory you create just for this exercise. No file in this module uses LocalShellBackend directly, so check its own docstring for the exact rootDir/virtualMode semantics rather than looking for a worked example nearby.
  • Reuse (or rewrite) the approve/reject review loop from the homework in the HITL lesson to handle the interrupt: it's what lets you see and vet a command before it runs.
  • Write a task that has the agent write a file with write_file inside the scratch directory (ungated, confined to rootDir).
  • Write a second task that has the agent use execute on a harmless, read-only target OUTSIDE rootDir (e.g. pwd, or listing your home directory). When the interrupt fires, read the exact command before approving it, then confirm it succeeds anyway, proving virtualMode never scoped execute in the first place.
  • Try rejecting an execute call once and see the agent respond to your rejection message instead of the command's real output.