๐ค Universal AI Agent Spawner - Zero Dependencies Required! Type-Driven Architecture with Built-in Mock Mode
npm install agent-spawner-v2A 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.
---
- 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
typescript
// โ 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
$3
`
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ CLI INTERFACE โ โ User Interface
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ APPLICATION LAYER โ โ Orchestration
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ DOMAIN LAYER โ โ Business Logic
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ INFRASTRUCTURE LAYER โ โ Side Effects
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
`$3
- ๐ง 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
`bash
Clone the repository
git clone
cd agent-spawner-v2Install dependencies
npm installBuild the project
npm run buildInstall globally for CLI usage
npm install -g .
`---
๐ USAGE
$3
`bash
Spawn an agent with Anthropic Claude
agent-spawner spawn -p "Explain quantum computing" -r anthropicUse Z.AI provider with specific model
agent-spawner spawn -p "Write Python code" -r zai -m glm-4.6Terminal mode for interactive sessions
agent-spawner spawn -p "Debug this issue" -e terminalBackground execution with timeout
agent-spawner spawn -p "Long running task" -e background -t 600Load configuration from file
agent-spawner spawn -c config.json -p "Custom prompt"Save output to file
agent-spawner spawn -p "Generate report" -o report.txtList active sessions
agent-spawner listCancel a running session
agent-spawner cancel
`$3
`typescript
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
$3
`json
{
"prompt": "Your agent prompt here",
"provider": "anthropic",
"model": "claude-3-sonnet",
"mode": "inline",
"timeout": 300,
"environment": {
"CUSTOM_VAR": "value"
}
}
`$3
| 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 |$3
-
inline: Run synchronously and return output
- terminal: Open in terminal for interactive sessions
- background: Run asynchronously with auto-cleanup---
๐งช DEVELOPMENT
$3
`typescript
// โ
Branded types prevent confusion
type SessionId = Branded;
type AgentPrompt = Branded;// โ
Sum types ensure exhaustive handling
type AgentState =
| { _tag: 'Created' }
| { _tag: 'Running' }
| { _tag: 'Completed' };
// โ
Result types make errors explicit
type Result =
| { _tag: 'Success'; value: T }
| { _tag: 'Failure'; error: E };
`$3
`bash
Type checking (no compilation)
npm run type-checkBuild project
npm run buildRun tests
npm testWatch tests
npm run test:watchCoverage report
npm run test:coverageLint code
npm run lint
`$3
- 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
$3
`typescript
// ๐ฏ 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)
});
`$3
`typescript
// โ Validation everywhere
function validateUser(user: any): boolean {
return user.email && user.age > 0;
}// โ
Parse once, trust everywhere
const parseUser = (input: unknown): Result => {
// Parse and validate at boundary
return Success(validatedUser);
};
// Now we can trust User type everywhere
function processUser(user: User): Result {
// No validation needed - User is always valid
}
`---
๐ PERFORMANCE
$3
- Immutable Data: Prevents accidental mutations
- Resource Cleanup: Automatic process and file cleanup
- Event-Driven: Non-blocking async operations$3
- Process Isolation: Each agent runs in separate process
- Concurrent Execution: Multiple agents can run simultaneously
- Resource Limits: Configurable timeouts and auto-cleanup---
๐ SAFETY & SECURITY
$3
- No Runtime Type Errors: All data validated at boundaries
- Exhaustive Pattern Matching: All states handled explicitly
- Immutable by Default: Prevents unintended side effects$3
- 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
$3
1. Type-Driven Development: Start with types, not code
2. Railway Oriented Programming: Make errors explicit
3. Pure Functions: Separate business logic from side effects
4. Immutability: All data structures must be immutable
5. Exhaustiveness: Handle every possible state
$3
- [ ] All functions are total and pure
- [ ] Error handling uses Result monads
- [ ] No
any` types or type assertions---
MIT License - see LICENSE file for details.
---
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.