Level: Intermediate · Env: Google Cloud Shell or local terminal with gcloud, kubectl, and Python 3.11+
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.
By the end you'll be able to:
Deployment or Job resourcesSandboxTemplate with gVisor (runtimeClassName: gvisor) and controller-managed zero-trust NetworkPolicy (networkPolicyManagement: Managed)SandboxWarmPool and SandboxClaimk8s-agent-sandbox Python SDK (SandboxClient) to claim sandboxes, write files, execute commands, and reconnect across turns (adopt_existing=True)adk web) and correlate every tool call with its backing GKE podWhen 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 |
| Stateless replicas behind a load balancer - file edits in turn 1 land on a different pod in turn 2 |
| One-shot batch execution - spinning up a fresh pod for every shell command adds 15-30s of cold-start latency per turn |
Agent Sandbox ( | Pre-warmed, stateful singleton pod per session with sub-second claim latency, sticky routing via |
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
SandboxTemplate — Blueprint for each sandbox pod (runtimeClassName: gvisor, non-root user uid=1000, dropped capabilities, and networkPolicyManagement: Managed).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.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.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:
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.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).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.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:
runtimeClassName: gvisor intercepts container syscalls in a user-space kernel so untrusted code never touches the host node's Linux kernel directly.networkPolicyManagement: Managed instructs the controller to automatically reconcile a strict NetworkPolicy that allows ingress only from sandbox-router and blocks egress to cluster-internal RFC1918 CIDRs and the cloud metadata server (169.254.169.254/32).automountServiceAccountToken: false ensures no Kubernetes API bearer token is mounted inside the container filesystem.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.
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:
test_percentage_coupon_applied — fails because integer floor division (coupon_pct // 100) zeroes out any discount under 100%test_exact_fifty_dollar_order_gets_free_shipping — fails because discounted_subtotal > 5000 has an off-by-one bug on exact $50.00 orderstest_rejects_negative_or_zero_quantity — fails because qty <= 0 is never validatedCheck 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!
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.
python3 workshop.py check-security --tenant alice
This runs three live probes inside alice's sandbox pod:
uname -r — prints the virtualized gVisor kernel version (4.4.0), proving container processes do not share the host node's Linux kernel.id — confirms the runtime executes as unprivileged uid=1000(user) gid=1000(user).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.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 |
| Claims a warm pod (or reconnects) and returns |
| Writes the buggy |
| Lists files in the sandbox workspace via |
| Reads a file from the sandbox via |
| Writes patched code to the sandbox via |
| Runs |
| Verifies gVisor |
| Calls |
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:
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:
claim_sandbox(tenant="alice") — adopts a pre-warmed pod from workshop-warmpool.seed_buggy_project(tenant="alice").run_in_sandbox(command="python3 -m unittest -v test_order_service.py") and sees 3 failures.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=...).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!
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:
alice's pod has ['__pycache__', 'order_service.py', 'test_order_service.py']bob's pod has [] (a completely clean workspace on a separate gVisor pod)Check the security boundary of alice's sandbox.
The agent calls check_sandbox_security(tenant="alice") and reports:
gvisor_kernel: 4.4.0process_identity: uid=1000(user) gid=1000(user) groups=1000(user)metadata_ssrf_blocked: trueDelete 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
sigs.k8s.io/agent-sandbox) gives AI agents stateful, singleton pod-backed workspaces on Kubernetes.SandboxTemplate centralizes defense-in-depth (runtimeClassName: gvisor, non-root user, automountServiceAccountToken: false, and networkPolicyManagement: Managed).SandboxWarmPool + SandboxClaim eliminate pod cold-start latency by keeping pre-warmed sandboxes ready for instant adoption and refilling the pool in the background.SandboxClient(..., adopt_existing=True) lets multi-turn coding agents reconnect to the exact same pod across tool calls and turns.