Skip to content

Handlers

Lifecycle handlers are Python classes that run at specific points around an agent or a whole abt run / abt dispatch invocation — similar to Airflow operators, Prefect flow hooks, or Dagster asset hooks. Use them for side-effects that live outside the agent prompt: audit logging, Slack pings, metric emission, external webhooks.

When to reach for a handler

Use a handler when you want:

  • a side-effect that must run after success or failure (Slack post, Jira update, metric flush) and must not block the main run;
  • a guardrail that records audit events for compliance (who ran what, for how long, which tokens);
  • a cross-cutting behaviour (redaction, PII scanning, structured summary) that should apply to many agents or every run.

Use a transformer instead when you want to change the agent's text output, and a retriever when you want to augment the prompt.

Where handlers live

Handlers live under paths.handlers (default: handlers/). Every .py file in that directory is imported at compile time and every abt.sdk.Handler subclass is registered by its class name (which must be unique across the project).

# abt.yaml
paths:
  handlers: handlers

abt compile finds handlers through paths.handlers in abt.yaml. To compile against a different handlers directory, for example in a test fixture, point paths.handlers at it in the abt.yaml you compile with.

Writing a handler

# handlers/slack_audit.py
from __future__ import annotations

from typing import Any

from abt.sdk import Handler


class SlackAuditHandler(Handler):
    """Post a short audit line to Slack when an agent finishes."""

    timeout_seconds = 10.0
    fail_silent = True

    def __init__(self, *, channel: str, emoji: str = ":robot_face:") -> None:
        self.channel = channel
        self.emoji = emoji

    def run(self, **context: Any) -> None:
        abt = context["abt"]
        abt.log.info(
            "posting to %s: %s %s/%s %s",
            self.channel,
            self.emoji,
            context["scope"],
            context["event"],
            context.get("agent_name") or context.get("workflow_name") or "run",
        )
  • Inherit from abt.sdk.Handler. Both sync (def run(...)) and async (async def run(...)) are supported — the dispatcher detects which one you wrote.
  • timeout_seconds (class var, default 30.0) caps one execution. Set to None to opt out.
  • fail_silent (class var, default True) controls the failure-isolation policy. With fail_silent=True, a failing handler is recorded in run_results.json and the main run continues. With fail_silent=False, the dispatcher raises E_HANDLER_FAILED (and --fail-on-handler-error forces this behaviour globally).
  • The **context payload is a typed abt.sdk.HandlerContext mapping with keys like event, scope, run_id, status, elapsed_seconds, agent_name/workflow_name, text, structured, token_usage, plus context["abt"] for the handler API.

The abt API inside run(**context)

context["abt"] exposes a small, stable surface:

  • abt.log.info(...) / warning(...) / error(...) — a logger routed through the redacting formatter.
  • abt.redact(text) — run the same secret-redaction rules used by abt.
  • abt.manifest — read-only reference to the compiled WritableManifest (or None if the handler runs outside a compiled context).
  • abt.target_dir() — path to <workspace>/target/ for side-effect writes.
  • abt.get_credentials(namespace) — read credentials from the active profiles.yaml (same source as sources/exposures). Returns dict[str, str]; an empty dict when no profile is active or the lookup raises.
class S3UploadHandler(Handler):
    def run(self, **context):
        creds = context["abt"].get_credentials("aws")
        # creds = {"access_key_id": "...", "secret_access_key": "..."}

Never mutate abt.manifest or the incoming context — mutations are not propagated to other handlers.

Declaring handlers on an agent

Reference a handler class by its class name and pass __init__ kwargs as YAML, directly in the agent's own frontmatter. Both a bare string and a single-key mapping are accepted:

---
description: Reviewer agent.
tools: [word_count]
on_success:
  - SlackAuditHandler:
      channel: "#example-audit"
      emoji: ":white_check_mark:"
  - ExampleAuditHandler                 # bare class name, no kwargs; defined by `abt init --with-handlers`
on_failure:
  - SlackAuditHandler:
      channel: "#example-alerts"
      emoji: ":rotating_light:"
---
Review the draft you are given.

{{ var('...') }} placeholders are rendered with the usual compile-time precedence (CLI flags > env > abt.yaml), so you can drive kwargs from profiles or runtime flags. A {{ env_var('NAME') }} kwarg stays as written in manifest.json and is resolved from the environment when the handler is built, so a token never lands in committed or served artifacts. This holds for kwargs under config.handlers in abt.yaml too. Only a kwarg that used env_var() is rendered at that point, so a var() value that happens to contain {{ env_var(...) }} stays literal text.

