# Models, Projects and Animation API

Revisions are retired: Save/API/Export do not generate, store or validate tokens. Do not send If-Match or expectedRevision. Legacy response revision fields are empty for client compatibility, and old export revision parameters are ignored. Writes remain authenticated, owner-scoped and serialized; the last successful Save replaces stored data. Export files use stable latest direction/clip URLs; explicitly prepare fresh output after editing.


## Model lifecycle and subscriptions

PIXAT uses monthly subscription quotas: Free 3 Models / 500 successful external API requests; Starter $3 or THB99 for 30 / 5,000; Creator $10 or THB330 for 100 / 20,000; Studio $20 or THB660 for 300 / 100,000. Existing Models can remain stored without a count cap. Creation and Clone consume one Model slot; deletion never refunds it. Image uploads and browser editing/Save/Export have no credit debit. Existing purchased credit balances remain preserved as legacy balances.

GET /api/subscription returns remaining Model/request quotas, plan, billing period and daily aggregate counts (Asia/Bangkok). Successful Bearer API requests consume one request; browser requests, quota reads, compatibility quotes, HEAD and exported-file downloads do not. Failed calls do not consume monthly requests, but admitted calls count toward per-minute limits. 429 exposes quota/rate/busy errors and Retry-After where applicable; batch related edits and avoid polling. No individual API request details are stored. See SUBSCRIPTIONS.md for policy and setup.

POST /api/models/credit-quote (or /api/v2/models/credit-quote) is retained for compatibility with cost:0, creation ID and token. Use creditModelId: quote.id for once-only creation retries and creditQuote: quote.token for old clients. Quota is enforced atomically on creation; deleted IDs cannot be reused. GET /api/credits is a compatibility quota response: balance means remaining Model slots, not credits. Atlas PUT returns credits.charged:0. Agents must never initiate Stripe subscription/upgrade/payment operations; the owner uses /account/subscription.

Export automatically saves browser edits without changing visibility or locking the Model. Owners can edit and export repeatedly in Draft, Public and Private. Clone/copy remains an independent editable Draft and consumes the recipient's Model quota. Retain ownership, asset-version and permission checks for every mutation. A failed transactional copy does not consume a slot; durable pending writes recover without creating twice.

## API v2 and asset compatibility

New Agent Models use `/api/v2/models` with `config.assetVersion: 2`: immutable atlas/Concept Art URLs, Part integer `rect` and optional RLE mask, without cropped Part `src`. See [Atlas-only asset contract](atlas-v2.md). Existing Rig document `version: 2` is independent of API/asset version. Model route tables below describe the legacy `/api/models` prefix; the same suffixes exist under `/api/v2/models` with identical auth/conflict rules. Full v2 writes require atlas-only assets. V2 reads also support legacy Models; use their legacy prefix for full writes unless explicitly converting. Legacy full reads/writes of an atlas-only Model return `409 asset_version_requires_v2`. Existing crop-image Models are not migrated automatically; Clone retains asset version.

Model data and write endpoints are account-scoped. Source-image GET/HEAD and the image catalog are public, independent of Model visibility. Browser clients use the PIXAT session cookie and CSRF header. AI clients obtain a 30-day Bearer access token and a persistent refresh token through the PKCE device authorization flow. Refresh tokens remain valid until the user revokes their connection. Never send or store either token in model JSON. AI writes and deletes require no revision. Requests and responses use JSON except atlas image upload. A model ID can be either the 32-character legacy ID or the 25-character short ID.

The user approves connections from Account → AI Agent after logging into PIXAT with Google. Reapproval of the same client ID and installation label reuses its existing grant; keep both stable across sessions and projects. PIXAT does not independently attest caller-supplied software/device names. Owners may explicitly merge legacy entries they identify as the same AI, including entries with old project-based client/device labels. Merging retains their exact client/grant bindings and existing tokens; revoking the merged entry invalidates all its linked access/refresh tokens together. Tokens can manage Models and Project folders, but cannot read profile data or manage account settings.

