import type { renderFailureReasons } from '../tracking/tool-fields.ts'; type RenderFailureReason = (typeof renderFailureReasons)[number]; // Hyperframes 0.9.7 emits a terminal @hf-diagnostic on stdout. Only transmit known reason names. const diagnosticReasons = new Map([ ['CAPTURE_PROTOCOL_TIMEOUT', 'browser_protocol_timeout'], ['CAPTURE_TRANSIENT_BROWSER', 'transient_browser_error'], ['CAPTURE_MEMORY_EXHAUSTION', 'memory_exhausted'], ['PAGE_ERROR', 'page_error'], ['COMPOSITION_ZERO_DURATION', 'zero_duration'], ['ENOSPC', 'disk_full'], ['EMFILE', 'file_limit'], ]); export function classifyRenderFailure(output: string): RenderFailureReason { for (const line of output.split('\n').reverse()) { if (!line.startsWith('@hf-diagnostic ') || line.length > 16_384) continue; try { const diagnostic = JSON.parse(line.slice('@hf-diagnostic '.length)); if (diagnostic?.operation !== 'render' || diagnostic.version !== 1 || typeof diagnostic.code !== 'string') continue; const reason = diagnosticReasons.get(diagnostic.code); if (reason) return reason; break; } catch { /* Non-diagnostic output is still usable on older renderers. */ } } if (/listen (?:EPERM|EACCES).*?(?:127\.0\.0\.1|::1|localhost)/i.test(output)) return 'local_port_denied'; if (/Chrome cannot start|Failed to launch (?:the )?browser/i.test(output)) return 'browser_start'; if (/Error while opening encoder|Unknown encoder|Error initializing output stream/i.test(output)) return 'encoder'; if (/\bPage\.captureScreenshot timed out\b/i.test(output)) return 'screenshot_timeout'; if (/\bnet::ERR_NO_BUFFER_SPACE\b/i.test(output)) return 'socket_buffer_exhausted'; if (/\b(?:JavaScript heap out of memory|Reached heap limit)\b/i.test(output)) return 'memory_exhausted'; return 'unclassified'; }