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:
co-authored by
Claude Opus 4.6
parent
2c0323d5fb
commit
4d8b18a58a
+65
-120
@@ -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()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user