| Method | Path | Purpose |
| --- | --- | --- |
| `POST` | `/api/agent-auth/device` | Start PKCE device authorization with a caller-supplied `client_id` and optional `client_name` and `instance_name`. |
| `POST` | `/api/agent-auth/token` | Poll approval and exchange the device code and PKCE verifier for Bearer access and refresh tokens. |
| `POST` | `/api/agent-auth/refresh` | Exchange a refresh token for a new 30-day access token. The refresh token stays the same and remains valid until connection revocation. |
| `GET` | `/api/agent-auth/device-info?user_code=...` | Read the requesting AI name on the approval page. |
| `POST` | `/api/agent-auth/approve` | Owner approves or denies the pending request. |
| `GET` | `/api/agent-connections` | List account authorization grants. |
| `DELETE` | `/api/agent-connections/{connectionId}` | Revoke one connection and its active tokens. |

`/api/models` is the canonical Model route. `/api/projects` remains a legacy alias for Models; Project folders use `/api/project-folders`.

## AI Login and authorization

1. Generate a cryptographically random PKCE `code_verifier` (43–128 URL-safe characters) and compute `code_challenge = BASE64URL(SHA256(code_verifier))`.
2. Start with `POST /api/agent-auth/device` and `{ "client_id": "your-agent-id", "client_name": "Your AI Agent", "instance_name": "Optional device label", "code_challenge_method": "S256", "code_challenge": "..." }`. Use a stable ID for this AI integration, identify the runtime accurately, and use `instance_name` to distinguish installations. Do not assume a fixed list of AI providers.
3. Ask the user to open the returned `verification_uri`, Login to PIXAT with Google, and approve the named AI.
4. Poll `POST /api/agent-auth/token` with the returned `device_code` and original `code_verifier`, respecting `interval`, until approved or expired.
5. Keep both returned tokens in an approved secure secret store. On Windows, the PIXAT Skill helper uses Windows Credential Manager and refreshes access tokens automatically. Never put tokens in model files. Revocation removes access and refresh credentials for only that connection immediately.

## Project folders

A Model is the existing character/rig/animation document. A Project is an account-private folder containing many Models. Each Model is unfiled or belongs to one Project. Existing Model IDs, JSON and Studio URLs are preserved. Membership is stored separately from rig JSON. Project folders do not inherit/publish permissions; visibility and Export Sprite / Clone Model remain per Model.

| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/project-folders` | List folders: `projects: [{id,name,revision,modelIds,modelCount,created_at,updated_at}]`. |
| `POST` | `/api/project-folders` | Create an empty Project with `{ "name": "..." }` (1–80 characters); returns `id` and `revision`. |
| `PATCH` | `/api/project-folders/{projectId}` | Rename with `{ "name": "..." }`. AI writes need no revision. |
| `DELETE` | `/api/project-folders/{projectId}` | Delete only the folder. Models remain unfiled; no Model assets are deleted. AI writes need no revision. |
| `GET` | `/api/models/{modelId}/project-folder` | Read membership: `{modelId,projectId,revision}`; revision is the Model revision. |
| `PUT` | `/api/models/{modelId}/project-folder` | Move with `{ "projectId": "folder-id" }`, or null to unfile. Owner only; AI writes need no revision. |

`GET /api/models` returns `models` (with `projects` retained as a compatibility alias); each Model has its folder `projectId` or null. `POST /api/models` accepts optional `projectId`; omitting it preserves membership on an overwrite. Owner reads include membership; visitor responses do not expose folder details. Owner Clone accepts optional `projectId` and otherwise inherits the source folder. Copies from other accounts start unfiled. Canonical Clone/copy responses use `modelId` for the created Model, `projectId`/`folderId` for its folder, and `url` for Studio. Legacy `/api/projects/{id}/clone` or `/copy` retain their old `projectId` meaning (the created Model); use `/api/models` for new clients. The legacy `sourceProject` provenance field still refers to a source Model and is preserved for compatibility.

Examples: create a Project folder, then create multiple Models with its `projectId`. Open `/studio?projectId={projectId}` to create a Model in that Project. Open `/studio/{modelId}` to edit, or `/studio-agent/{modelId}` for the visible live preview.

## Public source images

Validated Concept Art, atlas and mapped Part crops are copied to `/uploads/model-images/{imageId}.{png|webp|jpg}` and served directly by the web server with `Cache-Control: public, max-age=31536000, immutable`. Image IDs are 64 hexadecimal characters: normal uploads use the content hash, while new Clone/copy operations hash the new Model ID together with image bytes to create physically separate files. A Clone rewrites every saved raster source and atlas slot to its own copy, including images embedded in legacy configs. No image read requires an account, Bearer token, CSRF, publication permission or MySQL connection. Model GET/POST/PUT responses provide an `images` catalog; upload responses provide `url`. Old images are materialized on first Model read or legacy image request. API v2 persists atlas/Concept Art URLs and rect/mask metadata without cropped Part src or individual Part download files; see the atlas-only contract above. Visibility and usage permissions continue to control Model JSON/Clone/exports, not image bytes. Successful image replacement/removal releases prior files when no saved Model, private atlas slot, unmigrated legacy config, pending credit write or saved checkpoint references them. This cleanup applies to subsequent writes and does not sweep historical orphan files or migrate existing Clones.

## Models

| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/models` | List this account's models. Response has `models: [{id,name,description,projectId,updated_at,size}]` (and legacy `projects` alias). |
| `POST` | `/api/models` | Create a model, or save over an existing model when `id` is supplied. Body: `{ "name": "...", "description": "...", "config": { ... } }`. |
| `GET` | `/api/models/{id}` | Read full model config, current revision and `updated_at` (UTC ISO timestamp of the last saved model change, including animation or atlas writes). |
| `GET` | `/api/v2/models/{id}/preview` | Studio Agent preview config/images; owners can read any status, nonowners (including anonymous) can read Public only. Returns `readOnly: true` for nonowners. Supports both asset versions. |
| `PUT` | `/api/models/{id}` | Replace full model config. Body: `{ "name": "...", "config": { ... } }`. |
| `PATCH` | `/api/models/{id}` | Change just `name` and/or `description`, without replacing animation or rig data. |
| `DELETE` | `/api/models/{id}` | Delete model and its server-side atlas assets. |
| `POST` | `/api/models/{id}/clone` | Clone an owned model into a new independent Draft, including its animation and image assets. No revision is required. |
| `GET` | `/api/models/{id}/atlas/{direction}` | Read the PNG/WebP source atlas without login; redirects to its immutable public image URL. |
| `PUT` | `/api/models/{id}/atlas/{direction}` | Upload or replace that direction's PNG/WebP source atlas; response includes a public `url`. Accepts an owner-scoped AI Bearer token or an owner session with CSRF protection. |
| `DELETE` | `/api/models/{id}/atlas/{direction}` | Remove that direction's source atlas reference/original; previously published hash URLs remain cached/public. Accepts an owner-scoped AI Bearer token or an owner session with CSRF protection. |
| `GET` | `/api/models/{id}/concept-art` | Public Concept Art image redirect; no login required. |
| `GET` | `/api/models/{id}/images` | Public image-only catalog: `conceptArt`, `atlases[direction]`, `parts[direction][partId]`. |
| `GET` | `/api/models/{id}/publication` | Read visibility, Clone permission, always-enabled Export and revision for an owned Model. |
| `PUT` | `/api/models/{id}/publication` | Set visibility and Clone permission; returns the new revision. |
| `PATCH` | `/api/models/{id}/publication` | Update only supplied settings without If-Match; preserve visibility when omitted. |
| `POST` | `/api/models/{id}/copy` | Copy another owner's public model when `copyTemplate` is enabled. Requires a signed-in account session; uses one monthly Model slot. |
| `GET` | `/api/project-analytics` | Read the authenticated account's 30-day activity chart, per-project counts, lifetime copies, and recent copy recipients. |

Visibility statuses are draft, public and private. Owners can edit and export in all statuses. Draft and Private are owner-only; Public permits nonowner viewing. Legacy Unlisted normalizes to Private. Export is always enabled for viewers; only copyTemplate is a configurable visitor permission. Owners always retain Export and Clone access.

Analytics are owner-scoped. Activity totals and daily series include views, play starts, Sprite exports, Animation exports, and copies. View/play/export totals and daily series cover the latest 30 days; copy totals and recipient history are lifetime values. Recipient records contain display name, date, and copied model ID, but no email. Views count actions, not unique visitors.

The publication `PUT` body is `{ "status": "public", "permissions": { "exportSprite": true, "copyTemplate": true } }`. Status determines visibility without locking edits. `exportSprite` is always true for viewers (legacy false inputs are ignored); `copyTemplate` permits a copy into another account (one Model slot). Owners can export and Clone (one Model slot) regardless of outsider permissions. No marketplace price or resale field is used. No revision is required. Rig/Animation edits and Export are free; the retired `/purchase` route still returns HTTP 410.

