---
name: bot-spawner-extraction
status: completed
created: 2025-10-20T15:25:20Z
updated: 2025-10-22T09:50:00Z
progress: 100%
prd: .claude/prds/bot-spawner-extraction.md
github: https://github.com/BuzzTrail/video-extension/issues/164
---

# Epic: Bot Spawner Extraction

## Overview

**STRATEGY PIVOT (2025-10-21):** Rewrite screenshare bots in Node.js instead of extracting Python code. This eliminates the Python/asyncio hang issue entirely by using a pure Node.js + Playwright + LiveKit stack.

**Core Goal:** Create a dedicated `bot-spawner` Railway service with Node.js-based screenshare bots that replace the problematic Python implementation.

**Key Insight:** The Python asyncio hang on Railway has been a persistent blocker. Rather than debug it, we're eliminating Python entirely by rewriting bots in Node.js using Playwright (which works reliably on Railway) and LiveKit's Node.js SDK.

**Benefits:**
- Single language stack (Node.js/TypeScript everywhere)
- No Python/Node.js hybrid complexity
- Playwright for Node.js is mature and Railway-tested
- LiveKit Node.js SDK is well-supported
- Eliminates asyncio hang issue permanently

## Architecture Decisions

### 1. Service Separation Strategy
- **Decision:** Extract bot spawning to dedicated Railway service with HTTP API
- **Rationale:**
  - Isolates Python environment from Motia/Node.js
  - Enables independent deployment and debugging (2min vs 10min)
  - Provides clear logs separated from API service
  - Allows experimentation with different Python versions/configs
- **Alternative Rejected:** Keep everything in slide-system (current blocker state)

### 2. Communication Pattern
- **Decision:** HTTP REST API between slide-system and bot-spawner
- **Rationale:**
  - Simple, debuggable protocol
  - Railway internal networking (`service.railway.internal`)
  - No breaking changes to existing API contracts
  - Can add request/response logging easily
- **Alternative Rejected:** Message queue (over-engineering for debugging)

### 3. Bot Implementation Language
- **Decision:** Rewrite bots in Node.js/TypeScript using Playwright + LiveKit SDK
- **Rationale:**
  - Eliminates Python asyncio hang issue entirely
  - Single language stack (Node.js everywhere)
  - Playwright for Node.js works reliably on Railway
  - LiveKit has excellent Node.js SDK support
  - Easier debugging and development workflow
  - Railway Railpack optimized for Node.js
- **Alternative Rejected:** Debug Python asyncio (months of effort, unclear if solvable)

### 4. Deployment Strategy
- **Decision:** Use Railway Railpack for pure Node.js deployment
- **Rationale:**
  - No Dockerfile needed (Railpack handles Node.js natively)
  - Fast build times (already proven with bot-spawner skeleton)
  - Playwright installation via npm postinstall script
  - Simple, maintainable deployment pipeline
- **Alternative Rejected:** Docker with Ubuntu 24.04 (unnecessary complexity for Node.js)

### 5. Implementation Strategy
- **Decision:** Incremental port from Python to Node.js with parallel testing
- **Rationale:**
  - Port core bot functionality first (Playwright screenshot + LiveKit streaming)
  - Add Supabase slide control integration second
  - Test each component independently before integration
  - Keep Python bots running in slide-system until Node.js version is validated
- **Alternative Rejected:** Big-bang rewrite (too risky, hard to debug)

## Technical Approach

### Backend Services

#### Bot-Spawner Service (NEW - Node.js Only)
**Technology Stack:**
- Node.js 20 / TypeScript
- Express HTTP server
- Playwright (headless Chromium)
- LiveKit Node.js SDK (@livekit/rtc-node)
- Supabase JS client
- Railway Railpack deployment

**API Endpoints:**
```
POST /api/bots/screenshare/spawn-livekit
POST /api/bots/:id/kill
GET  /api/bots/:id/status
GET  /health
```

**Core Responsibilities:**
- Spawn Node.js bot workers (in-process or child processes)
- Capture Playwright screenshots at 30fps
- Stream screenshots to LiveKit room via screenshare track
- Listen to Supabase Realtime for slide control commands
- Update Supabase `active_bots` table
- Return bot metadata (bot_id, status, room_name)

**Key Implementation Details:**
- Pure TypeScript implementation (no Python)
- Playwright for headless browsing
- LiveKit Node SDK for WebRTC streaming
- Supabase Realtime for slide navigation
- In-memory bot registry for status tracking

