---
title: "Hooks and Events"
description: "The Autohand Code Agent SDK streams every meaningful moment in an agent run as an event. You can observe these events for logging, react to them to update a UI, or intercept them with hooks to change behavior."
sidebar:
  label: "Hooks and events"
seo:
  title: "Hooks and Events | Autohand Code Agent SDK"
  description: "Understand how the Autohand Code Agent SDK exposes hooks and events across JavaScript, TypeScript, Python, Go, Java, and Swift."
---

## Events are the SDK contract

The Autohand Code CLI runs the reasoning loop. The SDK opens a JSON-RPC or stdio connection to the CLI and receives a stream of events. Your application never needs to host the model or implement tool calling itself; it only needs to understand the events.

This design keeps SDKs thin, consistent across languages, and safe. The CLI enforces permissions and file access; the SDK observes and responds.

## Common event types

CLI-backed hosts in all nine languages can observe the original JSON-RPC method and its parameters. Swift exposes this transport on macOS. Its in-process agent loop has a separate event stream.

| Event | When it fires | Key fields |
| --- | --- | --- |
| `turn_start` | A new reasoning turn begins | turnId, iteration |
| `message_update` | The model streams a token or fragment | delta, message |
| `tool_start` | A tool is about to run | toolName, args |
| `tool_end` | A tool has finished | toolName, output, success |
| `permission_request` | The CLI needs user approval | requestId, tool, description |
| `file_modified` | A tool created, modified, or deleted a file | filePath, changeType, toolId |
| `error` | A runtime or transport error occurred | message, recoverable |

## Observe CLI 0.9.13 notifications [#runtime-notifications]

Subscribe before starting the CLI to receive startup announcements. Use the method on the original packet to identify it. Keep callbacks short so the transport can continue reading responses.

| Wire method | Fields to read | How to use it |
| --- | --- | --- |
| `autohand.updateAvailable` | `currentVersion`, `latestVersion`, `channel`, `updateCommand`, optional `releaseUrl` | Show the available release. The CLI checks in the background and may send one notice per connection. |
| `autohand.hook.programStatus` | `state`, `timestamp`, optional `id`, `title`, `message` | Render idle, working, blocked, done, error, or clear. A blocked report includes `kind` (permission, question, or auth). Working and blocked reports may include progress from 0 to 100. |
| `autohand.skillAttachment` | `receipt`, `timestamp` | Correlate a skill revision with its task and request using `taskId`, `requestId`, `reference`, and `contentDigest`. Receipt state is `submitted` for a provider request or `supplied` for an external handoff. |
| `autohand.toolStart`, `autohand.toolEnd` | `toolId`, optional `parentToolId` | Group tool calls made by a tool script under the parent call. A tool stopped by the user or host ends with `success: false` and `interrupted: true`. |
| `autohand.hook.stop` | Optional `outcome` | Distinguish `completed`, `interrupted`, `needs_review`, and `failed` when reporting a turn. |
| `autohand.hook.subagentStop` | `subagentId`, optional `status` and `reason` | Distinguish completed, partial, failed, and cancelled work. A partial result can carry `reason: "iteration_limit"`. |

Older CLI versions can omit these methods or optional fields. Preserve the original packet when recording events so future fields survive a round trip.

## Shared CLI hook notifications [#cli-hook-events]

These hook notifications are available through the CLI-backed event stream. Newer additions, such as the TypeScript rate-limit event below, have their own SDK and bundled-runtime requirements.

| Normalized event | What it reports |
| --- | --- |
| `hook_pre_tool` | A tool is about to run, including its name and arguments. |
| `hook_post_tool` | A tool completed, including success, output, and duration. |
| `file_modified` | A CLI hook reports a created, modified, or deleted path. |
| `hook_pre_prompt` | The CLI accepted an instruction and its mentioned files. |
| `hook_post_response` | A response completed with usage, tool-call count, and duration. |
| `hook_session_error` | The active session reports an error and optional context. |
| `hook_stop` | The runtime stop hook reports final usage and duration. |
| `hook_session_start` | A startup, resume, or clear session lifecycle begins. |
| `hook_session_end` | A session ends because of quit, clear, exit, or error. |
| `hook_subagent_stop` | A subagent completes or fails. |
| `hook_permission_request` | A hook observes the tool action awaiting permission. |
| `hook_notification` | A configured notification hook emits a typed message. |
| `hook_context_compacted` | Context was compacted, including usage and cropped-message counts. |
| `hook_context_overflow` | Context overflow recovery cropped messages. |
| `hook_context_warning` | Context use crossed the warning threshold. |
| `hook_context_critical` | Context use crossed the critical threshold. |

