# PIXL Studio Engine and BASE44: Integration Guide

Nov 16, 2026 · @רן

## 1. Overview

The PIXL Studio engine is live and implements brief v1.0 field for field; BASE44 connects to it at two touch points and calls one HTTPS API. This guide is the complete contract for the BASE44 side. Where it adds to `PIXL-STUDIO-BASE44-BRIEF.md` (v1.0), this guide wins, and every addition is backward compatible.

**Who does what**

- **BASE44 (the shell):** all screens, the entities the customer sees, credits (the existing atomic deduction), and three backend functions: `studioToken`, `studioWebhook`, `studioApprovalView`.
- **Engine (the private server):** the agent, the gates, rendering, media providers, file storage, and the project state machine. It never touches BASE44 entities directly.

**The two touch points**

1. **Browser to engine:** the frontend calls the engine API through `components/studio/engine/engineClient`, with a 15 minute JWT from `studioToken` in the `Authorization` header. Live updates come over one server sent events stream per project.
2. **Engine to BASE44:** the engine calls `studioWebhook` with signed JSON for every change the shell must store: project state, reviews, assets, credits, delivery, failure. For `credits.reserve` it waits for the answer.

&#91;embedded content: architecture · 3 parts, 4 connections\]

The browser talks to the engine with a token from BASE44; the engine reports back only through studioWebhook.

**What is new since brief v1.0**

| Area | Addition | Section |
| --- | --- | --- |
| Voices | `GET /v1/voices`: the Hebrew catalog, 50 male and 50 female voices, each with a demo sample | 9 |
| Fonts | `POST /v1/fonts` checks an uploaded font file and stores it for the brand | 9 |
| Characters | `POST /v1/characters` returns four proposals, then the identity sheet | 9 |
| Brand | `POST /v1/brands/extract` returns name, palette, font and logo from a website | 9 |
| Connection tests | `GET /v1/handshake` and `POST /v1/handshake/webhook` for the admin console | 11 |
| Projects | `POST /v1/projects/:id/retry` continues a failed project from the same stage | 4 |
| Webhooks | `project.failed` carries `failReason`; `review.created` carries `engineReviewId` | 6 |

## 2. Connection settings

Three values connect the two sides, and the secrets are already in place on both: only `engineUrl` changes when the engine moves to its final domain.

| Setting | Where | Value |
| --- | --- | --- |
| `engineUrl` | `StudioSettings.engineUrl` (entity, not a secret) | `https://studio.pixl.co.il` (live since 16 November 2026, behind Cloudflare; the temporary `https://studio-pixl.169-58-89-179.sslip.io` still answers during the switch) |
| `STUDIO_JWT_SECRET` | BASE44 Secrets page and the engine `.env` | Same value on both sides (already set) |
| `STUDIO_WEBHOOK_SECRET` | BASE44 Secrets page and the engine `.env` | Same value on both sides (already set, verified: a wrong signature gets 401) |
| Webhook URL | Engine `.env` | `https://visual-israel-create.base44.app/functions/studioWebhook` |

**Browser origins (CORS).** The engine answers browser calls from `https://pixl.co.il`, any `*.pixl.co.il`, and any `*.base44.app` origin, which covers the BASE44 editor preview. Opening CORS this wide is safe because every call still needs a token signed with `STUDIO_JWT_SECRET`. A call from an unlisted origin fails in the browser with a CORS error, not with an API error.

**Mock mode.** While `StudioSettings.mockMode` is true, `engineClient` uses its mock adapter and never calls the engine. Turning it off needs no code change: the real adapter reads `engineUrl` and calls the API in section 4.

**Never in the browser:** the two secrets, any provider key, any credit write. The browser holds only the 15 minute token from `studioToken`.

## 3. Authentication: studioToken

Every engine call carries `Authorization: Bearer <token>`, a JWT signed HS256 with `STUDIO_JWT_SECRET` and valid for 15 minutes; the engine rejects anything else with 401.

**The function.** `studioToken` is called by the signed in frontend with `{ projectId }`, where `projectId` is the BASE44 `StudioProject` id, or `""` for calls not tied to a project (estimate, preview, voices, fonts, characters, brand extract). It checks that the user is allowed by `StudioSettings` and owns the project (or is admin), then returns `{ token, expiresAt, engineUrl }`.

**Claims the engine checks**

| Claim | Value | Engine rule |
| --- | --- | --- |
| `iss` | `"pixl-base44"` | Must match exactly |
| `sub` | The BASE44 user id | Owner of the projects this user creates |
| `pid` | The BASE44 project id, or `""` | If not empty, the token works only for that project |
| `role` | `"user"` or `"admin"` | Admin reads and acts on every project |
| `iat`, `exp` | Seconds since epoch, `exp = iat + 900` | 30 seconds of clock skew allowed |

The header must be `{"alg":"HS256","typ":"JWT"}`. Sign with Web Crypto (HMAC SHA-256) over `base64url(header) + "." + base64url(payload)`, with base64url without padding. No external library.

