# Xpace Chat API contract v1 (server ↔ web app ↔ CRM bridge)

Base `/api`. JSON. Auth: cookie `xc_session` (set by `/auth/login` or `/auth/sso`), or header `Authorization: Bearer <token>`.
Errors: `{ error: { code, message } }` with 4xx/5xx. Times ISO-8601 UTC. Pagination: `?limit=&before=<iso>`.
Every list the UI needs is shaped for the screen, not for the table.

## Auth / me
- `POST /auth/login {email, password}` → `{ me }`
- `POST /auth/forgot {email}` → `{ ok: true }` always (same answer for an unknown email). A 6-digit code goes to the person's WhatsApp, or to `password-reset.txt` in the data folder.
- `POST /auth/reset {email, code, password}` → `{ me }` and a session cookie; 400 `bad_code`, 429 `too_many_tries`.
- `GET /mail`, `PUT /mail {host, port, security: ssl|starttls|none, user, pass?, from, from_name?}`, `POST /mail/test` (admin with the settings right). The password is never returned (`has_password` only). When email is set up, `/auth/forgot` emails the code first, then WhatsApp, then the file.
- `POST /auth/password {current, password}` (signed in) → `{ ok: true }`; 400 `bad_current`. Other sessions of that person end.
- `POST /auth/sso {token}` → token = base64url(json{staff_email, name, role, rights, crm_staff_id, exp}) + "." + hex HMAC-SHA256(settings.crm.sso_secret). Creates/updates staff. → `{ me }`
- `POST /auth/logout`
- `GET /me` → `{ id, name, role, rights[], lang, live, setup_pct, counts: { waiting, drafts, followups, approvals } }`
- `GET /i18n/:lang` → flat `{ key: text }`

## Rooms & messages
- `GET /rooms?filter=waiting|drafts|followups|all|team|internal&staff=<id|me|all>&q=` → `[{ id, kind, title, contact: {id,name,phone_masked,stage,area,salesperson_id,salesperson_name,consent_offers,optout}, channel: {id,kind,label}, last: {text,at,dir}, badges: ['waiting','draft_ready','followup_due','internal'], waiting_min, draft_id, unread, taken_over_by_name }]`
- `GET /rooms/:id` → `{ room, contact, members: [{name, kind, channel}], window: {open: bool, minutes_left}, taken_over_by, can_send: bool, read_only_reason }`
- `GET /rooms/:id/messages?before=` → `[{ id, dir, via, text, media, from_name, from_kind customer|staff|bot|external, channel_kind, translation, at, draft: {id,text,intent,drafter,note,status,template_name} | null }]`  (draft attached to the message it answers; pending drafts also in `pending_drafts`)
- `POST /rooms/:id/send {text, to_contact_id?, channel_account_id?, schedule_at?}` → human-typed reply: goes through the gate → `{ status: sent|would_send|blocked|scheduled, reason }`
- `POST /rooms/:id/draft` → ask the AI for a new draft → `{ draft }`
- `POST /rooms/:id/takeover` / `POST /rooms/:id/handback`
- `POST /rooms/:id/summary` → `{ text }`
- `GET /rooms/:id/tasks`, `POST /rooms/:id/tasks {title, assignee_staff_id, due_at, source_message_id?}`

## Drafts
- `POST /drafts/:id/approve {text?}` (text = approve with my edit) → `{ status, reason }`
- `POST /drafts/:id/reject {reason?}`
- `POST /drafts/:id/schedule {at}`
- `POST /drafts/:id/cancel`

## Follow-ups
- `GET /followups` → `{ due_today: [row], tomorrow: [row], later: [row], scheduled: [row] }` row = `{ id, contact: {id,name}, room_id, step, due_at, draft: {id,text,template_name,status}, quiet_days, next: [{when,label}] }`
- `POST /followups/:id/skip`
- `GET /followup-rules` → `[{id, stage, step, days, template_id, template_name, active}]` + `settings.followups_enabled, quiet_start, quiet_end, max_per_stage`
- `PUT /followup-rules {rules:[...], followups_enabled, quiet_start, quiet_end, max_per_stage}` (manage_followups)

## Templates / saved messages
- `GET /templates` → `[{id,name,kind,category,language,body,status,usable_for_bulk}]`
- `POST /templates`, `PUT /templates/:id`, `POST /templates/:id/status {status}`, `DELETE /templates/:id`
- `POST /templates/:id/test` → `{ preview }` (nothing sent)

