# AbraCadabra — Official AI Prompt & SDK Reference

> Single-file HTML5 app specification and live data & database SDK (`window.kehiData`) for AbraCadabra.
> Reference URL: https://abra-cadabra.app/llms.txt

## 1. Required App Structure
- Output **one complete, self-contained HTML5 document** (`<!DOCTYPE html>`, `<html lang="he" dir="rtl">`) with all CSS in `<style>` and all JS in `<script>`. Do NOT link external local files (`./style.css`, `./app.js`).
- Build responsive layouts that work cleanly on both **mobile portrait (`390×844`)** and **ESP32-S3 landscape touchscreens (`800×480`)**.
- Always write the brand name as `AbraCadabra`.
- **Sandboxed runtime (STRICT):** Apps run inside a sandboxed `<iframe>` without `allow-same-origin`. **NEVER** use `localStorage`, `sessionStorage`, or `document.cookie` for app data (accessing them throws `SecurityError` and breaks persistence). Keep transient UI state in JS memory, and store **all persistent app data** exclusively in `window.kehiData.clientSupabase`.
- **Visual Editor compatibility:** Add `data-kehi-group="<group-name>"` (for example `data-kehi-group="place-card"`, `data-kehi-group="filter-btn"`) on repeating cards/buttons/rows so AbraCadabra's Visual Editor can resize and style all matching items together.

## 2. Critical Security Rules (SAFETY_GUARD)
AbraCadabra automatically blocks imported or generated code that violates any rule below:
1. **NEVER access Supabase directly:** Forbidden strings/APIs include `*.supabase.co`, `sb_publishable_`, `sb_secret_`, `service_role`, `@supabase/supabase-js`, and `createClient()`.
2. **NEVER embed AI or external API keys in browser code:** Forbidden URLs/keys include `https://api.openai.com`, `https://api.anthropic.com`, `https://generativelanguage.googleapis.com`, `sk-proj-...`, `sk-ant-...`, and `AIzaSy...`.
3. **NEVER execute arbitrary code or DB mutations:** Do not use `eval()`, `new Function()`, or send `POST`/`PUT`/`PATCH`/`DELETE` requests to `/api/data/mitzpe`.
   - **Use ONLY `query` / `save` / `patch` / `remove` on `clientSupabase`:** NEVER call `.insert(`, `.update(`, `.upsert(`, or `.delete(` (not on `clientSupabase`, nor on `Map`/`Set`/custom objects). Always use `.query()`, `.save(table, rows, { upsert })`, `.patch(table, { id }, data)`, and `.remove(table, { id })`, and use plain JS `filter` / `splice` / object keys for in-memory structures.
4. **Always use `window.kehiData`:** AbraCadabra injects `window.kehiData` automatically at runtime (in the Simulator and in published `/p/:slug` URLs). Guard `if (!window.kehiData)` and handle `res.ok === false` cleanly.

## 3. `window.kehiData` SDK Specification

### Layer A & B1: Public / Community Connectors (Available in Simulator, Public `/p/:slug`, Private apps, and ESP32)

#### `await window.kehiData.getMitzpe(resource, params?)`
Fetches verified read-only Mitzpe Ramon community data.
- `resource`: `'places'` | `'events'` | `'posts'` | `'categories'`
- `params` (optional): `{ category_group?, category?, type?, q?, limit?, offset? }`
- Response: `{ ok: true, community: 'mitzpe', resource, readOnly: true, count, items: [...] }` (or `{ ok: false, error }`)

Resources & exact returned fields:
- **`places`**
  - Fields: `id`, `name_he`, `name_en`, `category`, `category_group`, `address`, `phone`, `hours`, `hours_status`, `website`, `maps_url`, `note`, `lat`, `lng`, `badge`
  - Exact filter params: category_group, category | Searchable via `q`: name_he, name_en, category, address, note | Default limit: 20, Max limit: 50
- **`events`**
  - Fields: `id`, `title`, `starts_at`, `ends_at`, `start_date`, `when_text`, `venue_name`, `venue_place_id`, `address`, `price_text`, `organizer`, `description`
  - Exact filter params: none (use q/limit/offset) | Searchable via `q`: title, venue_name, description | Default limit: 20, Max limit: 50
