feat: v4 — TUI fight loop, rate limiting, webhook tooling, expanded choreographies

- Fight loop CLI with TUI renderer (ink-style terminal UI)
- Rate limiting middleware for API routes
- Queue cooldowns wired into orchestrator after fights
- Webhook test utility for bot debugging
- API docs route
- Expanded FightScene choreographies and weapon props
- Fix Drizzle transaction execution in orchestrator
- Schema additions, scoring/challenge/mock expansions

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
Dorian
2026-03-07 00:14:46 +00:00
co-authored by Claude Opus 4.6
parent 2c0323d5fb
commit 4d8b18a58a
24 changed files with 2973 additions and 721 deletions
+50 -12
View File
@@ -2,11 +2,14 @@ import { Hono } from 'hono'
import { nanoid } from 'nanoid'
import { createHash, randomBytes } from 'crypto'
import { db, schema } from '../db/index.js'
import { eq } from 'drizzle-orm'
import { eq, sql } from 'drizzle-orm'
import { isAllowedWebhookUrl } from '../engine/orchestrator.js'
import { testWebhook } from '../engine/webhook-test.js'
import { rateLimit } from '../middleware/rate-limit.js'
export const authRouter = new Hono()
// Login with Nostr pubkey — returns bot if one exists
// Login with Nostr pubkey
authRouter.post('/login', async (c) => {
const body = await c.req.json()
const { pubkey } = body
@@ -27,6 +30,7 @@ authRouter.post('/login', async (c) => {
winStreak: schema.bots.winStreak,
bestStreak: schema.bots.bestStreak,
tier: schema.bots.tier,
isActive: schema.bots.isActive,
}).from(schema.bots).where(eq(schema.bots.publicKey, pubkey)).limit(1)
if (rows.length === 0) {
@@ -37,7 +41,7 @@ authRouter.post('/login', async (c) => {
})
// Register a new bot with Nostr pubkey
authRouter.post('/register', async (c) => {
authRouter.post('/register', rateLimit(3600_000, 5), async (c) => {
const body = await c.req.json()
const { pubkey, name, webhookUrl, archetype, profilePicUrl } = body
@@ -53,6 +57,8 @@ authRouter.post('/register', async (c) => {
return c.json({ error: 'Name must be alphanumeric, hyphens, or underscores.' }, 400)
}
const normalizedName = name.toLowerCase()
if (!webhookUrl || typeof webhookUrl !== 'string') {
return c.json({ error: 'webhookUrl is required.' }, 400)
}
@@ -63,6 +69,10 @@ authRouter.post('/register', async (c) => {
return c.json({ error: 'webhookUrl must be a valid URL.' }, 400)
}
if (!isAllowedWebhookUrl(webhookUrl)) {
return c.json({ error: 'webhookUrl must not point to private/internal addresses.' }, 400)
}
// Check pubkey not already used
const existingPk = await db.select({ id: schema.bots.id })
.from(schema.bots)
@@ -73,24 +83,34 @@ authRouter.post('/register', async (c) => {
return c.json({ error: 'This Nostr key already has a bot.' }, 409)
}
// Check name not taken
// Check name not taken (case-insensitive)
const existingName = await db.select({ id: schema.bots.id })
.from(schema.bots)
.where(eq(schema.bots.name, name))
.where(eq(sql`LOWER(${schema.bots.name})`, normalizedName))
.limit(1)
if (existingName.length > 0) {
return c.json({ error: 'A bot with that name already exists.' }, 409)
}
// Test the webhook
const testResult = await testWebhook(webhookUrl)
if (!testResult.reachable || !testResult.validResponse) {
return c.json({
error: 'Webhook verification failed.',
details: testResult.error || 'Webhook must return {"answer": "..."} as JSON.',
latencyMs: testResult.latencyMs,
}, 422)
}
const id = nanoid(12)
const secret = randomBytes(32).toString('hex')
await db.insert(schema.bots).values({
id,
name,
webhookUrl: webhookUrl,
avatarSeed: name,
name: normalizedName,
webhookUrl,
avatarSeed: normalizedName,
archetype: archetype || 'standard',
secretHash: createHash('sha256').update(secret).digest('hex'),
publicKey: pubkey,
@@ -100,9 +120,10 @@ authRouter.post('/register', async (c) => {
return c.json({
id,
name,
name: normalizedName,
archetype: archetype || 'standard',
message: 'Bot registered.',
webhookLatencyMs: testResult.latencyMs,
message: 'Bot registered. Webhook verified.',
}, 201)
})
@@ -124,8 +145,25 @@ authRouter.post('/update', async (c) => {
return c.json({ error: 'No bot found for this key.' }, 404)
}
const updates: Record<string, string> = {}
if (webhookUrl) updates.webhookUrl = webhookUrl
const updates: Record<string, unknown> = {}
if (webhookUrl) {
if (!isAllowedWebhookUrl(webhookUrl)) {
return c.json({ error: 'webhookUrl must not point to private/internal addresses.' }, 400)
}
// Test new webhook before accepting
const testResult = await testWebhook(webhookUrl)
if (!testResult.reachable || !testResult.validResponse) {
return c.json({
error: 'Webhook verification failed.',
details: testResult.error,
}, 422)
}
updates.webhookUrl = webhookUrl
updates.consecutiveErrors = 0
updates.isActive = true
}
if (profilePicUrl) updates.profilePicUrl = profilePicUrl
if (Object.keys(updates).length > 0) {
+199 -14
View File
@@ -2,8 +2,11 @@ import { Hono } from 'hono'
import { nanoid } from 'nanoid'
import { createHash, randomBytes } from 'crypto'
import { db, schema } from '../db/index.js'
import { eq, or, desc } from 'drizzle-orm'
import { eq, or, desc, sql } from 'drizzle-orm'
import { TIER_NAMES, TIER_COLORS } from '../engine/scoring.js'
import { isAllowedWebhookUrl } from '../engine/orchestrator.js'
import { testWebhook } from '../engine/webhook-test.js'
import { rateLimit } from '../middleware/rate-limit.js'
export const botsRouter = new Hono()
@@ -11,8 +14,8 @@ function hashSecret(secret: string): string {
return createHash('sha256').update(secret).digest('hex')
}
// Register a new bot
botsRouter.post('/', async (c) => {
// Rate limit registration: 5 per hour per IP
botsRouter.post('/', rateLimit(3600_000, 5), async (c) => {
const body = await c.req.json()
const { name, webhook_url, avatar_seed } = body
@@ -24,6 +27,9 @@ botsRouter.post('/', async (c) => {
return c.json({ error: 'Name must be alphanumeric, hyphens, or underscores.' }, 400)
}
// Force lowercase for case-insensitive uniqueness
const normalizedName = name.toLowerCase()
if (!webhook_url || typeof webhook_url !== 'string') {
return c.json({ error: 'webhook_url is required.' }, 400)
}
@@ -34,33 +40,49 @@ botsRouter.post('/', async (c) => {
return c.json({ error: 'webhook_url must be a valid URL.' }, 400)
}
// Check for duplicate name
// SSRF check
if (!isAllowedWebhookUrl(webhook_url)) {
return c.json({ error: 'webhook_url must not point to private/internal addresses.' }, 400)
}
// Check for duplicate name (case-insensitive)
const existing = await db.select({ id: schema.bots.id })
.from(schema.bots)
.where(eq(schema.bots.name, name))
.where(eq(sql`LOWER(${schema.bots.name})`, normalizedName))
.limit(1)
if (existing.length > 0) {
return c.json({ error: 'A bot with that name already exists.' }, 409)
}
// Test the webhook before accepting registration
const testResult = await testWebhook(webhook_url)
if (!testResult.reachable || !testResult.validResponse) {
return c.json({
error: 'Webhook verification failed.',
details: testResult.error || 'Webhook must return {"answer": "..."} as JSON.',
latencyMs: testResult.latencyMs,
}, 422)
}
const id = nanoid(12)
const secret = randomBytes(32).toString('hex')
await db.insert(schema.bots).values({
id,
name,
name: normalizedName,
webhookUrl: webhook_url,
avatarSeed: avatar_seed || name,
avatarSeed: avatar_seed || normalizedName,
secretHash: hashSecret(secret),
createdAt: new Date().toISOString(),
})
return c.json({
id,
name,
name: normalizedName,
secret,
message: 'Bot registered. Save your secret -- it will not be shown again.',
webhookLatencyMs: testResult.latencyMs,
message: 'Bot registered. Webhook verified. Save your secret -- it will not be shown again.',
}, 201)
})
@@ -98,7 +120,7 @@ botsRouter.get('/:name', async (c) => {
tier: schema.bots.tier,
isActive: schema.bots.isActive,
createdAt: schema.bots.createdAt,
}).from(schema.bots).where(eq(schema.bots.name, name)).limit(1)
}).from(schema.bots).where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase())).limit(1)
if (rows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
@@ -107,7 +129,7 @@ botsRouter.get('/:name', async (c) => {
return c.json(rows[0])
})
// Get bot stats full account page data
// Get bot stats -- full account page data
botsRouter.get('/:name/stats', async (c) => {
const name = c.req.param('name')
const botRows = await db.select({
@@ -123,7 +145,7 @@ botsRouter.get('/:name/stats', async (c) => {
tier: schema.bots.tier,
isActive: schema.bots.isActive,
createdAt: schema.bots.createdAt,
}).from(schema.bots).where(eq(schema.bots.name, name)).limit(1)
}).from(schema.bots).where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase())).limit(1)
if (botRows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
@@ -190,12 +212,42 @@ botsRouter.get('/:name/stats', async (c) => {
})
})
// Health check a bot's webhook
// Test a bot's webhook with a real challenge
botsRouter.post('/:name/test', async (c) => {
const name = c.req.param('name')
const rows = await db.select({
id: schema.bots.id,
webhookUrl: schema.bots.webhookUrl,
}).from(schema.bots).where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase())).limit(1)
if (rows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
}
const result = await testWebhook(rows[0].webhookUrl)
// If test passes and bot was deactivated, reactivate it
if (result.reachable && result.validResponse) {
await db.update(schema.bots).set({
consecutiveErrors: 0,
isActive: true,
}).where(eq(schema.bots.id, rows[0].id))
}
return c.json({
...result,
message: result.validResponse
? 'Webhook verified. Bot is ready to fight.'
: 'Webhook test failed. Fix the issue and try again.',
})
})
// Legacy health check
botsRouter.post('/:name/health', async (c) => {
const name = c.req.param('name')
const rows = await db.select({
webhookUrl: schema.bots.webhookUrl,
}).from(schema.bots).where(eq(schema.bots.name, name)).limit(1)
}).from(schema.bots).where(eq(sql`LOWER(${schema.bots.name})`, name.toLowerCase())).limit(1)
if (rows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
@@ -217,3 +269,136 @@ botsRouter.post('/:name/health', async (c) => {
return c.json({ reachable: false, status: 0 })
}
})
// ══════════════════════════════════════════════════════════
// Developer Tools
// ══════════════════════════════════════════════════════════
import { pickChallenge, type Challenge } from '../engine/challenges.js'
import { checkAnswer } from '../engine/answers.js'
// Test a bot's webhook with a real challenge and score the answer
botsRouter.post('/:name/test-challenge', async (c) => {
const name = c.req.param('name')
const rows = await db.select({
id: schema.bots.id,
webhookUrl: schema.bots.webhookUrl,
}).from(schema.bots).where(eq(schema.bots.name, name)).limit(1)
if (rows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
}
const bot = rows[0]
// Pick a random factual challenge so we can verify the answer
const challenge = pickChallenge(new Set(), null)
const payload = {
fight_id: 'test_challenge',
round: 0,
type: challenge.type,
challenge: challenge.prompt,
constraints: {
timeout_ms: challenge.timeout_ms,
max_tokens: 500,
},
opponent: { name: 'test_bot', wins: 0, losses: 0 },
arena: 'test',
arena_modifier: null,
}
const start = Date.now()
try {
const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), challenge.timeout_ms)
const res = await fetch(bot.webhookUrl, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
signal: controller.signal,
})
clearTimeout(timeout)
const latencyMs = Date.now() - start
if (!res.ok) {
return c.json({
passed: false,
challenge: { type: challenge.type, label: challenge.label, prompt: challenge.prompt, scoring: challenge.scoring },
error: `Webhook returned HTTP ${res.status}. Expected 200.`,
latencyMs,
})
}
const text = await res.text()
let data: { answer?: string; trash_talk?: string }
try {
data = JSON.parse(text)
} catch {
return c.json({
passed: false,
challenge: { type: challenge.type, label: challenge.label, prompt: challenge.prompt, scoring: challenge.scoring },
error: `Response is not valid JSON. Got: ${text.slice(0, 200)}`,
latencyMs,
})
}
if (typeof data.answer !== 'string') {
return c.json({
passed: false,
challenge: { type: challenge.type, label: challenge.label, prompt: challenge.prompt, scoring: challenge.scoring },
error: 'Response JSON missing "answer" field (string). Got: ' + JSON.stringify(data).slice(0, 200),
latencyMs,
yourResponse: data,
})
}
// Score the answer
const isFactual = challenge.scoring === 'factual' && challenge.answers && challenge.answers.length > 0
let score = 0
let correct = false
if (isFactual) {
score = checkAnswer(data.answer, challenge.answers!)
correct = score > 0
}
return c.json({
passed: true,
challenge: {
type: challenge.type,
label: challenge.label,
prompt: challenge.prompt,
scoring: challenge.scoring,
...(isFactual ? { acceptedAnswers: challenge.answers } : {}),
},
yourAnswer: data.answer,
yourTrashTalk: data.trash_talk || null,
latencyMs,
...(isFactual ? {
correct,
confidence: score,
verdict: correct
? score >= 1.0 ? 'PERFECT MATCH' : 'PARTIAL MATCH (still counts as correct)'
: 'WRONG — your answer did not match any accepted answer',
} : {
verdict: 'CREATIVE — no correct answer, scored on quality + speed',
}),
})
} catch (err: unknown) {
const latencyMs = Date.now() - start
const isAbort = err instanceof Error && err.name === 'AbortError'
return c.json({
passed: false,
challenge: { type: challenge.type, label: challenge.label, prompt: challenge.prompt, scoring: challenge.scoring },
error: isAbort
? `Webhook timed out after ${challenge.timeout_ms}ms. Your bot must respond faster.`
: `Connection failed: ${err instanceof Error ? err.message : String(err)}`,
latencyMs,
})
}
})
+153
View File
@@ -0,0 +1,153 @@
import { Hono } from 'hono'
import { getAllChallengeTypes } from '../engine/challenges.js'
export const docsRouter = new Hono()
docsRouter.get('/webhook', (c) => {
return c.json({
title: 'BOTFIGHTS Webhook API',
version: '1.0',
overview: 'Your bot receives fight challenges via POST requests to your webhook URL. Respond with JSON containing your answer.',
webhook_request: {
method: 'POST',
content_type: 'application/json',
description: 'Sent to your webhook URL for each round of a fight.',
fields: {
fight_id: { type: 'string', description: 'Unique ID of this fight (12 chars).' },
round: { type: 'number', description: 'Round number (1-10).' },
type: { type: 'string', description: 'Challenge type (e.g. "speed_blitz", "riddle", "roast_battle").', values: getAllChallengeTypes() },
challenge: { type: 'string', description: 'The question or prompt to answer.' },
constraints: {
type: 'object',
fields: {
timeout_ms: { type: 'number', description: 'Maximum time to respond in milliseconds (8000-20000).' },
max_tokens: { type: 'number', description: 'Suggested max response length (500).' },
},
},
opponent: {
type: 'object',
fields: {
name: { type: 'string', description: 'Opponent bot name.' },
wins: { type: 'number', description: 'Opponent total wins.' },
losses: { type: 'number', description: 'Opponent total losses.' },
},
},
arena: { type: 'string', description: 'Arena ID for this fight.' },
arena_modifier: { type: 'string|null', description: 'Special arena rule (e.g. "speed_2x"). Can be null.' },
},
example: {
fight_id: 'abc123def456',
round: 1,
type: 'speed_blitz',
challenge: 'What is the capital of Australia?',
constraints: { timeout_ms: 8000, max_tokens: 500 },
opponent: { name: 'chad_gpt', wins: 48, losses: 10 },
arena: 'datacenter',
arena_modifier: null,
},
},
webhook_response: {
content_type: 'application/json',
status_code: 200,
description: 'Return JSON with your answer. Must respond within the timeout.',
fields: {
answer: { type: 'string', required: true, description: 'Your answer to the challenge. Max 2000 characters.' },
trash_talk: { type: 'string', required: false, description: 'Optional smack talk shown to spectators. Max 200 characters.' },
},
example: {
answer: 'Canberra',
trash_talk: 'Too easy. Next question please.',
},
},
scoring: {
factual_challenges: {
description: 'Questions with correct answers. Your answer is checked against accepted answers with fuzzy matching.',
matching_rules: [
'Case insensitive: "Canberra" = "canberra"',
'Punctuation stripped: "can\'t" = "cant"',
'Numbers: "8" = "eight" = "Eight"',
'Plurals: "tardigrade" = "tardigrades"',
'Contractions: "don\'t" = "do not"',
'Containment: "The answer is Canberra" matches "canberra"',
'Leading articles stripped: "A map" = "map"',
'True/false: starts with "true"/"false", or "yes"/"no"/"correct"/"wrong"',
],
scoring_rules: [
'Both correct: faster bot wins the round (speed tiebreaker)',
'One correct, one wrong: correct bot wins big (9+ points)',
'Both wrong: speed tiebreaker in low range',
],
},
creative_challenges: {
description: 'Open-ended prompts with no correct answer. Scored on response quality and speed.',
scoring_rules: [
'Response 20-500 characters: best score',
'Very short (<20 chars): penalized',
'Very long (>500 chars): slightly penalized',
'Faster responses score higher',
],
},
},
failure_modes: {
timeout: 'Your bot did not respond within timeout_ms. You lose the round and take 1.5x damage.',
error: 'Your webhook returned a non-200 status or crashed. Same penalty as timeout.',
invalid_json: 'Response body is not valid JSON. Treated as an error.',
missing_answer: 'JSON response has no "answer" field. Treated as an error.',
deactivation: 'After 5 consecutive errors, your bot is auto-deactivated. Fix your webhook and re-register.',
},
challenge_types: {
factual: [
{ type: 'speed_blitz', label: 'Speed Blitz', timeout_ms: 8000, description: 'Quick knowledge questions. Speed matters.' },
{ type: 'math_blitz', label: 'Math Blitz', timeout_ms: 10000, description: 'Math problems. Return the number.' },
{ type: 'riddle', label: 'Riddle Me This', timeout_ms: 15000, description: 'Classic riddles. Think laterally.' },
{ type: 'hallucination_check', label: 'Hallucination Check', timeout_ms: 12000, description: 'True/false statements. Spot the myth.' },
{ type: 'trap_card', label: 'Trap Card', timeout_ms: 12000, description: 'Prompt injection attempts. Answer the real question.' },
{ type: 'magic_duel', label: 'Logic Duel', timeout_ms: 12000, description: 'Trick questions and lateral thinking.' },
{ type: 'sports_showdown', label: 'Sports Showdown', timeout_ms: 8000, description: 'Sports trivia.' },
{ type: 'vehicle_mayhem', label: 'Vehicle Mayhem', timeout_ms: 8000, description: 'Transport and vehicle facts.' },
{ type: 'nature_clash', label: 'Nature Clash', timeout_ms: 10000, description: 'Nature and biology facts.' },
{ type: 'animal_kingdom', label: 'Animal Kingdom', timeout_ms: 10000, description: 'Animal trivia.' },
{ type: 'hack_battle', label: 'Hack Battle', timeout_ms: 12000, description: 'Cybersecurity knowledge.' },
],
creative: [
{ type: 'roast_battle', label: 'Roast Battle', timeout_ms: 15000, description: 'Trash talk and roasts. Be funny.' },
{ type: 'creative_writing', label: 'Creative Writing', timeout_ms: 20000, description: 'Short stories and creative prose.' },
{ type: 'meme_war', label: 'Meme War', timeout_ms: 12000, description: 'Meme references and internet humor.' },
{ type: 'code_golf', label: 'Code Golf', timeout_ms: 20000, description: 'Write the shortest code possible.' },
{ type: 'wrestling_match', label: 'Wrestling Match', timeout_ms: 15000, description: 'Debate and argumentation.' },
],
},
testing: {
test_webhook: {
method: 'POST',
path: '/api/bots/{name}/test-webhook',
description: 'Tests basic connectivity. Sends a dummy challenge and checks if your webhook responds with valid JSON.',
},
test_challenge: {
method: 'POST',
path: '/api/bots/{name}/test-challenge',
description: 'Sends a REAL challenge to your webhook and scores the answer. Shows whether your answer would be marked correct.',
},
mock_fight: {
method: 'POST',
path: '/api/queue/join/{botId}',
description: 'Join the fight queue. If no opponents, you fight a mock bot after 3 seconds.',
},
},
tips: [
'For factual questions, return JUST the answer. "Canberra" is better than "I think the answer might be Canberra because..."',
'Speed matters! Both correct → faster bot wins. Respond as fast as you can.',
'For true/false, start your response with "true" or "false".',
'Trap Card challenges include prompt injection attempts. Ignore the tricks, answer the real question.',
'For creative challenges, aim for 100-400 characters. Too short or too long is penalized.',
'Your trash_talk is shown to spectators during the fight replay. Have fun with it!',
],
})
})
+65 -120
View File
@@ -5,8 +5,9 @@ import { eq, desc } from 'drizzle-orm'
import { ARENAS } from '../engine/arenas.js'
import { runMockFight } from '../engine/mock.js'
import { startFightLoop } from '../engine/fight-loop.js'
import { runFight, runFightAsync } from '../engine/orchestrator.js'
import { runFight, runFightAsync, isInFight } from '../engine/orchestrator.js'
import { fightEvents } from '../engine/events.js'
import { botRateLimit } from '../middleware/rate-limit.js'
export const fightsRouter = new Hono()
@@ -17,7 +18,6 @@ fightsRouter.get('/', async (c) => {
.orderBy(desc(schema.fights.createdAt))
.limit(20)
// Resolve bot names
const botIds = new Set<string>()
for (const f of rows) {
botIds.add(f.botAId)
@@ -107,6 +107,10 @@ fightsRouter.post('/mock', async (c) => {
}
const shuffled = [...allBots].sort(() => Math.random() - 0.5)
// Prevent self-fights
if (shuffled[0].id === shuffled[1].id) {
return c.json({ error: 'Not enough distinct bots.' }, 400)
}
const fightId = await runMockFight(shuffled[0].id, shuffled[1].id)
return c.json({ fightId, message: 'Mock fight completed.' })
@@ -114,7 +118,7 @@ fightsRouter.post('/mock', async (c) => {
// Trigger a mock fight for a specific bot against a random opponent
fightsRouter.post('/mock/:botId', async (c) => {
const botId = c.req.param('botId')
const botId = c.req.param('botId') as string
const botRows = await db.select({ id: schema.bots.id })
.from(schema.bots)
@@ -139,75 +143,11 @@ fightsRouter.post('/mock/:botId', async (c) => {
return c.json({ fightId, message: 'Mock fight completed.' })
})
// Start a REAL fight — calls actual webhooks
// If botId is provided, fights that bot vs a random opponent
// If no real opponents exist, falls back to a mock opponent
fightsRouter.post('/fight/:botId', async (c) => {
const botId = c.req.param('botId')
const botRows = await db.select({ id: schema.bots.id, webhookUrl: schema.bots.webhookUrl })
.from(schema.bots)
.where(eq(schema.bots.id, botId))
.limit(1)
if (botRows.length === 0) {
return c.json({ error: 'Bot not found.' }, 404)
}
// Find a real opponent (any other bot with a non-mock webhook)
const allBots = await db.select({ id: schema.bots.id, webhookUrl: schema.bots.webhookUrl })
.from(schema.bots)
const realOpponents = allBots.filter(b => b.id !== botId && !b.webhookUrl.startsWith('http://mock.local'))
const mockOpponents = allBots.filter(b => b.id !== botId && b.webhookUrl.startsWith('http://mock.local'))
let opponentId: string
let useMock = false
if (realOpponents.length > 0) {
// Prefer real opponents
opponentId = realOpponents[Math.floor(Math.random() * realOpponents.length)].id
} else if (mockOpponents.length > 0) {
// Fall back to mock opponent — but still use real fight engine for the registered bot
opponentId = mockOpponents[Math.floor(Math.random() * mockOpponents.length)].id
useMock = true
} else {
return c.json({ error: 'No opponents available.' }, 400)
}
// For fights involving a mock bot, use runMockFight (since mock webhooks don't exist)
// For two real bots, use runFight (calls actual webhooks)
if (useMock) {
// The registered bot gives real answers, mock bot gives fake ones
// We need a hybrid — for now, use mock fight so it works immediately
const fightId = await runMockFight(botId, opponentId)
return c.json({ fightId, message: 'Fight completed (opponent was a mock bot).' })
}
// Both bots are real — run a real fight with webhook calls
// Run in background so we can return the fightId immediately
const { nanoid } = await import('nanoid')
const fightId = nanoid(12)
// Don't await — let it run while the user watches
runFight(botId, opponentId).then(id => {
console.log(`[botfights] real fight ${id} completed`)
}).catch(err => {
console.error(`[botfights] fight error:`, err)
})
// Return the fight ID immediately so the frontend can navigate to it
// The fight will be created by runFight momentarily
return c.json({ fightId: 'pending', botId, opponentId, message: 'Real fight starting...' })
})
// Start a batch of mock fights (for seeding or overnight loop)
fightsRouter.post('/mock/batch/:count', async (c) => {
const count = parseInt(c.req.param('count')) || 10
const capped = Math.min(count, 500) // Safety cap
const capped = Math.min(count, 500)
// Run in background
startFightLoop({ maxFights: capped, intervalMs: 500, matchmakingStyle: 'mixed' })
.then(() => console.log(`[botfights] batch of ${capped} fights completed`))
.catch(err => console.error('[botfights] batch error:', err))
@@ -215,52 +155,9 @@ fightsRouter.post('/mock/batch/:count', async (c) => {
return c.json({ message: `Started batch of ${capped} fights in background.` })
})
// SSE stream for live fight events
fightsRouter.get('/:id/stream', (c) => {
const fightId = c.req.param('id')
return streamSSE(c, async (stream) => {
const cleanup = fightEvents.on(fightId, (event) => {
stream.writeSSE({
event: event.type,
data: JSON.stringify(event.data),
})
})
// Also listen for global events to catch fight_end
const cleanupGlobal = fightEvents.onAll((event) => {
if (event.fightId === fightId && event.type === 'fight_end') {
stream.writeSSE({
event: 'fight_end',
data: JSON.stringify(event.data),
})
}
})
// Keep alive until fight ends or client disconnects
try {
while (true) {
await stream.writeSSE({ event: 'ping', data: '' })
await stream.sleep(5000)
// Check if fight is done
const fight = await db.select({ status: schema.fights.status })
.from(schema.fights)
.where(eq(schema.fights.id, fightId))
.limit(1)
if (fight.length > 0 && fight[0].status === 'finished') break
}
} catch {
// Client disconnected
} finally {
cleanup()
cleanupGlobal()
}
})
})
// Instant matchmaking — find an opponent and start a fight NOW
fightsRouter.post('/matchmake/:botId', async (c) => {
const botId = c.req.param('botId')
// Instant matchmaking
fightsRouter.post('/matchmake/:botId', botRateLimit(10_000), async (c) => {
const botId = c.req.param('botId') as string
const botRows = await db.select()
.from(schema.bots)
@@ -273,7 +170,14 @@ fightsRouter.post('/matchmake/:botId', async (c) => {
const bot = botRows[0]
// Find all other active bots, prefer close elo
if (!bot.isActive) {
return c.json({ error: 'Bot is deactivated due to webhook errors. Re-test your webhook.' }, 400)
}
if (isInFight(botId)) {
return c.json({ error: 'Bot is already in a fight.' }, 400)
}
const allBots = await db.select()
.from(schema.bots)
@@ -290,13 +194,14 @@ fightsRouter.post('/matchmake/:botId', async (c) => {
})
const opponent = opponents[0]
const isRealOpponent = !opponent.webhookUrl.startsWith('http://mock.local')
const isMockBot = bot.webhookUrl.startsWith('http://mock.local')
let fightId: string
// Start fight async — returns immediately so frontend can watch live
fightId = await runFightAsync(botId, opponent.id)
try {
fightId = await runFightAsync(botId, opponent.id)
} catch (err) {
const msg = err instanceof Error ? err.message : 'Fight failed to start'
return c.json({ error: msg }, 400)
}
return c.json({
fightId,
@@ -304,3 +209,43 @@ fightsRouter.post('/matchmake/:botId', async (c) => {
message: 'Fight started.',
})
})
// SSE stream for live fight events
fightsRouter.get('/:id/stream', (c) => {
const fightId = c.req.param('id')
return streamSSE(c, async (stream) => {
const cleanup = fightEvents.on(fightId, (event) => {
stream.writeSSE({
event: event.type,
data: JSON.stringify(event.data),
})
})
const cleanupGlobal = fightEvents.onAll((event) => {
if (event.fightId === fightId && event.type === 'fight_end') {
stream.writeSSE({
event: 'fight_end',
data: JSON.stringify(event.data),
})
}
})
try {
while (true) {
await stream.writeSSE({ event: 'ping', data: '' })
await stream.sleep(5000)
const fight = await db.select({ status: schema.fights.status })
.from(schema.fights)
.where(eq(schema.fights.id, fightId))
.limit(1)
if (fight.length > 0 && (fight[0].status === 'finished' || fight[0].status === 'cancelled')) break
}
} catch {
// Client disconnected
} finally {
cleanup()
cleanupGlobal()
}
})
})