Skip to content

Conversation

@rickycambrian
Copy link

@rickycambrian rickycambrian commented Nov 22, 2025

Summary

Implemented a comprehensive hook system for Gemini CLI, introducing feature parity with Claude Code hooks. This allows developers to intercept and modify key lifecycle events (like session start, user prompts, tool execution, and model requests) using external scripts or plugins.

Details

This PR adds the core infrastructure and CLI commands to support hooks:

  • Core Architecture:

    • HookRegistry: Loads and manages hook definitions from settings.json.
    • HookRunner: Executes command-based hooks via child processes, handling the JSON-over-stdin protocol compatible with Claude Code.
    • Events: Defined types for SessionStart, SessionEnd, BeforeAgent, AfterAgent, BeforeTool, AfterTool, BeforeModel, and more.
  • CLI Integration:

    • Integrated hooks into gemini.tsx (Session lifecycle).
    • Integrated into useGeminiStream.ts and nonInteractiveCli.ts (Agent loop and Model interaction).
    • Integrated into CoreToolScheduler.ts (Tool execution and blocking).
  • New Commands:

    • gemini hooks migrate: Automatically converts existing Claude Code configuration (~/.claude/settings.json) to Gemini format (~/.gemini/settings.json), remapping paths and event names.
    • gemini hooks list: Displays currently active hooks.

Related Issues

#9140, #9139, #9138, #9137, #9135, #9134, #9133, #9132, #9111, #9109, #9107, #9103, #9098, #9096, #9093, #9091, #9089, #9086, #9083, #9081, #9079, #9077, #9071

How to Validate

  1. Build the project:

    npm run build
  2. Migrate existing Claude hooks (if available):

    node packages/cli/dist/index.js hooks migrate

    Expected Result: Output confirming migration and the number of enabled events. Check ~/.gemini/settings.json to see the hooks section.

  3. List active hooks:

    node packages/cli/dist/index.js hooks list

    Expected Result: A list of events (e.g., SessionStart, BeforeAgent) and the scripts configured for them.

  4. Verify execution:

    • Start a session: node packages/cli/dist/index.js
    • Verification: If you have a SessionStart hook (like session-start.sh), verify it ran (e.g., check your logs or database).
    • Send a prompt.
    • Verification: BeforeAgent hooks should fire.
    • Use a tool.
    • Verification: BeforeTool and AfterTool hooks should fire.

Pre-Merge Checklist

  • Updated relevant documentation and README (if needed)
  • Added/updated tests (if needed)
  • Noted breaking changes (if any)
  • Validated on required platforms/methods:
    • MacOS
      • npm run
      • npx
      • Docker
      • Podman
      • Seatbelt
    • Windows
      • npm run
      • npx
      • Docker
    • Linux
      • npm run
      • npx
      • Docker

@rickycambrian rickycambrian requested review from a team as code owners November 22, 2025 13:39
@google-cla
Copy link

google-cla bot commented Nov 22, 2025

Thanks for your pull request! It looks like this may be your first contribution to a Google open source project. Before we can look at your pull request, you'll need to sign a Contributor License Agreement (CLA).

View this failed invocation of the CLA check for more information.

For the most up to date status, view the checks section at the bottom of the pull request.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @rickycambrian, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a powerful and flexible hook system to the Gemini CLI, enabling developers to intercept and modify various stages of the CLI's operation. By providing feature parity with Claude Code's hook functionality and an automated migration path, it significantly enhances the customizability and integration capabilities for users, allowing them to extend the CLI's behavior with external scripts and plugins.

Highlights

  • Comprehensive Hook System: Implemented a new, extensible hook system for the Gemini CLI, allowing developers to intercept and modify key lifecycle events.
  • Claude Code Hooks Parity & Migration: Achieved feature parity with Claude Code hooks and introduced a gemini hooks migrate command for automatic conversion of existing Claude Code configurations to the Gemini format.
  • New CLI Commands: Added gemini hooks list to display active hooks and gemini hooks migrate for configuration transfer, enhancing CLI manageability.
  • Extensive Integration: Hooks are integrated across critical CLI components, including session lifecycle (SessionStart, SessionEnd), agent interactions (BeforeAgent, AfterAgent), tool execution (BeforeTool, AfterTool), and model requests (BeforeModel).
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system, which is a fantastic addition for extensibility, and includes a migration path from Claude Code. The implementation covers a wide range of lifecycle events. However, the review has identified several critical and high-severity issues that must be addressed before merging. These include a potential ReDoS vulnerability from user-configured regex matchers, a critical bug where BeforeModel hook modifications are ignored, and multiple instances of incomplete or hardcoded data being passed to hooks, which will break their functionality for any non-trivial use case. Please review the detailed comments for each issue.

@rickycambrian
Copy link
Author

