钩子 (Hooks)

本页目录

Hooks 支持您在 Antigravity 执行循环期间的特定点运行自定义脚本或 shell 命令,以强制执行规则、执行 linter 或捕获诊断信息。

Antigravity App

在 Antigravity App 中管理钩子

在 Antigravity App 中,钩子在位于自定义目录中的 hooks.json 文件中配置:

  • 工作区级别:工作区根目录中的 .agents/hooks.json。
  • 全局级别:~/.gemini/config/hooks.json。
  • 插件级:封装在已安装插件的 hooks.json 文件内(可通过自定义 > 已安装管理)。

对于 Antigravity App,钩子(hook)有效负载中的 <app_data_dir> 会解析为 ~/.gemini/antigravity。

Schema 与文件格式

hooks.json 文件将钩子名称映射到其事件配置:

{
  "my-linter-hook": {
    "PostToolUse": [
      {
        "matcher": "run_command",
        "hooks": [
          {
            "type": "command",
            "command": "./scripts/lint.sh",
            "timeout": 10
          }
        ]
      }
    ]
  },
  "safety-gate": {
    "enabled": false,
    "PreToolUse": [
      {
        "matcher": "run_command",
        "hooks": [
          {
            "command": "./scripts/safety-check.sh"
          }
        ]
      }
    ]
  },
  "reminder": {
    "PreInvocation": [
      {
        "type": "command",
        "command": "./scripts/reminder.sh"
      }
    ]
  },
  "session-init": {
    "SessionStart": [
      {
        "type": "command",
        "command": "./scripts/init-env.sh"
      }
    ]
  }
}

钩子定义字段

每个钩子定义支持以下字段:

字段类型描述
enabledboolean可选。设置为 false 以禁用钩子而不将其移除。默认为 true。
SessionStartarray在新对话会话启动时、首次模型调用之前运行一次的处理器。
PreToolUsearray在执行工具之前运行的处理程序。
PostToolUsearray工具完成后运行的处理程序。
PreInvocationarray在 Antigravity 调用模型之前运行的处理程序。
PostInvocationarray每次模型调用完成后立即运行的处理程序。
停止 (Stop)array当执行循环终止时运行的处理程序。

支持的事件类型

Antigravity 支持以下钩子事件:

事件描述匹配器目标
SessionStart在新对话会话启动时、首次模型调用之前触发一次。N/A(忽略匹配器)
PreToolUse在执行工具之前触发。工具名称(例如,run_command)
PostToolUse工具完成后触发。工具名称
PreInvocation在调用模型之前触发。N/A(忽略匹配器)
PostInvocation每次模型调用完成后立即触发。N/A(忽略匹配器)
停止 (Stop)执行终止时触发。N/A(忽略匹配器)

匹配器 (Matcher)

对于 PreToolUse 和 PostToolUse,您可以在 matcher 字段中使用正则表达式来指定哪些工具触发钩子:

  • "" 或 "*":匹配所有工具。
  • "run_command":完全匹配run_command。
  • "run_command|view_file":匹配任一工具。
  • "browser_.*":匹配任何以browser_开头的工具。

支持的工具

对于 PreToolUse 和 PostToolUse 匹配器,您可以根据按类别分组的标准工具名称匹配。

文件与目录操作

以下工具管理文件和目录:

  • view_file: View the contents of a file.
    • 参数:AbsolutePath、StartLine(可选)、EndLine(可选)、IsSkillFile(可选)
  • write_to_file: Create new files.
    • 参数:TargetFile、Overwrite、CodeContent、Description、IsArtifact(可选)、ArtifactMetadata(可选)
  • replace_file_content: Edit a single contiguous block of text in a file.
    • 参数:TargetFile、Instruction、Description、AllowMultiple、TargetContent、ReplacementContent、StartLine、EndLine、TargetLintErrorIds(可选)
  • multi_replace_file_content: Make multiple, non-contiguous edits to the same file.
    • 参数:TargetFile、Instruction、Description、ReplacementChunks(块数组)、TargetLintErrorIds(可选)、ArtifactMetadata(可选)
  • list_dir: List the contents of a directory.
    • 参数: DirectoryPath
  • find_by_name: Search for files and directories using glob patterns.
    • 参数:SearchDirectory、Pattern、Type(可选)、Excludes(可选)、Extensions(可选)、FullPath(可选)、MaxDepth(可选)