`POST /api/models/{id}/clone` is owner-only. It creates a new Draft with a distinct model ID and copies the source config, animation sidecar and source image originals. No revision is required for AI requests. For another owner's public model, `/copy` requires a signed-in account session and the current `copyTemplate` permission; it currently rejects Agent Bearer tokens. Copies retain source attribution and use one monthly Model slot. Owner-only `/clone` supports Agent Bearer credentials and returns `modelId`, folder `projectId`, `revision` and `url`.

Model `config` uses the PIXAT Parts Rig JSON format (`format: "pixat-parts-rig"`, version 1 or 2). Keep unknown fields when editing it so rig and atlas data are preserved. A `PATCH` is preferred for model metadata edits.

### New custom Rig models

Create new work with `modelType: "custom-rig"`. This model starts with no Basic Human Nodes or built-in image Paths. Define each Node and Path in `customNodes` and `customPaths`; both Path endpoints must be Nodes in the custom Node list. A connection point is the shared anatomical pivot/attachment where two independently mapped pieces meet and move together, not an arbitrary crop edge. Reuse one Node ID in both pieces' `bones` and `pathNodeOrder`; set each Path's corresponding `connectionPaths` entry to the Path that owns that endpoint Node. Entries in `connectionPaths` match `connections` by index. Crop-local positions can differ, but the shared Node has one canvas-space Rig position so both pieces meet. Derive the joint graph from the creature's actual anatomy and intended movement, not a fixed human template; for example, a dragon may need wing-root/joints and tail segments, while an elephant may need a trunk-root and flexible trunk-bend chain. For human-proportioned characters with separate limbs, put anatomical left/right shoulder and hip attachments in the torso part and reuse them as the arm/leg endpoints. Recalculate all canvas coordinates independently from each direction's artwork while keeping the same logical anatomical Node IDs; do not mirror or reuse front-view positions blindly. New-model Animation data must use only those custom Node IDs. Clones retain their source model type, Nodes, Rig, and Animation.

```json
{
  "modelType": "custom-rig",
  "customPaths": [{"id":"path-head","name":"Head","connections":["node-neck","node-crown"],"connectionPaths":["path-head","path-head"]}],
  "customNodes": [
    {"id":"node-neck","pathId":"path-head","name":"Neck","parent":null,"beforeNode":null,"branch":false,"ratio":0.5},
    {"id":"node-crown","pathId":"path-head","name":"Crown","parent":"node-face","beforeNode":null,"branch":false,"ratio":0.5},
    {"id":"node-face","pathId":"path-head","name":"Face","parent":"node-neck","beforeNode":"node-crown","branch":false,"ratio":0.5}
  ],
  "configurations": {"custom-rig": {"front": {"rig": {
    "node-neck":{"x":128,"y":176},"node-face":{"x":128,"y":128},"node-crown":{"x":128,"y":80}
  }}}}
}
```

Weapons, armor, and wearable gear can be mapped as additional image Paths attached to the character's anatomical Rig. Align a weapon's grip with the hand Node, armor with its actual body contact points, and multi-point gear with real secondary anchors/branch Nodes. Reuse body Node IDs at shared joints and use `connectionPaths` to identify their owning Paths. Measure equipment-local bone positions inside its crop and the shared Rig positions separately for every direction. By default, let attached gear inherit movement from its host body Node and do not author separate gear animation unless requested. Validate attachment alignment and layer order in all configured views. The API does not simulate equipment physics or provide inventory slots or equip/unequip runtime behavior.

Rig mapping checklist for each configured direction:

1. Inspect that direction's atlas and identify independently moving image pieces. Define one custom Path per image piece; do not assume Basic Human's six parts.
2. Design the skeleton to match the character. Use stable `node-...` IDs, and put every Node in `customNodes` with its owning `pathId`. Each Path's `connections` contains exactly two endpoint IDs, and both endpoint Nodes must be included in `customNodes`. Reuse one Node ID where adjacent image pieces meet at the same anatomical joint; include it in both pieces' local bone maps and identify its owning Path in `connectionPaths`. Root Nodes use `parent: null`. For an ordered chain, each internal Node's `parent` is the preceding Node and `beforeNode` is the following Node. Keep parent references topologically ordered.
3. Map each cropped part in `configurations.custom-rig[direction].parts[pathId]`. Store its image `src`, `width`, `height`, `pivot`, `offset`, atlas `rect`, local `bones`, `skin`, and `pathNodeOrder`. `bones` maps every Node ID along that Path to `{x,y}` in pixels relative to the crop's top-left. Keep source transparency and crop offsets aligned.
4. In `configurations.custom-rig[direction].rig`, map the exact same Node IDs to `{x,y}` positions in full-canvas pixels. Coordinates use the frame's top-left as origin. Include every Node used by that direction and a matching `parents` map; use `null` for roots. Preserve Node topology between views but measure each direction's coordinates separately.
5. Before creating Animation, verify all Path endpoints and parent references resolve, each part's `bones` covers its `pathNodeOrder`, every Rig Node has a canvas position in every configured direction, and there are no duplicate IDs or parent cycles. Save and reread the model. Then call `GET /api/models/{id}/animations` and confirm that `nodeIds` contains the new Nodes only.

The two coordinate maps are deliberately different: `parts[pathId].bones[nodeId]` is local to the cropped image, while `rig[nodeId]` is on the direction's animation canvas. They refer to the same Node IDs and must line up when the part is assembled.

Atlas upload accepts the raw image bytes as the request body, with `Content-Type: image/png` or `image/webp`; the image must be at most 25 MB and 16 megapixels. Requests are account-scoped and accept the 30-day Bearer access token or an owner session with CSRF protection. Read saved source bytes from atlas PUT's public `url` or Model GET's `images.atlases[direction]`. Legacy `GET /api/models/{id}/atlas/{direction}` redirects to `image/png` or `image/webp`, not JSON, with no authentication or database lookup. Studio retrieves this public source atlas when opening the model or selecting that direction, so its Mapping step appears even when the config only contains mapped part crops. Mapped part crops, bone positions, parent links, and skin data are stored in the model `config` through `PUT /api/models/{id}`. The API has eight direction keys but no dedicated `enabledDirections` or direction-count property yet; model APIs can store per-direction data, but this does not hide unused directions in Studio.

## Animation node list

Animation endpoints use arrays of Nodes so external tools can address each node explicitly. Supported directions are `front`, `front-right`, `right`, `back-right`, `back`, `back-left`, `left`, and `front-left`. Existing models may use `human-basic`; new models should use `custom-rig`, which has no implicit standard Nodes. Supported Node IDs are returned as `nodeIds` by the list endpoint and are scoped to the model's model type and custom Nodes.

| Method | Path | Purpose |
| --- | --- | --- |
| `GET` | `/api/models/{id}/animations` | Read animation data in Node-list form for every saved direction. |
| `PUT` | `/api/models/{id}/animations/{direction}/custom` | Replace custom keyframes for one direction. |
| `PUT` | `/api/models/{id}/animations/{direction}/idle` | Replace idle node overrides for one direction. |
| `PUT` | `/api/models/{id}/animations/{direction}/walk` | Replace walk node overrides for one direction. |
| `PUT` | `/api/models/{id}/animations/{direction}/run` | Replace run node overrides for one direction. |
| `PUT` | `/api/models/{id}/animations/{direction}/clips` | Replace named editable keyframe clips for one direction. |

Custom animation request:

```json
{
  "fps": 12,
  "frames": [
    { "frame": 0, "nodes": [
      { "id": "node-root", "x": 0, "y": 0, "rotation": 0, "scaleX": 1, "scaleY": 1 },
      { "id": "node-mid", "x": -4, "y": 12, "rotation": 18, "scaleX": 1, "scaleY": 1 }
    ]},
    { "frame": 12, "nodes": [
      { "id": "node-root", "x": 0, "y": 0, "rotation": 0, "scaleX": 1, "scaleY": 1 },
      { "id": "node-mid", "x": 3, "y": 2, "rotation": -12, "scaleX": 1, "scaleY": 1 }
    ]}
  ]
}
```

Custom frame numbers are integers from 0 through 24. At most 25 frames and 100 Nodes per frame are accepted. `human-basic` accepts its standard skeleton IDs plus model custom Nodes; `custom-rig` accepts only custom Node IDs defined by that model. The `nodeIds` response lists valid IDs and `transformFields` lists `x`, `y`, `rotation`, `scaleX`, `scaleY`, `opacity`, `brightness`, `saturation`, `hue`. Transforms use parent-local offsets in canvas pixels for `x/y` (canvas-space for roots, ±4096), clockwise degrees for `rotation` (Z-only, ±36000), and positive multipliers for `scaleX/scaleY` (0.1–8). Rotation/translation default to zero and scales to 1. Legacy `rotationX/rotationY` are ignored and omitted on explicit writes; preview, thumbnails and exports always use planar Z rotation. Do not send them. `rotationZ` and `z` are not supported fields. Sending an empty `frames` array clears custom keyframes.

