如何在 Cloud Run 上使用 Claude Agent SDK 部署自主智能体

1. 简介

概览

AI 智能体正在从简单的对话式聊天机器人转变为能够执行 bash 命令、运行单元测试、查询 API 和修改源代码的自主系统。在生产环境中安全运行这些工作负载面临两大核心架构挑战:

  1. 代码执行安全:由 LLM 生成的不受信任的代码不应直接在主机操作系统上运行,也不应访问平台密文和凭证。
  2. 状态和计算生命周期:Agentic Workflows 可以要求持久的专用工作区(例如长期运行的开发环境、交互式终端或后台开发服务器),也可以要求无状态、事件驱动、可缩减至零的 API(例如传入的网络钩子或自动问题分类)。

在此 Codelab 中,您将使用官方 Claude Agent SDK (claude-agent-sdk) 在 Google Cloud Run 上构建和部署自主 AI 智能体,并使用 Cloud Run 沙盒和沙盒模板(公开预览版)进行软件隔离的 gVisor 代码执行。

您可以使用以下两种部署模型之一来部署智能体 Harness:

  • 路径 A:Cloud Run 实例(公开试用功能 - 专用单例主机,最长 7 天,确定性网址,跨轮次持久 /workspace 卷,计算费用约为 11.40 美元/月)。
  • 路径 B:使用 concurrency=1 的 Cloud Run 服务(可缩容至零的无服务器、按请求付费、闲置计算费用为 0 美元、临时执行)。

架构:大脑与双手分离

为了说明安全边界,我们使用“大脑与双手”的比喻(一种说明性的心理模型,而非官方产品术语):两种部署路径都强制执行严格的不变性,即大脑(主机容器)与双手(沙盒)隔离。

┌────────────────────────────────────────────────────────────────────────┐
│ Cloud Run Host Container (The Brain)                                   │
│ - FastAPI Web Server (POST /chat, IAM-authenticated by default)        │
│ - Claude Agent SDK (`claude-agent-sdk`, state in `/tmp/claude`)        │
│ - Calls Claude on Agent Platform using Cloud Run service account (ADC) │
│                                                                        │
│   │                                                                    │
│   ▼ Dispatches untrusted commands via In-Process MCP Tool              │
│                                                                        │
│ ┌──────────────────────────────────────────────────────────────────┐   │
│ │ Cloud Run Sandbox (The Hands)                                    │   │
│ │ - Spawned using `/usr/local/gcp/bin/sandbox do --template`       │   │
│ │ - Dedicated sibling container image (`sandboxes.templates`)      │   │
│ │ - Dedicated gVisor kernel; no access to host FS, env, or creds   │   │
│ │ - Writable per-sandbox overlay + configurable internet egress    │   │
│ └──────────────────────────────────────────────────────────────────┘   │
└────────────────────────────────────────────────────────────────────────┘

学习内容

  • 如何使用 Claude Agent SDK 和进程内 Model Context Protocol (MCP) 工具构建智能体 Harness。
  • 如何通过 /usr/local/gcp/bin/sandbox 将不受信任的 shell 命令路由到软件隔离的 Cloud Run 沙盒。
  • 如何根据有状态性和成本目标在 Cloud Run 实例和 Cloud Run 服务 (concurrency=1) 之间进行选择。
  • 如何使用应用默认凭证 (ADC) 通过 Agent Platform (CLAUDE_CODE_USE_VERTEX=1) 对 Claude Agent SDK 进行身份验证,无需管理 API 密钥。
  • 如何验证沙盒隔离和出站网络连接。

2. 实例与服务

在部署之前,请查看下面的决策矩阵,选择最适合您的目标工作负载的路径:

架构指标

路径 A:Cloud Run 实例

路径 B:Cloud Run 服务 (concurrency=1)

计算模型

专用单例容器(最长可连续运行 7 天)

临时自动扩缩容器池

扩缩和实例数上限

单一实例(1 个实例)

从 0 扩缩到 --max-instances(在此 Codelab 中设置为 5,以限制并发费用上限)

空闲成本

计算费用约为 11.40 美元/月(共享 CPU 上的 2 个 vCPU/2 GiB)

$0.00(空闲时缩减至 0 个实例)

结算粒度

在实例存在期间持续计费(Claude token 单独计费)

按请求轮次计费,精确到毫秒(Claude 词元单独计费)

网址和寻址

