{"_id":"12-factor-agents","name":"12-factor-agents","dist-tags":{"latest":"1.0.0"},"versions":{"1.0.0":{"name":"12-factor-agents","version":"1.0.0","description":"12-factor methodology for autonomous AI agents - state management, checkpointing, resumable workflows","main":"dist/index.js","types":"dist/index.d.ts","bin":{"12fa":"dist/bin/12fa.js"},"repository":{"type":"git","url":"git+https://github.com/anombyte/12-factor-agents.git"},"homepage":"https://github.com/anombyte/12-factor-agents#readme","bugs":{"url":"https://github.com/anombyte/12-factor-agents/issues"},"scripts":{"build":"tsc","prepublishOnly":"npm run build","test":"echo \"Tests coming soon\" && exit 0","example":"npm run build && node dist/examples/simple-workflow.js"},"keywords":["ai","agents","12-factor","workflow","state-management","checkpointing","autonomous","resumable","workflow-orchestration","agent-framework","ntfy","notifications"],"author":{"name":"anombyte"},"license":"MIT","publishConfig":{"access":"public"},"devDependencies":{"@types/node":"^20.0.0","typescript":"^5.0.0"},"engines":{"node":">=18.0.0"},"gitHead":"73c0fd2d99584431c967b0b11671f947acc38fdd","_id":"12-factor-agents@1.0.0","_nodeVersion":"22.21.1","_npmVersion":"11.6.2","dist":{"integrity":"sha512-vl5pDH6g7utOZDwAwHqT/HeZ3UMReKL3TDdfhuHsMLc36ZY2BCjImWFZU91XRBUmElKGuxZ1j1hn2PJr5yh9TA==","shasum":"a4c95cc97e180c68749dfb1e5c23dc2fe11a6aea","tarball":"https://registry.npmjs.org/12-factor-agents/-/12-factor-agents-1.0.0.tgz","fileCount":27,"unpackedSize":80731,"signatures":[{"keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U","sig":"MEUCIF8UoKS5s9kmohLmCODOqltvCi+c2hArpxcjjVojKmVfAiEApKAvpV6nCtMC0Jx25vWZHmUsfKwk6x/GqKV7EjTQk0Q="}]},"_npmUser":{"name":"hbruinsma","email":"hayden.bruinsma@gmail.com"},"directories":{},"maintainers":[{"name":"hbruinsma","email":"hayden.bruinsma@gmail.com"}],"_npmOperationalInternal":{"host":"s3://npm-registry-packages-npm-production","tmp":"tmp/12-factor-agents_1.0.0_1764344061835_0.6623298925294479"},"_hasShrinkwrap":false}},"time":{"created":"2025-11-28T15:34:21.718Z","1.0.0":"2025-11-28T15:34:22.040Z","modified":"2025-11-28T15:34:22.347Z"},"maintainers":[{"name":"hbruinsma","email":"hayden.bruinsma@gmail.com"}],"description":"12-factor methodology for autonomous AI agents - state management, checkpointing, resumable workflows","homepage":"https://github.com/anombyte/12-factor-agents#readme","keywords":["ai","agents","12-factor","workflow","state-management","checkpointing","autonomous","resumable","workflow-orchestration","agent-framework","ntfy","notifications"],"repository":{"type":"git","url":"git+https://github.com/anombyte/12-factor-agents.git"},"author":{"name":"anombyte"},"bugs":{"url":"https://github.com/anombyte/12-factor-agents/issues"},"license":"MIT","readme":"# 12-factor-agents\n\n[![npm version](https://badge.fury.io/js/12-factor-agents.svg)](https://www.npmjs.com/package/12-factor-agents)\n[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)\n[![Node.js Version](https://img.shields.io/badge/node-%3E%3D18-brightgreen.svg)](https://nodejs.org)\n[![npm downloads](https://img.shields.io/npm/dm/12-factor-agents.svg)](https://www.npmjs.com/package/12-factor-agents)\n\n> 12-factor methodology for autonomous AI agents - state management, checkpointing, resumable workflows\n\n## Overview\n\n**12-factor-agents** brings the proven principles of [12-factor apps](https://12factor.net/) to autonomous AI agent workflows. It provides robust infrastructure for long-running, resumable, and observable agent operations.\n\n### Core Principles\n\n1. **Stateless Brains, Stateful System** - Agents are ephemeral, state persists\n2. **Checkpointed Steps** - Every step is saved, workflows are resumable\n3. **Idempotent Actions** - Steps can be safely retried\n4. **Resumable Workflows** - Pick up exactly where you left off\n5. **Human-in-the-Loop Batching** - Collect inputs, minimize interruptions\n6. **Observable Operations** - Comprehensive logging and notifications\n\n## Installation\n\n```bash\nnpm install 12-factor-agents\n```\n\nOr globally for CLI access:\n\n```bash\nnpm install -g 12-factor-agents\n```\n\n## Quick Start (5 minutes)\n\n### 1. Initialize a Project\n\n```bash\ncd your-project\nnpx 12fa init\n```\n\nThis creates `.12fa/` directory for state management.\n\n### 2. Basic Workflow\n\n```typescript\nimport { WorkflowRunner } from '12-factor-agents';\n\nconst runner = new WorkflowRunner({\n  projectRoot: process.cwd(),\n  enableGitCheckpoints: true,\n  enableNtfy: false\n});\n\nawait runner.runWorkflow('my-workflow', [\n  {\n    id: 'step-1',\n    name: 'First step',\n    action: async () => {\n      console.log('Doing work...');\n    }\n  },\n  {\n    id: 'step-2',\n    name: 'Second step',\n    action: async () => {\n      console.log('More work...');\n    }\n  }\n]);\n```\n\n### 3. Run It\n\n```bash\nnpx ts-node your-script.ts\n# or\nnode your-script.js\n```\n\nIf interrupted, run it again—it will resume from the last checkpoint.\n\n## Architecture\n\n```\n┌─────────────────────────────────────────────────────────┐\n│                    WorkflowRunner                       │\n│  Orchestrates state, checkpoints, logging, and inputs   │\n└────────────────┬────────────────────────────────────────┘\n                 │\n     ┌───────────┼───────────┬─────────────┬──────────┐\n     │           │           │             │          │\n┌────▼─┐  ┌─────▼──┐  ┌─────▼────┐  ┌────▼──┐  ┌───▼──┐\n│State │  │Checkpoint│  │Feature  │  │Progress│  │Input │\n│Mgr   │  │Manager   │  │Tracker  │  │Logger  │  │Coll  │\n└──────┘  └──────────┘  └─────────┘  └────────┘  └──────┘\n     │           │           │             │          │\n     └───────────┼───────────┴─────────────┴──────────┘\n                 │\n         ┌───────▼────────┐\n         │  .12fa/ State  │\n         │  Persistence   │\n         └────────────────┘\n                 │\n            ┌────▼─────┬──────────┬─────────────┐\n            │  Git     │ NTFY     │  Filesystem │\n            │ Commits  │ Notify   │  Logs       │\n            └──────────┴──────────┴─────────────┘\n```\n\n## CLI Commands\n\n```bash\n# Project initialization\n12fa init                              # Set up state directory\n\n# Workflow management\n12fa status                            # Show current workflow status\n12fa checkpoints                       # List all checkpoints\n12fa restore <checkpoint-id>           # Restore to checkpoint\n\n# Feature tracking\n12fa features                          # List all features\n12fa add-feature \"Name\" [priority]     # Create feature\n\n# Monitoring\n12fa logs [session-id]                 # Show progress logs\n12fa inputs                            # List pending human inputs\n12fa respond <input-id> <response>     # Provide input response\n\n# Cleanup\n12fa clean                             # Remove all state (destructive)\n12fa --help                            # Show help\n```\n\n## Comprehensive Guide\n\n### Programmatic Usage\n\n```typescript\nimport { WorkflowRunner } from '12-factor-agents';\n\nconst runner = new WorkflowRunner({\n  projectRoot: process.cwd(),\n  enableGitCheckpoints: true,\n  enableNtfy: process.env.ENABLE_NTFY === 'true',\n  autoCommit: false\n});\n\nawait runner.runWorkflow('build-feature', [\n  {\n    id: 'analyze',\n    name: 'Analyze requirements',\n    action: async () => {\n      console.log('Analyzing...');\n    }\n  },\n  {\n    id: 'implement',\n    name: 'Implement feature',\n    action: async () => {\n      console.log('Implementing...');\n    },\n    idempotent: true  // Safe to retry\n  },\n  {\n    id: 'test',\n    name: 'Run tests',\n    action: async () => {\n      console.log('Testing...');\n    },\n    rollback: async () => {\n      console.log('Rolling back...');\n    }\n  }\n]);\n```\n\n## Features\n\n### State Management\n\nPersistent state across workflow executions:\n\n```typescript\nconst stateManager = runner.getStateManager();\n\n// Check if step was completed\nif (stateManager.isStepCompleted('build')) {\n  console.log('Build already done, skipping...');\n}\n\n// Update context\nstateManager.updateContext({\n  apiKey: 'xxx',\n  deploymentUrl: 'https://example.com'\n});\n```\n\n### Git Checkpointing\n\nAutomatic git commits at each step:\n\n```typescript\nconst checkpointManager = runner.getCheckpointManager();\n\n// Create manual checkpoint\ncheckpointManager.createCheckpoint(\n  'deployment',\n  'pre-deploy',\n  { version: '1.2.3' },\n  'Ready for deployment'\n);\n\n// List all checkpoints\nconst checkpoints = checkpointManager.listCheckpoints();\n\n// Restore to previous checkpoint\ncheckpointManager.restoreCheckpoint('deployment-pre-deploy-1234567890');\n```\n\n### Feature Tracking\n\nManage features with priorities and status:\n\n```typescript\nconst featureTracker = runner.getFeatureTracker();\n\n// Add feature\nconst feature = featureTracker.addFeature('User authentication', 'high');\n\n// Update status\nfeatureTracker.updateFeatureStatus(feature.id, 'in-progress');\nfeatureTracker.updateFeatureStatus(feature.id, 'complete');\n\n// List features by status\nconst pending = featureTracker.listFeatures('pending');\n```\n\n### Progress Logging\n\nChronological logging of all workflow actions:\n\n```typescript\nconst progressLogger = runner.getProgressLogger();\n\n// Log action\nprogressLogger.log(\n  sessionId,\n  'build',\n  'compile',\n  'Compiling TypeScript',\n  'success',\n  'Built 42 files',\n  1234 // duration in ms\n);\n\n// Get session stats\nconst stats = progressLogger.getSessionStats(sessionId);\nconsole.log(`Success rate: ${stats.successful}/${stats.totalActions}`);\n```\n\n### Human Input Collection\n\nBatch human inputs to minimize interruptions:\n\n```typescript\nconst inputCollector = runner.getInputCollector();\n\n// Request input\nconst inputId = inputCollector.requestInput(\n  'Which API endpoint should we use?',\n  { options: ['staging', 'production'] }\n);\n\n// Check pending inputs\nconst pending = inputCollector.getPendingInputs();\n\n// Provide response\ninputCollector.provideResponse(inputId, 'staging');\n\n// Wait for response (async)\nconst response = await inputCollector.waitForResponse(inputId, 60000);\n```\n\n### NTFY Notifications\n\nReal-time notifications to desktop/mobile:\n\n```typescript\nconst ntfyClient = runner.getNtfyClient();\n\n// Built-in notification types\nntfyClient.notifyStart('deployment', 'Starting deployment to production');\nntfyClient.notifyComplete('deployment', 'Deployment successful');\nntfyClient.notifyError('deployment', 'Deployment failed: timeout');\nntfyClient.notifyBlocked('deployment', 'Waiting for approval');\nntfyClient.notifyInputRequired('Select environment', inputId);\n\n// Custom notification\nntfyClient.send({\n  title: 'Custom Event',\n  message: 'Something happened',\n  priority: 'high',\n  tags: ['warning', 'robot'],\n  click: 'https://example.com',\n  actions: [\n    {\n      action: 'view',\n      label: 'View Details',\n      url: 'https://dashboard.example.com'\n    }\n  ]\n});\n```\n\n## CLI Usage\n\n```bash\n# Initialize project\n12fa init\n\n# Show workflow status\n12fa status\n\n# List checkpoints\n12fa checkpoints\n\n# Restore checkpoint\n12fa restore <checkpoint-id>\n\n# Feature management\n12fa features\n12fa add-feature \"User authentication\" high\n\n# View logs\n12fa logs\n12fa logs <session-id>\n\n# Human inputs\n12fa inputs\n12fa respond <input-id> \"production\"\n\n# Clean all state (WARNING: destructive)\n12fa clean\n```\n\n## Configuration\n\n```typescript\ninterface WorkflowConfig {\n  projectRoot: string;           // Required: project directory\n  stateDir?: string;             // Default: .12fa/\n  enableGitCheckpoints?: boolean; // Default: true\n  enableNtfy?: boolean;          // Default: false\n  ntfyUrl?: string;              // Default: http://localhost:8889\n  ntfyTopic?: string;            // Default: anombyte-dev\n  autoCommit?: boolean;          // Default: false\n}\n```\n\n## NTFY Setup\n\n```bash\n# Auto-setup (installs + starts server)\n./node_modules/12-factor-agents/scripts/setup-ntfy.sh\n\n# Manual setup\nntfy serve --listen-http :8889 &\n\n# Subscribe to notifications\n# Web: http://localhost:8889/anombyte-dev\n# Mobile: Install ntfy app, subscribe to anombyte-dev\n```\n\n## Project Structure\n\n```\nyour-project/\n└── .12fa/\n    ├── agent-state.json          # Current workflow state\n    ├── checkpoints/              # Step checkpoints\n    │   └── *.json\n    ├── features.json             # Feature tracking\n    ├── progress.jsonl            # Chronological logs\n    └── human-inputs.json         # Input requests/responses\n```\n\n## Best Practices\n\n### 1. Design Idempotent Steps\n\n```typescript\n{\n  id: 'install-deps',\n  name: 'Install dependencies',\n  action: async () => {\n    // Check if already installed\n    if (fs.existsSync('node_modules')) {\n      console.log('Dependencies already installed');\n      return;\n    }\n    await exec('npm install');\n  },\n  idempotent: true\n}\n```\n\n### 2. Use Checkpoints for Critical Steps\n\n```typescript\nconst checkpoint = checkpointManager.createCheckpoint(\n  'deployment',\n  'pre-deploy',\n  { version, buildHash },\n  'Pre-deployment checkpoint'\n);\n```\n\n### 3. Batch Human Inputs\n\n```typescript\n// Collect all inputs upfront\nconst envInput = inputCollector.requestInput('Environment?');\nconst versionInput = inputCollector.requestInput('Version tag?');\n\n// Notify once\nntfyClient.send({\n  title: 'Input Required',\n  message: '2 questions need answers',\n  priority: 'high'\n});\n\n// Wait for all responses\nconst [env, version] = await Promise.all([\n  inputCollector.waitForResponse(envInput),\n  inputCollector.waitForResponse(versionInput)\n]);\n```\n\n### 4. Log Everything\n\n```typescript\nprogressLogger.log(\n  sessionId,\n  phase,\n  step,\n  action,\n  result,\n  details,\n  duration\n);\n```\n\n## Examples\n\nSee `/examples` directory for complete workflows:\n\n- `build-pipeline.ts` - CI/CD workflow\n- `data-migration.ts` - Database migration\n- `feature-development.ts` - TDD workflow\n\n## Troubleshooting\n\n### Workflow won't resume\n\nCheck that `.12fa/agent-state.json` exists and is readable:\n\n```bash\nls -la .12fa/\ncat .12fa/agent-state.json\n```\n\n### NTFY notifications not working\n\nEnsure ntfy server is running:\n\n```bash\n# Check if running\nlsof -i :8889\n\n# Start ntfy server\nntfy serve --listen-http :8889 &\n\n# Subscribe to notifications\n# Go to: http://localhost:8889/anombyte-dev\n```\n\n### CLI commands not found\n\nEnsure the package is installed globally or use npx:\n\n```bash\n# Global install\nnpm install -g 12-factor-agents\n12fa --help\n\n# Or with npx\nnpx 12-factor-agents --help\n```\n\n## Contributing\n\nContributions welcome! Areas for enhancement:\n\n- Test suite (Jest/Vitest)\n- Example workflows\n- MCP server integration\n- Advanced recovery strategies\n- Performance optimizations\n\n## Roadmap\n\n- **v1.0.0** (current) - Stable core + CLI\n- **v1.1.0** - Enhanced error messages and debugging\n- **v1.2.0** - Performance optimizations\n- **v2.0.0** - MCP server integration + advanced patterns\n\n## License\n\nMIT\n\n## Author\n\nanombyte\n\n---\n\nBuilt for autonomous AI agents. Inspired by [12-factor apps](https://12factor.net/). Designed for production.\n\nPerfect for CI/CD pipelines, data migrations, multi-step deployments, and human-supervised AI tasks.\n\n[See CHANGELOG for detailed release notes.](CHANGELOG.md)\n","readmeFilename":"README.md","_rev":"1-9229ee295260baed367733852043bb11"}