> ## Documentation Index
> Fetch the complete documentation index at: https://lab.pollack.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Agent Hooks

> Portable hook API for steering agent behavior at the tool-call boundary — write once, run on any runtime

**[What's New →](/docs/agent-hooks/whats-new)**

**What's new in 0.6.4:** Built on Spring AI 2.0.0 GA and Spring Boot 4.0.7, with an OWASP CVE gate added to the build. The prior 0.6.3 release migrated onto the new Claude SDK and aligned on the Jackson 2.21.2 BOM. The hook-API architecture — core plus the Spring AI, Claude, and Gemini adapters — is unchanged.

Every agent framework implements hooks differently.
Claude Code has shell-based hooks. Strands has steering callbacks. Spring AI has advisors.
Your safety policy, logging, and steering logic gets rewritten for each one.

Agent Hooks is a portable Java API that lets you write hook logic once and run it on any runtime that has an adapter.
The core module has zero dependencies — it defines the event model, decision types, and registry.
Adapters (Spring AI, Claude Agent SDK, and Gemini CLI) wire the core into their runtime's tool-call lifecycle.
Your hooks move with you when your agent infrastructure changes.

## Why Hooks

LLMs are probabilistic — prompt-based instructions drift under token pressure.
Agents skip steps, forget constraints, and ignore guardrails.
Hooks solve this by moving critical logic out of the prompt and into deterministic code that intercepts every tool call, the same way servlet filters intercept HTTP requests:

* **Safety** — Block dangerous operations before they execute. A `Block` decision short-circuits immediately and cannot be overridden by later hooks.
* **Observability** — Log every tool call, capture timing data, and feed traces into [Agent Journal](/projects/agent-journal) for behavioral analysis.
* **Steering** — Modify tool inputs in flight. Subsequent hooks see the modified input, so transformations chain cleanly.

## How It Works

Hooks intercept at two points in the tool-call lifecycle:

```
BeforeToolCall ──► Tool Executes ──► AfterToolCall
     │                                    │
  Block?  ◄── short-circuit            Retry?
  Modify? ◄── chains                   Log / observe
  Proceed ◄── default                  Cleanup (reverse order)
```

Register hooks with type-safe generics and optional tool-name filtering:

```java theme={null}
// Block all shell commands
registry.onTool("shell.*", BeforeToolCall.class, event ->
    HookDecision.block("Shell access disabled in this environment"));

// Log every tool call
registry.on(AfterToolCall.class, event -> {
    log.info("{} completed in {}ms", event.toolName(), event.duration().toMillis());
    return HookDecision.proceed();
});

// Redirect file writes to a sandbox directory
registry.onTool("write.*", BeforeToolCall.class, event -> {
    String sandboxed = event.toolInput()
        .replace("/home/user", "/sandbox");
    return HookDecision.modify(sandboxed);
});
```

## Decision Model

`HookDecision` is a sealed type with four variants:

| Decision  | When                 | Behavior                                             |
| --------- | -------------------- | ---------------------------------------------------- |
| `Proceed` | Default              | Tool executes normally                               |
| `Block`   | Safety / policy      | Short-circuits immediately — later hooks never run   |
| `Modify`  | Input transformation | Passes modified input to the next hook in the chain  |
| `Retry`   | AfterToolCall only   | Re-executes the tool (e.g., after transient failure) |

Multiple hooks execute in priority order (default: 100, lower = earlier).
AfterToolCall hooks fire in reverse priority order for proper cleanup semantics.

## Modules

| Module               | What it does                                                                                   | Dependencies               |
| -------------------- | ---------------------------------------------------------------------------------------------- | -------------------------- |
| `agent-hooks-core`   | Pure Java 17 API — events, decisions, registry                                                 | Zero (portable)            |
| `agent-hooks-spring` | Spring AI adapter — wraps `ToolCallback` with hook dispatch, auto-configures via Boot          | Spring AI, Spring Boot     |
| `agent-hooks-claude` | Claude Agent SDK adapter — bridges hook providers to Claude CLI hooks via `AgentHookBridge`    | Claude Code SDK (provided) |
| `agent-hooks-gemini` | Gemini CLI adapter — stateless stdin/stdout dispatcher for Gemini's subprocess-per-event model | Jackson (compile)          |

## Event Hierarchy

The event system is open (unsealed) — you can define custom events for your runtime:

| Event                       | Interface   | Decisions                         |
| --------------------------- | ----------- | --------------------------------- |
| `BeforeToolCall`            | `ToolEvent` | Proceed, Block, Modify            |
| `AfterToolCall`             | `ToolEvent` | Proceed, Retry                    |
| `SessionStart`              | `HookEvent` | Observation only                  |
| `SessionEnd`                | `HookEvent` | Observation only                  |
| `UserPromptSubmit`          | `HookEvent` | Observation only (Claude adapter) |
| `AgentStop`                 | `HookEvent` | Observation only (Claude adapter) |
| `SubagentStop`              | `HookEvent` | Observation only (Claude adapter) |
| `PreCompact`                | `HookEvent` | Observation only (Claude adapter) |
| `GeminiBeforeAgent`         | `HookEvent` | Observation only (Gemini adapter) |
| `GeminiAfterAgent`          | `HookEvent` | Observation only (Gemini adapter) |
| `GeminiBeforeModel`         | `HookEvent` | Observation only (Gemini adapter) |
| `GeminiAfterModel`          | `HookEvent` | Observation only (Gemini adapter) |
| `GeminiBeforeToolSelection` | `HookEvent` | Observation only (Gemini adapter) |
| `GeminiNotification`        | `HookEvent` | Observation only (Gemini adapter) |
| `GeminiPreCompress`         | `HookEvent` | Observation only (Gemini adapter) |

## Quick Start

```xml theme={null}
<!-- Core API (zero dependencies) -->
<dependency>
    <groupId>io.github.markpollack</groupId>
    <artifactId>agent-hooks-core</artifactId>
    <version>0.6.4</version>
</dependency>

<!-- Spring AI adapter (auto-configured) -->
<dependency>
    <groupId>io.github.markpollack</groupId>
    <artifactId>agent-hooks-spring</artifactId>
    <version>0.6.4</version>
</dependency>
```

```xml theme={null}
<!-- Claude Agent SDK adapter -->
<dependency>
    <groupId>io.github.markpollack</groupId>
    <artifactId>agent-hooks-claude</artifactId>
    <version>0.6.4</version>
</dependency>
```

```xml theme={null}
<!-- Gemini CLI adapter (stateless subprocess) -->
<dependency>
    <groupId>io.github.markpollack</groupId>
    <artifactId>agent-hooks-gemini</artifactId>
    <version>0.6.4</version>
</dependency>
```

## Write Once, Run Anywhere

The same `AgentHookProvider` works on all three runtimes — this is the core value proposition.

```java theme={null}
// This provider works on Spring AI, Claude CLI, and Gemini CLI
public class SecurityHooks implements AgentHookProvider {
    @Override
    public void registerHooks(AgentHookRegistry registry) {
        registry.onTool("Bash", BeforeToolCall.class, event ->
            HookDecision.block("Shell access not permitted"));
    }
}
```

**Spring AI** — register as a `@Component` bean, auto-configuration handles the rest:

```java theme={null}
@Component
public class MySecurityHooks extends SecurityHooks {}
```

**Claude Agent SDK** — bridge into the Claude `HookRegistry`:

```java theme={null}
AgentHookRegistry registry = new AgentHookRegistry();
registry.register(new SecurityHooks());

AgentHookBridge bridge = new AgentHookBridge(registry);
bridge.registerInto(claudeHookRegistry);
```

The bridge registers callbacks for all six Claude hook events (PreToolUse, PostToolUse, UserPromptSubmit, Stop, SubagentStop, PreCompact). It converts Claude SDK types to core events, dispatches through your hooks, and maps decisions back to Claude's `HookOutput`.

Tool call duration is tracked via wall-clock timing across the pre/post hook boundary.
Each Claude session gets its own `HookContext` for isolated state and history.

**Gemini CLI** — stateless subprocess dispatcher reads JSON from stdin:

```java theme={null}
public class MyGeminiHooks {
    public static void main(String[] args) throws Exception {
        GeminiHookDispatcher.create(new SecurityHooks())
            .run();  // reads stdin, dispatches, writes stdout, exits
    }
}
```

Gemini CLI spawns the hook process per event. The dispatcher maps all 11 Gemini events to core and Gemini-specific `HookEvent` records.
`HookContext` is fresh per invocation — stateless hooks (security gates, audit logging) work out of the box.
Note: Gemini BeforeTool can only allow or block — `Modify` is downgraded to allow with a warning.

## Documentation

<CardGroup cols={2}>
  <Card title="Source Code" icon="github" href="https://github.com/markpollack/agent-hooks">
    Core API, Spring AI adapter, Claude adapter, and Gemini adapter
  </Card>

  <Card title="Design Notes" icon="compass-drafting" href="https://github.com/markpollack/agent-hooks/blob/main/plans/DESIGN.md">
    Architecture decisions, event hierarchy, dispatch semantics
  </Card>
</CardGroup>

## Used By

* **[Agent Workflow](/projects/agent-workflow)** — hooks apply automatically to any workflow step that invokes tools
* **[Agent Journal](/projects/agent-journal)** — hook provider that logs tool-call events to a journal Run
