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

# Lifecycle Hooks

> Observe and control the agent loop with typed lifecycle hooks.

Lifecycle hooks let you observe and control specific points in the `callModel` agent loop. Use them to:

* Inspect, modify, or block tool calls before execution
* Record successful and failed tool executions
* Rewrite or reject user prompts
* Decide whether approval-gated tools run
* Override stop conditions
* Track sessions, model calls, token usage, latency, and cost
* Run custom, type-safe application events

Lifecycle hooks are different from transport hooks such as `SDKHooks` and `BeforeRequestHook`. Transport hooks intercept HTTP requests. Lifecycle hooks fire on events within the agent loop.

## Quick start

Pass built-in hooks directly to `callModel` with the `hooks` option:

```typescript expandable lines theme={null}
import { OpenRouter, tool } from '@openrouter/agent';
import { z } from 'zod/v4';

const openrouter = new OpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY,
});

const shellTool = tool({
  name: 'run_shell',
  description: 'Run a shell command',
  inputSchema: z.object({ command: z.string() }),
  outputSchema: z.object({ output: z.string() }),
  execute: async ({ command }) => ({
    output: await runInSandbox(command),
  }),
});

const result = openrouter.callModel({
  model: 'openai/gpt-5.4',
  input: 'Delete temporary build files',
  tools: [shellTool] as const,
  hooks: {
    PreToolUse: [
      {
        matcher: 'run_shell',
        handler: ({ toolInput }) => {
          if (String(toolInput.command).includes('rm -rf /')) {
            return {
              block: 'Refusing to run a destructive command',
            };
          }
        },
      },
    ],
    PostToolUse: [
      {
        handler: ({ toolName, durationMs }) => {
          recordToolLatency(toolName, durationMs);
        },
      },
    ],
  },
});

console.log(await result.getText());
```

```python title="Python" lines theme={null}
import asyncio
import os
from pydantic import BaseModel
from openrouter_agent import OpenRouter, HookEntry, call_model, tool


class ShellInput(BaseModel):
    command: str


class ShellOutput(BaseModel):
    output: str


def run_in_sandbox(command: str) -> str:
    return f"(sandbox) ran: {command}"


def record_tool_latency(tool_name, duration_ms):
    print(f"[latency] {tool_name}: {duration_ms} ms")


def block_destructive(payload, ctx):
    if "rm -rf /" in str(payload.get("tool_input", {}).get("command", "")):
        return {"block": "Refusing to run a destructive command"}
    return None


async def main() -> None:
    client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])

    shell_tool = tool(
        name="run_shell",
        description="Run a shell command",
        input_schema=ShellInput,
        output_schema=ShellOutput,
        execute=lambda params, ctx: ShellOutput(output=run_in_sandbox(params.command)),
    )

    result = call_model(
        client,
        {
            "model": "openai/gpt-5.4",
            "input": "Delete temporary build files",
            "tools": [shell_tool],
            "hooks": {
                "PreToolUse": [HookEntry(handler=block_destructive, matcher="run_shell")],
                "PostToolUse": [
                    HookEntry(
                        handler=lambda payload, ctx: record_tool_latency(
                            payload.get("tool_name"), payload.get("duration_ms")
                        )
                    )
                ],
            },
        },
    )

    print(await result.get_text())


asyncio.run(main())

```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"strings"
	"time"
)

// Hooks mirrors the built-in PreToolUse / PostToolUse lifecycle hooks.
type Hooks struct {
	// PreToolUse runs before a tool executes. Return a non-empty reason to block it.
	PreToolUse func(name string, input map[string]any) (blockReason string)
	// PostToolUse runs after a tool executes.
	PostToolUse func(name string, d time.Duration)
}

func runInSandbox(command string) string { return "(sandbox, not executed) " + command }

func recordToolLatency(name string, d time.Duration) {
	fmt.Printf("[PostToolUse] %s took %s\n", name, d)
}

func isDestructive(command string) bool {
	fields := strings.Fields(command)
	for i, f := range fields {
		if f == "rm" && i+2 < len(fields) && strings.Contains(fields[i+1], "r") && (fields[i+2] == "/" || fields[i+2] == "/*") {
			return true
		}
	}
	return false
}

type toolCall struct {
	ID       string `json:"id"`
	Function struct {
		Name      string `json:"name"`
		Arguments string `json:"arguments"`
	} `json:"function"`
}

// callModel runs a tool loop against OpenRouter, invoking hooks around each tool call.
func callModel(model, prompt string, tools []any, hooks Hooks) (string, error) {
	messages := []any{map[string]any{"role": "user", "content": prompt}}
	for turn := 0; turn < 5; turn++ {
		body, _ := json.Marshal(map[string]any{"model": model, "messages": messages, "tools": tools})
		req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(body))
		req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
		req.Header.Set("Content-Type", "application/json")
		res, err := http.DefaultClient.Do(req)
		if err != nil {
			return "", err
		}
		data, _ := io.ReadAll(res.Body)
		res.Body.Close()
		if res.StatusCode != http.StatusOK {
			return "", fmt.Errorf("HTTP %d: %s", res.StatusCode, data)
		}
		var out struct {
			Choices []struct {
				Message json.RawMessage `json:"message"`
			} `json:"choices"`
		}
		if err := json.Unmarshal(data, &out); err != nil || len(out.Choices) == 0 {
			return "", fmt.Errorf("unexpected response: %s", data)
		}
		var msg struct {
			Content   string     `json:"content"`
			ToolCalls []toolCall `json:"tool_calls"`
		}
		if err := json.Unmarshal(out.Choices[0].Message, &msg); err != nil {
			return "", err
		}
		if len(msg.ToolCalls) == 0 {
			return msg.Content, nil
		}
		messages = append(messages, out.Choices[0].Message)

		for _, tc := range msg.ToolCalls {
			var input map[string]any
			json.Unmarshal([]byte(tc.Function.Arguments), &input)
			fmt.Printf("-> %s(%s)\n", tc.Function.Name, tc.Function.Arguments)
			var result any
			if reason := hooks.PreToolUse(tc.Function.Name, input); reason != "" {
				fmt.Printf("[PreToolUse] blocked: %s\n", reason)
				result = map[string]string{"error": reason}
			} else {
				start := time.Now()
				result = map[string]string{"output": runInSandbox(fmt.Sprint(input["command"]))}
				hooks.PostToolUse(tc.Function.Name, time.Since(start))
			}
			content, _ := json.Marshal(result)
			messages = append(messages, map[string]any{"role": "tool", "tool_call_id": tc.ID, "content": string(content)})
		}
	}
	return "", fmt.Errorf("stopped after 5 turns without a final answer")
}