## MCP and learning notifications [#extension-events]

| Normalized event | What your host should do |
| --- | --- |
| `mcp_invoke_request` | Review an MCP tool invocation request and respond through the SDK's MCP response API. |
| `mcp_tools_changed` | Refresh the MCP tool catalog exposed by the host UI. |
| `learn_progress` | Render progress while the CLI analyzes, loads, evaluates, generates, or updates learned material. |

C#/.NET currently names the first normalized string `mcp_invocation_request`; its typed `McpInvocationRequestEvent` carries the same CLI notification. Unknown or malformed newer notifications remain available through each wrapper's unknown-event fallback instead of being discarded.

<a id="rate-limits"></a>

## Handle rate limits in TypeScript

Updated TypeScript SDK builds validate `autohand.hook.rateLimit` and expose it as `hook_rate_limit`. This is an observation event, not a permission request. Older SDKs or malformed payloads can surface through `unknown_notification`; upgrade the SDK and its bundled CLI together.

| Field | Contract |
| --- | --- |
| `error`, `timestamp` | Required strings describing the failure and notification time. |
| `code`, `model`, `provider` | Optional strings for the classified error and provider context. |
| `retryAfterMs` | Optional finite, non-negative duration in milliseconds. It may be absent; do not assume zero means retry immediately. |
| `httpStatus` | Optional integer HTTP status from 100 through 599; a rate-limit response commonly reports 429. |

```ts
import { Agent } from '@autohandai/agent-sdk';

const agent = await Agent.create({ cwd: '.' });

try {
  const run = await agent.send('Inspect package.json and summarize the package.');
  for await (const event of run.stream()) {
    if (event.type === 'hook_rate_limit') {
      console.error(event.error, {
        provider: event.provider,
        model: event.model,
        httpStatus: event.httpStatus,
        retryAfterMs: event.retryAfterMs,
      });
    }
  }
  await run.wait();
} finally {
  await agent.close();
}
```

The CLI emits the dedicated `rate-limit` hook and still reports the normal `session-error` hook (`hook_session_error` in the SDK). It does not automatically retry a rate-limited session through its session-retry loop. Keep consuming the stream until the turn ends; displaying a rate-limit notice is not a request to restart the run.

If your application chooses to retry, make that decision explicitly after the current run settles, respect any available retry timing, and check the provider's quota or billing state. Do not start a retry from both error hooks. See [bundled-runtime verification](/agent-sdk/io/step-control#runtime-compatibility) for the tested HTTP 429 path.

## Stream events

Every SDK provides a streaming prompt method that yields events. These examples demonstrate the same event-loop shape in a representative set of SDKs; use the language reference for its native event type names.

```js title="JavaScript"
import { AutohandSDK } from '@autohandai/agent-sdk';

const sdk = new AutohandSDK({ cwd: '.' });
await sdk.start();

for await (const event of sdk.streamPrompt({ message: 'Refactor auth.js' })) {
  if (event.type === 'message_update') process.stdout.write(event.delta ?? '');
  if (event.type === 'tool_start') console.log('Tool:', event.toolName);
  if (event.type === 'permission_request') {
    await sdk.permissionResponse({ requestId: event.requestId, allowed: true });
  }
}

await sdk.stop();
```

```ts title="TypeScript"
import { AutohandSDK, type AgentEvent } from '@autohandai/agent-sdk';

const sdk = new AutohandSDK({ cwd: '.' });
await sdk.start();

for await (const event of sdk.streamPrompt({ message: 'Refactor auth.ts' })) {
  handleEvent(event);
}

function handleEvent(event: AgentEvent) {
  if (event.type === 'message_update') process.stdout.write(event.delta ?? '');
  if (event.type === 'tool_end') console.log(event.toolName, event.duration);
}

await sdk.stop();
```

