---
url: /antigravity/hooks.md
description: >-
  了解如何配置 hooks.json，管理 Antigravity 2.0 执行循环的关键事件（PreToolUse, PostToolUse,
  PreInvocation, PostInvocation, Stop）及输入输出规范。
---

# 钩子系统 (Hooks)

钩子（Hooks）允许您在 Antigravity 执行循环的特定节点运行自定义脚本或 Shell 命令。这在强制执行自定义规范、运行 Linter（代码检查工具）或自动捕获诊断信息时非常强大。

## 配置方式 (Configuration)

钩子在您自定义目录中的 `hooks.json` 文件中进行配置（例如工作空间中的 `.agents/` 或 `~/.gemini/config/`）。

## 模式与文件格式 (Schema and File Format)

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

```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"
      }
    ]
  }
}
```

### 钩子定义字段 (Hook Definition Fields)

| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **enabled** | boolean | 可选。设为 `false` 以禁用此钩子而不将其删除。默认为 `true`。 |
| **PreToolUse** | array | 在工具执行前运行的处理程序。 |
| **PostToolUse** | array | 在工具执行完毕后运行的处理程序。 |
| **PreInvocation** | array | 在 Antigravity 调用大模型前运行的处理程序。 |
| **PostInvocation** | array | 在工具调用流程结束后运行的处理程序。 |
| **Stop** | array | 在执行循环终止时运行的处理程序。 |

### 支持的事件 (Supported Events)

| 事件 (Event) | 描述 | 匹配器目标 (Matcher Target) |
| :--- | :--- | :--- |
| **PreToolUse** | 在工具执行前触发。 | 工具名称（如 `run_command`） |
| **PostToolUse** | 在工具完成后触发。 | 工具名称 |
| **PreInvocation** | 在调用大模型前触发。 | 无（忽略匹配器） |
| **PostInvocation**| 在工具调用流程结束后触发。| 无（忽略匹配器） |
| **Stop** | 在执行终止时触发。 | 无（忽略匹配器） |

### 匹配器 (Matcher)

对于 `PreToolUse` 和 `PostToolUse`，您可以在 `matcher` 字段中使用正则表达式来指定触发钩子的工具：

* `""` 或 `"*"`：匹配所有工具。
* `"run_command"`：精确匹配 `run_command`。
* `"run_command|view_file"`：匹配这两个工具之一。
* `"browser_.*"`：匹配任何以 `browser_` 开头的工具。

> \[!NOTE]
> 对于 `PreInvocation`、`PostInvocation` 和 `Stop`，其结构更简单（直接在事件键下的处理程序列表），且匹配器会被忽略。

### 支持的工具 (Supported Tools)

对于 `PreToolUse` 和 `PostToolUse` 匹配器，您可以针对以下按类别分组的工具名称进行匹配：

#### 文件与目录操作

* `view_file`：查看文件内容。
* `write_to_file`：创建新文件。
* `replace_file_content`：编辑文件中单个连续的文本块。
* `multi_replace_file_content`：对同一文件进行多次非连续的编辑。
* `list_dir`：列出目录内容。
* `find_by_name`：使用 Glob 模式搜索文件和目录。

#### 搜索与研究

* `grep_search`：在特定路径中进行快速文本搜索。
* `search_web`：执行常规网页搜索。
* `read_url_content`：获取公开 URL 的文本内容。

#### 系统与执行

* `run_command`：提议运行 Bash 命令。
* `manage_task`：与后台任务交互。
* `schedule`：设置定时器或循环 Cron 任务。
* `list_permissions`：查看当前资源访问授权。
* `ask_permission`：请求额外的细粒度作用域权限。

#### Agent 协同

* `invoke_subagent`：派生出专门的子 Agent。
* `define_subagent`：创建自定义子 Agent。
* `send_message`：与其他 Agent 进行通信。
* `manage_subagents`：列出或终止活动的子 Agent。

#### 交互与媒体

* `ask_question`：提出多项选择题。
* `generate_image`：创建或编辑图像。

### 钩子处理程序配置 (Hook Handler Configuration)

`hooks` 数组中的每个项目支持以下字段：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **type** | string | 可选。目前仅支持 `"command"`。默认为 `"command"`。 |
| **command** | string | 必填。要执行的 Shell 命令。 |
| **timeout** | integer | 可选。超时时间（以秒为单位）。默认为 `30`。 |

## 输入/输出协定 (Input/Output Contract)

钩子通过 `stdin` 接收 JSON 输入，并应通过 `stdout` 返回 JSON 输出。字段名使用驼峰命名法（camelCase）。

### 通用输入字段 (Common Input Fields)

所有钩子在通过 `stdin` 传入的输入 Payload 中都会收到以下系统元数据字段：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **conversationId** | string | 当前活动 Agent 对话的唯一 UUID。 |
| **workspacePaths** | array of strings | 代表用户挂载的工作空间的绝对目录路径。 |
| **transcriptPath** | string | 对话日志文件 `transcript.jsonl` 的绝对路径。 |
| **artifactDirectoryPath** | string| 包含所有对话 Artifacts 产物和屏幕截图的目录绝对路径。 |

### PreToolUse

在工具执行前触发。

#### 模式 (Schema)

输入字段 (`stdin`)：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **toolCall** | object | 提议执行的工具调用的详细信息。 |
| **toolCall.name** | string | 正在执行的工具名称（例如 `run_command`）。 |
| **toolCall.args** | object | 传递给该工具的参数。 |
| **stepIdx** | integer | 当前步骤在轨迹中以 0 为起点的索引。 |
| *(通用字段)* | - | 包含 `conversationId`、`workspacePaths`、`transcriptPath`、`artifactDirectoryPath`。 |