Each of the comments by @gemini-code-assist have been addressed, but I'm not sure how to get its feedback again. Everything seems to be working well for me locally:
image

@gemini-code-assist
Copy link
Contributor

Hello @rickycambrian! I'm glad to hear that the previous comments were helpful and that things are working well for you locally. To get new feedback and trigger another review of your pull request, please use the command /gemini review in a new comment. This will prompt me to perform a fresh code review based on the current state of your pull request.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system, providing feature parity with Claude Code hooks and allowing for lifecycle event interception. The changes are extensive, touching core logic, CLI commands, and configuration management. The implementation is well-structured, with clear separation of concerns for hook registration, execution, and migration. My review focuses on a few high-severity issues related to maintainability and correctness, specifically around the settings persistence mechanism which appears brittle, and unsafe type casting of data coming from external hooks, which could lead to runtime errors.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system, a significant and well-structured feature addition. The implementation spans from core logic to new CLI commands for managing hooks, including a migration path from Claude Code. My review focuses on a few high-severity issues that could impact the reliability and user experience of this new system. I've identified a potential for data loss during configuration migration and inconsistencies in how hook data is prepared, which could lead to hooks failing in certain scenarios. Addressing these points will greatly enhance the robustness of this new functionality.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system to the Gemini CLI, achieving feature parity with Claude Code hooks and providing a migration path. The implementation is extensive, touching upon core CLI lifecycle events, command handling, and configuration management. The new gemini hooks command suite is a great addition for developers wanting to extend the CLI's functionality. My review focuses on ensuring the new commands are robust, persistent, and predictable for the user. I've identified a few high-severity issues related to state persistence, command idempotency, and process management that should be addressed to improve the feature's reliability.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system, providing feature parity with Claude Code hooks and allowing developers to intercept key lifecycle events. The implementation is well-structured, with clear separation of concerns for hook registration, execution, and configuration. The addition of CLI commands for managing hooks, including a migration tool, is a great enhancement for user experience.

My review focuses on improving the robustness of the newly added commands. I've identified several places where file I/O and other operations that can fail are not wrapped in try...catch blocks. This could lead to unhandled exceptions and cause the CLI to crash. Adding proper error handling will make the new features more resilient and provide a better experience for users, especially in cases of misconfiguration or file system issues.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system, a significant and well-structured feature addition. The implementation includes support for various lifecycle events, CLI commands for management, and a migration path from Claude Code. The code is generally robust, with good error handling for hook execution. My main feedback is a logic issue in the hook migration script that could lead to data loss.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system, providing feature parity with Claude Code hooks and enabling developers to intercept and modify key lifecycle events. The implementation includes the core architecture for hooks, CLI integration, and new commands for managing hooks, including a migration tool from Claude Code configurations.

My review identified a critical issue in the migration logic that could lead to duplicated hooks and incorrect behavior if the migration command is run multiple times. I have provided a detailed comment and a suggested code change to address this. The rest of the implementation appears solid and well-structured.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system, providing feature parity with Claude Code hooks and enabling developers to intercept key lifecycle events. The implementation is well-structured, with a clear separation of concerns between the hook registry, runner, and event definitions. The addition of CLI commands for managing hooks, including a migration tool for existing Claude Code configurations, is a thoughtful touch that will improve user adoption.

My review focuses on a few key architectural points that could be improved for robustness and to better meet developer expectations: ensuring the persistence of enable/disable actions for all hook types, providing the complete context to the BeforeModel hook, and correcting a shallow copy issue in the migration logic. Addressing these will make the new hook system even more powerful and intuitive.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system to the Gemini CLI, providing feature parity with Claude Code hooks and allowing developers to intercept and customize various lifecycle events. The implementation is extensive, adding new commands for hook management, a migration path from Claude Code, and integrating hook execution points throughout the application's core logic. The code is generally well-structured and robust. However, I've identified two high-severity issues: one related to potential data loss in the migration script, and another concerning a ReDoS vulnerability in the tool hook matching logic. Addressing these will significantly improve the safety and reliability of this new feature.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive and well-designed hook system, achieving feature parity with Claude Code hooks and providing a smooth migration path. The architecture is solid, with clear separation of concerns between the HookRegistry and HookRunner. The integration across interactive, non-interactive, and tool-scheduling parts of the CLI is thorough. I've identified one high-severity issue regarding input validation from hooks that would improve the system's robustness. Overall, this is an excellent addition to the project.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive and well-structured hook system, which is a fantastic addition for extensibility. The implementation, including the migration path from Claude Code, is robust. My review identifies two key areas for improvement to enhance the security and resilience of this new system. The most critical issue is a security vulnerability in the regular expression timeout logic that could lead to a Denial of Service attack. Additionally, I've suggested adding validation for the conversation history structure after modification by a hook to make the core application more robust against misbehaving hooks.

