diff --git a/README.md b/README.md index f4e02b55..928a1f8f 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ Codemode is a Bun workspace. It was called runline through 0.45; see [Migrate fr | [`packages/codemode-duckdb`](packages/codemode-duckdb) | The `duckdb` plugin as a package, published as `@shiftlabs/codemode-duckdb` | | [`packages/codemode-node`](packages/codemode-node) | The `node` plugin as a package, published as `@shiftlabs/codemode-node` | | [`packages/codemode-websearch`](packages/codemode-websearch) | The `websearch` plugin as a package, published as `@shiftlabs/codemode-websearch` | +| [`packages/codemode-imagegen`](packages/codemode-imagegen) | The `imagegen` plugin as a package, published as `@shiftlabs/codemode-imagegen` | | [`packages/package-tests`](packages/package-tests) | What the tests of those packages share. Not published | | [`packages/runline`](packages/runline) | The `runline` package on npm, which forwards to codemode until 0.48.0 | diff --git a/bun.lock b/bun.lock index 5a6d3fc1..38c06156 100644 --- a/bun.lock +++ b/bun.lock @@ -85,6 +85,21 @@ "typebox": "*", }, }, + "packages/codemode-imagegen": { + "name": "@shiftlabs/codemode-imagegen", + "version": "0.1.0", + "devDependencies": { + "@shiftlabs/codemode": "workspace:*", + "@types/bun": "^1.2.17", + "@types/node": "^25.5.0", + "typebox": "^1.1.35", + "typescript": "^5.8.0", + }, + "peerDependencies": { + "@shiftlabs/codemode": ">0.46.0", + "typebox": "*", + }, + }, "packages/codemode-node": { "name": "@shiftlabs/codemode-node", "version": "0.1.0", @@ -287,6 +302,8 @@ "@shiftlabs/codemode-duckdb": ["@shiftlabs/codemode-duckdb@workspace:packages/codemode-duckdb"], + "@shiftlabs/codemode-imagegen": ["@shiftlabs/codemode-imagegen@workspace:packages/codemode-imagegen"], + "@shiftlabs/codemode-node": ["@shiftlabs/codemode-node@workspace:packages/codemode-node"], "@shiftlabs/codemode-powershell": ["@shiftlabs/codemode-powershell@workspace:packages/codemode-powershell"], diff --git a/docs/bundled-plugins.md b/docs/bundled-plugins.md index 832f11b6..596ae6ab 100644 --- a/docs/bundled-plugins.md +++ b/docs/bundled-plugins.md @@ -2,7 +2,7 @@ Codemode ships with plugins for SaaS, DevOps, productivity, and image-generation APIs. They are part of the `codemode` package and need no installation. -Host capabilities are separate packages to install: [`codemode-node`](../packages/codemode-node/README.md) for Node.js scripts, [`codemode-bash`](../packages/codemode-bash/README.md) and [`codemode-powershell`](../packages/codemode-powershell/README.md) for commands, and [`codemode-duckdb`](../packages/codemode-duckdb/README.md) for SQL. Web search across providers is the [`codemode-websearch`](../packages/codemode-websearch/README.md) package. +Host capabilities are separate packages to install: [`codemode-node`](../packages/codemode-node/README.md) for Node.js scripts, [`codemode-bash`](../packages/codemode-bash/README.md) and [`codemode-powershell`](../packages/codemode-powershell/README.md) for commands, and [`codemode-duckdb`](../packages/codemode-duckdb/README.md) for SQL. Web search across providers is the [`codemode-websearch`](../packages/codemode-websearch/README.md) package, and image generation across providers is [`codemode-imagegen`](../packages/codemode-imagegen/README.md). A bundled plugin becomes available to `codemode exec` once it has a connection. The last column lists each required connection field and, in parentheses, the environment variable that can supply it: diff --git a/packages/codemode-imagegen/README.md b/packages/codemode-imagegen/README.md new file mode 100644 index 00000000..71d1eec0 --- /dev/null +++ b/packages/codemode-imagegen/README.md @@ -0,0 +1,183 @@ +# codemode-imagegen + +A [codemode](../../README.md) package with one plugin, `imagegen`, that makes and edits images through the image provider you have a key for. + +Code calls `imagegen.create` and `imagegen.edit` the same way whichever provider answers, and gets files in one shape. Code never names a provider: the connection chooses it. Code can name a model, from the list `imagegen.models` returns. + +## Install + +Install the package and set the key of one provider: + +```bash +codemode install npm:@shiftlabs/codemode-imagegen +export OPENAI_API_KEY=... +``` + +It needs a codemode newer than 0.46.0. + +## Make an image + +`imagegen.create` writes each image to a file and returns where it is: + +```bash +codemode exec 'return await imagegen.create({ prompt: "a red bicycle on snow", width: 1536, height: 1024 })' +``` + +```json +{ + "provider": "openai", + "model": "gpt-image-2.6-flare", + "images": [ + { + "path": "/tmp/imagegen-openai-3f9c2a1b7d4e5f60.png", + "mimeType": "image/png", + "byteLength": 1482113, + "width": 1536, + "height": 1024 + } + ] +} +``` + +| Input | Form | Meaning | +|---|---|---| +| `prompt` | Text | What the image shows | +| `model` | An id from `imagegen.models` | The model to use. The default is the connection's | +| `width`, `height` | Whole numbers from 256 to 4096, set together | The size in pixels. Without them, the model's own size | +| `numImages` | A whole number from 1 to 4 | How many images to make. The default is 1 | + +The files are in the host's [output directory](../../docs/sdk.md#limit-a-runs-result), or the system's temporary directory. Codemode never deletes them. + +## Edit an image + +`imagegen.edit` takes the same inputs and the paths of the images to work from: + +```js +await imagegen.edit({ + prompt: "make it night, with the street lamps lit", + images: ["/data/street.png"], +}); +``` + +`images` is 1 to 8 paths of PNG, JPEG, or WebP files. What a file is, its bytes say: one that is none of these is refused, whatever its name. Some models take one image, and a call that passes more is refused. + +## Choose a model + +`imagegen.models` lists the models the connection's provider has, what each can do, and the model each action uses when a call names none: + +```js +const { models, createModel, editModel } = await imagegen.models({ query: "vector" }); +// models: [{ id: "recraftv4_1_vector", create: true, edit: true }, ...] +await imagegen.create({ prompt: "a rocket logo", model: models[0].id }); +``` + +| Input | Meaning | +|---|---| +| `query` | Words to find models by | +| `limit` | The most models to return, from 1 to 200. The default is 50 | + +A call that names a model is checked against the provider's models before anything is made. A model the provider does not have, or one that cannot do what the action does, is refused. + +The list is the models this package knows of with the provider's own list laid over them. Codemode asks the provider once and keeps the answer for ten minutes. fal and Replicate host thousands of models: without `query` the list is their best-known ones, and with `query` it is what their search finds. Any image model of theirs can be named, listed or not. + +## Set a size + +`width` and `height` are pixels, for every provider. A model that takes other sizes makes the nearest one it can, and each image in the result says the size it came out at: + +| Provider | What a size becomes | +|---|---| +| `openai` | The same pixels, with sides rounded to 16 and the longer side at most three times the shorter, for `gpt-image-2` and later. The nearest of three sizes for the `gpt-image-1` line | +| `google` | The nearest aspect ratio | +| `xai` | The nearest aspect ratio, and a resolution of 1k, 1.5k, or 2k | +| `recraft` | The nearest aspect ratio | +| `together` | The same pixels, with sides rounded to 16 and kept from 256 to 1920 | +| `fal`, `replicate` | What the model's own schema takes: pixels, or the nearest of its sizes or aspect ratios | + +A model with no size input refuses a call that sets one. + +## Choose a provider + +The connection chooses the provider, and no action has an input for it. A request goes to the connection's `provider` when it names one, else to the first provider in this table that has a key: + +| Provider | Key | Lists its models | Models | +|---|---|---|---| +| `openai` | `OPENAI_API_KEY` | Yes | GPT Image | +| `google` | `GOOGLE_API_KEY` | Yes | Gemini image models (Nano Banana) | +| `xai` | `XAI_API_KEY` | Yes | Grok Imagine | +| `recraft` | `RECRAFT_API_KEY` | No | Recraft raster and vector models | +| `together` | `TOGETHER_API_KEY` | Yes | FLUX and others it hosts | +| `fal` | `FAL_KEY` | Yes | Any image model fal hosts | +| `replicate` | `REPLICATE_API_TOKEN` | Yes | Any image model Replicate hosts | + +The result's `provider` and `model` say which answered. + +## Configure the connection + +Add a connection to keep keys in codemode, or to choose the provider and its models. Every field is optional: + +```bash +codemode connection add imagegen --plugin imagegen --set provider=google --set createModel=gemini-3-pro-image +``` + +| Field | Meaning | +|---|---| +| `provider` | The provider every request goes to. The default is the first with a key | +| `createModel`, `editModel` | The model each action uses when a call names none. The default is the provider's | +| `ApiKey` | The provider's key, such as `openaiApiKey`. The default is its environment variable | + +Each key is declared with the addresses that may receive it. A request to one provider sends no other provider's key, and an image a provider hands over as a link is fetched without any key. + +## Add a provider + +A host that embeds codemode builds the plugin from its own list of providers. A provider is its key's place in a request, the addresses that may receive the key, the models it has, and a function that makes the images of one request: + +```typescript +import { Codemode } from "@shiftlabs/codemode"; +import { type ImageProvider, imagegen, PROVIDERS } from "@shiftlabs/codemode-imagegen"; + +const acme: ImageProvider = { + name: "acme", + env: "ACME_IMAGE_KEY", + key: { header: "X-Acme-Key" }, + targets: { acme: { baseUrl: "https://images.acme.example/", methods: ["POST"] } }, + defaults: { create: "acme-1" }, + models: [{ id: "acme-1", create: true, edit: false }], + generate: async (api, { prompt, model, numImages, size }) => { + const { images } = await api.request<{ images: string[] }>({ + path: "make", + method: "POST", + json: { prompt, model: model.id, count: numImages, ...size }, + }); + return images.map((base64) => ({ base64 })); + }, +}; + +const codemode = Codemode.create({ plugins: [imagegen([acme, ...PROVIDERS])] }); +``` + +The list's order is the order a provider is chosen in. A provider that lists its models over its API adds `listModels`. The package is TypeScript source, so the host imports it with a runtime that runs TypeScript, such as Bun. + +## Handle failures + +| Outcome | Result | +|---|---| +| No provider has a key | The call rejects and names the environment variables | +| A file in `images` is not a PNG, JPEG, or WebP image | The call rejects before anything is made | +| The provider has no such model, or the model cannot do what the action does | The call rejects and points to `imagegen.models` | +| The model has no input for the size, the count, or the images a call sets | The call rejects and says what to leave out | +| The provider refuses the request | The call rejects with `imagegen.: request failed (HTTP )` | +| The model answers no image | The call rejects. The provider may have refused the prompt | +| A queued request on fal or Replicate runs past five minutes | The call rejects and names the request, which is not cancelled | + +A provider's error text is not included in the message, because it can repeat the key it was sent. + +## Understand the limits + +- `create` and `edit` are labelled `write`: each call is billed by the provider and writes files. +- A provider whose models could not be listed judges a model id itself. +- Google's models answer one image a request, so `numImages` is that many requests. +- Recraft keeps the size of an image it edits, and edits one image. +- An image is fetched from fal's and Replicate's own file hosts only. +- On Replicate, an image to edit is uploaded as a file first, which Replicate keeps until it expires. On fal it is sent inside the request, which fal recommends for small files only. +- A request to a provider is not ended when the run ends. +- The bundled `openai`, `googleImage`, `xai`, `recraft`, `together`, `fal`, and `replicate` plugins are separate from this package, each with its own connection. diff --git a/packages/codemode-imagegen/package.json b/packages/codemode-imagegen/package.json new file mode 100644 index 00000000..02cd0e58 --- /dev/null +++ b/packages/codemode-imagegen/package.json @@ -0,0 +1,51 @@ +{ + "name": "@shiftlabs/codemode-imagegen", + "version": "0.1.0", + "description": "Make and edit images from codemode through one set of actions, whichever image provider you have a key for", + "type": "module", + "keywords": [ + "codemode-plugin", + "image-generation", + "images", + "openai", + "gemini", + "flux", + "fal", + "replicate" + ], + "codemode": { + "plugins": [ + "./src/index.ts" + ] + }, + "files": [ + "src", + "README.md" + ], + "scripts": { + "test": "bun test tests", + "typecheck": "tsc --noEmit -p ." + }, + "repository": { + "type": "git", + "url": "git+https://github.com/shift-labs-ai/codemode.git", + "directory": "packages/codemode-imagegen" + }, + "homepage": "https://github.com/shift-labs-ai/codemode/tree/main/packages/codemode-imagegen#readme", + "bugs": { + "url": "https://github.com/shift-labs-ai/codemode/issues" + }, + "license": "MIT", + "peerDependencies": { + "@shiftlabs/codemode": ">0.46.0", + "typebox": "*" + }, + "devDependencies": { + "@shiftlabs/codemode": "workspace:*", + "@types/bun": "^1.2.17", + "@types/node": "^25.5.0", + "typebox": "^1.1.35", + "typescript": "^5.8.0" + }, + "exports": "./src/index.ts" +} diff --git a/packages/codemode-imagegen/src/image.ts b/packages/codemode-imagegen/src/image.ts new file mode 100644 index 00000000..e677068d --- /dev/null +++ b/packages/codemode-imagegen/src/image.ts @@ -0,0 +1,105 @@ +/** + * What an image is, read from its first bytes: its type, and its size in + * pixels where the format states one. And the two forms an API takes an + * image's bytes in. + */ + +/** An image's bytes in base64, for an API that takes them in JSON. */ +export function base64Of(image: { bytes: Uint8Array }): string { + return Buffer.from(image.bytes).toString("base64"); +} + +/** An image as a `data:` URL, for an API that takes a link or one of these. */ +export function dataUrlOf(image: { + bytes: Uint8Array; + mimeType: string; +}): string { + return `data:${image.mimeType};base64,${base64Of(image)}`; +} + +export interface ImageFacts { + mimeType: string; + width?: number; + height?: number; +} + +/** The file extension of each type an image provider answers with. */ +export const EXTENSIONS: Readonly> = { + "image/png": ".png", + "image/jpeg": ".jpg", + "image/webp": ".webp", + "image/gif": ".gif", + "image/svg+xml": ".svg", +}; + +function ascii(bytes: Uint8Array, start: number, length: number): string { + return String.fromCharCode(...bytes.subarray(start, start + length)); +} + +function jpegSize( + bytes: Uint8Array, +): { width: number; height: number } | undefined { + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + let at = 2; + while (at + 9 < bytes.length && bytes[at] === 0xff) { + const marker = bytes[at + 1]; + // A start-of-frame segment holds the size; C4, C8 and CC are tables, not frames. + if ( + marker >= 0xc0 && + marker <= 0xcf && + ![0xc4, 0xc8, 0xcc].includes(marker) + ) + return { height: view.getUint16(at + 5), width: view.getUint16(at + 7) }; + at += 2 + view.getUint16(at + 2); + } + return undefined; +} + +function webpSize( + bytes: Uint8Array, +): { width: number; height: number } | undefined { + if (bytes.length < 30) return undefined; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + const chunk = ascii(bytes, 12, 4); + if (chunk === "VP8X") { + const u24 = (at: number) => + view.getUint16(at, true) | (bytes[at + 2] << 16); + return { width: 1 + u24(24), height: 1 + u24(27) }; + } + if (chunk === "VP8L") { + const bits = view.getUint32(21, true); + return { width: 1 + (bits & 0x3fff), height: 1 + ((bits >>> 14) & 0x3fff) }; + } + if (chunk === "VP8 ") + return { + width: view.getUint16(26, true) & 0x3fff, + height: view.getUint16(28, true) & 0x3fff, + }; + return undefined; +} + +/** The type and size of an image, or nothing when the bytes are no image this package writes. */ +export function imageFacts(bytes: Uint8Array): ImageFacts | undefined { + if (bytes.length < 12) return undefined; + const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength); + if (ascii(bytes, 1, 3) === "PNG" && bytes.length >= 24) + return { + mimeType: "image/png", + width: view.getUint32(16), + height: view.getUint32(20), + }; + if (bytes[0] === 0xff && bytes[1] === 0xd8) + return { mimeType: "image/jpeg", ...jpegSize(bytes) }; + if (ascii(bytes, 0, 4) === "RIFF" && ascii(bytes, 8, 4) === "WEBP") + return { mimeType: "image/webp", ...webpSize(bytes) }; + if (ascii(bytes, 0, 3) === "GIF") + return { + mimeType: "image/gif", + width: view.getUint16(6, true), + height: view.getUint16(8, true), + }; + const start = new TextDecoder().decode(bytes.subarray(0, 1024)).trimStart(); + if (start.startsWith("<") && start.includes(" a file in the host's output directory + * + * A connection holds a key per provider. Each key is declared with the + * addresses that may receive it, so a request to one provider sends no other + * provider's key. Code never names a provider. + */ + +import { basename } from "node:path"; +import { setTimeout as sleep } from "node:timers/promises"; +import { + type ActionContext, + type CodemodePluginAPI, + type CredentialDeclaration, + type CredentialTarget, + credentialJson, + downloadResource, + type PluginFunction, + readLocalFile, + staticCredential, + writeOutputFile, +} from "@shiftlabs/codemode"; +import { packageVersion } from "@shiftlabs/codemode/utils/cli"; +import * as t from "typebox"; +import { EXTENSIONS, imageFacts } from "./image.js"; +import { PROVIDERS } from "./providers/index.js"; +import type { + ImageModel, + ImageProvider, + ProducedImage, + ProviderApi, + SourceImage, +} from "./types.js"; + +export * from "./providers/index.js"; +export type { Size } from "./size.js"; +export * from "./types.js"; + +const NAME = "imagegen"; +const MAX_IMAGES = 4; +const MAX_SOURCES = 8; +const MIN_SIDE = 256; +const MAX_SIDE = 4096; +/** Larger than any provider takes inline. */ +const MAX_SOURCE_BYTES = 50 * 1024 * 1024; +const MAX_LISTED = 200; +const DEFAULT_LISTED = 50; +/** A provider may take minutes to make an image. A host caps this at its own ceiling. */ +const TIMEOUT_MS = 5 * 60_000; +/** How long a provider's list of models is kept before it is asked for again. */ +const MODELS_TTL_MS = 10 * 60_000; + +/** What `create` and `edit` do, by the name of the action. */ +type Kind = "create" | "edit"; + +/** The connection field that holds a provider's key. */ +function keyField(provider: ImageProvider): string { + return `${provider.name}ApiKey`; +} + +/** Whether the connection holds a key for the provider. */ +function hasKey( + provider: ImageProvider, + config: Readonly>, +): boolean { + return Boolean(config[keyField(provider)]); +} + +/** + * One credential for every provider: a part per provider, each optional and + * each placed only on that provider's targets, so a connection holds the + * keys it has and a key is sent to its own provider alone. + */ +function credentialOf(providers: ImageProvider[]): CredentialDeclaration { + const names = providers.map((provider) => provider.name); + return staticCredential({ + id: "codemodeImagegen", + auth: { + kind: "static", + parts: names, + optionalParts: names, + placements: providers.map(({ name, key, targets }) => + "query" in key + ? { + in: "query", + part: name, + name: key.query, + targets: Object.keys(targets), + } + : { + in: "header", + part: name, + name: key.header, + ...(key.prefix === undefined ? {} : { prefix: key.prefix }), + targets: Object.keys(targets), + }, + ), + }, + local: Object.fromEntries( + providers.map((provider) => [provider.name, keyField(provider)]), + ), + targets: Object.fromEntries( + providers.flatMap((provider) => + Object.entries(provider.targets).map( + ([name, target]): [string, CredentialTarget] => [ + name, + { ...target, timeoutMs: TIMEOUT_MS }, + ], + ), + ), + ), + }); +} + +/** + * The provider a request goes to. The connection decides, never the call: + * its `provider` when it names one, else the first provider it has a key + * for. A host that signs requests keeps the keys, so only a connection that + * signs for itself (`signsItself`) is asked to hold the key of the provider + * it names. + */ +function chosen( + providers: ImageProvider[], + config: Readonly>, + signsItself: boolean, +): ImageProvider { + const name = config.provider; + if (name === undefined) { + const first = providers.find((candidate) => hasKey(candidate, config)); + if (first) return first; + throw new Error( + `${NAME}: no image provider has a key. Set one of ${providers.map((candidate) => candidate.env).join(", ")}, or the connection's "provider" when the host keeps the keys.`, + ); + } + const provider = providers.find((candidate) => candidate.name === name); + if (!provider) + throw new Error( + `${NAME}: the connection names the provider ${JSON.stringify(name)}. The providers are ${providers.map((candidate) => candidate.name).join(", ")}.`, + ); + if (signsItself && !hasKey(provider, config)) + throw new Error( + `${NAME}: no key for ${provider.name}, the connection's provider. Set ${provider.env}.`, + ); + return provider; +} + +/** The model an action uses when the call names none: the connection's, else the provider's. */ +function defaultModel( + provider: ImageProvider, + config: Readonly>, + kind: Kind, +): string | undefined { + const configured = config[`${kind}Model`]; + return typeof configured === "string" && configured + ? configured + : provider.defaults[kind]; +} + +/** A model as an action answers it: what the provider's own fields for it are stay inside. */ +function described({ id, name, description, create, edit }: ImageModel) { + return { + id, + ...(name ? { name } : {}), + ...(description ? { description } : {}), + create, + edit, + }; +} + +/** The types of image every provider documents taking to edit. */ +const SOURCE_TYPES = ["image/png", "image/jpeg", "image/webp"]; + +/** Read an image to edit. What it is, its bytes say: a file that is none of the types a model edits is refused. */ +async function sourceImage(path: string): Promise { + const bytes = await readLocalFile(path, { + subject: `${NAME}: ${path}`, + maxBytes: MAX_SOURCE_BYTES, + oversize: `${NAME}: ${path} is larger than ${MAX_SOURCE_BYTES / (1024 * 1024)} MiB`, + }); + const facts = imageFacts(bytes); + if (!facts || !SOURCE_TYPES.includes(facts.mimeType)) + throw new Error(`${NAME}: ${path} is not a PNG, JPEG or WebP image.`); + return { bytes, mimeType: facts.mimeType, fileName: basename(path) }; +} + +const sizeInputs = { + width: t.Optional( + t.Integer({ + minimum: MIN_SIDE, + maximum: MAX_SIDE, + description: `Width in pixels, from ${MIN_SIDE} to ${MAX_SIDE}. Set with height, or leave both out for the model's own size`, + }), + ), + height: t.Optional( + t.Integer({ + minimum: MIN_SIDE, + maximum: MAX_SIDE, + description: `Height in pixels, from ${MIN_SIDE} to ${MAX_SIDE}. Set with width. A model that takes other sizes makes the nearest one, and each image says its own`, + }), + ), +}; + +const numImages = t.Optional( + t.Integer({ + minimum: 1, + maximum: MAX_IMAGES, + description: `How many images to make, from 1 to ${MAX_IMAGES}. The default is 1`, + }), +); + +const modelInput = (kind: Kind) => + t.Optional( + t.String({ + minLength: 1, + description: `A model id from ${NAME}.models() that can ${kind}. The default is the connection's`, + }), + ); + +const imagesOutput = { + type: "object", + properties: { + provider: { type: "string" }, + model: { type: "string" }, + images: { + type: "array", + items: { + type: "object", + properties: { + path: { type: "string" }, + mimeType: { type: "string" }, + byteLength: { type: "integer" }, + width: { type: "integer" }, + height: { type: "integer" }, + }, + required: ["path", "mimeType", "byteLength"], + }, + }, + }, + required: ["provider", "model", "images"], +}; + +/** + * The `imagegen` plugin over `providers`, in the order one is chosen when + * the connection names none. A host adds a provider of its own by passing a + * list that includes it. + */ +export function imagegen( + providers: ImageProvider[] = PROVIDERS, +): PluginFunction { + const credential = credentialOf(providers); + const names = providers.map((provider) => provider.name); + /** Each provider's models, by the connection that listed them, with when the list was made. */ + const lists = new Map(); + /** A provider's models, and whether the provider itself could be asked for them. */ + interface Listed { + models: ImageModel[]; + asked: boolean; + } + + function apiOf(ctx: ActionContext, provider: ImageProvider): ProviderApi { + const [first] = Object.keys(provider.targets); + return { + request: ({ target, ...call }) => + credentialJson(ctx, credential, `${NAME}.${provider.name}`, { + target: target ?? first, + ...call, + }), + wait: async (ms) => { + await sleep(ms, undefined, { signal: ctx.signal }); + }, + }; + } + + /** + * A provider's models: the ones the package knows of, with the provider's + * own list laid over them. The provider is asked once in a while, and one + * that cannot be asked leaves the known ones, to be asked again next time. + */ + async function modelsOf( + ctx: ActionContext, + provider: ImageProvider, + ): Promise { + const key = `${ctx.connection.name}\0${provider.name}`; + const kept = lists.get(key); + if (kept && Date.now() - kept.at < MODELS_TTL_MS) + return { models: kept.models, asked: true }; + const byId = new Map(provider.models.map((model) => [model.id, model])); + try { + const live = await provider.listModels?.(apiOf(ctx, provider)); + for (const model of live ?? []) byId.set(model.id, model); + } catch { + return { models: [...byId.values()], asked: false }; + } + const models = [...byId.values()]; + lists.set(key, { at: Date.now(), models }); + return { models, asked: true }; + } + + /** The model a request uses, checked against the provider's models before anything is made. */ + async function modelFor( + ctx: ActionContext, + provider: ImageProvider, + named: string | undefined, + kind: Kind, + ): Promise { + const id = named ?? defaultModel(provider, ctx.connection.config, kind); + if (!id) + throw new Error( + `${NAME}: ${provider.name} has no model to ${kind} with by default. Pass one from ${NAME}.models().`, + ); + const { models, asked } = await modelsOf(ctx, provider); + const model = + models.find((listed) => listed.id === id) ?? + (await provider.findModel?.(apiOf(ctx, provider), id)) ?? + // A provider that could not be asked for its models judges the id itself. + (asked ? undefined : { id, create: true, edit: true }); + if (!model) + throw new Error( + `${NAME}: ${provider.name} has no image model ${JSON.stringify(id)}. List its models with ${NAME}.models().`, + ); + if (!model[kind]) + throw new Error( + `${NAME}: ${id} cannot ${kind} images. List the models that can with ${NAME}.models().`, + ); + return model; + } + + /** An image's bytes, fetched without the key from one of the provider's download hosts when it is a link. */ + async function bytesOf( + provider: ImageProvider, + produced: ProducedImage, + ): Promise { + if ("base64" in produced) return Buffer.from(produced.base64, "base64"); + const url = new URL(produced.url); + if ( + !provider.downloads?.some( + (host) => url.hostname === host || url.hostname.endsWith(`.${host}`), + ) + ) + throw new Error( + `${NAME}: ${provider.name} answered an image somewhere this package does not fetch from.`, + ); + const response = await downloadResource(url.href, { + allowedOrigins: [url.origin], + fetch: globalThis.fetch, + }); + if (!response.ok) + throw new Error( + `${NAME}: the image could not be fetched (HTTP ${response.status}).`, + ); + return new Uint8Array(await response.arrayBuffer()); + } + + async function make( + ctx: ActionContext, + kind: Kind, + input: { + prompt: string; + model?: string; + width?: number; + height?: number; + numImages?: number; + images?: string[]; + }, + ) { + if ((input.width === undefined) !== (input.height === undefined)) + throw new Error(`${NAME}: set width and height together, or neither.`); + const provider = chosen(providers, ctx.connection.config, !ctx.credentials); + const model = await modelFor(ctx, provider, input.model, kind); + const images = await Promise.all((input.images ?? []).map(sourceImage)); + const produced = await provider.generate(apiOf(ctx, provider), { + prompt: input.prompt, + model, + numImages: input.numImages ?? 1, + ...(input.width !== undefined && input.height !== undefined + ? { size: { width: input.width, height: input.height } } + : {}), + images, + }); + if (!produced.length) + throw new Error( + `${NAME}: ${model.id} answered no image. It may have refused the prompt.`, + ); + const written = []; + for (const one of produced) { + const bytes = await bytesOf(provider, one); + const facts = imageFacts(bytes); + if (!facts) + throw new Error( + `${NAME}: ${model.id} answered something that is no image.`, + ); + written.push({ + path: writeOutputFile( + `${NAME}-${provider.name}`, + EXTENSIONS[facts.mimeType], + bytes, + ctx.outputDir, + ), + mimeType: facts.mimeType, + byteLength: bytes.byteLength, + ...(facts.width && facts.height + ? { width: facts.width, height: facts.height } + : {}), + }); + } + return { provider: provider.name, model: model.id, images: written }; + } + + return function plugin(rl: CodemodePluginAPI): void { + rl.setName(NAME); + rl.setVersion(packageVersion(import.meta.url)); + rl.setDescription( + "Make and edit images through the image provider the connection chooses, and list its models.", + ); + rl.setCredential(credential); + rl.setConnectionSchema( + t.Object({ + provider: t.Optional( + t.String({ + enum: names, + description: + "The provider every request goes to. The default is the first provider with a key", + }), + ), + createModel: t.Optional( + t.String({ + description: + "The model create uses when a call names none. The default is the provider's", + }), + ), + editModel: t.Optional( + t.String({ + description: + "The model edit uses when a call names none. The default is the provider's", + }), + ), + ...Object.fromEntries( + providers.map((provider) => [ + keyField(provider), + t.Optional( + t.String({ + env: provider.env, + description: `API key for ${provider.name}`, + }), + ), + ]), + ), + }), + ); + + rl.registerAction("create", { + access: "write", + description: + "Make images from a prompt. Writes each image to a file and returns its path, type and size in pixels. Billed by the provider.", + hints: { openWorld: true }, + inputSchema: t.Object( + { + prompt: t.String({ + minLength: 1, + description: "What the image shows. Be specific and descriptive", + }), + model: modelInput("create"), + ...sizeInputs, + numImages, + }, + { additionalProperties: false }, + ), + outputSchema: imagesOutput, + execute: (input, ctx) => make(ctx, "create", input), + }); + + rl.registerAction("edit", { + access: "write", + description: + "Make images from a prompt and existing images: change one, or combine several. Writes each image to a file and returns its path, type and size in pixels. Billed by the provider.", + hints: { openWorld: true }, + inputSchema: t.Object( + { + prompt: t.String({ + minLength: 1, + description: "What to change, or what to make of the images", + }), + images: t.Array(t.String({ minLength: 1 }), { + minItems: 1, + maxItems: MAX_SOURCES, + description: `Paths of 1 to ${MAX_SOURCES} image files (PNG, JPEG or WebP) to edit. Some models take one`, + }), + model: modelInput("edit"), + ...sizeInputs, + numImages, + }, + { additionalProperties: false }, + ), + outputSchema: imagesOutput, + execute: (input, ctx) => make(ctx, "edit", input), + }); + + rl.registerAction("models", { + access: "read", + description: + "List the image models create and edit can use, with what each can do and the model each action uses by default.", + hints: { openWorld: true }, + inputSchema: t.Object( + { + query: t.Optional( + t.String({ + minLength: 1, + description: + "Words to find models by, such as flux or vector. Without it, the list is the provider's own, or its best-known models when it has thousands", + }), + ), + limit: t.Optional( + t.Integer({ + minimum: 1, + maximum: MAX_LISTED, + description: `The most models to return, from 1 to ${MAX_LISTED}. The default is ${DEFAULT_LISTED}`, + }), + ), + }, + { additionalProperties: false }, + ), + outputSchema: { + type: "object", + properties: { + provider: { type: "string" }, + createModel: { type: "string" }, + editModel: { type: "string" }, + models: { + type: "array", + items: { + type: "object", + properties: { + id: { type: "string" }, + name: { type: "string" }, + description: { type: "string" }, + create: { type: "boolean" }, + edit: { type: "boolean" }, + }, + required: ["id", "create", "edit"], + }, + }, + }, + required: ["provider", "models"], + }, + async execute(input, ctx) { + const { config } = ctx.connection; + const provider = chosen(providers, config, !ctx.credentials); + const words = input.query?.toLowerCase().split(/\s+/).filter(Boolean); + const matches = (model: ImageModel) => + !words || + words.every((word) => + `${model.id} ${model.name ?? ""} ${model.description ?? ""}` + .toLowerCase() + .includes(word), + ); + const known = (await modelsOf(ctx, provider)).models.filter(matches); + // A provider with thousands of models is searched for what its list does not hold. + const searched = + input.query && provider.findModel + ? await provider.listModels?.(apiOf(ctx, provider), input.query) + : []; + const byId = new Map( + [...(searched ?? []), ...known].map((model) => [model.id, model]), + ); + const createModel = defaultModel(provider, config, "create"); + const editModel = defaultModel(provider, config, "edit"); + return { + provider: provider.name, + ...(createModel ? { createModel } : {}), + ...(editModel ? { editModel } : {}), + models: [...byId.values()] + .slice(0, input.limit ?? DEFAULT_LISTED) + .map(described), + }; + }, + }); + }; +} + +export default imagegen(); diff --git a/packages/codemode-imagegen/src/providers/answer.ts b/packages/codemode-imagegen/src/providers/answer.ts new file mode 100644 index 00000000..88c17101 --- /dev/null +++ b/packages/codemode-imagegen/src/providers/answer.ts @@ -0,0 +1,13 @@ +import type { ProducedImage } from "../types.js"; + +/** The answer of an API in OpenAI's shape: each image in base64 under `data`. */ +export interface ImagesAnswer { + data?: Array<{ b64_json?: string }>; +} + +/** The images of such an answer. */ +export function imagesOf(answer: ImagesAnswer): ProducedImage[] { + return (answer.data ?? []).flatMap(({ b64_json }) => + b64_json ? [{ base64: b64_json }] : [], + ); +} diff --git a/packages/codemode-imagegen/src/providers/fal.ts b/packages/codemode-imagegen/src/providers/fal.ts new file mode 100644 index 00000000..946d3178 --- /dev/null +++ b/packages/codemode-imagegen/src/providers/fal.ts @@ -0,0 +1,139 @@ +import { pathSegments } from "@shiftlabs/codemode"; +import { dataUrlOf } from "../image.js"; +import { inputFor } from "../schema.js"; +import type { ImageModel, ImageProvider, ProviderApi } from "../types.js"; +import { describedModel, finished, hostedModel } from "./hosted.js"; + +/** fal's categories for the two things this package does. */ +const CATEGORIES = ["text-to-image", "image-to-image"]; +/** Every queue request declares a JSON body, the bodyless ones too. */ +const JSON_BODY = { "Content-Type": "application/json" }; + +interface Listed { + endpoint_id?: string; + metadata?: { display_name?: string; description?: string; category?: string }; + openapi?: { components?: { schemas?: Record } }; +} + +function listed({ endpoint_id, metadata }: Listed): ImageModel[] { + return endpoint_id && CATEGORIES.includes(metadata?.category ?? "") + ? [ + { + id: endpoint_id, + ...(metadata?.display_name ? { name: metadata.display_name } : {}), + ...(metadata?.description + ? { description: metadata.description } + : {}), + create: metadata?.category === "text-to-image", + edit: metadata?.category === "image-to-image", + }, + ] + : []; +} + +/** Where requests are queued, and what the addresses a queued request answers are beneath. */ +const QUEUE = "https://queue.fal.run/"; + +/** + * The path of an address fal answered for a queued request. fal asks about a + * request under the model's application, not its whole id, and says where. + */ +function queuePath(url: string | undefined): string { + if (!url?.startsWith(QUEUE)) + throw new Error("fal answered no address to ask about the request at."); + return pathSegments(url.slice(QUEUE.length)); +} + +async function findModel(api: ProviderApi, id: string) { + const { models } = await api.request<{ models?: Listed[] }>({ + target: "falCatalog", + path: "models", + query: { endpoint_id: id, expand: "openapi-3.0" }, + }); + const found = models?.find((model) => model.endpoint_id === id); + if (!found || !listed(found).length) return undefined; + const schemas = found.openapi?.components?.schemas ?? {}; + const input = Object.entries(schemas).find(([name]) => + name.endsWith("Input"), + ); + return hostedModel(listed(found)[0], input?.[1], schemas); +} + +export const fal: ImageProvider = { + name: "fal", + env: "FAL_KEY", + key: { header: "Authorization", prefix: "Key " }, + targets: { + fal: { baseUrl: QUEUE, methods: ["GET", "POST"] }, + falCatalog: { baseUrl: "https://api.fal.ai/v1/", methods: ["GET"] }, + }, + downloads: ["fal.media"], + defaults: { create: "fal-ai/flux/schnell", edit: "fal-ai/flux-pro/kontext" }, + models: [ + { + id: "fal-ai/flux/schnell", + name: "FLUX.1 [schnell]", + create: true, + edit: false, + }, + { + id: "fal-ai/flux-pro/kontext", + name: "FLUX.1 Kontext [pro]", + create: false, + edit: true, + }, + ], + // fal hosts thousands of models, so a list is the first of each category, or those a query finds. + async listModels(api, query) { + const pages = await Promise.all( + CATEGORIES.map((category) => + api.request<{ models?: Listed[] }>({ + target: "falCatalog", + path: "models", + query: { category, status: "active", limit: 50, q: query }, + }), + ), + ); + return pages.flatMap((page) => (page.models ?? []).flatMap(listed)); + }, + findModel, + async generate(api, request) { + const { id } = request.model; + const { fields } = await describedModel(request.model, (found) => + findModel(api, found), + ); + const queued = await api.request<{ + request_id?: string; + status_url?: string; + response_url?: string; + }>({ + path: pathSegments(id), + method: "POST", + headers: JSON_BODY, + // fal's API takes no upload, so an image to edit goes inside the request. + body: new TextEncoder().encode( + JSON.stringify(await inputFor(fields, request, dataUrlOf)), + ), + }); + const { request_id } = queued; + if (!request_id) throw new Error("fal answered no request id."); + const status = queuePath(queued.status_url); + const result = queuePath(queued.response_url); + await finished(api, `fal request ${request_id}`, async () => { + const state = await api.request<{ status?: string; error?: unknown }>({ + path: status, + headers: JSON_BODY, + }); + if (state.status !== "COMPLETED") return undefined; + if (state.error) throw new Error(`fal request ${request_id} failed.`); + return true; + }); + const output = await api.request<{ + images?: Array<{ url?: string }>; + image?: { url?: string }; + }>({ path: result, headers: JSON_BODY }); + return [...(output.images ?? []), output.image ?? {}].flatMap(({ url }) => + url ? [{ url }] : [], + ); + }, +}; diff --git a/packages/codemode-imagegen/src/providers/google.ts b/packages/codemode-imagegen/src/providers/google.ts new file mode 100644 index 00000000..2a24eaab --- /dev/null +++ b/packages/codemode-imagegen/src/providers/google.ts @@ -0,0 +1,121 @@ +import { pathSegment } from "@shiftlabs/codemode"; +import { base64Of } from "../image.js"; +import { nearestRatio } from "../size.js"; +import type { ImageModel, ImageProvider } from "../types.js"; + +/** The aspect ratios every Gemini image model takes. */ +const RATIOS = [ + "1:1", + "2:3", + "3:2", + "3:4", + "4:3", + "4:5", + "5:4", + "9:16", + "16:9", + "21:9", +]; + +interface Listed { + models?: Array<{ + name?: string; + displayName?: string; + description?: string; + supportedGenerationMethods?: string[]; + }>; +} + +interface Answer { + candidates?: Array<{ + content?: { parts?: Array<{ inlineData?: { data?: string } }> }; + }>; +} + +const model = (id: string, name?: string): ImageModel => ({ + id, + ...(name ? { name } : {}), + create: true, + edit: true, +}); + +export const google: ImageProvider = { + name: "google", + env: "GOOGLE_API_KEY", + key: { query: "key" }, + targets: { + google: { + baseUrl: "https://generativelanguage.googleapis.com/v1beta/", + methods: ["GET", "POST"], + }, + }, + defaults: { + create: "gemini-2.5-flash-image", + edit: "gemini-2.5-flash-image", + }, + models: [ + model("gemini-2.5-flash-image", "Nano Banana"), + model("gemini-3.1-flash-image", "Nano Banana 2"), + model("gemini-3.1-flash-lite-image", "Nano Banana 2 Lite"), + model("gemini-3-pro-image", "Nano Banana Pro"), + model("gemini-nano-banana-2.1", "Nano Banana 2.1"), + ], + // The list is of every Gemini model, so the image ones are told by their names. + async listModels(api) { + const { models } = await api.request({ + path: "models", + query: { pageSize: 1000 }, + }); + return (models ?? []).flatMap((listed) => { + const id = listed.name?.replace(/^models\//, "") ?? ""; + return /image|banana/.test(id) && + listed.supportedGenerationMethods?.includes("generateContent") + ? [ + { + ...model(id, listed.displayName), + ...(listed.description + ? { description: listed.description } + : {}), + }, + ] + : []; + }); + }, + // A request answers one image, so several images are several requests. + async generate(api, { prompt, model: { id }, numImages, size, images }) { + const one = () => + api.request({ + path: `models/${pathSegment(id)}:generateContent`, + method: "POST", + json: { + contents: [ + { + parts: [ + { text: prompt }, + ...images.map((image) => ({ + inlineData: { + mimeType: image.mimeType, + data: base64Of(image), + }, + })), + ], + }, + ], + generationConfig: { + responseModalities: ["IMAGE", "TEXT"], + ...(size + ? { imageConfig: { aspectRatio: nearestRatio(size, RATIOS) } } + : {}), + }, + }, + }); + const answers = await Promise.all(Array.from({ length: numImages }, one)); + return answers.flatMap((answer) => + (answer.candidates ?? []).flatMap((candidate) => + (candidate.content?.parts ?? []).flatMap((part) => + part.inlineData?.data ? [{ base64: part.inlineData.data }] : [], + ), + ), + ); + }, +}; diff --git a/packages/codemode-imagegen/src/providers/hosted.ts b/packages/codemode-imagegen/src/providers/hosted.ts new file mode 100644 index 00000000..63996d27 --- /dev/null +++ b/packages/codemode-imagegen/src/providers/hosted.ts @@ -0,0 +1,74 @@ +/** + * What fal and Replicate share: each hosts other people's models, publishes + * every model's input schema, and runs a request as a job that is waited on. + */ + +import { fieldsOf, type ModelFields } from "../schema.js"; +import type { ImageModel, ProviderApi } from "../types.js"; + +/** How long a job may take before the wait for it is given up. */ +export const JOB_DEADLINE_MS = 5 * 60_000; +const POLL_MS = 1_500; + +/** A hosted model as its host describes it: the fields its input takes, and the version to run. */ +export interface HostedModel extends ImageModel { + fields: ModelFields; + version?: string; +} + +/** A model and its fields from its input schema, or nothing when it takes no prompt. */ +export function hostedModel( + about: { id: string; name?: string; description?: string; version?: string }, + input: unknown, + schemas: unknown, +): HostedModel | undefined { + const fields = fieldsOf(input, schemas); + return ( + fields && { + id: about.id, + ...(about.name ? { name: about.name } : {}), + ...(about.description ? { description: about.description } : {}), + ...(about.version ? { version: about.version } : {}), + create: !fields.images?.required, + edit: fields.images !== undefined, + fields, + } + ); +} + +/** + * A request's model as its host describes it. A model the plugin found by + * its id already is; one from a list is asked for with `find`. + */ +export async function describedModel( + model: ImageModel, + find: (id: string) => Promise, +): Promise { + const described = + "fields" in model ? (model as HostedModel) : await find(model.id); + if (!described) + throw new Error(`${model.id} publishes no input this package can fill.`); + return described; +} + +/** + * Ask `check` for a job's outcome until it has one. `check` answers + * `undefined` while the job runs. The job is not cancelled when the wait + * ends: `label` names it in the error so it can be found. + */ +export async function finished( + api: ProviderApi, + label: string, + check: () => Promise, +): Promise { + const deadline = Date.now() + JOB_DEADLINE_MS; + for (;;) { + const outcome = await check(); + if (outcome !== undefined) return outcome; + if (Date.now() >= deadline) + throw new Error( + `${label} is still running after ${JOB_DEADLINE_MS / 60_000} minutes. It was not cancelled.`, + ); + await api.wait(POLL_MS); + } +} diff --git a/packages/codemode-imagegen/src/providers/index.ts b/packages/codemode-imagegen/src/providers/index.ts new file mode 100644 index 00000000..960041e8 --- /dev/null +++ b/packages/codemode-imagegen/src/providers/index.ts @@ -0,0 +1,24 @@ +import type { ImageProvider } from "../types.js"; +import { fal } from "./fal.js"; +import { google } from "./google.js"; +import { openai } from "./openai.js"; +import { recraft } from "./recraft.js"; +import { replicate } from "./replicate.js"; +import { together } from "./together.js"; +import { xai } from "./xai.js"; + +export { fal, google, openai, recraft, replicate, together, xai }; + +/** + * Every provider, in the order one is chosen when the connection names + * none: those that make their own models, then those that host others'. + */ +export const PROVIDERS: ImageProvider[] = [ + openai, + google, + xai, + recraft, + together, + fal, + replicate, +]; diff --git a/packages/codemode-imagegen/src/providers/openai.ts b/packages/codemode-imagegen/src/providers/openai.ts new file mode 100644 index 00000000..e8c0c285 --- /dev/null +++ b/packages/codemode-imagegen/src/providers/openai.ts @@ -0,0 +1,93 @@ +import { multipartBody } from "@shiftlabs/codemode"; +import { fitSize, nearestSize, type Size } from "../size.js"; +import type { ImageModel, ImageProvider } from "../types.js"; +import { type ImagesAnswer, imagesOf } from "./answer.js"; + +/** The sizes the GPT Image 1 line takes. */ +const FIXED_SIZES: Size[] = [ + { width: 1024, height: 1024 }, + { width: 1536, height: 1024 }, + { width: 1024, height: 1536 }, +]; +/** What gpt-image-2 and later take: any size within these bounds. */ +const FREE_SIZES = { + multiple: 16, + maxSide: 3840, + minPixels: 655_360, + maxPixels: 8_294_400, + maxRatio: 3, +}; + +const takesFixedSizes = (id: string) => id.startsWith("gpt-image-1"); + +function model(id: string): ImageModel { + return { id, create: true, edit: true }; +} + +function sizeFor(id: string, size: Size): string { + const { width, height } = takesFixedSizes(id) + ? nearestSize(size, FIXED_SIZES) + : fitSize(size, FREE_SIZES); + return `${width}x${height}`; +} + +export const openai: ImageProvider = { + name: "openai", + env: "OPENAI_API_KEY", + key: { header: "Authorization", prefix: "Bearer " }, + targets: { + openai: { baseUrl: "https://api.openai.com/v1/", methods: ["GET", "POST"] }, + }, + defaults: { create: "gpt-image-2.6-flare", edit: "gpt-image-2.6-flare" }, + models: [ + "gpt-image-2.6-flare", + "gpt-image-2.6-sunburst", + "gpt-image-2.5-flare", + "gpt-image-2.5-sunburst", + "gpt-image-2", + ].map(model), + // The list is of every model the key reaches, of any kind, so the image ones are told by their names. + async listModels(api) { + const { data } = await api.request<{ data?: Array<{ id?: unknown }> }>({ + path: "models", + }); + return (data ?? []).flatMap(({ id }) => + typeof id === "string" && /^(gpt-image-|chatgpt-image-)/.test(id) + ? [model(id)] + : [], + ); + }, + async generate(api, { prompt, model: { id }, numImages, size, images }) { + const common = { + model: id, + prompt, + n: numImages, + ...(size ? { size: sizeFor(id, size) } : {}), + }; + let answer: ImagesAnswer; + if (images.length) { + const form = new FormData(); + for (const [name, value] of Object.entries(common)) + form.append(name, String(value)); + for (const image of images) + form.append( + "image[]", + new Blob([image.bytes], { type: image.mimeType }), + image.fileName, + ); + const { body, contentType } = await multipartBody(form); + answer = await api.request({ + path: "images/edits", + method: "POST", + body, + headers: { "Content-Type": contentType }, + }); + } else + answer = await api.request({ + path: "images/generations", + method: "POST", + json: { ...common, output_format: "png" }, + }); + return imagesOf(answer); + }, +}; diff --git a/packages/codemode-imagegen/src/providers/recraft.ts b/packages/codemode-imagegen/src/providers/recraft.ts new file mode 100644 index 00000000..9703015c --- /dev/null +++ b/packages/codemode-imagegen/src/providers/recraft.ts @@ -0,0 +1,99 @@ +import { dataUrlOf } from "../image.js"; +import { nearestRatio } from "../size.js"; +import type { ImageModel, ImageProvider } from "../types.js"; +import { type ImagesAnswer, imagesOf } from "./answer.js"; + +/** The shapes every Recraft model takes, as `w:h`. */ +const RATIOS = [ + "1:1", + "2:1", + "1:2", + "3:2", + "2:3", + "4:3", + "3:4", + "5:4", + "4:5", + "6:10", + "14:10", + "10:14", + "16:9", + "9:16", +]; +/** How far an edit departs from its image, from 0 to 1. Recraft requires one; this keeps the image recognisable. */ +const EDIT_STRENGTH = 0.2; + +/** Every line edits an image except V2 and the Flash model. */ +const model = (id: string): ImageModel => ({ + id, + create: true, + edit: !/^recraftv2|flash/.test(id), +}); + +export const recraft: ImageProvider = { + name: "recraft", + env: "RECRAFT_API_KEY", + key: { header: "Authorization", prefix: "Bearer " }, + targets: { + recraft: { + baseUrl: "https://external.api.recraft.ai/v1/", + methods: ["POST"], + }, + }, + defaults: { create: "recraftv4_1", edit: "recraftv4_1" }, + // Recraft's API lists no models, so these are the ones its reference names. + models: [ + "recraftv4_1", + "recraftv4_1_pro", + "recraftv4_1_vector", + "recraftv4_1_pro_vector", + "recraftv4_1_flash_v2", + "recraftv4_1_utility", + "recraftv4_1_utility_pro", + "recraftv4_1_utility_vector", + "recraftv4_1_utility_pro_vector", + "recraftv4", + "recraftv4_pro", + "recraftv4_vector", + "recraftv4_pro_vector", + "recraftv3", + "recraftv3_vector", + "recraftv2", + "recraftv2_vector", + ].map(model), + async generate(api, { prompt, model: { id }, numImages, size, images }) { + if (images.length > 1) + throw new Error("recraft edits one image. Pass one path in images."); + if (images.length && size) + throw new Error( + "recraft keeps the size of the image it edits. Leave width and height out.", + ); + const common = { + prompt, + model: id, + n: numImages, + response_format: "b64_json", + }; + const answer = await api.request( + images.length + ? { + path: "images/imageToImage", + method: "POST", + json: { + ...common, + image_url: dataUrlOf(images[0]), + strength: EDIT_STRENGTH, + }, + } + : { + path: "images/generations", + method: "POST", + json: { + ...common, + ...(size ? { size: nearestRatio(size, RATIOS) } : {}), + }, + }, + ); + return imagesOf(answer); + }, +}; diff --git a/packages/codemode-imagegen/src/providers/replicate.ts b/packages/codemode-imagegen/src/providers/replicate.ts new file mode 100644 index 00000000..23d4b812 --- /dev/null +++ b/packages/codemode-imagegen/src/providers/replicate.ts @@ -0,0 +1,185 @@ +import { multipartBody, pathSegment, pathSegments } from "@shiftlabs/codemode"; +import { inputFor } from "../schema.js"; +import type { + ImageModel, + ImageProvider, + ProviderApi, + SourceImage, +} from "../types.js"; +import { describedModel, finished, hostedModel } from "./hosted.js"; + +/** Replicate's collections for the two things this package does. */ +const COLLECTIONS = [ + { slug: "text-to-image", create: true, edit: false }, + { slug: "image-editing", create: false, edit: true }, +]; + +interface Listed { + owner?: string; + name?: string; + description?: string; + latest_version?: { + id?: string; + openapi_schema?: { components?: { schemas?: Record } }; + }; +} + +/** The states a prediction ends in without an output. */ +const ENDED = ["failed", "canceled", "aborted"]; + +interface Prediction { + id?: string; + status?: string; + output?: unknown; +} + +/** A model a search found, with the tags that say what it does. */ +interface Found { + model?: Listed; + metadata?: { tags?: string[] }; +} + +const idOf = ({ owner, name }: Listed) => + owner && name ? `${owner}/${name}` : ""; + +function listed( + model: Listed, + can: { create: boolean; edit: boolean }, +): ImageModel[] { + return idOf(model) + ? [ + { + id: idOf(model), + ...(model.description ? { description: model.description } : {}), + ...can, + }, + ] + : []; +} + +/** Upload an image to edit as a file, and answer the address a model reads it from. */ +async function uploaded(api: ProviderApi, image: SourceImage): Promise { + const form = new FormData(); + form.append( + "content", + new Blob([image.bytes], { type: image.mimeType }), + image.fileName, + ); + const { body, contentType } = await multipartBody(form); + const file = await api.request<{ urls?: { get?: string } }>({ + path: "files", + method: "POST", + body, + headers: { "Content-Type": contentType }, + }); + if (!file.urls?.get) + throw new Error("replicate answered no address for an uploaded image."); + return file.urls.get; +} + +async function findModel(api: ProviderApi, id: string) { + const model = await api.request({ + path: `models/${pathSegments(id)}`, + }); + const schemas = + model.latest_version?.openapi_schema?.components?.schemas ?? {}; + return hostedModel( + { + id, + description: model.description, + version: model.latest_version?.id, + }, + schemas.Input, + schemas, + ); +} + +export const replicate: ImageProvider = { + name: "replicate", + env: "REPLICATE_API_TOKEN", + key: { header: "Authorization", prefix: "Bearer " }, + targets: { + replicate: { + baseUrl: "https://api.replicate.com/v1/", + methods: ["GET", "POST"], + allowedHeaders: ["Prefer"], + }, + }, + downloads: ["replicate.delivery"], + defaults: { + create: "black-forest-labs/flux-schnell", + edit: "black-forest-labs/flux-kontext-pro", + }, + models: [ + { id: "black-forest-labs/flux-schnell", create: true, edit: false }, + { id: "black-forest-labs/flux-kontext-pro", create: false, edit: true }, + ], + // Replicate hosts thousands of models, so a list is its two image collections, or what a search finds. + async listModels(api, query) { + if (query) { + const { models } = await api.request<{ models?: Found[] }>({ + path: "search", + query: { query, limit: 50 }, + }); + // A search finds models of every kind: its tags say which make images, and how. + return (models ?? []).flatMap(({ model, metadata }) => { + const tags = metadata?.tags ?? []; + const create = tags.includes("text-to-image"); + const edit = + tags.includes("image-to-image") || tags.includes("image-editing"); + return model && (create || edit) ? listed(model, { create, edit }) : []; + }); + } + const collections = await Promise.all( + COLLECTIONS.map(({ slug }) => + api.request<{ models?: Listed[] }>({ path: `collections/${slug}` }), + ), + ); + return collections.flatMap((collection, index) => + (collection.models ?? []).flatMap((model) => + listed(model, COLLECTIONS[index]), + ), + ); + }, + findModel, + async generate(api, request) { + const { id } = request.model; + const { fields, version } = await describedModel(request.model, (found) => + findModel(api, found), + ); + const input = await inputFor(fields, request, (image) => + uploaded(api, image), + ); + // The request waits up to a minute for the model, and answers a running job past that. + let prediction = await api.request({ + path: "predictions", + method: "POST", + headers: { Prefer: "wait" }, + json: { + version: version ? `${id}:${version}` : id, + input, + }, + }); + const { id: job } = prediction; + if (!job) throw new Error("replicate answered no prediction id."); + let asked = false; + const output = await finished( + api, + `replicate prediction ${job}`, + async () => { + if (asked) + prediction = await api.request({ + path: `predictions/${pathSegment(job)}`, + }); + asked = true; + if (prediction.status === "succeeded") return prediction.output ?? null; + if (ENDED.includes(prediction.status ?? "")) + throw new Error(`replicate prediction ${job} ${prediction.status}.`); + return undefined; + }, + ); + return (Array.isArray(output) ? output : [output]).flatMap((url) => + typeof url === "string" ? [{ url }] : [], + ); + }, +}; diff --git a/packages/codemode-imagegen/src/providers/together.ts b/packages/codemode-imagegen/src/providers/together.ts new file mode 100644 index 00000000..29a44113 --- /dev/null +++ b/packages/codemode-imagegen/src/providers/together.ts @@ -0,0 +1,111 @@ +import { dataUrlOf } from "../image.js"; +import { fitSize } from "../size.js"; +import type { ImageModel, ImageProvider } from "../types.js"; +import { type ImagesAnswer, imagesOf } from "./answer.js"; + +/** + * Together documents sides from 256 to 1920 for the FLUX.2 line; every model + * is held to them. The ratio keeps the shorter side at 256 or more when the + * longer is brought down to 1920. + */ +const SIZES = { + multiple: 16, + maxSide: 1920, + minPixels: 65_536, + maxPixels: 3_686_400, + maxRatio: 1920 / 256, +}; + +/** Whether a model takes images to edit: the Kontext and FLUX.2 lines, and Google's. */ +const edits = (id: string) => /kontext|FLUX\.2|flash-image|gemini/i.test(id); +/** The Kontext line takes its one image as `image_url`; the others take a list. */ +const takesOneImage = (id: string) => /kontext/i.test(id); + +const model = (id: string, name?: string): ImageModel => ({ + id, + ...(name ? { name } : {}), + create: true, + edit: edits(id), +}); + +interface Listed { + id?: string; + display_name?: string; + type?: string; +} + +export const together: ImageProvider = { + name: "together", + env: "TOGETHER_API_KEY", + key: { header: "Authorization", prefix: "Bearer " }, + targets: { + together: { + baseUrl: "https://api.together.ai/v1/", + methods: ["GET", "POST"], + }, + }, + defaults: { + create: "black-forest-labs/FLUX.2-dev", + edit: "black-forest-labs/FLUX.1-kontext-pro", + }, + // The image models of Together's catalog. + models: [ + "black-forest-labs/FLUX.2-dev", + "black-forest-labs/FLUX.2-pro", + "black-forest-labs/FLUX.2-flex", + "black-forest-labs/FLUX.2-max", + "black-forest-labs/FLUX.1.1-pro", + "black-forest-labs/FLUX.1-kontext-pro", + "black-forest-labs/FLUX.1-kontext-max", + "google/flash-image-2.5", + "google/flash-image-3.1", + "google/flash-image-3.1-lite", + "google/gemini-3-pro-image", + "openai/gpt-image-2", + "openai/gpt-image-1.5", + "ByteDance-Seed/Seedream-3.0", + "ByteDance-Seed/Seedream-4.0", + "ByteDance/Seedream-5.0-lite", + "ideogram/ideogram-3.0", + "ideogram/ideogram-4.0", + "prunaai/p-image-ideogram", + "Qwen/Qwen-Image", + "Qwen/Qwen-Image-2.0", + "Qwen/Qwen-Image-2.0-Pro", + "Rundiffusion/Juggernaut-Lightning-Flux", + "RunDiffusion/Juggernaut-pro-flux", + "stabilityai/stable-diffusion-xl-base-1.0", + "Wan-AI/Wan2.6-image", + ].map((id) => model(id)), + async listModels(api) { + const answer = await api.request({ + path: "models", + }); + return (Array.isArray(answer) ? answer : (answer.data ?? [])).flatMap( + ({ id, display_name, type }) => + id && type === "image" ? [model(id, display_name)] : [], + ); + }, + async generate(api, { prompt, model: { id }, numImages, size, images }) { + if (takesOneImage(id) && images.length > 1) + throw new Error(`${id} takes one image. Pass one path in images.`); + const urls = images.map(dataUrlOf); + const answer = await api.request({ + path: "images/generations", + method: "POST", + json: { + model: id, + prompt, + n: numImages, + response_format: "base64", + ...(size ? fitSize(size, SIZES) : {}), + ...(urls.length + ? takesOneImage(id) + ? { image_url: urls[0] } + : { reference_images: urls } + : {}), + }, + }); + return imagesOf(answer); + }, +}; diff --git a/packages/codemode-imagegen/src/providers/xai.ts b/packages/codemode-imagegen/src/providers/xai.ts new file mode 100644 index 00000000..3e11d5d9 --- /dev/null +++ b/packages/codemode-imagegen/src/providers/xai.ts @@ -0,0 +1,85 @@ +import { dataUrlOf } from "../image.js"; +import { nearestRatio, type Size } from "../size.js"; +import type { ImageProvider } from "../types.js"; +import { type ImagesAnswer, imagesOf } from "./answer.js"; + +/** The aspect ratios xAI's image models take. */ +const RATIOS = [ + "1:1", + "3:4", + "4:3", + "9:16", + "16:9", + "2:3", + "3:2", + "9:19.5", + "19.5:9", + "9:20", + "20:9", + "1:2", + "2:1", + "21:9", + "5:2", +]; + +/** The resolution tier whose longer side is closest above the one asked for. */ +function resolutionFor({ width, height }: Size): string { + const longer = Math.max(width, height); + return longer <= 1024 ? "1k" : longer <= 1536 ? "1.5k" : "2k"; +} + +interface Listed { + models?: Array<{ id?: string; input_modalities?: string[] }>; +} + +export const xai: ImageProvider = { + name: "xai", + env: "XAI_API_KEY", + key: { header: "Authorization", prefix: "Bearer " }, + targets: { + xai: { baseUrl: "https://api.x.ai/v1/", methods: ["GET", "POST"] }, + }, + defaults: { + create: "grok-imagine-image-2.0", + edit: "grok-imagine-image-2.0", + }, + models: [{ id: "grok-imagine-image-2.0", create: true, edit: true }], + async listModels(api) { + const { models } = await api.request({ + path: "image-generation-models", + }); + return (models ?? []).flatMap(({ id, input_modalities }) => + id + ? [ + { + id, + create: true, + edit: (input_modalities ?? []).includes("image"), + }, + ] + : [], + ); + }, + async generate(api, { prompt, model, numImages, size, images }) { + const sources = images.map((image) => ({ url: dataUrlOf(image) })); + const answer = await api.request({ + path: images.length ? "images/edits" : "images/generations", + method: "POST", + json: { + model: model.id, + prompt, + n: numImages, + response_format: "b64_json", + ...(size + ? { + aspect_ratio: nearestRatio(size, RATIOS), + resolution: resolutionFor(size), + } + : {}), + ...(sources.length === 1 ? { image: sources[0] } : {}), + ...(sources.length > 1 ? { images: sources } : {}), + }, + }); + return imagesOf(answer); + }, +}; diff --git a/packages/codemode-imagegen/src/schema.ts b/packages/codemode-imagegen/src/schema.ts new file mode 100644 index 00000000..549076ed --- /dev/null +++ b/packages/codemode-imagegen/src/schema.ts @@ -0,0 +1,150 @@ +/** + * A model's inputs, read from the JSON Schema its host publishes. fal and + * Replicate host thousands of models that name the same things differently + * (`num_images` or `num_outputs`, `image_url` or `input_image`); this finds + * which of a model's fields take the prompt, the count, the size and the + * images, so one request can be written as that model's input. + */ + +import { nearestRatio, nearestSize, parseSize, type Size } from "./size.js"; +import type { ImageRequest, SourceImage } from "./types.js"; + +type Schema = Record; + +/** Where one model takes each part of a request. */ +export interface ModelFields { + prompt: string; + count?: string; + /** The field that takes images, and whether it takes several. */ + images?: { name: string; many: boolean; required: boolean }; + size?: + | { kind: "object"; name: string } + | { kind: "pair" } + | { kind: "choice"; name: string; choices: string[] }; +} + +const COUNT_FIELDS = ["num_images", "num_outputs", "number_of_images", "n"]; +const IMAGE_FIELDS = [ + "image_urls", + "image_url", + "input_images", + "input_image", + "image_input", + "reference_images", + "images", + "image", +]; + +function record(value: unknown): Schema { + return value !== null && typeof value === "object" && !Array.isArray(value) + ? (value as Schema) + : {}; +} + +/** A property with the schemas it refers to folded in, so its type and choices are its own. */ +function resolved(property: unknown, schemas: Schema): Schema { + const schema = record(property); + const parts = [schema.allOf, schema.anyOf, schema.oneOf].flatMap((list) => + Array.isArray(list) ? list : [], + ); + const reference = (one: Schema) => + typeof one.$ref === "string" + ? record(schemas[one.$ref.split("/").pop() ?? ""]) + : one; + const all = [ + reference(schema), + ...parts.map((part) => reference(record(part))), + ]; + return { + types: all.flatMap((one) => + typeof one.type === "string" ? [one.type] : [], + ), + choices: all.flatMap((one) => + Array.isArray(one.enum) + ? one.enum.filter((choice) => typeof choice === "string") + : [], + ), + }; +} + +/** The fields of a model's input schema, or nothing when it takes no prompt. */ +export function fieldsOf( + input: unknown, + schemas: unknown, +): ModelFields | undefined { + const properties = record(record(input).properties); + const required = record(input).required; + const has = (name: string) => Object.hasOwn(properties, name); + if (!has("prompt")) return undefined; + const describe = (name: string) => + resolved(properties[name], record(schemas)); + const fields: ModelFields = { prompt: "prompt" }; + fields.count = COUNT_FIELDS.find(has); + const images = IMAGE_FIELDS.find(has); + if (images) + fields.images = { + name: images, + many: (describe(images).types as string[]).includes("array"), + required: Array.isArray(required) && required.includes(images), + }; + if (has("image_size")) fields.size = { kind: "object", name: "image_size" }; + else if (has("width") && has("height")) fields.size = { kind: "pair" }; + else + for (const name of ["aspect_ratio", "size"]) { + const choices = (describe(name).choices as string[]).filter(parseSize); + if (has(name) && choices.length) { + fields.size = { kind: "choice", name, choices }; + break; + } + } + return fields; +} + +/** The one of a model's size choices closest to `size`: each is `W:H` or `WxH`. */ +function choiceFor(size: Size, choices: string[]): string { + const exact = choices.filter((choice) => /x/i.test(choice)); + if (!exact.length) return nearestRatio(size, choices); + const nearest = nearestSize( + size, + exact.map((choice) => parseSize(choice) as Size), + ); + return exact.find((choice) => { + const parsed = parseSize(choice) as Size; + return parsed.width === nearest.width && parsed.height === nearest.height; + }) as string; +} + +/** + * A request written as one model's input. Rejects when the model has no + * field for a part the request sets. `source` gives the form the host takes + * an image to edit in, a link or a `data:` URL, and is asked only once the + * request is known to fit the model. + */ +export async function inputFor( + fields: ModelFields, + request: ImageRequest, + source: (image: SourceImage) => string | Promise, +): Promise> { + const { model, size, images, numImages } = request; + const input: Record = { [fields.prompt]: request.prompt }; + if (fields.count) input[fields.count] = numImages; + else if (numImages > 1) + throw new Error( + `${model.id} makes one image a request. Leave numImages out.`, + ); + if (size) { + if (!fields.size) + throw new Error(`${model.id} takes no size. Leave width and height out.`); + if (fields.size.kind === "pair") Object.assign(input, size); + else if (fields.size.kind === "object") input[fields.size.name] = size; + else input[fields.size.name] = choiceFor(size, fields.size.choices); + } + if (images.length) { + if (!fields.images) throw new Error(`${model.id} takes no images.`); + if (!fields.images.many && images.length > 1) + throw new Error(`${model.id} takes one image. Pass one path in images.`); + const urls = await Promise.all(images.map(source)); + input[fields.images.name] = fields.images.many ? urls : urls[0]; + } + return input; +} diff --git a/packages/codemode-imagegen/src/size.ts b/packages/codemode-imagegen/src/size.ts new file mode 100644 index 00000000..cda057c9 --- /dev/null +++ b/packages/codemode-imagegen/src/size.ts @@ -0,0 +1,107 @@ +/** + * Sizes in pixels, and their translation to what a provider's model takes: + * one of a set of sizes, an aspect ratio, or pixels within its own bounds. + */ + +export interface Size { + width: number; + height: number; +} + +/** How far apart two shapes are: 0 for the same aspect ratio. */ +function shapeDistance(a: Size, b: Size): number { + return Math.abs(Math.log(a.width / a.height) - Math.log(b.width / b.height)); +} + +/** `W:H` or `WxH` as a size, or nothing when the text is neither. */ +export function parseSize(text: string): Size | undefined { + const match = /^(\d+(?:\.\d+)?)\s*[:xX]\s*(\d+(?:\.\d+)?)$/.exec(text.trim()); + if (!match) return undefined; + const [width, height] = [Number(match[1]), Number(match[2])]; + return width > 0 && height > 0 ? { width, height } : undefined; +} + +/** + * The one of `sizes` closest to `size`: the nearest shape, and among equal + * shapes the nearest area. + */ +export function nearestSize(size: Size, sizes: readonly Size[]): Size { + const area = (one: Size) => one.width * one.height; + return [...sizes].sort( + (a, b) => + shapeDistance(size, a) - shapeDistance(size, b) || + Math.abs(area(a) - area(size)) - Math.abs(area(b) - area(size)), + )[0]; +} + +/** The one of `ratios`, each `W:H`, whose shape is closest to `size`. */ +export function nearestRatio(size: Size, ratios: readonly string[]): string { + const parsed = ratios.flatMap((ratio) => { + const shape = parseSize(ratio); + return shape ? [{ ratio, shape }] : []; + }); + return parsed.sort( + (a, b) => shapeDistance(size, a.shape) - shapeDistance(size, b.shape), + )[0].ratio; +} + +/** + * `size` brought within a model's bounds, keeping its shape as nearly as + * the bounds allow: each side a multiple of `multiple` and at most + * `maxSide`, the area between `minPixels` and `maxPixels`, and the longer + * side at most `maxRatio` times the shorter. + */ +export function fitSize( + size: Size, + bounds: { + multiple: number; + maxSide: number; + minPixels: number; + maxPixels: number; + maxRatio?: number; + }, +): Size { + const maxRatio = bounds.maxRatio ?? Number.POSITIVE_INFINITY; + const top = bounds.maxSide - (bounds.maxSide % bounds.multiple); + let { width, height } = size; + width = Math.min(width, height * maxRatio); + height = Math.min(height, width * maxRatio); + const scale = (factor: number) => { + width *= factor; + height *= factor; + }; + if (width * height < bounds.minPixels) + scale(Math.sqrt(bounds.minPixels / (width * height))); + if (width * height > bounds.maxPixels) + scale(Math.sqrt(bounds.maxPixels / (width * height))); + if (Math.max(width, height) > bounds.maxSide) + scale(bounds.maxSide / Math.max(width, height)); + const snap = (side: number) => + Math.min( + top, + Math.max( + bounds.multiple, + Math.round(side / bounds.multiple) * bounds.multiple, + ), + ); + const fitted = { width: snap(width), height: snap(height) }; + // Rounding can leave the shape or the area a step outside its bounds: move one side a step back in. + const sides = (): ["width" | "height", "width" | "height"] => + fitted.width >= fitted.height ? ["width", "height"] : ["height", "width"]; + const tooLong = (longer: number, shorter: number) => + longer > top || longer > shorter * maxRatio; + const shrink = () => { + fitted[sides()[0]] -= bounds.multiple; + }; + // The longer side grows unless that passes its own bounds; then the shorter does. + const grow = () => { + const [longer, shorter] = sides(); + const grown = fitted[longer] + bounds.multiple; + fitted[tooLong(grown, fitted[shorter]) ? shorter : longer] += + bounds.multiple; + }; + while (tooLong(fitted[sides()[0]], fitted[sides()[1]])) shrink(); + while (fitted.width * fitted.height < bounds.minPixels) grow(); + while (fitted.width * fitted.height > bounds.maxPixels) shrink(); + return fitted; +} diff --git a/packages/codemode-imagegen/src/types.ts b/packages/codemode-imagegen/src/types.ts new file mode 100644 index 00000000..59249990 --- /dev/null +++ b/packages/codemode-imagegen/src/types.ts @@ -0,0 +1,93 @@ +/** + * What an image provider is to the plugin: where it is and where its key + * goes, the models it has, and how one request for images is made of it. + */ + +import type { Size } from "./size.js"; + +/** A model a provider makes images with. */ +export interface ImageModel { + /** The id the provider's API takes, and the one code passes as `model`. */ + id: string; + name?: string; + description?: string; + /** Whether it makes an image from a prompt alone. */ + create: boolean; + /** Whether it makes an image from a prompt and images. */ + edit: boolean; +} + +/** An image read from disk to edit. */ +export interface SourceImage { + bytes: Uint8Array; + mimeType: string; + fileName: string; +} + +/** One request for images, the same for every provider. */ +export interface ImageRequest { + prompt: string; + model: ImageModel; + numImages: number; + /** The pixels asked for. A provider gets as close as its model allows. */ + size?: Size; + /** The images to edit, in order. Empty when the request creates one. */ + images: SourceImage[]; +} + +/** An image as a provider hands it over: its bytes in base64, or where to fetch them. */ +export type ProducedImage = { base64: string } | { url: string }; + +/** One request to a provider's API. */ +export interface ApiCall { + /** The provider's target to call. The default is its first. */ + target?: string; + path: string; + method?: "GET" | "POST"; + query?: Record; + json?: unknown; + /** A body that is not JSON, with its `Content-Type` among `headers`. */ + body?: Uint8Array; + headers?: Record; +} + +/** What a provider reaches the outside through. The plugin signs and sends. */ +export interface ProviderApi { + /** Send a signed request to one of the provider's targets and read its JSON answer. */ + request(call: ApiCall): Promise; + /** Wait, or reject when the run that asked ends. */ + wait(ms: number): Promise; +} + +/** An address a provider's key may be sent beneath. */ +export interface ProviderTarget { + /** An HTTPS address ending in `/`. */ + baseUrl: string; + methods: Array<"GET" | "POST">; + /** Headers its requests carry beside `Accept` and `Content-Type`. */ + allowedHeaders?: string[]; +} + +/** An image API: where it is, where its key goes, its models, and how it makes images. */ +export interface ImageProvider { + /** The name a connection gives as its `provider`, and the stem of the key's connection field. */ + name: string; + /** The environment variable that fills the key. */ + env: string; + /** Where the key goes in a request: a header, or a query parameter. */ + key: { header: string; prefix?: string } | { query: string }; + /** The addresses the key may be sent beneath, by a name no other provider uses. The first is the default. */ + targets: Record; + /** Hosts its images are fetched from, each with its subdomains. Fetches carry no key. */ + downloads?: string[]; + /** The model each action uses when neither the call nor the connection names one. */ + defaults: { create: string; edit?: string }; + /** The models the package knows of. A live list is laid over these. */ + models: ImageModel[]; + /** The provider's own list of its image models, where its API has one: all of them, or those that match `query`. */ + listModels?(api: ProviderApi, query?: string): Promise; + /** One model by its id, for a provider with more models than a list holds. */ + findModel?(api: ProviderApi, id: string): Promise; + /** Make the images of one request. */ + generate(api: ProviderApi, request: ImageRequest): Promise; +} diff --git a/packages/codemode-imagegen/tests/imagegen.test.ts b/packages/codemode-imagegen/tests/imagegen.test.ts new file mode 100644 index 00000000..6a9d6606 --- /dev/null +++ b/packages/codemode-imagegen/tests/imagegen.test.ts @@ -0,0 +1,1431 @@ +/** + * The image generation package: its three actions through a real engine + * with the providers' hosts stood in for, the pieces that translate a size + * and read a model's schema, and the package as codemode's package manager + * loads it. + */ + +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { afterEach, describe, it } from "node:test"; +import { fileURLToPath } from "node:url"; +import type { PluginFunction } from "@shiftlabs/codemode"; +import { stubFetch } from "../../codemode/src/tests/helpers/plugin.js"; +import { describePackage, pluginHarness } from "../../package-tests/harness.js"; +import { imageFacts } from "../src/image.js"; +import { type ImageProvider, imagegen, PROVIDERS } from "../src/index.js"; +import { fieldsOf, inputFor } from "../src/schema.js"; +import { fitSize, nearestRatio, nearestSize } from "../src/size.js"; + +const PACKAGE = fileURLToPath(new URL("..", import.meta.url)); + +/** The first bytes of a PNG of this size: all that tells an image's type and size. */ +function png(width: number, height: number): Buffer { + const bytes = Buffer.alloc(33); + Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]).copy(bytes); + bytes.writeUInt32BE(13, 8); + bytes.write("IHDR", 12); + bytes.writeUInt32BE(width, 16); + bytes.writeUInt32BE(height, 20); + return bytes; +} + +const PNG = png(1024, 768); +const B64 = PNG.toString("base64"); + +interface Sent { + method: string; + url: string; + headers: Record; + /** The body as JSON, or as text when it is not JSON. */ + body: unknown; +} + +const originalFetch = globalThis.fetch; +afterEach(() => { + globalThis.fetch = originalFetch; +}); + +/** + * Answer each request by the first route whose text its URL holds, and + * collect what was sent. A route answers JSON, or bytes for a download. + */ +function serve( + routes: Array<[string, (sent: Sent) => unknown]>, + status = 200, +): Sent[] { + const all: Sent[] = []; + stubFetch(async (url, init) => { + const text = init?.body + ? Buffer.from(init.body as Uint8Array).toString() + : ""; + let body: unknown = text || null; + try { + body = text ? JSON.parse(text) : null; + } catch {} + const sent = { + method: init?.method ?? "GET", + url: String(url), + headers: Object.fromEntries(new Headers(init?.headers)), + body, + }; + all.push(sent); + const route = routes.find(([part]) => sent.url.includes(part)); + assert.ok(route, `no route for ${sent.method} ${sent.url}`); + const answer = route[1](sent); + return Buffer.isBuffer(answer) + ? new Response(new Uint8Array(answer)) + : Response.json(answer, { status }); + }); + return all; +} + +/** A plugin of its own for each engine, so one test's model list is not another's. */ +const fresh: PluginFunction = (rl) => imagegen()(rl); +const harness = pluginHarness(fresh, "imagegen"); + +interface Made { + provider: string; + model: string; + images: Array<{ + path: string; + mimeType: string; + byteLength: number; + width?: number; + height?: number; + }>; +} + +/** A connection with a key for every provider. */ +const ALL_KEYS = Object.fromEntries( + PROVIDERS.map(({ name }) => [`${name}ApiKey`, `KEY-${name}`]), +); +/** A connection with a key for every provider, whose provider is `name`. */ +const through = (name: string) => ({ ...ALL_KEYS, provider: name }); + +/** Run code against an engine whose output directory is the test's own. */ +async function run(code: string, config: Record) { + const { result, error } = await harness + .codemode(config, { outputDir: harness.tmp }) + .execute(code); + return { result: result as T, error }; +} + +async function call( + action: string, + input: Record, + config: Record, +): Promise { + const { result, error } = await run( + `return await imagegen.${action}(${JSON.stringify(input)})`, + config, + ); + assert.equal(error, undefined); + return result; +} + +async function refused( + action: string, + input: Record, + config: Record, +): Promise { + const { error } = await run( + `return await imagegen.${action}(${JSON.stringify(input)})`, + config, + ); + assert.ok(error, "the call should fail"); + return error.split("\n")[0]; +} + +/** A source image on disk, for an edit. */ +function source(name = "in.png"): string { + const path = join(harness.tmp, name); + writeFileSync(path, png(640, 480)); + return path; +} + +const b64Answer = { data: [{ b64_json: B64 }] }; +const WIDE = { width: 1600, height: 900 }; + +/** The requests that made images, without those that listed models. */ +const made = (sent: Sent[]) => sent.filter(({ method }) => method === "POST"); + +describe("imagegen.create through each provider that answers at once", () => { + const cases: Record< + string, + { + list: [string, unknown]; + url: string; + body: unknown; + answer: unknown; + key: [string, string] | "query"; + } + > = { + openai: { + list: [ + "/v1/models", + { data: [{ id: "gpt-image-2.6-flare" }, { id: "gpt-6" }] }, + ], + url: "https://api.openai.com/v1/images/generations", + body: { + model: "gpt-image-2.6-flare", + prompt: "a fox", + n: 2, + size: "1600x896", + output_format: "png", + }, + answer: b64Answer, + key: ["authorization", "Bearer KEY-openai"], + }, + xai: { + list: [ + "image-generation-models", + { + models: [ + { + id: "grok-imagine-image-2.0", + input_modalities: ["text", "image"], + }, + ], + }, + ], + url: "https://api.x.ai/v1/images/generations", + body: { + model: "grok-imagine-image-2.0", + prompt: "a fox", + n: 2, + response_format: "b64_json", + aspect_ratio: "16:9", + resolution: "2k", + }, + answer: b64Answer, + key: ["authorization", "Bearer KEY-xai"], + }, + together: { + list: [ + "/v1/models", + [ + { id: "black-forest-labs/FLUX.2-dev", type: "image" }, + { id: "meta/llama", type: "chat" }, + ], + ], + url: "https://api.together.ai/v1/images/generations", + body: { + model: "black-forest-labs/FLUX.2-dev", + prompt: "a fox", + n: 2, + response_format: "base64", + width: 1600, + height: 896, + }, + answer: b64Answer, + key: ["authorization", "Bearer KEY-together"], + }, + recraft: { + list: ["never", {}], + url: "https://external.api.recraft.ai/v1/images/generations", + body: { + prompt: "a fox", + model: "recraftv4_1", + n: 2, + response_format: "b64_json", + size: "16:9", + }, + answer: b64Answer, + key: ["authorization", "Bearer KEY-recraft"], + }, + }; + + for (const [name, { list, url, body, answer, key }] of Object.entries( + cases, + )) { + it(`${name}: sends its API's request with its own key alone, and writes what it answers`, async () => { + const sent = serve([ + ["generations", () => answer], + [list[0], () => list[1]], + ]); + const result = await call( + "create", + { prompt: "a fox", numImages: 2, ...WIDE }, + through(name), + ); + const [request] = made(sent); + assert.deepEqual({ url: request.url, body: request.body }, { url, body }); + if (key !== "query") assert.equal(request.headers[key[0]], key[1]); + for (const other of PROVIDERS) + assert.equal( + JSON.stringify(sent).includes(`KEY-${other.name}`), + other.name === name, + `${other.name}'s key in a request to ${name}`, + ); + assert.equal(result.provider, name); + assert.equal(result.images.length, 1); + const [image] = result.images; + assert.deepEqual( + { ...image, path: dirname(image.path) }, + { + path: harness.tmp, + mimeType: "image/png", + byteLength: PNG.byteLength, + width: 1024, + height: 768, + }, + ); + assert.match( + image.path, + new RegExp(`imagegen-${name}-[0-9a-f]{16}\\.png$`), + ); + assert.deepEqual(readFileSync(image.path), PNG); + }); + } + + it("google: asks once for each image, with the nearest aspect ratio, and its key in the query", async () => { + const sent = serve([ + [ + ":generateContent", + () => ({ + candidates: [ + { + content: { + parts: [{ text: "here" }, { inlineData: { data: B64 } }], + }, + }, + ], + }), + ], + ["/models", () => ({ models: [] })], + ]); + const result = await call( + "create", + { prompt: "a fox", numImages: 2, ...WIDE }, + through("google"), + ); + const requests = made(sent); + assert.equal(requests.length, 2); + assert.equal( + requests[0].url, + "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash-image:generateContent?key=KEY-google", + ); + assert.deepEqual(requests[0].body, { + contents: [{ parts: [{ text: "a fox" }] }], + generationConfig: { + responseModalities: ["IMAGE", "TEXT"], + imageConfig: { aspectRatio: "16:9" }, + }, + }); + assert.equal(result.images.length, 2); + }); + + it("sends no size when none is asked for", async () => { + const sent = serve([ + ["generations", () => b64Answer], + ["/models", () => ({ data: [] })], + ]); + await call("create", { prompt: "a fox" }, through("openai")); + assert.deepEqual(made(sent)[0].body, { + model: "gpt-image-2.6-flare", + prompt: "a fox", + n: 1, + output_format: "png", + }); + }); +}); + +describe("imagegen.edit", () => { + it("openai: uploads the images as a form", async () => { + const sent = serve([ + ["images/edits", () => b64Answer], + ["/models", () => ({ data: [] })], + ]); + const result = await call( + "edit", + { prompt: "make it night", images: [source("a.png"), source("b.png")] }, + through("openai"), + ); + const [request] = made(sent); + assert.equal(request.url, "https://api.openai.com/v1/images/edits"); + assert.match(request.headers["content-type"], /^multipart\/form-data/); + const form = String(request.body); + for (const part of [ + 'name="model"\r\n\r\ngpt-image-2.6-flare', + 'name="prompt"\r\n\r\nmake it night', + 'name="image[]"; filename="a.png"', + 'name="image[]"; filename="b.png"', + ]) + assert.ok(form.includes(part), part); + assert.equal(result.images.length, 1); + }); + + it("sends each provider the image in the form its API takes", async () => { + const path = source(); + const dataUrl = `data:image/png;base64,${png(640, 480).toString("base64")}`; + const expected: Record]> = { + xai: ["https://api.x.ai/v1/images/edits", { image: { url: dataUrl } }], + together: [ + "https://api.together.ai/v1/images/generations", + { image_url: dataUrl, model: "black-forest-labs/FLUX.1-kontext-pro" }, + ], + recraft: [ + "https://external.api.recraft.ai/v1/images/imageToImage", + { image_url: dataUrl, strength: 0.2 }, + ], + }; + for (const [name, [url, fields]] of Object.entries(expected)) { + const sent = serve([ + ["images/", () => b64Answer], + ["models", () => ({})], + ]); + await call("edit", { prompt: "p", images: [path] }, through(name)); + const [request] = made(sent); + assert.equal(request.url, url, name); + const body = request.body as Record; + for (const [field, value] of Object.entries(fields)) + assert.deepEqual(body[field], value, `${name} ${field}`); + } + }); + + it("google: sends the images inline beside the prompt", async () => { + const sent = serve([ + [ + ":generateContent", + () => ({ + candidates: [{ content: { parts: [{ inlineData: { data: B64 } }] } }], + }), + ], + ["/models", () => ({ models: [] })], + ]); + await call( + "edit", + { prompt: "p", images: [source()] }, + through("google"), + ); + assert.deepEqual((made(sent)[0].body as { contents: unknown }).contents, [ + { + parts: [ + { text: "p" }, + { + inlineData: { + mimeType: "image/png", + data: png(640, 480).toString("base64"), + }, + }, + ], + }, + ]); + }); + + it("refuses a file that is not an image, and one that is not there", async () => { + const sent = serve([["/models", () => ({ data: [] })]]); + // Its bytes say what a file is, so a name that ends in .png does not make one an image. + const text = join(harness.tmp, "notes.png"); + writeFileSync(text, "not an image"); + assert.match( + await refused("edit", { prompt: "p", images: [text] }, through("openai")), + /notes\.png is not a PNG, JPEG or WebP image\./, + ); + const svg = join(harness.tmp, "logo.svg"); + writeFileSync(svg, ''); + assert.match( + await refused("edit", { prompt: "p", images: [svg] }, through("openai")), + /logo\.svg is not a PNG, JPEG or WebP image\./, + ); + assert.match( + await refused( + "edit", + { prompt: "p", images: [join(harness.tmp, "gone.png")] }, + through("openai"), + ), + /gone\.png is unreadable \(ENOENT\)/, + ); + assert.equal(made(sent).length, 0); + }); +}); + +describe("a provider that hosts other people's models", () => { + /** What fal answers a queued request: its id, and where to ask about it. */ + const queued = { + request_id: "r-1", + status_url: "https://queue.fal.run/fal-ai/flux/requests/r-1/status", + response_url: "https://queue.fal.run/fal-ai/flux/requests/r-1", + }; + + const falSchema = (input: Record, category: string) => ({ + models: [ + { + endpoint_id: "fal-ai/flux/schnell", + metadata: { display_name: "FLUX.1 [schnell]", category }, + openapi: { + components: { + schemas: { + QueueStatus: {}, + FluxSchnellInput: { properties: input, required: ["prompt"] }, + }, + }, + }, + }, + ], + }); + + it("fal: reads the model's schema, queues the request, and fetches the image without the key", async () => { + const sent = serve([ + [ + "expand=openapi", + () => + falSchema( + { + prompt: { type: "string" }, + num_images: { type: "integer" }, + image_size: { + anyOf: [{ $ref: "#/components/schemas/ImageSize" }], + }, + }, + "text-to-image", + ), + ], + ["api.fal.ai", () => ({ models: [] })], + ["/status", () => ({ status: "COMPLETED" })], + [ + "/requests/r-1", + () => ({ images: [{ url: "https://v3.fal.media/files/a.png" }] }), + ], + ["queue.fal.run/fal-ai/flux/schnell", () => queued], + ["fal.media", () => PNG], + ]); + const result = await call( + "create", + { prompt: "a fox", numImages: 2, ...WIDE }, + through("fal"), + ); + const [submit] = made(sent); + assert.equal(submit.url, "https://queue.fal.run/fal-ai/flux/schnell"); + assert.deepEqual(submit.body, { + prompt: "a fox", + num_images: 2, + image_size: { width: 1600, height: 900 }, + }); + assert.equal(submit.headers.authorization, "Key KEY-fal"); + assert.deepEqual( + sent + .filter(({ url }) => url.includes("/requests/")) + .map(({ url }) => url), + [ + "https://queue.fal.run/fal-ai/flux/requests/r-1/status", + "https://queue.fal.run/fal-ai/flux/requests/r-1", + ], + ); + const download = sent.find(({ url }) => url.includes("fal.media")); + assert.equal(download?.headers.authorization, undefined); + assert.deepEqual(readFileSync(result.images[0].path), PNG); + assert.equal(result.model, "fal-ai/flux/schnell"); + }); + + it("fal: asks once for the schema of a model its list does not hold", async () => { + const sent = serve([ + [ + "expand=openapi", + () => ({ + models: [ + { + endpoint_id: "fal-ai/unlisted", + metadata: { category: "text-to-image" }, + openapi: { + components: { + schemas: { UnlistedInput: { properties: { prompt: {} } } }, + }, + }, + }, + ], + }), + ], + ["api.fal.ai", () => ({ models: [] })], + ["/status", () => ({ status: "COMPLETED" })], + [ + "/requests/r-1", + () => ({ images: [{ url: "https://fal.media/files/a.png" }] }), + ], + ["queue.fal.run", () => queued], + ["fal.media", () => PNG], + ]); + const result = await call( + "create", + { prompt: "p", model: "fal-ai/unlisted" }, + through("fal"), + ); + assert.equal(result.model, "fal-ai/unlisted"); + assert.equal( + sent.filter(({ url }) => url.includes("expand=openapi")).length, + 1, + ); + }); + + it("fal: asks about a request only where fal says to", async () => { + serve([ + [ + "expand=openapi", + () => falSchema({ prompt: { type: "string" } }, "text-to-image"), + ], + ["api.fal.ai", () => ({ models: [] })], + [ + "queue.fal.run", + () => ({ ...queued, status_url: "https://evil.example/r-1/status" }), + ], + ]); + assert.match( + await refused("create", { prompt: "p" }, through("fal")), + /fal answered no address to ask about the request at\./, + ); + }); + + it("fal: refuses a size the model has no field for, before queueing anything", async () => { + const sent = serve([ + [ + "expand=openapi", + () => falSchema({ prompt: { type: "string" } }, "text-to-image"), + ], + ["api.fal.ai", () => ({ models: [] })], + ]); + assert.equal( + await refused("create", { prompt: "p", ...WIDE }, through("fal")), + "Error: fal-ai/flux/schnell takes no size. Leave width and height out.", + ); + assert.equal(made(sent).length, 0); + }); + + it("refuses an image that is somewhere the provider's images do not come from", async () => { + serve([ + [ + "expand=openapi", + () => falSchema({ prompt: { type: "string" } }, "text-to-image"), + ], + ["api.fal.ai", () => ({ models: [] })], + ["/status", () => ({ status: "COMPLETED" })], + [ + "/requests/r-1", + () => ({ images: [{ url: "https://evil.example/a.png" }] }), + ], + ["queue.fal.run", () => queued], + ]); + assert.match( + await refused("create", { prompt: "p" }, through("fal")), + /fal answered an image somewhere this package does not fetch from\./, + ); + }); + + it("replicate: reads the model's schema, waits for the prediction, and fetches the image", async () => { + let asked = 0; + const sent = serve([ + ["/collections/", () => ({ models: [] })], + [ + "/models/black-forest-labs/flux-schnell", + () => ({ + owner: "black-forest-labs", + name: "flux-schnell", + latest_version: { + id: "v9", + openapi_schema: { + components: { + schemas: { + Input: { + properties: { + prompt: { type: "string" }, + num_outputs: { type: "integer" }, + aspect_ratio: { + allOf: [{ $ref: "#/components/schemas/aspect_ratio" }], + }, + }, + }, + aspect_ratio: { + type: "string", + enum: ["1:1", "16:9", "9:16"], + }, + }, + }, + }, + }, + }), + ], + [ + "/predictions/p-1", + () => { + asked++; + return { + id: "p-1", + status: "succeeded", + output: ["https://replicate.delivery/x/out.png"], + }; + }, + ], + ["/predictions", () => ({ id: "p-1", status: "starting" })], + ["replicate.delivery", () => PNG], + ]); + const result = await call( + "create", + { prompt: "a fox", ...WIDE }, + through("replicate"), + ); + const [create] = made(sent); + assert.equal(create.url, "https://api.replicate.com/v1/predictions"); + assert.equal(create.headers.prefer, "wait"); + assert.deepEqual(create.body, { + version: "black-forest-labs/flux-schnell:v9", + input: { prompt: "a fox", num_outputs: 1, aspect_ratio: "16:9" }, + }); + assert.equal(asked, 1); + assert.equal(result.images.length, 1); + }); +}); + +describe("replicate", () => { + const flux = { + owner: "black-forest-labs", + name: "flux-schnell", + latest_version: { + id: "v9", + openapi_schema: { + components: { schemas: { Input: { properties: { prompt: {} } } } }, + }, + }, + }; + + it("ends the wait when a prediction ends without an output", async () => { + for (const status of ["failed", "canceled", "aborted"]) { + serve([ + ["/collections/", () => ({ models: [] })], + ["/models/", () => flux], + ["/predictions", () => ({ id: "p-1", status })], + ]); + assert.match( + await refused("create", { prompt: "p" }, through("replicate")), + new RegExp(`replicate prediction p-1 ${status}\\.`), + ); + } + }); + + it("uploads an image to edit as a file, and gives the model its address", async () => { + const sent = serve([ + ["/collections/", () => ({ models: [] })], + [ + "/models/", + () => ({ + latest_version: { + id: "v2", + openapi_schema: { + components: { + schemas: { + Input: { + properties: { + prompt: {}, + input_image: { type: "string" }, + }, + required: ["prompt", "input_image"], + }, + }, + }, + }, + }, + }), + ], + [ + "/files", + () => ({ urls: { get: "https://api.replicate.com/v1/files/f-1" } }), + ], + [ + "/predictions", + () => ({ + id: "p-1", + status: "succeeded", + output: "https://replicate.delivery/x/out.png", + }), + ], + ["replicate.delivery", () => PNG], + ]); + await call( + "edit", + { prompt: "make it night", images: [source("street.png")] }, + through("replicate"), + ); + const [upload, prediction] = made(sent); + assert.equal(upload.url, "https://api.replicate.com/v1/files"); + assert.match(upload.headers["content-type"], /^multipart\/form-data/); + assert.ok( + String(upload.body).includes('name="content"; filename="street.png"'), + ); + assert.deepEqual(prediction.body, { + version: "black-forest-labs/flux-kontext-pro:v2", + input: { + prompt: "make it night", + input_image: "https://api.replicate.com/v1/files/f-1", + }, + }); + }); + + it("lists what a search finds by its tags: the image models, and what each does", async () => { + serve([ + ["/collections/", () => ({ models: [] })], + [ + "/search", + () => ({ + models: [ + { + model: { owner: "google", name: "nano-banana" }, + metadata: { tags: ["text-to-image", "image-editing"] }, + }, + { + model: { owner: "acme", name: "upscaler" }, + metadata: { tags: ["image-to-image"] }, + }, + { + model: { owner: "meta", name: "llama" }, + metadata: { tags: ["language-model"] }, + }, + ], + }), + ], + ]); + const found = await call<{ models: unknown[] }>( + "models", + { query: "banana" }, + through("replicate"), + ); + assert.deepEqual(found.models, [ + { id: "google/nano-banana", create: true, edit: true }, + { id: "acme/upscaler", create: false, edit: true }, + ]); + }); +}); + +describe("imagegen.models", () => { + it("lays the provider's own list over the models the package knows, and says each action's default", async () => { + const sent = serve([ + [ + "image-generation-models", + () => ({ + models: [ + { id: "grok-imagine-image-2.0", input_modalities: ["text"] }, + { id: "grok-imagine-image-3", input_modalities: ["text", "image"] }, + ], + }), + ], + ]); + assert.deepEqual(await call("models", {}, through("xai")), { + provider: "xai", + createModel: "grok-imagine-image-2.0", + editModel: "grok-imagine-image-2.0", + models: [ + { id: "grok-imagine-image-2.0", create: true, edit: false }, + { id: "grok-imagine-image-3", create: true, edit: true }, + ], + }); + assert.equal(sent[0].url, "https://api.x.ai/v1/image-generation-models"); + }); + + it("keeps the list for the connection, so a request does not ask for it again", async () => { + const sent = serve([ + ["generations", () => b64Answer], + ["image-generation-models", () => ({ models: [] })], + ]); + const { error } = await run( + `await imagegen.models({}); + await imagegen.create({ prompt: "a" }); + await imagegen.create({ prompt: "b" });`, + through("xai"), + ); + assert.equal(error, undefined); + assert.deepEqual( + sent.map(({ url }) => url.split("/v1/")[1]), + ["image-generation-models", "images/generations", "images/generations"], + ); + }); + + it("answers the models the package knows when the provider cannot be asked", async () => { + stubFetch(async () => Response.json({}, { status: 500 })); + const listed = await call<{ models: Array<{ id: string }> }>( + "models", + {}, + through("openai"), + ); + assert.deepEqual(listed.models.map(({ id }) => id).slice(0, 2), [ + "gpt-image-2.6-flare", + "gpt-image-2.6-sunburst", + ]); + }); + + it("finds models by words, and returns no more than asked", async () => { + serve([["never", () => ({})]]); + const all = await call<{ models: Array<{ id: string }> }>( + "models", + {}, + through("recraft"), + ); + assert.equal(all.models.length, 17); + assert.deepEqual( + ( + await call<{ models: Array<{ id: string }> }>( + "models", + { query: "v4_1 vector" }, + through("recraft"), + ) + ).models.map(({ id }) => id), + [ + "recraftv4_1_vector", + "recraftv4_1_pro_vector", + "recraftv4_1_utility_vector", + "recraftv4_1_utility_pro_vector", + ], + ); + assert.equal( + ( + await call<{ models: unknown[] }>( + "models", + { limit: 3 }, + through("recraft"), + ) + ).models.length, + 3, + ); + }); + + it("searches a provider with thousands of models for what its list does not hold", async () => { + const sent = serve([ + [ + "q=banana", + () => ({ + models: [ + { + endpoint_id: "fal-ai/nano-banana-pro", + metadata: { + display_name: "Nano Banana Pro", + category: "text-to-image", + }, + }, + { + endpoint_id: "fal-ai/kling", + metadata: { category: "text-to-video" }, + }, + ], + }), + ], + ["api.fal.ai", () => ({ models: [] })], + ]); + const found = await call<{ models: Array<{ id: string }> }>( + "models", + { query: "banana" }, + through("fal"), + ); + assert.deepEqual(found.models, [ + { + id: "fal-ai/nano-banana-pro", + name: "Nano Banana Pro", + create: true, + edit: false, + }, + ]); + assert.ok(sent.some(({ url }) => url.includes("category=image-to-image"))); + }); +}); + +describe("the model a request uses", () => { + const xaiList = (): [string, () => unknown] => [ + "image-generation-models", + () => ({ + models: [{ id: "grok-imagine-image-2.0", input_modalities: ["text"] }], + }), + ]; + + it("is the call's, else the connection's, else the provider's", async () => { + const sent = serve([ + ["generations", () => b64Answer], + [ + "/models", + () => ({ data: [{ id: "gpt-image-2" }, { id: "gpt-image-1.5" }] }), + ], + ]); + const config = { ...through("openai"), createModel: "gpt-image-2" }; + const models = async ( + input: Record, + c: Record = config, + ) => (await call("create", { prompt: "p", ...input }, c)).model; + assert.deepEqual( + [ + await models({ model: "gpt-image-1.5" }), + await models({}), + await models({}, through("openai")), + ], + ["gpt-image-1.5", "gpt-image-2", "gpt-image-2.6-flare"], + ); + assert.equal( + (made(sent)[0].body as { model: string }).model, + "gpt-image-1.5", + ); + }); + + it("is refused before anything is made when the provider has no such model", async () => { + const sent = serve([xaiList()]); + assert.equal( + await refused("create", { prompt: "p", model: "grok-9" }, through("xai")), + 'Error: imagegen: xai has no image model "grok-9". List its models with imagegen.models().', + ); + assert.equal(made(sent).length, 0); + }); + + it("is refused when it cannot do what the action does", async () => { + const sent = serve([xaiList()]); + assert.equal( + await refused( + "edit", + { prompt: "p", images: [source()] }, + through("xai"), + ), + "Error: imagegen: grok-imagine-image-2.0 cannot edit images. List the models that can with imagegen.models().", + ); + assert.equal(made(sent).length, 0); + }); + + it("is left to the provider to judge when its models could not be listed", async () => { + const sent = serve([ + ["generations", () => b64Answer], + [ + "image-generation-models", + () => { + throw new Error("down"); + }, + ], + ]); + const result = await call( + "create", + { prompt: "p", model: "grok-new" }, + through("xai"), + ); + assert.equal(result.model, "grok-new"); + assert.equal((made(sent)[0].body as { model: string }).model, "grok-new"); + }); +}); + +describe("the provider a request uses", () => { + it("is the first with a key, in the providers' order", async () => { + serve([ + ["generations", () => b64Answer], + ["models", () => ({})], + ]); + const result = await call( + "create", + { prompt: "p" }, + { togetherApiKey: "t", xaiApiKey: "x" }, + ); + assert.equal(result.provider, "xai"); + }); + + it("is never the call's: no action has an input that names one", async () => { + serve([]); + for (const [action, input] of [ + ["create", { prompt: "p", provider: "xai" }], + ["models", { provider: "xai" }], + ] as const) + assert.match( + await refused(action, input, ALL_KEYS), + new RegExp(`Invalid input for imagegen\\.${action}`), + ); + }); + + it("is refused when no provider has a key, or the connection's has none", async () => { + serve([]); + const none = await refused("create", { prompt: "p" }, {}); + assert.match(none, /imagegen: no image provider has a key\. Set one of /); + for (const { env } of PROVIDERS) assert.ok(none.includes(env), env); + assert.equal( + await refused("models", {}, { xaiApiKey: "x", provider: "openai" }), + "Error: imagegen: no key for openai, the connection's provider. Set OPENAI_API_KEY.", + ); + }); +}); + +describe("what a request accepts", () => { + it("refuses one side of a size without the other", async () => { + serve([]); + assert.equal( + await refused("create", { prompt: "p", width: 1024 }, ALL_KEYS), + "Error: imagegen: set width and height together, or neither.", + ); + }); + + it("refuses a value in another form than the one each input has", async () => { + const sent = serve([]); + for (const input of [ + { prompt: "" }, + { prompt: "p", numImages: 5 }, + { prompt: "p", width: 100, height: 100 }, + { prompt: "p", width: 1024.5, height: 1024 }, + { prompt: "p", size: "1024x1024" }, + { prompt: "p", aspectRatio: "16:9" }, + ]) + assert.match( + await refused("create", input, ALL_KEYS), + /Invalid input for imagegen\.create/, + JSON.stringify(input), + ); + assert.match( + await refused("edit", { prompt: "p", images: [] }, ALL_KEYS), + /Invalid input for imagegen\.edit/, + ); + assert.equal(sent.length, 0); + }); +}); + +describe("a provider that fails", () => { + it("is reported by provider and status, without what it answered", async () => { + serve( + [ + ["generations", () => ({ error: "the key KEY-xai is not valid" })], + ["models", () => ({})], + ], + 401, + ); + const error = await refused("create", { prompt: "p" }, through("xai")); + assert.equal(error, "Error: imagegen.xai: request failed (HTTP 401)"); + }); + + it("is refused when it answers no image, or something that is no image", async () => { + serve([ + ["generations", () => ({ data: [] })], + ["models", () => ({})], + ]); + assert.match( + await refused("create", { prompt: "p" }, through("xai")), + /grok-imagine-image-2\.0 answered no image\. It may have refused the prompt\./, + ); + serve([ + [ + "generations", + () => ({ + data: [ + { b64_json: Buffer.from("not an image at all").toString("base64") }, + ], + }), + ], + ["models", () => ({})], + ]); + assert.match( + await refused("create", { prompt: "p" }, through("xai")), + /answered something that is no image\./, + ); + }); +}); + +describe("a provider a host adds", () => { + const acme: ImageProvider = { + name: "acme", + env: "ACME_IMAGE_KEY", + key: { header: "X-Acme-Key" }, + targets: { + acme: { baseUrl: "https://images.acme.example/", methods: ["POST"] }, + }, + defaults: { create: "acme-1" }, + models: [{ id: "acme-1", create: true, edit: false }], + generate: async (api, { prompt, model }) => { + const { image } = await api.request<{ image: string }>({ + path: "make", + method: "POST", + json: { prompt, model: model.id }, + }); + return [{ base64: image }]; + }, + }; + const extended = pluginHarness(imagegen([acme, ...PROVIDERS]), "imagegen"); + + it("is used like the others, with a key of its own", async () => { + const sent = serve([["acme.example", () => ({ image: B64 })]]); + const { result, error } = await extended + .codemode( + { ...ALL_KEYS, acmeApiKey: "KEY-acme" }, + { outputDir: extended.tmp }, + ) + .execute('return await imagegen.create({ prompt: "p" })'); + assert.equal(error, undefined); + assert.equal((result as Made).provider, "acme"); + assert.equal(sent[0].headers["x-acme-key"], "KEY-acme"); + assert.ok(!JSON.stringify(sent).includes("KEY-openai")); + }); +}); + +describe("a size in pixels", () => { + it("becomes the nearest of a model's sizes: the nearest shape, then the nearest area", () => { + const sizes = [ + { width: 1024, height: 1024 }, + { width: 1536, height: 1024 }, + { width: 1024, height: 1536 }, + ]; + assert.deepEqual( + nearestSize({ width: 1600, height: 900 }, sizes), + sizes[1], + ); + assert.deepEqual(nearestSize({ width: 500, height: 520 }, sizes), sizes[0]); + assert.deepEqual( + nearestSize({ width: 900, height: 1600 }, sizes), + sizes[2], + ); + }); + + it("becomes the nearest of a model's aspect ratios", () => { + const ratios = ["1:1", "4:3", "3:4", "16:9", "9:16"]; + assert.equal(nearestRatio({ width: 1920, height: 1080 }, ratios), "16:9"); + assert.equal(nearestRatio({ width: 1000, height: 800 }, ratios), "4:3"); + assert.equal(nearestRatio({ width: 512, height: 512 }, ratios), "1:1"); + assert.equal(nearestRatio({ width: 600, height: 1200 }, ratios), "9:16"); + }); + + it("is brought within a model's bounds with its shape kept", () => { + const bounds = { + multiple: 16, + maxSide: 3840, + minPixels: 655_360, + maxPixels: 8_294_400, + }; + assert.deepEqual(fitSize({ width: 1600, height: 900 }, bounds), { + width: 1600, + height: 896, + }); + const small = fitSize({ width: 512, height: 512 }, bounds); + assert.ok( + small.width * small.height >= bounds.minPixels, + JSON.stringify(small), + ); + assert.equal(small.width, small.height); + const large = fitSize({ width: 4096, height: 4096 }, bounds); + assert.ok( + large.width * large.height <= bounds.maxPixels, + JSON.stringify(large), + ); + assert.ok(large.width <= 3840 && large.width % 16 === 0); + }); + + it("is kept within a model's bounds whatever is asked for", () => { + const cases = [ + { + // OpenAI's: the longer side at most three times the shorter. + bounds: { + multiple: 16, + maxSide: 3840, + minPixels: 655_360, + maxPixels: 8_294_400, + maxRatio: 3, + }, + widest: { width: 1392, height: 480 }, + }, + { + // Together's: both sides from 256 to 1920. + bounds: { + multiple: 16, + maxSide: 1920, + minPixels: 65_536, + maxPixels: 3_686_400, + maxRatio: 1920 / 256, + }, + widest: { width: 1920, height: 256 }, + }, + ]; + for (const { bounds, widest } of cases) { + assert.deepEqual(fitSize({ width: 4096, height: 256 }, bounds), widest); + for (let width = 256; width <= 4096; width += 96) + for (let height = 256; height <= 4096; height += 96) { + const fitted = fitSize({ width, height }, bounds); + const [longer, shorter] = [ + Math.max(fitted.width, fitted.height), + Math.min(fitted.width, fitted.height), + ]; + const pixels = fitted.width * fitted.height; + assert.ok( + fitted.width % 16 === 0 && + fitted.height % 16 === 0 && + longer <= bounds.maxSide && + longer <= shorter * bounds.maxRatio && + pixels >= bounds.minPixels && + pixels <= bounds.maxPixels, + `${width}x${height} became ${fitted.width}x${fitted.height}`, + ); + } + } + }); +}); + +describe("an image's first bytes", () => { + it("tell its type and size", () => { + assert.deepEqual(imageFacts(png(640, 480)), { + mimeType: "image/png", + width: 640, + height: 480, + }); + const gif = Buffer.alloc(16); + gif.write("GIF89a"); + gif.writeUInt16LE(320, 6); + gif.writeUInt16LE(200, 8); + assert.deepEqual(imageFacts(gif), { + mimeType: "image/gif", + width: 320, + height: 200, + }); + const jpeg = Buffer.from([ + 0xff, 0xd8, 0xff, 0xe0, 0x00, 0x04, 0x00, 0x00, 0xff, 0xc0, 0x00, 0x11, + 0x08, 0x01, 0xe0, 0x02, 0x80, 0x03, 0x00, 0x00, + ]); + assert.deepEqual(imageFacts(jpeg), { + mimeType: "image/jpeg", + width: 640, + height: 480, + }); + const webp = Buffer.alloc(30); + webp.write("RIFF"); + webp.write("WEBP", 8); + webp.write("VP8X", 12); + webp.writeUIntLE(799, 24, 3); + webp.writeUIntLE(599, 27, 3); + assert.deepEqual(imageFacts(webp), { + mimeType: "image/webp", + width: 800, + height: 600, + }); + assert.deepEqual( + imageFacts( + Buffer.from( + '\n', + ), + ), + { mimeType: "image/svg+xml" }, + ); + assert.equal(imageFacts(Buffer.from("plain text, long enough")), undefined); + }); +}); + +describe("a hosted model's schema", () => { + const request = { + prompt: "p", + model: { id: "m", create: true, edit: true }, + numImages: 2, + size: { width: 1600, height: 900 }, + images: [], + }; + const image = { + bytes: new Uint8Array([0]), + mimeType: "image/png", + fileName: "a.png", + }; + const dataUrl = "data:image/png;base64,AA=="; + const asDataUrl = () => dataUrl; + + it("says which fields take the count, the size and the images", () => { + assert.deepEqual( + fieldsOf( + { + properties: { + prompt: {}, + num_outputs: {}, + width: {}, + height: {}, + input_image: { type: "string" }, + }, + required: ["prompt", "input_image"], + }, + {}, + ), + { + prompt: "prompt", + count: "num_outputs", + images: { name: "input_image", many: false, required: true }, + size: { kind: "pair" }, + }, + ); + assert.equal(fieldsOf({ properties: { text: {} } }, {}), undefined); + }); + + it("writes a request as the model's input", async () => { + const pair = fieldsOf( + { properties: { prompt: {}, n: {}, width: {}, height: {} } }, + {}, + ); + assert.ok(pair); + assert.deepEqual(await inputFor(pair, request, asDataUrl), { + prompt: "p", + n: 2, + width: 1600, + height: 900, + }); + const sizes = fieldsOf( + { + properties: { prompt: {}, size: { enum: ["1024x1024", "1536x1024"] } }, + }, + {}, + ); + assert.ok(sizes); + assert.deepEqual( + await inputFor(sizes, { ...request, numImages: 1 }, asDataUrl), + { prompt: "p", size: "1536x1024" }, + ); + const many = fieldsOf( + { properties: { prompt: {}, image_urls: { type: "array" } } }, + {}, + ); + assert.ok(many); + assert.deepEqual( + await inputFor( + many, + { ...request, numImages: 1, size: undefined, images: [image, image] }, + asDataUrl, + ), + { prompt: "p", image_urls: [dataUrl, dataUrl] }, + ); + }); + + it("refuses a part of a request the model has no field for, before an image is asked for", async () => { + let asked = 0; + const counted = () => { + asked++; + return dataUrl; + }; + const bare = fieldsOf( + { properties: { prompt: {}, image_url: { type: "string" } } }, + {}, + ); + assert.ok(bare); + await assert.rejects( + inputFor(bare, request, counted), + /m makes one image a request/, + ); + await assert.rejects( + inputFor(bare, { ...request, numImages: 1 }, counted), + /m takes no size/, + ); + await assert.rejects( + inputFor( + bare, + { ...request, numImages: 1, size: undefined, images: [image, image] }, + counted, + ), + /m takes one image/, + ); + assert.equal(asked, 0); + }); +}); + +describe("the README", () => { + it("lists the providers in their order, with each key and whether its models are listed live", () => { + const readme = readFileSync(join(PACKAGE, "README.md"), "utf8"); + const rows = [ + ...readme.matchAll(/^\| `(\w+)` \| `(\w+)` \| (Yes|No) \|/gm), + ].map(([, name, env, live]) => [name, env, live]); + assert.deepEqual( + rows, + PROVIDERS.map(({ name, env, listModels }) => [ + name, + env, + listModels ? "Yes" : "No", + ]), + ); + }); +}); + +describePackage(PACKAGE, { + package: "@shiftlabs/codemode-imagegen", + plugin: "imagegen", + actions: 3, + write: 2, +}); diff --git a/packages/codemode-imagegen/tsconfig.json b/packages/codemode-imagegen/tsconfig.json new file mode 100644 index 00000000..956f602c --- /dev/null +++ b/packages/codemode-imagegen/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "esnext", + "module": "nodenext", + "moduleResolution": "nodenext", + "noEmit": true, + "strict": true, + "skipLibCheck": true, + "types": ["node", "bun"] + }, + "include": ["src", "tests"] +} diff --git a/packages/codemode-plugins/_shared/attachments.ts b/packages/codemode-plugins/_shared/attachments.ts index 5e6d1e84..75ba7d6a 100644 --- a/packages/codemode-plugins/_shared/attachments.ts +++ b/packages/codemode-plugins/_shared/attachments.ts @@ -1,7 +1,7 @@ import { basename } from "node:path"; +import { readLocalFile } from "@shiftlabs/codemode"; import * as t from "typebox"; import { DownloadedFile, standardBase64 } from "./base64.js"; -import { readLocalFile } from "./localFile.js"; import { STRICT } from "./schemas.js"; const id = t.String({ minLength: 1, pattern: "\\S" }); diff --git a/packages/codemode-plugins/_shared/mediaFile.ts b/packages/codemode-plugins/_shared/mediaFile.ts index ebf0d9ca..efedbee5 100644 --- a/packages/codemode-plugins/_shared/mediaFile.ts +++ b/packages/codemode-plugins/_shared/mediaFile.ts @@ -9,8 +9,7 @@ * available (same pattern as googleDrive/googleSlides). */ import { basename, extname } from "node:path"; -import { writeOutputFile } from "@shiftlabs/codemode"; -import { readLocalFile } from "./localFile.js"; +import { readLocalFile, writeOutputFile } from "@shiftlabs/codemode"; const MIME_EXT: Record = { "image/png": "png", diff --git a/packages/codemode-plugins/_shared/shiftUpload.ts b/packages/codemode-plugins/_shared/shiftUpload.ts index f0cb3494..050d4c24 100644 --- a/packages/codemode-plugins/_shared/shiftUpload.ts +++ b/packages/codemode-plugins/_shared/shiftUpload.ts @@ -1,7 +1,7 @@ import { openAsBlob } from "node:fs"; import { stat } from "node:fs/promises"; import { extname } from "node:path"; -import { readLocalFile } from "./localFile.js"; +import { readLocalFile } from "@shiftlabs/codemode"; /** * The Shift cloud signed-grant upload arc, shared by every plugin that diff --git a/packages/codemode-plugins/dropbox/src/index.ts b/packages/codemode-plugins/dropbox/src/index.ts index 12a18c74..338bd395 100644 --- a/packages/codemode-plugins/dropbox/src/index.ts +++ b/packages/codemode-plugins/dropbox/src/index.ts @@ -13,10 +13,10 @@ import { type CredentialCall, credentialRequest, jsonAnswer, + readLocalFile, responseFailed, } from "@shiftlabs/codemode"; import * as t from "typebox"; -import { readLocalFile } from "../../_shared/localFile.js"; import { stringEnum } from "../../_shared/schemas.js"; import { DROPBOX_AUTH_URL, diff --git a/packages/codemode-plugins/elevenlabs/src/shared.ts b/packages/codemode-plugins/elevenlabs/src/shared.ts index 80f6827a..4d080140 100644 --- a/packages/codemode-plugins/elevenlabs/src/shared.ts +++ b/packages/codemode-plugins/elevenlabs/src/shared.ts @@ -5,11 +5,11 @@ import { brokerFor, multipartBody, pathSegment, + readLocalFile, responseFailed, } from "@shiftlabs/codemode"; import * as t from "typebox"; import { Check } from "typebox/value"; -import { readLocalFile } from "../../_shared/localFile.js"; import { mediaDir, SEND_FILE_NOTE, diff --git a/packages/codemode-plugins/facebookPages/src/index.ts b/packages/codemode-plugins/facebookPages/src/index.ts index 9081b3cf..4585967e 100644 --- a/packages/codemode-plugins/facebookPages/src/index.ts +++ b/packages/codemode-plugins/facebookPages/src/index.ts @@ -15,9 +15,9 @@ import { type CodemodePluginAPI, multipartBody, pathSegment, + readLocalFile, } from "@shiftlabs/codemode"; import * as t from "typebox"; -import { readLocalFile } from "../../_shared/localFile.js"; import { fields, metaGraph, diff --git a/packages/codemode-plugins/googleDrive/src/index.ts b/packages/codemode-plugins/googleDrive/src/index.ts index 5a2da07a..66b1b7bb 100644 --- a/packages/codemode-plugins/googleDrive/src/index.ts +++ b/packages/codemode-plugins/googleDrive/src/index.ts @@ -66,6 +66,7 @@ import { jsonAnswer, pathSegment, rangedDownload, + readLocalFile, } from "@shiftlabs/codemode"; import * as t from "typebox"; import { standardBase64 } from "../../_shared/base64.js"; @@ -86,7 +87,6 @@ import { StringMap, StringOrStringArray, } from "../../_shared/googleSchemas.js"; -import { readLocalFile } from "../../_shared/localFile.js"; import { atLeastOne, exactlyOne, diff --git a/packages/codemode-plugins/instagram/src/index.ts b/packages/codemode-plugins/instagram/src/index.ts index 54015307..1c5783e3 100644 --- a/packages/codemode-plugins/instagram/src/index.ts +++ b/packages/codemode-plugins/instagram/src/index.ts @@ -22,9 +22,9 @@ import { type CodemodePluginAPI, jsonAnswer, pathSegment, + readLocalFile, } from "@shiftlabs/codemode"; import * as t from "typebox"; -import { readLocalFile } from "../../_shared/localFile.js"; import { fields, names, diff --git a/packages/codemode-plugins/shiftOcr/src/index.ts b/packages/codemode-plugins/shiftOcr/src/index.ts index ec9d7b61..a297cfe7 100644 --- a/packages/codemode-plugins/shiftOcr/src/index.ts +++ b/packages/codemode-plugins/shiftOcr/src/index.ts @@ -1,7 +1,10 @@ import { basename, extname } from "node:path"; -import { type CodemodePluginAPI, pathSegment } from "@shiftlabs/codemode"; +import { + type CodemodePluginAPI, + pathSegment, + readLocalFile, +} from "@shiftlabs/codemode"; import * as t from "typebox"; -import { readLocalFile } from "../../_shared/localFile.js"; import { type Ctx, STRICT_OBJECT } from "../../_shared/shiftCloud.js"; import { putThroughGrant, diff --git a/packages/codemode/src/index.ts b/packages/codemode/src/index.ts index 9f303fa4..950857e1 100644 --- a/packages/codemode/src/index.ts +++ b/packages/codemode/src/index.ts @@ -332,6 +332,7 @@ export { shellRunAction, syncExec, } from "./utils/cli.js"; +export { readLocalFile } from "./utils/local-file.js"; export { ACTION_MEMORY_BYTES, OutputFileWriter, diff --git a/packages/codemode/src/tests/plugin-input-helpers.test.ts b/packages/codemode/src/tests/plugin-input-helpers.test.ts index 867395f6..f7fd2712 100644 --- a/packages/codemode/src/tests/plugin-input-helpers.test.ts +++ b/packages/codemode/src/tests/plugin-input-helpers.test.ts @@ -11,13 +11,13 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { after, describe, it } from "node:test"; import { standardBase64 } from "../../../codemode-plugins/_shared/base64.js"; -import { readLocalFile } from "../../../codemode-plugins/_shared/localFile.js"; import { readImageInput } from "../../../codemode-plugins/_shared/mediaFile.js"; import googleDrive from "../../../codemode-plugins/googleDrive/src/index.js"; import microsoftFiles from "../../../codemode-plugins/microsoftFiles/src/index.js"; import { responseFailed } from "../credentials/plugin.js"; import { type CodemodePluginAPI, createPluginAPI } from "../plugin/api.js"; import type { ActionContext } from "../plugin/types.js"; +import { readLocalFile } from "../utils/local-file.js"; import { getAction, stubFetch } from "./helpers/plugin.js"; const dir = mkdtempSync(join(tmpdir(), "plugin-input-test-")); diff --git a/packages/codemode-plugins/_shared/localFile.ts b/packages/codemode/src/utils/local-file.ts similarity index 100% rename from packages/codemode-plugins/_shared/localFile.ts rename to packages/codemode/src/utils/local-file.ts