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

ai-agent-spawner

v3.0.0

Published

πŸš€ Universal AI Agent Spawner - CLI tool and function interface for spawning autonomous AI agents with multiple providers

Readme

πŸ€– AI Agent Spawner

Universal AI Agent Spawner - CLI tool and function interface for spawning autonomous AI agents with multiple providers

npm version License: MIT TypeScript

πŸš€ Features

🎯 DUAL INTERFACE: CLI Tool AND Function Library

  • CLI Mode: Powerful command-line tool for terminal usage
  • Function Mode: Programmatic interface for Node.js applications
  • Same Engine: Both use the same underlying agent spawning technology

πŸ”Œ Multi-Provider Support

  • Anthropic Claude: Native Claude Code integration
  • Z.AI: GLM-4.6 model support
  • Extensible: Easy to add new providers

🧠 Advanced System Prompt Management

  • File-based: Load system prompts from files (--system-prompt-file)
  • Inline: Direct system prompt strings (--append-system-prompt)
  • Reusable: Create libraries of agent personalities
  • No CLAUDE.md needed: Works without directory-based prompts

⚑ Non-Interactive Mode

  • Print Mode: Auto-exit after task completion (--print-mode)
  • JSON Output: Structured output for automation (--output-format json)
  • Perfect for: Scripts, CI/CD, automation pipelines

🏭 Enterprise-Ready Architecture

  • Factory Pattern: Clean, testable agent creation
  • Type Safe: Full TypeScript support with strict typing
  • Event-Driven: Monitor agent lifecycle with events
  • Cross-Platform: Windows, macOS, Linux support

πŸ“¦ Installation

# Install as CLI tool (global)
npm install -g ai-agent-spawner

# Install as dependency (local)
npm install ai-agent-spawner

# Install as development dependency
npm install --save-dev ai-agent-spawner

πŸ”§ Quick Start

πŸ–₯️ CLI Usage

Basic Commands

# Basic agent spawning
agent-spawner --prompt "Create a hello world file"

# With custom role
agent-spawner --prompt "Fix this bug" --role "Senior Debugger"

# Using Z.AI provider
agent-spawner --prompt "Write a poem" --provider zai --api-key "your-key"

# Inline execution (same terminal)
agent-spawner --prompt "What is 2+2?" --inline

🧠 System Prompt Management

# Using system prompt file
agent-spawner --prompt "Debug this code" --system-prompt-file "./debugger-prompt.md"

# Using inline system prompt
agent-spawner --prompt "Write Python code" --append-system-prompt "You are a Python expert"

# Create agent personalities without CLAUDE.md files!

⚑ Non-Interactive Mode (Auto-Exit)

# Print mode - exits after task completion
agent-spawner --prompt "What is 2+2?" --print-mode --inline

# JSON output for automation
agent-spawner --prompt "Analyze this code" --print-mode --output-format json --inline

# Perfect for scripts and CI/CD pipelines!

πŸ’» Function Interface

import { agentCodeTool, agentCodeToolSimple, agentCodeToolJSON } from 'ai-agent-spawner';

// Simple function interface - like def agent_code_tool(command: str)
const result = await agentCodeToolSimple("What is 3+3?");
// Returns: "6"

// Advanced interface with system prompt
const advanced = await agentCodeTool("What is your name?", {
  systemPrompt: "You are Captain Code. Always introduce yourself as 'Captain Code'.",
  outputFormat: "text"
});
// Returns: { success: true, output: "Captain Code...", metadata: {...} }

// JSON output for automation
const jsonResult = await agentCodeToolJSON("Calculate 5+3");
// Returns: { result: "8", sessionId: "...", duration: 1234, ... }

πŸ”₯ Function Examples

// Create specialized agents
const pythonCode = await agentCodeToolSimple("Write a Python function to validate emails", {
  systemPromptFile: "./python-expert.md"
});

// Batch processing
const tasks = [
  "Analyze this JavaScript code",
  "Write unit tests",
  "Create documentation"
];

const results = await Promise.all(
  tasks.map(task => agentCodeToolSimple(task, {
    systemPrompt: "You are a senior software engineer"
  }))
);

Advanced Usage with Factory

import { AgentFactory, AnthropicProvider, ZAIProvider } from '@ai-agents/spawner';

// Create factory with custom configuration
const factory = new AgentFactory();
factory.registerProvider(new AnthropicProvider());
factory.registerProvider(new ZAIProvider());

// Add event listeners
factory.addEventListener('session:created', (event) => {
  console.log(`Session created: ${event.sessionId}`);
});