- **`posts`**
  - Fields: `id`, `type`, `title`, `body`, `created_at`, `expires_at`, `partial_ok`, `fuel_share`
  - Exact filter params: type | Searchable via `q`: title, body | Default limit: 20, Max limit: 50
- **`categories`**
  - Fields: `category_group`, `count`
  - Exact filter params: none (use q/limit/offset) | Searchable via `q`: none | Default limit: 20, Max limit: 50

#### `await window.kehiData.getWeather(params?)`
Live weather & 4-day forecast (Open-Meteo, defaults to Mitzpe Ramon).
- `params` (optional): `{ city?: string, lat?: number, lon?: number }`
- Response: `{ ok: true, location, lat, lon, temperatureC, feelsLikeC, humidityPct, windKmh, weatherCode, description, forecast: [{ date, minTemp, maxTemp, description }], updatedAt }`

#### `await window.kehiData.getTransit(stopCode?)`
Real-time Israel public transit arrivals.
- `stopCode`: string (default `'13965'` — מרכז מסחרי מצפה רמון)
- Response: `{ ok: true, stopCode, stopName, arrivals: [{ line, destination, destinationCity, etaMinutes, etaTime, operator }], source, updatedAt }`

#### `await window.kehiData.getTraffic(origin?, destination?)`
Travel duration & live congestion estimate.
- Defaults: `origin = 'מצפה רמון'`, `destination = 'באר שבע'`
- Response: `{ ok: true, origin, destination, distanceKm, durationMinutes, durationInTrafficMinutes, trafficStatus, source, updatedAt }`

#### `await window.kehiData.callConnector(connectorId, endpointId, params?)`
Read-only community connectors generated from the Connectors Hub (GET only). Publishing shares the recipe only; each user brings their own vault credentials. Never embed API keys in HTML and never `fetch()` the upstream host from the browser.
- To propose a new connector, open the Connectors Hub popup and use **Add a new connector**.
- Response: `{ ok, data, status, cached?, connectorId, endpointId }` or `{ ok: false, code, error }`
- Published community connectors:
- None published yet. Users can propose a new read-only connector from the Connectors Hub popup.

### Layer A2: Personal Connectors (Simulator & Private `/p/:slug?key=...` ONLY — Blocked with HTTP 403 in Public `/p/:slug` Apps!)
Always check `if (!res.ok)` and show a clean fallback message when running as a public app or when the user hasn't connected the provider.
- `await window.kehiData.getCalendar()` → `{ ok: true, count, items: [{ id, title, startTime, endTime, location, isAllDay }] }`
- `await window.kehiData.getPriorityEmails()` → `{ ok: true, unreadScanned, count, items: [{ from, subject, actionNeeded, urgency }] }`
- `await window.kehiData.searchDrive(q?)` → `{ ok: true, count, items: [{ id, name, kind, modifiedTime, snippet, url }] }`
- `await window.kehiData.getSpotifyNowPlaying()` → `{ ok: true, isPlaying, track, artist, album, progressPct, progressMs, durationMs, albumArtUrl }`

### Layer C: Business AI & Local Knowledge Base (Keys stay encrypted in server Secrets Vault)
- `await window.kehiData.askAgent(promptOrMessages, options?)`
  - `promptOrMessages`: string or `[{ role: 'user' | 'assistant' | 'system', content: string }]`
  - `options`: `{ systemPrompt?, useKnowledgeBase?: boolean (default true), secretName?, maxTokens? }`
  - Response: `{ ok: true, reply, provider, model, usedKnowledgeBase, sources: [{ docId, title, chunkIndex, score }] }`
- `await window.kehiData.searchKnowledge(query, limit?)`
  - Response: `{ ok: true, count, items: [{ chunkId, docId, title, filename, chunkIndex, content, score }] }`
- `await window.kehiData.callVaultProxy(secretName, options?)`
  - `options`: `{ method?: 'GET'|'POST'|'PUT'|'PATCH', path?: string, query?: object, headers?: object, body?: any }`
  - Response: `{ ok, status, data }`