每个实例都有专用网址 (https://INSTANCE_URL.run.app)

服务端点 (https://SERVICE_URL.run.app);默认情况下没有会话亲和性(启用后会尽力而为)

路线可靠性

100% 确定性 1:1 实例路由

在自动扩缩的 Cloud Run 服务实例之间实现负载均衡

沙盒和主机状态

sandbox do --template 每次运行一个命令,并在各轮对话之间装载一个共享内存中 /workspace 卷(最长 7 天)

sandbox do --template 针对每个命令临时运行;实例在空闲时会缩减至零

后台进程

在主机上或在分离的沙盒中受支持 (sandbox run --detach)

请求完成后,系统会限制或暂停

主要应用场景

个人智能体助理、IDE 伴侣、编码机器人

Webhook 处理程序、事件驱动型流水线、自动化问题分类

您应该选择哪种方案?

  • 如果您要构建单所有者编程助手或个人助理,且需要永久性主机工作区(最长 7 天)和长时间运行的后台开发服务器,请选择路径 A(实例)。您还会获得一个专用网址,该网址可与工具和网络钩子搭配使用,而无需自定义路由标头。
  • 如果您要构建 webhook 端点(例如 GitHub PR 机器人或 Slack 机器人)、自动化事件驱动型流水线,或者希望在零星事件之间将服务完全扩缩到零(通过 --max-instances 限制最大并发支出),从而实现零闲置成本,请选择路径 B(服务)。

(您也可以使用同一容器映像完成这两条路径,以便直接比较它们的操作机制!)

3. 设置和要求

Google Cloud 项目设置和所需角色

  1. 登录 Google Cloud 控制台。
  2. 选择或创建已启用结算功能的 Google Cloud 项目。
  3. 验证您的账号在项目中是否具有以下 IAM 角色(包含在 Owner 中,或单独授予):
    • Cloud Run Developer (roles/run.developer) 和 Service Account User (roles/iam.serviceAccountUser),用于部署实例和服务。
    • Service Account Admin (roles/iam.serviceAccountAdmin)、Service Usage Admin (roles/serviceusage.serviceUsageAdmin) 和 Project IAM Admin (roles/resourcemanager.projectIamAdmin),以便创建运行时服务账号、启用 API 和授予 IAM 角色。
    • Consumer Procurement Entitlement Manager (roles/consumerprocurement.entitlementManager),用于在 Model Garden 中启用合作伙伴 Claude 模型。

打开 Cloud Shell

从 Cloud 控制台的顶部导航栏中激活 Google Cloud Shell。

对您的用户凭据进行身份验证,以便 gcloud auth print-identity-token 在测试受 IAM 保护的 Cloud Run 端点时可以生成 OpenID Connect (OIDC) 身份令牌:

gcloud auth login

设置环境变量

设置项目 ID、部署区域和专用运行时服务账号名称(如果 Cloud Shell 会话重新连接,请重新运行这些 export 命令):

export PROJECT_ID="<YOUR_PROJECT_ID>"
export REGION="us-west1"
export SA_NAME="claude-agent-sa"
export RUN_SA="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud config set project ${PROJECT_ID}

安装 gcloud beta(仅限本地终端)

Cloud Shell 已预安装 gcloud beta(在 Cloud Shell 中跳过此步骤,因为组件管理器已停用)。如果您改为从本地终端运行,请安装并更新 beta:

gcloud components install beta --quiet
gcloud components update --quiet

启用所需的 Google Cloud API

启用 Cloud Run、Agent Platform (aiplatform.googleapis.com)、IAM、Cloud Build 和 Artifact Registry API:

gcloud services enable \
  run.googleapis.com \
  aiplatform.googleapis.com \
  iam.googleapis.com \
  cloudbuild.googleapis.com \
  artifactregistry.googleapis.com

4. 在 Agent Platform 上启用 Claude 并配置 IAM

Claude Agent SDK 无需管理静态 Anthropic API 密钥,而是可以使用 Cloud Run 服务账号的应用默认凭证 (ADC) 直接向 Agent Platform 进行身份验证。

1. 在 Model Garden 中启用 Claude Sonnet 5.5

  1. 在 Google Cloud 控制台中打开 Model Garden。
  2. 搜索 Claude Sonnet 5.5 (claude-sonnet-5-5) 或 Claude Opus 5.5 (claude-opus-5-5),然后点击启用,为您的项目接受 Anthropic 合作伙伴条款。

2. 创建专用运行时服务账号

为 Cloud Run 代理创建专用运行时服务账号,并向其授予 Agent Platform User (roles/aiplatform.user) 角色,以便其可以调用 Claude 模型:

gcloud iam service-accounts create "${SA_NAME}" \
  --display-name="Claude Agent Runtime Service Account" \
  --project="${PROJECT_ID}" \
  --quiet

export RUN_SA="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${RUN_SA}" \
  --role="roles/aiplatform.user"

3. 可选:在构建之前验证 Claude 访问权限

在构建容器之前,请发送一个快速测试请求,以确认您的项目已启用 claude-sonnet-5-5(如果您想检查完整的 API 响应或错误正文,请移除 | jq '{content}'):

curl -sS --fail-with-body \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/publishers/anthropic/models/claude-sonnet-5-5:rawPredict" \
  -d @- << 'EOF' | jq '{content}'
{
  "anthropic_version": "vertex-2023-10-16",
  "max_tokens": 64,
  "messages": [
    {"role": "user", "content": "Reply with Hello! I'm Claude."}
  ]
}
EOF

预期输出:

{
  "content": [
    {
      "type": "text",
      "text": "Hello! I'm Claude."
    }
  ]
}

5. 构建智能体应用容器

为智能体源代码创建一个干净的目录:

mkdir -p claude-agent-app && cd claude-agent-app

使用 cat <<'EOF' 命令在 claude-agent-app 中创建五个文件,以便您可以直接在 Cloud Shell 中复制并运行每个代码块:

  1. sandbox_runner.py:封装 /usr/local/gcp/bin/sandbox,以将 shell 命令分派到 gVisor 沙盒中。
  2. agent.py:实例化 Claude Agent SDK 并配置进程内 bash 执行 MCP 工具。
  3. server.py:一个轻量级 FastAPI Web 服务器,用于提供 POST /chat。
  4. requirements.txt:Python 软件包依赖项。
  5. Dockerfile:封装 FastAPI 主机运行时的容器定义。

1. 创建“sandbox_runner.py”

此模块在智能体框架和 Cloud Run 沙盒启动器之间提供执行桥梁:

cat <<'EOF' > sandbox_runner.py
"""Sandbox Runner utilizing Cloud Run Sandbox launcher."""

from __future__ import annotations

import logging
import os
import subprocess
from dataclasses import dataclass

logger = logging.getLogger("sandbox-runner")


@dataclass
class ExecutionResult:
    stdout: str
    stderr: str
    exit_code: int


def _env_bool(name: str, default: bool) -> bool:
    raw = os.environ.get(name)
    if raw is None:
        return default
    return raw.strip().lower() in ("1", "true", "yes", "on")


class CloudRunSandboxRunner:
    """Dispatches shell commands into isolated gVisor sandbox templates."""

    def __init__(
        self,
        sandbox_bin: str = "/usr/local/gcp/bin/sandbox",
        template: str | None = None,
        default_allow_egress: bool | None = None,
    ):
        self.sandbox_bin = sandbox_bin
        self.template = (
            template
            if template is not None
            else os.environ.get("SANDBOX_TEMPLATE", "code-sandbox").strip()
        )
        self.default_allow_egress = (
            default_allow_egress
            if default_allow_egress is not None
            else _env_bool("SANDBOX_ALLOW_EGRESS", True)
        )
        self.is_available = os.path.exists(sandbox_bin) and os.access(
            sandbox_bin, os.X_OK
        )

    def execute(
        self,
        command: str,
        timeout: int = 60,
        allow_egress: bool | None = None,
    ) -> ExecutionResult:
        """Executes a command inside an ephemeral templated sandbox."""
        if not self.is_available:
            return ExecutionResult(
                stdout="",
                stderr="Cloud Run Sandbox binary is unavailable on this host.",
                exit_code=1,
            )
        if not self.template:
            return ExecutionResult(
                stdout="",
                stderr=(
                    "SANDBOX_TEMPLATE must be set to launch a sandbox template."
                ),
                exit_code=1,
            )

        egress = (
            self.default_allow_egress if allow_egress is None else allow_egress
        )
        cmd = [
            self.sandbox_bin,
            "do",
            "--stdin=false",
            "--template",
            self.template,
        ]
        if egress:
            cmd.append("--allow-egress")
        cmd.extend(["--", "/bin/sh", "-c", command])

        try:
            res = subprocess.run(
                cmd, capture_output=True, text=True, timeout=timeout, check=False
            )
            return ExecutionResult(
                stdout=res.stdout, stderr=res.stderr.strip(), exit_code=res.returncode
            )
        except subprocess.TimeoutExpired:
            return ExecutionResult(
                stdout="", stderr=f"Command timed out after {timeout} seconds.", exit_code=124
            )
        except Exception as e:
            logger.exception("Unexpected error during sandbox execution")
            return ExecutionResult(stdout="", stderr=str(e), exit_code=1)
EOF

2. 创建“agent.py”

定义 Claude 智能体框架,并注册一个名为 execute_bash 的进程内 MCP 工具,用于将 shell 命令路由到沙盒运行器。设置 tools=[] 会停用 Claude Code 的内置工具(Bash、Write、Edit 等),因此 execute_bash 是唯一的命令工具。每个请求都会使用 query() 运行一个 Claude Agent SDK 会话,直至完成:

cat <<'EOF' > agent.py
"""Claude Agent harness with in-process Cloud Run Sandbox tool."""

from __future__ import annotations

from typing import Any

from claude_agent_sdk import (
    ClaudeAgentOptions,
    ResultMessage,
    create_sdk_mcp_server,
    query,
    tool,
)
from sandbox_runner import CloudRunSandboxRunner

runner = CloudRunSandboxRunner()


@tool(
    "execute_bash",
    "Execute shell commands inside an isolated sandbox with internet egress.",
    {"command": str},
)
async def execute_bash(args: dict[str, Any]) -> dict[str, Any]:
    """Executes a command inside the gVisor sandbox and returns the combined output."""
    result = runner.execute(args["command"])
    output = []
    if result.stdout:
        output.append(result.stdout)
    if result.stderr:
        output.append(f"[STDERR]\n{result.stderr}")
    output.append(f"[Exit Code: {result.exit_code}]")
    return {"content": [{"type": "text", "text": "\n".join(output)}]}


class ClaudeAgent:
    """Runs one Claude Agent SDK session per prompt."""

    def __init__(self, options: ClaudeAgentOptions):
        self.options = options

    async def run(self, prompt: str) -> str:
        """Runs the agent loop to completion and returns Claude's final answer."""
        async for message in query(prompt=prompt, options=self.options):
            if isinstance(message, ResultMessage):
                if message.is_error:
                    raise RuntimeError(message.result or message.subtype)
                return message.result or ""
        raise RuntimeError("Claude Agent SDK ended without a result.")


def create_claude_agent() -> ClaudeAgent:
    """Initializes the Claude Agent with the sandbox as its only execution tool."""
    system_prompt = (
        "You are an autonomous AI coding assistant running on Google Cloud Run. "
        "You have access to a secure bash tool called 'execute_bash'. "
        "All bash commands run inside an isolated gVisor sandbox with outbound internet access. "
        "If /workspace exists, store persistent project files there across turns. "
        "Use this tool to explore the environment, execute Python code, compile programs, or run tests."
    )
    options = ClaudeAgentOptions(
        # Swap to another enabled Model Garden ID (e.g., "claude-opus-5-5") as needed.
        model="claude-sonnet-5-5",
        system_prompt=system_prompt,
        mcp_servers={"sandbox": create_sdk_mcp_server("sandbox", tools=[execute_bash])},
        allowed_tools=["mcp__sandbox__execute_bash"],
        # Disable Claude Code's built-in tools (Bash, Write, Edit, ...) so the
        # only way to run commands is through the sandboxed execute_bash tool.
        tools=[],
    )
    return ClaudeAgent(options)
EOF

3. 创建“server.py”

创建一个公开 POST /chat 的干净 FastAPI 服务器:

cat <<'EOF' > server.py
"""FastAPI endpoint serving the Claude Agent."""

from __future__ import annotations

import logging
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

from agent import create_claude_agent

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("claude-service")

app = FastAPI(title="Claude Agent Cloud Run Service")
agent = create_claude_agent()


class ChatRequest(BaseModel):
    prompt: str


class ChatResponse(BaseModel):
    response: str


@app.post("/chat", response_model=ChatResponse)
async def chat_endpoint(req: ChatRequest):
    if not req.prompt.strip():
        raise HTTPException(status_code=400, detail="Prompt must not be empty.")
    try:
        result = await agent.run(req.prompt)
        return ChatResponse(response=str(result))
    except Exception as e:
        logger.exception("Error during agent processing")
        raise HTTPException(status_code=500, detail=str(e))
EOF

4. 创建“requirements.txt”

cat <<'EOF' > requirements.txt
fastapi>=0.110.0
uvicorn>=0.28.0
pydantic>=2.0.0
claude-agent-sdk>=0.1.81
anthropic[vertex]>=0.40.0
EOF

5. 创建“Dockerfile”

cat <<'EOF' > Dockerfile
FROM python:3.11-slim

ENV PYTHONUNBUFFERED=1
ENV PORT=8080
# Store Claude Agent SDK session files in /tmp on the host container
# (defense-in-depth alongside sandbox template file system isolation).
ENV CLAUDE_CONFIG_DIR=/tmp/claude

WORKDIR /app

# Ensure CA certificates are present for TLS connections
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 8080

CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8080"]
EOF

6. 构建并推送容器映像

创建 Artifact Registry Docker 代码库(如果您的项目中已存在 agent-repo,请跳至下面的构建命令):

gcloud artifacts repositories create agent-repo \
  --repository-format=docker \
  --location=${REGION} \
  --description="Repository for Claude Agent containers"

使用 Cloud Build 构建并推送 FastAPI 主机容器映像:

export IMAGE_URI="${REGION}-docker.pkg.dev/${PROJECT_ID}/agent-repo/claude-agent:latest"

gcloud builds submit --tag ${IMAGE_URI}

6. 路径 A:部署到 Cloud Run 实例

如果您选择了路径 A:专用单例主机(最长 7 天),请按照此步骤操作。(否则,请跳转到下一部分,了解路径 B)。

1. 创建“instance.yaml”

使用专用 code-sandbox 模板和共享内存中 /workspace 卷创建 instance.yaml:

cat <<EOF > instance.yaml
apiVersion: run.googleapis.com/v1
kind: Instance
metadata:
  name: claude-agent-instance
  annotations:
    run.googleapis.com/launch-stage: BETA
spec:
  serviceAccountName: ${RUN_SA}
  containers:
  - image: ${IMAGE_URI}
    ports:
    - containerPort: 8080
    resources:
      limits:
        cpu: "2"
        memory: 2Gi
    sandboxLauncher: true
    volumeMounts:
    - name: workspace
      mountPath: /workspace
    env:
    - name: CLAUDE_CODE_USE_VERTEX
      value: "1"
    - name: ANTHROPIC_VERTEX_PROJECT_ID
      value: "${PROJECT_ID}"
    - name: CLOUD_ML_REGION
      value: "global"
    - name: SANDBOX_TEMPLATE
      value: "code-sandbox"
  volumes:
  - name: workspace
    emptyDir:
      medium: Memory
  sandboxes:
    templates:
    - name: code-sandbox
      image: python:3.11-slim
      volumeMounts:
      - name: workspace
        mountPath: /workspace
EOF

2. 部署 Cloud Run 实例

在公开试用功能 (run.googleapis.com/launch-stage: BETA) 期间,沙盒模板 (sandboxes.templates) 是使用 YAML 而非 gcloud CLI 标志以声明方式配置的。使用 gcloud beta run instances replace 从 instance.yaml 部署实例:

gcloud beta run instances replace instance.yaml --region ${REGION}

关键参数细分

  • serviceAccountName:以专用 claude-agent-sa 服务账号(而非默认 Compute Engine 服务账号)身份运行主机容器。
  • sandboxLauncher: true:将 /usr/local/gcp/bin/sandbox 注入主机容器,以便其可以监督 gVisor 沙盒。
  • sandboxes.templates 和 volumes:定义 code-sandbox 同级容器映像 (python:3.11-slim),并在主机容器和 code-sandbox 上装载共享的内存中 emptyDir 卷(/workspace 处的 workspace,计入实例的 2 GiB 内存限制)。每次 sandbox do --template code-sandbox 调用都会获得一个全新的 /tmp 和根叠加层,无法访问 /app 或 /tmp/claude,并且在最多 7 天内可以跨轮次持续访问 /workspace。
  • IAM 身份验证(默认):在不停用 Invoker IAM 检查的情况下分配 containerPort: 8080 会创建一个受 Cloud Run IAM 保护的专用 HTTPS 网址,从而满足 constraints/run.managed.requireInvokerIam。
  • env:配置 Claude Agent SDK (CLAUDE_CODE_USE_VERTEX=1),以使用实例的服务账号凭证在 Agent Platform (global) 上调用 Claude,并设置 SANDBOX_TEMPLATE=code-sandbox。
# Optional (personal, non-enterprise projects only):
gcloud beta run instances update claude-agent-instance \
  --region ${REGION} \
  --public

3. 检索实例网址

export INSTANCE_URL=$(gcloud beta run instances describe claude-agent-instance \
  --region ${REGION} \
  --format="value(status.urls[0])")

echo "Instance URL: ${INSTANCE_URL}"

7. 路径 B:部署到 Cloud Run 服务(并发数=1)

如果您选择了路径 B:可缩容至零的无服务器,请按照此步骤操作。

1. 创建“service.yaml”

使用 containerConcurrency: 1 和专用 code-sandbox 模板创建 service.yaml:

cat <<EOF > service.yaml
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: claude-agent-service
  annotations:
    run.googleapis.com/launch-stage: BETA
spec:
  template:
    metadata:
      annotations:
        autoscaling.knative.dev/minScale: "0"
        autoscaling.knative.dev/maxScale: "5"
        run.googleapis.com/execution-environment: gen2
    spec:
      serviceAccountName: ${RUN_SA}
      containerConcurrency: 1
      timeoutSeconds: 900
      containers:
      - image: ${IMAGE_URI}
        ports:
        - containerPort: 8080
        resources:
          limits:
            cpu: "2"
            memory: 2Gi
        sandboxLauncher: true
        env:
        - name: CLAUDE_CODE_USE_VERTEX
          value: "1"
        - name: ANTHROPIC_VERTEX_PROJECT_ID
          value: "${PROJECT_ID}"
        - name: CLOUD_ML_REGION
          value: "global"
        - name: SANDBOX_TEMPLATE
          value: "code-sandbox"
      sandboxes:
        templates:
        - name: code-sandbox
          image: python:3.11-slim
EOF

2. 部署 Cloud Run 服务

在公开试用功能 (run.googleapis.com/launch-stage: BETA) 期间,沙盒模板 (sandboxes.templates) 是使用 YAML 而不是 gcloud beta run deploy 标志以声明方式配置的。使用 gcloud beta run services replace 从 service.yaml 部署服务:

gcloud beta run services replace service.yaml --region ${REGION}

关键参数细分

  • serviceAccountName:以专用 claude-agent-sa 服务账号(而非默认 Compute Engine 服务账号)身份运行每个 Cloud Run 服务实例。
  • containerConcurrency: 1:确保每个 Cloud Run 服务实例一次严格处理一个智能体轮次,这样并发沙盒就不会争用实例的 2 个 vCPU/2 GiB 预算。
  • timeoutSeconds: 900:将每个请求的 HTTP 超时时间从默认的 5 分钟 (300s) 延长至 15 分钟(最长 3600s),这样多步智能体运行就不会在轮次中途超时(Cloud Run 实例默认为 60 分钟)。
  • minScale: "0" 和 maxScale: "5":可缩减至零(空闲时 CPU 结算费用为 0.00 美元),同时限制并发 Cloud Run 服务实例数量,以控制费用和 Claude API 配额用量。
  • execution-environment: gen2:选择启动沙盒所需的第二代执行环境。
  • sandboxLauncher: true 和 sandboxes.templates:在专用 python:3.11-slim 同级容器 (code-sandbox) 中启动每个命令,该容器具有可写的每个沙盒叠加层,并且无法访问主机文件系统。
  • IAM 身份验证(默认):使用 services replace 创建新服务时,默认情况下不会授予 allUsers,因此只有获得授权的调用方才能调用您的代理,从而满足 constraints/iam.allowedPolicyMemberDomains。
  • env:使用服务账号凭证将 Claude Agent SDK 调用 (CLAUDE_CODE_USE_VERTEX=1) 路由到 Agent Platform (global),并设置 SANDBOX_TEMPLATE=code-sandbox。
# Optional (personal, non-enterprise projects only):
gcloud run services add-iam-policy-binding claude-agent-service \
  --region ${REGION} \
  --member="allUsers" \
  --role="roles/run.invoker"

3. 检索服务网址

export SERVICE_URL=$(gcloud run services describe claude-agent-service \
  --region ${REGION} \
  --format="value(status.url)")

echo "Service URL: ${SERVICE_URL}"

8. 测试智能体并验证沙盒隔离

仅运行与您完成的部署路径匹配的代码块,以设置 TARGET_URL(在运行 curl 之前,请验证输出的网址不为空):

  • 如果您部署了路径 A(Cloud Run 实例):
export TARGET_URL="${INSTANCE_URL}"
echo "Target URL: ${TARGET_URL}"
  • 如果您部署了路径 B(Cloud Run 服务):
export TARGET_URL="${SERVICE_URL}"
echo "Target URL: ${TARGET_URL}"

1. 验证内核和沙盒隔离

让智能体检查其内核版本和操作系统环境,并使用 Google Cloud OIDC 身份令牌进行身份验证:

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Run uname -a and cat /etc/os-release using bash and report the kernel and distro."}'

预期响应:

{
  "response": "The kernel is 4.19.0-gvisor and the distro is Debian GNU/Linux 13 (trixie)."
}

智能体在沙盒内调用 execute_bash 工具,并报告 4.19.0-gvisor 沙盒内核以及 python:3.11-slim Debian 发行版,从而确认命令是在隔离的沙盒内运行,而不是在主机内核上运行。

2. 验证出站网络流量

让智能体使用 Python 的标准库验证 python:3.11-slim 沙盒中的网络出站流量:

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use execute_bash to fetch https://www.google.com with Python urllib.request and report the HTTP status code."}'

预期响应:

{
  "response": "The HTTP response status from https://www.google.com is 200."
}

由于 SANDBOX_ALLOW_EGRESS 在 CloudRunSandboxRunner 中默认为 true,因此沙盒可以提取依赖项、下载 git 代码库和查询公共 API,同时保持安全的沙盒环境(设置 SANDBOX_ALLOW_EGRESS=false 可阻止出站网络访问)。

3. 验证 Hosts 文件系统、环境和转录内容隔离

指示代理检查其是否可以在沙盒内看到主机容器的 /app 目录、/tmp/claude 会话文件或主机环境变量:

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Run ls -la /app, ls -la /tmp, and env inside bash and tell me if you can see /app, /tmp/claude, ANTHROPIC_VERTEX_PROJECT_ID, or CLAUDE_CODE_USE_VERTEX."}'

预期响应:

{
  "response": "ls: cannot access '/app': No such file or directory. /tmp is empty (no /tmp/claude), and neither ANTHROPIC_VERTEX_PROJECT_ID nor CLAUDE_CODE_USE_VERTEX is set in env."
}

代理报告称,/app 不存在 (No such file or directory),/tmp/claude 缺失,并且沙盒环境中既没有 ANTHROPIC_VERTEX_PROJECT_ID,也没有 CLAUDE_CODE_USE_VERTEX。由于 --template code-sandbox 会在同级容器中运行每个命令,而该同级容器使用的是其自己的 python:3.11-slim 映像,因此宿主容器的文件系统、凭据和会话记录会始终隔离在 The Brain 内部。

4. 验证 /workspace 在不同请求之间是否保持不变(路径 A:实例)

如果您部署了路径 A(Cloud Run 实例),instance.yaml 会在 code-sandbox 上的 /workspace 处装载内存中 emptyDir 卷。发送两个单独的 HTTP 请求,以验证写入 /workspace 的文件在临时 sandbox do 调用之间是否仍然存在,而 /tmp 每次都会重置:

# Request 1: Write one file to /workspace and one file to /tmp
curl -X POST "${INSTANCE_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use bash to write the current UTC timestamp to /workspace/session_note.txt and also write ephemeral to /tmp/ephemeral.txt, then confirm both files exist."}'

# Request 2: Read both files in a new request (new sandbox do invocation)
curl -X POST "${INSTANCE_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use bash to check cat /workspace/session_note.txt and ls -la /tmp/ephemeral.txt and report which file persisted."}'

