# AI jobs

**The core, the formats and the command line never call a model.** A plugin does, when you have
installed it and chosen who answers: a provider with your own key, or the plugin author's server.
The providers live in `@recit/ai`, an optional package the plugin depends on, never `recit` itself.
The plugin API and `@recit/ai` are **experimental**
([Stability](/documentation/reference/stability#experimental)).

## Run a job

```bash
recit ai                                       # the jobs of the project's plugins
recit ai deck.fromText --text notes.txt        # a text becomes deck.md
recit ai scene.rewrite slides.md --input '{"scene": "intro"}'
recit ai notes.write slides.md --write
recit ai rehearsal.timing slides.md --input '{"target": "10:00"}'
recit ai deck.toFilm slides.md                 # slides.film.story.md
```

A job returns a whole story, operations on the scenes of your story (by their `id`), or a report.
Récit checks the result before anything else: the story with its schema, the operations against your
scenes, a film by reading it as `recit render` would. A result that does not pass is refused and
nothing is written; it is never repaired in silence.

Then Récit shows a diff and asks before it writes. `--write` writes without asking; without a
terminal and without `--write`, nothing is written. `-o <file>` chooses where a new story goes.

## Your key

```ts
// recit.config.ts
plugins: [
  lorem({
    ai: { provider: "anthropic", model: "<model id>", apiKey: { env: "ANTHROPIC_API_KEY" } },
  }),
];
```

| Provider      | `provider`  | Where the key goes                         |
| ------------- | ----------- | ------------------------------------------ |
| Anthropic     | `anthropic` | the `x-api-key` header                     |
| OpenAI        | `openai`    | the `Authorization: Bearer` header         |
| Google Gemini | `gemini`    | the `x-goog-api-key` header, never the URL |

The call leaves your machine for that provider alone, by `fetch`. The key is read from the
environment at each call: it is never written in the config, never stored in the provider, never
printed (an error that would repeat it says `[redacted]`), and never reaches a built site. The model
id is the one the provider gives.

## The author's server

A plugin can send its jobs to its author's server instead, which keeps its prompts and its logic:

```ts
lorem({
  ai: { provider: "server", url: "https://ai.example.com", licenseKey: { env: "LOREM_LICENSE" } },
});
```

The contract is fixed: `POST <url>/v1/jobs/<job>`, the header `Authorization: Bearer <license>`, a
JSON body `{ "input": …, "story": … }`, and the job's result in JSON. A service that signs you in
gives a **token source** instead of a license key, a function that returns the current token of your
account: `serverProvider({ url, token: () => session.token() })`.

A job fails when the server cannot be reached; a build never depends on a license check.

**What is sent.** In the key mode, the job's input and your story go to the provider. In the server
mode, they go to the plugin's author. Récit sends nothing by itself. The plugin says which, in its
README.

## Media

A plugin can also generate media across four modalities beside `text`: `image` (generation and
editing), `speech`, `video` and `sound` (`@recit/ai/image` ships Google Gemini and OpenAI adapters,
`@recit/ai/speech` ships Google Gemini and ElevenLabs, `@recit/ai/video` ships Google Gemini, and
`@recit/ai/local` ships a ComfyUI image adapter). The plugin returns its media adapters from
`providers({ options, env })` and each job declares its `modalities`, receiving only those on
`context.providers`. When a declared modality has no configured provider, `recit ai` refuses the job
before calling `run` and points to the path without AI:
`<job> needs an image provider, and the plugin <plugin> chooses none: set its ai options in recit.config, or make the file yourself and record it with recit assets register <file> --origin human`.

**Where the content goes.** In the key mode, the request (prompt or text, plus any reference images,
first frame, or image and mask to edit) goes from your machine to the provider you chose, with your
key (`x-goog-api-key` for Google Gemini, `Authorization: Bearer` for OpenAI, `xi-api-key` for
ElevenLabs, never in the URL). In the server mode, the job's `input` and `story` go to the plugin
author's server (`POST <url>/v1/jobs/<job>`), which returns short-lived `https:` download URLs and
SHA-256 digests verified without sending your key or token. Nothing else leaves your machine, and
`recit build` never calls a provider. The media adapters of `@recit/ai` enforce this at runtime
(`assertAiJobConfirmed` of `recit/plugin`; `video.poll` stays free to follow a confirmed `start`):
called from a build hook or a script, they throw an error and send nothing. Once you confirmed or
set a ceiling, `recit ai` marks every request through `confirmAiProviders` of `recit/plugin`;
`runPluginJob` does the same in a test, and a plugin's own server (`createAiServer`) wraps the
adapters it runs for a client that confirmed. Récit Studio does not ask for a media confirmation
yet, so its media jobs are refused.

**Who pays, and how much.** The provider bills the account of your key (or the author's server
prices the job and may announce its price on `POST <url>/v1/jobs/<job>/estimate`).
`recit ai --dry-run` lists the media generations and their estimated cost (`Estimated total: …`)
without calling a media provider (if the job also calls a text model, those tokens still run and are
not counted). The estimate comes from the `pricing` the plugin declares on each media adapter,
`{ unit, price, currency? }` with `unit` one of `image`, `second`, `character` or `token` (`USD`
when `currency` is absent); an adapter without `pricing` has an unknown cost. `token` prices a voice
billed by its tokens, as Gemini does: `price` per audio token out, `inputPrice` per text token in
and `tokensPerSecond` of audio
(`{ unit: "token", price: 0.00001, inputPrice: 0.0000005, tokensPerSecond: 25 }`); before any audio
exists, the estimate counts 15 characters of text per second of speech and 4 characters per text
token. `--max-cost <amount>` and the plugin's `maxCost` option, when it has one, cap spending — the
smaller wins — and refuse an unknown cost or an overrun before calling the provider. Outside a
terminal without `--max-cost`, `recit ai` stops after the estimate even with `--write`. After a
priced generation it prints `Spent: …`; when media went through the cache,
`Report: <n> generated, <m> reused from the cache.` (a run served entirely from the cache spends
nothing and prints only the report). A job that leaves prompts aside returns them as `skipped`
(`{ id, reason }`) next to its files: `recit ai` prints `Skipped <id>: <reason>` for each and adds
`, <k> skipped` to the report (or `Report: <k> skipped.` when nothing used the cache). Image,
speech, sound and video outputs are cached in `.recit/cache/ai/` (keyed by the request, plugin
options, plugin version and secret variable names, never secret values; a video once its `poll` is
done): an identical generation is not paid twice, and re-running after an error reuses what is
already cached at no cost.

```ts
// src/ai.ts of a plugin, with geminiImage from "@recit/ai/image": the adapter declares its price
providers: ({ options, env }) => ({
  image: geminiImage({ apiKey: { env: "GEMINI_API_KEY" }, model: "<model id>", env, pricing: { unit: "image", price: 0.04 } }),
}),
```

```bash
recit ai image.generate --input '{"prompt": "Lorem ipsum"}' --dry-run
recit ai image.generate --input '{"prompt": "Lorem ipsum"}' --max-cost 0.10 --write
```

For speech with character timestamps, `elevenlabsSpeech` of `@recit/ai/speech` calls ElevenLabs with
`{ env: "ELEVENLABS_API_KEY" }` in `xi-api-key`, returns MP3 audio (`audio/mpeg`) with `timings`
(`{ text, start, end }`, one per character, in seconds from the start of the audio), takes no
`style`, and prices by `character`:

```ts
// src/ai.ts of a plugin, with elevenlabsSpeech from "@recit/ai/speech"
providers: ({ env }) => ({
  speech: elevenlabsSpeech({
    apiKey: { env: "ELEVENLABS_API_KEY" },
    model: "eleven_multilingual_v2",
    voice: "<voice id>",
    env,
    pricing: { unit: "character", price: 0.0003 },
  }),
}),
```

The reference plugin turns its media jobs on with its `media` option,
`lorem({ media: { provider: "gemini", imageModel: "…", speechModel: "…", apiKey: { env: "GEMINI_API_KEY" } } })`,
and declares no `pricing`: its generations have an unknown cost, so `--max-cost` refuses them and
only the confirmation in a terminal lets them run.

For OpenAI images, `openaiImage` of `@recit/ai/image` generates from a prompt (and optional
reference images) and edits an image with an optional `mask` (`POST /v1/images/generations` and
`POST /v1/images/edits`, `Authorization: Bearer` header, optional `quality`, no `seed`). It speaks
the dialect of the `gpt-image-*` models, not the one of `dall-e-2` and `dall-e-3`, and sends one of
their sizes, `1024x1024`, `1536x1024` or `1024x1536`, chosen from the asked ratio (`auto` without
one):

```ts
// src/ai.ts of a plugin, with openaiImage from "@recit/ai/image": generation and mask editing, no seed
providers: ({ env }) => ({
  image: openaiImage({
    apiKey: { env: "OPENAI_API_KEY" },
    model: "gpt-image-1",
    quality: "high",
    env,
    pricing: { unit: "image", price: 0.04 },
  }),
}),
```

**Local models.** For images on your own machine, `comfyImage` of `@recit/ai/local` talks to a
ComfyUI server (`http://127.0.0.1:8188` by default, or `https:`, with `http:` accepted only on this
machine or a private network) that you install and start yourself, with no key. Pass a workflow
exported in ComfyUI's API format (`workflow`, cloned per call) and map `inputs.prompt` (plus
optional `seed`, `width`, `height`, and `image` / `mask` on a `LoadImage` node to enable `edit`;
reference images go in the workflow itself rather than `request.references`) to their node ids: each
call posts the graph to `/prompt`, polls `/history/<prompt_id>` until completion, and reads the
image from `/view` (with optional `{ unit: "image", price }` `pricing` for `--dry-run`). Local text
models already go through `directProvider({ provider: "openai", baseUrl })` from `@recit/ai`; since
the key goes with each call, its `baseUrl` is `https:`, or `http:` on this machine only.

```ts
// src/ai.ts of a plugin, with comfyImage from "@recit/ai/local": local ComfyUI, no key
providers: ({ options: { workflow } }) => ({
  image: comfyImage({
    workflow,
    inputs: { prompt: { node: "6", input: "text" }, seed: { node: "3", input: "seed" } },
  }),
}),
```

**What is written.** A media job returns `{ kind: "asset", files }`. Before touching disk,
`recit ai` checks every destination path (relative, inside the story's folder or working directory,
at most 256 MiB), lists the planned files with their MIME type and byte size, and asks before
writing unless `--write` is set. Next to each file it writes `<file>.json` with `origin` (`ai` or
`mixed`), `aiGenerated: true` and `mediaType`, plus `tool`, `model`, `seed`, `references`, `author`,
`license`, `prompt` and `promptHash` (via `registerAsset` when naming a bible prompt), `duration`,
`speechVoice` and `timings` (each character of a timed voice, from the speech provider) when
present. When a regenerated image of a bible prompt comes back under another extension (or another
media file under another extension of the same family), `recit ai` lists the old AI file of the same
prompt as `(superseded, removed)` and removes it with its `.json` after the write
(`Removed <file>.`); a file without an `origin: "ai"` provenance for that prompt is never removed.
See [Provenance](/documentation/scenario/provenance) for `license` and `--strict` (`aiGenerated` is
a field of that file, not a label shown on the page), and
[Animation frames](/documentation/scenario/animation-frames) for the animation frames of a bible.

**How to revoke.** Unset the environment variable (read at each call, never stored) or revoke the
key at the provider. Remove the plugin's `media` option — or the plugin itself — from
`recit.config.ts`, and delete `.recit/cache/ai/` to clear cached outputs. Any registered file stays
an ordinary file of the project: `recit build` reads it without a key, and you can replace it at any
time with `recit assets register <file> --origin human`.

**Test media jobs without a network**: `fakeAiProviders` of `recit/plugin/testing` returns
deterministic SVG images and silent WAV audio, and a video provider only when you pass its bytes
(`fakeAiProviders({ video: { data, mimeType } })`), while recording every request.

## The generation register

Every run of a named job by `recit ai` writes one record in `.recit/jobs/<id>.json` under the
project's folder (next to `recit.config` and `.recit/cache/`). Neither `recit ai` alone (the job
list), nor `--dry-run`, nor an estimate declined before spending, nor a ceiling (`--max-cost` or the
plugin's `maxCost`) refusing the first paid call (a text call counts as paid) writes one; a failed
run writes `state: "failed"` with `error` before rethrowing, and a failure to write the record
itself prints `Could not record this run in .recit/jobs/: …` without failing the job. `recit build`
never reads `.recit/jobs/`. Ignore `.recit/` (or `.recit/jobs/`) in git like `.recit/cache/`: local
runs stay out of version control while generated files and their `<file>.json` provenance enter the
repository.

`recit schema ai-job` prints its JSON Schema (`https://recit.dev/schema/v1/ai-job.json`,
`x-recit-stability: preview`, `AiJobRecordSchema` of `@recit/core/plugin`):

- `kind` (`"ai-job"`), `version` (`1`), optional `$schema`, and `id` (`<UTC compact date>-<8 hex>`,
  also the file name).
- `tool`: `"recit ai"` today, with `job` and `plugin`; `"opencode"` and `"claude"` (with `session`)
  are written by `recit ai jobs record` ([Write with an agent](/documentation/ai/agent-recipe)).
- `models` (sorted `provider/model` identifiers without duplicates) and `requests` (the 64-character
  `aiRequestHash` of every media generation made or reused from `.recit/cache/ai/`, in order). A
  video counts once its `poll` is done, and a run served from the cache keeps the model in `models`
  and `spent: 0`.
- `state` (`"done"` or `"failed"`), `error` when `"failed"`, `startedAt` (UTC ISO date-time) and
  `duration` (milliseconds).
- `costs` (`{ currency, estimated?, spent? }` per currency) and `files` (`{ file, provenance? }`,
  POSIX `/` paths relative to the project's folder, with `provenance` carrying `origin`, `tool`,
  `model`, `seed`, `prompt`, `references`, `license`, `author`, `duration`, `speechVoice` and
  `timings` on media outputs).

```json
{
  "$schema": "https://recit.dev/schema/v1/ai-job.json",
  "kind": "ai-job",
  "version": 1,
  "id": "20261119T103000Z-1a2b3c4d",
  "tool": "recit ai",
  "job": "images.generate",
  "plugin": "lorem",
  "models": ["gemini/lorem-image-1"],
  "requests": [
    "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"
  ],
  "state": "done",
  "startedAt": "2026-11-19T10:30:00.000Z",
  "duration": 1420,
  "costs": [
    {
      "currency": "USD",
      "estimated": 0.04,
      "spent": 0.04
    }
  ],
  "files": [
    {
      "file": "assets/lorem-hero.png",
      "provenance": {
        "origin": "ai",
        "tool": "gemini",
        "model": "lorem-image-1",
        "seed": 42,
        "prompt": "lorem-hero",
        "references": ["cast/lorem-canonical.png"],
        "license": "CC-BY-4.0",
        "author": "Lorem Ipsum"
      }
    }
  ]
}
```

`recit ai jobs` lists the recorded runs from oldest to newest and sums up their count, duration and
costs (`--since <when>` keeps runs since an ISO date or date-time such as `2026-11-19` or a duration
such as `30m`, `12h`, `7d` or `2w`; `--json` prints `{ records, summary }` as JSON; `-c <path>`
points at `recit.config.*`). It locates `recit.config` only to find `.recit/jobs/` and reads that
folder directly without loading `recit.config` or the plugins. Unreadable or invalid `.json` files
are reported (`Skipped .recit/jobs/<file>: …`) and skipped. A plugin job named literally `jobs` is
shadowed by the subcommand (plugin jobs use `<format>.<action>` names such as `deck.fromText`).

```sh
recit ai jobs
recit ai jobs --since 7d
recit ai jobs --json
```

```text
20261119T103000Z-1a2b3c4d  2026-11-19 10:30  done  images.generate (lorem)  1.4 s  0.04 USD  1 file
20261119T104500Z-5e6f7a8b  2026-11-19 10:45  failed  notes.write (lorem)  680 ms  -  no file
    error: Lorem ipsum provider error

2 runs (1 done, 1 failed), 2.1 s, spent 0.04 USD (estimated 0.04 USD).
```

## Writing jobs

```ts
// src/ai.ts of a plugin
import { directProvider, serverProvider } from "@recit/ai";
import type { PluginAi } from "recit/plugin";
import * as z from "zod";

const ai: PluginAi = {
  jobs: {
    "notes.write": {
      description: "Writes the speaker notes of every slide",
      story: "required",
      run: async ({ story, provider, helpers }) => {
        const answer = await provider.generate({
          system: 'Write two spoken sentences per slide. Answer {"notes": [{"id", "notes"}]}.',
          messages: [{ role: "user", content: JSON.stringify(story?.scenes) }],
          json: true,
        });
        const { notes } = z
          .object({ notes: z.array(z.object({ id: z.string(), notes: z.string() })) })
          .parse(helpers.parseJson(answer.text));
        return { kind: "ops", ops: notes.map(({ id, notes }) => ({ op: "patch", id, notes })) };
      },
    },
  },
  provider: ({ options, env }) => directProvider({ ...yourOptions(options), env }),
};
export default ai;
```

When the model stopped at its token limit, `answer.truncated` is `true`: the text is cut, so a job
that parses JSON checks it first and asks for a higher `maxTokens` rather than reporting a broken
answer. A complete answer has no `truncated` field.

A job's name is words joined by dots (`deck.fromText`). Its `input` is a zod schema, filled from
`--input` and `--text`. In the key mode its `run` gets the provider, the story in JSON, the plugin's
options and `helpers` (`fromMarkdown`, `toMarkdown`, `estimateSpeech`, `parseJson`), plus the media
`providers` it declares in `modalities` and the project's `scenario` prompt templates (`template`,
`promptTemplates`) when `recit ai` runs it. When the file is a bible, or a story whose front matter
names one with `cast:`, it also gets `prompts`: the folder of the story (`dir`) and each image
prompt of the bible, with its text built from that template, its fingerprint (`hash`, which an image
records as `promptHash`), its `aspect`, its `seed` (from `seed=`), its `references` and its image's
`status` (`missing`, `stale` or `present`, with the image's path in `asset`), and in `frames` the
key frames of each prompt with `animation=`, their pose guide as SVG text (`guideSvg`), and in
`assets` every image next to the bible, with the `prompt`, `promptHash` and `origin` its provenance
file records. A plugin reads a bible this way without depending on `@recit/scenario` (the reference
plugin's `images.generate` and `frames.generate` read it); `runPluginJob` takes `prompts` too, to
test such a job. An operation is `{ op: "patch", id, body?, notes?, title? }` or
`{ op: "replace", id, scene }`; `notes: null` removes the notes. The reference plugin,
`examples/plugin-lorem`, has fourteen jobs: eight for stories (`deck.fromText`, `scene.rewrite`,
`scene.translate`, `deck.rewrite`, `deck.translate`, `notes.write`, `rehearsal.timing` and
`deck.toFilm`) and six for media (`image.generate`, `images.generate`, `frames.generate`,
`image.edit`, `voice.synthesize` and `video.generate`).

The eight story jobs are defined once in `@recit/ai/jobs`: a plugin that wants them as they are
passes `DECK_JOBS` in its `ai.jobs`, beside its own, and Récit Studio's built-in plugin does the
same. `ask(context, schema, system, prompt)` of the same entry asks the model for JSON, checks it
with the schema and says when the answer was cut by the token limit.

A server runs the same jobs: `serveAiJobs(DECK_JOBS, { provider })` of `@recit/ai/server` gives
`createAiServer` text jobs that parse the request's input with each job's schema and use the
server's provider. A wrong input answers 400 with what to send; a job that calls a media modality is
refused, since only `recit ai` and Récit Studio confirm a media job.

On the server, `createAiServer` of `@recit/ai/server` is a standard `Request` → `Response` handler,
with no framework: it checks the token with your function, runs the job and checks its result.

```ts
import { createAiServer } from "@recit/ai/server";

export default {
  fetch: createAiServer({
    verify: async (token) => licenses.has(token),
    jobs: { "notes.write": async ({ input, story }) => runNotes(input, story) },
  }),
};
```

A job that returns media needs `storeAsset`, which stores each file and gives back its `https:`
address (without it, an `asset` result answers `501`); `estimates` prices a job for
`POST <url>/v1/jobs/<job>/estimate`. There is no payment in it: accounts, quotas and billing stay
yours.

**Test a job without a network**: `fakeAiProvider` and `runPluginJob` of `recit/plugin/testing`
([Writing a plugin](/documentation/plugins/writing#test-it)).
