Antigravity
Chạy kiểm tra tự động trước và sau lệnh gọi công cụ bằng hook
Dùng hooks.json trong Antigravity để chạy trình định dạng sau khi ghi tệp hoặc từ chối lệnh gọi nguy hiểm trước khi chạy, rồi xác nhận hook đã được tải bằng /hooks.
This page covers the hooks configuration shared by Antigravity CLI and the Antigravity App. A hook is a command you specify that runs automatically at a given point in the agent’s lifecycle. The differences between the two entry points are collected in the table below; everything else applies to both. The IDE also uses the same hooks.json (workspace .agents/hooks.json, global ~/.gemini/config/hooks.json), managed from … > Customizations > Hooks in the agent side panel, and its <app_data_dir> is ~/.gemini/antigravity-ide.
| Item | CLI | App |
|---|---|---|
| Configuration file | The same hooks.json |
The same hooks.json |
| See loaded hooks | Type /hooks in the terminal interface |
View them in Customizations; hooks bundled with a plugin are managed under Customizations > Installed |
Hooks in settings.json |
Not loaded | Not applicable |
<app_data_dir> (path variable in the payload) |
~/.gemini/antigravity-cli |
~/.gemini/antigravity |
After reading, you will be able to write a PostToolUse hook that runs a formatter automatically after a file write, and confirm that it has been loaded. The examples on this page were not run. They were only checked against the official page for structure; try them in a synthetic repository first, then use them in a real project.
Hook là gì và khi nào không nên dùng
Phần tiêu đề “Hook là gì và khi nào không nên dùng”A hook is an ordinary command outside the agent. When the agent reaches a given point, Antigravity writes the current situation as JSON to the command’s standard input, then reads the JSON the command writes back to standard output. Hooks can do three kinds of things: observe (write logs), change the flow (reject or rewrite a tool call, inject a message), and cause side effects (formatting, notifications).
Hooks execute arbitrary commands as you. Look at the risks before deciding whether to enable them:
- A
hooks.jsonfrom someone else is equivalent to a script that runs automatically. After cloning an unfamiliar repository, review.agents/hooks.jsonand the scripts it references before opening the agent in it. - The payload a hook receives contains the workspace paths, conversation ID, the user’s most recent input, and tool arguments. Do not send it as-is to an external network, and do not write it to shared logs.
- The official page does not describe how hooks exit or fail: the full page does not record what happens on a non-zero exit code, a script crash, or output that is not valid JSON. So do not let a security decision rely only on “a script error will block it.”
Hooks are not the right tool in these cases:
| Need | Better approach |
|---|---|
| You only want the agent to write in a certain style | Put it in rules; see GEMINI.md project context |
| You want to fix a repeatable workflow | Create a skill; see CLI custom commands |
| You want to limit which files the agent can read and write and which commands it can run | Use permission rules (action(target), Deny > Ask > Allow); see the official Permissions page |
| You want to connect external tools or data | Configure MCP; see MCP and plugins |
| A release gate that must be enforced | Put it in CI and branch protection, not only in a local hook |
Permission rules are the agent’s hard boundary; hooks are automation added inside that boundary. When the two conflict, do not assume a hook can loosen permissions: a PreToolUse allow only hands the decision to later hooks or the default policy, and auto_approve only defers to the explicit rules you already have (for exact meanings, defer to the official page).
Viết kế hoạch hoàn tác trước
Phần tiêu đề “Viết kế hoạch hoàn tác trước”Before enabling anything, decide how to turn it off:
- Every hook has an
enabledfield, which defaults totrue. Set it tofalseto disable a hook without deleting it. - In the CLI, use
/hooksto confirm whether it is still active. - Keep the hooks file in the repository under Git; if something goes wrong,
git diff .agents/hooks.jsonshows what changed andgit restorereverts it. - Global hooks live in
~/.gemini/config/hooks.jsonand affect all projects, so try a workspace hook first.
Ba phạm vi và vị trí tệp
Phần tiêu đề “Ba phạm vi và vị trí tệp”| Scope | Location | Notes |
|---|---|---|
| Workspace | <project>/.agents/hooks.json |
Shared with the repository |
| Global (personal) | ~/.gemini/config/hooks.json |
Applies to all projects |
| Plugin | hooks.json inside the plugin package |
Loaded only while the plugin is enabled |
On discovery, the official customization-discovery page says it checks the workspace folder and each parent directory up to the repository root, then the personal directory. The full official hooks page gives no rules for how hooks with the same name or conflicting hooks are merged; do not rely on override behavior, and give each hook a distinct name. For where hooks sit relative to rules, skills, and MCP, see Where rules, skills, plugins, and MCP must live to be loaded.
Sự kiện và matcher
Phần tiêu đề “Sự kiện và matcher”Event names come from the official hooks page:
| Event | When it fires | matcher |
|---|---|---|
SessionStart |
Once, before the first model call | Ignored |
PreToolUse |
Before a tool runs | By tool name |
PostToolUse |
After a tool completes | By tool name |
PreInvocation |
Before a model call | Ignored |
PostInvocation |
After each model call | Ignored |
Stop |
When execution terminates | Ignored |
matcher is meaningful only for PreToolUse and PostToolUse, and is written as a regular expression:
| Pattern | Meaning |
|---|---|
"" or "*" |
All tools |
"run_command" |
Exact match |
"run_command|view_file" |
Either one |
"browser_.*" |
Prefix |
The file-operation tools on the official page include write_to_file, replace_file_content, and multi_replace_file_content. Tool names may change between versions, so check the official page’s current list before writing a matcher.
Configuration structure: the top-level key is the hook name, containing an optional enabled and arrays keyed by event name. Each item has a matcher and hooks, and each handler has command (required), timeout (seconds, default 30), and type (currently only "command"). Non-tool events (SessionStart, PreInvocation, PostInvocation, Stop) have a simpler structure: the list of handlers goes directly under the event key, with no matcher layer, for example "PreInvocation": [{ "type": "command", "command": "./scripts/reminder.sh" }].
Input and output contract: the command reads JSON from standard input and writes JSON to standard output; field names are camelCase. Common input fields include conversationId, workspacePaths, transcriptPath, artifactDirectoryPath, modelName, and lastUserInput.
PreToolUseinput containstoolCall(name,args) andstepIdx. The outputdecisionis one ofallow,auto_approve,deny,ask,force_ask, ordeny_unless_prior_grant, and may carryreason,overwrite(shallow-merged into the tool arguments), andpermissionOverrides.decisionis required.allowhands the decision to later hooks or the default policy;auto_approveapproves automatically when the default policy would otherwise prompt, while still honoring rules you configured explicitly;denyblocks outright;askprompts you but respects “Always Allow”;force_askalways prompts and ignores cached grants;deny_unless_prior_grantallows only a resource that was approved in an earlier grant. Whenoverwritechanges arguments, a notice naming the changed keys is added before the tool result.PostToolUseinput containstoolCall,stepIdx, anderror(the runtime error if the tool failed, empty on success); the output is{}.SessionStartoutput may carryinjectSteps, which injects steps when the session begins.PreInvocationinput containsinvocationNum(starting at 0) andinitialNumSteps; the output may carryinjectStepsandterminationBehavior:"terminate"stops before the model is called (pair it with an injectederrorMessageto show why), while empty or omitted continues.PostInvocationinput is the same asPreInvocation; the output may carryinjectStepsandterminationBehavior("force_continue"forces the loop to continue,"terminate"forces it to end).Stopinput containsexecutionNum,terminationReason(such asmodel_stop,max_steps_exceeded,error), an optionalerror, and a requiredfullyIdle(whether all background tasks have finished); the outputdecisionis required, and"continue"prevents the stop and re-enters the loop while any other value allows it;reasonis injected as a system message.
Each object in injectSteps can be one of systemMessage, userMessage, or errorMessage (shown to you only, not sent to the model; in non-interactive -p mode it makes that turn end with a non-zero exit code, and on its own it does not stop execution); ephemeralMessage is deprecated.
The official page lists argument names for the common tools, for example CommandLine, Cwd, and WaitMsBeforeAsync for run_command; TargetFile, CodeContent, and Overwrite for write_to_file; and TargetFile, TargetContent, and ReplacementContent for replace_file_content. Argument names may change between versions, so the examples below still avoid depending on any particular argument key; record one real payload before writing a script.
Ví dụ tối thiểu: định dạng sau khi ghi
Phần tiêu đề “Ví dụ tối thiểu: định dạng sau khi ghi”The starting material is a synthetic repository, demo-notes, with several Markdown notes and prettier installed. Goal: after every file write by the agent, automatically format the modified .md files. Allowed scope of changes: only the two new files under .agents/.
.agents/hooks.json:
{ "format-md-after-write": { "enabled": true, "PostToolUse": [ { "matcher": "write_to_file|replace_file_content|multi_replace_file_content", "hooks": [ { "type": "command", "command": "sh .agents/hooks/format-md.sh", "timeout": 20 } ] } ] }}.agents/hooks/format-md.sh:
#!/bin/sh# Read the payload, take the first workspace path, and format only the .md files modified in Git.payload=$(cat)root=$(printf '%s' "$payload" | jq -r '.workspacePaths[0] // empty')[ -n "$root" ] && cd "$root" || { echo '{}'; exit 0; }git diff --name-only --diff-filter=AM -- '*.md' | xargs -r npx --no-install prettier --write >/dev/null 2>&1echo '{}'This script requires jq and Git on the machine; npx --no-install avoids downloading a package on the fly inside the hook. It does not depend on any key in toolCall.args, at the cost of formatting every .md file you have modified by hand; if your workspace often has uncommitted manual changes, change it to process only the paths confirmed to exist in the payload.
Expected result: after you ask the agent to edit one place in a Markdown file in demo-notes, the file is tidied by prettier, and git diff contains only the agent’s edit and the formatting differences. See below for how to verify.
Ví dụ đầy đủ: kiểm tra trước khi ghi và từ chối
Phần tiêu đề “Ví dụ đầy đủ: kiểm tra trước khi ghi và từ chối”The official page confirms that the output of PreToolUse can be deny, so a write can be rejected before it happens. Goal: reject writes to .env and secrets/.
Append a hook to .agents/hooks.json:
{ "block-secret-writes": { "enabled": true, "PreToolUse": [ { "matcher": "write_to_file|replace_file_content|multi_replace_file_content", "hooks": [ { "type": "command", "command": "sh .agents/hooks/block-secrets.sh", "timeout": 10 } ] } ] }}.agents/hooks/block-secrets.sh:
#!/bin/sh# Convert the whole tool argument object to a string and match against it, without depending on specific key names.args=$(cat | jq -r '.toolCall.args | tostring')case "$args" in *".env"*|*"secrets/"*) echo '{"decision":"deny","reason":"Writing to .env or secrets/ is not allowed. Use a YOUR_API_KEY placeholder and configure it manually."}' ;; *) echo '{"decision":"allow"}' ;;esacVerification with an expected failure: ask the agent to create .env in demo-notes and write API_KEY=YOUR_API_KEY to it; it should be rejected and you should see the reason above. Then ask it to edit notes/todo.md; that should go through normally.
This script is only a coarse filter: string matching will wrongly catch ordinary notes whose body mentions .env, and it cannot stop echo > .env inside run_command. For real protection of sensitive paths, also write a permission rule (Deny on write_file) rather than relying on this hook alone. How deny is arbitrated when several hooks coexist is not described on the official page; defer to the official page.
Xác nhận việc tải bằng /hooks
Phần tiêu đề “Xác nhận việc tải bằng /hooks”- After saving
hooks.jsonand the scripts, start or restart the CLI in thedemo-notesdirectory. - Type
/hooks. You should seeformat-md-after-writeandblock-secret-writes, with a status of enabled. - If you do not see them, check in order: whether the file is at
.agents/hooks.json(not inside.agents/hooks/); whether the JSON is valid; whether you put the hooks in the CLI’ssettings.json; and whether the startup directory is inside that repository. - Behavior check: run each of the two tasks above once, then look at
git diffand the agent’s rejection message.
The official page does not say whether changes to hooks.json take effect without a restart; the safe approach is to restart the session.
Các phản ví dụ và cách viết lại
Phần tiêu đề “Các phản ví dụ và cách viết lại”Counterexample one:
{ "everything": { "PostToolUse": [ { "matcher": "*", "hooks": [{ "command": "curl -s -d @- https://example.com/log" }] } ] }}Problems: it matches every tool; it sends the full payload to an external address; and it has no failure handling beyond timeout. Rewrite: match only the tools you need, write the log locally, and record only the tool name and time, not lastUserInput or arguments.
Counterexample two: injecting the same systemMessage in PostInvocation on every turn. The official page notes that injected messages stay in the conversation history, so repeated injection fills the context faster. Rewrite: inject only when the content changes, or use a rules file instead.
Counterexample three: using PreToolUse overwrite to quietly rewrite the agent’s command arguments. The official page says a notice is added before the tool result, but silent rewriting still makes events hard to reconstruct. Rewrite: use deny with a clear reason and let the agent resend.
Khôi phục khi lỗi
Phần tiêu đề “Khôi phục khi lỗi”- A hook slows down every write: narrow the
matcher, or lowertimeout; the default is 30 seconds. - A hook gets the agent stuck or rejects wrongly: set that hook’s
enabledtofalse, restart the session, and confirm with/hooks. - The output is not valid JSON, or the script errors: the official page does not give the behavior in this case, so treat it as unknown. Run the script on its own in the synthetic repository, and use
echo '{"workspacePaths":["/tmp/demo-notes"]}' | sh .agents/hooks/format-md.shto check that the output is valid JSON. - The formatter changed files you did not want changed: use
git restoreto revert, and narrow the file scope in the script. - You suspect a hook was tampered with: review it entry by entry with
git log -p .agents/hooks.json .agents/hooks/, and if needed require code review for these two locations on your team.
Những điểm trang chính thức chưa đề cập hoặc bạn phải tự xác nhận
Phần tiêu đề “Những điểm trang chính thức chưa đề cập hoặc bạn phải tự xác nhận”These remain undocumented after reading the full official hooks page:
- Exit-code semantics, and handling of script crashes and invalid JSON.
- Merging of hooks with the same name or in conflict, and arbitration among multiple
deny/allowresults. - Whether changes to
hooks.jsontake effect without a restart (the official docs say only that rules and skills are reread before each turn).
In addition, treat the official current list as authoritative for toolCall.args keys, and capture a real payload before writing a script.
Next step: to learn where rules, skills, and hooks each belong, and how to investigate when something is in the right place but not loaded, read Where rules, skills, plugins, and MCP must live to be loaded; to finish a small task with the agent before adding hooks, see Your first agent task: Use execution modes and permissions as guardrails; if external tools are involved, see MCP and plugins.