### Layer C3: Payments (Cardcom credit + Bit), Morning invoices & AI video (Higgsfield)
Built-in connectors. The OWNER saves credentials once in Connectors Hub → they stay encrypted in the server vault. Never put Cardcom / Morning / Higgsfield keys or URLs in HTML.
- `await window.kehiData.payments.createCheckout({ items?, amount?, description?, customer?, successUrl? })`
  - `items`: `[{ sku, quantity }]` priced from the owner's server-side catalog, or (only if the owner allowed custom amounts) `[{ name, price, quantity }]`
  - `amount` is optional; if sent it must equal the server-computed total. `customer`: `{ name?, email?, phone? }` (email → Morning invoice is emailed)
  - Response: `{ ok, orderId, amount, currency: 'ILS', items, checkoutUrl, bitUrl }`
  - Then call `window.kehiData.payments.openCheckout(result, { useBit?: boolean })` to send the buyer to the secure Cardcom page (credit card / Bit).
- `await window.kehiData.payments.getOrderStatus(orderId)` → `{ ok, orderId, status: 'created'|'pending'|'paid'|'failed', paid, amount, items, paymentMethod, invoice: { status, number?, url? } }`
  - Payment status is set ONLY by the server after verifying with Cardcom. Show "paid" only when `paid === true`.
- `window.kehiData.payments.readReturn()` → `{ orderId, payment } | null` after the buyer returns to the app (`?kehiOrder=...&kehiPayment=paid|pending|failed|cancel`); always confirm with `getOrderStatus`.
- Morning (חשבונית ירוקה) tax invoice/receipt is issued automatically after a verified payment when the owner enables it — the app does not call Morning directly.
- `await window.kehiData.video.create({ prompt, imageUrl?, duration?, aspectRatio? })` → `{ ok, jobId, status }` (image-to-video when `imageUrl` is given, else text-to-video; 3–10 s)
- `await window.kehiData.video.getStatus(jobId)` → `{ ok, status: 'queued'|'in_progress'|'completed'|'failed'|'nsfw'|'canceled', done, videoUrl }`
- `await window.kehiData.video.waitFor(jobId, { intervalMs?, timeoutMs?, onProgress? })` polls until done.
- Kid profiles: no payments; AI video only if a parent enabled it, with strict prompt filtering and the kid's own studio images.

### Layer C2: App Database — Built-in Per-App SQLite + Private Supabase (`window.kehiData.clientSupabase`)
Works **out of the box with zero setup**: every project gets its own isolated SQLite database (starting empty — **0 demo tables**), and migrates to the owner's private Supabase with 1 click whenever connected.
- **Canonical methods (use ONLY these — never `.insert()`, `.update()`, `.upsert()`, `.delete()`):**
  - `await window.kehiData.clientSupabase.status()` → `{ ok, connected, sqliteReady, mode, projectName }`
  - `await window.kehiData.clientSupabase.ensureTable(table, [{ name, type }])` → creates/updates a table tailored to the app (column types: `'text'`, `'integer'`, `'number'`, `'boolean'`, `'timestamp'`). Automatically includes `id INTEGER PRIMARY KEY AUTOINCREMENT` and `created_at TIMESTAMP`. **Call `ensureTable` ONLY when the app actually persists data (inventory, orders, bookings, scores, CRM, tasks); never create unused tables on stateless apps like players or calculators.**
  - `await window.kehiData.clientSupabase.query(table, { select?, eq?, orderBy?, limit? })` → `{ ok, data, count }`
    - **Query defaults & limits:** `limit` defaults to **`50`** (max **`500`** in built-in SQLite, **`200`** in Supabase). `orderBy` defaults to **`id.desc`** in SQLite (newest first); pass e.g. `{ limit: 200, orderBy: 'id.asc' }` when you want oldest-first or more than 50 rows. Returns `data: []` safely if the table does not exist yet.
  - `await window.kehiData.clientSupabase.save(table, rowOrRows, { upsert?: boolean })` → `{ ok, data, count }`
  - `await window.kehiData.clientSupabase.patch(table, { id }, partialData)` → `{ ok, data, count }`
  - `await window.kehiData.clientSupabase.remove(table, { id })` → `{ ok, data, count }`
