Agents are State Machines


Everyone is building “agents” now. But if you look at the agentic work that actually ships in enterprises, very little of it is a chatbot. Most of it looks like this -

  • Something arrives (an email, a document, a ticket)
  • An LLM classifies or extracts something
  • An LLM drafts something, maybe looking things up with a tool or two
  • A human checks it - minutes, hours or days later
  • Then something happens in a real system (an email is sent, a DB is updated, money moves)

That is not a chat, that is a long-running workflow with some LLM steps and a human in the middle. And it brings a bunch of very old problems back -

  • The process must stop and wait (for days) and resume later - even if the worker restarted in between
  • LLM calls are slow, cost money, fail sometimes and are non-deterministic
  • When a customer asks “what happened to my ticket?”, someone needs an answer

In my previous posts I wrote about state machines built with composition, the Result pattern and OpenTelemetry. This post puts all three together - and it turns out they fit agentic workflows really well.

The Demo - A Support Inbox Agent

The demo (code on GitHub) handles the support inbox of an (imaginary) online coffee shop -

  • An email arrives and Claude classifies it - order status, refund, complaint, spam, other
  • For order and refund questions, Claude drafts a reply and can call a lookup_order tool to check the order
  • The draft waits for a human, who approves it or rejects it with feedback (then Claude redrafts)
  • Once approved, the reply is sent and, for refund requests, the refund is issued

The support ticket state machine The happy path runs left to right, error states sit above the step that failed, and a rejected draft loops through REVISION_REQUESTED until it’s approved - or escalated after the second rejection

The State Machine, Revisited

In the 2023 post, a transition was declared with the state it runs in, what it does, and where it goes on success or failure. The demo uses the exact same idea - this is the whole workflow -

export const triageWorkflow = ({ db, claude, model }: TriageDeps) => [
transition({
name: 'ticket.classify',
underCondition: 'RECEIVED',
coreAction: classifyEmail(claude, model),
successTo: routeByClassification, // -> NEEDS_REPLY | CLOSED_SPAM | ESCALATED
errorTo: 'CLASSIFY_FAILED',
}),
transition({
name: 'ticket.draft_reply',
underCondition: ['NEEDS_REPLY', 'REVISION_REQUESTED'],
coreAction: draftReply(claude, model, db),
successTo: 'AWAITING_APPROVAL',
errorTo: 'DRAFT_FAILED',
}),
// ---- the workflow stops here until a human reviews the draft ----
transition({
name: 'ticket.send_reply',
underCondition: 'APPROVED',
coreAction: sendReply(db),
successTo: 'REPLY_SENT',
errorTo: 'SEND_FAILED',
}),
transition({
name: 'ticket.resolve',
underCondition: 'REPLY_SENT',
coreAction: match(resolutionFor, { refund: issueRefund(db) }, keepAsIs),
successTo: 'RESOLVED',
errorTo: 'REFUND_FAILED',
}),
]

Every major decision and code path is in one place, and it reads like the diagram above. A few things changed since 2023 though -

  • The context is immutable. A transition returns a new { state, history, data } instead of mutating a class
  • Core actions return a Result. The services are written exactly like in my Result post - { ok } moves the workflow to successTo, { error } to errorTo. No try/catch anywhere in the business code
  • successTo can be a function. That’s how the classification picks the next state - routeByClassification is a small, pure, trivially testable function
  • match (also from the 2023 post) picks a core action based on the data - only refund requests with an order id issue a refund

Waiting for a Human is Just a State

This is my favourite part. How do we “pause” a workflow for two days? We don’t! We persist the state after every transition -

export const runWorkflow =
<S extends string, D>(transitions: readonly Transition<S, D>[], persist: (workflow: Workflow<S, D>) => Promise<unknown>) =>
(start: Workflow<S, D>): Promise<Workflow<S, D>> =>
transitions.reduce(async (previous, transition) => {
const before = await previous
const after = await transition(before)
if (after !== before) await persist(after)
return after
}, Promise.resolve(start))

After drafting, the ticket is in AWAITING_APPROVAL. No transition matches that state, so the rest of the list simply passes the ticket through and the worker is done. Nothing is running, nothing is waiting in memory.

When the human decides, the API runs the review - which is just another transition -

const reviewTransition = (review: Review) =>
transitionState<TicketState, TicketData>({
name: 'ticket.review',
underCondition: 'AWAITING_APPROVAL',
coreAction: recordReview(review),
successTo: routeReview, // -> APPROVED | REVISION_REQUESTED | ESCALATED
errorTo: 'ESCALATED',
})

… and puts the ticket back on the queue. The worker runs the same list again. Classification and drafting don’t match APPROVED, so they are skipped, and the workflow continues with sending the reply. The guards (underCondition) are what make the workflow resumable - after a human decision, after a deploy, after a crash.

And of course the history tells the whole story of a ticket -

10:18:13 ticket.classify RECEIVED -> NEEDS_REPLY
10:18:15 ticket.draft_reply NEEDS_REPLY -> AWAITING_APPROVAL
10:18:57 ticket.review AWAITING_APPROVAL -> REVISION_REQUESTED
10:18:59 ticket.draft_reply REVISION_REQUESTED -> AWAITING_APPROVAL
10:19:42 ticket.review AWAITING_APPROVAL -> APPROVED
10:19:42 ticket.send_reply APPROVED -> REPLY_SENT
10:19:42 ticket.resolve REPLY_SENT -> RESOLVED

The LLM Steps

The LLM steps are just services returning a Result, nothing special about them. Classification uses structured output - the response is validated against a zod schema by the SDK -

export const ClassificationSchema = z.object({
category: z.enum(['order_status', 'refund', 'complaint', 'spam', 'other']),
urgency: z.enum(['low', 'normal', 'high']),
confidence: z.number().describe('How sure you are about the category, from 0 to 1'),
orderId: z.string().nullable().describe('The order id (a UUID) if the email mentions one, otherwise null'),
summary: z.string().describe('One sentence: what the customer wants'),
})

Note the confidence - anything below 0.7 goes to a human (ESCALATED) instead of an LLM-drafted reply. Cheap guardrail, and it’s just a line in routeByClassification.

Drafting is the “agentic” step - Claude decides whether to call the lookup_order tool, and the SDK’s tool runner runs the loop -

const lookupOrder = (db: Db) =>
betaZodTool({
name: 'lookup_order',
description: 'Look up an order by its id. Returns status, total (in cents) and tracking code.',
inputSchema: OrderLookupSchema,
run: async ({ orderId }) =>
JSON.stringify((await ordersRepo.findById(db, orderId).catch(() => undefined)) ?? { error: `no order ${orderId}` }),
})

One more thing worth saying - the email is customer input. The prompts put it inside <email> tags and tell the model to treat it as data, never as instructions. And the most important prompt-injection defence is the design itself: nothing irreversible happens before a human has approved it.

Seeing It - Tracing Inside the State Machine

As promised in my last post, the tracing goes into transitionState itself -

export const transitionState =
<S extends string, D>(spec: TransitionSpec<S, D>): Transition<S, D> =>
async (workflow) =>
!applies(spec.underCondition, workflow.state)
? workflow
: tracer.startActiveSpan(spec.name, { attributes: { 'workflow.state.from': workflow.state } }, async (span) => {
const result = await runSafely(spec.coreAction, workflow.data)
const moved = next(spec, workflow, result)
span.setAttribute('workflow.state.to', moved.state)
isErr(result) ? markFailed(span, spec.name, result.error) : span.setStatus({ code: SpanStatusCode.OK })
workflowTransitions.add(1, { transition: spec.name, from: workflow.state, to: moved.state })
span.end()
return moved
})

Every transition that runs is a span with its from and to state. Transitions that are skipped create nothing - so the trace shows exactly the path the ticket took, and no noise.

The Claude SDK Traces Itself

The Anthropic SDK has OpenTelemetry built in - it uses whatever tracer provider the app registered (our NodeSDK from the last post), so with zero extra code every model call shows up as an anthropic.messages.create span, nested under our transition, with GenAI semantic convention attributes - model, effort level, input and output tokens. The tool runner and every tool call get their own spans too, with the SQL query of lookup_order nested inside.

I also pass the ticket id as the conversation id, so every LLM call of a ticket - across all its episodes - shares gen_ai.conversation.id -

claude.beta.messages.toolRunner({ ...params }, { openTelemetry: { conversationId } })

By default the SDK exports metadata only - no prompts, no responses. For a support inbox full of names, addresses and order details, that’s exactly the right default. Switching on full content is a deliberate decision you make for debugging, and your tracing backend then stores customer emails under its own retention rules.

Not just Claude - none of this is tied to one LLM provider. The state machine, the Result services and the episode tracing don’t know which model sits behind classifyEmail and draftReply - the LLM calls sit in one small foundational file (plus the tool definition), so moving to OpenAI, Gemini or a local model means rewriting those, not the workflow. The observability carries over too: the GenAI semantic conventions are vendor-neutral, so any SDK or OpenTelemetry instrumentation that follows them produces the same kind of gen_ai.* spans, and the metrics I record myself (gen_ai.client.token.usage, gen_ai.client.operation.duration) use the convention’s names - the dashboard keeps working whichever model you pick.

Episode 1 - the email arrives, gets classified and a reply is drafted Episode 1 - POST /emails on the API, then the worker: ticket.classify and ticket.draft_reply are our transitions, everything anthropic.* comes from the Claude SDK - including the tool runner calling lookup_order (with its SQL query) between two model calls

Don’t Keep a Trace Open for Two Days

In the last post, one trace from the HTTP request to the end of the work was exactly right. Here it isn’t. Look at what happens to a single ticket -

Monday 11:00 email arrives ─► classify ─► draft ─► AWAITING_APPROVAL
... nothing runs for two days ...
Wednesday 13:00 human clicks "approve" ─► send reply ─► issue refund ─► RESOLVED

As one trace, the root span would have to stay open for two days - some process would have to keep it in memory (and lose it on the next deploy), the waterfall would be two days wide with all the real work squashed into two slivers, and most backends would consider the trace finished long before Wednesday anyway. And conceptually, the human’s click isn’t a “child” of the email - it’s a new event.

So each external event - the email arriving, each human review - gets its own, normal trace. I call it an episode. Within an episode, everything works exactly like in the last post (parent / child spans, traceparent through the queue to the worker). Between episodes there is no parent / child relationship, just an OTEL span link - a “see also” pointer from a span in one trace to a span in another. It doesn’t make any trace longer, it just says “this follows from that” -

Trace T1 - episode 1 (Monday, ~6s) Trace T2 - episode 2 (Wednesday, ~20ms)
┌──────────────────────────────┐ ┌───────────────────────────────┐
│ POST /emails │ │ POST /tickets/:id/review │
│ ├ ticket.create │ link │ ├ episode.start ─────────────┼──► T1
│ └ queue.publish │ ◄───────── │ ├ ticket.review │
│ └ ticket.advance │ │ └ queue.publish │
│ ├ ticket.classify │ │ └ ticket.advance │
│ └ ticket.draft_reply│ │ ├ ticket.send_reply │
└──────────────────────────────┘ │ └ ticket.resolve │
└───────────────────────────────┘

To make that work, the ticket row stores two extra columns -

ColumnHoldsUsed for
trace_idsevery episode’s trace id - [T1, T2, ...]support: “show me everything about this ticket”
last_traceparentthe traceparent of the latest episodelinking the next episode back to it

Link up traces with “episodes”:

  • Episode 1 - the email’s API request starts trace T1 as usual. Creating the ticket stores T1’s id in trace_ids and its traceparent in last_traceparent. The worker continues T1 through the queue, stops at AWAITING_APPROVAL, and T1 is complete - after a few seconds
  • Episode 2 - two days later, POST /review arrives without any trace context, so OTEL starts a fresh trace T2 on its own. The first step, episode.start, does three things: link to T1 (read from last_traceparent), append T2 to trace_ids, and overwrite last_traceparent with T2 - so a third episode would link to T2

The link itself is one line of OTEL API -

export const linkTo = (carrier: Carrier | null, attributes: Attributes = {}): void => {
const spanContext = carrier && trace.getSpanContext(propagation.extract(ROOT_CONTEXT, carrier))
if (spanContext) trace.getActiveSpan()?.addLink({ context: spanContext, attributes })
}

What we end up with is a chain (T3 → T2 → T1, a bit like git commits pointing to their parent), an index (trace_ids on the ticket) and a search key (ticket.id on every span). Every trace stays small and readable, and nothing is kept open while a human thinks. “What happened to ticket X?” now has three easy answers - GET /tickets/:id returns its trace ids, the 🔗 in Tempo jumps from one episode to the previous one, or one TraceQL query lists them all -

{ span.ticket.id = "dedc8e0d-42f1-4ff9-8eaf-0d032669e29d" }

Episode 2 - the human approves, the reply is sent Episode 2 - a new trace, started by the human’s review. episode.start carries the span link (🔗) back to episode 1, then ticket.review, ticket.send_reply and ticket.resolve run

Metrics That Matter for Agents

The usual metrics (latency, errors) are still there, but agentic workflows need a few new ones -

  • Approval rate - how often the human approves the draft. This is the quality metric of the agent, measured on real traffic, for free
  • Time to human decision - spoiler: it dwarfs the LLM latency by orders of magnitude. If you want faster resolutions, optimise the review UI, not the prompt
  • Tickets by state - how many tickets are sitting in AWAITING_APPROVAL, how many ended in an error state
  • Tokens and estimated cost per resolved ticket - the number your CFO will ask about. I record the GenAI semconv metrics (gen_ai.client.token.usage, gen_ai.client.operation.duration) and an estimated cost from list prices

As in the last post, the dashboard lives in the repo and is provisioned on startup.

The Support Agent dashboard A real run with Claude - three tickets, one rejected draft (75% approval), humans taking ~25-55 seconds to decide while the LLM takes 2-5 seconds, and $0.06 in total - $0.02 per resolved ticket

Conclusion

An “agent” in production is mostly a workflow - and workflows have been solved for decades. Modelled as a state machine of small composed functions -

  • The LLM steps are just services returning a Result
  • Waiting for a human is just a state, resuming is just running the list again
  • Tracing lives in one function, and the Claude SDK adds its own spans for free
  • Episodes linked by span links make long-running work observable without hour-long traces

None of this needs an agent framework - just functions, composition, and OTEL. We get our simple unit testable and composable functions, a clear “workflow” defined like a flowchart / diagram and the ability to check where any “ticket” is while having dashboards to monitor the whole system as well.

Now go build some agents - ones you can actually see and inspect 🔍