func main() {
	tools := []any{map[string]any{
		"type": "function",
		"function": map[string]any{
			"name":        "run_shell",
			"description": "Run a shell command",
			"parameters": map[string]any{
				"type":       "object",
				"properties": map[string]any{"command": map[string]any{"type": "string"}},
				"required":   []string{"command"},
			},
		},
	}}

	hooks := Hooks{
		PreToolUse: func(name string, input map[string]any) string {
			if name == "run_shell" && isDestructive(fmt.Sprint(input["command"])) {
				return "Refusing to run a destructive command"
			}
			return ""
		},
		PostToolUse: recordToolLatency,
	}

	text, err := callModel("openai/gpt-5.4", "Delete temporary build files", tools, hooks)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(text)
}

```

```text title="Output" theme={null}
[latency] run_shell: 0.058889000001727254 ms
Deleted temporary build files.
```

Inline configuration supports all built-in hooks. Use a `HooksManager` when you need custom hooks, dynamic registration, programmatic emission, or explicit lifecycle control.

## HooksManager

Create a manager and pass it to one or more `callModel` calls:

```typescript expandable lines theme={null}
import { HooksManager, OpenRouter, callModel, tool } from '@openrouter/agent';
import { z } from 'zod';

function audit(sessionId: string, toolInput: unknown) {
  console.log(`[audit ${sessionId}]`, JSON.stringify(toolInput));
}

const databaseTool = tool({
  name: 'db_find_old_records',
  description: 'Find (and optionally delete) database records older than a number of days',
  inputSchema: z.object({
    olderThanDays: z.number(),
    dryRun: z.boolean().optional(),
  }),
  execute: async ({ olderThanDays, dryRun }) => ({
    olderThanDays,
    dryRun: dryRun ?? false,
    matched: 42,
    deleted: dryRun ? 0 : 42,
  }),
});

const hooks = new HooksManager();

const unsubscribe = hooks.on('PreToolUse', {
  matcher: /^db_/,
  filter: ({ toolInput }) => Object.keys(toolInput).length > 0,
  handler: ({ toolInput }, context) => {
    audit(context.sessionId, toolInput);

    return {
      mutatedInput: {
        ...toolInput,
        dryRun: true,
      },
    };
  },
});

const openrouter = new OpenRouter({
  apiKey: process.env.OPENROUTER_API_KEY,
});

const result = callModel(openrouter, {
  model: 'openai/gpt-5.4',
  input: 'Check which old records can be removed',
  tools: [databaseTool] as const,
  hooks,
});

const text = await result.getText();
console.log(text);
unsubscribe();

```

```python title="Python" lines theme={null}
import asyncio
import json
import os
import re

from pydantic import BaseModel
from openrouter_agent import HookEntry, HookName, HooksManager, OpenRouter, call_model, tool


def audit(session_id, tool_input):
    print(f"[audit {session_id}]", json.dumps(tool_input))


class DbInput(BaseModel):
    older_than_days: int
    dry_run: bool | None = None


database_tool = tool(
    name="db_find_old_records",
    description="Find (and optionally delete) database records older than a number of days",
    input_schema=DbInput,
    execute=lambda params, ctx: {
        "older_than_days": params.older_than_days,
        "dry_run": bool(params.dry_run),
        "matched": 42,
        "deleted": 0 if params.dry_run else 42,
    },
)

hooks = HooksManager()


def pre_tool_use(payload, context):
    tool_input = payload["tool_input"]
    audit(context.session_id, tool_input)
    return {"mutated_input": {**tool_input, "dry_run": True}}


unsubscribe = hooks.on(
    HookName.PreToolUse.value,
    HookEntry(
        matcher=re.compile(r"^db_"),
        filter=lambda payload: len(payload["tool_input"]) > 0,
        handler=pre_tool_use,
    ),
)


async def main():
    client = OpenRouter(api_key=os.environ["OPENROUTER_API_KEY"])
    result = call_model(
        client,
        {
            "model": "openai/gpt-5.4",
            "input": "Check which old records can be removed",
            "tools": [database_tool],
            "hooks": hooks,
        },
    )
    print(await result.get_text())
    unsubscribe()


asyncio.run(main())

```

```go title="Go" lines theme={null}
package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
	"regexp"
)

type HookContext struct{ SessionID string }

// PreToolUseResult can replace the tool input, block the call with a reason, or both.
type PreToolUseResult struct {
	MutatedInput map[string]any
	Block        string
}

