Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 0 additions & 5 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,6 @@
"!packages/codemode-plugins/oneSimpleApi",
"!packages/codemode-plugins/onfleet",
"!packages/codemode-plugins/openThesaurus",
"!packages/codemode-plugins/openai",
"!packages/codemode-plugins/openweathermap",
"!packages/codemode-plugins/oura",
"!packages/codemode-plugins/paddle",
Expand All @@ -150,9 +149,7 @@
"!packages/codemode-plugins/quickbooks",
"!packages/codemode-plugins/quickchart",
"!packages/codemode-plugins/raindrop",
"!packages/codemode-plugins/recraft",
"!packages/codemode-plugins/reddit",
"!packages/codemode-plugins/replicate",
"!packages/codemode-plugins/rocketchat",
"!packages/codemode-plugins/rundeck",
"!packages/codemode-plugins/salesmate",
Expand Down Expand Up @@ -180,7 +177,6 @@
"!packages/codemode-plugins/telegram",
"!packages/codemode-plugins/thehive",
"!packages/codemode-plugins/thehiveProject",
"!packages/codemode-plugins/together",
"!packages/codemode-plugins/travisci",
"!packages/codemode-plugins/trello",
"!packages/codemode-plugins/twilio",
Expand All @@ -197,7 +193,6 @@
"!packages/codemode-plugins/wekan",
"!packages/codemode-plugins/woocommerce",
"!packages/codemode-plugins/wordpress",
"!packages/codemode-plugins/xai",
"!packages/codemode-plugins/xero",
"!packages/codemode-plugins/yourls",
"!packages/codemode-plugins/zammad",
Expand Down
2 changes: 1 addition & 1 deletion packages/codemode-imagegen/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ The list is the models this package knows of with the provider's own list laid o