搜索与调研

以下工具搜索文件和网络:

  • grep_search: Run fast text searches within specific paths.
    • 参数:SearchPath、Query、IsRegex(可选)、CaseInsensitive(可选)、Includes(可选)、MatchPerLine(可选)
  • search_web: Perform a general web search.
    • 参数:query、domain(可选)
  • read_url_content: Fetch text content of a public URL.
    • 参数: Url

系统与命令执行

以下工具执行命令和管理权限:

  • run_command: Propose a Bash command to run.
    • 参数:CommandLine、Cwd、WaitMsBeforeAsync、RunPersistent(可选)、RequestedTerminalID(可选)
  • manage_task: Interact with background tasks.
    • 参数:Action('list'、'kill'、'status'、'send_input')、TaskId(可选)、Input(可选)
  • /schedule: Set timers or recurring cron jobs.
    • 参数:DurationSeconds(可选)、CronExpression(可选)、MaxIterations(可选)、Prompt
  • list_permissions: View current resource access grants.
    • 参数:无
  • ask_permission: Request additional scoped permissions.
    • 参数:Action、Target、Reason

Agent 协同

以下工具协调子 Agent:

  • invoke_subagent: Spawn specialized subagents.
    • 参数:Subagents(Prompt、Role、TypeName、Workspace(可选)的规格数组)
  • define_subagent: Create a custom subagent.
    • 参数:name、description、system_prompt、enable_mcp_tools(可选)、enable_write_tools(可选)、enable_subagent_tools(可选)
  • send_message: Communicate with other agents.
    • 参数:Recipient、Message
  • manage_subagents: List or terminate active subagents.
    • 参数:Action('list'、'kill'、'kill_all')、ConversationIds(可选)

交互与媒体

以下工具处理用户交互和媒体生成:

  • ask_question: Ask multiple-choice questions.
    • 参数:questions(question、options、is_multi_select 的一系列问题)
  • generate_image: Create or edit images.
    • 参数:Prompt、ImageName、ImagePaths(可选)

钩子处理器配置

hooks 数组中的每一项都支持以下字段:

字段类型描述
typestring可选。目前仅支持"command"。默认为 "command"。
commandstring必填。要执行的 shell 命令。
timeoutinteger可选。超时(以秒为单位)。默认为 30。

输入与输出契约

钩子通过 标准输入 以 JSON 形式接收输入,并通过 标准输出 以 JSON 形式返回输出。字段名称使用驼峰命名法。

通用输入字段

所有钩子在 stdin 上的输入负载中接收以下系统元数据字段:

字段类型描述
conversationIdstring活动 Agent 对话的唯一 UUID。
workspacePaths字符串数组代表已安装工作区的绝对目录路径。
transcriptPathstringThe absolute path to the persistent transcript.jsonl conversation logs.
注意: This file lives in <app_data_dir>/brain/<conversationId>/.system_generated/logs/transcript.jsonl where <app_data_dir> is:
  • ~/.gemini/antigravity 为 Antigravity App
  • ~/.gemini/antigravity-cli 为 Antigravity CLI
  • ~/.gemini/antigravity-ide 为 Antigravity IDE
artifactDirectoryPathstring包含所有对话产物和屏幕截图的目录的绝对路径。
modelNamestring处理调用的模型的名称或标识符(例如,gemini-3.6-flash-medium)。
lastUserInputstring对话中最近一次的用户提示词。

SessionStart

在新对话会话启动时、首次模型调用之前触发一次。

输入字段(标准输入):

字段类型描述
(公共字段)包括 conversationId、workspacePaths、transcriptPath、artifactDirectoryPath、modelName 和 lastUserInput。

输出字段(标准输出):

字段类型描述
injectSteps对象数组可选。在会话开始时注入到对话轨迹中的步骤列表(与 PreInvocation 注入步骤的 Schema 相同)。

