# Generations Lifecycle

> OpenGen processes every media generation as a durable, workspace-private job across eight REST endpoints. Submit once with a persisted Idempotency-Key and optional Prefer wait up to 25 seconds, follow updates via Server-Sent Events or compact status long-polling, recover lost responses via read-only lookup, cancel explicitly, and purge terminal outputs on demand.

## Agent Prompt

```text
Manage generation jobs safely end-to-end using https://opengen.dev/docs/generations:
1. Always inspect the model schema (GET https://opengen.dev/v1/models/{provider}/{model}) and run POST https://opengen.dev/v1/pricing/estimate before confirming maxCostMicros with the user.
2. Persist a unique Idempotency-Key (1–200 chars) and the exact canonical JSON body before calling POST https://opengen.dev/v1/generations (optional Prefer: wait=20 for fast images) or MCP generate(waitMs=20000).
3. On timeout or network drop, NEVER mint a new Idempotency-Key — call read-only GET https://opengen.dev/v1/generations/lookup?idempotencyKey=... or MCP job_get({ idempotencyKey }).
4. Follow progress via GET https://opengen.dev/v1/generations/{id}/events (SSE), GET https://opengen.dev/v1/generations/{id}/status?afterRevision=...&waitMs=25000, or webhooks, then fetch fresh signed output links via GET https://opengen.dev/v1/generations/{id} (or job_get).
```

## All 8 generation endpoints

Every endpoint under the `generations` OpenAPI tag is strictly workspace-private and served with `Cache-Control: no-store`:

| Method & Path                         | Operation ID        | Scope      | Purpose                                                                                                                                                                                                                                                  |
| ------------------------------------- | ------------------- | ---------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `POST /v1/generations`                | `media.generate`    | `generate` | Submit one canonical generation with required `Idempotency-Key` (1–200 chars) and optional `Prefer: wait=N` (`0–25`s). Returns `202 Accepted` (or `200 OK` if ready inside `Prefer: wait`) with `Location: /v1/generations/{id}`                         |
| `GET /v1/generations`                 | `jobs.list`         | `read`     | List workspace generation jobs newest-first. Returns `X-Next-Cursor` header for pagination; filters: `modelId`, `providerId`, `deploymentId`, `endpointRegion`, `operation`, `keyId`, `status`, `project`, `since`, `until`, `limit` (`1–100`), `cursor` |
| `GET /v1/generations/lookup`          | `jobs.lookup`       | `read`     | Read-only recovery of a job by `?idempotencyKey=<key>` when the original submit response was lost. Never creates a job                                                                                                                                   |
| `GET /v1/generations/{id}`            | `jobs.get`          | `read`     | Read full job details, billing state, `structuredError`, and fresh short-lived signed `/media` output URLs while retained                                                                                                                                |
| `GET /v1/generations/{id}/status`     | `jobs.status`       | `read`     | Compact status long-poll (`?afterRevision=<64-hex>&waitMs=<0..25000>`). Returns `{ job, changed, timedOut }` with 64-hex `revision`, `progress`, and `timings`                                                                                           |
| `GET /v1/generations/{id}/events`     | `jobs.events`       | `read`     | Bounded 50-second `text/event-stream` SSE stream (`?afterRevision=` or `Last-Event-ID` header) with 10s heartbeats and clean reconnect cursor                                                                                                            |
| `POST /v1/generations/{id}/cancel`    | `jobs.cancel`       | `generate` | Immediately cancels a `queued` job (`200 OK`, releases hold) or requests upstream cancellation on a `running` job (`202 Accepted`, `cancellationState: "requested"`)                                                                                     |
| `DELETE /v1/generations/{id}/outputs` | `jobs.purgeOutputs` | `generate` | Permanently deletes retained private output bytes on a terminal settled job while preserving job metadata and ledger history                                                                                                                             |

## Canonical request envelope

Every generation request uses one consistent envelope across all 54 models and 10 operations:

```json
{
  "modelId": "openai/gpt-image-2",
  "operation": "text-to-image",
  "input": {
    "prompt": "Minimalist studio photo of a frosted glass carafe on travertine stone",
    "resolution": "1K",
    "aspectRatio": "1:1",
    "quality": "low"
  },
  "billing": "managed",
  "maxCostMicros": 50000,
  "metadata": {
    "project": "catalog-hero",
    "tags": { "env": "staging", "batch": "dec-02" }
  }
}
```

Optional envelope fields:

- `billing`: `"managed"` (default prepaid workspace credit) or `"byok"` (encrypted workspace provider key).
- `routeId` or `routing`: pin an exact regional route or declare routing constraints (see [Regional Routing & Privacy](/docs/regional-routing)).
- `maxCostMicros`: integer micro-USD ceiling for managed generations (`1 USD = 1,000,000 micro-USD`).
- `metadata`: private `project` (up to 80 chars) and up to 16 `tags` (for filtering in `GET /v1/generations` and cost attribution in `GET /v1/analytics`).
- `previousJobId`: owned completed job UUID for supported continuations (such as Omni `video-extend`).
- `queueStartDeadlineAt`: ISO-8601 UTC deadline after which a still-queued job fails with `start_deadline_exceeded` before dispatch.
- `webhookUrl` and `webhookEvents`: per-request Ed25519-signed webhook callback (see [Webhooks & Ed25519 Verification](/docs/webhooks)).