// PreToolUseHook mirrors a HooksManager PreToolUse registration.
type PreToolUseHook struct {
	Matcher *regexp.Regexp
	Filter  func(toolInput map[string]any) bool
	Handler func(toolInput map[string]any, ctx HookContext) PreToolUseResult
}

type HooksManager struct{ pre []*PreToolUseHook }

// OnPreToolUse registers a hook and returns an unsubscribe function.
func (h *HooksManager) OnPreToolUse(hook PreToolUseHook) func() {
	i := len(h.pre)
	h.pre = append(h.pre, &hook)
	return func() { h.pre[i] = nil }
}

// runPreToolUse pipes the input through each matching handler. A non-empty block reason stops the chain.
func (h *HooksManager) runPreToolUse(name string, input map[string]any, ctx HookContext) (map[string]any, string) {
	for _, hook := range h.pre {
		if hook == nil || (hook.Matcher != nil && !hook.Matcher.MatchString(name)) || (hook.Filter != nil && !hook.Filter(input)) {
			continue
		}
		result := hook.Handler(input, ctx)
		if result.MutatedInput != nil {
			input = result.MutatedInput
		}
		if result.Block != "" {
			return input, result.Block
		}
	}
	return input, ""
}

func audit(sessionID string, toolInput any) {
	b, _ := json.Marshal(toolInput)
	fmt.Printf("[audit %s] %s\n", sessionID, b)
}

func dbFindOldRecords(input map[string]any) map[string]any {
	dryRun, _ := input["dryRun"].(bool)
	deleted := 42
	if dryRun {
		deleted = 0
	}
	return map[string]any{"olderThanDays": input["olderThanDays"], "dryRun": dryRun, "matched": 42, "deleted": deleted}
}

var databaseTool = map[string]any{
	"type": "function",
	"function": map[string]any{
		"name":        "db_find_old_records",
		"description": "Find (and optionally delete) database records older than a number of days",
		"parameters": map[string]any{
			"type": "object",
			"properties": map[string]any{
				"olderThanDays": map[string]any{"type": "number"},
				"dryRun":        map[string]any{"type": "boolean"},
			},
			"required": []string{"olderThanDays"},
		},
	},
}

// callModel runs a tool loop against OpenRouter, invoking hooks before each tool call.
func callModel(model, prompt, sessionID string, hooks *HooksManager) (string, error) {
	messages := []any{map[string]any{"role": "user", "content": prompt}}
	for turn := 0; turn < 5; turn++ {
		body, _ := json.Marshal(map[string]any{"model": model, "messages": messages, "tools": []any{databaseTool}})
		req, _ := http.NewRequest("POST", "https://openrouter.ai/api/v1/chat/completions", bytes.NewReader(body))
		req.Header.Set("Authorization", "Bearer "+os.Getenv("OPENROUTER_API_KEY"))
		req.Header.Set("Content-Type", "application/json")
		res, err := http.DefaultClient.Do(req)
		if err != nil {
			return "", err
		}
		data, _ := io.ReadAll(res.Body)
		res.Body.Close()
		if res.StatusCode != http.StatusOK {
			return "", fmt.Errorf("HTTP %d: %s", res.StatusCode, data)
		}
		var out struct {
			Choices []struct {
				Message json.RawMessage `json:"message"`
			} `json:"choices"`
		}
		if err := json.Unmarshal(data, &out); err != nil || len(out.Choices) == 0 {
			return "", fmt.Errorf("unexpected response: %s", data)
		}
		var msg struct {
			Content   string `json:"content"`
			ToolCalls []struct {
				ID       string `json:"id"`
				Function struct {
					Name      string `json:"name"`
					Arguments string `json:"arguments"`
				} `json:"function"`
			} `json:"tool_calls"`
		}
		if err := json.Unmarshal(out.Choices[0].Message, &msg); err != nil {
			return "", err
		}
		if len(msg.ToolCalls) == 0 {
			return msg.Content, nil
		}
		messages = append(messages, out.Choices[0].Message)
		for _, tc := range msg.ToolCalls {
			input := map[string]any{}
			if err := json.Unmarshal([]byte(tc.Function.Arguments), &input); err != nil {
				// Invalid arguments: report a parse error without running hooks or the tool.
				messages = append(messages, map[string]any{"role": "tool", "tool_call_id": tc.ID, "content": "Error: invalid tool arguments: " + err.Error()})
				continue
			}
			input, block := hooks.runPreToolUse(tc.Function.Name, input, HookContext{SessionID: sessionID})
			if block != "" {
				// A blocked call skips the tool; the reason goes back to the model.
				messages = append(messages, map[string]any{"role": "tool", "tool_call_id": tc.ID, "content": block})
				continue
			}
			content, _ := json.Marshal(dbFindOldRecords(input))
			messages = append(messages, map[string]any{"role": "tool", "tool_call_id": tc.ID, "content": string(content)})
		}
	}
	return "", fmt.Errorf("stopped after 5 turns without a final answer")
}

func main() {
	hooks := &HooksManager{}

	unsubscribe := hooks.OnPreToolUse(PreToolUseHook{
		Matcher: regexp.MustCompile(`^db_`),
		Filter:  func(toolInput map[string]any) bool { return len(toolInput) > 0 },
		Handler: func(toolInput map[string]any, ctx HookContext) PreToolUseResult {
			audit(ctx.SessionID, toolInput)
			mutated := map[string]any{}
			for k, v := range toolInput {
				mutated[k] = v
			}
			mutated["dryRun"] = true
			return PreToolUseResult{MutatedInput: mutated}
		},
	})

	text, err := callModel("openai/gpt-5.4", "Check which old records can be removed", "conv-123", hooks)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(text)
	unsubscribe()
}