- **Mandatory schema & ID rules:**
  - **`snake_case` columns ONLY:** Every table name and column name MUST be lowercase `snake_case` (`/^[a-z][a-z0-9_]*$/`, e.g. `color_hex`, `color_name`, `created_at`). NEVER use `camelCase` (`colorHex`) or mix casings.
  - **NEVER send `id` on insert:** `id` is auto-generated by the database (`INTEGER PRIMARY KEY AUTOINCREMENT`). Omit `id` completely when inserting new rows via `save()` — NEVER generate string/UUID IDs like `'part_1'` or `crypto.randomUUID()`. Only pass a numeric `id` in `eq: { id }` for `patch`/`remove` or when upserting an existing DB row.
  - **SQLite vs Supabase column creation:** Built-in SQLite (`mode: 'sqlite'`) auto-adds missing columns in both `ensureTable` and `save`/`patch`. Connected Supabase (`mode: 'supabase'`) only runs `CREATE TABLE IF NOT EXISTS` inside `ensureTable` (when OAuth SQL runner is active; it does NOT alter existing tables or run in public `/p/:slug` apps), and PostgREST `save()`/`patch()` fails if a column does not exist. Therefore **ALWAYS declare ALL columns upfront in `ensureTable`**.
- **Required Seed-on-Boot Pattern (always check `res.ok` & show visible error UI):**
```js
const COLS = [
  { name: 'name', type: 'text' },
  { name: 'category', type: 'text' },
  { name: 'color_hex', type: 'text' },
  { name: 'qty', type: 'integer' },
];
const INITIAL_ROWS = [
  { name: 'לבנה 2x4', category: 'Bricks', color_hex: '#DC2626', qty: 12 },
]; // NO id field on insert!

async function initData() {
  const db = window.kehiData && window.kehiData.clientSupabase;
  if (!db) { showErrorUI('חיבור מסד הנתונים אינו זמין'); return; }

  const eRes = await db.ensureTable('lego_parts', COLS);
  if (!eRes.ok) { showErrorUI(eRes.error || 'שגיאה ביצירת הטבלה'); return; }

  let qRes = await db.query('lego_parts', { limit: 200, orderBy: 'id.asc' });
  if (!qRes.ok) { showErrorUI(qRes.error || 'שגיאה בטעינת הנתונים'); return; }

  if (qRes.data.length === 0) {
    const sRes = await db.save('lego_parts', INITIAL_ROWS);
    if (!sRes.ok) { showErrorUI(sRes.error || 'שגיאה בשמירת נתוני הפתיחה'); return; }
    qRes = await db.query('lego_parts', { limit: 200, orderBy: 'id.asc' });
    if (!qRes.ok) { showErrorUI(qRes.error || 'שגיאה ברענון הנתונים'); return; }
  }
  renderRows(qRes.data);
}
```

### Layer D: Hardware Bridge (ESP32 Simulator / Devices)
- Read initial values from `window.kehiHardware` (`{ temperature, buttonCount }`).
- Listen for live updates via `window.addEventListener('message', (e) => ...)` checking `e.data?.type === 'hardware:temperature'` (`e.data.value`) or `'hardware:button'`.

### Layer D2: Real devices and personal data (device keys)
- Personal data on a physical board (`/api/esp32/data/personal/{calendar,emails,drive,spotify/*}`) needs a **per-device key**. It is installed **only** when the signed-in owner flashes the board from the studio over USB; it is bound to that board's MAC and to the owner profile, with read-only scopes the owner controls in **Connectors → Authorized devices**.
- Firmware sends it with `kehi_device_auth(http);` (headers `X-Kehi-Device-Key` + `X-Kehi-Device-Id`), read from the board's NVS. Never hardcode, print or invent a key; downloaded or externally flashed firmware has none and gets `401`.
- Spotify playback control (`POST …/spotify/control`) needs the separate write scope `spotify_control`, granted only when the app calls `kehiData.spotify.control`. Old profile-wide `esp1.` tokens are retired (401 `DEVICE_TOKEN_RETIRED`) — re-flash the board from the studio.
- Device keys work only on those routes — never on studio, vault, payments, AI, or app routes. Every access (allowed or denied) is logged for the owner. Device keys are accepted **only over HTTPS**; a key sent over plain HTTP is refused (403 `DEVICE_HTTPS_REQUIRED`). The board's network OTA page is locked: updates over the network need the one-time code shown on the board's screen in safe mode.
- Public data (weather, transit, traffic, Mitzpe) needs no key.