## Job status, delivery, and cancellation states

OpenGen tracks execution status, private output delivery, and cancellation independently so callers never confuse upstream completion with downloadable media or confirmed refunds:

### Execution `status`

| Status               | Terminal?            | Meaning                                                                                                                                                |
| -------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `queued`             | No                   | Admitted and reserved locally; waiting for worker dispatch                                                                                             |
| `submitting`         | No                   | Worker is actively submitting to the upstream provider                                                                                                 |
| `running`            | No                   | Upstream provider accepted the task and is executing                                                                                                   |
| `submission-unknown` | Yes (reconciliation) | Upstream acceptance could not be confirmed after timeout or transport failure. Reserved funds stay held pending reconciliation — **never** blind-retry |
| `succeeded`          | Yes                  | Upstream provider reported completion; inspect `deliveryStatus` before downloading outputs                                                             |
| `failed`             | Yes                  | Upstream or admission failure recorded in `structuredError`                                                                                            |
| `cancelled`          | Yes                  | Cancellation confirmed                                                                                                                                 |

### Delivery `deliveryStatus`

- `pending`: worker is downloading, verifying container signatures/SHA-256, and writing outputs into private object storage.
- `available`: all output receipts are stored privately and `outputs[]` contains valid signed URLs.
- `partial`: at least one output slot succeeded while another failed (inspect `deliveryErrors[]`).
- `failed`: output capture failed; inspect `deliveryErrors[]` and `structuredError`.
- `expired`: outputs expired or were explicitly purged via `DELETE /v1/generations/{id}/outputs`.
- `unverified`: legacy/unverified delivery receipt state.

### Cancellation `cancellationState`

- `none`: no cancellation requested.
- `requested`: upstream cancellation was requested for a `running` job (`POST /v1/generations/{id}/cancel` returned `202 Accepted`). Reserved credits remain held until polling confirms terminal non-billable cancellation.
- `confirmed`: cancellation confirmed (`queued` jobs transition immediately to `status: "cancelled"` with `200 OK` and hold released).
- `rejected` or `unsupported`: the upstream provider rejected or does not support mid-flight cancellation; the job may finish and settle normally.

> [!WARNING]
> Cancellation does **not** establish refundability on a running provider task. Only confirmed non-billable cancellation releases reserved managed credit.

## Synchronous `Prefer: wait`, SSE streaming, and compact polling

Choose the waiting strategy that fits your latency profile:

- **Fast images (`Prefer: wait=20`)**: Send RFC 7240 `Prefer: wait=20` (clamped `0–25`s) on `POST /v1/generations`. If the job reaches a terminal state with non-pending delivery inside the window, OpenGen returns `200 OK` with `Preference-Applied: wait=20` and populated `outputs[]`. Otherwise it returns `202 Accepted` cleanly so you continue asynchronously.
- **Server-Sent Events (`GET /v1/generations/{id}/events`)**: Streams `event: status` frames carrying `id: <64-hex-revision>`, `: heartbeat` comments every `10` seconds, `event: done` once terminal with non-pending delivery, and `event: reconnect` with `retry: 1000` at the bounded `50`-second connection ceiling so `EventSource` or custom clients reconnect seamlessly using `Last-Event-ID`. Re-authorizes credentials on every poll tick.
- **Compact status long-poll (`GET /v1/generations/{id}/status`)**: Pass `afterRevision=<previous-revision>&waitMs=25000` to receive `{ job, changed, timedOut }` without resending full input payloads or re-signing media links until the job finishes.

```bash tab="cURL"
# Stream live job status via SSE (reconnecting with Last-Event-ID if needed)
curl -N "$OPENGEN_API_URL/v1/generations/$JOB_ID/events" \
  -H "Authorization: Bearer $OPENGEN_API_KEY" \
  -H "Accept: text/event-stream"

# Compact status long-poll
curl --fail-with-body \
  "$OPENGEN_API_URL/v1/generations/$JOB_ID/status?waitMs=20000" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"

# List recent succeeded video jobs with cursor pagination
curl --fail-with-body -i \
  "$OPENGEN_API_URL/v1/generations?status=succeeded&operation=image-to-video&limit=20" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"
```

```ts tab="TypeScript"
const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` };

// Follow status via compact long-poll using revision tokens
let afterRevision: string | undefined;
while (true) {
  const qs = new URLSearchParams({ waitMs: '25000' });
  if (afterRevision) qs.set('afterRevision', afterRevision);
  const { job } = await fetch(`${baseUrl}/v1/generations/${jobId}/status?${qs}`, {
    headers,
  }).then((r) => r.json());
  afterRevision = job.revision;
  if (
    ['failed', 'cancelled', 'submission-unknown'].includes(job.status) ||
    (job.status === 'succeeded' && job.deliveryStatus !== 'pending')
  ) {
    break;
  }
}

