寫完 #05 Rules 的最後一個坑,緊接著就繞不開 hooks.json 了。

Rules 寫得再嚴厲,本質上還是塞進 Prompt 裡的軟約束。上下文一長、工具呼叫一多,模型照樣可能忘掉末尾那句「絕對禁止 git push --force」,或者直接執行一條不帶參數的裸 pytest,把幾千行錯誤堆疊全刷進上下文。

Antigravity 的 Lifecycle Hooks 就是用來兜底這類「不能靠模型自覺」的事情的。它不和模型商量,而是直接嵌在 Agent 執行迴圈的固定關卡上:每到特定階段,執行時期同步阻塞地把上下文透過 stdin 餵給你的外部腳本,再根據腳本 stdout 回傳的 JSON 決定放行、硬攔、改寫參數,或者把準備停工的 Agent 拉回去接著修測試。


一、設定檔放哪裡,怎麼組織?

Hooks 統一寫在單一 hooks.json 檔案裡,依生效範圍可以放在三個位置:

存放位置 生效範圍 常見用途
.agents/hooks.json 目前專案(可提交進 Git) 團隊共享的危險指令攔截、自動 Lint、提交前驗收門禁
~/.gemini/config/hooks.json 本機所有工作區 個人全域稽核日誌、跨專案安全兜底
plugins/<name>/hooks.json 對應外掛啟用期間 隨外掛打包分發的自動化守衛與校驗腳本

外掛目錄的硬坑:執行時期的外掛發現機制只會嚴格讀取外掛根目錄的 <plugin_dir>/hooks.json。雖然用 agy plugin import(或 install)匯入純 Gemini CLI(gemini-extension.json)或 Claude Code(.claude-plugin/plugin.json)擴充功能時,安裝器會把 hooks/hooks.json 搬運到外掛根目錄;但 Antigravity 原生外掛(包含 plugin.json、.antigravity-plugin/plugin.json、.gemini-plugin/plugin.json 或透過 plugins.json 載入的目錄)不會執行搬運步驟,必須把 hooks.json 直接放在外掛根目錄。

1. 檔案結構與合併規則

hooks.json 頂層是一個 JSON 物件,每個頂層 key 都是你自訂的 hook 名稱,下面依事件名稱掛接處理器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
{
"safety-gate": {
"enabled": true,
"PreToolUse": [
{
"matcher": "run_command",
"hooks": [
{
"type": "command",
"command": "python3 ./scripts/pre-tool-guard.py",
"timeout": 10
}
]
}
]
},
"post-lint": {
"PostToolUse": [
{
"matcher": "edit_file|write_file",
"hooks": [
{
"command": "./scripts/post-tool-lint.sh",
"timeout": 15
}
]
}
]
},
"stop-test-gate": {
"enabled": false,
"Stop": [
{
"type": "command",
"command": "./scripts/stop-test-gate.sh",
"timeout": 25
}
]
}
}

設定裡有幾個細節容易忽略:

  • 臨時開關:在命名 hook 這一層加 "enabled": false 就能一鍵關閉整組處理器,除錯時不用刪設定。
  • 多來源合併:來自專案、全域或不同外掛的多個命名 hook,如果監聽同一個事件,會被合併並依順序逐一執行。
  • 執行方式與逾時:handler 目前只支援 "type": "command"(可省略,預設就是 "command")。Unix 上透過 sh -c 執行,Windows 上透過 cmd /c 執行,~ 會自動展開為家目錄;timeout 預設 30 秒。

2. 工作目錄與外掛環境變數(高頻踩坑點)

每個 hook 子程序啟動時,程序的工作目錄是 hooks.json 所在的目錄(例如 .agents/ 或 plugins/<name>/),而不是 Agent 目前操作的專案目錄。正因如此,上面範例裡才能直接寫 ./scripts/pre-tool-guard.py 指向同目錄下的腳本;但腳本內部如果要操作儲存庫檔案、跑 git 或 pytest,必須讀取 stdin JSON 裡的 cwd 欄位。

如果 hook 隨外掛分發,執行時期還會給子程序注入兩個環境變數:

  • PLUGIN_ROOT:外掛根目錄路徑;
  • PLUGIN_DATA:已安裝外掛的持久化資料目錄(與外掛內 MCP 伺服器拿到的路徑一致)。

