---
name: Port Bot Spawning Logic
status: closed
created: 2025-10-20T15:30:53Z
updated: 2025-10-21T13:57:40Z
closed_reason: Strategy pivot - Replaced by Node.js bot rewrite approach
github: https://github.com/BuzzTrail/video-extension/issues/156
depends_on: [162]
parallel: false
conflicts_with: [005]
---

# Task: Port Bot Spawning Logic

## Description

Create Express API endpoints in bot-spawner that proxy bot spawn requests to slide-system. Bot-spawner is a **pure Node.js service** that provides a management layer for bot operations.

**Approach:**
1. Create Express API endpoints that match slide-system's bot API
2. Implement HTTP proxy calls to slide-system internal service
3. Add request/response logging and monitoring
4. Implement bot management endpoints (kill, status, logs)
5. Test locally before deploying to Railway

**Architecture:** Bot-spawner (Node.js proxy) → slide-system (Python bot execution)

**Benefit:** Clean separation, simple Node.js-only service, no Python+Node.js hybrid complexity.

## Acceptance Criteria

- [ ] Express proxy endpoints implemented:
  - `POST /api/bots/screenshare/spawn-livekit` → forwards to slide-system
  - `POST /api/bots/tool-forwarder/spawn` → forwards to slide-system
  - `POST /api/bots/:id/kill` → forwards to slide-system
  - `GET /api/bots/:id/status` → forwards to slide-system
  - `GET /api/bots/:id/logs` → forwards to slide-system
- [ ] HTTP client configured with Railway internal networking (`slide-system.railway.internal`)
- [ ] Request/response logging for all proxy calls
- [ ] Error handling for slide-system unavailability
- [ ] Local testing: Proxy endpoints work with local slide-system
- [ ] Deployed to Railway staging
- [ ] End-to-end test: External client → bot-spawner → slide-system → bot spawns

## Technical Details

### Implementation Approach

**1. Configure Slide-System HTTP Client:**

Create `apps/bot-spawner/src/config/slide-system-client.ts`:
```typescript
import axios from 'axios';

const SLIDE_SYSTEM_URL = process.env.SLIDE_SYSTEM_URL || 'http://localhost:3000';

export const slideSystemClient = axios.create({
  baseURL: SLIDE_SYSTEM_URL,
  timeout: 30000, // 30 second timeout
  headers: {
    'Content-Type': 'application/json'
  }
});

// Add request logging
slideSystemClient.interceptors.request.use(
  (config) => {
    console.log(`[Proxy Request] ${config.method?.toUpperCase()} ${config.url}`);
    return config;
  },
  (error) => {
    console.error('[Proxy Request Error]', error);
    return Promise.reject(error);
  }
);

// Add response logging
slideSystemClient.interceptors.response.use(
  (response) => {
    console.log(`[Proxy Response] ${response.status} ${response.config.url}`);
    return response;
  },
  (error) => {
    console.error('[Proxy Response Error]', error.message);
    return Promise.reject(error);
  }
);
```

**2. Implement Proxy Endpoints (`apps/bot-spawner/src/routes/bots.ts`):**
```typescript
import { Router } from 'express';
import { slideSystemClient } from '../config/slide-system-client';

const router = Router();

// Proxy: Spawn LiveKit screenshare bot
router.post('/api/bots/screenshare/spawn-livekit', async (req, res) => {
  try {
    const response = await slideSystemClient.post('/api/bots/screenshare/spawn-livekit', req.body);
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error('[Proxy Error] spawn-livekit:', error);
    res.status(error.response?.status || 500).json({
      error: 'Failed to spawn bot',
      details: error.message
    });
  }
});

// Proxy: Spawn tool-forwarder bot
router.post('/api/bots/tool-forwarder/spawn', async (req, res) => {
  try {
    const response = await slideSystemClient.post('/api/bots/tool-forwarder/spawn', req.body);
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error('[Proxy Error] tool-forwarder spawn:', error);
    res.status(error.response?.status || 500).json({
      error: 'Failed to spawn bot',
      details: error.message
    });
  }
});

// Proxy: Kill bot
router.post('/api/bots/:id/kill', async (req, res) => {
  try {
    const response = await slideSystemClient.post(`/api/bots/${req.params.id}/kill`);
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error('[Proxy Error] kill bot:', error);
    res.status(error.response?.status || 500).json({
      error: 'Failed to kill bot',
      details: error.message
    });
  }
});

// Proxy: Get bot status
router.get('/api/bots/:id/status', async (req, res) => {
  try {
    const response = await slideSystemClient.get(`/api/bots/${req.params.id}/status`);
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error('[Proxy Error] bot status:', error);
    res.status(error.response?.status || 500).json({
      error: 'Failed to get bot status',
      details: error.message
    });
  }
});

// Proxy: Get bot logs
router.get('/api/bots/:id/logs', async (req, res) => {
  try {
    const response = await slideSystemClient.get(`/api/bots/${req.params.id}/logs`, {
      params: req.query
    });
    res.status(response.status).json(response.data);
  } catch (error) {
    console.error('[Proxy Error] bot logs:', error);
    res.status(error.response?.status || 500).json({
      error: 'Failed to get bot logs',
      details: error.message
    });
  }
});

export default router;
```

