# AragonRouter — API documentation

docsVersion: 1.11.0

Connect your applications and agents through one gateway.

- [Your first request](#quickstart)
- [Authentication and ownership](#authentication)
- [Discover models and capabilities](#discovery)
- [OpenAI compatible messages](#llm-openai)
- [Anthropic messages](#llm-anthropic)
- [Agent augmentation](#llm-agent)
- [Capability hints](#capability-hints)
- [Streaming responses](#llm-streaming)
- [Platform skills](#skills)
- [Workflow runs](#graphs)
- [Generate images](#ai-image)
- [Generate videos](#ai-video)
- [Synthesize speech](#tts)
- [Search images](#image-search)
- [Search videos](#video-search)
- [Search sound effects](#audio-search)
- [Read and cancel jobs](#jobs)
- [Download and delete assets](#assets)
- [Save search material](#ingest)
- [Quota, errors, and retries](#quotas-errors)
- [Agent Skill installation](#agent-skill)

<a id="quickstart"></a>
## Your first request

Discover a model, set your gateway key, and make one deliberate request.

Sign in and issue your own ar- key in My credentials. Registration may be disabled; contact the administrator when needed. Set ARAGON_BASE_URL to the gateway origin and ARAGON_API_KEY in your runtime. Discover models and capabilities before generating. Reading this page and installing the skill consume no quota.

Related operations: [Discover models and capabilities](#discovery), [OpenAI compatible messages](#llm-openai)

<a id="authentication"></a>
## Authentication and ownership

Keep gateway credentials in the calling environment.

All scripts send Authorization: Bearer using ARAGON_API_KEY. LLM routes also accept x-api-key, but not a session cookie alone. Media routes and capabilities additionally accept console sessions. Revoked keys and disabled or deleted accounts return 401. Call from your backend or agent environment; cross-origin browser CORS access is not provided. Never forward the gateway key to external asset URLs.

Administrators and their keys can manage all jobs and assets. Ordinary accounts can manage their account records using any of their valid keys. Records without a user belong only to their originating system key; a system key is not an administrator. Unknown and unauthorized resources both return 404.

<a id="discovery"></a>
## Discover models and capabilities

Read live availability, limits, and personal quota before calling.

GET /api/v1/models returns object=list with data entries containing id, object, owned_by, provider and optional display_name. An empty list is valid. Choose the matching endpoint for openai or anthropic. A route provider does not reveal its protocol: ask the administrator and send the public model id. The gateway does not translate protocols.

GET /api/v1/capabilities returns six entries with id, kind, label, enabled, available, unavailableReason, limits and quota. available does not guarantee quota or future success. Image limits.models contains string ids; video models are objects with id, label, profile, modes, resolutions, maxRefImages, supportsLastFrame and supportsCameraFixed. Use object.id, not the object. TTS limits.voices also contains objects: use voices[].id or defaultVoice. Empty defaults do not authorize guessing a model or voice. Built-in video descriptions do not prove entitlement.

### GET /api/v1/models

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`


#### JSON request

GET /api/v1/models returns object=list with data entries containing id, object, owned_by, provider and optional display_name. An empty list is valid. Choose the matching endpoint for openai or anthropic. A route provider does not reveal its protocol: ask the administrator and send the public model id. The gateway does not translate protocols.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/models"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/models'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/models"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/models";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "object": "list",
  "data": [
    {
      "id": "public-model-id",
      "object": "model",
      "owned_by": "gateway",
      "provider": "openai",
      "display_name": "Public model"
    }
  ]
}
```

### GET /api/v1/capabilities

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`


#### JSON request

Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/capabilities"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/capabilities'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/capabilities"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/capabilities";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": [
    {
      "id": "ai_image",
      "kind": "generate",
      "label": {
        "en": "AI image",
        "zh": "AI image"
      },
      "enabled": true,
      "available": true,
      "unavailableReason": null,
      "limits": {
        "models": [
          "public-image-model"
        ],
        "sizes": [
          "1024x1024",
          "2048x2048",
          "1280x720",
          "720x1280",
          "1024x576",
          "576x1024"
        ],
        "defaultSize": "2048x2048",
        "promptMaxChars": 2000,
        "maxCount": 4,
        "maxReferenceImages": 1,
        "watermarkDefault": true
      },
      "quota": {
        "unit": "image",
        "dailyLimit": 10,
        "used": 1,
        "remaining": 9,
        "resetsAt": 1800057600000
      }
    },
    {
      "id": "ai_video",
      "kind": "async",
      "label": {
        "en": "AI video",
        "zh": "AI video"
      },
      "enabled": true,
      "available": true,
      "unavailableReason": null,
      "limits": {
        "models": [
          {
            "id": "public-video-model",
            "label": "Public video",
            "profile": "seedance_2",
            "modes": [
              "description",
              "keyframe",
              "reference"
            ],
            "resolutions": [
              "480p",
              "720p",
              "1080p"
            ],
            "maxRefImages": 4,
            "supportsLastFrame": true,
            "supportsCameraFixed": false
          }
        ],
        "duration": {
          "min": 4,
          "max": 12,
          "default": 5
        },
        "aspectRatios": [
          "16:9",
          "9:16",
          "1:1"
        ],
        "promptMaxChars": 2000
      },
      "quota": {
        "unit": "video",
        "dailyLimit": 0,
        "used": 0,
        "remaining": null,
        "resetsAt": 1800057600000
      }
    },
    {
      "id": "tts",
      "kind": "stream",
      "label": {
        "en": "Speech",
        "zh": "Speech"
      },
      "enabled": true,
      "available": true,
      "unavailableReason": null,
      "limits": {
        "voices": [
          {
            "id": "discovered-voice",
            "label": "Voice",
            "category": "Example",
            "language": "en-US",
            "generation": "2.0"
          }
        ],
        "defaultVoice": "discovered-voice",
        "maxChars": 1000,
        "speed": {
          "min": 0.5,
          "max": 2,
          "default": 1
        },
        "formats": [
          "mp3"
        ]
      },
      "quota": {
        "unit": "thousand_chars",
        "dailyLimit": 0,
        "used": 0,
        "remaining": null,
        "resetsAt": 1800057600000
      }
    },
    {
      "id": "image_search",
      "kind": "search",
      "label": {
        "en": "image_search",
        "zh": "image_search"
      },
      "enabled": true,
      "available": true,
      "unavailableReason": null,
      "limits": {
        "perPage": {
          "max": 30,
          "default": 20
        },
        "orientations": [
          "landscape",
          "portrait",
          "squarish"
        ],
        "colors": [
          "black_and_white",
          "black",
          "white",
          "yellow",
          "orange",
          "red",
          "purple",
          "magenta",
          "green",
          "teal",
          "blue"
        ],
        "orderBy": [
          "relevant",
          "latest"
        ]
      },
      "quota": {
        "unit": "search",
        "dailyLimit": 0,
        "used": 0,
        "remaining": null,
        "resetsAt": 1800057600000
      }
    },
    {
      "id": "video_search",
      "kind": "search",
      "label": {
        "en": "video_search",
        "zh": "video_search"
      },
      "enabled": true,
      "available": true,
      "unavailableReason": null,
      "limits": {
        "perPage": {
          "max": 80,
          "default": 20
        },
        "orientations": [
          "landscape",
          "portrait",
          "mixed"
        ]
      },
      "quota": {
        "unit": "search",
        "dailyLimit": 0,
        "used": 0,
        "remaining": null,
        "resetsAt": 1800057600000
      }
    },
    {
      "id": "audio_search",
      "kind": "search",
      "label": {
        "en": "audio_search",
        "zh": "audio_search"
      },
      "enabled": true,
      "available": true,
      "unavailableReason": null,
      "limits": {
        "perPage": {
          "max": 150,
          "default": 20
        },
        "audioTypes": [
          "music",
          "sound-effect",
          "speech",
          "ambient",
          "nature"
        ],
        "sorts": [
          "score",
          "downloads_desc",
          "rating_desc",
          "created_desc",
          "created_asc",
          "duration_asc",
          "duration_desc"
        ],
        "duration": {
          "minSeconds": 0,
          "maxSeconds": 3600
        }
      },
      "quota": {
        "unit": "search",
        "dailyLimit": 0,
        "used": 0,
        "remaining": null,
        "resetsAt": 1800057600000
      }
    }
  ]
}
```

### GET /api/v1/plan

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`


#### JSON request

GET /api/v1/plan returns the plan of the key owner (plan, period, limits, usage, exempt). Monthly requests, monthly tokens and requests per minute are counted on the two LLM endpoints only; a refused call answers 429 with plan_quota_exceeded or plan_rate_limited before any upstream is contacted. The 429 body carries error.code, plan, limit, window, resets_at (quota) or retry_after_s (per minute) and upgrade_url. A quota refusal sends x-should-retry: false (do not retry until resets_at); a per-minute refusal sends Retry-After. Read usage.resetsAt to know when the window rolls over. Administrators and system keys answer exempt=true with zero limits.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/plan"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/plan'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/plan"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/plan";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "plan": {
      "id": "advanced",
      "name": "Advanced",
      "tier": "premium"
    },
    "period": {
      "start": 1795000000000,
      "end": 1797592000000
    },
    "limits": {
      "requests": 50000,
      "tokens": 10000000,
      "rpm": 60,
      "keys": 10,
      "mediaQuotaPct": 200
    },
    "usage": {
      "windowStart": 1795000000000,
      "resetsAt": 1797592000000,
      "requests": 7420,
      "inputTokens": 812345,
      "outputTokens": 402110,
      "activeKeys": 3
    },
    "exempt": false
  }
}
```

<a id="llm-openai"></a>
## OpenAI compatible messages

Use chat/completions with a discovered public model id.

Send model and messages, with max_tokens:64 for the minimal example. Read choices[0].message.content. Success retains the upstream OpenAI response shape. Gateway errors use type=error and error.type/message. An optional OpenAI SDK uses base_url=ORIGIN + /api/v1 and max_retries=0. Do not repeat /v1 or send an internal route target id.

### POST /api/v1/chat/completions

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json | text/event-stream`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | `string` | Required | Public model id from live discovery; empty examples must be replaced. |
| `messages` | `array` | Required | Messages in the selected upstream protocol. |
| `max_tokens` | `integer` | Optional | Maximum generated tokens; example budget 64. |
| `stream` | `boolean` | Optional | Use SSE when true; handle event framing and terminal markers. (default: `false`) |

#### JSON request

Replace REPLACE_WITH_DISCOVERED_MODEL with a supported public model id.
Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/chat/completions"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "model": "REPLACE_WITH_DISCOVERED_MODEL",
  "messages": [
    {
      "role": "user",
      "content": "Hello, world"
    }
  ],
  "max_tokens": 64,
  "stream": false
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/chat/completions'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"model":"REPLACE_WITH_DISCOVERED_MODEL","messages":[{"role":"user","content":"Hello, world"}],"max_tokens":64,"stream":false}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/chat/completions"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"model\":\"REPLACE_WITH_DISCOVERED_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Hello, world\"}],\"max_tokens\":64,\"stream\":false}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/chat/completions";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"model":"REPLACE_WITH_DISCOVERED_MODEL","messages":[{"role":"user","content":"Hello, world"}],"max_tokens":64,"stream":false}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(result.choices[0].message.content);
```

**Response** (200)

```json
{
  "id": "chat-example",
  "object": "chat.completion",
  "choices": [
    {
      "index": 0,
      "message": {
        "role": "assistant",
        "content": "Hello"
      },
      "finish_reason": "stop"
    }
  ],
  "usage": {
    "prompt_tokens": 10,
    "completion_tokens": 2
  }
}
```

#### Incremental streaming

Replace REPLACE_WITH_DISCOVERED_MODEL with a supported public model id.
Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell + curl; displays raw SSE events. Check the protocol terminal marker.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
work=$(mktemp -d)
trap 'rm -f "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "model": "REPLACE_WITH_DISCOVERED_MODEL",
  "messages": [
    {
      "role": "user",
      "content": "Hello, world"
    }
  ],
  "max_tokens": 64,
  "stream": true
}
ARAGON_JSON
)
# --fail-with-body rejects HTTP errors; the final check also rejects redirects.
status=$(curl --no-buffer --silent --show-error --fail-with-body --max-time 600 \
  -X POST "$ORIGIN/api/v1/chat/completions" -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Accept: text/event-stream' \
  -H 'Content-Type: application/json; charset=utf-8' --data-binary "$payload" \
  --dump-header "$work/headers" --output /dev/stderr --write-out "%{http_code}")
[ "$status" = 200 ] || { echo "Unexpected HTTP $status" >&2; exit 1; }
grep -Ei '^content-type:[[:space:]]*text/event-stream' "$work/headers" >/dev/null || exit 1
# OpenAI: [DONE]; Anthropic: message_stop, error means failure.
# EOF without the marker means possible truncation; do not automatically resend.
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/chat/completions'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$headers['Accept'] = 'text/event-stream'
$json = '{"model":"REPLACE_WITH_DISCOVERED_MODEL","messages":[{"role":"user","content":"Hello, world"}],"max_tokens":64,"stream":true}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
Add-Type -AssemblyName System.Net.Http
$handler = New-Object System.Net.Http.HttpClientHandler
$handler.AllowAutoRedirect = $false
$client = New-Object System.Net.Http.HttpClient($handler)
$client.Timeout = [TimeSpan]::FromSeconds(600)
$request = New-Object System.Net.Http.HttpRequestMessage([Net.Http.HttpMethod]::Post, $url)
foreach ($header in $headers.GetEnumerator()) {
  [void]$request.Headers.TryAddWithoutValidation($header.Key, [string]$header.Value)
}
$request.Content = New-Object System.Net.Http.ByteArrayContent(,$body)
$request.Content.Headers.ContentType =
  [Net.Http.Headers.MediaTypeHeaderValue]::Parse("application/json; charset=utf-8")
$clock = [Diagnostics.Stopwatch]::StartNew()
$response = $null; $stream = $null; $reader = $null
try {
  $response = $client.SendAsync($request,
    [Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()
  if ([int]$response.StatusCode -ne 200) { throw ("HTTP " + [int]$response.StatusCode) }
  if ($response.Content.Headers.ContentType.MediaType -ne "text/event-stream") {
    throw "Expected text/event-stream"
  }
  $stream = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
  $reader = New-Object IO.StreamReader($stream, [Text.Encoding]::UTF8)
  $lines = New-Object Collections.Generic.List[string]
  $ended = $false
  while (-not $ended) {
    $remaining = 600000 - $clock.ElapsedMilliseconds
    if ($remaining -le 0) { throw "SSE total budget exceeded" }
    $task = $reader.ReadLineAsync()
    if (-not $task.Wait([int]$remaining)) { throw "SSE total budget exceeded" }
    $line = $task.GetAwaiter().GetResult()
    if ($null -eq $line) { break }
    if ($line -ne "") { $lines.Add($line); continue }
    $parts = @($lines | Where-Object { $_.StartsWith("data:") } |
      ForEach-Object { $_.Substring(5).TrimStart([char]32) })
    $lines.Clear(); $data = $parts -join "`n"
    if (-not $data) { continue }
    if ($data -eq "[DONE]") { $ended = $true; continue }
    $event = $data | ConvertFrom-Json
    if ($event.type -eq "error" -or $null -ne $event.error) {
      throw ($event.error | ConvertTo-Json -Depth 5)
    }
    if ($event.type -eq "message_stop") { $ended = $true; continue }
    if ($event.choices) { [Console]::Write($event.choices[0].delta.content) }
    elseif ($event.delta.text) { [Console]::Write($event.delta.text) }
  }
  if (-not $ended) { throw "Truncated SSE: no terminal marker; partial output retained" }
} finally {
  if ($reader) { $reader.Dispose() }; if ($stream) { $stream.Dispose() }
  if ($response) { $response.Dispose() }
  $request.Dispose(); $client.Dispose(); $handler.Dispose()
}
```

##### python

```python
# Python 3 + requests; save as a .py file. Preserve partial output; no retries.
import codecs, json, os, subprocess, sys, time
from urllib.parse import urlsplit
SSE_TOTAL_SECONDS = 600
# The supervising process bounds headers and body, including slow-drip responses.
if sys.argv[1:] != ["--aragon-stream-worker"]:
    worker = subprocess.Popen([sys.executable, "-u", __file__, "--aragon-stream-worker"])
    try:
        status = worker.wait(timeout=SSE_TOTAL_SECONDS)
    except subprocess.TimeoutExpired:
        worker.kill(); worker.wait()
        raise TimeoutError("SSE total budget exceeded; partial output retained; outcome unknown")
    except BaseException:
        if worker.poll() is None: worker.kill()
        worker.wait(); raise
    raise SystemExit(status)
import requests
origin = os.environ.get("ARAGON_BASE_URL")
key = os.environ.get("ARAGON_API_KEY")
if not origin or not key: raise RuntimeError("Set gateway environment")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or parsed.username or
        parsed.path or parsed.query or parsed.fragment): raise RuntimeError("Invalid origin")
headers = json.loads("{\"Accept\":\"text/event-stream\"}")
headers.update({"Authorization": "Bearer " + key,
                "Content-Type": "application/json; charset=utf-8"})
payload = json.loads("{\"model\":\"REPLACE_WITH_DISCOVERED_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Hello, world\"}],\"max_tokens\":64,\"stream\":true}")
deadline = time.monotonic() + SSE_TOTAL_SECONDS
with requests.post(origin + "/api/v1/chat/completions", headers=headers, json=payload,
                   stream=True, timeout=(30, 30), allow_redirects=False) as response:
    if response.status_code != 200: raise RuntimeError("HTTP %s: %s" %
        (response.status_code, response.text))
    if response.headers.get("Content-Type", "").split(";")[0] != "text/event-stream":
        raise RuntimeError("Expected text/event-stream")
    def read_lines():
        decoder = codecs.getincrementaldecoder("utf-8")()
        pending, after_cr = "", False
        for chunk in response.iter_content(chunk_size=1):
            if time.monotonic() >= deadline: raise TimeoutError("SSE total budget exceeded")
            for character in decoder.decode(chunk):
                if after_cr and character == "\n":
                    after_cr = False; continue
                after_cr = character == "\r"
                if character in ("\r", "\n"):
                    yield pending
                    pending = ""
                else: pending += character
        decoder.decode(b"", final=True)
    lines, ended = [], False
    try:
        for line in read_lines():
            if time.monotonic() >= deadline: raise TimeoutError("SSE total budget exceeded")
            if line:
                lines.append(line)
                continue
            data = "\n".join(item[5:].lstrip(" ") for item in lines
                             if item.startswith("data:"))
            lines = []
            if not data: continue
            if data == "[DONE]": ended = True; break
            event = json.loads(data)
            if event.get("type") == "error" or event.get("error") is not None:
                raise RuntimeError(str(event.get("error")))
            if event.get("type") == "message_stop": ended = True; break
            choices = event.get("choices", [])
            text = (choices[0].get("delta", {}).get("content", "") if choices
                    else event.get("delta", {}).get("text", ""))
            print(text, end="", flush=True)
        if not ended: raise RuntimeError("Truncated SSE: no terminal marker")
    except BaseException:
        print("\nPartial output retained; generation outcome unknown")
        raise
```

##### node

```javascript
// Node.js >=22.5; .mjs. Keep partial output on failure; never resubmit automatically.
const origin = process.env.ARAGON_BASE_URL;
if (!origin || !process.env.ARAGON_API_KEY) throw new Error("Set gateway environment");
const base = new URL(origin);
if (!["http:","https:"].includes(base.protocol) || base.origin !== origin || base.username)
  throw new Error("Expected a pure http(s) origin");
const headers = {"Accept":"text/event-stream","Content-Type":"application/json; charset=utf-8"};
headers.Authorization = "Bearer " + process.env.ARAGON_API_KEY;
const response = await fetch(origin + "/api/v1/chat/completions", {
  method: "POST", headers, redirect: "error", signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"model":"REPLACE_WITH_DISCOVERED_MODEL","messages":[{"role":"user","content":"Hello, world"}],"max_tokens":64,"stream":true}),
});
if (response.status !== 200) throw new Error("HTTP " + response.status + ": " +
  await response.text());
if ((response.headers.get("content-type") || "").split(";")[0] !== "text/event-stream")
  throw new Error("Expected text/event-stream");
const decoder = new TextDecoder("utf-8");
let pending = "", eventLines = [], ended = false, afterCr = false;
function acceptEvent(lines) {
  const data = lines.filter(line => line.startsWith("data:"))
    .map(line => line.slice(5).replace(/^ /, "")).join("\n");
  if (!data) return;
  if (data === "[DONE]") { ended = true; return; }
  const event = JSON.parse(data);
  if (event.type === "error" || event.error != null)
    throw new Error(JSON.stringify(event.error));
  if (event.type === "message_stop") { ended = true; return; }
  process.stdout.write(event.choices?.[0]?.delta?.content || event.delta?.text || "");
}
try {
  for await (const chunk of response.body) {
    for (const character of decoder.decode(chunk, { stream: true })) {
      if (afterCr && character === "\n") { afterCr = false; continue; }
      afterCr = character === "\r";
      if (character === "\r" || character === "\n") {
        if (pending === "") { acceptEvent(eventLines); eventLines = []; }
        else eventLines.push(pending);
        pending = "";
      } else pending += character;
      if (ended) break;
    }
    if (ended) break;
  }
  if (!ended) throw new Error("SSE ended without a terminal marker; output may be truncated");
} catch (error) {
  console.error("Partial output retained; generation outcome unknown"); throw error;
}
```

**Response** (200)

```text
data: {"choices":[{"delta":{"content":"Hello"}}]}

data: [DONE]
```

<a id="llm-anthropic"></a>
## Anthropic messages

Use messages with max_tokens and the native Anthropic response.

Send model, messages and max_tokens. The example sends anthropic-version: 2023-06-01; the gateway can supply its configured default when absent. Read text blocks in content. The optional Anthropic SDK uses base_url=ORIGIN + /api and max_retries=0, since the SDK appends /v1/messages. Model support follows the selected upstream protocol.

### POST /api/v1/messages

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json | text/event-stream`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `model` | `string` | Required | Public model id from live discovery; empty examples must be replaced. |
| `messages` | `array` | Required | Messages in the selected upstream protocol. |
| `max_tokens` | `integer` | Required | Maximum generated tokens; example budget 64. |
| `stream` | `boolean` | Optional | Use SSE when true; handle event framing and terminal markers. (default: `false`) |

#### JSON request

Replace REPLACE_WITH_DISCOVERED_MODEL with a supported public model id.
Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/messages"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "model": "REPLACE_WITH_DISCOVERED_MODEL",
  "messages": [
    {
      "role": "user",
      "content": "Hello, world"
    }
  ],
  "max_tokens": 64,
  "stream": false
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'anthropic-version: 2023-06-01' \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/messages'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$headers['anthropic-version'] = '2023-06-01'
$json = '{"model":"REPLACE_WITH_DISCOVERED_MODEL","messages":[{"role":"user","content":"Hello, world"}],"max_tokens":64,"stream":false}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/messages"
headers = json.loads("{\"anthropic-version\":\"2023-06-01\"}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"model\":\"REPLACE_WITH_DISCOVERED_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Hello, world\"}],\"max_tokens\":64,\"stream\":false}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/messages";
const url = new URL(path, origin);
const headers = {"anthropic-version":"2023-06-01"};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"model":"REPLACE_WITH_DISCOVERED_MODEL","messages":[{"role":"user","content":"Hello, world"}],"max_tokens":64,"stream":false}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(result.content.filter(block => block.type === "text")
  .map(block => block.text).join(""));
```

**Response** (200)

```json
{
  "id": "message-example",
  "type": "message",
  "role": "assistant",
  "content": [
    {
      "type": "text",
      "text": "Hello"
    }
  ],
  "stop_reason": "end_turn",
  "usage": {
    "input_tokens": 10,
    "output_tokens": 2
  }
}
```

#### Incremental streaming

Replace REPLACE_WITH_DISCOVERED_MODEL with a supported public model id.
Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell + curl; displays raw SSE events. Check the protocol terminal marker.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
work=$(mktemp -d)
trap 'rm -f "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "model": "REPLACE_WITH_DISCOVERED_MODEL",
  "messages": [
    {
      "role": "user",
      "content": "Hello, world"
    }
  ],
  "max_tokens": 64,
  "stream": true
}
ARAGON_JSON
)
# --fail-with-body rejects HTTP errors; the final check also rejects redirects.
status=$(curl --no-buffer --silent --show-error --fail-with-body --max-time 600 \
  -X POST "$ORIGIN/api/v1/messages" -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'anthropic-version: 2023-06-01' \
  -H 'Accept: text/event-stream' \
  -H 'Content-Type: application/json; charset=utf-8' --data-binary "$payload" \
  --dump-header "$work/headers" --output /dev/stderr --write-out "%{http_code}")
[ "$status" = 200 ] || { echo "Unexpected HTTP $status" >&2; exit 1; }
grep -Ei '^content-type:[[:space:]]*text/event-stream' "$work/headers" >/dev/null || exit 1
# OpenAI: [DONE]; Anthropic: message_stop, error means failure.
# EOF without the marker means possible truncation; do not automatically resend.
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/messages'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$headers['anthropic-version'] = '2023-06-01'
$headers['Accept'] = 'text/event-stream'
$json = '{"model":"REPLACE_WITH_DISCOVERED_MODEL","messages":[{"role":"user","content":"Hello, world"}],"max_tokens":64,"stream":true}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
Add-Type -AssemblyName System.Net.Http
$handler = New-Object System.Net.Http.HttpClientHandler
$handler.AllowAutoRedirect = $false
$client = New-Object System.Net.Http.HttpClient($handler)
$client.Timeout = [TimeSpan]::FromSeconds(600)
$request = New-Object System.Net.Http.HttpRequestMessage([Net.Http.HttpMethod]::Post, $url)
foreach ($header in $headers.GetEnumerator()) {
  [void]$request.Headers.TryAddWithoutValidation($header.Key, [string]$header.Value)
}
$request.Content = New-Object System.Net.Http.ByteArrayContent(,$body)
$request.Content.Headers.ContentType =
  [Net.Http.Headers.MediaTypeHeaderValue]::Parse("application/json; charset=utf-8")
$clock = [Diagnostics.Stopwatch]::StartNew()
$response = $null; $stream = $null; $reader = $null
try {
  $response = $client.SendAsync($request,
    [Net.Http.HttpCompletionOption]::ResponseHeadersRead).GetAwaiter().GetResult()
  if ([int]$response.StatusCode -ne 200) { throw ("HTTP " + [int]$response.StatusCode) }
  if ($response.Content.Headers.ContentType.MediaType -ne "text/event-stream") {
    throw "Expected text/event-stream"
  }
  $stream = $response.Content.ReadAsStreamAsync().GetAwaiter().GetResult()
  $reader = New-Object IO.StreamReader($stream, [Text.Encoding]::UTF8)
  $lines = New-Object Collections.Generic.List[string]
  $ended = $false
  while (-not $ended) {
    $remaining = 600000 - $clock.ElapsedMilliseconds
    if ($remaining -le 0) { throw "SSE total budget exceeded" }
    $task = $reader.ReadLineAsync()
    if (-not $task.Wait([int]$remaining)) { throw "SSE total budget exceeded" }
    $line = $task.GetAwaiter().GetResult()
    if ($null -eq $line) { break }
    if ($line -ne "") { $lines.Add($line); continue }
    $parts = @($lines | Where-Object { $_.StartsWith("data:") } |
      ForEach-Object { $_.Substring(5).TrimStart([char]32) })
    $lines.Clear(); $data = $parts -join "`n"
    if (-not $data) { continue }
    if ($data -eq "[DONE]") { $ended = $true; continue }
    $event = $data | ConvertFrom-Json
    if ($event.type -eq "error" -or $null -ne $event.error) {
      throw ($event.error | ConvertTo-Json -Depth 5)
    }
    if ($event.type -eq "message_stop") { $ended = $true; continue }
    if ($event.choices) { [Console]::Write($event.choices[0].delta.content) }
    elseif ($event.delta.text) { [Console]::Write($event.delta.text) }
  }
  if (-not $ended) { throw "Truncated SSE: no terminal marker; partial output retained" }
} finally {
  if ($reader) { $reader.Dispose() }; if ($stream) { $stream.Dispose() }
  if ($response) { $response.Dispose() }
  $request.Dispose(); $client.Dispose(); $handler.Dispose()
}
```

##### python

```python
# Python 3 + requests; save as a .py file. Preserve partial output; no retries.
import codecs, json, os, subprocess, sys, time
from urllib.parse import urlsplit
SSE_TOTAL_SECONDS = 600
# The supervising process bounds headers and body, including slow-drip responses.
if sys.argv[1:] != ["--aragon-stream-worker"]:
    worker = subprocess.Popen([sys.executable, "-u", __file__, "--aragon-stream-worker"])
    try:
        status = worker.wait(timeout=SSE_TOTAL_SECONDS)
    except subprocess.TimeoutExpired:
        worker.kill(); worker.wait()
        raise TimeoutError("SSE total budget exceeded; partial output retained; outcome unknown")
    except BaseException:
        if worker.poll() is None: worker.kill()
        worker.wait(); raise
    raise SystemExit(status)
import requests
origin = os.environ.get("ARAGON_BASE_URL")
key = os.environ.get("ARAGON_API_KEY")
if not origin or not key: raise RuntimeError("Set gateway environment")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or parsed.username or
        parsed.path or parsed.query or parsed.fragment): raise RuntimeError("Invalid origin")
headers = json.loads("{\"anthropic-version\":\"2023-06-01\",\"Accept\":\"text/event-stream\"}")
headers.update({"Authorization": "Bearer " + key,
                "Content-Type": "application/json; charset=utf-8"})
payload = json.loads("{\"model\":\"REPLACE_WITH_DISCOVERED_MODEL\",\"messages\":[{\"role\":\"user\",\"content\":\"Hello, world\"}],\"max_tokens\":64,\"stream\":true}")
deadline = time.monotonic() + SSE_TOTAL_SECONDS
with requests.post(origin + "/api/v1/messages", headers=headers, json=payload,
                   stream=True, timeout=(30, 30), allow_redirects=False) as response:
    if response.status_code != 200: raise RuntimeError("HTTP %s: %s" %
        (response.status_code, response.text))
    if response.headers.get("Content-Type", "").split(";")[0] != "text/event-stream":
        raise RuntimeError("Expected text/event-stream")
    def read_lines():
        decoder = codecs.getincrementaldecoder("utf-8")()
        pending, after_cr = "", False
        for chunk in response.iter_content(chunk_size=1):
            if time.monotonic() >= deadline: raise TimeoutError("SSE total budget exceeded")
            for character in decoder.decode(chunk):
                if after_cr and character == "\n":
                    after_cr = False; continue
                after_cr = character == "\r"
                if character in ("\r", "\n"):
                    yield pending
                    pending = ""
                else: pending += character
        decoder.decode(b"", final=True)
    lines, ended = [], False
    try:
        for line in read_lines():
            if time.monotonic() >= deadline: raise TimeoutError("SSE total budget exceeded")
            if line:
                lines.append(line)
                continue
            data = "\n".join(item[5:].lstrip(" ") for item in lines
                             if item.startswith("data:"))
            lines = []
            if not data: continue
            if data == "[DONE]": ended = True; break
            event = json.loads(data)
            if event.get("type") == "error" or event.get("error") is not None:
                raise RuntimeError(str(event.get("error")))
            if event.get("type") == "message_stop": ended = True; break
            choices = event.get("choices", [])
            text = (choices[0].get("delta", {}).get("content", "") if choices
                    else event.get("delta", {}).get("text", ""))
            print(text, end="", flush=True)
        if not ended: raise RuntimeError("Truncated SSE: no terminal marker")
    except BaseException:
        print("\nPartial output retained; generation outcome unknown")
        raise
```

##### node

```javascript
// Node.js >=22.5; .mjs. Keep partial output on failure; never resubmit automatically.
const origin = process.env.ARAGON_BASE_URL;
if (!origin || !process.env.ARAGON_API_KEY) throw new Error("Set gateway environment");
const base = new URL(origin);
if (!["http:","https:"].includes(base.protocol) || base.origin !== origin || base.username)
  throw new Error("Expected a pure http(s) origin");
const headers = {"anthropic-version":"2023-06-01","Accept":"text/event-stream","Content-Type":"application/json; charset=utf-8"};
headers.Authorization = "Bearer " + process.env.ARAGON_API_KEY;
const response = await fetch(origin + "/api/v1/messages", {
  method: "POST", headers, redirect: "error", signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"model":"REPLACE_WITH_DISCOVERED_MODEL","messages":[{"role":"user","content":"Hello, world"}],"max_tokens":64,"stream":true}),
});
if (response.status !== 200) throw new Error("HTTP " + response.status + ": " +
  await response.text());
if ((response.headers.get("content-type") || "").split(";")[0] !== "text/event-stream")
  throw new Error("Expected text/event-stream");
const decoder = new TextDecoder("utf-8");
let pending = "", eventLines = [], ended = false, afterCr = false;
function acceptEvent(lines) {
  const data = lines.filter(line => line.startsWith("data:"))
    .map(line => line.slice(5).replace(/^ /, "")).join("\n");
  if (!data) return;
  if (data === "[DONE]") { ended = true; return; }
  const event = JSON.parse(data);
  if (event.type === "error" || event.error != null)
    throw new Error(JSON.stringify(event.error));
  if (event.type === "message_stop") { ended = true; return; }
  process.stdout.write(event.choices?.[0]?.delta?.content || event.delta?.text || "");
}
try {
  for await (const chunk of response.body) {
    for (const character of decoder.decode(chunk, { stream: true })) {
      if (afterCr && character === "\n") { afterCr = false; continue; }
      afterCr = character === "\r";
      if (character === "\r" || character === "\n") {
        if (pending === "") { acceptEvent(eventLines); eventLines = []; }
        else eventLines.push(pending);
        pending = "";
      } else pending += character;
      if (ended) break;
    }
    if (ended) break;
  }
  if (!ended) throw new Error("SSE ended without a terminal marker; output may be truncated");
} catch (error) {
  console.error("Partial output retained; generation outcome unknown"); throw error;
}
```

**Response** (200)

```text
event: content_block_delta
data: {"type":"content_block_delta","delta":{"type":"text_delta","text":"Hello"}}

event: message_stop
data: {"type":"message_stop"}
```

<a id="llm-agent"></a>
## Agent augmentation

Models that carry reflection, genes and memory from the router.

For models an administrator has switched on, the router appends a short advisory block to the end of your last user message: notes you saved, relevant experience and, in long tasks, a second opinion from a fast reviewer. Your request is otherwise unchanged and the response is never rewritten. Send x-aragon-agent: off to skip it for one request, and x-aragon-conversation to separate conversations that start with the same text. An administrator may also publish organization guidance, read-only notes such as house style or terminology, which ride in the same block when they apply to your model and plan; the same header opts out, and text that must always apply belongs in the route system prompt instead.

When a request was augmented, the response carries x-aragon-agent with counts only, for example "reflection; guidance=1; gene=2; memory=3" (guidance counts organization guidance). GET /api/v1/agent reports what would apply to your key. After a preflight wait the value ends with "; wait=<ms>".

By default the reviewer runs after your response and its advice reaches the next request, so latency is unchanged. An administrator may instead choose preflight: only on a request that ends with a tool result, the router waits for the reviewer up to a limit the administrator sets, then forwards the request either way. When it waited, the header ends with "; wait=<ms>", for example "reflection; gene=2; wait=1840", and the request log duration includes that wait. GET /api/v1/agent shows reflectionMode per model ("after" or "preflight").

In a chat message, start a line with #remember followed by the text and the router saves it to your memory and has the model confirm in one sentence. Text that looks like a secret is refused and not saved.

No x-aragon-agent header usually means one of: the model is not switched on for your tier, your master switch is off, an administrator disabled the layer for you, the daily fast-model allowance is used up, the conversation has no user message to attach to, or the fast model is temporarily unavailable. Send x-aragon-agent: off to see whether the augmentation caused a problem. If an augmented request is answered with HTTP 400, ask the administrator to run the compatibility check for that model; the router never retries a request without the augmentation.

### GET /api/v1/agent

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`


#### JSON request

When a request was augmented, the response carries x-aragon-agent with counts only, for example "reflection; guidance=1; gene=2; memory=3" (guidance counts organization guidance). GET /api/v1/agent reports what would apply to your key. After a preflight wait the value ends with "; wait=<ms>".

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/agent"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/agent'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/agent"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/agent";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "layer": "on",
    "enabled": true,
    "subject": true,
    "user": {
      "enabled": true,
      "reflection": true,
      "geneUse": true,
      "memoryUse": true,
      "geneLearning": "suggest",
      "memoryLearning": "suggest"
    },
    "models": [
      {
        "id": "public-model-id",
        "reflection": true,
        "gene": true,
        "memory": true,
        "reflectionMode": "after"
      }
    ],
    "counts": {
      "genes": 12,
      "memories": 37,
      "inbox": 3
    },
    "capability": {
      "enabled": true,
      "active": true,
      "sources": {
        "lexicon": true,
        "reflection": true,
        "gap": true
      },
      "pass": true
    }
  }
}
```

<a id="capability-hints"></a>
## Capability hints

Your Agent learns about image, video, speech and stock-media generation from the router, with nothing installed.

When an administrator switches capability hints on and your request clearly asks for an image, a video, a voice-over or stock media, the router appends a short block to your last user message that names the matching AragonRouter capability, the one HTTP call that uses it and how to fetch the result. Most requests get nothing, so the extra context is zero. The block never changes your instructions or tool permissions; when task triage is on (below) it is worded as a directive about the task instead of optional documentation. A client that cannot send an HTTP POST receives one sentence that points to the Studio page instead. If an AragonRouter Skill is already installed, it keeps priority.

The block carries a capability pass: arp1.… in the Authorization bearer header, valid for about 20 minutes, for the capabilities named in the block only, and only for the generation, search, ingest, job-read and asset-read endpoints. It reads and writes only what its own key produced and cannot call the LLM endpoints, delete assets or cancel jobs. It may appear in the logs of your model provider, like the rest of the request.

Send x-aragon-capabilities: off to skip the block for one request (x-aragon-agent: off skips every augmentation). Members can switch it off under Agent settings; it needs reflection to be on. The response header x-aragon-agent adds capability=<n> when a block was attached.

Task triage: when a new task arrives from a client that can run shell commands or scripts, the router can ask the fast model about it in the same request, so a need the keyword list cannot see (for example a landing page that needs a hero image) is attached to that very request. The router waits for the fast model for a bounded time (waitMs, 2.5 s by default); if the keyword list already matched, triage runs in the background and its answer rides the next request. The response header x-aragon-agent then carries a triage=<outcome> segment with one of five words: hit, none, timeout, late or detached. While the Agent has not called the capability yet, short reminder blocks repeat the call shape (at most 5 reminders over 12 requests) because the block is not part of your client history. Each triaged task costs one fast-model call and sends the task text to the fast-model provider; text that looks like a secret is skipped. The router has not verified that real clients follow the block.

When a task reaches the router from a client with a shell or script tool, and nothing more specific speaks for that task, the router attaches one short deterministic menu (under 320 characters, at most once per task) naming the capabilities this key may use today, one HTTP path each. It needs no fast model, causes no wait and carries no capability pass: use the same API key as this LLM connection, or read GET /api/v1/capabilities for the shapes. It is background knowledge, so it says only "use one if the task needs it". A deployment can switch it off, and then every request is byte-for-byte what it was before this block existed.

When a capability call fails, the router answers the next request of that task with the smallest block that changes what the Agent does next, chosen from the error code in the tool result: a fresh pass when the old one expired, the request fields once per task when the body was malformed, one "wait or tell the user" line plus a few quiet requests when the call was rate limited or out of quota, one "retry it now, it was free" line when the error body says retryable: true (the request never reached the upstream), or a final sentence with the Studio as the way out when this key can never make that call. The codes a failed job reports (job.error.code, for example submission_unknown) are classified the same way, and the capability they belong to is read from the job body itself. The response header x-aragon-agent does not change shape; the block is bounded per task and never repeats itself. The router has not verified that real clients surface the error body it reads.

The call line follows the shell the client exposes. With only PowerShell available it reads: use curl.exe (not the curl alias) or Invoke-RestMethod, write the JSON body to a file and send it with --data-binary "@file.json". x-aragon-capabilities: off still switches off everything described here, triage and reminders included.

### GET /api/v1/capabilities/{id}/guide

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `text/markdown`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `path string` | Required | Capability id: ai_image, ai_video, tts, image_search, video_search or audio_search. |
| `lang` | `string` | Optional | Language of the headings, en or zh-CN. (default: `en`) |
| `shell` | `string` | Optional | Shell the example command is written for: posix or powershell. (default: `posix`) |

#### Download bytes

GET /api/v1/capabilities/{id}/guide returns the full guide of one capability as Markdown (at most 6 KB), including your own limits and quota. The block links to it; nothing fetches it for you.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_CAPABILITY_ID:?Set ARAGON_CAPABILITY_ID}"
case "$ARAGON_CAPABILITY_ID" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_CAPABILITY_ID" | jq -sRr @uri)
path='/api/v1/capabilities//guide'
url="$ORIGIN/api/v1/capabilities/$resource_id/guide"
work=$(mktemp -d "./.aragon-download.XXXXXXXX")
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in text/markdown) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
mv "$work/body" 'aragon-asset.bin'
printf '%s\n' 'aragon-asset.bin'
# Normal EOF cannot prove semantic audio completeness.
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_CAPABILITY_ID
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/capabilities/{id}/guide'.Replace("{id}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$target = Join-Path (Get-Location).Path 'aragon-asset.bin'
$temporary = $target + "." + [Guid]::NewGuid().ToString("N") + ".partial"
try {
  $parameters.OutFile = $temporary
  $parameters.PassThru = $true
  $response = Invoke-WebRequest @parameters
  if ([int]$response.StatusCode -notin @(200)) {
    throw ("Unexpected HTTP " + $response.StatusCode)
  }
  $mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
  if ($mime -notin @('text/markdown')) { throw ("Unexpected Content-Type: " + $mime) }
  Move-Item -LiteralPath $temporary -Destination $target -Force
  Write-Output $target
} finally {
  if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary }
}
# Normal EOF cannot prove semantic audio completeness.
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_CAPABILITY_ID")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/capabilities/{id}/guide".replace("{id}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["text/markdown"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    target = Path("aragon-asset.bin")
    fd, name = tempfile.mkstemp(prefix=".aragon-", dir=target.parent)
    temporary = Path(name)
    try:
        with os.fdopen(fd, "wb") as output:
            for chunk in response.iter_content(65536): output.write(chunk)
        temporary.replace(target)
        print(target)
    except BaseException:
        temporary.unlink(missing_ok=True)
        raise
    # Normal EOF cannot prove semantic audio completeness.
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_CAPABILITY_ID;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_CAPABILITY_ID to the resource id");
const path = "/api/v1/capabilities/{id}/guide".replace("{id}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["text/markdown"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const { open, rename, unlink } = await import("node:fs/promises");
const { randomUUID } = await import("node:crypto");
const target = "aragon-asset.bin";
const temporary = target + "." + randomUUID() + ".partial";
const file = await open(temporary, "wx");
try {
  if (!response.body) throw new Error("Missing response body");
  for await (const chunk of response.body) await file.writeFile(chunk);
  await file.close();
  await rename(temporary, target);
  console.log(target);
} catch (error) {
  await file.close();
  await unlink(temporary);
  throw new Error("Incomplete output; existing target preserved", { cause: error });
}
// Normal EOF does not prove semantic audio completeness.
```

**Response** (200)

`binary`

Related operations: [Discover models and capabilities](#discovery)

<a id="llm-streaming"></a>
## Streaming responses

Handle complete SSE events and detect truncated generations.

Set stream:true and Accept:text/event-stream. SSE events end at blank lines, not at network chunk boundaries; data may span multiple lines and UTF-8 characters may span chunks. OpenAI ends with [DONE]; Anthropic ends with message_stop, while error is a failure. EOF before a terminal marker means a possibly truncated generation. Preserve received text and do not automatically resubmit. curl displays raw events; Python requires requests and Node.js requires 22.5 or later with an .mjs file.

Related operations: [OpenAI compatible messages](#llm-openai), [Anthropic messages](#llm-anthropic)

<a id="skills"></a>
## Platform skills

Short instructions the router delivers with your own requests, with nothing installed.

GET /api/v1/skills lists the skills a key may receive: the platform library plus the key owner's own published skills, filtered by plan, by model and by enabled. Each entry carries slug, name, description, when, tags, version, scope and units, where units is the cost of the full card so a client can decide whether to expand it. GET /api/v1/skills/{slug} returns one skill as text/markdown, with an ETag and a private one-minute cache; sending If-None-Match answers 304. Neither call spends quota, and a slug that belongs to someone else answers exactly like one that does not exist.

Two request headers tune the delivery of one call. x-aragon-skills: off skips skills for that request only - it lowers, it never raises. x-aragon-skills: slug-a,slug-b promotes up to three skills for that request; promotion changes order only, so every gate (enabled, status, scope, plan, model, the card ceiling and the budget) still applies, and an unknown slug is ignored silently.

When skills rode along, the response header x-aragon-agent gains a skill=<n> segment with the number of cards placed; the segments that were already there keep their meaning and their order. The request log stores the same placement in agent_applied as an s<n> run. GET /api/v1/agent reports what would apply to this key before you send anything.

### GET /api/v1/skills

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`


#### JSON request

GET /api/v1/skills lists the skills a key may receive: the platform library plus the key owner's own published skills, filtered by plan, by model and by enabled. Each entry carries slug, name, description, when, tags, version, scope and units, where units is the cost of the full card so a client can decide whether to expand it. GET /api/v1/skills/{slug} returns one skill as text/markdown, with an ETag and a private one-minute cache; sending If-None-Match answers 304. Neither call spends quota, and a slug that belongs to someone else answers exactly like one that does not exist.
Two request headers tune the delivery of one call. x-aragon-skills: off skips skills for that request only - it lowers, it never raises. x-aragon-skills: slug-a,slug-b promotes up to three skills for that request; promotion changes order only, so every gate (enabled, status, scope, plan, model, the card ceiling and the budget) still applies, and an unknown slug is ignored silently.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/skills"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/skills'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/skills"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/skills";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "object": "list",
  "has_more": false,
  "data": [
    {
      "slug": "report-weekly",
      "name": "Weekly report",
      "description": "Writes the weekly report from the template",
      "when": "the user asks for the weekly report",
      "tags": [
        "writing"
      ],
      "version": 3,
      "scope": "platform",
      "units": 412
    }
  ]
}
```

### GET /api/v1/skills/{slug}

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200 / 304

**Response**: `text/markdown`


#### Download bytes

GET /api/v1/skills lists the skills a key may receive: the platform library plus the key owner's own published skills, filtered by plan, by model and by enabled. Each entry carries slug, name, description, when, tags, version, scope and units, where units is the cost of the full card so a client can decide whether to expand it. GET /api/v1/skills/{slug} returns one skill as text/markdown, with an ETag and a private one-minute cache; sending If-None-Match answers 304. Neither call spends quota, and a slug that belongs to someone else answers exactly like one that does not exist.
When skills rode along, the response header x-aragon-agent gains a skill=<n> segment with the number of cards placed; the segments that were already there keep their meaning and their order. The request log stores the same placement in agent_applied as an s<n> run. GET /api/v1/agent reports what would apply to this key before you send anything.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_SKILL_SLUG:?Set ARAGON_SKILL_SLUG}"
case "$ARAGON_SKILL_SLUG" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_SKILL_SLUG" | jq -sRr @uri)
path='/api/v1/skills/'
url="$ORIGIN/api/v1/skills/$resource_id"
work=$(mktemp -d "./.aragon-download.XXXXXXXX")
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'If-None-Match: "0123456789abcdef"' \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in text/markdown) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
mv "$work/body" 'aragon-asset.bin'
printf '%s\n' 'aragon-asset.bin'
# Normal EOF cannot prove semantic audio completeness.
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_SKILL_SLUG
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/skills/{slug}'.Replace("{slug}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$headers['If-None-Match'] = '"0123456789abcdef"'
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$target = Join-Path (Get-Location).Path 'aragon-asset.bin'
$temporary = $target + "." + [Guid]::NewGuid().ToString("N") + ".partial"
try {
  $parameters.OutFile = $temporary
  $parameters.PassThru = $true
  $response = Invoke-WebRequest @parameters
  if ([int]$response.StatusCode -notin @(200)) {
    throw ("Unexpected HTTP " + $response.StatusCode)
  }
  $mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
  if ($mime -notin @('text/markdown')) { throw ("Unexpected Content-Type: " + $mime) }
  Move-Item -LiteralPath $temporary -Destination $target -Force
  Write-Output $target
} finally {
  if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary }
}
# Normal EOF cannot prove semantic audio completeness.
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_SKILL_SLUG")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/skills/{slug}".replace("{slug}", quote(resource_id, safe=""))
headers = json.loads("{\"If-None-Match\":\"\\\"0123456789abcdef\\\"\"}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["text/markdown"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    target = Path("aragon-asset.bin")
    fd, name = tempfile.mkstemp(prefix=".aragon-", dir=target.parent)
    temporary = Path(name)
    try:
        with os.fdopen(fd, "wb") as output:
            for chunk in response.iter_content(65536): output.write(chunk)
        temporary.replace(target)
        print(target)
    except BaseException:
        temporary.unlink(missing_ok=True)
        raise
    # Normal EOF cannot prove semantic audio completeness.
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_SKILL_SLUG;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_SKILL_SLUG to the resource id");
const path = "/api/v1/skills/{slug}".replace("{slug}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {"If-None-Match":"\"0123456789abcdef\""};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["text/markdown"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const { open, rename, unlink } = await import("node:fs/promises");
const { randomUUID } = await import("node:crypto");
const target = "aragon-asset.bin";
const temporary = target + "." + randomUUID() + ".partial";
const file = await open(temporary, "wx");
try {
  if (!response.body) throw new Error("Missing response body");
  for await (const chunk of response.body) await file.writeFile(chunk);
  await file.close();
  await rename(temporary, target);
  console.log(target);
} catch (error) {
  await file.close();
  await unlink(temporary);
  throw new Error("Incomplete output; existing target preserved", { cause: error });
}
// Normal EOF does not prove semantic audio completeness.
```

**Response** (200)

`binary`

### POST /api/v1/skills/{slug}/feedback

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `slug` | `path string` | Required | The slug of a skill this key can read. |
| `verdict` | `string` | Required | One of helped, misleading, not_applicable or outdated. not_applicable means the card was irrelevant to the task (a retrieval problem), not that the content is wrong. |
| `note` | `string` | Optional | An optional short note, at most 200 characters. |

#### JSON request

POST /api/v1/skills/{slug}/feedback records one verdict about a card that was delivered: helped, misleading, not_applicable or outdated, with an optional note of up to 200 characters. It answers counts only - helped, misleading, flagged, pinCleared - never the skill itself. Three verdicts per skill per key per day; the fourth answers 409 SKILL_LIMIT_REACHED. A verdict never switches a skill off: at most it flags it for review, which costs its pin slot and nothing else. A slug that belongs to somebody else answers the same 404 as one that does not exist.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_SKILL_SLUG:?Set ARAGON_SKILL_SLUG}"
case "$ARAGON_SKILL_SLUG" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_SKILL_SLUG" | jq -sRr @uri)
path='/api/v1/skills//feedback'
url="$ORIGIN/api/v1/skills/$resource_id/feedback"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "verdict": "helped",
  "note": "the template saved a rewrite"
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_SKILL_SLUG
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/skills/{slug}/feedback'.Replace("{slug}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"verdict":"helped","note":"the template saved a rewrite"}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_SKILL_SLUG")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/skills/{slug}/feedback".replace("{slug}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"verdict\":\"helped\",\"note\":\"the template saved a rewrite\"}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_SKILL_SLUG;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_SKILL_SLUG to the resource id");
const path = "/api/v1/skills/{slug}/feedback".replace("{slug}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"verdict":"helped","note":"the template saved a rewrite"}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "helped": 4,
    "misleading": 0,
    "flagged": false,
    "pinCleared": false
  }
}
```

Related operations: [Agent augmentation](#llm-agent)

<a id="graphs"></a>
## Workflow runs

Read which workflows a key may use, then read and drive one run of it.

GET /api/v1/graphs lists the workflows this key can hit right now: the name, the status, how it triggers and the id of its last run. It never returns the workflow body - that arrives compiled into the envelope the gateway attaches to your own requests - and it never lists another account's workflows. GET /api/v1/graphs/runs/{runId} answers where a run is: the current step, its goal, the sentence that completes it, how many steps are done, and the two or three paths that leave it. Both calls spend no quota.

POST /api/v1/graphs/runs/{runId}/events with an outcome of ok, blocked or skipped reports that a step is finished; only ok advances the run, because the gateway cannot guess which path a blocked step should have taken. Reporting the same (runId, step, outcome) again answers 200 without advancing twice, so a retried call is always safe. POST /api/v1/graphs/runs/{runId}/abandon gives up explicitly. A run that is already finished answers 409 GRAPH_RUN_FINISHED.

### GET /api/v1/graphs

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`


#### JSON request

GET /api/v1/graphs lists the workflows this key can hit right now: the name, the status, how it triggers and the id of its last run. It never returns the workflow body - that arrives compiled into the envelope the gateway attaches to your own requests - and it never lists another account's workflows. GET /api/v1/graphs/runs/{runId} answers where a run is: the current step, its goal, the sentence that completes it, how many steps are done, and the two or three paths that leave it. Both calls spend no quota.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/graphs"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/graphs'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/graphs"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/graphs";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "object": "list",
  "data": [
    {
      "id": "gw_3f9c1b2a4d",
      "name": "Review before publishing",
      "status": "published",
      "triggers": {
        "mode": "deterministic"
      },
      "lastRun": {
        "id": "r_8a1d2f4c",
        "status": "active",
        "updatedAt": 1800000010000
      }
    }
  ]
}
```

### GET /api/v1/graphs/runs/{runId}

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `runId` | `path string` | Required | The run id from the workflow list or from the attached envelope. |

#### JSON request

GET /api/v1/graphs lists the workflows this key can hit right now: the name, the status, how it triggers and the id of its last run. It never returns the workflow body - that arrives compiled into the envelope the gateway attaches to your own requests - and it never lists another account's workflows. GET /api/v1/graphs/runs/{runId} answers where a run is: the current step, its goal, the sentence that completes it, how many steps are done, and the two or three paths that leave it. Both calls spend no quota.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_RUN_ID:?Set ARAGON_RUN_ID}"
case "$ARAGON_RUN_ID" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_RUN_ID" | jq -sRr @uri)
path='/api/v1/graphs/runs/'
url="$ORIGIN/api/v1/graphs/runs/$resource_id"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_RUN_ID
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/graphs/runs/{runId}'.Replace("{runId}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_RUN_ID")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/graphs/runs/{runId}".replace("{runId}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_RUN_ID;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_RUN_ID to the resource id");
const path = "/api/v1/graphs/runs/{runId}".replace("{runId}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "runId": "r_8a1d2f4c",
    "workflowId": "gw_3f9c1b2a4d",
    "status": "active",
    "currentNode": {
      "id": "n_5b1e0a7c",
      "title": "Check every factual claim",
      "purpose": "Verify the claims and cite a source for each",
      "doneWhen": "Every claim has a source; unverified ones are marked"
    },
    "stepsDone": 2,
    "next": [
      {
        "edgeId": "e_11a2b3c4",
        "label": "passed",
        "toTitle": "Summarise the list"
      },
      {
        "edgeId": "e_22d4e5f6",
        "label": "blocked",
        "toTitle": "Ask the author"
      }
    ]
  }
}
```

### POST /api/v1/graphs/runs/{runId}/events

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `runId` | `path string` | Required | The run id from the workflow list or from the attached envelope. |
| `outcome` | `string` | Required | One of ok, blocked or skipped. ok advances the run by one step; the other two are recorded and leave the run where it is. |
| `note` | `string` | Optional | An optional sentence the platform may use to judge the step. |

#### JSON request

POST /api/v1/graphs/runs/{runId}/events with an outcome of ok, blocked or skipped reports that a step is finished; only ok advances the run, because the gateway cannot guess which path a blocked step should have taken. Reporting the same (runId, step, outcome) again answers 200 without advancing twice, so a retried call is always safe. POST /api/v1/graphs/runs/{runId}/abandon gives up explicitly. A run that is already finished answers 409 GRAPH_RUN_FINISHED.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_RUN_ID:?Set ARAGON_RUN_ID}"
case "$ARAGON_RUN_ID" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_RUN_ID" | jq -sRr @uri)
path='/api/v1/graphs/runs//events'
url="$ORIGIN/api/v1/graphs/runs/$resource_id/events"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "outcome": "ok",
  "note": "each claim now carries a source"
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_RUN_ID
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/graphs/runs/{runId}/events'.Replace("{runId}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"outcome":"ok","note":"each claim now carries a source"}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_RUN_ID")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/graphs/runs/{runId}/events".replace("{runId}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"outcome\":\"ok\",\"note\":\"each claim now carries a source\"}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_RUN_ID;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_RUN_ID to the resource id");
const path = "/api/v1/graphs/runs/{runId}/events".replace("{runId}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"outcome":"ok","note":"each claim now carries a source"}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "runId": "r_8a1d2f4c",
    "workflowId": "gw_3f9c1b2a4d",
    "status": "active",
    "currentNode": {
      "id": "n_7c2f9d31",
      "title": "Summarise the list",
      "purpose": "",
      "doneWhen": ""
    },
    "stepsDone": 3,
    "next": []
  },
  "advanced": true
}
```

### POST /api/v1/graphs/runs/{runId}/abandon

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `runId` | `path string` | Required | The run id from the workflow list or from the attached envelope. |

#### JSON request

POST /api/v1/graphs/runs/{runId}/events with an outcome of ok, blocked or skipped reports that a step is finished; only ok advances the run, because the gateway cannot guess which path a blocked step should have taken. Reporting the same (runId, step, outcome) again answers 200 without advancing twice, so a retried call is always safe. POST /api/v1/graphs/runs/{runId}/abandon gives up explicitly. A run that is already finished answers 409 GRAPH_RUN_FINISHED.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_RUN_ID:?Set ARAGON_RUN_ID}"
case "$ARAGON_RUN_ID" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_RUN_ID" | jq -sRr @uri)
path='/api/v1/graphs/runs//abandon'
url="$ORIGIN/api/v1/graphs/runs/$resource_id/abandon"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_RUN_ID
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/graphs/runs/{runId}/abandon'.Replace("{runId}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_RUN_ID")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/graphs/runs/{runId}/abandon".replace("{runId}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_RUN_ID;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_RUN_ID to the resource id");
const path = "/api/v1/graphs/runs/{runId}/abandon".replace("{runId}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "runId": "r_8a1d2f4c",
    "status": "abandoned",
    "endReason": "user"
  }
}
```

Related operations: [Agent augmentation](#llm-agent)

<a id="ai-image"></a>
## Generate images

Generate one or more images and handle partial success safely.

prompt is required, with a factory maximum of 2000 characters. count defaults to 1 and ranges from 1 to 4. size comes from limits.sizes, factory default 2048x2048; model must be configured and serviceable. watermark defaults to true. referenceImage accepts one HTTPS URL, image data URI or owned gateway asset path, subject to SSRF, ownership and size checks. Use count and referenceImage rather than upstream n or image fields.

HTTP 200 contains data.assets, failed, optional errors, model and latencyMs. A partial result is still 200: use completed assets and never resend the entire batch merely because failed is positive. Quota is reserved by count and refunded only for failures the server determines refundable. Disconnects, submission_unknown, and storage failures after delivery may remain billed; neither assets.length nor failed proves the final debit. Check authenticated quota after uncertainty.

### POST /api/v1/media/images/generations

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `prompt` | `string` | Required | Nonempty prompt; factory maximum 2000 characters. |
| `count` | `integer` | Optional | Integer 1–4. Quota is initially reserved by count. (default: `1`) |
| `size` | `string` | Optional | Choose a size from live limits.sizes. — `ai_image.limits.sizes` |
| `model` | `string` | Optional | Public model id from live discovery; empty examples must be replaced. — `ai_image.limits.models` |
| `watermark` | `boolean` | Optional | Whether the selected model applies a watermark. (default: `true`) |
| `referenceImage` | `string` | Optional | One HTTPS URL, image data URI or owned gateway asset. |

#### JSON request

Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/images/generations"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "prompt": "A red apple on a white table",
  "count": 1
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/images/generations'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"prompt":"A red apple on a white table","count":1}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/images/generations"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"prompt\":\"A red apple on a white table\",\"count\":1}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/images/generations";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"prompt":"A red apple on a white table","count":1}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "assets": [
      {
        "id": "asset-example",
        "kind": "image",
        "mime": "image/png",
        "bytes": 1024,
        "width": 2048,
        "height": 2048,
        "durationMs": null,
        "url": "/api/v1/media/assets/asset-example",
        "title": null,
        "origin": "generated",
        "createdAt": 1800000000000,
        "expiresAt": null,
        "attribution": null
      }
    ],
    "failed": 0,
    "model": "public-image-model",
    "latencyMs": 1000
  }
}
```

#### Partial image result

HTTP 200 contains data.assets, failed, optional errors, model and latencyMs. A partial result is still 200: use completed assets and never resend the entire batch merely because failed is positive. Quota is reserved by count and refunded only for failures the server determines refundable. Disconnects, submission_unknown, and storage failures after delivery may remain billed; neither assets.length nor failed proves the final debit. Check authenticated quota after uncertainty.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/images/generations"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "prompt": "A red apple on a white table",
  "count": 2
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/images/generations'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"prompt":"A red apple on a white table","count":2}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/images/generations"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"prompt\":\"A red apple on a white table\",\"count\":2}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/images/generations";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"prompt":"A red apple on a white table","count":2}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "assets": [
      {
        "id": "asset-example",
        "kind": "image",
        "mime": "image/png",
        "bytes": 1024,
        "width": 2048,
        "height": 2048,
        "durationMs": null,
        "url": "/api/v1/media/assets/asset-example",
        "title": null,
        "origin": "generated",
        "createdAt": 1800000000000,
        "expiresAt": null,
        "attribution": null
      }
    ],
    "failed": 1,
    "errors": [
      {
        "code": "upstream_unavailable",
        "message": "One image failed"
      }
    ],
    "model": "public-image-model",
    "latencyMs": 1000
  }
}
```

#### Possibly billed image failure

HTTP 200 contains data.assets, failed, optional errors, model and latencyMs. A partial result is still 200: use completed assets and never resend the entire batch merely because failed is positive. Quota is reserved by count and refunded only for failures the server determines refundable. Disconnects, submission_unknown, and storage failures after delivery may remain billed; neither assets.length nor failed proves the final debit. Check authenticated quota after uncertainty.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/images/generations"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "prompt": "A red apple on a white table",
  "count": 2
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/images/generations'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"prompt":"A red apple on a white table","count":2}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/images/generations"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"prompt\":\"A red apple on a white table\",\"count\":2}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/images/generations";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"prompt":"A red apple on a white table","count":2}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "assets": [
      {
        "id": "asset-example",
        "kind": "image",
        "mime": "image/png",
        "bytes": 1024,
        "width": 2048,
        "height": 2048,
        "durationMs": null,
        "url": "/api/v1/media/assets/asset-example",
        "title": null,
        "origin": "generated",
        "createdAt": 1800000000000,
        "expiresAt": null,
        "attribution": null
      }
    ],
    "failed": 1,
    "errors": [
      {
        "code": "submission_unknown",
        "message": "Submission may be billed"
      }
    ],
    "model": "public-image-model",
    "latencyMs": 1000
  }
}
```

<a id="ai-video"></a>
## Generate videos

Submit once, save the job id, then read the existing task.

prompt is required (factory maximum 2000). Defaults: mode=description, duration=5 seconds (integer 4–12), aspectRatio=16:9 (also 9:16 or 1:1), resolution=720p (also 480p or 1080p), watermark=false, cameraFixed=false. Choose options from the selected live model descriptor. A 202 response may already contain a failed job: inspect status/error and save data.job.id immediately. There are no completion webhooks or global idempotency keys.

keyframe requires firstFrameUrl; lastFrameUrl is allowed only if the model supports it, and referenceImageUrls must be absent. reference uses referenceImageUrls with a product maximum of 8, often lower by model. description normally has no images; its compatibility form accepts up to two referenceImageUrls and normalizes them to keyframes. Explicit firstFrameUrl/lastFrameUrl in description is rejected. Gateway reference images require sides 300–6000px and aspect ratio 0.4–2.5.

### POST /api/v1/media/videos/generations

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 202

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `prompt` | `string` | Required | Nonempty prompt; factory maximum 2000 characters. |
| `model` | `string` | Optional | Public model id from live discovery; empty examples must be replaced. — `ai_video.limits.models[].id` |
| `mode` | `string` | Optional | description, keyframe or reference; subject to model limits. (default: `description`) |
| `duration` | `integer` | Optional | Integer seconds 4–12; use selected model limits. (default: `5`) |
| `aspectRatio` | `string` | Optional | 16:9, 9:16 or 1:1, subject to model support. (default: `16:9`) |
| `resolution` | `string` | Optional | 480p, 720p or 1080p, subject to model support. (default: `720p`) |
| `watermark` | `boolean` | Optional | Whether the selected model applies a watermark. (default: `false`) |
| `cameraFixed` | `boolean` | Optional | Requires selected model support. (default: `false`) |
| `firstFrameUrl` | `string` | Optional | Required only in keyframe mode. |
| `lastFrameUrl` | `string` | Optional | Optional keyframe tail if supported. |
| `referenceImageUrls` | `string[]` | Optional | Reference images; product maximum 8, model may allow fewer. |

#### JSON request

Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/videos/generations"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "prompt": "A calm lake at sunrise",
  "duration": 5,
  "aspectRatio": "16:9",
  "resolution": "720p"
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 202) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/videos/generations'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"prompt":"A calm lake at sunrise","duration":5,"aspectRatio":"16:9","resolution":"720p"}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(202)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
Write-Output ("Save ARAGON_JOB_ID: " + $result.data.job.id)
Write-Output ("Status: " + $result.data.job.status)
$result.data.job.error | ConvertTo-Json -Depth 5
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/videos/generations"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"prompt\":\"A calm lake at sunrise\",\"duration\":5,\"aspectRatio\":\"16:9\",\"resolution\":\"720p\"}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [202]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/videos/generations";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"prompt":"A calm lake at sunrise","duration":5,"aspectRatio":"16:9","resolution":"720p"}),
});
if (![202].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
console.log("Save ARAGON_JOB_ID:", result.data.job.id,
  "status:", result.data.job.status, "error:", result.data.job.error);
```

**Response** (202)

```json
{
  "data": {
    "job": {
      "id": "job-example",
      "capability": "ai_video",
      "status": "queued",
      "phase": "queued",
      "model": "public-video-model",
      "params": {
        "prompt": "A calm lake at sunrise",
        "promptChars": 22,
        "duration": 5,
        "resolution": "720p",
        "aspectRatio": "16:9",
        "mode": "description"
      },
      "error": null,
      "asset": null,
      "createdAt": 1800000000000,
      "updatedAt": 1800000000000,
      "finishedAt": null,
      "deadlineAt": 1800007200000
    }
  }
}
```

Related operations: [Read and cancel jobs](#jobs)

<a id="tts"></a>
## Synthesize speech

Receive a protected MP3 asset or consume audio bytes.

text is required, factory maximum 1000 characters; use live limits.maxChars. Choose voice from defaultVoice or voices[].id. speed defaults to 1; recommended 0.5–2. The adapter accepts finite 0.1–3 and clamps to 0.5–2, while values outside 0.1–3 are invalid. response=url (default) returns data.asset, voice and durationMs; response=stream returns audio/mpeg. No format selector is provided: output is MP3. A failure before streaming may be JSON; check HTTP and MIME before writing bytes. Streaming ends after at most 300 seconds and normal EOF cannot prove semantic audio completeness.

### POST /api/v1/media/audio/speech

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json | audio/mpeg`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `text` | `string` | Required | Nonempty text, limited by live maxChars. — `tts.limits.maxChars` |
| `voice` | `string` | Optional | String id from voices[].id or defaultVoice. — `tts.limits.voices[].id` |
| `speed` | `number` | Optional | Recommended 0.5–2; finite 0.1–3 accepted and clamped. (default: `1`) |
| `response` | `string` | Optional | url returns JSON; stream returns audio/mpeg. (default: `url`) |

#### JSON request

Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/audio/speech"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "text": "Hello, world",
  "response": "url"
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/audio/speech'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"text":"Hello, world","response":"url"}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/audio/speech"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"text\":\"Hello, world\",\"response\":\"url\"}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/audio/speech";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"text":"Hello, world","response":"url"}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "asset": {
      "id": "asset-example",
      "kind": "audio",
      "mime": "audio/mpeg",
      "bytes": 1024,
      "width": null,
      "height": null,
      "durationMs": 1500,
      "url": "/api/v1/media/assets/asset-example",
      "title": null,
      "origin": "generated",
      "createdAt": 1800000000000,
      "expiresAt": null,
      "attribution": null
    },
    "voice": "discovered-voice",
    "durationMs": 1500
  }
}
```

#### Download bytes

Check HTTP and MIME before publishing the complete file; preserve an existing target on failure.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/audio/speech"
work=$(mktemp -d "./.aragon-download.XXXXXXXX")
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "text": "Hello, world",
  "response": "stream"
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in audio/mpeg) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
mv "$work/body" 'aragon-output.mp3'
printf '%s\n' 'aragon-output.mp3'
# Normal EOF cannot prove semantic audio completeness.
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/audio/speech'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"text":"Hello, world","response":"stream"}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$target = Join-Path (Get-Location).Path 'aragon-output.mp3'
$temporary = $target + "." + [Guid]::NewGuid().ToString("N") + ".partial"
try {
  $parameters.OutFile = $temporary
  $parameters.PassThru = $true
  $response = Invoke-WebRequest @parameters
  if ([int]$response.StatusCode -notin @(200)) {
    throw ("Unexpected HTTP " + $response.StatusCode)
  }
  $mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
  if ($mime -notin @('audio/mpeg')) { throw ("Unexpected Content-Type: " + $mime) }
  Move-Item -LiteralPath $temporary -Destination $target -Force
  Write-Output $target
} finally {
  if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary }
}
# Normal EOF cannot prove semantic audio completeness.
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/audio/speech"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"text\":\"Hello, world\",\"response\":\"stream\"}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["audio/mpeg"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    target = Path("aragon-output.mp3")
    fd, name = tempfile.mkstemp(prefix=".aragon-", dir=target.parent)
    temporary = Path(name)
    try:
        with os.fdopen(fd, "wb") as output:
            for chunk in response.iter_content(65536): output.write(chunk)
        temporary.replace(target)
        print(target)
    except BaseException:
        temporary.unlink(missing_ok=True)
        raise
    # Normal EOF cannot prove semantic audio completeness.
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/audio/speech";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"text":"Hello, world","response":"stream"}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["audio/mpeg"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const { open, rename, unlink } = await import("node:fs/promises");
const { randomUUID } = await import("node:crypto");
const target = "aragon-output.mp3";
const temporary = target + "." + randomUUID() + ".partial";
const file = await open(temporary, "wx");
try {
  if (!response.body) throw new Error("Missing response body");
  for await (const chunk of response.body) await file.writeFile(chunk);
  await file.close();
  await rename(temporary, target);
  console.log(target);
} catch (error) {
  await file.close();
  await unlink(temporary);
  throw new Error("Incomplete output; existing target preserved", { cause: error });
}
// Normal EOF does not prove semantic audio completeness.
```

**Response** (200)

`binary`

<a id="image-search"></a>
## Search images

Find images, preserve attribution, and use opaque pagination.

Send query (1–200 characters) and optional perPage (default 20, factory maximum 30). orientation is landscape, portrait or squarish; color/orderBy follow live limits. Items contain id, description, width, height, color, thumbUrl, previewUrl, downloadUrl, author, pageUrl and optional downloadLocation. Keep attribution and original downloadLocation when saving Unsplash material.

Search returns data.items,total,hasMore,nextCursor,attribution. Resend nextCursor unchanged with the same query and filters; do not parse it or invent a page number. A disabled upstream can invalidate a cursor (400 invalid_cursor): restart from the first page. Preserve service and author attribution. External downloadUrl requests must not inherit gateway credentials.

### POST /api/v1/media/search/images

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `query` | `string` | Required | Nonempty search query, maximum 200 characters. |
| `perPage` | `integer` | Optional | Default 20; maximum depends on capability limits. (default: `20`) |
| `cursor` | `string` | Optional | Opaque nextCursor, resent unchanged with original filters. |
| `orientation` | `string` | Optional | Choose orientation from this capability limits. — `image_search.limits` |
| `color` | `string` | Optional | Choose supported filter values from live limits. — `image_search.limits` |
| `orderBy` | `string` | Optional | Choose supported filter values from live limits. — `image_search.limits` |

#### JSON request

Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/search/images"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "query": "ocean",
  "perPage": 3
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/search/images'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"query":"ocean","perPage":3}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/search/images"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"query\":\"ocean\",\"perPage\":3}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/search/images";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"query":"ocean","perPage":3}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "items": [
      {
        "id": "search-example",
        "author": {
          "name": "Example author",
          "url": "https://example.com/author"
        },
        "pageUrl": "https://example.com/item",
        "downloadUrl": "https://example.com/file",
        "description": "Ocean",
        "width": 2048,
        "height": 1365,
        "color": "#005577",
        "thumbUrl": "https://example.com/thumb",
        "previewUrl": "https://example.com/preview",
        "downloadLocation": "https://api.unsplash.com/photos/example/download"
      }
    ],
    "total": 1,
    "hasMore": false,
    "nextCursor": null,
    "attribution": {
      "source": "example",
      "text": "Example author / Example source",
      "url": "https://example.com/item"
    }
  }
}
```

<a id="video-search"></a>
## Search videos

Find video previews and download locations.

query is required (maximum 200); perPage defaults to 20 with factory maximum 80. orientation is landscape, portrait or mixed. Items contain id, width, height, durationMs, thumbUrl, previewUrl, downloadUrl, author and pageUrl. Search does not save items into your asset library.

Search returns data.items,total,hasMore,nextCursor,attribution. Resend nextCursor unchanged with the same query and filters; do not parse it or invent a page number. A disabled upstream can invalidate a cursor (400 invalid_cursor): restart from the first page. Preserve service and author attribution. External downloadUrl requests must not inherit gateway credentials.

### POST /api/v1/media/search/videos

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `query` | `string` | Required | Nonempty search query, maximum 200 characters. |
| `perPage` | `integer` | Optional | Default 20; maximum depends on capability limits. (default: `20`) |
| `cursor` | `string` | Optional | Opaque nextCursor, resent unchanged with original filters. |
| `orientation` | `string` | Optional | Choose orientation from this capability limits. — `video_search.limits` |

#### JSON request

Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/search/videos"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "query": "ocean",
  "perPage": 3
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/search/videos'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"query":"ocean","perPage":3}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/search/videos"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"query\":\"ocean\",\"perPage\":3}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/search/videos";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"query":"ocean","perPage":3}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "items": [
      {
        "id": "search-example",
        "author": {
          "name": "Example author",
          "url": "https://example.com/author"
        },
        "pageUrl": "https://example.com/item",
        "downloadUrl": "https://example.com/file",
        "width": 1920,
        "height": 1080,
        "durationMs": 12000,
        "thumbUrl": "https://example.com/thumb",
        "previewUrl": "https://example.com/preview.mp4"
      }
    ],
    "total": 1,
    "hasMore": false,
    "nextCursor": null,
    "attribution": {
      "source": "example",
      "text": "Example author / Example source",
      "url": "https://example.com/item"
    }
  }
}
```

