Gemini 中文指南
获取 API 密钥 ↗

钩子

↓ 下载 MarkdownInteractions API

挂钩允许您在智能体执行代码或修改其远程沙箱内的文件之前或之后运行自定义脚本或外部 HTTP 请求。使用钩子通过自动化护栏和后台工作流程来扩展智能体循环,例如:

  • 加强安全和通道护栏 在执行高风险 shell 命令或受限文件读取之前。
  • 自动化数据管道转换 在智能体创建或修改文件之后。
  • 流媒体企业审计遥测 工具执行后到外部监控系统。
python
import json
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

hooks_config = {
    "security-gate": {
        "pre_tool_execution": [
            {
                "matcher": "code_execution",
                "hooks": [
                    {
                        "type": "command",
                        "command": "python3 /.agents/hooks-scripts/gate.py",
                        "timeout": 10,
                    }
                ],
            }
        ]
    }
}

gate_script = """#!/usr/bin/env python3
import sys, json
data = json.load(sys.stdin)
cmd = str(data.get("tool_call", {}).get("args", {}))
if "rm -rf" in cmd:
    print(json.dumps({"decision": "deny", "reason": "Destructive command blocked by security gate."}))
else:
    print(json.dumps({"decision": "allow"}))
"""

interaction = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input="Run `rm -rf /tmp/forbidden` using code_execution.",
    tools=[{"type": "code_execution"}],
    environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/hooks.json",
                "content": json.dumps(hooks_config, indent=2),
            },
            {
                "type": "inline",
                "target": ".agents/hooks-scripts/gate.py",
                "content": gate_script,
            },
        ],
    },
)
print(interaction.output_text)

支持的生命周期事件 #

挂钩支持沙箱内的 2 事件:

活动当它着火时它的作用
pre_tool_execution在工具运行之前可以批准(allow) 或块 (deny) 执行之前的工具。当被阻止时,模型会看到你的拒绝原因并进行调整。
post_tool_execution工具完成后立即运行后续任务,例如格式化代码、运行单元测试或记录遥测数据。无法阻止或撤消已完成的操作。

pre_tool_execution #

在工具执行之前触发。您的脚本读取工具调用详细信息 stdin 并输出其决策 JSON (allow 或 deny) 到 stdout.

输入有效负载(stdin):

json
{
  "tool_call": {
    "name": "code_execution",
    "args": {
      "code": "rm -rf /tmp/forbidden",
      "language": "bash"
    }
  },
  "environment_id": "env_xyz789"
}

输出响应(stdout):

要批准工具调用:

json
{
  "decision": "allow"
}

要阻止工具调用并向模型返回反馈:

json
{
  "decision": "deny",
  "reason": "Destructive command blocked by security gate."
}

当钩子拒绝命令时,会立即跳过工具调用。 智能体在当前回合中看到包含拒绝原因的错误结果。然后,模型可以通过选择替代命令或向用户解释该块来进行自我纠正。

如果您的脚本输出无法识别的 JSON、纯文本或除 {"decision": "deny"},运行时将响应视为批准(allow).

post_tool_execution #

工具完成后立即触发。您的脚本读取执行详细信息和任何错误状态 stdin.

输入有效负载(stdin):

json
{
  "tool_call": {
    "name": "code_execution",
    "args": {
      "code": "python3 /workspace/app.py",
      "language": "bash"
    }
  },
  "environment_id": "env_xyz789"
}

如果 shell 命令将错误打印到标准错误 (stderr)或文件系统操作失败, "error" 包含错误文本的字段包含在有效负载中。当命令成功且没有错误时, "error" 字段被完全省略。

输出响应(stdout):

json
{}

由于后工具挂钩严格针对代码格式化或日志记录等后台任务运行,因此运行时会忽略返回的任何决策值 stdout.

配置发现 #

运行时自动发现钩子定义 .agents/hooks.json 或 /.agents/hooks.json 沙盒环境内。您可以提供 hooks.json 与使用任何支持的自定义脚本一起 环境来源:

  • 存储库安装:一个 Git 存储库,包含 .agents/hooks.json 旁边 AGENTS.md.
  • 云存储(gcs):一个 GCS 桶,包含 hooks.json 复制到环境中。
  • 内联源:传入的原始JSON字符串和脚本内容 environment.sources 打电话时 client.interactions.create.

hooks.json 图式 #

A hooks.json 文件组事件定义(pre_tool_execution 或 post_tool_execution)在自定义名称下。您可以独立启用或禁用每个组:

json
{
  "security-gate": {
    "enabled": true,
    "pre_tool_execution": [
      {
        "matcher": "code_execution",
        "hooks": [
          {
            "type": "command",
            "command": "python3 /.agents/hooks-scripts/gate.py",
            "timeout": 10
          }
        ]
      }
    ]
  },
  "auto-format": {
    "post_tool_execution": [
      {
        "matcher": "*",
        "hooks": [
          {
            "type": "command",
            "command": "python3 /.agents/hooks-scripts/auto_lint.py",
            "timeout": 15
          }
        ]
      }
    ]
  }
}

