# Persian text to speech

> Turn text into Persian speech (MP3). English text is translated to Persian first; Persian text is used as is. You can check and edit the Persian text before the audio is made. Sequence: `GET /api/v1/farsi-tts/pricing` → `POST /api/v1/farsi-tts/jobs` (holds Fara) → poll `GET /api/v1/farsi-tts/jobs/{id}` until `awaiting_review` → optional `PATCH /api/v1/farsi-tts/jobs/{id}/text` → `POST /api/v1/farsi-tts/jobs/{id}/approve` → poll until `completed` → `GET /api/v1/farsi-tts/jobs/{id}/download`.

## At a glance

- Base path: `/api/v1/farsi-tts`
- Auth: `Authorization: Bearer fara_sk_...` ([Authentication](https://faraatarjomeh.com/api/v1/docs/authentication.md))
- Scope: `read` for GET, `write` for everything else
- Spends Fara: yes, `POST /api/v1/farsi-tts/jobs` holds Fara. Everything else is free.
- Async: yes. Seconds to a few minutes.
- Review: always. Every job stops at `awaiting_review` until you approve or cancel. After 3 days in review it is cancelled and its Fara is released.
- `If-Match`: not used by this feature (edit and approve take no review version)
- Terminal statuses: `completed`, `failed`, `cancelled`
- Webhook events: `farsi_tts.awaiting_review`, `farsi_tts.completed`, `farsi_tts.failed`, `farsi_tts.cancelled`
- Output: MP3

## Before you start

### Price and limits

```http
GET /api/v1/farsi-tts/pricing HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK`:

```json
{ "faraPerMin": 1.87, "charsPerMinute": 1000, "maxInputChars": 20000, "holdHeadroom": 1.3 }
```

```bash
curl -sS "https://faraatarjomeh.com/api/v1/farsi-tts/pricing" -H "Authorization: Bearer $FARA_API_KEY"
```

| Field | Meaning |
|---|---|
| `charsPerMinute` | Characters of Persian text per minute of speech. |
| `maxInputChars` | Most characters in `text` (after trimming spaces at both ends). Characters are Unicode code points. |
| `holdHeadroom` | The hold covers `length × holdHeadroom`, to leave room for the text growing in translation and for edits. |
| `faraPerMin` | Fara per minute of speech. |

**Estimate before create:** hold ≈ `length / charsPerMinute × holdHeadroom × faraPerMin` (rounded); the charge ≈ `length of the Persian text / charsPerMinute × faraPerMin`. The create answer gives the exact hold in `job.cost.faraCharged`. The final charge is the real cost. If it is above the hold, the difference is charged as an extra ledger row when your balance covers it; if it does not, only the hold is charged. If the hold is above the user's budget, cancel at once: the hold is released and nothing is charged.

### How much text the hold covers (`reservedChars`)

At create, the hold is sized for `ceil(length / charsPerMinute × holdHeadroom)` minutes (at least 1). The job shows `reservedChars = that number of minutes × charsPerMinute`. **The Persian text that is spoken must not be longer than `reservedChars`.** Edits longer than that are refused, and approve is refused if the translated text grew past it. Then shorten the text with `PATCH /api/v1/farsi-tts/jobs/{id}/text` before approving.

Example: 412 English characters → 0.54 minutes → 1 minute held → `reservedChars: 1000`.

| Limit | Value |
|---|---|
| `text` length | 1 to `maxInputChars` (today 20,000) characters |
| Spoken Persian text | at most `reservedChars` |
| Rate limits | 120 requests per 60 s per API key; job creation 300 uploads per hour per account |

## Steps

### 1. Create the job

Send an `Idempotency-Key` (a new UUID per job). A success (and a `500`/`502`/`504`) is stored for 24 hours: sending the same key again returns that first answer and never charges twice. A `4xx` or `503` answer is not stored, so after you fix the request (or the user tops up) you can send it again with the same key.

```http
POST /api/v1/farsi-tts/jobs HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json
Idempotency-Key: 1f2e3d4c-5b6a-4978-8a9b-0c1d2e3f4a5b

{
  "text": "Welcome to our store. Orders placed before noon ship the same day.",
  "sourceLang": "en",
  "voiceGender": "female"
}
```

Response `201 Created`:

```json
{
  "job": {
    "_id": "66f5d2b4c6e8f0a1b3c5d7e9",
    "sourceLang": "en",
    "voiceGender": "female",
    "status": "pending",
    "stage": "queued",
    "progress": 5,
    "cost": { "faraCharged": 2, "minutesBilled": 1 },
    "audio": null,
    "customerErrorCode": null,
    "inputText": "Welcome to our store. Orders placed before noon ship the same day.",
    "farsiText": "",
    "reservedChars": 1000,
    "estimatedMinutes": 0.066,
    "estimatedCost": { "faraCharged": 2, "minutesBilled": 1 },
    "createdAt": "2026-09-25T12:00:00.000Z",
    "updatedAt": "2026-09-25T12:00:00.000Z",
    "completedAt": null,
    "failedAt": null
  }
}
```

```bash
curl -sS -X POST "https://faraatarjomeh.com/api/v1/farsi-tts/jobs" \
  -H "Authorization: Bearer $FARA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: $(uuidgen)" \
  -d '{"text":"Welcome to our store. Orders placed before noon ship the same day.","sourceLang":"en","voiceGender":"female"}'
```

| Field | Type | Required | Default | Allowed values | Notes |
|---|---|---|---|---|---|
| `text` | string | yes | — | 1 to `maxInputChars` characters after trimming | The text to speak. |
| `sourceLang` | string | yes | — | `en`, `fa` | `en`: translated to Persian first, then you review the Persian. `fa`: used as is; `farsiText` equals `text` at once. No other languages. |
| `voiceId` | string | no | `male` | a voice `id` from `GET /api/v1/farsi-tts/voices`, `male`, `female` | The voice. Anything else answers `400`. |
| `voiceGender` | string | no | `male` | `male`, `female` | The voice, used when `voiceId` is left out. |
| `voiceMood` | string | no | `neutral` | `neutral`, `friendly`, `formal`, `happy`, `sad`, `calm`, `energetic`, `serious` | How the voice sounds. Does not change the price. |

`GET /api/v1/farsi-tts/voices` lists the voices (`voices`: `id`, `gender`, Persian and English names, `previewUrl` of a short Persian sample) and the moods (`moods`). Always read the list from that call; voices can be added.

### 2. Wait for the Persian text

Poll every 10 seconds (or wait for `farsi_tts.awaiting_review`).

```http
GET /api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9 HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK`:

```json
{
  "job": {
    "_id": "66f5d2b4c6e8f0a1b3c5d7e9",
    "sourceLang": "en",
    "voiceGender": "female",
    "status": "awaiting_review",
    "stage": "awaiting_review",
    "progress": 50,
    "cost": { "faraCharged": 2, "minutesBilled": 1 },
    "inputText": "Welcome to our store. Orders placed before noon ship the same day.",
    "farsiText": "به فروشگاه ما خوش آمدید. سفارش‌هایی که پیش از ظهر ثبت شوند، همان روز ارسال می‌شوند.",
    "reservedChars": 1000,
    "estimatedMinutes": 0.083,
    "estimatedCost": { "faraCharged": 2, "minutesBilled": 1 },
    "customerErrorCode": null
  }
}
```

```bash
curl -sS "https://faraatarjomeh.com/api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9" -H "Authorization: Bearer $FARA_API_KEY"
```

| Field | Type | Notes |
|---|---|---|
| `_id` | string | Job id (24 hex characters). |
| `status` | string | See [State machine](#state-machine). |
| `stage` | string | Display only: `queued`, `translating`, `awaiting_review`, `synthesizing`, `finalizing`, `done`. More values can appear. |
| `inputText` | string | Your text as sent (trimmed). Only on single-job GET and create. |
| `farsiText` | string | The Persian text that will be spoken. `""` until translated. Editable in review. Only on single-job GET and create. |
| `reservedChars` | integer | Most characters `farsiText` may have. |
| `estimatedMinutes` | number | `length of farsiText (or inputText) / charsPerMinute`, not rounded. |
| `estimatedCost` | object or null | Price for the current text: `{ faraCharged, minutesBilled }`. |
| `cost` | object | The hold while running; after `completed`, the real charge plus `heldFara` and `refundedFara`. |
| `audio` | object or null | After `completed`: `{ "durationSeconds": 5.8 }`. |
| `customerErrorCode` | string or null | Why a `failed` job failed. |

The list call `GET /api/v1/farsi-tts/jobs?limit=20&offset=0` returns `{ "jobs": [ ... ] }` without `inputText`, `farsiText`, `reservedChars` and the estimate fields. Add `q` to search by name: the name you gave the job or its original file name, ignoring case, at most 100 characters.

### 3. Edit the Persian text (optional)

Replaces the whole `farsiText`. No `If-Match`.

```http
PATCH /api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9/text HTTP/1.1
Authorization: Bearer fara_sk_...
Content-Type: application/json

{"text": "به فروشگاه ما خوش آمدید. سفارش‌های پیش از ظهر، همان روز ارسال می‌شوند."}
```

Response `200 OK`:

```json
{ "ok": true, "estimatedMinutes": 0.07, "estimatedCost": { "faraCharged": 2, "minutesBilled": 1 } }
```

```bash
curl -sS -X PATCH "https://faraatarjomeh.com/api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9/text" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Content-Type: application/json" \
  -d '{"text":"به فروشگاه ما خوش آمدید. سفارش‌های پیش از ظهر، همان روز ارسال می‌شوند."}'
```

| Body field | Type | Required | Notes |
|---|---|---|---|
| `text` | string | yes | Non-empty after trimming. At most `maxInputChars` and at most `reservedChars` characters, else `413` with `maxChars`. |

Only in `awaiting_review`, else `409`. The last edit wins; there is no version check.

### 4. Approve

```http
POST /api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9/approve HTTP/1.1
Authorization: Bearer fara_sk_...
Idempotency-Key: 9a8b7c6d-5e4f-4a3b-8c2d-1e0f9a8b7c6d
```

Response `200 OK`:

```json
{ "ok": true, "status": "active" }
```

```bash
curl -sS -X POST "https://faraatarjomeh.com/api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9/approve" \
  -H "Authorization: Bearer $FARA_API_KEY" -H "Idempotency-Key: $(uuidgen)"
```

Refused with `409` when `farsiText` is empty, or when it is longer than `reservedChars` (the body then has `maxChars`; shorten with step 3 and approve again). Approve uses the Fara already held.

### 5. Download the MP3

Needs `status: "completed"`, else `409`.

```http
GET /api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9/download HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK`, `Content-Type: audio/mpeg`, `Accept-Ranges: bytes`, `Content-Disposition: attachment; filename="farsi-tts-66f5d2b4c6e8f0a1b3c5d7e9.mp3"`. One `Range: bytes=start-end` gives `206`; a bad range gives `416`.

```bash
curl -sS -o speech-fa.mp3 "https://faraatarjomeh.com/api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9/download" \
  -H "Authorization: Bearer $FARA_API_KEY"
```

### Delete

```http
DELETE /api/v1/farsi-tts/jobs/{id} HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `204 No Content`. Removes the text and the audio from our servers. This cannot be undone. Ledger rows (billing history) stay. Only a finished job (`completed`, `failed` or `cancelled`) can be deleted. A job that is still running or queued, or waiting for review, answers `409` with `JOB_NOT_FINISHED`: cancel it first. After the delete the job answers `404`. Open to every account.

### Cancel

```http
POST /api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9/cancel HTTP/1.1
Authorization: Bearer fara_sk_...
```

Response `200 OK`: `{ "ok": true }`. The hold is released. Works in any status except `completed` and `cancelled`, and not once the last step has started (`stage` is `finalizing` or `done`) → `409`.

```bash
curl -sS -X POST "https://faraatarjomeh.com/api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9/cancel" -H "Authorization: Bearer $FARA_API_KEY"
```

There is no retry call. After `failed` (hold released), create a new job.

## State machine

| `status` | Terminal? | Meaning | Next action for the client |
|---|---|---|---|
| `pending` | no | Queued, or translating English to Persian. | Poll. |
| `awaiting_review` | no | Persian text ready. Waits up to 3 days, then is cancelled and refunded. | Edit (optional), then `approve`; or `cancel`. |
| `active` | no | Making the audio. | Poll. |
| `completed` | yes | Done and charged. | Download. |
| `failed` | yes | Stopped. Hold released. `customerErrorCode` says why. | `NO_SPEECH_FOUND`: the text was empty after translation; fix the text. `SERVICE_BUSY`, `TOOK_TOO_LONG`, `GENERIC`: create a new job once. |
| `cancelled` | yes | Cancelled by you, or the review was left for 3 days. Hold released. | Nothing. |

Transitions: create → `pending` → `awaiting_review` → (`approve`) → `active` → `completed`. Any error → `failed`. `cancel` → `cancelled`. Treat any other status as still running.

## Billing

1. `POST /api/v1/farsi-tts/jobs` holds the price of `ceil(length / charsPerMinute × holdHeadroom)` minutes (`job.cost.faraCharged`). `402` if the balance is too low; nothing is held on any `4xx`.
2. The English-to-Persian translation, review and edits use the same hold.
3. When the audio is made, the real cost is charged, from the real audio length. If it is above the hold, the difference is charged as an extra ledger row when your balance covers it; if it does not, only the hold is charged. Anything held and not used is released (`cost.heldFara`, `cost.refundedFara`).
4. On `failed` or `cancelled` the whole hold is released.

See [Billing](https://faraatarjomeh.com/api/v1/docs/billing.md).

## Webhook events

| Event | When |
|---|---|
| `farsi_tts.awaiting_review` | The Persian text is ready for review. |
| `farsi_tts.completed` | The MP3 is ready. |
| `farsi_tts.failed` | The job failed. GET the job for `customerErrorCode`. |
| `farsi_tts.cancelled` | The job was cancelled. |

Payload: `{ "type": "farsi_tts.completed", "timestamp": "...", "id": "evt_...", "data": { "object": "farsi_tts", "id": "66f5d2b4c6e8f0a1b3c5d7e9", "status": "completed", "createdAt": "...", "updatedAt": "...", "links": { "self": "https://faraatarjomeh.com/api/v1/farsi-tts/jobs/66f5d2b4c6e8f0a1b3c5d7e9" } } }`. See [Webhooks](https://faraatarjomeh.com/api/v1/docs/webhooks.md).

## Errors and recovery

All errors are `application/problem+json`. Branch on `code`. See [Errors](https://faraatarjomeh.com/api/v1/docs/errors.md).

| HTTP | `code` | When | Retry? | What the client should do |
|---|---|---|---|---|
| 400 | [`BAD_REQUEST`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-bad-request) | `text` missing or empty, `sourceLang` not `en`/`fa`, bad `voiceId`, `voiceGender` or `voiceMood`. | no | Fix the request. |
| 413 | [`PAYLOAD_TOO_LARGE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-payload-too-large) | `text` over `maxInputChars` (create or edit), or edit over `reservedChars`. Body has `maxChars`. | no | Shorten the text, or split it into several jobs. |
| 402 | [`INSUFFICIENT_CREDITS`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-insufficient-credits) | Balance below the hold. Body has `required` (the hold). | no | Tell the user; they top up at https://faraatarjomeh.com. After the top-up, send the same request again; the same `Idempotency-Key` is fine (4xx answers are not stored). |
| 402 | [`CHARGEBACK_LIABILITY_OUTSTANDING`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-chargeback-liability-outstanding) | A payment was reversed. | no | Tell the user to settle it on the website. |
| 404 | [`NOT_FOUND`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-not-found) | No such job. | no | Check the id. |
| 409 | [`CONFLICT`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-conflict) | Edit or approve outside `awaiting_review`; approve with empty text; approve with text over `reservedChars` (body has `maxChars`); download before `completed`; cancel too late. | refresh | GET the job and decide from `status`; for `maxChars`, shorten the text first. |
| 409 | [`HOLD_NOT_FOUND`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-hold-not-found) | On approve: the hold is gone; the job is cancelled. | no | Create a new job. |
| 409 | [`IDEMPOTENCY_KEY_IN_USE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-idempotency-key-in-use) | First request with this key still running. | yes | Wait `Retry-After`, resend with the same key. |
| 429 | [`RATE_LIMITED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-rate-limited) | Too many requests. | yes | Wait `Retry-After` seconds. |
| 500, 502, 504 | [`INTERNAL_ERROR`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-internal-error), [`UPSTREAM_ERROR`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upstream-error), [`UPSTREAM_TIMEOUT`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-upstream-timeout) | Unknown outcome: the job may or may not exist. This answer is stored, so the same `Idempotency-Key` only replays it. | check first | List jobs with `GET /api/v1/farsi-tts/jobs` and look for one with the same `sourceLang` created in the last minutes (the list has no text). Only if there is none, send the request again with a NEW `Idempotency-Key`. |
| 503 | [`FEATURE_DISABLED`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-feature-disabled) | Text to speech is off on this server. | later | Try again much later. |
| 503 | [`CREDIT_RESERVATION_UNAVAILABLE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-credit-reservation-unavailable) | Could not hold Fara right now. | yes | Wait `Retry-After`, resend with the same `Idempotency-Key`. |
| 503 | [`SERVICE_BUSY`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-service-busy) | On approve: could not start the audio. The job is now `failed` and its hold released. | no | Wait `Retry-After` (30 s), then create a new job. |
| 503 | [`SERVICE_UNAVAILABLE`](https://faraatarjomeh.com/api/v1/docs/errors.md#error-service-unavailable) | On create: could not queue the job; hold released. | yes | Back off, resend with the same `Idempotency-Key`. |

## Rules for agents

- Estimate the hold from `faraPerMin` before create, then confirm it in the create answer. If it is above the user's budget, cancel at once.
- Use `sourceLang: "fa"` only for text that is already Persian. For English use `en`.
- Before approving, check `farsiText` length against `reservedChars`. If it is longer, shorten it with `PATCH /api/v1/farsi-tts/jobs/{id}/text` (ask the user what to cut unless they allowed you to decide).
- Approve without the user only if they said so; otherwise show `farsiText` and wait.
- Send a new `Idempotency-Key` on create and approve; reuse it only when retrying the same call.
- Poll no faster than every 10 seconds. Branch on `code` and `customerErrorCode`, never on `detail`. Treat unknown statuses as still running.

## Complete script

Both scripts: create from English → wait for the Persian text → trim-check → approve (only when the user allowed it) → wait → download. Set `FARA_API_KEY`, `FARA_BASE_URL` and `MAX_FARA`.

```python
# Python 3.9+, pip install requests
import os, sys, time, uuid
import requests

BASE = os.environ.get("FARA_BASE_URL", "https://faraatarjomeh.com").rstrip("/")
H = {"Authorization": f"Bearer {os.environ['FARA_API_KEY']}"}
TEXT = "Welcome to our store. Orders placed before noon ship the same day."
MAX_FARA = 30

def check(r):
    if r.status_code >= 400:
        p = r.json() if "json" in r.headers.get("Content-Type", "") else {}
        raise SystemExit(f"{r.status_code} {p.get('code')}: {p.get('detail')} {p.get('maxChars', '')}")
    return r

def wait(job_id, stop):
    while True:
        job = check(requests.get(f"{BASE}/api/v1/farsi-tts/jobs/{job_id}", headers=H, timeout=60)).json()["job"]
        print(job["status"], job.get("stage"))
        if job["status"] in stop:
            return job
        time.sleep(10)

pricing = check(requests.get(f"{BASE}/api/v1/farsi-tts/pricing", headers=H, timeout=30)).json()
if len(TEXT.strip()) > pricing["maxInputChars"]:
    sys.exit("text is too long; split it")

job = check(requests.post(f"{BASE}/api/v1/farsi-tts/jobs", timeout=60,
                          headers={**H, "Idempotency-Key": str(uuid.uuid4())},
                          json={"text": TEXT, "sourceLang": "en", "voiceGender": "female"})).json()["job"]
job_id = job["_id"]
print("job:", job_id, "held:", job["cost"]["faraCharged"], "Fara")
if job["cost"]["faraCharged"] > MAX_FARA:
    check(requests.post(f"{BASE}/api/v1/farsi-tts/jobs/{job_id}/cancel", headers=H, timeout=30))
    sys.exit("over budget; cancelled, hold released")

job = wait(job_id, ("awaiting_review", "completed", "failed", "cancelled"))
if job["status"] == "awaiting_review":
    print("Persian:", job["farsiText"])
    if len(job["farsiText"]) > job["reservedChars"]:
        sys.exit(f"Persian text is longer than {job['reservedChars']} characters; shorten it with PATCH .../text")
    check(requests.post(f"{BASE}/api/v1/farsi-tts/jobs/{job_id}/approve", timeout=60,
                        headers={**H, "Idempotency-Key": str(uuid.uuid4())}))
    job = wait(job_id, ("completed", "failed", "cancelled"))
if job["status"] != "completed":
    sys.exit(f"job ended as {job['status']} ({job.get('customerErrorCode')})")

mp3 = check(requests.get(f"{BASE}/api/v1/farsi-tts/jobs/{job_id}/download", headers=H, timeout=300))
with open("speech-fa.mp3", "wb") as f:
    f.write(mp3.content)
print("charged:", job["cost"]["faraCharged"], "Fara")
```

```js
// Node.js 20+ (ESM: save as tts.mjs)
import { writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";

const BASE = (process.env.FARA_BASE_URL ?? "https://faraatarjomeh.com").replace(/\/+$/, "");
const H = { Authorization: `Bearer ${process.env.FARA_API_KEY}` };
const TEXT = "Welcome to our store. Orders placed before noon ship the same day.";
const MAX_FARA = 30;
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function call(path, init = {}) {
  const res = await fetch(`${BASE}${path}`, { ...init, headers: { ...H, ...init.headers } });
  if (!res.ok) {
    const p = await res.json().catch(() => ({}));
    throw Object.assign(new Error(`${res.status} ${p.code}: ${p.detail}`), { code: p.code, body: p });
  }
  return res;
}
async function wait(id, stop) {
  for (;;) {
    const { job } = await (await call(`/api/v1/farsi-tts/jobs/${id}`)).json();
    console.log(job.status, job.stage);
    if (stop.includes(job.status)) return job;
    await sleep(10_000);
  }
}

const pricing = await (await call("/api/v1/farsi-tts/pricing")).json();
if ([...TEXT.trim()].length > pricing.maxInputChars) throw new Error("text is too long; split it");

let { job } = await (await call("/api/v1/farsi-tts/jobs", {
  method: "POST",
  headers: { "Content-Type": "application/json", "Idempotency-Key": randomUUID() },
  body: JSON.stringify({ text: TEXT, sourceLang: "en", voiceGender: "female" }),
})).json();
const jobId = job._id;
console.log("job:", jobId, "held:", job.cost.faraCharged, "Fara");
if (job.cost.faraCharged > MAX_FARA) {
  await call(`/api/v1/farsi-tts/jobs/${jobId}/cancel`, { method: "POST" });
  throw new Error("over budget; cancelled, hold released");
}

job = await wait(jobId, ["awaiting_review", "completed", "failed", "cancelled"]);
if (job.status === "awaiting_review") {
  console.log("Persian:", job.farsiText);
  if ([...job.farsiText].length > job.reservedChars) {
    throw new Error(`Persian text is longer than ${job.reservedChars} characters; shorten it with PATCH .../text`);
  }
  await call(`/api/v1/farsi-tts/jobs/${jobId}/approve`, { method: "POST", headers: { "Idempotency-Key": randomUUID() } });
  job = await wait(jobId, ["completed", "failed", "cancelled"]);
}
if (job.status !== "completed") throw new Error(`job ended as ${job.status} (${job.customerErrorCode})`);

const mp3 = await call(`/api/v1/farsi-tts/jobs/${jobId}/download`);
await writeFile("speech-fa.mp3", Buffer.from(await mp3.arrayBuffer()));
console.log("charged:", job.cost.faraCharged, "Fara");
```