// Spawn agent
const result = await factory.spawnAgent({
  prompt: 'Analyze this codebase',
  role: 'Senior Developer',
  provider: 'anthropic',
  verbose: true,
  providerConfig: {
    timeout: 600000, // 10 minutes
    model: 'claude-3-sonnet-20240229'
  }
});

πŸ”Œ Plugin System

Create custom plugins to extend functionality:

import { IAgentPlugin, IAgentFactory } from '@ai-agents/spawner';

export class CustomPlugin implements IAgentPlugin {
  readonly name = 'custom-plugin';
  readonly version = '1.0.0';

  async initialize(factory: IAgentFactory): Promise<void> {
    // Add event listeners
    factory.addEventListener('session:created', (event) => {
      console.log('Custom plugin: Session created!');
    });
  }

  async cleanup(): Promise<void> {
    // Cleanup resources
  }
}

// Register plugin
const factory = new AgentFactory();
await factory.registerPlugin(new CustomPlugin());

πŸ“š API Reference

Function Interface API

// Main function interface
interface AgentToolResult {
  success: boolean;                  // Success status
  output: string;                    // Agent response/output
  error?: string;                    // Error message if failed
  metadata?: {
    sessionId: string;               // Unique session identifier
    duration?: number;               // Execution time in ms
    provider?: string;               // AI provider used
  };
}

// Simple function - like def agent_code_tool(command: str)
async function agentCodeToolSimple(command: string): Promise<string>;

// Advanced function with options
async function agentCodeTool(
  command: string,
  options?: {
    role?: string;                   // Agent role
    systemPrompt?: string;           // Inline system prompt
    systemPromptFile?: string;       // Path to system prompt file
    provider?: 'anthropic' | 'zai'; // AI provider
    apiKey?: string;                 // API key for provider
    outputFormat?: 'text' | 'json'; // Output format
    verbose?: boolean;               // Enable verbose output
  }
): Promise<AgentToolResult>;

// JSON output function
async function agentCodeToolJSON(command: string, options?: Omit<Parameters<typeof agentCodeTool>[1], 'outputFormat'>): Promise<any>;

Core Types

interface AgentConfig {
  prompt: string;                    // Required: Task for the agent
  role?: string;                     // Optional: Agent role
  description?: string;              // Optional: Agent description
  verbose?: boolean;                 // Optional: Enable verbose output
  keepOpen?: boolean;                // Optional: Keep terminal open
  inline?: boolean;                  // Optional: Run inline
  printMode?: boolean;               // Optional: Use non-interactive mode
  outputFormat?: 'text' | 'json' | 'stream-json'; // Output format
  appendSystemPrompt?: string;       // Optional: System prompt to append
  systemPromptFile?: string;         // Optional: Path to system prompt file
  provider?: 'anthropic' | 'zai';    // Optional: AI provider
  providerConfig?: ProviderConfig;   // Optional: Provider-specific config
}

interface ProviderConfig {
  apiKey?: string;                   // API key for provider
  baseUrl?: string;                  // Custom base URL
  model?: string;                    // Custom model
  timeout?: number;                  // Request timeout
  customHeaders?: Record<string, string>; // Custom headers
}

interface SpawnResult {
  sessionId: string;                 // Unique session identifier
  scriptPath: string;                // Path to generated script
  success: boolean;                  // Success status
  process?: any;                     // Child process reference
  error?: string;                    // Error message if failed
}

Factory API

class AgentFactory {
  registerProvider(provider: IAgentProvider): void;
  getProvider(type: ProviderType): IAgentProvider | undefined;
  createSession(config: AgentConfig): AgentSession;
  spawnAgent(config: AgentConfig): Promise<SpawnResult>;
  addEventListener(eventType: AgentEventType, listener: AgentEventListener): void;
  removeEventListener(eventType: AgentEventType, listener: AgentEventListener): void;
  cleanup(): Promise<void>;
}

Event Types

type AgentEventType =
  | 'session:created'    // Session initialized
  | 'session:started'    // Agent process started
  | 'session:completed'  // Agent finished successfully
  | 'session:failed'     // Agent failed with error
  | 'process:error';     // Process-level error

interface AgentEvent {
  type: AgentEventType;
  sessionId: string;
  timestamp: Date;
  data?: any;
  error?: Error;
}

πŸ› οΈ Configuration

Environment variables:

# Global configuration
AGENT_SPAWNER_TEMP_DIR=/tmp/agents          # Custom temp directory
AGENT_SPAWNER_TIMEOUT=300000                 # Default timeout (ms)
AGENT_SPAWNER_KEEP_OPEN=true                 # Keep terminals open
AGENT_SPAWNER_VERBOSE=false                  # Default verbose mode
AGENT_SPAWNER_DEFAULT_PROVIDER=anthropic     # Default provider
AGENT_SPAWNER_MAX_AGENTS=10                  # Max concurrent agents

