---
title: Hooks
description: Understand hook suspension, resolution, cancellation, and resume.
type: conceptual
summary: Learn how hooks suspend agent work, emit state, accept resolutions, and support replay.
---

# Hooks



Hooks are runtime suspension points. They emit internal messages so clients can
render pending, resolved, or cancelled state.

## Hook lifecycle

```python
approval = await ai.hook(
    "approve_contact_mothership",
    payload=ai.tools.ToolApproval,
    metadata={"tool": "contact_mothership"},
)
```

The hook checks for a pre-registered resolution first. If none exists, it emits
a pending `HookEvent` and waits on a live future.

## Live hook registry

Live hooks are stored by label while an agent run is active. `resolve_hook`
settles the waiting future:

```python
ai.resolve_hook(
    "approve_contact_mothership",
    {"granted": True, "reason": "approved"},
)
```

The run removes live hook entries when the hook resolves or the run finishes.

## Pending resolutions

When no live hook exists, `resolve_hook` stores the resolution for a later
replay:

```python
ai.resolve_hook(
    "approve_contact_mothership",
    ai.tools.ToolApproval(granted=True, reason="approved"),
)
```

The next matching `ai.hook` consumes that value and returns immediately.

## Hook events

Hooks emit `HookEvent` objects. The event message has role `internal` and
contains a `HookPart`:

```python
if isinstance(event, ai.events.HookEvent):
    print(event.hook.hook_id, event.hook.status)
```

## Abort and resume

Serverless handlers can abort a run after a pending hook event:

```python
if event.hook.status == "pending":
    ai.abort_pending_hook(event.hook)
```

Persist the messages, collect the user's response, call `resolve_hook`, and run
the agent again with the restored messages.

## Cancellation

Cancel a live hook when the waiting workflow should stop:

```python
await ai.cancel_hook("approve_contact_mothership", reason="client disconnected")
```

Cancellation emits a hook event with `status="cancelled"`.

## Cleanup

The runtime tracks hook labels for each run. When the run exits, it removes live
hooks and pending resolutions for those labels, then closes scoped Model Context
Protocol (MCP) connections.


---

For a semantic overview of all documentation, see [/sitemap.md](/sitemap.md)

For an index of all available documentation, see [/llms.txt](/llms.txt)