注意它們不會被範本展開進 command 字串裡,而是標準子程序環境變數。引用外掛自帶腳本直接用相對路徑,引用持久化快取目錄時讓 shell 去讀變數即可,例如:

1
2
3
{
"command": "./hooks/check.sh --cache \"$PLUGIN_DATA\""
}

二、6 大生命週期事件與執行鏈路

Antigravity 一共開放了 6 個生命週期事件。結構上分成兩類:工具級事件(PreToolUse / PostToolUse)是 Grouped 結構,必須包一層 matcher 和 hooks 陣列;其餘 4 個迴圈級事件是 Flat 結構,直接放 handler 物件陣列。

Antigravity Hooks 6 大生命週期事件與決策攔截鏈路

先看一張精簡對照表,寫設定時可以直接當速查表用:

事件名稱 觸發時機 結構與 Matcher 關鍵輸入 / 輸出控制能力
SessionStart 新工作階段首次啟動時觸發一次 Flat(無 matcher) 僅公共中繼資料 → 輸出 injectSteps 注入啟動提示
PreInvocation 每次請求模型之前 Flat(無 matcher) 含 invocationNum/initialNumSteps → injectSteps、terminationBehavior: "terminate"
PreToolUse 單一工具執行之前 Grouped(matcher 正規表示式) 含 toolCall/stepIdx → decision(allow/deny/ask/force_ask)、reason、permissionOverrides、overwrite
PostToolUse 單一工具執行完成後 Grouped(matcher 正規表示式) 含同 toolCall.id 與失敗時的 error → 輸出空物件 {}
PostInvocation 本輪工具呼叫結束後 Flat(無 matcher) 同 PreInvocation → injectSteps、terminationBehavior("force_continue" / "terminate")
Stop 執行迴圈準備結束前 Flat(無 matcher) 含 executionNum/terminationReason/fullyIdle/continuationActive → decision: "continue" + reason

把 6 個事件放回 Agent 的單輪執行迴圈裡看,整個攔截與續跑流轉非常清晰:

有幾個事件欄位平時用不到,但一到關鍵場景特別順手,這裡單獨點一下:

  • PreInvocation 的 injectSteps 支援 3 種有效類型(ephemeralMessage 已廢棄,不再建議使用):
    1. {"systemMessage": {"systemMessage": "...", "metadata": {...}}}:持久化進對話軌跡;注意值必須是巢狀物件而非純字串。如果只想把一段 Markdown 直接內嵌展示給使用者看、不發給模型,可以把正文放進 metadata.user_markdown,把 systemMessage 留成 ""。
    2. {"userMessage": "..."}:注入一條使用者訊息(純字串)。
    3. {"errorMessage": {"userMessage": "..."}}:向使用者顯示錯誤訊息且不發給模型;在 -p 非互動模式下會以非零結束代碼標記本輪失敗,但它本身不會中止迴圈,想直接攔停必須同時回傳 "terminationBehavior": "terminate"。
  • Stop 的 terminationReason 列舉:來自 ExecutorTerminationReason 去掉 EXECUTOR_TERMINATION_REASON_ 前綴,包括 NO_TOOL_CALL、MAX_INVOCATIONS、MAX_FORCED_INVOCATIONS、MAX_TOKEN_BUDGET_EXCEEDED、ERROR、USER_CANCELED、TERMINAL_STEP_TYPE、TERMINAL_CUSTOM_HOOK、INJECTED_RESPONSE。寫門禁腳本時一定要核對這個欄位,不能把使用者手動 Ctrl+C(USER_CANCELED)或上游錯誤(ERROR)給強行續跑回來。

三、Stdin / Stdout 協定的 3 個關鍵細節

所有 hook 的通訊方式都極簡:執行時期往 stdin 寫一個 JSON,腳本往 stdout 吐一個 JSON。但真上手寫腳本,最容易栽在下面 3 個協定細節上。

1. 所有 key 一律 camelCase(protojson 編碼)

每個事件的 stdin 都會帶上這組公共欄位:

1
2
3
4
5
6
7
8
9
10
{
"conversationId": "ec33ebf9-0cba-4100-8142-c61503f6c587",
"workspacePaths": ["/home/user/demo-app"],
"transcriptPath": "/home/user/.gemini/antigravity-cli/brain/ec33ebf9-0cba-4100-8142-c61503f6c587/.system_generated/logs/transcript.jsonl",
"artifactDirectoryPath": "/home/user/.gemini/antigravity-cli/brain/ec33ebf9-0cba-4100-8142-c61503f6c587",
"modelName": "auto",
"lastUserInput": "Fix the failing unit test",
"hookEventName": "PreToolUse",
"cwd": "/home/user/demo-app"
}