```

```text title="Output" theme={null}
[audit conv-123] {"olderThanDays":30,"dryRun":true}
Found 42 records older than 30 days that can be removed.

No records were deleted because this was a dry run.
```

`HooksManager` is available from `@openrouter/agent` and from the focused `@openrouter/agent/hooks-manager` subpath.

Every handler receives a validated `payload` and a context object:

```typescript lines theme={null}
interface LifecycleHookContext {
  readonly signal: AbortSignal;
  readonly hookName: string;
  readonly sessionId: string;
}
```

The SDK supplies the current run's session ID for each lifecycle event. A single manager can therefore be shared by concurrent `callModel` runs without mixing their session IDs.

## Built-in hooks

| Hook | When it fires | Effect |
| - | - | - |
| `SessionStart` | Before the initial request | Observe |
| `UserPromptSubmit` | Before the initial prompt | Rewrite or reject |
| `PostModelCall` | After each model response | Observe |
| `PermissionRequest` | Before tool approval | Allow, deny, or ask |
| `PreToolUse` | Before client tool execution | Rewrite or block |
| `PostToolUse` | After tool success | Observe |
| `PostToolUseFailure` | After tool failure | Observe |
| `Stop` | When `stopWhen` stops the loop | Append or resume |
| `SessionEnd` | When the run exits | Observe |

### SessionStart

`SessionStart` fires once before the initial model request. Its optional `config` summarizes the run without exposing the full request:

The exported payload type allows an extensible config record:

```typescript lines theme={null}
type SessionStartPayload = {
  readonly config?: Record<string, unknown>;
};
```

The agent loop currently emits this config:

```typescript lines theme={null}
{
  hasTools: boolean;
  hasApproval: boolean;
  hasState: boolean;
}
```

Use it to initialize tracing, audit records, or session-scoped resources. Handlers are observational and do not return a result.

### UserPromptSubmit

`UserPromptSubmit` fires before the initial user prompt is sent:

```typescript lines theme={null}
type UserPromptSubmitPayload = {
  prompt: string;
};

type UserPromptSubmitResult = {
  mutatedPrompt?: string;
  reject?: boolean | string;
};
```

`mutatedPrompt` replaces the prompt. `reject: true` aborts with a default error, while a non-empty string becomes the rejection reason.

For structured input, the SDK uses the latest user-role text. If it cannot extract user text, it skips this hook.

```typescript lines theme={null}
hooks.on('UserPromptSubmit', {
  handler: ({ prompt }) => {
    if (containsSecret(prompt)) {
      return { reject: 'Remove secrets before submitting this prompt' };
    }

    return { mutatedPrompt: redactPersonalData(prompt) };
  },
});
```

```python title="Python" lines theme={null}
def on_user_prompt_submit(payload, ctx):
    prompt = payload["prompt"]
    if contains_secret(prompt):
        return {"reject": "Remove secrets before submitting this prompt"}

    return {"mutated_prompt": redact_personal_data(prompt)}


hooks.on("UserPromptSubmit", HookEntry(handler=on_user_prompt_submit))

```

```go title="Go" lines theme={null}
hooks.OnUserPromptSubmit(UserPromptSubmitHook{
	Handler: func(prompt string, ctx HookContext) UserPromptSubmitResult {
		if containsSecret(prompt) {
			return UserPromptSubmitResult{Reject: "Remove secrets before submitting this prompt"}
		}

		return UserPromptSubmitResult{MutatedPrompt: redactPersonalData(prompt)}
	},
})
```

### PostModelCall

`PostModelCall` fires once for every completed model response, including:

* The initial request
* Approval or HITL resume requests
* Follow-up requests after tool rounds
* The final request created by `allowFinalResponse`
* Empty-final retries

```typescript lines theme={null}
type PostModelCallPayload = {
  sessionId: string;
  responseId: string;
  model: string;
  durationMs: number;
  turnType: 'initial' | 'resume' | 'tool_round' | 'final' | 'retry';
  turnNumber: number;
  usage?: ModelCallUsage;
};

type ModelCallUsage = {
  inputTokens: number;
  outputTokens: number;
  totalTokens: number;
  cachedTokens: number;
  reasoningTokens: number;
  cost?: number;
};
```

`responseId` is the OpenRouter generation ID. `durationMs` measures from request dispatch until the full response is materialized, including stream consumption. The hook is observational and is suitable for one tracing span per model call.

```typescript lines theme={null}
hooks.on('PostModelCall', {
  handler: (payload, context) => {
    recordModelSpan({
      sessionId: context.sessionId,
      generationId: payload.responseId,
      model: payload.model,
      durationMs: payload.durationMs,
      cost: payload.usage?.cost,
    });
  },
});
```

```python title="Python" lines theme={null}
def on_post_model_call(payload, ctx):
    record_model_span({
        "session_id": ctx.session_id,
        "generation_id": payload.get("response_id"),
        "model": payload.get("model"),
        "duration_ms": payload.get("duration_ms"),
        "cost": (payload.get("usage") or {}).get("cost"),
    })


hooks.on("PostModelCall", HookEntry(handler=on_post_model_call))