<a id="audio-search"></a>
## Search sound effects

Find preview-quality audio with its author and license.

query is required (maximum 200); perPage defaults to 20 with factory maximum 150. Discover audioType, sort, minDurationSeconds and maxDurationSeconds in limits. Items contain id, name, description, durationMs, tags, license, author, previewUrl, downloadUrl, pageUrl and optional waveformUrl, sizeBytes, channels and sampleRate. These are previews; OAuth original-quality downloads are not promised.

Search returns data.items,total,hasMore,nextCursor,attribution. Resend nextCursor unchanged with the same query and filters; do not parse it or invent a page number. A disabled upstream can invalidate a cursor (400 invalid_cursor): restart from the first page. Preserve service and author attribution. External downloadUrl requests must not inherit gateway credentials.

### POST /api/v1/media/search/sounds

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `query` | `string` | Required | Nonempty search query, maximum 200 characters. |
| `perPage` | `integer` | Optional | Default 20; maximum depends on capability limits. (default: `20`) |
| `cursor` | `string` | Optional | Opaque nextCursor, resent unchanged with original filters. |
| `audioType` | `string` | Optional | Choose supported filter values from live limits. — `audio_search.limits` |
| `sort` | `string` | Optional | Choose supported filter values from live limits. — `audio_search.limits` |
| `minDurationSeconds` | `number` | Optional | Choose supported filter values from live limits. — `audio_search.limits` |
| `maxDurationSeconds` | `number` | Optional | Choose supported filter values from live limits. — `audio_search.limits` |