## Bulk send
- `POST /bulk/preview {filters, template_id, route}` → `{ count, skipped: [{contact_id,name,reason}], sample: [{contact_id,name,salesperson_name,last_in_at,route}], est_cost, route_used, spend_month, cap }`
  filters = `{ stages[], areas[], sources[], quiet_days_min, consent_only: true, contact_ids[], phones[] }`
- `POST /bulk {name, filters, template_id, route, when: {mode: on_approval|at|spread, at?, per_day?, days?}}` → `{ bulk }`
- `POST /bulk/:id/submit` → pending_approval; `POST /bulk/:id/approve` (approve_campaign, not preparer); `/reject {reason}`; `/pause`; `/resume`; `/cancel`
- `GET /bulk` → list with `{ id, name, state, count, sent, replied, skipped, est_cost, when, prepared_by_name, approved_by_name, created_at }`
- `GET /bulk/:id` → detail + recipients

## Internal rooms & tasks
- `GET /internal/rooms` → `{ teams: [room], projects: [room] }` room = `{ id, kind, title, channel_kind, member_count, open_tasks, unread, last }`
- `POST /internal/rooms {kind: team|project, title, contact_id?, member_staff_ids[], channel_account_id?, external_id?}`
- `GET /tasks?room_id=&assignee=me|all&state=open|done` → `[task + assignee_name + room_title]`
- `POST /tasks/:id/done`, `POST /tasks/:id/reopen`, `PUT /tasks/:id`
- `GET /rooms/:id/suggestions` → AI-spotted items for recent messages `[{message_id, kind: task|customer_notice, title, assignee_staff_id?, due_at?, draft_text?}]`
- `GET /whereabouts` → `[{staff_id, name, where, until}]` (from tasks + calendar when CRM bridged)

## Team / owner
- `GET /team/overview` → `{ kpis: {new_leads_week, first_reply_min, drafts_unedited_pct, measurements_booked, spend_wa_rm, spend_ai_rm}, waiting: [{room_id, contact_name, salesperson_name, waiting_min, stage}], team: [{staff_id, name, account_label, owner_kind, chats_today, drafts_sent, on_leave, covered_by}], internal_feed: [{at, from, text, room_id}] }`
- `GET /approvals` → `[{id, kind, text, ref, requested_by_name, created_at, actions: [...]}]`
- `POST /approvals/:id/approve|reject {reason?}`
- `POST /rooms/:id/assign {staff_id}`