```

```go title="Go" lines theme={null}
hooks.OnPostModelCall(PostModelCallHook{
	Handler: func(payload PostModelCallPayload, ctx HookContext) {
		recordModelSpan(ModelSpan{
			SessionID:    ctx.SessionID,
			GenerationID: payload.ResponseID,
			Model:        payload.Model,
			DurationMs:   payload.DurationMs,
			Cost:         payload.Usage.Cost,
		})
	},
})
```

A failed stream that never produces a complete response does not emit `PostModelCall`. A materialized `response.incomplete` response does emit it. `usage` is omitted when the server does not report usage, and `usage.cost` is only present when server-side usage accounting reports cost.

On a no-tools streaming path, the response becomes complete only after stream consumption. The hook therefore fires during session teardown, immediately before `SessionEnd`.

### PermissionRequest

`PermissionRequest` fires when a tool requires approval, before the SDK pauses for a user decision:

```typescript lines theme={null}
type PermissionRequestPayload = {
  toolName: string;
  toolInput: Record<string, unknown>;
  riskLevel: 'low' | 'medium' | 'high';
};

type PermissionRequestResult = {
  decision: 'allow' | 'deny' | 'ask_user';
  reason?: string;
};
```

* `allow` skips the approval gate and runs the tool through the normal loop.
* `deny` does not run the tool and sends a rejected result to the model.
* `ask_user` continues into the normal approval flow.

When multiple handlers return decisions, the last returned decision wins. The SDK derives `riskLevel` from the approval rule: callback-based rules are `high`, blanket `true` rules are `medium`, and other cases are `low`.

```typescript lines theme={null}
hooks.on('PermissionRequest', {
  matcher: 'read_file',
  handler: ({ toolInput }) => {
    if (isAllowedPath(toolInput.path)) {
      return { decision: 'allow' };
    }

    return {
      decision: 'deny',
      reason: 'The requested path is outside the workspace',
    };
  },
});
```

```python title="Python" lines theme={null}
def on_permission_request(payload, ctx):
    if is_allowed_path(payload["tool_input"]["path"]):
        return {"decision": "allow"}

    return {
        "decision": "deny",
        "reason": "The requested path is outside the workspace",
    }


hooks.on("PermissionRequest", HookEntry(handler=on_permission_request, matcher="read_file"))

```

### PreToolUse

`PreToolUse` fires before client tool execution, including normal tool rounds and resumed approval flows:

```typescript lines theme={null}
type PreToolUsePayload = {
  toolName: string;
  toolInput: Record<string, unknown>;
};

type PreToolUseResult = {
  mutatedInput?: Record<string, unknown>;
  block?: boolean | string;
};
```

`mutatedInput` replaces the arguments before schema validation and execution. `block: true` skips execution with a default reason. A non-empty string skips execution and is sent to the model as the reason.

If the model supplied invalid JSON arguments, the SDK produces a parse error without emitting the tool hooks because no valid tool input exists.

```typescript lines theme={null}
hooks.on('PreToolUse', {
  matcher: 'search',
  handler: ({ toolInput }) => ({
    mutatedInput: {
      ...toolInput,
      limit: Math.min(Number(toolInput.limit ?? 10), 50),
    },
  }),
});
```

```python title="Python" lines theme={null}
def on_pre_tool_use(payload, ctx):
    tool_input = payload["tool_input"]
    return {
        "mutated_input": {
            **tool_input,
            "limit": min(int(tool_input.get("limit", 10)), 50),
        },
    }


hooks.on("PreToolUse", HookEntry(handler=on_pre_tool_use, matcher="search"))

```

```go title="Go" lines theme={null}
hooks.OnPreToolUse(PreToolUseHook{
	Matcher: regexp.MustCompile(`^search$`),
	Handler: func(toolInput map[string]any, ctx HookContext) PreToolUseResult {
		limit := 10.0
		if v, ok := toolInput["limit"].(float64); ok {
			limit = v
		}
		mutated := map[string]any{}
		for k, v := range toolInput {
			mutated[k] = v
		}
		mutated["limit"] = math.Min(limit, 50)
		return PreToolUseResult{MutatedInput: mutated}
	},
})
```

### PostToolUse

`PostToolUse` fires after successful tool execution:

```typescript lines theme={null}
type PostToolUsePayload = {
  toolName: string;
  toolInput: Record<string, unknown>;
  toolOutput: unknown;
  durationMs: number;
};
```

It is observational and has no result. `toolInput` contains the effective arguments after any `PreToolUse` mutation.

### PostToolUseFailure

`PostToolUseFailure` fires when a tool executes and throws or returns an error:

```typescript lines theme={null}
type PostToolUseFailurePayload = {
  toolName: string;
  toolInput: Record<string, unknown>;
  error: unknown;
};
```

It does not fire when the tool never ran, including a `PermissionRequest` denial, user rejection, `PreToolUse` block, invalid JSON arguments, or an HITL tool pausing for later input. Observe those outcomes in the corresponding gating hook. The post-use hook fires after a paused HITL tool is resumed and successfully completes.

### Stop

`Stop` fires when a `stopWhen` condition halts the loop:

```typescript lines theme={null}
type StopPayload = {
  reason: 'max_turns';
};

type StopResult = {
  forceResume?: boolean;
  appendPrompt?: string;
};
```

`appendPrompt` injects a user message, but does not by itself continue the tool loop. Prompts from multiple handlers are joined with newlines. If any handler returns `forceResume: true`, the loop continues, subject to a limit of three consecutive overrides without progress.

A tool output or a fresh model response resets that counter. Blocked and denied tool outputs also count as progress because the model receives the feedback. A bare `forceResume` normally triggers the same stop condition again and uses the override limit. Pair it with `appendPrompt` or a stop condition whose external state can change.

```typescript lines theme={null}
hooks.on('Stop', {
  handler: ({ reason }) => {
    if (reason === 'max_turns' && shouldAskForSummary()) {
      return {
        forceResume: true,
        appendPrompt: 'Summarize the work completed so far.',
      };
    }
  },
});
```

```python title="Python" lines theme={null}
def on_stop(payload, ctx):
    if payload.get("reason") == "max_turns" and should_ask_for_summary():
        return {
            "force_resume": True,
            "append_prompt": "Summarize the work completed so far.",
        }


