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>
This commit is contained in:
Loma Bot Ops
2026-11-22 21:52:09 +07:00
parent 4a673ebb28
commit 6994ba1a4e
41 changed files with 2007 additions and 113 deletions
+13 -58
View File
@@ -1,84 +1,39 @@
import Anthropic from "@anthropic-ai/sdk";
import { zodOutputFormat } from "@anthropic-ai/sdk/helpers/zod";
import type * as z from "zod/v4";
// Compatibility module: all structured content now runs through Codex CLI.
import * as z from "zod/v4";
import { prisma } from "@/lib/db";
import { UserFacingError } from "@/lib/facebook/client";
export const AI_MODEL = "claude-opus-5-5";
/** Successful AI calls allowed per page in any rolling 24 hours (cost guard). */
import { runAutomation } from "./automation";
export const AI_DAILY_LIMIT_PER_PAGE = 30;
let client: Anthropic | null = null;
function getClient(): Anthropic {
if (!process.env.ANTHROPIC_API_KEY && !process.env.ANTHROPIC_AUTH_TOKEN) {
throw new UserFacingError("ยังไม่ได้ตั้งค่า AI — ผู้ดูแลระบบต้องใส่ ANTHROPIC_API_KEY ก่อน");
}
// Interactive routes: fail fast rather than hold the request for the SDK's 10-minute default.
client ??= new Anthropic({ timeout: 55_000, maxRetries: 1 });
return client;
}
function toUserFacing(e: unknown, kind: string): UserFacingError {
if (e instanceof UserFacingError) return e;
console.error(`[ai:${kind}] request failed`, e);
if (e instanceof Anthropic.AuthenticationError || e instanceof Anthropic.PermissionDeniedError) {
return new UserFacingError("API key ของ AI ใช้ไม่ได้ — ผู้ดูแลระบบต้องตรวจ ANTHROPIC_API_KEY");
}
if (e instanceof Anthropic.RateLimitError) return new UserFacingError("AI มีคนใช้มากหรือเกินโควตา ลองใหม่ในอีกสักครู่");
if (e instanceof Anthropic.APIConnectionError) return new UserFacingError("ติดต่อ AI ไม่ได้ ลองใหม่อีกครั้ง");
return new UserFacingError("AI ทำงานไม่สำเร็จ ลองใหม่อีกครั้ง");
}
/**
* One structured-output call to Claude, counted against the page's daily limit.
* Every failure becomes a UserFacingError with safe Thai text; details go to the server log.
*/
export async function generateStructured<S extends z.ZodType>(req: {
kind: "caption" | "profile" | "week-plan" | "check" | "reply";
kind: "caption" | "profile" | "week-plan" | "check" | "reply" | "image-prompt" | "post-generation";
pageId: string;
userId: string;
system: string;
prompt: string;
schema: S;
effort: "low" | "medium";
waitForWorker?: boolean;
}): Promise<z.infer<S>> {
const since = new Date(Date.now() - 24 * 60 * 60 * 1000);
const used = await prisma.aiUsage.count({ where: { pageId: req.pageId, createdAt: { gte: since } } });
// Images have their own, tighter limit (lib/ai/image.ts) and must not eat the text quota.
const used = await prisma.aiUsage.count({ where: { pageId: req.pageId, kind: { not: "image" }, createdAt: { gte: since } } });
if (used >= AI_DAILY_LIMIT_PER_PAGE) {
throw new UserFacingError(`เพจนี้ใช้ AI ครบ ${AI_DAILY_LIMIT_PER_PAGE} ครั้งใน 24 ชั่วโมงแล้ว ลองใหม่ภายหลัง`);
}
let response;
try {
response = await getClient().messages.parse({
model: AI_MODEL,
max_tokens: 16000,
system: req.system,
output_config: { effort: req.effort, format: zodOutputFormat(req.schema) },
messages: [{ role: "user", content: req.prompt }],
});
} catch (e) {
throw toUserFacing(e, req.kind);
}
if (response.stop_reason === "refusal") {
console.warn(`[ai:${req.kind}] refused`, response.stop_details);
throw new UserFacingError("AI ไม่เขียนเนื้อหานี้ให้ ลองปรับหัวข้อหรือถ้อยคำ");
}
if (!response.parsed_output) {
console.error(`[ai:${req.kind}] no parsed output`, { stop_reason: response.stop_reason });
throw new UserFacingError("AI ตอบกลับไม่ครบ ลองใหม่อีกครั้ง");
}
const response = await runAutomation({ kind: "text", system: req.system, prompt: req.prompt, schema: z.toJSONSchema(req.schema) }, { waitForWorker: req.waitForWorker });
const result = req.schema.safeParse(response.result);
if (!result.success) throw new UserFacingError("Codex ตอบกลับไม่ครบรูปแบบ ลองใหม่อีกครั้ง");
await prisma.aiUsage.create({
data: {
pageId: req.pageId,
userId: req.userId,
kind: req.kind,
inputTokens: response.usage.input_tokens,
outputTokens: response.usage.output_tokens,
inputTokens: 0,
outputTokens: 0,
},
});
return response.parsed_output;
return result.data;
}