> ## Documentation Index
> Fetch the complete documentation index at: https://docs.embededitor.com/llms.txt
> Use this file to discover all available pages before exploring further.

# AI

> Open and close the AI, ask it for an edit in words, stop it and end the conversation, have it compose the annotations in its Annotate mode, remove and generate in an area of the photo, edit the whole photo by words, and take its background off, from code.

`ask` does what the AI's ✦, its selector and its field do: open and close it, choose its mode, put words in the field as its **Examples** do, **Generate** with words and **Stop**, and ends the conversation. `retouch` does what the AI's brush and its buttons do: the mark, **Generate**, **Generate** again and **Remove**, and **Remove Background**. `annotate.create()` and `annotate.recreate()` are the AI's **Annotate** mode: its **Generate**, and its **Generate** with the same words. Each follows [the rules of every command](https://docs.embededitor.com/api-reference/commands/overview.md#how-every-command-behaves), and this page says what the AI adds to them.

The examples call the handle `editor`. See [Get the handle](https://docs.embededitor.com/api-reference/commands/overview.md#get-the-handle).

> [!NOTE]
>
> Full and Trial only. Each command needs the function of yours that does its work, and rejects with `NOT_AVAILABLE` without it:
>
> * [`onAiChooseCommands`](https://docs.embededitor.com/ai/on-ai-choose-commands) for `ask.send()`, `annotate.create()` and `annotate.recreate()`;
> * [`onAiEditImage`](https://docs.embededitor.com/ai/on-ai-edit-image) for `retouch.run()`, `retouch.remove()` and `retouch.more()` (and [`crop.expand()` and `crop.more()`](https://docs.embededitor.com/api-reference/commands/adjust#expand)), and it or `onAiChooseCommands` for `retouch.mark()`, `retouch.moveMark()`, `retouch.removeMark()`, `retouch.erase()`, `retouch.unmark()`, `retouch.selectMark()` and `retouch.setBrush()`; without either there is no mark, and [`read.mark()`](#read-mark) answers `[]`;
> * [`onAiRemoveBackground`](https://docs.embededitor.com/ai/on-ai-remove-background) for `retouch.removeBackground()`;
> * any of your AI functions for `ask.stop()` and `ask.end()`, which stop any of the AI's work, and for `ask.close()`;
> * `onAiChooseCommands`, `onAiEditImage` or `onAiRemoveBackground` for `ask.open()` and `ask.setText()`, and `onAiChooseCommands` while Annotate is open; for `ask.setAction()`, the one the mode runs (`onAiChooseCommands` or `onAiEditImage` for **Edit**, `onAiEditImage` for **Remove Object**, `onAiRemoveBackground` for **Remove Background**, and `onAiChooseCommands` for **Annotate**, with Annotate on); `onAiEditImage` for `ask.setReferenceImage()`.
>
> The commands of the photo's modes (`ask.send()`, `ask.setReferenceImage()` and the retouch commands that open the AI) reject with `NOT_AVAILABLE` while Annotate is open, where the ✦ opens the AI's **Annotate** mode: [`annotate.close()`](https://docs.embededitor.com/api-reference/commands/annotate#open-close) first, or [`ask.setAction()`](#setaction) with a photo's mode, which closes Annotate. `annotate.create()` and `annotate.recreate()` open Annotate first where it is closed.
>
> In the Free and the Lite they reject with `NOT_AVAILABLE` too, `read.mark()` answers `null`, and `commands()` leaves them out.

## How a Request Behaves

A request is `ask.send()`, `annotate.create()` or `annotate.recreate()`: what the person does by writing in the AI's field and tapping **Generate**.

* **The field opens, and the AI's card says what the AI does.** The AI's field opens in the menu, in place of the tools row, in the **Annotate** mode's words for `annotate.create()` and `annotate.recreate()`. While the AI works, the card at the top of the photo quotes the words sent (for `annotate.recreate()`, the words of the request it redoes) and shows the short phrase the model writes before each action, or a phrase of the editor's for the tool it runs ("Looking at the photo…"), with **Stop**, and the photo's edge glows in the colors of the AI's brush. Once the AI is done, the card shows the AI's reply under the words it answers, and the conversation goes on (the **Annotate** mode's field reads **What else to annotate?**, as it does after a request that was stopped).
* **The editor waits.** While the AI works, the photo and the menu take no tap, and Undo, Redo, Reset, Save, Copy and Share are off. The editor takes no input but Close, Escape, the AI's card (its **Stop** and its pill) and the whole Agent panel (**Disconnect** among it); the lit ✦ takes none, and the menu's band rests dimmed until the request ends. Escape stops the request, as **Stop** does; with the reference image's veil or the **Examples** list open, the first Escape folds it, the work going on, and the next one stops the request. A command you call meanwhile waits its turn and runs once the request is done, on its result. `ask.stop()` and `ask.end()` don't wait: they act on the request that holds the queue.
* **Each tool call is a command.** The model calls the editor's commands as its tools (none of a tool you turned off: see [the tools](https://docs.embededitor.com/ai/on-ai-choose-commands.md#the-tools)), one after the other, and each runs as `run` runs it: its change lands on the photo with its motion. A call that fails goes back to the model as its answer, so it can fix it, and never rejects the request.
* **It selects nothing.** What a request makes or changes lands unselected, so the person sees the finished work, not an action bar over it. A selection of the person's stays, unless the request removed that piece. An Undo or a Redo of a request selects nothing it made or removed either: only what the person had selected there, where it still is.
* **It is one undo step.** Everything a request did is one step, stopped halfway too: one `history.undo()` takes all of it back, and one `change` event fires as it ends. A request the AI only answers in words makes no step and fires no event.
* **It plays at most 30 rounds.** A round is one call to your `onAiChooseCommands`. A request still working after the 30th resolves with what it did and the model's last words.
* **The conversation goes on.** The next request goes on in the same conversation, so the model knows what it already did ("make the 2 bigger"). Closing the AI (its lit ✦, Escape, `ask.close()`) keeps it: the conversation ends with `ask.end()` alone, and when another image opens.

It rejects with:

* `AI_FAILED` when your `onAiChooseCommands` rejects, your error as its `cause`, or resolves to something that is no message, or to `tool_calls` that is no list of calls. The AI's card says **Couldn’t Complete the Request** (**Couldn’t Generate the Image** for a `send()` with an `area`), with your error's message under it when your function rejected with an `Error` that has one and isn't one of the editor's own (`EmbedEditorError`), **Try again.** otherwise. What the AI did so far stays, as one undo step, and the conversation keeps it for the next request.
* `NOT_AVAILABLE` when the editor leaves the page, is destroyed or opens another image while the AI works, for a `send()` while Annotate is open, and for a `send()` whose `area` is a `BACKGROUND` before a background was removed. No notice shows.
* `INVALID_COMMAND` for a `text` with no words (`props` `['input.text']`), and for a `send()` whose `area` has nothing of the photo in it, a `MARK` with nothing marked among them (`props` `['input.area']`).

## Ask

```ts theme={"dark"}
ask: {
	close: () => Promise<null>;
	end: () => Promise<null>;
	open: () => Promise<null>;
	send: (input: { area?: AiArea; text: string }) => Promise<{ reply: string }>;
	setAction: (input: { action: 'ANNOTATE' | 'GENERATE' | 'REMOVE_BACKGROUND' | 'REMOVE_OBJECT' }) => Promise<null>;
	setReferenceImage: (input: { referenceImage: string | null }) => Promise<null>;
	setText: (input: { text: string }) => Promise<null>;
	stop: () => Promise<null>;
};
```

### open()

Opens the AI, as a tap on its ✦ beside Annotate's button: the AI of where the person is, out of Annotate on the photo's mode chosen last (the first the selector offers, the first time), and in Annotate on its **Annotate** mode. Its rows take the menu: the tools row and Annotate's button hide while it is open, and its button, lit, stands at the right end of its selector's row: filled in your accent with an ✕ in place of the ✦, as Annotate's button is when on. The conversation, the field's words and the areas marked come back as `close()` left them. A ratio the Aspect section still waits on lands first. It resolves to `null` once the AI is open; already open, it stays as it is. It rejects with `NOT_AVAILABLE` without `onAiChooseCommands`, `onAiEditImage` or `onAiRemoveBackground` (`onAiDetectObjects` alone opens none: its Detect runs in Obfuscate), and while Annotate is open without `onAiChooseCommands`.

### close()

Closes the AI, as a tap on its lit ✦ or Escape outside its field, and loses nothing: it opens again (`open()`, `send()`) with the conversation going on, its field's words and the areas marked (unseen while it is closed) as they were; its last reply or failure leaves its card. The menu comes back where it was as the AI opened, whichever modes were chosen meanwhile: Annotate open where the AI opened in it (open again where a photo's mode closed it), Annotate closed where it opened only for the selector's **Annotate**, and the tool and its Scale or Aspect section as they were. What the AI made stays. Closing never fails: where Annotate can't open again as the AI closes (your `enableAnnotate` is off, or a gesture or a Save is under way), the AI closes and the menu lands on the tools, as a close from them does, and `ask.close()` resolves `null`.

Other commands close the AI on their way somewhere, losing nothing, and go where they were sent: [`menu.select()`](https://docs.embededitor.com/api-reference/commands/menu-read#select), [`menu.toggle()`](https://docs.embededitor.com/api-reference/commands/menu-read#toggle) once its ring's tap lands (with Annotate open, it leaves the **Annotate** mode open), [`menu.openSection()`](https://docs.embededitor.com/api-reference/commands/adjust#opensection), [`annotate.open()` and `annotate.close()`](https://docs.embededitor.com/api-reference/commands/annotate#open-close), [`annotate.select()`](https://docs.embededitor.com/api-reference/commands/annotate#select) and [`annotate.setTool()`](https://docs.embededitor.com/api-reference/commands/annotate#settool) as they open Annotate, and `annotate.setTool()` with the **Annotate** mode open, Annotate staying open. It resolves to `null`; with the AI closed, it changes nothing.

```ts ask-close.ts theme={"dark"}
await editor.ask.open();
await editor.ask.send({ text: 'Make it warmer' });
await editor.ask.close(); // the person goes on editing
await editor.ask.open(); // the conversation, the words and the areas are back
```

### send()

Asks the AI for something in words, as the person writes it in the field and taps **Generate**. The AI does it with the editor's own tools: it hides, crops, sets a filter, adjusts, removes and generates in an area, and, with nothing marked, adds or changes anything in the photo by editing it whole (`retouch_run` with `{ kind: 'ALL' }`, your `onAiEditImage`'s `'EDIT_PHOTO'`): "Furnish this room with contemporary furniture" keeps the room and puts furniture in it. A thing named for removal with nothing marked goes by `retouch_remove` over its box. It never annotates: the model is offered none of Annotate's commands, and [`annotate.create()`](#annotate-create) is the one way to annotate with the AI. The model gets your words as they are.

**text** `string` *required*

What you ask for, in any language. The editor's guide asks the AI to answer, and to write its texts on the photo, in the request's language, or in the editor's `lang` when the request doesn't make it clear.

**area** `AiArea`

The place of the photo the request is about, one of [the areas](#the-area): "remove this" or "put a vase here" about what the person marked. It shows while the request's fill of it works (the whole photo shows none: the photo stays as it is, only its edge glowing) and is written into none of the person's areas (`{ kind: 'MARK' }` is the one the person marked), and the model is told how many areas it is and their boxes in the photo's px after your words, as [`read.mark()`](#read-mark) gives them, with one rule: `retouch_remove` removes what is marked and `retouch_run` generates there, both with `{ kind: 'MARK' }`, so that with `onAiEditImage` it changes exactly the marked pixels, never their boxes. A `RECT` or a `POLYGON` you name is told the same way in words that call nothing marked, as the person marked nothing there: `{ kind: 'MARK' }` stands for that area in the request, and `retouch_remove` removes what is in it. The whole photo and the background are told by their own kind, never as a mark, as the person marked nothing there: the line names the whole photo or the background with its box and offers `retouch_run` with `{ kind: 'ALL' }` or `{ kind: 'BACKGROUND' }` alone, as neither is an object to remove, and a `retouch_remove` of `{ kind: 'MARK' }` there is rejected with `INVALID_COMMAND` (`props` `['input.area']`). An area other than `MARK` is filled once in the request: once its fill lands, `read_mark` gives `[]` and another fill of it in the request (`{ kind: 'MARK' }`, or the whole photo's or the background's own kind) is rejected the same way, so the request never reaches the areas the person marked. A `BACKGROUND` before a background was removed rejects `NOT_AVAILABLE`; an area with nothing of the photo in it, a `MARK` with nothing marked among them, rejects `INVALID_COMMAND`, the field left closed.

It resolves once the AI is done to `{ reply }`, the AI's last words, which the AI's card shows. `ask.stop()`, the card's **Stop** or Escape resolve it at once, with its words so far.

### setAction()

Chooses the AI's mode, as a tap on its selector on the menu's top edge, **Edit** | **Remove Object** | **Remove Background** | **Annotate**, and the rows under it become that mode's:

* `GENERATE`, **Edit**: the field and its button, words over the areas marked, or over the whole photo with nothing marked (through the conversation with `onAiChooseCommands`, else by `retouch.run()` of `ALL`, the photo edited whole), or an image over the areas marked, or over the whole photo with nothing marked, sent with **Generate** (the brush and its size beside and under it);
* `REMOVE_OBJECT`, the brush and **Remove**, which runs [`retouch.remove()`](#remove) of the areas, off until something is marked;
* `REMOVE_BACKGROUND`, **Remove**, which runs [`retouch.removeBackground()`](#removebackground), with no brush and no areas on show (they stay marked for the next mode). With [`enableAiRemoveBackgroundPrompt`](https://docs.embededitor.com/api-reference/props#ai), the field of what to keep and **Remove**; once the background is cut, with `onAiEditImage`, the field of the new background and **Generate**;
* `ANNOTATE`, **Annotate**: the field whose **Generate** composes Annotate's pieces, as [`annotate.create()`](#annotate-create) does. Annotate opens under it where it is closed, as [`annotate.open()`](https://docs.embededitor.com/api-reference/commands/annotate#open-close) opens it, and closes with the AI where it opened only for it (`close()`), the pieces made staying.

**action** `'ANNOTATE' | 'GENERATE' | 'REMOVE_BACKGROUND' | 'REMOVE_OBJECT'` *required*

The mode. Each needs the function of yours it runs: `onAiChooseCommands` or `onAiEditImage` for `GENERATE`, `onAiEditImage` for `REMOVE_OBJECT`, `onAiRemoveBackground` for `REMOVE_BACKGROUND`, and `onAiChooseCommands` for `ANNOTATE`, with Annotate on (`enableAnnotate`). The selector shows the ones yours run, in that order, where they are two or more.

The AI opens on it if it is closed, as `open()` opens it. A photo's mode chosen while Annotate is open closes Annotate first, in the **Annotate** mode or not: the photo's modes never stand over Annotate. The areas marked stay (unseen in **Remove Background** and **Annotate**; `REMOVE_OBJECT` shows them while it is chosen, the ones a **Generate** hid too, so **Remove** is on in front of them), and so do each mode's words (the photo's modes share theirs). The photo's mode chosen lasts while the editor is open, a close and an open of the AI included. It resolves to `null` once the mode shows. It rejects with `NOT_AVAILABLE` for a mode your functions don't run.

### setReferenceImage()

Puts the reference image in the field of **Edit**, as its **Add Image** does, or takes it away, as the ✕ on its thumbnail does: the thumbnail shows in the field's right end, and **Generate** sends the image with the words, or alone. The image fills the whole marked area, so it needs an area marked, and never goes to the whole photo.

**referenceImage** `string | null` *required*

The image's URL (`http(s):`, `data:` or `blob:`, as [`retouch.run()`](#run) takes it), which the editor reads and shrinks to a PNG of at most 2048 px on its longer side, its transparency kept. `null` takes the image away.

An image opens the AI on **Edit** if it is closed, as `open()` opens it, and `null` opens nothing. While the AI works it waits its turn behind the work, as [`setAction()`](#setaction) does, and lands once the work ends (the menu takes no tap meanwhile). It resolves to `null` once the field shows the change. It rejects with `NOT_AVAILABLE` outside **Edit** (another mode chosen, or Annotate open) and without `onAiEditImage`, and with `INVALID_COMMAND` (`props: ['input.referenceImage']`) for an image the editor can't read.

### setText()

Puts words in the AI's field, as a choice in its **Examples** does: the question mark at the field's start opens a short list of what to ask there, and the one chosen takes the place of what the field holds. Nothing is sent, and the field takes no focus, so a phone's keyboard stays down: the field's button sends the words as the person's tap would.

**text** `string` *required*

The words, one line, as the field holds them. `''` empties the field.

The AI of where the person is opens if it is closed, as `open()` opens it: on the photo's mode chosen out of Annotate, on its **Annotate** mode in it. While the AI works it waits its turn behind the work, as [`setAction()`](#setaction) does, and lands once the work ends. It resolves to `null` once the field shows the words. It rejects with `NOT_AVAILABLE` where there is no field to fill: without `onAiChooseCommands`, `onAiEditImage` or `onAiRemoveBackground` (without `onAiChooseCommands` while Annotate is open), and in **Remove Object** or a **Remove Background** with no field (its lone **Remove**); and with `INVALID_COMMAND` (`props: ['input.text']`) for words with a line break.

### stop()

Stops the request under way, as the card's **Stop**: what the AI did so far stays, as one undo step, and `send()` resolves with its words so far. It stops any other work of the AI's too, each command resolving as its own section says: the [retouch commands](#retouch), [`crop.expand()`](https://docs.embededitor.com/api-reference/commands/adjust#expand) which gives the photo back as it was with no undo step, [`crop.more()`](https://docs.embededitor.com/api-reference/commands/adjust#more), which keeps the edit as it was, and [`obfuscate.detect()`](https://docs.embededitor.com/api-reference/commands/obfuscate-marks#detect). It resolves to `null` at once, even while the work holds the queue. With no work under way, it changes nothing, once a gesture the person holds has ended.

### end()

Ends the conversation, yours alone (the person closes the AI with `close()`'s ✦, losing nothing): a request under way stops first, as with `stop()`, and the AI closes with the mark, the AI's card, the reference image and the field's words. Every image a fill landed stays on the photo, a step of the history. The next request starts a new conversation. It resolves to `null` at once while the AI works, even while a request holds the queue, and otherwise once a gesture the person holds has ended.

```ts ask.ts theme={"dark"}
const { reply } = await editor.ask.send({ text: 'Make it black and white' });
const more = await editor.ask.send({ text: 'Take the filter off' }); // the same conversation

await editor.ask.end(); // the next request starts a new one
```

A Stop of your own, for a request you sent:

```ts stop.ts theme={"dark"}
const request = editor.ask.send({ text: 'Blur every face' });

stopButton.addEventListener('click', () => {
	editor.ask.stop(); // what the AI did so far stays, one undo step
});

const { reply } = await request; // its words so far
```

## The Area

```ts theme={"dark"}
type AiArea =
	| { kind: 'ALL' }
	| { kind: 'BACKGROUND' }
	| { kind: 'MARK' }
	| { kind: 'POLYGON'; points: { x: number; y: number }[] }
	| { height: number; kind: 'RECT'; width: number; x: number; y: number };
```

Where the AI works on the photo, by its `kind`. `retouch.run()` and `ask.send()` take any of them, and `retouch.mark()` and `retouch.erase()` the outlines alone. `retouch.remove()` takes `MARK`, `POLYGON` and `RECT`: the whole photo and its background are no object to remove. A model's `retouch_run`, the AI's in a request and an agent's over [MCP](https://docs.embededitor.com/mcp/overview.md), takes `MARK`, `ALL` and `BACKGROUND` alone, and an outline of its own rejects with `INVALID_COMMAND` (`props` `['input.area.kind']`), your function never asked: a box the model picked went to the fill, which redrew what stood in it, where the whole photo's edit keeps the rest. Its `retouch_remove` keeps the outlines, to remove a thing by its box. Each becomes the work's area, shown while its work runs, but for `ALL`, whose edit leaves the photo as it is under the edge's glow alone: `MARK` is the mark the person made, whose areas the work reads and, once it lands, hides (a **Generate**) or takes with it (a **Remove**); any other is an area of your own, which no area of the person's ever gives way to, so the person's areas stay as they were whether the work lands, fails or is stopped. `retouch.run()` and `retouch.remove()` change the area's pixels, and `ask.send()` tells the model how many areas it is and their boxes, with the way to fill them: `retouch_run` of `{ kind: 'MARK' }` changes exactly the marked pixels, never their boxes. Points and rects are in the photo's px, the state's.

The mark is a list of areas: each stroke of the **Brush** (an outline it closes on where it began fills its inside) and each `retouch.mark()` clear of the others is an area of its own, and one that touches areas joins them into one. [`read.mark()`](#read-mark) lists their boxes, in order: the `index` the area commands take.

| `kind` | The place | Where it can't be taken |
| - | - | - |
| `ALL` | The whole photo: `retouch.run()` edits it by the words and the image, what they don't name kept (your function's `'EDIT_PHOTO'`). | `retouch.mark()` and `retouch.remove()` reject with `INVALID_COMMAND`. |
| `BACKGROUND` | What **Remove Background** took away: a fill there is the new background's **Generate**. | Before a background was removed, `NOT_AVAILABLE`; `retouch.mark()` rejects with `INVALID_COMMAND`. |
| `MARK` | The mark on screen, every area of it together, as the **Brush** and `retouch.mark()` made it. | With nothing marked, `INVALID_COMMAND`; `retouch.mark()` rejects with `INVALID_COMMAND`. |
| `POLYGON` | A closed outline of 3 `points` or more. | Nowhere, with some of the photo in it. |
| `RECT` | A rectangle. | Nowhere, with some of the photo in it. |

An area with nothing of the photo in it rejects with `INVALID_COMMAND` (`props` `['input.area']`), the editor as it was. `retouch.mark()` and `retouch.erase()` take an outline only where it fills half or more of some pixel of the photo, a pixel the fill would keep, the same on every photo and at any size: a rect 1 px wide and 0.55 px tall is taken inside one row and one column of pixels, and rejects where it falls across two rows and two columns, as at x 400.18 and y 300.5 (0.41 of the pixel it fills most), though across two columns in one row, as at x 400.05, it fills 0.52 and is taken; a rect 1000 px long and 0.4 px tall rejects. The share is the outline's exact geometry, the same in every browser. A browser's own fill can part from it near a half: Chromium and Firefox fill a `POLYGON` reading each pixel at four heights, so for an ordinary outline, within about a quarter of a pixel either side of a half, their fill may keep a pixel the rule didn't take, or none of an outline it took (one drawn of finer strands can part further); their `RECT`, and every fill of Safari's, agree, but for exactly a half, which Chromium and Firefox keep and Safari doesn't. A `POLYGON` fills as a canvas fills it (nonzero winding), so one whose edges cross, as a box's corners listed in Z order, fills each of its loops. `retouch.run()`, `retouch.remove()` and `ask.send()` take any area a canvas draws something of on the photo, as they always have; one too thin for the fill to keep a pixel of rejects with `AI_FAILED`, the model having changed nothing in it. Every coordinate of an area (`retouch.mark()`, `retouch.erase()`, `retouch.run()`, `retouch.remove()` and `ask.send()`), a `RECT`'s side, and `retouch.moveMark()`'s `x` and `y` stay within 1,000,000,000 either way; past that the command rejects with `INVALID_COMMAND`, `props` naming it. No other command is held to it.

## Retouch

```ts theme={"dark"}
retouch: {
	erase: (input: { area: Extract<AiArea, { kind: 'POLYGON' | 'RECT' }> }) => Promise<null>;
	mark: (input: { area: Extract<AiArea, { kind: 'POLYGON' | 'RECT' }> }) => Promise<{ index: number }>;
	more: (input: { id: string; prompt?: string }) => Promise<{ id: string | null }>;
	moveMark: (input: { index: number; x: number; y: number }) => Promise<null>;
	remove: (input: { area: Extract<AiArea, { kind: 'MARK' | 'POLYGON' | 'RECT' }> }) => Promise<{ id: string | null }>;
	removeBackground: (input?: { prompt?: string }) => Promise<{ id: string | null }>;
	removeMark: (input: { index: number }) => Promise<null>;
	run: (input: { area: AiArea; prompt?: string; referenceImage?: string | null }) => Promise<{ id: string | null }>;
	selectMark: (input: { index: number | null }) => Promise<null>;
	setBrush: (input: { mode?: 'BRUSH' | 'ERASER'; size?: number }) => Promise<null>;
	unmark: () => Promise<null>;
};
```

What the AI's brush and its buttons do, on the same path as the person's taps. `run()`, `remove()` and `more()` call your [`onAiEditImage`](https://docs.embededitor.com/ai/on-ai-edit-image), and `removeBackground()` your [`onAiRemoveBackground`](https://docs.embededitor.com/ai/on-ai-remove-background).

* **The card says what the AI does.** While your function works, the AI's field opens and the AI's card at the top of the photo says what it does (**Removing…** for `remove()`, **Generating…** for `run()`, **Removing the background…**), under the words asked, with its **Stop**, the photo's edge glows in the colors of the AI's brush, and a fill's mark glows on the photo; a second line under it says the call takes longer than usual once it runs 50 seconds. The editor takes no input meanwhile but what a request leaves live (above): Close, Escape, the AI's card (its **Stop** and its pill) and the whole Agent panel (**Disconnect** among it); Escape stops, as **Stop** does.
* **A stop leaves the photo as it was.** `ask.stop()`, **Stop** or Escape resolve the command at once: `run()`, `remove()`, `more()` and `removeBackground()` with `{ id: null }`, the person's areas as they were. Your function's `signal` aborts.
* **One undo step.** A fill, a cut and a **Generate** asked again are one step each, and fire one `change`: `history.undo()` and `history.redo()` walk through them, one image your function gave each. Marking (adding, moving, erasing and deleting an area) makes none.
* **Inside a request, part of it.** When the model calls `retouch_run`, `retouch_remove` or `retouch_remove_background` as its tool, in an `ask.send()`, the work is part of that request and its undo step, and its failure goes back to the model as its tool's answer, with nothing on the card. Its `retouch_run` takes no outline of its own ([the areas](#the-area)): with nothing marked it edits the whole photo, `{ kind: 'ALL' }`.
* **Pixels, not the state.** What your functions give back becomes part of the photo, never of the state a host keeps: the state `read.state()`, `change` and `save` give holds none of it. Save's `src` holds it: see [Saved State](https://docs.embededitor.com/saving/saved-state.md#with-the-ai).
* **A failure keeps the photo as it was.** When your function rejects outside a request, the AI's card says **Couldn’t Generate the Image** (**Couldn’t Remove the Object** for `remove()`) or **Couldn’t Remove the Background**, with your error's message under it when your function rejected with an `Error` that has one and isn't one of the editor's own (`EmbedEditorError`), **Try again.** otherwise, and the command rejects with `AI_FAILED`, your error as its `cause`. When the editor itself fails on the way (an image it can't draw, read or encode), the card says the same title over **Try again.**, and the command rejects with `AI_FAILED`, that error as its `cause`.

### run()

Generates in an area of the photo through your `onAiEditImage`, as **Generate**: the words, or the image, say what to put there (a **Remove** is [`remove()`](#remove)). The area is shown while the work runs (for `ALL`, only the photo's edge glows), and your function gets the operation `'GENERATE_AREA'` (`'GENERATE_BACKGROUND'` for `BACKGROUND`), the piece of the photo around it, its mask, the words and the image: see [What the Editor Sends](https://docs.embededitor.com/ai/on-ai-edit-image.md#what-the-editor-sends). For `ALL`, the photo is edited whole by the words and the image, as **Generate** with nothing marked: "Furnish this room with contemporary furniture" keeps the room and puts furniture in it. Your function gets the operation `'EDIT_PHOTO'`, the whole photo with no mask, the words and the image.

**area** `AiArea` *required*

Where to fill: one of [the areas](#the-area). `{ kind: 'MARK' }` fills every area the person marked, together; `{ kind: 'ALL' }` edits the whole photo.

**prompt** `string` (default: '')

What to put there, in the person's words, trimmed. With `''` there must be a `referenceImage`.

**referenceImage** `string | null` (default: null)

An image that says what to put there, as the field's **Add Image**: a URL (`http(s):`, `data:` or `blob:`). The editor reads it and sends your function a PNG of at most 2048 px on its longer side. With it, the fill is a **Generate**, even with no words. One the editor can't read as an image rejects with `INVALID_COMMAND` (`props` `['input.referenceImage']`), the field and the mark as they were.

Neither words nor an image rejects with `INVALID_COMMAND` (`props` `['input.prompt']`): a fill that asks for nothing is a **Remove**, and [`remove()`](#remove) does it.

The image your function gives lands in the area alone, blended into the photo around it; for `ALL`, whole over the photo. A **Generate** of the person's own mark keeps their areas, hidden, until a stroke or one of the mark's commands shows them again, and `read.mark()` still lists them; with **Remove Object** chosen they stay shown. An area of yours (`ALL`, `BACKGROUND`, a `POLYGON` or a `RECT`, `run()`'s or a model's through `ask.send()`) is shown while its work runs, `ALL` with only the photo's edge glowing, and written into no area of the person's: they stay as they were, whether the work lands, fails or is stopped. Outside the area, the photo stays as it was, every pixel. It lands as one undo step, and [`more()`](#more) asks for another in its place. An image that changed nothing (its pixels in the area less than 1 in 255 further, on average, from the piece it was sent than its pixels outside the area: see [onAiEditImage](https://docs.embededitor.com/ai/on-ai-edit-image.md)) lands nothing: the AI's card says **Nothing Changed** and `run()` rejects with `AI_FAILED`.

**id** `string | null`

The id of its edit: `'r1'`, `'r2'`… in the order the editor made them, each image an edit of its own. `null` when it was stopped.

It rejects with `NOT_AVAILABLE` for a `BACKGROUND` area before a background was removed, `INVALID_COMMAND` for neither words nor an image, for an area with nothing of the photo in it and for a `referenceImage` the editor can't read, and `AI_FAILED` when your function rejects (your error its `cause`), or resolves to anything but one image (a list of them too, or a `Blob` the browser can't read as an image) or to one that changed nothing in the area (always, where the area is too thin to mark a pixel of the photo), or when the editor fails on the way (an image it can't draw, read or encode), that error its `cause`. The person's areas stay, for another go.

### more()

Asks your `onAiEditImage` again for a **Generate** on the photo, as **Generate** over an area that holds one: the edit `id` (`run()`'s), over its own piece of the photo and its mask, with the words `prompt`, or its own with none, and its own image. The AI's card says it generates, with **Stop**. The image it gives lands on the photo in that edit's place, as one undo step (`history.undo()` brings the edit before it back), and the person's areas hide while it shows, as `run()`'s do: it is what **Generate** pressed again over the same areas runs. It resolves to `{ id }`, the new edit's, as `run()` does; `ask.stop()` resolves it with `{ id: null }`, the photo as it was.

**id** `string` *required*

The edit to ask again: a **Generate**'s on the photo on screen (`run()`'s `id`).

**prompt** `string`

What to put there now, trimmed. Without it, the edit's own words.

It rejects with `NOT_FOUND` for an edit the photo on screen doesn't hold (an Undo took it off, or the memory limit drew its image into the photo: see [`onAiEditImage`](https://docs.embededitor.com/ai/on-ai-edit-image#what-it-gives-back)), an **Expand**'s (an [**Expand**](https://docs.embededitor.com/api-reference/commands/adjust.md#expand)'s is [`crop.more()`](https://docs.embededitor.com/api-reference/commands/adjust#more)'s), a **Remove**'s and one an Expand again cut; with `INVALID_COMMAND` where it would ask with neither words nor an image (`props` `['input.prompt']`); and with `AI_FAILED` as `run()` does, the photo as it was.

```ts retouch.ts theme={"dark"}
await editor.retouch.mark({ area: { kind: 'RECT', x: 40, y: 40, width: 80, height: 60 } }); // a rectangle, in the photo's px
await editor.retouch.remove({ area: { kind: 'MARK' } }); // Remove: no words, one undo step

const { id } = await editor.retouch.run({
	area: { kind: 'RECT', x: 220, y: 120, width: 100, height: 100 },
	prompt: 'a small glass vase with red roses'
}); // the vase, one undo step

if (id) {
	await editor.retouch.more({ id, prompt: 'a tall glass vase with tulips' }); // the tulips in its place, one undo step more
}

await editor.history.undo(); // the vase with red roses back on the photo
```

### mark()

Adds an outline to the AI's mark, its inside filled, as a closed **Brush** outline's is: a `POLYGON` or a `RECT`. Clear of every area, it is an area of its own, the last; where it touches areas (or comes within 5 px of them on the screen, the editor's view at rest in the tool open), it joins them into the first of them. The area it made or joined is selected, and the areas show, a **Generate**'s hidden ones too. The AI's field opens, where the brush shows (on **Edit** where **Remove Background**, which has no brush, was the mode, as a tap on the selector chooses it), and the AI's last reply leaves its card. No undo step: the mark is no edit. It resolves to `{ index }`, the area's place in [`read.mark()`](#read-mark)'s list. It rejects with `INVALID_COMMAND` for `MARK`, `ALL` and `BACKGROUND` (`props` `['input.area.kind']`: its schema takes the two outlines alone), and for an outline that fills less than half of every pixel of the photo (`['input.area']`), and for one with nothing on the photo's window as the crop shows it (`['input.area']`), as a **Brush** stroke there marks nothing (one partly on it is taken whole), the editor as it was; and with `NOT_AVAILABLE` while the editor has no size on the page (inside an element with `display: none`, or before its first layout), with no screen to count the 5 px on.

```ts areas.ts theme={"dark"}
const { index } = await editor.retouch.mark({ area: { kind: 'RECT', x: 40, y: 40, width: 80, height: 60 } }); // 0
await editor.retouch.mark({ area: { kind: 'RECT', x: 200, y: 160, width: 60, height: 40 } }); // clear of it: 1
await editor.retouch.moveMark({ index, x: 60, y: 50 }); // its box's top-left there
await editor.retouch.erase({ area: { kind: 'RECT', x: 190, y: 150, width: 80, height: 60 } }); // all of the second: it goes

const boxes = editor.read.mark(); // the first area's alone, moved
```

### moveMark()

Moves the area `index` whole, as its **Move**: its box's top-left corner (as `read.mark()` gives it, the whole area's, past the photo's edges too) goes to `x`, `y` in the photo's px, as far as a handle's worth of it (17.5 px on the screen) stays on the photo's window, as an Annotate piece's drag stops (a drag of **Move** stops the area whole at the photo's edge on Move's side). What of it lies off the photo is never filled. The AI's field opens, where the brush shows (on **Edit** where **Remove Background** was the mode, as `mark()` does), the areas show, and the AI's last reply leaves its card. No undo step. It resolves to `null`, and rejects with `NOT_FOUND` for an `index` with no area or for one with nothing on the photo's window, the crop as it shows (`read.mark()` still lists it), with `INVALID_COMMAND` for an `x` or a `y` past 1,000,000,000 either way (`props` `['input.x']`, `['input.y']`), the area where it was, and with `NOT_AVAILABLE` while the editor has no size on the page (inside an element with `display: none`, or before its first layout), with no screen to keep the handle on.

### erase()

Takes a piece off the mark, as the **Eraser** does: a `POLYGON` or a `RECT`, cut from every area it touches. An area it leaves with nothing marked goes, and the areas after it move up a place in the list. The AI's field opens, where the brush shows (on **Edit** where **Remove Background** was the mode, as `mark()` does), the areas show, and the AI's last reply leaves its card. No undo step. It resolves to `null`, and rejects with `INVALID_COMMAND` for `MARK`, `ALL` and `BACKGROUND` (`props` `['input.area.kind']`: its schema takes the two outlines alone), and for an outline that fills less than half of every pixel of the photo (`['input.area']`), and for one with nothing on the photo's window as the crop shows it (`['input.area']`), as an **Eraser** stroke there erases nothing (one partly on it cuts all it touches), the mark as it was.

### removeMark()

Deletes the area `index`, as its **Delete**: the areas after it move up a place in the list. The AI's field opens, where the brush shows (on **Edit** where **Remove Background** was the mode, as `mark()` does), the areas show, and the AI's last reply leaves its card. No undo step. It resolves to `null`, and rejects with `NOT_FOUND` for an `index` with no area or for one with nothing on the photo's window, the crop as it shows (`read.mark()` still lists it).

### selectMark()

Selects the area `index`, as a still press inside it does with the **Brush**: its bar (**Move** and **Delete**) goes onto it, and its **Move**, its **Delete** and the arrow keys act on it, as `moveMark()` and `removeMark()` do. [`read.selection()`](https://docs.embededitor.com/api-reference/commands/menu-read#read) and the `select` event tell it, `{ index, kind: 'MARK' }`. The AI's field opens, where the brush shows (on **Edit** where **Remove Background** was the mode, as `mark()` does), and the areas show, a **Generate**'s hidden ones too. With the **Eraser** chosen (`setBrush()`), the area stays selected and its bar waits for the **Brush**. `null` lets the selection go, as Escape does, and opens nothing. No undo step. It resolves to `null`, and rejects with `NOT_FOUND` for an `index` with no area or for one with nothing on the photo's window, the crop as it shows (`read.mark()` still lists it), which a press there never selects.

### setBrush()

Sets the brush's mode and size, as the **Brush** | **Eraser** capsule and the size's ruler under the AI's field do, for as long as the editor is open: what `input` gives of them, the rest kept. It opens nothing, as [`obfuscate.setLook()`](https://docs.embededitor.com/api-reference/commands/obfuscate-marks) sets a look, and `mark()` and `erase()` take outlines whatever the brush. An empty input changes nothing. No undo step. It resolves to `null`.

**mode** `'BRUSH' | 'ERASER'`

`'BRUSH'`: a stroke paints an area, and a still press inside one selects it. `'ERASER'`: a stroke takes off what it touches, and no area shows its bar.

**size** `number`

The diameter both paint at, in whole CSS px on the screen, 5 to 50 (20 when the editor opens). Any other value rejects with `INVALID_COMMAND` (`props` `['input.size']`).

### unmark()

Clears the AI's mark, every area of it, as the **Eraser** over all of it. No undo step. It resolves to `null`.

### remove()

Removes what an area of the photo holds through your `onAiEditImage`, as **Remove Object**'s **Remove**: your function gets the operation `'ERASE_AREA'`, the piece of the photo around the area and its mask, no words and no image, and fills the area with what surrounds it. The AI's card says **Removing…**, with **Stop**.

**area** `AiArea` *required*

What to remove: `{ kind: 'MARK' }`, every area the person marked together, a `POLYGON` or a `RECT`. `ALL` and `BACKGROUND` reject with `INVALID_COMMAND` (`props` `['input.area.kind']`; the schema `commands()` gives offers the three kinds only): the whole photo and its background are no object to remove. Inside an `ask.send()` about one of them, the model's `{ kind: 'MARK' }` is that area, and rejects with `['input.area']`.

The image your function gives lands in the area alone, as one undo step, which `more()` takes none of. After a `MARK` that worked, every area the person marked goes; after a `POLYGON` or a `RECT`, their areas stay as they were, and so they do where the work fails or is stopped. It resolves to `{ id }` as `run()` does, and rejects as `run()` does, but for the words.

The example under [`more()`](#more) removes a marked rectangle and then generates in another.

### removeBackground()

Takes the photo's background off through your `onAiRemoveBackground`, as **Remove Background**'s **Remove** (with `enableAiRemoveBackgroundPrompt`, its **Remove**). Your function gets a JPEG of the photo with the AI's edits alone, at most 2048 px on its longer side, and the editor keeps only the alpha it gives back, stretched over the photo: see [What the Editor Sends](https://docs.embededitor.com/ai/on-ai-remove-background.md#what-the-editor-sends).

**prompt** `string` (default: '')

What to keep, in words, trimmed: `'the woman and her dog'`. Only with [`enableAiRemoveBackgroundPrompt`](https://docs.embededitor.com/api-reference/props#ai): without it, words reject with `NOT_AVAILABLE`.

The cut is one undo step. Where the photo is transparent it shows over a checkerboard, and Save keeps the transparency in a PNG or a WebP; a JPEG is white there. Then `run()` with `{ kind: 'BACKGROUND' }` is the new background's **Generate**, and so is `ask.send()` with that area, whose model writes the fill's words: in **Remove Background** once the background is cut, the field's **Generate** sends the second in words with `onAiChooseCommands`, as on a mark, and the first otherwise. Either way the new background goes under the subject, its soft edge blended into it.

It resolves to `{ id }`, the cut's id, as `remove()` does. It rejects with `NOT_AVAILABLE` once the background is cut, with `NOT_FOUND` where your function's cut separates almost nothing (less than 0.5 % of its pixels below half alpha, or less than 0.5 % at half or above), the notice saying **Nothing Found**, with `AI_FAILED` when your function rejects (your error its `cause`) or resolves to no image, or when the editor fails on the way (an image it can't draw, read or encode), that error its `cause`, and with `EXPORT_FAILED` when the photo can't be made, the card saying **Couldn’t Remove the Background**.

```ts background.ts theme={"dark"}
await editor.retouch.removeBackground(); // the subject over a checkerboard
await editor.retouch.run({ area: { kind: 'BACKGROUND' }, prompt: 'a sunlit wooden table' }); // the new background's Generate
```

## read.mark()

The areas the person marked on the photo with the AI's **Brush** or with `retouch.mark()`: each area's box, `{ x, y, width, height }` in the photo's px, the state's, in their order, one for each area, the `index` the area commands take. A box is the whole area's: one a move left partly off the photo runs past its edges (`x` or `y` negative, or past its width or height), though only what lies on the photo is filled. `retouch.run()` and `retouch.remove()` with `{ kind: 'MARK' }` work on them all together, and `ask.send()` tells the model how many they are and their boxes. Areas a **Generate** hid are listed too, and so are areas the crop left off the photo's window, which show nothing and no fill takes until the crop widens. It answers at once, as every read: `[]` with nothing marked, which is none yet, the **Eraser** over all of it, or a mark of the photo before an [**Expand**](https://docs.embededitor.com/api-reference/commands/adjust.md#expand), until an Undo brings that photo back; and without `onAiEditImage` and `onAiChooseCommands`, where there is no brush.

The editor's own AI and an agent over [MCP](https://docs.embededitor.com/mcp/overview.md) are offered it as `read_mark`, where there is a brush, and read it when the person speaks of "this" or "here".

## Annotate Mode

```ts theme={"dark"}
create: (input: { text: string }) => Promise<{ ids: string[]; reply: string }>;

recreate: () => Promise<{ ids: string[]; reply: string }>;
```

Both are in the `annotate` group: `editor.annotate.create()` and `editor.annotate.recreate()`. They are the AI's **Annotate** mode: the ✦ opens on it while Annotate is open, and the selector's **Annotate** chooses it, opening Annotate under it. With `enableAnnotate: false` they reject with `NOT_AVAILABLE`.

### annotate.create()

The person gives the content in words, and the AI composes the annotations as an art director: it decides the story, the style, where each piece goes and what each text says. The content can be what to annotate ("number the furniture") or a subject with the facts ("highlight this headset's features to sell it: 40 h battery, foam, folds").

It is the same request as `ask.send()`, in the same conversation, the field open in the **Annotate** mode's words (**What to annotate?**). The model gets your words after one line, which tells it to annotate:

```text theme={"dark"}
Annotate the photo for this request, as the art director: Point out the basil
```

**text** `string` *required*

What to annotate, or the subject and the facts to show, in any language.

It resolves once the AI is done to `{ ids, reply }`:

**ids** `string[]`

The composition's annotations on the photo, earlier ones first. The composition is the pieces the conversation's requests in the **Annotate** mode made, and the edits of them. A piece the person drew or copied is never part of it, even one that takes an id a removal freed.

**reply** `string`

The AI's last words. The editor's guide asks for one short sentence saying what it made.

`ask.stop()` resolves it at once, as it does `send()`.

### annotate.recreate()

**Generate** with the words of the last request, in the **Annotate** mode: the composition's annotations go, each with what it owns (a text the person pinned to one goes with it, as Delete takes it), and the AI composes again for the same request, in another style, on the same conversation. The model gets this line as the request:

```text theme={"dark"}
Make another composition for the same request, in a different style.
```

The removal and the new composition are one undo step, so one `history.undo()` brings the composition before back. The composition it removes is the one on the photo now: a composition `history.undo()` brought back is the one that goes. It resolves to `{ ids, reply }`, as `create()` does. With no composition to redo (no `create()` in this conversation, or one `ask.end()` ended), it rejects with `NOT_FOUND`, before anything opens or your `onAiChooseCommands` is called.

```ts create.ts theme={"dark"}
const { ids, reply } = await editor.annotate.create({ text: 'Point out the basil' });

await editor.annotate.recreate(); // another composition, in a different style
await editor.history.undo(); // the first one back
```

The model never gets `create` or `recreate` as tools. See [the tools](https://docs.embededitor.com/ai/on-ai-choose-commands.md#the-tools).

## Errors

| `code` | When |
| - | - |
| `NOT_AVAILABLE` | No function of yours for the command (see the note at the top), Annotate turned off for `annotate.create()`, `annotate.recreate()` and `ask.setAction()`'s `ANNOTATE`, a `BACKGROUND` area before a background was removed, words for `retouch.removeBackground()` without `enableAiRemoveBackgroundPrompt`, a second `retouch.removeBackground()` once the background is cut, `retouch.mark()` and `retouch.moveMark()` while the editor has no size on the page (inside an element with `display: none`, or before its first layout), the commands of the photo's modes while Annotate is open (`ask.send()`, `ask.setReferenceImage()` and the retouch commands that open the AI), `ask.setReferenceImage()` outside **Edit**, `ask.setText()` where no field shows, or the editor left the page, was destroyed or opened another image while the AI worked. Always in the Free and the Lite. |
| `INVALID_COMMAND` | A `text` with no words; an `area` with nothing of the photo in it (a `MARK` with nothing marked); for `retouch.mark()` and `retouch.erase()`, a `MARK`, `ALL` or `BACKGROUND` (`input.area.kind`), an outline that fills less than half of every pixel of the photo, or one with nothing on the photo's window; for `retouch.moveMark()`, an `x` or a `y` past 1,000,000,000 either way; for `ask.setText()`, words with a line break (`input.text`); for `ask.setReferenceImage()`, an image the editor can't read (`input.referenceImage`); for `retouch.run()`, neither `prompt` nor `referenceImage` (`input.prompt`) and a `referenceImage` the editor can't read as an image; for `retouch.more()`, neither words nor an image to ask with (`input.prompt`); for `retouch.remove()`, an `ALL` or a `BACKGROUND` (`input.area.kind`); inside an `ask.send()` about an area, a `MARK` once the request's fill of it landed, and `retouch.remove()`'s `MARK` where the area is the whole photo or the background (`input.area`). |
| `NOT_FOUND` | `annotate.recreate()` with no composition to redo; `retouch.moveMark()`, `retouch.removeMark()` and `retouch.selectMark()` for an `index` with no area, or with nothing on the photo's window; `retouch.more()` for an edit the photo on screen doesn't hold (an Undo took it off, or the memory limit drew its image into the photo), an **Expand**'s edit (`crop.more()` takes those; it rejects a **Generate**'s the same way), a **Remove**'s or one an Expand again cut; `retouch.removeBackground()` where your function's cut separates almost nothing. |
| `AI_FAILED` | Your function rejected, `cause` your error, or resolved to something its contract doesn't take: from `onAiChooseCommands` no message, or `tool_calls` that is no list of calls; from `onAiEditImage` anything but one image, a list of them too, or one that changed nothing in the mark; from `onAiRemoveBackground` no image. Or the editor failed on the way (an image it couldn't draw, read or encode), `cause` that error. |
| `EXPORT_FAILED` | `retouch.removeBackground()` couldn't make the photo to send. |


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.