openapi: 3.0.3
info:
  title: Wildfield API
  description: |
    Wildfield is an HTML ad builder with AI-powered image generation, design systems, and multi-format export.

    ## Authentication
    Endpoints in this spec accept an API key via the `X-API-Key` header (keys start with `adk_`).
    `requireAuth()` also accepts an `Authorization: Bearer <jwt>` header for browser sessions, but API
    clients should use the API key. Create keys at wildfield.io or via `POST /api/auth/api-keys`.

    ## Scope
    This spec documents the full API-key-usable surface: generative AI editing, the render/export
    pipeline, uploads, website capture, cloud integrations (Dropbox + Google Drive), admin/usage, and
    activity logging. Browser OAuth/redirect endpoints (`integrations/{dropbox,gdrive}/{connect,callback,disconnect}`,
    `integrations/gdrive/token`, and `auth/callback`) are session-cookie/redirect flows and are out of
    scope for this API-key spec.

    ## Response format
    Most JSON responses use `{ ok: true, ...data }` on success or `{ ok: false, error: "message" }` on
    failure. A few older endpoints return a bare error object `{ error: "message" }` on failure, and the
    integrations status endpoint returns an unwrapped object.
  version: 1.0.0
  contact:
    name: Popcandi
    url: https://wildfield.io

servers:
  - url: https://wildfield.io
    description: Production

security:
  - apiKey: []

components:
  schemas:
    VectorImageInput:
      description: PNG, JPEG or WebP. Public HTTP(S) URL, base64 data URI, or base64 upload. Inline uploads are stored in public Blob storage before fal receives the URL. Use the existing image upload flow for files above the serverless JSON body limit.
      oneOf:
        - { type: string }
        - type: object
          required: [base64, contentType]
          properties:
            base64: { type: string }
            contentType: { type: string, enum: [image/png, image/jpeg, image/webp] }
    VectorResult:
      type: object
      required: [ok, svg, path, filename, credits]
      properties:
        ok: { type: boolean }
        svg: { type: string, description: Editable SVG with the leading full-viewBox background removed }
        path: { type: string, description: Public Blob URL }
        filename: { type: string }
        credits: { type: integer, description: Legacy compatibility field, always zero }
  securitySchemes:
    apiKey:
      type: apiKey
      in: header
      name: X-API-Key
      description: API key with `adk_` prefix. Create via POST /api/auth/api-keys.

