# Layers -- Agent API > Layers is a browser-based image/video editor. An agent can join the person's > own open Layers over Seance, the Noise Factor collaboration service, and run > Layers' commands in it: add and change layers, paint, select, mask, and look > at the canvas. An agent that drives its own browser can call the same > commands through the in-page `window.LayersAgent` API instead. This file is > the contract for software agents that control Layers. The full contract adds a reference for every command and its arguments: https://layers.noisefactor.io/llms-full.txt Layers is an island. Its document is a stack of layers, not program text, and it shares nothing with other apps. A Layers session joins only Layers, and programs and images do not move between Layers and Noisedeck, Polymorphic, Visualize, HD4, Foundry or Shade. For the roles and control paths of the other Noise Factor products, including Timeline's project-folder CLI and Layers' separate document, start from the platform guide at https://noisefactor.io/llms.txt. ## Connect to the person's Layers Use this route when you can run shell commands. It works with the Layers the person already has open: their composition and their canvas. 1. Ask the person to open https://layers.noisefactor.io, choose **connect agent...** in the File menu, click **Go Online**, then **Copy Prompt**, and paste the prompt to you. The prompt names this file and the session link. (Without that dialog: File, **live collab...**, **Take Online**, then send the link or the six-character code.) 2. Get the agent tool. It needs Node 22.4 or later and nothing else: `curl -fsSLO https://noisedeck.app/agent/seance-agent.mjs` 3. Join: `node seance-agent.mjs join `. It prints the session name (`layers`), its `dialect` (`layers`), its `rev` and the open app tabs. A background process keeps the session joined between commands. | Command | What it does | |---|---| | `node seance-agent.mjs commands` | Lists Layers' commands and their arguments. `[not available remotely]` marks the commands that a session cannot run. | | `node seance-agent.mjs call [JSON]` | Runs one command in the person's tab and prints its envelope, for example `call addLayer '{"kind":"effect","effectId":"synth/gradient"}'`. | | `node seance-agent.mjs look [--size N] [--format png\|jpg] [--out FILE]` | Saves an image of the person's canvas (`getThumbnail`). Its path is `result.envelope.result.image.path`; open the file with your image tool. | | `node seance-agent.mjs status` | Lists the joined sessions. For a Layers session, `rev` counts the changes to its document. | | `node seance-agent.mjs wait [--since REV] [--timeout S]` | Waits until the person changes the composition. With `--since`, a change after that `rev` from `status` returns at once. | | `node seance-agent.mjs image-put ` | Adds a PNG, JPEG, GIF or WebP file to the session. `result.ref` is its `image:`. | | `node seance-agent.mjs image-get [--out FILE]` | Saves an image that the session holds to a file. | | `node seance-agent.mjs leave` / `stop` | Leaves the session / stops the background process. | Every command prints JSON, except `commands`, which prints text (`--json` gives JSON). The exit code is 0 for success, 1 when Layers refused the command (read `result.envelope.error.code`), and 2 when the tool could not run it (read `error.code`; the codes are listed below). The tool leaves `state` out of the envelopes that it prints; `--state` keeps it. `node seance-agent.mjs help` lists every option. `program`, `set` and `validate` do not apply to Layers, which has no program text: `program` answers `NO_DOCUMENT`, and `set` and `validate` answer `NOT_FOUND_COMMAND`. `transfer` to or from a Layers session answers `ISLAND`. To follow the person: read `rev` from `status`, do your work, then run `wait --since `. It returns when the person changes the composition. Your own commands do not count as the person's changes. If the person uses the app while one of your commands runs, `wait` counts that command's change as theirs too. Read the composition again before each edit. How it works, so you can explain it to the person: - The tool joins the session as an anonymous participant, which the person sees join. It runs commands in the tab that took the composition online, through the session, with the same checks as the in-page API. The changes appear in the person's layer stack, and the person can undo them. A tab that joined the session from its link does not answer, even one that becomes the session's owner after the person's tab leaves. After the person reloads their tab, it answers again (a copy of it that the browser duplicates answers too). - Everyone in the session receives every answer, and anyone who can edit the session can send commands to that tab. So nothing that the person keeps in this browser is reachable through a session: saved projects (`getProjectInfo`, `listProjects`, `openProject`, `saveProject`, `saveProjectAs`, `deleteProject`), settings and the foreground color (`getSettings`, `setSettings`, `getForegroundColor`, `setForegroundColor`), fonts (`listInstalledFonts`, `installFontBundle`), exports and their jobs (`exportImage`, `exportVideo`, `releaseExport`, `getJob`, `waitForJob`, `cancelJob`), recovery copies (`listRecoveryCopies`, `restoreRecoveryCopy`, `discardRecoveryCopy`), the session itself (`takeOnline`, `joinSession`, `goOffline`) and exact pixels (`getRasterRegion`). `newProject` would also take the session offline. These commands answer `REMOTE_UNAVAILABLE`, and `commands` marks them. Suggest that the person goes offline (File, **stop live collab**, then **Go Offline**) when you are done. - In each answer, `state` leaves out `foreground`, `jobs`, `recentExports` and `settings`. `state.project` keeps only `canUndo` and `canRedo`, and the `media` of a media layer has no `filename`. - `undo` and `redo` stay within the changes made since the session went online. The states from before it can hold the person's offline work, including images that never went into the session. A step into them answers `CONFLICT_BEFORE_SESSION`. - Images travel as bytes. `look`, and `call` with `getThumbnail`, `getCanvasImageBytes` or `getLayerThumbnail`, add the image to the session as its own bytes. In place of base64 `bytes`, the result has `image: { id, mimeType, bytes }`, where `id` is the SHA-256 of the image and `bytes` is its size. The tool saves the image as a file and adds its `path`. - To add an image to the composition, add the file with `image-put`, then name it as `image:`: `call pasteImageFromBytes '{"source":{"kind":"url","value":"image:"}}'` (or `addLayer` with `kind: "media"`, `mediaType: "image"` and the same `source`). A request that carries an image as base64 text answers `IMAGE_AS_TEXT`. A request that names media by any other link answers `OUTSIDE_LINK`, because the person's browser would fetch it. - A session holds at most 32 images, and the composition's own images and masks need room too. The tab takes at most 16 images in ten minutes; past that, image commands answer `IMAGE_LIMIT` with `details.retryAfter` in seconds. Look when the composition has changed, not in a loop. - A session cannot hold video layers. Agent tool errors (exit code 2, `error.code`): - `NO_SESSION`: no session is joined, or more than one and none was named. - `UNKNOWN_SESSION`, `SESSION_LOCKED`, `REFUSED`: the session code is wrong or expired, the session is locked, or the session refused the join. - `NO_APP_TAB`: the tab that took the session online did not answer. Ask the person to keep it open, or to go online again and send the new code. - `TIMEOUT`: the tab did not answer in time. Check `status`, then try again. - `READONLY`: the session lets this agent only watch: `wait` and `status` work, and every app command, `commands` and `look` included, is refused. Ask the person to allow guests to edit. - `SESSION_CLOSED`, `SESSION_REFUSED`: the connection closed, or the session server refused a request (the message says why). - `ISLAND`: a `transfer` to or from a Layers session. Layers shares nothing with other apps. - `IMAGE_FAILED`, `NO_DOCUMENT`, `USAGE`, `INVALID_JSON`: an image transfer failed, a document is missing, or the command line was wrong. - `CONNECT_FAILED`, `RATE_LIMITED`: `join` could not reach the session server, or the server is limiting joins from this address. Wait a minute, then join again. - `INVALID_IMAGE`, `BAD_RESPONSE`: an image id is malformed, or the app sent an answer that the tool could not read. - `DAEMON_FAILED`, `INTERNAL_ERROR`: the tool's background process did not start, or the tool failed. If it happens again, run `stop` and join again. - A file that the tool cannot read gives the system's code, such as `ENOENT`. ## Control Layers in a browser you drive Use this route when you control a browser yourself. Its API exists only in the page. You need a browser tool that can run JavaScript in a page. A tool that only fetches HTML cannot use Layers. 1. Open https://layers.noisefactor.io in your browser tool. 2. Run JavaScript in the page. Wait for `window.LayersAgent.ready`. 3. Call commands. Every command is an async method that returns an envelope. ```js await window.LayersAgent.ready // resolves once bootstrap is done const v = window.LayersAgent.version // current API version (e.g. "1.0") const env = await window.LayersAgent.getState({}) // any command ``` The document is in that page. To keep your work, call `saveProject({ name })`. `saveProject` writes the project to the storage of that browser. --- ## Keep results small Your browser tool sends each script result back to you. A large result uses a large part of your context. - Return only the fields that you need from each script. - Every envelope includes the full `state`. Remove it when you do not need it. - `exportImage` always returns the full image as base64 in `result.bytes`. Remove `bytes` before you return the envelope, unless you need the bytes. To get only the bytes, without a download, pass `triggerDownload: false`. - To look at the canvas, call `getThumbnail`. By default, its longest side is 256 pixels. - The agent tool saves images as files and prints only their paths. Open a file with your image tool; do not print its bytes. ```js const env = await LayersAgent.exportImage({ format: 'png' }) // starts the download const { bytes, ...result } = env.result return { ok: env.ok, result } ``` --- ## The envelope Every command response -- success or failure -- has this shape: ```js // success { ok: true, command: "getState", apiVersion: "1.0", result: { /* command-specific */ }, state: { /* full state snapshot */ }, warnings: [{ code: "...", message: "..." }] // optional } // failure { ok: false, command: "addLayer", apiVersion: "1.0", error: { code: "INVALID_ARGS_ENUM", message: "Unknown kind: ...", details: { field: "kind", got: "foo" } }, state: { /* full state snapshot */ } } ``` **Every response includes state, whether the command succeeds or fails.** Read `env.state` after each mutation. A separate `getState` call is unnecessary. --- ## Warnings `env.warnings`, when present on a success envelope, is an array of structured objects (not plain strings): ```js { code: "UNKNOWN_SETTING_KEY", // stable identifier; agents can switch on this key: "foo", // optional; the offending field if applicable message: "unknown setting key: foo (ignored)" // human-readable } ``` The response includes `warnings` only when the array is non-empty. Handle unknown warning codes. New codes may appear without an `apiVersion` change. Examples: - `UNKNOWN_SETTING_KEY` from `setSettings` -- the key was ignored - `THEME_PERSIST_FAILED` from `setSettings` -- localStorage write threw - `PROJECT_STORAGE_ERROR` from `listProjects` -- the storage layer threw an exception. The command returned the available result, usually an empty list. - `SESSION_TAKEN_OFFLINE` from `newProject`/`openProject` -- an online Seance session went offline first. These commands replace the whole composition, which a shared session cannot represent. --- ## State snapshot shape ``` state: { apiVersion, schemaVersion, project: { id, name, isDirty, canUndo, canRedo, canSaveAs }, canvas: { width, height }, view: { zoomMode, tool, selectionTool, maskEditLayerId, maskOverlayLayerId, scrollX, scrollY, scrollMaxX, scrollMaxY, isPlaying, loopDuration }, foreground: { color }, selection: null | { kind, bounds, isEmpty, polygonPoints?, mask? }, layers: [{ id, name, sourceType, visible, opacity, blendMode, locked, transform, media, effect, drawing: { strokeCount, strokeIds, strokeIdsTruncated } | null, children: [{ id, name, effectId, visible, params, mask }], mask }], selectedLayerIds, activeLayerId, jobs: [{ id, kind, status, startedAt, updatedAt, completedAt, progress, result, error }], // most recent 20 recentExports: [{ id, kind, filename, mimeType, sizeBytes, createdAt }], settings: { theme?, exportImage?, exportVideo? }, collaboration: { available, status, sessionId, shareUrl } } ``` Through a session, the state has no `foreground`, `jobs`, `recentExports` or `settings`, `project` is `{ canUndo, canRedo }`, and `media` has no `filename`. `sourceType` is one of `effect | drawing | media | text`. `selection.kind` is `rectangle | oval | lasso | polygon | wand | color-range`. `jobs.status` is `queued | running | succeeded | failed | cancelled`. `mask` on a layer or child effect is null or a summary with `width`, `height`, `coverage`, and `bounds`. A layer mask also has `enabled` and `visible`. Raster selections have the same summary in `selection.mask`. Use `getRasterRegion` for exact pixels in a browser you drive; a session cannot read them. Summaries do not contain pixel arrays. --- ## Tool discovery llms-full.txt lists every command with a description and its arguments. You can also read the same data from the page: ```js // Every public command const commands = Object.keys(window.LayersAgent) .filter(k => typeof window.LayersAgent[k] === 'function' && !k.startsWith('_')) // A one-line description of each command, in groups const { COMMAND_GROUPS } = await import('/js/agent/descriptions.js') // The argument schema of each command that takes arguments const { SCHEMAS } = await import('/js/agent/schemas.js') console.log(SCHEMAS.addLayer) // -> { type:'object', properties:{ kind:{type:'string', enum:[...]}, ... }, required:['kind'] } ``` A command whose `SCHEMAS` entry is null takes no arguments. Skip `_`-prefixed names. They are not public commands. New commands and nested layer, transform, and child property objects reject undeclared keys with `INVALID_ARGS_UNKNOWN`. Most existing command argument roots remain permissive for compatibility; `llms-full.txt` marks closed schemas. Free-form effect parameter and media source objects remain open. `setSettings` keeps its `UNKNOWN_SETTING_KEY` warning for unknown settings. The commands cover these operations: - Create, read, update, and delete layers. Set layer properties and transforms. - Set effect parameters and child effects. - Draw with `paintStroke` and `drawShape`. Read existing strokes with `getDrawingStrokes`. Fill an area with `fillRegion`. Read and paint masks. - Create and modify rectangle, oval, polygon, lasso, wand, and color-range selections. - Manage projects, undo, and redo. - Control the view, foreground, toolbar tool, selection tool, pan, settings, zoom, and playback. - Resize the canvas or image. Adjust levels, contrast, and white balance automatically. - Export images and videos. Install and list fonts. Manage jobs. --- ## Error codes | Code | When | |---|---| | `INVALID_ARGS_TYPE` | wrong type | | `INVALID_ARGS_REQUIRED` | missing required field | | `INVALID_ARGS_RANGE` | number, string length or item count out of range | | `INVALID_ARGS_ENUM` | not in allowed enum | | `INVALID_ARGS_UNKNOWN` | an undeclared field on a strict command (llms-full.txt names them), or an effect parameter that the effect does not declare | | `NOT_FOUND_LAYER` | unknown layer id or child effect id | | `NOT_FOUND_STROKE` | unknown stroke id on a drawing layer (`eraseStroke`) | | `NOT_FOUND_EFFECT` | unknown effect id (from `getEffectDefinition`, `details` includes `didYouMean`) | | `NOT_FOUND_JOB` | unknown job id | | `NOT_FOUND_PROJECT` | unknown project id | | `NOT_FOUND_EXPORT` | `releaseExport` got an id that has no `captureOnly` video URL | | `CONFLICT_BASE_LAYER` | `deleteLayer` or `reorderLayer` tried to change the base layer, or to move a layer to index 0 | | `CONFLICT_DUPLICATE_FAILED` | the app could not duplicate the layer | | `CONFLICT_TOOL_BLOCKED_FOR_TYPE` | the command does not support this layer type (`flipLayer` on a layer that is not media) | | `CONFLICT_NOT_TRANSFORMABLE_LAYER` | the layer has no raster source to transform | | `CONFLICT_NOT_EFFECT_LAYER` | the layer is not an effect layer | | `CONFLICT_NOT_DRAWING_LAYER` | the layer is not a drawing layer | | `CONFLICT_NO_SELECTION` | the command needs an active selection | | `CONFLICT_LAYER_HAS_MASK` | the layer already has a mask | | `CONFLICT_NO_MASK` | the layer has no mask | | `CONFLICT_MEDIA_BLOCKED_ONLINE` | a video layer while a collaboration session is online | | `CONFLICT_PROJECT_REPLACEMENT` | `newProject` or `openProject` did not complete (`details.status` gives the reason) | | `NOT_FOUND_RECOVERY` | a recovery copy id is no longer available | | `CONFLICT_RECOVERY_IN_USE` | another browser tab owns that recovery copy | | `CONFLICT_FEATURE_UNAVAILABLE` | online collaboration is disabled in this build | | `CONFLICT_SESSION_TRANSITION` | taking the project online or joining a session did not complete | | `CONFLICT_JOB_IN_PROGRESS` | a duplicate job is already running (e.g. installFontBundle) | | `JOB_LIMIT_EXCEEDED` | too many active jobs (cap = 20) | | `JOB_CANCELLED` | the job was cancelled (terminal state, not an error per se) | | `RESOURCE_DECODE_FAILED` | base64 / URL fetch / image decode failed, or the online session has no image `image:` | | `RENDER_LAYER_COMPOSITE_FAILED` | the renderer could not isolate the layer (`getLayerThumbnail`) | | `NOT_FOUND_COMMAND` | a session request named a command that Layers does not have | | `REMOTE_UNAVAILABLE` | the command needs the person at the browser, and came through a session | | `CONFLICT_SESSION_ENDED` | the session that sent the command was no longer online in the tab when the command's turn came; the command did not run | | `CONFLICT_BEFORE_SESSION` | through a session, `undo` or `redo` would restore a state from before the session went online | | `IMAGE_LIMIT` | the tab already took 16 images in ten minutes. `details.retryAfter` is in seconds | | `IMAGE_AS_TEXT` | a session request or answer would carry an image as base64 text. Add the image with `image-put` and use `image:` | | `OUTSIDE_LINK` | a session request names media by a link other than `image:` | | `IMAGE_UPLOAD_FAILED` | the tab could not add an image to the session (a session holds up to 32 images of up to 8 MiB each) | | `INTERNAL_ERROR` | unexpected handler throw. Through a session it also means the session rejected a change that the tab already made; read the state before trying again | `details` usually names the field or value that caused the error. Some conflict errors send an empty `details`. From `getEffectDefinition`, `NOT_FOUND_EFFECT` also gives `details.didYouMean`: the 3 closest effect ids by Levenshtein distance. --- ## Jobs (long-running operations) Some commands return immediately with a `jobId` and run in the background: - `installFontBundle` -- downloads ~140 MB font bundle into IndexedDB - `exportVideo` -- frame-by-frame video encode (can take minutes for long clips) Pattern (in-page): ```js const { result: { jobId } } = await LayersAgent.exportVideo({ width: 1024, height: 1024, framerate: 30, duration: 5, format: 'mp4', quality: 'high' }) // Poll const job = (await LayersAgent.getJob({ jobId })).result // { id, kind, status, progress:{phase, current, total, message}, result, error } // Or block const settled = (await LayersAgent.waitForJob({ jobId, timeoutMs: 120000 })).result // settled.status === 'succeeded' | 'failed' | 'cancelled', plus settled.timedOut if applicable // Cancel await LayersAgent.cancelJob({ jobId }) ``` A timeout is not a failure. `waitForJob` then returns `ok: true` and the job with `timedOut: true`. Check `timedOut` before you read `status`. Without `timeoutMs`, or with `timeoutMs: 0`, `waitForJob` waits with no limit. Your browser tool can stop a script that runs too long. For a long job, call `waitForJob` with a short `timeoutMs`. Repeat the call while the result has `timedOut: true`. A settled job has no `timedOut` field. A failed job has `status: 'failed'` and `error: { code, message, details }`. These codes appear in `error.code`: | Code | When | |---|---| | `JOB_FAILED` | the job failed, and no specific code applies | | `VIDEO_EXPORT_ENCODE_FAILED` | the MP4 encoder failed. Try a lower resolution or `format: 'zip'` | | `VIDEO_EXPORT_EMPTY` | the MP4 export produced no video data | | `VIDEO_DURATION_UNAVAILABLE` | a video layer has no finite duration | | `CONFLICT_EXPORT_IN_PROGRESS` | a video export from the editor dialog is running | A cancelled job has `status: 'cancelled'` and `error.code` `JOB_CANCELLED`. `JOB_KINDS` is exported from `/js/agent/jobs.js`: ```js import { JOB_KINDS } from '/js/agent/jobs.js' // JOB_KINDS.INSTALL_FONT_BUNDLE === 'install-font-bundle' // JOB_KINDS.EXPORT_VIDEO === 'export-video' ``` `installFontBundle` passes AbortSignal to the loader's fetch and extraction calls. Cancellation takes effect at chunk or font boundaries. A single font extraction cannot be interrupted. JSZip extracts a variable font of 5+ MB in one call. Cancellation during that call may take several seconds. `exportVideo` checks for cancellation at every frame boundary and before encoder finalization. --- ## Exports & downloads `exportImage` and `exportVideo` both record an entry into `state.recentExports`: ```js { id, kind: 'image'|'video', filename, mimeType, sizeBytes, createdAt } ``` By default, both commands start a browser download. The browser puts the file in its download folder. A downloaded image uses the `filename` of its export entry. Layers names a downloaded video `layers-