寫過 Claude Code Hook 的人順手寫 .tool_name、.hook_event_name、.session_id 會直接取到 null——Antigravity 的 payload 走 protojson 編碼,所有鍵名都是 camelCase(例如 conversationId、stepIdx、toolCall、hookEventName)。唯一例外是某些工具內部的 args(例如 run_command 裡的 CommandLine),保持的是工具自身的 schema 大小寫。

2. transcriptPath 與 artifactDirectoryPath 隨入口變化

同一個專案,你在不同入口跑 Agent,這兩個路徑裡的產品目錄名稱不一樣:

使用入口 路徑中的產品目錄名稱
agy CLI antigravity-cli/
Antigravity 2.0 桌面端 antigravity/
Antigravity IDE antigravity-ide/

所以腳本裡如果要讀目前工作階段的 transcript.jsonl 或往產物目錄寫報告,直接用 stdin 給的 transcriptPath / artifactDirectoryPath,別自己硬拼 ~/.gemini/antigravity/...。

3. matcher 比對規則與工具名稱來源

PreToolUse 和 PostToolUse 裡的 matcher 是正規表示式,比對的是工具名稱(由底層步驟類型去掉 CORTEX_STEP_TYPE_ 前綴並轉小寫得到):

  • "*" 或 "":比對全部工具;
  • "run_command":精確比對終端機執行工具;
  • "run_command|read_file":或比對其中任意一個;
  • "browser_.*":正規前綴比對所有瀏覽器工具。

四、三大高頻實戰腳本(附本機驗證輸出)

寫 hook 腳本有個很省事的除錯習慣:不用每次都啟動一整輪真實對話去碰運氣,直接用 echo '{...}' | ./script 餵一份模擬 payload,看 stdout 是不是合法 JSON、看 stderr 日誌對不對,調通再掛進 .agents/hooks.json。

PreToolUse 阻斷/改寫與 Stop 防無窮迴圈 stdin/stdout 實測

實戰 1:PreToolUse 高危指令阻斷 + overwrite 參數改寫

這是我自己在專案裡必配的一道硬關卡,一份腳本同時做三件事:

  1. 命中 rm -rf / 或 git push --force:直接回傳 deny 攔死;
  2. 命中 git push / kubectl apply / npm publish:回傳 force_ask,無視之前點過的「Always Allow」快取,每次都強制彈出確認;
  3. 跑裸 pytest 且沒帶 --tb= 參數:回傳 allow + overwrite,自動補上 --tb=short -q,避免超長 traceback 刷爆上下文。

儲存為 .agents/scripts/pre-tool-guard.py:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#!/usr/bin/env python3
import json
import re
import sys

payload = json.load(sys.stdin)
tool = payload.get("toolCall", {})
args = tool.get("args", {})
cmd = args.get("CommandLine", "")
cwd = payload.get("cwd", "")

# 1. 高風險命令直接阻斷
DENY_PATTERNS = [
(r"(^|[;&|]\s*)rm\s+-rf\s+(/|~|\$HOME|\*)(\s|$)", "禁止對根目錄、家目錄或萬用字元執行 rm -rf"),
(r"\bgit\s+push\b.*(--force|-f\b)", "禁止直接 git push --force,請先確認分支保護策略"),
]
for pattern, reason in DENY_PATTERNS:
if re.search(pattern, cmd):
print(f"[pre-tool-guard] DENY step={payload.get('stepIdx')} cwd={cwd} cmd={cmd}", file=sys.stderr)
print(json.dumps({"decision": "deny", "reason": reason}, ensure_ascii=False))
sys.exit(0)

# 2. 高影響操作強制人工確認(忽略 Always Allow 快取)
if re.search(r"\b(git\s+push|kubectl\s+apply|npm\s+publish)\b", cmd):
print(json.dumps({
"decision": "force_ask",
"reason": f"偵測到外部副作用命令,需人工逐次確認:{cmd}"
}, ensure_ascii=False))
sys.exit(0)

# 3. 安全參數改寫(shallow top-level overwrite)
if re.match(r"^\s*pytest(\s|$)", cmd) and "--tb=" not in cmd:
rewritten = f"{cmd.strip()} --tb=short -q"
print(f"[pre-tool-guard] OVERWRITE: {cmd!r} -> {rewritten!r}", file=sys.stderr)
print(json.dumps({
"decision": "allow",
"overwrite": {"CommandLine": rewritten}
}, ensure_ascii=False))
sys.exit(0)

print(json.dumps({"decision": "allow"}))

本機直接餵三筆 stdin 實測,結果如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# 1) 命中高風險強制推送 -> deny
$ echo '{"hookEventName":"PreToolUse","cwd":"/home/user/demo-app","stepIdx":12,"toolCall":{"id":"toolu_01","name":"run_command","args":{"CommandLine":"git push origin main --force"}}}' \
| python3 .agents/scripts/pre-tool-guard.py
[pre-tool-guard] DENY step=12 cwd=/home/user/demo-app cmd=git push origin main --force
{"decision": "deny", "reason": "禁止直接 git push --force,請先確認分支保護策略"}

# 2) 命中裸 pytest -> allow + overwrite
$ echo '{"hookEventName":"PreToolUse","cwd":"/home/user/demo-app","stepIdx":15,"toolCall":{"id":"toolu_02","name":"run_command","args":{"CommandLine":"pytest tests/api"}}}' \
| python3 .agents/scripts/pre-tool-guard.py
[pre-tool-guard] OVERWRITE: 'pytest tests/api' -> 'pytest tests/api --tb=short -q'
{"decision": "allow", "overwrite": {"CommandLine": "pytest tests/api --tb=short -q"}}

# 3) 一般 push -> force_ask
$ echo '{"hookEventName":"PreToolUse","cwd":"/home/user/demo-app","stepIdx":18,"toolCall":{"id":"toolu_03","name":"run_command","args":{"CommandLine":"git push origin feat/hooks"}}}' \
| python3 .agents/scripts/pre-tool-guard.py
{"decision": "force_ask", "reason": "偵測到外部副作用命令,需人工逐次確認:git push origin feat/hooks"}

關於 overwrite,有兩個執行時期行為一定要記牢:

  1. 它是頂層淺合併(shallow top-level merge):overwrite 裡的每個 key 會直接取代工具 args 裡對應的頂層 key。如果某個頂層欄位本身是巢狀物件,它會被整塊取代,不會做 deep merge——所以改巢狀物件時,必須先把原物件從 stdin 讀出來合併完整再塞回 overwrite。
  2. 模型會收到改寫通知:實際執行並寫入軌跡的是改寫後的工具呼叫,而由於模型自己記住的是它最初發出的呼叫,Antigravity 會在回傳給模型的工具結果前自動拼接一段前綴提示,明確告訴模型哪些參數鍵被 hook 改寫了,避免模型對輸出格式產生幻覺。

實戰 2:PostToolUse 寫檔後自動 Lint / Format

PostToolUse 的傳入參數裡帶有和 PreToolUse 完全一致的 toolCall.id(方便做耗時或呼叫配對稽核),如果工具執行失敗還會帶上 error 欄位。

下面這個腳本掛在 edit_file|write_file 上:工具發生錯誤時直接記日誌跳過;成功後切到 payload 裡的 cwd,對 .py 檔案跑自動檢查/格式化,把工具輸出全部重導向到 stderr(>&2),最後在 stdout 老老實實回傳 {}。

儲存為 .agents/scripts/post-tool-lint.sh(記得 chmod +x):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/usr/bin/env bash
set -euo pipefail

PAYLOAD="$(cat)"
TOOL_ID="$(jq -r '.toolCall.id // ""' <<<"$PAYLOAD")"
TOOL_NAME="$(jq -r '.toolCall.name // ""' <<<"$PAYLOAD")"
TOOL_ERR="$(jq -r '.error // ""' <<<"$PAYLOAD")"
CWD="$(jq -r '.cwd // ""' <<<"$PAYLOAD")"
TARGET="$(jq -r '.toolCall.args.Path // ""' <<<"$PAYLOAD")"

# 1. 工具本身失敗時只記錄日誌,不盲目執行 lint
if [[ -n "$TOOL_ERR" ]]; then
echo "[post-lint] skip failed call id=$TOOL_ID tool=$TOOL_NAME err=$TOOL_ERR" >&2
printf '{}\n'
exit 0
fi

# 2. 切到 payload 裡的 cwd(而非 hooks.json 所在目錄),所有輸出導向 stderr
if [[ -n "$CWD" && -d "$CWD" && "$TARGET" == *.py ]]; then
echo "[post-lint] checking $TARGET in $CWD (id=$TOOL_ID)" >&2
(cd "$CWD" && ruff check --fix "$TARGET" >&2) || true
fi

# 3. PostToolUse 協定要求 stdout 嚴格回傳空 JSON 物件
printf '{}\n'

本機輸入兩筆測試事件驗證 stdout 純淨度:

1
2
3
4
5
6
7
8
9
10
11
# 工具正常完成
$ echo '{"hookEventName":"PostToolUse","cwd":"/home/user/demo-app","stepIdx":6,"toolCall":{"id":"toolu_04","name":"edit_file","args":{"Path":"src/app.py"}}}' \
| .agents/scripts/post-tool-lint.sh
[post-lint] checking src/app.py in /home/user/demo-app (id=toolu_04)
{}

# 工具報錯(帶 error 欄位)
$ echo '{"hookEventName":"PostToolUse","cwd":"/home/user/demo-app","stepIdx":7,"error":"exit status 1","toolCall":{"id":"toolu_05","name":"run_command","args":{"CommandLine":"npm test"}}}' \
| .agents/scripts/post-tool-lint.sh
[post-lint] skip failed call id=toolu_05 tool=run_command err=exit status 1
{}

實戰 3:Stop 驗收門禁 + continuationActive 防無窮迴圈

Stop 鉤子最實用的場景是「交付驗收」:模型覺得自己改完了,準備交卷停工,我們在 Stop 裡順手跑一遍快速單元測試。如果單元測試掛了,回傳 {"decision": "continue", "reason": "..."},把原因作為 system message 注入對話,把 Agent 拉回迴圈繼續修。

但這裡有一個致命坑:如果測試環境本身有問題或者模型一次沒修好,沒有熔斷條件的 Stop 鉤子會把 Agent 無限拉回迴圈,一直燒到觸發 MAX_FORCED_INVOCATIONS 才停。

正確寫法必須加兩道熔斷前置檢查:

  1. terminationReason != "NO_TOOL_CALL" 時立刻放行(不攔使用者取消、錯誤、超限或上游 hook 終止);
  2. continuationActive == true 時立刻放行——因為 continuationActive 在本輪已經由 Stop 鉤子續跑過時為 true,直到使用者發下一條新訊息才會重設回 false。

儲存為 .agents/scripts/stop-test-gate.sh(記得 chmod +x):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#!/usr/bin/env bash
set -euo pipefail

PAYLOAD="$(cat)"
REASON="$(jq -r '.terminationReason // ""' <<<"$PAYLOAD")"
CONT="$(jq -r '.continuationActive // false' <<<"$PAYLOAD")"
EXEC_NUM="$(jq -r '.executionNum // 0' <<<"$PAYLOAD")"
CWD="$(jq -r '.cwd // ""' <<<"$PAYLOAD")"

# 1. 非正常結束(使用者取消、報錯、超限、其他 hook 終止)直接放行
if [[ "$REASON" != "NO_TOOL_CALL" ]]; then
echo "[stop-gate] skip: terminationReason=$REASON" >&2
jq -nc '{"decision":"stop"}'
exit 0
fi

# 2. 防無窮迴圈:本輪已經由 Stop hook 續跑過,立刻放行
if [[ "$CONT" == "true" ]]; then
echo "[stop-gate] skip: continuationActive=true (executionNum=$EXEC_NUM)" >&2
jq -nc '{"decision":"stop"}'
exit 0
fi

# 3. 切到 Agent 的 cwd 執行快速單元測試(所有輸出重新導向至 stderr)
if [[ -n "$CWD" && -d "$CWD" ]]; then
if ! (cd "$CWD" && pytest -q --tb=short >&2); then
echo "[stop-gate] test check failed in $CWD" >&2
jq -nc --arg r "驗收門禁失敗:單元測試未通過,請先定位並修復失敗案例後再結束本輪。" \
'{"decision":"continue","reason":$r}'
exit 0
fi
fi

jq -nc '{"decision":"stop"}'