#### JSON request

Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/search/sounds"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "query": "ocean",
  "perPage": 3
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/search/sounds'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"query":"ocean","perPage":3}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/search/sounds"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"query\":\"ocean\",\"perPage\":3}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/search/sounds";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"query":"ocean","perPage":3}),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "items": [
      {
        "id": "search-example",
        "author": {
          "name": "Example author",
          "url": "https://example.com/author"
        },
        "pageUrl": "https://example.com/item",
        "downloadUrl": "https://example.com/file",
        "name": "Ocean waves",
        "description": "Waves",
        "durationMs": 5000,
        "tags": [
          "ocean"
        ],
        "license": "CC0",
        "previewUrl": "https://example.com/preview.mp3",
        "waveformUrl": "https://example.com/waveform",
        "sizeBytes": 80000,
        "channels": 2,
        "sampleRate": 44100
      }
    ],
    "total": 1,
    "hasMore": false,
    "nextCursor": null,
    "attribution": {
      "source": "example",
      "text": "Example author / Example source",
      "url": "https://example.com/item"
    }
  }
}
```

<a id="jobs"></a>
## Read and cancel jobs

Bound polling by the task deadline and retry reads only.

Queued/running are live; succeeded/failed/expired/cancelled are terminal. phase is presentation progress, not a terminal state. Poll with ARAGON_JOB_ID separately from generation. Require a valid epoch-millisecond deadlineAt; use min(deadlineAt+60s, start+121min). Begin at 2 seconds, increasing to 10. Before every request and wait, recompute remaining budget; GET timeout is at most 30 seconds and remaining time. An earlier deadline tightens the budget. Missing deadline stops with the saved id.

Stop on 401/403/404 and other nonrecoverable 4xx. For 429 honor valid Retry-After seconds or HTTP-date, default 10 seconds, within the total budget. Retry only GET after network failures or 502/503/504, stopping after 5 consecutive failures; valid responses reset that count. Always retain the job id on errors, timeout or interruption. succeeded with asset=null means no asset currently available; do not regenerate automatically.

Cancel returns 202 with data.job, upstreamStillRunning:true and notice. Cancellation is local: upstream work and billing may continue, quota is not refunded. Cancelling a terminal task returns 409 job_already_finished. A task error is distinct from HTTP failure and stops automatic polling.

### GET /api/v1/media/jobs/{id}

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `path string` | Required | Opaque resource id, encoded as one URL path segment. |

#### JSON request

Queued/running are live; succeeded/failed/expired/cancelled are terminal. phase is presentation progress, not a terminal state. Poll with ARAGON_JOB_ID separately from generation. Require a valid epoch-millisecond deadlineAt; use min(deadlineAt+60s, start+121min). Begin at 2 seconds, increasing to 10. Before every request and wait, recompute remaining budget; GET timeout is at most 30 seconds and remaining time. An earlier deadline tightens the budget. Missing deadline stops with the saved id.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_JOB_ID:?Set ARAGON_JOB_ID}"
case "$ARAGON_JOB_ID" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_JOB_ID" | jq -sRr @uri)
path='/api/v1/media/jobs/'
url="$ORIGIN/api/v1/media/jobs/$resource_id"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_JOB_ID
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/media/jobs/{id}'.Replace("{id}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(200)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_JOB_ID")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/media/jobs/{id}".replace("{id}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_JOB_ID;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_JOB_ID to the resource id");
const path = "/api/v1/media/jobs/{id}".replace("{id}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (200)

```json
{
  "data": {
    "job": {
      "id": "job-example",
      "capability": "ai_video",
      "status": "queued",
      "phase": "queued",
      "model": "public-video-model",
      "params": {
        "prompt": "A calm lake at sunrise",
        "promptChars": 22,
        "duration": 5,
        "resolution": "720p",
        "aspectRatio": "16:9",
        "mode": "description"
      },
      "error": null,
      "asset": null,
      "createdAt": 1800000000000,
      "updatedAt": 1800000000000,
      "finishedAt": null,
      "deadlineAt": 1800007200000
    }
  }
}
```

#### Read-only job polling

Stop on 401/403/404 and other nonrecoverable 4xx. For 429 honor valid Retry-After seconds or HTTP-date, default 10 seconds, within the total budget. Retry only GET after network failures or 502/503/504, stopping after 5 consecutive failures; valid responses reset that count. Always retain the job id on errors, timeout or interruption. succeeded with asset=null means no asset currently available; do not regenerate automatically.

##### curl

```sh
# POSIX shell + curl + jq >=1.6; read only. No new generation is submitted.
(
set -eu
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
ORIGIN="${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
: "${ARAGON_JOB_ID:?Set ARAGON_JOB_ID from the earlier submit response}"
case "$ARAGON_JOB_ID" in .|..) exit 2 ;; esac
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
id=$(printf "%s" "$ARAGON_JOB_ID" | jq -sRr @uri)
url="$ORIGIN/api/v1/media/jobs/$id"
work=$(mktemp -d)
trap 'printf "ARAGON_JOB_ID=%s\n" "$ARAGON_JOB_ID" >&2; rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
deadline=$(jq -nr 'now + 121 * 60'); gap=2; failures=0
remaining() { jq -nr --argjson deadline "$deadline" '$deadline-now'; }
wait_poll() {
  jq -ne --argjson wait "$1" --argjson remaining "$(remaining)" '$wait < $remaining' >/dev/null || exit 1
  sleep "$1"
}
while :; do
  budget=$(remaining)
  jq -ne --argjson budget "$budget" '$budget>0' >/dev/null || exit 1
  timeout=$(jq -nr --argjson budget "$budget" '[$budget,30]|min')
  if status=$(curl --silent --show-error --max-time "$timeout" -X GET "$url" \
      -H "Authorization: Bearer $ARAGON_API_KEY" --dump-header "$work/headers" \
      --output "$work/body" --write-out "%{http_code}"); then :; else status=000; fi
  jq -ne --argjson budget "$(remaining)" '$budget>0' >/dev/null || exit 1
  case "$status" in
    429)
      failures=0
      retry=$(awk 'tolower($1)=="retry-after:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1)
      delay=$(jq -nr --arg value "$retry" 'if ($value|test("^[0-9]+$")) then
        ($value|tonumber) else (try (($value|strptime("%a, %d %b %Y %H:%M:%S GMT")
        |mktime)-now | [.,0]|max) catch 10) end')
      wait_poll "$delay"; continue ;;
    000|502|503|504)
      failures=$((failures+1)); [ "$failures" -lt 5 ] || exit 1
      wait_poll "$gap"; continue ;;
    200) ;;
    *) cat "$work/body" >&2; exit 1 ;;
  esac
  grep -Ei '^content-type:[[:space:]]*application/json' "$work/headers" >/dev/null || exit 1
  jq -e '.data.job.deadlineAt | type=="number" and .>0' "$work/body" >/dev/null || exit 1
  failures=0
  deadline=$(jq -r --argjson previous "$deadline" \
    '[.data.job.deadlineAt/1000+60,$previous]|min' "$work/body")
  state=$(jq -r '.data.job.status' "$work/body")
  if jq -e '.data.job.error != null' "$work/body" >/dev/null; then
    cat "$work/body"; break
  fi
  case "$state" in
    succeeded|failed|expired|cancelled) cat "$work/body"; break ;;
    queued|running) ;;
    *) echo "Unknown job status" >&2; exit 1 ;;
  esac
  wait_poll "$gap"; gap=$((gap+2)); [ "$gap" -le 10 ] || gap=10
