Level: Intermediate · Env: Google Cloud Shell or local terminal with gcloud, kubectl, and Python 3.11+

What you'll build

An autonomous coding agent (autofix_agent) that claims pre-warmed, gVisor-isolated Kubernetes pods in milliseconds using Agent Sandbox (sigs.k8s.io/agent-sandbox), seeds a buggy e-commerce checkout module, runs unit tests inside the sandbox, inspects the failures, patches all three bugs, and verifies kernel and network isolation on GKE Autopilot.

Learning objectives

By the end you'll be able to:

When an AI agent writes and executes code, running subprocess.run() inside the agent's own process is a critical security risk: untrusted LLM-generated code can read the agent's API keys, reach cloud metadata endpoints (169.254.169.254), or tamper with other users' files.

Plain Kubernetes primitives don't quite fit interactive agent loops either:

Kubernetes Primitive

Why it falls short for interactive AI agents

Deployment

Stateless replicas behind a load balancer - file edits in turn 1 land on a different pod in turn 2

Job

One-shot batch execution - spinning up a fresh pod for every shell command adds 15-30s of cold-start latency per turn

Agent Sandbox (Sandbox + SandboxWarmPool + SandboxClaim)

Pre-warmed, stateful singleton pod per session with sub-second claim latency, sticky routing via sandbox-router, gVisor kernel isolation, and automatic zero-trust NetworkPolicy

flowchart LR User["Developer / Web UI"] Agent["autofix_agent (Coding Agent)"] Router["sandbox-router (ClusterIP)"] Pool["SandboxWarmPool (2 warm pods)"] PodA["Sandbox Pod (alice) - gVisor"] PodB["Sandbox Pod (bob) - gVisor"] User --> Agent Agent -- "k8s-agent-sandbox SDK" --> Router Router -- "X-Sandbox-ID: workshop-alice" --> PodA Router -- "X-Sandbox-ID: workshop-bob" --> PodB Pool -. "sub-second adoption" .-> PodA Pool -. "sub-second adoption" .-> PodB
View diagram source
flowchart LR
    User["Developer / Web UI"]
    Agent["autofix_agent (Coding Agent)"]
    Router["sandbox-router (ClusterIP)"]
    Pool["SandboxWarmPool (2 warm pods)"]
    PodA["Sandbox Pod (alice) - gVisor"]
    PodB["Sandbox Pod (bob) - gVisor"]

    User --> Agent
    Agent -- "k8s-agent-sandbox SDK" --> Router
    Router -- "X-Sandbox-ID: workshop-alice" --> PodA
    Router -- "X-Sandbox-ID: workshop-bob" --> PodB
    Pool -. "sub-second adoption" .-> PodA
    Pool -. "sub-second adoption" .-> PodB

The four building blocks

  1. SandboxTemplate — Blueprint for each sandbox pod (runtimeClassName: gvisor, non-root user uid=1000, dropped capabilities, and networkPolicyManagement: Managed).
  2. SandboxWarmPool — Keeps a pool of pre-started pods warm so claiming a sandbox takes milliseconds instead of waiting for GKE Autopilot node provisioning or image pulls.
  3. SandboxClaim — Binds a user or agent session (for example, workshop-alice) to a warm pod and triggers the pool to replenish itself in the background.
  4. sandbox-router — Stateless Go reverse proxy in agent-sandbox-system that routes SDK file and command calls to the right sandbox pod via the X-Sandbox-ID header.

Clone the workshop repository and move into the agent-sandbox-gke directory:

git clone https://github.com/adityajoshi12/ai-workshops/
cd ai-workshops/agent-sandbox-gke

Authenticate gcloud and set your GCP project:

gcloud auth login
gcloud auth application-default login
gcloud config set project YOUR_PROJECT_ID

gcloud services enable container.googleapis.com aiplatform.googleapis.com

Run setup-gke.sh to create (or reuse) a GKE Autopilot cluster, install the official Agent Sandbox controller release (sandbox-with-extensions.yaml), and deploy sandbox-router:

./setup-gke.sh