预期响应(请求 2):

{
  "response": "/workspace/session_note.txt persisted with timestamp 2026-..., while /tmp/ephemeral.txt does not exist (No such file or directory)."
}

/workspace/session_note.txt 会在内存中跨轮次保留(在活跃的 Cloud Run 实例上最多保留 7 天),而 /tmp/ephemeral.txt 会在请求 1 的 sandbox do 容器退出后立即被舍弃。

9. 状态和沙盒细微差别(深入探究)

为什么 containerConcurrency: 1 对 Cloud Run 服务至关重要

标准无状态 Web 应用每个 Cloud Run 服务实例可处理 80 多个并发请求。对于运行沙盒的 AI 智能体,单请求并发至关重要:

  1. 共享实例 CPU 和内存预算:沙盒模板容器在同一 Cloud Run 服务实例中运行,并共享其 2 个 vCPU 和 2 GiB 内存分配。设置 containerConcurrency: 1 可确保每个活跃智能体轮次都能获得完整的实例 CPU 和内存预算,而不会受到并发编译器或 Python 运行时的争用。
  2. 主机端 SDK 隔离:在监督者容器上隔离每轮 Claude Agent SDK 执行,以便并发轮次不会争用主机内存或暂存空间。

沙盒模板、端点身份验证和多用户会话授权

  • 专用沙盒根文件系统 (sandboxes.templates):运行 sandbox do --template code-sandbox 会在专用同级容器 (python:3.11-slim) 中启动每个命令,并具有可写的每个沙盒叠加层(默认为 --write=true)。沙盒无法访问宿主容器的文件系统,从而保护 /app、Secret Manager 或 Cloud Storage 卷装载以及 /tmp/claude 转录内容。您可以在沙盒模板中定义最多 10 个不同的工具映像,而无需向 FastAPI 主机容器添加编译器或 CLI。
  • 端点级访问权限(Cloud Run IAM 和 IAP):保持启用 Invoker IAM 检查可确保只有获得授权的主体(或 Identity-Aware Proxy 背后的用户)才能访问 POST /chat。路径 A(实例)为单一所有者的个人智能体运行单一共享主机环境,不处理多租户流量。
  • 多用户会话所有权:如果您扩展 POST /chat 以接受多轮 resume 的 session_id,Cloud Run IAM 和 IAP 仅验证谁可以调用服务。在恢复会话之前,请将每个 session_id 绑定到应用中经过身份验证的调用方身份。