## 4. Minimal Starter Template

```html
<!DOCTYPE html>
<html lang="he" dir="rtl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>המדריך החי — מצפה רמון | AbraCadabra</title>
  <style>
    :root { --bg: #faf7f2; --card: #ffffff; --text: #1f2430; --muted: #6b7280; --accent: #ea580c; --border: #e7e1d6; }
    * { box-sizing: border-box; }
    body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: var(--bg); color: var(--text); padding: 16px; }
    .wrap { max-width: 920px; margin: 0 auto; display: flex; flex-direction: column; gap: 14px; }
    .hero { background: var(--card); border: 1px solid var(--border); border-radius: 16px; padding: 16px; display: flex; justify-content: space-between; align-items: center; gap: 12px; flex-wrap: wrap; }
    .weather-pill { background: #fff7ed; color: #9a3412; border: 1px solid #fed7aa; padding: 8px 12px; border-radius: 999px; font-weight: 700; font-size: 13px; }
    .grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 12px; }
    .card { background: var(--card); border: 1px solid var(--border); border-radius: 14px; padding: 14px; display: flex; flex-direction: column; gap: 6px; }
    .badge { align-self: flex-start; font-size: 11px; font-weight: 700; background: #fff7ed; color: var(--accent); padding: 3px 8px; border-radius: 999px; }
    .meta { font-size: 13px; color: var(--muted); }
    .btn { margin-top: auto; align-self: flex-start; background: var(--accent); color: #fff; text-decoration: none; padding: 6px 12px; border-radius: 10px; font-size: 12px; font-weight: 700; }
  </style>
</head>
<body>
  <div class="wrap">
    <header class="hero">
      <div>
        <h1 style="margin:0;font-size:20px;">מקומות מומלצים במצפה רמון</h1>
        <p style="margin:4px 0 0;color:var(--muted);font-size:13px;">נבנה ב-AbraCadabra</p>
      </div>
      <div id="weather" class="weather-pill">טוען מזג אוויר...</div>
    </header>
    <main id="places" class="grid"></main>
  </div>
  <script>
    function esc(v) {
      return String(v == null ? '' : v).replace(/[&<>"']/g, function (c) {
        return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c];
      });
    }
    async function loadApp() {
      var listEl = document.getElementById('places');
      var weatherEl = document.getElementById('weather');
      if (!window.kehiData) {
        listEl.innerHTML = '<div class="card">window.kehiData זמין רק בתוך הסימולטור או בפרסום ב-AbraCadabra.</div>';
        return;
      }
      var res = await Promise.all([
        window.kehiData.getWeather({ city: 'מצפה רמון' }),
        window.kehiData.getMitzpe('places', { limit: 6 })
      ]);
      var w = res[0];
      var p = res[1];
      weatherEl.textContent = (w && w.ok) ? (w.location + ': ' + w.temperatureC + '°C • ' + w.description) : 'מזג אוויר לא זמין';
      if (!p || !p.ok || !Array.isArray(p.items) || p.items.length === 0) {
        listEl.innerHTML = '<div class="card">' + esc((p && p.error) || 'לא נמצאו מקומות להצגה') + '</div>';
        return;
      }
      listEl.innerHTML = p.items.map(function (item) {
        return '<article class="card" data-kehi-group="place-card">' +
          '<span class="badge">' + esc(item.category || item.category_group || 'מקום') + '</span>' +
          '<h2 style="margin:0;font-size:16px;">' + esc(item.name_he || item.name_en) + '</h2>' +
          '<div class="meta">' + esc(item.address || '') + (item.hours ? ' • ' + esc(item.hours) : '') + '</div>' +
          (item.maps_url ? '<a class="btn" href="' + esc(item.maps_url) + '" target="_blank" rel="noopener">ניווט במפה</a>' : '') +
        '</article>';
      }).join('');
    }
    loadApp();
  </script>
</body>
</html>
```