What setup-gke.sh does under the hood:

  1. Creates (or reuses) a GKE Autopilot cluster named agent-sandbox-workshop in us-central1. GKE Autopilot includes GKE Sandbox (gVisor) out of the box — any pod with runtimeClassName: gvisor automatically runs inside its own user-space kernel.
  2. Applies sandbox-with-extensions.yaml from the latest kubernetes-sigs/agent-sandbox GitHub release, registering the core Sandbox CRD (agents.x-k8s.io/v1beta1) and extension CRDs (SandboxTemplate, SandboxWarmPool, SandboxClaim under extensions.agents.x-k8s.io/v1beta1).
  3. Deploys manifests/00-sandbox-router.yaml and pins its image tag (registry.k8s.io/agent-sandbox/sandbox-router-go:v1.0.6) to match the installed controller release.
  4. Creates the agent-sandbox-workshop namespace and sets it as your current kubectl namespace.

Verify both control-plane deployments are Running before continuing:

kubectl get pods -n agent-sandbox-system

You should see agent-sandbox-controller (1/1) and two sandbox-router replicas (1/1).

Now create a Python virtual environment and install the required packages (k8s-agent-sandbox and google-adk):

python3 -m venv .venv
source .venv/bin/activate
pip install --upgrade pip
pip install -r requirements.txt

Inspect manifests/01-sandboxtemplate.yaml before applying it:

manifests/01-sandboxtemplate.yaml

apiVersion: extensions.agents.x-k8s.io/v1beta1
kind: SandboxTemplate
metadata:
  name: workshop-template
  namespace: agent-sandbox-workshop
spec:
  networkPolicyManagement: Managed
  podTemplate:
    spec:
      runtimeClassName: gvisor
      automountServiceAccountToken: false
      securityContext:
        runAsNonRoot: true
        runAsUser: 1000
        runAsGroup: 1000
      containers:
        - name: python-runtime
          image: us-central1-docker.pkg.dev/k8s-staging-images/agent-sandbox/python-runtime-sandbox:latest-main
          ports:
            - containerPort: 8888
          securityContext:
            allowPrivilegeEscalation: false
            capabilities:
              drop:
                - ALL

Three lines in this template do the heavy security lifting:

Now inspect manifests/02-sandboxwarmpool.yaml:

manifests/02-sandboxwarmpool.yaml

apiVersion: extensions.agents.x-k8s.io/v1beta1
kind: SandboxWarmPool
metadata:
  name: workshop-warmpool
  namespace: agent-sandbox-workshop
spec:
  replicas: 2
  sandboxTemplateRef:
    name: workshop-template

Apply both manifests and wait for the two pre-warmed gVisor pods to become ready:

kubectl apply -f manifests/01-sandboxtemplate.yaml
kubectl apply -f manifests/02-sandboxwarmpool.yaml

kubectl wait sandboxwarmpool/workshop-warmpool   -n agent-sandbox-workshop   --for=jsonpath='{.status.readyReplicas}'=2 --timeout=180s

Open a second terminal and leave a live watch running for the rest of the codelab:

kubectl get pods,sandboxclaims -n agent-sandbox-workshop -w

Open workshop.py. It uses SandboxClient from k8s_agent_sandbox to demonstrate the four stages of a coding agent session in ~180 lines of plain Python:

workshop.py (excerpt)

from k8s_agent_sandbox import SandboxClient

def get_sandbox(client: SandboxClient, tenant: str):
    claim_name = f"workshop-{tenant}"
    sandbox = client.create_sandbox(
        warmpool="workshop-warmpool",
        namespace="agent-sandbox-workshop",
        claim_name=claim_name,
        adopt_existing=True,
    )
    return sandbox

Notice adopt_existing=True: on the first call, create_sandbox creates SandboxClaim/workshop-alice and adopts a warm pod from workshop-warmpool. On subsequent calls for the same tenant, it reconnects to that exact same pod so files written in earlier steps are still on disk.

1. Seed the buggy project and run unit tests (3 FAIL, 1 PASS)

python3 workshop.py seed --tenant alice

You'll see the backing pod name and container printed in the terminal, followed by unittest output showing 3 failing tests in order_service.py:

Check your kubectl get pods,sandboxclaims -w terminal: as soon as workshop-alice claimed one warm pod, workshop-warmpool automatically spawned a replacement pod to keep readyReplicas at 2!

2. Reconnect to the same sandbox and fix the bugs (4 PASS)

python3 workshop.py fix --tenant alice

Notice that workshop.py fix connects to the exact same pod (adopt_existing=True), sees order_service.py and test_order_service.py already in the workspace, overwrites order_service.py with the fixed implementation, and re-runs unittest — all 4 tests pass.

3. Verify the gVisor & NetworkPolicy security boundary

python3 workshop.py check-security --tenant alice