#### Slide-System Changes (MINIMAL)
**Modifications:**
- `bot-spawn-livekit.step.ts`: Replace `spawn()` with `fetch()` to bot-spawner
- Add `BOT_SPAWNER_URL` environment variable
- Error handling for HTTP failures
- Request/response logging

**No Changes To:**
- Python bot code (screenshare-bot, tool-forwarder)
- Supabase schema
- Frontend (voice-demo-ui)
- API contracts (100% backward compatible)

### Infrastructure

#### Railway Services
**Current:**
- `slide-system` (Node.js + Python mixed)

**After:**
- `slide-system` (Node.js only, eventually)
- `bot-spawner` (Node.js + Python isolated)

**Networking:**
- Internal Railway DNS: `bot-spawner.railway.internal:3001`
- Not exposed to public internet
- Service-to-service HTTP calls

#### Dockerfile Structure
```dockerfile
FROM ubuntu:24.04

# Install Node.js 20 (for Express server)
RUN curl -fsSL https://deb.nodesource.com/setup_20.x | bash -
RUN apt-get install -y nodejs

# Install Python 3.11 via deadsnakes PPA
RUN add-apt-repository ppa:deadsnakes/ppa
RUN apt-get install -y python3.11 python3.11-venv

# Install uv, Playwright browsers, bot dependencies
# Copy bot code and API server code
# Expose port 3001 and start Express server
```

#### Environment Variables
**Bot-Spawner Service:**
- `LIVEKIT_URL`, `LIVEKIT_API_KEY`, `LIVEKIT_API_SECRET`
- `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`
- `DAILY_PIPECAT_API_KEY` (for tool-forwarder)
- `PORT=3001`

**Slide-System Service:**
- `BOT_SPAWNER_URL=http://bot-spawner.railway.internal:3001`
- (Remove LiveKit vars after cutover)

### Testing & Debugging Approach

#### Phase 0: Pre-Flight Validation (NEW)
1. **Railway Internal Networking Test**
   - Deploy 2 minimal services (hello-world)
   - Verify HTTP calls work via `.railway.internal`
   - Measure latency (must be <50ms)

2. **Python Environment Test**
   - Deploy diagnostic.py script
   - Test asyncio import in isolation
   - Verify Python 3.11 works on Railway

3. **Subprocess Spawn Test**
   - Express server spawns test Python script
   - Verify detached process survives
   - Confirm stdout/stderr capture works

#### Heavy Instrumentation Strategy
```python
# Instrument bot.py startup
print("BOT STARTUP: Python version:", sys.version)
print("BOT STARTUP: asyncio import starting...")
import asyncio
print("BOT STARTUP: asyncio import SUCCESS")
print("BOT STARTUP: Creating event loop...")
loop = asyncio.new_event_loop()
print("BOT STARTUP: Event loop created")
```

**Goal:** Capture WHERE the hang occurs with clear timestamps.

## Implementation Strategy

### Development Phases

**Phase 0: Pre-Flight Validation (1 day) - CRITICAL**
- Validate Railway internal networking
- Test Python 3.11 in minimal bot-spawner
- Deploy diagnostic script, verify asyncio import

**Phase 1: Bot-Spawner Skeleton (2-3 days)**
- Create NX app: `apps/bot-spawner`
- Set up Express server with health endpoint
- Create Railway project and deploy
- Verify service accessible internally

**Phase 2: Port Bot Spawning Logic (3-4 days)**
- Extract spawn logic from `bot-spawn-livekit.step.ts`
- Create Express routes for spawn endpoints
- Test locally, then deploy to Railway staging
- Deploy diagnostic script first, then real bots

**Phase 3: Slide-System Integration (2-3 days)**
- Modify `bot-spawn-livekit.step.ts` to use HTTP API
- Add error handling and retries
- Test end-to-end locally
- Deploy to Railway staging

**Phase 4: Production Cutover (2-3 days)**
- Deploy bot-spawner to production
- Update slide-system environment variables
- Monitor for 48 hours
- Collect data and analyze findings

**Phase 5: Iteration & Learning (Ongoing)**
- Try Python 3.13 if 3.11 works
- Test different Dockerfile bases
- Experiment with spawn methods
- Form hypotheses based on logs

### Risk Mitigation

**High Risk: Railway internal networking fails**
- Mitigation: Test in Phase 0 before building
- Fallback: Use public URLs with API key auth

**High Risk: Asyncio hang persists in bot-spawner**
- Mitigation: This is expected - goal is to SEE where it hangs
- Response: Use clear logs to form next hypothesis

**Medium Risk: Service-to-service latency too high**
- Mitigation: Benchmark in Phase 0
- Acceptance: <50ms is fine for debugging

