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, default30.0) caps one execution. Set toNoneto opt out.fail_silent(class var, defaultTrue) controls the failure-isolation policy. Withfail_silent=True, a failing handler is recorded inrun_results.jsonand the main run continues. Withfail_silent=False, the dispatcher raisesE_HANDLER_FAILED(and--fail-on-handler-errorforces this behaviour globally).- The
**contextpayload is a typedabt.sdk.HandlerContextmapping with keys likeevent,scope,run_id,status,elapsed_seconds,agent_name/workflow_name,text,structured,token_usage, pluscontext["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 byabt.abt.manifest— read-only reference to the compiledWritableManifest(orNoneif 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 activeprofiles.yaml(same source as sources/exposures). Returnsdict[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:
- Project defaults run before per-site frontmatter.
- 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
RunResultis produced, beforetarget/run_results/<run_id>/run_results.jsonis written, so the artifact always contains the fullhandlers: [...]tuple with per-handlerok/elapsed_ms/error_code/error_message/source(configvsfrontmatter). - Run lifecycle handlers (
on_start/on_end) fire once perabt run/abt dispatchinvocation. abt dispatch --skip-exposures(and everyabt chatturn) fires no handlers — agenton_success/on_failureand runon_start/on_endare 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 atINFO, and--fail-on-handler-error/ABT_HANDLERS_FAIL_FASThave 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 (theabt runexit code is unchanged). - Escalation turns that first-failed record into a parent-run failure with
ok=falseanderror="handler <Class> (<event>) failed: ...". Four switches enable it (most specific wins): --fail-on-handler-erroron the CLI,ABT_HANDLERS_FAIL_FAST=1environment variable,config.handlers.fail_fast: trueinabt.yaml,- per-class
fail_silent = Falseon theHandlersubclass — always escalates that specific handler regardless of any global switch. - Sync
def run(...)implementations run onasyncio.to_threadso they never block the event loop; asyncasync def run(...)methods are awaited directly. Every call is wrapped inasyncio.wait_for(timeout_seconds). - Timeout caveat for sync handlers:
asyncio.wait_forcan only cancel the awaiter — it cannot forcibly stop a Python thread. A sync handler that blocks pasttimeout_secondsis recorded asok=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 asasync def run(...)and use cooperative cancellation (or wrap the blocking call inasyncio.shield-friendly primitives you can cancel). - Every handler invocation lands in the per-run Python log
(
<workspace>/logs/abt.log): successes atDEBUG(handler <Class> ok in <ms>ms (event=..., scope=..., source=...)) and timeouts / exceptions atWARNING. The authoritative per-handler record always lives inrun_results.json → handlers[]regardless of log level. - File writes from handlers belong under
<workspace>/target/— usecontext["abt"].target_dir()(or theABT_TARGET_DIRenv var after the project has loaded). Don't use cwd-relativetarget/…paths; they bypass workspace routing. During--statelessruns, writes go to an auto-created temp workspace (--workspaceis 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 bothon_success/on_failureand 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, orconfig.handlers.fail_fast) to turn a handler failure into anE_HANDLER_FAILEDparent-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.handlerscarries every discovered handler class name with its__init__signature — the same payloadabt list --handlersprints.
Inventory, docs, and diagnostics
abt list --handlersprints every discovered class with its__init__signature so you can see which kwargs are required and their defaults.abt docs generateproduces a Handlers tab in the HTML docs site, including reverse-lookup ("used by which agent").abt doctorincludes thehandler_refs_resolvedrule 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.