#!/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/<model>: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 "<prompt>" --out apps/loom/Sources/CottonPaper/Media.xcassets/emptyInbox.imageset/emptyInbox.png * pnpm gen:asset "<prompt>" --out path.png --aspect 16:9 * pnpm gen:asset "<prompt>" --out path.png --size 2K --model gemini-3-pro-image * pnpm gen:asset "<prompt>" --out path.png --provider openai --aspect 1:1 * * Flags: * --out <path> (required) destination, relative to the cwd or absolute * --provider <p> gemini (default) | openai * --aspect <a> 1:1 (model default) | 2:3 | 3:2 | 3:4 | 4:3 | 4:5 | 5:4 | 9:16 | 16:9 | 21:9 * --size <s> 1K (model default) | 2K | 4K — the long edge, not pixels. Gemini only. * --model <m> 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));exportconst REPO_ROOT = resolve(HERE, "..");/** The image providers this tool speaks to. Gemini is the default. */exportconst PROVIDERS = ["gemini", "openai"] asconst;exporttypeProvider = (typeof PROVIDERS)[number];exportconst DEFAULT_PROVIDER: Provider = "gemini";/** The variable that authenticates a Gemini call. */exportconst KEY_VAR = "COTTON_IMAGE_API_KEY";/** The variable that authenticates an OpenAI call — the owner's standing key. */exportconst OPENAI_KEY_VAR = "OPENAI_API_KEY";/** Where the key lives when it is not exported. Gitignored; never committed. */exportconst KEY_FILE = ".env.local";/** Where a key is minted. Printed in the missing-key sentence. */exportconst KEY_SOURCE_URL = "https://aistudio.google.com/apikey";exportconst OPENAI_KEY_SOURCE_URL = "https://platform.openai.com/api-keys";/** One key variable per provider — `.env.local` holds both, under both names. */exportconst KEY_VAR_BY_PROVIDER: Record<Provider, string> = { gemini: KEY_VAR, openai: OPENAI_KEY_VAR,};exportconst KEY_SOURCE_URL_BY_PROVIDER: Record<Provider, string> = { gemini: KEY_SOURCE_URL, openai: OPENAI_KEY_SOURCE_URL,};exportconst GEMINI_BASE_URL = "https://generativelanguage.googleapis.com";exportconst OPENAI_BASE_URL = "https://api.openai.com";exportconst DEFAULT_MODEL = "gemini-2.5-flash-image";exportconst OPENAI_DEFAULT_MODEL = "gpt-image-1";exportconst DEFAULT_MODEL_BY_PROVIDER: Record<Provider, string> = { gemini: DEFAULT_MODEL, openai: OPENAI_DEFAULT_MODEL,};/** `generationConfig.imageConfig.aspectRatio` — the values the API accepts. */exportconst ASPECT_RATIOS = ["1:1", "2:3", "3:2", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9",] asconst;/** `generationConfig.imageConfig.imageSize` — the long edge, uppercase K. */exportconst IMAGE_SIZES = ["1K", "2K", "4K"] asconst;/** * 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. */exportconst OPENAI_SIZES_BY_MODEL: Record<string, readonly string[]> = {"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. */exportconst 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. */exportconst MAX_ASPECT_STRETCH = 1.5;/** Extension per returned mime type, so `--out foo.png` stays honest. */const EXTENSION_BY_MIME: Record<string, string> = {"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. */exportclassUsageErrorextendsError {}/** No key for the chosen provider anywhere. Exit 2 — an operator problem. */exportclassMissingKeyErrorextendsError {}/** The API refused, or answered without an image. Exit 1. */exportclassGenerationErrorextendsError {}/** The exit code for a thrown error. Pure, so the exit-2 rule is testable. */exportfunction exitCodeFor(err: unknown): number {if (err instanceofUsageError || err instanceofMissingKeyError) return2;return1;}/** What replaces a key that turns up in text that is about to be printed. */exportconst 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. */exportfunction redact(text: string, apiKey: string): string {return apiKey ? text.split(apiKey).join(REDACTED) : text;}// ============================================================================// Arguments// ============================================================================exportinterfaceArgs { 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<string, string> = {"--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.",};exportfunction 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("--")) thrownewUsageError(`${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) {thrownewUsageError(`${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 asreadonly string[]).includes(p)) {thrownewUsageError(`--provider ${p} is not one of ${PROVIDERS.join(", ")}`); } provider = p asProvider;break; }default:if (a.startsWith("--")) thrownewUsageError(`unknown flag: ${a}`); positional.push(a); } }const prompt = positional.join(" ").trim();if (!prompt) thrownewUsageError('missing prompt. Usage: pnpm gen:asset "<prompt>" --out <path>');if (!out) thrownewUsageError("missing --out <path>");if (aspect !== undefined && !(ASPECT_RATIOS asreadonly string[]).includes(aspect)) {thrownewUsageError(`--aspect ${aspect} is not one of ${ASPECT_RATIOS.join(", ")}`); }if (size !== undefined && !(IMAGE_SIZES asreadonly string[]).includes(size)) {thrownewUsageError(`--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) {thrownewUsageError(`--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 };}exportconst USAGE = `gen:asset — generate a dev UI asset with Gemini or OpenAI and write it into the repo. pnpm gen:asset "<prompt>" --out <path> [--provider <p>] [--aspect <a>] [--size <s>] [--model <m>] --out <path> (required) destination, relative to the cwd or absolute --provider <p> ${PROVIDERS.join(" | ")} (default ${DEFAULT_PROVIDER}) --aspect <a> ${ASPECT_RATIOS.join(" | ")} — on openai this maps to the nearest size the model has --size <s> ${IMAGE_SIZES.join(" | ")} (the long edge) — gemini only --model <m> 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. */exportfunction parseEnvFile(text: string): Record<string, string> {const out: Record<string, string> = {};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;}exportinterfaceKeySources { 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. */exportfunction 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;thrownewMissingKeyError(`${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);returnNumber(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. */exportfunction openAiSizeFor(model: string, aspect: string | undefined): string {const sizes: readonly string[] | undefined = OPENAI_SIZES_BY_MODEL[model];if (sizes === undefined) {thrownewUsageError(`--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) {thrownewUsageError(`--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// ============================================================================exportinterfaceApiRequest { url: string; headers: Record<string, string>; body: Record<string, unknown>;}/** * 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. */exportfunction buildGeminiRequest(args: Args, apiKey: string, baseUrl: string = GEMINI_BASE_URL): ApiRequest {const imageConfig: Record<string, string> = {};if (args.aspect) imageConfig.aspectRatio = args.aspect;if (args.size) imageConfig.imageSize = args.size;const generationConfig: Record<string, unknown> = { 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. */exportfunction buildOpenAiRequest(args: Args, apiKey: string, baseUrl: string = OPENAI_BASE_URL): ApiRequest {const body: Record<string, unknown> = { 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. */exportfunction 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// ============================================================================exportinterfaceGeneratedImage { bytes: Buffer; mimeType: string;}function asRecord(v: unknown): Record<string, unknown> | null {return v !== null && typeof v === "object" && !Array.isArray(v) ? (v asRecord<string, unknown>) : null;}/** The `{ error: { code, status, message } }` envelope, as a printable line. */exportfunction 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. */exportfunction 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}` : ""}`;}exportconst ERROR_DETAIL_BY_PROVIDER: Record<Provider, (payload: unknown, status: number) => 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. */exportfunction extractGeminiImage(payload: unknown): GeneratedImage {const root = asRecord(payload);const feedback = asRecord(root?.promptFeedback);if (typeof feedback?.blockReason === "string") {thrownewGenerationError(`the prompt was blocked (${feedback.blockReason})`); }const candidates = Array.isArray(root?.candidates) ? root.candidates : [];const candidate = asRecord(candidates[0]);if (!candidate) thrownewGenerationError("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(" — ");thrownewGenerationError(`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. */exportfunction extractOpenAiImage(payload: unknown): GeneratedImage {const data = Array.isArray(asRecord(payload)?.data) ? (asRecord(payload)!.data as unknown[]) : [];const first = asRecord(data[0]);if (!first) thrownewGenerationError("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" : "";thrownewGenerationError(`the model returned no image${why}`);}exportconst EXTRACT_BY_PROVIDER: Record<Provider, (payload: unknown) => GeneratedImage> = { gemini: extractGeminiImage, openai: extractOpenAiImage,};// ============================================================================// The call// ============================================================================exportinterfaceGenerateOptions { fetchImpl?: typeof fetch; baseUrl?: string; timeoutMs?: number;}/** POST, then read. Nothing here ever prints or re-throws the key. */exportasyncfunction generateImage( args: Args, apiKey: string, opts: GenerateOptions = {},): Promise<GeneratedImage> {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 => newGenerationError(redact(`${args.model} — ${why}`, apiKey));const controller = newAbortController();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 asError).name === "AbortError" ? `timed out after ${timeoutMs}ms` : (err asError).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. */exportfunction 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. */exportfunction 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 {returnnull; }}exportasyncfunction main(argv: string[] = process.argv.slice(2)): Promise<void> {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 instanceofUsageError) console.error(`\n${USAGE}`); process.exit(code); });}