This runs three live probes inside alice's sandbox pod:

  1. uname -r — prints the virtualized gVisor kernel version (4.4.0), proving container processes do not share the host node's Linux kernel.
  2. id — confirms the runtime executes as unprivileged uid=1000(user) gid=1000(user).
  3. A Python HTTP probe to http://169.254.169.254 (the GKE instance metadata server) — times out and exits non-zero because the controller-managed NetworkPolicy drops egress to 169.254.169.254/32.

4. Clean up the claim

python3 workshop.py cleanup --tenant alice

This deletes SandboxClaim/workshop-alice and terminates its backing pod.

In the previous step, workshop.py applied a pre-written fix. Now let's hand the sandbox tools to Gemini so the LLM diagnoses and fixes the bugs autonomously!

Open autofix_agent/agent.py. It wraps SandboxClient into 8 typed Python tool functions and passes them to an Agent:

autofix_agent/agent.py (excerpt)

def _connect(tenant: str):
    claim_name = f"workshop-{tenant}"
    start = time.monotonic()
    sbx = _client.create_sandbox(
        warmpool=WARMPOOL,
        namespace=NAMESPACE,
        claim_name=claim_name,
        adopt_existing=True,
    )
    elapsed_ms = round((time.monotonic() - start) * 1000, 1)
    pod_name = sbx.get_pod_name()
    logger.info(
        "[AgentSandbox] tenant=%s claim=%s pod=%s container=python-runtime (%sms)",
        tenant, claim_name, pod_name, elapsed_ms,
    )
    return sbx, claim_name, pod_name, elapsed_ms

Every tool returns a structured dict that includes sandbox_pod (sbx.get_pod_name()), container (python-runtime), and claim_latency_ms:

Tool Function

What it does inside the tenant's sandbox

claim_sandbox(tenant)

Claims a warm pod (or reconnects) and returns sandbox_pod, claim_latency_ms, and kernel

seed_buggy_project(tenant)

Writes the buggy order_service.py and test_order_service.py into the sandbox

list_sandbox_files(tenant)

Lists files in the sandbox workspace via sbx.files.list(".")

read_sandbox_file(path, tenant)

Reads a file from the sandbox via sbx.files.read(path)

write_sandbox_file(path, content, tenant)

Writes patched code to the sandbox via sbx.files.write(path, content)

run_in_sandbox(command, tenant)

Runs unittest or shell commands via sbx.commands.run(command)

check_sandbox_security(tenant)

Verifies gVisor uname -r, non-root id, and blocked 169.254.169.254 SSRF

delete_sandbox(tenant)

Calls sbx.terminate() to delete the SandboxClaim and pod

sequenceDiagram participant U as Developer (Web UI) participant A as autofix_agent (Gemini) participant R as sandbox-router participant P as Sandbox Pod (gVisor) U->>A: "Claim a sandbox for alice, seed the buggy project, and fix all 3 bugs" A->>R: claim_sandbox(tenant="alice") R->>P: Adopt warm pod (workshop-warmpool-xxx) A->>R: seed_buggy_project(tenant="alice") A->>R: run_in_sandbox("python3 -m unittest -v test_order_service.py") P-->>A: 3 FAILED, 1 OK (exit_code=1) A->>R: read_sandbox_file("order_service.py") P-->>A: Buggy source code A->>R: write_sandbox_file("order_service.py", patched_code) A->>R: run_in_sandbox("python3 -m unittest -v test_order_service.py") P-->>A: 4 OK (exit_code=0) A-->>U: Summary with sandbox_pod, claim_latency_ms, and root causes fixed
View diagram source
sequenceDiagram
    participant U as Developer (Web UI)
    participant A as autofix_agent (Gemini)
    participant R as sandbox-router
    participant P as Sandbox Pod (gVisor)

    U->>A: "Claim a sandbox for alice, seed the buggy project, and fix all 3 bugs"
    A->>R: claim_sandbox(tenant="alice")
    R->>P: Adopt warm pod (workshop-warmpool-xxx)
    A->>R: seed_buggy_project(tenant="alice")
    A->>R: run_in_sandbox("python3 -m unittest -v test_order_service.py")
    P-->>A: 3 FAILED, 1 OK (exit_code=1)
    A->>R: read_sandbox_file("order_service.py")
    P-->>A: Buggy source code
    A->>R: write_sandbox_file("order_service.py", patched_code)
    A->>R: run_in_sandbox("python3 -m unittest -v test_order_service.py")
    P-->>A: 4 OK (exit_code=0)
    A-->>U: Summary with sandbox_pod, claim_latency_ms, and root causes fixed

