Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
feat(images): edit_image tool with markup-guided edits for GPT-Image-2.6 (#6210)
Krishna Dobhal2b9fb005497a
diff --git a/docs/image-generation.md b/docs/image-generation.mdindex 20213f1546..c4fef76b05 100644--- a/docs/image-generation.md+++ b/docs/image-generation.md@@ -39,6 +39,15 @@ link from the avatar editor opens it in Simple mode too). Choose:Bots are shown `generate_image` only while the base or the backup has what itneeds, so a bot never spends a turn finding out it cannot make images.+`edit_image` changes an image the bot already has, from a prompt. It takes two+paths in the bot's working folder: the image (PNG, JPEG or WebP, up to 10 MB)+and, optionally, a markup: a transparent PNG of the same size with marks drawn+over the image (circles, arrows, scribbles) that point at where to change. It+calls `/v1/images/edits` and needs a GPT-Image-2.6 model (Sunburst or Flare) on+OpenAI as the base or the backup. A markup that is not a transparent PNG, or not+the image's size, is refused before any request. It counts toward the images per+reply and the daily cap like `generate_image`.+| Provider | Key | Default model | Endpoint || --- | --- | --- | --- || OpenAI | its own, in this section | `gpt-image-2` | `api.openai.com/v1/images/generations` |diff --git a/packages/phone-protocol/src/tool-groups.ts b/packages/phone-protocol/src/tool-groups.tsindex 297b5e5364..a510f56581 100644--- a/packages/phone-protocol/src/tool-groups.ts+++ b/packages/phone-protocol/src/tool-groups.ts@@ -10,7 +10,7 @@ export const TOOL_GROUP_LABELS: Readonly<Record<ToolGroup, string>> = {/** About how many tokens each group's tool definitions add to every request where the workspace has the group. */export const TOOL_GROUP_TOKENS: Readonly<Record<ToolGroup, number>> = {- meetings: 900, data: 1600, pages: 1500, images: 200, email: 1300,+ meetings: 900, data: 1600, pages: 1500, images: 480, email: 1300,};/** The agents server's environment variable that carries `toolsOff`: group ids joined with commas. */diff --git a/server/activity.ts b/server/activity.tsindex f4dff530cb..cd54e7af5a 100644--- a/server/activity.ts+++ b/server/activity.ts@@ -96,6 +96,7 @@ const TEAM_ACTION_KEYS: Record<string, string> = {fill_login: "activity.tool.team.fillLogin",find_tool: "activity.tool.team.findTool",generate_image: "activity.tool.team.generateImage",+ edit_image: "activity.tool.team.editImage",list_bots: "activity.tool.team.listBots",list_room_targets: "activity.tool.team.listRoomTargets",list_rooms: "activity.tool.team.listRooms",diff --git a/server/drivers/agents-catalog-goldens/bridged.profiles.json b/server/drivers/agents-catalog-goldens/bridged.profiles.jsonindex a44af4a6c6..d3bdd6f71a 100644--- a/server/drivers/agents-catalog-goldens/bridged.profiles.json+++ b/server/drivers/agents-catalog-goldens/bridged.profiles.json@@ -472,8 +472,8 @@]},"skills+shared+voice+x+team+images": {- "bytes": 18190,- "sha256": "c2c131f1db2214a9dfc2cfa7304e8d8ee652ce5982f6ff0f74f1d0abaa55978d",+ "bytes": 18202,+ "sha256": "fbb8da4a3580ffc08ffc25512a01a39d596415caa21abeea598ed71ef3ac035e","tools": ["tool_result_read","list_room_targets",@@ -632,8 +632,8 @@]},"default+images": {- "bytes": 17281,- "sha256": "1c7a2353df73c3218338f9375f8112e2b9c64f99e245a1041361e93a6b073396",+ "bytes": 17293,+ "sha256": "57195ecdbb6e346f8530ab92624d35a33975773be9946426a060d05b45085c81","tools": ["tool_result_read","list_room_targets",@@ -655,8 +655,8 @@]},"skills+shared+voice+x+team+images+hosting": {- "bytes": 19392,- "sha256": "ba9309e7562d7d3bfa3f9aa05a32bce5b89313d46f059deac5836b2e03e44e60",+ "bytes": 19404,+ "sha256": "a6cd3d2513dae376d09a45626d7bac0e680c6a97b02c2b9f63f5f7a9f2b6062e","tools": ["tool_result_read","list_room_targets",diff --git a/server/drivers/agents-catalog-goldens/bridged.tools-list.json b/server/drivers/agents-catalog-goldens/bridged.tools-list.jsonindex 36d3abc909..ab1e5b847e 100644--- a/server/drivers/agents-catalog-goldens/bridged.tools-list.json+++ b/server/drivers/agents-catalog-goldens/bridged.tools-list.json@@ -494,7 +494,7 @@},{"name": "find_tool",- "description": "Find an OpenMausBot tool that is not in your tool list. Say what you want to do in a few words, or give the tool's name. Each match comes back with its description and exact input schema; run one with use_tool. Tools reached this way: list_shared_computers, shared_computer, assignment_status, usage_limits, list_threads, close_thread, rename_thread, start_thread, burst, list_models, vm_exec, show_widget, show_html, unpublish_page, create_bot, list_team_setup, list_team_library, propose_team_setup, propose_bot_deletion, manage_room, x_search, research_search, research_endpoint, research_call, decide, extract, generate_image, report_bug, check_app_hosting, retry_thread, memory_log, session_search, trigger_info, trigger, delete_trigger, wait_until, list_waits, cancel_wait, propose_profile, propose_model, propose_team_memory, skills_list, skill_manage, mcp_server, app_settings.",+ "description": "Find an OpenMausBot tool that is not in your tool list. Say what you want to do in a few words, or give the tool's name. Each match comes back with its description and exact input schema; run one with use_tool. Tools reached this way: list_shared_computers, shared_computer, assignment_status, usage_limits, list_threads, close_thread, rename_thread, start_thread, burst, list_models, vm_exec, show_widget, show_html, unpublish_page, create_bot, list_team_setup, list_team_library, propose_team_setup, propose_bot_deletion, manage_room, x_search, research_search, research_endpoint, research_call, decide, extract, edit_image, generate_image, report_bug, check_app_hosting, retry_thread, memory_log, session_search, trigger_info, trigger, delete_trigger, wait_until, list_waits, cancel_wait, propose_profile, propose_model, propose_team_memory, skills_list, skill_manage, mcp_server, app_settings.","inputSchema": {"type": "object","additionalProperties": false,diff --git a/server/drivers/agents-catalog-goldens/full.tools-list.json b/server/drivers/agents-catalog-goldens/full.tools-list.jsonindex a378e1c92d..aec3c4a68b 100644--- a/server/drivers/agents-catalog-goldens/full.tools-list.json+++ b/server/drivers/agents-catalog-goldens/full.tools-list.json@@ -1210,6 +1210,32 @@]}},+ {+ "name": "edit_image",+ "description": "Change an existing image from a text instruction, optionally guided by a markup PNG: marks (circles, arrows, scribbles) drawn on a transparent background at the image's exact size, which point at where to change. Both files are paths in your working folder. The result is attached to your reply when the turn ends. Needs a GPT-Image-2.6 model on OpenAI.",+ "inputSchema": {+ "type": "object",+ "additionalProperties": false,+ "properties": {+ "prompt": {+ "type": "string",+ "description": "What to change, in English. Refer to the marks if there is a markup."+ },+ "image": {+ "type": "string",+ "description": "Path of the PNG, JPEG or WebP to change."+ },+ "markup": {+ "type": "string",+ "description": "Path of a transparent PNG with the marks, the same size as the image."+ }+ },+ "required": [+ "prompt",+ "image"+ ]+ }+ },{"name": "generate_image","description": "Create one image from a text description with the person's image provider; it is attached to your reply when the turn ends, so do not describe or link it again. Write the prompt in English, concrete and visual. Name a provider only when the person asked for that one.",diff --git a/server/drivers/agents-catalog-wire.test.ts b/server/drivers/agents-catalog-wire.test.tsindex 7f25681145..3045b51a26 100644--- a/server/drivers/agents-catalog-wire.test.ts+++ b/server/drivers/agents-catalog-wire.test.ts@@ -113,9 +113,9 @@ const BUDGET_BASELINE: Record<string, number> = {"default+no-computer-pick": 55422,"default+room": 52418,"non-chief+room": 44001,- "skills+shared+voice+x+team+images": 66378,- "default+images": 58612,- "skills+shared+voice+x+team+images+hosting": 68241,+ "skills+shared+voice+x+team+images": 68112,+ "default+images": 59141,+ "skills+shared+voice+x+team+images+hosting": 69975,"default+hosting": 58497,"default+tools-off": 53040,};@@ -277,9 +277,9 @@ describe("agents proxy tools/list golden", () => {}});- it("mounts generate_image only when an image provider is set up, and adds nothing else", () => {+ it("mounts generate_image and edit_image only when an image provider is set up, and adds nothing else", () => {const names = (wire: string) => toolsOf(wire).map((tool) => tool.name);- expect(names(wires["default+images"]!).filter((tool) => tool !== "generate_image")).toEqual(names(wires.default!));+ expect(names(wires["default+images"]!).filter((tool) => tool !== "generate_image" && tool !== "edit_image")).toEqual(names(wires.default!));for (const [name, profile] of Object.entries(PROFILES)) {expect(names(wires[name]!).includes("generate_image"), name).toBe(profile.env.OMB_IMAGE_GENERATION === "1");}diff --git a/server/drivers/agents-image-tools.ts b/server/drivers/agents-image-tools.tsindex 25a71b4b15..b610afaaa9 100644--- a/server/drivers/agents-image-tools.ts+++ b/server/drivers/agents-image-tools.ts@@ -2,10 +2,10 @@ import type { ToolCallContext, ToolCallResult } from "./agents-call.ts";import type { Json } from "./agents-client.ts";export const IMAGE_PROMPT_MAX_CHARS = 4000;-export const IMAGE_TOOL_NAMES: ReadonlySet<string> = new Set(["generate_image"]);+export const IMAGE_TOOL_NAMES: ReadonlySet<string> = new Set(["generate_image", "edit_image"]);-export async function callImageTool(_name: string, args: Json, context: ToolCallContext): Promise<ToolCallResult> {- const { ok, body } = await context.client.apiResponse("/api/internal/images/generate", {+export async function callImageTool(name: string, args: Json, context: ToolCallContext): Promise<ToolCallResult> {+ const { ok, body } = await context.client.apiResponse(name === "edit_image" ? "/api/internal/images/edit" : "/api/internal/images/generate", {method: "POST",body: JSON.stringify({ fromBotId: context.botId, fromThreadId: context.threadId, ...args }),});@@ -13,6 +13,21 @@ export async function callImageTool(_name: string, args: Json, context: ToolCall}export const IMAGE_TOOL_DEFINITIONS = [+ {+ name: "edit_image",+ description:+ "Change an existing image from a text instruction, optionally guided by a markup PNG: marks (circles, arrows, scribbles) drawn on a transparent background at the image's exact size, which point at where to change. Both files are paths in your working folder. The result is attached to your reply when the turn ends. Needs a GPT-Image-2.6 model on OpenAI.",+ inputSchema: {+ type: "object",+ additionalProperties: false,+ properties: {+ prompt: { type: "string", minLength: 1, maxLength: IMAGE_PROMPT_MAX_CHARS, description: "What to change, in English. Refer to the marks if there is a markup." },+ image: { type: "string", minLength: 1, maxLength: 1000, description: "Path of the PNG, JPEG or WebP to change." },+ markup: { type: "string", minLength: 1, maxLength: 1000, description: "Path of a transparent PNG with the marks, the same size as the image." },+ },+ required: ["prompt", "image"],+ },+ },{name: "generate_image",description:diff --git a/server/image-generation.test.ts b/server/image-generation.test.tsindex cb9f896f8c..29a0a611a3 100644--- a/server/image-generation.test.ts+++ b/server/image-generation.test.ts@@ -1,7 +1,7 @@import { describe, expect, it, vi } from "vitest";import { IMAGE_DEFAULT_MODELS } from "../shared/image-generation.ts";-import { generateImage, imageGenerationReady, imageSlots } from "./image-generation.ts";+import { generateImage, imageGenerationReady, imageSlots, markupProblem } from "./image-generation.ts";const PNG = Buffer.from("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNk+A8AAQUBAScY42YAAAAASUVORK5CYII=", "base64");const BOTH = {@@ -79,6 +79,42 @@ describe("animated GIF", () => {});});+describe("image edits", () => {+ const png = (width: number, height: number, colorType: number) => {+ const head = Buffer.alloc(26);+ Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]).copy(head);+ head.writeUInt32BE(width, 16); head.writeUInt32BE(height, 20); head[24] = 8; head[25] = colorType;+ return { bytes: head, mime: "image/png" };+ };+ const cfg = (model: string) => ({ imageGen: { key: "openai-secret", primary: { provider: "openai" as const, model } } });++ it("posts the image and the markup to /images/edits with no generated size", async () => {+ const fetchMock = vi.fn(async () => imageResponse());+ const image = png(64, 64, 2), markup = png(64, 64, 6);+ await generateImage(cfg("gpt-image-2.6-sunburst"), { prompt: "remove the circled cup", edit: { image, markup } }, { fetchImpl: fetchMock });+ const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];+ const body = JSON.parse(String(init.body));+ expect(url).toBe("https://api.openai.com/v1/images/edits");+ expect(body.images).toEqual([{ image_url: `data:image/png;base64,${image.bytes.toString("base64")}` }]);+ expect(body.markup).toEqual({ image_url: `data:image/png;base64,${markup.bytes.toString("base64")}` });+ expect(body).not.toHaveProperty("size");+ });++ it("refuses models that are not GPT-Image-2.6 before any request", async () => {+ const fetchMock = vi.fn(async () => imageResponse());+ await expect(generateImage(cfg("gpt-image-2"), { prompt: "x", edit: { image: png(8, 8, 2) } }, { fetchImpl: fetchMock })).rejects.toThrow(/GPT-Image-2.6/);+ expect(fetchMock).not.toHaveBeenCalled();+ });++ it("explains a markup that cannot be used", () => {+ const image = png(64, 64, 2);+ expect(markupProblem(image, png(64, 64, 6))).toBeNull();+ expect(markupProblem(image, png(64, 64, 2))).toMatch(/transparent/);+ expect(markupProblem(image, png(32, 64, 6))).toMatch(/same size/);+ expect(markupProblem(image, { bytes: Buffer.from("not a png"), mime: "image/png" })).toMatch(/must be a PNG/);+ });+});+describe("provider requests", () => {it("sends a Gemini key only to Google's OpenAI-compatible image route", async () => {const fetchMock = vi.fn<typeof fetch>(async () => imageResponse());diff --git a/server/image-generation.ts b/server/image-generation.tsindex 9bc28a20db..0f9fb3450e 100644--- a/server/image-generation.ts+++ b/server/image-generation.ts@@ -25,12 +25,41 @@ export interface ImageSlot {export type ImageAspect = "1:1" | "16:9" | "9:16";+export interface ImageInput {+ bytes: Buffer;+ mime: string;+}+export interface ImageRequest {prompt: string;aspect?: ImageAspect;draft?: boolean;/** An animated GIF, from a GPT-Image-2.6 model only. */gif?: { frames?: number; frameDurationMs?: number };+ /** Changes `image` instead of making a new one; `markup` is a transparent PNG of marks drawn over it. GPT-Image-2.6 only. */+ edit?: { image: ImageInput; markup?: ImageInput };+}++const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);++function pngInfo(bytes: Buffer): { width: number; height: number; alpha: boolean } | null {+ if (bytes.length < 26 || !bytes.subarray(0, 8).equals(PNG_SIGNATURE)) return null;+ return {+ width: bytes.readUInt32BE(16), height: bytes.readUInt32BE(20),+ alpha: bytes[25] === 4 || bytes[25] === 6 || bytes.includes("tRNS", 0, "latin1"),+ };+}++/** Why the markup cannot go with this image, in words a bot can act on; null when it can. */+export function markupProblem(image: ImageInput, markup: ImageInput): string | null {+ const marks = pngInfo(markup.bytes);+ if (!marks) return "The markup must be a PNG.";+ if (!marks.alpha) return "The markup must be a transparent PNG: the marks drawn on a transparent background, not a flattened copy of the image.";+ const base = pngInfo(image.bytes);+ if (base && (base.width !== marks.width || base.height !== marks.height)) {+ return `The markup is ${marks.width}x${marks.height} but the image is ${base.width}x${base.height}; they must be the same size.`;+ }+ return null;}export interface GeneratedImage {@@ -217,13 +246,22 @@ export async function generateImageWith(const gif = request.gif && {output_format: "gif", ...(frames && { frame_count: frames }), ...(frameDurationMs && { frame_duration_ms: frameDurationMs }),};- const body = { model: slot.model, prompt: request.prompt, ...provider.body(request), ...(complexity && { complexity }), ...gif };+ const { edit } = request;+ if (edit && !gpt26) fail("Editing an image needs a GPT-Image-2.6 model (Sunburst or Flare) on OpenAI", 409, true);+ const { size: _generatedSize, ...params } = provider.body(request);+ const dataUrl = ({ bytes, mime }: ImageInput) => ({ image_url: `data:${mime};base64,${bytes.toString("base64")}` });+ const editFields = edit && { images: [dataUrl(edit.image)], ...(edit.markup && { markup: dataUrl(edit.markup) }) };+ const url = edit ? provider.url(cfg).replace(/\/generations$/, "/edits") : provider.url(cfg);+ const body = {+ model: slot.model, prompt: request.prompt, ...(edit ? params : { ...params, size: _generatedSize }),+ ...(complexity && { complexity }), ...gif, ...editFields,+ };const timeoutSignal = AbortSignal.timeout(timeoutMs);const cancelled = () => cancel?.aborted === true && !timeoutSignal.aborted;const send = async (payload: Record<string, unknown>): Promise<Response> => {try {- return await fetchImpl(provider.url(cfg), {+ return await fetchImpl(url, {method: "POST",headers,body: JSON.stringify(payload),diff --git a/server/index.ts b/server/index.tsindex 804da32de5..9a73e168d4 100644--- a/server/index.ts+++ b/server/index.ts@@ -12931,7 +12931,7 @@ const handleRequest = async (req: IncomingMessage, res: ServerResponse) => {throw Object.assign(new Error(TURN_ENDED_REFUSAL), { status: 401 });}};- const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await cloudComputerResets.internal({ method, path, res, json, sender: internalSender, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await meetingsHost.internal({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, active: () => internalCapabilityIsActive(internalCapability) }) !== PASS || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS) return; const callSignal = turnCallSignals.signal(internalCapability, res); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: callSignal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle, bot: internalSender })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;+ const botFolders = async () => ({ roots: messageFileRootsForThread(internalSender.id, internalCapability.threadId).filter((root) => root !== ATTACHMENTS_DIR), vmWorkspace: (await attachmentVmForTurn(internalCapability))?.workspaceDir ?? null }); if (await lentMcp.route({ method, path, req, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS || await internalToolRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, folders: botFolders }) !== PASS || await waitRoutes({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, ...waitTurnChecks(internalCapability, internalSender) }) !== PASS || await teamMessages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await devsReports.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || (computerAsks && await computerAsks.internal({ method, path, res, json, turn: internalCapability, readBody: readInternalBody }) !== PASS) || await cloudComputerResets.internal({ method, path, res, json, sender: internalSender, threadId: internalCapability.threadId, readBody: readInternalBody }) !== PASS || await meetingsHost.internal({ method, path, res, json, readBody: readInternalBody, bot: internalSender, threadId: internalCapability.threadId, active: () => internalCapabilityIsActive(internalCapability) }) !== PASS || await imageTools.internal({ method, path, res, json, readBody: readInternalBody, folders: botFolders, threadId: internalCapability.threadId, requireActive: requireActiveInternalCapability, personTurn: turnOrigin(internalCapability).kind === "user" || (Boolean(roomRun(internalCapability.generation)?.requestMessageId) && guestDrivenTurns.get(internalCapability.threadId) !== internalCapability.generation) }) !== PASS) return; const callSignal = turnCallSignals.signal(internalCapability, res); if (await publishedPages.internal({ method, path, res, json, botId: internalSender.id, threadId: internalCapability.threadId, readBody: readInternalBody, requireActive: requireActiveInternalCapability, signal: callSignal, folders: botFolders, post: (text, publishedPage, bundle) => { const source = connectorThread(internalSender.id, internalCapability.threadId); return !source ? null : (bundle && publishedPages.show({ threadId: internalCapability.threadId, card: publishedPage, bundle, bot: internalSender })) || store.appendMessage(internalCapability.threadId, { role: "bot", kind: "text", text, publishedPage, ...(source.group ? { from: { botId: internalSender.id, name: internalSender.name, color: internalSender.color } } : {}) }).id; } }) !== PASS) return;const delegatedThisTurn = (taskId: string) => {(internalCapability.delegatedThisTurn ??= new Set()).add(taskId);};diff --git a/server/routes/image-tools.ts b/server/routes/image-tools.tsindex 7af1bcafcb..d9e28a6c9e 100644--- a/server/routes/image-tools.ts+++ b/server/routes/image-tools.ts@@ -1,12 +1,16 @@+import { readFile, stat } from "node:fs/promises";import type { ServerResponse } from "node:http";+import { extname } from "node:path";import { z } from "zod";import { IMAGE_MAX_PER_TURN_DEFAULT, IMAGE_PROVIDERS } from "../../shared/image-generation.ts";import { IMAGE_PROMPT_MAX_CHARS } from "../drivers/agents-image-tools.ts";import {- generateImage, imageGenerationReady, imageProviderName, imageSlots,- type GeneratedImage, type ImageCredentials,+ generateImage, imageGenerationReady, imageProviderName, imageSlots, markupProblem,+ type GeneratedImage, type ImageCredentials, type ImageInput,} from "../image-generation.ts";+import { IMAGE_MAX_BYTES } from "../attachments.ts";+import { botFileSource, PageBundleError, type BotFolders } from "../pages/bundle.ts";import { createImageDailyCap, type ImageDailyCap } from "../image-daily-cap.ts";import type { json } from "../harness/http.ts";import { PASS } from "./table.ts";@@ -28,6 +32,31 @@ const requestSchema = z.object({frameDurationMs: z.number().int().min(20).max(2000).optional(),});+const editSchema = z.object({+ prompt: z.string().trim().min(1).max(IMAGE_PROMPT_MAX_CHARS),+ image: z.string().trim().min(1).max(1000),+ markup: z.string().trim().min(1).max(1000).optional(),+});++const EDIT_IMAGE_TYPES: Record<string, string> = { ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" };++/** A PNG, JPEG or WebP in the bot's own folders, or a sentence saying what is wrong with the path. */+async function readEditImage(file: string, folders: BotFolders): Promise<ImageInput | string> {+ let target: string;+ try {+ target = await botFileSource(file, folders);+ } catch (error) {+ if (!(error instanceof PageBundleError)) throw error;+ return error.status === 403 ? "Only files in your working folder can be read. Save it there first." : `Nothing was found at ${file.slice(0, 200)}.`;+ }+ const mime = EDIT_IMAGE_TYPES[extname(target).toLowerCase()];+ if (!mime) return `${file.slice(0, 200)} is not a PNG, JPEG or WebP image.`;+ const info = await stat(target);+ if (!info.isFile()) return "An image must be a file, not a folder.";+ if (info.size > IMAGE_MAX_BYTES) return `${file.slice(0, 200)} is over ${IMAGE_MAX_BYTES / 1024 / 1024} MB. Make it smaller first.`;+ return { bytes: await readFile(target), mime };+}+export interface ImageTurn {key: string;parked: () => number;@@ -49,7 +78,7 @@ export interface ImageToolDeps {type Outcome = { status: number; body: { text: string } | { error: string } };-export async function generateImageForTurn(raw: unknown, deps: ImageToolDeps): Promise<Outcome> {+export async function generateImageForTurn(raw: unknown, deps: ImageToolDeps, edit?: { image: ImageInput; markup?: ImageInput }): Promise<Outcome> {const parsed = requestSchema.safeParse(raw);if (!parsed.success) {return { status: 400, body: { error: `generate_image takes a prompt (1 to ${IMAGE_PROMPT_MAX_CHARS} characters), an optional aspect (1:1, 16:9 or 9:16) and an optional provider.` } };@@ -81,7 +110,7 @@ export async function generateImageForTurn(raw: unknown, deps: ImageToolDeps): Plet made = false;deps.inFlight.set(turn.key, (deps.inFlight.get(turn.key) ?? 0) + 1);try {- const image = await generateImage(deps.cfg, { prompt, aspect, ...(format && { gif: { frames, frameDurationMs } }) }, { slot, fetchImpl: deps.fetchImpl, signal: deps.signal });+ const image = await generateImage(deps.cfg, { prompt, aspect, ...(format && { gif: { frames, frameDurationMs } }), ...(edit && { edit }) }, { slot, fetchImpl: deps.fetchImpl, signal: deps.signal });made = true;if (!turn.attach({ bytes: image.bytes, mime: image.mime })) return { status: 409, body: { error: IMAGE_MESSAGES.noTurn } };const backup = image.usedFallback ? `, the person's backup image provider${image.baseError ? `, because the base failed: ${image.baseError}` : ""}` : "";@@ -107,6 +136,7 @@ export interface ImageRouteContext {threadId: string;requireActive: () => void;personTurn: boolean;+ folders: BotFolders;}export interface ImageTurnStore {@@ -138,11 +168,23 @@ export function createImageToolRoutes(deps: ImageTurnStore & { config: () => Imaconst daily = createImageDailyCap(deps.dataDir);return {async internal(ctx: ImageRouteContext): Promise<typeof PASS | void> {- if (ctx.method !== "POST" || ctx.path !== "/api/internal/images/generate") return PASS;+ const editing = ctx.path === "/api/internal/images/edit";+ if (ctx.method !== "POST" || (!editing && ctx.path !== "/api/internal/images/generate")) return PASS;const turn = imageTurn(deps, ctx.threadId, ctx.requireActive);const call = new AbortController();ctx.res.once("close", () => { if (!ctx.res.writableEnded) call.abort(); });- const outcome = await generateImageForTurn(await ctx.readBody(), { cfg: deps.config(), personTurn: ctx.personTurn, daily, fetchImpl: deps.fetchImpl, turn, inFlight, signal: call.signal });+ const body = await ctx.readBody();+ let edit: { image: ImageInput; markup?: ImageInput } | undefined;+ if (editing) {+ const parsed = editSchema.safeParse(body);+ if (!parsed.success) return ctx.json(ctx.res, 400, { error: "edit_image takes a prompt, the path of the image to change and, optionally, the path of a transparent PNG of marks drawn over it." });+ const image = await readEditImage(parsed.data.image, ctx.folders);+ const markup = parsed.data.markup ? await readEditImage(parsed.data.markup, ctx.folders) : undefined;+ const problem = typeof image === "string" ? image : typeof markup === "string" ? markup : markup && markupProblem(image, markup);+ if (problem) return ctx.json(ctx.res, 400, { error: problem });+ edit = { image: image as ImageInput, ...(markup && { markup: markup as ImageInput }) };+ }+ const outcome = await generateImageForTurn(editing ? { prompt: (body as { prompt: string }).prompt } : body, { cfg: deps.config(), personTurn: ctx.personTurn, daily, fetchImpl: deps.fetchImpl, turn, inFlight, signal: call.signal }, edit);ctx.json(ctx.res, outcome.status, outcome.body);},};diff --git a/shared/usage-trace.ts b/shared/usage-trace.tsindex 29bf79f73c..380941a4a0 100644--- a/shared/usage-trace.ts+++ b/shared/usage-trace.ts@@ -165,7 +165,7 @@ const BUILT_IN_ICONS: ReadonlyArray<[RegExp, TraceToolIcon]> = [[/^(?:(?:open|start|list|close|retry)_threads?|list_bots|list_rooms|list_room_targets|post_to_room|create_room|manage_room)$/, "bots"],[/^(?:phone|android|adb)(?:_[a-z_]+)?$/, "phone"],[/^(?:todowrite|update_plan|plan|think)$/, "plan"],- [/^(?:generate_image|image_generation|imagegen|create_image)$/, "image"],+ [/^(?:generate_image|edit_image|image_generation|imagegen|create_image)$/, "image"],];/** What a tool call should look like in a trace: an icon, and the app or MCP server it belongs to. */diff --git a/src/locales/de.json b/src/locales/de.jsonindex 7bea238da5..579939d230 100644--- a/src/locales/de.json+++ b/src/locales/de.json@@ -4024,5 +4024,6 @@"imageGen.complexity.help": "Wie detailreich GPT-Image-2.6-Bilder sind. Niedriger ist einfacher und schneller.","imageGen.complexity.low": "Niedrig","imageGen.complexity.medium": "Mittel",- "imageGen.complexity.high": "Hoch"+ "imageGen.complexity.high": "Hoch",+ "activity.tool.team.editImage": "Bild bearbeiten"}diff --git a/src/locales/en.json b/src/locales/en.jsonindex 0696c3f11d..81a7dd3c61 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -9463,6 +9463,7 @@"activity.tool.team.fillLogin": "Fill login","activity.tool.team.findTool": "Find tool","activity.tool.team.generateImage": "Generate image",+ "activity.tool.team.editImage": "Edit image","activity.tool.team.listBots": "List bots","activity.tool.team.listRoomTargets": "List room targets","activity.tool.team.listRooms": "List rooms",diff --git a/src/locales/es.json b/src/locales/es.jsonindex e0ed928dc6..c71face328 100644--- a/src/locales/es.json+++ b/src/locales/es.json@@ -6512,5 +6512,6 @@"imageGen.complexity.help": "Cuánto detalle tienen las imágenes de GPT-Image-2.6. Más bajo es más simple y rápido.","imageGen.complexity.low": "Bajo","imageGen.complexity.medium": "Medio",- "imageGen.complexity.high": "Alto"+ "imageGen.complexity.high": "Alto",+ "activity.tool.team.editImage": "Editar imagen"}diff --git a/src/locales/fr.json b/src/locales/fr.jsonindex 7cb297f943..7ac929faca 100644--- a/src/locales/fr.json+++ b/src/locales/fr.json@@ -3812,5 +3812,6 @@"imageGen.complexity.help": "Le niveau de détail des images GPT-Image-2.6. Plus bas, c'est plus simple et plus rapide.","imageGen.complexity.low": "Faible","imageGen.complexity.medium": "Moyen",- "imageGen.complexity.high": "Élevé"+ "imageGen.complexity.high": "Élevé",+ "activity.tool.team.editImage": "Modifier l'image"}diff --git a/src/locales/hi.json b/src/locales/hi.jsonindex 97a56ab33a..90c248e00f 100644--- a/src/locales/hi.json+++ b/src/locales/hi.json@@ -3666,5 +3666,6 @@"imageGen.complexity.help": "GPT-Image-2.6 की छवियाँ कितनी विस्तृत हों। कम का मतलब सरल और तेज़।","imageGen.complexity.low": "कम","imageGen.complexity.medium": "मध्यम",- "imageGen.complexity.high": "उच्च"+ "imageGen.complexity.high": "उच्च",+ "activity.tool.team.editImage": "छवि संपादित करें"}diff --git a/src/locales/it.json b/src/locales/it.jsonindex 1335ff1bb1..97c686dac6 100644--- a/src/locales/it.json+++ b/src/locales/it.json@@ -7136,5 +7136,6 @@"imageGen.complexity.help": "Quanto sono dettagliate le immagini di GPT-Image-2.6. Più basso è più semplice e veloce.","imageGen.complexity.low": "Basso","imageGen.complexity.medium": "Medio",- "imageGen.complexity.high": "Alto"+ "imageGen.complexity.high": "Alto",+ "activity.tool.team.editImage": "Modifica immagine"}diff --git a/src/locales/ja.json b/src/locales/ja.jsonindex 0bab26b064..26c73cb050 100644--- a/src/locales/ja.json+++ b/src/locales/ja.json@@ -8107,5 +8107,6 @@"imageGen.complexity.help": "GPT-Image-2.6 の画像の詳細さ。低いほどシンプルで高速です。","imageGen.complexity.low": "低","imageGen.complexity.medium": "中",- "imageGen.complexity.high": "高"+ "imageGen.complexity.high": "高",+ "activity.tool.team.editImage": "画像を編集"}diff --git a/src/locales/ko.json b/src/locales/ko.jsonindex ea01af3a86..5bed4918fc 100644--- a/src/locales/ko.json+++ b/src/locales/ko.json@@ -7797,5 +7797,6 @@"imageGen.complexity.help": "GPT-Image-2.6 이미지의 세부 정도입니다. 낮을수록 단순하고 빠릅니다.","imageGen.complexity.low": "낮음","imageGen.complexity.medium": "보통",- "imageGen.complexity.high": "높음"+ "imageGen.complexity.high": "높음",+ "activity.tool.team.editImage": "이미지 편집"}diff --git a/src/locales/pl.json b/src/locales/pl.jsonindex a333b78e4e..78664fdf8e 100644--- a/src/locales/pl.json+++ b/src/locales/pl.json@@ -7276,5 +7276,6 @@"imageGen.complexity.help": "Jak szczegółowe są obrazy GPT-Image-2.6. Niższy poziom jest prostszy i szybszy.","imageGen.complexity.low": "Niski","imageGen.complexity.medium": "Średni",- "imageGen.complexity.high": "Wysoki"+ "imageGen.complexity.high": "Wysoki",+ "activity.tool.team.editImage": "Edytuj obraz"}diff --git a/src/locales/pt-br.json b/src/locales/pt-br.jsonindex aaf3a6f88b..965d799412 100644--- a/src/locales/pt-br.json+++ b/src/locales/pt-br.json@@ -11078,5 +11078,6 @@"imageGen.complexity.help": "Quão detalhadas são as imagens do GPT-Image-2.6. Menor é mais simples e mais rápido.","imageGen.complexity.low": "Baixo","imageGen.complexity.medium": "Médio",- "imageGen.complexity.high": "Alto"+ "imageGen.complexity.high": "Alto",+ "activity.tool.team.editImage": "Editar imagem"}diff --git a/src/locales/ru.json b/src/locales/ru.jsonindex cd25808707..72f00e007a 100644--- a/src/locales/ru.json+++ b/src/locales/ru.json@@ -7330,5 +7330,6 @@"imageGen.complexity.help": "Насколько детализированы изображения GPT-Image-2.6. Ниже — проще и быстрее.","imageGen.complexity.low": "Низкий","imageGen.complexity.medium": "Средний",- "imageGen.complexity.high": "Высокий"+ "imageGen.complexity.high": "Высокий",+ "activity.tool.team.editImage": "Редактировать изображение"}diff --git a/src/locales/tr.json b/src/locales/tr.jsonindex 498e71d4c5..e8314bb818 100644--- a/src/locales/tr.json+++ b/src/locales/tr.json@@ -6012,5 +6012,6 @@"imageGen.complexity.help": "GPT-Image-2.6 görsellerinin ne kadar ayrıntılı olacağı. Düşük daha basit ve daha hızlıdır.","imageGen.complexity.low": "Düşük","imageGen.complexity.medium": "Orta",- "imageGen.complexity.high": "Yüksek"+ "imageGen.complexity.high": "Yüksek",+ "activity.tool.team.editImage": "Görseli düzenle"}diff --git a/src/locales/uk.json b/src/locales/uk.jsonindex ad6b674d43..16ce810ed2 100644--- a/src/locales/uk.json+++ b/src/locales/uk.json@@ -4087,5 +4087,6 @@"imageGen.complexity.help": "Наскільки детальними є зображення GPT-Image-2.6. Нижчий рівень простіший і швидший.","imageGen.complexity.low": "Низький","imageGen.complexity.medium": "Середній",- "imageGen.complexity.high": "Високий"+ "imageGen.complexity.high": "Високий",+ "activity.tool.team.editImage": "Редагувати зображення"}diff --git a/src/locales/vi.json b/src/locales/vi.jsonindex c19c3b7ac6..2fe7ca8986 100644--- a/src/locales/vi.json+++ b/src/locales/vi.json@@ -6012,5 +6012,6 @@"imageGen.complexity.help": "Mức độ chi tiết của ảnh GPT-Image-2.6. Thấp hơn thì đơn giản và nhanh hơn.","imageGen.complexity.low": "Thấp","imageGen.complexity.medium": "Trung bình",- "imageGen.complexity.high": "Cao"+ "imageGen.complexity.high": "Cao",+ "activity.tool.team.editImage": "Chỉnh sửa ảnh"}diff --git a/src/locales/zh-tw.json b/src/locales/zh-tw.jsonindex 29168825ee..d103cb8aea 100644--- a/src/locales/zh-tw.json+++ b/src/locales/zh-tw.json@@ -10361,5 +10361,6 @@"imageGen.complexity.help": "GPT-Image-2.6 圖片的細節程度。越低越簡單、越快。","imageGen.complexity.low": "低","imageGen.complexity.medium": "中",- "imageGen.complexity.high": "高"+ "imageGen.complexity.high": "高",+ "activity.tool.team.editImage": "編輯圖片"}diff --git a/src/locales/zh.json b/src/locales/zh.jsonindex d64306eac4..70deb7c8ed 100644--- a/src/locales/zh.json+++ b/src/locales/zh.json@@ -10257,5 +10257,6 @@"imageGen.complexity.help": "GPT-Image-2.6 图片的细节程度。越低越简单、越快。","imageGen.complexity.low": "低","imageGen.complexity.medium": "中",- "imageGen.complexity.high": "高"+ "imageGen.complexity.high": "高",+ "activity.tool.team.editImage": "编辑图片"}