**3. Environment Variables:**
```bash
# Local development
SLIDE_SYSTEM_URL=http://localhost:3000

# Railway production
SLIDE_SYSTEM_URL=http://slide-system.railway.internal:8080
```

### Key Considerations

- **Exact Same Logic:** Copy spawn code from slide-system, minimal changes
- **Detached Processes:** Must use `detached: true` and `unref()`
- **Log Capture:** Stdout/stderr to files for debugging
- **Heavy Instrumentation:** Log every step of spawn process
- **Diagnostic First:** Test asyncio import before real bot deployment
- **No Bot Code Changes:** Bot.py remains unchanged (validates environment-agnostic assumption)

### Files Affected

**New files:**
- `apps/bot-spawner/bots/screenshare-bot/` (copied from slide-system)
- `apps/bot-spawner/bots/tool-forwarder/` (copied from slide-system)
- `apps/bot-spawner/src/routes/spawn-livekit.ts`
- `apps/bot-spawner/src/routes/spawn-tool-forwarder.ts`
- `apps/bot-spawner/src/routes/kill.ts`
- `apps/bot-spawner/src/routes/status.ts`
- `apps/bot-spawner/src/routes/logs.ts`

**Modified files:**
- `apps/bot-spawner/src/main.ts` (register routes)
- `apps/bot-spawner/railway.json` (add buildCommand for Python setup)
- `apps/bot-spawner/install-bots.sh` (new script to install Python deps)

## Dependencies

**Depends On:**
- [ ] Task 003: Bot-spawner service created and deployed

**Conflicts With:**
- Task 005 (slide-system integration) modifies same bot spawn flow

**External:**
- [ ] Python bot code works when spawned from new environment
- [ ] Playwright browsers install successfully in Railway container
- [ ] Supabase credentials have permissions for active_bots table

## Effort Estimate

- **Size:** L (Large)
- **Hours:** 12-16 hours
  - Copy bot code: 1 hour
  - Update Dockerfile for Python deps: 2-3 hours
  - Implement spawn endpoints: 4-5 hours
  - Implement kill/status/logs endpoints: 2 hours
  - Local testing: 2-3 hours
  - Deploy diagnostic script: 1 hour
  - Deploy real bots to Railway: 2 hours
  - Troubleshoot and iterate: 2-3 hours
- **Parallel:** false (blocks Task 005)

## Definition of Done

- [ ] Diagnostic script deployed and verifies asyncio import works
- [ ] Bot spawns successfully locally (joins LiveKit room)
- [ ] Bot spawns successfully on Railway staging
- [ ] Bot logs captured to files (`/app/logs/bot-*.log`)
- [ ] Supabase `active_bots` table updated correctly
- [ ] Bot survives bot-spawner service restart (detached process works)
- [ ] Kill endpoint terminates bot process
- [ ] Status endpoint returns bot metadata
- [ ] Logs endpoint streams bot log file
- [ ] Heavy instrumentation shows WHERE in startup sequence bot hangs (if any)

**Validation:**
```bash
# Test spawn endpoint locally
curl -X POST http://localhost:3001/api/bots/screenshare/spawn-livekit \
  -H "Content-Type: application/json" \
  -d '{
    "room_name": "test-room",
    "deck_url": "https://example.com/deck",
    "session_id": "test-session",
    "screenshare_token": "test-token"
  }'

# Check bot logs
curl http://localhost:3001/api/bots/{bot_id}/logs?tail=100

# Verify bot in Supabase
# Check active_bots table for status = 'running'
```

**Success Metrics:**
- If bot works on Railway → **SUCCESS!** (proves Motia interaction issue)
- If bot still hangs → **STILL SUCCESS!** (we see WHERE via logs)
