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
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.mjsRead the full example: examples/18_state_machine.mjs →