Skip to content
AgenticAIWiki
  1. Learn
  2. Part 8
  3. 44. Hooks and the agent lifecycle
  4. 44.1

Lesson 44.1 · 1 of 4 · 5 min read · Reviewed 24 Nov 2026

Lifecycle events

By the end, you can

  • Name the main lifecycle events an agent emits.
  • Pick the right event for a given control or logging need.

The agent loopAgent loop: The cycle of calling the model, running any tools it requests, returning the results and repeating until it stops. from chapter 42 has natural seams: a session starts, a prompt arrives, a tool is about to run, a tool has run, the agentAgent: A system where a model decides its own next steps, calling tools in a loop until the task is done. stops. A hookHook: Code that runs automatically at a lifecycle event, such as before or after a tool call, to check, block or log it. is your own code attached to one of those seams.

The events

Event Fires when Typical use
SessionStart A session begins or resumes Load project facts into context
UserPromptSubmit The user’s message arrives Add context, reject unsafe prompts
PreToolUse Before a tool call runs Block, allow or ask; edit the input
PostToolUse After a tool call returns Validate output, format code, log
Stop / SubagentStop The agent or a subagent finishes Check the work is really done
PreCompact Before history is summarised Save notes you don’t want lost
Notification The agent needs attention Ping a person
SessionEnd The session closes Clean up, write an audit record

Why hooks matter for architects

A line in the system promptSystem prompt: Instructions passed in the top-level system field that set the model’s role, rules and context for the whole conversation. is a request. A hook is a guarantee. If a rule must hold every single time, such as “never touch the production database” or “always run the formatter after an edit”, it belongs in a hook. Lesson 44.4 makes this choice explicit.

Hooks run in Claude Code (configured in settings.json) and in the Agent SDKClaude Agent SDK: Anthropic’s library for building agents on the same loop that powers Claude Code, with tools, hooks, subagents and MCP. (passed as callbacks). The ideas are the same in both.

Key points

  • Hooks are your code that runs at fixed points in the agent's lifecycle, outside the model.
  • Key events: SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, Stop, SubagentStop, PreCompact, SessionEnd and Notification.
  • Because a hook is code, it runs every time. The model can't forget or talk its way past it.
Hands-on labRuns in the Playground

Wire hooks to lifecycle events

Attach your own code to the right lifecycle events of a simulated agent session.

You will have: A script that registers SessionStart, UserPromptSubmit and PreCompact hooks and prints the event log.

Steps

  1. Run the starter and read the order of events it prints.
  2. Add a SessionStart hook that loads the build command into context once.
  3. Add a UserPromptSubmit hook that adds the on-call engineer to context.
  4. Add a PreCompact hook that saves every 'decided:' line before history is summarised.
  5. Run it again and check the notes survived the summary.

Done when

  • 11 events fire, in the order SessionStart, UserPromptSubmit, PreToolUse, PostToolUse, PreCompact, Stop, SessionEnd.
  • Context holds the build command and the on-call name.
  • 2 decisions are saved before the history is replaced by a summary.

Open in the Playground No API key needed.

Starter code (Python)
# A tiny agent session that fires lifecycle events. Your hooks run at each seam.
HOOKS = {}
log = []
context = []
notes = []


def on(event):
    def register(fn):
        HOOKS.setdefault(event, []).append(fn)
        return fn
    return register


def fire(event, payload):
    for fn in HOOKS.get(event, []):
        fn(payload)
    log.append(event)


# TODO: SessionStart hook: append "Build: make test" to payload["context"] (once per session)
# TODO: UserPromptSubmit hook: append "On call: Priya" to payload["context"]
# TODO: PreCompact hook: copy every history line that starts with "decided:" into payload["notes"]


def run_session():
    fire("SessionStart", {"context": context})
    fire("UserPromptSubmit", {"prompt": "Fix the flaky test", "context": context})
    history = ["decided: retry once", "read file a.py", "decided: keep timeout at 5s"]
    for tool in ["Read", "Edit", "Bash"]:
        fire("PreToolUse", {"tool": tool})
        fire("PostToolUse", {"tool": tool})
    fire("PreCompact", {"history": history, "notes": notes})
    history[:] = ["summary: fixed the flaky test"]   # the details are gone after this
    fire("Stop", {})
    fire("SessionEnd", {})


run_session()
print("events fired:", len(log))
print("order:", " > ".join(dict.fromkeys(log)))
print("context:", context)
print("notes saved:", len(notes), notes)
Show a solution
# A tiny agent session that fires lifecycle events. Your hooks run at each seam.
HOOKS = {}
log = []
context = []
notes = []


def on(event):
    def register(fn):
        HOOKS.setdefault(event, []).append(fn)
        return fn
    return register


def fire(event, payload):
    for fn in HOOKS.get(event, []):
        fn(payload)
    log.append(event)


@on("SessionStart")
def load_project_facts(payload):
    payload["context"].append("Build: make test")


@on("UserPromptSubmit")
def add_on_call(payload):
    payload["context"].append("On call: Priya")


@on("PreCompact")
def save_decisions(payload):
    payload["notes"].extend(h for h in payload["history"] if h.startswith("decided:"))


def run_session():
    fire("SessionStart", {"context": context})
    fire("UserPromptSubmit", {"prompt": "Fix the flaky test", "context": context})
    history = ["decided: retry once", "read file a.py", "decided: keep timeout at 5s"]
    for tool in ["Read", "Edit", "Bash"]:
        fire("PreToolUse", {"tool": tool})
        fire("PostToolUse", {"tool": tool})
    fire("PreCompact", {"history": history, "notes": notes})
    history[:] = ["summary: fixed the flaky test"]   # the details are gone after this
    fire("Stop", {})
    fire("SessionEnd", {})


run_session()
print("events fired:", len(log))
print("order:", " > ".join(dict.fromkeys(log)))
print("context:", context)
print("notes saved:", len(notes), notes)
Quick checkYou want to add today's on-call engineer to the context whenever a user sends a message. Which event fits?
How sure are you?
Pick an answer and how sure you are