Files
PAGIVA/scripts/post-generation-worker.mjs
T
Loma Bot Ops 6994ba1a4e Move AI to Codex CLI + ChatGPT browser workers with a durable post queue
Text generation now runs through a PM2 automation worker (codex exec) and
images through the ChatGPT Chrome extension, replacing the Anthropic API.
generateStructured keeps its signature; results are Zod-validated on the web
side and the worker is reached with a bearer secret.

- AI image assistant in the post editor: editable prompt step, then image
  (square or 3:2 only, since Instagram rejects 2:3), stored via putBlob
- Full-post queue (PostGenerationJob + migration): enqueue returns 202, FIFO
  claim under an advisory lock, heartbeat, stale-job failure, per-user
  request key, cancel while QUEUED; output is always a DRAFT with audit rows
- Separate 10 images/page/day quota; text quota excludes images
- Worker reports Codex usage-limit as 429 with a clear Thai message
- Docs: AI-AUTOMATION.md, ARCHITECTURE/README/.env.example updated

Known gap: the live FIFO queue check (scripts/check-post-queue.mjs) has not
passed yet; the last run hit the Codex account usage limit.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-22 21:52:09 +07:00

21 lines
1.1 KiB
JavaScript

import "dotenv/config";
const base = (process.env.POST_QUEUE_APP_URL || process.env.NEXT_PUBLIC_APP_URL || "").replace(/\/+$/, "");
const secret = process.env.POST_QUEUE_SECRET;
if (!base || !secret || secret.length < 32) throw new Error("Configure POST_QUEUE_APP_URL and POST_QUEUE_SECRET (at least 32 characters)");
let stopping = false;
for (const signal of ["SIGINT", "SIGTERM"]) process.on(signal, () => { stopping = true; });
console.log("[post-queue] worker started");
while (!stopping) {
try {
const response = await fetch(`${base}/api/cron/post-generation`, {
method: "POST", headers: { Authorization: `Bearer ${secret}` }, signal: AbortSignal.timeout(920_000),
});
if (!response.ok) throw new Error(`Queue endpoint status ${response.status}`);
const result = await response.json();
if (result.processed) { console.log(`[post-queue] ${result.jobId}: ${result.status}`); continue; }
} catch (error) { console.error("[post-queue] polling failed", error.message); }
if (!stopping) await new Promise((resolve) => setTimeout(resolve, 3000));
}
console.log("[post-queue] worker stopped");