export type TimeoutRole = "Devil" | "Defense" | "Synthesis"; export class DevilTimeoutError extends Error { constructor( public role: TimeoutRole, public timeoutMs: number, ) { super(`${role} timed out after ${Math.round(timeoutMs / 1000)}s`); this.name = "DevilTimeoutError"; } } export function formatDebateError(error: unknown): string { if (error instanceof DevilTimeoutError) { return `${error.message}. Likely huge context or stalled provider. Run /compact, then retry /devil.`; } return error instanceof Error ? error.message : String(error); } export async function withRoleTimeout( role: TimeoutRole, timeoutMs: number, parentSignal: AbortSignal | undefined, run: (signal: AbortSignal) => Promise, onTimeout?: () => void, ): Promise { if (parentSignal?.aborted) throw new Error("Aborted"); const controller = new AbortController(); let timeoutId: ReturnType | undefined; let rejectTimeout: ((error: Error) => void) | undefined; const timeout = new Promise((_, reject) => { rejectTimeout = reject; timeoutId = setTimeout(() => { onTimeout?.(); controller.abort(); reject(new DevilTimeoutError(role, timeoutMs)); }, timeoutMs); }); const abortParent = () => { controller.abort(); rejectTimeout?.(new Error("Aborted")); }; parentSignal?.addEventListener("abort", abortParent, { once: true }); try { return await Promise.race([run(controller.signal), timeout]); } finally { if (timeoutId) clearTimeout(timeoutId); parentSignal?.removeEventListener("abort", abortParent); } }