Stately
PackagesAgent

Agent patterns

Common agent patterns (ReAct, reflection, plan-and-execute, RAG, supervisor, and more) as copy-paste XState machines you can run in 60 seconds.

Alpha: @statelyai/agent 2.0 is in alpha. APIs can change between releases; pin an exact version. Feedback: github.com/statelyai/agent.

Every well-known agent pattern is a control-flow shape: a loop, a branch, a fan-out, a handoff. This library makes each one an explicit XState machine you can read, test, and run. Below is a use-case map: pick a pattern, open its example, copy the one file.

Copy-paste in 60 seconds

Each pattern is a single self-contained index.ts — no shared harness, no local imports. To lift one:

  1. Copy the one example file into your project as index.ts.

  2. Install the runtime deps (the provider package major must match your installed ai major — this repo is on ai@6, so @ai-sdk/openai@3, not 4):

    pnpm add @statelyai/agent@2.0.0-alpha.10 ai@^6 zod@^4 xstate@6.0.0-alpha.21 @ai-sdk/openai@^3
    pnpm add -D @types/node typescript tsx
  3. The examples use Node globals (process, console, import.meta.url), so give TypeScript a tsconfig.json with "types": ["node"]:

    {
      "compilerOptions": {
        "module": "nodenext",
        "moduleResolution": "nodenext",
        "target": "es2022",
        "strict": true,
        "types": ["node"]
      }
    }
  4. Run it: OPENAI_API_KEY=... npx tsx index.ts (or swap in any host).

Peer ranges (from @statelyai/agent): ai@^6.0.67, xstate@>=6.0.0-alpha.16 <6.0.0, zod@^3.25 || ^4. @statelyai/agent is alpha — pin the exact version.

Every example is dual-mode: run it directly against a real model, or drive it with injected mock executors in a test (no key, no network). Swap the host without touching the machine (see Eject to your stack).

Reasoning and tool loops

PatternWhat it's forExampleWhat the machine buys you
ReActReason then act, one tool call at a time, until an answerreact-agentA step-budget guard bounds the loop; the reason-or-act choice is a typed discriminated union, not free text
Tool callingModel selects a tool, typed actors execute ittool-callingTool dispatch is explicit states; progress reports through transitions
Plan-and-executePlan the steps up front, then execute eachplan-and-executePlanner output is structured; execution states iterate the plan (the ReWOO evidence-map idea)
ReflectionGenerate, critique, revise until good enoughreflection-writerThe generate ↔ reflect loop is two states; a guard caps revisions so it can't spin forever
Evaluator-optimizerScore an output, optimize, repeat to thresholdai-sdk-evaluator-optimizerThe scoring gate is a guard; the loop terminates by construction

Retrieval

PatternWhat it's forExampleWhat the machine buys you
RAGRetrieve, then answer grounded in the resultsragRetrieve and answer are separate typed states; conversational memory lives in context
Corrective RAG (CRAG)Grade retrieved docs, re-query or fall back when they're weakcorrective-ragSelf-correction is explicit branch states, not buried conditionals
SQL agentGenerate a query, run it, synthesize an answersql-agentQuery generation, DB execution, and synthesis are separate states you can test in isolation

Routing and chaining

PatternWhat it's forExampleWhat the machine buys you
RoutingClassify the input, dispatch to a specialized pathai-sdk-routingThe route is a decision over legal events; each branch is its own state
Prompt chainingRun steps in a fixed sequenceai-sdk-marketing-chainThe chain is a linear state sequence; each link is independently typed and inspectable
TriageClassify a ticket into structured fieldstriageStructured output validated against a schema before it leaves the state

Multi-agent

PatternWhat it's forExampleWhat the machine buys you
SupervisorA router dispatches to one of several specialist workerssupervisorThe routing request's structured output hands off to a typed worker; the graph is the org chart
Swarm handoffSpecialists hand the conversation off to each other across turnsswarm-handoffHandoffs are transitions between typed child actors, persisted across turns
Orchestrator-workerAn orchestrator fans work out to workers and gathers resultsai-sdk-orchestrator-workerFan-out and join are plain Promise.all over host actors; the machine owns the coordination
Fan-out (map-reduce)Plan N subtasks at runtime, run them, reducefan-outDynamic parallelism from a planner, then a deterministic reduce state

See Multi-agent for sub-agents and child actors.

Control and safety

PatternWhat it's forExampleWhat the machine buys you
Human in the loopPause for approval, persist, resume in another processhuman-in-the-loopAn idle state is a durable pause; the snapshot is plain JSON you store anywhere
GuardrailsGate input and output through explicit validation statesguardrailsGuardrails are gate states with guards, not prompt pleading; an illegal path is unreachable
Context compactionBound the context window by summarizing stale turnscontext-compactionA compacting state folds old history into a running summary once it passes a threshold
Customer supportConditional escalation to a human on sensitive actionscustomer-supportSensitive actions gate on an interrupt state; the model can't act past the guard

See Human in the loop for the idle-first pause and snapshot resume.

On this page