Repository navigation
feat(platform): let agents generate images under an opt-in policy - #3811
Merged
Merged
Conversation
Agents get image generation back as a governed, opt-in capability. The policy is a file like every other governance policy: a missing file and `enabled: false` both mean off, and when it is on both pin fields absent mean automatic selection. The pin is all-or-nothing, as for the vision and transcription pins, and may stay in place while the policy is off so turning it back on restores the admin's choice.
The image-generation resolver and its settings picker need to know which models generate images. A live listing's image output modality now tags the entry `image-generation` (chat lists keep skipping it on `outputsMedia`), and OpenRouter's image-only models, which its default listing leaves out, are fetched from `?output_modalities=image` as a supplement: a failed fetch narrows image coverage, never the chat catalog. The static OpenAI catalog gains gpt-image-1 and gpt-image-1-mini with the vendor's text-input, image-input and image-output token prices; the catalog pricing schema grows an optional `imageInputCentsPerMillion` for the image-input rate the vendor prices apart.
Image generation needs two provider dialects, kept as pure data mapping so both are pinned by tests without a paid call. OpenRouter's current documentation describes its dedicated Image API (POST /images with model, prompt, n, aspect_ratio and input_references, answering base64 images and a USD cost) as the way to generate images, and it serves the image-only models its chat completions do not, so that is the OpenRouter wire. OpenAI's images API is the other one: /images/generations as JSON, or /images/edits as multipart form data when reference images ride along, answering base64 images and token counts. Each request asks for one image, since several models serve only n = 1. The bytes decide the stored format and only raster images are accepted, because a deliverable is served back to people and an SVG can carry script. A refusal carried on a 200 reads as the provider refusing.
The model an agent's image comes from is decided in one place, the way the vision and transcription models are. The policy is the switch and is read strictly, so an unreadable or invalid file is named instead of being taken as on or silently as off. When it is on, a pin wins but is never replaced by another model when it stops being servable; otherwise the first model of a short curated list (Gemini 2.5 Flash Image, GPT Image 1 Mini, GPT Image 1, FLUX.2 Pro) that the organization reaches is used. Only OpenAI-format providers with an active API-key or environment default credential take part, their allowlist applies, and automatic selection only uses OpenRouter and OpenAI, whose image APIs were checked against their documentation. A pin may name another compatible provider. The Models settings page reads the same admission, without secrets, through GET /api/app/providers/image-generation-model. Saving the policy refreshes every open session's provider reads. New organizations are seeded with the policy off.
…ient A single generation call against the resolved image model goes through safeFetch with the same private-host policy as every other provider call, so the credential rides the request from the server and never enters a sandbox. A provider refusal comes back as the provider's own sentence, run through the shared secret redaction plus the call's own key, whatever format the credential stores it in. The ledger figure is the provider's reported charge (OpenRouter's USD cost, in cents) or, when a provider reports only tokens (OpenAI), the catalog price of the text-input, image-input and image-output tokens it reported. A call it cannot price books 0 and still counts as a request, so a request cap binds.
Agents working a task or an automation step create images through the same bridge the in-sandbox MCP shim already uses for workspace tools (workspace_tool, then POST /api/tools/execute), so the provider key never enters the container. The tool reads and bounds its arguments (prompt, path, size, count up to 4, up to 4 reference images read from the workspace), then checks that the turn its token serves is still live, re-reads the policy so switching it off stops the next call, and measures the budget of the run's person before any provider call, refusing with the cap's own sentence (shared with the chat lane now). It generates the images concurrently, books every produced image in the usage ledger under the run's person and agent through the same attribution resolver the turn's own spend uses, logs one structured record without the prompt, and stages the files into the turn's delivery box or /agent/workspace, inline or through a transit blob. The token names its turn in a new `turnOp` scope field; the door hands that, never the request body, to the dispatch. An identical call from the same turn within ten minutes collects the first call's images, so an agent whose MCP client gave up waiting can retry without paying twice.
A task run (fresh start and steer restart) and an automation agent step (start and the resume after an answered question) now ask the image model resolver at the moment they mint their session token. Only when the organization's policy is on and a model resolves does the turn get the grant, the op its images are booked and delivered for, and one instruction line naming the tool and the delivery box. Otherwise the tool is absent and the instructions never mention it, so no agent is told about a tool it cannot call. The resolution never fails a turn: an unreadable policy or a missing model leaves the tool out and logs why.
The in-sandbox MCP bridge bounds every platform call at 30 seconds, and an image generation can take a minute or two per image. Long-running workspace tools (generate_image) now get their own five-minute bound, and while such a call runs the bridge reports MCP progress on the caller's progress token, which restarts the timeout of an MCP client on the SDK's defaults (60 seconds, as OpenCode's). Every other call keeps the 30-second bound. The bounds read environment overrides for the bridge's own test, which shrinks them to run in about a second.
Codex gives up on an MCP tool call after 60 seconds unless the server entry says otherwise, which would cut off an image generation the platform is still finishing. The bridge's server entry now sets `tool_timeout_sec` just past the bridge's own longest bound, so the bridge's timeout sentence reaches the agent. Checked against the pinned Codex 0.142.5, which parses the override (`codex mcp list --json`). The Codex golden execs are re-frozen for the added pair.
Admins turn image generation on under Settings > Governance > Models, next to the vision model. The section's switch saves at once and keeps the saved model choice; while it is on, an Image model row offers Automatic or any image model the organization's credentials can serve, saved through the page's Save/Discard cluster like the other model sections. The list and the current pick come from the server with the admission a turn applies, so the picker cannot offer a model the tool could not call; an unavailable pin stays visible as a refusal with a repair path, and a malformed saved file can be repaired from the page. Messages ship in English, German and French.
Chat stays retrieval-only and never creates images; agents do, when an admin turns image generation on. The assistant's deliverables rule now names an image among the work it hands to a task instead of attempting it or promising it later.
A managed configuration may declare the image_generation policy like any other governance policy. Its pin now gets the same consistency check the vision and transcription pins get: a declared provider must speak the OpenAI format and, when it declares its catalog, list the pinned model as an image generator.
Agents can create images again, governed by an admin switch, so the docs say where and how in English, German and French. The Models page gains the section that turns it on and picks the model; project agents and the automation agent node say they can create images when it is on; chat says it never creates images and points at a task; policies and limits restores the note that image generation needs cost or request limits and says an image is checked before the image model is called; usage analytics and how usage is counted say where an image appears and whom it counts against; the self-hosted provider reference documents the policy file, the provider calls and what a custom endpoint must declare.
New behaviour ships with its boxes. Governance gains GOV-F38 (off until turned on; the tool appears only then), GOV-F39 (pin a model, kept while off) and GOV-B14 (an unavailable pin refuses and never falls back); the admin-only policy list of GOV-B13 names image_generation. Tasks gains TASK-F48 (an agent creates an image into the deliverables, booked to the run's starter) and TASK-B25 (a reached cap refuses the image, not the run); automations gains AUTO-F54 (an agent node's image lands in its output). The Cost headers count the new boxes, and the automation reference lists the specs that own the rest.
A generate_image call spent on the provider outside every hold the budget admissions count, so racing work could each read the same remaining balance and together pass a nearly reached cap. The turn's op row now records the one generation it has in flight (its admission time, estimated cost and image requests), how many images the turn was admitted for, and what its images cost (migration 0134). The in-flight holds every budget admission reads add a running generation's estimate to its turn's allowance, and count one request per image it may make; a subscription turn, which holds no allowance, holds while a generation runs. A check constraint keeps a hold beside an in-flight mark.
A turn's model spend is capped by the allowance its gateway key is minted with, but generate_image spent outside that key: with no budget rule the check always allowed, so a looping or misled agent could create images until its twelve-hour deadline. Before any provider call, the admission (one transaction under the organization's budget-admission lock) now refuses a second generation while one of the turn's own is in flight, stops at 16 images per turn, measures the estimate (25 cents an image) against what the turn's allowance has left after its live model spend and its earlier images (a subscription turn uses the deployment's default allowance), and checks the budget caps against every hold in flight, the turn's own allowance included. An admitted call holds its estimate; the settle books the real cost and releases the hold in one transaction. The rest of the call path, from the same review: - a reply the provider billed without a usable image is booked, and image rows carry cost and requests, never tokens; - a reference image is at most 4 MB (20 MB a call), read with a byte cap, PNG, JPEG or WebP only, and the request is built once per call; - in the delivery box only a bare file name is accepted, since the box delivers its top level alone; subfolders stay under the workspace; - an identical retry is recognised by its reference images' content too; - a transport failure is told without the network detail, which goes to the log; GPT image models are asked for medium quality, and OpenRouter gets 1:1 for a square image. The per-turn allowance knob moves beside the turn deadline so the admission can read it. A backend:integration lane proves the admission on the real schema, racing calls included.
The tool rides the platform bridge, which only a harness that mounts MCP servers can reach. Pi, Hermes and Cursor declare capabilities.mcp false, yet a turn on them was granted generate_image, bound to its op and told about it in its instructions: a tool it could never call. Both hosts now resolve image generation only for a harness whose YAML declares MCP, on every start path (task start and steer restart, automation start and answered-ask resume); otherwise the grant, the turn reference and the instruction line stay absent.
The Models page said every agent turn gets the image tool; only a runtime with Tale's MCP channel does. It and the provider reference now say how one turn is bounded: 16 images, one generation at a time, and the turn's allowance shared with its model use (a subscription turn uses the deployment's default). The policies page says precisely how an image request is checked: it holds an estimate while it runs, beside what its own run may still spend. Usage analytics notes that image rows carry no tokens and that a billed request without a usable image counts too; the provider reference names the request settings (aspect ratio, medium quality) and the reference-image formats and size.
The image generation row now names what the admission specs own end to end: one generation per turn, the per-turn ceiling and allowance, holds counted by every other admission, racing calls on the real schema (the checkImageGenerationAdmission integration lane), the settle, the delivery-box path rule, the reference-image caps and the MCP gate.
The usage-attribution README still said an agent's image books one row per image and is measured net of every other hold. It books one row per billed request without tokens, and is admitted against every hold in flight, its own turn's allowance included, and against the turn's allowance; the integration lane that proves racing admissions is listed with its unit guard.
This was referenced Sep 29, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Image generation comes back as an agent capability, per the founder's call: project agents working a task and automation agent nodes can create images through a new server-side
generate_imageworkspace tool. It is governed and opt-in: animage_generationgovernance policy (a file, off by default) turns it on and optionally pins a model. Chat stays retrieval-only and gains no tool; the chat assistant now names an image among the deliverables it hands to a task.A review round (commits
51e368a52..5cddeda44) bounded the spend: every call is admitted against the turn's allowance, a per-turn ceiling, one call in flight per turn and the budget caps with holds, before any provider call.How the pieces fit
image_generationinpackages/shared/src/schemas/governance.ts:{enabled, providerSlug?, modelId?}. A missing file orenabled: falsemeans off; both pin fields absent means automatic; the pin is all-or-nothing and may stay while off. It is read strictly, like the transcription pin, so an unreadable or invalid file is named on the settings page and never taken as on. New organizations are seeded withenabled: false; existing ones have no file, which also means off. Saving it tells every open browser session to refresh its provider reads.backend/core/lib/providers/resolve_image_model.tsmirrors the vision/transcription resolvers: pinned (never replaced when it stops being servable), then the first model of a short curated list the org reaches (google/gemini-2.5-flash-image,gpt-image-1-mini,gpt-image-1,black-forest-labs/flux.2-pro, matched across provider spellings), then none. Only OpenAI-format providers with an activeapi-key/envdefault credential take part, their model allowlist applies, and automatic selection only uses OpenRouter and OpenAI. The catalog marks image generators with a newimage-generationtag; OpenRouter's image-only models come from a?output_modalities=imagesupplement listing; the static OpenAI catalog gainsgpt-image-1andgpt-image-1-miniwith their token prices.turnOpand one instruction line only on a harness whose YAML declares MCP (the tool rides the bridge; Pi, Hermes and Cursor have none), while the policy is on and a model resolves. Otherwise the tool is absent and never mentioned; a resolution problem never fails the turn.generate_image {prompt, path?, size?, count? (1-4), inputImages? (up to 4)}rides the existing bridge (workspace_tool→POST /api/tools/execute→node_only/sandbox/workspace_image_tool.ts); the provider key never enters the sandbox. Arguments are bounded; a path in the delivery box must be a bare file name (the box delivers only its top level), subfolders only under/agent/workspace; reference images are PNG, JPEG or WebP, at most 4 MB each (20 MB a call), read with a byte cap. The turn must still be live (itsturnOpcomes from the token row, never the body) and the policy is re-read on every call. An identical call within 10 minutes, same reference bytes included, collects the first call's images (per process by design).backend/domains/sandbox/image-generation.ts, one transaction under the organization's budget-admission lock, before any provider call): refuses a second generation while one of the same turn runs; stops at 16 images per turn; holds 25 cents an image and measures that against what the turn's allowance has left after its live model spend (read from the gateway) and its earlier images, a subscription turn using the deployment's default allowance; checks every budget cap against the booked usage plus every hold in flight, the turn's own allowance included. An admitted call leaves its estimate on the op row as a hold that every other admission (chat, turns, images) counts; the settle books each billed request and releases the hold in one transaction. Migration 0134 adds the op-row columns and a check that a hold only exists beside an in-flight mark.POST <base>/images,n: 1,aspect_ratio1:1/3:2/2:3,input_referencesas data URLs); OpenAI through/images/generations(JSON) or/images/edits(multipart),quality: mediumfor GPT image models. The request is built once per call and sent once per image, throughsafeFetchwith the usual private-host policy and credential resolution. A transport failure is told to the agent without network detail (logged instead). Only raster images are stored; the bytes decide the extension.usage_ledgerrow per billed request (a reply without a usable image included) under the run's starter (__automation__for trigger runs), the run's agent or automation, and its API key; cost is OpenRouter's reported charge or, for OpenAI, the catalog price of the reported tokens; no tokens are booked, per the docs. The refusal for a reached cap reuses the chat lane's sentence.console.info('[image-generation] generated', {...})record per call (model, images, billed requests, bytes, cost, duration), never the prompt.generate_image300 s (other calls keep 30 s) and reports MCP progress; Codex's bridge server getstool_timeout_sec=330.Deviations from the brief, with reasons
modalities: it is the documented way, serves image-only models, takes a count and references, and reportsusage.cost.sizeissquare|landscape|portrait(a pixel size is read by its orientation), because the two APIs spell sizes differently.image_hold_cents,image_hold_requests) that the reservation query adds to the op'sbudget_cents, rather than being added intobudget_cents: the allowance check needs the gateway allowance unchanged, and a subscription turn'sbudget_centsis NULL (writing a figure there would leave a phantom hold after the settle).current_usage, the only spend signal, survives an update), which this change does not do.sessionReadFile, which gains an optional byte cap. The per-turn allowance knob moved next to the turn deadline so the admission can read it.Checklist
bun run checkpasses (format, lint, typecheck, all tests). Not run as one command; its parts were run on the touched workspaces:oxfmt --check, type-aware oxlint on every touched file, platformtsc, the full platform server project (902 files, 12,184 tests) and UI project (514 files, 4,423 tests),packages/shared,services/docs(200), the CLI config suites, the daemon shim test;bunx knipclean.bun run lint:sastpasses (Opengrep): run on the TypeScript files this branch changed, 0 findings (the repo's patterns exclude test files;integration-check.tsis over the scanner's size limit).services/platform/messages/{en,de,fr}.yml(governance.imageGeneration.*); node-CHoverride needed.docs/{en,de,fr}/: Models page (with the per-turn limits and the MCP requirement), project agents, automations concepts, chat basics, policies and limits (how an image request is checked and held), usage analytics (no tokens, billed requests without an image), how usage is counted, and the self-hosted provider reference (policy file, request settings, limits, custom endpoints).Test plan
Automated (all green locally):
packages/shared/src/schemas/governance.test.ts. Resolution:backend/core/lib/providers/resolve_image_model.test.ts; strict file reads:backend/domains/governance/vision-policy-read.test.ts.quality, charges carried on unusable replies, reference formats):image_wire.test.ts; the call (built once, charges, generic transport errors):image_generation.test.ts.workspace_image_tool.test.ts; the byte-capped read:helpers/session_client.test.ts; routing:workspace_tools_bridge.image.test.ts; the door'sturnOp:dispatch-routes.test.ts.backend/domains/sandbox/image-generation.test.ts; the holds query:backend/domains/governance/budget-reservations.test.ts.ITEST_LANES=checkImageGenerationAdmission,checkSandboxGatewayKeyReclaim,checkChatThreadSurface bun run backend:integrationon a fresh throwaway database: 46/46 (two racing calls near a cap: one admitted, one refused; two racing calls of one turn: one told to wait; ceiling, allowance and subscription default; holds before and after the settle; ledger rows with cost, requests and no tokens; the check constraint), and the existing turn-reservation and chat-admission lanes over the changed holds query.agent_run_host.image_generation.test.ts,agent_host.image_generation.test.ts(Pi and Hermes get no tool).image-generation-editor.test.tsx,provider-reads.test.tsx. Bridge timing:tale-connectors-mcp.test.ts, Codex golden execs.bun run lint:manualandcheck-guide.tson the touched suites.Manual boxes: GOV-F38, GOV-F39, GOV-B14, TASK-F48, TASK-B25, AUTO-F54; the admission guards are owned by the specs above (coverage row in
tests/manual/reference/automation.md).Not verified
backend:integrationrun; only the three lanes above ran (a filtered run is not full coverage).services/sandbox-runtime/daemon:file-ops.test.ts(stalled URL deadline) andmain.test.ts(partial exec body) fail on this machine; this change does not touch them.