done
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; read only. Save the original ARAGON_JOB_ID.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
$jobId = $env:ARAGON_JOB_ID; $key = $env:ARAGON_API_KEY
if (-not $origin -or -not $jobId -or -not $key -or $jobId -in @(".", "..")) {
  throw "Set ARAGON_BASE_URL, ARAGON_JOB_ID and ARAGON_API_KEY"
}
$base = [Uri]$origin
if ($base.Scheme -notin @("http", "https") -or $base.UserInfo -or
    $base.GetLeftPart([UriPartial]::Authority) -cne $origin) { throw "Invalid origin" }
$url = $origin + "/api/v1/media/jobs/" + [Uri]::EscapeDataString($jobId)
Add-Type -AssemblyName System.Net.Http
$handler = New-Object System.Net.Http.HttpClientHandler
$handler.AllowAutoRedirect = $false
$client = New-Object System.Net.Http.HttpClient($handler)
$client.Timeout = [Threading.Timeout]::InfiniteTimeSpan
$clock = [Diagnostics.Stopwatch]::StartNew()
$deadline = 121 * 60000; $gap = 2000; $failures = 0
$deadline = [double]$deadline
function Wait-Poll([double]$milliseconds) {
  if ($milliseconds -ge ($deadline - $clock.ElapsedMilliseconds)) {
    throw "Polling budget exhausted"
  }
  Start-Sleep -Milliseconds ([int]$milliseconds)
}
function Get-RetryDelay([string]$value) {
  if ($value -match "^\d+$") { return [double]$value * 1000 }
  $date = [DateTimeOffset]::MinValue
  if ([DateTimeOffset]::TryParse($value, [ref]$date)) {
    return [Math]::Max([double]0, ($date - [DateTimeOffset]::UtcNow).TotalMilliseconds)
  }
  return 10000
}
try {
  while ($true) {
    $remaining = $deadline - $clock.ElapsedMilliseconds
    if ($remaining -lt 1) { throw "Polling budget exhausted" }
    $status = 0; $retryAfter = $null
    $response = $null
    $request = New-Object Net.Http.HttpRequestMessage([Net.Http.HttpMethod]::Get, $url)
    [void]$request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + $key)
    $cancel = New-Object Threading.CancellationTokenSource
    $cancel.CancelAfter([int][Math]::Floor([Math]::Min(30000,$remaining)))
    try {
      $task = $client.SendAsync($request,
        [Net.Http.HttpCompletionOption]::ResponseContentRead, $cancel.Token)
      $response = $task.GetAwaiter().GetResult()
      $status = [int]$response.StatusCode
      if ($response.Headers.RetryAfter) { $retryAfter = $response.Headers.RetryAfter.ToString() }
      $contentType = ""
      if ($response.Content.Headers.ContentType) {
        $contentType = $response.Content.Headers.ContentType.MediaType
      }
      $content = $response.Content.ReadAsStringAsync().GetAwaiter().GetResult()
    } catch {
      $status = 0
    } finally {
      if ($response) { $response.Dispose() }
      $request.Dispose(); $cancel.Dispose()
    }
    if ($clock.ElapsedMilliseconds -ge $deadline) { throw "Polling budget exhausted" }
    if ($status -eq 429) {
      $failures = 0; Wait-Poll (Get-RetryDelay $retryAfter); continue
    }
    if ($status -eq 0 -or $status -in @(502,503,504)) {
      $failures += 1
      if ($failures -ge 5) { throw ("Repeated read failure HTTP " + $status) }
      Wait-Poll $gap; continue
    }
    if ($status -ne 200) { throw ("HTTP " + $status) }
    if ($contentType -ne "application/json") {
      throw "Expected application/json"
    }
    $job = ($content | ConvertFrom-Json).data.job
    if (-not $job -or $job.deadlineAt -isnot [ValueType] -or
        $job.deadlineAt -is [bool] -or [double]$job.deadlineAt -le 0 -or
        [double]::IsNaN([double]$job.deadlineAt) -or
        [double]::IsInfinity([double]$job.deadlineAt)) {
      throw "Incomplete job response: valid deadlineAt required"
    }
    $failures = 0
    $remainingJob = [double]$job.deadlineAt + 60000 -
      [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()
    $deadline = [Math]::Min([double]$deadline,
      [double]($clock.ElapsedMilliseconds + $remainingJob))
    if ($job.status -in @("succeeded","failed","expired","cancelled") -or $job.error) {
      $job | ConvertTo-Json -Depth 30
      if ($job.status -eq "succeeded" -and -not $job.asset) {
        Write-Output "Asset unavailable or deleted; do not regenerate automatically"
      }
      break
    }
    if ($job.status -notin @("queued","running")) { throw "Unknown status" }
    Wait-Poll $gap; $gap = [Math]::Min(10000, $gap + 2000)
  }
} finally {
  $client.Dispose(); $handler.Dispose()
  Write-Output ("ARAGON_JOB_ID=" + $jobId)
}
```

##### python

```python
# Python 3 + requests; save as a .py file. Read only: use the earlier job id.
import json, math, os, subprocess, sys, time
from urllib.parse import urlsplit, quote
from email.utils import parsedate_to_datetime
origin = os.environ.get("ARAGON_BASE_URL")
key, job_id = os.environ.get("ARAGON_API_KEY"), os.environ.get("ARAGON_JOB_ID")
if not origin or not key or not job_id or job_id in (".", ".."):
    raise RuntimeError("Set ARAGON_BASE_URL, ARAGON_API_KEY and ARAGON_JOB_ID")
