š Universal AI Agent Spawner - CLI tool and function interface for spawning autonomous AI agents with multiple providers
npm install ai-agent-spawner--system-prompt-file)
--append-system-prompt)
--print-mode)
--output-format json)
bash
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
$3
#### Basic Commands
`bash
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
`bash
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)
`bash
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!
`
$3
`typescript
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
`typescript
// 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"
}))
);
`
$3
`typescript
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:
`typescript
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 {
// Add event listeners
factory.addEventListener('session:created', (event) => {
console.log('Custom plugin: Session created!');
});
}
async cleanup(): Promise {
// Cleanup resources
}
}
// Register plugin
const factory = new AgentFactory();
await factory.registerPlugin(new CustomPlugin());
`
š API Reference
$3
`typescript
// 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;
// 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;
// JSON output function
async function agentCodeToolJSON(command: string, options?: Omit[1], 'outputFormat'>): Promise;
`
$3
`typescript
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; // 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
}
`
$3
`typescript
class AgentFactory {
registerProvider(provider: IAgentProvider): void;
getProvider(type: ProviderType): IAgentProvider | undefined;
createSession(config: AgentConfig): AgentSession;
spawnAgent(config: AgentConfig): Promise;
addEventListener(eventType: AgentEventType, listener: AgentEventListener): void;
removeEventListener(eventType: AgentEventType, listener: AgentEventListener): void;
cleanup(): Promise;
}
`
$3
`typescript
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:
`bash
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
`
$3
- Factory Method Pattern: For agent creation
- Strategy Pattern: For provider implementations
- Observer Pattern: For event handling
- Plugin Pattern: For extensibility
š Building
`bash
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
$3
Create reusable agent personalities:
`markdown
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.
`
`bash
Use the system prompt file
agent-spawner --prompt "Write a sorting algorithm" --system-prompt-file "./python-expert.md"
`
$3
`typescript
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
});
})
);
`
$3
`bash
#!/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!"
`
$3
`python
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`)