```python title="Python"
import asyncio
from autohand_sdk import AutohandSDK

async def main():
    async with AutohandSDK(cwd=".") as sdk:
        async for event in sdk.stream_prompt("Refactor auth.py"):
            if event["type"] == "message_update":
                print(event.get("delta", ""), end="")
            if event["type"] == "tool_start":
                print("Tool:", event.get("tool_name"))

asyncio.run(main())
```

```go title="Go"
package main

import (
  "context"
  "fmt"

  "github.com/autohandai/agent-sdk-go/autohand"
)

func main() {
  ctx := context.Background()
  sdk := autohand.NewClient(autohand.Config{Cwd: "."})

  events, _ := sdk.StreamPrompt(ctx, "Refactor auth.go")
  for event := range events {
    if event.Type == "message_update" {
      fmt.Print(event.Delta)
    }
    if event.Type == "tool_start" {
      fmt.Println("Tool:", event.ToolName)
    }
  }
}
```

```java title="Java"
import ai.autohand.sdk.AutohandClient;
import ai.autohand.sdk.AgentEvent;

var sdk = AutohandClient.builder().cwd(".").build();

sdk.streamPrompt("Refactor AuthService.java").forEach((AgentEvent event) -> {
  switch (event.type()) {
    case "message_update" -> System.out.print(event.delta());
    case "tool_start" -> System.out.println("Tool: " + event.toolName());
    default -> {}
  }
});
```

```swift title="Swift"
import AutohandSDK

let sdk = AutohandClient(cwd: ".")

for try await event in sdk.streamPrompt("Refactor AuthService.swift") {
    switch event.type {
    case .messageUpdate:
        print(event.delta ?? "", terminator: "")
    case .toolStart:
        print("Tool: \(event.toolName ?? "")")
    default:
        break
    }
}
```

## Intercept behavior with hooks

In addition to observing events, you can intercept actions with CLI lifecycle hooks. A hook is a shell command, not an in-process callback: it is registered under the `hooks` key of the CLI config file (`~/.autohand/config.json`, or a trusted project's `.autohand/config.json`) and runs on the named event, such as `pre-tool`, `post-tool`, `pre-prompt`, or `stop`. Because every SDK drives the same CLI, these hooks apply to SDK runs too, unless the CLI is started with `--bare`. This is useful for guardrails, audit logging, and custom integrations.

```json title="config.json"
{
  "hooks": {
    "enabled": true,
    "hooks": [
      {
        "event": "pre-tool",
        "command": "~/.autohand/hooks/block-rm-rf.sh",
        "description": "Block rm -rf",
        "filter": { "tool": ["run_command"] }
      }
    ]
  }
}
```

```bash title="Hook script"
#!/usr/bin/env bash
# ~/.autohand/hooks/block-rm-rf.sh
# The CLI passes the hook context as JSON on stdin.
command="$(jq -r '.tool_input.command // empty')"
if [[ "$command" == *"rm -rf"* ]]; then
  echo "Blocked dangerous command" >&2
  exit 2
fi
exit 0
```

The command receives the event context as `HOOK_*` environment variables and as JSON on stdin. Exit with code 2 to block the action; the stderr text becomes the reason. Alternatively, exit 0 and print `{"decision": "block", "reason": "..."}` on stdout. Other non-zero exit codes are logged and the action continues. To approve or deny tool actions in your own process instead, handle `permission_request` events from the stream. The TypeScript, Go, and Java SDKs also ship hook-management methods (`addHook`, `getHooks`, and related), but they call `autohand.hooks.*` RPC methods that CLI 0.9.13 does not register, so register hooks in the config file.

## Event ordering guarantees

- Events for a single turn are delivered in order.
- `tool_start` always precedes `tool_end` for the same invocation.
- `permission_request` is emitted before the action is taken. The loop waits until the SDK responds or a timeout occurs.
- Pre-action hook notifications arrive before their matching action; post-action hook notifications include the completed result.
- Unknown notification fallbacks preserve the original RPC method and payload so a newer CLI does not silently lose data.

## Best practices

- Handle events asynchronously. Do not block the event stream with network calls unless the event requires a decision, such as permission\_request.
- Persist important events outside the process. The stream ends when the session closes.
- Use typed SDK clients when available so event fields are validated at compile time or runtime.
- Keep hook commands fast and stateless. Synchronous hooks block the action until they exit or hit their timeout (5 seconds by default).