// Fetch full job once delivered to obtain fresh signed /media URLs
const completed = await fetch(`${baseUrl}/v1/generations/${jobId}`, { headers }).then((r) =>
  r.json(),
);
console.log(completed.outputs);
```

```python tab="Python"
import json
import os
import time
import httpx

base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
headers = {"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"}

with httpx.Client(base_url=base_url, headers=headers, timeout=60.0) as client:
    after_revision = None
    done = False
    while not done:
        params = {"afterRevision": after_revision} if after_revision else None
        event_name = None
        retry_ms = 1000
        with client.stream("GET", f"/v1/generations/{job_id}/events", params=params) as stream:
            stream.raise_for_status()
            for line in stream.iter_lines():
                if line.startswith("id: "):
                    after_revision = line[4:].strip()
                elif line.startswith("event: "):
                    event_name = line[7:].strip()
                elif line.startswith("retry: "):
                    retry_ms = int(line[7:].strip())
                elif line.startswith("data: "):
                    data = line[6:]
                    print(event_name or "message", data)
                    if event_name == "reconnect":
                        payload = json.loads(data)
                        after_revision = payload.get("afterRevision") or after_revision
                    elif event_name == "done":
                        done = True
                        break
                elif line == "":
                    if event_name == "done":
                        done = True
                        break
                    event_name = None
        if not done:
            time.sleep(max(0.0, retry_ms / 1000.0))

    completed = client.get(f"/v1/generations/{job_id}").raise_for_status().json()
print(completed["outputs"])
```

```json tab="MCP"
{
  "tool": "job_get",
  "arguments": {
    "id": "00000000-0000-4000-8000-000000000001",
    "afterRevision": "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef",
    "waitMs": 25000
  }
}
```

```bash tab="CLI"
# Wait/resume an existing job (Ctrl+C stops waiting only; never cancels upstream work)
opengen job resume "$JOB_ID"

# Recover a lost submission response safely by original idempotency key
opengen job recover --idempotency-key "$OPENGEN_IDEMPOTENCY_KEY"
```

## Private media delivery, cancellation, and output purging

- **First-party `/media` URLs**: Images `<= 3.5 MiB` stream directly (`200 OK`) from the OpenGen origin; larger images, videos, and HTTP `Range` requests return `302 Found` to a short-lived private storage URL (`<= 300` seconds) stripped of any caller tracking query parameters (such as `?utm_source=...`). Re-read `GET /v1/generations/{id}` (or MCP `job_get`) to refresh an expired (`410 Gone`) URL while outputs remain retained.
- **Reusing an output**: Pass `output.outputIndex` (the stable receipt slot, independent of array position) to `POST /v1/assets` with `{ "source": "job_output", "sourceJobId": "<jobId>", "outputIndex": 0 }` to feed a generated image or video into a downstream edit or video model.
- **Cancelling and purging outputs**:

```bash tab="cURL"
# Request cancellation of an existing job
curl --fail-with-body -X POST "$OPENGEN_API_URL/v1/generations/$JOB_ID/cancel" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"

# Permanently purge retained output bytes on a terminal settled job
curl --fail-with-body -X DELETE "$OPENGEN_API_URL/v1/generations/$JOB_ID/outputs" \
  -H "Authorization: Bearer $OPENGEN_API_KEY"
```

```ts tab="TypeScript"
const baseUrl = process.env.OPENGEN_API_URL ?? 'https://opengen.dev';
const headers = { Authorization: `Bearer ${process.env.OPENGEN_API_KEY}` };

const purged = await fetch(`${baseUrl}/v1/generations/${jobId}/outputs`, {
  method: 'DELETE',
  headers,
}).then((r) => r.json());

console.log(purged.deliveryStatus, purged.outputsPurgedAt, purged.deletedCount);
```

```python tab="Python"
import os
import httpx

base_url = os.environ.get("OPENGEN_API_URL", "https://opengen.dev")
response = httpx.delete(
    f"{base_url}/v1/generations/{job_id}/outputs",
    headers={"Authorization": f"Bearer {os.environ['OPENGEN_API_KEY']}"},
    timeout=30.0,
)
response.raise_for_status()
print(response.json())
```

```json tab="MCP"
{
  "tool": "purge_job_outputs",
  "arguments": {
    "id": "00000000-0000-4000-8000-000000000001"
  }
}
```

```bash tab="CLI"
opengen job cancel "$JOB_ID"
opengen job purge-outputs "$JOB_ID"
```

Purging requires the job to be terminal and — for succeeded managed jobs — settled (`settledMicros !== null`). Active delivery leases or unsettled managed jobs return `409` (`job_not_terminal`, `output_purge_pending_settlement`, or `output_delivery_in_progress`). Purging is idempotent and leaves job metadata and billing history intact.
