agent-spawner-v2
v3.1.1
Published
π€ Universal AI Agent Spawner - Zero Dependencies Required! Type-Driven Architecture with Built-in Mock Mode
Maintainers
Readme
π€ Agent Spawner V2
Type-Driven Architecture with Railway Oriented Programming
A universal AI agent spawner built with verifiable type system that makes invalid states mathematically impossible. This implementation follows Domain-Driven Design (DDD), Type-Driven Development (TyDD), and Railway Oriented Programming (ROP) principles.
π§ ARCHITECTURAL PHILOSOPHY
Zero-Bug Physics
This codebase is designed with constructive correctness where the compiler prevents runtime errors through:
- Algebraic Data Types (ADTs): Sum and Product types eliminate invalid states
- Parse, Don't Validate: Trust types after boundary validation
- Railway Oriented Programming: Explicit error handling with Result monads
- Branded Types: Prevent primitive obsession
Type System Supremacy
// β Invalid states are impossible:
type AgentState =
| { _tag: 'Created'; sessionId: SessionId; createdAt: Date }
| { _tag: 'Running'; sessionId: SessionId; processId: ProcessId; startedAt: Date }
| { _tag: 'Completed'; sessionId: SessionId; output: string; completedAt: Date };
// You cannot accidentally:
// - Complete a non-running agent
// - Pass a wrong session ID type
// - Forget to handle a stateπ PROJECT STRUCTURE
agent-spawner-v2/
βββ π src/ # Source code
β βββ π§ domain/ # Domain logic (pure functions)
β βββ π― application/ # Application orchestration
β βββ ποΈ infrastructure/ # Side effects (I/O, processes)
β βββ π cli/ # CLI interface
βββ π tests/ # Test suite
β βββ π§ͺ unit/ # Unit tests
β βββ π integration/ # Integration tests
β βββ π οΈ utils/ # Test utilities
βββ π docs/ # Documentation
βββ π dist/ # Built JavaScript
βββ βοΈ Config files # TypeScript, Jest, etc.ποΈ ARCHITECTURE
Layered Architecture
βββββββββββββββββββββββββββββββββββββββββββ
β CLI INTERFACE β β User Interface
βββββββββββββββββββββββββββββββββββββββββββ€
β APPLICATION LAYER β β Orchestration
βββββββββββββββββββββββββββββββββββββββββββ€
β DOMAIN LAYER β β Business Logic
βββββββββββββββββββββββββββββββββββββββββββ€
β INFRASTRUCTURE LAYER β β Side Effects
βββββββββββββββββββββββββββββββββββββββββββCore Components
- π§ Domain Types: Immutable, verifiable data structures
- β‘ Domain Services: Pure business logic functions
- π― Application Service: Orchestrates workflows
- ποΈ Infrastructure: File system, process management
- π CLI: Type-safe command interface
π¦ INSTALLATION
# Clone the repository
git clone <repository-url>
cd agent-spawner-v2
# Install dependencies
npm install
# Build the project
npm run build
# Install globally for CLI usage
npm install -g .π USAGE
Command Line Interface
# Spawn an agent with Anthropic Claude
agent-spawner spawn -p "Explain quantum computing" -r anthropic
# Use Z.AI provider with specific model
agent-spawner spawn -p "Write Python code" -r zai -m glm-4.6
# Terminal mode for interactive sessions
agent-spawner spawn -p "Debug this issue" -e terminal
# Background execution with timeout
agent-spawner spawn -p "Long running task" -e background -t 600
# Load configuration from file
agent-spawner spawn -c config.json -p "Custom prompt"
# Save output to file
agent-spawner spawn -p "Generate report" -o report.txt
# List active sessions
agent-spawner list
# Cancel a running session
agent-spawner cancel <sessionId>Programmatic Interface
import { createAgentService, parseAgentConfig } from 'agent-spawner-v2';
// Create service instance
const service = createAgentService();
// Parse configuration
const config = parseAgentConfig({
prompt: "Explain TypeScript",
provider: { _tag: 'Anthropic' },
executionMode: { _tag: 'Inline', timeout: 300 }
});
// Spawn agent
if (config._tag === 'Success') {
const result = await service.spawnAgent(config.value);
if (result._tag === 'Success') {
console.log('Agent spawned:', result.value.sessionId);
}
}π§ CONFIGURATION
Configuration File (JSON)
{
"prompt": "Your agent prompt here",
"provider": "anthropic",
"model": "claude-3-sonnet",
"mode": "inline",
"timeout": 300,
"environment": {
"CUSTOM_VAR": "value"
}
}Supported Providers
| Provider | Models | Environment Variables |
|----------|--------|----------------------|
| Anthropic | claude-3-sonnet, claude-3-opus, claude-3-haiku | ANTHROPIC_API_KEY |
| Z.AI | glm-4.6 | ZAI_API_KEY |
| OpenAI | gpt-4, gpt-3.5-turbo | OPENAI_API_KEY |
Execution Modes
inline: Run synchronously and return outputterminal: Open in terminal for interactive sessionsbackground: Run asynchronously with auto-cleanup
π§ͺ DEVELOPMENT
Type Safety First
// β
Branded types prevent confusion
type SessionId = Branded<string, 'SessionId'>;
type AgentPrompt = Branded<string, 'AgentPrompt'>;
// β
Sum types ensure exhaustive handling
type AgentState =
| { _tag: 'Created' }
| { _tag: 'Running' }
| { _tag: 'Completed' };
// β
Result types make errors explicit
type Result<T, E> =
| { _tag: 'Success'; value: T }
| { _tag: 'Failure'; error: E };Build & Test
# Type checking (no compilation)
npm run type-check
# Build project
npm run build
# Run tests
npm test
# Watch tests
npm run test:watch
# Coverage report
npm run test:coverage
# Lint code
npm run lintTesting Philosophy
- Property-Based Testing: Verify invariants with random data
- Type-Driven Tests: Test every branch of discriminated unions
- Integration Tests: Verify complete workflows
- Mock-Free Testing: Test pure functions directly
ποΈ ARCHITECTURAL PATTERNS
Railway Oriented Programming
// π― Linear error handling, no try/catch
const result = await pipe(
parseAgentConfig(input),
chain(validateConfig),
chain(createSession),
chain(spawnAgent),
chain(monitorExecution)
);
// π― Explicit error handling
match(result, {
Success: (value) => console.log('Success:', value),
Failure: (error) => console.error('Error:', error)
});Parse, Don't Validate
// β Validation everywhere
function validateUser(user: any): boolean {
return user.email && user.age > 0;
}
// β
Parse once, trust everywhere
const parseUser = (input: unknown): Result<User, ParseError> => {
// Parse and validate at boundary
return Success(validatedUser);
};
// Now we can trust User type everywhere
function processUser(user: User): Result<ProcessedUser, BusinessError> {
// No validation needed - User is always valid
}π PERFORMANCE
Memory Management
- Immutable Data: Prevents accidental mutations
- Resource Cleanup: Automatic process and file cleanup
- Event-Driven: Non-blocking async operations
Scalability
- Process Isolation: Each agent runs in separate process
- Concurrent Execution: Multiple agents can run simultaneously
- Resource Limits: Configurable timeouts and auto-cleanup
π SAFETY & SECURITY
Type System Safety
- No Runtime Type Errors: All data validated at boundaries
- Exhaustive Pattern Matching: All states handled explicitly
- Immutable by Default: Prevents unintended side effects
Security Features
- Environment Variable Sanitization: Secure API key handling
- Script Generation Safety: No eval or code injection
- Process Isolation: Agents run in isolated processes
- Resource Cleanup: Prevents resource leaks
π€ CONTRIBUTING
Development Principles
- Type-Driven Development: Start with types, not code
- Railway Oriented Programming: Make errors explicit
- Pure Functions: Separate business logic from side effects
- Immutability: All data structures must be immutable
- Exhaustiveness: Handle every possible state
Code Review Checklist
- [ ] All functions are total and pure
- [ ] Error handling uses Result monads
- [ ] No
anytypes or type assertions - [ ] All discriminated unions are exhaustive
- [ ] All data structures are immutable
- [ ] No try/catch in business logic
π LICENSE
MIT License - see LICENSE file for details.
π ACKNOWLEDGMENTS
This architecture is inspired by:
- Domain-Driven Design (Eric Evans)
- Type-Driven Development (Edwin Brady)
- Functional Programming (Scott Wlaschin)
- Railway Oriented Programming (Scott Wlaschin)
Built with β€οΈ using TypeScript, Functional Programming, and Type-Driven Development.
