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:
@@ -8,7 +8,7 @@ import { generateStructured } from "@/lib/ai/claude";
|
||||
import { CAPTION_REFINEMENTS, profilePrompt, type CaptionRefinement } from "@/lib/ai/shared";
|
||||
import { CAPTION_RULES, platformRule } from "@/lib/ai/prompts";
|
||||
|
||||
export const maxDuration = 120;
|
||||
export const maxDuration = 300;
|
||||
|
||||
const CaptionVariants = z.object({
|
||||
variants: z.array(
|
||||
|
||||
@@ -7,7 +7,7 @@ import { UserFacingError } from "@/lib/facebook/client";
|
||||
import { generateStructured } from "@/lib/ai/claude";
|
||||
import { profilePrompt } from "@/lib/ai/shared";
|
||||
|
||||
export const maxDuration = 120;
|
||||
export const maxDuration = 300;
|
||||
|
||||
const LEVELS = ["high", "medium", "low"] as const;
|
||||
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import * as z from "zod/v4";
|
||||
import { appUrl } from "@/lib/base-path";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requirePageAction } from "@/lib/auth/user";
|
||||
import { errorResponse, readJson, str } from "@/lib/http";
|
||||
import { UserFacingError } from "@/lib/facebook/client";
|
||||
import { generateStructured } from "@/lib/ai/claude";
|
||||
import { profilePrompt } from "@/lib/ai/shared";
|
||||
import { assertImageQuota, generateImage } from "@/lib/ai/image";
|
||||
import { IMAGE_PROMPT_MAX, IMAGE_SIZES, type ImageSizeKey } from "@/lib/ai/image-shared";
|
||||
import { putBlob } from "@/lib/storage/blob";
|
||||
|
||||
export const maxDuration = 360;
|
||||
|
||||
const ImagePrompt = z.object({
|
||||
prompt: z.string().describe("The finished English prompt for the image model"),
|
||||
});
|
||||
|
||||
const SYSTEM = `You write prompts for an AI image generator. The images illustrate Facebook and Instagram posts for a small Thai business page; a person reads and may edit your prompt before any image is made.
|
||||
|
||||
- Output one English prompt of 60-140 words: subject, setting, composition, lighting, colour mood, and photographic or illustration style.
|
||||
- Show only what the owner described or what <shop_profile> states. Never invent products, packaging, prices or claims.
|
||||
- Ask for no text, lettering, logos, watermarks or brand names inside the image (image models spell Thai badly; the caption carries the words).
|
||||
- No identifiable real people, celebrities or copyrighted characters. If people appear, keep them generic.
|
||||
- No before/after imagery and no exaggerated results (cures, guaranteed outcomes).
|
||||
- Match the shop's tone and audience through the visual mood.`;
|
||||
|
||||
/**
|
||||
* Two steps, both explicit button presses in the editor:
|
||||
* - `{ action: "prompt", pageId, description }` → an editable prompt (Codex CLI, nothing saved)
|
||||
* - `{ action: "generate", pageId, prompt, size }` → the image (ChatGPT browser), stored like an upload → `{ url }`
|
||||
* The returned URL only fills the editor; the post still goes through normal approval.
|
||||
*/
|
||||
export async function POST(req: Request) {
|
||||
const body = await readJson(req);
|
||||
const pageId = str(body.pageId);
|
||||
const auth = await requirePageAction(pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
|
||||
try {
|
||||
// SUPERADMIN passes the role check for any id, so confirm the page exists.
|
||||
const page = await prisma.page.findUnique({
|
||||
where: { id: pageId },
|
||||
select: { profile: { select: { business: true, audience: true, tone: true, avoid: true, cta: true } } },
|
||||
});
|
||||
if (!page) return NextResponse.json({ error: "ไม่พบเพจ" }, { status: 404 });
|
||||
|
||||
const action = str(body.action);
|
||||
if (action === "prompt") {
|
||||
const description = str(body.description).trim();
|
||||
if (!description) throw new UserFacingError("บอก AI ว่าอยากได้รูปแบบไหน");
|
||||
if (description.length > 1000) throw new UserFacingError("คำอธิบายยาวเกิน 1,000 ตัวอักษร");
|
||||
const result = await generateStructured({
|
||||
kind: "image-prompt",
|
||||
pageId,
|
||||
userId: auth.user.id,
|
||||
system: SYSTEM,
|
||||
prompt: `${profilePrompt(page.profile)}\n\nWrite the image prompt for the idea below.\n\n<idea>\n${description}\n</idea>`,
|
||||
schema: ImagePrompt,
|
||||
effort: "low",
|
||||
});
|
||||
const prompt = result.prompt.trim();
|
||||
if (!prompt) throw new UserFacingError("AI ตอบกลับไม่ครบ ลองใหม่อีกครั้ง");
|
||||
return NextResponse.json({ prompt, profileMissing: !page.profile });
|
||||
}
|
||||
|
||||
if (action === "generate") {
|
||||
const prompt = str(body.prompt).trim();
|
||||
const size = str(body.size);
|
||||
if (!prompt) throw new UserFacingError("ใส่คำอธิบายรูปก่อน");
|
||||
if (prompt.length > IMAGE_PROMPT_MAX) throw new UserFacingError(`คำอธิบายรูปยาวเกิน ${IMAGE_PROMPT_MAX.toLocaleString("th-TH")} ตัวอักษร`);
|
||||
if (!Object.hasOwn(IMAGE_SIZES, size)) throw new UserFacingError("ไม่รู้จักขนาดรูปนี้");
|
||||
|
||||
await assertImageQuota(pageId);
|
||||
const image = await generateImage(prompt, size as ImageSizeKey);
|
||||
const file = new File([new Uint8Array(image.bytes)], "ai-image.jpg", { type: image.contentType });
|
||||
const blob = await putBlob(`posts/${pageId}/ai-image.jpg`, file, { contentType: image.contentType }, appUrl(new URL(req.url).origin));
|
||||
// Recorded only after the image is stored, so a failed save doesn't spend quota.
|
||||
await prisma.aiUsage.create({
|
||||
data: { pageId, userId: auth.user.id, kind: "image", inputTokens: image.inputTokens, outputTokens: image.outputTokens },
|
||||
});
|
||||
return NextResponse.json({ url: blob.url });
|
||||
}
|
||||
|
||||
throw new UserFacingError("ไม่รู้จักคำสั่งนี้");
|
||||
} catch (e) {
|
||||
return errorResponse(e, "ai:image");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { actorLabel, requirePageAction } from "@/lib/auth/user";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { JOB_SELECT } from "@/lib/ai/post-queue";
|
||||
|
||||
export async function GET(_req: Request, ctx: RouteContext<"/api/ai/post-jobs/[id]">) {
|
||||
const { id } = await ctx.params;
|
||||
const job = await prisma.postGenerationJob.findUnique({ where: { id }, select: { pageId: true } });
|
||||
if (!job) return NextResponse.json({ error: "ไม่พบงาน" }, { status: 404 });
|
||||
const auth = await requirePageAction(job.pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
return NextResponse.json({ job: await prisma.postGenerationJob.findUnique({ where: { id }, select: JOB_SELECT }) }, { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
export async function DELETE(_req: Request, ctx: RouteContext<"/api/ai/post-jobs/[id]">) {
|
||||
const { id } = await ctx.params;
|
||||
const job = await prisma.postGenerationJob.findUnique({ where: { id }, select: { pageId: true } });
|
||||
if (!job) return NextResponse.json({ error: "ไม่พบงาน" }, { status: 404 });
|
||||
const auth = await requirePageAction(job.pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
const cancelled = await prisma.$transaction(async (tx) => {
|
||||
const changed = await tx.postGenerationJob.updateMany({ where: { id, status: "QUEUED" }, data: { status: "CANCELLED", stage: "cancelled", finishedAt: new Date() } });
|
||||
if (!changed.count) return false;
|
||||
await audit({ action: "AI_POST_CANCELLED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId: job.pageId, detail: { jobId: id } }, tx);
|
||||
return true;
|
||||
});
|
||||
if (!cancelled) return NextResponse.json({ error: "ยกเลิกได้เฉพาะงานที่ยังรอคิว งานนี้เริ่มทำหรือจบแล้ว" }, { status: 409 });
|
||||
return NextResponse.json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { NextResponse } from "next/server";
|
||||
import * as z from "zod/v4";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { actorLabel, requirePageAction } from "@/lib/auth/user";
|
||||
import { audit } from "@/lib/audit";
|
||||
import { readJson, str, errorResponse } from "@/lib/http";
|
||||
import { UserFacingError } from "@/lib/facebook/client";
|
||||
import { JOB_SELECT } from "@/lib/ai/post-queue";
|
||||
import { IMAGE_DAILY_LIMIT_PER_PAGE } from "@/lib/ai/image";
|
||||
import { bkkMidnight, isDayKey } from "@/lib/board";
|
||||
|
||||
const Input = z.object({ requestKey: z.uuid(), topic: z.string().trim().min(1).max(1000), targets: z.array(z.enum(["FACEBOOK", "INSTAGRAM"])).min(1).max(2), plannedDay: z.string().optional() });
|
||||
|
||||
export async function GET(req: Request) {
|
||||
const pageId = new URL(req.url).searchParams.get("pageId") || "";
|
||||
const auth = await requirePageAction(pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
const jobs = await prisma.postGenerationJob.findMany({ where: { pageId }, select: JOB_SELECT, orderBy: [{ createdAt: "desc" }, { id: "desc" }], take: 30 });
|
||||
return NextResponse.json({ jobs }, { headers: { "Cache-Control": "no-store" } });
|
||||
}
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const body = await readJson(req);
|
||||
const pageId = str(body.pageId);
|
||||
const auth = await requirePageAction(pageId, "editPost");
|
||||
if (!auth.ok) return auth.response;
|
||||
try {
|
||||
const input = Input.safeParse(body);
|
||||
if (!input.success) throw new UserFacingError("กรอกหัวข้อไม่เกิน 1,000 ตัวอักษร และเลือกช่องทางก่อนเข้าคิว");
|
||||
const { requestKey, topic, plannedDay } = input.data;
|
||||
const targets = [...new Set(input.data.targets)].sort();
|
||||
if (plannedDay && !isDayKey(plannedDay)) throw new UserFacingError("วันที่วางแผนโพสต์ไม่ถูกต้อง");
|
||||
const plannedAt = plannedDay ? bkkMidnight(plannedDay) : null;
|
||||
const result = await prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${`ai-post:${pageId}`}))`;
|
||||
const existing = await tx.postGenerationJob.findUnique({ where: { requestedById_requestKey: { requestedById: auth.user.id, requestKey } } });
|
||||
if (existing) {
|
||||
if (existing.pageId !== pageId || existing.topic !== topic || existing.targets.join() !== targets.join() || existing.plannedAt?.toISOString() !== plannedAt?.toISOString()) throw new UserFacingError("คำขอนี้ใช้กับงานอื่นแล้ว กรุณาสร้างคำขอใหม่");
|
||||
return { job: existing, duplicate: true };
|
||||
}
|
||||
const page = await tx.page.findUnique({ where: { id: pageId }, select: { status: true, igUserId: true, profile: { select: { business: true, audience: true, tone: true, avoid: true, cta: true } } } });
|
||||
if (!page || page.status === "DISCONNECTED") throw new UserFacingError("ไม่พบเพจที่พร้อมสร้างโพสต์");
|
||||
if (!page.profile?.business.trim()) throw new UserFacingError("ตั้งค่าโปรไฟล์ร้านก่อน เพื่อให้ AI สร้างโพสต์จากข้อมูลจริงของร้าน");
|
||||
if (targets.includes("INSTAGRAM") && !page.igUserId) throw new UserFacingError("เพจนี้ยังไม่ได้ผูก Instagram");
|
||||
const pending = await tx.postGenerationJob.count({ where: { pageId, status: { in: ["QUEUED", "RUNNING"] } } });
|
||||
if (pending >= 5) throw new UserFacingError("เพจนี้มีงานค้างครบ 5 งานแล้ว รอให้เสร็จก่อนเพิ่มคิว");
|
||||
const used = await tx.aiUsage.count({ where: { pageId, kind: "image", createdAt: { gte: new Date(Date.now() - 24 * 60 * 60_000) } } });
|
||||
if (used + pending >= IMAGE_DAILY_LIMIT_PER_PAGE) throw new UserFacingError("โควตาภาพของเพจนี้ถูกใช้หรือจองเต็มแล้ว ลองใหม่ภายหลัง");
|
||||
const job = await tx.postGenerationJob.create({ data: { pageId, requestedById: auth.user.id, requestKey, topic, targets, plannedAt, profileSnapshot: page.profile } });
|
||||
await audit({ action: "AI_POST_QUEUED", actorId: auth.user.id, actorLabel: actorLabel(auth.user), pageId, detail: { jobId: job.id } }, tx);
|
||||
return { job, duplicate: false };
|
||||
});
|
||||
const job = await prisma.postGenerationJob.findUniqueOrThrow({ where: { id: result.job.id }, select: JOB_SELECT });
|
||||
return NextResponse.json({ job, duplicate: result.duplicate }, { status: result.duplicate ? 200 : 202 });
|
||||
} catch (error) { return errorResponse(error, "post-queue:create"); }
|
||||
}
|
||||
@@ -10,7 +10,7 @@ import { MAX_MESSAGE_LENGTH } from "@/lib/facebook/messagingWindow";
|
||||
import { generateStructured } from "@/lib/ai/claude";
|
||||
import { profilePrompt } from "@/lib/ai/shared";
|
||||
|
||||
export const maxDuration = 120;
|
||||
export const maxDuration = 300;
|
||||
|
||||
const Replies = z.object({ replies: z.array(z.string().describe("One complete chat reply in Thai")) });
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ import { profilePrompt } from "@/lib/ai/shared";
|
||||
import { CAPTION_RULES, platformRule } from "@/lib/ai/prompts";
|
||||
import { addDays, bkkDayKey, bkkMidnight, isDayKey, weekStartOf } from "@/lib/board";
|
||||
|
||||
export const maxDuration = 120;
|
||||
export const maxDuration = 300;
|
||||
|
||||
const WeekPlan = z.object({
|
||||
posts: z.array(
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import { NextResponse } from "next/server";
|
||||
import { appUrl } from "@/lib/base-path";
|
||||
import { processNextPostJob } from "@/lib/ai/post-queue";
|
||||
|
||||
export const runtime = "nodejs";
|
||||
export const maxDuration = 900;
|
||||
|
||||
/** Only the private queue worker can claim/process jobs; no user cookie is accepted. */
|
||||
export async function POST(req: Request) {
|
||||
const secret = process.env.POST_QUEUE_SECRET;
|
||||
const expected = Buffer.from(`Bearer ${secret || ""}`);
|
||||
const provided = Buffer.from(req.headers.get("authorization") || "");
|
||||
if (!secret || secret.length < 32 || expected.length !== provided.length || !timingSafeEqual(expected, provided)) return NextResponse.json({ error: "unauthorized" }, { status: 401 });
|
||||
return NextResponse.json(await processNextPostJob(appUrl(new URL(req.url).origin)));
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import { generateStructured } from "@/lib/ai/claude";
|
||||
import { collectAnalysisSource } from "@/lib/analysis/source";
|
||||
import { PROFILE_FIELDS, type ShopProfile } from "@/lib/ai/shared";
|
||||
|
||||
export const maxDuration = 120;
|
||||
export const maxDuration = 300;
|
||||
|
||||
const DraftProfile = z.object({
|
||||
business: z.string().describe("What the shop sells, price ranges, delivery area and selling points seen in the posts"),
|
||||
|
||||
Reference in New Issue
Block a user