Use parent-local translation and positive scale for projected front/back foot lift and motion toward/away from the viewer. The renderer does not tilt flat images, calculate depth from X/Y angles or reorder Paths by depth. Saved `layerOrder` remains authoritative. This does not synthesize missing palm, sole or side artwork.

For character animation, combine `rotation`, parent-local `x/y` and positive `scaleX/scaleY` according to the viewing direction. Side-view motion within the image plane can use constant-length rotational chains; front/back foot lift often needs translation and projected segment shortening, and diagonal views combine both. There is no rotation-only rule. Anatomical limb length can stay stable while its projected 2D length changes. Keep a transform entry for every active Node on each authored frame and ensure each visible part moves through its parent or purposeful local transforms. Scale propagates to descendant offsets; derive local translations after inherited rotation/scale to avoid counting a lift twice. For human-like joints, preserve natural flexion and avoid hyperextension; a projected front/back 2D angle is not the anatomical 3D joint angle. Review texture deformation and equipment attachment as well as Node positions. Frame data does not simulate physics or synthesize missing visible surfaces.

For built-in `idle`, `walk`, and `run`, send `{ "fps": 12, "nodes": [...] }`. These are per-node transform overrides layered on the built-in motion, not a custom sequence of frame keys. An empty `nodes` list clears overrides for that direction and built-in animation.

Named keyframe clips can use project-specific names such as `jump`, `die`, or `explorer`, or replace built-in `idle` and `run` for a particular model. Send `{ "animation": "jump", "clips": { "jump": { "fps": 12, "frames": [...] } } }` to create `jump` and select it. The `clips` object replaces the complete named-clip set for the selected direction, so include any existing clips that should be preserved. Each clip supports up to 25 keyframes numbered 0–24, and each keyframe uses the same Node-list format as `custom`. Clip names must start with a lowercase letter and may contain lowercase letters, numbers, underscores, or hyphens (up to 32 characters). The selected `animation` is optional and may be `bind`, `idle`, `walk`, `run`, `custom`, `die`, `explorer`, or a saved clip name included in the submitted `clips` object. Each clip retains its own FPS, optional `frameCount`, and editable timeline in Parts Rig.

The animation-list response has this shape:

```json
{
  "id": "project-id",
  "revision": "...",
  "modelType": "custom-rig",
  "nodeIds": ["node-root", "node-mid", "node-tip"],
  "directions": {
    "front": {
      "animation": "custom",
      "fps": 12,
      "frames": [{ "frame": 0, "nodes": [{ "id": "node-root", "x": 0, "y": 0, "rotation": 0, "scaleX": 1, "scaleY": 1 }] }],
      "overrides": { "walk": [{ "id": "node-mid", "x": 0, "y": 0, "rotation": 10, "scaleX": 1, "scaleY": 1 }] }
    }
  }
}
```

Read Model/Animation data once before editing. Save without If-Match or expectedRevision. Do not poll or call revision endpoints; refresh the visible Studio Agent once after API saves.

Each direction in the animation-list response may also include a `clips` object. A clip contains its own `fps`, optional `frameCount`, and `frames`; frames use Node arrays like the custom animation response above.

## Agent authoring contract (Skill 1.45.0)

After model authoring, open `/studio-agent/{modelId}` to inspect Rig and realtime Animation previews using the shared Studio renderer. After each successful API write, click its header ↻ button once to load the saved result, or reload the same tab when there is no manual draft. Owners can manually drag existing mapped Nodes and explicitly Save or discard all local drafts; manual refresh is disabled while dirty, and Save uses `If-Match` to reject concurrent changes. Browser writes that supply `If-Match` receive the same revision conflict checks as AI writes. Agents still read and author data through this API. The page has no Model JSON panel or command console. Select direction/Animation in its gallery and use URL parameters for bone overlays or paused-frame inspection; see [Studio Agent preview guide](studio-agent-commands.md). Account and normal Studio redirect unsigned visitors to `/login` and return to the requested page after sign-in. Studio Agent allows unsigned/nonowner viewers of Public Models to select directions/clips in read-only mode; Draft, Private and Unlisted previews return 404 for nonowners. Its full preview request is `GET /api/v2/models/{id}/preview`, which returns readOnly: false for owners and readOnly: true for nonowners on every explicit load. Normal Studio remains the signed-in full interactive editor with export tools. All mutations remain owner-scoped.

