# Plugin System

pi-gateway provides a powerful plugin system with 14 hooks and 8 registration methods.

## Plugin Structure

```typescript
// my-plugin/index.ts
import type { GatewayPluginApi } from 'pi-gateway';

export default function myPlugin(api: GatewayPluginApi) {
  // Register hooks
  api.registerHook(['message_received'], async (ctx) => {
    console.log('Message received:', ctx.message);
  });
}
```

## Registration Methods

| Method | Description |
|--------|-------------|
| `registerChannel()` | Register a bot channel |
| `registerTool()` | Register an agent tool |
| `registerHook()` | Register lifecycle hooks |
| `registerHttpRoute()` | Register HTTP endpoint |
| `registerGatewayMethod()` | Register WebSocket method |
| `registerCommand()` | Register slash command |
| `registerCliCommand()` | Register CLI command |
| `registerService()` | Register background service |

## Available Hooks

| Hook | When |
|------|------|
| `before_agent_start` | Before agent starts |
| `agent_end` | After agent finishes |
| `message_received` | Message from channel |
| `message_sending` | Before sending (mutable) |
| `message_sent` | After sending |
| `before_tool_call` | Before tool execution |
| `after_tool_call` | After tool execution |
| `tool_result_persist` | Transform before persist |
| `session_start` | Session created |
| `session_end` | Session ended |
| `before_compaction` | Before context compact |
| `after_compaction` | After context compact |
| `gateway_start` | Gateway started |
| `gateway_stop` | Gateway stopped |

## Example: Logging Plugin

```typescript
export default function loggingPlugin(api: GatewayPluginApi) {
  api.registerHook(['message_received', 'message_sent'], async (ctx) => {
    console.log(`[${ctx.hook}]`, ctx.sessionKey);
  });

  api.registerHook(['agent_end'], async (ctx) => {
    console.log(`[agent_end] Tokens: ${ctx.usage?.totalTokens}`);
  });
}
```

## Loading Plugins

Add to `pi-gateway.jsonc`:

```jsonc
{
  "plugins": [
    "./plugins/my-plugin/index.ts"
  ]
}
```