| 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 |
| `openai` | The same pixels, with sides rounded to 16 and the longer side at most three times the shorter |
| `google` | The nearest aspect ratio |
| `xai` | The nearest aspect ratio, and a resolution of 1k, 1.5k, or 2k |
| `recraft` | The nearest aspect ratio |
Expand Down
4 changes: 2 additions & 2 deletions packages/codemode-imagegen/src/providers/google.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@ export const google: ImageProvider = {
},
},
defaults: {
create: "gemini-2.5-flash-image",
edit: "gemini-2.5-flash-image",
create: "gemini-nano-banana-2.1",
edit: "gemini-nano-banana-2.1",
},
models: [
model("gemini-2.5-flash-image", "Nano Banana"),
Expand Down
25 changes: 8 additions & 17 deletions packages/codemode-imagegen/src/providers/openai.ts
Original file line number Diff line number Diff line change
@@ -1,33 +1,23 @@
import { multipartBody } from "@shiftlabs/codemode";
import { fitSize, nearestSize, type Size } from "../size.js";
import { fitSize, 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 = {
/** A GPT Image model takes any size within these bounds. */
const 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);
function sizeFor(size: Size): string {
const { width, height } = fitSize(size, SIZES);
return `${width}x${height}`;
}

Expand All @@ -47,12 +37,13 @@ export const openai: ImageProvider = {
"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.
// The gpt-image-1 line takes other sizes and shuts down on 2026-12-01, so it is left out.
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)
typeof id === "string" && /^(gpt-image-(?!1)|chatgpt-image-)/.test(id)
? [model(id)]
: [],
);
Expand All @@ -62,7 +53,7 @@ export const openai: ImageProvider = {
model: id,
prompt,
n: numImages,
...(size ? { size: sizeFor(id, size) } : {}),
...(size ? { size: sizeFor(size) } : {}),
};
let answer: ImagesAnswer;
if (images.length) {
Expand Down
20 changes: 15 additions & 5 deletions packages/codemode-imagegen/tests/imagegen.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -294,7 +294,7 @@ describe("imagegen.create through each provider that answers at once", () => {
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",
"https://generativelanguage.googleapis.com/v1beta/models/gemini-nano-banana-2.1:generateContent?key=KEY-google",
);
assert.deepEqual(requests[0].body, {
contents: [{ parts: [{ text: "a fox" }] }],
Expand Down Expand Up @@ -927,7 +927,13 @@ describe("the model a request uses", () => {
["generations", () => b64Answer],
[
"/models",
() => ({ data: [{ id: "gpt-image-2" }, { id: "gpt-image-1.5" }] }),
() => ({
data: [
{ id: "gpt-image-2" },
{ id: "chatgpt-image-latest" },
{ id: "gpt-image-1.5" },
],
}),
],
]);
const config = { ...through("openai"), createModel: "gpt-image-2" };
Expand All @@ -937,15 +943,19 @@ describe("the model a request uses", () => {
) => (await call<Made>("create", { prompt: "p", ...input }, c)).model;
assert.deepEqual(
[
await models({ model: "gpt-image-1.5" }),
await models({ model: "chatgpt-image-latest" }),
await models({}),
await models({}, through("openai")),
],
["gpt-image-1.5", "gpt-image-2", "gpt-image-2.6-flare"],
["chatgpt-image-latest", "gpt-image-2", "gpt-image-2.6-flare"],
);
assert.equal(
(made(sent)[0].body as { model: string }).model,
"gpt-image-1.5",
"chatgpt-image-latest",
);
assert.match(
await refused("create", { prompt: "p", model: "gpt-image-1.5" }, config),
/gpt-image-1\.5/,
);
});

Expand Down
70 changes: 29 additions & 41 deletions packages/codemode-plugins/_shared/mediaFile.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,12 @@
* send_file/attachment tool. Plugins load in-process via jiti, so node:fs is
* available (same pattern as googleDrive/googleSlides).
*/
import { basename, extname } from "node:path";
import { readLocalFile, writeOutputFile } from "@shiftlabs/codemode";
import {
imageFacts,
type LocalImage,
readLocalImage,
writeOutputFile,
} from "@shiftlabs/codemode";

const MIME_EXT: Record<string, string> = {
"image/png": "png",
Expand Down Expand Up @@ -59,7 +63,9 @@ export function mediaDir(

/**
* Write media bytes to an output file of their own in `saveDir`, which an
* action takes from `mediaDir()`.
* action takes from `mediaDir()`. What an image is, its bytes say:
* `mimeType` names the type of other media, and of an image whose bytes
* tell none.
*/
export function writeMediaFile(opts: {
bytes: Uint8Array;
Expand All @@ -69,7 +75,10 @@ export function writeMediaFile(opts: {
saveDir?: string;
stamp?: number;
}): SavedMedia {
const mimeType = opts.mimeType ?? "image/png";
const declared = opts.mimeType ?? "image/png";
const mimeType = /^image\//i.test(declared)
? (imageFacts(opts.bytes)?.mimeType ?? declared)
: declared;
const stamp = opts.stamp ?? Date.now();
if (!/^[\w-]+$/.test(opts.provider))
throw new Error("invalid media provider name");
Expand All @@ -82,10 +91,7 @@ export function writeMediaFile(opts: {
return { path, mimeType, byteLength: opts.bytes.byteLength };
}

/**
* Decode base64 media bytes and write them, for the providers that answer
* with base64 rather than a URL to download.
*/
/** Decode an image a provider answers in base64 and write it. */
export function writeImageFile(opts: {
base64: string;
mimeType?: string;
Expand All @@ -104,50 +110,32 @@ export function writeImageFile(opts: {
export const SEND_FILE_NOTE =
"File(s) written to disk. Deliver each to the user with send_file using its `path`.";

const EXT_MIME: Record<string, string> = {
png: "image/png",
jpg: "image/jpeg",
jpeg: "image/jpeg",
webp: "image/webp",
gif: "image/gif",
};

export interface LoadedImage {
bytes: Buffer<ArrayBuffer>;
base64: string;
mimeType: string;
dataUri: string;
fileName: string;
}

/** Larger than any provider accepts inline; a data URI past it only fails remotely. */
/** Larger than any provider accepts inline; an image past it only fails remotely. */
const MAX_IMAGE_BYTES = 50 * 1024 * 1024;
/** The types of image an `image.edit` call takes, unless its plugin names its own. */
export const IMAGE_TYPES: readonly string[] = [
"image/png",
"image/jpeg",
"image/webp",
"image/gif",
];

/**
* Read a local image for an `image.edit` call: bytes + base64 + mime
* (from the extension) + a `data:` URI for JSON APIs. Errors carry the
* plugin's name so they point at the right tool.
* Read a local image for an `image.edit` call. What it is, its bytes say,
* never its name, and one that is none of `types` is refused. Errors carry
* the plugin's name so they point at the right tool.
*/
export async function readImageInput(
imagePath: string,
pluginName: string,
): Promise<LoadedImage> {
types: readonly string[] = IMAGE_TYPES,
): Promise<LocalImage> {
if (typeof imagePath !== "string" || imagePath.trim().length === 0) {
throw new Error(`${pluginName}: imagePath is required`);
}
const bytes = await readLocalFile(imagePath, {
return readLocalImage(imagePath, {
subject: `${pluginName}: imagePath`,
maxBytes: MAX_IMAGE_BYTES,
oversize: `${pluginName}: imagePath exceeds ${MAX_IMAGE_BYTES / (1024 * 1024)} MiB`,
types,
});
const ext = extname(imagePath).slice(1).toLowerCase();
const mimeType = EXT_MIME[ext] ?? "image/png";
const base64 = bytes.toString("base64");
return {
bytes,
base64,
mimeType,
dataUri: `data:${mimeType};base64,${base64}`,
fileName: basename(imagePath),
};
}
6 changes: 4 additions & 2 deletions packages/codemode-plugins/fal/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { CodemodePluginAPI } from "@shiftlabs/codemode";
import { type CodemodePluginAPI, imageDataUrl } from "@shiftlabs/codemode";
import * as t from "typebox";
import { mediaDir, readImageInput } from "../../_shared/mediaFile.js";
import { parseSize } from "../../_shared/parseSize.js";
Expand Down Expand Up @@ -183,7 +183,9 @@ export default function fal(rl: CodemodePluginAPI): void {
p.model ?? EDIT_MODEL,
{
prompt: p.prompt,
[key]: key.endsWith("_urls") ? [image.dataUri] : image.dataUri,
[key]: key.endsWith("_urls")
? [imageDataUrl(image)]
: imageDataUrl(image),
},
"images",
);
Expand Down
19 changes: 12 additions & 7 deletions packages/codemode-plugins/googleImage/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import {
type ActionContext,
type CodemodePluginAPI,
credentialJson,
imageBase64,
pathSegment,
} from "@shiftlabs/codemode";
import * as t from "typebox";
Expand All @@ -36,6 +37,10 @@ import {
import { STRICT } from "../../_shared/schemas.js";
import { googleImageCredential } from "./credentials.js";

/** Nano Banana 2.1, the model Google recommends for new work. */
const MODEL = "gemini-nano-banana-2.1";
const MODEL_DESCRIPTION = `Gemini image model ID, e.g. gemini-3.1-flash-lite-image (fastest and cheapest) or gemini-3-pro-image. Defaults to ${MODEL}.`;

/** The model as one path segment before the fixed :generateContent verb. */
function generateContent(
ctx: ActionContext,
Expand Down Expand Up @@ -112,16 +117,15 @@ export default function googleImage(rl: CodemodePluginAPI) {
model: t.Optional(
t.String({
minLength: 1,
description:
"Gemini image model ID. Defaults to gemini-2.5-flash-image.",
description: MODEL_DESCRIPTION,
}),
),
saveDir: t.Optional(t.String({ description: SAVE_DIR_DESCRIPTION })),
},
STRICT,
),
async execute(p, ctx) {
const model = p.model ?? "gemini-2.5-flash-image";
const model = p.model ?? MODEL;
const data = await generateContent(ctx, model, {
contents: [{ parts: [{ text: p.prompt }] }],
generationConfig: { responseModalities: ["IMAGE", "TEXT"] },
Expand All @@ -148,8 +152,7 @@ export default function googleImage(rl: CodemodePluginAPI) {
model: t.Optional(
t.String({
minLength: 1,
description:
"Gemini image model ID. Defaults to gemini-2.5-flash-image.",
description: MODEL_DESCRIPTION,
}),
),
saveDir: t.Optional(t.String({ description: SAVE_DIR_DESCRIPTION })),
Expand All @@ -159,13 +162,15 @@ export default function googleImage(rl: CodemodePluginAPI) {
async execute(p, ctx) {
const img = await readImageInput(p.imagePath, "googleImage");

const model = p.model ?? "gemini-2.5-flash-image";
const model = p.model ?? MODEL;
const data = await generateContent(ctx, model, {
contents: [
{
parts: [
{ text: p.prompt },
{ inlineData: { mimeType: img.mimeType, data: img.base64 } },
{
inlineData: { mimeType: img.mimeType, data: imageBase64(img) },
},
],
},
],
Expand Down
Loading