# Provider-specific
ZAI_API_KEY=your-zai-api-key                 # Z.AI API key
ANTHROPIC_API_KEY=your-key                   # Anthropic API key (if needed)

πŸ—οΈ Architecture

The package follows clean architecture principles:

@ai-agents/spawner/
β”œβ”€β”€ src/
β”‚   β”œβ”€β”€ core/           # Core abstractions and factory
β”‚   β”‚   β”œβ”€β”€ types.ts    # Type definitions
β”‚   β”‚   β”œβ”€β”€ AgentFactory.ts
β”‚   β”‚   └── PluginManager.ts
β”‚   β”œβ”€β”€ providers/      # AI provider implementations
β”‚   β”‚   β”œβ”€β”€ AnthropicProvider.ts
β”‚   β”‚   └── ZAIProvider.ts
β”‚   β”œβ”€β”€ cli/           # Command-line interface
β”‚   β”‚   └── index.ts
β”‚   β”œβ”€β”€ utils/         # Shared utilities
β”‚   β”‚   β”œβ”€β”€ logger.ts
β”‚   β”‚   └── config.ts
β”‚   └── index.ts       # Main entry point
β”œβ”€β”€ examples/          # Usage examples
└── dist/             # Compiled output

Design Patterns

  • Factory Method Pattern: For agent creation
  • Strategy Pattern: For provider implementations
  • Observer Pattern: For event handling
  • Plugin Pattern: For extensibility

πŸš€ Building

# Clone repository
git clone https://github.com/ai-agents/spawner.git
cd spawner

# Install dependencies
npm install

# Build
npm run build

# Run tests
npm test

# Run examples
npm run dev

πŸ“ Examples

System Prompt Files

Create reusable agent personalities:

# python-expert.md
You are a Python Expert Agent. You specialize in:
- Python best practices and PEP 8 standards
- Writing clean, maintainable Python code
- Python testing with pytest and unittest

Always respond with "🐍 Python Expert:" prefix and provide detailed, well-commented code examples.
# Use the system prompt file
agent-spawner --prompt "Write a sorting algorithm" --system-prompt-file "./python-expert.md"

Batch Processing

import { agentCodeToolSimple } from 'ai-agent-spawner';

// Process multiple tasks with different agents
const tasks = [
  { prompt: "Debug this Python code", agent: "python-expert.md" },
  { prompt: "Review this JavaScript", agent: "js-expert.md" },
  { prompt: "Write documentation", agent: "tech-writer.md" }
];

const results = await Promise.all(
  tasks.map(async task => {
    return await agentCodeToolSimple(task.prompt, {
      systemPromptFile: task.agent
    });
  })
);

CLI Automation Script

#!/bin/bash
# automate-analysis.sh

echo "πŸ” Starting code analysis..."

# Static analysis
agent-spawner \
  --prompt "Analyze code quality and suggest improvements" \
  --system-prompt-file "./code-reviewer.md" \
  --print-mode \
  --output-format json \
  --inline > analysis.json

# Security scan
agent-spawner \
  --prompt "Check for security vulnerabilities" \
  --system-prompt-file "./security-expert.md" \
  --print-mode \
  --inline > security.txt

echo "βœ… Analysis complete!"

Python Integration

import asyncio
import subprocess
import json

async def run_agent_analysis(code: str) -> dict:
    """Run agent analysis from Python"""
    cmd = [
        'node', '-e',
        f"""
        const {{ agentCodeToolJSON }} = require('ai-agent-spawner');

        agentCodeToolJSON('Analyze this code: {code}', {{
          systemPrompt: 'You are a senior code reviewer. Focus on security, performance, and maintainability.',
          outputFormat: 'json'
        }}).then(result => console.log(JSON.stringify(result))).catch(console.error);
        """
    ]

    result = subprocess.run(cmd, capture_output=True, text=True)
    return json.loads(result.stdout)

# Usage
analysis = await run_agent_analysis("function add(a,b) { return a+b }")
print(f"Score: {analysis.get('score', 'N/A')}")
print(f"Issues: {analysis.get('issues', [])}")

🀝 Contributing

  1. Fork the repository
  2. Create feature branch (git checkout -b feature/amazing-feature)
  3. Commit changes (git commit -m 'Add amazing feature')
  4. Push to branch (git push origin feature/amazing-feature)
  5. Open Pull Request

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • Anthropic Claude for the amazing AI platform
  • Z.AI for GLM-4.6 model support
  • The TypeScript community for excellent tooling

πŸ“ž Support


Made with ❀️ by the AI Agent Spawner Team