/** * Watchdog: detects stalled subagent runs. * * A subagent is considered "stalled" when it produces no events * (message_end / tool_execution_*) for longer than `stallMs`. This is the * primary reliability mechanism that fixes "child stopped but parent never * knew" — the in-process AgentSession model has no process-exit signal, so * we synthesize one via event-heartbeat watchdog. * * Every relevant child event must call `touch()` to reset the timer. * The `promise` rejects once the stall threshold is crossed; race it against * the normal completion path in `runChild`. */ export interface Watchdog { /** Reset the last-event timestamp to now. Call on every child event. */ touch(): void; /** Rejects with a stall Error once the threshold is crossed. */ readonly promise: Promise; /** Stop the timer. Idempotent. Always call in finally. */ dispose(): void; } export function createWatchdog(stallMs: number, label: string): Watchdog { let lastEventAt = Date.now(); let disposed = false; let timer: ReturnType | undefined; const promise = new Promise((_, reject) => { const interval = Math.max(1000, Math.min(5000, Math.floor(stallMs / 4))); timer = setInterval(() => { if (disposed) return; if (Date.now() - lastEventAt > stallMs) { disposed = true; if (timer) clearInterval(timer); timer = undefined; reject(new Error(`${label} stalled: no activity for ${Math.round(stallMs / 1000)}s`)); } }, interval); // Don't let a dangling watchdog keep the Node event loop alive forever. if (typeof (promise as any).unref === "function") timer.unref?.(); }); return { touch() { lastEventAt = Date.now(); }, promise, dispose() { if (disposed) return; disposed = true; if (timer) { clearInterval(timer); timer = undefined; } }, }; }