@rickycambrian
Copy link
Author

/gemini review

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a comprehensive hook system, providing feature parity with Claude Code hooks and allowing developers to intercept and modify key lifecycle events. The implementation is robust, including a migration command for existing configurations and security considerations like ReDoS protection for hook matchers. My review focuses on improving the safety of the new hooks install command and restoring a compile-time type safety check to prevent future bugs.

…ingful code change, need to confirm changes. Also worked on test coverage
Replace pattern detection approach with worker thread-based regex
testing that provides true timeout protection. Pattern detection
was insufficient as a blocklist approach - can be bypassed by
clever attackers.

Key changes:
- Execute regex tests in isolated worker threads with hard timeout
- Inline worker code to avoid separate file dependencies
- Terminate worker forcefully if regex takes >100ms
- Prevents event loop blocking from catastrophic backtracking
- Update BeforeTool/AfterTool hooks to use Promise.all for parallel evaluation

This addresses critical security feedback about ReDoS vulnerability
where setTimeout() doesn't work with synchronous regex execution.
Worker threads can be forcefully terminated, providing robust
protection against malicious regex patterns from untrusted sources.
@Edilmo
Copy link
Contributor

Edilmo commented Nov 29, 2025

Tagging @Edilmo and @abhipatel12 who should review this from the Google side. 👍

I left a comment in the Feature ticket.
Basically all the functionality of hooks has the core fully implemented and most of the hooks ready (only 3 pending for review this week). The next step is the UI (CLI commands) and documentations, which is also in a fork.

Sorry this effort has taken some time (the code has couple months ready) but given the impactful nature of the change, this require very careful review, so the work had to be broken in small pieces (+20 PRs), get carefully reviewed, by different members of the team, and then merge incrementally.

I have reviewed this PR and we have all covered either in the code merged or in the code coming in the next couple weeks (reviews): commands, documentation, and example.

Please comment in the feature or any of the linked tickets and PRs.

cc: @abhipatel12 @scidomino

@czhifa
Copy link

czhifa commented Dec 2, 2025

@rickycambrian Just check out the latest version,
https://github.com/rickycambrian/gemini-cli/tree/ricky-hooks-dev

And execute npm install && npm run build && node packages/cli/dist/index.js

Then input one query after started gemini-cli locally, but not trigger the hook SessionStart.

Can you help to check if missing any configuration. Thanks in advance.

Plus, the test environment is CentOS 8.

@gemini-code-assist
Copy link
Contributor

Hello @czhifa, thank you for testing and reporting this issue! I understand that the SessionStart hook isn't firing for you after checking out the latest branch and building locally. Let's troubleshoot this together.

Based on the documentation provided by @rickycambrian in comment #23, here are a few things to check:

  1. Enable Hooks in settings.json: The most common reason for hooks not firing is that they aren't explicitly enabled. Please ensure your ~/.gemini/settings.json (or project-specific .gemini/settings.json) has "enableHooks": true under the "tools" section, like this:

    {
      "tools": {
        "enableHooks": true
      }
    }
  2. Hook Configuration: Double-check that your settings.json correctly defines the SessionStart hook. It should look something like this:

    {
      "hooks": {
        "SessionStart": [
          {
            "hooks": [
              {
                "type": "command",
                "command": "/tmp/test_hook.sh SessionStart" // Or your actual script path
              }
            ]
          }
        ]
      },
      "tools": {
        "enableHooks": true
      }
    }
  3. Script Executability: Ensure your hook script (e.g., /tmp/test_hook.sh) has execute permissions. You can set this with chmod +x /path/to/your/script.sh.

  4. Manual Script Test: Try running your hook script manually with sample JSON input to see if it produces the expected output and logs. This helps isolate if the issue is with the script itself or the CLI's hook invocation.

    echo '{"hook_event_name": "SessionStart", "source": "Startup", "session_id": "123", "cwd": "/tmp", "timestamp": "2025-01-01T00:00:00Z"}' | /path/to/your/script.sh
  5. Debug Logs: If the above steps don't reveal the problem, try enabling debug mode for the CLI to get more verbose output:

    export DEBUG=gemini:*
    node packages/cli/dist/index.js

    Then check the console output for any messages related to hook execution.

Let me know if any of these checks help you identify the missing configuration or issue!

@czhifa
Copy link

czhifa commented Dec 2, 2025

4. hook script manually with sample JSON input to se

Actually, I have read all the tips as above after sent the question. And also open the debugging flag, but not get any hint.

I have no idea about next step.

@scidomino
Copy link
Collaborator

Sorry, we just merged a hooks system that was being worked on by @Edilmo .

Closing this out as it surely conflicts with what we already have at head.

@scidomino scidomino closed this Dec 3, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants