Advanced Orchestration Engines ⏱ 11 min read 📁 examples/18_state_machine.mjs

Lesson 19: State Machine Orchestration

Construct LLM-planned finite state machines with deterministic transition evaluation, mid-run graph mutation, and checkpoint/resume capabilities.

1. Why This Feature Exists

Some workflows are cyclical or require complex branching logic that DAGs cannot represent. State machines provide loops, conditional branching, and deterministic transitions for mission-critical processes.

2. Key Symbols and Exports

StateMachine
Node-based execution graph with explicit state transitions and context memory.
Mid-Run Graph Mutation
Dynamically add, remove, or rewire state transitions based on intermediate evaluation.
Checkpoint & Resume
Serialize state machine execution state to JSON and restore from arbitrary checkpoints.
Deterministic Transitions
Evaluates guard conditions to choose next state with zero prompt ambiguity.

3. Implementation Walkthrough

import {
    ProviderType,
    resolveProvider,
    initializeClient,
    loadCredentials,
    getDefaultModel,
    StateMachine
} from 'merci-sdk';

const PROVIDER = resolveProvider();
const { client } = await initializeClient({ provider: PROVIDER, options: loadCredentials({ provider: PROVIDER }) });

const machine = new StateMachine({
    client,
    model: getDefaultModel({ provider: PROVIDER }),
    initialState: 'DRAFT',
    states: {
        DRAFT: {
            execute: async (ctx) => ({ draft: 'Initial architecture document.' }),
            transitions: [{ target: 'REVIEW' }]
        },
        REVIEW: {
            execute: async (ctx) => ({ approved: false, feedback: 'Needs security hardening.' }),
            transitions: [
                { target: 'PUBLISH', condition: (ctx) => ctx.approved === true },
                { target: 'REVISE', condition: (ctx) => ctx.approved === false }
            ]
        },
        REVISE: {
            execute: async (ctx) => ({ draft: 'Hardened architecture document.', approved: true }),
            transitions: [{ target: 'REVIEW' }]
        },
        PUBLISH: {
            execute: async (ctx) => ({ published: true }),
            terminal: true
        }
    }
});

const finalContext = await machine.run();
console.log('Final State Context:', finalContext);

4. Wire and Telemetry Mechanics

State transitions evaluate JavaScript guard conditions locally. Node executions trigger session steps and log 'state_machine:transition' telemetry events.

5. Run the Example

Execute the runnable example directly from the repository root:

node examples/18_state_machine.mjs

Read the full example: examples/18_state_machine.mjs →

Expected Output: Executes multi-state cycle (Draft -> Review -> Revise -> Review -> Publish) with checkpoint saves and transition logs.