```javascript
// studioToken: the signing part
const enc = new TextEncoder();
const b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
const now = Math.floor(Date.now() / 1000);
const header = b64url(enc.encode(JSON.stringify({ alg: "HS256", typ: "JWT" })));
const payload = b64url(enc.encode(JSON.stringify({ iss: "pixl-base44", sub: user.id, pid: projectId || "", role: isAdmin ? "admin" : "user", iat: now, exp: now + 900 })));
const key = await crypto.subtle.importKey("raw", enc.encode(Deno.env.get("STUDIO_JWT_SECRET")), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const sig = b64url(await crypto.subtle.sign("HMAC", key, enc.encode(`${header}.${payload}`)));
return { token: `${header}.${payload}.${sig}`, expiresAt: new Date((now + 900) * 1000).toISOString(), engineUrl: settings.engineUrl };
```

**Rules for engineClient**

- Cache one token per `projectId`, and refresh it one minute before `expiresAt`.
- Use a project bound token (`pid` set) for every `/v1/projects/:id/...` call, and an unbound token (`pid: ""`) for the rest.
- On 401 with code `token_expired`, refresh once and retry the call once.
- The event stream sends the token in the header, never in the URL (section 5).

## 4. Engine API reference

All calls go to `engineUrl`, send and receive JSON, and carry the bearer token from section 3; `:id` accepts either the `engineProjectId` or the BASE44 project id. A machine readable spec is served at `GET /v1/openapi.json`.

### Projects

| Call | Body | Answer |
| --- | --- | --- |
| `POST /v1/projects` | `{ projectId, mode, order, brandKit }` | 201 `{ engineProjectId, stage }`. Calling it again with the same `projectId` returns the same project (safe to retry) |
| `GET /v1/projects/:id` | none | `{ engineProjectId, projectId, stage, status, failReason, planSummary, assets, costs: { estimate, reserved, charged }, pendingReview, finalUrl, thumbUrl }` |
| `POST /v1/projects/:id/messages` | `{ text, attachments: [{ url, name, kind }], sceneRef }` | 202 `{ accepted: true }` |
| `GET /v1/projects/:id/events` | none | Server sent events (section 5) |
| `POST /v1/projects/:id/reviews/:reviewId` | `{ decision, notes, edits: [{ path, value }], commentIds }` | `{ stage }` |
| `POST /v1/projects/:id/comments` | `{ version, sceneId, fromSec, toSec, text, fixClass }` | `{ commentId }` |
| `POST /v1/projects/:id/approval-links` | `{ gate, permissions, days }` | `{ token, expiresAt }` |
| `POST /v1/projects/:id/cancel` | none | `{ ok: true }` |
| `POST /v1/projects/:id/retry` | none | `{ ok: true }`. New: continues a failed project from the stage it stopped at |

**Field notes**

- `mode` is `"input"` (form) or `"director"` (chat). `order` is the object of brief section 8; unknown fields are kept and passed to the agent. Invalid values answer 400 `bad_order` naming the field, for example `order.quality`.
- `pendingReview` is `null` or `{ reviewId, gate, version, summary, package, suggestions, missing, cost }`. `package.files` is a list of `{ url, path, assetId }`; images are stills, an `.mp4` is the draft or the final.
- `decision` is `"approve"`, `"changes"` or `"reject"`. `changes` and `reject` both send the gate back one stage with the notes; `cancel` is the only way to stop a project.
- At G2, `approve` reserves the credits first (section 7). Too few credits answers 402 `insufficient_credits` and the gate stays open, so the same call can be repeated after a top up.
- `fixClass` is one of `text`, `timing`, `visual`, `sound`, `other`. `permissions` is `view`, `comment` or `approve`; `days` is 1 to 30, default 7.
- `studioApprovalView` forwards a decision from a client link with a server side token: `role: "admin"` and `pid` set to that project.

### Orders, previews and files

| Call | Body | Answer |
| --- | --- | --- |
| `GET /v1/capabilities` | none | `{ capabilities: { voice, music, image, video, avatar, lipsync, stock, sfx, upscale, fonts } }` |
| `POST /v1/estimate` | `{ order }` | `{ credits, breakdown: [{ item, credits }], etaSec }` |
| `POST /v1/preview/still` | `{ order, brandKit }` | `{ imageUrl, ttlSec }`. About 20 seconds, 6 per minute per user, no credits |
| `POST /v1/voices/preview` | `{ voiceId, text }` (120 characters max) | `{ audioUrl }`. `voiceProfileId` is accepted as an alias of `voiceId` |
| `POST /v1/uploads/sign` | `{ name, contentType, sizeBytes, purpose }` | `{ uploadUrl, headers, fileUrl, expiresAt }` |

- The estimate prices only what the engine can produce today: a capability that is `false` is never in the breakdown.
- Uploads go from the browser straight to storage: `PUT uploadUrl` with exactly the returned `headers`, then save `fileUrl`. The URL is valid for 15 minutes. Allowed: images, video, audio, fonts, PDF and text, up to 2 GB.
- Every `fileUrl`, `url`, `finalUrl` and `thumbUrl` the engine returns is permanent and safe to store in an entity. It redirects to a fresh short lived storage link on each request.

