Skip to content

feat(platform): let agents generate images under an opt-in policy - #3811

Merged
yannickmonney merged 20 commits into
mainfrom
feat/agent-image-generation
Sep 29, 2026
Merged

yannickmonney merged 20 commits into
mainfrom
feat/agent-image-generation

Conversation

@yannickmonney

@yannickmonney yannickmonney commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

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_image workspace tool. It is governed and opt-in: an image_generation governance 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

  • Policy. image_generation in packages/shared/src/schemas/governance.ts: {enabled, providerSlug?, modelId?}. A missing file or enabled: false means 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 with enabled: false; existing ones have no file, which also means off. Saving it tells every open browser session to refresh its provider reads.
  • Resolution. backend/core/lib/providers/resolve_image_model.ts mirrors 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 active api-key/env default credential take part, their model allowlist applies, and automatic selection only uses OpenRouter and OpenAI. The catalog marks image generators with a new image-generation tag; OpenRouter's image-only models come from a ?output_modalities=image supplement listing; the static OpenAI catalog gains gpt-image-1 and gpt-image-1-mini with their token prices.
  • Offering. The task host (fresh start and steer restart) and the automation host (start and answered-ask resume) grant the tool, its turnOp and 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.
  • Tool. 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 (its turnOp comes 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).
  • Admission and settle (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.
  • Providers. OpenRouter through its Image API (POST <base>/images, n: 1, aspect_ratio 1:1/3:2/2:3, input_references as data URLs); OpenAI through /images/generations (JSON) or /images/edits (multipart), quality: medium for GPT image models. The request is built once per call and sent once per image, through safeFetch with 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.
  • Metering. One usage_ledger row 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.
  • Observability. One console.info('[image-generation] generated', {...}) record per call (model, images, billed requests, bytes, cost, duration), never the prompt.
  • Settings. A section on Settings > Governance > Models: a switch that saves at once and keeps the pin, and an Image model picker (Automatic or any admitted image model) with the current pick, refusals and repair paths. EN/DE/FR messages.
  • Bridge timing. The shim allows generate_image 300 s (other calls keep 30 s) and reports MCP progress; Codex's bridge server gets tool_timeout_sec=330.

Deviations from the brief, with reasons

  1. OpenRouter uses its dedicated Image API, not chat completions with modalities: it is the documented way, serves image-only models, takes a count and references, and reports usage.cost.
  2. size is square | landscape | portrait (a pixel size is read by its orientation), because the two APIs spell sizes differently.
  3. Automatic selection only walks OpenRouter and OpenAI; a pin may name another OpenAI-compatible provider's image model.
  4. The in-flight hold has columns of its own (image_hold_cents, image_hold_requests) that the reservation query adds to the op's budget_cents, rather than being added into budget_cents: the allowance check needs the gateway allowance unchanged, and a subscription turn's budget_cents is NULL (writing a figure there would leave a phantom hold after the settle).
  5. The gateway key's own cap is not lowered by image spend. Images are admitted only into what the allowance has left after the model's live spend, but model calls after an image can still use the key's whole allowance, so a turn's worst case is about two allowances; the budget caps still see both, because the turn's hold and the booked images both count. Lowering the key's cap would need the pinned Bifrost's budget-update semantics verified (whether current_usage, the only spend signal, survives an update), which this change does not do.
  6. The per-image hold is a flat 25 cents, well above the curated models at medium quality (1 to 7 cents); a pinned model priced higher can overshoot by its difference once, since the next call is measured against booked cost.
  7. Out-of-scope files touched for the tool to work end to end: the in-sandbox MCP shim and the Codex exec builder (timeouts), the chat assistant's deliverables sentence, the CLI configuration check, and sessionReadFile, which gains an optional byte cap. The per-turn allowance knob moved next to the turn deadline so the admission can read it.
  8. The brief called the settings area "Content & Models"; its visible label is Models.

Checklist

  • bun run check passes (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, platform tsc, 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 knip clean.
  • bun run lint:sast passes (Opengrep): run on the TypeScript files this branch changed, 0 findings (the repo's patterns exclude test files; integration-check.ts is over the scanner's size limit).
  • Translations updated in services/platform/messages/{en,de,fr}.yml (governance.imageGeneration.*); no de-CH override needed.
  • Docs updated in 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).
  • README N/A: no feature list mentions images.

Test plan

Automated (all green locally):

  • Policy schema: 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.
  • Provider shapes and replies (aspect ratios, quality, charges carried on unusable replies, reference formats): image_wire.test.ts; the call (built once, charges, generic transport errors): image_generation.test.ts.
  • The tool (argument, path and reference guards, delivery-box bare names, admission refusals relayed, settle on every path including failures, unusable replies booked, racing calls, identical retry with reference content): workspace_image_tool.test.ts; the byte-capped read: helpers/session_client.test.ts; routing: workspace_tools_bridge.image.test.ts; the door's turnOp: dispatch-routes.test.ts.
  • Admission and settle (in-flight refusal and stale takeover, ceiling, allowance with live model spend, subscription default, caps with the turn's own hold, settle without tokens): backend/domains/sandbox/image-generation.test.ts; the holds query: backend/domains/governance/budget-reservations.test.ts.
  • Real Postgres: ITEST_LANES=checkImageGenerationAdmission,checkSandboxGatewayKeyReclaim,checkChatThreadSurface bun run backend:integration on 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.
  • Harness gating: agent_run_host.image_generation.test.ts, agent_host.image_generation.test.ts (Pi and Hermes get no tool).
  • Settings: image-generation-editor.test.tsx, provider-reads.test.tsx. Bridge timing: tale-connectors-mcp.test.ts, Codex golden execs.
  • bun run lint:manual and check-guide.ts on 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

  • No live provider call or sandbox run creating an image, no browser pass of the Models section, and no docs screenshot of it (to be captured after merge).
  • The full backend:integration run; only the three lanes above ran (a filtered run is not full coverage).
  • Provider request and reply shapes against the providers' documentation only (no paid call).
  • MCP client timeouts: Codex parse-checked on the pinned CLI; OpenCode, Claude Code and Gemini CLI from their docs and source; OpenClaw and Qwen Code not checked.
  • The gateway key's cap is not lowered by image spend (deviation 5).
  • German and French texts have had no independent native read-through.
  • services/sandbox-runtime/daemon: file-ops.test.ts (stalled URL deadline) and main.test.ts (partial exec body) fail on this machine; this change does not touch them.

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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant