# Bring your own provider to Darkroom

> Give Darkroom your own image or video provider and model catalogue. Decode the catalogue with parseMediaCatalogue, pass it beside your provider, and keep Darkroom's retained-output and no-silent-redispatch guarantees.

Darkroom is the package that runs a generation as a durable operation. It
retains the provider's bytes, saves them, and replays the same request without
paying again. It ships with the Fungi gateway's models. A host that calls a
different provider, such as fal.ai, supplies that provider's model list too.

This page covers the model list (the catalogue), the provider function and the
Durable Object that runs a job. For the Quick start, install and the Workers AI
provider, see the
[Darkroom documentation](https://docs.fungi.computer/darkroom/).

## How a provider and its catalogue fit

A provider owns its model list. Darkroom checks every request against the
catalogue of the provider that will run it. A request for a model outside the
catalogue, or settings outside that model's bounds, is refused before billing
and before dispatch.

- The built-in provider uses the gateway's catalogue. A `fal-ai/...` id is
  refused there.
- A provider you inject uses the catalogue you pass. A gateway model id is
  refused there.

You supply the catalogue as data. Decode it once with `parseMediaCatalogue`. It
throws `MediaSettingsError` that names the first problem when an entry is
malformed or contradicts itself. `mediaCatalogueSchema` is the same decoder as a
Zod schema, for a host that already validates its configuration with Zod.

The decoder checks that:

- the list has between 1 and 256 entries;
- every `id` is unique;
- a model has video bounds exactly when its `kind` is `"video"`;
- a video model's durations sit inside its minimum and maximum, and include the
  default;
- a video model's formats include its default resolution and aspect ratio.

Each entry carries the bounds Darkroom enforces: prompt length, dimensions or
exact sizes, steps, reference counts and, for video, durations, formats and
per-second prices.

A video entry sets `video.provider` to `"host"`. That tells Darkroom your
provider owns the model's wire format. Darkroom builds no gateway request for
it. The other values (`seedance`, `veo`, `minimax`) are the gateway's own
request formats. Image entries have no provider field.

## Write the catalogue

This catalogue has one image model. The entry is the one Darkroom's own test
decodes.

```ts
import { parseMediaCatalogue } from "@fungi.computer/darkroom";

export const falCatalogue = parseMediaCatalogue([
  {
    id: "fal-ai/flux/dev",
    label: "FLUX dev (fal.ai)",
    kind: "image",
    tier: "balanced",
    outputFormats: ["png"],
    maxPromptLength: 500,
    input: {
      transport: "json",
      dimensions: "own",
      maxDimension: 1024,
      maxDimensionDocumented: true,
      defaultWidth: 512,
      defaultHeight: 512,
      steps: "steps",
      maxSteps: 12,
      defaultSteps: 6,
      referenceField: null,
      maxReferences: 0,
      referenceDimension: null,
      referenceFormat: "png",
    },
    sizes: null,
    video: null,
  },
]);
```

A video entry also needs a `video` object. The Darkroom README has a complete
fal.ai video example with prices and reference roles.

## Write the provider

A provider is one function. It receives settings that Darkroom has already
validated against your catalogue, plus the reference images, and returns the
output bytes and their format.

```ts
import type { MediaProvider } from "@fungi.computer/darkroom";

declare const FAL_KEY: string; // from your host's environment

export const falProvider: MediaProvider = async (settings, _refs, signal) => {
  const queued = await fetch(`https://queue.fal.run/${settings.model}`, {
    method: "POST",
    headers: {
      Authorization: `Key ${FAL_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      prompt: settings.prompt,
      // Add fal.ai's size and step fields from settings.width, settings.height
      // and settings.steps.
    }),
    signal: signal ?? null,
  });
  if (!queued.ok)
    throw new Error(`fal.ai refused the request: ${queued.status}`);
  // Poll the queue, download the image and return its bytes.
  return { bytes: new Uint8Array(), format: "png" };
};
```

The request body and the queue polling follow fal.ai's API, not Darkroom's. Take
them from fal.ai's documentation. Darkroom only needs the function to return
real bytes and the actual encoding in `format`.

## Pass both to Darkroom

The catalogue goes in two places, because two code paths use it.

```ts
import { createMediaService } from "@fungi.computer/darkroom/server";
import { MediaOperationDO } from "@fungi.computer/darkroom/cloudflare";

// The durable job engine runs your provider from its alarm.
export class FalMediaOperationDO extends MediaOperationDO {
  protected override mediaProvider() {
    return falProvider;
  }
  protected override mediaCatalogue() {
    return falCatalogue;
  }
}

// In the request path, pass the catalogue and your own quote.
const service = createMediaService({
  // scope, operations, metering and destination as in the README quick start
  provider: falProvider,
  catalogue: falCatalogue,
  estimate: (settings) => 1_000,
  // ...
});
```

If you override `mediaProvider` but not `mediaCatalogue`, the Durable Object
keeps the gateway's catalogue. Override both.

`estimate` is yours. It returns the provider's cost for the validated settings
in milliunits (1 USD is 100,000 milliunits). Darkroom does not know fal.ai's
prices. Set the `prices` in a video entry and your `estimate` to agree.

`GET /models` then lists your catalogue. If the host gives no `readReference`
function on the destination, Darkroom lists every model as accepting zero
reference images, even where your entry allows them.

## What Darkroom guarantees

Darkroom owns the operation around your provider. You do not need to rebuild
these.

- **Identity comes from the host.** The host chooses `actorId`, `namespace`,
  `owner` and `destinationId`. A request body cannot choose them.
- **One request id, one operation.** The operation captures its identity and
  input first. Repeating the same request id replays the saved result. The same
  id with different input returns `409`.
- **Output is retained before it is saved.** Darkroom keeps the provider's exact
  bytes in the object store (the `APP_ARTIFACTS` R2 bucket in the README). If
  the destination write fails, a retry reuses those bytes and does not call the
  provider again.
- **No silent redispatch.** An ambiguous provider execution, such as a lost
  reply, is never dispatched again by Darkroom. A terminal provider failure does
  not repeat the paid attempt.
- **Refusals happen early.** An unknown model or out-of-bounds setting is
  refused before billing admission or dispatch.
- **Video runs in the background.** A video generation runs from the operation's
  alarm. The service answers `202` with a `Retry-After`. Retry the same request
  id to collect the result.

## What your host must do

- **Authenticate and authorize.** Darkroom takes the identity you give it. The
  README quick start admits one local owner. Add real authentication and
  destination authorization before you serve anyone else.
- **Own the provider call.** Auth, the wire format, polling and downloading are
  yours. Return the real output encoding.
- **Keep the catalogue true.** Darkroom enforces the bounds you declare. It
  cannot know that fal.ai changed a limit.
- **Quote and settle.** Declare `metering: "unmetered"` if you pay your provider
  directly. Otherwise supply idempotent `admit` and `settle` functions and your
  own `refusalMessages`. Your `estimate` is an estimate. Your metering owner
  sets the customer price.
- **Provide the stores.** Run the operation Durable Object with SQLite, and an
  R2 bucket for retained output.
- **Reset old stores yourself.** Pre-launch operation stores must use the
  current schema. Darkroom does not migrate them.

## Limits today

- A stored reference still carries a `computerId`. Darkroom was built for Apps
  that read references from a Computer. The operation record stores a
  `computerId` for the destination, set from the host's `destinationId`. The
  README quick start passes `destinationId: "outputs"`, so the value need not
  name a real Computer. Treat it as a stable destination id.
- Reference images are bounded to 30 files, 8 MiB each and 24 MiB in total. A
  catalogue entry can set a tighter limit, not a looser one.
- The Cloudflare adapter that runs the durable operation targets workerd, celld
  and Cloudflare, with SQLite Durable Objects and R2.
- Darkroom does not ship its tests in the package. Your own provider needs its
  own tests. Darkroom's test uses `fal-ai` ids against a fake provider, in
  `test/custom-catalogue.test.ts` in the repository.

## Where next

- [Prints](/apps/prints/) is the App that uses Darkroom.
- [Make and save images](/guides/make-and-save-images/) shows the owner's side.
