npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

agent-state-machine

v2.5.0

Published

A workflow orchestrator for running agents and scripts in sequence with state management

Downloads

4,452

Readme

agent-state-machine

A workflow runner for building linear, stateful agent workflows in plain JavaScript.

You write normal async/await code. The runtime handles:

  • Auto-persisted memory (saved to disk on mutation)
  • Auto-tracked fileTree (detects file changes made by agents via Git)
  • Human-in-the-loop blocking via askHuman() or agent-driven interactions
  • Local JS agents + Markdown agents (LLM-powered)
  • Agent retries with history logging for failures

Install

You need to install the package globally to get the CLI, and locally in your project so your workflow can import the library.

Global CLI

Provides the state-machine command.

# npm
npm i -g agent-state-machine

# pnpm
pnpm add -g agent-state-machine

Local Library

Required so your workflow.js can import { agent, memory, fileTree } from 'agent-state-machine'.

# npm
npm i agent-state-machine

# pnpm (for monorepos/turbo, install in root)
pnpm add agent-state-machine -w

Requirements: Node.js >= 16.


CLI

state-machine --setup <workflow-name>
state-machine --setup <workflow-name> --template <template-name>
state-machine run <workflow-name>
state-machine run <workflow-name> -reset
state-machine run <workflow-name> -reset-hard

state-machine -reset <workflow-name>
state-machine -reset-hard <workflow-name>

state-machine history <workflow-name> [limit]

Templates live in templates/ and starter is used by default.

Workflows live in:

workflows/<name>/
├── workflow.js        # Native JS workflow (async/await)
├── config.js          # Model/API key configuration
├── package.json       # Sets "type": "module" for this workflow folder
├── agents/            # Custom agents (.js/.mjs/.cjs or .md)
├── interactions/      # Human-in-the-loop files (auto-created)
├── state/             # current.json, history.jsonl
└── steering/          # global.md + config.json

Writing workflows (native JS)

Edit config.js to set models and API keys for the workflow.

/**
/**
 * project-builder Workflow
 *
 * Native JavaScript workflow - write normal async/await code!
 *
 * Features:
 * - memory object auto-persists to disk (use memory guards for idempotency)
 * - Use standard JS control flow (if, for, etc.)
 * - Interactive prompts pause and wait for user input
 */

import { agent, memory, askHuman, parallel } from 'agent-state-machine';
import { notify } from './scripts/mac-notification.js';

export default async function() {
  console.log('Starting project-builder workflow...');

  // Example: Get user input (saved to memory)
  const userLocation = await askHuman('Where do you live?');
  console.log('Example prompt answer:', userLocation);

  const userInfo = await agent('yoda-name-collector');
  memory.userInfo = userInfo;

  // Provide context
  // const userInfo = await agent('yoda-name-collector', { name: 'Luke' });

  console.log('Example agent memory.userInfo:', memory.userInfo || userInfo);

  // Context is explicit: pass what the agent needs
  const { greeting } = await agent('yoda-greeter', { userLocation, memory });
  console.log('Example agent greeting:', greeting);

  // Or you can provide context manually
  // await agent('yoda-greeter', userInfo);

  // Example: Parallel execution
  // const [a, b, c] = await parallel([
  //   agent('yoda-greeter', { name: 'the names augustus but friends call me gus' }),
  //   agent('yoda-greeter', { name: 'uriah' }),
  //   agent('yoda-greeter', { name: 'lucas' })
  // ]);

  // console.log('a: ' + JSON.stringify(a))
  // console.log('b: ' + JSON.stringify(b))
  // console.log('c: ' + JSON.stringify(c))

  notify(['project-builder', userInfo.name || userInfo + ' has been greeted!']);

  console.log('Workflow completed!');
}

Resuming workflows

state-machine run restarts your workflow from the top, loading the persisted state.

If the workflow needs human input, it will block inline in the terminal. You can answer in the terminal, edit interactions/<slug>.md, or respond in the browser.

If the process is interrupted, running state-machine run <workflow-name> again will continue execution (assuming your workflow uses memory to skip completed steps).


Core API

agent(name, params?, options?)

Runs workflows/<name>/agents/<agent>.(js|mjs|cjs) or <agent>.md.

const out = await agent('review', { file: 'src/app.js' });
memory.lastReview = out;

Options:

  • retry (number | false): default 2 (3 total attempts). Use false to disable retries.
  • steering (string | string[]): extra steering files to load from workflows/<name>/steering/.

Context is explicit: only params are provided to agents unless you pass additional data.

memory

