The open-source AI receptionist for businesses. Answers every call, books the appointment and hands over to a person when needed. You own the code and the data.
TypeScript ai-receptionistanswering-serviceappointment-bookinglivekitlocal-firstmcpopen-sourceself-hostedsiptelephonytypescriptvoice-agentvoice-ai
Own phone system: putting calls through 3CX, checked on 3CX 20 (PR 2030)
Tim Gutberlet0b3973cd93e9
diff --git a/docs/architecture.md b/docs/architecture.mdindex 8a8f71a9..029368c8 100644--- a/docs/architecture.md+++ b/docs/architecture.md@@ -44,23 +44,23 @@ Out of scope for v1: messaging channels, outbound campaigns, multi-location rout## 4. Components-| Component | Choice | Notes |-|---|---|---|-| Phone numbers + PSTN | **Telnyx** (default: FQDN connection to LiveKit SIP); Twilio as second adapter (Elastic SIP Trunking); a business's own phone system or SIP provider by SIP trunk ("Own phone system"); Plivo later; LiveKit Phone Numbers for zero-config hosted inbound | One `TelephonyProvider` interface: search/buy/port numbers, SIP trunk to LiveKit, outbound, transfer, status webhooks |-| Media / SIP bridge | **LiveKit** server + LiveKit SIP (self-hosted); LiveKit Cloud (US region) for the hosted version | Rooms make listen-in and take-over trivial |-| Voice agent | **LiveKit Agents, TypeScript** (agents-js); Python/Pipecat as fallback adapter | Imports the registry's Zod schemas; audio turn detector, tool calling, DTMF, noise cancellation |-| Voice pipeline | **Cascaded** by default, each stage chosen by config: AssemblyAI Universal-3 Pro with `max_accuracy` turn ends (STT; Deepgram Flux as alternative) → an OpenAI mini model, OpenAI direct (LLM; OpenRouter, Anthropic, Gemini, Groq or Mistral as alternatives) → ElevenLabs (TTS; Cartesia as alternative). **Realtime** as an option: one speech-to-speech model (OpenAI Realtime, gpt-realtime-mini by default; Gemini Live later) hears the caller and answers in its own voice, picked under Server admin › Providers › Answering calls. Then the assistant speaks with one of the model's own voices, picked per assistant (`assistants.realtime_voice`, Settings › Assistant › Voice; '' is marin, `REALTIME_DEFAULT_VOICE`), and there is no cached greeting; warm transfers work as on the three stages, with the connecting line in the realtime voice and the consult leg on OpenAI's speech and transcription models (same key); the model speaks the greeting. When the model's connection is not open within 4 s at the start of a call (its connect timeout), the three stages answer that call when the install has them, with their own greeting and no extra line; without them the call waits for the model's next try and asks for the greeting once it is connected (`apps/agent/src/realtime-connect.ts`). The fixed lines (silence reminders, closing line, goodbye, time limit, busy line) are made by OpenAI's speech model (`gpt-4o-mini-tts`) in the realtime voice with the same key, cached like the greeting, and played while the model's own replies are off (`apps/agent/src/realtime-lines.ts`); asked to say them, the model often said something else. With other languages allowed, and when the line cannot be made in time, the model is asked to say it When the three stages' voice provider fails during a call (quota used up: ElevenLabs then sends no audio and no error; a refused key, an outage, a timeout), the rest of the call is spoken by OpenAI's speech model (`gpt-4o-mini-tts`, the realtime voice) with any OpenAI key that is set up, else by another voice provider with a key (`VoiceWithBackup`, `apps/agent/src/pipeline.ts`); audio made that way is not cached as the voice's own | All behind adapters; final defaults after a latency test on real calls |-| API | **Hono** + `@hono/zod-openapi` + Zod, own `defineAction()` | One definition → REST, OpenAPI, MCP, client command |-| MCP | Official MCP TypeScript SDK v2, Streamable HTTP, stateless | API keys first, OAuth via Better Auth later |-| Database | **Postgres** + **Drizzle** (schema + migrations) | Source of truth |-| Sync to clients | Own **outbox** for writes + `ReadSyncAdapter` for reads; **Electric** default, PowerSync tested swap, LISTEN/NOTIFY + WebSocket possible | See §6 |-| Jobs | **pg-boss** | Post-call summaries, notifications, calendar sync, reminders, webhooks |-| Auth | **Better Auth**: email sign-in code + Google/Apple/Microsoft/GitHub sign-in, organizations, API keys, OAuth provider for MCP | Same OAuth consent can grant calendar access |-| Calendar | Own **Google Calendar**, **Microsoft Graph**, **CalDAV** (iCloud, Fastmail, Nextcloud), **Cal.com** and **Calendly** adapters | See §8 |-| Recordings | LiveKit egress into a `RecordingStore`: a shared directory (default, self-hosted) or any S3-compatible bucket (AWS S3, Cloudflare R2, Hetzner, Backblaze B2, MinIO), picked under Server admin › Providers › Recording storage (§12) | Played through an authenticated API route; signed URLs with S3. Each call keeps the store its recording is in (`calls.recording_store`) |-| Web app | **React SPA (Vite)** with local store, outbox, service worker | Built from the merged prototype (`prototypes/inbox-html`, Relay design) |-| Monorepo | **pnpm + Turborepo** | Layout in §11 |-| Billing (Linedesk Cloud only) | **Stripe** Checkout, subscriptions and recharge invoices; usage paid from a prepaid balance in our own append-only ledger in Postgres (no Stripe meters) | `packages/billing`, provider `none` by default |+| Component | Choice | Notes |+| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |+| Phone numbers + PSTN | **Telnyx** (default: FQDN connection to LiveKit SIP); Twilio as second adapter (Elastic SIP Trunking); a business's own phone system or SIP provider by SIP trunk ("Own phone system"); Plivo later; LiveKit Phone Numbers for zero-config hosted inbound | One `TelephonyProvider` interface: search/buy/port numbers, SIP trunk to LiveKit, outbound, transfer, status webhooks |+| Media / SIP bridge | **LiveKit** server + LiveKit SIP (self-hosted); LiveKit Cloud (US region) for the hosted version | Rooms make listen-in and take-over trivial |+| Voice agent | **LiveKit Agents, TypeScript** (agents-js); Python/Pipecat as fallback adapter | Imports the registry's Zod schemas; audio turn detector, tool calling, DTMF, noise cancellation |+| Voice pipeline | **Cascaded** by default, each stage chosen by config: AssemblyAI Universal-3 Pro with `max_accuracy` turn ends (STT; Deepgram Flux as alternative) → an OpenAI mini model, OpenAI direct (LLM; OpenRouter, Anthropic, Gemini, Groq or Mistral as alternatives) → ElevenLabs (TTS; Cartesia as alternative). **Realtime** as an option: one speech-to-speech model (OpenAI Realtime, gpt-realtime-mini by default; Gemini Live later) hears the caller and answers in its own voice, picked under Server admin › Providers › Answering calls. Then the assistant speaks with one of the model's own voices, picked per assistant (`assistants.realtime_voice`, Settings › Assistant › Voice; '' is marin, `REALTIME_DEFAULT_VOICE`), and there is no cached greeting; warm transfers work as on the three stages, with the connecting line in the realtime voice and the consult leg on OpenAI's speech and transcription models (same key); the model speaks the greeting. When the model's connection is not open within 4 s at the start of a call (its connect timeout), the three stages answer that call when the install has them, with their own greeting and no extra line; without them the call waits for the model's next try and asks for the greeting once it is connected (`apps/agent/src/realtime-connect.ts`). The fixed lines (silence reminders, closing line, goodbye, time limit, busy line) are made by OpenAI's speech model (`gpt-4o-mini-tts`) in the realtime voice with the same key, cached like the greeting, and played while the model's own replies are off (`apps/agent/src/realtime-lines.ts`); asked to say them, the model often said something else. With other languages allowed, and when the line cannot be made in time, the model is asked to say it When the three stages' voice provider fails during a call (quota used up: ElevenLabs then sends no audio and no error; a refused key, an outage, a timeout), the rest of the call is spoken by OpenAI's speech model (`gpt-4o-mini-tts`, the realtime voice) with any OpenAI key that is set up, else by another voice provider with a key (`VoiceWithBackup`, `apps/agent/src/pipeline.ts`); audio made that way is not cached as the voice's own | All behind adapters; final defaults after a latency test on real calls |+| API | **Hono** + `@hono/zod-openapi` + Zod, own `defineAction()` | One definition → REST, OpenAPI, MCP, client command |+| MCP | Official MCP TypeScript SDK v2, Streamable HTTP, stateless | API keys first, OAuth via Better Auth later |+| Database | **Postgres** + **Drizzle** (schema + migrations) | Source of truth |+| Sync to clients | Own **outbox** for writes + `ReadSyncAdapter` for reads; **Electric** default, PowerSync tested swap, LISTEN/NOTIFY + WebSocket possible | See §6 |+| Jobs | **pg-boss** | Post-call summaries, notifications, calendar sync, reminders, webhooks |+| Auth | **Better Auth**: email sign-in code + Google/Apple/Microsoft/GitHub sign-in, organizations, API keys, OAuth provider for MCP | Same OAuth consent can grant calendar access |+| Calendar | Own **Google Calendar**, **Microsoft Graph**, **CalDAV** (iCloud, Fastmail, Nextcloud), **Cal.com** and **Calendly** adapters | See §8 |+| Recordings | LiveKit egress into a `RecordingStore`: a shared directory (default, self-hosted) or any S3-compatible bucket (AWS S3, Cloudflare R2, Hetzner, Backblaze B2, MinIO), picked under Server admin › Providers › Recording storage (§12) | Played through an authenticated API route; signed URLs with S3. Each call keeps the store its recording is in (`calls.recording_store`) |+| Web app | **React SPA (Vite)** with local store, outbox, service worker | Built from the merged prototype (`prototypes/inbox-html`, Relay design) |+| Monorepo | **pnpm + Turborepo** | Layout in §11 |+| Billing (Linedesk Cloud only) | **Stripe** Checkout, subscriptions and recharge invoices; usage paid from a prepaid balance in our own append-only ledger in Postgres (no Stripe meters) | `packages/billing`, provider `none` by default |## 5. Action registry@@ -71,35 +71,39 @@ defineAction({name: 'call.markDone',input: z.object({ callId: z.string() }),permission: 'call:write',- apply: (store, input) => { /* optimistic local change, runs in the browser */ },- handler: async (ctx, input) => { /* authoritative, runs on the server, writes Postgres */ },+ apply: (store, input) => {+ /* optimistic local change, runs in the browser */+ },+ handler: async (ctx, input) => {+ /* authoritative, runs on the server, writes Postgres */+ },event: 'call.done',})```From that definition we generate:-| Surface | Generated |-|---|---|-| Web app | instant local mutation (`apply`) + outbox command, ⌘K entry |-| REST | `POST /v1/actions/<name>` + OpenAPI spec |-| MCP | one tool per action, same schema and permission; a result that can carry caller text comes back inside `untrusted_caller_content` (docs/api.md, MCP) |-| Voice agent | tool with the same schema (e.g. `appointment.book`) |+| Surface | Generated |+| ------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |+| Web app | instant local mutation (`apply`) + outbox command, ⌘K entry |+| REST | `POST /v1/actions/<name>` + OpenAPI spec |+| MCP | one tool per action, same schema and permission; a result that can carry caller text comes back inside `untrusted_caller_content` (docs/api.md, MCP) |+| Voice agent | tool with the same schema (e.g. `appointment.book`) || Browser agent | WebMCP tool on the page (`document.modelContext`) for each public action the signed-in person may run, same name and schema as MCP (docs/api.md, "In the browser") |-| Events | internal event per action; an assistant's webhook at call start, during the call (its lookups) and after the call (docs/webhooks.md) |+| Events | internal event per action; an assistant's webhook at call start, during the call (its lookups) and after the call (docs/webhooks.md) |Reads are defined once as named queries and exposed to the UI (live via sync), REST and MCP.### v1 actions (initial set)-| Area | Actions |-|---|---|-| Calls | `call.markDone`, `call.markNotDone`, `call.remind`, `call.clearReminder`, `call.markRead`, `call.markUnread`, `call.assign`, `call.callBack`, `call.delete` |-| Live call | `call.listen`, `call.takeOver`, `call.hangUp` |-| Bookings | `calendar.findSlots`, `appointment.book`, `appointment.reschedule`, `appointment.cancel` |-| Contacts | `contact.lookup`, `contact.update` |-| Agent-only | `call.takeMessage`, `call.transfer`, `call.end`, `call.flagUrgent` |-| Settings | `assistant.update`, `appointmentType.upsert`, `calendar.connect`, `calendar.setFlags`, `phoneNumber.setup`, `phoneNumber.verifyForwarding` |+| Area | Actions |+| ---------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Calls | `call.markDone`, `call.markNotDone`, `call.remind`, `call.clearReminder`, `call.markRead`, `call.markUnread`, `call.assign`, `call.callBack`, `call.delete` |+| Live call | `call.listen`, `call.takeOver`, `call.hangUp` |+| Bookings | `calendar.findSlots`, `appointment.book`, `appointment.reschedule`, `appointment.cancel` |+| Contacts | `contact.lookup`, `contact.update` |+| Agent-only | `call.takeMessage`, `call.transfer`, `call.end`, `call.flagUrgent` |+| Settings | `assistant.update`, `appointmentType.upsert`, `calendar.connect`, `calendar.setFlags`, `phoneNumber.setup`, `phoneNumber.verifyForwarding` |## 6. Sync: "commands up, data down"@@ -118,14 +122,14 @@ Reads are defined once as named queries and exposed to the UI (live via sync), R4. **Greeting.** Configurable greeting; AI disclosure on by default (configurable, §10).5. **Conversation.** The agent follows the assistant config (About the business, booking types, urgent and transfer rules). Its tools are registry actions:- | Tool | Effect |- |---|---|- | `contact.lookup` | Contact + history |- | `calendar.findSlots(type, window)` | Free slots = working hours ∩ free/busy of conflict calendars − buffers − min notice |- | `appointment.book` / `.reschedule` / `.cancel` | Writes the calendar event, stores `Booking`, links the call |- | `call.flagUrgent` | Marks urgent (e.g. "leak", "gas smell"), triggers notification |+ | Tool | Effect |+ | ----------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+ | `contact.lookup` | Contact + history |+ | `calendar.findSlots(type, window)` | Free slots = working hours ∩ free/busy of conflict calendars − buffers − min notice |+ | `appointment.book` / `.reschedule` / `.cancel` | Writes the calendar event, stores `Booking`, links the call |+ | `call.flagUrgent` | Marks urgent (e.g. "leak", "gas smell"), triggers notification || `transfer_call` → `call.transfer(to, name, urgent, result)` | Warm transfer to the transfer contact whose condition fits (see below); when nobody accepts, the contact's fallback: a message marked urgent, a message, or the next contact that fits |- | `call.end` | Hangs up politely |+ | `call.end` | Hangs up politely |**Limits on one call** (what a caller can make the assistant spend or send): at most 3 messages (`MESSAGES_PER_CALL`, each one is a push; only next steps with `kind: 'message'` count, so a note the API adds takes no slot) and 2 bookings (`BOOKINGS_PER_CALL`) per call, counted under a per-call advisory lock; members are not limited. `calendar.findSlots` on a call looks only in the calendars of the assistant that answered it. Links in a booking's reason are replaced with "[link removed]" before it reaches the calendar. A call flagged urgent while it ran stays urgent after the summary, and is never filed as spam (it becomes a callback). Test calls from the web app: 6 in 10 minutes and 20 a day per user over all their workspaces, and 200 a day on the install (`TEST_CALLS_PER_DAY`; reaching it logs an `ALERT` line). They count the tokens issued, used or not: each one is a row in the command log (`assistant.testCallToken`, its room, never the token), counted and written under one install-wide advisory lock, so neither a burst of tokens nor several API processes get past them. A test room opens at most one call.**Public demo calls** (`apps/api/src/demo-call.ts`, [public-demo.md](public-demo.md)): off unless `DEMO_CALLS=on`. A website's gateway (its own serverless function, never the browser) asks `POST /v1/demo/call` with a Bearer secret (`DEMO_GATEWAY_SECRET`, compared in constant time; registered before the sign-in guard, no CORS) for one of the install's demo assistants (`DEMO_ASSISTANTS`, industry to assistant id) and a peppered hash of the visitor's address. The API signs the same browser token as a test call, for one new room `demo-…`, with `demo: true` in the dispatch metadata: the agent adds "This is a two-minute demo." to the greeting and ends the call after `DEMO_CALL_MAX_SECONDS` (120) with its own line. The limits are counted like test calls, from the command-log rows of the tokens (`demo.callToken`, input `{industry, ipHash, country}`) under one install-wide advisory lock: per ipHash 3 an hour and 6 a day, tokens per day (`DEMO_DAILY_CALLS` 300), a daily budget (`DEMO_DAILY_USD`, each token at 210 s of call plus a summary with the overview's rates; $0 a call is refused), the demo workspace's spending cap, calls at once (live demo calls plus unjoined tokens of the last 60 s, `DEMO_MAX_CONCURRENT` 3), the demo workspace still safe (`DEMO_WORKSPACE_ID`, every demo assistant in it; no phone number, calendar connection or active webhook in it, the assistant neither recording nor putting anyone through) and whether the agent would answer; refusals of the install's own log `ALERT demo calls`. More than 20 wrong secrets from one address in 10 minutes get 429. The stale-call sweep ends a demo call still live 150 s after it started: the room is deleted first, and the call is filed only once that worked. The hourly `demoCalls.cleanup` job removes the `ipHash` from tokens older than 24 hours and clears demo calls older than `DEMO_TRANSCRIPT_DAYS` (7): transcript lines, activity, evaluation and knowledge questions deleted, title, summary and next steps emptied, the row kept (deleted) with its length so the spending cap still counts it. `apps/api/src/demo-workspace.ts` sets up the demo workspace from a data file.@@ -143,7 +147,7 @@ Reads are defined once as named queries and exposed to the UI (live via sync), R8. **After-call transcription** (`apps/api/src/after-call-transcript.ts`; Server admin › Features › After-call transcription, `afterCallTranscript.get/.set`, instance_settings `after_call_transcript`). A feature, not a provider: each service is connected once under Providers, and this only picks which connected one transcribes. **It uploads each call's recording file to the picked service**: OpenAI `gpt-transcribe`, Deepgram Nova-3 (pre-recorded, `diarize`, `utterances`, `mip_opt_out=true`: not used for training), AssemblyAI Universal (`speaker_labels`, upload then poll, the whole run within 480 s, below the job's 600 s expiry; the transcript is deleted there once read; a transcription it could not make is not retried) or ElevenLabs Scribe v2 (`diarize`, word times); the adapters are in `apps/api/src/transcriber.ts`, each with its size limit, 25 MB for all (a 30-minute call, the longest an assistant stays on, is about 24 MB; the API container has 256 MB), checked before the file is read, and no response body in any error. A recording on this server is sent as a Blob backed by the file (`openAsBlob`), not read into memory. The live transcript comes from the live speech to text (three stages) or the realtime model's transcriber: fast, but it mishears. Off until an instance admin picks a service there; nothing picks one by default (`afterCallTranscript.set`, audited as an admin change). Key: the one stored for that service under Providers (`transcriptKeyFrom` in `packages/actions/src/settings.ts`; ElevenLabs: speech to text or voice; OpenAI: speech to text, realtime model or language model; Deepgram and AssemblyAI: speech to text), the first that has one; never a key only in .env. A service not connected shows "Connect <service> first", a link to its provider. When the agent reports the recording (`call.setRecording`, after `call.finish`), the API queues the `call.transcribe` job (not for a workspace that keeps no recordings). It reads the recording from its store and gets text back, with speaker turns where the provider gives them. `apps/api/src/transcript-align.ts` puts it back onto the lines: the assistant's lines are exact (the text its voice spoke) and are the anchors (word alignment, longest common subsequence; numbers compared digit by digit, "five oh three" = "503"), and the words between them replace the caller's lines there; with speaker turns, the words of the speaker who said the assistant's lines never go into a caller line. Only caller lines change, in one transaction (the browser gets them over sync); the assistant's, team and tool lines stay. Less than half of the assistant's words found in the text: nothing changes. A failure for now (provider, bucket) is retried 3 times, a refusal for good (400, 401, 403, 404, 413, 415, 422) is not; then the live transcript stays. When a provider is selected and the call was recorded, the call's news waits for the corrected transcript (`call.finish` with `awaitTranscript` sets `calls.awaiting_transcript_until`, `apps/api/src/call-news.ts`): the agent sends `call.correctTranscript` after `call.setRecording` (the provider hears the recording now, at most 30 s; once per call, `transcript_requested_at`), summarizes the corrected lines with the same summary prompt and sends `call.finalize`, which stores that summary and queues the email, the "finished" push, the evaluation, the after-call webhook and the integrations (no 20 s delay then: the recording is saved). If the agent never gets there, the `CALL_RELEASE` job sends the news with the live summary after `AWAIT_TRANSCRIPT_MAX_SEC` (60 s) and queues the background transcription; whichever comes first takes the hold off, so the news goes once; a sweep every 5 minutes releases any hold still left (the job gave up). A `call.finalize` after the release changes nothing (the call keeps the summary its email went out with), and while held, a title or summary the team changed stays. Without a provider or a recording, the news goes at `call.finish`, as before. The provider gets hints (`apps/api/src/transcript-hints.ts`): the business, assistant and appointment type names, the contact's name and company only when a member saved them (a name from the live transcript may be the misheard one), at most 20 terms, and the language when the assistant speaks only one (else the provider detects it; Deepgram `multi`). Only names, no prompt text. A provider that refuses the hints (400, 422) is asked once more without them. Members are not told that the transcript was corrected.9. **Post-call job.** An LLM pass returns structured JSON: `title`, `summary`, `outcome`, `urgency`, `intent`, `actionItems[]`, `fields[]`, spam score. The call moves to the right view. There is no tool to take a message during the call (removed 2026-11-15): the assistant gets what the team needs and says the team will get back to the caller, and this pass writes the request as an action item. Besides the transcript it gets the action items already saved (only the message a transfer saves when nobody takes the call, `call.takeMessage`) and the details the collection steps got (`CallLog.details`: name, numbers, address, email, dates, each marked confirmed or a best guess); it may write only those phone numbers. A confirmed callback number makes a call it calls answered a call back, and without a summary confirmed details still leave a call back. With no number to call back on (no caller ID, none given) no item asks to call back or says the number is missing: the items say what the caller wants, the summary says no number was left, and a call back is filed as a message (`apps/agent/src/summary.ts`).10. **Notify.** Email per finished call and Web Push (opt-in per member and browser; VAPID keys from env; one notification per call that a flagged-urgent, message-taken (a transfer nobody took) or finished push updates; payload is who called plus, if opted in, one line); daily digest for the rest later. See [self-hosting.md](self-hosting.md#push-notifications).- **Who hears about calls** (`apps/api/src/email-routing.ts`; Settings › Assistant › Who hears about calls, the one place for call emails): one row per member with "Email for every call" (the member's own `member_notification_settings.email`; everyone switches their own, owners and admins the others' with `team.updateMemberNotifications`, an admin never an owner's) and a row "New teammates" (`workspace_settings.notify_email_default`, `notifications.setDefaults`: what a new teammate starts with; changing it first writes the old value as their own for every member who still followed it, so nobody's row flips). Everyone reads the rows with `callEmails.get`. An assistant's `email_rules` add people for some calls: up to 20 rules, each with "when the call is about" (`when`, required; there is no rule name), the members it sends to (`to`, also with "Email for every call" off) and optionally one of them to assign the call to (`assign`; an assign that is not one of the rule's members is saved as none). No rules: the every-call members get every call, nothing is stored. With rules, after the call one model request gets the numbered rules and the call and only says which rules fit (`{"rules":[n...],"reason":"..."}`); the code picks the recipients: the every-call members and the members of the fitting rules. The code also assigns: the first fitting rule, in list order, whose assignee is still a member, only while nobody has the call (`assignByRouting`). Nothing fits: the every-call members only. Rules are on only when the instance admin has set up a language model; without one the page offers only the switches and routing works as if there were no rules. A failed request or over routing's 120 requests an hour per workspace: the every-call members and every rule's members (fallback), as nobody can tell which rules fit. The decision is stored in `calls.email_route` (`mode`, `to`, `rules` (the topics (`when`) of the fitting rules, as they were then), `reason`, `assigned_user_id`, `problem`) before the email is sent, and a retry sends to exactly its `to`; the call view shows it as one line under "Emailed after the call" ("Emailed Dave and Mike · about water heaters, boilers or no hot water · assigned to Dave"), the model's reason behind a "?". Call emails go to members only: the rules name members, and the page shows each with their email address. The earlier single instruction with @mentions, its outside addresses (`email_recipients`) and their stop link are gone, and so are its columns (`email_routing`, `email_assign`).+ **Who hears about calls** (`apps/api/src/email-routing.ts`; Settings › Assistant › Who hears about calls, the one place for call emails): one row per member with "Email for every call" (the member's own `member_notification_settings.email`; everyone switches their own, owners and admins the others' with `team.updateMemberNotifications`, an admin never an owner's) and a row "New teammates" (`workspace_settings.notify_email_default`, `notifications.setDefaults`: what a new teammate starts with; changing it first writes the old value as their own for every member who still followed it, so nobody's row flips). Everyone reads the rows with `callEmails.get`. An assistant's `email_rules` add people for some calls: up to 20 rules, each with "when the call is about" (`when`, required; there is no rule name), the members it sends to (`to`, also with "Email for every call" off) and optionally one of them to assign the call to (`assign`; an assign that is not one of the rule's members is saved as none). No rules: the every-call members get every call, nothing is stored. With rules, after the call one model request gets the numbered rules and the call and only says which rules fit (`{"rules":[n...],"reason":"..."}`); the code picks the recipients: the every-call members and the members of the fitting rules. The code also assigns: the first fitting rule, in list order, whose assignee is still a member, only while nobody has the call (`assignByRouting`). Nothing fits: the every-call members only. Rules are on only when the instance admin has set up a language model; without one the page offers only the switches and routing works as if there were no rules. A failed request or over routing's 120 requests an hour per workspace: the every-call members and every rule's members (fallback), as nobody can tell which rules fit. The decision is stored in `calls.email_route` (`mode`, `to`, `rules` (the topics (`when`) of the fitting rules, as they were then), `reason`, `assigned_user_id`, `problem`) before the email is sent, and a retry sends to exactly its `to`; the call view shows it as one line under "Emailed after the call" ("Emailed Dave and Mike · about water heaters, boilers or no hot water · assigned to Dave"), the model's reason behind a "?". Call emails go to members only: the rules name members, and the page shows each with their email address. The earlier single instruction with @mentions, its outside addresses (`email_recipients`) and their stop link are gone, and so are its columns (`email_routing`, `email_assign`).Target latencies: answer < 1 ring after forward, first agent word < 1.2 s, turn latency < 800 ms, call summary ready < 10 s after hang-up.@@ -197,7 +201,7 @@ Target latencies: answer < 1 ring after forward, first agent word < 1.2 s, turn- `phoneNumber.release` only detaches such a number (nothing at a carrier), and deleting a workspace leaves nothing at a carrier either and removes its LiveKit trunks, in and out, at once.- **Putting a call through** from such a number goes out through the business's phone system, never the install's carrier account. `sipTrunk.setOutbound` { outbound: { host, transport: udp | tcp | tls, username, password } | null } stores where and how (the same encrypted rows; the whole of `outbound` is `sensitive` and the password never comes back). The password is given with every change: with the stored one, a changed host would be sent that password's digest. At most 10 changes in 10 minutes per workspace; refused for support access (impersonation), like the two password actions. The API writes one LiveKit outbound trunk, `linedesk-sipout-<workspace id>-<mark>`, with the workspace's phone system numbers as caller IDs, after the settings, a number or a release commit (one at a time per workspace); trunks of older settings go, and all of them without settings or numbers, or when the workspace is deleted. The mark is an HMAC (`SECRETS_KEY`) of the settings and the address dialled. `carrier.transferTrunk` answers `{ carrier: 'sip', trunkName }` for such a number (refused while nothing is set up or the host is refused: the assistant takes a message), and the agent dials through the trunk of that exact name or asks `carrier.provisionTransferTrunk { from }` to write it again.- **The host must be public** (`sipHostCheck`): refused are a private, loopback or link-local address, a name with such an address behind it, a name that does not resolve within 3 s, and this server's own addresses (`LIVEKIT_SIP_ENDPOINT`, `LIVEKIT_NODE_IP`, the host of `PUBLIC_URL`). Checked when saved, each time the trunk is written, and at each call's start (`carrier.transferTrunk`). Over UDP and TCP the trunk dials the address that was checked, not the name, and the trunk's name carries that address: when the name points elsewhere later, the agent finds no trunk of the new name and the API writes one for the newly checked address. Over TLS the trunk dials the name (the certificate is for it), so there LiveKit's own lookup decides. `SIP_ALLOW_PRIVATE_HOSTS=true` allows private addresses for a phone system in the same closed network, never loopback or link-local ones. All workspaces' calls leave from this server's address, so nothing on the internet should trust that address alone: a phone system or carrier that lets calls in by source address without a password could be dialled through by any workspace.-- **Checking the setup.** Incoming: the dialog says whether a call to one of the numbers has arrived (from the `calls` rows the browser has), else to call the number. Putting through: `sipTrunk.testCall` { to } rings one phone through the phone system with the stored settings (20 s, then hangs up; its own LiveKit room, no call row) and answers `{ ok: true }` or `{ ok: false, reason: sign_in | refused | no_answer | busy | unreachable }` (only the kind of failure, never the phone system's exact answer, so it is no probe for other servers). It is read-only for the action runner: no transaction and no lock are held while the phone rings, and a transfer of a live call never waits for it. The same rules as a transfer from such a number (the route's countries, never one of the workspace's own numbers); one at a time per workspace, at most 5 in 10 minutes per workspace and 30 on the install, counted per API process; refused for support access, over MCP for personal keys and before the email address is confirmed. The dialog has the steps for FreePBX (checked on FreePBX 15: a chan_pjsip trunk named after the user name, Authentication Both, Registration None, over TCP, plus an outbound route for the number; for putting through, the trunk's Context `from-internal`) for 3CX (checked on 3CX 20 Update 10, incoming calls only: a Generic VoIP Provider trunk with Type of authentication "Do not require - IP based", since 3CX otherwise sends REGISTER, which LiveKit SIP answers with 405; 3CX still answers the password challenge of the call; the outbound rule's prefix and the forwarding target are the number without `+`, because 3CX cuts `+` and the country code off; the rule needs a department; putting calls through 3CX is not confirmed, 3CX did not identify the trunk's calls in the test) and for any other phone system.+- **Checking the setup.** Incoming: the dialog says whether a call to one of the numbers has arrived (from the `calls` rows the browser has), else to call the number. Putting through: `sipTrunk.testCall` { to } rings one phone through the phone system with the stored settings (20 s, then hangs up; its own LiveKit room, no call row) and answers `{ ok: true }` or `{ ok: false, reason: sign_in | refused | no_answer | busy | unreachable }` (only the kind of failure, never the phone system's exact answer, so it is no probe for other servers). It is read-only for the action runner: no transaction and no lock are held while the phone rings, and a transfer of a live call never waits for it. The same rules as a transfer from such a number (the route's countries, never one of the workspace's own numbers); one at a time per workspace, at most 5 in 10 minutes per workspace and 30 on the install, counted per API process; refused for support access, over MCP for personal keys and before the email address is confirmed. The dialog has the steps for FreePBX (checked on FreePBX 15: a chan_pjsip trunk named after the user name, Authentication Both, Registration None, over TCP, plus an outbound route for the number; for putting through, the trunk's Context `from-internal`) for 3CX (checked on 3CX 20 Update 10: a Generic VoIP Provider trunk with Type of authentication "Do not require - IP based", since 3CX otherwise sends REGISTER, which LiveKit SIP answers with 405; 3CX still answers the password challenge of the call; the outbound rule's prefix and the forwarding target are the number without `+`, because 3CX cuts `+` and the country code off; the rule needs a department; putting through: 3CX takes a call of the trunk only from the address under Registrar/Server, so not through an address translation that changes it, asks for no password, and sends it to the trunk's Default route, or to the user of a DID that is entered exactly as dialled, with the `+`) and for any other phone system.- **Where these calls may go:** the destination policy treats them as their own route, `sip`: the countries of the workspace's phone system numbers only (the business's own lines and bill). The workspace's daily transfer minutes count; the install-wide minutes do not.- **An install without a carrier** (a self-hoster with only its own phone system) never runs `setup-sip`, so LiveKit has no dispatch rule. The number sync makes it when the first own trunk exists: `linedesk-inbound`, one room per call (`call-…`) with the voice agent, bound to the own trunks, as `setup-sip` makes it. `setup-sip` replaces it, own trunks included, once the operator adds a carrier. Putting calls through from such numbers needs no install trunk either.@@ -350,7 +354,7 @@ Better Auth's admin plugin was not used: it adds impersonation, user creation, p- its actor carries the admin (`Actor.apiKeyImpersonator`, from `actorForApiKey`): every command it runs records `commands.impersonated_by` = the admin (`impersonatorOf`, `apps/api/src/impersonation-guard.ts`), so the audit log lists them under impersonation, naming the admin. Reads are not commands, except `call.export` (`READS_LOGGED_WHEN_IMPERSONATED`, run-action.ts): with an admin behind it (signed in as the user, or such a key) it gets a `commands` row with the redacted input and no data, so every export of calls is in the audit log too;- Integrations › API keys says "Created by {admin} during support access" under the key (`created_during_support`, `created_during_support_by` = the admin's name, else address, in `apiKey.list`; never their id);- revoking a key while impersonating is a command like any other there: `commands.impersonated_by` names the admin.- A key still never manages keys, and the key keeps following its creator's role (the user's).+ A key still never manages keys, and the key keeps following its creator's role (the user's).**Command log.** Every non-read-only command is a row in `commands` (`apps/api/src/run-action.ts`), for idempotent replays and the audit log, kept as little as that needs (`apps/api/src/command-log.ts`). Inputs are stored with `sensitive` fields `[redacted]` (provider and carrier keys, invitation ids; the same names in the result's `data` too). Results keep their rows only by id (`rowIds`): a replay reads those rows again and returns them as they are now. Actions marked `logged: 'ids'` keep only ids, numbers and booleans of input and result data, every other value as `[omitted]`: `call.start`, `call.appendTranscript`, `call.finish`, `call.takeMessage`, `call.transfer`, `appointment.book`/`.cancel`/`.reschedule`, `contact.import`, `contact.merge` (only `keepId` and `mergeId`; the merged details are on the contact). Deleting a call or a contact cuts the commands about it (by `callId`, or for a contact `contactId`, `keepId` or `mergeId`, in input or result data; jsonb containment, served by GIN indexes on the unpruned rows) down the same way, in the same transaction. A daily job (`commands.prune`, 03:47; index on `created_at` of the unpruned rows) does the same for every command older than 90 days, except the audited actions (`AUDITED_ACTIONS`: team, admin, keys, integrations; a change of transfer contacts, `TRANSFER_CHANGE_ACTIONS`, is pruned too but keeps its `data.transferChanges`), whose inputs the audit log shows; `pruned_at` says when. What stays of every command: who, when, which action, workspace, refused or not, the impersonating admin.@@ -407,8 +411,16 @@ Better Auth's admin plugin was not used: it adds impersonation, user creation, p"stt": { "provider": "deepgram", "api_key": "…" },"llm": { "provider": "openrouter", "api_key": "…", "model": "…" },"tts": { "provider": "elevenlabs", "api_key": "…", "model": null, "voice_id": null },- "recording": { "provider": "s3", "endpoint": "https://….r2.cloudflarestorage.com", "region": "auto", "bucket": "…",- "access_key_id": "…", "secret_access_key": "…", "prefix": null, "force_path_style": null }+ "recording": {+ "provider": "s3",+ "endpoint": "https://….r2.cloudflarestorage.com",+ "region": "auto",+ "bucket": "…",+ "access_key_id": "…",+ "secret_access_key": "…",+ "prefix": null,+ "force_path_style": null+ }}```@@ -444,15 +456,15 @@ For `apps/agent/src/config.ts`: `stt.model`, `llm.model`, `tts.model` and `tts.v- **Server admin** (`instance:admin`, a property of the user, granted by `context.ts` only in a session that passed the admin sign-in check): Server admin, and creating workspaces. **Only server admins create workspaces** (decided 2026-11-15): the app (`POST /v1/workspaces`), the setup MCP's `workspace_create` and Server admin › Workspaces › New workspace, all through `workspace.create` (`apps/api/src/workspace-creation-handlers.ts`; the app and the setup MCP keep their own checks in front). The app has one New workspace dialog (`apps/web/src/shell/NewWorkspace.tsx`, from the workspace menu and from Server admin › Workspaces, decision Q8): Owner "Me" sends `POST /v1/workspaces` and opens the new workspace; Owner by email runs `workspace.create` with that owner and stays where it was. With an owner by email: through Add user, an existing confirmed account becomes the owner at once, anyone else gets an owner invitation; the admin does not join. Without an owner (the app, the setup agent), or with the admin's own address: the admin becomes the owner through a member row, and the workspace becomes their active one. The check is the session's `instance:admin`, not the account flag (`apps/api/src/workspace-creation.ts`). Someone without a workspace sees "Waiting for an invitation. Ask your server admin to add you." with their open invitations, Account settings and Use a different account. Self-serve workspace creation for Linedesk Cloud comes with billing (decided, not built yet; Linedesk Cloud below).- **Accounts without a workspace** exist only when someone kept them: deleting a workspace (Server admin, or its owner), a server admin removing someone from their last workspace (`membership.remove`) and leaving one's last workspace (`team.leave` with `deleteAccount: true`, required from the last workspace; the dialog asks "Also delete my account", ticked) delete the accounts of members who have no other workspace by default (never a server admin's, also not one only through `INSTANCE_ADMIN_EMAILS`: one `isInstanceAdmin` rule), with a box to keep them (`keepAccounts` for a workspace delete, `keepAccount` for `membership.remove`). Account deletion rules (decided 2026-11-15): removing someone in the workspace (`team.removeMember`) keeps their account by default; only the workspace's owner may ask to delete it (`deleteAccount: true`, the owner's unticked box; anyone else gets 403, read from the member row), with a sign-in within the last 10 minutes as for leaving (`removeNeedsFreshSignIn`, refusal code `SIGN_IN_AGAIN`). A removal (`team.removeMember`, `membership.remove`) cancels the pending invitations the removed person sent to that workspace, kept account or not, with an audit line `invitation_withdrawn` each; the remove dialog says how many. Whoever loses their account by a removal is emailed (`workspace.deletedEmail` job with `removed`, by the remover or "The server admin of <site host>"). `team.leave` that would delete the account needs a sign-in within the last 10 minutes (the session's `createdAt`, `leaveNeedsFreshSignIn` in `apps/api/src/owner-step-up.ts`, checked in `run-action.ts` and in the handler; refusal code `SIGN_IN_AGAIN`, the dialog offers "Sign in again"). Other pending invitations a deleted account sent (a leave, a workspace delete, other workspaces) pass to their workspace's owner (`deleteAccounts`, workspace-delete.ts) with an audit line `invitation_reassigned` each that names the owner (`auth_events.subject_id`); in a workspace with no other owner they go with the account. Server admin › Users has a "No workspace" filter for accounts without a membership; nothing deletes them on its own. A new account made by a sign-in that ends up in no workspace (the invitation went away meanwhile) is deleted again (`joinOrUndo`, instance-admin.ts; audit `sign_up_undone`, and each join as `invitation_accepted`). Removing someone or leaving unassigns the person's calls in that workspace and drops their per-member rows there (notification settings, personal go-live checklist rows, unfinished calendar connects; `forgetMember`, memberships.ts), so a re-invited member starts from the defaults.-| Who | Actions (registry, 2026-11-15) |-| --- | --- |-| Member and up (44) | account.removeAvatar, account.setAvatar, appointment.book/.cancel/.reschedule, calendar.findSlots, call.assign/.clearReminder/.delete/.listen/.markDone/.markNotDone/.markNotSpam/.markRead/.markSpam/.markUnread/.remind/.restore/.setActionItems/.setUrgency/.takeOver, contact.block/.create/.delete/.import/.merge/.restore/.unblock/.update, feedback.send (to the Linedesk team, docs/api.md), holidays.lookup, insights.get, member.list, notifications.get/.update (own), outbound.countries, push.subscribe/.unsubscribe, starPrompt.answer, team.leave, team.list, voice.catalog/.options, workspace.getSettings |-| Admin and owner (76) | apiKey.*, appointmentType.*, assistant.* (create, delete, update, versions, test call), assistantCalendar.*, business.import/.search, businessHours.set, calendar.connectStart/.connectFinish/.disconnect/.listCalendars, call.evaluate/.export/.getEvaluation/.listEvaluations, carrier.get/.set/.test, closedDays.set, evaluation.*, holidays.set, knowledge.import, knowledgeQuestion.*, notifications.setDefaults, onboarding.*, phoneNumber.*, sample.add/.remove, team.getMember/.invite/.removeMember/.removeMemberAvatar/.resendInvite/.revokeInvite/.setMemberAvatar/.setRole/.updateMemberNotifications/.updateMemberProfile, voice.clone, webhook.*, workspace.rename/.setIcon/.removeIcon/.updateSettings |-| Owner only (3) | team.transferOwnership, workspace.deleteOwn, workspace.deletePreview |-| Server admin (47) | agentSetup.*, branding.set, feedback.resend/.setupReports, install.setProgress, instanceAdmin.*, invitation.resend/.revoke, membership.*, outboundCountries.*, provider.* (except provider.reportOk), setupEmails.*, systemPrompt.*, user.*, voiceCloning.*, callQuality.*, afterCallTranscript.*, workspace.create/.delete/.disable/.enable/.setSpendingCap |-| Voice agent (18) | call.start/.finish/.appendTranscript/.transfer/.reportVoiceFailure/…, carrier.provisionTransferTrunk/.transferTrunk, provider.reportOk |-| Any signed-in account (3) | invitation.accept/.decline/.listMine |-| Impersonation (1) | impersonation.stop |+| Who | Actions (registry, 2026-11-15) |+| ------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Member and up (44) | account.removeAvatar, account.setAvatar, appointment.book/.cancel/.reschedule, calendar.findSlots, call.assign/.clearReminder/.delete/.listen/.markDone/.markNotDone/.markNotSpam/.markRead/.markSpam/.markUnread/.remind/.restore/.setActionItems/.setUrgency/.takeOver, contact.block/.create/.delete/.import/.merge/.restore/.unblock/.update, feedback.send (to the Linedesk team, docs/api.md), holidays.lookup, insights.get, member.list, notifications.get/.update (own), outbound.countries, push.subscribe/.unsubscribe, starPrompt.answer, team.leave, team.list, voice.catalog/.options, workspace.getSettings |+| Admin and owner (76) | apiKey._, appointmentType._, assistant.* (create, delete, update, versions, test call), assistantCalendar._, business.import/.search, businessHours.set, calendar.connectStart/.connectFinish/.disconnect/.listCalendars, call.evaluate/.export/.getEvaluation/.listEvaluations, carrier.get/.set/.test, closedDays.set, evaluation._, holidays.set, knowledge.import, knowledgeQuestion._, notifications.setDefaults, onboarding._, phoneNumber._, sample.add/.remove, team.getMember/.invite/.removeMember/.removeMemberAvatar/.resendInvite/.revokeInvite/.setMemberAvatar/.setRole/.updateMemberNotifications/.updateMemberProfile, voice.clone, webhook._, workspace.rename/.setIcon/.removeIcon/.updateSettings |+| Owner only (3) | team.transferOwnership, workspace.deleteOwn, workspace.deletePreview |+| Server admin (47) | agentSetup._, branding.set, feedback.resend/.setupReports, install.setProgress, instanceAdmin._, invitation.resend/.revoke, membership._, outboundCountries._, provider.* (except provider.reportOk), setupEmails._, systemPrompt._, user._, voiceCloning._, callQuality._, afterCallTranscript._, workspace.create/.delete/.disable/.enable/.setSpendingCap |+| Voice agent (18) | call.start/.finish/.appendTranscript/.transfer/.reportVoiceFailure/…, carrier.provisionTransferTrunk/.transferTrunk, provider.reportOk |+| Any signed-in account (3) | invitation.accept/.decline/.listMine |+| Impersonation (1) | impersonation.stop |REST routes outside the registry: `/v1/admin/*` need `instance:admin`; `/v1/shape/*` add the workspace filter and leave webhook endpoints out for members; `GET /v1/calls/<id>/recording`, voice previews, `/v1/me`, avatars and icons are member reads of their own workspace; `POST /v1/workspaces` needs `instance:admin` (above).diff --git a/packages/i18n/locales/en/settings.json b/packages/i18n/locales/en/settings.jsonindex 21b8c55e..95adf8a0 100644--- a/packages/i18n/locales/en/settings.json+++ b/packages/i18n/locales/en/settings.json@@ -1717,7 +1717,7 @@"sip.guide.threecx.account": "On the tab General: Main Trunk Number: {number}. Authentication ID (SIP User ID): {username}. Authentication password: the password. Type of authentication: Do not require - IP based (with another type 3CX tries to register, which fails). Registrar/Server: {host}. Port: {port}. Leave Create an outbound rule for this SIP Trunk ticked.","sip.guide.threecx.rule": "3CX now opens the outbound rule. Calls to numbers starting with prefix: {plain}, without the plus. Under Calls from Departments, select your department: without one the rule does not apply. Save.","sip.guide.threecx.send": "Send the calls the assistant should answer to {plain}, for example with Forward to Outside Number. Enter it without the plus: 3CX cuts the plus and the country code off.",- "sip.guide.threecx.transfer": "With 3CX, putting calls through is not confirmed: in our test 3CX did not accept calls from {brand} on this trunk. You can leave this off; the assistant then takes a message.",+ "sip.guide.threecx.transfer": "In 3CX, open the trunk. On the tab General, set Default route to the user, ring group or queue that takes the calls the assistant puts through. To reach one person by their own number, add that number on the tab DID Numbers exactly as you enter it in {brand}, with the plus, and pick it under Assigned DID number(s) of that user. A number that 3CX does not know goes to the default route. 3CX takes these calls only from the address under Registrar/Server of the trunk. Here, enter the public host of your 3CX, the transport of the trunk, and the same user name and password as above.","sip.guide.threecx.transport": "On the tab Options, set Transport Protocol to {transport}. Save.","sip.guide.threecx.trunk": "In the 3CX admin console, open Voice & Chat › Add Trunk. As Provider, pick Generic VoIP Provider (Registration). OK.","sip.line.connect": "Connect",