Skip to content
Esc
↑↓navigate↵open⌘Jpreview
Start
On this page

Intercept and control agent behaviour with hooks

In the SDKs the “hook” surface is the JSON-RPC event stream. You observe what the agent does, log it, and decide whether to allow, deny, or alter the next step. The CLI also runs lifecycle hooks: shell commands registered in its config file for events such as pre-prompt, pre-tool, and stop.

Two layers of hooks

  • SDK-level (event stream): subscribe to tool_start, tool_update, tool_end, file_modified, permission_request, and error. Use these for logging, metrics, UI rendering, audit trails, and approval gates.
  • CLI-level (lifecycle hooks): register shell commands under the hooks key of the CLI config file (~/.autohand/config.json, or a trusted project’s .autohand/config.json). They run on lifecycle events such as pre-prompt, pre-tool, post-tool, file-modified, and stop. Use these for organisation-wide policy, secret scrubbing, or audit logging.

The Swift SDK additionally exposes a HookManager that the PermissionManager consults for in-process approval decisions.

Hook into the event stream

Wrap a streamPrompt loop in a small dispatcher. Each branch is a hook: keep them fast, push slow work to a background queue.

import { AutohandSDK } from '@autohandai/agent-sdk';

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

for await (const event of sdk.streamPrompt({ message: prompt })) {
  switch (event.type) {
    case 'tool_start':
      logger.info('tool.start', { tool: event.toolName });
      break;
    case 'tool_end':
      logger.info('tool.end', { tool: event.toolName, durationMs: event.durationMs });
      break;
    case 'file_modified':
      cache.invalidate(event.path);
      break;
    case 'permission_request': {
      const dangerous = ['run_command', 'delete_path'].includes(event.tool);
      const allowed = !dangerous;
      await sdk.permissionResponse({ requestId: event.requestId, allowed });
      break;
    }
    case 'error':
      metrics.increment('agent.error', { code: event.code });
      break;
  }
}
from autohand_sdk import AutohandSDK

async with AutohandSDK(cwd=".") as sdk:
    async for event in sdk.stream_prompt(prompt):
        t = event["type"]
        if t == "tool_start":
            logger.info("tool.start", extra={"tool": event.get("tool_name")})
        elif t == "tool_end":
            logger.info("tool.end", extra={"tool": event.get("tool_name")})
        elif t == "file_modified":
            cache.invalidate(event.get("path"))
        elif t == "permission_request":
            dangerous = event.get("tool") in {"run_command", "delete_path"}
            await sdk.respond_to_permission(
                event["request_id"],
                decision="deny" if dangerous else "allow",
                allowed=not dangerous,
            )
        elif t == "error":
            metrics.increment("agent.error")
for event := range events {
    switch e := event.(type) {
    case autohand.ToolStartEvent:
        log.Info("tool.start", "tool", e.ToolName)
    case autohand.ToolEndEvent:
        log.Info("tool.end", "tool", e.ToolName)
    case autohand.FileModifiedEvent:
        cache.Invalidate(e.Path)
    case autohand.PermissionRequestEvent:
        dangerous := e.Tool == "run_command" || e.Tool == "delete_path"
        scope := autohand.ScopeOnce
        _ = sdk.PermissionResponse(ctx, e.RequestID, !dangerous, scope)
    case autohand.ErrorEvent:
        metrics.Increment("agent.error")
    }
}
sdk.streamPrompt(new PromptParams(prompt), event -> {
    if (event instanceof Events.ToolStartEvent tse) {
        logger.info("tool.start tool={}", tse.toolName());
    } else if (event instanceof Events.ToolEndEvent tee) {
        logger.info("tool.end tool={}", tee.toolName());
    } else if (event instanceof Events.FileModifiedEvent fme) {
        cache.invalidate(fme.path());
    } else if (event instanceof Events.PermissionRequestEvent pre) {
        boolean dangerous = pre.tool().equals("run_command") || pre.tool().equals("delete_path");
        if (dangerous) {
            sdk.denyPermission(pre.requestId(), DecisionScope.ONCE);
        } else {
            sdk.allowPermission(pre.requestId(), DecisionScope.ONCE);
        }
    } else if (event instanceof Events.ErrorEvent err) {
        metrics.increment("agent.error");
    }
});
let hookManager = HookManager()
let permissionManager = PermissionManager(
    hookManager: hookManager,
    mode: .interactive
)
Runner.setPermissionManager(permissionManager)

for try await event in Runner.runStream(agent: agent, prompt: prompt) {
    switch event.type {
    case .toolStart:
        logger.info("tool.start (event.toolName ?? "")")
    case .toolEnd:
        logger.info("tool.end (event.toolName ?? "")")
    case .error:
        metrics.increment("agent.error")
    default:
        break
    }
}

CLI lifecycle hooks

The Autohand Code CLI does not auto-discover scripts from a directory. Each hook is an entry in the hooks.hooks array of the config file, naming an event and a command. The command receives its context as HOOK_* environment variables and as a JSON object on stdin. Two events cover the prompt lifecycle:

  • pre-prompt: runs before the CLI processes user input. The prompt is in the instruction field of the stdin JSON (and $HOOK_INSTRUCTION). Exit with code 2, or print {"decision": "block", "reason": "..."} on stdout and exit 0, to block the prompt. Print {"additionalContext": "..."} to add a note to the conversation. The hook cannot rewrite the prompt, and other non-zero exit codes are logged without blocking.
  • stop: runs when a turn completes, with the session ID, turn duration, and token usage. It does not receive the response text. Use it for audit logging or downstream notifications.

Because the SDKs drive the same CLI over JSON-RPC, this is the right layer for org-wide policy that should apply to every SDK consumer, including ad-hoc CLI use. Hooks are skipped when the CLI runs with --bare (the SDK’s bare: true option). The TypeScript, Go, and Java SDKs 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.

{
  "hooks": {
    "enabled": true,
    "hooks": [
      {
        "event": "pre-prompt",
        "command": "~/.autohand/hooks/scrub-secrets.sh",
        "description": "Block prompts that contain AWS access keys"
      }
    ]
  }
}
#!/usr/bin/env bash
# ~/.autohand/hooks/scrub-secrets.sh
# The hook context arrives as JSON on stdin; the prompt is in .instruction
set -euo pipefail

prompt="$(jq -r '.instruction // empty')"

if grep -qE 'AKIA[0-9A-Z]{16}' <<< "$prompt"; then
  echo "blocked: AWS access key in prompt" >&2
  exit 2
fi

Best practices

  • Treat the event stream as your hook surface. It is consistent across SDKs and forward-compatible with new event types.
  • Keep handlers fast. Push slow work (network calls, disk writes) to a background queue.
  • Use CLI lifecycle hooks for policy that has to apply to every CLI run, not just SDK code paths.
  • Always handle error events and permission_request in interactive mode.
  • Avoid mutating the prompt mid-stream. If you need to redirect the agent, call abort() and start a new run.

Last updated on

Was this helpful?

Send Feedback

Help us improve this documentation page. Your feedback is valuable.

We'll only contact you if we need clarification