實測三種狀態(首次失敗攔截、續跑後熔斷放行、使用者取消放行):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 1) 首次正常結束但測試失敗 -> 攔住並注入 reason 續跑
$ echo '{"hookEventName":"Stop","cwd":"/tmp/demo","executionNum":0,"terminationReason":"NO_TOOL_CALL","fullyIdle":true,"continuationActive":false}' \
| .agents/scripts/stop-test-gate.sh
[stop-gate] test check failed in /tmp/demo
{"decision":"continue","reason":"驗收門禁失敗:單元測試未通過,請先定位並修復失敗案例後再結束本輪。"}

# 2) 續跑一輪後再次走到 Stop(continuationActive: true)-> 熔斷放行
$ echo '{"hookEventName":"Stop","cwd":"/tmp/demo","executionNum":1,"terminationReason":"NO_TOOL_CALL","fullyIdle":true,"continuationActive":true}' \
| .agents/scripts/stop-test-gate.sh
[stop-gate] skip: continuationActive=true (executionNum=1)
{"decision":"stop"}

# 3) 使用者主動中斷(USER_CANCELED)-> 絕不強行續跑
$ echo '{"hookEventName":"Stop","cwd":"/tmp/demo","executionNum":0,"terminationReason":"USER_CANCELED","fullyIdle":true,"continuationActive":false}' \
| .agents/scripts/stop-test-gate.sh
[stop-gate] skip: terminationReason=USER_CANCELED
{"decision":"stop"}

五、踩坑記錄、目前限制與 Claude Code 差異

把上面三套腳本實際跑順之後,有 4 條硬限制和踩坑經驗最值得提前避開:

  1. 所有 Hook 都是同步阻塞的,沒有非同步模式
    Hook 腳本跑多久,Agent 迴圈就卡多久,預設 30 秒逾時。千萬別在 PostToolUse 裡掛全量 npm run build 或幾十秒的整合測試——單檔格式化(ruff / prettier)控制在 1~3 秒內,重型驗證放到 Stop 鉤子或獨立任務裡做。
  2. 程序工作目錄 ≠ Agent 工作目錄
    Hook 是在 hooks.json 所在目錄(通常是 .agents/)裡起程序的。腳本裡寫相對路徑讀 package.json 或跑 git status 會直接撲空,切記先從 stdin 取出 .cwd 再 cd 過去。
  3. stdout 只要混進一行非 JSON 文字就會直接解析失敗
    腳本裡加除錯 echo、或者呼叫 ruff/pytest/git 忘了重導向,只要有一行一般輸出落進 stdout,Antigravity 解析 JSON 就會掛。鐵律是:除了最後輸出 JSON 的那一句,腳本裡所有指令和日誌一律重導向到 >&2(stderr)。
  4. 目前只支援 type: "command"
    官方文件明確標註了目前限制:暫不支援 HTTP Webhook 類型的 hook,也不支援 prompt-based hook(讓小模型做二次審核)。如果確實需要呼叫外部 HTTP 介面或模型,只能自己包一層 shell / Python 腳本走 command 類型發請求,並盯緊 timeout。

最後,如果你之前寫過 Claude Code 的 Hooks,遷移到 Antigravity 時重點注意這 3 處差異,別憑肌肉記憶硬搬:

比較項目 Antigravity(AGY) Claude Code
設定檔位置 獨立 hooks.json(.agents/、~/.gemini/config/ 或外掛根目錄),頂層依自訂名稱分組並支援 enabled 開關 寫在 settings.json / settings.local.json 的 hooks 欄位下
Payload 鍵名風格 統一 camelCase(protojson:conversationId、hookEventName、toolCall、stepIdx) 以 snake_case 為主(session_id、hook_event_name、tool_name、tool_input)
特有事件與改寫能力 提供細粒度的 PreInvocation / PostInvocation(支援 injectSteps、metadata.user_markdown、force_continue)及 PreToolUse 的淺合併 overwrite 參數改寫 側重 PreToolUse / PostToolUse / UserPromptSubmit / Stop 等事件,參數改寫欄位結構與協定命名不同

下一篇我們繼續沿著客製化擴充往下走,把 MCP 外部工具整合、延遲載入以及 MCP Apps 的 ui:// 內嵌互動介面拆透。如果想直接看把 Hooks 落到多人業務儲存庫裡的進階寫法(用詞法解析 + heredoc + Python AST 防 bash -c / python -c 逃逸的雙協定攔截器),可以直接延伸閱讀 工程化實戰 #3:專案級 .agent/ 隔離、雙協定 Hooks 與唯讀 DB/Redis 外掛。


系列導覽