For authored running clips, read [Reproduce a smooth running cycle](run-cycle.md). It records the calibrated side-view contact/IK/rotation workflow, front/back and diagonal projected poses using translation/scale, and per-character, per-direction visual acceptance checks. Example humanoid parameters and planar IK constraints do not apply universally to every view.

For Z rotation and projected movement, read [Z-only rotation and projected movement](depth-rotation.md). It explains legacy X/Y compatibility and front/back foot lift using translation/scale. Preserve equipment attachment, ground contact and surface identity.

For original character art and missing direction atlases, read [Concept Art to direction parts](concept-to-directions.md). The Skill stores original image data/hash in `config.conceptArt` and optional provenance in `config.directionSources` through normal model POST/PUT. These are preserved config conventions, with no dedicated Concept Art upload/generation endpoint or Studio control. Image generation uses the Agent's image tool; resulting atlases use the existing direction atlas API. The full JSON request and saved config each have an 80 MiB limit, including embedded image data and serialization overhead.

Read [Rig mapping and animation authoring](rig-and-animation.md) for staged New Model creation, crop fields, torso attachment branches, bind-coordinate assembly and the renderer's local-transform equations. `customNodes`/`customPaths` are JSON lists. The server rejects duplicate IDs, unknown owning Paths, invalid endpoints/owners, parent cycles, incomplete Rig positions and mapped main chains that disagree with parents; valid Nodes are canonicalized parent-first. Every owned branch attachment must be present in its owning crop's `bones`, while `pathNodeOrder` contains only the main deformation chain. Atlas upload does not create these mappings.

Before mapping, the Agent must inspect anatomical artwork boundaries: the torso reaches the shoulder sockets, each arm starts there and owns its moving sleeve/upper arm, and other pieces meet at their actual neck/hip/grip attachments. Use concealed seam overlap without duplicate visible anatomy. Rectangular crops and Node alignment alone cannot fix an arm stub painted into the torso. These are Skill authoring checks; the API does not validate image anatomy.

Mapped crop data URLs must encode valid PNG/WebP bytes with matching width/height; pivot and offset coordinates must be finite. Unknown bind Node IDs are rejected.

AI atlas upload/delete must target an existing owned model and do not require If-Match. Revision checks are disabled. GET atlas follows a public redirect to raw binary; download direct image URLs without credentials. Windows clients can use `Invoke-WebRequest -Uri ('<PIXAT_ORIGIN>' + $imageUrl) -OutFile '<image.png>'`.

For new `custom-rig` models, author walking/running through named `clips.walk`/`clips.run`. Static `/walk` or `/run` overrides do not create a gait on an arbitrary custom skeleton. Named clips bypass Basic Human's preset motion entirely. Frame numbers and FPS must be integers. When `frameCount` is omitted, playback/export use the last authored frame N, not the editor limit of 24. An identical closing frame N is retained for editing but omitted from playback/export, yielding N samples; otherwise N+1 samples play. For example, closing frame 12 gives a 0.4 s loop at 30 FPS; closing frame 24 gives a 0.8 s loop. Shorter clips do not hold their final pose until frame 24. The `/clips` writer replaces only that direction's named clips; preserve existing clips explicitly. If an active arbitrary clip is removed without specifying another selection, selection returns to `bind`.

### Set animation length (`frameCount`)

Set `frameCount` to an integer **1–25** to control playback and export length explicitly, independently of the current frame and keyframe count. At 30 FPS, `frameCount: 12` plays frames **0–11** for **0.4 seconds**. The number of stored keys does not change this value.

