This page covers in-process lifecycle hooks (SETUP, SESSION_START, BEFORE_AGENT, etc.) that fire inside a running agent. For HTTP inbound triggers that start agent runs from external services via
POST /hooks/<path>, see Gateway Inbound Hooks.How It Works
Lifecycle Events
Quick Start
1
Import Hook Components
2
Register a Hook
3
Use with Agent
Core Events
Tool Events
BEFORE_TOOL and AFTER_TOOL fire on both sync (chat) and async (achat) paths. A blocking BEFORE_TOOL hook returning HookResult.block(reason=...) prevents tool execution on either path — use it for security gates without worrying which entrypoint the caller uses.Tool Definition Events
BEFORE_TOOL_DEFINITIONS lets you shape the tool list the LLM actually sees — without changing the agent’s permanent tool registration. Mutate tool_definitions in place; the runtime only adopts in-place mutations.
BeforeToolDefinitionsInput Fields
model field:
Agent Events
LLM Events
Session Events
Bot runtime semantics: In the bot runtime (
BotOS), SESSION_START fires exactly once per user session lifetime — on the first message, not on every message. SESSION_END fires when the user sends /new, when a policy auto-reset triggers, when stale sessions are reaped, or on reset_all. The reason field on SessionEndInput is one of clear, policy, stale, or clear_all.Error Events
Async vs Sync
ON_RETRY fires on both sync and async retry paths. If you register the handler as a regular def, it is dispatched in a thread executor on the async path; if you register an async def, it is awaited directly. Either form is safe on both paths.
Retry is on by default, so
ON_RETRY fires with no config needed on both the native OpenAI-client path and the LiteLLM path (default max_retries=3). It only stops firing if you disable retry with retry=False. See Agent Retry.Released in PraisonAI #2386 — earlier versions skipped this event on the async path.
OnRetryInput Fields
TheOnRetryInput event includes both new tool-specific fields and legacy fields for backward compatibility:
New fields (recommended):
tool_name: Name of the failing toolattempt: Current attempt number (1-based)max_attempts: Maximum attempts configureddelay_ms: Delay before this retry in millisecondserror_type: Classified error type (timeout,rate_limit,connection_error,unknown)error: Original exception object
RetryBackoffConfig() policy applied to every Agent — see Agent Retry). ON_RETRY now fires on default Agents too; pass retry=False to disable retries and stop these fires:
delay_seconds: Seconds the agent will sleep before the next attemptattempt: Current attempt number (0-based)operation:"llm_request"(sync) or"async_llm_request"(async)error_message: String representation of the failingLLMErrormax_retries: ConfiguredRetryBackoffConfig.max_retriesretry_count: Same asattempt + 1(1-based legacy alias)
retry_count: Same asattemptmax_retries: Same asmax_attemptserror_message: String representation oferror
Agent-Level Error Callbacks
In addition to hook events, agents support a directon_error callback for LLM failures:
Hook Events vs Agent Callbacks
Extended Events
User Interaction Events
Subagent Events
System Events
Plugin persisters subscribe to
AFTER_COMPACTION to read event_data.summary. See Compacted Session Resume for the built-in checkpoint that ships with PraisonAI, and Context Compaction for the full CompactionResult fields.Message Events
MESSAGE_RECEIVED is a first-class control point: hooks can drop an inbound message so the agent never runs, or rewrite the message content before the agent (or memory) sees it. This is symmetric with MESSAGE_SENDING on the outbound side.
The hook now returns a decision that every platform adapter (Telegram, Slack, Discord, WhatsApp, Email, AgentMail) honours:
HookResult.deny(reason=...)→ the message is dropped; agent dispatch is skipped entirely.HookResult(modified_input={"content": "..."})→ the inbound message content is rewritten before dispatch.NoneorHookResult.allow()→ message passes through unchanged (default).- Hook errors are non-fatal — a raising hook logs the error and lets the message through.
MESSAGE_RECEIVED and MESSAGE_SENDING are the two message-lifecycle events that do gate — deny drops the message entirely, modified_input["content"] rewrites it. The gate is safe from both sync and async adapters (Telegram, Slack, Discord, WhatsApp, Email, AgentMail) — no async def required in your hook. See PraisonAI #2589.Drop / block an inbound message
Redact PII before the agent sees it
Authorise sender against an allowlist
How the gate applies decisions
When multiple
MESSAGE_RECEIVED hooks run, the last matching modification wins. Hook errors are non-fatal — the message passes through unchanged.MESSAGE_UNDELIVERED — close the loop on a permanent failure
Fires when the gateway’s DeliveryRouter classifies a send as permanently failed. Observability only — the hook does not gate anything.
gateway.notify_on_undelivered config.
Gateway Events
Schedule & background events
Schedule hooks fire when scheduled jobs are managed and triggered byBotOS. JOB_COMPLETED fires when a background subagent job launched via spawn_subagent(background=True) reaches a terminal state — after the internal on_complete callback runs, best-effort (a raising handler cannot crash the worker).
Background Job Events
JOB_COMPLETED fires when a background job reaches a terminal state (COMPLETED or FAILED). It fires after the internal on_complete callback runs — a raising handler cannot crash the worker.
JobCompletedInput Fields
Typical uses:
- Observability and metrics on background job durations and failure rates
- Custom delivery routing when the built-in
deliver=token is insufficient - External side effects on completion (webhooks, database writes)
Storage Events
CLI Backend Events
CLI_BACKEND_EXECUTE fires on both success and failure, so subprocess startup errors and timeouts stay traceable — the payload’s error field carries the exception message on the failure path.
This hook is observe-only — it cannot gate the CLI backend call. Return
HookResult.allow() (or return nothing). For a policy gate on tool use, register on BEFORE_TOOL instead.CliBackendExecuteInput Fields
Two safety mechanisms apply at
to_dict() time (the payload that reaches log sinks): prompt/system values that follow -p, --prompt, -i, --input, -m, --message, --system are replaced with "<redacted>", and content is truncated to the first 500 characters. The live in-memory command field is left untouched — only the serialised payload is redacted.Trace CLI delegation programmatically
Enable the built-in tracer plugin
Thecli_backend_tracer plugin from praisonai-plugins is the batteries-included consumer of this hook — it logs every delegation to the standard praisonai logger. Enable it with one env var and a plugin toggle:
codex exec / grok -p / gemini -p / claude delegation appears in the log stream, with the prompt value already redacted.
What gets masked
redact_command masks the value that follows these flags, leaving the flag itself visible for verification:
Non-list
command values (already-serialised strings, None) pass through unchanged.
Kanban Events
When a task with
workspace_kind="worktree" fails to merge cleanly, KANBAN_TASK_BLOCKED fires with conflicted_files: list[str] in the payload so alerting agents can surface the exact merge conflict. See Kanban → Per-Task Worktree Isolation.Preserved worktree comments (not a hook — a task comment). A clean-merge task may also carry a
worktree_preserved at <path>: <reason> comment when the dispatcher’s lossless guard refuses to tear down a worktree with uncommitted changes or unmerged commits (or when git worktree remove itself fails). No hook fires — poll for the comment via kanban_show(task_id) if you need to alert on it. See Kanban → Lossless-only worktree teardown.Dependency Auto-Promotion Events
When the dispatcher auto-promotes a child task,KANBAN_TASK_MOVED fires with this payload:
Auto-promotion events do not include
from_status. Check for its absence if you need to distinguish auto-promotions from manual moves.Complete Event Reference
Bot Runtime Lifecycle
Gateway and session hooks are emitted byBotOS and BotSessionManager — no extra wiring needed when your agent is passed to a bot.
- All emission is best-effort and a no-op when no hooks are registered (zero overhead)
BEFORE_AGENT/AFTER_AGENTare fired byagent.chat()itself — they are not re-fired at the gateway boundary to avoid double-dispatch- In async contexts (e.g. inside
BotSessionManager.chat), emission is fire-and-forget; in sync contexts it is blocking
MESSAGE_RECEIVED and MESSAGE_SENDING are policy gates, not passive observers. deny drops the message; modified_input["content"] rewrites it. Gateway/session lifecycle events (GATEWAY_START, GATEWAY_STOP, SESSION_START, SESSION_END) remain best-effort observability points and do not gate startup or shutdown. CLI_BACKEND_EXECUTE is also observe-only — it is orthogonal to the message gates and cannot stop the CLI delegation; it only reports that a subprocess turn happened.Best Practices
Keep hooks lightweight
Keep hooks lightweight
Hooks run synchronously. Avoid heavy operations that could slow down agent execution.
Use matchers for filtering
Use matchers for filtering
Use pattern matchers to only run hooks for specific tools or operations.
Return early
Return early
Return
HookResult.allow() quickly for non-matching cases to minimize overhead.Handle errors gracefully
Handle errors gracefully
Wrap hook logic in try/except to prevent breaking agent execution.
Related
Inbound Message Gate
Drop or redact incoming messages before the agent sees them
Hooks
Hook system overview
Kanban Tasks
Kanban hook events and lifecycle
Plugins
Plugin system with hooks