hooks.on("Stop", HookEntry(handler=on_stop))
```

```go title="Go" lines theme={null}
hooks.OnStop(StopHook{
	Handler: func(payload StopPayload, ctx HookContext) StopResult {
		if payload.Reason == "max_turns" && shouldAskForSummary() {
			return StopResult{
				ForceResume:  true,
				AppendPrompt: "Summarize the work completed so far.",
			}
		}
		return StopResult{}
	},
})
```

### SessionEnd

`SessionEnd` fires once when a started session exits:

```typescript lines theme={null}
type SessionEndPayload = {
  reason: 'user' | 'error' | 'max_turns' | 'complete';
  totalUsage?: SessionUsageTotals;
};

type SessionUsageTotals = ModelCallUsage & {
  modelCalls: number;
};
```

`totalUsage` is present when at least one model response completed. Token fields are summed across calls. `cost` is included when at least one response reported it.

When `SessionStart` succeeds, `SessionEnd` fires exactly once for that run on completion, approval pause, interruption, error, and no-tools streaming teardown. An approval pause currently ends with `reason: 'complete'`.

Approval and HITL resume calls skip `SessionStart` and `SessionEnd`, but tool hooks still fire and detached work is still drained. A teardown error is logged and never replaces the run's original error.

## Matchers and filters

Use `matcher` to register handlers for selected tool names:

```typescript lines theme={null}
type ToolMatcher =
  | string
  | RegExp
  | ((toolName: string) => boolean);
```

```typescript lines theme={null}
hooks.on('PreToolUse', {
  matcher: /^filesystem_/,
  filter: ({ toolInput }) => toolInput.path !== undefined,
  handler: ({ toolInput }) => {
    validateWorkspacePath(toolInput.path);
  },
});
```

```python title="Python" lines theme={null}
def has_path(payload, *_):
    return payload["tool_input"].get("path") is not None


def on_pre_tool_use(payload, ctx):
    validate_workspace_path(payload["tool_input"]["path"])


hooks.on(
    "PreToolUse",
    HookEntry(
        handler=on_pre_tool_use,
        matcher=re.compile(r"^filesystem_"),
        filter=has_path,
    ),
)

```

```go title="Go" lines theme={null}
hooks.OnPreToolUse(PreToolUseHook{
	Matcher: regexp.MustCompile(`^filesystem_`),
	Filter: func(toolInput map[string]any) bool {
		_, ok := toolInput["path"]
		return ok
	},
	Handler: func(toolInput map[string]any, ctx HookContext) PreToolUseResult {
		validateWorkspacePath(fmt.Sprint(toolInput["path"]))
		return PreToolUseResult{}
	},
})
```

A string matches exactly. A regular expression or predicate can match a set of tools. A matcher-scoped handler is skipped when an event has no tool name. `filter` receives the hook payload and can add any further condition.

Matchers are intended for tool-scoped hooks. Use `filter` by itself for session, prompt, model-call, and stop hooks.

## Handler chain behavior

Handlers run sequentially in registration order.

1. The SDK checks the handler's matcher and filter.
2. It calls the handler with the latest payload.
3. A mutation replaces the corresponding payload field for later handlers.
4. A block or rejection stops the remaining handler chain.

Mutations therefore pipe through the chain:

```typescript lines theme={null}
hooks.on('PreToolUse', {
  matcher: 'query_database',
  handler: ({ toolInput }) => ({
    mutatedInput: { ...toolInput, limit: 100 },
  }),
});

hooks.on('PreToolUse', {
  matcher: 'query_database',
  handler: ({ toolInput }) => {
    // Sees limit: 100 from the previous handler.
    return isSafeQuery(toolInput)
      ? undefined
      : { block: 'Unsafe query' };
  },
});
```

```python title="Python" lines theme={null}
def apply_limit(payload, ctx):
    return {"mutated_input": {**payload["tool_input"], "limit": 100}}


hooks.on("PreToolUse", HookEntry(handler=apply_limit, matcher="query_database"))


def check_query(payload, ctx):
    # Sees limit: 100 from the previous handler.
    if not is_safe_query(payload["tool_input"]):
        return {"block": "Unsafe query"}


hooks.on("PreToolUse", HookEntry(handler=check_query, matcher="query_database"))

```

```go title="Go" lines theme={null}
hooks.OnPreToolUse(PreToolUseHook{
	Matcher: regexp.MustCompile(`^query_database$`),
	Handler: func(toolInput map[string]any, ctx HookContext) PreToolUseResult {
		mutated := map[string]any{}
		for k, v := range toolInput {
			mutated[k] = v
		}
		mutated["limit"] = 100
		return PreToolUseResult{MutatedInput: mutated}
	},
})