## Connect (admin)
- `GET /connect` → `{ accounts: [account + staff_name + status + last_check], meta: {connected, waba_id, templates_count, live}, wecom: {connected, staff_count, groups}, setup: {steps: [{key, done}], pct, can_go_live} }`
- `POST /connect/accounts {kind: whatsapp_link, label, staff_id, owner_kind}` → account
- `GET /connect/accounts/:id/qr` (SSE: `event: qr|linked|disconnected|error`)
- `POST /connect/accounts/:id/{restart,disconnect,remove}`
- `POST /connect/accounts/:id/agree` (own number, by that staff only) / `/stop`
- `PUT /connect/accounts/:id {label, staff_id, approvers[], owner_kind}`
- `POST /connect/meta/paste {access_token, waba_id, phone_number_id?, app_secret?, verify_token?}` (app_secret is needed to accept Meta's signed webhooks) · `POST /connect/meta/app {app_id, config_id, app_secret}` · `POST /connect/meta/exchange {code}` · `POST /connect/meta/refresh` · `POST /connect/meta/disconnect` · `GET /connect/meta/webhook-info`
- `POST /connect/wecom {corp_id, bot_id, secret, token, aes_key}` · `POST /connect/wecom/disconnect`
- (0.6.0) `POST /connect/golive` and `/connect/testmode` are gone: the app is always live. `GET /connect` `setup` is now `{steps: [{key, done}], left, pct, next}` (guidance only, never a lock) and `meta` also has `has_secret`, `verify_token`; the response has `webhook: {meta_url, verify_token}`.
- `PUT /connect/accounts/:id {label, staff_id, owner_kind, backup_account_id}`: `backup_account_id` pairs a phone with a Meta number (or the other way round) as backup; 400 `bad_backup` if both are the same kind.
- `GET /link-health` → per phone `{id, state, hint, reasons…}` used for the plain 'linked but no chats' / 'phone disconnected' messages.

## Scheduling (0.6.0)
- `GET /scheduled` → `{items: [{kind: message|followup|bulk, id, at, text, who, room_id, status, can_edit, people?, mode?}], tz_offset_min, enabled, bulk_enabled, followups_enabled}`: everything waiting to go out, visible to its owner (managers see all).
- `POST /drafts/:id/schedule {at, text?}` · `PUT /drafts/:id/schedule {at?, text?}` (change the time or text) · `POST /drafts/:id/cancel`
- `PUT /bulk/:id/schedule {at}` · `POST /bulk/:id/cancel` (before it starts)
- The queue is stored in the database; a restart does not lose it. Held items (found in test mode before 0.6.0) are `status:paused` with a one-time notice.
- `PUT /settings {tz_offset_min}`: the tenant's time zone (default Malaysia, 480). All times in the app are shown and entered in it.

## Plain API key for other AI tools (0.6.0)
- `GET /connect/v1/api-key` (admin) → `{ok, base, tools, link: {id, access, created_at, last_used_at, created_by} | null}`; `POST /connect/v1/api-key` → `{ok, key, base, link}` (key `xca_` + 48 hex, **shown once**, only its sha256 is stored; a second POST makes a new key and the old one stops at once).
- Levels and disconnect use the same `/connect/v1/links/:id/{access,test,reset,disconnect}` as Claude (Look only / Allow changes).
- REST, base `https://<address>/api/ai/v1`, header `Authorization: Bearer <key>` (https or loopback only; browsers' `Origin` header is refused; rate limited): `GET /` (who am I), `GET /tools` (names, descriptions, input schema, `needs: change`), `POST /tools/:name {…args}` → `{ok, result}`. Same tools, same limits as the Claude connector; it never sends a message to a customer.

## Leads to the paired CRM (0.3.0)
- `GET /connect/v1/links` (admin) also returns `crm_leads: {waiting, unsure, message} | null` (null when no CRM is paired).
- `POST /connect/v1/links/:id/send-leads` (admin) → `{ok, sent, crm_leads}`: send what is waiting now (also gives refused leads another go).
- `POST /contacts/:id/send-to-crm` → `{ok, crm: {state, message, can_send}}`: queue one lead by hand (older chats, or "send again" after an unclear answer; the page warns first).
- `POST /contacts/:id/already-in-crm` → `{ok, crm}`: the person checked, the lead is there; it is never sent.
- `GET /rooms/:id` contact has `crm_push: {state: waiting|sending|unsure|sent, message, can_send} | null`.

## Claude (MCP) connector (0.4.0)
- `POST /connect/v1/cards/claude/connect` (admin) → `{ok, key, address, connector, link}`: makes the one Claude key (`xcc_` + 48 hex). **The only response that ever holds the key.** Only its sha256 is stored. 409 if one exists already.
- `POST /connect/v1/links/:id/reset` (admin, the Claude link) → same shape with a new key; the old key stops at once; access goes back to Look only. `POST /connect/v1/cards/claude/reset` does the same by card.
- `POST /connect/v1/links/:id/{test,disconnect,access}` work for the Claude link like for any link (access needs `confirmed:true` to raise to `change`). `GET /connect/v1/cards` has the `claude` card with `state_code` (waiting|connected|paused|key_rejected|unreachable), `last_used_at`, `connector {base, tools {read[], write[]}}`; never the key.
- `POST /mcp/<key>` or `POST /mcp` with `Authorization: Bearer <key>`: MCP over Streamable HTTP, plain JSON replies, no sessions (JSON-RPC 2.0; protocol 2025-06-18, 2025-03-26, 2024-11-05). Methods: `initialize`, `notifications/initialized` (202), `ping`, `tools/list`, `tools/call`. Batches up to 20, body up to 256 KB, reply up to 1 MB, 40 tool calls a minute per key (over that, the call answers with a plain "too many calls" error). A browser request carrying a foreign `Origin` is 403. A bad or missing key is HTTP 401 (JSON-RPC error -32001, `WWW-Authenticate: Bearer`); too many bad tries from one address or too many calls on one key is 429; paused is 423; any other method than POST is 405.
- Tools. Read (always): `get_overview`, `list_conversations`, `get_conversation`, `list_leads`, `get_lead`, `find_contact`, `list_pending_drafts`. Write (only when the link is Look and change; hidden from `tools/list` and refused on a direct call otherwise): `create_lead`, `create_draft_reply`. No tool sends, approves or schedules a message.
- Claude acts as the admin who pressed Connect: it sees only customer conversations that person can see. Private notes, team/direct/project rooms, staff contacts and the not-sorted tray are never returned; phone numbers are partly hidden.
- Audit events: `link.connected`, `mcp_key.create`, `link.access_changed`, `link.tested`, `link.reset`, `link.disconnected`, `mcp_key.revoke`, and one `mcp.<tool>` per tool call (ids only, `ok`, `refused`). No key, no customer text.

## Teach the AI
- `GET /brain` → brain without api_key (has `api_key_set: bool`) + `todo: [string]` + `usage_month`
- `PUT /brain {…}` (settings right) · `POST /brain/try {customer_name, message}` → `{ draft, intent, drafter, note, tokens }`
- `POST /brain/business {company_name, what_you_do, areas, packages, measurement_fee, transport_fee, materials, lead_time, payment_terms, warranty, address_hours, not_do, other}` → writes the fact sheet

## Settings, spend, reports, tray
- `GET /settings` / `PUT /settings` (settings right; audited per key)
- `GET /staff` / `POST /staff` / `PUT /staff/:id`
- `GET /spend?month=` → `{ rows: [{category, count, est_cost, would_cost}], total, cap, warn, dryrun_count }` · `GET /spend.csv`
- `GET /reports/audit?limit=`
- `GET /tray` (own-number owner only) → `[{phone_hash, name_guess, last_at, count, messages:[...]}]` · `POST /tray/:hash/customer {name}` · `POST /tray/:hash/personal`
- `POST /quick-add {name, phone, source, area, note}` → `{ contact, room, assigned_to }`

## Events
- `GET /events` SSE: `room` (updated room row), `draft` (new/changed), `approval`, `connect` (account state), `toast` ({level,text}).

## Webhooks (no auth, signature-checked)
- `GET|POST /hooks/meta` · `POST /hooks/wecom`

## Version (0.6.0)
`GET /api/version` (no sign-in) returns `{ "version": "0.6.0" }`. `GET /api/health` and `GET /api/me` also carry `version`. The number is read from `package.json`.

## Link health (0.5.0)
`GET /api/link-health` (signed in) returns `{ accounts: [...] }`, one entry per linked-by-scan WhatsApp phone: `id, label, phone, state, own, hint, recorded, held, set_aside, reasons, linked_at, last_at`. Admins (settings right) see every phone; everyone else sees only their own. `hint` is one of `ok, waiting_first, own_not_agreed, no_phone, held_private, set_aside, not_linked`. Only counts are kept (setting `link.stats.<id>`), never message text. A fresh scan resets the counts.


## Learn from your chats (0.7.0, needs the Settings right)
- POST /api/brain/learn/read {files:[{name,b64|text}], ours?} -> {chats, messages, exchanges, transcript, estimate} (nothing saved)
- POST /api/brain/learn/site {url} -> {text, chars} (public websites only)
- POST /api/brain/learn/propose {transcript?, website?} -> {items:[{kind,title,text,customer?}]} (calls the AI; nothing saved)
- POST /api/brain/learn/apply {items} -> {added} (saves what a person kept)
- GET /api/brain/examples, DELETE /api/brain/examples/:i
- GET /api/brain/lessons, POST /api/brain/lessons/:id {keep}


## Follow-up sequences (0.7.1) - right: manage_followups
- GET /api/sequences: sequences with steps and counts, stage list, daily cap, linked numbers, salespeople.
- POST /api/sequences, PUT /api/sequences/:id, DELETE /api/sequences/:id: body {name, active, mode: draft|auto, send_from: chat|company|own, conditions {stages, areas, sources, salespeople, min_messages, offers, words}, steps [{wait_hours, send_time "HH:MM", text}]}.
- POST /api/sequences/:id/on {on}; POST /api/sequences/preview {id?, conditions}; GET /api/sequences/:id/runs; POST /api/sequence-runs/:id/stop; PUT /api/sequences/config {daily_cap}.

## Translation (0.11.0, phase 1)
- GET /api/translate/config: {enabled, provider, providers, languages, active_languages, key_ready, key_problem}. PUT (right: settings) {enabled?, provider?}. Off by default.
- GET /api/me/reading, PUT /api/me/reading {lang: ''|en|ms|zh, mode: auto|translated|bilingual}: this person's reading language ('' = app language) and display mode.
- GET /api/rooms/:id/messages: each message gains `tr` {state: same|done|failed|pending|off|none|unclear, id, text, src, flagged}; the reply gains `reading` {lang, mode, pref, enabled}.
- POST /api/rooms/:id/translate {message_id?, retry?}: translate now into the caller's reading language (one message, or the latest 20) -> {lang, done, failed, unavailable}.
- POST /api/translations/:id/flag {note?}: report a wrong translation. GET /api/translate/flags and POST /api/translate/flags/:id/resolve need the settings right; the list only holds rooms the caller may open.