base = urlsplit(origin)
if (base.scheme not in ("http", "https") or not base.netloc or base.username or
        base.path or base.query or base.fragment): raise RuntimeError("Invalid origin")
url = origin + "/api/v1/media/jobs/" + quote(job_id, safe="")
POLL_REQUEST_SECONDS = 30
POLL_TOTAL_SECONDS = 121 * 60
if len(sys.argv) == 3 and sys.argv[1] == "--aragon-poll-read":
    import requests
    seconds = float(sys.argv[2])
    with requests.get(url, headers={"Authorization": "Bearer " + key},
            allow_redirects=False, timeout=(seconds/2, seconds/2)) as response:
        print(json.dumps({"status": response.status_code, "headers": dict(response.headers),
                          "content": response.content.decode("utf-8", errors="replace")}))
    raise SystemExit(0)
deadline = time.monotonic() + POLL_TOTAL_SECONDS
gap, failures = 2, 0
def remaining(): return deadline - time.monotonic()
def wait(seconds):
    if seconds >= remaining(): raise TimeoutError("Polling budget exhausted")
    time.sleep(seconds)
def retry_delay(value):
    if value and value.isdigit(): return int(value)
    try: return max(0, parsedate_to_datetime(value).timestamp() - time.time())
    except (TypeError, ValueError, OverflowError): return 10