hooks.OnPreToolUse(PreToolUseHook{
	Matcher: regexp.MustCompile(`^query_database$`),
	Handler: func(toolInput map[string]any, ctx HookContext) PreToolUseResult {
		// Sees limit: 100 from the previous handler.
		if isSafeQuery(toolInput) {
			return PreToolUseResult{}
		}
		return PreToolUseResult{Block: "Unsafe query"}
	},
})
```

A blocking handler's mutation is still applied before the chain stops. Empty strings do not block or reject. Return `mutatedInput` or `mutatedPrompt` instead of mutating nested payload values in place.

By default, a throwing handler, matcher, or filter is logged and skipped. Use strict mode to propagate these failures, which is useful in tests:

```typescript lines theme={null}
const hooks = new HooksManager(undefined, {
  throwOnHandlerError: true,
});
```

```python title="Python" lines theme={null}
hooks = HooksManager(throw_on_handler_error=True)
```

```go title="Go" lines theme={null}
hooks := NewHooksManager(HooksManagerOptions{
	ThrowOnHandlerError: true,
})
```

Payload and result schema failures follow the same error policy.

## Asynchronous handlers

Handlers may return a promise. The chain waits for a normal asynchronous handler before running the next handler:

```typescript lines theme={null}
hooks.on('PreToolUse', {
  handler: async ({ toolInput }) => {
    await validatePolicy(toolInput);
  },
});
```

```python title="Python" lines theme={null}
async def on_pre_tool_use(payload, ctx):
    await validate_policy(payload["tool_input"])


hooks.on("PreToolUse", HookEntry(handler=on_pre_tool_use))

```

```go title="Go" lines theme={null}
hooks.OnPreToolUse(PreToolUseHook{
	Handler: func(toolInput map[string]any, ctx HookContext) PreToolUseResult {
		// Blocking call: the chain waits for it to return before the next handler.
		validatePolicy(ctx, toolInput)
		return PreToolUseResult{}
	},
})
```

To detach telemetry or audit work without delaying the loop, return an `AsyncOutput` signal:

```typescript lines theme={null}
hooks.on('PostToolUse', {
  handler: (payload, context) => ({
    async: true,
    work: sendTelemetry(payload, {
      signal: context.signal,
    }),
    asyncTimeout: 5_000,
  }),
});
```

```python title="Python" lines theme={null}
def on_post_tool_use(payload, ctx):
    return {
        "async": True,
        "work": send_telemetry(payload, cancel_event=ctx.cancel_event),
        "async_timeout": 5_000,
    }


hooks.on("PostToolUse", HookEntry(handler=on_post_tool_use))

```

```go title="Go" lines theme={null}
hooks.OnPostToolUse(PostToolUseHook{
	Handler: func(payload PostToolUsePayload, ctx HookContext) PostToolUseResult {
		return PostToolUseResult{
			Async: true,
			Work: func(workCtx context.Context) error {
				return sendTelemetry(workCtx, payload)
			},
			AsyncTimeout: 5 * time.Second,
		}
	},
})
```

The asynchronous signal has this exact shape:

```typescript lines theme={null}
interface AsyncOutput {
  readonly async: true;
  readonly work?: Promise<unknown>;
  readonly asyncTimeout?: number;
}
```

The default timeout is 30 seconds. On timeout, the handler context's signal is aborted and the timeout is logged. JavaScript promises cannot be forcibly cancelled, so background work should observe `context.signal`.

The manager tracks detached work. Use its lifecycle methods during shutdown:

```typescript lines theme={null}
hooks.abortInflight('Application shutting down');
await hooks.drain();
```

```go title="Go" lines theme={null}
hooks.AbortInflight("Application shutting down")
hooks.Drain()

```

`abortInflight()` aborts the signals for active handler work. `drain()` waits for all detached work to settle. The agent loop also drains pending hook work when a run ends.

Use the exported `isAsyncOutput(value)` type guard when handling hook return values yourself. Objects with extra fields are not asynchronous signals, so a mutation cannot be accidentally discarded.

## Custom hooks

Define custom hooks with Zod payload and result schemas:

```typescript expandable lines theme={null}
import { HooksManager } from '@openrouter/agent';
import { z } from 'zod/v4';

const hooks = new HooksManager({
  DeploymentGate: {
    payload: z.object({
      environment: z.string(),
      version: z.string(),
    }),
    result: z.object({
      approved: z.boolean(),
    }),
  },
  AuditLog: {
    payload: z.object({
      event: z.string(),
    }),
    result: z.void(),
  },
});

hooks.on('DeploymentGate', {
  handler: ({ environment }) => ({
    approved: environment !== 'production',
  }),
});

const { results } = await hooks.emit('DeploymentGate', {
  environment: 'staging',
  version: '1.2.3',
});

console.log(results[0]?.approved);
```

```python title="Python" lines theme={null}
import asyncio
from types import SimpleNamespace
from pydantic import BaseModel
from openrouter_agent import HookEntry, HooksManager


class DeploymentGatePayload(BaseModel):
    environment: str
    version: str


class DeploymentGateResult(BaseModel):
    approved: bool


class AuditLogPayload(BaseModel):
    event: str


# Each custom hook definition exposes `payload` and `result` schema attributes.
hooks = HooksManager({
    "DeploymentGate": SimpleNamespace(payload=DeploymentGatePayload, result=DeploymentGateResult),
    "AuditLog": SimpleNamespace(payload=AuditLogPayload, result=None),
})


def deployment_gate(payload, ctx):
    environment = payload["environment"] if isinstance(payload, dict) else payload.environment
    return DeploymentGateResult(approved=environment != "production")


hooks.on("DeploymentGate", HookEntry(handler=deployment_gate))


async def main():
    emitted = await hooks.emit("DeploymentGate", {"environment": "staging", "version": "1.2.3"})
    if emitted.results:
        first = emitted.results[0]
        approved = first["approved"] if isinstance(first, dict) else first.approved
        print(approved)
    else:
        print(None)


asyncio.run(main())

```

```go title="Go" lines theme={null}
package main

import "fmt"

// Typed payload and result schemas for each custom hook.
type DeploymentGatePayload struct {
	Environment string
	Version     string
}

type DeploymentGateResult struct {
	Approved bool
}

type AuditLogPayload struct {
	Event string
}