状态持久性:本地内存与快照恢复

  • 路径 A(实例)- 三个独立的状态层:
    1. 沙盒 /workspace 文件:在共享的内存中 emptyDir 卷(计入实例的 2 GiB 内存限制)中最多可保留 sandbox do 轮对话,最长可保留 7 天,而 /tmp 和根叠加层写入会在每次命令后重置。
    2. 长时间运行的后台进程:由于 sandbox do 会在每个命令执行后退出,因此沙盒内的开发服务器或监视器需要一个分离的沙盒(sandbox run --detach 搭配 sandbox exec)。
    3. 多轮对话记录:默认情况下,query() 会启动新的提示轮次。传递 resume(或 ClaudeSDKClient)或将转写内容持久保存到外部存储空间,以便在不同请求之间保留聊天记录。
  • 路径 B(服务):流量停止后,Cloud Run 服务实例会缩容至零,此时本地磁盘和内存状态会被清除。将多轮对话文件和会话状态持久保存到外部存储空间(例如 Cloud Storage、Firestore 或 Cloud Spanner),并在每轮对话开始时重新加载。

10. 清理

为避免持续产生 Google Cloud 费用(尤其是路径 A,在删除前每月会产生约 11.40 美元的费用),请删除您创建的资源:

  • 如果您部署了路径 A(Cloud Run 实例):