输出字段 (`stdout`)：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **decision** | string | 必填。控制如何拦截或准入该工具调用：- `"allow"`：自动允许工具执行。- `"deny"`：立即硬性拦截执行。- `"ask"`：提示用户，但遵守“总是允许”的配置。- `"force_ask"`：总是提示用户，忽略已缓存的权限。 |
| **reason** | string | 可选。向 Agent 或用户展示该决策的解释。 |
| **permissionOverrides** | array of strings | 可选。覆盖默认工具权限的资源字符串列表（如 `["read_file(/path)", "command(args)"]`）。 |

#### 示例

输入 (`stdin`)：

```json
{
  "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": "/workspace/project/.gemini/jetski/transcript.jsonl",
  "artifactDirectoryPath": "/workspace/project/.gemini/jetski/artifacts"
}
```

输出 (`stdout`)：

```json
{
  "decision": "ask",
  "reason": "Requires confirmation for test execution.",
  "permissionOverrides": [
    "command(npm test)"
  ]
}
```

### PostToolUse

在工具完成运行后触发。

#### 模式 (Schema)

输入字段 (`stdin`)：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **stepIdx** | integer | 已完成步骤的 0 起点索引。 |
| **error** | string | 可选。如果工具调用失败，则为详细的运行时错误消息；如果成功，则为空。 |
| *(通用字段)* | - | 包含 `conversationId`、`workspacePaths`、`transcriptPath`、`artifactDirectoryPath`。 |

输出字段 (`stdout`)：返回一个空的 JSON 对象 `{}`。

#### 示例

输入 (`stdin`)：

```json
{
  "stepIdx": 5,
  "error": "exit status 1",
  "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
  "workspacePaths": [
    "/workspace/project"
  ],
  "transcriptPath": "/workspace/project/.gemini/jetski/transcript.jsonl",
  "artifactDirectoryPath": "/workspace/project/.gemini/jetski/artifacts"
}
```

输出 (`stdout`)：`{}`

### PreInvocation

在调用大模型前触发。

#### 模式 (Schema)

输入字段 (`stdin`)：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **invocationNum** | integer | 当前模型调用的序列号。 |
| **initialNumSteps** | integer | 目前在轨迹中的步数。 |
| *(通用字段)* | - | 包含 `conversationId`、`workspacePaths`、`transcriptPath`、`artifactDirectoryPath`。 |

输出字段 (`stdout`)：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **injectSteps** | array of objects | 可选。在大模型被调用之前，要注入到对话轨迹中的步骤列表。 |

**注入的步骤模式 (Injected Step Schema)**：`injectSteps` 数组中的每个对象可以包含以下字段之一：

* `toolCall` (object)：要执行的工具调用。
* `userMessage` (string)：来自用户的消息。
* `ephemeralMessage` (string)：临时的系统消息。

#### 示例

输入 (`stdin`)：

```json
{
  "invocationNum": 3,
  "initialNumSteps": 10,
  "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
  "workspacePaths": [
    "/workspace/project"
  ],
  "transcriptPath": "/workspace/project/.gemini/jetski/transcript.jsonl",
  "artifactDirectoryPath": "/workspace/project/.gemini/jetski/artifacts"
}
```

输出 (`stdout`)：

```json
{
  "injectSteps": [
    {
      "ephemeralMessage": "Remember to lint"
    }
  ]
}
```

### PostInvocation

在工具调用流程结束后触发。

#### 模式 (Schema)

输入字段 (`stdin`)：与 `PreInvocation` 输入字段相同。

输出字段 (`stdout`)：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **injectSteps** | array of objects | 可选。在模型调用完成后注入的步骤列表（模式与 `PreInvocation` 注入步骤相同）。 |
| **terminationBehavior** | string | 可选。控制注入后的执行流程：- `"force_continue"`：强制循环继续。- `"terminate"`：强制循环终止。- `""`（或省略）：默认行为。 |

#### 示例

输入 (`stdin`)：与 `PreInvocation` 相同。
输出 (`stdout`)：

```json
{
  "injectSteps": [],
  "terminationBehavior": ""
}
```

### Stop

在执行循环终止时触发。

#### 模式 (Schema)

输入字段 (`stdin`)：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **executionNum** | integer | 执行尝试的序列号。 |
| **terminationReason** | string | 执行停止的原因（例如 `"model_stop"`, `"max_steps_exceeded"`, `"error"`）。 |
| **error** | string | 可选。如果停止是由系统错误引起的，则为错误消息。 |
| **fullyIdle** | boolean | 必填。如果 Agent 完全运行结束，且所有后台命令或异步任务都已完成，则为 `true`。如果有活跃的后台任务仍在运行，则为 `false`。 |
| *(通用字段)* | - | 包含 `conversationId`、`workspacePaths`、`transcriptPath`、`artifactDirectoryPath`。 |

输出字段 (`stdout`)：
| 字段 | 类型 | 描述 |
| :--- | :--- | :--- |
| **decision** | string | 必填。设置为 `"continue"` 以阻止 Agent 停止，并重新进入执行循环。任何其他值都将允许停止。 |
| **reason** | string | 可选。如果 `decision` 是 `"continue"`，该消息将被作为系统消息注入到对话中。 |

#### 示例

输入 (`stdin`)：

```json
{
  "executionNum": 1,
  "terminationReason": "model_stop",
  "error": "",
  "fullyIdle": true,
  "conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
  "workspacePaths": [
    "/workspace/project"
  ],
  "transcriptPath": "/workspace/project/.gemini/jetski/transcript.jsonl",
  "artifactDirectoryPath": "/workspace/project/.gemini/jetski/artifacts"
}
```

输出 (`stdout`)：

```json
{
  "decision": "continue",
  "reason": "Not done yet"
}
```
