# Sanaa Booking Connector — specification, version 1

A software partner implements this once so Sanaa can read and change bookings in the partner's own system while an AI receptionist is on a call. Sanaa calls your server; you answer with JSON. A complete working example is in [`examples/reference-connector/server.mjs`](../examples/reference-connector/server.mjs) (about 200 lines, no dependencies), and a conformance check (`POST /api/v1/connector/test`) tells you exactly what to fix.

## How a call works

```
Caller ↔ Sanaa (voice AI) ──tool call──▶ Sanaa gateway ──signed HTTPS──▶ your connector ──▶ your booking system
```

While the caller waits, the AI asks for open times, books, cancels and so on. Every answer is read aloud, so speed and correctness matter: **aim for under 2.5 seconds per answer; Sanaa gives up at 4.5 seconds.**

## Request

`POST {base_url}/{operation}` — for example `POST https://api.yourcompany.com/sanaa/book`.

| Header | Meaning |
|---|---|
| `Content-Type: application/json` | |
| `Sanaa-Connector-Version: 1` | Contract version |
| `Sanaa-Request-Id` | Unique per request; log it |
| `Sanaa-Timestamp` | Unix seconds when the request was signed |
| `Sanaa-Signature` | `v1=` + hex HMAC-SHA256 of `"<timestamp>.<raw body>"` using your connector secret |
| `Idempotency-Key` | Present on every operation that changes something (see below) |

Body (the "envelope"):

```json
{
  "version": "1",
  "operation": "book",
  "request_id": "req_9f2c...",
  "test": false,
  "tenant": { "id": "Sanaa's id for the customer", "external_id": "your id for that customer" },
  "call": { "id": "the phone call's id, or null" },
  "args": { "starts_at": "2026-11-20T14:00:00.000Z", "customer_name": "Jane", "customer_phone": "+15551234567" }
}
```

- `tenant.external_id` is the id **you** gave when you created the customer in Sanaa. Use it to find the right business in your system.
- `test: true` means a conformance or sandbox run: use test data and make **no real bookings**.
- `args` contains only the arguments listed below for that operation. Nothing else is ever sent.

### Verify the signature — always, before anything else

```js
import { createHmac, timingSafeEqual } from 'node:crypto'

function verify(secret, rawBody, signatureHeader, timestampHeader) {
  const ts = Number(timestampHeader)
  if (!Number.isInteger(ts) || Math.abs(Date.now() / 1000 - ts) > 300) return false   // stale: reject
  const expected = Buffer.from('v1=' + createHmac('sha256', secret).update(`${ts}.${rawBody}`).digest('hex'))
  const received = Buffer.from(signatureHeader ?? '')
  return expected.length === received.length && timingSafeEqual(expected, received)
}
```

Compute the HMAC over the **exact raw bytes** you received, not a re-serialised object. Reject a bad or missing signature with `401`. The conformance check sends a wrongly signed request and fails you if you answer it.

## Operations

All eleven are required. Responses are JSON objects with HTTP `200` on success. Fields not listed are ignored, strings are cut at 500 characters and lists at 50 items.