匹配器语法和规则 #

中的每个规则组 hooks.json 定义处理程序何时以及如何使用 matcher 和 hooks 属性:

领域类型说明
enabledboolean可选。设置为 false 禁用该组(true 默认情况下)。
matcherstring正则表达式模式匹配容器内的目标工具名称。
hooksarray处理程序定义的有序列表(command 或 http)。处理程序按声明顺序依次运行。

正则表达式评估的工作原理#

当智能体调用沙箱内的工具时,运行时会根据您的名称评估该工具的容器名称。 matcher 使用标准 RE2 正则表达式的模式。如果正则表达式与工具名称匹配,则所有处理程序 hooks 数组按顺序执行。如果多个规则组与同一工具匹配,则所有相应的处理程序数组都会运行。

您可以针对任何内置容器工具名称:代码执行(code_execution)或文件系统操作(view_file, write_to_file, replace_file_content, list_dir, 和 delete_file).

常见匹配器表达式#

  • "code_execution":shell 命令和脚本执行的精确字符串匹配。
  • "write_to_file":文件系统文件创建和磁盘写入完全匹配。
  • "view_file|write_to_file":管道分隔在单个规则中匹配多个特定工具名称。
  • ".*_file":正则表达式通配符匹配任何以结尾的工具 _file (例如 view_file, write_to_file, 或 delete_file)。这仅涵盖文件系统工具集的一部分, replace_file_content 和 list_dir 不结束于 _file,因此当您需要它们时明确命名它们。标准 RE2 正则表达式需要 .*;简单的 shell 全局变量,例如 *_file 是无效的正则表达式语法,将无法匹配。
  • ".*" 或 "*" 或 "":拦截容器内每个工具调用的包罗万象的模式。

处理程序类型 #

命令挂钩 #

命令挂钩在沙箱内执行 shell 命令或脚本。该脚本接收事件 JSON stdin 并输出其决策 JSON stdout.

领域类型说明
typestring必须是 "command".
commandstring在沙箱内运行的命令行(例如, python3 /.agents/hooks-scripts/gate.py).
timeoutinteger超时(以秒为单位)。默认值: 30.

HTTP 挂钩 #

HTTP 挂钩将事件 JSON 作为 POST 请求直接从沙箱网络内部发送到外部 HTTPS URL。目标服务器使用完全相同的 JSON 格式在 HTTP 响应正文中返回其决定({"decision": "allow"} 或 {"decision": "deny", "reason": "..."}).

领域类型说明
typestring必须是 "http".
urlstring将事件有效负载发布到的外部 HTTPS 端点。
headersobject非敏感自定义标头的可选键值对(例如 {"X-Event-Source": "agent-sandbox"})。对于身份验证,请使用 凭证 相反,在网络白名单上。
timeoutinteger超时(以秒为单位)。默认值: 30.

出口代理和 token 转换 #

由于 HTTP 挂钩直接从沙箱网络命名空间内部执行,因此传出请求会通过透明出口代理。该架构为您提供 2 关键的安全优势:

  • 网络许可名单: 目标端点必须在您的环境中明确允许 network.allowlist。环回流量(127.0.0.1 或 localhost) 被代理阻止;始终以列入白名单的外部端点为目标。
  • 凭证注入: 您不需要在里面存储API 密钥或秘密持有者token .agents/hooks.json 或将它们安装到容器中。将秘密存储一次 凭证 并通过您环境中的 ID 引用它 network.allowlist。出口代理会自动拦截传出的 HTTP 挂钩流量,并在离开沙箱之前在线路上注入真实的身​​份验证标头。内联 transform 规则以与在线上相同的方式设置标头,当您想要在整个项目中重复使用机密并将其轮换到一处时,可以使用凭证。参见 网络配置.

运行时如何处理决策和失败 #

  • 同步等待: 智能体暂停并等待您的挂钩完成,然后再继续。
  • 阻止工具执行: 如果你的预工具钩子返回 {"decision": "deny", "reason": "<your reason>"},运行时立即取消工具调用。该模型会在其对话历史记录中看到您的拒绝原因,并通过选择安全的替代方案或向用户解释阻止进行调整。
  • 处理脚本崩溃、HTTP 错误和超时: 如果命令脚本崩溃(非零退出状态)、HTTP 挂钩返回非 2xx 状态代码(例如 4xx 或 5xx 服务器错误),或者操作超时或返回无法识别的 JSON,运行时会将其视为批准(allow)。工具执行会正常继续,因此损坏的脚本或无法访问的遥测服务器永远不会导致您的应用程序死锁。

常见用例 #

数据隐私和合规性的多轮恢复 #

当挂钩阻止访问受限资源(例如包含个人身份信息 (PII) 或机密财务记录的目录)时,您可以通过 previous_interaction_id 下一次调用时,将在相同的环境中继续转动。 智能体读取拒绝解释并通过查询批准的公共表来自动恢复。