// EmitOptions carries per-emit values, such as the session ID, to every handler.
type EmitOptions struct {
	SessionID string
}

// Hook is a typed chain of handlers for one custom hook.
type Hook[P, R any] struct {
	handlers []func(P, EmitOptions) R
}

func (h *Hook[P, R]) On(handler func(P, EmitOptions) R) {
	h.handlers = append(h.handlers, handler)
}

func (h *Hook[P, R]) Emit(payload P, opts EmitOptions) []R {
	results := make([]R, 0, len(h.handlers))
	for _, handler := range h.handlers {
		results = append(results, handler(payload, opts))
	}
	return results
}

type CustomHooks struct {
	DeploymentGate Hook[DeploymentGatePayload, DeploymentGateResult]
	AuditLog       Hook[AuditLogPayload, struct{}]
}

func main() {
	hooks := &CustomHooks{}

	hooks.DeploymentGate.On(func(p DeploymentGatePayload, opts EmitOptions) DeploymentGateResult {
		return DeploymentGateResult{Approved: p.Environment != "production"}
	})

	results := hooks.DeploymentGate.Emit(DeploymentGatePayload{
		Environment: "staging",
		Version:     "1.2.3",
	}, EmitOptions{SessionID: "deploy-123"})

	if len(results) > 0 {
		fmt.Println(results[0].Approved)
	}
}

```

```text title="Output" theme={null}
true
```

Payloads and non-void results are validated on every `emit()`. Zod transforms, defaults, and coercion are applied before handlers run, so handlers receive the schema output type.

Custom hook names must be non-empty and cannot collide with built-in names. Custom hooks do not inherit built-in mutation or blocking behavior. Inline configuration only supports built-in hooks.

When directly emitting from a manager shared by concurrent operations, pass a per-emit session ID:

```typescript lines theme={null}
await hooks.emit(
  'AuditLog',
  { event: 'deployment_started' },
  { sessionId: deployment.id },
);
```

```python title="Python" lines theme={null}
await hooks.emit(
    "AuditLog",
    {"event": "deployment_started"},
    session_id=deployment.id,
)
```

```go title="Go" lines theme={null}
hooks.AuditLog.Emit(
	AuditLogPayload{Event: "deployment_started"},
	EmitOptions{SessionID: deployment.ID},
)
```

`setSessionId()` sets a manager-wide default for direct emissions. It is last-writer-wins, so prefer the per-emit value when operations may overlap.

## HooksManager API

### constructor

```typescript lines theme={null}
new HooksManager(customHooks?, options?)
```

```python title="Python" lines theme={null}
HooksManager(custom_hooks)
```

```go title="Go" lines theme={null}
hooks := NewHooksManager(customHooks, options) // either argument may be nil
```

* `customHooks` maps custom names to Zod `payload` and `result` schemas.
* `options.throwOnHandlerError` propagates hook errors when `true`.

### on

```typescript lines theme={null}
hooks.on(hookName, entry): () => void
```

Registers a typed handler and returns an unsubscribe function. An entry has a `handler` and optional `matcher` and `filter`.

### off

```typescript lines theme={null}
hooks.off(hookName, handler): boolean
```

Removes a specific handler. Returns whether it was found.

### removeAll

```typescript lines theme={null}
hooks.removeAll(hookName?): void
```

Removes handlers for one hook, or every handler when no name is supplied.

### setSessionId

```typescript lines theme={null}
hooks.setSessionId(sessionId): void
```

Sets the default `context.sessionId` for direct `emit()` calls. This mutable default is last-writer-wins. Use the per-emit override for concurrent work.

### emit

```typescript lines theme={null}
await hooks.emit(hookName, payload, {
  toolName,
  sessionId,
});
```

```python title="Python" lines theme={null}
await hooks.emit(
    hook_name,
    payload,
    tool_name=tool_name,
    session_id=session_id,
)
```

```go title="Go" lines theme={null}
hooks.Emit(hookName, payload, EmitOptions{
	ToolName:  toolName,
	SessionID: sessionID,
})
```

Validates the payload, runs the chain, and returns:

```typescript lines theme={null}
type EmitResult<Result, Payload> = {
  results: Result[];
  pending: Promise<void>[];
  finalPayload: Payload;
  blocked: boolean;
  mutated: boolean;
};
```

`toolName` supplies the value used by matchers. `sessionId` overrides the manager default for this emission.

### hasHandlers

```typescript lines theme={null}
hooks.hasHandlers(hookName): boolean
```

Returns whether the hook has any registered handlers.

### abortInflight and drain

```typescript lines theme={null}
hooks.abortInflight(reason?): void
await hooks.drain(): Promise<void>
```

```python title="Python" lines theme={null}
async def shutdown(hooks):
    hooks.abort_inflight()  # -> None
    await hooks.drain()  # -> None

```

```go title="Go" lines theme={null}
hooks.AbortInflight("shutdown") // reason is optional; pass "" to omit
hooks.Drain()                   // blocks until detached hook work settles
```

Abort active handler signals, then await detached work during graceful shutdown.

## Next steps

* **[Tools](https://openrouter.ai/docs/agent-sdk/call-model/tools.md)** - Define and execute typed tools
* **[Tool Approval & State](https://openrouter.ai/docs/agent-sdk/call-model/tool-approval-state.md)** - Pause and resume approval-gated tools
* **[Stop Conditions](https://openrouter.ai/docs/agent-sdk/call-model/stop-conditions.md)** - Control when the agent loop ends
* **[API Reference](https://openrouter.ai/docs/agent-sdk/call-model/api-reference.md)** - Review complete `callModel` types and exports