| Operation | `args` | Success response (required fields in **bold**) |
|---|---|---|
| `check-availability` | `date` (YYYY-MM-DD), optional `service_id`, `staff_id`, `window_start`, `window_end` (HH:MM, local), `find_next_available` | **`available`** (bool), **`slots`**: list of {**`starts_at`**, **`ends_at`** (ISO 8601), **`spoken_time`** (e.g. "2:30 PM", in the business's local time), `staff_id`, `staff_name`}; optional `date` |
| `hold-slot` | `starts_at`, `ends_at`, `staff_id` | **`success`**; optional `hold_seconds` |
| `book` | `starts_at`, `customer_name`, `customer_phone`, optional `service_id`, `service_ids`, `staff_id`, `customer_email` | **`success`**, `booking_id` (required when `success` is true), `confirmation` |
| `find-booking` | `caller_phone` and/or `booking_id`, `customer_name` | **`found`**, **`bookings`**: list of {**`id`**, **`starts_at`**, `status`, `service_name`, `staff_name`, `spoken`} — upcoming, confirmed bookings only |
| `cancel-booking` | `booking_id`, optional `reason` | **`success`** |
| `reschedule-booking` | `booking_id`, `new_starts_at` | **`success`**; optional `booking_id`, `new_starts_at`, `new_ends_at` |
| `customer-history` | `caller_phone` | **`found`**; optional `customer_name`, `last_visit`, `total_visits`, `top_service`, `last_service_name`, `last_service_id` |
| `services` | none | **`services`**: list of {**`id`**, **`name`**, **`duration_minutes`**, `price`, `description`} |
| `upsell-suggestions` | `service_id`, `caller_phone` | **`suggestions`**: same item shape as `services` (an empty list is fine) |
| `add-to-waitlist` | `name`, `phone`, optional `service_id`, `preferred_date`, `notes` | **`success`** |
| `business-profile` | none | **`business_name`**, **`timezone`** (IANA), **`services`**, **`staff`** (list of {**`id`**, **`name`**}); optional `hours`, `transfer_number`, `faqs` (list of {question, answer}), `policies` ({`cancellation_cutoff_minutes`, `min_booking_lead_minutes`, `store_policy`}) |

`hours` is `{ "monday": { "open": "09:00", "close": "17:00" }, "sunday": { "closed": true }, ... }` using lowercase weekday names.

Every response may also include `spoken` (a sentence the AI can say as-is) and `error` (for your logs). Include `spoken` on refusals ("Sorry, that time was just taken.") so the caller hears something natural.

## Status codes

| Situation | Answer with |
|---|---|
| Success | `200` and the body above |
| Bad or missing signature, stale timestamp | `401` |
| Unknown booking | `404` |
| Slot already taken / conflict | `409` |
| Invalid input | `400` or `422` |
| Your system is having trouble | `5xx` (or `429`) |

Sanaa turns these into results the AI understands: `404` → not found, `409` → conflict, `400/422` → validation error, `5xx` on a lookup → "temporary failure", **`5xx` or no answer on a change → "unknown result"** (Sanaa tells the caller it could not confirm, and the AI checks with `find-booking` rather than guessing). A `200` whose body does not match the shapes above is treated the same way, so return the documented shape exactly.

## Idempotency

Every operation that changes something (`hold-slot`, `book`, `cancel-booking`, `reschedule-booking`, `add-to-waitlist`) carries an `Idempotency-Key`. **If you see a key you have already processed, return the same answer and do not repeat the change.** The key is stable if the call is retried and different for a genuinely new request, so booking, cancelling and booking the same time again works. Sanaa never retries a change itself; the voice platform may. Reads are retried once on a network error or `5xx`.

## Limits and rules

- **HTTPS only**, a public hostname. URLs pointing at private, internal or cloud-metadata addresses are refused when you save the connector and again before each call. Redirects are not followed.
- **Time:** 4.5 seconds in total per call, including any retry.
- **Size:** responses over 1 MB are rejected.
- **Secret:** shown once when the connector is created (`csec_…`). Rotate it with `rotate_secret: true`; there is no overlap window, so update your server first or accept a brief failure.
- **Test data:** requests with `"test": true` must never touch real customers or real calendars.

## Conformance check

`POST /api/v1/connector/test` runs about twenty signed requests in test mode and returns a report. Required checks: business profile, services, availability (with at least two open slots in the next 14 days of your **test** calendar), hold, book, **same `Idempotency-Key` returns the same booking**, **double-booking is refused**, find, reschedule, cancel, **a cancelled booking is no longer listed**, cancelling an unknown booking is a clean error, invalid input is a clean error, customer history, upsell, waitlist, **a wrongly signed request is rejected**, and 95% of answers under 2.5 seconds. Optional (warning only): a request signed an hour ago is rejected.

Passing is required before Sanaa routes a live call to your connector.
