# MetaGhost Desktop 1.1.21: API documentation

Local API hosted by the Desktop computer. OpenAPI 3.1 is the description format; apiVersion 1 is the HTTP contract.

## From connection to first result

Open MetaGhost Desktop, sign in and go to Settings > API. Enable the server, keep remote access disabled, generate a key if needed and Apply changes. Keep Desktop open. This guide targets Desktop 1.1.21, API contract 1.

```powershell
curl.exe "http://127.0.0.1:3847/api/v1/health"
```

```json
{
  "status": "ok",
  "version": "1.1.21",
  "apiVersion": "1",
  "activeJobs": 0
}
```

Create a basic local Spoof job using paths on the Desktop computer. Give each execution a unique Idempotency-Key and save it with the exact JSON body. Keep keys in an environment variable or secret store, never in URLs or shared examples.

```http
POST http://127.0.0.1:3847/api/v1/jobs
Authorization: Bearer YOUR_LOCAL_API_KEY
Content-Type: application/json
Idempotency-Key: YOUR_UNIQUE_WORKFLOW_RUN_ID

{
  "operation": "spoof",
  "filePath": "C:\\Media\\photo.jpg",
  "outputFolder": "C:\\Media\\output",
  "batchCount": 1
}
```

A 202 response returns jobId. Save it, poll the job and inspect outcome, errors and artifacts before downloading. The Python 3.10+ and Node.js 22+ starters below use standard libraries, loopback only and a ten-minute polling deadline. They submit once and never overwrite an existing download.

```powershell
$env:METAGHOST_API_KEY = Read-Host "MetaGhost API key"
python .\quickstart.py "C:\Media\photo.jpg" "C:\Media\output" ".\result.jpg"
# Or:
node .\quickstart.mjs "C:\Media\photo.jpg" "C:\Media\output" ".\result-2.jpg"
```

## Connection & access

The API runs inside Desktop at http://127.0.0.1:3847/api/v1 by default. Historical /api routes remain compatible aliases. Use the port displayed in Settings > API. Apply changes restarts the API and cancels active and queued jobs; completed outputs are kept.

Only GET /api/v1/health and /api/health are public. Other operations require Authorization: Bearer YOUR_LOCAL_API_KEY and an authorized MetaGhost account. Missing or invalid keys return 401, denied permissions 403, and temporarily unavailable account verification retryable 503. Existing keys are not rotated automatically; generated keys take effect after Apply changes.

```http
GET http://127.0.0.1:3847/api/v1/capabilities
Authorization: Bearer YOUR_LOCAL_API_KEY
```

## Files, presets & Drive

Choose filePath for one local file, files for several, driveInputFileIds for explicitly granted Drive files, or driveInputFolder for accessible children of a folder. Choose one source only. Local paths must be absolute and exist on the Desktop computer. File-producing jobs need an outputFolder or a supported Drive destination. Inspect /tools for each operation.

Supported images: JPG, JPEG, PNG, WebP, HEIC, BMP, TIFF. Supported videos: MP4, MOV, AVI, MKV, WebM, M4V. Operation-specific restrictions still apply.

POST /api/v1/upload accepts raw bytes with Content-Type: application/octet-stream and X-Filename. No multipart. Its response contains filePath, originalName and size; use filePath in the job. Maximum 500 MiB per file, 20 GiB retained storage, seven-day retention. Oversized input returns structured 413; exhausted storage returns 507.

GET /api/v1/presets returns saved image/video preset names. A mixed batch needs the same name in both lists. Omit preset for basic defaults; unsaved UI controls are not used. Paid diffusion or adversarial presets require confirmCredits: true. Only unchanged historical recipes on POST /api/jobs may retain approval after restoring their original API key.

Connect Drive in Desktop Settings and check GET /api/v1/drive/status. Desktop 1.1.21 accepts up to 250 explicit Picker-granted file IDs; granting a folder does not grant every child. Use folder IDs, not sharing URLs. A missing connection returns 412; inaccessible selections can fail separately. Downloader supports Drive output only; Probe and Risk Analyzer have no Drive output.

```json
{
  "operation": "spoof",
  "driveInputFileIds": [
    "YOUR_GRANTED_FILE_ID"
  ],
  "driveOutputFolder": "YOUR_OUTPUT_FOLDER_ID"
}
```

Inspect drive.uploadResult, confirmed receipts, errors, cancelled, uploadError and drive.recovery before declaring delivery successful. Retrieve Drive results from Drive; local API download returns 409. Recovery files can expire. The local starters intentionally reject Drive bodies.

## Jobs, retries & results

After acceptance, retain jobId and inspect skipped. Drive counts may remain unknown until preflight. Poll every few seconds with a finite deadline: queued and processing are in progress; completed, failed and cancelled are terminal. completed may be partial. Check outcome, per-file errors and delivery results. progress.phase describes work, not a separate status.

```http
GET http://127.0.0.1:3847/api/v1/jobs/YOUR_JOB_ID
Authorization: Bearer YOUR_LOCAL_API_KEY
```

Use artifacts[].downloadUrl to select the correct output, including multi-file results. This relative URL resolves against the Desktop server origin. Batch index selects a result; artifact selects a file inside it. Probe, Risk Analyzer and Captions with reason: no_speech and charged: false may return no file.

Retry the same execution with the same Idempotency-Key and unchanged JSON body. Receipts survive restart and history clearing for 24 hours. A changed body returns 409 IDEMPOTENCY_CONFLICT. jobAvailable: false means the receipt prevents re-execution but history is unavailable. A new, expired or missing key can create a new job. Preserve the key when a submission response is lost.

DELETE /api/v1/jobs/{jobId} requests cancellation. Committed GPU work may finish first; completed outputs remain. Stopping your script does not cancel a job. GET /api/v1/jobs returns the latest 50 account jobs. History retains up to 100 terminal jobs for 24 hours. Restart marks interrupted work API_RESTARTED instead of resuming it. DELETE /api/v1/jobs clears finished history, preserving files and idempotency receipts.

## Tools, credits & limits

Read GET /api/v1/tools and /api/v1/capabilities before automation. Check available, supported sources and destinations, Drive modes and pricing. Operations include spoof, probe, risk-analyzer, convert, reduce, short-maker, captions, download and conditionally available synthid. Use operation and its options; Short Maker requires an existing template from /short-maker/templates.

Captions and SynthID require confirmCredits: true; Downloader requires confirmExternalNetwork: true. For source-second Captions pricing, call POST /api/v1/captions/quote with a local filePath and optional language, then approve requiredLimit as options.maxCreditsPerVideo. The quote does not start paid processing. Drive files are quoted after download. Legacy runtimes may not offer quotes. There is no credit-balance API route.

Desktop 1.1.21 allows 250 Spoof inputs, 100 repetitions per file and 1,000 total output operations. Collage needs four distinct compatible inputs per media type and creates grouped outputs. Other operations do not support batchCount repetition and can have different input limits. Read limits.operations from /capabilities.

One API job processes at a time with up to 10 waiting jobs; active UI work can delay the queue. In 1.1.21 all JSON bodies are limited to 64 KiB. Uploads are limited to 500 MiB. Inspect capabilities for per-tool and storage limits.

## Next update: prepared changes

The next build is planned to accept 1,000 explicit local/Drive inputs and 2 MiB of authenticated job JSON; other JSON endpoints retain 64 KiB. Removal of the old Spoof repetition/output quotas is also prepared. These changes are not part of Desktop 1.1.21. Check the installed build through /capabilities before sending larger jobs.