python
import json
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

hooks_config = {
    "privacy-gate": {
        "pre_tool_execution": [
            {
                "matcher": "view_file",
                "hooks": [
                    {
                        "type": "command",
                        "command": "python3 /.agents/hooks-scripts/check_privacy.py",
                        "timeout": 5,
                    }
                ],
            }
        ]
    }
}

check_privacy_script = """#!/usr/bin/env python3
import sys, json
data = json.load(sys.stdin)
path = str(data.get("tool_call", {}).get("args", {}).get("path", ""))

if "/private/" in path:
    resp = {
        "decision": "deny",
        "reason": "Access to confidential `/private/` records is blocked by PII compliance policy. Query approved `/public/` summary tables instead."
    }
else:
    resp = {"decision": "allow"}

print(json.dumps(resp))
"""

# Step 1: Agent attempts to read confidential PII records and is intercepted
int_1 = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input="Use your filesystem tool to read `/workspace/private/employees.json` and summarize the employee details.",
    environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/hooks.json",
                "content": json.dumps(hooks_config, indent=2),
            },
            {
                "type": "inline",
                "target": ".agents/hooks-scripts/check_privacy.py",
                "content": check_privacy_script,
            },
            {
                "type": "inline",
                "target": "workspace/private/employees.json",
                "content": '{"employees": [{"id": 1, "salary": 150000, "ssn": "000-00-0000"}]}',
            },
            {
                "type": "inline",
                "target": "workspace/public/summary.json",
                "content": '{"department": "Engineering", "team_size": 42, "status": "active"}',
            },
        ],
    },
)
print(int_1.output_text)

# Step 2: Continue in the same environment using previous_interaction_id; agent recovers with public tables
int_2 = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input="Understood. Please read the approved `/workspace/public/summary.json` file instead and provide the summary.",
    environment=int_1.environment_id,
    previous_interaction_id=int_1.id,
)
print(int_2.output_text)

外部审计日志记录和遥测 #

每当读取或修改文件时,将实时审核事件从沙箱内部发送到外部监控服务器。

  • 匹配多种工具: 由于匹配器使用标准正则表达式,因此您可以使用管道将多个工具组合在单个规则中(view_file|write_to_file|replace_file_content) 或通配符 (.*_file).
  • 对您的配置保密: 将身份验证 token 存储为 凭证 并通过您环境中的 ID 引用它 网络配置 (network.allowlist.credential)。出口代理在传出请求上注入真实承载 token。此示例将标头设置为内联 transform 相反,它受同一代理保护,并且适合 token 属于这一配置的情况。
python
import json
from google import genai

client = genai.Client(http_options={"api_version": "v1beta"})

# Define hook without secrets; the egress proxy injects headers dynamically
hooks_config = {
    "audit-logging": {
        "post_tool_execution": [
            {
                "matcher": "view_file|write_to_file|replace_file_content",
                "hooks": [
                    {
                        "type": "http",
                        "url": "https://telemetry.example.com/api/v1/agent-events",
                        "timeout": 10,
                    }
                ],
            }
        ]
    }
}

interaction = client.interactions.create(
    agent="antigravity-preview-09-2026",
    input="Use your filesystem tool to create `/workspace/audit.log` containing 'event 1', then immediately read it back using your filesystem read tool.",
    environment={
        "type": "remote",
        "sources": [
            {
                "type": "inline",
                "target": ".agents/hooks.json",
                "content": json.dumps(hooks_config, indent=2),
            }
        ],
        "network": {
            "allowlist": [
                {
                    "domain": "telemetry.example.com",
                    "transform": {
                        "Authorization": "Bearer telemetry_secret_token_123",
                    },
                },
                {"domain": "*"},
            ]
        },
    },
)
print(interaction.output_text)

限制 #

  • 沙盒工具范围: Hooks拦截沙箱内的内置工具:代码执行(code_execution)和文件系统操作(view_file, write_to_file, replace_file_content, list_dir, 和 delete_file)。它们不会针对自定义函数调用触发(function) 或外部 Model Context Protocol (mcp_server) 在容器外处理的工具。
  • 网络许可名单: HTTP 挂钩在容器网络内部运行。您必须在您的环境中明确允许目标 URL network.allowlist。环回地址(localhost, 127.0.0.1)被代理阻止。
  • 错误自动批准: 如果挂钩脚本崩溃(非零退出状态)、超时或失败,运行时会记录失败并允许工具调用继续。这可以确保损坏的 linter 脚本或挂起的进程永远不会使您的应用程序陷入死锁。
  • 沙箱配置保护: 由于钩子在容器沙箱内部执行,智能体使用文件系统写入工具或shell代码执行权限可以修改本地 .agents/hooks.json 或可写工作区中的脚本。使用集装箱挂钩作为自动化政策指导和操作护栏;如果需要对不受信任的模型执行进行严格的防篡改,请从只读存储库挂载配置源。

后续步骤 #

搜索标题、API 名称或正文内容