## 5. Live events

One stream per open project, `GET /v1/projects/:id/events`, read with `fetch` and a stream reader so the token stays in the `Authorization` header; never `EventSource`, never the token in the URL.

**Wire format.** Standard server sent events. Each event has a numeric `id`, an `event` name and one `data` line of JSON, ending with a blank line. A ping arrives every 15 seconds with no `id`. The stream was held open 10 minutes through the public domain in testing, with every ping on time.

```text
id: 412
event: progress
data: {"stage":"assets","label":"מייצרים קריינות","percent":55}

event: ping
data: {}
```

| Event | Data | What the UI does |
| --- | --- | --- |
| `message` | `{ id, role, text, cards: [{ kind, title, options, allowText }] }` | Adds a chat bubble. `role` is `agent`, `system` or `user` (the customer's own message, echoed). A card of `kind: "question"` shows its `options` as buttons, plus a text box when `allowText` is true |
| `progress` | `{ stage, label, percent }` | Updates the production line. `stage` may be `""` when the agent reports work inside the current stage |
| `file` | `{ assetId, kind, url, name }` | Adds a still, draft, voice or final to the stage view |
| `review_ready` | `{ reviewId, gate }` | Opens the gate panel; fetch the package with `GET /v1/projects/:id` (`pendingReview`) |
| `state` | `{ stage, status }` | Moves the production line, enables or disables actions |
| `cost` | `{ estimate, reserved, charged }` | Updates the three credit numbers |
| `error` | `{ code, message, retryable, balance?, needed? }` | Shows `message` (Hebrew). `insufficient_credits` carries `balance` and `needed` for the top up offer |
| `ping` | `{}` | Nothing. Keeps the connection open |

**Reconnect.** Keep the last `id` you processed. On reconnect, send it in the `Last-Event-ID` header: the engine replays every event after it from its database, so nothing is missed and nothing is shown twice. On the first connect, send `0` (or nothing) to get the full history, which rebuilds the page after a reload.

**Fallback.** If the stream fails three times in a row, poll `GET /v1/projects/:id` every 4 seconds and keep trying the stream in the background. The project read has everything the events carry except chat history.

**Restarts.** When the engine is redeployed, open streams close cleanly within a second; reconnect with `Last-Event-ID` as above.

## 6. Webhooks: studioWebhook

The engine POSTs every change the shell must store to `studioWebhook`, signed, with a stable event id, and retries until it gets a 2xx. The function must verify, deduplicate, apply, and answer 200.

**Request**

- Headers: `Content-Type: application/json`, `X-Studio-Signature: sha256=<hex>`, `X-Studio-Event-Id: <id>`.
- Body: `{ eventId, type, projectId, at, data }`. `projectId` is the BASE44 `StudioProject` id; `at` is ISO 8601.
- Signature: HMAC SHA-256 of the **raw body bytes** with `STUDIO_WEBHOOK_SECRET`, hex, prefixed `sha256=`. Verify before parsing, and compare in constant time.

```javascript
// studioWebhook: verify and deduplicate
const raw = await req.text();
const enc = new TextEncoder();
const key = await crypto.subtle.importKey("raw", enc.encode(Deno.env.get("STUDIO_WEBHOOK_SECRET")), { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, enc.encode(raw)));
const expected = "sha256=" + [...mac].map((b) => b.toString(16).padStart(2, "0")).join("");
const got = req.headers.get("x-studio-signature") ?? "";
if (got.length !== expected.length || ![...got].every((c, i) => c === expected[i])) return Response.json({ error: "Invalid signature" }, { status: 401 });
const eventId = req.headers.get("x-studio-event-id");
// seen before: return the stored first answer, apply nothing
const event = JSON.parse(raw);
```

**Idempotency.** Store each `X-Studio-Event-Id` with the answer you gave. The same id again returns that first answer and changes nothing. The engine reuses the id on every retry, including for `credits.reserve`.

**Retries.** 2xx means delivered. 408, 429 and 5xx are retried after 5 s, 15 s, 1 min, 2 min, 5 min, 10 min, 15 min, 30 min, then hourly, up to 20 attempts. Any other 4xx is final. So answer 200 for duplicates and for types you ignore, and keep 4xx for a bad signature (401) or a project that does not exist (404). Events of one project arrive in the order they happened.

### Types

| Type | `data` | What studioWebhook does | Answer |
| --- | --- | --- | --- |
| `project.state` | `{ stage, status, planSummary }` | Update `stage`, `status`, `planSummary`, `lastEventAt` on StudioProject | `{ ok: true }` |
| `review.created` | `{ reviewId, engineReviewId, gate, version, summary, package, suggestions, missing, cost, decision, auto }` | Create StudioReview. If `decision` is `"pending"`, set the project `status` to `waiting_user`. If `auto` is true the gate passed by run mode: store it with `decision: "approved"` and do not wait | `{ ok: true }` |
| `review.decided` | `{ reviewId, engineReviewId, gate, decision, notes, by, auto? }` | Update the StudioReview with `engineReviewId`: `decision` (`approved`, `changes` or `rejected`), `clientNotes`, `decidedAt` | `{ ok: true }` |
| `asset.created` | `{ assetId, kind, url, name, provider, credits, status, meta }` | Create or update StudioAsset by `assetId` | `{ ok: true }` |
| `credits.reserve` | `{ credits, userId, breakdown: [{ item, credits }] }` | Atomically move `credits` from the user's balance into a CreditReservation (section 7) | `{ ok: true, reservationId, balance }` or `{ ok: false, reason: "insufficient_credits", balance }` |
| `credits.charge` | `{ credits, ref, note, reservationId }` | Move `credits` from reserved to charged, append `{ ref, credits, at, note }` to `items`. Never above `reserved` | `{ ok: true }` |
| `credits.release` | `{ credits, charged, reserved, reason, reservationId }` | Return `reserved - charged` to the balance (by your own books), status `released` | `{ ok: true, released }` |
| `project.delivered` | `{ finalUrl, thumbUrl, assets: [{ id, kind, url, name }] }` | Set `finalUrl`, `thumbUrl`, status `delivered` | `{ ok: true }` |
| `project.failed` | `{ reason, failReason, stage }` | Set status `failed` and `failReason`. The customer can retry (section 4) | `{ ok: true }` |

The answer may be bare or wrapped as `{ data: { ... } }`; the engine reads both. Only `credits.reserve` answers are acted on; for the other types any 2xx is enough.

**System event: `pricing.updated`.** Sent when the model catalog or the credit rules change, with `projectId: "system"` and `data` equal to the full answer of `GET /v1/models` (section 9). Handle it before the project lookup: store or cache the tiers and prices, and answer `{ ok: true }`. Answering 404 for it marks the event as failed on the engine side, so the shell would keep showing old prices until the next change.

## 7. Credits

Credits move only inside `studioWebhook`, through the existing atomic deduction; the engine decides when and how much, and BASE44 keeps the books. Nothing is reserved or charged before the customer approves G2.

1. **Estimate (before G2).** The screen shows the engine's numbers from `POST /v1/estimate`, then from the `cost` events, with the word "הערכה". No credit entity changes.
2. **Reserve (G2 approve).** The engine sends `credits.reserve` with the G2 price and waits up to about 20 seconds. `ok: true` reserves and the project moves on. `ok: false` answers the customer's approve call with 402 `insufficient_credits`; the gate stays open and the page offers the existing purchase flow. After a top up, the same approve call works.
3. **Charge (per asset).** Each paid item (a voice line, music, an image, the final render) sends one `credits.charge` after it succeeded. A failed item is never charged. The engine refuses any item that would go above the reservation, before it calls the provider.
4. **Release (delivery or cancel).** The engine sends one `credits.release`. Compute the refund from your own CreditReservation: `reserved - charged`. Items already made stay charged on cancel.

**Worked example (the first real project, 16 November 2026)**

| Step | Event | Reserved | Charged | Balance |
| --- | --- | --- | --- | --- |
| Start | none | 0 | 0 | 2000 |
| G2 approved | `credits.reserve` 222 | 222 | 0 | 1778 |
| 7 voice lines | 7 times `credits.charge`, 13 in total | 222 | 13 | 1778 |
| Music | `credits.charge` 20 | 222 | 33 | 1778 |
| Final render | `credits.charge` 6 | 222 | 39 | 1778 |
| Delivered | `credits.release` 183 | 39 (closed) | 39 | 1961 |

**Rules for the shell**

- After G2, the project page shows three numbers at all times: reserved, charged, and left (`reserved - charged`), from the `cost` events.
- Reject a `credits.charge` that would pass `reserved` (answer `{ ok: false, reason: "above_reservation" }`); the engine never sends one, so this only guards against bugs.
- One reservation per project in this version. If the customer later asks for more than the reservation covers, the agent says what it costs and asks; a second reservation is not supported yet.
- One credit is 0.15₪, as today. The per item prices are being calibrated against measured cost; they live only in the engine, so a change never needs a BASE44 release.

## 8. Stages, gates and run modes

A project moves through 12 stages; the five gates are where the customer decides, and the engine enforces them on the server whatever the agent or the browser does.

| Stage | Gate | Status while there | The UI shows |
| --- | --- | --- | --- |
| `intake` |  | `active` | "מקבלים את ההזמנה" and the progress line |
| `G0_brief` | G0 בריף | `waiting_user` if it stops | The five line brief and what is missing |
| `messaging` |  | `active` | Progress |
| `G1_script` | G1 תסריט | `waiting_user` if it stops | Hooks, the script word for word, screen texts, claims to confirm |
| `planning` |  | `active` | Progress |
| `G2_storyboard` | G2 סטוריבורד ומחיר | `waiting_user`, always | A still per scene, the price by item, the approve button |
| `assets` |  | `active` | Progress, files as they arrive, the three credit numbers |
| `assembly` |  | `active` | Progress |
| `G3_draft` | G3 טיוטה | `waiting_user` if it stops | The draft player, timeline comments, what was checked |
| `finishing` |  | `active` | "מרנדרים את הסרטון הסופי", queue position |
| `G4_final` | G4 סרטון סופי | `waiting_user` if it stops | The final file, thumbnail, QC result |
| `delivered` |  | `delivered` | Download |

**Which gates stop** (from `order.runMode`):

| Run mode | Stops at | Passes by itself |
| --- | --- | --- |
| `every-gate` | G0, G1, G2, G3, G4 | none |
| `key-gates` (default) | G2, G3 | G0, G1, G4 |
| `fast` | G2 | G0, G1, G3, G4 |

A gate that passes by itself still sends `review.created` with `auto: true` and `decision: "approved"`, so the history is complete.

**Side statuses.** `failed` keeps the stage and carries `failReason`; `POST /v1/projects/:id/retry` continues from there. `cancelled` is final and releases the credits. A question from the agent (a `message` with question cards) sets `waiting_user` without a gate; the customer's answer through `POST /messages` resumes the work.

**Server rules the UI can rely on.** A tool that costs credits is refused before G2 is approved; the final render is refused before G3 is approved; forward moves need an approve decision; `changes` and `reject` go back exactly one stage.

## 9. Library: voices, fonts, characters, brand

Four calls feed the `StudioLibrary` and `StudioBrand` pages; each answers from the engine, so BASE44 stores only what the customer chose.

### Voices

The catalog has **100 Hebrew voices: 50 male and 50 female**, chosen from Google's Gemini voice library (2,114 voices). Each was recorded saying the same Hebrew ad line and scored for native Hebrew, clarity and ad fit. The 26 Gemini studio voices come first, then the library voices best suited to ads, spread across pitch and character. Every voice has a Hebrew name, description, tags and a demo made by our system.

| Call | Answer |
| --- | --- |
| `GET /v1/voices?gender=female&q=פרסומות` | `{ voices, defaultVoiceId, total, connected }`; both filters are optional |
| `GET /v1/voices/:voiceId/sample.mp3` | The demo, public (no token), for an `<audio>` tag |
| `POST /v1/voices/preview` `{ voiceId, text }` | `{ audioUrl, voiceId }`: the customer's own text (120 characters) in that voice. The same text and voice are served from cache |

One voice in the answer:

```json
{ "voiceId": "autonoe", "name": "Autonoe", "nameHe": "שירה", "gender": "female", "pitch": "high",
  "persona": "Storyteller & Narrator", "description": "חיובי, קצבי ומשכנע, מצוין לפרסומות קידום מכירות והשקות",
  "tags": ["אנרגטי", "אופטימי", "פרסומות"], "sampleUrl": "https://.../v1/voices/autonoe/sample.mp3", "rank": 3, "isDefault": false }
```

**How BASE44 uses it.** Fill the system `VoiceProfile` records from this list once (admin), with `providerVoiceId = voiceId`, `name = nameHe`, `sampleUrl`, `tags`, `scope: "system"`. In the order, send the chosen voice as `order.voice.providerVoiceId` (or `voiceProfileId`, if it holds the same value). Without a voice, the engine uses `defaultVoiceId`.

### Fonts

`POST /v1/fonts` is `multipart/form-data` with `file` (TTF, OTF, WOFF or WOFF2, up to 30 MB), `brandId`, and an optional `family` name. The engine checks the file with the kit's checker and stores it.

```json
{ "fontId": "fnt_...", "family": "Rubik", "weight": 700, "style": "normal", "verdict": "partial", "hebrewCoverage": 100,
  "weights": [700], "embedAllowed": true, "fileUrl": "https://...", "notes": ["Hebrew letters are present but digits are missing ..."] }
```

`verdict` is `ok`, `partial` or `no-hebrew`; show `notes` to the customer before they approve the font. Map it to `FontFamily` and `FontFile` (`hebrewCoverage`, `verdict`, `embedAllowed`, `url = fileUrl`). `GET /v1/fonts?brandId=...` returns `{ families }`, the system font Heebo first. Checked brand fonts (not `no-hebrew`, embedding allowed) reach every new project of that brand automatically.

### Characters

AI characters are made in two calls (about 30 seconds each), rate limited to 3 a minute per user:

1. `POST /v1/characters` `{ description, brandId }` returns `{ characterId, proposals: [{ id, imageUrl }] }`: four portrait proposals.
2. `POST /v1/characters` `{ pick: "<proposal id>", name, brandId }` returns the character: `{ characterId, name, status: "ready", portraitUrl, sheetUrls: [portrait, identity sheet, expressions] }`.

`GET /v1/characters?brandId=...` lists the ready ones. Store them in `CharacterProfile` (`providerId = characterId`, `sheetUrls`). Characters are fictional people. A talking avatar of a real person needs the consent flow and an avatar provider, which is not connected yet (`capabilities.avatar` is false).

### Brand extraction

`POST /v1/brands/extract` `{ url }` returns `{ name, palette: { bg, bg2, text, muted, accent, alarm, good, onAccent }, font, logoUrl, radius, confidence, sourceUrl, candidates }` in about 10 seconds. Tested on pixl.co.il: name "PixL", accent `#0ec9d7`, font Assistant, and the logo. Show it as a proposal in `StudioBrand`; the customer approves before it is saved to `BrandKit`. Private and local addresses are refused (400 `bad_url`).

### Uploads

Customer files (logo, footage, product photos) use `POST /v1/uploads/sign` and a direct `PUT` (section 4). Pass the resulting `fileUrl` in `order.content.files: [{ url, name, kind }]` or in a message's `attachments`; the engine copies them into the project for the agent.

### Models and tiers (KIE)

Every AI image, video, avatar, lip sync, upscale and background removal runs through one provider, KIE.ai, in **three tiers the customer chooses: חסכוני (`cheap`), רגיל (`standard`), פרימיום (`premium`)**. The engine owns the model choice and the prices; BASE44 shows them and never computes them.

| Capability | חסכוני | רגיל | פרימיום |
| --- | --- | --- | --- |
| Image, 2K | Seedream 5.5, 4 credits | Nano Banana 2, 6 credits | Nano Banana Pro, 9 credits |
| Image edit with references | Seedream 5.5 Edit, 4 | Nano Banana 2, 6 | Nano Banana Pro, 9 |
| Talking presenter (per second) | Kling Avatar 720p, 5 | OmniHuman 2.0, 7 | Kling Avatar Pro 1080p, 10 |
| Lip sync on a video (per second) | Volcengine Lite, 4 | Volcengine Basic, 4 | Volcengine Basic, 4 |
| Image upscale | Recraft Crisp, 1 | KIE x2, 2 | Topaz x2, 10 |
| Background removal | Recraft, 1 | Recraft, 1 | Recraft, 1 |
| AI video | being added; listed by `GET /v1/models` when live |  |  |

Prices are our credits (0.15₪ each), with the platform markup already applied. The live values always come from the API, never from this table:

- `GET /v1/models` returns `{ version, hash, updatedAt, tierLabels, capabilities: { <cap>: { labelHe, unit, tiers: { cheap, standard, premium } } } }`. Each tier has `labelHe`, `model`, `description`, `unit`, `creditsPerUnit`, `example: { label, credits }`, `maxSeconds`, `minSeconds`, `durations`.
- The customer's choice goes into the order: `order.tier` for the whole project (default `"standard"`), and optionally `order.tiers` per capability, for example `{ "video": "premium", "image": "cheap" }`. The G2 price is computed from these tiers.
- When prices or models change, the engine sends `pricing.updated` to `studioWebhook` (section 6), so the shell refreshes without polling.

## 10. Errors

Every error has one shape, `{ error: { code, message, ...details } }`; the shell branches on `code` and on the HTTP status, never on `message` (English, for logs).

| Status | `code` | When | What the shell does |
| --- | --- | --- | --- |
| 400 | `bad_request` | A required field is missing | Fix the call; show a generic error |
| 400 | `bad_order` | An order field has a value not allowed; `message` names it, e.g. `order.quality` | Highlight that field in the form |
| 400 | `bad_url` | A URL is invalid, private or local | "הכתובת לא תקינה" |
| 401 | `unauthorized` | No token, bad signature, wrong issuer | Get a new token; if it fails again, show an error |
| 401 | `token_expired` | The token is older than 15 minutes | Refresh once and retry |
| 402 | `insufficient_credits` | G2 approval with too low a balance; carries `balance`, `needed` | Keep G2 open, offer the purchase flow |
| 403 | `forbidden` | Not the owner, a token bound to another project, or admin only | "אין הרשאה" |
| 404 | `not_found` | Unknown project, review, voice or proposal | Reload the page |
| 409 | `already_decided` | The review was already decided (double click, second tab) | Reload the project |
| 409 | `invalid_transition` | The action does not fit the current stage | Reload the project |
| 409 | `project_closed` | A message to a cancelled or delivered project | Disable the chat |
| 413 | `too_large` | Upload over the limit (2 GB, fonts 30 MB) | Show the limit |
| 415 | `unsupported_type` | File type not accepted | Show the accepted types |
| 422 | `font_unreadable` | The file is not a valid font | "הקובץ אינו פונט תקין" |
| 429 | `rate_limited` | Too many previews, uploads or extractions in a minute | Retry after a minute |
| 429 | `busy` | Preview renderer full | Retry in a few seconds |
| 502 | `provider_failed`, `fetch_failed`, `capture_failed` | A media provider or a website failed | Offer a retry |
| 503 | `capability_off` | A capability that is not connected | Show "בקרוב" |
| 503 | `credits_unavailable` | `studioWebhook` did not answer the reserve | Keep G2 open, "נסו שוב בעוד רגע" |
| 500 | `internal`, `preview_failed` | An engine bug | Show a generic error; the engine logs it |

Errors during production do not come back as HTTP errors: they arrive as `error` events and as `project.failed` (sections 5 and 6).

## 11. Connection tests

The admin console (`StudioAdmin`) runs six checks with one button; when all six pass, the connection is proven in both directions and `mockMode` can be turned off. Each check is one call from the browser through `engineClient`.

| # | Check | Call | Passes when |
| --- | --- | --- | --- |
| 1 | Engine reachable | `GET /healthz` (no token) | 200 and `ok: true` |
| 2 | Token accepted | `GET /v1/handshake` | 200; `token.sub` is the admin's id, `token.role` is `admin`, `origin.allowed` is true, `clockSkewSec` is between -30 and 30 |
| 3 | Live events | `GET /v1/handshake/events` | One `message` event arrives within 2 seconds, then 5 `ping` events, 2 seconds apart |
| 4 | Webhook and secret | `POST /v1/handshake/webhook` (admin token) | `sent: true` and `signatureAccepted: true` (the engine signed a test event and `studioWebhook` did not answer 401) |
| 5 | Direct upload | `POST /v1/uploads/sign`, then `PUT` a 1 KB text file to `uploadUrl` | The `PUT` answers 200 and `fileUrl` downloads the same bytes |
| 6 | Capabilities and price | `GET /v1/capabilities`, then `POST /v1/estimate` with a sample order | Both 200, and the estimate has `credits > 0` |

What the engine returns for check 2, as tested on 16 November 2026:

```json
{ "ok": true,
  "engine": { "version": "0.3.0", "url": "https://studio-pixl.169-58-89-179.sslip.io", "time": "2026-11-16T07:57:22Z" },
  "token": { "sub": "<user id>", "pid": "", "role": "admin", "expiresAt": "2026-11-16T08:12:22Z", "clockSkewSec": 0 },
  "origin": { "value": "https://visual-israel-create.base44.app", "allowed": true },
  "webhook": { "configured": true, "url": "https://visual-israel-create.base44.app/functions/studioWebhook" },
  "capabilities": { "voice": true, "music": true, "image": true, "video": false, "avatar": false, "lipsync": false, "stock": false, "sfx": true, "upscale": false, "fonts": true } }
```

**studioWebhook and the test event.** Check 4 sends `type: "engine.ping"` with `projectId: "engine-connectivity-check"`. Today the function answers 404 `project_not_found`, which already proves the signature passed. Optionally, answer `{ ok: true, pong: true }` for `engine.ping` before the project lookup, so the check reads clearly.

**When a check fails**

- 2 fails with a CORS error in the browser console: the origin is not on the engine's list (section 2).
- 2 fails with 401: `STUDIO_JWT_SECRET` differs between the two sides, or the issuer is not `pixl-base44`.
- 3 hangs, then delivers everything at once: something between the browser and the engine buffers the stream.
- 4 shows `signatureAccepted: false`: `STUDIO_WEBHOOK_SECRET` differs, or the function hashes the parsed JSON instead of the raw body.

## 12. Prompts for the BASE44 builder

Paste them one at a time, in this order, after adding this guide to the app's file library as `PIXL-STUDIO-ENGINE-GUIDE.md`. Each prompt ends with a check, so a step is finished only when its check passes.

**Prompt 1: the contract**

```text
Read PIXL-STUDIO-ENGINE-GUIDE.md fully. It extends PIXL-STUDIO-BASE44-BRIEF.md and wins where they differ.
List every difference between the guide and what is built today (functions, engineClient, entities, pages).
Do not change code yet. Answer with the list, grouped by: functions, engineClient, entities, pages.
```

**Prompt 2: studioWebhook**

```text
Update the backend function studioWebhook to match section 6 of PIXL-STUDIO-ENGINE-GUIDE.md exactly.
- Verify X-Studio-Signature over the raw body before parsing (constant time compare). 401 when it does not match.
- Idempotency by X-Studio-Event-Id: store the first answer and return it again for the same id, changing nothing.
- Handle all nine types of the table, with the answers shown. For review.created with auto: true, store decision approved and do not set waiting_user.
- credits.reserve, credits.charge and credits.release use only the existing atomic credit function. Never charge above reserved. The release amount comes from our own CreditReservation (reserved minus charged).
- Answer { ok: true, pong: true } for type engine.ping, before looking up the project.
- Unknown types answer 200 { ok: true }.
Check: a request with a wrong signature gets 401, and the same signed event sent twice changes the data once.
```

**Prompt 3: studioToken**

```text
Check the backend function studioToken against section 3 of PIXL-STUDIO-ENGINE-GUIDE.md: HS256 with Web Crypto, header {"alg":"HS256","typ":"JWT"}, base64url without padding, claims iss "pixl-base44", sub, pid (project id or ""), role ("user" or "admin"), iat, exp = iat + 900.
It returns { token, expiresAt, engineUrl } and refuses users not allowed by StudioSettings or not owning the project (admins excepted).
Check: decode a token and show its header and claims (never the secret).
```

**Prompt 4: engineClient, the real adapter**

```text
In components/studio/engine/engineClient, implement the real adapter next to the mock one, following sections 3, 4, 5 and 10 of PIXL-STUDIO-ENGINE-GUIDE.md:
- one cached token per projectId from studioToken, refreshed one minute before expiresAt; on 401 token_expired refresh once and retry once
- every call in section 4 and section 9, JSON in and out, errors parsed as { error: { code, message } } and thrown with code, status and details
- the event stream with fetch and a stream reader (never EventSource), Last-Event-ID on reconnect, history from 0 on first load, and after three failed connects a poll of GET /v1/projects/:id every 4 seconds while it keeps trying
- the adapter is chosen by StudioSettings.mockMode; no other code may fetch the engine
Check: with mockMode off, an order goes to G2 and the stills appear on the project page.
```

**Prompt 5: the admin connection tests**

```text
In StudioAdmin, add a "בדיקת חיבור למנוע" card with one button that runs the six checks of section 11 of PIXL-STUDIO-ENGINE-GUIDE.md in order, through engineClient, and shows each one as passed or failed with the reason. Hebrew UI, right to left.
Check: all six pass against the engine URL in StudioSettings.
```

**Prompt 6: voices**

```text
Following section 9 of PIXL-STUDIO-ENGINE-GUIDE.md:
- In StudioAdmin, add a button "ייבוא קולות מהמנוע" that reads GET /v1/voices and creates or updates the system VoiceProfile records (providerVoiceId = voiceId, name = nameHe, sampleUrl, tags, language "he", kind "catalog", scope "system"). It never deletes a profile a project uses.
- In the order form and StudioLibrary, the voice picker shows nameHe, the description, the tags, a gender filter and a play button for sampleUrl, plus a "נסו עם הטקסט שלכם" field that calls POST /v1/voices/preview.
- The chosen voice goes into order.voice.providerVoiceId.
Check: 100 voices appear, 50 per gender, and both the sample and the preview play.
```

**Prompt 7: fonts, characters and brand**

```text
Following section 9 of PIXL-STUDIO-ENGINE-GUIDE.md, connect:
- StudioBrand: "חילוץ מהאתר" calls POST /v1/brands/extract and shows the result as a proposal the customer approves before it is saved to BrandKit.
- StudioLibrary fonts: upload sends multipart to POST /v1/fonts with brandId, shows verdict, hebrewCoverage and notes, and saves FontFamily and FontFile. A font with verdict no-hebrew is shown with a warning and cannot be chosen for captions.
- StudioLibrary characters: a description field calls POST /v1/characters, shows the four proposals, and a pick calls it again with { pick, name } and saves CharacterProfile (providerId = characterId, sheetUrls).
Check: one of each completes end to end.
```

**Prompt 8: switch off mock mode**

```text
Set StudioSettings.mockMode to false for admins only (audience: admins). Run one order end to end: form, G2 approve, G3 approve, download. Report: the credits reserved, charged and released as shown on the project page and in CreditReservation, and any screen that still shows mock data.
```

**Prompt 9: model tiers and prices**

```text
Following section 9 (Models and tiers) and section 6 (pricing.updated) of PIXL-STUDIO-ENGINE-GUIDE.md:
- Set StudioSettings.engineUrl to https://studio.pixl.co.il.
- In the order form, add one choice "רמת הפקה" with three options from GET /v1/models: חסכוני, רגיל, פרימיום. Under each option show the model name and the example price of each capability the order uses. Save it as order.tier (default standard). An advanced panel may set order.tiers per capability.
- Every price shown comes from the engine: GET /v1/models for unit prices, POST /v1/estimate for the order total. Never multiply prices in the browser.
- In studioWebhook, handle type pricing.updated (projectId "system") before the project lookup: save data in a new entity StudioPricing (one record: version, hash, updatedAt, catalog object) and answer { ok: true }. The order form reads StudioPricing first and refreshes from GET /v1/models when hash differs.
- A capability that is false in GET /v1/capabilities is shown as "בקרוב".
Check: switching the tier changes the estimate shown before G2, and a pricing.updated event updates StudioPricing.
```

## 13. Contract versions

The contract only grows: fields and calls are added, never renamed or removed without a new version agreed on both sides. The engine's version is in `GET /healthz` and `GET /v1/handshake`.

| Date | Engine | Contract change |
| --- | --- | --- |
| 16 November 2026 | 0.4.x | Engine at `https://studio.pixl.co.il`. KIE as the single media provider: `GET /v1/models`, `order.tier` and `order.tiers`, the `pricing.updated` system event, capabilities `avatar`, `lipsync`, `upscale` on. CORS open to `*.base44.app` and `*.pixl.co.il`. A status page at `/` |
| 16 November 2026 | 0.3.0 | Voices catalog and samples, fonts upload, characters, brand extraction, handshake checks, `GET /v1/openapi.json`, `voiceId` in voice preview |
| 15 November 2026 | 0.2.2 | First real video delivered. `review.created` carries `engineReviewId` and `auto`; `project.failed` carries `failReason`; `POST /v1/projects/:id/retry` |
| 15 November 2026 | 0.1.0 | Brief v1.0 implemented field for field |

**Rule for changes.** A change either side needs goes into this guide first, then into both sides together. When in doubt, ask the engine owner before building around a difference.
