mirror of
https://github.com/Dasemu/chatgpt-imagegen-mcp.git
synced 2026-11-26 15:26:21 +00:00
feat: generate images through chatgpt.com with Playwright behind an MCP server
Port of ZenvairoProspect's imagegen (legacy/whatsapp-mockup) to the ZenvairoMediaGenerator-MCP submit+poll contract: persistent logged-in Chromium profile, selector fallback lists, serial queue with pacing and a circuit breaker for usage limits and lost sessions, signed public URLs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
15c2a90f08
commit
b46db0cf6a
17 files changed
+1717
No files matched your search
@@ -0,0 +1,100 @@
|
||||
import { ASPECT_RATIOS } from "./chatgpt/prompts.js";
|
||||
import { sniffImageMime } from "./image.js";
|
||||
import type { GenerationReferenceImage, InlineReferenceImage, ReferenceImage, ToolArgument } from "./types.js";
|
||||
|
||||
export const MODEL = {
|
||||
name: "chatgpt-web",
|
||||
aliases: ["chatgpt", "gpt-image", "chatgpt-image"],
|
||||
description: "Image generation through the chatgpt.com web UI (the account's current image model), driven by Playwright. One image per new chat; jobs run one at a time.",
|
||||
arguments: [
|
||||
{ name: "prompt", required: true, description: "Image description, any language. Max 8000 characters." },
|
||||
{ name: "aspect_ratio", required: false, default: "auto", allowedValues: [...ASPECT_RATIOS], description: "Requested in the prompt; ChatGPT honours it best-effort. 'auto' lets the model choose." },
|
||||
{ name: "image_count", required: false, default: 1, minimum: 1, maximum: 4, description: "Number of images, each generated sequentially in its own chat." },
|
||||
{ name: "reference_images", required: false, maximumItems: 4, format: "array of {generation_id, index?} or {base64, mime_type}", description: "Images uploaded to the chat as references (PNG, JPEG or WebP)." },
|
||||
],
|
||||
} as const;
|
||||
|
||||
export interface NormalizedArguments {
|
||||
prompt: string;
|
||||
aspect_ratio: string;
|
||||
image_count: number;
|
||||
reference_images?: ReferenceImage[];
|
||||
}
|
||||
|
||||
export function resolveModel(requested: string): string {
|
||||
const normalized = requested.trim().toLowerCase();
|
||||
if (normalized === MODEL.name || (MODEL.aliases as readonly string[]).includes(normalized)) return MODEL.name;
|
||||
throw new Error(`Unknown model '${requested}'. Available: ${MODEL.name} (aliases: ${MODEL.aliases.join(", ")})`);
|
||||
}
|
||||
|
||||
export function normalizeArguments(input: ToolArgument[]): NormalizedArguments {
|
||||
const known = new Set<string>(MODEL.arguments.map((argument) => argument.name));
|
||||
const values: Record<string, unknown> = {};
|
||||
for (const argument of input) {
|
||||
if (!known.has(argument.name)) throw new Error(`Unknown argument '${argument.name}' for model ${MODEL.name}`);
|
||||
if (Object.hasOwn(values, argument.name)) throw new Error(`Duplicate argument '${argument.name}'`);
|
||||
values[argument.name] = argument.value;
|
||||
}
|
||||
|
||||
if (typeof values.prompt !== "string" || values.prompt.trim().length === 0) throw new Error("Missing required argument 'prompt' (non-empty string)");
|
||||
if (values.prompt.length > 8000) throw new Error("'prompt' must be at most 8000 characters");
|
||||
|
||||
const aspectRatio = values.aspect_ratio ?? "auto";
|
||||
if (typeof aspectRatio !== "string" || !(ASPECT_RATIOS as readonly string[]).includes(aspectRatio)) {
|
||||
throw new Error(`Invalid 'aspect_ratio': ${JSON.stringify(aspectRatio)}. Allowed: ${ASPECT_RATIOS.join(", ")}`);
|
||||
}
|
||||
|
||||
const imageCount = values.image_count ?? 1;
|
||||
if (!Number.isInteger(imageCount) || Number(imageCount) < 1 || Number(imageCount) > 4) throw new Error("'image_count' must be an integer between 1 and 4");
|
||||
|
||||
return {
|
||||
prompt: values.prompt,
|
||||
aspect_ratio: aspectRatio,
|
||||
image_count: Number(imageCount),
|
||||
...(values.reference_images !== undefined ? { reference_images: normalizeReferenceImages(values.reference_images) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeReferenceImages(input: unknown): ReferenceImage[] {
|
||||
if (!Array.isArray(input) || input.length < 1 || input.length > 4) {
|
||||
throw new Error("'reference_images' must be an array of 1 to 4 {base64, mime_type} or {generation_id, index?} objects");
|
||||
}
|
||||
const maxPerImageBytes = 20 * 1024 * 1024;
|
||||
return input.map((value, position): ReferenceImage => {
|
||||
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error(`reference_images[${position}] must be an object`);
|
||||
const record = value as Record<string, unknown>;
|
||||
const hasInline = Object.hasOwn(record, "base64") || Object.hasOwn(record, "mime_type");
|
||||
const hasGeneration = Object.hasOwn(record, "generation_id") || Object.hasOwn(record, "index");
|
||||
if (hasInline && hasGeneration) throw new Error(`reference_images[${position}] must use either {base64, mime_type} or {generation_id, index?}, not both`);
|
||||
|
||||
if (hasGeneration) {
|
||||
if (typeof record.generation_id !== "string" || !isUuid(record.generation_id)) throw new Error(`reference_images[${position}].generation_id must be a valid UUID`);
|
||||
const index = record.index ?? 0;
|
||||
if (!Number.isInteger(index) || Number(index) < 0) throw new Error(`reference_images[${position}].index must be a non-negative integer`);
|
||||
return { generation_id: record.generation_id, index: Number(index) } satisfies GenerationReferenceImage;
|
||||
}
|
||||
|
||||
if (typeof record.base64 !== "string" || record.base64.length === 0) throw new Error(`reference_images[${position}].base64 must be a non-empty string`);
|
||||
let base64 = record.base64;
|
||||
let mimeType = record.mime_type;
|
||||
const dataUri = base64.match(/^data:(image\/(?:png|jpeg|webp));base64,(.+)$/s);
|
||||
if (dataUri) {
|
||||
mimeType ??= dataUri[1];
|
||||
base64 = dataUri[2];
|
||||
}
|
||||
base64 = base64.replace(/\s/g, "");
|
||||
if (!/^[A-Za-z0-9+/]*={0,2}$/.test(base64) || base64.length % 4 !== 0) throw new Error(`reference_images[${position}].base64 is not valid standard base64`);
|
||||
if (mimeType !== "image/png" && mimeType !== "image/jpeg" && mimeType !== "image/webp") {
|
||||
throw new Error(`reference_images[${position}].mime_type must be image/png, image/jpeg or image/webp`);
|
||||
}
|
||||
const padding = base64.endsWith("==") ? 2 : base64.endsWith("=") ? 1 : 0;
|
||||
const decodedBytes = Math.floor(base64.length * 3 / 4) - padding;
|
||||
if (decodedBytes <= 0 || decodedBytes > maxPerImageBytes) throw new Error(`reference_images[${position}] exceeds the 20 MiB per-image limit`);
|
||||
if (sniffImageMime(Buffer.from(base64.slice(0, 24), "base64")) !== mimeType) throw new Error(`reference_images[${position}] content does not match ${mimeType}`);
|
||||
return { base64, mime_type: mimeType } satisfies InlineReferenceImage;
|
||||
});
|
||||
}
|
||||
|
||||
function isUuid(value: string): boolean {
|
||||
return /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
import { mkdir } from "node:fs/promises";
|
||||
import { chromium, type BrowserContext, type Page } from "playwright";
|
||||
import { audit } from "../log.js";
|
||||
import type { ChatGptConfig } from "./config.js";
|
||||
|
||||
/**
|
||||
* Owns the persistent Chromium profile. Chromium locks the profile directory, so only one
|
||||
* process (the server or `npm run login`) may use it at a time.
|
||||
*/
|
||||
export class BrowserSession {
|
||||
private context?: BrowserContext;
|
||||
private idleTimer?: NodeJS.Timeout;
|
||||
|
||||
constructor(private readonly config: ChatGptConfig) {}
|
||||
|
||||
async page(headless = this.config.headless): Promise<Page> {
|
||||
this.clearIdleTimer();
|
||||
if (!this.context) {
|
||||
await mkdir(this.config.profileDir, { recursive: true, mode: 0o700 });
|
||||
this.context = await chromium.launchPersistentContext(this.config.profileDir, {
|
||||
headless,
|
||||
...(this.config.channel ? { channel: this.config.channel } : {}),
|
||||
...(this.config.userAgent ? { userAgent: this.config.userAgent } : {}),
|
||||
locale: this.config.locale,
|
||||
viewport: { width: 1440, height: 900 },
|
||||
args: ["--disable-blink-features=AutomationControlled"],
|
||||
ignoreDefaultArgs: ["--enable-automation"],
|
||||
acceptDownloads: true,
|
||||
});
|
||||
this.context.on("close", () => { this.context = undefined; });
|
||||
audit("browser_launched", { headless, channel: this.config.channel ?? "chromium" });
|
||||
}
|
||||
return this.context.pages()[0] ?? this.context.newPage();
|
||||
}
|
||||
|
||||
/** Closes the browser after a quiet period so Chromium does not hold memory between jobs. */
|
||||
release(): void {
|
||||
this.clearIdleTimer();
|
||||
this.idleTimer = setTimeout(() => void this.close(), this.config.browserIdleCloseMs);
|
||||
this.idleTimer.unref();
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
this.clearIdleTimer();
|
||||
const context = this.context;
|
||||
this.context = undefined;
|
||||
if (context) {
|
||||
await context.close().catch(() => undefined);
|
||||
audit("browser_closed");
|
||||
}
|
||||
}
|
||||
|
||||
private clearIdleTimer(): void {
|
||||
if (this.idleTimer) clearTimeout(this.idleTimer);
|
||||
this.idleTimer = undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
import { mkdir, readdir, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import type { Locator, Page } from "playwright";
|
||||
import { audit } from "../log.js";
|
||||
import type { InlineReferenceImage } from "../types.js";
|
||||
import { ContentPolicyBlocked, ImageGenerationError, SessionNotReady, TurnTimedOut, UsageLimitReached } from "./errors.js";
|
||||
import * as sel from "./selectors.js";
|
||||
|
||||
export const NAVIGATION_TIMEOUT_MS = 60_000;
|
||||
export const COMPOSER_TIMEOUT_MS = 30_000;
|
||||
export const POLL_INTERVAL_MS = 2_000;
|
||||
export const TURN_START_TIMEOUT_MS = 30_000;
|
||||
export const SETTLE_AFTER_TURN_MS = 3_000;
|
||||
export const UPLOAD_TIMEOUT_MS = 90_000;
|
||||
export const MIN_IMAGE_SIDE = 256;
|
||||
export const STABLE_POLLS = 3;
|
||||
export const TEXT_ONLY_GRACE_MS = 20_000;
|
||||
|
||||
export interface ImageCandidate {
|
||||
src: string;
|
||||
width: number;
|
||||
height: number;
|
||||
complete: boolean;
|
||||
inUserMessage: boolean;
|
||||
}
|
||||
|
||||
export interface Timing {
|
||||
pollIntervalMs: number;
|
||||
turnStartTimeoutMs: number;
|
||||
settleAfterTurnMs: number;
|
||||
stablePolls: number;
|
||||
textOnlyGraceMs: number;
|
||||
}
|
||||
|
||||
export const DEFAULT_TIMING: Timing = {
|
||||
pollIntervalMs: POLL_INTERVAL_MS,
|
||||
turnStartTimeoutMs: TURN_START_TIMEOUT_MS,
|
||||
settleAfterTurnMs: SETTLE_AFTER_TURN_MS,
|
||||
stablePolls: STABLE_POLLS,
|
||||
textOnlyGraceMs: TEXT_ONLY_GRACE_MS,
|
||||
};
|
||||
|
||||
export function containsAny(text: string | undefined, markers: string[]): boolean {
|
||||
const normalized = (text || "").toLowerCase().replace(/[’`]/g, "'");
|
||||
return markers.some((marker) => normalized.includes(marker));
|
||||
}
|
||||
|
||||
export function isProbablyImageUrl(src: string): boolean {
|
||||
if (!src) return false;
|
||||
if (src.startsWith("data:image/svg+xml")) return false;
|
||||
if (src.startsWith("data:image/") || src.startsWith("blob:")) return true;
|
||||
let parsed: URL;
|
||||
try { parsed = new URL(src); } catch { return false; }
|
||||
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") return false;
|
||||
const lower = src.toLowerCase();
|
||||
return !["/avatar", "profile-picture", "gravatar", ".svg", "favicon"].some((token) => lower.includes(token));
|
||||
}
|
||||
|
||||
export function decodeDataUri(src: string): Buffer {
|
||||
const comma = src.indexOf(",");
|
||||
if (comma < 0) throw new ImageGenerationError("Malformed image data URI");
|
||||
if (!src.slice(0, comma).includes(";base64")) throw new ImageGenerationError("Image data URI is not base64 encoded");
|
||||
return Buffer.from(src.slice(comma + 1), "base64");
|
||||
}
|
||||
|
||||
export function pickGeneratedImage(candidates: ImageCandidate[], baseline: Set<string>): ImageCandidate | undefined {
|
||||
const eligible = candidates.filter((candidate) =>
|
||||
!candidate.inUserMessage
|
||||
&& !baseline.has(candidate.src)
|
||||
&& isProbablyImageUrl(candidate.src)
|
||||
&& candidate.width >= MIN_IMAGE_SIDE
|
||||
&& candidate.height >= MIN_IMAGE_SIDE);
|
||||
return eligible.at(-1);
|
||||
}
|
||||
|
||||
export async function firstVisible(page: Page, selectors: string[], timeoutMs = 0): Promise<Locator | undefined> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
for (;;) {
|
||||
for (const selector of selectors) {
|
||||
try {
|
||||
const locator = page.locator(selector).first();
|
||||
if (await locator.count() > 0 && await locator.isVisible()) return locator;
|
||||
} catch {
|
||||
// Invalid or detached selector: try the next alternative.
|
||||
}
|
||||
}
|
||||
if (Date.now() >= deadline) return undefined;
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
}
|
||||
|
||||
export async function firstAttached(page: Page, selectors: string[]): Promise<Locator | undefined> {
|
||||
for (const selector of selectors) {
|
||||
const locator = page.locator(selector).first();
|
||||
if (await locator.count().catch(() => 0) > 0) return locator;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export async function isLoggedIn(page: Page): Promise<boolean> {
|
||||
if (await firstVisible(page, sel.LOGIN_MARKERS)) return false;
|
||||
return Boolean(await firstAttached(page, sel.LOGGED_IN_MARKERS));
|
||||
}
|
||||
|
||||
export async function ensureSession(page: Page): Promise<void> {
|
||||
if (await firstVisible(page, sel.LOGIN_MARKERS)) throw new SessionNotReady();
|
||||
}
|
||||
|
||||
export async function dismissModals(page: Page): Promise<void> {
|
||||
for (const selector of sel.DISMISS_BUTTONS) {
|
||||
try {
|
||||
const locator = page.locator(selector).first();
|
||||
if (await locator.count() > 0 && await locator.isVisible()) {
|
||||
await locator.click({ timeout: 2000 });
|
||||
await page.waitForTimeout(500);
|
||||
}
|
||||
} catch {
|
||||
// Modal vanished on its own.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function openNewChat(page: Page, url: string, diagnostics?: Diagnostics): Promise<void> {
|
||||
// The root URL always opens an empty thread; clicking "New chat" is less stable.
|
||||
await page.goto(url, { timeout: NAVIGATION_TIMEOUT_MS, waitUntil: "domcontentloaded" });
|
||||
await page.waitForTimeout(2500);
|
||||
await ensureSession(page);
|
||||
await dismissModals(page);
|
||||
if (!await firstVisible(page, sel.COMPOSER, COMPOSER_TIMEOUT_MS)) {
|
||||
await diagnostics?.save(page, "composer-not-found");
|
||||
throw new ImageGenerationError("chatgpt.com composer not found; check selectors.COMPOSER", "UI_CHANGED");
|
||||
}
|
||||
}
|
||||
|
||||
export async function attachReferences(page: Page, references: InlineReferenceImage[], diagnostics?: Diagnostics, timing = DEFAULT_TIMING): Promise<void> {
|
||||
if (references.length === 0) return;
|
||||
const input = await firstAttached(page, sel.FILE_INPUT);
|
||||
if (!input) {
|
||||
await diagnostics?.save(page, "file-input-not-found");
|
||||
throw new ImageGenerationError("chatgpt.com file input not found; check selectors.FILE_INPUT", "UI_CHANGED");
|
||||
}
|
||||
await input.setInputFiles(references.map((reference, index) => ({
|
||||
name: `reference-${index + 1}.${reference.mime_type.split("/")[1].replace("jpeg", "jpg")}`,
|
||||
mimeType: reference.mime_type,
|
||||
buffer: Buffer.from(reference.base64, "base64"),
|
||||
})));
|
||||
const deadline = Date.now() + UPLOAD_TIMEOUT_MS;
|
||||
await page.waitForTimeout(timing.pollIntervalMs);
|
||||
while (Date.now() < deadline) {
|
||||
const uploading = await firstVisible(page, sel.ATTACHMENT_IN_PROGRESS);
|
||||
const send = await firstVisible(page, sel.SEND_BUTTON);
|
||||
if (!uploading && (!send || await send.isEnabled())) return;
|
||||
await page.waitForTimeout(timing.pollIntervalMs);
|
||||
}
|
||||
await diagnostics?.save(page, "reference-upload-timeout");
|
||||
throw new TurnTimedOut(`Reference images did not finish uploading in ${UPLOAD_TIMEOUT_MS / 1000}s`);
|
||||
}
|
||||
|
||||
export async function sendMessage(page: Page, text: string, diagnostics?: Diagnostics): Promise<void> {
|
||||
const composer = await firstVisible(page, sel.COMPOSER, COMPOSER_TIMEOUT_MS);
|
||||
if (!composer) {
|
||||
await diagnostics?.save(page, "composer-unavailable");
|
||||
throw new ImageGenerationError("Composer unavailable when sending the message", "UI_CHANGED");
|
||||
}
|
||||
await composer.click({ timeout: 10_000 });
|
||||
try {
|
||||
await composer.fill(text, { timeout: 10_000 });
|
||||
} catch {
|
||||
await page.keyboard.insertText(text);
|
||||
}
|
||||
await page.waitForTimeout(400 + Math.floor(Math.random() * 800));
|
||||
const send = await firstVisible(page, sel.SEND_BUTTON);
|
||||
if (send) {
|
||||
try {
|
||||
await send.click({ timeout: 5000 });
|
||||
return;
|
||||
} catch {
|
||||
// Fall back to Enter below.
|
||||
}
|
||||
}
|
||||
await page.keyboard.press("Enter");
|
||||
}
|
||||
|
||||
export async function lastAssistantText(page: Page): Promise<string> {
|
||||
for (const selector of sel.ASSISTANT_MESSAGE) {
|
||||
try {
|
||||
const locator = page.locator(selector);
|
||||
if (await locator.count() > 0) return await locator.last().innerText({ timeout: 5000 });
|
||||
} catch {
|
||||
// Try the next alternative.
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
export async function raiseIfBlocked(page: Page): Promise<void> {
|
||||
const banner = await firstVisible(page, sel.ERROR_BANNER);
|
||||
const bannerText = banner ? await banner.innerText({ timeout: 2000 }).catch(() => "") : "";
|
||||
// Only the banner and the assistant reply are checked: the user's own prompt may contain any words.
|
||||
const reply = await lastAssistantText(page);
|
||||
if (containsAny(bannerText, sel.USAGE_LIMIT_TEXTS) || containsAny(reply, sel.USAGE_LIMIT_TEXTS)) {
|
||||
throw new UsageLimitReached(`ChatGPT reports a usage limit: ${(bannerText || reply).slice(0, 300)}`);
|
||||
}
|
||||
}
|
||||
|
||||
export async function waitForTurnComplete(page: Page, timeoutMs: number, diagnostics?: Diagnostics, timing = DEFAULT_TIMING): Promise<void> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const startedDeadline = Math.min(deadline, Date.now() + timing.turnStartTimeoutMs);
|
||||
while (Date.now() < startedDeadline) {
|
||||
if (await firstVisible(page, sel.STOP_BUTTON)) break;
|
||||
await page.waitForTimeout(timing.pollIntervalMs);
|
||||
}
|
||||
let consecutiveIdle = 0;
|
||||
while (Date.now() < deadline) {
|
||||
await raiseIfBlocked(page);
|
||||
if (await firstVisible(page, sel.STOP_BUTTON)) {
|
||||
consecutiveIdle = 0;
|
||||
} else if (++consecutiveIdle >= 2) {
|
||||
await page.waitForTimeout(timing.settleAfterTurnMs);
|
||||
return;
|
||||
}
|
||||
await page.waitForTimeout(timing.pollIntervalMs);
|
||||
}
|
||||
await diagnostics?.save(page, "turn-timeout");
|
||||
throw new TurnTimedOut(`ChatGPT did not finish the turn in ${Math.round(timeoutMs / 1000)}s`);
|
||||
}
|
||||
|
||||
export async function collectImageCandidates(page: Page): Promise<ImageCandidate[]> {
|
||||
return page.evaluate((userSelectors) => Array.from(document.querySelectorAll("img")).map((img) => ({
|
||||
src: img.currentSrc || img.src,
|
||||
width: img.naturalWidth,
|
||||
height: img.naturalHeight,
|
||||
complete: img.complete,
|
||||
inUserMessage: userSelectors.some((selector) => img.closest(selector) !== null),
|
||||
})), sel.USER_MESSAGE);
|
||||
}
|
||||
|
||||
export async function imageSources(page: Page): Promise<Set<string>> {
|
||||
return new Set((await collectImageCandidates(page)).map((candidate) => candidate.src));
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a new, fully loaded image outside our own message whose src stays the same for a few
|
||||
* polls. ChatGPT first shows blurred partial previews, so the first image seen is not the final one.
|
||||
*/
|
||||
export async function waitForGeneratedImage(page: Page, baseline: Set<string>, timeoutMs: number, diagnostics?: Diagnostics, timing = DEFAULT_TIMING): Promise<string> {
|
||||
const deadline = Date.now() + timeoutMs;
|
||||
const textOnlyDeadline = Date.now() + timing.textOnlyGraceMs;
|
||||
let lastSrc = "";
|
||||
let stableCount = 0;
|
||||
while (Date.now() < deadline) {
|
||||
await raiseIfBlocked(page);
|
||||
const reply = await lastAssistantText(page);
|
||||
const inProgress = containsAny(reply, sel.IMAGE_IN_PROGRESS_TEXTS) || Boolean(await firstVisible(page, sel.STOP_BUTTON));
|
||||
const candidate = pickGeneratedImage(await collectImageCandidates(page), baseline);
|
||||
if (candidate && candidate.complete && !inProgress) {
|
||||
stableCount = candidate.src === lastSrc ? stableCount + 1 : 1;
|
||||
lastSrc = candidate.src;
|
||||
if (stableCount >= timing.stablePolls) return candidate.src;
|
||||
} else {
|
||||
stableCount = 0;
|
||||
lastSrc = candidate?.src ?? "";
|
||||
}
|
||||
if (!candidate && !inProgress && Date.now() > textOnlyDeadline && reply.trim()) {
|
||||
await diagnostics?.save(page, "text-reply-without-image");
|
||||
if (containsAny(reply, sel.CONTENT_POLICY_TEXTS)) throw new ContentPolicyBlocked(`ChatGPT refused the request: ${reply.slice(0, 500)}`);
|
||||
if (containsAny(reply, sel.TRANSIENT_ERROR_TEXTS)) throw new ImageGenerationError(`ChatGPT returned an error: ${reply.slice(0, 500)}`);
|
||||
throw new ImageGenerationError(`ChatGPT replied with text instead of an image: ${reply.slice(0, 500)}`, "NO_IMAGE_RETURNED");
|
||||
}
|
||||
await page.waitForTimeout(timing.pollIntervalMs);
|
||||
}
|
||||
await diagnostics?.save(page, "image-not-found");
|
||||
throw new TurnTimedOut(`No generated image appeared in ${Math.round(timeoutMs / 1000)}s; check selectors and diagnostics`);
|
||||
}
|
||||
|
||||
export async function downloadImage(page: Page, src: string): Promise<Buffer> {
|
||||
if (src.startsWith("data:")) return decodeDataUri(src);
|
||||
if (src.startsWith("blob:")) {
|
||||
const base64 = await page.evaluate(async (url) => {
|
||||
const blob = await (await fetch(url)).blob();
|
||||
const bytes = new Uint8Array(await blob.arrayBuffer());
|
||||
let binary = "";
|
||||
for (let offset = 0; offset < bytes.length; offset += 0x8000) binary += String.fromCharCode(...bytes.subarray(offset, offset + 0x8000));
|
||||
return btoa(binary);
|
||||
}, src);
|
||||
return Buffer.from(base64, "base64");
|
||||
}
|
||||
// The browser request context carries the session cookies; a plain fetch from Node gets 403.
|
||||
const response = await page.request.get(src, { timeout: 120_000 });
|
||||
if (!response.ok()) throw new ImageGenerationError(`Image download failed: HTTP ${response.status()}`);
|
||||
return response.body();
|
||||
}
|
||||
|
||||
export class Diagnostics {
|
||||
constructor(private readonly dir: string, private readonly keep: number) {}
|
||||
|
||||
/** Dumps HTML + screenshot of the current page. Never throws. Files may contain conversation text. */
|
||||
async save(page: Page, reason: string): Promise<string | undefined> {
|
||||
try {
|
||||
await mkdir(this.dir, { recursive: true, mode: 0o750 });
|
||||
const slug = reason.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
|
||||
const base = path.join(this.dir, `${new Date().toISOString().replace(/[:.]/g, "-")}-${slug}`);
|
||||
await writeFile(`${base}.html`, await page.content(), { mode: 0o640 });
|
||||
await page.screenshot({ path: `${base}.png`, fullPage: false, timeout: 10_000 }).catch(() => undefined);
|
||||
await this.prune();
|
||||
audit("diagnostic_saved", { reason, file: path.basename(base) });
|
||||
return base;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private async prune(): Promise<void> {
|
||||
const entries = await readdir(this.dir);
|
||||
const htmlFiles = await Promise.all(entries.filter((name) => name.endsWith(".html")).map(async (name) => ({ name, mtime: (await stat(path.join(this.dir, name))).mtimeMs })));
|
||||
htmlFiles.sort((a, b) => a.mtime - b.mtime);
|
||||
for (const stale of htmlFiles.slice(0, Math.max(0, htmlFiles.length - this.keep))) {
|
||||
const base = path.join(this.dir, stale.name.slice(0, -5));
|
||||
await unlink(`${base}.html`).catch(() => undefined);
|
||||
await unlink(`${base}.png`).catch(() => undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import path from "node:path";
|
||||
|
||||
export interface ChatGptConfig {
|
||||
url: string;
|
||||
profileDir: string;
|
||||
headless: boolean;
|
||||
channel?: string;
|
||||
userAgent?: string;
|
||||
locale: string;
|
||||
turnTimeoutMs: number;
|
||||
imageTimeoutMs: number;
|
||||
browserIdleCloseMs: number;
|
||||
diagnosticsDir: string;
|
||||
maxDiagnostics: number;
|
||||
}
|
||||
|
||||
export function loadChatGptConfig(env: NodeJS.ProcessEnv = process.env): ChatGptConfig {
|
||||
return {
|
||||
url: env.CHATGPT_URL || "https://chatgpt.com/",
|
||||
profileDir: path.resolve(env.CHATGPT_PROFILE_DIR || "profiles/chatgpt"),
|
||||
headless: env.CHATGPT_HEADLESS === "true",
|
||||
channel: env.CHATGPT_BROWSER_CHANNEL || undefined,
|
||||
userAgent: env.CHATGPT_USER_AGENT || undefined,
|
||||
locale: env.CHATGPT_LOCALE || "es-ES",
|
||||
turnTimeoutMs: (Number(env.CHATGPT_TURN_TIMEOUT_SECONDS) || 600) * 1000,
|
||||
imageTimeoutMs: (Number(env.CHATGPT_IMAGE_TIMEOUT_SECONDS) || 180) * 1000,
|
||||
browserIdleCloseMs: (Number(env.CHATGPT_BROWSER_IDLE_CLOSE_MINUTES) || 10) * 60 * 1000,
|
||||
diagnosticsDir: path.resolve(env.DIAGNOSTICS_DIR || "diagnostics"),
|
||||
maxDiagnostics: Number(env.MAX_DIAGNOSTICS) || 10,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
export class ImageGenerationError extends Error {
|
||||
constructor(message: string, readonly code = "GENERATION_FAILED") {
|
||||
super(message);
|
||||
this.name = new.target.name;
|
||||
}
|
||||
}
|
||||
|
||||
/** The profile is not logged in. A configuration problem: stop and ask for a manual login. */
|
||||
export class SessionNotReady extends ImageGenerationError {
|
||||
constructor(message = "chatgpt.com asks to log in: stop the service, run `npm run login` and start it again") {
|
||||
super(message, "SESSION_NOT_READY");
|
||||
}
|
||||
}
|
||||
|
||||
/** chatgpt.com shows a usage/rate limit notice. Back off instead of retrying. */
|
||||
export class UsageLimitReached extends ImageGenerationError {
|
||||
constructor(message = "ChatGPT reports that the usage limit has been reached") {
|
||||
super(message, "USAGE_LIMIT_REACHED");
|
||||
}
|
||||
}
|
||||
|
||||
export class ContentPolicyBlocked extends ImageGenerationError {
|
||||
constructor(message: string) {
|
||||
super(message, "CONTENT_POLICY_BLOCKED");
|
||||
}
|
||||
}
|
||||
|
||||
export class TurnTimedOut extends ImageGenerationError {
|
||||
constructor(message: string) {
|
||||
super(message, "TURN_TIMED_OUT");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
export const ASPECT_RATIOS = ["auto", "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"] as const;
|
||||
|
||||
const ORIENTATION: Record<string, string> = {
|
||||
"1:1": "square", "2:3": "portrait", "3:4": "portrait", "4:5": "portrait", "9:16": "vertical",
|
||||
"3:2": "landscape", "4:3": "landscape", "5:4": "landscape", "16:9": "widescreen landscape", "21:9": "ultra-wide landscape",
|
||||
};
|
||||
|
||||
/** Wraps the caller's prompt so ChatGPT generates directly instead of chatting about it. */
|
||||
export function buildImageRequest(prompt: string, aspectRatio: string, referenceCount: number): string {
|
||||
const instructions = [
|
||||
"Generate an image with the prompt below. Do not comment on it, do not rewrite it and do not ask me any questions: create exactly one image right away, at the highest quality available.",
|
||||
];
|
||||
if (aspectRatio !== "auto") instructions.push(`The image must use a ${aspectRatio} aspect ratio (${ORIENTATION[aspectRatio] ?? "custom"} format).`);
|
||||
if (referenceCount > 0) {
|
||||
instructions.push(referenceCount === 1
|
||||
? "Use the attached image as the reference described in the prompt."
|
||||
: `Use the ${referenceCount} attached images as the references described in the prompt.`);
|
||||
}
|
||||
return `${instructions.join(" ")}\n\n${prompt.trim()}`;
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
import type { Page } from "playwright";
|
||||
import { imageDimensions } from "../image.js";
|
||||
import { audit } from "../log.js";
|
||||
import { removeOutputs, storeImage } from "../media.js";
|
||||
import type { ImageRequest, StoredOutput } from "../types.js";
|
||||
import { BrowserSession } from "./browser.js";
|
||||
import {
|
||||
attachReferences, Diagnostics, downloadImage, imageSources, isLoggedIn, openNewChat, sendMessage, waitForGeneratedImage, waitForTurnComplete,
|
||||
} from "./client.js";
|
||||
import { loadChatGptConfig, type ChatGptConfig } from "./config.js";
|
||||
import { ImageGenerationError, TurnTimedOut } from "./errors.js";
|
||||
import { buildImageRequest } from "./prompts.js";
|
||||
|
||||
export const MIN_IMAGE_BYTES = 20_000;
|
||||
|
||||
export interface ImageProvider {
|
||||
generateImages(generationId: string, request: ImageRequest): Promise<StoredOutput[]>;
|
||||
checkSession(): Promise<boolean>;
|
||||
close(): Promise<void>;
|
||||
}
|
||||
|
||||
export class ChatGptImageProvider implements ImageProvider {
|
||||
private readonly browser: BrowserSession;
|
||||
private readonly diagnostics: Diagnostics;
|
||||
|
||||
constructor(private readonly config: ChatGptConfig = loadChatGptConfig()) {
|
||||
this.browser = new BrowserSession(config);
|
||||
this.diagnostics = new Diagnostics(config.diagnosticsDir, config.maxDiagnostics);
|
||||
}
|
||||
|
||||
/** One new chat per image: a fresh thread keeps earlier images out of the DOM and out of the context. */
|
||||
async generateImages(generationId: string, request: ImageRequest): Promise<StoredOutput[]> {
|
||||
const outputs: StoredOutput[] = [];
|
||||
try {
|
||||
const page = await this.browser.page();
|
||||
for (let index = 0; index < request.imageCount; index += 1) {
|
||||
const started = Date.now();
|
||||
const image = await this.generateOne(page, request);
|
||||
outputs.push(await storeImage(generationId, index, image));
|
||||
audit("chatgpt_image_generated", { generationId, index, sizeBytes: image.length, durationMs: Date.now() - started });
|
||||
}
|
||||
return outputs;
|
||||
} catch (error) {
|
||||
await removeOutputs(outputs);
|
||||
throw error;
|
||||
} finally {
|
||||
this.browser.release();
|
||||
}
|
||||
}
|
||||
|
||||
async checkSession(): Promise<boolean> {
|
||||
try {
|
||||
const page = await this.browser.page();
|
||||
await page.goto(this.config.url, { timeout: 60_000, waitUntil: "domcontentloaded" });
|
||||
await page.waitForTimeout(3000);
|
||||
for (let attempt = 0; attempt < 5; attempt += 1) {
|
||||
if (await isLoggedIn(page)) return true;
|
||||
await page.waitForTimeout(2000);
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
this.browser.release();
|
||||
}
|
||||
}
|
||||
|
||||
async close(): Promise<void> {
|
||||
await this.browser.close();
|
||||
}
|
||||
|
||||
private async generateOne(page: Page, request: ImageRequest): Promise<Buffer> {
|
||||
await openNewChat(page, this.config.url, this.diagnostics);
|
||||
const baseline = await imageSources(page);
|
||||
await attachReferences(page, request.references, this.diagnostics);
|
||||
await sendMessage(page, buildImageRequest(request.prompt, request.aspectRatio, request.references.length), this.diagnostics);
|
||||
try {
|
||||
await waitForTurnComplete(page, this.config.turnTimeoutMs, this.diagnostics);
|
||||
} catch (error) {
|
||||
// A turn that never settles is acceptable when the image is already on the page.
|
||||
if (!(error instanceof TurnTimedOut)) throw error;
|
||||
}
|
||||
const src = await waitForGeneratedImage(page, baseline, this.config.imageTimeoutMs, this.diagnostics);
|
||||
const image = await downloadImage(page, src);
|
||||
if (image.length < MIN_IMAGE_BYTES) throw new ImageGenerationError(`Downloaded image is suspiciously small (${image.length} bytes)`);
|
||||
if (!imageDimensions(image)) throw new ImageGenerationError("Downloaded file is not a readable PNG, JPEG or WebP image");
|
||||
return image;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
// The only module that knows the chatgpt.com DOM. Every constant is an ordered list of
|
||||
// alternatives, most stable first. When the UI changes, add the new selector at the front.
|
||||
|
||||
export const COMPOSER = [
|
||||
"#prompt-textarea",
|
||||
'div[contenteditable="true"][id="prompt-textarea"]',
|
||||
'div.ProseMirror[contenteditable="true"]',
|
||||
'textarea[data-id="root"]',
|
||||
'div[contenteditable="true"]',
|
||||
];
|
||||
|
||||
export const SEND_BUTTON = [
|
||||
'button[data-testid="send-button"]',
|
||||
"button#composer-submit-button",
|
||||
'button[aria-label="Send prompt"]',
|
||||
'button[aria-label="Enviar mensaje"]',
|
||||
'button[aria-label="Enviar solicitud"]',
|
||||
];
|
||||
|
||||
export const STOP_BUTTON = [
|
||||
'button[data-testid="stop-button"]',
|
||||
'button[aria-label="Stop streaming"]',
|
||||
'button[aria-label="Stop generating"]',
|
||||
'button[aria-label="Detener la generación"]',
|
||||
'button[aria-label="Detener streaming"]',
|
||||
];
|
||||
|
||||
export const FILE_INPUT = [
|
||||
'input[type="file"][accept*="image"]',
|
||||
'input[type="file"]',
|
||||
];
|
||||
|
||||
export const ATTACHMENT_IN_PROGRESS = [
|
||||
'div[data-testid="attachment-upload-progress"]',
|
||||
'[role="progressbar"]',
|
||||
];
|
||||
|
||||
export const ASSISTANT_MESSAGE = [
|
||||
'div[data-message-author-role="assistant"]',
|
||||
'article[data-testid^="conversation-turn-"] div[data-message-author-role="assistant"]',
|
||||
"div.agent-turn",
|
||||
];
|
||||
|
||||
// Images inside these containers were uploaded by us (references), never generated output.
|
||||
export const USER_MESSAGE = [
|
||||
'div[data-message-author-role="user"]',
|
||||
'article[data-turn="user"]',
|
||||
];
|
||||
|
||||
export const LOGIN_MARKERS = [
|
||||
'button[data-testid="login-button"]',
|
||||
'a[href*="/auth/login"]',
|
||||
'button[data-testid="signup-button"]',
|
||||
'form[action*="/api/auth/signin"]',
|
||||
];
|
||||
|
||||
// Never add the composer here: chatgpt.com also renders it for logged-out guests.
|
||||
export const LOGGED_IN_MARKERS = [
|
||||
'button[data-testid="profile-button"]',
|
||||
'div[data-testid="accounts-profile-button"]',
|
||||
'nav[aria-label="Chat history"]',
|
||||
'nav[aria-label="Historial de chats"]',
|
||||
];
|
||||
|
||||
export const DISMISS_BUTTONS = [
|
||||
'button[data-testid="close-button"]',
|
||||
'div[role="dialog"] button[data-testid="dismiss-button"]',
|
||||
'div[role="dialog"] button[aria-label="Close"]',
|
||||
'div[role="dialog"] button[aria-label="Cerrar"]',
|
||||
];
|
||||
|
||||
export const ERROR_BANNER = [
|
||||
'div[role="alert"]',
|
||||
"div.text-token-text-error",
|
||||
'div[data-testid="error-banner"]',
|
||||
];
|
||||
|
||||
export const USAGE_LIMIT_TEXTS = [
|
||||
"you've reached our limit of messages",
|
||||
"you have reached our limit of messages",
|
||||
"you've hit the limit",
|
||||
"you've hit the plus plan limit",
|
||||
"image generation limit",
|
||||
"you can create images again",
|
||||
"usage limit",
|
||||
"has alcanzado el límite",
|
||||
"límite de mensajes",
|
||||
"límite de uso",
|
||||
"límite de generación de imágenes",
|
||||
"no puedes generar más imágenes",
|
||||
"podrás crear imágenes de nuevo",
|
||||
];
|
||||
|
||||
export const TRANSIENT_ERROR_TEXTS = [
|
||||
"something went wrong",
|
||||
"network error",
|
||||
"i wasn't able to generate",
|
||||
"i'm unable to generate",
|
||||
"se ha producido un error",
|
||||
"ha ocurrido un error",
|
||||
"error de red",
|
||||
"no he podido generar",
|
||||
];
|
||||
|
||||
export const CONTENT_POLICY_TEXTS = [
|
||||
"content policy",
|
||||
"content policies",
|
||||
"violate our",
|
||||
"política de contenido",
|
||||
"políticas de contenido",
|
||||
"infringir nuestras",
|
||||
];
|
||||
|
||||
// Shown while the image is still being rendered (the preview is a blurred partial image).
|
||||
export const IMAGE_IN_PROGRESS_TEXTS = [
|
||||
"creating image",
|
||||
"generating image",
|
||||
"creando imagen",
|
||||
"generando imagen",
|
||||
];
|
||||
@@ -0,0 +1,48 @@
|
||||
import type { ImageMimeType } from "./types.js";
|
||||
|
||||
const PNG_SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
|
||||
|
||||
export function sniffImageMime(data: Buffer): ImageMimeType | undefined {
|
||||
if (data.length >= 8 && data.subarray(0, 8).equals(PNG_SIGNATURE)) return "image/png";
|
||||
if (data.length >= 3 && data[0] === 0xff && data[1] === 0xd8 && data[2] === 0xff) return "image/jpeg";
|
||||
if (data.length >= 12 && data.subarray(0, 4).toString("ascii") === "RIFF" && data.subarray(8, 12).toString("ascii") === "WEBP") return "image/webp";
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function extensionFor(mimeType: ImageMimeType): "png" | "jpg" | "webp" {
|
||||
return mimeType === "image/jpeg" ? "jpg" : mimeType === "image/webp" ? "webp" : "png";
|
||||
}
|
||||
|
||||
export function imageDimensions(data: Buffer): { width: number; height: number } | undefined {
|
||||
const mime = sniffImageMime(data);
|
||||
if (mime === "image/png" && data.length >= 24) return { width: data.readUInt32BE(16), height: data.readUInt32BE(20) };
|
||||
if (mime === "image/jpeg") return jpegDimensions(data);
|
||||
if (mime === "image/webp") return webpDimensions(data);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function jpegDimensions(data: Buffer): { width: number; height: number } | undefined {
|
||||
let offset = 2;
|
||||
while (offset + 9 < data.length) {
|
||||
if (data[offset] !== 0xff) { offset += 1; continue; }
|
||||
const marker = data[offset + 1];
|
||||
if (marker === 0xd8 || marker === 0x01 || (marker >= 0xd0 && marker <= 0xd7)) { offset += 2; continue; }
|
||||
const length = data.readUInt16BE(offset + 2);
|
||||
const isStartOfFrame = marker >= 0xc0 && marker <= 0xcf && marker !== 0xc4 && marker !== 0xc8 && marker !== 0xcc;
|
||||
if (isStartOfFrame) return { height: data.readUInt16BE(offset + 5), width: data.readUInt16BE(offset + 7) };
|
||||
offset += 2 + length;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
function webpDimensions(data: Buffer): { width: number; height: number } | undefined {
|
||||
if (data.length < 30) return undefined;
|
||||
const chunk = data.subarray(12, 16).toString("ascii");
|
||||
if (chunk === "VP8X") return { width: data.readUIntLE(24, 3) + 1, height: data.readUIntLE(27, 3) + 1 };
|
||||
if (chunk === "VP8L") {
|
||||
const bits = data.readUInt32LE(21);
|
||||
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
|
||||
}
|
||||
if (chunk === "VP8 ") return { width: data.readUInt16LE(26) & 0x3fff, height: data.readUInt16LE(28) & 0x3fff };
|
||||
return undefined;
|
||||
}
|
||||
+124
@@ -0,0 +1,124 @@
|
||||
import "dotenv/config";
|
||||
import { timingSafeEqual } from "node:crypto";
|
||||
import express from "express";
|
||||
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
||||
import { ChatGptImageProvider } from "./chatgpt/provider.js";
|
||||
import { JobManager } from "./jobs.js";
|
||||
import { audit, auditError } from "./log.js";
|
||||
import { cleanupOrphanMedia, ensureMediaDir, isOutputFilename, mediaDir, resolvePublicOutput } from "./media.js";
|
||||
import { publicMediaSigningConfigured, validatePublicMediaSignature } from "./public-media.js";
|
||||
import { registerTools } from "./tools.js";
|
||||
import { registerUpdateRoutes } from "./update.js";
|
||||
|
||||
const provider = new ChatGptImageProvider();
|
||||
const jobs = new JobManager(provider);
|
||||
const retentionHours = Number(process.env.MEDIA_RETENTION_HOURS) || 168;
|
||||
await ensureMediaDir();
|
||||
const orphanCleanup = async () => {
|
||||
const removed = await cleanupOrphanMedia(retentionHours);
|
||||
if (removed > 0) audit("orphan_media_expired", { removed, retentionHours });
|
||||
};
|
||||
await orphanCleanup();
|
||||
await jobs.restoreCompletedJobs();
|
||||
jobs.startCleanup(retentionHours);
|
||||
setInterval(() => void orphanCleanup().catch((error) => auditError("orphan_media_cleanup_failed", error)), 15 * 60 * 1000).unref();
|
||||
|
||||
function buildServer(): McpServer {
|
||||
const server = new McpServer({ name: "zenvairo-chatgpt-imagegen", version: "0.1.0" });
|
||||
registerTools(server, jobs);
|
||||
return server;
|
||||
}
|
||||
|
||||
const app = express();
|
||||
app.disable("x-powered-by");
|
||||
if (process.env.TRUST_PROXY) app.set("trust proxy", /^\d+$/.test(process.env.TRUST_PROXY) ? Number(process.env.TRUST_PROXY) : process.env.TRUST_PROXY);
|
||||
app.use(express.json({ limit: `${Number(process.env.MAX_MCP_REQUEST_MB) || 40}mb` }));
|
||||
|
||||
app.get("/public-media/:filename", async (req, res) => {
|
||||
res.setHeader("Cache-Control", "private, no-store");
|
||||
const validation = validatePublicMediaSignature(req.params.filename, req.query.expires, req.query.signature);
|
||||
if (!validation.valid) {
|
||||
res.status(validation.reason === "expired" ? 410 : 403).json({ error: validation.reason === "expired" ? "url_expired" : "invalid_signature" });
|
||||
return;
|
||||
}
|
||||
const output = await resolvePublicOutput(req.params.filename);
|
||||
if (!output) {
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return;
|
||||
}
|
||||
res.setHeader("Content-Type", output.mimeType);
|
||||
res.setHeader("X-Content-Type-Options", "nosniff");
|
||||
res.sendFile(output.filename, { root: mediaDir, dotfiles: "deny", maxAge: 0 }, (error) => {
|
||||
if (error && !res.headersSent) res.status(404).json({ error: "not_found" });
|
||||
});
|
||||
});
|
||||
|
||||
registerUpdateRoutes(app);
|
||||
app.use(authenticate);
|
||||
|
||||
app.get("/health", (_req, res) => res.json({ ok: true, service: "zenvairo-chatgpt-imagegen", publicMediaSigningConfigured: publicMediaSigningConfigured(), ...jobs.status() }));
|
||||
app.get("/media/:filename", (req, res) => {
|
||||
if (!isOutputFilename(req.params.filename)) {
|
||||
res.status(404).json({ error: "not_found" });
|
||||
return;
|
||||
}
|
||||
res.sendFile(req.params.filename, { root: mediaDir, dotfiles: "deny", maxAge: 0 }, (error) => {
|
||||
if (error && !res.headersSent) res.status(404).json({ error: "not_found" });
|
||||
});
|
||||
});
|
||||
|
||||
app.post("/mcp", async (req, res) => {
|
||||
const started = Date.now();
|
||||
try {
|
||||
const server = buildServer();
|
||||
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
||||
res.on("close", () => { void transport.close(); void server.close(); });
|
||||
await server.connect(transport);
|
||||
await transport.handleRequest(req, res, req.body);
|
||||
audit("mcp_request", { method: req.body?.method, tool: req.body?.params?.name, durationMs: Date.now() - started, statusCode: res.statusCode });
|
||||
} catch (error) {
|
||||
auditError("mcp_request_failed", error, { method: req.body?.method, durationMs: Date.now() - started });
|
||||
if (!res.headersSent) res.status(500).json({ jsonrpc: "2.0", error: { code: -32603, message: "Internal server error" }, id: req.body?.id ?? null });
|
||||
}
|
||||
});
|
||||
const methodNotAllowed = (_req: express.Request, res: express.Response) => {
|
||||
res.status(405).json({ error: "Method not allowed; this stateless Streamable HTTP server accepts POST /mcp." });
|
||||
};
|
||||
app.get("/mcp", methodNotAllowed);
|
||||
app.delete("/mcp", methodNotAllowed);
|
||||
|
||||
const port = Number(process.env.PORT) || 8088;
|
||||
const host = process.env.HOST || "127.0.0.1";
|
||||
const httpServer = app.listen(port, host, () => audit("server_started", { host, port, endpoint: "/mcp", mediaRetentionHours: retentionHours }));
|
||||
|
||||
for (const signal of ["SIGINT", "SIGTERM"] as const) {
|
||||
process.once(signal, () => {
|
||||
audit("server_stopping", { signal });
|
||||
httpServer.close();
|
||||
void provider.close().finally(() => process.exit(0));
|
||||
});
|
||||
}
|
||||
|
||||
function authenticate(req: express.Request, res: express.Response, next: express.NextFunction): void {
|
||||
const required = process.env.MCP_SERVER_TOKEN;
|
||||
if (!required) {
|
||||
res.status(503).json({ error: "server_not_configured", message: "MCP_SERVER_TOKEN is required" });
|
||||
return;
|
||||
}
|
||||
const authorization = req.get("authorization") || "";
|
||||
const bearer = authorization.startsWith("Bearer ") ? authorization.slice(7) : "";
|
||||
const injected = req.get("x-mcp-server-token") || "";
|
||||
if (!safeEqual(required, bearer) && !safeEqual(required, injected)) {
|
||||
res.setHeader("WWW-Authenticate", "Bearer");
|
||||
res.status(401).json({ error: "unauthorized" });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
function safeEqual(expected: string, actual: string): boolean {
|
||||
const a = Buffer.from(expected);
|
||||
const b = Buffer.from(actual);
|
||||
return a.length === b.length && timingSafeEqual(a, b);
|
||||
}
|
||||
+284
@@ -0,0 +1,284 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import type { NormalizedArguments } from "./arguments.js";
|
||||
import { ImageGenerationError, SessionNotReady, UsageLimitReached } from "./chatgpt/errors.js";
|
||||
import type { ImageProvider } from "./chatgpt/provider.js";
|
||||
import { audit, auditError } from "./log.js";
|
||||
import { generationWasPurged, loadPersistedJob, loadPersistedJobs, outputExists, persistCompletedJob, purgeGeneration } from "./media.js";
|
||||
import type { GenerationJob, InlineReferenceImage, JobError, ReferenceImage } from "./types.js";
|
||||
|
||||
export interface JobManagerOptions {
|
||||
minIntervalMs: number;
|
||||
maxIntervalMs: number;
|
||||
usageLimitCooldownMs: number;
|
||||
sessionRecheckMs: number;
|
||||
maxQueueLength: number;
|
||||
}
|
||||
|
||||
export function jobManagerOptionsFromEnv(env: NodeJS.ProcessEnv = process.env): JobManagerOptions {
|
||||
const minIntervalMs = (Number(env.CHATGPT_MIN_INTERVAL_SECONDS) || 30) * 1000;
|
||||
return {
|
||||
minIntervalMs,
|
||||
maxIntervalMs: Math.max(minIntervalMs, (Number(env.CHATGPT_MAX_INTERVAL_SECONDS) || 90) * 1000),
|
||||
usageLimitCooldownMs: (Number(env.CHATGPT_USAGE_LIMIT_COOLDOWN_MINUTES) || 60) * 60 * 1000,
|
||||
sessionRecheckMs: (Number(env.CHATGPT_SESSION_RECHECK_MINUTES) || 5) * 60 * 1000,
|
||||
maxQueueLength: Number(env.MAX_QUEUE_LENGTH) || 20,
|
||||
};
|
||||
}
|
||||
|
||||
interface Circuit {
|
||||
reason: "usage_limit" | "session";
|
||||
until: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
type Task =
|
||||
| { kind: "generate"; job: GenerationJob }
|
||||
| { kind: "session_check"; resolve: (loggedIn: boolean) => void; reject: (error: unknown) => void };
|
||||
|
||||
/**
|
||||
* Serial queue: one Chromium profile means one generation at a time. Adds random pacing between
|
||||
* generations and a circuit breaker for usage limits and lost sessions.
|
||||
*/
|
||||
export class JobManager {
|
||||
private readonly jobs = new Map<string, GenerationJob>();
|
||||
private readonly queue: Task[] = [];
|
||||
private draining = false;
|
||||
private lastFinishedAt = 0;
|
||||
private circuit?: Circuit;
|
||||
private session: { loggedIn?: boolean; checkedAt?: string } = {};
|
||||
|
||||
constructor(private readonly provider: ImageProvider, private readonly options: JobManagerOptions = jobManagerOptionsFromEnv()) {}
|
||||
|
||||
async submit(model: string, args: NormalizedArguments, taskTraceId?: string): Promise<GenerationJob> {
|
||||
this.assertAccepting();
|
||||
if (this.pendingGenerations() >= this.options.maxQueueLength) {
|
||||
throw new Error(`QUEUE_FULL: ${this.options.maxQueueLength} generations are already waiting; try again later`);
|
||||
}
|
||||
const references = await this.resolveReferences(args.reference_images);
|
||||
const now = new Date().toISOString();
|
||||
const job: GenerationJob = {
|
||||
generationId: randomUUID(), taskTraceId, model, status: "QUEUING", createdAt: now, updatedAt: now,
|
||||
request: { prompt: args.prompt, aspectRatio: args.aspect_ratio, imageCount: args.image_count, references },
|
||||
};
|
||||
this.jobs.set(job.generationId, job);
|
||||
this.queue.push({ kind: "generate", job });
|
||||
audit("generation_queued", { generationId: job.generationId, taskTraceId, model, imageCount: args.image_count, referenceImageCount: references.length, queueLength: this.queue.length });
|
||||
setImmediate(() => void this.drain());
|
||||
return job;
|
||||
}
|
||||
|
||||
/** Runs through the queue so it never touches the browser while a generation is in progress. */
|
||||
checkSession(): Promise<boolean> {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.queue.push({ kind: "session_check", resolve, reject });
|
||||
setImmediate(() => void this.drain());
|
||||
});
|
||||
}
|
||||
|
||||
get(generationId: string): GenerationJob | undefined {
|
||||
const job = this.jobs.get(generationId);
|
||||
if (job?.status === "QUEUING") {
|
||||
job.queuePosition = this.queue.filter((task) => task.kind === "generate").findIndex((task) => task.kind === "generate" && task.job === job) + 1;
|
||||
} else if (job) {
|
||||
job.queuePosition = undefined;
|
||||
}
|
||||
return job;
|
||||
}
|
||||
|
||||
status(): Record<string, unknown> {
|
||||
const circuit = this.openCircuit();
|
||||
return {
|
||||
queueLength: this.pendingGenerations(),
|
||||
running: [...this.jobs.values()].some((job) => job.status === "RUNNING"),
|
||||
session: this.session,
|
||||
circuit: circuit ? { reason: circuit.reason, retryAfter: new Date(circuit.until).toISOString(), message: circuit.message } : null,
|
||||
};
|
||||
}
|
||||
|
||||
async restoreCompletedJobs(): Promise<number> {
|
||||
const restored = await loadPersistedJobs();
|
||||
for (const job of restored) this.jobs.set(job.generationId, job);
|
||||
if (restored.length > 0) audit("completed_jobs_restored", { count: restored.length });
|
||||
return restored.length;
|
||||
}
|
||||
|
||||
usage(): Record<string, unknown> {
|
||||
const jobs = [...this.jobs.values()];
|
||||
return {
|
||||
scope: "current process plus completed generations restored from retained disk manifests",
|
||||
quotaAvailable: false,
|
||||
quotaMessage: "chatgpt.com does not expose remaining image quota; a usage-limit notice opens the circuit breaker instead.",
|
||||
jobsTracked: jobs.length,
|
||||
jobsCompleted: jobs.filter((job) => job.status === "COMPLETED").length,
|
||||
jobsFailed: jobs.filter((job) => job.status === "FAILED").length,
|
||||
jobsInProgress: jobs.filter((job) => job.status === "QUEUING" || job.status === "RUNNING").length,
|
||||
imagesGenerated: jobs.reduce((sum, job) => sum + (job.outputs?.length ?? 0), 0),
|
||||
...this.status(),
|
||||
};
|
||||
}
|
||||
|
||||
startCleanup(retentionHours: number): NodeJS.Timeout {
|
||||
const interval = setInterval(() => void this.cleanup(retentionHours), 15 * 60 * 1000);
|
||||
interval.unref();
|
||||
return interval;
|
||||
}
|
||||
|
||||
async cleanup(retentionHours: number): Promise<void> {
|
||||
const cutoff = Date.now() - retentionHours * 60 * 60 * 1000;
|
||||
for (const [id, job] of this.jobs) {
|
||||
if ((job.status === "COMPLETED" || job.status === "FAILED") && new Date(job.updatedAt).getTime() < cutoff) {
|
||||
await purgeGeneration(job);
|
||||
this.jobs.delete(id);
|
||||
audit("generation_expired", { generationId: id, retentionHours });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async drain(): Promise<void> {
|
||||
if (this.draining) return;
|
||||
this.draining = true;
|
||||
try {
|
||||
for (let task = this.queue[0]; task; task = this.queue[0]) {
|
||||
if (task.kind === "session_check") {
|
||||
this.queue.shift();
|
||||
await this.runSessionCheck(task);
|
||||
continue;
|
||||
}
|
||||
const circuit = this.openCircuit();
|
||||
if (circuit) {
|
||||
this.queue.shift();
|
||||
const jobError = circuitError(circuit);
|
||||
this.fail(task.job, new Error(jobError.message), jobError);
|
||||
continue;
|
||||
}
|
||||
await this.pace();
|
||||
this.queue.shift();
|
||||
await this.run(task.job);
|
||||
}
|
||||
} finally {
|
||||
this.draining = false;
|
||||
}
|
||||
}
|
||||
|
||||
private async pace(): Promise<void> {
|
||||
if (this.lastFinishedAt === 0) return;
|
||||
const { minIntervalMs, maxIntervalMs } = this.options;
|
||||
const interval = minIntervalMs + Math.random() * (maxIntervalMs - minIntervalMs);
|
||||
const wait = this.lastFinishedAt + interval - Date.now();
|
||||
if (wait > 0) await new Promise((resolve) => setTimeout(resolve, wait));
|
||||
}
|
||||
|
||||
private async run(job: GenerationJob): Promise<void> {
|
||||
if (!job.request) return this.fail(job, new Error("Job has no request"));
|
||||
job.status = "RUNNING"; job.startedAt = new Date().toISOString(); job.updatedAt = job.startedAt;
|
||||
audit("generation_started", { generationId: job.generationId, model: job.model });
|
||||
try {
|
||||
const outputs = await this.provider.generateImages(job.generationId, job.request);
|
||||
job.status = "COMPLETED"; job.outputs = outputs; job.completedAt = new Date().toISOString(); job.updatedAt = job.completedAt;
|
||||
job.request = undefined;
|
||||
this.session = { loggedIn: true, checkedAt: job.completedAt };
|
||||
await persistCompletedJob(job);
|
||||
audit("generation_completed", { generationId: job.generationId, outputCount: outputs.length, outputBytes: outputs.reduce((sum, output) => sum + output.sizeBytes, 0), durationMs: Date.now() - new Date(job.startedAt).getTime() });
|
||||
} catch (error) {
|
||||
this.tripCircuit(error);
|
||||
this.fail(job, error);
|
||||
} finally {
|
||||
this.lastFinishedAt = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
private async runSessionCheck(task: Extract<Task, { kind: "session_check" }>): Promise<void> {
|
||||
try {
|
||||
const loggedIn = await this.provider.checkSession();
|
||||
this.session = { loggedIn, checkedAt: new Date().toISOString() };
|
||||
if (loggedIn && this.circuit?.reason === "session") this.circuit = undefined;
|
||||
audit("session_checked", { loggedIn });
|
||||
task.resolve(loggedIn);
|
||||
} catch (error) {
|
||||
auditError("session_check_failed", error);
|
||||
task.reject(error);
|
||||
}
|
||||
}
|
||||
|
||||
private tripCircuit(error: unknown): void {
|
||||
let reason: Circuit["reason"] | undefined;
|
||||
let cooldown = 0;
|
||||
if (error instanceof UsageLimitReached) { reason = "usage_limit"; cooldown = this.options.usageLimitCooldownMs; }
|
||||
if (error instanceof SessionNotReady) {
|
||||
reason = "session"; cooldown = this.options.sessionRecheckMs;
|
||||
this.session = { loggedIn: false, checkedAt: new Date().toISOString() };
|
||||
}
|
||||
if (!reason) return;
|
||||
this.circuit = { reason, until: Date.now() + cooldown, message: (error as Error).message };
|
||||
audit("circuit_opened", { reason, retryAfter: new Date(this.circuit.until).toISOString() });
|
||||
}
|
||||
|
||||
private openCircuit(): Circuit | undefined {
|
||||
if (this.circuit && this.circuit.until <= Date.now()) this.circuit = undefined;
|
||||
return this.circuit;
|
||||
}
|
||||
|
||||
private assertAccepting(): void {
|
||||
const circuit = this.openCircuit();
|
||||
if (circuit) {
|
||||
const error = circuitError(circuit);
|
||||
throw new Error(`${error.code}: ${error.message} (retry after ${error.retryAfter})`);
|
||||
}
|
||||
}
|
||||
|
||||
private pendingGenerations(): number {
|
||||
return this.queue.filter((task) => task.kind === "generate").length;
|
||||
}
|
||||
|
||||
private fail(job: GenerationJob, error: unknown, jobError: JobError = toJobError(error)): void {
|
||||
job.status = "FAILED"; job.updatedAt = new Date().toISOString(); job.completedAt = job.updatedAt;
|
||||
job.request = undefined;
|
||||
job.error = jobError;
|
||||
auditError("generation_failed", error, { generationId: job.generationId, code: job.error.code, durationMs: job.startedAt ? Date.now() - new Date(job.startedAt).getTime() : undefined });
|
||||
}
|
||||
|
||||
private async resolveReferences(references: ReferenceImage[] | undefined): Promise<InlineReferenceImage[]> {
|
||||
if (!references) return [];
|
||||
const maxAggregateBytes = Math.floor((Number(process.env.MAX_REFERENCE_INPUT_MB) || 25) * 1024 * 1024);
|
||||
let aggregateBytes = 0;
|
||||
const resolved: InlineReferenceImage[] = [];
|
||||
for (const [position, reference] of references.entries()) {
|
||||
if ("base64" in reference) {
|
||||
aggregateBytes += Math.floor(reference.base64.length * 3 / 4);
|
||||
resolved.push(reference);
|
||||
} else {
|
||||
const label = `reference_images[${position}] generation_id ${reference.generation_id}`;
|
||||
let source = this.jobs.get(reference.generation_id) ?? await loadPersistedJob(reference.generation_id);
|
||||
if (!source) {
|
||||
throw new Error(await generationWasPurged(reference.generation_id) ? `REFERENCE_GENERATION_EXPIRED: ${label} has expired` : `REFERENCE_GENERATION_NOT_FOUND: ${label} does not exist`);
|
||||
}
|
||||
if (source.status !== "COMPLETED" || !source.outputs) throw new Error(`REFERENCE_GENERATION_NOT_COMPLETED: ${label} has status ${source.status}; wait for COMPLETED`);
|
||||
const output = source.outputs.find((candidate) => candidate.index === reference.index);
|
||||
if (!output) throw new Error(`REFERENCE_INDEX_OUT_OF_RANGE: ${label} has no output ${reference.index}`);
|
||||
if (!(await outputExists(output))) throw new Error(`REFERENCE_GENERATION_EXPIRED: ${label} output ${reference.index} has expired`);
|
||||
aggregateBytes += output.sizeBytes;
|
||||
resolved.push({ base64: (await readFile(output.path)).toString("base64"), mime_type: output.mimeType as InlineReferenceImage["mime_type"] });
|
||||
}
|
||||
if (aggregateBytes > maxAggregateBytes) throw new Error(`REFERENCE_INPUT_TOO_LARGE: reference_images exceed MAX_REFERENCE_INPUT_MB (${maxAggregateBytes} bytes)`);
|
||||
}
|
||||
return resolved;
|
||||
}
|
||||
}
|
||||
|
||||
function circuitError(circuit: Circuit): JobError {
|
||||
return circuit.reason === "usage_limit"
|
||||
? { code: "USAGE_LIMIT_REACHED", message: "ChatGPT usage limit reached; generation paused", retryable: true, retryAfter: new Date(circuit.until).toISOString() }
|
||||
: { code: "SESSION_NOT_READY", message: "The ChatGPT profile is not logged in; an operator must run `npm run login`", retryable: false, retryAfter: new Date(circuit.until).toISOString() };
|
||||
}
|
||||
|
||||
export function toJobError(error: unknown): JobError {
|
||||
const message = (error instanceof Error ? error.message : String(error)).slice(0, 2000);
|
||||
if (error instanceof ImageGenerationError) {
|
||||
const retryable = ["USAGE_LIMIT_REACHED", "TURN_TIMED_OUT", "GENERATION_FAILED", "NO_IMAGE_RETURNED"].includes(error.code);
|
||||
return { code: error.code, message, retryable };
|
||||
}
|
||||
if (/Timeout|net::ERR_|Target page, context or browser has been closed/i.test(message)) return { code: "BROWSER_ERROR", message, retryable: true };
|
||||
if (/Executable doesn't exist|ProcessSingleton|SingletonLock|profile.*in use/i.test(message)) return { code: "SERVER_NOT_CONFIGURED", message, retryable: false };
|
||||
return { code: "GENERATION_FAILED", message, retryable: false };
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
export function audit(event: string, fields: Record<string, unknown> = {}): void {
|
||||
process.stdout.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level: "info", event, ...fields })}\n`);
|
||||
}
|
||||
|
||||
export function auditError(event: string, error: unknown, fields: Record<string, unknown> = {}): void {
|
||||
const details = errorDetails(error);
|
||||
process.stderr.write(`${JSON.stringify({ timestamp: new Date().toISOString(), level: "error", event, ...fields, ...details })}\n`);
|
||||
}
|
||||
|
||||
export function errorDetails(error: unknown): { errorName: string; errorMessage: string; providerStatus?: number } {
|
||||
if (error instanceof Error) {
|
||||
const status = providerStatus(error);
|
||||
return { errorName: error.name, errorMessage: error.message, ...(status ? { providerStatus: status } : {}) };
|
||||
}
|
||||
return { errorName: "UnknownError", errorMessage: String(error) };
|
||||
}
|
||||
|
||||
export function providerStatus(error: unknown): number | undefined {
|
||||
if (!error || typeof error !== "object") return undefined;
|
||||
const record = error as Record<string, unknown>;
|
||||
const candidates = [record.status, record.statusCode, record.code];
|
||||
for (const value of candidates) {
|
||||
const parsed = typeof value === "number" ? value : Number(value);
|
||||
if (Number.isInteger(parsed) && parsed >= 100 && parsed <= 599) return parsed;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import "dotenv/config";
|
||||
import { BrowserSession } from "./chatgpt/browser.js";
|
||||
import { isLoggedIn } from "./chatgpt/client.js";
|
||||
import { loadChatGptConfig } from "./chatgpt/config.js";
|
||||
|
||||
// Opens chatgpt.com in a visible browser with the persistent profile so an operator can log in
|
||||
// by hand (2FA included). The service must be stopped: Chromium locks the profile directory.
|
||||
// `--check` only reports whether the profile is logged in.
|
||||
const config = loadChatGptConfig();
|
||||
const checkOnly = process.argv.includes("--check");
|
||||
const browser = new BrowserSession(config);
|
||||
|
||||
try {
|
||||
const page = await browser.page(checkOnly ? config.headless : false);
|
||||
await page.goto(config.url, { timeout: 60_000, waitUntil: "domcontentloaded" });
|
||||
if (!checkOnly) console.log(`Profile: ${config.profileDir}\nLog in to chatgpt.com in the opened window. It closes by itself once the session is detected (10 min max).`);
|
||||
const attempts = checkOnly ? 5 : 200;
|
||||
let loggedIn = false;
|
||||
for (let attempt = 0; attempt < attempts && !loggedIn; attempt += 1) {
|
||||
await page.waitForTimeout(3000);
|
||||
loggedIn = await isLoggedIn(page);
|
||||
}
|
||||
console.log(loggedIn ? "Session detected: the profile is logged in." : "No logged-in session detected.");
|
||||
process.exitCode = loggedIn ? 0 : 1;
|
||||
} catch (error) {
|
||||
console.error(`Login failed: ${error instanceof Error ? error.message : String(error)}`);
|
||||
process.exitCode = 2;
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
+194
@@ -0,0 +1,194 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { mkdir, readdir, readFile, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||
import path from "node:path";
|
||||
import { extensionFor, imageDimensions, sniffImageMime } from "./image.js";
|
||||
import { createPublicMediaUrl } from "./public-media.js";
|
||||
import type { GenerationJob, StoredOutput } from "./types.js";
|
||||
|
||||
export const mediaDir = path.resolve(process.env.MEDIA_DIR || "media");
|
||||
export const maxInlineBytes = Math.floor((Number(process.env.MAX_INLINE_MEDIA_MB) || 25) * 1024 * 1024);
|
||||
export const maxMediaBytes = Math.floor((Number(process.env.MAX_MEDIA_MB) || 50) * 1024 * 1024);
|
||||
const tombstoneRetentionDays = Number(process.env.TOMBSTONE_RETENTION_DAYS) || 30;
|
||||
const OUTPUT_FILENAME = /^([0-9a-f-]{36})-(\d+)\.(png|jpg|webp)$/;
|
||||
|
||||
export async function ensureMediaDir(): Promise<void> {
|
||||
await mkdir(mediaDir, { recursive: true });
|
||||
}
|
||||
|
||||
export async function storeImage(generationId: string, index: number, buffer: Buffer): Promise<StoredOutput> {
|
||||
if (buffer.length === 0) throw new Error("ChatGPT returned an empty image");
|
||||
if (buffer.length > maxMediaBytes) throw new Error(`Generated image exceeds MAX_MEDIA_MB (${maxMediaBytes} bytes)`);
|
||||
const mimeType = sniffImageMime(buffer);
|
||||
if (!mimeType) throw new Error("Downloaded file is not a PNG, JPEG or WebP image");
|
||||
const filename = `${generationId}-${index}.${extensionFor(mimeType)}`;
|
||||
const outputPath = path.join(mediaDir, filename);
|
||||
await writeFile(outputPath, buffer, { mode: 0o640 });
|
||||
return {
|
||||
index, path: outputPath, filename, mimeType, sizeBytes: buffer.length,
|
||||
sha256: createHash("sha256").update(buffer).digest("hex"), ...imageDimensions(buffer),
|
||||
};
|
||||
}
|
||||
|
||||
export async function outputPayload(outputs: StoredOutput[], publicBaseUrl: string, includeBase64 = false): Promise<Array<Record<string, unknown>>> {
|
||||
const totalBytes = outputs.reduce((sum, output) => sum + output.sizeBytes, 0);
|
||||
const inline = includeBase64 && totalBytes <= maxInlineBytes;
|
||||
const base = publicBaseUrl.replace(/\/+$/, "");
|
||||
return Promise.all(outputs.map(async (output) => ({
|
||||
index: output.index,
|
||||
mimeType: output.mimeType,
|
||||
sizeBytes: output.sizeBytes,
|
||||
sha256: output.sha256,
|
||||
...(output.width && output.height ? { width: output.width, height: output.height } : {}),
|
||||
...createPublicMediaUrl(output.filename, base),
|
||||
downloadUrl: `${base}/media/${encodeURIComponent(output.filename)}`,
|
||||
...(inline ? { base64: (await readFile(output.path)).toString("base64") } : {}),
|
||||
})));
|
||||
}
|
||||
|
||||
export function isOutputFilename(filename: string): boolean {
|
||||
return OUTPUT_FILENAME.test(filename);
|
||||
}
|
||||
|
||||
export async function resolvePublicOutput(filename: string): Promise<StoredOutput | undefined> {
|
||||
const match = filename.match(OUTPUT_FILENAME);
|
||||
if (!match) return undefined;
|
||||
const job = await loadPersistedJob(match[1]);
|
||||
const output = job?.outputs?.find((candidate) => candidate.filename === filename && candidate.index === Number(match[2]));
|
||||
if (!output || !(await outputExists(output))) return undefined;
|
||||
return output;
|
||||
}
|
||||
|
||||
export async function removeOutputs(outputs: StoredOutput[] | undefined): Promise<void> {
|
||||
if (!outputs) return;
|
||||
await Promise.all(outputs.map((output) => unlink(output.path).catch(() => undefined)));
|
||||
}
|
||||
|
||||
export async function persistCompletedJob(job: GenerationJob): Promise<void> {
|
||||
if (job.status !== "COMPLETED" || !job.outputs) throw new Error("Only completed jobs with outputs can be persisted");
|
||||
const manifest = {
|
||||
version: 1,
|
||||
generationId: job.generationId,
|
||||
taskTraceId: job.taskTraceId,
|
||||
model: job.model,
|
||||
status: "COMPLETED",
|
||||
createdAt: job.createdAt,
|
||||
startedAt: job.startedAt,
|
||||
completedAt: job.completedAt,
|
||||
updatedAt: job.updatedAt,
|
||||
outputs: job.outputs.map(({ path: _path, ...output }) => output),
|
||||
};
|
||||
const target = manifestPath(job.generationId);
|
||||
const temporary = `${target}.${process.pid}.tmp`;
|
||||
await writeFile(temporary, JSON.stringify(manifest), { mode: 0o640 });
|
||||
await rename(temporary, target);
|
||||
}
|
||||
|
||||
export async function loadPersistedJobs(): Promise<GenerationJob[]> {
|
||||
const jobs: GenerationJob[] = [];
|
||||
for (const filename of await readdir(mediaDir)) {
|
||||
const match = filename.match(/^([0-9a-f-]{36})\.manifest\.json$/);
|
||||
if (!match) continue;
|
||||
const job = await loadPersistedJob(match[1]);
|
||||
if (job) jobs.push(job);
|
||||
}
|
||||
return jobs;
|
||||
}
|
||||
|
||||
export async function loadPersistedJob(generationId: string): Promise<GenerationJob | undefined> {
|
||||
try {
|
||||
const parsed = JSON.parse(await readFile(manifestPath(generationId), "utf8")) as Record<string, unknown>;
|
||||
if (parsed.version !== 1 || parsed.generationId !== generationId || parsed.status !== "COMPLETED") return undefined;
|
||||
if (!Array.isArray(parsed.outputs)) return undefined;
|
||||
const outputs: StoredOutput[] = parsed.outputs.map((value, position) => {
|
||||
if (!value || typeof value !== "object") throw new Error("Invalid persisted output");
|
||||
const output = value as Record<string, unknown>;
|
||||
const index = Number(output.index ?? position);
|
||||
const filename = String(output.filename ?? "");
|
||||
if (!Number.isInteger(index) || index < 0 || !filename.startsWith(`${generationId}-${index}.`) || !isOutputFilename(filename)) {
|
||||
throw new Error("Invalid persisted output path");
|
||||
}
|
||||
return {
|
||||
index,
|
||||
path: path.join(mediaDir, filename),
|
||||
filename,
|
||||
mimeType: String(output.mimeType),
|
||||
sizeBytes: Number(output.sizeBytes),
|
||||
sha256: String(output.sha256),
|
||||
...(Number(output.width) > 0 && Number(output.height) > 0 ? { width: Number(output.width), height: Number(output.height) } : {}),
|
||||
};
|
||||
});
|
||||
return {
|
||||
generationId,
|
||||
taskTraceId: typeof parsed.taskTraceId === "string" ? parsed.taskTraceId : undefined,
|
||||
model: String(parsed.model),
|
||||
status: "COMPLETED",
|
||||
createdAt: String(parsed.createdAt),
|
||||
startedAt: typeof parsed.startedAt === "string" ? parsed.startedAt : undefined,
|
||||
completedAt: typeof parsed.completedAt === "string" ? parsed.completedAt : undefined,
|
||||
updatedAt: String(parsed.updatedAt),
|
||||
outputs,
|
||||
};
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
export async function purgeGeneration(job: GenerationJob): Promise<void> {
|
||||
await removeOutputs(job.outputs);
|
||||
await unlink(manifestPath(job.generationId)).catch(() => undefined);
|
||||
await writeTombstone(job.generationId);
|
||||
}
|
||||
|
||||
export async function generationWasPurged(generationId: string): Promise<boolean> {
|
||||
try {
|
||||
return (await stat(tombstonePath(generationId))).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function outputExists(output: StoredOutput): Promise<boolean> {
|
||||
try {
|
||||
const file = await stat(output.path);
|
||||
return file.isFile() && file.size === output.sizeBytes;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export async function cleanupOrphanMedia(retentionHours: number): Promise<number> {
|
||||
const cutoff = Date.now() - retentionHours * 60 * 60 * 1000;
|
||||
const tombstoneCutoff = Date.now() - tombstoneRetentionDays * 24 * 60 * 60 * 1000;
|
||||
let removed = 0;
|
||||
for (const filename of await readdir(mediaDir)) {
|
||||
const artifact = filename.match(/^([0-9a-f-]{36})(?:-\d+\.(?:png|jpg|webp)|\.manifest\.json)$/);
|
||||
const tombstone = filename.match(/^([0-9a-f-]{36})\.expired\.json$/);
|
||||
if (!artifact && !tombstone) continue;
|
||||
const outputPath = path.join(mediaDir, filename);
|
||||
try {
|
||||
const file = await stat(outputPath);
|
||||
if (artifact && file.mtimeMs < cutoff) {
|
||||
await unlink(outputPath);
|
||||
await writeTombstone(artifact[1]);
|
||||
removed += 1;
|
||||
} else if (tombstone && file.mtimeMs < tombstoneCutoff) {
|
||||
await unlink(outputPath);
|
||||
}
|
||||
} catch {
|
||||
// A concurrent cleanup/download may have removed the file.
|
||||
}
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
function manifestPath(generationId: string): string {
|
||||
return path.join(mediaDir, `${generationId}.manifest.json`);
|
||||
}
|
||||
|
||||
function tombstonePath(generationId: string): string {
|
||||
return path.join(mediaDir, `${generationId}.expired.json`);
|
||||
}
|
||||
|
||||
async function writeTombstone(generationId: string): Promise<void> {
|
||||
await writeFile(tombstonePath(generationId), JSON.stringify({ generationId, purgedAt: new Date().toISOString() }), { mode: 0o640 });
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { createHmac, timingSafeEqual } from "node:crypto";
|
||||
|
||||
const DEFAULT_TTL_SECONDS = 24 * 60 * 60;
|
||||
const MAX_TTL_SECONDS = 7 * 24 * 60 * 60;
|
||||
const CLOCK_SKEW_SECONDS = 60;
|
||||
|
||||
export interface SignedPublicMediaUrl {
|
||||
publicUrl: string;
|
||||
publicUrlExpiresAt: string;
|
||||
}
|
||||
|
||||
export function publicMediaTtlSeconds(): number {
|
||||
const configured = Number(process.env.PUBLIC_MEDIA_URL_TTL_SECONDS);
|
||||
if (!Number.isInteger(configured) || configured < 60) return DEFAULT_TTL_SECONDS;
|
||||
return Math.min(configured, MAX_TTL_SECONDS);
|
||||
}
|
||||
|
||||
export function publicMediaSigningConfigured(): boolean {
|
||||
return signingSecret().length >= 32;
|
||||
}
|
||||
|
||||
export function createPublicMediaUrl(
|
||||
filename: string,
|
||||
publicBaseUrl: string,
|
||||
nowMs = Date.now(),
|
||||
): SignedPublicMediaUrl {
|
||||
assertSafeFilename(filename);
|
||||
const secret = requireSigningSecret();
|
||||
const expires = Math.floor(nowMs / 1000) + publicMediaTtlSeconds();
|
||||
const signature = sign(filename, expires, secret);
|
||||
const base = publicBaseUrl.replace(/\/+$/, "");
|
||||
return {
|
||||
publicUrl: `${base}/public-media/${encodeURIComponent(filename)}?expires=${expires}&signature=${signature}`,
|
||||
publicUrlExpiresAt: new Date(expires * 1000).toISOString(),
|
||||
};
|
||||
}
|
||||
|
||||
export function validatePublicMediaSignature(
|
||||
filename: string,
|
||||
rawExpires: unknown,
|
||||
rawSignature: unknown,
|
||||
nowMs = Date.now(),
|
||||
): { valid: true; expires: number } | { valid: false; reason: "invalid" | "expired" } {
|
||||
if (!publicMediaSigningConfigured()) return { valid: false, reason: "invalid" };
|
||||
try {
|
||||
assertSafeFilename(filename);
|
||||
} catch {
|
||||
return { valid: false, reason: "invalid" };
|
||||
}
|
||||
if (typeof rawExpires !== "string" || !/^\d{10}$/.test(rawExpires)) return { valid: false, reason: "invalid" };
|
||||
if (typeof rawSignature !== "string" || !/^[A-Za-z0-9_-]{43}$/.test(rawSignature)) return { valid: false, reason: "invalid" };
|
||||
|
||||
const expires = Number(rawExpires);
|
||||
const nowSeconds = Math.floor(nowMs / 1000);
|
||||
if (!Number.isSafeInteger(expires)) return { valid: false, reason: "invalid" };
|
||||
if (expires < nowSeconds) return { valid: false, reason: "expired" };
|
||||
if (expires > nowSeconds + publicMediaTtlSeconds() + CLOCK_SKEW_SECONDS) return { valid: false, reason: "invalid" };
|
||||
|
||||
const expected = Buffer.from(sign(filename, expires, requireSigningSecret()));
|
||||
const actual = Buffer.from(rawSignature);
|
||||
if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return { valid: false, reason: "invalid" };
|
||||
return { valid: true, expires };
|
||||
}
|
||||
|
||||
function sign(filename: string, expires: number, secret: string): string {
|
||||
return createHmac("sha256", secret)
|
||||
.update(`zenvairo-public-media-v1\n${filename}\n${expires}`, "utf8")
|
||||
.digest("base64url");
|
||||
}
|
||||
|
||||
function signingSecret(): string {
|
||||
return process.env.PUBLIC_MEDIA_SIGNING_SECRET || "";
|
||||
}
|
||||
|
||||
function requireSigningSecret(): string {
|
||||
const secret = signingSecret();
|
||||
if (secret.length < 32) throw new Error("PUBLIC_MEDIA_SIGNING_SECRET must contain at least 32 characters");
|
||||
return secret;
|
||||
}
|
||||
|
||||
function assertSafeFilename(filename: string): void {
|
||||
if (!/^[0-9a-f-]{36}-\d+\.(png|jpg|webp)$/.test(filename)) throw new Error("Invalid public media filename");
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||
import { z } from "zod";
|
||||
import { MODEL, normalizeArguments, resolveModel } from "./arguments.js";
|
||||
import type { JobManager } from "./jobs.js";
|
||||
import { maxInlineBytes, outputExists, outputPayload } from "./media.js";
|
||||
import { publicMediaTtlSeconds } from "./public-media.js";
|
||||
|
||||
const taskTraceIdSchema = z.string().uuid().optional().describe("Optional UUID used to group related calls.");
|
||||
const referenceImageSchema = z.union([
|
||||
z.object({ generation_id: z.string().uuid(), index: z.number().int().min(0).optional() }),
|
||||
z.object({ base64: z.string().min(1), mime_type: z.enum(["image/png", "image/jpeg", "image/webp"]) }),
|
||||
]);
|
||||
const argumentsSchema = z.array(z.object({
|
||||
name: z.string().min(1),
|
||||
value: z.union([z.string(), z.number(), z.boolean(), z.array(referenceImageSchema)]),
|
||||
})).describe("List of {name, value} pairs. See who_am_i for the accepted arguments.");
|
||||
|
||||
export function registerTools(server: McpServer, jobs: JobManager): void {
|
||||
const retentionHours = Number(process.env.MEDIA_RETENTION_HOURS) || 168;
|
||||
const publicBaseUrl = process.env.PUBLIC_BASE_URL || `http://127.0.0.1:${Number(process.env.PORT) || 8088}`;
|
||||
|
||||
server.tool("who_am_i", "Describe the ChatGPT web image backend: model, accepted arguments, queue and session state.", {
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ taskTraceId }) => jsonResult({
|
||||
service: "Zenvairo ChatGPT Image MCP",
|
||||
taskTraceId,
|
||||
backend: "chatgpt.com web UI automated with Playwright (unofficial; uses the logged-in account's image quota)",
|
||||
workflow: "generate_image returns a generationId immediately; poll query_tasks every 10-20 s. Jobs run one at a time and each image takes roughly 1-3 minutes plus queue time.",
|
||||
resultDelivery: {
|
||||
default: "outputs[].publicUrl (HMAC-signed, no credentials needed)",
|
||||
publicUrlTtlSeconds: publicMediaTtlSeconds(),
|
||||
inlineBase64: `query_tasks with include_base64=true, up to ${Math.floor(maxInlineBytes / 1024 / 1024)} MiB`,
|
||||
},
|
||||
generationRetentionHours: retentionHours,
|
||||
models: { image: [MODEL] },
|
||||
state: jobs.status(),
|
||||
}));
|
||||
|
||||
server.tool("generate_image", "Queue an image generation on chatgpt.com and return a generationId immediately. Poll it with query_tasks.", {
|
||||
model: z.string().min(1).default(MODEL.name).describe(`Use '${MODEL.name}'.`),
|
||||
arguments: argumentsSchema,
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ model, arguments: inputArguments, taskTraceId }) => {
|
||||
try {
|
||||
const job = await jobs.submit(resolveModel(model), normalizeArguments(inputArguments), taskTraceId);
|
||||
return jsonResult({ generationId: job.generationId, status: job.status, model: job.model, queuePosition: jobs.get(job.generationId)?.queuePosition });
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
const code = message.match(/^([A-Z][A-Z_]+):/)?.[1] ?? "INVALID_REQUEST";
|
||||
return jsonResult({ status: "FAILED", error: { code, message } }, true);
|
||||
}
|
||||
});
|
||||
|
||||
server.tool("query_tasks", "Poll an image generation. COMPLETED results include outputs[].publicUrl (expiring signed URL) that can be passed to other tools directly.", {
|
||||
generationId: z.string().uuid(),
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
include_base64: z.boolean().default(false).describe("Default false. Set true only when the image bytes are needed inline."),
|
||||
}, async ({ generationId, taskTraceId, include_base64 }) => {
|
||||
const job = jobs.get(generationId);
|
||||
if (!job) return jsonResult({ generationId, status: "FAILED", error: { code: "JOB_NOT_FOUND", message: "Unknown or expired generationId", retryable: false } }, true);
|
||||
if (taskTraceId && job.taskTraceId && taskTraceId !== job.taskTraceId) {
|
||||
return jsonResult({ generationId, status: "FAILED", error: { code: "TRACE_ID_MISMATCH", message: "taskTraceId does not match this generation", retryable: false } }, true);
|
||||
}
|
||||
const payload: Record<string, unknown> = {
|
||||
generationId: job.generationId, taskTraceId: job.taskTraceId, status: job.status, model: job.model,
|
||||
...(job.queuePosition ? { queuePosition: job.queuePosition } : {}),
|
||||
createdAt: job.createdAt, startedAt: job.startedAt, completedAt: job.completedAt,
|
||||
};
|
||||
if (job.status === "FAILED") payload.error = job.error;
|
||||
if (job.status === "COMPLETED" && job.outputs) {
|
||||
if (!(await Promise.all(job.outputs.map(outputExists))).every(Boolean)) {
|
||||
return jsonResult({ ...payload, status: "FAILED", error: { code: "MEDIA_EXPIRED", message: "Generated media is no longer available", retryable: false } }, true);
|
||||
}
|
||||
payload.outputs = await outputPayload(job.outputs, publicBaseUrl, include_base64);
|
||||
}
|
||||
return jsonResult(payload, job.status === "FAILED");
|
||||
});
|
||||
|
||||
server.tool("check_session", "Open chatgpt.com with the server's browser profile and report whether it is logged in. Waits for any running generation first.", {
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ taskTraceId }) => {
|
||||
try {
|
||||
const loggedIn = await jobs.checkSession();
|
||||
return jsonResult({ taskTraceId, loggedIn, ...(loggedIn ? {} : { action: "An operator must stop the service and run `npm run login` (see docs/chatgpt-session.md)." }) }, !loggedIn);
|
||||
} catch (error) {
|
||||
return jsonResult({ taskTraceId, loggedIn: false, error: { code: "BROWSER_ERROR", message: error instanceof Error ? error.message : String(error) } }, true);
|
||||
}
|
||||
});
|
||||
|
||||
server.tool("get_usage", "Return process-local generation counters, queue length and circuit-breaker state.", {
|
||||
taskTraceId: taskTraceIdSchema,
|
||||
}, async ({ taskTraceId }) => jsonResult({ taskTraceId, ...jobs.usage() }));
|
||||
}
|
||||
|
||||
function jsonResult(payload: Record<string, unknown>, isError = false): { content: Array<{ type: "text"; text: string }>; isError?: boolean } {
|
||||
return { content: [{ type: "text", text: JSON.stringify(payload) }], ...(isError ? { isError: true } : {}) };
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
export type JobStatus = "QUEUING" | "RUNNING" | "COMPLETED" | "FAILED";
|
||||
|
||||
export interface ToolArgument {
|
||||
name: string;
|
||||
value: unknown;
|
||||
}
|
||||
|
||||
export interface StoredOutput {
|
||||
index: number;
|
||||
path: string;
|
||||
filename: string;
|
||||
mimeType: string;
|
||||
sizeBytes: number;
|
||||
sha256: string;
|
||||
width?: number;
|
||||
height?: number;
|
||||
}
|
||||
|
||||
export type ImageMimeType = "image/png" | "image/jpeg" | "image/webp";
|
||||
|
||||
export interface InlineReferenceImage {
|
||||
base64: string;
|
||||
mime_type: ImageMimeType;
|
||||
}
|
||||
|
||||
export interface GenerationReferenceImage {
|
||||
generation_id: string;
|
||||
index: number;
|
||||
}
|
||||
|
||||
export type ReferenceImage = InlineReferenceImage | GenerationReferenceImage;
|
||||
|
||||
export interface ImageRequest {
|
||||
prompt: string;
|
||||
aspectRatio: string;
|
||||
imageCount: number;
|
||||
references: InlineReferenceImage[];
|
||||
}
|
||||
|
||||
export interface JobError {
|
||||
code: string;
|
||||
message: string;
|
||||
retryable: boolean;
|
||||
retryAfter?: string;
|
||||
}
|
||||
|
||||
export interface GenerationJob {
|
||||
generationId: string;
|
||||
taskTraceId?: string;
|
||||
model: string;
|
||||
request?: ImageRequest;
|
||||
status: JobStatus;
|
||||
queuePosition?: number;
|
||||
createdAt: string;
|
||||
startedAt?: string;
|
||||
completedAt?: string;
|
||||
updatedAt: string;
|
||||
outputs?: StoredOutput[];
|
||||
error?: JobError;
|
||||
}
|
||||
Reference in new issue
Block a user