#!/usr/bin/env tsx /** * gen-asset — generate a dev UI asset and write the bytes into the repo. For * the visual chrome Claude commits into the apps (illustrations, empty-states, * decorative/hero/background art, logos, the 1024² icon master). * * TWO PROVIDERS, BOTH CALLED DIRECTLY. There is no server and no edge function * in the path (it used to POST to a `generate-asset` Supabase edge function in * the Tinmen monorepo; that stack is retired and the function is gone): * * `--provider gemini` (the default) POSTs `generativelanguage.googleapis.com` * `/v1/models/:generateContent` with `responseModalities: ["IMAGE"]`, * and the base64 bytes come back on an inline-data part. * * `--provider openai` POSTs `api.openai.com/v1/images/generations` with * `{model, prompt, n: 1, size, …}`, and the base64 bytes come back on * `data[0].b64_json`. OpenAI has no aspect-ratio knob — it takes a pixel * size — so `--aspect` maps to the nearest size the model actually has, of * the SAME orientation, and refuses by name when nothing is near enough * (`--aspect 21:9` on `gpt-image-1`). A flag that quietly stopped applying * would be the silent fallback this repo bans. * * THE KEYS, one per provider, each read from the environment first and then * from `.env.local` at the repo root, which is gitignored: * * gemini → `COTTON_IMAGE_API_KEY`, a Google AI Studio key. Header * `x-goog-api-key`. * openai → `OPENAI_API_KEY`, a platform.openai.com key. Header * `Authorization: Bearer`. * * A key travels in that HEADER only: never in the URL, never in argv, never in * a log line, and never in an error message — an error built out of a response * body is redacted against the key before it is thrown. * * Committed UI chrome lives in the repo — this tool never touches a media host. * * Usage: * pnpm gen:asset "" --out apps/loom/Sources/CottonPaper/Media.xcassets/emptyInbox.imageset/emptyInbox.png * pnpm gen:asset "" --out path.png --aspect 16:9 * pnpm gen:asset "" --out path.png --size 2K --model gemini-3-pro-image * pnpm gen:asset "" --out path.png --provider openai --aspect 1:1 * * Flags: * --out (required) destination, relative to the cwd or absolute * --provider