paths:
  # ── Auth ──────────────────────────────────────────────
  /api/auth/me:
    get:
      tags: [Auth]
      summary: Get current user profile
      responses:
        '200':
          description: User profile
          content:
            application/json:
              schema:
                type: object
                properties:
                  id: { type: string }
                  email: { type: string }
                  displayName: { type: string }
                  isAdmin: { type: boolean }

  /api/auth/api-keys:
    get:
      tags: [Auth]
      summary: List API keys
      responses:
        '200':
          description: List of keys (raw key values are not returned)
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  keys:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        name: { type: string }
                        last_used_at: { type: string, format: date-time }
                        created_at: { type: string, format: date-time }
    post:
      tags: [Auth]
      summary: Create a new API key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string, description: "Human-readable label" }
      responses:
        '200':
          description: Key created (raw key only shown once)
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  key: { type: string, description: "Raw API key. Save this, it won't be shown again" }
                  name: { type: string }
    delete:
      tags: [Auth]
      summary: Revoke an API key
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id: { type: string }
      responses:
        '200':
          description: Key revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }

  # ── Design Systems ────────────────────────────────────
  /api/design-systems/list:
    get:
      tags: [Design Systems]
      summary: List accessible design systems
      responses:
        '200':
          description: Design systems the authenticated user can access
          content:
            application/json:
              schema:
                type: object
                properties:
                  designSystems:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        name: { type: string }
                        data: { type: object, description: "Brand colours, fonts, logos, etc." }

  /api/design-systems/create:
    post:
      tags: [Design Systems]
      summary: Create a design system
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name, data]
              properties:
                name: { type: string }
                data:
                  type: object
                  description: "Brand data: colours, fonts, logos, etc."
      responses:
        '200':
          description: Created
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  id: { type: string, description: "Auto-generated slug from name" }
                  name: { type: string }
        '409':
          description: Design system with that ID already exists

  /api/design-systems/save:
    post:
      tags: [Design Systems]
      summary: Update a design system
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id, data]
              properties:
                id: { type: string }
                data: { type: object }
      responses:
        '200':
          description: Updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  id: { type: string }

  /api/design-systems/delete:
    post:
      tags: [Design Systems]
      summary: Delete a design system
      description: Cannot delete the "default" design system.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id: { type: string }
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  id: { type: string }

  # ── Projects ──────────────────────────────────────────
  /api/projects/list:
    get:
      tags: [Projects]
      summary: List projects
      parameters:
        - name: designSystemId
          in: query
          schema: { type: string }
          description: Filter by design system ID
        - name: includeTest
          in: query
          schema: { type: string }
          description: Pass 1 to include this caller's own projects whose names start with STRESS or with QA followed by a space or hyphen. Other people's test projects stay hidden. The editor omits this parameter.
        - name: scope
          in: query
          schema: { type: string, enum: [all] }
          description: Admin only. Pass all to list every project. Ignored unless the caller is an admin. The editor and the MCP list tool do not pass this.
      responses:
        '200':
          description: Project list
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  projects:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        filename: { type: string }
                        name: { type: string }
                        designSystemId: { type: string }
                        sceneCount: { type: integer }
                        savedAt: { type: string, format: date-time }

  /api/projects/{id}:
    get:
      tags: [Projects]
      summary: Get a project by ID
      parameters:
        - name: id
          in: path
          required: true
          schema: { type: string }
      responses:
        '200':
          description: Full project data
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  id: { type: string }
                  filename: { type: string }
                  project: { type: object, description: "Complete project JSON" }
        '404':
          description: Project not found

  /api/projects/save:
    post:
      tags: [Projects]
      summary: Create or update a project
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [filename, project]
              properties:
                filename: { type: string }
                project: { type: object, description: "Full project data" }
                projectId: { type: string, description: "If updating existing project" }
      responses:
        '200':
          description: Saved
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  id: { type: string }
                  filename: { type: string }

  /api/projects/delete:
    post:
      tags: [Projects]
      summary: Delete a project
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id: { type: string }
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }

  /api/projects/duplicate:
    post:
      tags: [Projects]
      summary: Duplicate a project
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id]
              properties:
                id: { type: string }
                sceneIds: { type: array, items: { type: string }, description: "Copy only these scenes, with every layer, format, framing, focus pin and the whole preset. Link families are kept among them." }
                name: { type: string, description: "Name of the copy. Default: \"<name> (Copy)\"." }
      responses:
        '200':
          description: Duplicated
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  id: { type: string, description: "New project ID" }
                  name: { type: string }
                  sceneCount: { type: integer }

  /api/projects/live-feed:
    get:
      tags: [Projects]
      summary: Your own editor live feed for a project
      description: The live feed (YouTube link and its look) belongs to the signed-in user, per project. It is never part of the project, so no other user, review link or export sees it.
      parameters:
        - { name: id, in: query, required: true, schema: { type: string, format: uuid } }
      responses:
        '200':
          description: Your feed, or null when you have not set one
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  feed: { type: object, nullable: true }
        '503': { description: Live feed storage is not set up yet }
    post:
      tags: [Projects]
      summary: Save or clear your own editor live feed for a project
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [id, feed]
              properties:
                id: { type: string, format: uuid }
                feed:
                  type: object
                  nullable: true
                  description: "{ source: off|youtube|screen|camera, youtubeUrl, opacity 0-100, mode: over|behind, fit: fit|cover, mouseFx? }. null clears it."
      responses:
        '200': { description: Saved }
        '400': { description: Invalid feed or YouTube link }
        '404': { description: Project not found or not yours to open }
        '429': { description: Rate limited }

  # ── AI Generation ─────────────────────────────────────
  /api/agent/add-scene:
    post:
      tags: [Agent]
      summary: Add one scene, or a duplicate of one, without sending the whole project (MCP add_scene)
      description: >-
        Appends a new scene (the create_project scene shape) or a deep copy of an existing scene with a new id.
        Existing scenes, their stateGroupIds and their layers are never changed, except a source that starts a family
        with linked true. A duplicate keeps every layer with its glyphs, layout boxes and per-layer motion; it is
        independent unless linked is true. The write is a
        compare-and-swap on the version read; pass revision to be refused if the project was saved since.
        At most 60 scenes per project.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                revision: { type: integer, description: "The revision from GET /api/projects/{id}. A different current revision is a 409 stale_version and nothing is written." }
                duplicateFrom:
                  type: object
                  description: "Copy this scene. Give sceneId or sceneIndex (0-based). Omit to add a new scene."
                  properties:
                    sceneId: { type: string }
                    sceneIndex: { type: integer }
                scene: { type: object, description: "A new scene: h1, h2, h3, cta, role, bgType, bgImage, colours, layout, notes, duration. Not with duplicateFrom." }
                fields: { type: object, description: "patch_scene fields set on the new scene only (name, h1, h2, bgImage, hidden, adCopy, ...). adCopy is post copy, edited on Selects and the review link, not in the Layout panel." }
                index: { type: integer, description: "Insert position (0-based). Default: the end." }
                linked: { type: boolean, default: false, description: "Duplicate only: join the source scene's linked family, after its last scene unless index is given. A source with no family starts a new one with the copy." }
                addToTimeline: { type: boolean, default: true, description: "An independent new scene is placed on the overview timeline, after its source when duplicating." }
      responses:
        '200':
          description: Scene added
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  sceneIndex: { type: integer }
                  name: { type: string }
                  stateGroupId: { type: string, nullable: true }
                  sceneCount: { type: integer }
                  revision: { type: integer, nullable: true, description: "The project revision after the write" }
                  duplicatedFrom: { type: string, nullable: true }
                  warnings: { type: array, items: { type: string } }
                  critique: { type: object }
        '400': { description: "Bad request, scene not found, or the 60-scene limit" }
        '409': { description: "stale_version: the project was saved since revision, or by the editor during the write. Nothing was written." }

  /api/agent/delete-scenes:
    post:
      tags: [Agent]
      summary: Delete scenes by id without sending the whole project (MCP delete_scene)
      description: >-
        Removes the scenes and cleans every reference to them: overview timeline and shared family heads pass to the
        next member of the family, play order, active scene, and layer links whose next scene is gone. Deleting every
        scene is refused. Compare-and-swap write; pass revision to be refused if the project was saved since.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId, sceneIds]
              properties:
                projectId: { type: string }
                sceneIds: { type: array, items: { type: string } }
                revision: { type: integer }
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  removed: { type: array, items: { type: string } }
                  sceneCount: { type: integer }
                  revision: { type: integer, nullable: true }
        '400': { description: "Unknown scene id, empty sceneIds, or every scene" }
        '409': { description: "stale_version: nothing was written." }

  /api/agent/move-scenes:
    post:
      tags: [Agent]
      summary: Copy or move scenes to another project or a new one (MCP move_scenes)
      description: >-
        Scenes keep every layer, format, per-format framing, focus pin, motion and ad copy. Link families are
        restricted to the moved scenes; scene ids, stateGroupIds and layer link ids that exist in the target are
        re-minted (idMap). A new project takes the source preset (colours, campaign, characterIds) and project
        settings. mode move writes the target first, then removes the scenes from the source (retried once on a
        newer copy); if that still fails the reply is 200 with sourceRemoved false and a warning.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [fromProjectId, sceneIds]
              properties:
                fromProjectId: { type: string }
                sceneIds: { type: array, items: { type: string } }
                toProjectId: { type: string, description: "Existing target. Pass this or newProjectName." }
                newProjectName: { type: string, description: "Create a new project. Pass this or toProjectId." }
                mode: { type: string, enum: [move, copy], default: move }
                revision: { type: integer, description: "Source revision" }
                toRevision: { type: integer, description: "Target revision" }
      responses:
        '200':
          description: Copied, and removed from the source for mode move
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  mode: { type: string }
                  toProjectId: { type: string }
                  created: { type: boolean }
                  sceneIds: { type: array, items: { type: string }, description: "The scene ids in the target" }
                  idMap: { type: object, description: "Source scene id to target scene id, when any was re-minted" }
                  sourceRemoved: { type: boolean }
                  sourceRevision: { type: integer, nullable: true }
                  targetRevision: { type: integer, nullable: true }
                  warnings: { type: array, items: { type: string } }
        '400': { description: "Bad request, unknown scene, every scene with mode move, or the 60-scene limit" }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the source or target open in the editor. Nothing was written." }

  /api/agent/patch-project:
    post:
      tags: [Agent]
      summary: Merge top-level project fields without sending the whole project (MCP update_project patch)
      description: >-
        preset merges key by key; other fields are replaced; null removes a key or field. scenes and designSystemId
        cannot be patched. Compare-and-swap write; pass revision to be refused if the project was saved since.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId, patch]
              properties:
                projectId: { type: string }
                patch: { type: object }
                revision: { type: integer }
      responses:
        '200':
          description: Patched
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  id: { type: string }
                  changed: { type: array, items: { type: string } }
                  revision: { type: integer, nullable: true }
        '400': { description: "Bad patch, scenes or designSystemId" }
        '409': { description: "stale_version: nothing was written." }

  /api/agent/preview-scene:
    post:
      tags: [Agent]
      summary: Render one scene to a PNG with a critique, including pixel contrast (MCP preview_scene)
      description: >-
        Renders the editor's own still of the scene (the review link render): layers, vector art and layout boxes
        drawn, hidden objects left out. Each visible text object is measured against the pixels behind it (the frame
        rendered again with the type transparent); type under 3:1 (large) or 4.5:1 (small), or with over 30% of its
        area on near-identical tones, is a low_contrast_image fail. Safe to call in parallel.
        Rate limit: "preview" preset (30 per 60s burst, 500 per 24h). A 429 response includes a descriptive
        error message and a Retry-After header.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                format: { type: string, enum: [square, portrait, vertical, landscape, wide] }
                t: { type: number, minimum: 0, maximum: 1, default: 1, description: "Scrub across the animation window; 1 is the final look" }
                image: { type: boolean, default: true, description: "false returns the critique only (critique_scene uses this)" }
                placement: { type: string, enum: [stories, reels, feed45, tiktok, youtube, meta_feed], description: "Where the ad runs. stories/reels/feed45/tiktok/youtube are checked at format vertical; meta_feed (Meta Feed caption/CTA overlay, bottom ~14% of the 4:5 frame) is checked at format portrait. Default: the scene's placement.vertical or placement.portrait, else stories." }
      responses:
        '200':
          description: Preview
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  format: { type: string }
                  width: { type: integer }
                  height: { type: integer }
                  renderer: { type: string, enum: [editor, simplified], description: "simplified only when the editor build could not run" }
                  rendererNote: { type: string }
                  image_base64: { type: string }
                  mimeType: { type: string }
                  critique:
                    type: object
                    properties:
                      ok: { type: boolean }
                      fails: { type: array, items: { type: object, properties: { code: { type: string }, message: { type: string } } } }
                      contrast:
                        type: array
                        description: "One entry per measured text object"
                        items:
                          type: object
                          properties:
                            role: { type: string, enum: [h1, h2, h3, cta, disclaimer] }
                            ok: { type: boolean }
                            skipped: { type: boolean }
                            ratio: { type: number, nullable: true, description: "Median WCAG contrast ratio against the pixels behind the text" }
                            lostShare: { type: number, nullable: true }
                            required: { type: number }
                            color: { type: string }
                            reason: { type: string }
        '429': { description: "Rate limited. Includes Retry-After header and a descriptive message, e.g. 'Preview rate limit: 30 per 60 seconds. Try again in 23s.'" }
        '503': { description: "The capture browser could not start; try again" }

  /api/agent/apply-physics:
    get:
      tags: [Agent]
      summary: List Animate Physics recipe names (MCP get_motion_skill companion)
      security:
        - apiKey: []
      responses:
        '200':
          description: Recipe names
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  recipes: { type: array, items: { type: string } }
        '401': { description: Missing or invalid API key }
    post:
      tags: [Agent]
      summary: Stamp a named physics recipe onto a scene (MCP apply_physics_recipe)
      description: >-
        Writes the recipe onto a vector layer. Does not invent gsapCode. The editor rebakes on load.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId, recipe]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                recipe: { type: string }
                layerId: { type: string }
                format: { type: string }
                seed: {}
                loop: {}
                glyph: { type: string }
                glyphScale: { type: number }
                markSvg: { type: string }
                particleMarks: { type: array, items: {} }
                createNew: { type: boolean }
      responses:
        '200':
          description: Stamped
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  markCount: { type: integer }
                  note: { type: string }
        '400': { description: "projectId or recipe missing, scene not found, or the stamp was refused" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/export-composition:
    post:
      tags: [Agent]
      summary: Build render-ready composition HTML (MCP export_composition_html)
      description: >-
        Same buildComposition output the editor posts to /api/renders/video. scope timeline (default)
        exports every scene; scope scene exports one scene. copyVariant is refused.
        Rate limit preset mcp_read.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                format: { type: string }
                scope: { type: string, enum: [timeline, scene], default: timeline }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                copyVariant: { type: string, description: "If present, 400. Copy combinations are no longer supported." }
      responses:
        '200':
          description: Composition HTML
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  projectId: { type: string }
                  html: { type: string }
                  width: { type: integer }
                  height: { type: integer }
                  format: { type: string }
                  scope: { type: string }
                  sceneCount: { type: integer }
                  durationSec: { type: number, nullable: true }
                  note: { type: string }
        '400': { description: "Bad scope, empty format, copyVariant, or a disabled format" }
        '404': { description: Project data missing }
        '429': { description: Rate limited }
        '500': { description: Read or export failed }

  /api/agent/link-layers:
    post:
      tags: [Agent]
      summary: Link vector layers across two scenes (MCP link_layers)
      description: >-
        Links layers so particles morph when each scene has its own formation and the same seed.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                fromSceneId: { type: string }
                fromSceneIndex: { type: integer }
                toSceneId: { type: string }
                toSceneIndex: { type: integer }
                layerId: { type: string }
                fromLayerId: { type: string }
                toLayerId: { type: string }
                seed: {}
                matchCounts: { type: boolean }
                preservePools: { type: boolean }
                parent: { type: string }
                toParent: { type: string }
      responses:
        '200':
          description: Linked
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  note: { type: string }
        '400': { description: "projectId or a scene endpoint missing, scene not found, or the link was refused" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/link-scenes:
    post:
      tags: [Agent]
      summary: Put scenes in one linked family (MCP link_scenes)
      description: >-
        Shares a stateGroupId. share defaults on. unlink clears stateGroupId on the given scenes.
        sceneIds are required. Linking needs at least two ids unless unlink is true.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId, sceneIds]
              properties:
                projectId: { type: string }
                sceneIds: { type: array, items: { type: string } }
                groupId: { type: string }
                share: { type: boolean }
                unlink: { type: boolean }
      responses:
        '200':
          description: Linked or unlinked
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  groupId: { type: string }
                  sceneIds: { type: array, items: { type: string } }
                  shareLinkedScenes: { type: boolean }
                  shareLinkedGroupIds: { type: array, items: { type: string } }
        '400': { description: "projectId or sceneIds missing, scene not found, or fewer than two scenes" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/motion-memory:
    get:
      tags: [Agent]
      summary: Recall exported motion patterns (MCP recall_motion)
      description: >-
        When the motion flag is off the reply is enabled false and an empty patterns list.
      parameters:
        - name: designSystemId
          in: query
          schema: { type: string }
        - name: limit
          in: query
          schema: { type: integer, default: 8 }
      responses:
        '200':
          description: Patterns, or an empty list when the feature is off
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  enabled: { type: boolean }
                  patterns: { type: array, items: { type: object } }
        '401': { description: Missing or invalid API key }

  /api/agent/motion-skill:
    get:
      tags: [Agent]
      summary: Load the motion skill prompt and data (MCP get_motion_skill)
      responses:
        '200':
          description: Skill
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  version: { type: string }
                  prompt: { type: string }
                  data: { type: object }
        '401': { description: Missing or invalid API key }

  /api/agent/patch-scene:
    post:
      tags: [Agent]
      summary: Patch fields on one scene (MCP patch_scene)
      description: >-
        fields must be an object. Does not read revision. Linked type copy can update other scenes
        in the family (sharedWith). The reply includes a critique.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId, fields]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                fields: { type: object }
      responses:
        '200':
          description: Patched
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  scene: { type: object }
                  sharedWith: { type: array, items: { type: string } }
                  critique: { type: object }
                  approvalCopySynced: { type: boolean }
        '400': { description: "projectId or fields missing, scene not found, or the patch was refused" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/set-geo-mask:
    get:
      tags: [Agent]
      summary: Read a scene geo mask and force group
      parameters:
        - name: projectId
          in: query
          required: true
          schema: { type: string }
        - name: sceneId
          in: query
          schema: { type: string }
        - name: sceneIndex
          in: query
          schema: { type: integer }
      responses:
        '200':
          description: Current mask
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  version: { type: string }
                  geoMask: { type: object, nullable: true }
                  forceGroup: { type: object, nullable: true }
        '400': { description: projectId missing or scene not found }
        '404': { description: Project data missing }
    post:
      tags: [Agent]
      summary: Set a scene geo mask and stamp it onto layers (MCP set_geo_mask)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                geoMask: {}
                forceGroup: {}
                forceFrom: { type: string }
                layerIds: { type: array, items: { type: string } }
      responses:
        '200':
          description: Written
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  geoMask: { type: object, nullable: true }
                  forceGroup: { type: object, nullable: true }
                  forceFrom: { type: string }
                  layerCount: { type: integer }
                  note: { type: string }
        '400': { description: "projectId missing, scene not found, or the mask SVG could not be loaded" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/set-glyph-overrides:
    get:
      tags: [Agent]
      summary: Read glyph overrides on a vector layer
      description: A GET, or a POST with overrides null, reads. A POST with overrides writes.
      parameters:
        - name: projectId
          in: query
          required: true
          schema: { type: string }
        - name: sceneId
          in: query
          schema: { type: string }
        - name: sceneIndex
          in: query
          schema: { type: integer }
        - name: layerId
          in: query
          schema: { type: string }
        - name: overrides
          in: query
          schema: {}
      responses:
        '200':
          description: Current overrides
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
        '400': { description: projectId missing or scene not found }
        '404': { description: Project data missing }
    post:
      tags: [Agent]
      summary: Write glyph overrides (MCP set_glyph_overrides)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                layerId: { type: string }
                overrides: { type: object, nullable: true, description: "Null reads. An object writes svg, char, colorOv, scale, slots." }
      responses:
        '200':
          description: Read or written
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  note: { type: string }
        '400': { description: "projectId missing, scene not found, or an override SVG could not be loaded" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/set-particle-marks:
    post:
      tags: [Agent]
      summary: Set particle mark size, colour, or SVG (MCP set_particle_marks)
      description: >-
        At least one of glyphScale, markSvg, particleMarks, color, or glyphColor is required.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                layerId: { type: string }
                glyphScale: { type: number }
                markSvg: { type: string }
                particleMarks: { type: array, items: {} }
                glyph: { type: string }
                color: { type: string }
                glyphColor: { type: string }
      responses:
        '200':
          description: Updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  note: { type: string }
        '400': { description: "Nothing to set, scene not found, or a mark SVG could not be loaded" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/stamp-formation:
    post:
      tags: [Agent]
      summary: Stamp a formation onto a vector layer (MCP stamp_formation)
      description: >-
        Requires points, svg, or text. Returns previewPng so the formation can be checked before a video render.
        Particle size is glyphScale (default 40).
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                layerId: { type: string }
                createNew: { type: boolean }
                svg: { type: string }
                points: { type: array, items: {} }
                count: { type: integer }
                format: { type: string }
                seed: {}
                loop: {}
                prompt: { type: string }
                glyph: { type: string }
                text: { type: string }
                sampleMode: { type: string }
                fillMode: { type: string }
                color: { type: string }
                glyphColor: { type: string }
                glyphScale: { type: number }
                markSvg: { type: string }
                particleMarks: { type: array, items: {} }
      responses:
        '200':
          description: Stamped
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  layerId: { type: string }
                  pointCount: { type: integer }
                  seed: {}
                  formats: {}
                  sampleMode: { type: string }
                  formationText: { type: string }
                  glyphScale: { type: number }
                  colorOv: { type: string }
                  markCount: { type: integer }
                  previewPng: { type: string }
                  previewError: { type: string }
                  note: { type: string }
        '400': { description: "No points, svg, or text, scene not found, or the stamp was refused" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/stamp-formation-stack:
    post:
      tags: [Agent]
      summary: Stamp a formation stack across one or two scenes (MCP stamp_formation_stack)
      description: >-
        projectId is required. The rest of the body is passed to the stack applier, including
        sceneId, sceneIndex, toSceneId, toSceneIndex, structure, plateType, field, phases, seed,
        loop, glyphScale, plates, forceFrom, glyphOverrides, softPlate, a, b, dualCompare, geoMask,
        markSvg, particleMarks, glyphColor, color, and format.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                toSceneId: { type: string }
                toSceneIndex: { type: integer }
                a: {}
                b: {}
                dualCompare: {}
                geoMask: {}
                markSvg: { type: string }
                particleMarks: { type: array, items: {} }
                glyphColor: { type: string }
                color: { type: string }
                format: { type: string }
                structure: { type: string }
                plateType: { type: string }
                field: {}
                phases: {}
                seed: {}
                loop: {}
                glyphScale: { type: number }
                plates: { type: array, items: {} }
                forceFrom: { type: string }
                glyphOverrides: {}
                softPlate: { type: boolean }
      responses:
        '200':
          description: Stamped
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  note: { type: string }
        '400': { description: "projectId missing, scene not found, SVG could not be loaded, or the stack was refused" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/agent/stamp-soft-plate:
    post:
      tags: [Agent]
      summary: Stamp a thin frosted plate under a mix stack (MCP stamp_soft_plate)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer }
                layerId: { type: string }
                createNew: { type: boolean }
                recipe: { type: string }
                preset: { type: string }
                opacity: { type: number }
                radius: { type: number }
                blur: { type: number }
                color: { type: string }
                plateColor: { type: string }
                glyph: { type: string }
      responses:
        '200':
          description: Stamped
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  note: { type: string }
        '400': { description: "projectId missing, scene not found, or the plate was refused" }
        '404': { description: Project data missing }
        '409': { description: "stale_version: nothing was written." }
        '423': { description: "Someone else has the project open in the editor. Nothing was written." }
        '500': { description: Failed to read or write the project }

  /api/approval/delete:
    post:
      tags: [Approval]
      summary: Delete approval items by review token (MCP delete_approval_items)
      description: >-
        Public. The review token authorises the call, not an API key. Does not rotate the token.
      security: []
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [token]
              properties:
                token: { type: string }
                itemId: { type: string }
                itemIds: { type: array, items: { type: string }, description: "itemId or a non-empty itemIds list is required." }
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  deleted: { type: array, items: { type: string } }
                  count: { type: integer }
        '400': { description: "token missing, or item ids are not non-empty strings" }
        '404': { description: Review feed or items not found }
        '500': { description: Database read or delete failed }

  /api/approval/feed:
    get:
      tags: [Approval]
      summary: List approval items for a review token (MCP list_approval_items)
      description: >-
        Public. The review token authorises the call, not an API key. Cache-Control is no-store.
        includeDecided defaults on; 0 returns pending items only.
      security: []
      parameters:
        - name: token
          in: query
          required: true
          schema: { type: string }
        - name: includeDecided
          in: query
          schema: { type: string, default: "1" }
          description: "0 means pending only. Anything else includes decided items."
        - name: project
          in: query
          schema: { type: string }
          description: Optional project id filter
      responses:
        '200':
          description: Feed
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  designSystem:
                    type: object
                    properties:
                      id: { type: string }
                      name: { type: string }
                      logoSvg: { type: string }
                      accent: { type: string }
                  items: { type: array, items: { type: object } }
        '400': { description: token required }
        '404': { description: Review feed not found }
        '500': { description: Database read failed }

  /api/approval/share:
    post:
      tags: [Approval]
      summary: Mint or return the review link (MCP create_review_link)
      description: >-
        Requires a project that has a design system, or a designSystemId. Write access is required.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                projectId: { type: string }
                designSystemId: { type: string }
      responses:
        '200':
          description: Review link
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  token: { type: string }
                  reviewUrl: { type: string }
                  minted: { type: boolean }
        '400': { description: "No design system on the project, and no designSystemId" }
        '401': { description: Missing or invalid API key }
        '403': { description: No write access }
        '404': { description: Project not found }

  /api/approval/submit:
    post:
      tags: [Approval]
      summary: Submit scenes for approval (MCP submit_for_approval)
      description: >-
        projectId and a non-empty sceneIds list are required. allowEmptyCopy lets an API-key caller
        submit a scene that has no primary text; otherwise that case is 400 missing_primary_text.
        Durable review media that fails the check is 422.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId, sceneIds]
              properties:
                projectId: { type: string }
                sceneIds: { type: array, items: { type: string } }
                previews: { type: object, additionalProperties: { type: string } }
                sceneMeta: { type: object }
                sequence: { type: boolean }
                allowEmptyCopy: { type: boolean }
      responses:
        '200':
          description: Submitted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  token: { type: string }
                  reviewUrl: { type: string }
                  count: { type: integer }
                  items: { type: array, items: { type: object } }
                  warnings: { type: array, items: { type: string } }
        '400': { description: "Bad body, project has no design system, unknown scene id, or missing primary text" }
        '401': { description: Missing or invalid API key }
        '403': { description: No access }
        '422': { description: Review media failed the durability check }
        '500': { description: Failed to load the project or write approval items }

  /api/genai/generate:
    post:
      tags: [AI Generation]
      summary: Generate an image from a text prompt
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                prompt: { type: string, description: "Text prompt for image generation" }
                model:
                  type: string
                  enum: [gpt-image-2.6-flare, gpt-image-2.6-sunburst, gpt-image-2.5-flare, gpt-image-2.5-sunburst, gpt-image-2, nano-banana-pro, krea-2, flux-2-pro, flux-3, ideogram-4.5, recraft-v3, recraft-v3-transparent, gpt-image-1, flux-dev, flux-pro, imagen4, imagen4-fast, ideogram-v3, ideogram-v2]
                  default: gpt-image-2.5-flare
                  description: "The last seven values (gpt-image-1, flux-dev, flux-pro, imagen4, imagen4-fast, ideogram-v3, ideogram-v2) are legacy aliases that run a current model. Omitted model uses gpt-image-2.5-flare. gpt-image-2.6-flare and gpt-image-2.6-sunburst accept quality, reasoning_effort, output_format (incl gif), frame_count, frame_duration_ms, and background."
                width: { type: integer, default: 2160 }
                height: { type: integer, default: 2160 }
                format: { type: string, description: "Ad format key (square, portrait, vertical, landscape, wide). Sets width and height when those are omitted." }
                filename: { type: string, default: generated.png }
                design_system_id: { type: string, description: "Optional. Appends that design system's saved global prompt when globalGenPrompt is omitted, and scopes the stored blob." }
                image_urls:
                  type: array
                  items: { type: string }
                  description: "Reference image URLs. Accepted only by models with a reference route, capped by that model: gpt-image-2.5-flare, gpt-image-2.5-sunburst, gpt-image-2 and ideogram-v3 take 16; nano-banana-pro takes 14; flux-2-pro, flux-dev and flux-pro take 9; flux-3 takes 10; ideogram-4.5 takes 5 (the first URL is the source). Any other model, including krea-2 and recraft-v3, rejects image_urls with 400. Over the cap is 400. The handler does not read sceneImageUrl or projectId."
                characterIds:
                  type: array
                  items: { type: string }
                  description: "Character ids belonging to design_system_id. A selection that fails validation is 422."
      responses:
        '200':
          description: Image generated
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string, description: "Vercel Blob URL" }
                  filename: { type: string }
                  cdn_url: { type: string, description: "Upstream CDN URL" }

  /api/genai/outpaint:
    post:
      tags: [AI Generation]
      summary: Extend image edges with AI outpainting
      description: Expand an image in any direction using AI. Send the image as a base64 data URI.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [image_data]
              properties:
                image_data: { type: string, description: "Base64 data URI of the source image" }
                expand_top: { type: integer, default: 0, description: "Pixels to expand at top" }
                expand_bottom: { type: integer, default: 0 }
                expand_left: { type: integer, default: 0 }
                expand_right: { type: integer, default: 0 }
                filename: { type: string, default: extended.png }
      responses:
        '200':
          description: Image extended
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string }
                  filename: { type: string }

  /api/genai/enhance:
    post:
      tags: [AI Generation]
      summary: Upscale/enhance an image
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [image_url]
              properties:
                image_url: { type: string }
                model:
                  type: string
                  enum: [aura-sr, creative-upscaler, clarity-upscaler]
                  default: aura-sr
                filename: { type: string, default: enhanced.png }
      responses:
        '200':
          description: Image enhanced
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  url: { type: string }
                  filename: { type: string }

  /api/genai/retouch:
    post:
      tags: [AI Generation]
      summary: Retouch regions of an image (erase or inpaint)
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [image_url, mask_url]
              properties:
                image_url: { type: string }
                mask_url: { type: string, description: "Black/white mask; white areas get retouched" }
                mode: { type: string, enum: [erase, inpaint], default: erase, description: "Erase removes objects; inpaint replaces with prompt-described content. Any mode other than erase is treated as inpaint." }
                prompt: { type: string, default: "", description: "Required for inpaint mode, ignored for erase" }
                model:
                  type: string
                  description: "Omit to use the mode default. Erase accepts only fal-ai/flux-pro/v1/erase (also the erase default). Inpaint accepts fal-ai/bria/genfill (default), fal-ai/flux-pro/v1/fill, fal-ai/flux-lora/inpainting, fal-ai/flux-general/inpainting. An explicit model outside that mode's list is 400 and is not charged."
                filename: { type: string, default: retouched.png }
      responses:
        '200':
          description: Image retouched
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  url: { type: string }
                  filename: { type: string }

  /api/genai/crop:
    post:
      tags: [AI Generation]
      summary: Crop an image
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [image_url]
              properties:
                image_url: { type: string }
                crop_top: { type: number, default: 0, description: "Percentage to crop from top (0-40)" }
                crop_bottom: { type: number, default: 0 }
                crop_left: { type: number, default: 0 }
                crop_right: { type: number, default: 0 }
                frame_width: { type: integer, description: "Frame width in pixels (for scale-aware crop)" }
                frame_height: { type: integer }
                bg_scale: { type: number, default: 100 }
                focus_x: { type: number, default: 50 }
                focus_y: { type: number, default: 50 }
                filename: { type: string, default: cropped.png }
      responses:
        '200':
          description: Image cropped
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string }
                  filename: { type: string }
                  width: { type: integer }
                  height: { type: integer }

  /api/genai/vector:
    post:
      tags: [AI Generation]
      summary: Generate an editable SVG
      description: Recraft V4.1 stays the default for logos, ridge lines and posters. Ideogram supports reference-matched brand marks and lettering. Provider prices per SVG are USD 0.08 for Recraft; Ideogram low 0.13, medium 0.16, high 0.20, high with references 0.32, before Wildfield markup. Recraft ignores references and viewBox.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [prompt]
              properties:
                prompt: { type: string }
                model: { type: string, enum: [recraft-v4.1, ideogram-vector], default: recraft-v4.1 }
                quality: { type: string, enum: [low, medium, high], default: medium }
                aspect_ratio: { type: string, enum: [auto, '1:1', '1:4', '1:3', '1:2', '9:16', '10:16', '2:3', '3:4', '4:5', '5:4', '4:3', '3:2', '16:10', '16:9', '2:1', '3:1', '4:1'], default: auto }
                seed: { type: integer }
                references:
                  type: array
                  maxItems: 5
                  description: Ideogram only, 10 MB per image, first image is primary
                  items: { $ref: '#/components/schemas/VectorImageInput' }
                viewBox: { type: string, description: Legacy accepted but ignored input }
                filename: { type: string, default: generated.svg }
      responses:
        '200':
          description: SVG generated and billed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/VectorResult' }
        '400': { description: Invalid model, quality, aspect, references or image input }

  /api/genai/image-to-vector:
    post:
      tags: [AI Generation]
      summary: Trace an image into an editable SVG
      description: Ideogram traces a logo, plate or brand still for Vector layers, formations and marks. Detailed keeps finer detail for flat logos; simple uses fewer shapes for photos. PNG, JPEG or WebP up to 50 MB. Provider cost USD 0.10 per SVG before Wildfield markup. Supply exactly one imageUrl or upload.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              oneOf:
                - required: [imageUrl]
                - required: [upload]
              properties:
                imageUrl: { type: string, description: Public HTTP(S) URL or data URI }
                upload: { $ref: '#/components/schemas/VectorImageInput' }
                mode: { type: string, enum: [detailed, simple, default], default: detailed, description: detailed maps to the provider default mode }
                filename: { type: string, default: generated.svg }
      responses:
        '200':
          description: SVG traced and billed
          content:
            application/json:
              schema: { $ref: '#/components/schemas/VectorResult' }
        '400': { description: Invalid mode, image type or image size }

  /api/genai/list:
    get:
      tags: [AI Generation]
      summary: List generated images
      responses:
        '200':
          description: Generated images
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  images:
                    type: array
                    items:
                      type: object
                      properties:
                        url: { type: string }
                        filename: { type: string }
                        uploadedAt: { type: string, format: date-time }
                        size: { type: integer }

  /api/genai/save-image:
    post:
      tags: [AI Generation]
      summary: Save an image URL to storage
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url: { type: string }
                filename: { type: string, default: generated.png }
      responses:
        '200':
          description: Image saved
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string }
                  filename: { type: string }

  /api/genai/edit:
    post:
      tags: [AI Generation]
      summary: Natural-language image editing
      description: >
        Edit an image with a text instruction (e.g. "make the background blurry") via fal.ai.
        The `ideogram-rembg` model removes the background and ignores the prompt; all other models
        require a prompt.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [image_url]
              properties:
                image_url: { type: string, description: "Public URL of the source image" }
                prompt: { type: string, default: "", description: "Edit instruction (required unless model is ideogram-rembg)" }
                model:
                  type: string
                  enum: [gpt-image-2.6-flare, gpt-image-2.6-sunburst, gpt-image-2.5-flare, gpt-image-2.5-sunburst, gpt-image-2, nano-banana-pro, nano-banana-2, nano-banana, flux-kontext, qwen-edit, seedream-edit, ideogram-rembg, flux-2-pro, flux-3, ideogram-4.5]
                  default: nano-banana-pro
                  description: "Default when omitted is nano-banana-pro (the edit handler's default, not the generate default). nano-banana-2 runs Nano Banana 2.1 (google/nano-banana-2.1/edit). An unknown key falls back to nano-banana-pro and its reference cap of 14."
                filename: { type: string, default: edited.png }
                design_system_id: { type: string, description: "Optional. Scopes the stored blob path" }
                format: { type: string, description: "Ad format key (square, portrait, vertical, landscape, wide). Locks the output aspect when width and height are omitted." }
                width: { type: integer, description: "Output width in pixels. Sent with height, this is preferred over format." }
                height: { type: integer, description: "Output height in pixels. Sent with width." }
                image_urls:
                  type: array
                  items: { type: string }
                  description: "Extra reference URLs. Deduped together with image_url, then capped: gpt-image-2.5-flare, gpt-image-2.5-sunburst and gpt-image-2 take 16; nano-banana-pro and nano-banana-2 take 14; flux-3 and seedream-edit take 10; flux-2-pro takes 9; ideogram-4.5 takes 5; nano-banana takes 3; flux-kontext, qwen-edit and ideogram-rembg take 1. Over the cap is 400."
      responses:
        '200':
          description: Image edited
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string, description: "Vercel Blob URL" }
                  url: { type: string }
                  filename: { type: string }
                  cdn_url: { type: string, description: "Upstream fal CDN URL" }

  /api/genai/inpaint:
    post:
      tags: [AI Generation]
      summary: Inpaint masked regions of an image
      description: >
        Backwards-compatible alias of `/api/genai/retouch` with `mode` defaulting to `inpaint`.
        White areas of the mask are replaced with prompt-described content.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [image_url, mask_url]
              properties:
                image_url: { type: string }
                mask_url: { type: string, description: "Black/white mask; white areas get inpainted" }
                mode: { type: string, enum: [erase, inpaint], default: inpaint }
                prompt: { type: string, default: "", description: "Content to inpaint into the masked region" }
                model:
                  type: string
                  description: "Same allow list as /api/genai/retouch. This route defaults mode to inpaint, whose default model is fal-ai/bria/genfill. An explicit unknown model is 400."
                filename: { type: string, default: retouched.png }
      responses:
        '200':
          description: Image inpainted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  url: { type: string }
                  filename: { type: string }

  /api/genai/animate:
    post:
      tags: [AI Generation]
      summary: Generate a GSAP animation for a scene or element
      description: >
        Uses Claude to author GSAP 3 JavaScript. Scene mode (`scene: true`) returns one coordinated
        timeline across an element manifest; legacy per-element mode targets a single element by token.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              properties:
                scene: { type: boolean, description: "When true, use scene-level mode (requires prompt + elements)" }
                prompt: { type: string, description: "Natural-language description of the desired motion" }
                elements:
                  type: array
                  description: "Scene mode: element manifest. Each item has token, selector, label, and optional content."
                  items:
                    type: object
                    properties:
                      token: { type: string }
                      selector: { type: string }
                      label: { type: string }
                      content: { type: string }
                element: { type: string, description: "Per-element mode: element token (e.g. bg, h1, h2, ctaText, logo)" }
                cssClass: { type: string, description: "Per-element mode: override CSS class for an unknown element" }
                content: { type: string, description: "Per-element mode: current text/background of the element" }
                duration: { type: number, default: 3, minimum: 0, maximum: 30, description: "Scene duration in seconds, 0.1 to 30 (0 or omitted = 3). Under 0.1 is refused (400) for API writes." }
                format: { type: string }
                width: { type: integer, default: 1080 }
                height: { type: integer, default: 1080 }
      responses:
        '200':
          description: GSAP code generated
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  gsapCode: { type: string, description: "Executable GSAP JavaScript" }
                  genSceneDuration: { type: number, description: "Per-element mode: duration the timings were baked against" }

  /api/genai/enhance-video:
    post:
      tags: [AI Generation]
      summary: AI upscale / enhance a video
      description: >
        Upscales and cleans up a video via fal.ai (Topaz or video-upscaler). Long-running: the
        function polls the fal queue and re-hosts the result to Vercel Blob.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [video_url]
              properties:
                video_url: { type: string, description: "Public URL of the source video" }
                model: { type: string, enum: [topaz, video-upscaler], default: topaz }
                strength: { type: number, description: "0–1; >0.55 triggers a 4× upscale, otherwise 2×" }
                filename: { type: string, default: ai-enhanced.mp4 }
                design_system_id: { type: string, description: "Optional. Scopes the stored blob path" }
      responses:
        '200':
          description: Video enhanced
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  url: { type: string, description: "Vercel Blob URL (falls back to fal URL on re-host failure)" }

  /api/genai/delete:
    post:
      tags: [AI Generation]
      summary: Delete a generated image or upload
      description: >
        Deletes a blob by URL. Generations (`image-gen/...`) require admin, ownership, or design-system
        access; uploads (`uploads/...`) may be deleted by any authenticated user.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url: { type: string, description: "Blob URL to delete" }
      responses:
        '200':
          description: Deleted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }

  # ── Renders ───────────────────────────────────────────
  /api/renders/active:
    get:
      tags: [Renders]
      summary: The caller's in-flight video render, if any (MCP get_active_render)
      description: >-
        No query parameters. When the render state machine is unset, or the lookup fails,
        the reply is 200 with active null and unavailable true.
      responses:
        '200':
          description: Active render or none
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  unavailable: { type: boolean }
                  active:
                    nullable: true
                    type: object
                    properties:
                      renderId: { type: string }
                      executionArn: { type: string }
                      startedAt: { type: string }
        '401': { description: Missing or invalid API key }

  /api/renders/cancel:
    post:
      tags: [Renders]
      summary: Stop a video render and refund it (MCP cancel_render)
      description: >-
        executionArn must belong to this render state machine and to this account.
        A render that is already finished is left as it is.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [executionArn]
              properties:
                executionArn: { type: string }
      responses:
        '200':
          description: Stopped, or already finished
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  renderId: { type: string }
                  status: { type: string }
                  stopped: { type: boolean }
                  alreadyFinished: { type: boolean }
                  refund: { type: object }
                  artifacts: { type: object }
        '400': { description: "Missing, invalid, or foreign executionArn" }
        '403': { description: "NOT_YOUR_RENDER: this account did not start it" }
        '500': { description: "Render infrastructure is not configured, or the stop failed" }

  /api/renders/video:
    post:
      tags: [Renders]
      summary: Start a video render
      description: >
        Deploys the supplied HTML to the HyperFrames AWS Lambda render pipeline and starts an async
        render. Returns immediately with a render handle; poll `GET /api/renders/progress` with the
        `executionArn` to track status and retrieve the finished video URL.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [html, width, height]
              properties:
                html: { type: string, description: "Complete HTML document to render" }
                width: { type: integer }
                height: { type: integer }
                fps: { type: integer, default: 30 }
                quality: { type: string, default: high }
                format: { type: string, default: mp4 }
                loops:
                  type: integer
                  minimum: 1
                  maximum: 8
                  default: 1
                  description: >
                    Export the video repeated this many times. Validated here and refused (400) when it is
                    out of range or fractional, but ACTED ON by /api/renders/progress: the composition is
                    rendered once and the finished MP4 is repeated, so the render price does not multiply.
                    Pass the same value to /api/renders/progress.
      responses:
        '200':
          description: Render started
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  renderId: { type: string }
                  executionArn: { type: string, description: "Pass to /api/renders/progress to poll" }
                  loops: { type: integer, description: "The loop count this render was started with (1 when not asked for). Pass it to /api/renders/progress." }

  /api/renders/progress:
    get:
      tags: [Renders]
      summary: Check video render progress
      parameters:
        - name: executionArn
          in: query
          required: true
          schema: { type: string }
          description: The executionArn returned by /api/renders/video
        - name: filename
          in: query
          schema: { type: string, default: output.mp4 }
          description: Suggested download filename for the signed URL
        - name: loops
          in: query
          schema: { type: integer, minimum: 1, maximum: 8, default: 1 }
          description: >
            Repeat the finished video this many times, 1 to 8. The picture is stream-copied (the join is
            frame-exact) and the audio is re-encoded once from a sample-exact PCM loop (the join does not
            click). Out of range or fractional is refused with 400. Send `dur` (one pass, in seconds, as
            returned by /api/renders/video as durationSec) with it: each pass's audio is trimmed to it,
            without which the join carries the ~11ms of encoder padding that runs past the last frame.
      responses:
        '200':
          description: Current render status (videoUrl present once SUCCEEDED)
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  status: { type: string, description: "e.g. RUNNING, SUCCEEDED, FAILED" }
                  progress: { type: number, description: "Overall progress 0–1" }
                  framesRendered: { type: integer }
                  totalFrames: { type: integer }
                  costs: { type: object }
                  errors: { type: array, items: { type: object } }
                  videoUrl: { type: string, description: "Signed download URL (only when SUCCEEDED)" }
                  fileSize: { type: integer, description: "Output size in bytes (only when SUCCEEDED). The ORIGINAL single-pass render; a looped download is longer." }
                  loops: { type: integer, description: "The loop count applied (1 = the single pass)" }
                  looped: { type: boolean, description: "True when the returned URL is the repeated video" }

  /api/renders/screenshot:
    post:
      tags: [Renders]
      summary: Render HTML to a PNG screenshot
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [html, width, height]
              properties:
                html: { type: string, description: "Complete HTML document" }
                width: { type: integer, maximum: 4096, description: "CSS pixels" }
                height: { type: integer, maximum: 4096, description: "CSS pixels" }
                scale:
                  type: integer
                  minimum: 1
                  maximum: 4
                  default: 1
                  description: "Device pixels per CSS pixel. The PNG is width*scale x height*scale, capped at 8192px a side. The in-app PNG export sends 2."
      responses:
        '200':
          description: PNG image binary
          content:
            application/octet-stream:
              schema:
                type: string
                format: binary

  /api/renders/save:
    post:
      tags: [Renders]
      summary: Save a rendered image
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [dataUri]
              properties:
                dataUri: { type: string, description: "Base64 data URI" }
                filename: { type: string, default: render.png }
      responses:
        '200':
          description: Saved
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  filename: { type: string }
                  path: { type: string }

  # ── Uploads ───────────────────────────────────────────
  /api/uploads/image:
    post:
      tags: [Uploads]
      summary: Upload an image file
      description: Send raw binary image data (not JSON). Set Content-Type to the image MIME type.
      parameters:
        - name: filename
          in: query
          schema: { type: string }
      requestBody:
        required: true
        content:
          image/png:
            schema: { type: string, format: binary }
          image/jpeg:
            schema: { type: string, format: binary }
          image/webp:
            schema: { type: string, format: binary }
      responses:
        '200':
          description: Uploaded
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  url: { type: string }

  /api/uploads/audio-url:
    post:
      tags: [Uploads]
      summary: Import an audio file from a URL
      description: Wildfield fetches a public http(s) audio URL (mp3, wav, ogg, aac, m4a, webm) and stores it in Blob. Up to 500 MB per file, so full-length songs work. This is what MCP upload_audio calls.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url: { type: string }
                filename: { type: string, default: audio.mp3 }
      responses:
        '200':
          description: Imported
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  url: { type: string }
                  bytes: { type: integer }
                  contentType: { type: string }
        '413':
          description: Over the 500 MB limit

  /api/uploads/audio:
    post:
      tags: [Uploads]
      summary: Upload an audio file
      description: Send raw binary audio data (not JSON). Set Content-Type to the audio MIME type. The request body is limited to 4.5 MB (a Vercel function limit); for a longer song use /api/uploads/audio-url or the app's direct upload (up to 500 MB).
      parameters:
        - name: filename
          in: query
          schema: { type: string, default: upload.mp3 }
      requestBody:
        required: true
        content:
          audio/mpeg:
            schema: { type: string, format: binary }
          audio/wav:
            schema: { type: string, format: binary }
          audio/ogg:
            schema: { type: string, format: binary }
          audio/mp4:
            schema: { type: string, format: binary }
      responses:
        '200':
          description: Uploaded
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  url: { type: string }

  /api/uploads/client-token:
    post:
      tags: [Uploads]
      summary: Issue a Vercel Blob client-upload token
      description: >
        Returns a token for direct browser-to-Blob uploads (up to 500MB) of image and video files,
        used with `@vercel/blob/client`. The request/response bodies follow the Vercel Blob client
        upload protocol.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              description: "Vercel Blob client upload handshake payload"
      responses:
        '200':
          description: Token / completion response (Vercel Blob client upload protocol)
          content:
            application/json:
              schema:
                type: object

  # ── Capture ───────────────────────────────────────────
  /api/agent/create-vector-layer:
    post:
      tags: [Agent]
      summary: Create a vector layer (glyph mark, or a Code mode SVG)
      description: >
        Mints a new vector layer on a scene. Without svg it carries one glyph mark for physics and
        formation tools. With svg (v1.1106.0) the artwork is a Code mode SVG: it is sanitised against
        an allowlist (script, foreignObject, event handlers, javascript: URLs, external href and url()
        and @import are removed; internal #refs stay; data: only for raster images), every group and
        path gets a stable id (kept on re-import), and fill, stroke and stop colours map to the
        design system tokens within colorTolerance. Unmatched colours are left as they are and listed.
        The art covers the project's active format at 100%. get_project returns the stored SVG and its
        ids under codeVectors.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [projectId]
              properties:
                projectId: { type: string }
                sceneId: { type: string }
                sceneIndex: { type: integer, description: "0-based" }
                name: { type: string, description: "Layer name (default Vector N)" }
                glyph: { type: string, description: "Character for the mark (default *). Not with svg." }
                glyphScale: { type: number, description: "Particle mark size 20 to 200 (default 40)" }
                color: { type: string, description: "Particle colour hex (alias glyphColor)" }
                glyphColor: { type: string }
                svg: { type: string, description: "SVG markup, or an https URL to one, for a Code mode layer" }
                colorTolerance: { type: number, default: 5, description: "With svg: CIE76 delta E for a colour to take a token" }
      responses:
        '200':
          description: Layer created
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  sceneId: { type: string }
                  layerId: { type: string }
                  glyphId: { type: string, description: "With svg" }
                  name: { type: string }
                  code:
                    type: object
                    description: "With svg: the import result"
                    properties:
                      svg: { type: string, description: "The stored, sanitised SVG" }
                      ids: { type: array, items: { type: string }, description: "Every part id, document order" }
                      parts: { type: array, items: { type: object }, description: "The parts tree: id, tag, tokens, hidden, locked, children" }
                      tokens: { type: array, items: { type: object }, description: "Each mapped paint: id, prop, token, from, to, distance" }
                      unmatched: { type: array, items: { type: object }, description: "Colours left as they are: color, count, ids, nearest" }
                      removed: { type: object, description: "Counts of what the sanitiser removed, by kind" }
                      summary: { type: string }
                      warnings: { type: array, items: { type: string } }
                      box: { type: object, description: "The art box in px at scale 100 (w, h)" }
        '400':
          description: Missing projectId, scene not found, or the SVG could not be imported
        '423':
          description: The project is open in the editor by someone else

  /api/capture/url:
    post:
      tags: [Capture]
      summary: Screenshot a live website
      description: >
        Navigates to a URL in headless Chrome, auto-scrolls to trigger lazy-loaded content, and
        returns a PNG. Private/loopback hosts are blocked. Returns binary, not JSON.
        It costs no credits and shares the 'render' rate limit (6 per minute, 100 per day, per user)
        with the other headless Chrome endpoint, POST /api/renders/screenshot.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url: { type: string, description: "http(s) URL to capture" }
                width: { type: integer, default: 1280, maximum: 4096 }
                height: { type: integer, default: 720, maximum: 4096 }
                fullPage: { type: boolean, default: false, description: "Capture the entire scrollable page" }
      responses:
        '200':
          description: PNG image binary
          content:
            application/octet-stream:
              schema: { type: string, format: binary }

  /api/capture/frame-check:
    post:
      tags: [Capture]
      summary: Check whether a web page can be shown in an iframe
      description: >
        Used by the editor's live feed "Web page" source before it frames a page. Reads only the
        target's response headers (a HEAD request, then a one-byte ranged GET if HEAD is refused) and
        applies the browser rules: an enforced Content-Security-Policy frame-ancestors directive
        decides when present (Content-Security-Policy-Report-Only is ignored), otherwise
        X-Frame-Options (DENY or conflicting values refuse, SAMEORIGIN allows only a Wildfield page,
        invalid values are ignored). The page is judged against https://wildfield.io,
        https://www.wildfield.io and the request's own https Origin. A page whose final URL is http is
        refused as insecure (mixed content). No body content from the target is ever returned.
        Private, loopback and metadata addresses are refused, including through DNS and redirects
        (at most 4 redirects). Verdicts are cached for 5 minutes. Rate limited to 30 per minute per
        user. Costs no credits.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [url]
              properties:
                url: { type: string, maxLength: 2048, description: "http(s) URL without a username or password" }
      responses:
        '200':
          description: Verdict
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  status:
                    type: string
                    enum: [allowed, refused, unreachable]
                    description: "unreachable: the page answered 4xx/5xx, timed out (5 s) or failed on the network"
                  reason:
                    type: string
                    description: "ok, xfo-deny, xfo-sameorigin, xfo-allow-from, csp-frame-ancestors, insecure, http-<status>, timeout or network"
                  finalUrl: { type: string, description: "URL after redirects" }
                  insecure: { type: boolean, description: "The final URL is http" }
                  cached: { type: boolean, description: "Answered from the 5 minute cache" }
        '400': { description: "Missing, malformed, too long, non-http(s) or credential-bearing url" }
        '401': { description: Not signed in }
        '403': { description: "The address is private or otherwise blocked. { ok: false, code: blocked_host, error }" }
        '429': { description: "Rate limited. Retry-After header; { ok: false, code: rate_limited, error, retryAfter }" }

  # ── Integrations ──────────────────────────────────────
  # NOTE: OAuth connect/callback/disconnect + gdrive/token + auth/callback are browser
  # session/redirect flows and are intentionally NOT documented here (see info.description).
  /api/integrations/status:
    get:
      tags: [Integrations]
      summary: Connected cloud providers
      description: >
        Returns which providers the user has connected (no tokens) plus whether the server has app
        credentials and the Google Picker config. This endpoint returns an unwrapped object.
      responses:
        '200':
          description: Integration status
          content:
            application/json:
              schema:
                type: object
                properties:
                  dropbox:
                    type: object
                    properties:
                      connected: { type: boolean }
                      accountName: { type: string, nullable: true }
                      configured: { type: boolean }
                  gdrive:
                    type: object
                    properties:
                      connected: { type: boolean }
                      accountName: { type: string, nullable: true }
                      configured: { type: boolean }
                      pickerApiKey: { type: string, nullable: true }
                      appId: { type: string, nullable: true }

  /api/integrations/dropbox/link:
    get:
      tags: [Integrations]
      summary: Get a temporary direct link to a Dropbox file
      parameters:
        - name: path
          in: query
          required: true
          schema: { type: string }
          description: "Dropbox path to the file, e.g. /folder/file.jpg"
      responses:
        '200':
          description: Temporary link (~4h)
          content:
            application/json:
              schema:
                type: object
                properties:
                  link: { type: string }
                  name: { type: string, nullable: true }
        '409':
          description: Dropbox not connected

  /api/integrations/dropbox/list:
    get:
      tags: [Integrations]
      summary: List Dropbox subfolders and media files
      parameters:
        - name: path
          in: query
          schema: { type: string }
          description: "Dropbox path; empty or '/' lists the root"
      responses:
        '200':
          description: Folders and media files at the path
          content:
            application/json:
              schema:
                type: object
                properties:
                  path: { type: string }
                  folders:
                    type: array
                    items:
                      type: object
                      properties:
                        name: { type: string }
                        path: { type: string }
                        pathDisplay: { type: string }
                  files:
                    type: array
                    items:
                      type: object
                      properties:
                        name: { type: string }
                        path: { type: string }
                        pathDisplay: { type: string }
                        kind: { type: string, enum: [image, video] }
                        size: { type: integer }
        '409':
          description: Dropbox not connected

  /api/integrations/dropbox/mkdir:
    post:
      tags: [Integrations]
      summary: Create a Dropbox folder
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [path]
              properties:
                path: { type: string, description: "Folder path to create (autorenames on conflict)" }
      responses:
        '200':
          description: Folder created
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string }
                  name: { type: string }
        '409':
          description: Dropbox not connected

  /api/integrations/dropbox/upload:
    post:
      tags: [Integrations]
      summary: Relay a public URL into Dropbox
      description: >
        Server fetches the public `srcUrl` and uploads the bytes to Dropbox at `destPath`.
        Single-shot, ≤150MB.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [srcUrl, destPath]
              properties:
                srcUrl: { type: string, description: "Public URL to fetch" }
                destPath: { type: string, description: "Destination Dropbox path" }
      responses:
        '200':
          description: Uploaded
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string }
                  name: { type: string }
        '409':
          description: Dropbox not connected
        '413':
          description: File exceeds the 150MB single-shot limit

  /api/integrations/gdrive/link:
    get:
      tags: [Integrations]
      summary: Get a signed, expiring URL for a Drive file
      description: >
        Returns a signed same-origin URL (served by /api/integrations/gdrive/file) that streams the
        Drive file, usable as an img/video src.
      parameters:
        - name: path
          in: query
          required: true
          schema: { type: string }
          description: "Google Drive file ID"
      responses:
        '200':
          description: Signed link
          content:
            application/json:
              schema:
                type: object
                properties:
                  link: { type: string }

  /api/integrations/gdrive/file:
    get:
      tags: [Integrations]
      summary: Stream a Drive file's bytes
      description: >
        Streams the file's bytes. Authorized by the HMAC-signed query params issued by
        /api/integrations/gdrive/link (NOT an API key or session), so it works as an img/video src.
        Forwards Range requests.
      parameters:
        - name: id
          in: query
          required: true
          schema: { type: string }
          description: "Google Drive file ID"
        - name: u
          in: query
          required: true
          schema: { type: string }
          description: "Signed user identifier"
        - name: exp
          in: query
          required: true
          schema: { type: string }
          description: "Signature expiry"
        - name: sig
          in: query
          required: true
          schema: { type: string }
          description: "HMAC signature"
      security: []
      responses:
        '200':
          description: File bytes (200, or 206 for Range requests)
          content:
            application/octet-stream:
              schema: { type: string, format: binary }
        '403':
          description: Invalid or expired signature

  /api/integrations/gdrive/mkdir:
    post:
      tags: [Integrations]
      summary: Create a Google Drive folder
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [name]
              properties:
                name: { type: string }
                parent: { type: string, description: "Parent folder ID; omit or 'root' for My Drive root" }
      responses:
        '200':
          description: Folder created
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string, description: "New folder ID" }
                  name: { type: string }
        '409':
          description: Google Drive not connected

  /api/integrations/gdrive/upload:
    post:
      tags: [Integrations]
      summary: Relay a public URL into Google Drive
      description: >
        Server fetches the public `srcUrl` and uploads it into Drive as `name`. `destPath` is an
        optional folder ID; when omitted the app's auto-created "Wildfield" folder is used. Single-shot,
        ≤150MB.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [srcUrl, name]
              properties:
                srcUrl: { type: string, description: "Public URL to fetch" }
                name: { type: string, description: "Filename in Drive" }
                destPath: { type: string, description: "Destination folder ID (optional)" }
      responses:
        '200':
          description: Uploaded
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
                  path: { type: string, description: "New file ID" }
                  name: { type: string }
        '409':
          description: Google Drive not connected
        '413':
          description: File exceeds the 150MB single-shot limit

  # ── Admin ─────────────────────────────────────────────
  # All admin endpoints additionally require an admin account (requireAdmin).
  /api/admin/access:
    post:
      tags: [Admin]
      summary: Grant a user access to a design system
      description: Requires an admin account.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [userId, designSystemId]
              properties:
                userId: { type: string }
                designSystemId: { type: string }
                role: { type: string, default: editor }
      responses:
        '200':
          description: Access granted
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }
    delete:
      tags: [Admin]
      summary: Revoke a user's access to a design system
      description: Requires an admin account.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [userId, designSystemId]
              properties:
                userId: { type: string }
                designSystemId: { type: string }
      responses:
        '200':
          description: Access revoked
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }

  /api/admin/users:
    get:
      tags: [Admin]
      summary: List all users with profiles and access
      description: Requires an admin account.
      responses:
        '200':
          description: User list
          content:
            application/json:
              schema:
                type: object
                properties:
                  users:
                    type: array
                    items:
                      type: object
                      properties:
                        id: { type: string }
                        email: { type: string }
                        displayName: { type: string, nullable: true }
                        isAdmin: { type: boolean }
                        approved: { type: boolean }
                        createdAt: { type: string, format: date-time }
                        access:
                          type: array
                          items:
                            type: object
                            properties:
                              designSystemId: { type: string }
                              role: { type: string }
    patch:
      tags: [Admin]
      summary: Update a user (toggle admin / approval)
      description: Requires an admin account. Provide isAdmin and/or approved.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [userId]
              properties:
                userId: { type: string }
                isAdmin: { type: boolean }
                approved: { type: boolean }
      responses:
        '200':
          description: Updated
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }

  /api/admin/usage:
    get:
      tags: [Admin]
      summary: Usage and cost report
      description: Requires an admin account. Aggregates the usage log per user with pricing.
      parameters:
        - name: period
          in: query
          schema: { type: string, default: 30d }
          description: "Look-back window, e.g. 30d, 7d"
        - name: user_id
          in: query
          schema: { type: string }
          description: "Filter to a single user"
      responses:
        '200':
          description: Usage report
          content:
            application/json:
              schema:
                type: object
                properties:
                  period: { type: string }
                  since: { type: string, format: date-time }
                  totalCostUsd: { type: string }
                  totalChargeAud: { type: string }
                  totalOperations: { type: integer }
                  users:
                    type: array
                    items:
                      type: object
                      properties:
                        userId: { type: string }
                        email: { type: string }
                        displayName: { type: string, nullable: true }
                        totalCostUsdCents: { type: integer }
                        totalChargeAudCents: { type: integer }
                        operationCount: { type: integer }
                        byOperation: { type: object }
                  prices: { type: object }

  # ── Activity ──────────────────────────────────────────
  /api/activity/log:
    post:
      tags: [Activity]
      summary: Record an activity log entry
      requestBody:
        required: true
        content:
          application/json:
            schema:
              type: object
              required: [action]
              properties:
                action: { type: string }
                details: { type: object, default: {} }
      responses:
        '200':
          description: Logged
          content:
            application/json:
              schema:
                type: object
                properties:
                  ok: { type: boolean }

  # ── Proxy ─────────────────────────────────────────────
  /api/proxy:
    get:
      tags: [Proxy]
      summary: Same-origin asset proxy
      description: >
        Fetches a remote image/video and streams it back same-origin with CORS headers so client-side
        canvas reads aren't tainted. Stores nothing. Private/loopback hosts are blocked; assets >50MB
        are rejected.
      parameters:
        - name: url
          in: query
          required: true
          schema: { type: string }
          description: "http(s) URL of the image/video to proxy"
      responses:
        '200':
          description: Proxied asset bytes
          content:
            application/octet-stream:
              schema: { type: string, format: binary }
        '403':
          description: Blocked host
        '413':
          description: Asset too large (>50MB)
        '415':
          description: Not an image/video
