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}. Provider stalled or prompt too large.`; } return error instanceof Error ? error.message : String(error); } export async function withTimeoutCompactionRetry(opts: { run: () => Promise; compact: () => Promise; signal?: AbortSignal; onStatus?: (status: string) => void; }): Promise { try { return await opts.run(); } catch (error) { if (!(error instanceof DevilTimeoutError) || opts.signal?.aborted) throw error; opts.onStatus?.(`${error.message} · compacting`); try { await opts.compact(); } catch (compactError) { throw new Error( `${error.message}. Compaction failed: ${formatDebateError(compactError)}`, ); } if (opts.signal?.aborted) throw new Error("Aborted"); opts.onStatus?.("Compaction complete · retrying debate"); try { return await opts.run(); } catch (retryError) { if (retryError instanceof DevilTimeoutError) { throw new Error( `${retryError.message} after compaction. Provider stalled or prompt too large.`, ); } throw retryError; } } } 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); } }