gemini (default) | openai * --aspect 1:1 (model default) | 2:3 | 3:2 | 3:4 | 4:3 | 4:5 | 5:4 | 9:16 | 16:9 | 21:9 * --size 1K (model default) | 2K | 4K — the long edge, not pixels. Gemini only. * --model gemini: gemini-2.5-flash-image (default), gemini-3-pro-image * openai: gpt-image-1 (default), dall-e-3 * * Exit codes: 0 ok · 1 generation failed · 2 bad arguments, or no key. */ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"; import { dirname, isAbsolute, join, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const HERE = dirname(fileURLToPath(import.meta.url)); export const REPO_ROOT = resolve(HERE, ".."); /** The image providers this tool speaks to. Gemini is the default. */ export const PROVIDERS = ["gemini", "openai"] as const; export type Provider = (typeof PROVIDERS)[number]; export const DEFAULT_PROVIDER: Provider = "gemini"; /** The variable that authenticates a Gemini call. */ export const KEY_VAR = "COTTON_IMAGE_API_KEY"; /** The variable that authenticates an OpenAI call — the owner's standing key. */ export const OPENAI_KEY_VAR = "OPENAI_API_KEY"; /** Where the key lives when it is not exported. Gitignored; never committed. */ export const KEY_FILE = ".env.local"; /** Where a key is minted. Printed in the missing-key sentence. */ export const KEY_SOURCE_URL = "https://aistudio.google.com/apikey"; export const OPENAI_KEY_SOURCE_URL = "https://platform.openai.com/api-keys"; /** One key variable per provider — `.env.local` holds both, under both names. */ export const KEY_VAR_BY_PROVIDER: Record = { gemini: KEY_VAR, openai: OPENAI_KEY_VAR, }; export const KEY_SOURCE_URL_BY_PROVIDER: Record = { gemini: KEY_SOURCE_URL, openai: OPENAI_KEY_SOURCE_URL, }; export const GEMINI_BASE_URL = "https://generativelanguage.googleapis.com"; export const OPENAI_BASE_URL = "https://api.openai.com"; export const DEFAULT_MODEL = "gemini-2.5-flash-image"; export const OPENAI_DEFAULT_MODEL = "gpt-image-1"; export const DEFAULT_MODEL_BY_PROVIDER: Record = { gemini: DEFAULT_MODEL, openai: OPENAI_DEFAULT_MODEL, }; /** `generationConfig.imageConfig.aspectRatio` — the values the API accepts. */ export const ASPECT_RATIOS = [ "1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9", ] as const; /** `generationConfig.imageConfig.imageSize` — the long edge, uppercase K. */ export const IMAGE_SIZES = ["1K", "2K", "4K"] as const; /** * OpenAI takes a pixel size, not a ratio, and the set is per model. Both lists * are the API's own; neither model accepts anything else. */ export const OPENAI_SIZES_BY_MODEL: Record = { "gpt-image-1": ["1024x1024", "1536x1024", "1024x1536"], "dall-e-3": ["1024x1024", "1792x1024", "1024x1792"], }; /** With no `--aspect`, OpenAI is asked for the square. Every model has it. */ export const OPENAI_DEFAULT_SIZE = "1024x1024"; /** * How far a requested shape may be stretched onto a size the model has, as a * ratio of ratios. 1.5 keeps 9:16 → 1024x1536 (1.19×) and turns away * 21:9 → 1536x1024 (1.56×), which would be a different picture. */ export const MAX_ASPECT_STRETCH = 1.5; /** Extension per returned mime type, so `--out foo.png` stays honest. */ const EXTENSION_BY_MIME: Record = { "image/png": ".png", "image/jpeg": ".jpg", "image/webp": ".webp", }; // ============================================================================ // Errors — each one names the thing that is wrong, never the key itself. // ============================================================================ /** Bad arguments, or a flag that no provider here has behind it. Exit 2. */ export class UsageError extends Error {} /** No key for the chosen provider anywhere. Exit 2 — an operator problem. */ export class MissingKeyError extends Error {} /** The API refused, or answered without an image. Exit 1. */ export class GenerationError extends Error {} /** The exit code for a thrown error. Pure, so the exit-2 rule is testable. */ export function exitCodeFor(err: unknown): number { if (err instanceof UsageError || err instanceof MissingKeyError) return 2; return 1; } /** What replaces a key that turns up in text that is about to be printed. */ export const REDACTED = "[redacted]"; /** * Never print a key. An API that echoes the credential it just refused (OpenAI * says "Incorrect API key provided: sk-…") would otherwise put it in a terminal * and a PR description. */ export function redact(text: string, apiKey: string): string { return apiKey ? text.split(apiKey).join(REDACTED) : text; } // ============================================================================ // Arguments // ============================================================================ export interface Args { provider: Provider; prompt: string; out: string; aspect?: string; size?: string; model: string; } /** * Flags of the edge-function era. They are kept as NAMES so an old invocation * gets a sentence instead of a differently-shaped image: a flag that quietly * stops applying is exactly the silent fallback the repo bans. */ const RETIRED_FLAGS: Record = { "--transparent": "Neither provider gets a transparent-background control here. Prompt for a flat colour ground and cut it out, or use scripts/gen-caps/gen_image.py, which speaks the OpenAI images/edits endpoint.", "--quality": "There is no quality tier. Use --size 1K|2K|4K on gemini, or --model (gemini-3-pro-image, dall-e-3) for a different model.", "--format": "The output type is the model's; the written file takes its extension from the returned mime type.", }; export function parseArgs(argv: string[]): Args { const positional: string[] = []; let out = ""; let aspect: string | undefined; let size: string | undefined; let model: string | undefined; let provider: Provider = DEFAULT_PROVIDER; const next = (i: number, flag: string): string => { const v = argv[i]; if (v === undefined || v.startsWith("--")) throw new UsageError(`${flag} needs a value`); return v; }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; const retired = RETIRED_FLAGS[a]; if (retired !== undefined) { throw new UsageError(`${a} is not a flag of gen:asset. ${retired}`); } switch (a) { case "--out": out = next(++i, "--out"); break; case "--aspect": aspect = next(++i, "--aspect"); break; case "--size": size = next(++i, "--size"); break; case "--model": model = next(++i, "--model"); break; case "--provider": { const p = next(++i, "--provider"); if (!(PROVIDERS as readonly string[]).includes(p)) { throw new UsageError(`--provider ${p} is not one of ${PROVIDERS.join(", ")}`); } provider = p as Provider; break; } default: if (a.startsWith("--")) throw new UsageError(`unknown flag: ${a}`); positional.push(a); } } const prompt = positional.join(" ").trim(); if (!prompt) throw new UsageError('missing prompt. Usage: pnpm gen:asset "" --out '); if (!out) throw new UsageError("missing --out "); if (aspect !== undefined && !(ASPECT_RATIOS as readonly string[]).includes(aspect)) { throw new UsageError(`--aspect ${aspect} is not one of ${ASPECT_RATIOS.join(", ")}`); } if (size !== undefined && !(IMAGE_SIZES as readonly string[]).includes(size)) { throw new UsageError(`--size ${size} is not one of ${IMAGE_SIZES.join(", ")} (the long edge, not pixels — use --aspect for shape)`); } const resolvedModel = model ?? DEFAULT_MODEL_BY_PROVIDER[provider]; if (provider === "openai") { if (size !== undefined) { throw new UsageError( `--size is Gemini's long-edge knob; OpenAI's sizes are fixed per model (${(OPENAI_SIZES_BY_MODEL[resolvedModel] ?? [OPENAI_DEFAULT_SIZE]).join(", ")}). Drop --size and use --aspect.`, ); } // Resolved here, and again when the body is built: an unmappable shape or // an unknown model must cost no key lookup and no request. openAiSizeFor(resolvedModel, aspect); } return { provider, prompt, out, aspect, size, model: resolvedModel }; } export const USAGE = `gen:asset — generate a dev UI asset with Gemini or OpenAI and write it into the repo. pnpm gen:asset "" --out [--provider

] [--aspect ] [--size ] [--model ] --out (required) destination, relative to the cwd or absolute --provider

