# hooklib

Shared library for AI agent hook scripts — cache management, stderr formatting, MCP utilities.

## Overview

`hooklib` provides the common utilities used by hook scripts across AI agent CLIs
(Devin, OpenCode, Copilot, Windsurf). It is the extracted, versioned package form
of the original `agents/scripts/hooklib.py` from the
[ai-agents-config](https://pastoral-oyster.pikapod.net/dotfiles/ai-agents-config)
repository.

## Installation

```bash
# From the private DevPI registry
pip install --index-url https://pypi.registry.hochguertel.work/root/dev/+simple/ hooklib

# Or with uv
uv pip install --index-url https://pypi.registry.hochguertel.work/root/dev/+simple/ hooklib
```

## Usage

```python
from hooklib import (
    cache_dir,
    stderr,
    read_hook_context,
    HookContext,
    parse_mcp_tool_name,
    append_jsonl,
    utc_now_iso,
)

# Read hook event from stdin
ctx = read_hook_context(fallback_event_name="PreToolUse")

# Log the event
ctx.log("my-hook", custom_field="value")

# Write to stderr (captured by hook system)
stderr("Diagnostic message")

# Get a cache directory for this hook
cache = cache_dir("my-hook")
```

## Key functions

| Function | Description |
|----------|-------------|
| `read_hook_context()` | Read hook event JSON from stdin, return `HookContext` |
| `HookContext` | Immutable snapshot of hook event payload with convenience accessors |
| `cache_dir(name)` | Get/create a cache subdirectory under the agent config dir |
| `logs_dir()` | Get/create the logs directory under the agent config dir |
| `stderr(message)` | Write a diagnostic message to stderr |
| `append_jsonl(path, record)` | Append a JSON record to a JSONL file |
| `parse_mcp_tool_name(name)` | Parse `mcp__server__tool` into `(server, tool)` |
| `utc_now_iso()` | Current UTC time as ISO-8601 string |

## Development

```bash
# Install dev dependencies
uv sync

# Run tests
uv run pytest

# Build the package
uv build --no-sources
```

## License

MIT