try:
    while True:
        if remaining() <= 0: raise TimeoutError("Polling budget exhausted")
        try:
            timeout = min(POLL_REQUEST_SECONDS, remaining())
            result = subprocess.run([sys.executable, __file__, "--aragon-poll-read",
                str(timeout)], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
                encoding="utf-8", timeout=timeout)
            if result.returncode != 0: raise OSError("GET worker failed; retain job id")
            reply = json.loads(result.stdout)
            status, headers, content = reply["status"], reply["headers"], reply["content"]
            headers = {name.lower(): value for name, value in headers.items()}
        except (subprocess.TimeoutExpired, OSError):
            failures += 1
            if failures >= 5: raise
            wait(gap); continue
        if remaining() <= 0: raise TimeoutError("Polling budget exhausted")
        if status == 429:
            failures = 0
            wait(retry_delay(headers.get("retry-after"))); continue
        if status in (502, 503, 504):
            failures += 1
            if failures >= 5: raise RuntimeError("Repeated HTTP %s" % status)
            wait(gap); continue
        if status != 200: raise RuntimeError("HTTP %s: %s" % (status, content))
        if headers.get("content-type", "").split(";")[0] != "application/json":
            raise RuntimeError("Expected application/json")
        job = json.loads(content).get("data", {}).get("job")
        if (not job or not isinstance(job.get("deadlineAt"), (int, float)) or
                isinstance(job["deadlineAt"], bool) or
                not math.isfinite(job["deadlineAt"]) or job["deadlineAt"] <= 0):
            raise RuntimeError("Incomplete job response: valid deadlineAt required")
        failures = 0
        deadline = min(deadline, time.monotonic() + job["deadlineAt"]/1000 + 60 - time.time())
        if job["status"] in ("succeeded", "failed", "expired", "cancelled") or job.get("error"):
            print(json.dumps(job, ensure_ascii=False, indent=2))
            if job["status"] == "succeeded" and not job.get("asset"):
                print("Asset unavailable or deleted; do not regenerate automatically")
            break
        if job["status"] not in ("queued", "running"): raise RuntimeError("Unknown status")
        wait(gap); gap = min(10, gap + 2)