A persisted object for your workflow.

  • Mutations auto-save to workflows/<name>/state/current.json.
  • Use it as your "long-lived state" between runs.
memory.count = (memory.count || 0) + 1;

fileTree

Auto-tracked file changes made by agents.

  • Before each await agent(...), the runtime captures a Git baseline
  • After the agent completes, it detects created/modified/deleted files
  • Changes are stored in memory.fileTree and persisted to current.json
// Files are auto-tracked when agents create them
await agent('code-writer', { task: 'Create auth module' });

// Access tracked files
console.log(memory.fileTree);
// { "src/auth.js": { status: "created", createdBy: "code-writer", ... } }

// Pass file context to other agents
await agent('code-reviewer', { fileTree: memory.fileTree });

Configuration in config.js:

export const config = {
  // ... models and apiKeys ...
  projectRoot: process.env.PROJECT_ROOT,  // defaults to ../.. from workflow
  fileTracking: true,                     // enable/disable (default: true)
  fileTrackingIgnore: ['node_modules/**', '.git/**', 'dist/**'],
  fileTrackingKeepDeleted: false          // keep deleted files in tree
};

trackFile(path, options?) / untrackFile(path)

Manual file tracking utilities:

import { trackFile, getFileTree, untrackFile } from 'agent-state-machine';

trackFile('README.md', { caption: 'Project docs' });
const tree = getFileTree();
untrackFile('old-file.js');

askHuman(question, options?)

Gets user input.

  • In a TTY, it prompts in the terminal (or via the browser when remote follow is enabled).
  • Otherwise it creates interactions/<slug>.md and blocks until you confirm in the terminal (or respond in the browser).
const repo = await askHuman('What repo should I work on?', { slug: 'repo' });
memory.repo = repo;

parallel([...]) / parallelLimit([...], limit)

Run multiple agent() calls concurrently:

import { agent, parallel, parallelLimit } from 'agent-state-machine';

const [a, b] = await parallel([
  agent('review', { file: 'src/a.js' }),
  agent('review', { file: 'src/b.js' }),
]);

const results = await parallelLimit(
  ['a.js', 'b.js', 'c.js'].map(f => agent('review', { file: f })),
  2
);

Agents

Agents live in workflows/<workflow>/agents/.

JavaScript agents

ESM (.js / .mjs):

// workflows/<name>/agents/example.js
import { llm } from 'agent-state-machine';

export default async function handler(context) {
  // context includes:
  // - params passed to agent(name, params)
  // - context._steering (global + optional additional steering content)
  // - context._config (models/apiKeys/workflowDir/projectRoot)

  // Optionally return _files to annotate tracked files
  return {
    ok: true,
    _files: [{ path: 'src/example.js', caption: 'Example module' }]
  };
}

CommonJS (.cjs) (only if you prefer CJS):

// workflows/<name>/agents/example.cjs
async function handler(context) {
  return { ok: true };
}

module.exports = handler;
module.exports.handler = handler;

If you need to request human input from a JS agent, return an _interaction payload:

return {
  _interaction: {
    slug: 'approval',
    targetKey: 'approval',
    content: 'Please approve this change (yes/no).'
  }
};

The runtime will block execution and wait for your response in the terminal.

Markdown agents (.md)

Markdown agents are LLM-backed prompt templates with optional frontmatter. Frontmatter can include steering to load additional files from workflows/<name>/steering/.

---
model: smart
output: greeting
steering: tone, product
---
Generate a friendly greeting for {{name}}.

Calling it:

const { greeting } = await agent('greeter', { name: 'Sam' });
memory.greeting = greeting;

Models & LLM execution

In your workflow’s export const config = { models: { ... } }, each model value can be:

CLI command

export const config = {
  models: {
    smart: "claude -m claude-sonnet-4-20250514 -p"
  }
};

API target

Format: api:<provider>:<model>

export const config = {
  models: {
    smart: "api:openai:gpt-4.1-mini"
  },
  apiKeys: {
    openai: process.env.OPENAI_API_KEY
  }
};

The runtime captures the fully-built prompt in state/history.jsonl, viewable in the browser with live updates when running with the --local flag or via the remote URL. Remote follow links persist across runs (stored in config.js) unless you pass -n/--new to regenerate.


State & persistence

Native JS workflows persist to:

  • workflows/<name>/state/current.json — status, memory (includes fileTree), pending interaction
  • workflows/<name>/state/history.jsonl — event log (newest entries first, includes agent retry/failure entries)
  • workflows/<name>/interactions/*.md — human input files (when paused)

License

MIT