Modeling AI Agents as Finite State Machines
Almost every team's first production AI agent starts as a thirty-line while (!done) loop. You pass a system prompt, a transcript, and a dozen tool schemas to a model, execute whichever tool call comes back, append the result, and repeat until the model emits plain text. That loop is the direct engineering descendant of ReAct, introduced by Yao et al. at ICLR 2023 to interleave verbal reasoning traces with environment actions.1
On a benchmark or a staging demo, an unconstrained loop looks remarkably capable. In production, the failure modes show up as soon as real money, flaky APIs, and adversarial inputs enter the transcript:
- Runaway retries and unbounded token burn. A downstream endpoint returns HTTP 500 or an empty result; the model tweaks one argument and retries thirty times, paying quadratic input-token costs as the transcript balloons.
- Silent policy drift. Rules stuffed into a 2,000-word system prompt degrade as conversation turns accumulate. The model skips a verification step, forgets the second half of a compound request, or calls an irreversible write tool before gathering required inputs.
- Unrecoverable partial side effects. A worker container restarts right after calling
charge_cardorissue_refundand before sending the confirmation email. Restarting from the original user prompt means the stochastic model may take a different branch, double-refunding a customer or leaving two systems permanently out of sync. - Privilege escalation via prompt injection. Because every tool sits in the prompt on every turn, untrusted text read from a support ticket, webpage, or email shares the same execution privilege as the system instructions. One injected directive can trigger a write or exfiltration tool that had no business being callable during read-only investigation.
- Non-reproducible postmortems. When an incident fires, you are left staring at a 35-turn raw message blob trying to figure out which implicit internal "phase" the agent thought it was in when it went off the rails.
This reliability cliff shows up clearly in controlled evaluations. In -bench—published in 2024 by Shunyu Yao (the same first author behind ReAct) and colleagues at Sierra—agents were tested on realistic retail and airline support conversations against real database state and strict policy manuals.2 Even with native function calling, GPT-4o succeeded on roughly 61% of retail tasks and 35% of airline tasks on a single run (). Under their consistency metric—requiring an agent to succeed across independent trials of the same scenario—GPT-4o dropped below 25% by on retail.2 A quarter of retail failures came from breaking explicit domain rules (such as calling a single-use order-exchange tool on one item instead of collecting all requested items first), while another 19% silently dropped part of a compound user request.2
That failure rate comes from an architectural mistake: we handed a stochastic next-token predictor ownership of control flow, authorization, persistence, and termination. Moving those responsibilities out of the prompt and into a finite state machine (and, for real workflows, a statechart) draws a clean line between reasoning and execution.
Formalizing an Agent as a Guarded Transducer
In automata theory, a deterministic finite automaton is a 5-tuple that reads an input string and accepts or rejects it. As Wu et al. observe in StateFlow (COLM 2024), an LLM agent is not a passive language recognizer; it produces external actions and carries structured working memory across turns.3 The right mathematical object is an extended, guarded finite-state transducer:
Each component maps directly onto an engineering primitive in an agent runtime:
- (finite control states): The explicit lifecycle phases of the workflow—for example
INTAKE,INVESTIGATING,AWAITING_APPROVAL,EXECUTING_REFUND,COMPENSATING,RESOLVED,ESCALATED, andFAILED_SAFE. At any moment, the agent occupies a known state rather than an implicit mood inferred from chat history. - (typed extended context): Serializable domain state owned by code—
orderId,refundCents,stepsRemaining,idempotencyKey, verified tool outputs—strictly separated from the raw LLM message log. - (typed input events): Discrete events that trigger transitions. Some events are proposed by the LLM inside a state (
PROPOSE_REFUND,NEED_MORE_INFO); others arrive from the runtime or outside world (TOOL_TIMEOUT,APPROVAL_GRANTED,BUDGET_EXCEEDED). - (output actions): Side effects executed by the runtime on entry, exit, or transition: calling a scoped tool, writing a durable checkpoint, emitting an audit record, or triggering a rollback.
- (guarded partial transition function): Given the current state, context, and incoming event, deterministic code checks whether the transition is defined and whether its guard predicates pass before updating or emitting any action in .
- and : A single unambiguous entry state and an explicit set of terminal states distinguishing clean completion (
RESOLVED) from human handoff (ESCALATED) and safe abort (FAILED_SAFE).
Flat finite state machines work well for a five-state approval flow, then hit a classic wall on real workflows: state explosion. Take ten business stages, cross them with three retry states, an active human-cancellation listener, and a token-budget watchdog, and a flat FSM balloons to states with duplicated timeout and abort edges drawn out of almost every node.
David Harel solved this problem in 1987 with statecharts4—later standardized in W3C SCXML5 and brought into modern TypeScript engineering by XState.6 Four statechart extensions turn flat FSMs into a practical blueprint for production agents:
- Hierarchical (compound) states. Nest fine-grained sub-states (
INVESTIGATING.FETCH_ORDER,INVESTIGATING.VERIFY_POLICY) inside a parent state (INVESTIGATING). A singleBUDGET_EXCEEDEDorUSER_CANCELLEDtransition on the parent catches every child automatically, eliminating duplicate edges. - Orthogonal (parallel) regions. Track independent concerns concurrently without taking their Cartesian product—for instance, running a content-safety or policy monitor alongside an active reasoning region, or managing an approval SLA timer in parallel with notification retries.
- Guards. Pure boolean predicates evaluated over before a transition commits. Guards enforce invariants the model cannot talk its way around: dollar limits, maximum retries, verified user identity, or required evidence fields.
- Explicit
entryandexitactions. Attach setup and teardown invariants to state boundaries rather than individual arrows. EnteringEXECUTING_REFUNDderives an idempotency key and narrows permissions to the payment gateway; exitingEXECUTING_REFUNDdrops write credentials regardless of whether the transition went toRESOLVED,COMPENSATING, orFAILED_SAFE.
The Boundary: Deterministic Runtime vs. Stochastic Model
Once you adopt this formalism, the design rule for every component becomes straightforward: the deterministic state machine owns control flow, persistence, budgets, permissions, and side effects; the LLM acts as a bounded classifier and structured payload generator inside individual states.
| Concern | Deterministic State Machine Runtime | Stochastic LLM (Inside a State) |
|---|---|---|
| Control flow | Defines , legal edges , and terminal set | Proposes a candidate event for the current state |
| Tool access | Mounts only the read/write tools permitted in state | Chooses arguments for mounted tools and synthesizes observations |
| Policy & budgets | Evaluates deterministic guards (spend, retries, dollar caps, auth) | Explains policy decisions to users and drafts structured requests |
| Side effects | Executes writes with idempotency keys, retries, and compensations | Never mutates external systems directly without passing a transition |
| Persistence & pauses | Checkpoints (state, ctx, step) across crashes and human approvals | Stateless per invocation; receives a curated view of ctx |
Five engineering patterns make this separation hold up under production traffic.
1. State-Scoped Tools and Least Privilege by Topology
In a standard ReAct agent, every tool is mounted on turn one. If the agent needs read_support_ticket to understand a complaint and issue_refund to close it, both live in the same tool list while the model ingests untrusted user text. The OWASP Top 10 for LLM Applications flags this exact architecture under LLM06:2025 Excessive Agency, tracing agent compromises to three root causes: excessive functionality, excessive permissions, and excessive autonomy.7
Scoping tools to states eliminates excessive functionality by construction. In INVESTIGATING, the runtime passes only read-only tools (get_order, get_shipment_status, lookup_policy). The payment refund tool is absent from both the prompt schema and the state's dispatch table; even a textbook indirect prompt injection embedded in a customer's shipping note cannot invoke a tool that does not exist in INVESTIGATING.
Control-flow isolation alone is not the whole security story, however. As Debenedetti et al. demonstrate in CaMeL (Defeating Prompt Injections by Design, 2025), locking down which operations run stops control-flow hijacking, yet an attacker can still poison data flow—manipulating a tool's arguments (such as swapping a recipient email or inflating a refund amount) even along a legal execution path.8 CaMeL addresses this by tracking data provenance and enforcing capability policies when tools execute, solving 77% of AgentDojo benchmark tasks with provable policy guarantees compared to 84% for an undefended baseline.8 In an FSM agent, the equivalent defense pairs state-scoped toolsets with deterministic guards that cross-check LLM-proposed event payloads against trusted fields in ctx—for example, rejecting any refund event whose orderId or amountCents does not match the verified order record fetched from the database.
Shrinking toolsets and prompts per state also pays an immediate accuracy and cost dividend. In StateFlow, Wu et al. modeled multi-step SQL, Bash, and household-planning workflows as explicit finite state machines separating process grounding (states and transitions) from sub-task solving (state-specific prompts and tools).3 On GPT-3.5, StateFlow outperformed ReAct by 13 percentage points on InterCode SQL and 28 percentage points on ALFWorld while cutting LLM inference cost by and respectively.3
2. Constrained Event Emission and Deterministic Guards
Inside a state, the model should never return freeform prose that a fragile regex tries to route. Instead, each state defines the exact discriminated union of events the model is allowed to propose, enforced at decoding time via structured outputs. Willard and Louf formalized this mechanism in Outlines (2023), showing how regular expressions and context-free grammars compile into an FSM index over the model's vocabulary that masks invalid tokens in average time per decoding step.9
Constrained decoding guarantees syntactic validity: the model can only emit a legal event shape for state . Deterministic guards then enforce semantic and policy validity before the transition commits. Research frameworks like AgentSpec (Wang, Poskitt, and Sun; ICSE '26) generalize this idea into a runtime enforcement DSL of (trigger, predicate, enforcement) rules that inspect proposed actions in milliseconds—blocking over 90% of unsafe code executions in evaluation and enforcing 100% compliance across tested autonomous-driving law-violation scenarios.10 In an application-specific FSM, those predicates live right on the transition table where engineers already read and review code.
3. A Concrete Guarded Machine in TypeScript
You do not need a heavy abstraction layer to build this. Here is a stripped-down, realistic TypeScript implementation of a refund-resolution agent that enforces state-scoped tools, typed events, monetary approval guards, step budgets, and explicit compensation states:
export type AgentState =
| 'INVESTIGATING'
| 'AWAITING_APPROVAL'
| 'EXECUTING_REFUND'
| 'COMPENSATING'
| 'RESOLVED'
| 'ESCALATED'
| 'FAILED_SAFE'
export type TerminalState = 'RESOLVED' | 'ESCALATED' | 'FAILED_SAFE'
export interface AgentContext {
readonly runId: string
readonly orderId: string
readonly verifiedOrderTotalCents: number | null
readonly requestedRefundCents: number | null
readonly stepsRemaining: number
readonly paymentRefundId: string | null
readonly evidence: readonly string[]
readonly reason: string | null
}
export type AgentEvent =
| { type: 'EVIDENCE_FOUND'; orderTotalCents: number; summary: string }
| { type: 'PROPOSE_REFUND'; amountCents: number; rationale: string }
| { type: 'APPROVAL_GRANTED'; approverId: string }
| { type: 'APPROVAL_DENIED'; approverId: string; note: string }
| { type: 'REFUND_COMMITTED'; paymentRefundId: string }
| { type: 'DOWNSTREAM_SYNC_FAILED'; error: string }
| { type: 'COMPENSATION_DONE' }
| { type: 'BUDGET_EXCEEDED' }
| { type: 'FATAL_ERROR'; error: string }
const AUTO_APPROVE_LIMIT_CENTS = 25_000 // $250.00 hard policy ceiling
// Capability scoping: write tools are physically absent during investigation.
export const TOOLS_BY_STATE: Record<AgentState, readonly string[]> = {
INVESTIGATING: ['get_order', 'get_shipment_status', 'lookup_policy'],
AWAITING_APPROVAL: [], // Suspended on human signal; zero model calls
EXECUTING_REFUND: ['issue_refund', 'notify_customer'],
COMPENSATING: ['void_refund', 'open_ops_ticket'],
RESOLVED: [],
ESCALATED: [],
FAILED_SAFE: [],
}
export interface TransitionResult {
nextState: AgentState
nextCtx: AgentContext
effects: readonly string[]
}
export function isTerminal(state: AgentState): state is TerminalState {
return state === 'RESOLVED' || state === 'ESCALATED' || state === 'FAILED_SAFE'
}
export function transition(
state: AgentState,
ctx: AgentContext,
event: AgentEvent,
): TransitionResult {
// Parent-level guards: budget exhaustion and fatal errors apply to any active state
if (!isTerminal(state)) {
if (event.type === 'BUDGET_EXCEEDED') {
return {
nextState: 'ESCALATED',
nextCtx: { ...ctx, reason: 'Step budget exhausted before resolution' },
effects: ['checkpoint', 'emit_escalation_ticket'],
}
}
if (event.type === 'FATAL_ERROR') {
return {
nextState: 'FAILED_SAFE',
nextCtx: { ...ctx, reason: event.error },
effects: ['checkpoint', 'page_oncall_summary'],
}
}
}
switch (state) {
case 'INVESTIGATING': {
if (event.type === 'EVIDENCE_FOUND') {
return {
nextState: 'INVESTIGATING',
nextCtx: {
...ctx,
verifiedOrderTotalCents: event.orderTotalCents,
stepsRemaining: ctx.stepsRemaining - 1,
evidence: [...ctx.evidence, event.summary],
},
effects: ['checkpoint'],
}
}
if (event.type === 'PROPOSE_REFUND') {
// Data-flow guard: cannot refund without verified order total or over order value
if (
ctx.verifiedOrderTotalCents === null ||
event.amountCents <= 0 ||
event.amountCents > ctx.verifiedOrderTotalCents
) {
return {
nextState: 'ESCALATED',
nextCtx: {
...ctx,
reason: 'Proposed refund failed order-total invariant check',
},
effects: ['checkpoint', 'emit_escalation_ticket'],
}
}
// Monetary guard: high-value refunds must route through human approval
if (event.amountCents > AUTO_APPROVE_LIMIT_CENTS) {
return {
nextState: 'AWAITING_APPROVAL',
nextCtx: {
...ctx,
requestedRefundCents: event.amountCents,
reason: event.rationale,
},
effects: ['checkpoint', 'request_human_approval'],
}
}
return {
nextState: 'EXECUTING_REFUND',
nextCtx: {
...ctx,
requestedRefundCents: event.amountCents,
reason: event.rationale,
},
effects: ['checkpoint'],
}
}
break
}
case 'AWAITING_APPROVAL': {
if (event.type === 'APPROVAL_GRANTED') {
return {
nextState: 'EXECUTING_REFUND',
nextCtx: { ...ctx, reason: `Approved by ${event.approverId}` },
effects: ['checkpoint'],
}
}
if (event.type === 'APPROVAL_DENIED') {
return {
nextState: 'RESOLVED',
nextCtx: {
...ctx,
reason: `Denied by ${event.approverId}: ${event.note}`,
},
effects: ['checkpoint', 'send_denial_notice'],
}
}
break
}
case 'EXECUTING_REFUND': {
if (event.type === 'REFUND_COMMITTED') {
return {
nextState: 'RESOLVED',
nextCtx: { ...ctx, paymentRefundId: event.paymentRefundId },
effects: ['checkpoint', 'send_confirmation_email'],
}
}
if (event.type === 'DOWNSTREAM_SYNC_FAILED') {
return {
nextState: 'COMPENSATING',
nextCtx: { ...ctx, reason: event.error },
effects: ['checkpoint', 'rollback_partial_refund'],
}
}
break
}
case 'COMPENSATING': {
if (event.type === 'COMPENSATION_DONE') {
return {
nextState: 'FAILED_SAFE',
nextCtx: ctx,
effects: ['checkpoint', 'page_oncall_summary'],
}
}
break
}
}
throw new Error(`Illegal transition: cannot handle ${event.type} in state ${state}`)
}Notice what happens when you read that file in a pull request. You do not have to guess whether an agent can skip human sign-off on a $400 refund, whether an unverified order total can reach the payment gateway, or whether a crash during EXECUTING_REFUND leaves an unhandled exception. Every invariant is visible in one pure function, and every illegal (state, event) pair fails loudly instead of silently hallucinating forward.
4. Durable Execution and Idempotent Side Effects
Because the machine's entire control state reduces to a compact serializable tuple (runId, step, state, ctx), persistence stops being an afterthought. After each transition, the runner checkpoints the tuple before executing the next state's effects:
async function stepRunner(runId: string, resumedEvent?: AgentEvent) {
let { state, ctx, step } = await store.loadLatestCheckpoint(runId)
let pendingEvent = resumedEvent
while (!isTerminal(state)) {
if (state === 'AWAITING_APPROVAL' && !pendingEvent) {
return // Suspended until an external approval webhook supplies an event
}
const event =
pendingEvent ??
(ctx.stepsRemaining <= 0
? ({ type: 'BUDGET_EXCEEDED' } as const)
: await runStateHandler(state, ctx, {
allowedTools: TOOLS_BY_STATE[state],
idempotencyKey: `${runId}:${state}:${step}`,
}))
pendingEvent = undefined
const { nextState, nextCtx, effects } = transition(state, ctx, event)
step += 1
await store.saveCheckpoint({ runId, step, state: nextState, ctx: nextCtx, event })
await executeEffects(effects, nextCtx, `${runId}:effect:${step}`)
state = nextState
ctx = nextCtx
}
}Look closely at AWAITING_APPROVAL and idempotencyKey. When the agent enters AWAITING_APPROVAL, the worker exits cleanly and releases memory; a human reviewer can approve the ticket three hours or three days later via webhook, waking the machine from the exact checkpoint. And if the worker process dies mid-call during EXECUTING_REFUND, the retried call passes the identical idempotencyKey (${runId}:EXECUTING_REFUND:${step}) so the payment gateway deduplicates the refund instead of double-paying.
This checkpoint-and-replay architecture is exactly what modern durable execution engines automate under the hood:
- Temporal separates deterministic Workflow orchestration from non-deterministic Activities (LLM calls, tool invocations, external APIs). As Temporal engineers Mason Egger and Steve Androulakis emphasize, durable agents are deterministic in execution—given the same recorded Event History of Activity results, replay follows the exact same transitions after a crash—without being predetermined, because the LLM still chooses dynamic paths at runtime.11 Temporal already runs high-volume production coding agents including OpenAI's Codex web agent and Replit's Agent 3.11
- Restate runs a single-binary distributed execution log that journals every LLM call and tool step, supports durable sleep for human approvals, enforces concurrency ceilings, and provides built-in saga compensation primitives for rolling back earlier steps when later steps fail.12
- DBOS embeds durable execution as an in-process library backed directly by PostgreSQL, checkpointing workflow inputs and step outputs in database tables without requiring a separate orchestrator cluster—explicitly relying on the same two invariants: deterministic workflow orchestration and idempotent steps.13
- LangGraph models agents as stateful graphs paired with thread-scoped checkpointers (
SqliteSaver,PostgresSaver) for fault tolerance, time-travel replay, and human-in-the-loop interrupts alongside cross-thread stores for long-term memory.14
Whichever runtime you choose—a custom Postgres table, XState persisted to a database, LangGraph, DBOS, Restate, or Temporal—the underlying contract is identical: isolate stochastic model calls inside checkpointed boundaries, and keep transition logic pure and deterministic.
5. First-Class Failure States and Deterministic Testing
Naive loops treat errors as strings appended back into the chat history ("Error: stripe timeout, try again"), hoping the model invents a safe recovery plan. A state machine treats abnormal paths—AWAITING_APPROVAL, COMPENSATING, ESCALATED, FAILED_SAFE—as first-class citizens of . When escalation fires, the human operator receives a structured AgentContext snapshot showing verified evidence, the guard that tripped, and the step count, rather than having to reconstruct intent from raw prompt logs.
Even better, decoupling transition() from LLM inference restores normal software testing:
- Unit and property testing: Drive
transition()directly with synthetic events in milliseconds. Assert that no sequence of events can reachEXECUTING_REFUNDwithrequestedRefundCents > 25_000without first passing throughAPPROVAL_GRANTED. - Static graph verification in CI: Treat the transition table as a directed graph and check reachability automatically—every non-terminal state must have a bounded path to , no unreachable orphan states, and no cycles without a strictly decreasing budget counter in
ctx. - Offline trace replay: Because every production run logs its sequence of
(state, event)pairs, you can replay 500 historical incidents against updated guards or a newly prompted state handler without touching a live payment or email API.
Where Fine-Grained State Machines Break: The Hierarchical Hybrid
None of this means you should flatten every AI product into a rigid twenty-node state diagram.
In Anthropic's December 2024 engineering guide, "Building effective agents," the authors draw a sharp line between workflows (LLMs and tools orchestrated through predefined code paths) and agents (LLMs dynamically directing their own tool loops based on environment feedback).15 Workflows win on predictability and consistency when subtasks are well-defined. Open-ended problems—fixing an unfamiliar bug across twelve files on SWE-bench, or conducting open-ended technical research where the next query depends on what the previous document revealed—break if you try to hardcode every micro-step into a rigid state graph.15
When teams over-apply flat FSMs to exploratory tasks, they end up recreating a brittle expert system in TypeScript: fifty micro-states, awkward fallback edges, and a model constantly fighting the harness because reality didn't match step 4B of the flowchart.
The architecture that holds up across both deterministic business workflows and open-ended reasoning tasks is the hierarchical hybrid statechart:
- Outer layer (coarse-grained deterministic FSM): Owns governance, macro-phases, permissions, spend/step budgets, persistence, human checkpoints, and rollback. Typical outer states look like
PLAN -> EXPLORE_AND_DRAFT -> VERIFY -> AWAITING_APPROVAL -> COMMIT -> DONE, wrapped in a parent state that catchesBUDGET_EXCEEDED,POLICY_VIOLATION, andUSER_ABORT. - Inner layer (bounded agentic loop): Inside specific safe states—such as
EXPLORE_AND_DRAFTorINVESTIGATING—let the model run a free-flowing ReAct loop with dynamic tool selection. The inner loop stays strictly sandboxed: read-only or ephemeral-container tools only, a hard cap on iterations and tokens, and a single legal exit contract—emitting a typed event back up to the outer machine.
| Task Profile | Recommended Topology | Why |
|---|---|---|
| Single extraction, classification, or summarization | Single prompt + schema validation | Adding state machinery adds latency and boilerplate without value15 |
| Regulated business ops (refunds, KYC, billing, access changes) | Fine-grained FSM / statechart | Every write, approval gate, and rollback must be auditable and guarded |
| Software engineering, incident triage, deep research with real side effects | Hierarchical hybrid (coarse outer FSM + bounded inner agent loops) | Preserves model adaptability during exploration while locking down verification, approval, and commit |
| Ephemeral, fully sandboxed exploratory scratchpad | Bounded ReAct loop with hard step/cost caps | Blast radius is zero; fast iteration matters more than transition formality |
Look at how a serious production coding agent actually works under the hood. During EXPLORE_AND_EDIT, the model freely searches files, reads logs, edits code, and runs local tests inside an isolated sandbox. It cannot force-push to main or deploy to production from that state. When it believes the patch is ready, it emits PATCH_READY, transitioning the outer machine into a deterministic VERIFY state that runs the real CI suite, security scanners, and diff checks without asking the model's opinion. Only if deterministic verification passes does the outer machine advance to AWAITING_APPROVAL and, after human sign-off, COMMIT.
Put the State Where You Can Audit It
Language models are remarkably capable local reasoning engines and notoriously unreliable distributed systems coordinators. Asking a prompt to track multi-step workflow invariants, enforce authorization boundaries, manage crash recovery, and stop cleanly under failure guarantees fragile software.
Finite state machines and statecharts put both halves back where they belong. Let the model absorb ambiguity inside a state—reading messy inputs, choosing read-only queries, synthesizing evidence, proposing structured next events. Let deterministic, typed code own everything around it: which transitions are legal, which tools exist at each step, when a human must sign off, how crashes replay, and how partial writes unwind. When an agent wakes someone up at 3 a.m., you want to inspect a state table and an event log, not psychoanalyze a 35-turn chat transcript.
Footnotes
-
Shunyu Yao, Jeffrey Zhao, Dian Yu, Nan Du, Izhak Shafran, Karthik Narasimhan, and Yuan Cao, ReAct: Synergizing Reasoning and Acting in Language Models, International Conference on Learning Representations (ICLR 2023), arXiv:2210.03629. ↩
-
Shunyu Yao, Noah Shinn, Pedram Razavi, and Karthik Narasimhan, -bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains, Sierra (June 2024), arXiv:2406.12045 — introduces the reliability metric and documents GPT-4o function-calling scoring ~61% on -retail (~35% on -airline), dropping below 25% on in retail, with 25% of retail failures from policy/decision errors and 19% from partial resolution of compound requests. ↩ ↩2 ↩3
-
Yiran Wu, Tianwei Yue, Shaokun Zhang, Chi Wang, and Qingyun Wu, StateFlow: Enhancing LLM Task-Solving through State-Driven Workflows, Conference on Language Modeling (COLM 2024), arXiv:2403.11322 — models LLM workflows as a transducer FSM , outperforming ReAct by 13% on InterCode SQL and 28% on ALFWorld with and lower LLM inference cost respectively. ↩ ↩2 ↩3
-
David Harel, Statecharts: A visual formalism for complex systems, Science of Computer Programming, Vol. 8, Issue 3 (June 1987), pp. 231–274 — introduces hierarchical (compound) states, orthogonal concurrent regions, guards, and broadcast communication to overcome flat FSM state explosion. ↩
-
World Wide Web Consortium (W3C), State Chart XML (SCXML): State Machine Notation for Control Abstraction, W3C Recommendation (September 1, 2015). ↩
-
Stately / XState Documentation, What are state machines? States, events, and transitions — TypeScript implementation of Harel statecharts and the actor model. ↩
-
OWASP GenAI Security Project, LLM06:2025 Excessive Agency, OWASP Top 10 for Large Language Model Applications (2025) — categorizes agentic vulnerability root causes into excessive functionality, excessive permissions, and excessive autonomy. ↩
-
Edoardo Debenedetti, Ilia Shumailov, Tianqi Fan, Jamie Hayes, Nicholas Carlini, Daniel Fabian, Christoph Kern, Chongyang Shi, Andreas Terzis, and Florian Tramèr, Defeating Prompt Injections by Design, Google / Google DeepMind / ETH Zurich (2025), arXiv:2503.18813 — introduces CaMeL, separating control and data flows with capability-based policy enforcement (77% AgentDojo task completion with provable security vs. 84% undefended). ↩ ↩2
-
Brandon T. Willard and Rémi Louf, Efficient Guided Generation for Large Language Models, Normal Computing (July 2023), arXiv:2307.09702 — formulates constrained token generation via FSM-indexed vocabulary masks with average per-token overhead, implemented in Outlines. ↩
-
Haoyu Wang, Christopher M. Poskitt, and Jun Sun, AgentSpec: Customizable Runtime Enforcement for Safe and Reliable LLM Agents, Singapore Management University (2025; accepted at ICSE '26), arXiv:2503.18666 — enforces
(trigger, predicate, enforcement)runtime rules with millisecond overhead, preventing >90% of unsafe code executions on RedCode-Exec and enforcing 100% traffic-law compliance on tested FixDrive scenarios. ↩ -
Mason Egger and Steve Androulakis, Of course you can build dynamic AI agents with Temporal, Temporal Blog (November 12, 2025) — explains deterministic Workflow replay over non-deterministic LLM/tool Activities and notes production adoption by OpenAI's Codex web agent and Replit's Agent 3. ↩ ↩2
-
Restate Documentation, Use Cases: AI Agents — details durable step journaling, idle suspension for human-in-the-loop approvals, flow control, and compensation patterns. ↩
-
DBOS Documentation, DBOS Architecture — describes PostgreSQL-backed durable workflow checkpointing and recovery built on deterministic workflows and idempotent steps. ↩
-
LangChain Documentation, LangGraph Persistence — documents thread-scoped checkpointers (
InMemorySaver,SqliteSaver,PostgresSaver) for fault tolerance, time travel, and human-in-the-loop interrupts alongside cross-thread stores. ↩ -
Anthropic Engineering, Building effective agents (December 19, 2024) — distinguishes predefined-path workflows from model-directed autonomous agents and outlines compositional patterns (prompt chaining with gates, routing, parallelization, orchestrator-workers, evaluator-optimizer). ↩ ↩2 ↩3