ai-agent-spawner
v3.0.0
Published
π Universal AI Agent Spawner - CLI tool and function interface for spawning autonomous AI agents with multiple providers
Maintainers
Readme
π€ AI Agent Spawner
Universal AI Agent Spawner - CLI tool and function interface for spawning autonomous AI agents with multiple providers
π 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 outputDesign 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
- Fork the repository
- Create feature branch (
git checkout -b feature/amazing-feature) - Commit changes (
git commit -m 'Add amazing feature') - Push to branch (
git push origin feature/amazing-feature) - 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
- π§ Email: [email protected]
- π¬ Discord: Join our community
- π Issues: GitHub Issues
Made with β€οΈ by the AI Agent Spawner Team
