# Voiceswap API — agent guide

The same API as /docs, written for a coding agent: flat statements, exact types,
nothing to infer. Machine-readable spec: GET /openapi.json (OpenAPI 3.1, matches
the deployed routes).

Base URL: read it from the environment — $VOICESWAP_API_BASE, the api.* origin
of the deployment. Never hardcode a domain.
Auth: every request carries `Authorization: Bearer $VOICESWAP_API_KEY`
(keys start with vsk_, shown once at creation; never hardcode one).

## Rules
- Do not upload audio the user does not hold rights to. Ask first.
- Billing is per minute of INPUT audio, measured on the server, rounded up to
  the second. Failed, refused, and cancelled calls are never billed. There are
  no free minutes: the workspace needs a payment method or job POSTs return
  402 payment_required.
- Every job POST returns 202, `Location: /v1/jobs/{id}`, `Retry-After`, and a
  job containing `status_url`. Poll that URL when Retry-After allows. Cache its
  ETag and send If-None-Match; 304 means unchanged. Lifecycle:
  queued → processing → succeeded|failed, with queued|processing → cancelled.
- Never re-send a job POST as a "retry". If the response was lost, repeat the
  POST with the SAME Idempotency-Key.
- Send Idempotency-Key: <uuid> on every POST, PUT, PATCH, and DELETE. A repeat within 24 h returns
  the first result (header `idempotency-replayed: true`) and never creates a
  second job or a second charge. The same key with a DIFFERENT body is 409.
- On 429, read Retry-After (seconds) and wait at least that long. Do not
  tighten the loop. code queue_full = an operator-configured per-workspace
  concurrent-job cap (none by default); code rate_limited =
  rpm, per-key monthly minute cap, or workspace spend cap.
- Audio bytes never go in a job POST (JSON only — no multipart/form-data).
  Upload first, then reference the upload:
    1. POST /v1/uploads {"content_length": N, "rights_attestation": true}
       → { upload_id, put_url }
       then PUT the file bytes to put_url.
       (≤ 50 MB may instead use one PUT /v1/uploads/direct with the raw body;
       Content-Length and `x-voiceswap-rights-attestation: true` headers are
       required; when idempotency is used, also send a Content-Digest covering
       the bytes.)
    2. POST the job with {"input": {"upload_id": "..."}}.
- Attestation scope: every conversion-source upload requires the explicit
  declaration above. Clone/training dataset creation separately requires its
  own explicit declaration when that currently-disabled capability is enabled.
  Each acceptance records the current policy version and hash, signer, subject,
  context, and time in append-only evidence. Missing/false is 400 input_invalid.
- Results: GET /v1/jobs/{id}/result → { url, expires_at, format } — a signed
  download URL valid 15 min; call again for a fresh one. Outputs are deleted
  per retention policy (default: 1 h grace after success) — download promptly;
  after deletion the endpoint is 404.

## Endpoints
POST   /v1/swap                              replace the singer; body below
POST   /v1/vocals                            isolated vocal; input, params{denoise}, format
POST   /v1/instrumental                      backing track; input, format
GET    /v1/jobs/{id}                         poll status
DELETE /v1/jobs/{id}                         cancel queued/processing (else 409); cancelled = never billed
GET    /v1/jobs/{id}/result                  signed output URL (15 min)
GET    /v1/voices                            cursor page; query limit=25&amp;cursor=…
POST   /v1/uploads                           presigned single PUT (primary path)
PUT    /v1/uploads/direct                    raw-body upload ≤ 50 MB
POST   /v1/uploads/multipart                 initiate resumable upload
POST   /v1/uploads/multipart/{id}/parts      body {"part_numbers":[1..]} → signed part URLs
POST   /v1/uploads/multipart/{id}/complete   body {"parts":[{"part_number","etag"}]}
POST   /v1/uploads/multipart/{id}/abort      abort the session
POST   /v1/webhooks                          register endpoint → { id, url, secret } (secret shown once)
GET    /v1/webhooks                          cursor page; query limit=25&amp;cursor=…
DELETE /v1/webhooks/{id}                     deactivate endpoint
GET    /v1/webhooks/{id}/deliveries          cursor page; query limit=25&amp;cursor=…
POST   /v1/webhooks/deliveries/{id}/replay   requeue a delivery (incl. dead-lettered)
GET    /v1/ping                              auth check: echoes workspace + scopes

## Job body (POST /v1/swap)
content-type: application/json
  input                  required  {"upload_id": "<uuid>"} or {"r2_key": "<key>"};
                                   if both are sent, upload_id wins
  voice                  required  string, id from GET /v1/voices with status "ready"
  params.pitch           optional  int -24..24, semitones, default 0. Validated on
                                   the engine AFTER the 202 — out of range fails the
                                   job with input_invalid (never billed)
  params.preserve_timing optional  bool, default true. NO EFFECT today — conversion
                                   is always frame-exact; accepted for forward
                                   compatibility only
  params.denoise         optional  bool, default false. Speech-bypass only: applied
                                   when the input classifies as speech; ignored for
                                   music mixes (they go through separation)
  format                 optional  "wav"|"mp3"|"flac", default "wav"
  duration_hint_seconds  optional  number > 0 and <= 1800 (fractions allowed; the
                                   hold rounds up); sizes the credit hold only —
                                   billing always uses the measured duration.
                                   Ignored when a workspace spend cap (incl. the
                                   first-week ceiling) or key cap applies: the
                                   hold is then the 1800 s job maximum

