如何使用 Cloud Run 上的 Claude Agent SDK 部署自主代理程式

1. 簡介

總覽

AI 代理正從簡單的對話式聊天機器人,轉變為能執行 bash 指令、執行單元測試、查詢 API 及修改原始碼的自主系統。在正式環境中安全執行這些工作負載,會面臨兩項核心架構難題:

  1. 程式碼執行安全:LLM 生成的不受信任程式碼,不應直接在主機作業系統上執行,也不應存取平台密鑰和憑證。
  2. 狀態和運算生命週期:代理工作流程可能需要永久專屬工作區 (例如長期開發人員環境、互動式終端機或背景開發伺服器),或無狀態、事件導向、將資源調度率降至零的 API (例如傳入的 Webhook 或自動問題分類)。

在本程式碼實驗室中,您將使用 Google Cloud Run 上的官方 Claude Agent SDK (claude-agent-sdk),建構及部署自主 AI 代理,並搭配 Cloud Run 沙箱和沙箱範本 (公開預先發布版),在軟體隔離的 gVisor 環境中執行程式碼。

您可以透過下列兩種部署模型部署代理駕馭系統:

  • 路徑 A:Cloud Run 執行個體 (公開預先發布版 - 專屬單一主機,最長 7 天、確定性網址、跨回合永久 /workspace 磁碟區,運算費用約每月$11.40 美元)。
  • 路徑 B:Cloud Run 服務搭配 concurrency=1 (無伺服器,可將資源調度率降至零、按要求付費、閒置運算費用為 $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) 工具,建構代理程式。
  • 如何透過 /usr/local/gcp/bin/sandbox 將不受信任的殼層指令轉送至軟體隔離的 Cloud Run 沙箱。
  • 如何根據有狀態性和成本目標,選擇 Cloud Run 執行個體或 Cloud Run 服務 (concurrency=1)。
  • 如何使用應用程式預設憑證 (ADC) 驗證 Claude Agent SDK 與 Agent Platform (CLAUDE_CODE_USE_VERTEX=1),不需管理 API 金鑰。
  • 如何驗證沙箱隔離和傳出網路連線。

2. 執行個體與服務

部署前,請查看下方的決策矩陣,選擇最符合目標工作負載的路徑:

架構指標

路徑 A:Cloud Run 執行個體

路徑 B:Cloud Run 服務 (concurrency=1)

運算模型

專屬單例模式容器 (持續執行最多 7 天)

暫時性自動調度資源容器集區

資源調度與執行個體數量上限

單一執行個體 (1 個執行個體)

從 0 擴充至 --max-instances (在本程式碼實驗室中設為 5,以限制並行費用上限)

閒置成本

運算費用:每月約$11.40 美元 (2 個 vCPU/2 GiB 共用 CPU)

$0.00 (閒置時會縮減至 0 個執行個體)

計費精細程度

執行個體存在期間持續計費 (Claude 權杖費用另計)

按要求次數計費,最小單位為毫秒 (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 搭配使用,不需自訂轉送標頭。
  • 如果您要建構 Webhook 端點 (例如 GitHub PR 機器人或 Slack 機器人)、自動化事件導向管道,或希望在偶發事件之間將服務完全縮減至零,以達到零閒置成本 (--max-instances 可限制並行支出上限),請選擇路徑 B (服務)。

(您也可以使用相同的容器映像檔完成這兩種路徑,直接比較兩者的運作機制!)

3. 設定和需求

Google Cloud 雲端專案設定和必要角色

  1. 登入 Google Cloud 控制台。
  2. 選取或建立已啟用計費功能的 Google Cloud 雲端專案。
  3. 確認您的帳戶在專案中具備下列 IAM 角色 (包含在 Owner 中,或個別授予):
    • Cloud Run 開發人員 (roles/run.developer) 和服務帳戶使用者 (roles/iam.serviceAccountUser),以便部署執行個體和服務。
    • 服務帳戶管理員 (roles/iam.serviceAccountAdmin)、服務使用情形管理員 (roles/serviceusage.serviceUsageAdmin) 和專案 IAM 管理員 (roles/resourcemanager.projectIamAdmin),以便建立執行階段服務帳戶、啟用 API 及授予 IAM 角色。
    • 用戶採購授權管理員 (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 可使用 Cloud Run 服務帳戶的應用程式預設憑證 (ADC),直接向 Agent Platform 進行驗證,不必管理靜態 Anthropic API 金鑰。

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 使用者 (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,將殼層指令調度至 gVisor 沙箱。
  2. agent.py:例項化 Claude Agent SDK,並設定程序內 bash 執行 MCP 工具。
  3. server.py:提供 POST /chat 的輕量 FastAPI 網路伺服器。
  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 工具,將殼層指令轉送至沙箱執行元件。設定 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」

建立乾淨的 FastAPI 伺服器,公開 POST /chat:

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 驗證 (預設):分配 containerPort: 8080 時,如果不一併停用叫用者 IAM 檢查,系統會建立受 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. 驗證主機檔案系統、環境和轉錄稿隔離

指示代理程式檢查是否能在沙箱中看到主機容器的 /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 服務不可或缺的功能

標準無狀態網頁應用程式每個 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):啟用叫用者 IAM 檢查,確保只有授權主體 (或 Identity-Aware Proxy 後方使用者) 能存取 POST /chat。路徑 A (執行個體):為單一擁有者的個人代理執行單一共用主機環境,而非多租戶流量。
  • 多使用者工作階段擁有權:如果您擴充 POST /chat,接受多輪 resume 的 session_id,Cloud Run IAM 和 IAP 只會驗證誰可以呼叫服務。在繼續工作階段之前,請將每個 session_id 繫結至應用程式中已驗證的呼叫端身分。

狀態持續性:本機記憶體與快照重新凍結

  • 路徑 A (例項) - 三個獨立狀態層:
    1. 沙箱 /workspace 檔案:在共用的記憶體內 emptyDir 磁碟區中,最多可保留 sandbox do 個回合,最長可保留 7 天 (計入執行個體的 2 GiB 記憶體限制),而 /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 部署自主 AI 代理,該代理採用 Claude Sonnet 5.5 和 Claude Agent SDK!

完成的目標

  • 使用大腦與雙手架構分離技術,建構強化的代理工具。
  • 將不受信任的 Bash 指令,轉送至執行 gVisor 的軟體隔離 Cloud Run 沙箱 (sandboxes.templates)。
  • 使用應用程式預設憑證和 Agent Platform 使用者 (roles/aiplatform.user) 角色,設定無金鑰 Agent Platform 驗證 (CLAUDE_CODE_USE_VERTEX=1)。
  • 探討 Cloud Run 執行個體 (專屬網址、永久記憶體內 /workspace 磁碟區,最多 7 天,運算費用約$11.40 美元/月) 和 Cloud Run 服務 (concurrency=1) (將資源調度率降至零、事件導向、上限為 maxScale) 之間的取捨。