例子:

  • 输入(标准输入):
{
  "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
  "workspacePaths": ["/workspace/project"],
  "transcriptPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587/.system_generated/logs/transcript.jsonl",
  "artifactDirectoryPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587",
  "modelName": "gemini-3.6-flash-medium"
}
  • 输出(标准输出):
{
  "injectSteps": [
    {
      "systemMessage": {
        "systemMessage": "Environment initialized for workspace /workspace/project"
      }
    }
  ]
}

PreToolUse

在执行工具之前触发。

输入字段(标准输入):

字段类型描述
toolCallobject建议的工具调用的详细信息。
toolCall.namestring正在执行的工具的名称(例如,run_command)。
toolCall.argsobject传递给工具调用的参数。
stepIdxinteger轨迹中当前步骤的从 0 开始的索引。
(公共字段)包括 conversationId、workspacePaths、transcriptPath、artifactDirectoryPath、modelName 和 lastUserInput。

输出字段(标准输出):

字段类型描述
decisionstring必填。控制工具调用的门禁策略:
- "allow":允许工具调用继续执行,并交由下一个钩子或默认策略处理。
- "auto_approve":在默认策略本会弹出提示时自动批准工具调用,同时遵循用户明确配置的规则。
- "deny":立即强制拦截执行。
- "ask":提示您确认批准,但遵循“始终允许 (Always Allow)”设置。
- "force_ask":始终提示您确认批准,忽略已缓存的权限。
- "deny_unless_prior_grant":拒绝执行,除非该资源此前已在历史授权中获得批准。
reasonstring可选。 向 Agent 或您做出决定时显示的解释。
overwriteobject可选。在执行前合并(顶层浅合并)到 toolCall.args 中的替换参数。修改参数后,工具返回结果的开头会附上列出已变更键名的通知。
permissionOverrides字符串数组可选。 用于覆盖默认工具权限的资源字符串列表(例如,["read_file(/path)", "command(args)"])。

例子:

  • 输入(标准输入):
{
  "toolCall": {
    "name": "run_command",
    "args": {
      "CommandLine": "npm test",
      "Cwd": "/workspace/project",
      "WaitMsBeforeAsync": 5000
    }
  },
  "stepIdx": 19,
  "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
  "workspacePaths": ["/workspace/project"],
  "transcriptPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587/.system_generated/logs/transcript.jsonl",
  "artifactDirectoryPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587",
  "modelName": "gemini-3.6-flash-medium"
}
  • 输出(标准输出):
{
  "decision": "ask",
  "reason": "Requires confirmation for test execution.",
  "permissionOverrides": ["command(npm test)"]
}

PostToolUse

工具完成后触发。

输入字段(标准输入):

字段类型描述
toolCallobject已执行工具调用的详细信息(name 和 args)。
stepIdxinteger已完成步骤的从 0 开始的索引。
errorstring可选。如果工具调用失败,则详细的运行时错误消息。如果成功则为空。
(公共字段)包括 conversationId、workspacePaths、transcriptPath、artifactDirectoryPath、modelName 和 lastUserInput。

输出字段(标准输出):返回空 JSON 对象 {}。

例子:

  • 输入(标准输入):
{
  "toolCall": {
    "name": "run_command",
    "args": {
      "CommandLine": "npm test",
      "Cwd": "/workspace/project",
      "WaitMsBeforeAsync": 5000
    }
  },
  "stepIdx": 5,
  "error": "exit status 1",
  "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
  "workspacePaths": ["/workspace/project"],
  "transcriptPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587/.system_generated/logs/transcript.jsonl",
  "artifactDirectoryPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587",
  "modelName": "gemini-3.6-flash-medium"
}
  • 输出(标准输出): {}

PreInvocation

在调用模型之前触发。

输入字段(标准输入):

字段类型描述
invocationNuminteger当前模型调用的 0 索引序列号(第一次调用为 0)。
initialNumStepsinteger轨迹中当前的步数。
(公共字段)包括 conversationId、workspacePaths、transcriptPath、artifactDirectoryPath、modelName 和 lastUserInput。