gcloud beta run instances delete claude-agent-instance --region ${REGION}
  • 如果您部署了路径 B(Cloud Run 服务):
gcloud run services delete claude-agent-service --region ${REGION}
  • 删除 Artifact Registry 制品库(两条路径):
gcloud artifacts repositories delete agent-repo --location ${REGION}
  • 移除专用服务账号和 IAM 绑定(两种路径):
gcloud projects remove-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${RUN_SA}" \
  --role="roles/aiplatform.user"
gcloud iam service-accounts delete "${RUN_SA}" --project="${PROJECT_ID}"

11. 恭喜

您已在 Google Cloud Run 上部署了一个由 Claude Sonnet 5.5 和 Claude Agent SDK 提供支持的自主 AI 智能体!

您完成的任务

  • 使用大脑与双手架构分离,构建了强化的智能体 Harness。
  • 将不受信任的 bash 命令路由到运行 gVisor 的软件隔离 Cloud Run 沙盒 (sandboxes.templates) 中。
  • 使用应用默认凭证和 Agent Platform User (roles/aiplatform.user) 角色配置了无密钥 Agent Platform 身份验证 (CLAUDE_CODE_USE_VERTEX=1)。
  • 探讨了 Cloud Run 实例(专用网址、持久性内存 /workspace 卷,最长 7 天,计算费用约为 11.40 美元/月)与 Cloud Run 服务 (concurrency=1)(缩减至零、事件驱动、受 maxScale 限制)之间的权衡。