finally: print("ARAGON_JOB_ID=" + job_id)
```

##### node

```javascript
// Node.js >=22.5; .mjs. Read only: set ARAGON_JOB_ID from the earlier submit response.
const origin = process.env.ARAGON_BASE_URL;
const id = process.env.ARAGON_JOB_ID, key = process.env.ARAGON_API_KEY;
if (!origin || !id || !key || id === "." || id === "..")
  throw new Error("Set ARAGON_BASE_URL, ARAGON_JOB_ID and ARAGON_API_KEY");
const base = new URL(origin);
if (!["http:","https:"].includes(base.protocol) || base.origin !== origin || base.username)
  throw new Error("Expected a pure http(s) origin");
const url = origin + "/api/v1/media/jobs/" + encodeURIComponent(id);
const started = performance.now();
let deadline = started + 121 * 60000, gap = 2000, failures = 0;
const remaining = () => deadline - performance.now();
async function wait(milliseconds) {
  if (milliseconds >= remaining()) throw new Error("Polling budget exhausted");
  await new Promise(resolve => setTimeout(resolve, milliseconds));
}
function retryDelay(value) {
  if (value && /^\d+$/.test(value)) return Number(value) * 1000;
  const date = value ? Date.parse(value) : NaN;
  return Number.isFinite(date) ? Math.max(0, date - Date.now()) : 10000;
}
try {
  while (true) {
    if (remaining() <= 0) throw new Error("Polling budget exhausted");
    let response, text;
    try {
      response = await fetch(url, { method: "GET",
        headers: { Authorization: "Bearer " + key }, redirect: "error",
        signal: AbortSignal.timeout(Math.max(1, Math.floor(Math.min(30000, remaining())))) });
      text = await response.text();
    } catch (error) {
      if (++failures >= 5) throw error;
      await wait(gap); continue;
    }
    if (remaining() <= 0) throw new Error("Polling budget exhausted");
    if (response.status === 429) {
      failures = 0;
      await wait(retryDelay(response.headers.get("retry-after"))); continue;
    }
    if ([502,503,504].includes(response.status)) {
      if (++failures >= 5) throw new Error("Repeated HTTP " + response.status);
      await wait(gap); continue;
    }
    if (response.status !== 200) throw new Error("HTTP " + response.status + ": " + text);
    if ((response.headers.get("content-type") || "").split(";")[0] !== "application/json")
      throw new Error("Expected application/json");
    const job = JSON.parse(text).data?.job;
    if (!job || !Number.isFinite(job.deadlineAt) || job.deadlineAt <= 0)
      throw new Error("Incomplete job response: missing valid deadlineAt");
    failures = 0;
    deadline = Math.min(deadline, performance.now() + job.deadlineAt + 60000 - Date.now());
    if (["succeeded","failed","expired","cancelled"].includes(job.status) || job.error) {
      console.log(JSON.stringify(job, null, 2));
      if (job.status === "succeeded" && !job.asset)
        console.log("Asset unavailable or deleted; do not regenerate automatically");
      break;
    }
    if (!["queued","running"].includes(job.status)) throw new Error("Unknown job status");
    await wait(gap); gap = Math.min(10000, gap + 2000);
  }
} finally { console.log("ARAGON_JOB_ID=" + id); }
```

**Response** (200)

```json
{
  "data": {
    "job": {
      "id": "job-example",
      "capability": "ai_video",
      "status": "succeeded",
      "phase": "ready",
      "model": "public-video-model",
      "params": {
        "prompt": "A calm lake at sunrise",
        "promptChars": 22,
        "duration": 5,
        "resolution": "720p",
        "aspectRatio": "16:9",
        "mode": "description"
      },
      "error": null,
      "asset": {
        "id": "asset-example",
        "kind": "video",
        "mime": "video/mp4",
        "bytes": 1024,
        "width": 2048,
        "height": 2048,
        "durationMs": null,
        "url": "/api/v1/media/assets/asset-example",
        "title": null,
        "origin": "generated",
        "createdAt": 1800000000000,
        "expiresAt": null,
        "attribution": null
      },
      "createdAt": 1800000000000,
      "updatedAt": 1800000000000,
      "finishedAt": 1800000010000,
      "deadlineAt": 1800007200000
    }
  }
}
```

### POST /api/v1/media/jobs/{id}/cancel

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 202

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `path string` | Required | Opaque resource id, encoded as one URL path segment. |

#### JSON request

Cancel returns 202 with data.job, upstreamStillRunning:true and notice. Cancellation is local: upstream work and billing may continue, quota is not refunded. Cancelling a terminal task returns 409 job_already_finished. A task error is distinct from HTTP failure and stops automatic polling.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_JOB_ID:?Set ARAGON_JOB_ID}"
case "$ARAGON_JOB_ID" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_JOB_ID" | jq -sRr @uri)
path='/api/v1/media/jobs//cancel'
url="$ORIGIN/api/v1/media/jobs/$resource_id/cancel"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 202) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_JOB_ID
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/media/jobs/{id}/cancel'.Replace("{id}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(202)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_JOB_ID")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/media/jobs/{id}/cancel".replace("{id}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [202]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_JOB_ID;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_JOB_ID to the resource id");
const path = "/api/v1/media/jobs/{id}/cancel".replace("{id}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![202].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (202)

```json
{
  "data": {
    "job": {
      "id": "job-example",
      "capability": "ai_video",
      "status": "cancelled",
      "phase": "queued",
      "model": "public-video-model",
      "params": {
        "prompt": "A calm lake at sunrise",
        "promptChars": 22,
        "duration": 5,
        "resolution": "720p",
        "aspectRatio": "16:9",
        "mode": "description"
      },
      "error": null,
      "asset": null,
      "createdAt": 1800000000000,
      "updatedAt": 1800000000000,
      "finishedAt": null,
      "deadlineAt": 1800007200000
    },
    "upstreamStillRunning": true,
    "notice": "Upstream work and billing may continue"
  }
}
```

<a id="assets"></a>
## Download and delete assets

Protected gateway paths return bytes, not JSON.

Asset URLs are relative protected paths, not public sharing links. Resolve against the chosen origin, require exactly that origin, no userinfo/query/hash and one encoded nonempty id after /api/v1/media/assets/. Send the gateway key only there and refuse redirects. GET supports Range (206), If-None-Match (304 reuses a local copy) and 416 (correct the range); the basic example requires 200. DELETE returns 204 with no body; authorized repeat deletion is 204. Explicit deletion immediately reclaims files with no remaining references.

### GET /api/v1/media/assets/{id}

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 200 / 206 / 304

**Response**: `image/* | video/* | audio/*`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `path string` | Required | Opaque resource id, encoded as one URL path segment. |

#### Download bytes

Asset URLs are relative protected paths, not public sharing links. Resolve against the chosen origin, require exactly that origin, no userinfo/query/hash and one encoded nonempty id after /api/v1/media/assets/. Send the gateway key only there and refuse redirects. GET supports Range (206), If-None-Match (304 reuses a local copy) and 416 (correct the range); the basic example requires 200. DELETE returns 204 with no body; authorized repeat deletion is 204. Explicit deletion immediately reclaims files with no remaining references.
Check HTTP and MIME before publishing the complete file; preserve an existing target on failure.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_ASSET_ID:?Set ARAGON_ASSET_ID}"
case "$ARAGON_ASSET_ID" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_ASSET_ID" | jq -sRr @uri)
path='/api/v1/media/assets/'
url="$ORIGIN/api/v1/media/assets/$resource_id"
work=$(mktemp -d "./.aragon-download.XXXXXXXX")
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X GET "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 200) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in image/png|image/jpeg|image/webp|image/gif|video/mp4|video/webm|audio/mpeg|audio/wav|audio/ogg) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
mv "$work/body" 'aragon-asset.bin'
printf '%s\n' 'aragon-asset.bin'
# Normal EOF cannot prove semantic audio completeness.
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_ASSET_ID
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/media/assets/{id}'.Replace("{id}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'GET'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$target = Join-Path (Get-Location).Path 'aragon-asset.bin'
$temporary = $target + "." + [Guid]::NewGuid().ToString("N") + ".partial"
try {
  $parameters.OutFile = $temporary
  $parameters.PassThru = $true
  $response = Invoke-WebRequest @parameters
  if ([int]$response.StatusCode -notin @(200)) {
    throw ("Unexpected HTTP " + $response.StatusCode)
  }
  $mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
  if ($mime -notin @('image/png','image/jpeg','image/webp','image/gif','video/mp4','video/webm','audio/mpeg','audio/wav','audio/ogg')) { throw ("Unexpected Content-Type: " + $mime) }
  Move-Item -LiteralPath $temporary -Destination $target -Force
  Write-Output $target
} finally {
  if (Test-Path -LiteralPath $temporary) { Remove-Item -LiteralPath $temporary }
}
# Normal EOF cannot prove semantic audio completeness.
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_ASSET_ID")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/media/assets/{id}".replace("{id}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("GET", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [200]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["image/png","image/jpeg","image/webp","image/gif","video/mp4","video/webm","audio/mpeg","audio/wav","audio/ogg"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    target = Path("aragon-asset.bin")
    fd, name = tempfile.mkstemp(prefix=".aragon-", dir=target.parent)
    temporary = Path(name)
    try:
        with os.fdopen(fd, "wb") as output:
            for chunk in response.iter_content(65536): output.write(chunk)
        temporary.replace(target)
        print(target)
    except BaseException:
        temporary.unlink(missing_ok=True)
        raise
    # Normal EOF cannot prove semantic audio completeness.
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_ASSET_ID;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_ASSET_ID to the resource id");
const path = "/api/v1/media/assets/{id}".replace("{id}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "GET", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![200].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["image/png","image/jpeg","image/webp","image/gif","video/mp4","video/webm","audio/mpeg","audio/wav","audio/ogg"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const { open, rename, unlink } = await import("node:fs/promises");
const { randomUUID } = await import("node:crypto");
const target = "aragon-asset.bin";
const temporary = target + "." + randomUUID() + ".partial";
const file = await open(temporary, "wx");
try {
  if (!response.body) throw new Error("Missing response body");
  for await (const chunk of response.body) await file.writeFile(chunk);
  await file.close();
  await rename(temporary, target);
  console.log(target);
} catch (error) {
  await file.close();
  await unlink(temporary);
  throw new Error("Incomplete output; existing target preserved", { cause: error });
}
// Normal EOF does not prove semantic audio completeness.
```

**Response** (200)

`binary`

### DELETE /api/v1/media/assets/{id}

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 204

**Response**: `empty`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `id` | `path string` | Required | Opaque resource id, encoded as one URL path segment. |

#### Empty response

Asset URLs are relative protected paths, not public sharing links. Resolve against the chosen origin, require exactly that origin, no userinfo/query/hash and one encoded nonempty id after /api/v1/media/assets/. Send the gateway key only there and refuse redirects. GET supports Range (206), If-None-Match (304 reuses a local copy) and 416 (correct the range); the basic example requires 200. DELETE returns 204 with no body; authorized repeat deletion is 204. Explicit deletion immediately reclaims files with no remaining references.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
command -v jq >/dev/null || { echo "Requires jq >=1.6" >&2; exit 2; }
: "${ARAGON_ASSET_ID:?Set ARAGON_ASSET_ID}"
case "$ARAGON_ASSET_ID" in .|..) exit 2 ;; esac
resource_id=$(printf "%s" "$ARAGON_ASSET_ID" | jq -sRr @uri)
path='/api/v1/media/assets/'
url="$ORIGIN/api/v1/media/assets/$resource_id"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
status=$(curl --silent --show-error --max-time 600 -X DELETE "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 204) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
printf "HTTP 204\n"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$resourceId = $env:ARAGON_ASSET_ID
if (-not $resourceId -or $resourceId -in @(".", "..")) { throw "Set resource id" }
$path = '/api/v1/media/assets/{id}'.Replace("{id}", [Uri]::EscapeDataString($resourceId))
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$parameters = @{
  Uri = $url
  Method = 'DELETE'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(204)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
Write-Output "HTTP 204"
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
resource_id = os.environ.get("ARAGON_ASSET_ID")
if not resource_id or resource_id in (".", ".."): raise RuntimeError("Set resource id")
path = "/api/v1/media/assets/{id}".replace("{id}", quote(resource_id, safe=""))
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
with requests.request("DELETE", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True) as response:
    if response.status_code not in [204]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    print("HTTP 204")
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const resourceId = process.env.ARAGON_ASSET_ID;
if (!resourceId || resourceId === "." || resourceId === "..")
  throw new Error("Set ARAGON_ASSET_ID to the resource id");
const path = "/api/v1/media/assets/{id}".replace("{id}", encodeURIComponent(resourceId));
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
const response = await fetch(url, {
  method: "DELETE", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
});
if (![204].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
console.log("HTTP 204");
```

**Response** (204)

`empty`

<a id="ingest"></a>
## Save search material

Save allowed CDN results with real attribution.

sourceUrl is required, trimmed maximum 2048, and must belong to a CDN allowed by an enabled search upstream; this is not a general URL downloader. Pass attribution.text and attribution.url from the result. text is cleaned, trimmed and truncated to 200; url must be http(s), maximum 512. Attribution is recommended, not server-required. source is inferred by the server. There is no title parameter: asset title comes from cleaned attribution.text or null. Forward original downloadLocation for Unsplash download accounting; never fabricate it.

A successful save returns 201 with data.asset and consumes one additional unit of the matching search capability, separate from the search call. Saving shares generation concurrency slots: save serially to reduce 429 responses.

### POST /api/v1/media/ingest

**Authentication**: `Authorization: Bearer $ARAGON_API_KEY`

**Success status**: 201

**Response**: `application/json`

#### Parameters

| Field | Type | Required | Description |
| --- | --- | --- | --- |
| `sourceUrl` | `string` | Required | Allowed search CDN URL, trimmed maximum 2048 characters. |
| `attribution` | `{text?:string,url?:string}` | Optional | Recommended real source attribution; text≤200, http(s) url≤512. |
| `downloadLocation` | `string` | Optional | Original Unsplash downloadLocation, never fabricated. |

#### JSON request

Set the runtime variables before running. Refuse redirects and preserve errors.

##### curl

```sh
# POSIX shell; curl. Resource-id requests additionally require jq >=1.6.
(
set -eu
: "${ARAGON_BASE_URL:?Set ARAGON_BASE_URL}"; ORIGIN=$ARAGON_BASE_URL
: "${ARAGON_API_KEY:?Set ARAGON_API_KEY}"
printf "%s" "$ORIGIN" | LC_ALL=C grep -Eq '^https?://([A-Za-z0-9.-]+|\[[0-9A-Fa-f:.]+\])(:[0-9]{1,5})?$' || exit 2
url="$ORIGIN/api/v1/media/ingest"
work=$(mktemp -d)
trap 'rm -f "$work/body" "$work/headers"; rmdir "$work"' EXIT HUP INT TERM
payload=$(cat <<'ARAGON_JSON'
{
  "sourceUrl": "https://images.unsplash.com/photo-example",
  "attribution": {
    "text": "Example author / Unsplash",
    "url": "https://unsplash.com/@example"
  },
  "downloadLocation": "https://api.unsplash.com/photos/example/download"
}
ARAGON_JSON
)
status=$(curl --silent --show-error --max-time 600 -X POST "$url" \
  -H "Authorization: Bearer $ARAGON_API_KEY" \
  -H 'Content-Type: application/json; charset=utf-8' \
  --data-binary "$payload" \
  --dump-header "$work/headers" --output "$work/body" --write-out "%{http_code}")
case "$status" in 201) ;;
  *) cat "$work/body" >&2; printf "\nHTTP %s\n" "$status" >&2; exit 1 ;; esac
mime=$(awk 'tolower($1)=="content-type:" {$1=""; sub(/^ /, ""); print}' "$work/headers" | tr -d "\r" | tail -n 1 | cut -d ";" -f 1)
case "$mime" in application/json) ;; *) echo "Unexpected Content-Type" >&2; exit 1 ;; esac
cat "$work/body"
)
```

##### powershell

```powershell
# Windows PowerShell 5.1+; no automatic generation retries.
$ErrorActionPreference = "Stop"
$origin = $env:ARAGON_BASE_URL
if (-not $origin) { throw "Set ARAGON_BASE_URL" }
$parsedOrigin = [Uri]$origin
if ($parsedOrigin.Scheme -notin @("http", "https") -or
    $parsedOrigin.GetLeftPart([UriPartial]::Authority) -cne $origin -or
    $parsedOrigin.UserInfo) { throw "Expected a pure http(s) origin" }
if (-not $env:ARAGON_API_KEY) { throw "Set ARAGON_API_KEY" }
$path = '/api/v1/media/ingest'
$url = $origin + $path
$headers = @{ Authorization = "Bearer " + $env:ARAGON_API_KEY }
$json = '{"sourceUrl":"https://images.unsplash.com/photo-example","attribution":{"text":"Example author / Unsplash","url":"https://unsplash.com/@example"},"downloadLocation":"https://api.unsplash.com/photos/example/download"}'
$body = [Text.Encoding]::UTF8.GetBytes($json)
$parameters = @{
  Uri = $url
  Method = 'POST'
  Headers = $headers
  UseBasicParsing = $true
  MaximumRedirection = 0
  TimeoutSec = 600
  ErrorAction = "Stop"
  Body = $body
  ContentType = "application/json; charset=utf-8"
}
$response = Invoke-WebRequest @parameters
if ([int]$response.StatusCode -notin @(201)) {
  throw ("Unexpected HTTP " + $response.StatusCode)
}
$mime = ([string]$response.Headers["Content-Type"]).Split(";")[0].Trim()
if ($mime -notin @('application/json')) { throw ("Unexpected Content-Type: " + $mime) }
$result = $response.Content | ConvertFrom-Json
$result | ConvertTo-Json -Depth 30
```

##### python

```python
# Python 3; install requests separately. No automatic generation retries.
import json, os, tempfile
from pathlib import Path
from urllib.parse import urlsplit, quote
import requests
origin = os.environ.get("ARAGON_BASE_URL")
if not origin: raise RuntimeError("Set ARAGON_BASE_URL")
parsed = urlsplit(origin)
if (parsed.scheme not in ("http", "https") or not parsed.netloc or
        parsed.username or parsed.password or parsed.path or parsed.query or parsed.fragment):
    raise RuntimeError("Expected a pure http(s) origin")
key = os.environ.get("ARAGON_API_KEY")
if not key: raise RuntimeError("Set ARAGON_API_KEY")
path = "/api/v1/media/ingest"
headers = json.loads("{}")
headers["Authorization"] = "Bearer " + key
headers["Content-Type"] = "application/json; charset=utf-8"
payload = json.loads("{\"sourceUrl\":\"https://images.unsplash.com/photo-example\",\"attribution\":{\"text\":\"Example author / Unsplash\",\"url\":\"https://unsplash.com/@example\"},\"downloadLocation\":\"https://api.unsplash.com/photos/example/download\"}")
with requests.request("POST", origin + path,
        headers=headers, timeout=600, allow_redirects=False, stream=True, json=payload) as response:
    if response.status_code not in [201]:
        raise RuntimeError("HTTP %s: %s" % (response.status_code, response.text))
    mime = response.headers.get("Content-Type", "").split(";")[0].strip()
    if mime not in ["application/json"]:
        raise RuntimeError("Unexpected Content-Type: " + mime)
    result = response.json()
    print(json.dumps(result, ensure_ascii=False, indent=2))
```

##### node

```javascript
// Node.js >=22.5; save as an .mjs file. No automatic generation retries.
const origin = process.env.ARAGON_BASE_URL;
if (!origin) throw new Error("Set ARAGON_BASE_URL");
const parsedOrigin = new URL(origin);
if (!["http:","https:"].includes(parsedOrigin.protocol) ||
    parsedOrigin.origin !== origin || parsedOrigin.username || parsedOrigin.password)
  throw new Error("Expected a pure http(s) origin");
const key = process.env.ARAGON_API_KEY;
if (!key) throw new Error("Set ARAGON_API_KEY");
const path = "/api/v1/media/ingest";
const url = new URL(path, origin);
const headers = {};
headers.Authorization = "Bearer " + key;
headers["Content-Type"] = "application/json; charset=utf-8";
const response = await fetch(url, {
  method: "POST", headers, redirect: "error",
  signal: AbortSignal.timeout(600000),
  body: JSON.stringify({"sourceUrl":"https://images.unsplash.com/photo-example","attribution":{"text":"Example author / Unsplash","url":"https://unsplash.com/@example"},"downloadLocation":"https://api.unsplash.com/photos/example/download"}),
});
if (![201].includes(response.status))
  throw new Error("HTTP " + response.status + ": " + await response.text());
const mime = (response.headers.get("content-type") || "").split(";")[0].trim();
if (!["application/json"].includes(mime))
  throw new Error("Unexpected Content-Type: " + mime);
const result = await response.json();
console.log(JSON.stringify(result, null, 2));
```

**Response** (201)

```json
{
  "data": {
    "asset": {
      "id": "asset-example",
      "kind": "image",
      "mime": "image/png",
      "bytes": 1024,
      "width": 2048,
      "height": 2048,
      "durationMs": null,
      "url": "/api/v1/media/assets/asset-example",
      "title": null,
      "origin": "ingest",
      "createdAt": 1800000000000,
      "expiresAt": null,
      "attribution": {
        "source": "unsplash",
        "text": "Example author / Unsplash",
        "url": "https://unsplash.com/@example"
      }
    }
  }
}
```

<a id="quotas-errors"></a>
## Quota, errors, and retries

Preserve uncertainty and avoid duplicate paid submissions.

quota contains unit,dailyLimit,used,remaining,resetsAt. dailyLimit=0 and remaining=null mean unlimited. Quota resets at UTC midnight; display resetsAt in local time. Images count per image, videos per video, TTS per thousand JS string characters rounded up, search per call. Changing your own key does not bypass account quota. LLM errors and media errors have different envelopes; media errors carry error.code/message and sometimes field; internal_error can also occur.

Disable SDK/client automatic retries. Model/capability discovery, job GET and asset GET allow bounded retries. Search consumes quota: retry only after an explicitly recoverable rejection. Never blindly resend generation after a timeout, disconnect, 502/504 or submission_unknown; it may already be billed. Preserve request/job information, ask the user when another paid action is needed. Ordinary requests use a 600-second client timeout; requests timeout limits connect/read waits rather than an exact total wall clock. Stopping the local connection does not cancel upstream billing.

| HTTP | code | Description |
| --- | --- | --- |
| 400 | `invalid_request` | Correct message/field; do not repeat unchanged input. |
| 400 | `text_too_long` | Split according to live maxChars; each synthesis is metered. |
| 400 | `invalid_cursor` | Discard the cursor and restart the original search. |
| 400 | `no_credential` | Administrator probe only: configure a credential. |
| 400 | `confirm_required` | Administrator live test only: billing confirmation is required. |
| 401 | `authentication_error` | Check your gateway key and account status. |
| 403 | `capability_disabled` | Contact the administrator; repeated calls cannot enable this capability. |
| 403 | `tier_denied` | Ask the administrator to grant your account tier access. |
| 404 | `not_found` | Stop reading: missing, expired or unauthorized; never enumerate ids. |
| 409 | `job_already_finished` | Read the job and handle its existing terminal state. |
| 409 | `scope_changed` | Administrator quota scope changed; refresh before modifying. |
| 409 | `conflict` | Administrator configuration conflict; refresh and correct it. |
| 413 | `request_too_large` | Reduce JSON or inline-image size. |
| 413 | `asset_too_large` | Choose a smaller asset or output. |
| 413 | `storage_quota_exceeded` | Delete your unneeded assets or contact the administrator. |
| 415 | `unsupported_media` | Use a supported image, audio or video format. |
| 422 | `content_rejected` | Revise user content; never resubmit automatically. |
| 429 | `quota_exceeded` | Wait until quota.resetsAt or request an increased limit. |
| 429 | `too_many_inflight` | Wait for current work, then honor Retry-After. |
| 429 | `too_many_jobs` | Wait for existing video jobs to finish and retain their ids. |
| 429 | `upstream_rate_limited` | Honor Retry-After; generate again only after a confirmed pre-submission rejection. |
| 429 | `probe_throttled` | Administrator probe only: wait for Retry-After. |
| 502 | `upstream_unavailable` | The body carries retryable: true when the request never left the gateway (nothing was billed) and false when the provider already answered. Bounded read retries are allowed; never repeat uncertain generation. |
| 502 | `invalid_provider_response` | Preserve request/job information and contact the administrator. |
| 503 | `capability_not_configured` | Contact the administrator; this is not a client parameter error. |
| 503 | `capability_unavailable` | Refresh discovery and avoid frequent retries. |
| 503 | `egress_unavailable` | The body carries retryable: true when no request was handed to the tunnel. Contact the administrator about gateway egress. |
| 504 | `upstream_timeout` | Generation may be submitted; query the saved job, do not resubmit. |

| job.error.code | Description |
| --- | --- |
| `submission_unknown` | Retain the job id; submission and billing may have occurred. Stop polling this failed task. |
| `upstream_generation_failed` | Report the generation failure; let the user decide whether to create again. |
| `upstream_task_expired` | The upstream task expired; retain the id and report the terminal result. |
| `local_deadline_exceeded` | The gateway stopped waiting at its deadline; preserve the task information. |
| `asset_download_failed` | The generated result could not be stored; never fabricate an asset URL. |
| `invalid_provider_response` | The upstream task result was unreadable; retain the error and id. |

<a id="agent-skill"></a>
## Agent Skill installation

Install reusable knowledge and a private project connection in one step.

Open /console/install, choose Codex, Claude Code, Cursor or Generic, then generate and copy the instructions to your agent. The short-lived ticket creates a dedicated personal key; the installer verifies public artifacts and writes the skill, reference, runtime and project connection. Use --upgrade for verified unchanged earlier versions. Modified or unknown files are preserved as conflicts. Use --replace-credentials only for an explicit connection replacement. Installation runs discovery without paid generation. Generic agents must explicitly read SKILL.md.

connection.json schemaVersion 2 contains only public metadata, a fixed credentialsFile path and skill/reference/runtime/gitignore SHA-256 hashes. The private .local/credentials.json stores the baseUrl and personal key together. scripts/aragon.mjs reads this pair automatically, independent of cwd, and ignores conflicting environment variables. Corrupt private configuration fails closed. Secrets and recovery files are protected and Git-ignored; Windows requires native ACL support. Revoke connections on the Install page or in My credentials. Legacy installs without the local runtime may keep using ARAGON_BASE_URL and ARAGON_API_KEY, or upgrade from /console/install.