- Named clips: send `frameCount` inside each clip in the complete `/animations/{direction}/clips` collection, alongside `fps` and `frames`. Internal config uses `animationClips[name].frameCount`.
- Custom: send `frameCount` alongside `fps` and `frames` to `/animations/{direction}/custom`; config stores it on the direction.
- Presets: send `frameCount` alongside `fps` and `nodes` to `/animations/{direction}/{idle|walk|run}`; config stores `animationFrameCounts[name]`. This setting changes a full preset cycle's duration to count/FPS. It does not override a named clip with the same name.
- Full config/bulk `/animation` preserve direction `frameCount`, `animationFrameCounts`, and named clip `frameCount`. GET `/animations` and GET `/animation` return saved length fields. Omit them to retain the legacy inference behavior; named clips never inherit another clip's length.
- For a loop, an optional closing key at `frameCount` (within index 0–24) is retained for interpolation and can be inspected with Studio's current-frame input, but is not an extra playback/export sample. Match it to frame 0 for a seamless seam. Keys beyond that boundary stay saved, are hidden from the active timeline, and do not influence the active clip; expanding length exposes them again. Changing length does not retime keys.
- Normal Studio has a separate **จำนวนเฟรม** input and **เฟรมปัจจุบัน** input. Save the Model to persist the chosen length. Preview and both exports honor it; large sprite sheets use multiple rows to retain every frame. Bind remains one static frame.

For a 12-frame Run, use this shape (include the complete existing clip collection and actual Node poses):

```json
{"animation":"run","clips":{"run":{"fps":30,"frameCount":12,"frames":[{"frame":0,"nodes":[]},{"frame":12,"nodes":[]}]}}}
```

The legacy bulk `/animation` endpoint uses internal map-form `keyframes`/`animationClips` (not the Node-list `frames` form) and validates frame/FPS/Node transforms. Its model type must match the model's Rig. Prefer the documented direction-specific Node-list endpoints for agent writes. Full model PUT replaces all config and animation data: GET the current merged config before modifying and keep all unrelated directions and clips.

The helper logs safe request metadata and request IDs to `%LOCALAPPDATA%/PIXAT/logs`. It supports `-IfMatch` and `-OutputFile`, refreshes saved credentials, and never writes tokens into model files.

## Private export download URLs

`GET /api/models/{id}/exports/{direction}/{animation}` returns the current revision, `files: [{filename,url,contentType,bytes,sha256}]` and `prepareUrls: {sprite,webm}`. It lists cached output for the saved Model; it does not render on the server. Open a returned preparation URL in a signed-in Studio Agent browser to render through the shared Studio renderer and store the output once. See [Agent export/download workflow](export-download.md).

File GET/PUT endpoints append `/sprite.png`, `/sprite.json`, or `/animation.webm` to that manifest path. GET returns raw bytes with attachment filename, private/no-store caching and owner/device authentication. URLs are stable and have no revision parameter. Missing current output returns `404 export_not_ready`; legacy revision parameters are ignored.

The renderer uploads raw bytes with session CSRF or an owner device token. No revision token is required. PNG/WebM limits: 64 MiB; metadata: 64 KiB. Storage returns a stable URL, bytes and SHA-256. Artifacts are private per owner/Model/direction/clip; each generated file replaces the previous file.

Publication updates do not require revisions. PATCH accepts partial permission changes and preserves omitted values. Ownership/visibility checks and Model quota rules remain unchanged.

### Keyframe colour and visibility

Animation Node transforms also accept `opacity` (0–1, default 1), `brightness` (0–2, default 1), `saturation` (0–2, default 1), and `hue` (-180–180 degrees, default 0). These fields work in frame Node lists, overrides, named clips and bulk Studio animation writes, and are returned in `transformFields`. Missing fields retain the neutral defaults for older Models.

Values interpolate linearly between a Node's authored keys. Set `opacity: 0` to hide its Part, `saturation: 0` for greyscale, or `brightness: 1.5` to brighten. To hide for a whole interval, author opacity 0 at both interval boundaries; use adjacent frames for an abrupt hide/show. For example: `{"id":"node-root","opacity":0,"brightness":1,"saturation":1,"hue":0}`.

Each Node affects the entire Part whose mapped bone list includes it (including branch Nodes). Within that Part, opacity, brightness and saturation multiply across its Nodes; hue angles add. Shared mapped Nodes affect each Part that includes them. Appearance does not inherit through external parent links: hide separate child Parts explicitly. Prefer a single unshared Node per Part for colour/visibility keys. Effects apply to Studio/Agent previews, thumbnails and animation exports, without modifying source artwork or masks. API values use multipliers; Studio displays opacity, brightness and saturation as percentages.