Configure your Gemini backend (pick Vertex AI or Gemini Developer API) and launch adk web from the agent-sandbox-gke/ directory:

Option A - Vertex AI:

export GOOGLE_GENAI_USE_VERTEXAI=TRUE
export GOOGLE_CLOUD_PROJECT="$(gcloud config get-value project)"
export GOOGLE_CLOUD_LOCATION="global"

adk web
 or 
adk web --allow_origins="regex:https://.*\.cloudshell\.dev" # running in google cloudshell

Option B - Gemini API Key:

export GOOGLE_API_KEY="YOUR_GEMINI_API_KEY"
export GOOGLE_GENAI_USE_VERTEXAI=FALSE

adk web
 or
adk web --allow_origins="regex:https://.*\.cloudshell\.dev" # running in google cloudshell

Open http://127.0.0.1:8000 in your browser (or click Web Preview -> Preview on port 8000 in Cloud Shell) and select autofix_agent from the top-left dropdown.

Run these four prompts in order while watching both the Trace / Events panel in your browser and your terminal logs:

Prompt 1: Autonomous Bug-Fix Loop

Claim a sandbox for alice, seed the buggy project, run the unit tests in test_order_service.py, read order_service.py to fix all 3 bugs, and re-run the unit tests to confirm all 4 pass.

Watch the agent execute the entire software engineering loop on its own:

  1. Calls claim_sandbox(tenant="alice") — adopts a pre-warmed pod from workshop-warmpool.
  2. Calls seed_buggy_project(tenant="alice").
  3. Calls run_in_sandbox(command="python3 -m unittest -v test_order_service.py") and sees 3 failures.
  4. Calls read_sandbox_file(path="order_service.py"), spots the 3 bugs from the docstring and test tracebacks, and calls write_sandbox_file(path="order_service.py", content=...).
  5. Re-runs run_in_sandbox until all 4 unit tests return OK (exit_code: 0).

Click any tool call in the left-hand Events panel — every tool response shows the exact sandbox_pod name and container: "python-runtime", matching the [AgentSandbox] lines in your terminal!

Prompt 2: Multi-Tenant Filesystem Isolation (alice vs. bob)

Claim a second sandbox for bob and list the files in both alice and bob's sandboxes to prove they are running on separate pods with isolated filesystems.

The agent claims workshop-bob (adopting the second warm pod from workshop-warmpool) and calls list_sandbox_files for both tenants:

Prompt 3: Live Security & SSRF Boundary Verification

Check the security boundary of alice's sandbox.

The agent calls check_sandbox_security(tenant="alice") and reports:

Prompt 4: Clean Up Tenant Sandboxes

Delete both alice and bob's sandboxes.

The agent calls delete_sandbox for both alice and bob, deleting both SandboxClaim resources and terminating their pods.

no matches for kind "SandboxTemplate"

when applying manifests: The Agent Sandbox controller CRDs are not installed on the current cluster, or kubectl is pointing at a different cluster context. Run ./setup-gke.sh and confirm kubectl get crds | grep agents.x-k8s.io lists sandboxes, sandboxclaims, sandboxtemplates, and sandboxwarmpools.

sandbox-router

pods stuck in

ImagePullBackOff

or

Ready 0/1

: If you applied the upstream sandbox-router/deploy directory directly instead of manifests/00-sandbox-router.yaml, two things happen on GKE: the upstream example deployment.yaml references :latest (which does not exist on registry.k8s.io/agent-sandbox/sandbox-router-go), and the upstream example networkpolicy.yaml blocks egress to GKE's off-cluster control plane IP. Re-run ./setup-gke.sh to apply manifests/00-sandbox-router.yaml, which pins the release tag (v1.0.6) and omits the restrictive router NetworkPolicy.

FinishReason.MALFORMED_FUNCTION_CALL

in the Web UI: Gemini 3.5 Flash uses strict JSON schema function declarations. If you add a custom tool to autofix_agent/agent.py, make sure every parameter has a type annotation and an entry under Args: in the function docstring, and avoid pasting raw bash snippets with backticks inside Agent(instruction=...).

To delete only the workshop namespace (agent-sandbox-workshop) while keeping the GKE cluster running for more experiments:

./teardown-gke.sh

To delete the workshop namespace, sandbox-router, the controller, and the GKE Autopilot cluster completely so you incur zero ongoing cloud charges:

./teardown-gke.sh --full

Kubernetes Agent Sandbox Docsagent-sandbox GitHub Repository