Hierarchical states let cancel, deadline and escalation apply to every step of an agent loop, with inner-first overrides and history states for resume.
The same three checks in every step
A typical agent loop has a handful of steps: plan the next action, call a tool, observe the result, decide whether the goal is met. Around those steps sit concerns that apply to all of them. The user can cancel at any moment. The task has a deadline. A policy check can decide that a person must look before the agent continues. When the person approves, the agent should carry on from where it stopped, not start over.
In a loop written as plain code, those concerns end up repeated. Each step checks a cancellation flag, each step compares the clock with the deadline, each step knows how to hand off to a person, and the resume logic has to remember which step was active. Three steps and three cross-cutting events make nine places to get right. The tenth step someone adds next quarter will miss one of them.
Statecharts solved this problem for user interfaces and embedded controllers decades ago. David Harel's 1987 paper introduced hierarchical states, and the W3C SCXML recommendation (2015) gave them precise execution semantics. Two of their ideas fit agent loops closely: a transition declared on a parent state applies to every child, and a history state lets you return to whichever child was active when you left.
What a statechart region gives an agent loop
Put the loop's steps inside one compound state, called working here, with plan, act and observe as children. Declare the cross-cutting transitions once, on working:
cancelgoes tocancelled;deadlinegoes totimed_out;escalategoes toawaiting_human.
Because SCXML selects transitions by looking first at the active atomic state and then at each ancestor in turn, any child that does not handle cancel itself falls through to the parent's rule. Adding a fourth child step inherits all three behaviours without new code.
The inner-first rule also gives you a clean exception mechanism. A child that must react differently declares its own transition for the same event, and it wins. In the companion example, act handles cancel by moving to compensating, because an in-flight tool call may already have changed something that must be undone. A cancel during plan goes straight to cancelled.
Finally, awaiting_human resumes through working.H, a shallow history state. When the agent leaves working for a person's review, the machine records the active child. On resume it re-enters that child: an escalation raised during observe resumes in observe. If working has never been exited, history falls back to its initial child, plan.
The companion example
agent_statechart_region implements those three rules in under 100 lines of standard-library Python. Transitions are a table keyed by state and event; dispatch walks from the current state up through its ancestors and takes the first match; exiting a compound state records its active child.
TRANSITIONS = {
('plan', 'planned'): 'act',
('act', 'tool_ok'): 'observe',
('act', 'cancel'): 'compensating', # inner-first: undo the tool call before stopping
('compensating', 'compensated'): 'cancelled',
('observe', 'need_more'): 'plan',
('observe', 'goal_met'): 'done',
('working', 'cancel'): 'cancelled', # declared once, applies to plan, act and observe
('working', 'deadline'): 'timed_out',
('working', 'escalate'): 'awaiting_human',
('awaiting_human', 'resume'): 'working.H',
('awaiting_human', 'reject'): 'cancelled',
}The scenarios in its tests read like a specification. A deadline in plan, act or observe ends in timed_out. Escalating in act and resuming lands back in act; escalating in observe lands back in observe. Cancelling during act goes through compensating. A deadline that arrives during compensation is ignored, because compensating sits outside working on purpose: the undo must finish. Events after done are ignored and logged.
Running the first example in a review makes the difference visible. The statechart declares three cross-cutting transitions. The equivalent flat loop needs nine, one per step and event, and the count grows with every step added.
Every step against every cross-cutting event
Because the chart is a small table, its behaviour can be enumerated completely and reviewed as one grid. These are the outcomes the companion tests assert, one row per state the loop can be in.
| Current state | cancel | deadline | escalate |
|---|---|---|---|
| plan | cancelled, from the parent rule | timed_out | awaiting_human, resumes in plan |
| act | compensating, then cancelled | timed_out | awaiting_human, resumes in act |
| observe | cancelled, from the parent rule | timed_out | awaiting_human, resumes in observe |
| compensating | ignored and logged | ignored and logged | ignored and logged |
| awaiting_human | ignored and logged | ignored and logged | ignored and logged |
Two cells deserve a deliberate decision rather than a default. Should a deadline still fire while a person is reviewing the case? Here it does not, because the timer belongs to working and stops when the loop is exited; many teams want a separate review deadline on awaiting_human instead. And should a second cancel during compensation do anything? Here it does not, because a half-finished undo is worse than a slow one. Writing the grid down is how those choices get made on purpose.
What stays deterministic and what the agent decides
The statechart is control flow, and it should be entirely deterministic: the states, the transition table, the deadline timer, the escalation policy and the history bookkeeping. It is small enough to test exhaustively and to draw for a reviewer.
The agent produces events inside working: planned, tool_ok, need_more, goal_met. Its judgement decides which event to raise, never which state to enter. A model output that is not a known event for the current state is ignored and logged, not interpreted. That separation is what lets you swap prompts or models without re-validating cancellation and deadline behaviour.
At Belgavi's Book Store, the returns agent runs inside this structure. When Tanishka cancels CASE-5210 while the agent is issuing a store credit, the act state's own cancel rule moves to compensating, which reverses the credit before the case closes. When the same agent hits a policy threshold and escalates, Jenya reviews it, and approval resumes the case in the step that raised the escalation.
Migrating a flat loop
- List the cross-cutting events your loop already handles: cancellation, deadlines, escalation, budget exhaustion, operator pause. Find every place each is checked.
- Name the loop's steps as states and write the transition table for the happy path only.
- Move each cross-cutting check to a single transition on the parent state, and delete the per-step checks.
- For each step, ask whether any cross-cutting event needs different handling there. Those become child transitions that override the parent, such as
acton cancel. - Decide where resume should land, and add a history state rather than storing "last step" by hand.
- Persist the configuration, the current state plus recorded history, with each checkpoint, so a restarted worker resumes the same way a person's approval does.
Durable workflow engines can host this: the statechart becomes the workflow's control logic, and the timers and signals come from the engine. The structure is the same either way.
Trade-offs and failure modes
Statecharts add a concept the team must learn. Shallow versus deep history, inner-first priority and the exit order of nested states are precise but easy to misremember. Keep the hierarchy shallow; two levels cover most agent loops.
A child override can silently disable a safety rule. If act handles cancel and never reaches a terminal state, cancellation is broken only during tool calls. Test every cross-cutting event in every child, as the companion tests do.
History can resume into a step whose assumptions no longer hold. If a person edits the case while it waits, resuming in observe may evaluate a stale result. For those cases, resume to plan explicitly or re-read inputs on entry.
Timers belong to the runtime. A deadline event must be raised by a durable timer that survives restarts, not by a sleep inside the worker process.
When you do not need this
If the agent runs one short step with no cancellation or approval, a statechart is ceremony. If the whole job is a fixed sequence that a workflow engine already expresses with built-in cancellation scopes and timeouts, use those. The pattern pays off when an open-ended loop needs several cross-cutting behaviours and resumability.
Verification checklist
- For every child state and every cross-cutting event, assert the resulting state in a test.
- Assert that terminal states ignore further events and log them.
- Escalate from each step, resume, and assert the step is restored.
- Restart the worker in each state from a persisted configuration and assert identical behaviour.
- Feed an unknown model event in each state and assert it is ignored and logged.