import { UserFacingError } from "@/lib/facebook/client"; /** Authenticated bridge to the machine with Codex CLI and a dedicated Chrome profile. */ export async function runAutomation(body: Record, options: { waitForWorker?: boolean } = {}): Promise> { const url = process.env.AI_AUTOMATION_URL; const secret = process.env.AI_AUTOMATION_SECRET; if (!url || !secret) throw new UserFacingError("ยังไม่ได้ตั้งค่า automation worker — ติดต่อผู้ดูแลระบบ"); try { const attempts = options.waitForWorker ? 31 : 1; for (let attempt = 0; attempt < attempts; attempt++) { const response = await fetch(url, { method: "POST", headers: { Authorization: `Bearer ${secret}`, "Content-Type": "application/json" }, body: JSON.stringify(body), signal: AbortSignal.timeout(310_000), cache: "no-store", }); if (response.status === 409) { if (attempt + 1 < attempts) { await new Promise((resolve) => setTimeout(resolve, 2000)); continue; } throw new UserFacingError("Worker กำลังทำงานอื่น ลองสั่งสร้างใหม่เมื่อพร้อม"); } if (response.status === 429) throw new UserFacingError("โควตา AI ของบัญชีที่ใช้สร้างเนื้อหาเต็มชั่วคราว ลองใหม่อีกครั้งภายหลัง"); if (!response.ok) { const failure = await response.json().catch(() => ({})); const hints: Record = { DESKTOP_UNAVAILABLE: "เครื่องสร้างรูปไม่มีหน้าจอ Chrome ที่ใช้งานได้ — ปลดล็อก desktop session ของ worker แล้วลองใหม่", LOGIN_REQUIRED: "บัญชี ChatGPT บนเครื่อง worker ต้องเข้าสู่ระบบใหม่", CHAT_UNAVAILABLE: "หน้า ChatGPT บนเครื่อง worker ไม่พร้อมใช้งาน — ตรวจหน้าเว็บหรือ extension", IMAGE_EXPORT_FAILED: "สร้างรูปแล้ว แต่ดึงไฟล์จาก ChatGPT ไม่สำเร็จ — ตรวจรูปใน Chrome ก่อนลองใหม่", }; const code = typeof failure.code === "string" ? failure.code : "UNKNOWN"; console.error("[ai:automation] worker response", { status: response.status, code }); if (hints[code]) throw new UserFacingError(hints[code]); throw new Error(`Worker status ${response.status} (${code})`); } return await response.json(); } throw new Error("Worker did not accept the job"); } catch (error) { if (error instanceof UserFacingError) throw error; console.error("[ai:automation] worker failed", error); if (error instanceof DOMException && error.name === "AbortError") { throw new UserFacingError("Worker ไม่ตอบกลับภายในเวลาที่กำหนด — ตรวจว่า worker กำลังทำงานอยู่แล้วลองใหม่"); } if (error instanceof TypeError && /fetch|connect|ECONNREFUSED/i.test(error.message)) { throw new UserFacingError("เชื่อมต่อ worker ไม่ได้ — ตรวจว่า worker กำลังทำงานอยู่และ AI_AUTOMATION_URL ถูกต้อง"); } throw new UserFacingError("Automation ทำงานไม่สำเร็จ — ตรวจ worker และการ login แล้วลองใหม่"); } }