## Network & automation

Any HTTP client or automation platform can call this API. 127.0.0.1 refers to the client machine or container. A remote or cloud client needs a reachable Desktop host over a private network or VPN; its localhost does not point to your computer. For an HTTPS proxy, terminate TLS and restrict source access. Never expose the Desktop HTTP port directly on the public internet.

Scheduling belongs to the calling application. Keep Desktop open, preserve the execution key and jobId, respect queue limits and use bounded polling. A whole-workflow retry with a new key can duplicate work. Recover using the original key and unchanged body. Do not follow redirects with credentials.

## Official references

- [Current guide](https://metaghost.io/docs/api)
- [French guide](https://metaghost.io/fr/docs/api)
- [Desktop 1.0.81 archive](https://metaghost.io/docs/api/1.0.81)
- [OpenAPI JSON](https://metaghost.io/api-docs/openapi.json)
- [OpenAPI YAML](https://metaghost.io/api-docs/openapi.yaml)

## Complete request and response reference

The following OpenAPI document includes every route, method, authentication requirement, parameter, request body, response and schema for this release.

```json
{
  "openapi": "3.1.0",
  "info": {
    "title": "MetaGhost Desktop Local API",
    "version": "1.1.21",
    "description": "Desktop 1.1.21 local API. New integrations use /api/v1; /api remains a compatible alias. The API runs on the Desktop computer. Permission denials return HTTP 403; unavailable account authority returns retryable HTTP 503. This reference excludes unpublished capacity changes.",
    "x-api-contract-version": "1"
  },
  "servers": [
    {
      "url": "http://127.0.0.1:3847/api/v1",
      "description": "Versioned local endpoint"
    },
    {
      "url": "http://127.0.0.1:3847/api",
      "description": "Legacy-compatible alias"
    }
  ],
  "security": [
    {
      "bearerAuth": []
    }
  ],
  "tags": [
    {
      "name": "System"
    },
    {
      "name": "Tools"
    },
    {
      "name": "Jobs"
    },
    {
      "name": "Files"
    },
    {
      "name": "Google Drive"
    }
  ],
  "paths": {
    "/health": {
      "get": {
        "tags": [
          "System"
        ],
        "summary": "Check server health",
        "security": [],
        "responses": {
          "200": {
            "description": "Server is ready",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Health"
                }
              }
            }
          }
        }
      }
    },
    "/capabilities": {
      "get": {
        "tags": [
          "System"
        ],
        "summary": "Discover API version, compatibility, limits, and features",
        "responses": {
          "200": {
            "description": "Capabilities",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "apiVersion",
                    "routes",
                    "compatibility",
                    "limits",
                    "features"
                  ],
                  "additionalProperties": true
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/tools": {
      "get": {
        "tags": [
          "Tools"
        ],
        "summary": "Discover supported operations and their local, network, and credit requirements",
        "responses": {
          "200": {
            "description": "Tool operation catalogue",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "operations",
                    "submission"
                  ],
                  "properties": {
                    "operations": {
                      "type": "object",
                      "additionalProperties": {
                        "$ref": "#/components/schemas/ToolDefinition"
                      }
                    },
                    "submission": {
                      "type": "object",
                      "additionalProperties": true
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/presets": {
      "get": {
        "tags": [
          "System"
        ],
        "summary": "List image and video preset names",
        "responses": {
          "200": {
            "description": "Preset names",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "image",
                    "video"
                  ],
                  "properties": {
                    "image": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    },
                    "video": {
                      "type": "array",
                      "items": {
                        "type": "string"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/short-maker/templates": {
      "get": {
        "tags": [
          "Tools"
        ],
        "summary": "List safe built-in and custom Short Maker template summaries",
        "responses": {
          "200": {
            "description": "Available Short Maker templates",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "templates"
                  ],
                  "properties": {
                    "templates": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/ShortMakerTemplate"
                      }
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "503": {
            "description": "Template catalogue is not available in this Desktop session",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/captions/quote": {
      "post": {
        "summary": "Quote source-second transcription without starting processing or spending credits",
        "description": "Available on source-second runtimes. Legacy runtimes return LEGACY_PROTOCOL or QUOTE_UNAVAILABLE. Check the captions pricing catalogue first.",
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "required": [
                  "filePath"
                ],
                "properties": {
                  "filePath": {
                    "type": "string"
                  },
                  "options": {
                    "type": "object",
                    "properties": {
                      "language": {
                        "enum": [
                          "",
                          "fr",
                          "en",
                          "es",
                          "de",
                          "it",
                          "pt",
                          "nl"
                        ]
                      }
                    }
                  }
                }
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Current source quote; approve requiredLimit as options.maxCreditsPerVideo when creating a job",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "properties": {
                    "durationMs": {
                      "type": "number"
                    },
                    "units": {
                      "type": "integer"
                    },
                    "totalCredits": {
                      "type": "integer"
                    },
                    "newCredits": {
                      "type": "integer"
                    },
                    "requiredLimit": {
                      "type": "integer"
                    },
                    "priceModel": {
                      "type": "string"
                    },
                    "origin": {
                      "type": "string"
                    }
                  }
                }
              }
            }
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "default": {
            "description": "Invalid input, denied authorization or unavailable quote",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/jobs": {
      "post": {
        "tags": [
          "Jobs"
        ],
        "summary": "Create a spoof or Desktop tool job",
        "parameters": [
          {
            "$ref": "#/components/parameters/IdempotencyKey"
          },
          {
            "$ref": "#/components/parameters/RequestId"
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/json": {
              "schema": {
                "$ref": "#/components/schemas/CreateJobRequest"
              }
            }
          }
        },
        "responses": {
          "202": {
            "description": "Job accepted, or an idempotent replay",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/CreateJobResponse"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "412": {
            "$ref": "#/components/responses/PreconditionFailed"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "507": {
            "$ref": "#/components/responses/StorageUnavailable"
          }
        }
      },
      "get": {
        "tags": [
          "Jobs"
        ],
        "summary": "List up to 50 recent jobs",
        "responses": {
          "200": {
            "description": "Job history and queue state",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "jobs",
                    "queueLength",
                    "processing"
                  ],
                  "properties": {
                    "jobs": {
                      "type": "array",
                      "items": {
                        "$ref": "#/components/schemas/Job"
                      }
                    },
                    "queueLength": {
                      "type": "integer",
                      "minimum": 0
                    },
                    "processing": {
                      "type": "boolean"
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      },
      "delete": {
        "tags": [
          "Jobs"
        ],
        "summary": "Clear terminal jobs from local history",
        "responses": {
          "200": {
            "description": "Number of cleared jobs",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "cleared"
                  ],
                  "properties": {
                    "cleared": {
                      "type": "integer",
                      "minimum": 0
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/jobs/{jobId}": {
      "parameters": [
        {
          "$ref": "#/components/parameters/JobId"
        }
      ],
      "get": {
        "tags": [
          "Jobs"
        ],
        "summary": "Read job status, progress, outcome, and results",
        "responses": {
          "200": {
            "description": "Current job state",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Job"
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      },
      "delete": {
        "tags": [
          "Jobs"
        ],
        "summary": "Cancel a queued or processing job",
        "responses": {
          "200": {
            "description": "Job is cancelled",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "jobId",
                    "status"
                  ],
                  "properties": {
                    "jobId": {
                      "type": "string"
                    },
                    "status": {
                      "const": "cancelled"
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/upload": {
      "post": {
        "tags": [
          "Files"
        ],
        "summary": "Upload raw image or video bytes",
        "parameters": [
          {
            "name": "X-Filename",
            "in": "header",
            "required": true,
            "schema": {
              "type": "string",
              "maxLength": 255
            }
          }
        ],
        "requestBody": {
          "required": true,
          "content": {
            "application/octet-stream": {
              "schema": {
                "type": "string",
                "format": "binary",
                "maxLength": 524288000
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Upload retained for seven days",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "filePath",
                    "originalName",
                    "size"
                  ],
                  "properties": {
                    "filePath": {
                      "type": "string"
                    },
                    "originalName": {
                      "type": "string"
                    },
                    "size": {
                      "type": "integer",
                      "minimum": 1,
                      "maximum": 524288000
                    }
                  }
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "413": {
            "$ref": "#/components/responses/PayloadTooLarge"
          },
          "415": {
            "$ref": "#/components/responses/UnsupportedMediaType"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          },
          "507": {
            "description": "Retained upload storage ceiling reached",
            "content": {
              "application/json": {
                "schema": {
                  "$ref": "#/components/schemas/Error"
                }
              }
            }
          }
        }
      }
    },
    "/download/{jobId}": {
      "get": {
        "tags": [
          "Files"
        ],
        "summary": "Download a completed output",
        "parameters": [
          {
            "$ref": "#/components/parameters/JobId"
          },
          {
            "name": "index",
            "in": "query",
            "description": "Single job artifact index; legacy batch result index.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          },
          {
            "name": "artifact",
            "in": "query",
            "description": "Batch only; selects a file inside the selected result.",
            "schema": {
              "type": "integer",
              "minimum": 0,
              "default": 0
            }
          }
        ],
        "responses": {
          "200": {
            "description": "Output bytes",
            "content": {
              "application/octet-stream": {
                "schema": {
                  "type": "string",
                  "format": "binary"
                }
              }
            }
          },
          "400": {
            "$ref": "#/components/responses/BadRequest"
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "404": {
            "$ref": "#/components/responses/NotFound"
          },
          "409": {
            "$ref": "#/components/responses/Conflict"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    },
    "/drive/status": {
      "get": {
        "tags": [
          "Google Drive"
        ],
        "summary": "Check Desktop Google Drive readiness without exposing tokens",
        "responses": {
          "200": {
            "description": "Google Drive state",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object",
                  "required": [
                    "clientConfigured",
                    "connected"
                  ],
                  "properties": {
                    "clientConfigured": {
                      "type": "boolean"
                    },
                    "connected": {
                      "type": "boolean"
                    },
                    "email": {
                      "type": [
                        "string",
                        "null"
                      ]
                    },
                    "scope": {
                      "type": [
                        "string",
                        "null"
                      ]
                    }
                  }
                }
              }
            }
          },
          "401": {
            "$ref": "#/components/responses/Unauthorized"
          },
          "403": {
            "$ref": "#/components/responses/Forbidden"
          },
          "429": {
            "$ref": "#/components/responses/RateLimited"
          }
        }
      }
    }
  },
  "components": {
    "securitySchemes": {
      "bearerAuth": {
        "type": "http",
        "scheme": "bearer",
        "bearerFormat": "MetaGhost API key"
      }
    },
    "parameters": {
      "IdempotencyKey": {
        "name": "Idempotency-Key",
        "in": "header",
        "required": false,
        "description": "Unique visible ASCII value retained for 24 hours.",
        "schema": {
          "type": "string",
          "minLength": 1,
          "maxLength": 128
        }
      },
      "RequestId": {
        "name": "X-Request-ID",
        "in": "header",
        "required": false,
        "schema": {
          "type": "string",
          "minLength": 1,
          "maxLength": 96
        }
      },
      "JobId": {
        "name": "jobId",
        "in": "path",
        "required": true,
        "schema": {
          "type": "string",
          "pattern": "^job-[A-Za-z0-9_-]+$"
        }
      }
    },
    "schemas": {
      "Health": {
        "type": "object",
        "required": [
          "status",
          "version",
          "apiVersion",
          "activeJobs"
        ],
        "properties": {
          "status": {
            "const": "ok"
          },
          "version": {
            "type": "string",
            "description": "Desktop application version"
          },
          "apiVersion": {
            "const": "1"
          },
          "activeJobs": {
            "type": "integer",
            "minimum": 0
          }
        }
      },
      "CreateJobRequest": {
        "oneOf": [
          {
            "$ref": "#/components/schemas/SpoofJobRequest"
          },
          {
            "$ref": "#/components/schemas/ProbeJobRequest"
          },
          {
            "$ref": "#/components/schemas/RiskAnalyzerJobRequest"
          },
          {
            "$ref": "#/components/schemas/ConvertJobRequest"
          },
          {
            "$ref": "#/components/schemas/ReduceJobRequest"
          },
          {
            "$ref": "#/components/schemas/ShortMakerJobRequest"
          },
          {
            "$ref": "#/components/schemas/CaptionsJobRequest"
          },
          {
            "$ref": "#/components/schemas/DownloadJobRequest"
          },
          {
            "$ref": "#/components/schemas/SynthIdJobRequest"
          }
        ]
      },
      "DriveInputFileIds": {
        "type": "array",
        "minItems": 1,
        "maxItems": 250,
        "description": "Explicit file IDs already granted through the Google Picker. Duplicates are processed once. Mutually exclusive with local input and driveInputFolder; Drive folder access does not grant every child file.",
        "items": {
          "type": "string",
          "pattern": "^[A-Za-z0-9_-]{10,256}$"
        }
      },
      "LocalOrDriveInput": {
        "oneOf": [
          {
            "type": "object",
            "required": [
              "filePath"
            ],
            "properties": {
              "filePath": {
                "type": "string",
                "description": "Absolute local input path"
              }
            }
          },
          {
            "type": "object",
            "required": [
              "files"
            ],
            "properties": {
              "files": {
                "type": "array",
                "minItems": 1,
                "maxItems": 1000,
                "items": {
                  "type": "string"
                }
              }
            }
          },
          {
            "type": "object",
            "required": [
              "driveInputFolder"
            ],
            "properties": {
              "driveInputFolder": {
                "type": "string",
                "maxLength": 512
              }
            }
          },
          {
            "type": "object",
            "required": [
              "driveInputFileIds"
            ],
            "properties": {
              "driveInputFileIds": {
                "$ref": "#/components/schemas/DriveInputFileIds"
              }
            }
          }
        ]
      },
      "LocalOrDriveOutput": {
        "oneOf": [
          {
            "type": "object",
            "required": [
              "outputFolder"
            ],
            "properties": {
              "outputFolder": {
                "type": "string",
                "description": "Absolute local output folder"
              }
            }
          },
          {
            "type": "object",
            "required": [
              "driveOutputFolder"
            ],
            "properties": {
              "driveOutputFolder": {
                "type": "string",
                "maxLength": 512
              }
            }
          }
        ]
      },
      "SpoofJobRequest": {
        "type": "object",
        "description": "At most 250 input files, 100 repetitions per file, and 1000 total operations. Other tool jobs have different limits; batchCount repetition is only supported for spoof.",
        "additionalProperties": true,
        "properties": {
          "operation": {
            "enum": [
              "spoof"
            ],
            "default": "spoof"
          },
          "confirmCredits": {
            "type": "boolean",
            "description": "Required true for diffusion/adversarial presets except an unchanged paid recipe approved during key migration on the historical /api/jobs route."
          },
          "filePath": {
            "type": "string"
          },
          "files": {
            "type": "array",
            "minItems": 1,
            "maxItems": 250,
            "items": {
              "type": "string"
            }
          },
          "driveInputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "driveInputFileIds": {
            "$ref": "#/components/schemas/DriveInputFileIds"
          },
          "outputFolder": {
            "type": "string"
          },
          "driveOutputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "preset": {
            "type": "string",
            "maxLength": 128
          },
          "batchCount": {
            "type": "integer",
            "minimum": 1,
            "maximum": 100,
            "default": 1
          }
        },
        "oneOf": [
          {
            "required": [
              "filePath"
            ]
          },
          {
            "required": [
              "files"
            ]
          },
          {
            "required": [
              "driveInputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds"
            ]
          }
        ],
        "anyOf": [
          {
            "required": [
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveOutputFolder"
            ]
          }
        ]
      },
      "ProbeJobRequest": {
        "type": "object",
        "required": [
          "operation"
        ],
        "properties": {
          "operation": {
            "enum": [
              "probe",
              "media-probe"
            ]
          },
          "filePath": {
            "type": "string"
          },
          "files": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "type": "string"
            }
          },
          "driveInputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "driveInputFileIds": {
            "$ref": "#/components/schemas/DriveInputFileIds"
          },
          "options": {
            "type": "object",
            "properties": {
              "includeStreams": {
                "type": "boolean",
                "default": true
              },
              "includeMetadata": {
                "type": "boolean",
                "default": true
              }
            }
          }
        },
        "oneOf": [
          {
            "required": [
              "filePath"
            ]
          },
          {
            "required": [
              "files"
            ]
          },
          {
            "required": [
              "driveInputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds"
            ]
          }
        ]
      },
      "RiskAnalyzerJobRequest": {
        "type": "object",
        "required": [
          "operation"
        ],
        "properties": {
          "operation": {
            "enum": [
              "risk-analyzer",
              "risk"
            ]
          },
          "originalPath": {
            "type": "string"
          },
          "comparisonPaths": {
            "type": "array",
            "minItems": 1,
            "maxItems": 50,
            "items": {
              "type": "string"
            }
          },
          "files": {
            "type": "array",
            "minItems": 1,
            "maxItems": 50,
            "items": {
              "type": "string"
            }
          },
          "driveInputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "driveInputFileIds": {
            "$ref": "#/components/schemas/DriveInputFileIds"
          },
          "options": {
            "type": "object",
            "properties": {
              "originalFileName": {
                "type": "string",
                "maxLength": 260
              }
            }
          }
        },
        "oneOf": [
          {
            "required": [
              "originalPath",
              "comparisonPaths"
            ]
          },
          {
            "required": [
              "originalPath",
              "files"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "options"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "options"
            ]
          }
        ]
      },
      "ConvertJobRequest": {
        "type": "object",
        "required": [
          "operation"
        ],
        "properties": {
          "operation": {
            "enum": [
              "convert",
              "converter"
            ]
          },
          "filePath": {
            "type": "string"
          },
          "files": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "type": "string"
            }
          },
          "driveInputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "driveInputFileIds": {
            "$ref": "#/components/schemas/DriveInputFileIds"
          },
          "outputFolder": {
            "type": "string"
          },
          "driveOutputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "format": {
            "enum": [
              "jpeg",
              "jpg",
              "png",
              "webp",
              "bmp",
              "tiff",
              "mp4",
              "mov",
              "webm",
              "mkv",
              "gif"
            ],
            "description": "Compatibility alias for options.format"
          },
          "options": {
            "type": "object",
            "properties": {
              "forceSoftware": {
                "type": "boolean",
                "default": false
              },
              "format": {
                "enum": [
                  "jpeg",
                  "jpg",
                  "png",
                  "webp",
                  "bmp",
                  "tiff",
                  "mp4",
                  "mov",
                  "webm",
                  "mkv",
                  "gif"
                ]
              },
              "framerate": {
                "type": "integer",
                "minimum": 1,
                "maximum": 30,
                "default": 15
              },
              "scale": {
                "type": "integer",
                "minimum": 64,
                "maximum": 1920,
                "default": 720
              }
            }
          }
        },
        "anyOf": [
          {
            "required": [
              "options"
            ],
            "properties": {
              "options": {
                "required": [
                  "format"
                ]
              }
            }
          },
          {
            "required": [
              "format"
            ]
          }
        ],
        "oneOf": [
          {
            "required": [
              "filePath",
              "outputFolder"
            ]
          },
          {
            "required": [
              "filePath",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "files",
              "outputFolder"
            ]
          },
          {
            "required": [
              "files",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "driveOutputFolder"
            ]
          }
        ]
      },
      "ReduceJobRequest": {
        "type": "object",
        "required": [
          "operation"
        ],
        "properties": {
          "operation": {
            "enum": [
              "reduce",
              "file-reducer",
              "reducer"
            ]
          },
          "filePath": {
            "type": "string"
          },
          "files": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "type": "string"
            }
          },
          "driveInputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "driveInputFileIds": {
            "$ref": "#/components/schemas/DriveInputFileIds"
          },
          "outputFolder": {
            "type": "string"
          },
          "driveOutputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "options": {
            "type": "object",
            "properties": {
              "forceSoftware": {
                "type": "boolean",
                "default": false
              }
            }
          }
        },
        "oneOf": [
          {
            "required": [
              "filePath",
              "outputFolder"
            ]
          },
          {
            "required": [
              "filePath",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "files",
              "outputFolder"
            ]
          },
          {
            "required": [
              "files",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "driveOutputFolder"
            ]
          }
        ]
      },
      "ShortMakerJobRequest": {
        "type": "object",
        "required": [
          "operation",
          "options"
        ],
        "properties": {
          "operation": {
            "enum": [
              "short-maker",
              "shortmaker"
            ]
          },
          "filePath": {
            "type": "string"
          },
          "files": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "type": "string"
            }
          },
          "driveInputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "driveInputFileIds": {
            "$ref": "#/components/schemas/DriveInputFileIds"
          },
          "outputFolder": {
            "type": "string"
          },
          "driveOutputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "options": {
            "type": "object",
            "required": [
              "templateId"
            ],
            "properties": {
              "forceSoftware": {
                "type": "boolean",
                "default": false
              },
              "templateId": {
                "type": "string",
                "maxLength": 160
              },
              "durationMode": {
                "enum": [
                  "smart",
                  "template"
                ],
                "default": "smart"
              },
              "maxContentDuration": {
                "type": [
                  "number",
                  "null"
                ],
                "minimum": 1,
                "maximum": 3600
              },
              "keepSourceAudio": {
                "type": "boolean",
                "default": false
              },
              "randomizeTextPos": {
                "type": "boolean",
                "default": false
              },
              "randomSeed": {
                "type": "string",
                "maxLength": 200
              },
              "spoofEnabled": {
                "type": "boolean",
                "default": false
              },
              "spoofTier": {
                "enum": [
                  "fast",
                  "aggressive"
                ],
                "default": "fast"
              },
              "usMetadataEnabled": {
                "type": "boolean",
                "default": false
              },
              "metadataCountry": {
                "type": "string",
                "pattern": "^[A-Za-z]{2}$",
                "default": "US"
              },
              "metadataDeviceProfile": {
                "enum": [
                  "iphone",
                  "rayban"
                ],
                "default": "iphone"
              }
            }
          }
        },
        "oneOf": [
          {
            "required": [
              "filePath",
              "outputFolder"
            ]
          },
          {
            "required": [
              "filePath",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "files",
              "outputFolder"
            ]
          },
          {
            "required": [
              "files",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "driveOutputFolder"
            ]
          }
        ]
      },
      "CaptionsJobRequest": {
        "type": "object",
        "required": [
          "operation"
        ],
        "allOf": [
          {
            "$ref": "#/components/schemas/CreditConfirmation"
          }
        ],
        "properties": {
          "operation": {
            "enum": [
              "captions",
              "auto-captions"
            ]
          },
          "confirmCredits": {
            "type": "boolean"
          },
          "filePath": {
            "type": "string"
          },
          "files": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "type": "string"
            }
          },
          "driveInputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "driveInputFileIds": {
            "$ref": "#/components/schemas/DriveInputFileIds"
          },
          "outputFolder": {
            "type": "string"
          },
          "driveOutputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "options": {
            "type": "object",
            "properties": {
              "language": {
                "enum": [
                  "",
                  "fr",
                  "en",
                  "es",
                  "de",
                  "it",
                  "pt",
                  "nl"
                ],
                "default": ""
              },
              "tier": {
                "enum": [
                  "premium",
                  "fast"
                ],
                "default": "premium"
              },
              "maxCreditsPerVideo": {
                "type": "integer",
                "minimum": 0,
                "maximum": 90000,
                "description": "Explicit ceiling for each video's new source-second charges. Required before a nonzero charge on source-second runtimes; obtain a quote from /captions/quote."
              },
              "style": {
                "enum": [
                  "punch",
                  "karaoke",
                  "clean",
                  "beast",
                  "boxed",
                  "tiktok-clean",
                  "instagram-clean",
                  "creator-pop",
                  "word-focus"
                ],
                "default": "punch"
              },
              "overrides": {
                "type": "object",
                "additionalProperties": true
              },
              "confirmCredits": {
                "type": "boolean"
              }
            }
          }
        },
        "oneOf": [
          {
            "required": [
              "filePath",
              "outputFolder"
            ]
          },
          {
            "required": [
              "filePath",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "files",
              "outputFolder"
            ]
          },
          {
            "required": [
              "files",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "driveOutputFolder"
            ]
          }
        ]
      },
      "DownloadJobRequest": {
        "type": "object",
        "required": [
          "operation"
        ],
        "allOf": [
          {
            "$ref": "#/components/schemas/NetworkConfirmation"
          }
        ],
        "properties": {
          "operation": {
            "enum": [
              "download",
              "downloader"
            ]
          },
          "confirmExternalNetwork": {
            "type": "boolean"
          },
          "url": {
            "type": "string",
            "format": "uri",
            "maxLength": 4096
          },
          "urls": {
            "type": "array",
            "minItems": 1,
            "maxItems": 100,
            "items": {
              "type": "string",
              "format": "uri",
              "maxLength": 4096
            }
          },
          "outputFolder": {
            "type": "string"
          },
          "driveOutputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "options": {
            "type": "object",
            "properties": {
              "usMetadataEnabled": {
                "type": "boolean",
                "default": false
              },
              "metadataCountry": {
                "type": "string",
                "pattern": "^[A-Za-z]{2}$",
                "default": "US"
              },
              "metadataDeviceProfile": {
                "enum": [
                  "iphone",
                  "rayban"
                ],
                "default": "iphone"
              },
              "confirmExternalNetwork": {
                "type": "boolean"
              }
            }
          }
        },
        "oneOf": [
          {
            "required": [
              "url",
              "outputFolder"
            ]
          },
          {
            "required": [
              "url",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "urls",
              "outputFolder"
            ]
          },
          {
            "required": [
              "urls",
              "driveOutputFolder"
            ]
          }
        ]
      },
      "SynthIdJobRequest": {
        "type": "object",
        "required": [
          "operation",
          "preset"
        ],
        "allOf": [
          {
            "$ref": "#/components/schemas/CreditConfirmation"
          }
        ],
        "properties": {
          "operation": {
            "const": "synthid"
          },
          "confirmCredits": {
            "type": "boolean"
          },
          "preset": {
            "type": "string",
            "minLength": 1,
            "maxLength": 128
          },
          "filePath": {
            "type": "string"
          },
          "files": {
            "type": "array",
            "minItems": 1,
            "maxItems": 1000,
            "items": {
              "type": "string"
            }
          },
          "driveInputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "driveInputFileIds": {
            "$ref": "#/components/schemas/DriveInputFileIds"
          },
          "outputFolder": {
            "type": "string"
          },
          "driveOutputFolder": {
            "type": "string",
            "maxLength": 512
          },
          "options": {
            "type": "object",
            "properties": {
              "confirmCredits": {
                "type": "boolean"
              }
            }
          }
        },
        "oneOf": [
          {
            "required": [
              "filePath",
              "outputFolder"
            ]
          },
          {
            "required": [
              "filePath",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "files",
              "outputFolder"
            ]
          },
          {
            "required": [
              "files",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "outputFolder"
            ]
          },
          {
            "required": [
              "driveInputFolder",
              "driveOutputFolder"
            ]
          },
          {
            "required": [
              "driveInputFileIds",
              "driveOutputFolder"
            ]
          }
        ]
      },
      "CreditConfirmation": {
        "type": "object",
        "description": "Explicit approval at the request root or in options, matching the runtime. Missing or false approvals never authorize a charge.",
        "anyOf": [
          {
            "required": [
              "confirmCredits"
            ],
            "properties": {
              "confirmCredits": {
                "const": true
              }
            }
          },
          {
            "required": [
              "options"
            ],
            "properties": {
              "options": {
                "type": "object",
                "required": [
                  "confirmCredits"
                ],
                "properties": {
                  "confirmCredits": {
                    "const": true
                  }
                }
              }
            }
          }
        ]
      },
      "NetworkConfirmation": {
        "type": "object",
        "description": "Explicit approval at the request root or in options, matching the runtime.",
        "anyOf": [
          {
            "required": [
              "confirmExternalNetwork"
            ],
            "properties": {
              "confirmExternalNetwork": {
                "const": true
              }
            }
          },
          {
            "required": [
              "options"
            ],
            "properties": {
              "options": {
                "type": "object",
                "required": [
                  "confirmExternalNetwork"
                ],
                "properties": {
                  "confirmExternalNetwork": {
                    "const": true
                  }
                }
              }
            }
          }
        ]
      },
      "CreateJobResponse": {
        "type": "object",
        "required": [
          "jobId",
          "operation",
          "status",
          "inputFiles",
          "totalOperations",
          "skipped",
          "position"
        ],
        "properties": {
          "jobId": {
            "type": "string"
          },
          "operation": {
            "enum": [
              "spoof",
              "probe",
              "risk-analyzer",
              "convert",
              "reduce",
              "short-maker",
              "captions",
              "download",
              "synthid"
            ]
          },
          "status": {
            "enum": [
              "queued",
              "processing",
              "completed",
              "failed",
              "cancelled"
            ]
          },
          "inputFiles": {
            "type": [
              "integer",
              "null"
            ]
          },
          "batchCount": {
            "type": "integer",
            "default": 1
          },
          "totalOperations": {
            "type": [
              "integer",
              "null"
            ]
          },
          "skipped": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/FileError"
            }
          },
          "position": {
            "type": "integer",
            "minimum": 1
          },
          "drive": {
            "type": [
              "object",
              "null"
            ],
            "additionalProperties": true
          },
          "replayed": {
            "type": "boolean"
          },
          "jobAvailable": {
            "type": "boolean",
            "description": "False when a retained receipt outlives its job history; never rerun implicitly."
          },
          "outcome": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "success",
              "partial",
              "failed",
              "cancelled",
              null
            ]
          },
          "error_code": {
            "type": "string"
          },
          "error": {
            "type": "string"
          },
          "execution": {
            "enum": [
              "local",
              "hybrid",
              "network",
              "remote-gpu"
            ]
          },
          "credits": {
            "enum": [
              "none",
              "one-per-transcription",
              "variable"
            ]
          },
          "estimatedCredits": {
            "type": [
              "integer",
              "null"
            ],
            "minimum": 0
          }
        }
      },
      "Job": {
        "type": "object",
        "required": [
          "jobId",
          "operation",
          "status",
          "preset",
          "progress",
          "createdAt"
        ],
        "additionalProperties": true,
        "properties": {
          "jobId": {
            "type": "string"
          },
          "operation": {
            "enum": [
              "spoof",
              "probe",
              "risk-analyzer",
              "convert",
              "reduce",
              "short-maker",
              "captions",
              "download",
              "synthid"
            ]
          },
          "status": {
            "enum": [
              "queued",
              "processing",
              "completed",
              "failed",
              "cancelled"
            ]
          },
          "outcome": {
            "type": [
              "string",
              "null"
            ],
            "enum": [
              "success",
              "partial",
              "failed",
              "cancelled",
              null
            ]
          },
          "type": {
            "enum": [
              "single",
              "batch"
            ]
          },
          "preset": {
            "type": [
              "string",
              "null"
            ]
          },
          "progress": {
            "type": "object",
            "additionalProperties": true
          },
          "result": {
            "$ref": "#/components/schemas/ProcessingResult"
          },
          "results": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/ProcessingResult"
            }
          },
          "artifacts": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/LocalArtifact"
            }
          },
          "drive": {
            "$ref": "#/components/schemas/DriveJobState"
          },
          "errors": {
            "type": "array",
            "items": {
              "$ref": "#/components/schemas/FileError"
            }
          },
          "error": {
            "type": "string"
          },
          "error_code": {
            "type": "string"
          },
          "createdAt": {
            "type": "string",
            "format": "date-time"
          },
          "startedAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          },
          "completedAt": {
            "type": [
              "string",
              "null"
            ],
            "format": "date-time"
          }
        }
      },
      "LocalArtifact": {
        "type": "object",
        "required": [
          "resultIndex",
          "artifactIndex",
          "name",
          "localAvailable",
          "downloadUrl"
        ],
        "properties": {
          "resultIndex": {
            "type": "integer",
            "minimum": 0
          },
          "artifactIndex": {
            "type": "integer",
            "minimum": 0
          },
          "name": {
            "type": "string"
          },
          "localAvailable": {
            "type": "boolean"
          },
          "downloadUrl": {
            "type": "string",
            "description": "Relative URL; batch index selects a result and artifact selects a file inside it."
          }
        }
      },
      "ProcessingResult": {
        "type": "object",
        "additionalProperties": true,
        "description": "Operation-specific JSON; file-producing success requires existing non-empty files. Captions no_speech with charged false is a valid empty result.",
        "properties": {
          "outputPath": {
            "type": [
              "string",
              "null"
            ]
          },
          "files": {
            "type": "array",
            "items": {
              "type": "string"
            }
          },
          "localAvailable": {
            "type": "boolean"
          },
          "outcome": {
            "enum": [
              "success",
              "partial",
              "failed",
              "cancelled"
            ]
          },
          "reason": {
            "type": "string"
          },
          "charged": {
            "type": "boolean"
          },
          "delivery": {
            "$ref": "#/components/schemas/DriveDelivery"
          },
          "processing": {
            "type": "object",
            "additionalProperties": true
          }
        }
      },
      "DriveDelivery": {
        "type": "object",
        "required": [
          "provider",
          "status",
          "localAvailable"
        ],
        "properties": {
          "provider": {
            "const": "google-drive"
          },
          "status": {
            "enum": [
              "queued",
              "uploading",
              "uploaded",
              "failed",
              "cancelled"
            ]
          },
          "name": {
            "type": "string"
          },
          "fileId": {
            "type": [
              "string",
              "null"
            ]
          },
          "confirmed": {
            "type": "boolean"
          },
          "localAvailable": {
            "const": false
          },
          "recoveryAvailable": {
            "type": "boolean"
          }
        }
      },
      "DriveJobState": {
        "type": "object",
        "required": [
          "inputFolderId",
          "outputFolderId",
          "uploadResult",
          "uploadError",
          "recovery"
        ],
        "properties": {
          "inputFolderId": {
            "type": [
              "string",
              "null"
            ]
          },
          "outputFolderId": {
            "type": [
              "string",
              "null"
            ]
          },
          "uploadError": {
            "type": [
              "string",
              "null"
            ]
          },
          "uploadResult": {
            "type": [
              "object",
              "null"
            ],
            "properties": {
              "uploaded": {
                "type": "integer",
                "minimum": 0
              },
              "failed": {
                "type": "integer",
                "minimum": 0
              },
              "cancelled": {
                "type": "boolean"
              },
              "receipts": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/DriveDelivery"
                }
              },
              "errors": {
                "type": "array",
                "items": {
                  "$ref": "#/components/schemas/FileError"
                }
              }
            }
          },
          "recovery": {
            "type": "object",
            "required": [
              "available"
            ],
            "properties": {
              "available": {
                "type": "boolean"
              },
              "expiresAt": {
                "type": [
                  "string",
                  "null"
                ],
                "format": "date-time"
              }
            }
          }
        }
      },
      "FileError": {
        "type": "object",
        "required": [
          "file",
          "error"
        ],
        "properties": {
          "file": {
            "type": "string"
          },
          "error": {
            "type": "string"
          },
          "error_code": {
            "type": "string"
          }
        }
      },
      "ToolDefinition": {
        "type": "object",
        "required": [
          "operation",
          "label",
          "execution",
          "credits",
          "network",
          "input",
          "output",
          "supportsBatch",
          "supportsDriveInput",
          "supportsDriveOutput",
          "available"
        ],
        "properties": {
          "operation": {
            "type": "string"
          },
          "label": {
            "type": "string"
          },
          "execution": {
            "enum": [
              "local",
              "hybrid",
              "network",
              "remote-gpu"
            ]
          },
          "credits": {
            "enum": [
              "none",
              "one-per-transcription",
              "variable"
            ]
          },
          "network": {
            "type": "boolean"
          },
          "input": {
            "type": "string"
          },
          "output": {
            "enum": [
              "required",
              "none"
            ]
          },
          "supportsBatch": {
            "type": "boolean"
          },
          "supportsDriveInput": {
            "type": "boolean"
          },
          "supportsDriveOutput": {
            "type": "boolean"
          },
          "available": {
            "type": "boolean"
          },
          "unavailableReason": {
            "type": [
              "string",
              "null"
            ]
          },
          "unavailableCode": {
            "type": [
              "string",
              "null"
            ]
          },
          "requiresCreditConfirmation": {
            "type": "boolean"
          },
          "requiresNetworkConfirmation": {
            "type": "boolean"
          },
          "dependsOnPreset": {
            "type": "boolean"
          },
          "creditConfirmationScope": {
            "enum": [
              "paid-presets"
            ]
          },
          "limits": {
            "type": "object",
            "additionalProperties": {
              "type": "integer"
            }
          },
          "pricing": {
            "type": "object",
            "properties": {
              "model": {
                "type": "string"
              },
              "creditsPerSecond": {
                "type": "number"
              },
              "requiresCreditLimit": {
                "type": "boolean"
              },
              "limitField": {
                "type": "string"
              },
              "quotePath": {
                "type": "string"
              }
            }
          }
        }
      },
      "ShortMakerTemplate": {
        "type": "object",
        "required": [
          "id",
          "name",
          "source"
        ],
        "properties": {
          "id": {
            "type": "string",
            "maxLength": 160
          },
          "name": {
            "type": "string",
            "maxLength": 240
          },
          "source": {
            "enum": [
              "builtin",
              "custom"
            ]
          },
          "duration": {
            "type": [
              "number",
              "null"
            ]
          },
          "description": {
            "type": [
              "string",
              "null"
            ],
            "maxLength": 1000
          }
        }
      },
      "Error": {
        "type": "object",
        "required": [
          "error",
          "error_code",
          "request_id"
        ],
        "properties": {
          "error": {
            "type": "string"
          },
          "error_code": {
            "type": "string"
          },
          "request_id": {
            "type": [
              "string",
              "null"
            ]
          }
        },
        "additionalProperties": true
      }
    },
    "responses": {
      "BadRequest": {
        "description": "Invalid request",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "Unauthorized": {
        "description": "Missing or invalid Bearer key",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "Forbidden": {
        "description": "Subscription or team permission denied",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "NotFound": {
        "description": "Route, job, or output not found",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "Conflict": {
        "description": "Idempotency conflict",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "PreconditionFailed": {
        "description": "Google Drive is not configured or connected",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "PayloadTooLarge": {
        "description": "JSON or upload limit exceeded",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "RateLimited": {
        "description": "Queue or authentication rate limit exceeded",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "UnsupportedMediaType": {
        "description": "Multipart is unsupported; send raw binary bytes with X-Filename.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      },
      "StorageUnavailable": {
        "description": "Job journal unavailable or retained upload storage exhausted.",
        "content": {
          "application/json": {
            "schema": {
              "$ref": "#/components/schemas/Error"
            }
          }
        }
      }
    }
  }
}
```

## Complete examples

The examples below are the same files available for download from the guide. Python requires 3.10+ and JavaScript requires Node.js 22+. Both use standard libraries. Adapt the paths and configure your local API key before testing.

### quickstart.py

```python
"""MetaGhost Desktop 1.1.21, API contract 1. Python 3.10+. https://metaghost.io/docs/api#quickstart"""
import uuid
import re
import json
import os
import shutil
import sys
import time
from urllib.error import HTTPError
from urllib.parse import urlparse, quote
from urllib.request import Request, build_opener, HTTPRedirectHandler, ProxyHandler


class NoRedirect(HTTPRedirectHandler):
    def redirect_request(self, req, fp, code, msg, headers, newurl):
        raise RuntimeError("API redirects are not followed; the key stays on the local server.")


def run_job(base_url, api_key, body, timeout_seconds=600, poll_seconds=2, on_accepted=print, idempotency_key=None, on_execution=print):
    base = urlparse(base_url)
    if base.scheme != "http" or base.hostname not in ("127.0.0.1", "localhost", "::1") or base.username or base.password or base.query or base.fragment or base.path.rstrip("/") not in ("/api", "/api/v1"):
        raise ValueError("Run this example on the Desktop computer with an HTTP loopback API URL.")
    if not api_key:
        raise ValueError("Set METAGHOST_API_KEY to the key from Desktop Settings > API.")
    if body.get("driveInputFolder") or body.get("driveInputFileIds") or body.get("driveOutputFolder"):
        raise ValueError("This starter uses local files and local output. Follow the guide's Drive section for transfer polling and delivery.")
    opener = build_opener(NoRedirect, ProxyHandler({}))

    def request(path, data=None, extra_headers=None, authenticated=True, artifact=False):
        headers = {"Authorization": "Bearer " + api_key} if authenticated else {}
        headers.update(extra_headers or {})
        if data is not None:
            headers["Content-Type"] = "application/json"
        target = (base.scheme + "://" + base.netloc + path) if artifact else base_url.rstrip("/") + path
        req = Request(target, data=None if data is None else json.dumps(data).encode(), headers=headers)
        try:
            return opener.open(req, timeout=30)
        except HTTPError as error:
            raise RuntimeError(f"HTTP {error.code}: {error.read().decode()}; Retry-After: {error.headers.get('Retry-After', 'not provided')}") from error

    def read_json(path, **kwargs):
        with request(path, **kwargs) as response:
            return json.load(response)

    health = read_json("/health", authenticated=False)
    if health.get("status") != "ok" or health.get("apiVersion") != "1":
        raise RuntimeError("This example targets MetaGhost Desktop 1.1.21, API contract 1. Check the documentation for your installed version before submitting a job.")
    idempotency_key = idempotency_key or str(uuid.uuid4())
    if not re.fullmatch(r"[\x21-\x7e]{1,128}", idempotency_key):
        raise ValueError("Use an Idempotency-Key with 1 to 128 visible ASCII characters.")
    on_execution(idempotency_key)
    try:
        accepted = read_json("/jobs", data=body, extra_headers={"Idempotency-Key": idempotency_key})
    except Exception as error:
        raise RuntimeError(f"Submission could not be confirmed. Keep Idempotency-Key {idempotency_key} and the unchanged body to recover this execution; do not generate a new key. {error}") from error
    if accepted.get("jobAvailable") is False:
        raise RuntimeError("Receipt retained; history is unavailable. This execution was not restarted.")
    job_id = accepted["jobId"]
    on_accepted(job_id)
    deadline = time.monotonic() + timeout_seconds
    while time.monotonic() < deadline:
        job = read_json("/jobs/" + quote(job_id, safe=""))
        if job["status"] in ("failed", "cancelled"):
            raise RuntimeError(f"Job {job_id}: {job['status']}. {job.get('error') or job.get('errors', [])}")
        if job["status"] == "completed":
            drive = job.get("drive") or {}
            if job.get("outcome") != "success" or job.get("errors") or accepted.get("skipped") or drive.get("uploadError") or (drive.get("uploadResult") or {}).get("errors"):
                raise RuntimeError(f"Job {job_id} has partial results. Inspect errors/skipped files before using its output.")
            def download(index):
                artifacts = job.get("artifacts") or []
                if index < 0 or index >= len(artifacts) or not artifacts[index].get("downloadUrl"):
                    raise RuntimeError("This result has no downloadable local artifact.")
                target = urlparse(artifacts[index]["downloadUrl"])
                paths = [prefix + quote(job_id, safe="") for prefix in ("/api/download/", "/api/v1/download/")]
                if target.scheme or target.netloc or target.path not in paths:
                    raise RuntimeError("Unexpected artifact URL; credentials were not sent.")
                return request(target.path + ("?" + target.query if target.query else ""), artifact=True)
            return job, download
        time.sleep(poll_seconds)
    raise TimeoutError(f"Stopped waiting for {job_id}. The Desktop job was not cancelled; inspect it before retrying.")


if __name__ == "__main__":
    try:
        if len(sys.argv) != 4:
            raise ValueError("Usage: python quickstart.py INPUT_FILE DESKTOP_OUTPUT_FOLDER NEW_DOWNLOAD_FILE")
        source, output_folder, download_file = sys.argv[1:]
        if os.path.exists(download_file):
            raise ValueError("Choose a new download filename. Existing files are never overwritten.")
        body = {"filePath": source, "outputFolder": output_folder, "batchCount": 1}
        if os.environ.get("METAGHOST_PRESET"):
            body["preset"] = os.environ["METAGHOST_PRESET"]
        job, download = run_job(os.environ.get("METAGHOST_API_URL", "http://127.0.0.1:3847/api/v1"), os.environ.get("METAGHOST_API_KEY"), body,
                                idempotency_key=os.environ.get("METAGHOST_IDEMPOTENCY_KEY"),
                                on_execution=lambda key: print("Execution key: " + key + ". Preserve this key for recovery.", flush=True),
                                on_accepted=lambda job_id: print("Accepted " + job_id, flush=True))
        with download(0) as response, open(download_file, "xb") as destination:
            shutil.copyfileobj(response, destination)
        print(f"Completed {job['jobId']}. Downloaded first output to {download_file}")
    except Exception as error:
        print(str(error), file=sys.stderr)
        sys.exit(1)
```


### quickstart.mjs

```javascript
// MetaGhost Desktop 1.1.21, API contract 1. Node.js 22+. https://metaghost.io/docs/api#quickstart
import { randomUUID } from 'node:crypto';
import { existsSync, createWriteStream } from 'node:fs';
import { Readable } from 'node:stream';
import { pipeline } from 'node:stream/promises';
import { pathToFileURL } from 'node:url';

export async function runJob({ baseUrl, apiKey, body, timeoutMs = 600000, pollMs = 2000, onAccepted = () => {}, idempotencyKey = randomUUID(), onExecution = () => {} }) {
  const base = new URL(baseUrl);
  if (base.protocol !== 'http:' || !['127.0.0.1', 'localhost', '[::1]'].includes(base.hostname) || base.username || base.password || base.search || base.hash || !/^\/api(?:\/v1)?\/?$/.test(base.pathname)) {
    throw new Error('This example runs on the Desktop computer. Use an HTTP loopback URL without credentials, query or fragment.');
  }
  if (!apiKey) throw new Error('Set METAGHOST_API_KEY to the key shown in Desktop Settings > API.');
  if (body?.driveInputFolder || body?.driveInputFileIds || body?.driveOutputFolder) throw new Error('This starter uses local files and local output. Follow the guide’s Drive section for transfer polling and delivery.');
  const root = base.href.replace(/\/$/, '');
  const request = async (path, options = {}, authenticated = true, artifact = false) => {
    const response = await fetch(artifact ? `${base.origin}${path}` : `${root}${path}`, {
      ...options, redirect: 'error', signal: AbortSignal.timeout(30000),
      headers: { ...(authenticated ? { Authorization: `Bearer ${apiKey}` } : {}), ...options.headers },
    });
    if (!response.ok) {
      const text = await response.text();
      throw new Error(`HTTP ${response.status}: ${text}; Retry-After: ${response.headers.get('retry-after') || 'not provided'}`);
    }
    return response;
  };
  const health = await (await request('/health', {}, false)).json();
  if (health.status !== 'ok' || health.apiVersion !== '1') throw new Error('This example targets MetaGhost Desktop 1.1.21, API contract 1. Check the documentation for your installed version before submitting a job.');
  if (!/^[\x21-\x7e]{1,128}$/.test(idempotencyKey)) throw new Error('Use an Idempotency-Key with 1 to 128 visible ASCII characters.');
  onExecution(idempotencyKey);
  let accepted;
  try {
    accepted = await (await request('/jobs', {
      method: 'POST', headers: { 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey }, body: JSON.stringify(body),
    })).json();
  } catch (error) {
    throw new Error(`Submission could not be confirmed. Keep Idempotency-Key ${idempotencyKey} and the unchanged body to recover this execution; do not generate a new key. ${error.message}`);
  }
  if (accepted.jobAvailable === false) throw new Error(`Receipt retained for ${accepted.jobId}; history is unavailable. This execution was not restarted.`);
  if (!accepted.jobId) throw new Error('The server did not return a jobId; preserve the execution key.');
  onAccepted(accepted.jobId);
  const deadline = Date.now() + timeoutMs;
  while (Date.now() < deadline) {
    const job = await (await request(`/jobs/${encodeURIComponent(accepted.jobId)}`)).json();
    if (['failed', 'cancelled'].includes(job.status)) throw new Error(`Job ${accepted.jobId}: ${job.status}. ${job.error || JSON.stringify(job.errors || [])}`);
    if (job.status === 'completed') {
      if (job.outcome !== 'success' || job.errors?.length || accepted.skipped?.length || job.drive?.uploadError || job.drive?.uploadResult?.errors?.length) {
        throw new Error(`Job ${accepted.jobId} has partial results. Inspect errors/skipped files before using its output.`);
      }
      return { job, idempotencyKey, download: index => {
        const artifact = job.artifacts?.[index];
        const url = artifact?.downloadUrl;
        if (typeof url !== 'string') throw new Error('This result has no downloadable local artifact.');
        const target = new URL(url, base.origin);
        const paths = ['/api/download/', '/api/v1/download/'].map(prefix => prefix + encodeURIComponent(job.jobId));
        if (target.origin !== base.origin || target.username || target.password || !paths.includes(target.pathname)) throw new Error('Unexpected artifact URL; credentials were not sent.');
        return request(target.pathname + target.search, {}, true, true);
      } };
    }
    await new Promise(resolve => setTimeout(resolve, pollMs));
  }
  throw new Error(`Stopped waiting for ${accepted.jobId}. The Desktop job was not cancelled; inspect it before retrying.`);
}

if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
  const [filePath, outputFolder, downloadFile] = process.argv.slice(2);
  try {
    if (!filePath || !outputFolder || !downloadFile) throw new Error('Usage: node quickstart.mjs INPUT_FILE DESKTOP_OUTPUT_FOLDER NEW_DOWNLOAD_FILE');
    if (existsSync(downloadFile)) throw new Error('Choose a new download filename. Existing files are never overwritten.');
    const result = await runJob({
      baseUrl: process.env.METAGHOST_API_URL || 'http://127.0.0.1:3847/api/v1', apiKey: process.env.METAGHOST_API_KEY,
      body: { filePath, outputFolder, batchCount: 1, ...(process.env.METAGHOST_PRESET ? { preset: process.env.METAGHOST_PRESET } : {}) },
      idempotencyKey: process.env.METAGHOST_IDEMPOTENCY_KEY,
      onExecution: key => console.log(`Execution key: ${key}. Preserve this key for recovery.`),
      onAccepted: jobId => console.log(`Accepted ${jobId}`),
    });
    const response = await result.download(0);
    await pipeline(Readable.fromWeb(response.body), createWriteStream(downloadFile, { flags: 'wx' }));
    console.log(`Completed ${result.job.jobId}. Downloaded first output to ${downloadFile}`);
  } catch (error) { console.error(error.message); process.exitCode = 1; }
}
```