Handlers fire on the agent's own run outcome (on_success / on_failure). There are no approval-specific handler events, even for agents that use external approvals.

Project-wide defaults (config.handlers)

abt.yaml accepts a config.handlers block that layers defaults onto every agent and the run itself:

config:
  handlers:
    fail_fast: false              # default; --fail-on-handler-error overrides
    agent_defaults:
      on_success:
        - ExampleAuditHandler
    run_lifecycle:
      on_start:
        - ExampleAuditHandler: { label: run-start }
      on_end:
        - ExampleAuditHandler: { label: run-end }

agent_defaults is prepended to every agent's own on_success/on_failure chain, whether that agent runs as a dispatch entry point or deep inside another agent's subagents: tree.

Merging rules:

  1. Project defaults run before per-site frontmatter.
  2. Duplicate entries (same class name + kwargs) are deduplicated so an agent that explicitly repeats a default does not invoke it twice.

Runtime behaviour

  • Agent lifecycle handlers fire right after a RunResult is produced, before target/run_results/<run_id>/run_results.json is written, so the artifact always contains the full handlers: [...] tuple with per-handler ok / elapsed_ms / error_code / error_message / source (config vs frontmatter).
  • Run lifecycle handlers (on_start / on_end) fire once per abt run / abt dispatch invocation.
  • abt dispatch --skip-exposures (and every abt chat turn) fires no handlers — agent on_success / on_failure and run on_start / on_end are skipped — so a local or mocked run cannot post to Slack, upload to S3 or hit any other side effect a handler owns. The skip is logged at INFO, and --fail-on-handler-error / ABT_HANDLERS_FAIL_FAST have nothing to escalate.
  • By default a raising handler is isolated: the record lands with ok: false, error_code: "E_HANDLER_FAILED" and the parent run keeps its original status (the abt run exit code is unchanged).
  • Escalation turns that first-failed record into a parent-run failure with ok=false and error="handler <Class> (<event>) failed: ...". Four switches enable it (most specific wins):
  • --fail-on-handler-error on the CLI,
  • ABT_HANDLERS_FAIL_FAST=1 environment variable,
  • config.handlers.fail_fast: true in abt.yaml,
  • per-class fail_silent = False on the Handler subclass — always escalates that specific handler regardless of any global switch.
  • Sync def run(...) implementations run on asyncio.to_thread so they never block the event loop; async async def run(...) methods are awaited directly. Every call is wrapped in asyncio.wait_for(timeout_seconds).
  • Timeout caveat for sync handlers: asyncio.wait_for can only cancel the awaiter — it cannot forcibly stop a Python thread. A sync handler that blocks past timeout_seconds is recorded as ok=false, error_code="E_HANDLER_FAILED" and the run continues, but the underlying thread keeps running in the background and may still complete its side effects (writing a file, calling an API, …). If timely termination of side effects matters, write the handler as async def run(...) and use cooperative cancellation (or wrap the blocking call in asyncio.shield-friendly primitives you can cancel).
  • Every handler invocation lands in the per-run Python log (<workspace>/logs/abt.log): successes at DEBUG (handler <Class> ok in <ms>ms (event=..., scope=..., source=...)) and timeouts / exceptions at WARNING. The authoritative per-handler record always lives in run_results.json → handlers[] regardless of log level.
  • File writes from handlers belong under <workspace>/target/ — use context["abt"].target_dir() (or the ABT_TARGET_DIR env var after the project has loaded). Don't use cwd-relative target/… paths; they bypass workspace routing. During --stateless runs, writes go to an auto-created temp workspace (--workspace is ignored).

Built-in handlers

abt ships built-in handlers that are always available without placing files in handlers/. They are registered automatically alongside project-local handlers.

UploadArtifacts

Upload run artifacts (run_results.json, dag_summary.json, etc.) to S3 or a local directory after an agent's dispatch completes. Designed for abt watch deployments where you need durable artifact storage keyed by dispatch + source identity. Schema for the two JSON files: Run artifacts.

Save this as agents/production-triage.md:

---
name: production-triage
description: Triages production alerts
on_success:
  - UploadArtifacts:
      type: s3
      bucket: my-run-results-bucket
      region: eu-central-1
      key: "{project}/{agent}/{source_key}/{timestamp}"
      include:
        - run_results.json
        - dag_summary.json

on_failure:
  - UploadArtifacts:
      type: local
      key: "{project}/{agent}/{run_id}"
      destination: target/failed-artifacts
---
Triage the production alert you are given.

Parameters:

Parameter Default Description
type local s3 or local
bucket (required for s3) S3 bucket name
region $AWS_DEFAULT_REGION AWS region for S3
key {project}/{agent}/{run_id} Path template (see vars below). An unknown {placeholder} fails the handler at construction.
destination target/artifacts Local base directory (for local type); a relative path resolves against the project root
include all files Glob patterns for which files to upload

Template variables available in key:

Variable Resolves to
{project} Project name from manifest
{agent} Head agent name
{source_key} First source thread key with : replaced by /. The thread key slack:C0EXAMPLE01:1234567890.123456 renders as slack/C0EXAMPLE01/1234567890.123456.
{run_id} Unique run ID
{timestamp} ISO datetime (YYYY-MM-DDTHH:MM:SS)
{date} Date only (YYYY-MM-DD)

Context variables available to all handlers:

Key Type Description
run_results_dir str Path to the target/run_results/<run_id>/ directory
project_name str Project name
source_thread_keys list[str] Thread keys from resolved sources

These are in addition to the existing HandlerContext fields (event, scope, run_id, status, text, structured, token_usage, elapsed_seconds, agent_name, workflow_name, abt).

Ordering and failure isolation

  • Project-default handlers run before frontmatter handlers, and appear first in run_results.json, for both on_success/on_failure and lifecycle hooks.
  • A raising handler does not fail the run by default — the exception is caught, logged, and recorded alongside the other handler results; the parent run stays green. Set ABT_HANDLERS_FAIL_FAST=1 (or --fail-on-handler-error, or config.handlers.fail_fast) to turn a handler failure into an E_HANDLER_FAILED parent-run failure instead, with the handler records still attached.
  • Async handlers are awaited in place; a slow or hanging handler delays run completion like any other await.
  • manifest.handlers carries every discovered handler class name with its __init__ signature — the same payload abt list --handlers prints.

Inventory, docs, and diagnostics

  • abt list --handlers prints every discovered class with its __init__ signature so you can see which kwargs are required and their defaults.
  • abt docs generate produces a Handlers tab in the HTML docs site, including reverse-lookup ("used by which agent").
  • abt doctor includes the handler_refs_resolved rule that warns when an agent references a handler class that is missing from the compiled manifest (stale manifest or deleted file).

Errors

abt compile reports handler mistakes as one-line errors that name the agent and the hook; the E_HANDLER_* code is not part of the CLI output:

Mistake abt compile prints
Frontmatter references a class that is not registered ERROR: agent assistant on_success[0]: unknown handler 'NoSuchHandler'. Known handlers: SlackAuditHandler, …
A required __init__ parameter is missing ERROR: agent assistant on_success[0] SlackAuditHandler: missing required kwarg(s): channel.
A kwarg does not match the handler's __init__ signature ERROR: agent assistant on_success[0] SlackAuditHandler: unknown kwarg(s): nope. Declared: ['channel', 'emoji'].
A handler reference is neither a string nor a single-key mapping ERROR: agent assistant on_success[0] must be a string or a single-key mapping; got list.
A kwarg value the handler rejects ERROR: agent assistant on_success[0] UploadArtifacts: unknown key placeholder(s) {agnet}. Supported: ...

A handler can reject kwarg values at compile by defining a @classmethod validate_kwargs(cls, kwargs) that raises ValueError. Compile never constructs a handler, because constructors may do I/O, so this is the only place to check values before a run. When a kwarg uses env_var() the check is skipped at compile, because a validator may require that key and a partial check would be unsound. It runs on the rendered values when the handler is built. A ValueError there, or an unset variable with no default, is logged as an error and recorded as a failed handler (E_HANDLER_FAILED), so --fail-on-handler-error and config.handlers.fail_fast escalate it.

Other failures: two handler files that define the same class name, and a handler module that raises while it is imported at compile time, also fail the compile. A handler that raises during a run is recorded in the run's handler results with error_code: "E_HANDLER_FAILED"; it only fails the run when fail_silent=False or --fail-on-handler-error is set.