Files
WT-Offline/apps/ai-lab/server/lab-api.ts
T
N0VAN0M4LY 5786fee63b feat(ground-ai): add a replay trace and the AI lab viewer
Battle behaviour could only be judged by watching one bot at a time. The
AI now logs a replay trace and a local viewer plays it back on the map.

Game scripts:
- wto_ai_trace_common.das writes every diagnostics.traceIntervalSec the
  capture zones (WTO_AI|TRACE_CAP), every ground unit including players
  (TRACE_U) and each bot's decision state (TRACE_B: order, behavior,
  targets, what the turret looks at and why, barrel heading, fire denial,
  hit probability), plus part damage with its offender (HIT) and deaths
  (DEATH). It uses no engine module so a simulator can load it as is.
- The turret state records the reason and world direction of each look.
- New tuning diagnostics.trace and diagnostics.traceIntervalSec through
  server reader, patcher constants, launcher schema, fields and labels.

packages/ground-sim: readers for the baked .wtonav pack (mesh polygons,
cover points, tactical grid) and .pois.json, the trace parser and the
names of the logged codes.

apps/ai-lab: Vite viewer with a local API that lists nav packs and lab
logs and decrypts a chosen .clog with wtotools. It draws the nav mesh,
vehicles, barrels and wished turret directions, goals, target links,
shots, hits and deaths over a timeline, with per-bot strips for behavior,
fire denial and turret reason. Paths live in an untracked lab.local.json.
The lab has its own tsconfig and stays out of the root typecheck.

Root and launcher typechecks pass; the lab typechecks and replayed two
lab battles.
2026-12-06 13:53:52 +08:00

119 lines
5.0 KiB
TypeScript

/**
* Dev-server API of the AI lab (local only):
* GET /api/maps levels that have a navigation pack in mapsDir
* GET /api/maps/file?name= a pack or POI file of mapsDir
* GET /api/logs game logs (.clog) in logsDir, newest first
* GET /api/logs/text?name= a log decrypted with wtotools (cached until the log changes)
* Paths come from lab.local.json next to this app (see lab.local.example.json).
*/
import { execFile } from 'node:child_process';
import { createReadStream, existsSync, mkdirSync, readFileSync, readdirSync, statSync } from 'node:fs';
import type { ServerResponse } from 'node:http';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import type { Connect, Plugin } from 'vite';
interface LabConfig {
readonly mapsDir: string;
readonly logsDir: string;
readonly python: string;
}
const APP_DIR = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
const CACHE_DIR = path.join(APP_DIR, '.cache');
const SAFE_NAME = /^[\w.-]+$/;
function loadConfig(): LabConfig {
const file = path.join(APP_DIR, 'lab.local.json');
const raw = existsSync(file) ? (JSON.parse(readFileSync(file, 'utf8')) as Record<string, unknown>) : {};
const str = (key: string, fallback: string): string => (typeof raw[key] === 'string' ? (raw[key] as string) : fallback);
return {
mapsDir: str('mapsDir', path.resolve(APP_DIR, '../../build/nav-stage2-fix/maps')),
logsDir: str('logsDir', ''),
python: str('python', 'python'),
};
}
function sendJson(res: ServerResponse, status: number, body: unknown): void {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.end(JSON.stringify(body));
}
function sendFile(res: ServerResponse, file: string, type: string): void {
res.statusCode = 200;
res.setHeader('Content-Type', type);
createReadStream(file).pipe(res);
}
function listMaps(cfg: LabConfig): { level: string; pois: boolean }[] {
if (!existsSync(cfg.mapsDir)) return [];
return readdirSync(cfg.mapsDir)
.filter((f) => f.endsWith('.wtonav'))
.map((f) => {
const level = f.slice(0, -'.wtonav'.length);
return { level, pois: existsSync(path.join(cfg.mapsDir, `${level}.pois.json`)) };
});
}
function listLogs(cfg: LabConfig): { name: string; size: number; mtime: number }[] {
if (cfg.logsDir === '' || !existsSync(cfg.logsDir)) return [];
return readdirSync(cfg.logsDir)
.filter((f) => f.endsWith('.clog'))
.map((name) => {
const st = statSync(path.join(cfg.logsDir, name));
return { name, size: st.size, mtime: st.mtimeMs };
})
.sort((a, b) => b.mtime - a.mtime);
}
/** Decrypts `name` into the cache unless the cached text is newer than the log. */
function decryptLog(cfg: LabConfig, name: string): Promise<string> {
const source = path.join(cfg.logsDir, name);
const out = path.join(CACHE_DIR, `${name}.txt`);
mkdirSync(CACHE_DIR, { recursive: true });
if (existsSync(out) && statSync(out).mtimeMs >= statSync(source).mtimeMs) return Promise.resolve(out);
return new Promise((resolve, reject) => {
execFile(cfg.python, ['-m', 'wtotools.cli', 'decrypt-clog', source, '--out', out], { timeout: 180_000 }, (err, _stdout, stderr) => {
if (err !== null) reject(new Error(`decrypt-clog failed: ${stderr || err.message}`));
else resolve(out);
});
});
}
async function handle(cfg: LabConfig, url: URL, res: ServerResponse): Promise<boolean> {
const name = url.searchParams.get('name') ?? '';
if (url.pathname === '/api/maps') { sendJson(res, 200, listMaps(cfg)); return true; }
if (url.pathname === '/api/logs') { sendJson(res, 200, listLogs(cfg)); return true; }
if (url.pathname !== '/api/maps/file' && url.pathname !== '/api/logs/text') return false;
if (!SAFE_NAME.test(name)) { sendJson(res, 400, { error: 'bad file name' }); return true; }
if (url.pathname === '/api/maps/file') {
const file = path.join(cfg.mapsDir, name);
if (!existsSync(file)) sendJson(res, 404, { error: `no ${name} in ${cfg.mapsDir}` });
else sendFile(res, file, name.endsWith('.json') ? 'application/json' : 'application/octet-stream');
return true;
}
if (!name.endsWith('.clog') || !existsSync(path.join(cfg.logsDir, name))) {
sendJson(res, 404, { error: `no log ${name}` });
return true;
}
sendFile(res, await decryptLog(cfg, name), 'text/plain; charset=utf-8');
return true;
}
export function labApi(): Plugin {
return {
name: 'wto-ai-lab-api',
configureServer(server) {
const middleware: Connect.NextHandleFunction = (req, res, next) => {
const url = new URL(req.url ?? '/', 'http://localhost');
if (!url.pathname.startsWith('/api/')) { next(); return; }
handle(loadConfig(), url, res)
.then((handled) => { if (!handled) sendJson(res, 404, { error: 'unknown endpoint' }); })
.catch((err: unknown) => sendJson(res, 500, { error: err instanceof Error ? err.message : String(err) }));
};
server.middlewares.use(middleware);
},
};
}