202 → { id: "job_…", status: "queued", status_url, endpoint, voice_id, format,
        input_duration_seconds: null, billed_duration_seconds: null,
        failure: null, created_at, updated_at, finished_at: null,
        output_available: false, links: { self, result } }
Then poll. On success billed_duration_seconds and output_available appear; fetch
GET /v1/jobs/{id}/result. Input caps: 100 MB / 30 minutes per job.

## GET /v1/voices
200 → { "data": [ { id: "voice_…", name, status, kind, best_for: [..],
        library: bool, created_at } ], "has_more": bool, "next_cursor": string|null }
All public lists use `limit` (default 25, range 1–100) plus opaque `cursor`.
Never pass a voice whose status is not "ready" (not-ready = 409; unknown = 404
voice_not_found; out of key scope = 403).

## Private model imports (admin keys with explicit voices:import)

When /healthz reports components.imports.status=disabled, all import endpoints return 503 import_unavailable (retryable=false). Resume playground pushes when imports are enabled.

POST /v1/voices/imports  Send name (1–80 chars), rights_attestation=true, rights_basis (1–1000 characters), sample (boolean), and model_size_bytes (integer, 1–524288000). Include sample_size_bytes (integer, 1–20971520) exactly when sample=true.
201 returns voice_id, status=importing, model_put_url, sample_put_url (nullable), and expires_at.
PUT the model ZIP (≤500 MiB) with Content-Type: application/zip and the requested WAV/MP3/FLAC preview (≤20 MiB) with Content-Type: application/octet-stream within 15 minutes. Send Content-Length equal to the corresponding declared size. Include If-None-Match: * and omit x-amz-copy-source. The ZIP must contain only model.pth (torch.save) and optional model.index (FAISS) at the root. Rename Applio files before uploading. Use a protocol-2 weights checkpoint with data.pkl up to 2 MiB. Each entry may expand to 1 GiB. DEFLATE entries larger than 1 MiB expanded must stay within a 20:1 ratio. The expanded entries together may occupy up to 2 GiB. Use STORE or DEFLATE without directories, comments, ZIP64 or data descriptors. After the upload URLs expire, replay returns 409. Start a new import to obtain new upload URLs.
POST /v1/voices/imports/{voice_id}/complete  Empty body. Returns voice_id and status=ready, or 400 for an invalid upload.
GET /v1/voices/imports/{voice_id}  Returns voice_id and status (importing, ready or failed). Failed imports include reason.

## Errors
Every non-2xx JSON body is `application/problem+json` with
`{type,title,status,detail,instance,code,request_id,retryable}`. The nested
`error` member is deprecated compatibility data.
Each `type` is `https://voiceswap.dev/docs/errors#<code>` and resolves to the
public meaning/remediation registry.
  400 input_invalid (includes missing/false upload rights_attestation)
  401 unauthorized (missing/invalid/revoked token)
  402 payment_required   403 insufficient_scope | forbidden  404 not_found | voice_not_found
  409 conflict           429 rate_limited | queue_full (has Retry-After)
  500 separation_failed | quality_reject | internal
  400 webhook_destination_blocked (public HTTPS only)
  502 provider_rejected | provider_auth_failed
  503 provider_rate_limited | provider_degraded (has Retry-After)
  501 not_implemented (surface exists, action ships later — do not retry)
  503 oom_retry (retryable)                  504 timeout
None of these bill. Failed jobs expose `failure: {code,detail,retryable}`.

## Billing
<!-- prices:begin -->
Per processed input minute (USD): payg $0.10 · starter $0.08 · producer $0.06 · scale $0.04
<!-- prices:end -->
Rounded up to the second. Prices come from the versioned catalog (v1) — the
/docs Billing section renders the full table.

## Key scopes
A key can be restricted to specific endpoints and specific voices. Anything
outside the scope returns 403 and is never billed. Do not work around a 403 by
trying another endpoint — surface it and ask the user to widen the key.

## Webhooks (optional, instead of polling)
Deliveries are signed: header `vs-signature: t=<ts>,v1=<hex>` where
hex = hmac_sha256(secret, "<ts>.<raw_body>"). Verify before trusting; dedupe on
vs-event-id (delivery is at-least-once). Reject signatures older than 5 minutes.
Events: job.succeeded, job.failed, job.cancelled, voice.ready, voice.failed,
workspace.spend_alert, workspace.payment_failed, workspace.payment_method_saved,
workspace.topup_succeeded, workspace.clone_paid, workspace.refund_issued,
workspace.dispute_created. Ignore unknown future types. Retries:
1m/5m/30m/2h/8h → dead-letter; the replay endpoint revives dead deliveries.
Every event is `{id:"evt_…",type,created_at,data}`. The three job events form a
discriminated union and all carry the same full `data.job`; succeeded also has
`data.billing:{amount,currency}`. Treat `data.job.failure` exactly like polling.

## Do not
- Do not hardcode an API key or a domain. Read $VOICESWAP_API_KEY and
  $VOICESWAP_API_BASE from the environment.
- Do not send audio bytes in the job POST, and do not re-encode before upload —
  send the original file.
- Do not parallelise beyond the key's rpm limit. There is no per-workspace
  concurrent-job cap by default: extra jobs are accepted (202, `queued`) and
  switch to `processing` as soon as they are handed to the GPU provider — a
  job can report `processing` while it still waits for a free GPU worker, so
  a long `processing` is not a failure; keep polling.
- Read RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset, and
  RateLimit-Policy on authenticated API-key responses. A credential-free 401
  omits them; it is not a permanently exhausted quota. Never ignore Retry-After.