**Medium Risk: Cost spike from second service**
- Mitigation: Monitor Railway costs daily
- Note: Bot-spawner HTTP server is lightweight (~$5-10/month)

### Rollback Plan

**Triggers:** Within first 72 hours if:
- Bot spawn failure rate >20%
- Service-to-service errors >5%
- Critical bug or data loss

**Procedure (<30 minutes):**
1. Revert slide-system to use direct `spawn()`
2. Pause bot-spawner service
3. Monitor recovery
4. Document learnings

**Testing:** Test rollback in staging before production cutover.

## Task Breakdown Preview

### Phase 0: Pre-Flight Validation
- [ ] **Task 1: Railway Internal Networking Validation** - Deploy test services, verify HTTP calls work
- [ ] **Task 2: Python Environment Validation** - Deploy diagnostic.py, test asyncio import

### Phase 1-2: Bot-Spawner Service
- [ ] **Task 3: Create Bot-Spawner NX App & Railway Service** - Skeleton Express app, Dockerfile, health endpoint
- [ ] **Task 4: Port Bot Spawning Logic** - Extract spawn code, create API endpoints, test locally

### Phase 3: Integration
- [ ] **Task 5: Update Slide-System Integration** - HTTP client in Motia steps, error handling

### Phase 4: Deployment
- [ ] **Task 6: Production Cutover** - Deploy both services, monitor, collect data

### Phase 5: Learning & Iteration
- [ ] **Task 7: Analyze Findings & Experiment** - Review logs, test hypotheses, iterate on configs