输出字段(标准输出):

字段类型描述
injectSteps对象数组可选。 在调用模型之前注入对话轨迹的步骤列表。
terminationBehaviorstring可选。 控制调用模型前的执行流程:
- "terminate":在调用模型前立即停止执行(搭配注入的 errorMessage 可显示拦截消息)。
- ""(或省略):继续调用模型(默认)。

injectSteps 数组中的每个对象可以具有以下字段之一:

  • systemMessage(对象):发送给 Agent 的带外系统指令。其值是一个包含自身 systemMessage 字符串和可选 metadata 的对象(例如 {"systemMessage": {"systemMessage": "Remember to lint", "metadata": {"source": "policy"}}})。
  • userMessage(字符串):来自您的消息。
  • ephemeralMessage (string): Deprecated. Use systemMessage instead.
  • errorMessage(对象):向用户显示错误消息而不发送给模型(例如 {"userMessage": "Prompt blocked by policy."})。在非交互式 -p 模式下会将当前轮次标记为出错并返回非零退出码;除非搭配 "terminationBehavior": "terminate",否则不会单独停止执行。

例子:

  • 输入(标准输入):
{
  "invocationNum": 3,
  "initialNumSteps": 10,
  "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
  "workspacePaths": ["/workspace/project"],
  "transcriptPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587/.system_generated/logs/transcript.jsonl",
  "artifactDirectoryPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587",
  "modelName": "gemini-3.6-flash-medium",
  "lastUserInput": "Fix the failing unit test"
}
  • 输出 (stdout)(为 Agent 注入提醒):
{
  "injectSteps": [
    {
      "systemMessage": {
        "systemMessage": "Remember to lint"
      }
    }
  ]
}
  • 输出(标准输出)(在调用模型前拦截提示词):
{
  "injectSteps": [
    {
      "errorMessage": {
        "userMessage": "Prompt blocked by policy."
      }
    }
  ],
  "terminationBehavior": "terminate"
}

PostInvocation

每次模型调用完成后立即触发。

输入字段(标准输入):与 PreInvocation 输入字段相同(invocationNum 和 initialNumSteps)。

输出字段(标准输出):

字段类型描述
injectSteps对象数组可选。 调用完成后要注入的步骤列表(与 PreInvocation 注入步骤相同的架构)。
terminationBehaviorstring可选。 控制注入后的执行流程:
- "force_continue":强制循环继续。
- "terminate":强制循环终止。
- ""(或省略):默认行为。

例子:

  • 输入(标准输入):与PreInvocation相同。
  • 输出(标准输出):
{
  "injectSteps": [],
  "terminationBehavior": ""
}

停止 (Stop)

当执行循环终止时触发。

输入字段(标准输入):

字段类型描述
executionNuminteger执行尝试的序列号。
terminationReasonstring执行停止的原因(例如,"model_stop"、"max_steps_exceeded"、"error")。
errorstring可选。如果终止是由系统错误引起的,则显示错误消息。
fullyIdleboolean必填。 true 如果 Agent 完全完成并且所有后台命令或异步任务已完成。 false 如果活动后台任务仍在运行。
(公共字段)包括 conversationId、workspacePaths、transcriptPath、artifactDirectoryPath、modelName 和 lastUserInput。

输出字段(标准输出):

字段类型描述
decisionstring必填。 设置为 "continue" 以防止 Agent 停止并重新进入执行循环。任何其他值都允许停止。
reasonstring可选。 如果 decision 是 "continue",则该消息将作为系统消息注入到对话中。

例子:

  • 输入(标准输入):
{
  "executionNum": 1,
  "terminationReason": "model_stop",
  "error": "",
  "fullyIdle": true,
  "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
  "workspacePaths": ["/workspace/project"],
  "transcriptPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587/.system_generated/logs/transcript.jsonl",
  "artifactDirectoryPath": "~/.gemini/antigravity/brain/ec33ebf9-0cba-4100-8142-c61503f6c587",
  "modelName": "gemini-3.6-flash-medium"
}
  • 输出(标准输出):
{
  "decision": "continue",
  "reason": "Not done yet"
}