Antigravity
Run automatic checks before and after tool calls with hooks
Use hooks.json in Antigravity to run a formatter after a file write or reject a dangerous call before it runs, and confirm the hooks are loaded with /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. For the IDE’s entry point and menus, defer to the official page.
| 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.
What hooks are, and when not to use them
Section titled “What hooks are, and when not to use them”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: it 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).
Write the undo plan first
Section titled “Write the undo plan first”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.
The three scopes and file locations
Section titled “The three scopes and file locations”| 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 official page gives no rules for how hooks with the same name or conflicting hooks are merged, so defer to the official page; do not rely on override behavior, and give each hook a distinct name.
Events and matcher
Section titled “Events and 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"). Handlers for non-tool events go directly under the event key; for the details of that form, defer to the original official text.
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.PostToolUseinput containstoolCall,stepIdx, anderror; the output is{}.
Which keys appear in toolCall.args varies by tool, and this page did not check them one by one. The examples below therefore avoid depending on any particular argument key; record one real payload first, then adapt them.
Minimal example: format after writing
Section titled “Minimal example: format after writing”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.
Full example: check before writing and reject
Section titled “Full example: check before writing and reject”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.
Confirm loading with /hooks
Section titled “Confirm loading with /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.
Counterexamples and rewrites
Section titled “Counterexamples and rewrites”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.
Failure recovery
Section titled “Failure recovery”- 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.
Points the official page does not cover or that you must confirm yourself
Section titled “Points the official page does not cover or that you must confirm yourself”- Exit-code semantics, and handling of script crashes and invalid JSON: not documented on the official page.
- Merging and arbitration when multiple hooks conflict: not documented on the official page.
- The specific keys of
toolCall.args: they vary by tool, so capture a real payload first. - The App’s hook management interface and IDE menus: defer to the official page.
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, start with the official Customization discovery; to finish a small task with the agent first, see the official Using the CLI; if external tools are involved, see MCP and plugins.