**Total: 7 tasks** (simplified from PRD's 5 phases)

## Dependencies

### External Dependencies (BLOCKERS)
1. **Railway Internal Networking** - Must work for service-to-service HTTP
   - Test: Phase 0 validation
   - Risk: HIGH if fails
   - Mitigation: Fallback to public URLs with auth

2. **Python 3.11 on Railway** - Must install successfully
   - Test: Phase 0 diagnostic script
   - Risk: MEDIUM
   - Mitigation: Known to work from voice-agent

3. **Supabase Availability** - Database must remain stable
   - Risk: LOW
   - Mitigation: No schema changes

### Internal Dependencies
1. **Current Bot Code** - Must work when spawned from new service
   - Assumption: Bot code is environment-agnostic
   - Test: Deploy unchanged bot.py from bot-spawner

2. **NX Workspace** - Must support custom Dockerfiles
   - Risk: LOW (already proven)

3. **Railway Build System** - Must complete in reasonable time
   - Target: <10 minutes
   - Risk: LOW

## Success Criteria (Technical)

### **REFRAMED: Success = Learning, Not Fixing**

#### Primary Success (Learning Goals)
- ✅ **Clear visibility** into bot spawn process via isolated logs
- ✅ **Identify WHERE asyncio hangs** with instrumented startup
- ✅ **Ability to test** 5+ different configs in one day (vs current blocker state)
- ✅ **Data collection** to form informed hypotheses about root cause

#### Secondary Success (If Lucky)
- ✅ Bots work in bot-spawner (proves Motia interaction issue)
- ✅ Bots work with Python 3.11 but not 3.13 (proves version issue)
- ✅ Bots work with different base image (proves environment issue)

#### Operational Success
- ✅ Bot-spawner deploys successfully to Railway
- ✅ Service-to-service HTTP calls work (<50ms latency)
- ✅ Can deploy bot changes in 2 minutes vs 10 minutes
- ✅ Zero breaking changes to existing API contracts

#### Failure Acceptance
- ❌ If bots still don't work after extraction → **STILL SUCCESS**
  - Why: We'll have clear logs showing exactly where/why
  - Next: Use findings to try Docker-in-Docker, PM2, or other spawn methods

### Performance Benchmarks (Non-Critical)
- Bot spawn latency <5 seconds (if working)
- HTTP overhead <50ms
- No regression in voice-demo-ui experience

### Quality Gates (Critical)
- ✅ Phase 0 validation passes (networking, Python env)
- ✅ Rollback tested in staging before production
- ✅ Zero downtime during cutover
- ✅ Instrumentation captures full startup sequence

## Estimated Effort

**Total Timeline: 2-3 weeks**

**Phase 0 (Pre-Flight):** 1 day
- Railway networking test: 2-4 hours
- Python environment test: 2-4 hours

**Phase 1-2 (Bot-Spawner):** 5-7 days
- NX app creation: 1 day
- Dockerfile iteration: 1-2 days
- Port spawning logic: 2-3 days
- Local testing: 1 day

**Phase 3 (Integration):** 2-3 days
- Slide-system HTTP client: 1 day
- Error handling: 0.5 days
- Staging deployment: 0.5-1 day

**Phase 4 (Cutover):** 2-3 days
- Production deployment: 0.5 days
- Monitoring period: 2 days
- Initial analysis: 0.5 days

**Phase 5 (Iteration):** Ongoing
- Experiment velocity: ~3-5 tests per day (vs current 1 per day)

**Resource Requirements:**
- 1 developer, part-time (50% allocation)
- Railway budget: +$5-10/month for bot-spawner service

**Critical Path:**
1. Phase 0 validation (BLOCKER)
2. Bot-spawner deployment
3. Slide-system integration
4. Production cutover

**Risk Buffer:** +1 week for unexpected Railway issues

**Success Metric:** Even if bots don't work, we gain 3-5x faster iteration speed and clear diagnostic data.

## Completion Summary

**Epic Status: COMPLETED (2025-10-22)**

All phases of the Bot Spawner Extraction epic have been successfully completed:

✅ **Bot-Spawner Service Deployed** - Dedicated Railway service running on Node.js 20
✅ **Node.js Screenshare Bot** - Pure TypeScript implementation with Playwright + LiveKit
✅ **Database Type Safety** - Supabase TypeScript types generated and documented
✅ **Production Cutover** - Service deployed to Railway with health checks passing
✅ **Documentation Updated** - TypeScript type generation process documented

**Key Achievements:**
- Eliminated Python asyncio hang issue by rewriting bots in Node.js
- Achieved isolated bot-spawner service with 2-minute deploy times (vs 10 minutes)
- Established type-safe Supabase integration with proper TypeScript types
- Zero breaking changes to existing API contracts
- Bot-spawner successfully serving 86 active bots on Railway

**Production Status:**
- Service: `bot-spawner` on Railway (project: buzztrail-voice-agent)
- Health: ✅ Passing (last check: 2025-10-22T09:07:42Z)
- Active Bots: 86
- Node Version: v22.21.0

**Next Steps:**
- Monitor bot-spawner service in production
- Track bot spawn success rates
- Consider additional bot types (tool-forwarder) if needed

## Tasks Created

**Phase 0: Pre-Flight (OBSOLETE - Strategy Pivot)**
- [x] [#155](https://github.com/BuzzTrail/video-extension/issues/155) - Railway Internal Networking Validation (CLOSED - Not needed)
- [x] [#157](https://github.com/BuzzTrail/video-extension/issues/157) - Python Environment Validation (CLOSED - Not needed)

**Phase 1: Bot-Spawner Service**
- [x] [#162](https://github.com/BuzzTrail/video-extension/issues/162) - Create Bot-Spawner NX App & Railway Service (COMPLETED)

**Phase 2: Node.js Bot Implementation (NEW APPROACH)**
- [x] [#165](https://github.com/BuzzTrail/video-extension/issues/165) - Implement Node.js Screenshare Bot (COMPLETED)
- [x] [#166](https://github.com/BuzzTrail/video-extension/issues/166) - Implement LiveKit Video Streaming for Screenshare Bot (COMPLETED)

**Phase 3: Integration (COMPLETED)**
- [x] [#160](https://github.com/BuzzTrail/video-extension/issues/160) - Update Slide-System Integration (COMPLETED - includes TypeScript type generation)

**Phase 4: Production (COMPLETED)**
- [x] [#163](https://github.com/BuzzTrail/video-extension/issues/163) - Production Cutover (COMPLETED - bot-spawner deployed to Railway)

**Closed/Obsolete Tasks:**
- [x] [#156](https://github.com/BuzzTrail/video-extension/issues/156) - Port Bot Spawning Logic (CLOSED - Replaced by #165)
- [x] [#158](https://github.com/BuzzTrail/video-extension/issues/158) - Analyze Findings & Experiment (OBSOLETE - Not needed with Node.js approach)

**Total tasks:** 8
**Parallel tasks:** 1 (#157)
**Sequential tasks:** 7
**Estimated total effort:** 66-92 hours (2-3 weeks with 50% allocation)

**Critical Path:** #155 → #162 → #165 → #166 → #160 → #163

**Task Dependencies:**
```
     #155 (Networking) [CLOSED]
      ↓
#157 (Python) [CLOSED] → #162 (Bot-Spawner App) [COMPLETED]
                          ↓
                         #165 (Node.js Bot Core) [IN PROGRESS]
                          ↓
                         #166 (Video Streaming) [NEW]
                          ↓
                         #160 (Integration)
                          ↓
                         #163 (Production)

Obsolete: #156 (replaced by #165), #158 (not needed)
```