${PROVIDERS.join(" | ")} (default ${DEFAULT_PROVIDER}) --aspect ${ASPECT_RATIOS.join(" | ")} — on openai this maps to the nearest size the model has --size ${IMAGE_SIZES.join(" | ")} (the long edge) — gemini only --model gemini: ${DEFAULT_MODEL} (default), gemini-3-pro-image openai: ${Object.keys(OPENAI_SIZES_BY_MODEL).join(", ")} (default ${OPENAI_DEFAULT_MODEL}) Keys: ${KEY_VAR} (gemini, ${KEY_SOURCE_URL}) and ${OPENAI_KEY_VAR} (openai, ${OPENAI_KEY_SOURCE_URL}), exported or in ${KEY_FILE} at the repo root.`; // ============================================================================ // The key // ============================================================================ /** * A `.env.local` reader — deliberately small. Handles `export ` prefixes, `#` * comments, and single/double quoted values. It is not dotenv and does not * want to be: the two provider keys are read out of it by name. */ export function parseEnvFile(text: string): Record { const out: Record = {}; for (const raw of text.split("\n")) { const line = raw.trim(); if (line === "" || line.startsWith("#")) continue; const eq = line.indexOf("="); if (eq <= 0) continue; const key = line.slice(0, eq).replace(/^export\s+/, "").trim(); if (!/^[A-Za-z_][A-Za-z0-9_]*$/.test(key)) continue; let value = line.slice(eq + 1).trim(); if ( (value.startsWith('"') && value.endsWith('"') && value.length >= 2) || (value.startsWith("'") && value.endsWith("'") && value.length >= 2) ) { value = value.slice(1, -1); } out[key] = value; } return out; } export interface KeySources { env: NodeJS.ProcessEnv; /** Repo root, so the `.env.local` path is injectable in tests. */ repoRoot: string; /** File contents, or null when the file is absent or unreadable. */ readText: (path: string) => string | null; } /** * The environment wins; `.env.local` is the standing local copy. One file, * both names — the provider decides which line is read. */ export function resolveApiKey(src: KeySources, provider: Provider = DEFAULT_PROVIDER): string { const keyVar = KEY_VAR_BY_PROVIDER[provider]; const fromEnv = src.env[keyVar]?.trim(); if (fromEnv) return fromEnv; const file = join(src.repoRoot, KEY_FILE); const text = src.readText(file); const fromFile = text === null ? undefined : parseEnvFile(text)[keyVar]?.trim(); if (fromFile) return fromFile; throw new MissingKeyError( `${keyVar} is not set — export it, or put \`${keyVar}=…\` in ${file} (gitignored); mint one at ${KEY_SOURCE_URL_BY_PROVIDER[provider]}.`, ); } // ============================================================================ // The shape — `--aspect` onto an OpenAI pixel size // ============================================================================ function ratioOf(spec: string, separator: string): number { const [a, b] = spec.split(separator); return Number(a) / Number(b); } function orientationOf(ratio: number): "portrait" | "square" | "landscape" { if (ratio > 1) return "landscape"; if (ratio < 1) return "portrait"; return "square"; } /** * The nearest size the model actually has, of the SAME orientation — a portrait * request never comes back landscape. Beyond `MAX_ASPECT_STRETCH` there is no * nearest worth the name, and the flag is refused rather than silently reshaped. */ export function openAiSizeFor(model: string, aspect: string | undefined): string { const sizes: readonly string[] | undefined = OPENAI_SIZES_BY_MODEL[model]; if (sizes === undefined) { throw new UsageError( `--model ${model} is not an OpenAI image model this tool knows; use ${Object.keys(OPENAI_SIZES_BY_MODEL).join(" or ")}.`, ); } if (aspect === undefined) return OPENAI_DEFAULT_SIZE; const want = ratioOf(aspect, ":"); const orientation = orientationOf(want); let best: { size: string; stretch: number } | undefined; for (const size of sizes) { const have = ratioOf(size, "x"); if (orientationOf(have) !== orientation) continue; const stretch = Math.max(want / have, have / want); if (best === undefined || stretch < best.stretch) best = { size, stretch }; } if (best === undefined || best.stretch > MAX_ASPECT_STRETCH) { throw new UsageError( `--aspect ${aspect} has no ${model} size near it — ${model} generates ${sizes.join(", ")}. Ask for a nearer shape, or --provider gemini, which takes ${aspect} itself.`, ); } return best.size; } // ============================================================================ // The request // ============================================================================ export interface ApiRequest { url: string; headers: Record; body: Record; } /** * Build the `generateContent` call. The key goes in `x-goog-api-key` and * NOWHERE else — the URL is logged by proxies and shows up in shell history. */ export function buildGeminiRequest(args: Args, apiKey: string, baseUrl: string = GEMINI_BASE_URL): ApiRequest { const imageConfig: Record = {}; if (args.aspect) imageConfig.aspectRatio = args.aspect; if (args.size) imageConfig.imageSize = args.size; const generationConfig: Record = { responseModalities: ["IMAGE"] }; if (Object.keys(imageConfig).length > 0) generationConfig.imageConfig = imageConfig; return { url: `${baseUrl.replace(/\/+$/, "")}/v1/models/${args.model}:generateContent`, headers: { "content-type": "application/json", "x-goog-api-key": apiKey }, body: { contents: [{ parts: [{ text: args.prompt }] }], generationConfig, }, }; } /** * Build the `images/generations` call. The key goes in `Authorization: Bearer` * and nowhere else. `gpt-image-1` always answers base64 and takes * `output_format`; `dall-e-3` defaults to a URL and must be asked for * `b64_json`, because this tool writes bytes and never fetches a second time. */ export function buildOpenAiRequest(args: Args, apiKey: string, baseUrl: string = OPENAI_BASE_URL): ApiRequest { const body: Record = { model: args.model, prompt: args.prompt, n: 1, size: openAiSizeFor(args.model, args.aspect), }; if (args.model === "dall-e-3") body.response_format = "b64_json"; else body.output_format = "png"; return { url: `${baseUrl.replace(/\/+$/, "")}/v1/images/generations`, headers: { "content-type": "application/json", authorization: `Bearer ${apiKey}` }, body, }; } /** The provider's own call. `baseUrl` is injectable so a test never leaves. */ export function buildRequest(args: Args, apiKey: string, baseUrl?: string): ApiRequest { return args.provider === "openai" ? buildOpenAiRequest(args, apiKey, baseUrl ?? OPENAI_BASE_URL) : buildGeminiRequest(args, apiKey, baseUrl ?? GEMINI_BASE_URL); } // ============================================================================ // The response // ============================================================================ export interface GeneratedImage { bytes: Buffer; mimeType: string; } function asRecord(v: unknown): Record | null { return v !== null && typeof v === "object" && !Array.isArray(v) ? (v as Record) : null; } /** The `{ error: { code, status, message } }` envelope, as a printable line. */ export function geminiErrorDetail(payload: unknown, status: number): string { const err = asRecord(asRecord(payload)?.error); if (!err) return `HTTP ${status}`; const name = typeof err.status === "string" ? err.status : String(err.code ?? status); const message = typeof err.message === "string" ? err.message : ""; return `HTTP ${status} ${name}${message ? `: ${message}` : ""}`; } /** OpenAI's `{ error: { message, type, code } }` — the message IS the sentence. */ export function openAiErrorDetail(payload: unknown, status: number): string { const err = asRecord(asRecord(payload)?.error); if (!err) return `HTTP ${status}`; const name = typeof err.type === "string" ? err.type : typeof err.code === "string" ? err.code : ""; const message = typeof err.message === "string" ? err.message : ""; return `HTTP ${status}${name ? ` ${name}` : ""}${message ? `: ${message}` : ""}`; } export const ERROR_DETAIL_BY_PROVIDER: Record string> = { gemini: geminiErrorDetail, openai: openAiErrorDetail, }; /** * Pull the image off the first candidate. A model that declines answers 200 * with a `blockReason`, a non-STOP `finishReason`, or a text part explaining * itself — every one of those is surfaced rather than written to disk as a * zero-byte file. */ export function extractGeminiImage(payload: unknown): GeneratedImage { const root = asRecord(payload); const feedback = asRecord(root?.promptFeedback); if (typeof feedback?.blockReason === "string") { throw new GenerationError(`the prompt was blocked (${feedback.blockReason})`); } const candidates = Array.isArray(root?.candidates) ? root.candidates : []; const candidate = asRecord(candidates[0]); if (!candidate) throw new GenerationError("the response carried no candidates"); const parts = Array.isArray(asRecord(candidate.content)?.parts) ? (asRecord(candidate.content)!.parts as unknown[]) : []; const texts: string[] = []; for (const raw of parts) { const part = asRecord(raw); if (!part) continue; // Both spellings: the REST wire is snake_case, the SDKs camelCase. const inline = asRecord(part.inlineData) ?? asRecord(part.inline_data); const data = inline && (typeof inline.data === "string" ? inline.data : undefined); if (data) { const mimeType = (typeof inline?.mimeType === "string" && inline.mimeType) || (typeof inline?.mime_type === "string" && inline.mime_type) || "image/png"; return { bytes: Buffer.from(data, "base64"), mimeType }; } if (typeof part.text === "string" && part.text.trim()) texts.push(part.text.trim()); } const finish = typeof candidate.finishReason === "string" ? candidate.finishReason : ""; const why = [finish && finish !== "STOP" ? `finishReason ${finish}` : "", ...texts].filter(Boolean).join(" — "); throw new GenerationError(`the model returned no image${why ? ` — ${why}` : ""}`); } /** * `data[0].b64_json`. A `url` instead of bytes is the one near-miss worth * naming: `dall-e-3` answers that way unless asked for base64, and the link * expires, so it is a refusal rather than a second request. */ export function extractOpenAiImage(payload: unknown): GeneratedImage { const data = Array.isArray(asRecord(payload)?.data) ? (asRecord(payload)!.data as unknown[]) : []; const first = asRecord(data[0]); if (!first) throw new GenerationError("the response carried no data"); const b64 = typeof first.b64_json === "string" ? first.b64_json : ""; if (b64) return { bytes: Buffer.from(b64, "base64"), mimeType: "image/png" }; const why = typeof first.url === "string" ? " — it answered a url, not bytes" : ""; throw new GenerationError(`the model returned no image${why}`); } export const EXTRACT_BY_PROVIDER: Record GeneratedImage> = { gemini: extractGeminiImage, openai: extractOpenAiImage, }; // ============================================================================ // The call // ============================================================================ export interface GenerateOptions { fetchImpl?: typeof fetch; baseUrl?: string; timeoutMs?: number; } /** POST, then read. Nothing here ever prints or re-throws the key. */ export async function generateImage( args: Args, apiKey: string, opts: GenerateOptions = {}, ): Promise { const req = buildRequest(args, apiKey, opts.baseUrl); const fetchImpl = opts.fetchImpl ?? fetch; const timeoutMs = opts.timeoutMs ?? Number(process.env.COTTON_IMAGE_TIMEOUT_MS ?? 180_000); // Every message this function throws goes through here, so a key echoed back // by the API cannot reach a terminal or a PR description. const fail = (why: string): GenerationError => new GenerationError(redact(`${args.model} — ${why}`, apiKey)); const controller = new AbortController(); const timer = setTimeout(() => controller.abort(), timeoutMs); let text: string; let status: number; try { const res = await fetchImpl(req.url, { method: "POST", headers: req.headers, body: JSON.stringify(req.body), signal: controller.signal, }); status = res.status; text = await res.text(); } catch (err) { const why = (err as Error).name === "AbortError" ? `timed out after ${timeoutMs}ms` : (err as Error).message; throw fail(why); } finally { clearTimeout(timer); } let payload: unknown; try { payload = JSON.parse(text); } catch { throw fail(`HTTP ${status} with a non-JSON body`); } if (status < 200 || status >= 300) { throw fail(ERROR_DETAIL_BY_PROVIDER[args.provider](payload, status)); } return EXTRACT_BY_PROVIDER[args.provider](payload); } // ============================================================================ // The file // ============================================================================ /** * Where the bytes land. The requested path wins; its extension is corrected * only when the model answered with a different type than the name promises, * so nothing writes a JPEG into a `.png` a designer will later trust. */ export function resolveOutPath(out: string, mimeType: string, cwd: string): string { const abs = isAbsolute(out) ? out : resolve(cwd, out); const want = EXTENSION_BY_MIME[mimeType]; if (!want || abs.toLowerCase().endsWith(want) || (want === ".jpg" && abs.toLowerCase().endsWith(".jpeg"))) { return abs; } return `${abs.replace(/\.[A-Za-z0-9]+$/, "")}${want}`; } /** mkdir -p, then write. The one post-processing step this tool has ever had. */ export function writeAsset(path: string, bytes: Buffer): void { mkdirSync(dirname(path), { recursive: true }); writeFileSync(path, bytes); } // ============================================================================ // main // ============================================================================ function readTextOrNull(path: string): string | null { try { return readFileSync(path, "utf8"); } catch { return null; } } export async function main(argv: string[] = process.argv.slice(2)): Promise { const args = parseArgs(argv); const apiKey = resolveApiKey({ env: process.env, repoRoot: REPO_ROOT, readText: readTextOrNull }, args.provider); console.error(`gen-asset: generating with ${args.provider}/${args.model}…`); const image = await generateImage(args, apiKey); const outPath = resolveOutPath(args.out, image.mimeType, process.cwd()); writeAsset(outPath, image.bytes); console.error(`gen-asset: wrote ${outPath} (${image.mimeType}, ${image.bytes.length} bytes)`); } // Only run the IO main() when invoked directly, not when imported by a test. const invokedDirectly = process.argv[1] !== undefined && /gen-asset\.ts$/.test(process.argv[1]); if (invokedDirectly) { main().catch((err: unknown) => { const code = exitCodeFor(err); console.error(`gen-asset: ${(err as Error).message}`); if (err instanceof UsageError) console.error(`\n${USAGE}`); process.exit(code); }); }