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.
Linedesk architecture
Status: decided, 2026-11-10. This is the single source of truth for how Linedesk works. Product and architecture decisions are recorded in the pull requests that made them ("Decisions" in the description); what comes next is in ROADMAP.md.
1. What v1 does
A US service business (demo: a plumber in Portland) keeps its existing phone number and forwards calls it can't take to Linedesk. An AI assistant ("Maya" by default, renamable) answers, understands the request, books appointments into the business's calendar, takes messages, escalates emergencies to a person, and turns every call into an item in a keyboard-first inbox.
v1 = phone + calendar. It is built on the platform foundation (action registry, local-first sync, provider adapters) so WhatsApp, SMS and email can follow without rework.
Out of scope for v1: messaging channels, outbound campaigns, multi-location routing, enforced compliance guardrails (kept configurable, see §10).
2. Principles that shape the architecture
- One action, every surface. Every user or agent action is defined once and exposed as UI command, REST endpoint, MCP tool, ⌘K entry and voice-agent tool.
- Instant and offline. The UI applies every action locally at once and syncs in the background; it keeps working offline.
- Adapters with a recommended default. Telephony, speech, LLM, calendar and sync providers are swappable behind interfaces; setup always suggests one.
- Easy to self-host, able to scale.
docker compose upgives a working install; the same images scale horizontally. - Open-source ready. No secrets or customer data in the repo.
3. System overview
Caller ──PSTN──▶ Business number ──(conditional forward)──▶ Linedesk DID (Telnyx, default)
│ SIP
▼
LiveKit SIP service
│ joins room
▼
┌─────────── LiveKit room (one per call) ───────────┐
│ caller (SIP participant) │
│ voice agent (LiveKit Agents, TypeScript) │
│ owner (optional: browser or phone when taking over)│
└────────────────────────────────────────────────────┘
│ agent tools = registry actions
▼
Web app (Vite SPA) ─commands─▶ API (Hono): action registry ──▶ Postgres ◀── worker (pg-boss jobs)
local store + outbox ◀─reads── read-sync adapter (Electric) │
│ └── object storage (recordings)
REST + OpenAPI · MCP server · webhooks
│
Google Calendar · Microsoft Graph · CalDAV · Cal.com · Calendly
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 |
5. Action registry
Every action is defined once:
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 */
},
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) |
| 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) |
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 |
6. Sync: "commands up, data down"
- Writes: every registry call from the web app is a command. The client applies it to its local store immediately, persists it in an IndexedDB outbox and replays it in order to
POST /v1/actions/<name>(idempotent per command id). The server is authoritative; a rejection rolls the local change back and shows a toast. - Action answers (
apps/api/src/run-action.ts): 200{ ok: true, rows, data? }; 403{ ok: false, error, code: "forbidden" }when this caller may not do it (a missing permission, an owner-only rule, not while signed in as another user or with an API key; handlers throwForbidden); 409{ ok: false, error }when the data's state does not allow it (Reject: not found, the last owner); 422 for invalid input, said as plain sentences that name fields as people say them ("Account SID", notvalues.account_sid). A replayed command answers with the status of its first answer. Input fields an action does not take: 422 for API keys and other callers; dropped with a warning in the API log for the web app's sessions and the voice agent, because the outbox replays commands stored by an older release after a deploy and the agent can run one release behind the API. - Cross-site writes: every non-GET request under
/v1signed in by the session cookie (noAuthorization: Bearer) must come from the web app's origin (Originequal toWEB_ORIGIN) and beapplication/json, else 403cross_site_refused(apps/api/src/csrf.ts, before every/v1route). The cookie is SameSite=Lax, so a page on another subdomain of the same site would still send it, and atext/plainPOST needs no preflight. API keys and the agent (Bearer) are not affected; Better Auth checks the Origin of/api/auth/*itself. - Reads: Postgres → local store through our
ReadSyncAdapterinterface, scoped per workspace and permission. Default adapter: Electric. Swapping the provider touches only the adapter file, not the UI. Electric itself has no notion of workspaces, so only the API may reach it: it runs withELECTRIC_SECRET, which the API adds to every proxied shape request (GET /v1/shape/<table>), and in the compose stack Postgres and Electric are only on the internalbackendnetwork, which only theapiservice joins (the agent, LiveKit, SIP, egress, Redis and Caddy are not on it). - Offline: reads and queued writes survive a reload; a service worker serves the app shell.
- Live calls: transcript segments are rows like any other, so they arrive through the same read sync (target < 1 s).
7. Call lifecycle
Ring. The caller dials the business. If nobody answers within N rings (or the line is busy), the carrier forwards to the workspace's Linedesk number.
Ingress. The provider sends the call over SIP to LiveKit SIP. A dispatch rule maps the DID to a workspace and creates room
call_<id>. The API createsCall { status: live }; it appears at the top of Needs you with a live indicator.Caller lookup. First tool:
contact.lookup(phone)→ contact, past calls, upcoming bookings, so the assistant knows a returning customer (it does not greet them by name).Greeting. Configurable greeting; AI disclosure on by default (configurable, §10).
Conversation. The agent follows the assistant config (About the business, booking types, urgent and transfer rules). Its tools are registry actions:
Tool Effect contact.lookupContact + history calendar.findSlots(type, window)Free slots = working hours ∩ free/busy of conflict calendars − buffers − min notice appointment.book/.reschedule/.cancelWrites the calendar event, stores Booking, links the callcall.flagUrgentMarks 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.endHangs 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 withkind: '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.findSlotson 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 anALERTline). 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): off unlessDEMO_CALLS=on. A website's gateway (its own serverless function, never the browser) asksPOST /v1/demo/callwith 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 roomdemo-…, withdemo: truein the dispatch metadata: the agent adds "This is a two-minute demo." to the greeting and ends the call afterDEMO_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_CALLS300), 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_CONCURRENT3), 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 logALERT 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 hourlydemoCalls.cleanupjob removes theipHashfrom tokens older than 24 hours and clears demo calls older thanDEMO_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.tssets up the demo workspace from a data file. Monthly spending cap (apps/api/src/spending-cap.ts): off by default; an instance admin sets one per workspace in Server admin › Workspaces (workspace.setSpendingCap, USD, stored asorganization.spending_cap_cents; empty: no cap). The measure is the estimated cost of the workspace's calls this UTC month with the overview's rates (costEstimateinadmin-overview.ts; deleted calls count, sample calls do not, a live call counts once it finished). Once reached,call.startanswersoverCap(andblocked, for older agents): the call is filed as missed with "Call back" and the usual push, and the agent says one fixed line in the assistant's voice ("we can't take your call right now, we'll call you back") and hangs up, so the caller never hears silence and the cap costs a few seconds per call. Test calls are refused. Owners and instance admins get an email at 80 % and at 100 % (pg-boss jobspending.capAlert, once per workspace, month and level inspending_cap_alerts; a new cap starts the month's emails over). Calls already running when the cap is reached go on.Every tool call is also written to the transcript as a system event ("Checked availability · 3 slots").
Transfer contacts (per assistant,
assistants.transfers, an ordered list edited as a whole withassistant.update { transfers }; Settings › Assistant › Transfers): each contact has a name (unique in the list: the assistant picks by it), a number (null: none yet, the contact is inactive; checked by the outbound destination policy below: a landline, mobile or VoIP line in a country the workspace may call, never premium rate, shared cost, toll-free, personal, emergency or service numbers; never a Linedesk number or a line forwarding to one), a plain-languagecondition("The caller asks to speak to a person", "Urgent: burst pipe, gas smell, no heat", "Billing questions"),hours_only(not while the business is closed),ring_seconds(10–60, default 25),if_no_answer(message | next;message_urgentwas removed, migration 0070 made itmessage) andenabled. A new assistant starts with one contact, "The caller asks to speak to a person", without a number (inactive until one is set); a copied assistant starts from that default too. Migration 0046 turned the old single on-call number (transfer_urgent,transfer_number,transfer_hours_only, kept until the next release, then dropped) into the first contact, "Urgent: an emergency that needs a person right now". The agent takes the contacts that are on, have a number and are not limited to hours while closed (transferContactsFor), and gives the assistanttransfer_callfrom the start of the call when there is one (transferFrominapps/agent/src/worker.ts,apps/agent/src/transfer-tool.ts): how to dial each contact is looked up right away, but nothing is dialled until the assistant uses the tool, once a contact's condition fits. A contact that cannot be dialled on the call (no outbound trunk, a phone call test) counts as not answered: the next one is tried only when itsif_no_answerisnext. The prompt lists them in order with their conditions; the tool takes every contact whose condition fits, andtransferPlantries them in the owner's order: a contact whose fallback isnexthands over to the next one that fits (at most 3 tries a call); when nobody accepts, the last one's fallback applies (nextwith nobody left: a message). Before each ringback the caller hears a fixed line naming the contact ("I'm trying to reach Mike now…", then "Mike can't take the call right now. Let me try Sarah…"); when nobody accepts, the assistant tells the caller and takes a message.call.transferrecords the contact's name (calls.transfer_name); a transfer never changes the call's urgency (urgentfrom an older agent is ignored). Each try has its own consult room (<room>-oncall,<room>-oncall-2, …).Warm transfer, how one try works: The agent first asks the API with
call.transferdialing, which checks the number again against the outbound destination policy (the numbers or the install's list may have changed since it was saved), refuses (and logs) any number that is not an active transfer contact of the call's assistant (matched as E.164), and, as the agent picks them, a contact limited to business hours while closed and anyone in closure mode (test calls, which dial no real phone and use the call test's own contacts and hours, are not checked); it keeps the workspace's limits (6 transfers started an hour, one on-call leg ringing or connected at a time, the daily transfer minutes, under a per-workspace advisory lock); a refusal means a message, a refused destination makes the tool try the next contact that fits. The answer carries the caller ID to use and the minutes the leg may last. The caller hears a fixed "I'm trying to reach …" line, then a ringback tone; the agent joins a consult room<room>-oncalland dials the on-call number into it withCreateSIPParticipantthrough the LiveKit outbound trunklinedesk-outbound(setup-sip --outbound; Telnyx credential connection of the same name, caller ID = the business's Linedesk number, or a number of the workspace in the destination's country when it has one), ringing for the contact's ring time (default 25 s). A small voice session there (speech recognition and voice, no LLM) says "Call from about ." Press 1 or say yes…" (a name only as the caller's own when the team gave or confirmed it on the contact, else ", who says they are ,"; the same in the message the team gets when nobody took the call) (not interruptible), twice at most, and only after it has played counts key 1/2 or a short clear yes/no (at most six words, nothing that sounds like a voicemail greeting), so a voicemail is never put through. On yes the call's recording is stopped (the conversation with the on-call person is not recorded; if it cannot be stopped, nobody is put through and the assistant takes a message) and the agent bridges the audio of both rooms itself (audio-bridge.ts) and stays silent; the call ends when either side hangs up, outcometransferred. On no, no decision (voicemail) or no answer the consult room is deleted, which hangs up the on-call phone, and the assistant takes a message.call.transferstorestransfer_toandtransfer_result(connected | not_answered | declined | failed), and each result other thanconnectedadds the seconds of the leg it ends (from its dial, ringing included, at most to the call's end) totransfer_seconds, so every try of a call counts toward the daily minutes; the call row is locked, and a result whose number is not the open leg's (a late report of the try before) or aconnectedwithout a dial changes nothing and is logged; the call view shows "Transferred to …" or "Transfer not answered". The agent bridges instead of using LiveKit'sMoveParticipant(Cloud only: "not implemented" on self-hosted LiveKit 1.13) or SIP REFER (cold, carrier-dependent, the call leaves LiveKit). Closing the consult room is registered as a shutdown callback before anything is dialled, and a dial stops waiting as soon as the caller hangs up. Test calls never dial an on-call phone: on a browser test call a simulated person accepts and says it is a test (TEST_CALL_ON_CALL_LINE, the API setssimulateTransferin the test room's metadata), phone call tests (fromCALL_TEST_FROM) cannot dial anyone, and thetransfer-*call-test scenarios refuse--phoneand use a simulated on-call person (the one exception is the live transfer test below, an explicit opt-in). Thelinedesk-outboundTelnyx voice profile only allows the install's outbound countries (the countries of its install-account numbers plus the install's list; created on the global plan, the only one Telnyx accepts for new profiles), set again on everysetup-sip --outboundand, after the change commits, whenever an install-account number is connected or released or the list changes, and setup fails if Telnyx does not keep exactly that list; Linedesk only manages Telnyx objects namedlinedesk-*.Live transfer test (operators, over real phone lines; a few cents per call). It needs one more number in the install's Telnyx account (not connected to any workspace), the test on-call number, answered by the on-call responder (
apps/agent/src/oncall-responder.ts): the worker plays the on-call person, waits for the briefing, says "Yes, put them through." and presses 1, then says to the caller "Hi, this is Mike, the on-call plumber…" and hangs up, so the test caller's transcript proves the bridge. Setup, once: buy the number and point it at LiveKit SIP like any other (Telnyx connectionlinedesk-livekit), thensetup-oncall-test <on-call number> [--answer accept|decline|no-answer](its own inbound trunk and dispatch rulelinedesk-oncall-test, same carrier address list; never pass this number tosetup-sip), andsetup-sip --outbound <every business number>once for thelinedesk-outboundtrunk. Per run: add a transfer contact with the on-call number to the test workspace's assistant (condition: urgent); setCALL_TEST_ONCALL=<on-call number>in the agent's env and recreate the agent container;call-test transfer-accepted --phone(fromCALL_TEST_FROMtoCALL_TEST_TO). WithCALL_TEST_ONCALLset, a phone call test may be put through to exactly that number and no other (liveTransferTestAllows), and call-test allows--phonefor thetransfer-*scenarios; without it both stay refused. Check: the test caller's lines in the agent log ("business: Hi, this is Mike, the on-call plumber…"), the call shows "Transferred to …", the recording ends at the bridge, and nocall-*,*-oncalloroncall-test-*room is left after hang-up (lk room list). Afterwards: switch that contact off again (keep the number), unsetCALL_TEST_ONCALLand recreate the agent container (docker compose up -d agent; wait until the new worker is registered before the next call). The trunk, rule and number can stay for the next run; to tear the test down,setup-oncall-test --removedeletes the trunk and dispatch rule (calls to the number then reach no agent), and the number is released in the Telnyx portal. The on-call number may not be a Linedesk number or a line that forwards to one:assistant.updaterefuses both.Live view. Transcript streams to the web app. A live call shows "Live" in the inbox and, opened, a card with Listen (L) and Take over (⇧T) for any signed-in member of the workspace (owners, admins, members; not API keys, the agent or an instance admin signed in as someone). Both are read-only actions (
call.listen,call.takeOver,apps/api/src/live-call.ts) that check the call is live and in the member's workspace (another workspace's call is "not found") and sign a LiveKit token for that call's room only, valid 60 s for joining, no data messages and no changing its own attributes. Listen: hidden, cannot publish anything; the browser plays the call and shows the lines still being spoken (the agent's transcription streams, as in the test call). Take over: cannot publish at first either, and carries the member's name in the participant attributelinedesk.takeOver, which only the API can set. Another member's take-over holds the call for 90 s (time to join and hand over; the same member may rejoin; refused while a warm transfer is ringing or connected); after that the agent decides: the first member to join gets the call, anyone later or anyone it cannot hand over to is toldrefusedand removed from the room (removeParticipant). The agent (apps/agent/src/take-over.ts) stops listening to the caller, stops the recording (fail closed: if it cannot, it setslinedesk.handOff=<sid>:refusedon itself and carries on), says "I'm putting you through to now.", mutes itself, grants the member microphone-only publishing (updateParticipant) and setslinedesk.handOff=<sid>:ready; only then can the browser turn the microphone on. A member disabled during a call keeps their connection until it ends (tokens are checked only on joining). From there the call is like a connected warm transfer: not recorded or transcribed, no silence prompts or assistant time limit, outcometransferred, the transcript shows " took the call over". The member's Hang up ends the call; a dropped connection gets 15 s to rejoin. The browser keeps the session outside the call view (apps/web/src/call/liveSession.ts), so moving to another call does not drop the caller. Each first listen-in per member and each take-over is acall_eventsrow (listened,took_over). Hand back to the assistant and dialling the member's phone are not built.Hang-up. Recording finalised to object storage.
After-call transcription (
apps/api/src/after-call-transcript.ts; Server admin › Features › After-call transcription,afterCallTranscript.get/.set, instance_settingsafter_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: OpenAIgpt-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 inapps/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 (transcriptKeyFrominpackages/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 first", a link to its provider. When the agent reports the recording (call.setRecording, aftercall.finish), the API queues thecall.transcribejob (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.tsputs 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.finishwithawaitTranscriptsetscalls.awaiting_transcript_until,apps/api/src/call-news.ts): the agent sendscall.correctTranscriptaftercall.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 sendscall.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, theCALL_RELEASEjob sends the news with the live summary afterAWAIT_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). Acall.finalizeafter 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 atcall.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; Deepgrammulti). 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.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).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. 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 ownmember_notification_settings.email; everyone switches their own, owners and admins the others' withteam.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 withcallEmails.get. An assistant'semail_rulesadd 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 incalls.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 itsto; 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.
8. Phone setup and calendar
Phone number modes (PhoneNumber.mode):
forward_conditional(default): unanswered/busy calls go to Linedesk. Setup = dialing a carrier code (Verizon*71<number>, AT&T/T-Mobile**004*<number>#), verified with a test call.forward_all: Linedesk answers every call.new/ported: a new local number, or the existing number ported in.
Connecting a number (phoneNumber.setup, owner or admin, carrier from TELEPHONY_PROVIDER):
{ e164 }attaches a number that already exists in the carrier account and buys nothing; a number that is not there is rejected.{ areaCode, purchase: true }or{ e164, purchase: true }buys a number. This costs money and happens only withpurchase: true; if a later step fails, the bought number is released.- Either way the carrier is pointed at LiveKit SIP (
LIVEKIT_SIP_ENDPOINT) and thephone_numbersrow is stored. Once that commits, the API writes every connected number to LiveKit's inbound trunklinedesk-inbound(apps/api/src/inbound-trunk.ts), so the number takes calls when the command answers (from the carriers' signaling addresses only, see below); a release takes it off the same way.
Own carrier account (Settings › Phone numbers › Carrier; owners and admins, settings:write). By default a workspace uses the install's carrier (Server admin › Providers). It can bring its own Telnyx or Twilio account instead:
workspace_settings.carrier:default,twilioortelnyx. The credentials areprovider_settingsrows with the workspace's id: Twilio Account SID plus either an API key (SID and secret, recommended) or the auth token; Telnyx an API key. AES-256-GCM withSECRETS_KEY, each ciphertext bound toworkspace:<id>:<carrier>.<field>, so a value copied into another workspace's row does not decrypt. WithoutSECRETS_KEYsaving is refused.carrier.setreplaces the credentials as a whole (switching carrier or back todefaultdeletes the old ones); itsvaluesaresensitive, so the command log keeps them as[redacted]. The browser calls it directly, not through the outbox, so credentials are never kept in IndexedDB.carrier.getreturns the carrier, which fields are set, the Account SID and API key SID (not secret) and the last four characters of a stored secret of 12 characters or more; never a secret. Members and the agent token get 403.carrier.test("Test connection", run after every save) only reads: it lists up to 20 numbers of the account (TelephonyProvider.listNumbers) with an 8 second timeout, at most 10 per workspace in 10 minutes. 401/403 answer with a fixed text; other errors carry the carrier's text with every credential removed. Stored values that cannot be decrypted (anotherSECRETS_KEY) are reported as "enter them again", never with the operator's detail.Concurrency:
carrier.set,phoneNumber.setupandphoneNumber.releasefirst take a per-workspace transaction lock (pg_advisory_xact_lock(hashtext('carrier:<workspace id>')),lockWorkspaceCarrier), so the carrier cannot be switched while a number is being set up or released with it (setup holds its transaction across the carrier requests).Numbers already in the install's account (whatever carrier it is: Telnyx, Twilio or another adapter): only an instance admin may attach one to a workspace, whatever the workspace's bill (none, comped, paying) (
phoneNumber.setupwithout buying, or withpurchasefor a number the account already has; refused with 403 before the carrier is asked;phoneNumber.listCarrierNumberslists nothing for others); other members buy a new number or bring their own account (decision of 2026-11-19)./v1/mephoneSetup.canAttachtells the web app, which shows the quiet "Already have a number in ? Use it" link only then. Theworkspace:createCLI runs as the operator. Without a carrier (dev) and in the workspace's own account attaching is open to owners and admins.Buying on the install's account (the operator pays): someone who is not an instance admin buys only by area code, of the workspace's country (US, Canada or Puerto Rico,
NUMBER_BUY_COUNTRIES; a typed number could be anywhere), and the API refuses a purchase when the workspace holds 2 numbers bought there or bought 2 in the last 30 days, when the user bought 2 there in the last day (all their workspaces), or when 10 were bought on the install in the last hour, and install-wide at 20 a day and 100 in 30 days (NUMBER_PURCHASES_PER_DAY,NUMBER_PURCHASES_PER_30_DAYS; reaching it logs anALERT number purchasesline). An API key cannot buy on the install's account. Everything that can refuse (assistant, workspace state, limits) is checked before the carrier is asked. Every purchase is logged innumber_purchases, committed on its own before the carrier is asked, so it outlives a released number and a failed action: buying and releasing, or a purchase whose action fails afterwards, still counts (apps/api/src/number-purchases.ts). Purchases on the install's account run one at a time and setups in a workspace too (pg_try_advisory_xact_lock): one that comes meanwhile is refused at once ("Another number is being set up, try again in a moment") instead of holding a database connection while it waits;phoneNumber.setupalso setslock_timeout5 s. The purchase log is written through its own pool of two connections (ownCommitDb), so it never waits for a connection of the main pool that the waiting transactions hold. Instance admins' purchases (by_admin), the workspace's own account anddevare not counted or limited.Numbers:
phoneNumber.setupresolves the carrier per workspace (telephonyForWorkspace,apps/api/src/workspace-carrier.ts): the workspace's own account when it has one, else the install's. The number row stores which (phone_numbers.carrier_account:workspace|install), andphoneNumber.releasereleases or un-routes it only in that account: aworkspacenumber with the workspace's own credentials (read by the number's own workspace id), aninstallnumber with the install's carrier. Numbers that were connected before a workspace brought its own account stayinstall. Attaching looks the number up in the workspace's account, so a number can only be added by the workspace whose account has it (ande164is unique across the install).While numbers are in the workspace's own account,
carrier.setrefuses another carrier ordefault("Disconnect it first"), and new credentials for the same carrier must find every one of those numbers with the same carrier id (read-only look-ups), so a number is never managed with credentials of an account it is not in./v1/mephoneSetupreports the workspace's carrier (own account, else the install's); Settings › Phone numbers lets owners add numbers with their own account even when the install has no carrier.Webhooks of a workspace's account verify with that account's own key: the adapter built from the workspace's credentials (
ownCarrierProvider) checks Twilio signatures with the workspace's auth token (refused with only an API key: Twilio signs with the auth token) and Telnyx signatures with the workspace's optional webhook public key, never the install's. No API route receives carrier webhooks yet; a future one must pick the verifier by the number'scarrier_accountand workspace.Inbound calls still go through Linedesk's LiveKit SIP; the voice agent and the dispatch do not change (DID →
phone_numbersrow → workspace).Warm transfers dial out through the account the called number is in. An
installnumber uses the install'slinedesk-outboundtrunk as before. For aworkspacenumber the API (never the agent) sets up the outbound side,apps/api/src/transfer-trunk.ts: in the workspace's account an object namedlinedesk-outbound-<workspace id>(Twilio: Elastic SIP trunk with a termination domainlinedesk-outbound-<random>.pstn.twilio.comand a credential list,createTwilioOutbound; Telnyx: credential connection and a voice profile limited to the countries of the workspace's own-account numbers,createTelnyxOutbound), so two workspaces sharing one account never rotate each other's SIP password; and in LiveKit the trunklinedesk-outbound-<workspace id>-<account fingerprint>(a hash of the Twilio Account SID or the Telnyx key) with the workspace's own-account numbers as caller IDs. It is set up when a number is connected or released and when the carrier is set (carrier.setfirst deletes the workspace's LiveKit outbound trunks, so a trunk of an old account is never dialled through); carrier and LiveKit requests each give up after 8 s, and a failure is logged without undoing the change. The agent askscarrier.transferTrunk { from }(agent token,x-workspace-id; the number must be that workspace's) for the carrier and the trunk's exact name and finds it only when the transfer dials; when it is missing, lacks the caller ID, or the carrier refuses its credentials (SIP 401/407, once; not 403, which Twilio also sends for a destination the account may not call), it callscarrier.provisionTransferTrunk(under the workspace carrier lock, at most 3 per workspace in 10 minutes), which is logged in the command log and the audit log (kindkeys, likecarrier.set). A set-up caused byphoneNumber.setup,phoneNumber.releaseorcarrier.setwrites the same audit entry with its trigger. A new set-up creates the new LiveKit trunk before it deletes the old one. No carrier credential ever goes to the agent. A workspace cannot bring the install's own account (same Twilio Account SID or Telnyx key: refused; Telnyx names no account id without a request per key, so another key of the install's Telnyx account is not recognised); when the install's keys cannot be read the check cannot run and saving is refused. A number in a workspace's own account whose account is gone gets no transfer, never the install's trunk. On Twilio the allowed destinations are the account's own setting (Voice Geographic Permissions), which Linedesk never changes; Linedesk checks the on-call number before dialling (outbound destination policy below), and Server admin › Settings › Calls lists the allowed countries the install's Twilio account still blocks.Outbound destination policy (
packages/actions/src/outbound.ts,apps/api/src/outbound-policy.ts; decided 2026-11-15). Every number Linedesk dials (transfer contacts, the forwarding check's business number) goes through one function,outboundNumberProblem(e164, allowed, use), which returns the reason and one plain message naming the countries. Allowed countries depend on the route (numberRoute: the carrier account of the called number, as the transfer trunk is picked): through the install's account the countries of the workspace's install-account numbers plus the install's list (instance_settingsoutbound.countries, Server admin › Settings › Calls, orOUTBOUND_COUNTRIES, which replaces it while set); through the workspace's own account the countries of its own-account numbers only; the forwarding check (the install's check line) the install's ceiling,installDestinations(every install-account number's country plus the install's list, never own-account countries). Saving a contact accepts any route's countries. Canada and the other North American regions are countries of their own. A frequent toll-fraud destination (HIGH_RISK_COUNTRIES) needs a second confirmation in Server admin (confirmHighRisk). Number types: landline, mobile and VoIP only (libphonenumbermax); never premium rate, shared cost, toll-free, personal, UAN, pager, voicemail, invalid numbers or numbers without a country; never emergency or short numbers (also as+<code> 911); US N11 and 976 refused as before. Settings check it with the workspace's countries (a workspace without a number yet: any country, the dial is checked);call.transferdialingand the forwarding check check it strictly. Cost limits:OUTBOUND_MINUTES_PER_WORKSPACE_DAY(default 120) minutes of transferred calls per workspace in 24 hours (every leg:transfer_secondsof the tries that ended plus the open leg fromtransfer_atto the call's end, ringing included),OUTBOUND_MINUTES_INSTALL_DAY(default 2000) for all workspaces through the install's account (anALERTlog line when reached) andTRANSFER_MAX_MINUTES(default 30) per transferred call (0, or a value that is not whole minutes: transfers off), passed to LiveKit as the leg's maximum length; a refusal is a message and is in the command log. Caller ID: a workspace number in the destination's country (same carrier account and carrier) when there is one. Carriers: Telnyx profiles are kept at the allowed list (see above) and get Telnyx's own cost ceilings,max_destination_rate(TELNYX_MAX_DESTINATION_RATE, default $0.10/min) anddaily_spend_limitwithdaily_spend_limit_enabled(TELNYX_DAILY_SPEND_LIMIT, default $50 per profile and day), on create, on every set-up and destination sync, and at API start. A set-up fails closed: a profile Telnyx did not save with both at or below the configured values is never used (checkSaved), and the transfer or check is not set up. The startup sync (syncTelnyxProfiles, in the background, never blocking the start) patches every existinglinedesk-*profile, the install's and each workspace's own-account one, without a new password (no countries to give, as for an install or workspace without numbers: the limits only, the countries left as they are); a profile it cannot update keeps working with its old settings until then, so the sync tries again after 30 s, 2, 10 and 30 minutes, logs anALERT outboundline per failure and records the profile (instance_settingstelnyx.spendCaps:<profile>,apps/api/src/telnyx-spend-caps.ts); Server admin › Settings › Calls warns "Spend limits not confirmed" until a later sync or set-up confirms it. A rate above $1/min or a daily limit above $500 is applied but warned about at start; Twilio Geo permissions are read (DialingPermissions/Countries/<code>), never written.
What the business configures for its own account. Nothing on the SIP side: Linedesk provisions it through the carrier's API with the credentials.
- Twilio: in the Twilio Console, Account › API keys & tokens, create a Standard API key; enter the Account SID, the key SID and secret (or the auth token instead). Elastic SIP Trunking must be available on the account (it is by default). On "Add number", Linedesk creates (once) an Elastic SIP trunk named
linedesk-livekitwhose origination URI issip:<LIVEKIT_SIP_ENDPOINT>;transport=tcp(withLIVEKIT_SIP_TLS=on:sip:<LIVEKIT_SIP_ENDPOINT>:5061;transport=tlsand the trunk set to Secure, docs/hosting.md "Encrypted calls"), and attaches the number to it (a number belongs to one trunk, so a number on another trunk moves to this one). Disconnecting takes the number off that trunk (it then has no voice routing and stops answering until the business routes it again); nothing else in the account is changed. A number bought through Linedesk is bought in, and billed by, the business's account, and released there. - Telnyx: create an API key (Auth › API keys) and enter it. Linedesk creates (once) an FQDN connection
linedesk-livekitto<LIVEKIT_SIP_ENDPOINT>port 5060 over TCP (withLIVEKIT_SIP_TLS=on: port 5061 over TLS with SRTP) and assigns the number to it; disconnecting un-assigns it (connection_idnull) only if it is still on that connection, so it stops answering until the business routes it again; Settings says so before disconnecting. Objects not namedlinedesk-*are never changed. - Calls and numbers are billed by the carrier to the business; Linedesk does not see the carrier's invoice.
What the operator does. LIVEKIT_SIP_ENDPOINT must be reachable from the business's carrier (the same public address the install's carrier uses). Like every number, a newly connected one is added to LiveKit's inbound trunk by the API (see "Who may call in"). Open point (older than the address list below): LiveKit's inbound trunk has no allowed-address or credential list yet, so any SIP source that reaches the endpoint could present any connected number as the dialled number; with several carrier accounts the fix is per-trunk authentication or the carriers' signalling ranges (not built).
Own phone system (SIP trunk) (Settings › Phone numbers › Own phone system; owners and admins, settings:write; apps/api/src/sip-trunk.ts). A business that has its own phone system (3CX, Asterisk/FreePBX, Yeastar) or SIP provider sends the calls of a number straight to this server, without a carrier account in Linedesk. The number stays where it is.
sipTrunk.connectNumber{ e164, assistantId? } stores the number (phone_numbers.providerbyo_sip,carrier_accountsip, modenew) and asks no carrier. The workspace's first number makes its user name and password (provider_settingsrows of the workspace, providersip, encrypted like its carrier credentials). The password is in that answer once (secretResult, so never in the command log);sipTrunk.getreturns the SIP address and the user name, never the password;sipTrunk.newPasswordreplaces it (the old one stops working at once). The browser calls all three directly, not through the outbox. They needLIVEKIT_SIP_ENDPOINTandSECRETS_KEY; without them the page says the server cannot take such calls.- Each workspace has one LiveKit inbound trunk,
linedesk-sip-<workspace id>, with exactly its numbers and its user name and password (SIP digest), the install trunk's call length and audio encryption, and only the INVITE'sX-headers and itsUser-Agentas attributes (all headers would put the phone system'sProxy-Authorizationinto the call room; the one header that always arrives tells the agent that headers are passed; such a caller's number counts as not verified, as no carrier vouches for it). The trunk's metadata is a mark of its credentials and of these fixed settings, so the sync writes a trunk again when either changes, andsipTrunk.getanswersactive: falsewhile LiveKit's trunk is not the stored one yet (the dialog says so; one LiveKit request per read, at most 20 a minute per workspace, elsenull). LiveKit picks the trunk by the dialled number and then asks for that trunk's password, and it refuses a number on two trunks: so a phone system reaches only its own workspace's numbers. The number sync (apps/api/src/inbound-trunk.ts) writes these trunks with the install's: own trunks first give up numbers that are no longer theirs (a trunk without numbers is deleted), then the install's trunk gets its numbers (never an own one), then own trunks are created or changed (a trunk whose credentials are not the stored ones is replaced in place), and thelinedesk-inbounddispatch rule is bound to all of them.setup-sipkeeps the own trunks in the rule it makes. - The phone system sends calls to
sip:<number>@<LIVEKIT_SIP_ENDPOINT>:5060;transport=tcp(5061 andtlswithLIVEKIT_SIP_TLS) and must dial the number in international format, with or without the+(the agent adds it beforecall.startlooks the number up). A national number or an extension matches no trunk and is refused. - Nothing proves that the workspace holds the number it types in. So such a number never opens a country for outbound calls (
outbound-policy.tscounts install-account numbers only), never keeps another workspace from checking its own line, a workspace has at most 10 of them and connects at most 10 an hour, and support access (impersonation) can neither connect one nor make a password. A number typed in by the wrong workspace stays there until it is disconnected: an instance admin settles a dispute (support access with edits, the number's dialog, Disconnect). Moving a number that "never got a call" to whoever connects it next was tried and dropped: the proof (call rows) can be deleted or made by an attacker, so it would let a later workspace take a number during its owner's setup. - No address list: the password is what lets a call in, so the phone system may call from any address. LiveKit keeps trunk passwords in its Redis in clear, as it does the carriers' outbound credentials.
phoneNumber.releaseonly 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 ofoutboundissensitiveand 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.transferTrunkanswers{ 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 askscarrier.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 ofPUBLIC_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=trueallows 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
callsrows 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 Contextfrom-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, assetup-sipmakes it.setup-sipreplaces it, own trunks included, once the operator adds a carrier. Putting calls through from such numbers needs no install trunk either.
Who may call in (inbound SIP). LiveKit SIP listens on 5060 for the whole internet, and an INVITE carries whatever caller ID and called number the sender likes. So the inbound trunk linedesk-inbound only takes calls whose source IP is one of the carriers' published signaling addresses (allowedAddresses); any other INVITE matches no trunk, and since the dispatch rule is bound to that trunk, LiveKit answers 404 and no room, agent or call row is created. The addresses are in one file, packages/telephony/src/signaling-addresses.ts, with the source and the date each list was checked: Telnyx's primary and secondary signaling IP of every SIP region (sip.telnyx.com/voice.json), Twilio's Elastic SIP Trunking signaling gateways of every edge (/30 each). LiveKit compares IP entries only with the packet's source address (a hostname entry would be compared with the From host, which the caller sets), so only IPs and CIDR ranges are accepted.
setup-sipapplies it on every run: it updates the trunk in place (same id, no gap), creates it if missing, and warns about other LiveKit objects that would still let calls in from anywhere (inbound trunks with neither addresses nor credentials, dispatch rules bound to no trunk). It does not change them.- Which numbers the trunk takes calls to: exactly the connected numbers (
phone_numbers, every workspace and carrier account). The API writes them (apps/api/src/inbound-trunk.ts) afterphoneNumber.setupandphoneNumber.releasecommit, when it starts and every 5 minutes (a write that failed, a number removed another way), and again 15 s and 60 s after a failed write (logged asALERT inbound trunk). It changes only the numbers (a field update), never the addresses, headers or call length, which staysetup-sip's; it never creates the trunk (without it the API logs a warning: runsetup-siponce per install) and never writes the list empty (LiveKit would keep it, or withclearaccept every number). Writes never overlap: one at a time per API process, under an advisory lock across processes, each reading the numbers under the lock. Why not a trunk without a number list: Telnyx's and Twilio's signaling addresses are shared by all their customers, so anyone with an account there could then start a room and an agent for any called number. The numberssetup-sipis given are replaced by the API's list within minutes. - How long and how many calls (each minute costs speech recognition, the model and the voice on the operator's keys): the assistant says goodbye and hangs up after its own limit (
assistants.max_call_minutes, Settings › Assistant › Advanced; default 20 minutes,ASSISTANT_CALL_DEFAULT_MINUTES, the owner may set up to 30,ASSISTANT_CALL_MAX_MINUTES; the same on every usage level; a timer in the agent). A call it put through to a person goes on: the inbound trunk ends every call after 2 hours (maxCallDuration,CALL_MAX_MINUTES; LiveKit only takes it in a whole new trunk, sosetup-sipwrites the trunk back with exactly the numbers and addresses it just set, never fewer), and the on-call leg has the same cap. Silence on the line, per assistant (Settings › Assistant › Advanced;assistants.silence_first_gap_s,silence_reminders,silence_closing; defaults 8 s, 2, the default line): after the first gap with neither side speaking (the session'suserAwayTimeout) the assistant asks "Are you still there?", again after twice as long, and so on, then says the closing line and hangs up (remindOnSilence,hang-up.ts; with the defaults: asks at 8 and 24 s, closing at 56 s). A word from the caller starts it over; never during or after a transfer. The assistant always says something before a call ends: end_call without a goodbye of the model's gets "Thanks for calling. Goodbye!", the time limits have their own goodbye (test calls from the web app: 5 minutes), and busy and blocked callers hear one line before the agent hangs up (when the voice is set up). A workspace's assistant answers 5 phone calls at once (on a bill: the billing rules' 5 included plus the extra calls its owner bought, or an instance admin's cap for the bill; on no bill:LIVE_CALLS_PER_WORKSPACE; live phone calls started in the last 30 minutes, counted under a per-workspace advisory lock incall.start; test calls have their own limits): the next one is filed as a missed call with a callback and the usual push,call.startanswersbusyandblocked, and the agent says that all lines are busy and hangs up (an agent of the release before hangs up at once). Calls stuck live (the agent crashed, a deploy, a lost connection: nocall.finish) are ended by the stale-call sweep (apps/api/src/stale-calls.ts, every minute). It asks LiveKit once per sweep which rooms are open and how many participants each has (listLivekitRooms): a call with someone in its room is never ended, and a phone or browser test call whose room is gone or empty ends after 60 s without a new transcript line (an empty room is deleted: LiveKit keeps the room of an agent that died open, with nobody in it). Only when LiveKit cannot be asked, or for a call without a LiveKit room (simulated and sample calls), does time alone decide:STALE_LIVE_CALL_MINUTES(default 10) without a transcript line, 2 minutes for a browser test call; the sweep then also deletes the call's room, so a line still open is hung up on. A call put through to a person counts as stale only after 2 hours (and 5 minutes). Such a call is filed as "Call cut off": a callback when the caller had spoken, else a hang-up ("The call ended before it was wrapped up, and its transcript was not saved." when it lasted over 20 s). It still queues the after-call webhook and Zapier'scall_finished, ascall.finishdoes, so a call cut off by a deploy or a crashed agent reaches the integrations too. LIVEKIT_SIP_ALLOWED_ADDRESSES(defaulttelnyx twilio) lists carrier names and/or IPs and CIDR ranges, for BYO SIP or a self-hoster's own PBX;anyalone turns the restriction off andsetup-sipwarns. Anything else is refused, so a typo never leaves the trunk open (LiveKit itself silently drops entries it cannot parse, and an empty list means open).setup-sip --print-allowed-addressesprints the list for a firewall.- Why IP allowlists and not SIP digest (
authUsername/authPassword) for both carriers: Twilio's trunk origination does not answer a digest challenge. Telnyx delivers to our FQDN connection, and neither the FQDN connection API nor Telnyx's LiveKit guide offers credentials for calls Telnyx sends out (its user name and password are for calls into Telnyx); a Telnyx credential connection only delivers calls to a registered SIP client, and LiveKit SIP does not register. A digest challenge would refuse every real call. The cost of the allowlist: when a carrier adds signaling addresses, calls from them are refused until the file is updated; the carriers announce such changes, and thecheckeddates say when the list was last compared. - Per-workspace carrier accounts (Telnyx or Twilio) send from the same published addresses as the install's account, so one list covers every workspace. A workspace's own phone system or SIP provider is not on this list: it has a trunk of its own with a password ("Own phone system" above).
US practical notes: outbound needs a SIP trunk; Twilio needs Trust Hub + SHAKEN/STIR for A attestation; warm transfer needs the linedesk-outbound trunk (setup-sip --outbound, Telnyx for now); a cold transfer would need SIP REFER on the trunk (not used).
Calendar:
- Connecting: an owner or admin clicks Connect Google / Connect Microsoft (CalDAV: below) (
calendar.connectStart, returns the consent URL). The OAuth apps are the sign-in apps (GOOGLE_*,MICROSOFT_*), but the flow is Linedesk's own, not a Better Auth account link: a linked account would also become a way to sign in. State (32 random bytes, the row id ofcalendar_oauth_states) is bound to the member and workspace, single use, 10 minutes; PKCE S256. The provider returns toGET /v1/calendar/callback/<provider>(redirect URI<BETTER_AUTH_URL>/v1/calendar/callback/google|microsoft), which runscalendar.connectFinishas the signed-in member (the code is redacted in the command log) and redirects to#assistant/calendar. Not while impersonating. Sign-in asks for no calendar scope. - OAuth scopes (asked only when connecting): Google
calendar.events+calendar.freebusy+calendar.calendarlist.readonly(not restricted, no CASA audit; never Gmail/Drive on this app: support mailboxes use their own Gmail app, below), MicrosoftCalendars.ReadWrite+offline_access+User.Read. A Google grant without the calendar scopes is refused and revoked. - CalDAV (
packages/calendar/src/caldav.ts): Settings › Calendar › Add account › iCloud or CalDAV opens a form (iCloud, Fastmail or any server address; user name; app-specific password). The adapter finds the calendars from the address (current-user-principal, calendar-home-set, with/.well-known/caldavas fallback); a calendar's id is its collection URL, reminders lists (VTODO only) are left out, write access comes fromcurrent-user-privilege-set. Busy times come from the events themselves (calendar-queryREPORT withexpand; iCloud has no free-busy query): free (TRANSPARENT) and cancelled events take no time; recurring events the server does not expand are expanded inical.ts(DAILY, WEEKLY with BYDAY, MONTHLY, YEARLY, INTERVAL, COUNT, UNTIL, EXDATE, moved instances; any other rule counts as every day, so nothing is double-booked); all-day and floating times are in the business's time zone. A booking is<uid>.icsin the calendar (PUT withIf-None-Match: *), a change goes only over the version just read (If-Match), and the event's id is the uid. Plain fetch, XML and iCalendar read in the package, no SDK. Tested against an in-memory CalDAV server (caldav.test.ts) and a local Radicale. - Calendar tools beyond Google and Microsoft (CalDAV/iCloud, Calendly, Cal.com) are off until an instance admin switches them on, each one way (Server admin › Settings › Integrations › Calendar tools,
calendarTools.set,apps/api/src/calendar-tools.ts, oneinstance_settingsrow): off, members connect with their own key (keys: app-specific password, personal access token, API key), or with one click through the install's OAuth app (oauth; Calendly and Cal.com, whose apps are registry providerscalendlyandcalcomwith client ID and secret, shown in the Calendar group).GET /v1/calendar/providerslists what members may connect and how (ways:oauthorkey); a connect the other way is refused; calendars of a tool that is off are not offered to the agent nor booked into (assertToolWay). - Cal.com and Calendly (
packages/calendar/src/calcom.ts,calendly.ts) are scheduling tools with their own booking systems, and Linedesk uses them fully: an assistant calendar of a tool is one of its event types (assistant_calendars.duration_minholds its length; null for a plain calendar) and is its own appointment type,cal:<assistant calendar id>. The tool decides length, availability, buffers, notice and horizon:calendar.findSlotsoffers exactly the tool's start times (slots), Linedesk's appointment types, business hours and closures do not apply. The agent sees such a calendar among the appointment types (bookingContext); Linedesk's own types are listed only while the assistant also has a plain calendar (Google, Microsoft, CalDAV). A booking is made in the caller's name (attendeeoncreateEvent: name, number, email; without the caller's email the account's own address gets the tool's confirmation), the reason, number and address as notes (Cal.com) or as the answer to the event type's first free-text question (Calendly; a required question the assistant cannot answer stops the booking with what to change), and stored without a Linedesk type. A move gets a new id from the tool (Cal.com reschedules into a new booking; Calendly cannot move, so the adapter books the same invitee at the new time, then cancels the old one) andmoveBookingstores it. Auth: a key (stored as a login,calendar_credentials.scope=login) or an OAuth token (Calendly: PKCE, client as HTTP Basic, refresh tokens rotate, revoke; Cal.com: a client Cal.com approved, PKCE, no revoke); either way every request goes through the guarded fetch, with the tool's own API as the server. Cal.com is supported in Cal.com's cloud only (api.cal.com): a self-hosted Cal.com is not, there is no address field and an address sent with the key is not used (its API versions differ from the cloud's, decided 2026-11-15); Calendly's URIs are used only onapi.calendly.com. Calendly answers available times at most a week per request and never for the past: the adapter asks in pieces. Provider error texts are shortened and stripped of markup. Contract tests against in-memory servers shaped like the documented APIs:scheduling-tools.test.ts. - Connecting by password (
calendar.connectWithPassword, the password redacted in the command log; needs a confirmed email, not while impersonating): providers without an OAuth app (CalDAV) take the server address, the user name and an app-specific password. The address must be https on port 443 or 8443 and public:apps/api/src/calendar-server-fetch.tsrefuses private addresses (also after DNS, and on the address the connection really uses) and always link-local and cloud metadata addresses, and every request to the server goes through it with an 8-second deadline and a 5 MB cap on the answer. Every request and redirect (followed by hand) must stay on the member's server (sameSiteinpackages/calendar: the same host, or iCloud's per-accountpNN-caldav.icloud.com), so no href or redirect a server answers with gets the login elsewhere.WEBHOOK_ALLOW_PRIVATE_URLS=true(development) also allows http, other ports and private addresses. The user name may not contain a colon or control characters (HTTP Basic). The login is checked first (the server must accept it and show a calendar), then stored like tokens: the JSON login where the access token goes, an empty refresh token and an expiry of 1970 (no migration; a release before this one, during an update or a rollback, reads the row as an expired OAuth token, fails to refresh it and never sends the login). At most 10 connects with a key or password per workspace and hour (PASSWORD_CONNECTS_PER_HOUR, each counted when it starts, refused ones too; in memory per API process), so a workspace cannot guess passwords or probe servers through the API. The logins and tokens of CalDAV, Calendly and Cal.com are encrypted under slots with the provider's name (calendar.<connection id>.<provider>.access|refresh; Google and Microsoft keepcalendar.<connection id>.access|refresh): a release from before these providers takes every provider but Google for Microsoft, and cannot decrypt them, so it never sends them to Microsoft. The account is named by its user name, or<user name>@<host>when that is no address; the same account on another server is refused until disconnected. A refused login later marks the connectionneeds_reconnect; disconnecting deletes the login and tells the member to delete the app-specific password where they made it. - A connection (
calendar_connections: provider, account email, status, who connected it) belongs to the workspace and is synced; its tokens are incalendar_credentials(never synced), AES-256-GCM withSECRETS_KEY, each ciphertext bound to its connection and kind. An access token with less than a minute left is refreshed on use; Microsoft's new refresh token replaces the old. A refused refresh marks the connectionneeds_reconnect.calendar.disconnectdeletes the connection, its tokens and its assistant calendars, then revokes the grant at Google (Microsoft has no per-app revoke; the result tells the member where to remove it). - An assistant books into one or more calendars (
assistant_calendars: calendar, the owner's instruction for when to use it, enabled, one default). Only calendars the account can write to can be added; the name comes from the provider. - Availability engine in the API (
apps/api/src/bookings.ts): the business hours = working hours + exceptions when business hours are switched on (else Monday to Friday 9 to 5 in the workspace time zone); each appointment type is booked inside them, outside them or at any time (book_when,hoursForinpackages/calendar); appointment types (duration, buffer before and after, min notice, max days ahead, location), the chosen calendar's busy times at the provider (one request, 4 s timeout), existing bookings of that calendar.calendar.findSlotstakescalendarIdand localfromDate/toDate; each slot has a spokenlabel. - Booking on a call:
call.startreturnsbooking(appointment types with their required details, the answering assistant's enabled calendars of connected accounts with their instructions, today in the business time zone, andcanChangeBookings) or null; then the assistant only takes messages. The agent's toolsfind_slotsandbook_appointment(andcancel_appointment/reschedule_appointmentwhencanChangeBookings) runcalendar.findSlots,appointment.book,appointment.cancel,appointment.reschedule(permissioncalendar:write: every role; the agent runscalendar.findSlotsin its call's workspace and the other three only with itscallId). The model picks the calendar from the instructions; the API checks it belongs to the assistant that answered the call, re-checks the slot under a per-calendar advisory lock, writes the event (title<Type> · <Caller>, reason, phone, address, link to the call) and stores the booking; if the transaction fails the event is deleted. Caller ID is a hint, never identity (it is cheap to fake): the agent is never told a caller's bookings (upcomingis always empty, kept for older agents). To cancel or move one the caller says its day and the name it is booked under; the agent passes both (bookingDate,bookedName, never a booking id) and the API finds the one upcoming booking of the call's contact on that day in the business time zone whose name matches (every word of the booked name, in any order, and no other word), or refuses with the same answer whatever was wrong (no booking that day, another name, two matches, or, once found, anything that stops the change: its appointment type switched off, the calendar refusing; that change is rolled back in a savepoint). On reschedule the agent also sends the appointment type and calendar it searched with, and the API checks the new time with them before it looks for the booking, so a taken time says nothing about whether a booking exists. Every refusal is a miss, kept on the call (calls.booking_misses; the action succeeds withchanged: false, so the miss is not rolled back). One caller's changes run one at a time (an advisory lock per contact), so calls at once cannot each pass the check before the other counts. An agent of the release before gets a plain refusal before anything else, since it would read any answer as done: on reschedule when it sends no type and calendar, on cancel when it does not sendreadsRefusals. A new time taken since find_slots is no miss (slotTaken): the caller picks another one. At 3 misses in 24 hours over the caller's calls (by contact, or by number without one) booking changes by phone stop for that caller (canChangeBookingsfalse at the nextcall.start, every further try refused without counting) and the call that reached the limit is flagged urgent with a next step for the team and an urgent push. The agent also stops after two refusals on one call and takes a message. By id the agent can only change a booking made on the same call (the call test cleans up that way). A withheld or malformed caller ID (not E.164: "anonymous", "restricted", no caller ID at all) gets no contact (such callers would all share one), so no booking changes, no blocking by number, and it is never put on a booking as the phone number. Only bookings made through Linedesk exist. Each appointment type can require phone, email or address on top of name and reason. A booking with an email address queues a confirmation email (pg-bossbooking.confirm); no SMS yet. The call's outcome isbooked. - The caller on a call: the contact
call.startmatched (by number; none for a withheld number) comes back with its name andnote. The assistant always gets the name ("The caller is "Linda Park" (a saved contact)", quoted as data, incallerIdInstructions) and the note as "Notes from your team about this caller; take them into account" (callerNotesInstructionsinapps/agent/src/prompt.ts): whitespace collapsed, cut at 2,000 characters, between<caller_notes>tags (any variant of our tags in caller or note text is removed), never read out. Notes also come from imports and API keys, so they are information, never rules that override the prompt.call.startsends the caller history (earlier calls, open next steps, upcoming bookings under the contact's name) when the assistant's switch "Know the caller's previous calls" (behaviourcaller_history, on by default) is on; it goes in between<caller_history>tags as data, not instructions. There is no name check before the assistant uses the name, notes or history (decided 2026-11-15; a stricter variant for private data may come later), with one exception from the security review: caller details from the business's own system (call-start webhook: accounts, payments) still wait until the caller said the full name in them. The server checks a booking change by day and booked name; since the assistant knows the caller's name, someone faking a customer's number could learn both from it. Accepted by default (decided 2026-11-15); the assistant's switch "Ask for the booking name before changing an appointment" (behaviourask_booking_name, off by default) makes it keep the contact's and the booked name back whenever the caller can cancel or move a booking (call testspoofed-cancel).contacts.name_source(memberwhen typed, imported or confirmed in Linedesk;callerwhencall.finishorappointment.booksaved what a caller said) still decides what a person is told about the caller in a transfer briefing, and the contact panel shows "Name from caller · Confirm". Booking changes still check day and booked name on the server. The contact's Note field in the web app says which assistant sees it. - Caller-ID check ("Faked caller IDs"): the inbound trunk passes all SIP headers (
includeHeadersinapps/agent/src/sip-trunks.ts), and the agent reads the carrier's STIR/SHAKEN attestation and spam flag from the caller'ssip.h.*attributes (apps/agent/src/caller-attestation.ts) and sends both tocall.start(attestation: A, B, C, failed, none;spamLikely). They are kept on the call (calls.caller_attestation,calls.spam_likely). Only;verstat=in the P-Asserted-Identity URI (never in a display name or in From) and X-Twilio-VerStat on a call from a twilio.com host count.callerRecognized(packages/actions/src/calls.ts) decides whether the number names the caller: always for test and simulated calls; for a phone call only when the carrier vouched for the number (attestation A) while the assistant's switch "Recognize callers only when their carrier verified the number" (behaviourverified_caller_only, on by default) is on. Headers without a verstat count asnone(an INVITE someone sends from a carrier's signaling address, e.g. a SIP dial from any account at that carrier, carries none, whatever caller ID it sets). No headers at all (a trunk that does not pass them) counts as not verified too, since anyone who reaches such a trunk sets any caller ID; the agent then warns once per worker to runsetup-sip, which makes the trunk pass all headers. Otherwisecall.startsends the contact without name, note and name source (the number stays the callback number), no caller history, and a booking context without the contact (canChangeBookingsfalse, as for an unknown number;appointment.cancel/reschedulealso refuse on the server),appointment.bookdoes not fall back to the contact's saved email,call.lookUpCallerasks the business's webhook nothing, and a during-call lookup is sent withcaller: nullandcaller_verified: false. The inbox shows "Spam likely", the call view also "Number not verified". Telnyx inbound call screening is set to flag mode on the numbers (it never rejects). - Events: title
<Type> · <Caller>, description with summary, phone, address and a deep link to the call. - Sync back: Google
events.watch/ Graph subscriptions updateBookingwhen the owner moves or deletes an event.
9. Data model
Workspace(id, name, locale, avg_job_value, plan, region)
Member(id, workspace_id, name, email, role[owner|admin|member], phone)
PhoneNumber(id, workspace_id, e164, provider[telnyx|twilio|plivo|byo_sip], mode, forwarded_from, verified_at)
Assistant(id, workspace_id, name, voice{provider, voice_id}, languages[], greeting,
ai_disclosure, pipeline{mode[cascaded|realtime], stt, llm, tts},
business_profile{description, services[], service_area, address, hours, faqs[], never_say[]},
escalation{transfer_to_member_id, urgent_keywords[], rules[]}, capabilities{...})
CalendarConnection(id, workspace_id, provider[google|microsoft], account_email, status)
Calendar(id, connection_id, external_id, name, color, check_conflicts, book_into)
WorkspaceSettings(workspace_id, timezone) -- table workspace_settings; IANA zone, default America/New_York when missing
-- also country, language (null: Automatic), country_hint + country_hint_source (see below)
AvailabilityRule(id, workspace_id, weekday[0=Sunday..6], start_time, end_time) -- wall clock, end after start, 24:00 allowed
AvailabilityException(id, workspace_id, date, start_time?, end_time?) -- replaces the day's hours; no times = closed
AppointmentType(id, workspace_id, name, duration_min, buffer_min, min_notice_hours,
max_days_ahead, location[on_site|office|phone|video], enabled)
Contact(id, workspace_id, name, company, phone, email, address, tags[], note)
Call(id, workspace_id, contact_id, from, to, direction[in|out], started_at, ended_at, duration_sec,
status[live|completed], outcome[booked|rescheduled|cancelled|callback|message|answered|
transferred|hangup|spam], urgency[urgent|normal|low], intent, title, summary,
action_items[], fields[], language, answered_by[ai|human], recording_key, recording_store[file|s3],
inbox_state[open|done], reminder_at, reminder_label, unread, assignee_id,
deleted_at, billed_seconds)
TranscriptSegment(id, call_id, speaker[agent|caller|human|system], text, at_ms, tool_event?)
Booking(id, workspace_id, call_id, contact_id, appointment_type_id, start_at, end_at,
status[confirmed|rescheduled|cancelled], calendar_id, external_event_id)
Command(id, workspace_id, member_id, action, input, status, created_at) -- outbox replay log, idempotency
UsagePeriod(workspace_id, period, answered_seconds, cost_cents)
Workspace country (decided 2026-11-15; packages/actions/src/workspace-locale.ts, one function for the API and the web app, workspaceCountryOf). Many defaults follow it (phone numbers, holidays, call language, forwarding guide, currency, emergency number), so New workspace (the dialog and the first workspace's page) shows it, required, prefilled from the country hint. It is saved as workspace_settings.country (set) only when the user picks one; left as prefilled, the workspace stays Automatic on that hint, so a number connected later still decides it (the emergency number follows the country). The Business step in onboarding likewise saves the country only after Change. The hint (countryHintOf) is the visitor's country as the proxy in front names it (Caddy drops any X-Linedesk-Country a client sent and sets it from the header LINEDESK_COUNTRY_HEADER names, CF-IPCountry behind Cloudflare (docker-compose.cloudflare.yml), only for requests from a trusted proxy (LINEDESK_TRUSTED_PROXY_RANGES); a client reaching Caddy directly never picks it), else the country of the browser's time zone (IANA zone → country from the tz database's zone.tab, packages/actions/src/time-zone-countries.ts, generated by packages/actions/scripts/time-zone-countries.mjs), else the region of the browser's language; GET /v1/workspaces/country-hint answers it for the dialog. It is saved once at creation as country_hint and country_hint_source (sign_up_location | time_zone | browser_language, both with CHECK constraints; migration 0106); without one from the app, the country of the time zone the caller sent (never the US Eastern fallback nobody chose); for a workspace a server admin makes for another owner, never the admin's own sign-up location: only the two-letter country code and its source, never the IP address, and no geo-IP lookup or outside service is ever called (without such a proxy there is no sign-up location). A workspace made without a country (the API, the setup MCP, the command line) stays Automatic. Automatic, in order: the country set, the assistant's first number, the business phone (with its country code), the holiday calendar, the hint, else US (countrySource names which). Buying a number follows only a country something names (countryNamed: set, a number, the business phone, holidays); with only a hint or the US fallback, the area code picked names it and the bought number then sets the workspace's country, so a hint never blocks a purchase. Workspaces from before the hint are not handled: there were no production workspaces yet (decided 2026-11-15). The workspace language is no setting (decided 2026-11-16: the workspace "Call language" in Workspace settings › General and onboarding was removed, column dropped in migration 0112): it is the main language of the country in use (resolveWorkspaceLanguage, COUNTRY_LANGUAGES, else English), what call summaries, messages for the team and the texts filed on unanswered calls are written in, the language of invitations (when the app has it) and of booking confirmations to callers when the assistant has no main language of its own, and what an assistant without a main language of its own greets in; the call language is chosen per assistant (Settings › Assistant › Languages). Onboarding's Business step shows the country with Change, with the texts of Workspace settings › General; the phone field starts with the same country (useDefaultPhoneCountry, the API's resolvedCountry, before it loads the same order on what the browser has).
Inbox semantics
Views are derived, not stored. They answer one question: does a person still have to act?
- Needs you: open calls a person has to act on: live calls,
urgency = urgent, outcomescallback | message | hangup. Priority order inside each day: live, urgent, new-caller callbacks, other callbacks, messages, hang-ups. - Handled by Maya: open calls the assistant finished (
booked | rescheduled | cancelled | answered | transferred). Skim and clear with E. - Spam: outcome
spam, kept out of every other view, never deleted silently. - Reminders: calls with
reminder_atin the future; they return to their view when it passes. - Done:
inbox_state = done. - Search (
/) covers all calls, including transcripts.
E marks done (Z undoes), H sets a reminder. The sidebar value counter is count(calls), count(bookings) and count(bookings) × avg_job_value for the current week.
10. Compliance (configurable, not enforced in v1)
US first. Guardrails come once we know the starting states and use cases; the design keeps them easy to add:
- AI disclosure in the greeting: on by default (
at_start), configurable in every country: the owner keeps full control (decided 2026-11-17, after the legal review, A1/A2). The modes:never_confirm(not even when asked: it neither confirms nor denies being an AI, and never claims to be human),never,when_asked,at_start,at_start_consent. Settings › Assistant warns where a mode may break the law of the workspace's country (aiDisclosureRisk; the EEA/UK list inpackages/actions/src/eea.ts): a quiet hint forneverandwhen_asked, a warning fornever_confirm. Nothing is refused or changed at call time. - Recording notice: part of the greeting text, so what the greeting field says is what callers hear; the agent adds nothing. A new assistant's greeting says "This call may be recorded and transcribed." (in its main language,
spokenLines(...).recordingNotice) before its closing question (greetingFor,withRecordingSentenceinpackages/actions/src/assistant-prompt.ts); demo assistants, which never record, leave it out. Settings › Assistant › General checks each greeting against whether its calls are recorded (a recording store is set up, the assistant records, the workspace keeps recordings): recorded and the greeting does not say so (mentionsRecording, words in every call language), a warning with "Add recording notice"; not recorded and it still says so, a quiet line with "Remove that sentence". These are hints, never locks (all-party-consent states and the EU: the warning says why). A save that makes a greeting start or stop saying it is in the audit log (data.recordingNoticeChangeof assistant.update, kept past the 90-day prune; legal review 2026-11-17, A4). Migration 0187 wrote the old per-assistant notice (0108, 0177) into the greetings that said it and dropped its columns. Public demo calls are never recorded, and Settings › Recordings greys out the retention, kept as saved, under a note that links instance admins to Server admin › Providers › Recording storage and tells everyone else to ask their server admin. - Outbound-call consent (TCPA), data region: planned; nothing is enforced yet.
- Data retention: recordings (the audio) are kept 90 days by default (in every country; Settings › Recordings shows a quiet law hint for the EEA and the UK, where recording usually needs consent, and for a retention over 90 days; A5), per workspace (
workspace_settings.recording_retention_days, Settings, Recordings; empty keeps them); a daily job (apps/api/src/recording-retention.ts) deletes older audio from its store and clears the call'srecording_key, nothing else. "Don't keep" is0:call.startreturnskeepRecording: falseand the agent does not start egress (the transcript and summary come from live speech recognition, never from the recording); a recording made anyway (an older agent, the setting changed mid-call, one linked by the orphan sweep) is deleted right aftercall.setRecordingby therecording.deletejob (pg-boss, retried with backoff, both stores), and the daily job catches the rest. The call view then says "Recording not kept". The recording cleanup never deletes a call, its summary or its transcript (apps/api/test/recording-retention.test.tschecks it). Calls go only when someone deleted them: a deleted call (deleted_at,call.delete) can be restored for 30 days, then the daily jobdata.purgeDeleted(apps/api/src/data-purge.ts, 03:27 UTC) erases it for good: its recording file first (a store that refuses keeps the call for the next run), then the row, with its transcript, activity, evaluation, reply timings, app pushes and reservation (on delete cascade) and its unanswered knowledge questions; a booking made on it stays without the link. Contacts deleted 30 days ago go the same way (their calls and bookings lose the link); a merged contact (merged_into) forwards its number and goes only once the contact it was merged into is gone. One audit entry per workspace and run (data.purgeDeleted, actorretention:system);DATA_PURGE_DRY_RUN=trueonly logs. "Delete permanently now" (owners and admins, permissioncall:erase; ⌘K › Delete… in the inbox, a box in its dialog, off by default) sendscall.deletewithpermanent: true: the call is erased at once the same way (eraseCallNow; the recording file through therecording.fileDeletejob after the commit), never a live call, never another workspace's; one audit entrycall.eraseby the person. A member sending the flag is refused (403) and nothing is deleted. A workspace whose bill was canceled 90 days ago is deleted bydata.purgeCanceled. Otherwise onlypnpm db:seed -- --resetdeletes calls, for the demo workspace. - Spam scoring uses carrier attestation + number reputation.
11. Repository and deployment
Target monorepo layout (created by the foundation workstream):
apps/
web/ Vite SPA (local store, outbox, service worker)
api/ Hono server: registry, REST, OpenAPI, MCP, webhooks
agent/ LiveKit Agents (TypeScript)
packages/
actions/ defineAction(), registry, shared Zod schemas
db/ Drizzle schema + migrations
sync/ outbox, ReadSyncAdapter, Electric/PowerSync adapters
telephony/ TelephonyProvider + Telnyx/Twilio/Plivo/BYO-SIP adapters
calendar/ Google / Microsoft / CalDAV / Cal.com / Calendly adapters, availability engine
ui/ shared components from the prototype
prototypes/ clickable prototypes (no backend)
docs/
An earlier Next.js mock-up is archived outside this repository.
Default docker compose: caddy, app (web + API + MCP), worker, voice agent, postgres, electric, livekit-server, livekit-sip, redis/valkey (needed by LiveKit SIP; it holds the SIP trunks and dispatch rules, so it keeps them on a volume, redis_data, across updates); optional recording profile (livekit-egress writing to a shared directory; no storage server). LiveKit is on two networks, default (agent, outside world) and the internal voice (Valkey); its media must use only default, or it announces both addresses and calls stay silent. Docker does not keep the order of a container's interfaces (eth0 may be either network after a recreate), so LiveKit's entrypoint picks the interface that holds the default route (only default has one, voice is internal) and writes its name into rtc.interfaces.includes; the startup log says livekit: media interface <name> (<address>). App, worker and agent are stateless replicas; LiveKit scales via Redis; Postgres can be managed.
Updates without downtime (scripts/deploy.sh, what every update of an install runs, docs/self-hosting.md): Caddy (proxy, the only published web port) stays up and reaches the API and the web app's files (web) by service name, retrying a request on another container for up to 30 s when one cannot be reached. The script builds while the old version serves (the test server pulls images built by the deploy workflow instead, docs/ci.md), then replaces only services whose image or settings changed, start-first: a second api (or web) container starts next to the old one, and the old one is stopped once the new one is healthy. The voice agent goes the same way: the new worker registers with LiveKit (its health check), then the old one gets SIGTERM, reports itself full, finishes its calls and exits, so there is never a moment without a registered worker and no call is cut off. A call put through to a person lasts up to CALL_MAX_MINUTES (2 hours), so the old worker may drain for that long (the worker's drainTimeout, 125 minutes; stop_grace_period 130): the script sends SIGTERM and moves on, and Docker removes the old container in the background once it exits. LiveKit, LiveKit SIP, egress, Redis and Postgres carry every call and cannot run twice; a new version or new settings for them waits for a moment without live calls (calls.status = 'live'), at most LINEDESK_DEPLOY_QUIET_WAIT (30 minutes), and is otherwise left for the next deploy. The agent reaches the API through Caddy too (http://proxy:3100). A new Caddyfile is loaded into the running Caddy (caddy reload); only a change to its compose settings recreates it (a few seconds without the site).
Voice servers (optional, hosting.md "Separate voice servers"): the install scales by job, not by customer. The app server keeps the web app, the API, Postgres, Electric and Caddy and opens no SIP or call-audio port (docker-compose.voice-link.yml: the local call services are off, and livekit is a forwarder to voice server 1). Voice server 1 runs LiveKit, SIP, egress, Valkey and an agent worker (docker-compose.yml with docker-compose.voice-media.yml, the same call services as a single server); further voice servers run only agent workers (docker-compose.voice.yml, the same agent service with the same short list of variables). Every worker registers with voice server 1's LiveKit, which dispatches every call to a worker below AGENT_LOAD_THRESHOLD (LiveKit's agents.target_load, the same value), weighted by idle CPU. The servers reach each other only through WireGuard, through voice links (a small Caddy published on the WireGuard address and firewalled to the listed servers): on the app server the API's internal listener (proxy:3100, where the agent's tokens count; only /v1/agent/* and /v1/actions/*), on voice server 1 LiveKit (7880; only /agent, /rtc and the RoomService, SIP, Egress and AgentDispatch APIs). Call audio and SIP go to voice server 1's public address. No database or Electric is reachable from a voice server, but it holds install-wide secrets: the agent token and a LiveKit key, so it is hardened like the app server. scripts/deploy.sh on voice server 1 updates its call services only at a moment without LiveKit rooms; on a further voice server it only rolls the agent; on the app server the voice link and the forwarder are call services (recreated only at a moment without calls). Recordings go to S3-compatible storage (egress runs on voice server 1).
Dev mode (test server only, dev-mode.md): LINEDESK_MODE=dev adds docker-compose.dev.yml, which runs api, web (Vite dev server) and agent from the server's git checkout under a watcher instead of from images. An update fast-forwards the checkout (scripts/deploy-dev.sh, refused when the checkout has local changes); the API restarts in place in about two seconds while Caddy holds requests, and an agent restart ends its running calls. Production and self-hosting stay on images.
Migrations run once, when the new API container starts, while the old API still serves; the old agent may keep running for up to 2 hours. So every migration is expand/contract: it must work with the code of the previous release. Add (a nullable column or one with a default, a new table, a new index) in one release and start using it; drop or rename (a column, a table, a NOT NULL without a default, a changed type) only in a later release, once no running code reads or writes the old shape. A new unique index is a contract step too: the release before must already refuse what it forbids (0091's one-owner index was not, so the release before answered 500 on a second owner during that deploy). A rename is add-copy-switch-drop across releases.
Hosted version: same code, LiveKit Cloud (US), managed numbers, US East region, pass-through minute pricing.
12. Admin area and provider keys
For the operator of a multi-tenant install: a view above the workspaces, and the provider keys in the database instead of only in env.
Where things are (apps/web/src/admin/route.ts). Server admin has Overview and then three groups with a heading each, one place for each thing. Overview ("Ready for calls", Needs you: bills held or owing, Stripe events that failed, partners waiting, workspaces at risk; the numbers, costs, the funnel). Customers: Workspaces (views: all, at risk, usage by month), Users, Partners, Billing (bills, review, prices and rules, the billing switch; a Sign-up row links to Sign-up & access). Assistant: Prompt, Call quality (the quality levels assistants can pick, the reply delay, after-call transcription, the calls the evaluation flagged), Features (what workspaces get: international transfers, German numbers, voice cloning, calendar tools, the Zapier link). Server: Providers (connecting services: keys, tests and which provider a category uses, Stripe and the bot check included; call audio with LiveKit and its SIP bridge, read-only), Sign-up & access (self-serve sign-up with its countries, limits and the emails new workspaces get; the names no partner brand may use), Branding, Audit log (with Stripe's events and the setup reports as kinds of their own). Old addresses (#admin/usage, #admin/onboarding, #admin/signup, #admin/calls, #admin/numbers, #admin/tools, #admin/server, #admin/system, #admin/settings/…, #admin/billing/events, #admin/billing/signup, #admin/call-reviews) land on the new place.
Instance admin is a property of the user (user.instance_admin), separate from the workspace roles. It adds the permission instance:admin, which no role has, in whatever workspace the user is active (and without a workspace). Who gets it:
- the first user of an install: whoever enters the setup code the API prints to its log (First admin: setup code, below), or an address in
INSTANCE_ADMIN_EMAILSonce it is proven (email code or sign-in provider), or an account the operator makes withuser:create --adminon the server. Whoever merely reaches a fresh install cannot take it over without the code (there is no open sign-up). (Existing installs keep their admins.); - anyone an instance admin grants it to (
instanceAdmin.grant/instanceAdmin.revoke; the last enabled instance admin cannot be revoked or disabled); - addresses in
INSTANCE_ADMIN_EMAILS, evaluated on every request, so it applies to accounts that already exist, but only once the address is verified (an email code or a sign-in provider verifies it). An unverified address grants nothing (password sign-up is off for every address): otherwise someone could register the operator's address first and gain admin when the operator later verifies it.
Server admin needs the passkey (two levels). Workspace users (owners included) sign in with any method the install offers and a passkey stays optional for them. instance:admin (every Server admin page and setting, provider keys, setup links, impersonation, every instance-admin action and admin API) is granted only in a session that passed the passkey check, for 12 hours (apps/api/src/admin-second-factor.ts, one rule, no per-action exceptions): session.passkey_verified_at is set by the session.create hook on /passkey/verify-authentication (input: false, clients cannot set it), so it is bound to that session on the server, and only when the passkey response reports user verification (fingerprint, face or PIN; the plugin's afterVerification notes it for that request). Passkeys require user verification when added and when signing in (authenticatorSelection.userVerification: 'required'); a response without it is refused with 403 PASSKEY_USER_NOT_VERIFIED, and the prompt says "This passkey doesn't check your fingerprint, face or PIN, so it can't open Server admin. Use one that does, or ask another admin to reset your passkeys (on the server: user-passkeys.ts --remove)." Every session of an instance admin also has setupLink:end, so End access (agentSetup.revoke, own links only) works without the check. With AUTH_PASSKEY_ENABLED=false while the rule is on, the API warns at every start that nobody can open Server admin and prints no enrolment codes. An admin may sign in with an email code, a password, Google, Microsoft, GitHub or single sign-on and use their workspaces as before; opening Server admin then asks for the passkey once (apps/web/src/admin/SecondFactorPrompt.tsx, "Confirm with passkey", a passkey sign-in of the same account that starts the new session). No email code, password or provider sign-in counts for it, and nothing else is asked per action. Impersonation sessions never carry instance:admin. Without it, GET /v1/admin/*, every action with instance:admin (run-action.ts, and again in the handlers that matter, adminPasskeyRefusal) and POST /v1/impersonation/start answer 403 { code: "SECOND_FACTOR_REQUIRED", secondFactor: "confirm" | "enrol" | "email" } and /v1/me reports adminSecondFactor: confirm (has a passkey, confirm with it), enrol (no passkey yet: the page asks for the one-time enrolment code, adds the passkey and confirms with it once) or email (the address is not confirmed yet, which adding a passkey needs: sign in with an email code). Admins without a passkey (an install from before this rule, or after a reset) get an enrolment code from the first-run setup (the browser keeps it), from another admin (Users, "Give passkey code…"), from node apps/api/src/user-passkeys.ts --enrol --email … on the server, or from the API's log: at every start the API prints a code for each enabled admin without a passkey and without a working code (apps/api/src/admin-passkey-codes.ts; issued as the operator through user.issuePasskeyEnrolment, so audited, emailed and alerted; a code someone already has is never replaced). A lost passkey is recovered with user-passkeys.ts --remove --email … (or another admin's Reset passkeys), which prints the new code. Server admin › Overview recommends a second passkey to an admin with exactly one ("Add a second passkey, e.g. on your phone or a security key, so a lost device does not lock you out."; dismissible per browser, never enforced). The owner's own workspace delete keeps its own step-up (owner-step-up.ts, PASSKEY_STEP_UP_REQUIRED and the passkey dialog apps/web/src/admin/PasskeyStepUp.tsx). The handlers that return an enrolment code refuse a session without the passkey check themselves too, and nobody resets their own passkeys (another admin, or user-passkeys.ts --remove on the server). The CLI runs as the server operator without a session. session.passkey_grant_used_at (one grant per passkey sign-in for a setup link, #694) was dropped by migration 0117. Alerts (apps/api/src/admin-alerts.ts): every enabled instance admin is emailed when an admin passes the passkey check from a browser that has not passed that admin's check before (with ADMIN_SECOND_FACTOR=off: any sign-in of an admin from such a browser, since every sign-in then opens Server admin), when someone is made admin, when passkeys are reset and when an enrolment code is issued without a reset. Without email set up the alert is skipped with one log line (Admin alert not sent (email is not set up): <subject>), not an error. A browser is known by a random token in a long-lived cookie (apps/api/src/admin-devices.ts; __Host-admin_device on https: Secure, Path=/, no Domain, so no subdomain can set it; admin_device on http; httpOnly, 400 days); only its SHA-256 is stored, one row per admin and browser (admin_devices). Every check issues a new token and replaces the row's hash, so a copied cookie shows up as a new device at the next check, and a token the server did not issue is never stored (the browser counts as new). One browser shared by two admins alerts once at each switch between them (accepted). Cleared cookies, another browser or a private window count as new; impersonation never records a device; a failure to read or store the device counts as new (the alert goes out). Reset passkeys, revoking admin and disabling the account forget the user's browsers, and the daily commands.prune job deletes rows not seen for 400 days. Sign-ins that are not the check (email code, password, providers) send no email; every sign-in is still in the audit log (auth_events). The email names the admin, the time (UTC), the approximate browser and system ("Chrome on macOS", else a shortened browser string with links removed) and the address, and says what to do if it was not them. On an install with a single admin the alert goes only to that admin's own mailbox, which is the one an attacker would have: add a second admin; Server admin itself needs the passkey anyway. Better Auth's sign-in and linking with a provider ID token posted by the client (/sign-in/social, /link-social with idToken) are refused (refuseIdTokenSignIn, auth.ts): Linedesk signs in with providers only through the redirect. The redirect's state is one encrypted, browser-bound cookie that lasts 10 minutes (account.storeStateStrategy: 'cookie', auth.ts). With Better Auth's default, the state was in the database for 10 minutes but also needed a second cookie that lasted only 5, so a slow provider sign-in came back with ?error=state_mismatch. That error still appears when another provider sign-in was started in the same browser before the first one finished (the newer one replaces the cookie), or after 10 minutes; the sign-in page then says to start again. ADMIN_SECOND_FACTOR=off turns the passkey check and the email check off (only for installs without https, where passkeys cannot work; the new-device alert then covers every admin sign-in) and the API prints a warning at every start. A local install (every address that is set, PUBLIC_URL, WEB_ORIGIN and BETTER_AUTH_URL, is localhost, 127.0.0.1, [::1] or a *.localhost name: local development; the same check keeps the admin alerts quiet) has the check off by itself, for admins and the owner's step-ups, and the API says so in one line at start; ADMIN_SECOND_FACTOR=on turns it on there (localOnlyInstall, decided 2026-11-15). A tunnel (scripts/tunnel.sh, scripts/local-public.sh) sets a public address, so the check is on there. Authenticator app (apps/api/src/authenticator.ts, totp.ts): the fallback to the passkey, for an emergency or a computer without it; the passkey stays required. An instance admin with a passkey, after the passkey check, adds a TOTP app (RFC 6238: SHA-1, 30 s, 6 digits; QR code drawn in the browser) with account.authenticatorStart and account.authenticatorConfirm; the enrolment code never adds it. Later account.authenticatorCheck passes the check (permission secondFactor:own, which every session of an instance admin has, never while impersonating); it is refused for an account without a passkey, and adminSecondFactor is enrol for such an account whatever the session passed. Confirm and check run only through POST /v1/account/authenticator/confirm|check (authenticator-routes.ts), which set the device cookie and send the new-device alert like a passkey check; the generic action route refuses them. A right code sets session.passkey_verified_at and session.second_factor_method = 'authenticator' for this session: it opens Server admin and allows adding a passkey (no code), but removing or renaming passkeys, adding or removing the app, the email change without the old-address code and the owner's workspace delete need a passkey sign-in (passkeySignedIn, admin-second-factor.ts; a code is phishable). Tries are claimed atomically before the comparison, so parallel requests cannot get past the lock. The prompt then offers "Add a passkey on this device" (the checked session adds it without a code). Codes work once (admin_authenticators.last_step), one step either side of now; five wrong codes lock the app for 15 minutes (counted outside the action's transaction). The secret is AES-GCM encrypted with SECRETS_KEY, bound to the user. /v1/me reports hasAuthenticator to instance admins. Reset passkeys and revoking admin remove the app; removing it needs a checked session; both add and remove email the admin. No backup codes.
Better Auth's admin plugin was not used: it adds impersonation, user creation, password reset and its own role system as HTTP endpoints outside the action registry. Impersonation is built on the registry instead (below), with Better Auth's own sessions and cookies.
Impersonation. An instance admin can sign in as a user (Server admin › Users, the user, "Sign in as …"; or Server admin › Workspaces, the workspace, "Sign in as {owner}…") to see Linedesk as they do. Two registry actions, both in the command log: user.impersonate { userId, reason, workspaceId? } (instance:admin; the actor is the admin) and impersonation.stop (permission impersonation:stop, which only an impersonated session has; the actor is the user, commands.impersonated_by the admin). An action cannot set cookies, so both run only through POST /v1/impersonation/start and /stop (apps/api/src/impersonation-routes.ts); POST /v1/actions/<name> refuses them.
user.impersonaterefuses yourself, a disabled user, another instance admin (also one byINSTANCE_ADMIN_EMAILS) and a session that is itself an impersonation. A reason is required (reason, 3 to 300 characters, trimmed; 422 without): the dialog asks for it ("Reason (kept in the audit log)"), the command log keeps it with the input (audited actions are never pruned), and Server admin › Audit log shows "Signed in as {email}" with "Reason: …" under it (the result'sdata.subjectnames the user and files the entry under the workspace it opened in). It creates a Better Auth session for the user with its internal adapter:session.impersonated_by= the admin, expiry one hour, active workspace =workspaceIdwhen given, else the user's first.workspaceIdmust be a workspace the user is a member of (checked in the handler; 409 "this user is not a member of that workspace" otherwise, no session made). The route sets Better Auth's session cookie to it, signed as Better Auth signs it, and keeps the admin's own session token in a separate signed, httpOnly, SameSite=Lax cookie (better-auth.admin_session, Secure on https) for the same hour. The user's last sign-in is not touched.- The hour is fixed: the session is marked "not remembered" and a
session.updatehook keeps its expiry when Better Auth would extend it;resolveActoralso refuses it one hour after it started, and as soon as the admin is disabled or no longer an instance admin. - While impersonating, the actor has the user's workspace permissions plus
impersonation:stop, neverinstance:admin, so/v1/admin/*and admin actions are refused and no second impersonation starts. Registry actions are an allow-list (IMPERSONATION_ALLOWED_WRITESinapps/api/src/impersonation-guard.ts, checked centrally inrun-action.ts): read-only actions (exceptwebhook.test,call.lookUpCaller,call.askWebhook,carrier.testandassistant.startTestCall, which reach outside), inbox triage (call.markRead/markUnread/markDone/markNotDone/remind/clearReminder), API keys (apiKey.create/revoke, below) andimpersonation.stop; every other write answers 403 "Not possible while signed in as another user.", so apart from API keys nothing done as the user can outlast the hour (no invitations, members, webhooks, carrier, numbers, assistant or transfer settings, deleting the workspace, connecting a calendar). Commands recordimpersonated_by. Refused: Better Auth's endpoints that change credentials or the account's security or hand out tokens (change, set or verify a password, update the profile, change email, delete the user, list or revoke sessions, link or unlink accounts, account tokens, and asking for or redeeming the user's email confirmation code, so only the user confirms their own address;apps/api/src/impersonation-guard.ts),POST /v1/account/passwordandPOST /v1/workspaces; the web app does not mark calls read when an impersonating admin opens them. The guard is about the impersonation session: an admin who can read the install's outgoing mail (they set up email in Server admin › Providers) could still ask for a sign-in code without that session, so refusing sign-in codes while impersonating would protect nothing. impersonation.stopdeletes the impersonation session. The route then restores the admin's session from the admin cookie only if that cookie's signature is valid and its session exists, has not expired, is no impersonation and belongs to the admin who started it, who is still an enabled instance admin; otherwise the browser is just signed out. The admin cookie is cleared either way./v1/mereturnsimpersonation: { by, user, expiresAt } | null. The web app shows a dark bar under every page with whose session it is, who is in it, the minutes left and "Return to admin", which returns to the user's page in Server admin. Before starting and stopping, the outbox is sent and the local data of the ending session deleted.- Sign in as owner (Server admin › Workspaces › a workspace,
signInAsOwnerActioninapps/web/src/admin/actions.tsx): the button names the owner and runs the same start with the owner's id and thisworkspaceId, so the session opens in this workspace. Where the start would be refused (the owner is you, disabled or an instance admin) the button is shown disabled with the reason under it; a workspace without an owner has no button. The API refuses the same cases on its own. - No email to the user (decided 2026-11-21): signing in as a user and API keys made then send the user no email; the audit log is the record.
- API keys are allowed while impersonating (decision 2026-11-15: support often is about exactly this):
apiKey.create,apiKey.revokeandapiKey.listrun as the user. A key made then outlasts the hour by design. It has every feature of a normal key (the role asked for,call.export, everything else a key may run), and the admin may revoke any key of the workspace, as the user could (decided 2026-11-15: traceability instead of limits). What makes it traceable (apps/api/src/api-keys.ts):- it records the admin in
api_keys.created_by_impersonator(migration 0100), and its command incommands.impersonated_by; - its actor carries the admin (
Actor.apiKeyImpersonator, fromactorForApiKey): every command it runs recordscommands.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, exceptcall.export(READS_LOGGED_WHEN_IMPERSONATED, run-action.ts): with an admin behind it (signed in as the user, or such a key) it gets acommandsrow 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, inapiKey.list; never their id); - revoking a key while impersonating is a command like any other there:
commands.impersonated_bynames the admin. A key still never manages keys, and the key keeps following its creator's role (the user's).
- it records the admin in
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.
Audit log. Server admin › Audit log (GET /v1/admin/audit, instance:admin; apps/api/src/audit.ts): who did what, newest first, filtered by kind (sign-ins, sign-in methods, admin actions, team changes, provider keys, API keys, webhooks and AI agent setup, signed in as a user), person (email or name), workspace and dates, paged with a cursor. Two sources, merged: the command log (commands) for the actions in AUDITED_ACTIONS: admin actions (user.*, workspace.create/disable/enable/delete/setSpendingCap, instanceAdmin.*, membership.*, server-wide invitation.*, branding.set and the install-wide switches voiceCloning.set, callQuality.set, afterCallTranscript.set, setupEmails.set, outboundCountries.set with the list before in data.previous), team and role changes (team.*, invitation.accept/decline, workspace.deleteOwn), provider and carrier keys (provider.setKeys/clearKeys/setActive/connectOneKey, carrier.set; inputs already redacted), integrations (API keys, webhooks, calendar connections, phone number setup and release, setup links, and assistant.update or assistant.restoreVersion when it changed the transfer contacts, refused ones with transfers in their input included: data.transferChanges keeps only the contacts added, changed (which fields) and removed, by id, name and the number's last four digits, never the whole list; the admin page gets their names, and the input's contacts masked the same way; deleting the workspace cuts it to ids like its other commands) and impersonation (user.impersonate with its reason, impersonation.stop, and every action done while signed in as a user), refused attempts included; every action an AI agent ran with a setup link (commands.setup_key_id) is listed too, whatever the action, under integrations and marked "via AI agent setup link"; and auth_events for what happens in Better Auth's endpoints: sign-ins and sign-ups with their method (password, email code, passkey, Google, Microsoft, GitHub, OIDC; from the endpoint that created the session, in the session.create hook), a provider or password added to an account (account.create), passkeys added or removed, password changes and accepted invitations (after-hooks on those endpoints, only when they succeed). Impersonation sessions are not sign-ins. Other everyday actions (calls, contacts, most settings) are not audit entries, unless done while signed in as a user or through a setup link. Audited actions keep their input and result data for good (the 90-day prune skips them), including the address of whom a change was about (data.subject), so those rows outlive the account they name. Nothing in either table is ever deleted, and auth_events has no foreign keys, so entries outlive the user or workspace they name (the email at the time is kept). When a user is deleted, a database trigger anonymises their auth_events (email becomes deleted, IP address and user agent are cleared) and keeps the events; transcripts stay as they are. Answering a workspace invitation is refused while impersonating, so every accepted invitation is the user's own. A failed audit write is logged and never blocks the sign-in it describes.
Disabling. user.disable sets user.disabled_at, deletes the user's sessions and blocks new ones (a Better Auth session.create hook; the API also refuses a disabled user on every request). workspace.disable sets organization.disabled_at; call.start then rejects calls to its numbers, and its members keep only their read permissions (*:read): they can sign in and read, but no registry action that writes (triage, settings, phone numbers) runs for them. /v1/me reports workspace.disabled. Better Auth's own organization endpoints (invitations, roles) do not check it yet.
Deleting a workspace. workspace.delete { workspaceId, name } (instance:admin, so a session that passed the passkey check; apps/api/src/workspace-delete.ts; Server admin › Workspaces, "Delete workspace…", which names the calls, contacts, numbers and members and unlocks once the name is typed). The name must match on the server too. In one transaction: every table with a workspace_id column loses the workspace's rows (found from the Drizzle schema, children before the tables they reference, so a new table needs no change), then the organization row, with its members and invitations by foreign key. Kept: the audit log (commands, the workspace's non-audited commands cut down to ids like the 90-day prune; auth_events), number_purchases (the install's purchase limits count them) and voice_clones rows (consent records; the voices are deleted at the provider by job). Recording files are deleted by a recording.deleteFile job per file, queued in the transaction; the workspace's queued jobs (emails, pushes, webhook deliveries, evaluations) are dropped. Phone numbers, last: a number bought through Linedesk in the install's carrier account is released there; every other number (an attached one, or any in the workspace's own carrier account) is un-routed and stays its owner's; a carrier that fails or is not set up any more does not stop the delete, the result lists the number as left at the carrier and the admin sees it. The LiveKit trunk of its own carrier account is removed. Members who belong to no other workspace lose their accounts too, unless the admin ticks "Keep accounts" (keepAccounts); members of other workspaces and server admins always keep theirs (Workspace rights, Accounts without a workspace). Every member but the deleting admin is emailed (workspace.deletedEmail job, queued in the transaction before the numbers are released at the carrier, signed "The server admin of ", saying whether their account went too). Remaining sessions on the workspace move to none, so the next request lands on the user's next workspace, or the waiting page ("Waiting for an invitation"); an open tab of it shows that the workspace no longer exists. The command log entry (kind admin) keeps who, when, the workspace's id and name and how many rows went per table, never the data.
An owner deleting their own workspace. workspace.deleteOwn { name, keepOwnAccount?, keepAccounts? } (workspace:own, which only the owner role has, and the handler refuses anyone but the owner of the workspace, and impersonations; apps/api/src/workspace-delete-own.ts; Workspace settings › Danger zone, "Delete workspace…"). The same delete as above, plus: a fresh sign-in first (apps/api/src/owner-step-up.ts, checked in run-action.ts before the transaction and again in the handler): a sign-in in the last 10 minutes, and when the owner has a passkey that sign-in must be the passkey (PASSKEY_STEP_UP_REQUIRED, the web app's passkey dialog); without one the refusal is SIGN_IN_AGAIN and the dialog offers "Sign in again", which comes back to it. ADMIN_SECOND_FACTOR=off leaves only the 10 minutes. It waits for a confirmed email address like inviting. Every other member gets an email (workspace.deletedEmail job, queued in the transaction: who deleted it, when in the workspace's time zone, whether their account went too). Accounts: members who belong to no other workspace and are not instance admins are deleted, and so is the owner's own, unless keepAccounts (every account stays) or keepOwnAccount (only the owner's stays; then they land on the no-workspace page); an owner with another workspace continues there (nextWorkspaceId). workspace.deletePreview (owners, read-only) gives the dialog its counts (calls, contacts, numbers bought and attached, other members, accounts that go, whether the owner's own goes) and the step-up the server would ask for now. Command log kind team.
Providers. The registry in packages/actions/src/admin.ts describes each provider: label, category (telephony, speech to text, language model, voice, realtime model, email, sign-in and calendar, recording storage), its fields and which are secret or optional; apps/api/src/provider-test.ts holds how to test its connection. Shipped: Telnyx (API key, webhook public key; the default carrier), Twilio (account SID, auth token), Deepgram (API key), ElevenLabs Scribe, OpenAI transcription and AssemblyAI Universal-3.6 Pro (streaming speech recognition that detects the end of a turn itself; own key variables ELEVENLABS_STT_API_KEY, OPENAI_STT_API_KEY, ASSEMBLYAI_STT_API_KEY), OpenRouter (API key, zero data retention switch), OpenAI, Anthropic, Google Gemini, Groq and Mistral (API key; each on its OpenAI-compatible API, endpoints and default models in llmEndpoints, packages/actions/src/admin.ts, shared by the agent and the API), ElevenLabs and Cartesia (API key), OpenAI Realtime (API key; its key falls back to OPENAI_API_KEY), for email SMTP (URL, from; a preset for Amazon SES) and mail services with a key or app password: Resend, Postmark, SendGrid, Brevo, Mailgun and Gmail (address and app password); apps/api/src/email-services.ts turns the one that sends (picked, EMAIL_PROVIDER, else the first set up; plain SMTP first) into SMTP_URL and EMAIL_FROM at start: an SMTP URL on 587 for every service but Resend, which sends and is tested through its HTTPS API (https://resend:<key>@api.resend.com, apps/api/src/email-resend.ts; port 443, open on hosts that block outgoing SMTP such as DigitalOcean), for sign-in and calendar Google, Apple (Services ID, team ID, key ID, the .p8 key, the iOS app's bundle ID), Microsoft (with tenant), GitHub and OIDC (discovery URL, client, button label, trusted email domains), and for recording storage Local disk (file, no fields) and S3-compatible (s3, see below), and for billing Stripe (stripe: secret or restricted key and webhook signing secret, both secret; Linedesk Cloud only). Each field falls back to the variable the voice agent reads (apps/agent/src/config.ts): DEEPGRAM_API_KEY, S3_ENDPOINT and so on. The speech, language, voice and realtime providers hold only their key (decision of 2026-11-18): the call's models come from its call quality level (Server admin › Settings › Calls › Call quality, CALL_QUALITY_DEFAULTS), the after-call summary's from SUMMARY_MODEL_DEFAULTS (both in packages/actions/src/usage-level.ts), the voice from each assistant (else the provider's default voice); "Hear the voice" speaks with the default voice model of the level new assistants start on. The database stores provider id and field name as text (provider_settings, one row per field), so a new provider is an entry in the registry and no migration. workspace_id is null: the keys are for the whole install. Rows with a workspace id are a workspace's own carrier credentials (§8, Own carrier account); they never count for the install, the admin area does not list them, and only apps/api/src/workspace-carrier.ts reads them.
What stays in env. Only what the install needs before it can read its database: the secrets its containers share (POSTGRES_PASSWORD, ELECTRIC_SECRET, BETTER_AUTH_SECRET, SECRETS_KEY, AGENT_API_TOKEN, LiveKit's key and secret, which LiveKit, SIP and egress read from their own config), addresses (PUBLIC_URL) and limits. scripts/setup.sh writes them with random values, so a new install needs no hand-made .env. Every provider field keeps its variable as a fallback for scripted installs; apps/api/src/providers-import.ts moves set variables into the app.
Sign-in is read at start, email applies at once (apps/api/src/instance-env.ts): Better Auth is built with its sign-in providers once. server.ts copies the stored values of the email and sign-in categories into process.env (the stored value wins; serverEnv keeps the server's own variables, the fallback the admin area shows) and only then imports the app. A change of either (provider.setKeys/clearKeys, the email pick) needs Server admin, so the passkey check (an SMTP server or sign-in provider of one's own would hand over sign-in codes or any account), and emails every instance admin (signInCategories), the one who made it included. Email then applies without a restart: once the action committed and before it answers (onCommit, run-action.ts), the stored email settings are copied into process.env again (followEmailSettings; a read that started earlier is never applied over a later one) and the sender (email.ts) follows process.env. Codes still waiting to be used (sign-in, confirmation, password reset, email change) are deleted, and the alert goes through the sender in effect before the change, and through the new one too when it differs (the first setup has none before), so a mail server of an attacker's own cannot swallow the alert about itself. Picking which email provider sends (provider.setActive) alerts the same way; the email code endpoints of Better Auth are always loaded and answered only while email can go out. A sign-in change restarts the API once it has committed where something starts it again (LINEDESK_SELF_RESTART=1, set by docker/api-entrypoint.sh: Docker's restart policy, dev mode's runner); in pnpm dev it logs that a restart is needed, and Server admin › Providers shows sign-in as "saved, takes effect after the API restarts" until then. Every API process also compares the stored rows every 15 s: it follows changed email settings and restarts for changed sign-in settings, so a second process follows. Sign-in (sign_in) is the one category where every provider that is set up is in use at once (multiCategories); the dialog shows the redirect URIs to add to the provider's app. "Test connection" for an OAuth app exchanges a made-up code: the provider checks the client first (invalid_client) and the code second (invalid_grant), so a rejected code means the app is right. SMTP is tested by connecting and logging in.
Branding (Server admin › Branding, branding.set, apps/api/src/branding.ts): an install that runs under its own name sets the product name (shown wherever the app says Linedesk: menu, sign-in, tab title, emails, passkey prompts), a logo, the primary color (--action, text on it light or dark by contrast) and whether the GitHub star prompt shows (the one-time card, Star on GitHub in the sidebar and the line at the end of onboarding; the API reads the repository's star count from GitHub about once an hour, apps/api/src/github-stars.ts, and returns it as starCount, so browsers never call GitHub). Stored in instance_settings (branding as JSON, the logo under branding.logo). The browser turns any uploaded image into a PNG of at most 512×512 before it is sent; the server checks the PNG header and size and serves only that PNG (GET /v1/branding/logo.png?v=<version>, cached for good), so no uploaded SVG ever reaches a page. Public: GET /v1/branding (the web app reads it before sign-in and keeps it in localStorage for the next load) and GET /v1/branding/manifest.webmanifest (name and icons for the installed app). Each API process keeps the branding in memory for emails and messages (loaded at start, after its own change, every 30 s). Messages about the install itself say "this server" instead of a product name; developer-facing names (webhook headers, the API title, logs) stay Linedesk.
Push keys (VAPID) are made on the first start and stored in instance_settings (the private key encrypted), shared by every API process; VAPID_* on the server win.
First admin: setup code (apps/api/src/setup.ts). While the install has no user, the API prints a one-time code (8 characters, about 40 bits) to its log at every start and stores its SHA-256 in instance_settings. GET /v1/auth-methods reports setupNeeded; the sign-in page then asks for the code, a name, an email and a password, and POST /v1/setup creates the first instance admin and signs them in. Reading the log needs access to the server, so the code proves what INSTANCE_ADMIN_EMAILS proves otherwise; the address counts as confirmed, as with user:create --admin (there may be no email set up yet). One setup at a time (an advisory lock). Wrong codes are limited to 5 per address and 20 in all per 15 minutes; the code itself stays until the next start, so nobody can rotate it away from the operator. With two API processes starting at once (an update) only the last code printed works. INSTANCE_ADMIN_EMAILS and user:create --admin keep working.
- Values are encrypted with AES-256-GCM (
apps/api/src/secrets.ts); the key isSECRETS_KEY(32 bytes, base64). Without it, saving is refused with the reason. Losing or changing the key makes the stored values unreadable (the admin area still lists them as set; using them reports the problem): set the keys again. - Resolution on every use (
apps/api/src/provider-settings.ts): the stored value wins, the environment variable is the fallback. No restart needed after a change. - One provider per category is active. An instance admin picks it (
provider.setActive, stored ininstance_settingsasactive_provider.<category>). Without a pick, the category's variable names it (TELEPHONY_PROVIDER,STT_PROVIDER,LLM_PROVIDER,TTS_PROVIDER,REALTIME_PROVIDER,RECORDING_STORE, as for the agent); without that, each category uses the first provider in the registry with every needed field (telephony: Telnyx before Twilio, anddev, no carrier, when none is set up;TELEPHONY_PROVIDER=devkeeps it atdev). Recording storage and the realtime model have no such fallback (optInCategories): the local disk needs no fields and would always count as set up, so calls are recorded only once a store is picked orRECORDING_STOREnames one; a realtime model answers calls only once it is picked orREALTIME_PROVIDERnames one, and clearing the pick ("Stop using") goes back to speech to text, language model and voice. While it answers, the voice readiness check needs only it, the cost estimate counts it instead of the three stages, andvoice.optionssaysrealtime: true, so the assistant settings hide the voice picker. A picked or named provider that is not set up is not replaced by another one. - A secret never goes back to the browser.
GET /v1/admin/providersreturns per field the source in effect (app,envor none), the last four characters of a stored secret (none for values shorter than 12 characters or from env), and who changed it when; and per category the active provider. Fields that are not secret (account SID, model, Telnyx public key) are returned in full. provider.setKeysmarks itsvaluesassensitiveindefineAction;run-action.tsstores sensitive input fields incommandsas[redacted](keys kept, values dropped). Any new action that takes a secret must do the same.provider.testmakes one authenticated request with an 8 second timeout. On 401/403 the provider's text is not passed on, because providers echo parts of the key; other errors carry the provider's message with every key value removed.
Recording storage. Where LiveKit egress writes call audio and the API reads it (apps/api/src/recording-store.ts).
file, Local disk: a directory egress and the API share (RECORDINGS_DIR; therecordingsvolume with docker compose,data/recordingsin development). No fields; it stays in env because it is a path on the server. Needs therecordingcompose profile (pnpm recording:up).s3, S3-compatible: endpoint URL, region (defaultus-east-1;autofor R2), bucket, access key ID, secret access key (the only secret), optional path prefix and the switch "force path style" (endpoint/bucket/key; on by default, off givesbucket.endpoint/key). Env fallbacksS3_ENDPOINT,S3_REGION,S3_BUCKET,S3_ACCESS_KEY_ID,S3_SECRET_ACCESS_KEY,S3_PREFIX,S3_FORCE_PATH_STYLE. The edit form fills in endpoint, region and path style for AWS S3 (https://s3.<region>.amazonaws.com), Cloudflare R2 (https://<account-id>.r2.cloudflarestorage.com, regionauto), Hetzner Object Storage (https://<location>.your-objectstorage.com), Backblaze B2 and MinIO. The key needs read, write and delete on the bucket.- The voice agent gets the active store with
GET /v1/agent/provider-config(recording, below) and starts each egress with it: a file path in the shared directory, or an S3 upload with the keys in the request (egress needs no storage settings of its own). It reports the store with the recording (call.setRecording { store }), and the API keeps it incalls.recording_store. - Each recording is served, signed and deleted (retention job) from the store it is in, resolved on every use, so switching from the local disk to S3 (or back) needs no restart and older recordings keep playing from where they are. A call recorded before this column existed has
recording_storenull:RECORDING_STOREnames its store, the local disk without it. S3 settings are not kept per recording: a recording in a bucket plays with the S3 settings in effect, so moving to another bucket means copying the objects (or keeping the old settings). provider.testfor a store writes a small object (.linedesk-probe-<uuid>.txt, under the prefix), reads it back and deletes it, with the same 8 second timeout. Errors name the step and S3's status and error code (NoSuchBucket,SignatureDoesNotMatch); S3's error text is never passed on, because it quotes the key ID, and other text has the key ID and secret removed.workspace.getSettingsreportsrecordingOnfrom the same setting; the minute sweep that links unreported recordings looks in the active store.
LiveKit is part of the install, not a provider. Its URL, key and secret stay in env. GET /v1/admin/system reports, read-only, whether the server answers (ListRooms) and whether an inbound SIP trunk is configured (ListSIPInboundTrunk). The server answers the SIP API without the SIP bridge running, so this shows the SIP setup, not that the bridge is up; the bridge has no API of its own to ask. LiveKit's API does not report a version, so none is shown.
Providers in one place (packages/actions/src/provider-status.ts, apps/api/src/setup-checklist.ts, apps/web/src/admin/providerStatus.ts). The providers are shown in groups, with the same ids, order and words everywhere (Server admin › Providers, the overview's "Ready for calls" card, the install walkthrough, the setup MCP's setup_status and scripts/setup.sh --check): email, telephony (Phone carrier), answering (Answering calls: the realtime model, or speech to text, language model and voice), call-audio (LiveKit and its SIP bridge, read-only, set in .env), and the optional sign-in, calendar (the sign-in apps that also connect calendars), recording and business. The first four are what a call needs. One pure function, statusGroups, turns what is known about each provider (keys set, in use, the last test of exactly these keys from provider_tests, the recorded failures from provider_failures, how each assistant answers, LiveKit) into one status per group: Works, Failing: , Not set up, Partly works: , Checking…, Not tested, Not needed or Off (an optional group that is not set up). A recorded failure (a call, an email, the health check) beats a stored passing test until a newer test passes; keys saved after the failure make it count as the old keys' failure. Answering has one status, and its line says what actually answers, with the voice agent's fallback (pipelineFor): "Answered by OpenAI Realtime." The API computes it for GET /v1/admin/setup-checklist (read-only, never calls a provider); the web app computes the same from GET /v1/admin/providers (tests, failures, status) and the health check, and checks a provider that is set up but has no stored test once with the free key check (provider.test with free: balance, account, key and model lists; never tokens, speech or transcription). Server admin › Providers lists each group with its status and providers, a quiet "Recommended" on the one we suggest, and "Set up with an AI agent" on top while a group a call needs is not set up; #admin/providers/<group> scrolls to the group, #admin/providers/<provider> opens its dialog, and old category links land on their group. The provider's dialog is the one editor: status with when it was tested, "How to get a key" (the registry's guide for every provider, open until it works), the keys, Test again (the free check) and Try it (a real round trip, provider.tryOut, docs/api.md "Install setup by hand", including the emailed code). One key (provider.connectOneKey, OpenAI Realtime) is offered only in Answering's empty state. The overview's "Ready for calls" card is read-only: the groups a call needs, the API, read sync and voice agent, and an optional group only while it fails, each linking to where it is fixed; it folds to one line when everything works, and a failing carrier, Answering or call audio makes it "Calls are not answered" with the reason. Background health check (apps/api/src/provider-health-check.ts, pg-boss providers.healthCheck): every PROVIDER_HEALTH_CHECK_HOURS (default 6, 0 or off to turn it off) the free key check of every provider that is set up, never a paid round trip; results are stored like any test, a pass clears the provider's failure, a failure is recorded. The instance admins get one email when a provider that calls need and that is in use starts failing (provider_failures.alerted_at, once until it works again; a passing problem such as "not reachable" only when the check before failed too); optional providers and providers not in use fail quietly. Headless: scripts/setup.sh --check (apps/api/src/setup-check.ts) runs in the running api container; on a docker install whose stack is down it says to start it (exit 1), and only a development checkout (node_modules) runs it from the checkout. It runs provider.test as the operator once per provider in use and prints each group with its status and, for a group that is not set up, the recommended provider's steps; exit code 0 when every group a call needs works, 1 when something is missing or failing (or the stack is down), 2 when the check itself fails.
Setup reports (apps/api/src/setup-feedback.ts, docs/api.md "Feedback to the Linedesk team"). What an install sends out on its own account: with the admin's yes, the setup agent's report of what failed, was slow or went well, built and redacted by the server (never the agent): outcome and items, version, install type, a random install reference, the server steps' states, the agent's name; never keys, phone numbers, email addresses, business details, call content or IP addresses (a contact address only when the admin gave one). It is a feedback row (feedback.send with kind: setup, the same action as Help's reports) POSTed to SETUP_FEEDBACK_URL (off: kept only), retried hourly for 7 days while the endpoint is not there, listed in Server admin › Workspaces › At risk with Send again. Every other report (Help, feedback_send from a workspace's MCP client) goes by email to FEEDBACK_EMAIL.
Admin reads cross workspaces, so they are plain routes instead of read sync, all behind instance:admin: GET /v1/admin/workspaces, /v1/admin/users, /v1/admin/usage?months=6 (calls and minutes from calls.duration_sec per workspace and UTC calendar month) and /v1/admin/providers.
Agent tokens. The voice agent has two tokens. The install-wide AGENT_API_TOKEN opens a call (call.start, which finds the workspace by the dialled number; call.startTest, with the workspace from the dispatch the API signed in x-workspace-id; call.findForTest for the call test) and reads GET /v1/agent/provider-config. call.start and call.startTest return data.callToken (apps/api/src/agent-token.ts): ldcall_<payload>.<signature>, bound to the call's workspace and the call, valid for 4 hours, HMAC-signed with a key derived from BETTER_AUTH_SECRET (the agent never has it, so it cannot make one). Every later request about the call goes with it (apps/agent/src/api-client.ts); x-workspace-id must then be its workspace or absent. A call token runs only the call's actions for its own callId and refuses call.start, call.startTest and call.findForTest; the command log keeps it [redacted]. The agent role has only the agent permission: the agent actions plus the member actions marked agent in the registry (calendar.findSlots; appointment.book, .cancel and .reschedule only with a callId), never another member action and never GET /v1/shape/* (read sync needs call:read and refuses the agent). In a disabled workspace the agent can do nothing, with either token. Updates: an agent older than the API ignores callToken and keeps sending the install-wide token with x-workspace-id, which this release still accepts for call actions; an API older than the agent returns no callToken, and the agent then does the same. This compatibility window ends with the next release, by 2026-12-31 at the latest: it then refuses the install-wide token for everything but opening a call and reading the providers (contract). GET /v1/agent/provider-config refuses call tokens (403): a leaked call token never reads the install's keys. Call tokens follow the same entry rule as the install-wide token (internal listener only, checked first) and wrong ones count toward the same per-address throttle. Behind the voice link (voice servers, below) the count is per address and voice server: the link sets X-Linedesk-Voice-Node to the voice server's address, the API reads it only on the internal listener, and the public site removes it.
Voice agent config. GET /v1/agent/provider-config with the agent token (Authorization: Bearer $AGENT_API_TOKEN) returns, per speech and LLM category, for the realtime model (null unless picked) and for recording storage, the active provider and its values in clear, except the recording store's secret fields: the S3 secret access key stays with the API, which starts S3 recordings itself (call.startRecording, apps/api/src/recording-egress.ts: LiveKit egress gets the bucket's keys in the request; the agent stops the egress and waits for the file with its LiveKit keys as before). An API older than the agent still sends the secret, and the agent then starts the egress itself. The agent token is for the install's own network only: Caddy answers 404 for /v1/agent/* on the public site and marks every request it proxies from there with X-Linedesk-Entry: public (replacing what the client sent); the API accepts agent tokens only on requests marked internal, which Caddy's internal listener (proxy:3100) sets and the agent goes through. A request without the header (straight to the API) counts only outside production (NODE_ENV not production, as in pnpm dev); the images set NODE_ENV=production, so a container that reaches api:3100 around the proxy is refused. call.startRecording is refused once the call has ended or when its assistant has record_calls off; the API holds a lock on the call while it starts egress and returns the egress already recording the room, so a retry never records the call twice. AGENT_API_TOKEN must be at least 32 characters: the API refuses to start with a shorter one (the docker entrypoint turns the placeholders change-me and the .env.example development value off instead), and the agent refuses one too. Wrong agent tokens count per client address: after 10 in 10 minutes the address gets 429 for a while. The agent asks at the start of each call (apps/agent/src/config.ts, cached for 30 s per worker process), so an install can come up without keys and start answering once the operator has entered them. For a category that is null, or when the API cannot be reached, the agent uses its own env variables; a failure to reach the API is logged once, never with values. Members, instance admins included, get 403. A category is null when no provider is set up for it (or the picked one is not); optional fields such as model are null when unset. 409 { ok: false, error } when stored keys cannot be decrypted. The keys inside a category are the provider's field names from the registry.
{
"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 is { "provider": "file" } for the local disk, and null when calls are not recorded; then the agent's own RECORDING_STORE and S3_* apply, as for the other categories (apps/agent/src/recording.ts). An agent talking to an API without recording does the same.
For apps/agent/src/config.ts: stt.model, llm.model, tts.model and tts.voice_id are the stored values or the API's environment variables; when null, the agent keeps its own defaults (model ids, baseUrl per LLM provider). llm.model (live turns) and llm.summary_model (the summary after the call) are lists, "model, fallback, ..."; with OpenRouter the agent sends the list as models, so a rate limit or outage of one model falls through to the next. Defaults with OpenRouter: live google/gemini-3.5-flash-lite, openai/gpt-4.1-mini, summary google/gemini-3.5-flash-lite, openai/gpt-5.4-mini (Gemini direct: gemini-3.5-flash-lite for both; the 2.5 models are deprecated). An assistant's own language model (assistants.llm_model, from the usage-level list for the install's provider) goes first, the install's list after it as fallbacks (withAssistantModel); its own voice model (voice.model) replaces the install's (voiceModelFor).
Passwords (/sign-in/email): besides Better Auth's per-IP limit, 10 wrong passwords for one address in 15 minutes, from any IPs, pause password sign-in for it until the window has passed (sign-in-limits.ts); other ways in keep working.
Email sign-in by code. Better Auth's email OTP plugin (apps/api/src/auth.ts): a 6-digit code by email, valid 10 minutes, 3 tries per code (then a new one is needed), stored hashed; at most 3 requests a minute per client address (Better Auth's limit), and per email address and client address a wait before each new code that grows with each one (30 s, 2, 5, then 10 minutes; CODE_COOLDOWN_STEPS_S in packages/actions/src/code-cooldown.ts, so a person can always ask again, a little later each time; a refused request answers retryAfter in seconds and Retry-After, the pages count it down), under 5 codes in 10 minutes and 10 wrong codes an hour, plus per email address and client address 10 codes an hour and 20 wrong codes a day, and per account from any client address at most 40 codes and 30 wrong codes in a clock hour and 150 wrong codes in the last 24 hours (apps/api/src/sign-in-limits.ts; the caps per account are kept in Postgres, table sign_in_counters, only for addresses that have an account, so a restart, a second API process or a flood of other addresses does not reset them; the same caps are also kept in memory for every address, with or without an account, so the answer does not tell whether an account exists; the counter's commit does not wait for the disk, so its timing does not tell either; only failures count, and the caps across client addresses are sized so one network alone can not reach them: it takes at least 4 networks to pause code requests for an hour, 3 to pause code checks for an hour and 8 for a day; the person then signs in another way until the window has passed. At 150 guesses a day an even chance of guessing a code takes about 12 years. The limits per client address are in memory: blocked keys are kept apart from counting ones, so a flood of other addresses never lifts a block). A browser that signed in to the account before is not held by the caps across client addresses, which anyone with enough networks can fill (apps/api/src/known-browser.ts): every response that gives a browser a session (any sign-in method, and the session's daily refresh; not an admin signed in as the user) sets the known_browser cookie (__Host-known_browser on https; httpOnly, Lax, 90 days from the last sign-in), the account's id and the time, signed with HMAC-SHA256 under a key derived from BETTER_AUTH_SECRET. A code request or code check (sign-in, confirmation, password reset) whose address is the current address of the account the valid cookie names gets caps of its own instead, of the same sizes, per cookie and in memory (40 codes and 30 wrong codes an hour, 150 wrong codes a day), and its code checks also stop once the account's known browsers had 150 wrong codes in the last 24 hours (sign_in_counters, kind known_browser_failure, counted only for requests with a valid cookie for that account, so nobody without one can fill it, also not with parallel guesses from many networks; a restart or a flood of other cookies does not lift it; code requests have no such floor). So stolen cookies add at most another 150 guesses a day: at most 300 a day per account, an even chance of guessing a code in about 6 years. A provider sign-in (a 302 redirect) sets the cookie too, an error answer never; only the first value of each cookie name is read and only the first one with a valid signature is looked up, once per request. The limits per email address and client address still apply, and its codes and wrong codes still count towards the address's and the account's caps. Any other request (no cookie, a forged or expired one, one for another account, an email change's new address) is answered exactly as before; only a valid cookie leads to a database read. The email has the code in its subject and body and no link. A code sign-in marks the address verified. A first code sign-in makes an account only for an address with a pending invitation (No open sign-up, below). The same plugin sends the confirmation codes (Email confirmation before sensitive actions), password reset codes and the codes of an email change (both below).
Sign-in email button (apps/api/src/sign-in-link.ts, sign-in-link-routes.ts, apps/web/src/SignInLink.tsx): the sign-in code email shows "Sign in to " first and the code below. For an address that gets a code, a link is stored: identifier sign-in-link-<SHA-256 of the token> in verification, value the address and the code AES-GCM-encrypted with a key derived from the token (HKDF), expiring with the code. The button opens <origin><path>#sign-in=<token> (origin: the one the code was asked from when trusted, else WEB_ORIGIN; path: / for the sign-in page, /signup with the plan and interval for a code from the sign-up page, only the known values), so after Continue the flow goes on where it was: the app, or the sign-up page's details step with the terms. The link works in any browser or device (2026-11-17: mail apps often open links in another browser or their own in-app one); no cookie ties it to the browser that asked. The app removes the token from the address at once and asks POST /v1/sign-in-link/check {token}: ready with the address, else spent (unknown, expired, used, or its code was used, replaced, expired or out of tries: one answer). Nothing signs in until Continue, POST /v1/sign-in-link/use {token}, which deletes the row (one request wins) and runs Better Auth's /sign-in/email-otp with the code, so every rule of a typed code applies (tries, lockouts, the sign-up gate, invitations, the admin passkey check after sign-in) and the session cookie comes back to the browser that clicked; the browser that asked for the code is never signed in or approved by it, and its code is used up. Refusals keep Better Auth's code (e.g. 429 TOO_MANY_REQUESTS, 403 SIGNUP_CLOSED). Both routes are public, refuse another Origin (403), refuse a body over 1 KB (413), and allow 30 requests a minute per address. The page shows the address before Continue, so a link someone forwards from their own email cannot slip another account in unnoticed. The link row adds no new way to read the code: Better Auth's own row holds an unsalted SHA-256 of it.
Forgot password. Where password sign-in is on and email is delivered, the password step of the sign-in page offers "Forgot password?" (apps/api/src/password-reset.ts, Better Auth's /email-otp/request-password-reset and /email-otp/reset-password): a 6-digit code by email (same lifetime, tries and limits as a sign-in code, counted together with them), then the code with a new password (the sign-up rules), and the browser signs in with it. Every address gets the same answer; only an existing, enabled account gets a code. At the reset step every refused code (wrong, expired, out of tries, no account, disabled account) gets the same 400 INVALID_OTP and counts as a wrong code; the new password is checked before the code, so a typo in it costs no try. The reset proves the mailbox, as a code sign-in does, and gets the same rules: an address nobody had proven loses whatever got in before except the new password (account-linking.ts), every session of the account ends (once more after the reset, for a sign-in that was under way) and so do its agent setup keys, the account is emailed and the audit log records password_changed (method email_code). Passkeys stay; the new sign-in is a password sign-in, so changing passkeys and Server admin still need a passkey sign-in (H1). Without email delivery the page says to ask an administrator; with password sign-in off both endpoints are off.
Changing the email address (Account settings › Profile › Change; apps/api/src/email-change.ts on Better Auth's /email-otp/request-email-change and /email-otp/change-email), only where email codes are on: a 6-digit code goes to the new address, and typing it in moves the account there. It needs a sign-in in the last 10 minutes and, once the account has a passkey, a passkey sign-in in the last 12 hours; never while impersonating. A confirmed current address must confirm the change with a code sent to it too, unless the session is a passkey sign-in of the last 12 hours, so a stolen password alone cannot move the account. The code limits of sign-in codes apply to the new address, plus limits per account. An address that already has an account, or is listed in INSTANCE_ADMIN_EMAILS, gets no code: the asker sees the usual answer and that mailbox gets a notice; at the change step every refused code gets the same INVALID_OTP, so nobody learns whether an address is taken. After the change the account's other sessions end (this one stays), the old address is told (no undo link) and the audit log keeps both addresses (email_changed). Sign-in providers, the password and passkeys stay linked; providers keep signing in by their account id. No unproven-access cleanup: the account's own fresh session proves the new address. (#662)
Who is asking. Rate limits key on the client address, which the API resolves itself (apps/api/src/client-ip.ts): the connection's address, or, when the connection comes from a proxy listed in TRUSTED_PROXIES, the last X-Forwarded-For hop before the trusted proxies. It hands that to Better Auth in its own header, replacing any value a client sent; a client cannot pick its own bucket. Behind another reverse proxy (host Caddy → compose Caddy → API), the compose Caddy keeps the forwarded address only from the ranges in LINEDESK_TRUSTED_PROXY_RANGES (docker/Caddyfile, trusted_proxies); empty by default, so then every client shares the outer proxy's address. Per address, a before-hook allows 5 codes in 10 minutes and 10 sign-in tries an hour across codes; a refused request creates no code and leaves the current one and its tries alone. The plugin's plain verification check (/email-otp/check-verification-otp) and its older /forget-password/email-otp are disabled (disabledPaths), and so is Better Auth's email-link confirmation (/send-verification-email, /verify-email); send-verification-otp only sends sign-in codes (and confirmation codes for a session's own address), password reset codes come only from /email-otp/request-password-reset.
Workspace limit. There is none: WORKSPACE_LIMIT is retired until self-serve workspace creation comes with billing (decided 2026-11-15), since only server admins create workspaces. A server that still sets it gets one warning at start that it is ignored (workspaceLimitRemovedWarning in apps/api/src/workspace-creation.ts, called by apps/api/src/server.ts), and the app and the setup agent never answer "You can create up to N workspaces." One setup link creates at most 10 workspaces (SETUP_LINK_WORKSPACE_CAP in apps/api/src/workspace-creation.ts): workspace.create counts the link's workspace.create commands that were not refused (commands.setup_key_id), under a lock on the link's row in the same transaction, so several API processes cannot pass it either; deleted workspaces still count, and a new link may create 10 again. So a leaked link cannot fill the install.
No open sign-up. Nobody creates an account on their own (decided 2026-11-15; apps/api/src/signup-gate.ts). Accounts come only from the first-run setup (the setup code, or INSTANCE_ADMIN_EMAILS on an empty install), a workspace invitation, or a server admin (user.invite, workspace.create, user:create). Password sign-up is off in Better Auth (disableSignUp, refused before any lookup, so it tells nobody which addresses have an account). Better Auth's user.create hook, which a first code sign-in and a first provider sign-in go through, refuses everyone else with SIGNUP_CLOSED and "No account for this email. Ask your workspace admin for an invitation." An address with a pending, unexpired invitation to a workspace that is not disabled gets an account once the address is proven (a code or a sign-in provider; a password sign-up never makes an account), and that account joins every workspace it is invited to in the same step (joinInvitedWorkspaces, apps/api/src/memberships.ts; owner only while the workspace has none), so there is no account without a workspace unless someone kept it. A passkey is added to an existing account only. No code is sent to an address that cannot sign in, and the answer is the same (no account enumeration); the code page says "No code? No account for this email. Ask your workspace admin for an invitation." The sign-in page links to the sign-up page only while self-serve sign-up is open (selfServeSignup in GET /v1/auth-methods, selfServeState().open, Linedesk Cloud below): its footer then says "No account? Start your free trial", and "No account for this email" gets "Or start your free trial" below it; otherwise the footer says to ask for an invitation. AUTH_SIGNUP_ENABLED is no longer read; a server that still sets it gets a warning at start. Open sign-up for Linedesk Cloud is described under Linedesk Cloud below. Existing users sign in as before. People are added by an instance admin with user.invite (Add user in Server admin › Users): email, name, a workspace and a role there (owner, admin or member; member by default), and Server admin. The workspace may be left out only for a new instance admin, who can run the server without one. A new address gets an account, created unverified, and an invitation from the admin to the workspace, in one transaction; its one email ("You were added to on ") links to the invitation, so they join once a code or sign-in provider has proven the address, like every invitation: an unconfirmed account never holds a membership. That invitation is marked join_on_sign_in (also for the owner workspace.create adds this way): at the first sign-in that proves the exact invited address, the account joins without a Join click (a session.create hook, joinOnSignIn in memberships.ts; once, before it expires, logged as invitation_accepted with method admin_created); every other invitation to an existing account keeps the Join step. An existing account with a confirmed address joins at once with the role and gets a short notice (" added you to as "); one whose address is unconfirmed gets the invitation instead. Server admin's Add to workspace (membership.add) does the same: a confirmed account joins, an unconfirmed one gets an invitation from the admin, a disabled account or workspace is refused; membership.setRole to owner or admin is refused for an unconfirmed address. Every such add or invitation emails the workspace's owners (" added to as ", except the admin and the person themselves), since it changes who can see the workspace without them. These emails are sent in the handler before the transaction commits (there is no after-commit hook, as with team.invite); a notice that fails is logged and does not stop the action. A new instance admin without a workspace is filed in the audit log under no workspace. An existing account is never made an instance admin here (instanceAdmin.grant), a disabled account or workspace is refused. Without a workspace, a new admin gets an email saying how to sign in (their address and a code from the sign-in page; no code in it, since codes expire). The server operator's pnpm --filter @linedesk/api user:create --email … --name … --admin runs the same action and makes server admins only (without --admin it stops); it cannot add to a workspace, since an invitation names the person who sent it. A business with its owner is provisioned from the server with workspace-create.ts --name … --owner <email> [--owner-name …] [--as <server admin email>] [--number +1…] (decided 2026-11-15): it runs workspace.create as that server admin, so the audit entry, rights and owner rules are those of Server admin › Workspaces › New workspace (a confirmed account becomes the owner at once, anyone else gets the owner invitation from that admin, which needs email delivery), then marks onboarding done and attaches the number as the same admin; a disabled workspace stops it. --as may be left out only while the install has exactly one enabled server admin; with none or several the command stops, so it never invites in the name of an admin nobody chose. Run again, it finds the workspace with that name whose owner is, or is invited as, that address. Without email delivery the action is refused (except adding a confirmed account); if the email cannot be sent, nothing is created. Workspace owners and admins invite people into their own workspace (team.invite); that is the usual way in. A provider sign-in refused by the gate goes back to the sign-in page with ?error=SIGNUP_CLOSED (the hook's error code), not to a bare 403.
Linedesk Cloud: open sign-up with billing (decided 2026-11-15; sign-up built in billing PR 7, Checkout in PR 8; it changes the closed sign-up rule below for Linedesk Cloud only). Open sign-up is possible only when the billing provider in effect is Stripe (keys, billing.enabled and intact ledger guards) and the instance setting signup.selfServe is on (off by default, audited); both are checked in mayCreateUser. Every self-hosted install and every dev install stays closed as described above. Then mayCreateUser also lets a proven address (email code or sign-in provider; never a password sign-up) make an account, and account.signUp creates a bill (billing_accounts) and one workspace with that user as owner in pending_payment: no number, no browser test call and no agent setup link until Checkout with a card is done. "Only server admins create workspaces" becomes "server admins, or the owner of a bill, inside billing". Abuse controls before Checkout: the email code with per-address limits (3 an hour, 5 a day) and a global hourly cap, a disposable-domain blocklist checked before a code is sent, per-IP limits (3 an hour, 10 a day; IPv6 per /64), Turnstile on by default, one pending_payment workspace per account, accounts without a finished Checkout deleted after 7 days, and trial limits (1 workspace on Cloud, 2 for partners, 1 number per workspace, 2 calls at once). How it is built (PR 7): the sign-up page (/signup?plan=cloud&interval=year|month, apps/web/src/Signup.tsx) asks for the address, Turnstile and a code (POST /v1/signup/code, checks in admitSignupCode, apps/api/src/self-serve.ts), signs in with the code, then asks name, business name and country (POST /v1/signup → account.signUp, apps/api/src/signup-handlers.ts). The gate accepts an address only after such a code request in the last 15 minutes, so a provider sign-in or the plain sign-in page still cannot make an account. How Checkout is built (PR 8): the waiting screen runs billing.startCheckout (goToCheckout, apps/web/src/checkout.ts) and goes to Stripe; Stripe returns to /billing/return (apps/web/src/CheckoutReturn.tsx), which runs billing.confirmCheckout. confirmSession (apps/api/src/billing-checkout.ts) is the only code that takes a bill out of pending_payment, from the return page or from checkout.session.completed, always with the one-trial-per-card and no-prepaid checks; numbers on a billed workspace go through billingNumberRefusal.
Email confirmation before sensitive actions. An unconfirmed member (and an API key whose creator is unconfirmed) cannot create API keys, create or update webhooks, invite or re-invite members, change the carrier, set up or change a phone number (forwarding), connect a calendar or turn on the assistant's warm transfer to a number. The registry enforces this centrally with EMAIL_NOT_VERIFIED. Password accounts are prompted in the app to confirm a six-digit code. Sending and redeeming that confirmation code requires a session of the same unconfirmed address; wrong confirmation codes count with wrong sign-in codes (per address and IP bucket, sign-in-limits.ts); confirmation in that session preserves passwords, keys, webhooks and invitations, and keeps the session (no new one is made). Email-code sign-in without that session cleans up unproven access, as provider linking does. Not on an install without email delivery (no code could arrive). A password or passkey sign-in whose password or passkeys such a cleanup removed after Better Auth checked them gets no session (a session.create hook checks they are still there), so no sign-in under way during the cleanup keeps a way in. While an admin is signed in as the user, the confirmation code can be neither asked for nor redeemed (Impersonation).
Workspace rights (decided 2026-11-15). Who may run an action follows from its permission (packages/actions/src/rights.ts, rightOf; rolePermissions in define.ts), checked in runAction before the input is read (403 missing permission <p>); packages/actions/src/rights.test.ts lists every action of the registry by who may run it, and apps/api/test/workspace-rights.test.ts runs every workspace action as owner, admin, member, someone of another workspace and someone without a workspace.
- Owner: everything an admin can, plus deleting the workspace (
workspace.deleteOwn,workspace.deletePreview), handing it over (team.transferOwnership) and giving an AI agent a setup link for it (agentSetup.createWorkspaceKey,agentSetup.revokeWorkspace; docs/api.md, "Workspace owners' setup links"): permissionworkspace:own, held by the owner role only, never by an API key. Exactly one owner per workspace: a unique index (member_one_owner_uidx, migration 0091 kept the earliest owner of a workspace that had several and made the others admins),team.setRolegives admin or member only and never changes the owner, nobody removes the owner, the owner cannot leave (hand over first), an owner invitation to a workspace that has an owner joins as admin, and Server admin's Add user / Add to workspace refuse a second owner. Handing over (the owner in Team, or a server admin making someone owner withmembership.setRole) makes the old owner an admin in the same transaction. What the workspace pays (billing) is not the owner's alone since 2026-11-17: permissionbilling:manageis held by owners and admins, and by the bill's owner in a workspace on their bill whatever their role (decision of 2026-11-18; a session only,ownsBillOfinapps/api/src/context.ts), and each handler lets through only who manages the bill (its owner, or an owner or admin of the only workspace it pays for;managesBill); never by an API key or a setup link, and refused while an instance admin is signed in as someone else (refuseBillingActor,apps/api/src/usage-levels.ts); audited (kind team). - Admin: every workspace setting (assistant, hours and closed days, phone numbers, forwarding, calendars, knowledge, recordings, team notification defaults, evaluations, onboarding), the team except the owner (invite, roles, remove, a teammate's profile and notifications), API keys, webhooks and the call export:
settings:write,team:write,call:export. - Member: daily work: inbox and calls, contacts, reminders, appointments, their own profile and notifications; no workspace settings (
call:*,contact:write,calendar:*,team:read). Settings pages show members the values read-only with "Only admins can change this." (apps/web/src/settings/readOnly.ts). Members get no setup link (the setup MCP's keys are server admins'). - Server admin (
instance:admin, a property of the user, granted bycontext.tsonly 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'sworkspace_createand Server admin › Workspaces › New workspace, all throughworkspace.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" sendsPOST /v1/workspacesand opens the new workspace; Owner by email runsworkspace.createwith 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'sinstance: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.leavewithdeleteAccount: 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 throughINSTANCE_ADMIN_EMAILS: oneisInstanceAdminrule), with a box to keep them (keepAccountsfor a workspace delete,keepAccountformembership.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 codeSIGN_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 lineinvitation_withdrawneach; the remove dialog says how many. Whoever loses their account by a removal is emailed (workspace.deletedEmailjob withremoved, by the remover or "The server admin of ").team.leavethat would delete the account needs a sign-in within the last 10 minutes (the session'screatedAt,leaveNeedsFreshSignIninapps/api/src/owner-step-up.ts, checked inrun-action.tsand in the handler; refusal codeSIGN_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 lineinvitation_reassignedeach 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; auditsign_up_undone, and each join asinvitation_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 |
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).
System prompt. Server admin › System prompt shows the assistant's whole system prompt in the order buildInstructions() (apps/agent/src/prompt.ts) builds it, for every workspace of the install. Its fixed parts and their defaults are one table, PROMPT_TEXTS in packages/actions/src/prompt-texts.ts (a stable key, the section, the condition it is used under, the text with {variables}); the agent and the page both read it, so the text is never copied into the UI. Each part's fixed text is editable in place; the variables are chips that cannot change, and an edit must keep the default's variables in the same order (overrideFits). systemPrompt.get / .setPart / .resetPart (instance:admin, in the command log and the audit log) store an edit as a row of prompt_overrides (key, text, the default it was made against, who and when; migration 0116); setting the default text deletes the row. call.start hands the edits to the voice agent, which uses an edit only while it fits and the default for every other part; an edit is the admin's own instruction, not caller data, so it is not fenced (control characters are taken out). When a release changes a part's default, the page says "Default changed since your edit" (the stored default differs); when it changes the variables, the edit no longer fits, the default is used and the page says so. A blocked call gets no edits. The snapshot test apps/agent/src/prompt.snapshot.test.ts keeps the prompt without edits byte for byte.
Sign-in providers and account linking. Google, Apple, Microsoft, GitHub and one OpenID Connect provider, each on when its keys are set (apps/api/src/auth-methods.ts; GET /v1/auth-methods lists them for the sign-in page). The email address is the account: a provider sign-in lands in the account with the same email, however that account was made (email code, password, an invitation or user.invite that never signed in, another provider), and every method attaches to that one account. Condition: the provider proves the address (apps/api/src/account-linking.ts). Google: email_verified. Apple: email_verified too, also for its private relay addresses (@privaterelay.appleid.com, which join no existing account unless that account uses the relay address). Apple has no fixed client secret: the API signs one (ES256 JWT, 150 days) with the Sign in with Apple key and makes a new one after 30 days while it runs (apps/api/src/apple-sign-in.ts); Apple comes back with a cross-site form POST, which the API answers with a 303 to the same callback as a GET, so the browser sends the sign-in's state cookie and Better Auth's origin check never sees appleid.apple.com. Microsoft: a personal account (tenant 9188040d-6c67-4c5b-b112-36a304b66dad: Outlook.com, Hotmail, Live), or a work account whose ID token carries xms_edov (the tenant owns the email's domain; an optional claim the app registration must add) or lists the address in verified_primary_email; a work account's plain email claim is not proof, any tenant can set it. GitHub (apps/api/src/github-sign-in.ts, scopes read:user and user:email): the account's primary address from GET /user/emails, only when GitHub verified it; the public profile address and other addresses are never used. OIDC: email_verified, or, opted in with OIDC_TRUST_EMAIL_DOMAINS (only when the provider sends no such claim), an address on exactly one of the listed domains the provider owns. A sign-in that does not prove its address has no email: Better Auth stops with email_not_found before it looks up or creates a user, and the sign-in page says the provider didn't confirm the address. No provider is trusted by name (trustedProviders is empty) and requireLocalEmailVerified is off, so a proven provider email also joins an account whose own address was never verified; Better Auth then marks it verified, and an account.create hook removes what got in without proof (dropUnprovenAccessOf: other sign-in accounts, passkeys, sessions, API keys, webhooks, pending invitations, calendar connections) (otherwise someone who signed up with another person's address and a password would keep a way in). A first email-code sign-in that proves an unverified address does the same (dropUnprovenAccessAfterCodeSignIn, a user.update hook on /sign-in/email-otp). What dropUnprovenAccessOf removes: every other sign-in account (password, providers; the provider account being linked stays), passkeys, sessions, push subscriptions, API keys and AI agent setup links the account created (revoked), webhook endpoints and calendar connections it created and invitations it sent that are still pending, and in the workspaces it owns and created (its member row is the workspace's first; not one an instance admin or owner added it to) the assistants' warm transfer (switch and on-call number) and numbers set to forward every call go back to the defaults, recorded in the audit log per workspace as call_routing_reset. Workspaces it created stay, with their members. An unconfirmed address cannot add a passkey at all (403 EMAIL_NOT_VERIFIED). Better Auth's email link ("Confirm your email", /send-verification-email, /verify-email) is off (disabledPaths, auth.ts): addresses are confirmed only by an email code (typed, or the sign-in email's button, which redeems the same code) or a provider that proves them. Pending workspace invitations stay pending and can be accepted afterwards. A provider sign-in for an address with an account or a pending invitation works; any other is refused with SIGNUP_CLOSED. Provider accounts are keyed on the provider's stable id (Google sub, Microsoft oid, GitHub's numeric id).
Passkeys. Better Auth's passkey plugin (@better-auth/passkey, apps/api/src/passkeys.ts, table passkey), on unless AUTH_PASSKEY_ENABLED=false; the sign-in page offers "Continue with Passkey" when the server has it on and the browser supports WebAuthn (https or localhost). The relying party is the address people open: its host name is the rpID and its origin the only accepted origin, from PUBLIC_URL, else WEB_ORIGIN (with docker compose both are PUBLIC_URL). Changing that address makes existing passkeys unusable (people sign in another way and add a new one). A passkey signs in an existing account only: it is added under Account, Sign-in & security, by a signed-in member whose session is less than a day old (the plugin's fresh-session check), to that member's own account; there is no passkey-first sign-up (registration.requireSession, no resolveUser), so closed sign-up cannot be bypassed with one. Removing a passkey also needs a session less than a day old (a before-hook; the plugin itself only asks for a session) and works only on the member's own passkeys. Once an account has a passkey, or belongs to an instance admin, passkeys are its second factor (guardPasskeyChanges, a before-hook): adding, renaming or removing one then needs a session started by a passkey sign-in in the last 12 hours (passkeyVerifiedAt, 12 hours), else 403 PASSKEY_CONFIRMATION_REQUIRED, so someone with only the mailbox, the password or the Google account can neither add their own passkey nor remove the real ones. An instance admin's first passkey needs a one-time enrolment code (apps/api/src/passkey-enrolment.ts, else 403 PASSKEY_ENROLMENT_REQUIRED): instanceAdmin.grant, user.invite with admin, user.resetPasskeys and user.issuePasskeyEnrolment return it once to the admin who ran them (shown in a dialog, secretResult, never in the command log), and pnpm --filter @linedesk/api user:passkeys --enrol --email … (in Docker docker compose exec api node apps/api/src/user-passkeys.ts --enrol --email …) prints it for the first admin of an install, one set by INSTANCE_ADMIN_EMAILS or any admin without a passkey; the API's log at start has one too (above). Only a code, nothing ends: user.issuePasskeyEnrolment (Server admin › Users, "Give passkey code…"; the CLI's --enrol) is for an instance admin who has no passkey yet: it issues the code, emails them and alerts the admins, and removes nothing, so their sessions and AI agent setup links keep working (an agent that asks the admin to add a passkey keeps its link). The code is written in one statement only while no passkey row exists (issueFirstPasskeyEnrolment, also used by instanceAdmin.grant), so a passkey added at the same moment refuses it. It is refused when they have a passkey (that is the reset below), for a non-admin (no code needed), for a disabled account and on one's own account; it needs Server admin (the passkey check) like the reset. The email to them says who issued it and that nothing ended. Every handler that returns an enrolment code refuses an AI agent's setup key, an API key and an impersonation, also when passkey-confirmed. Only its SHA-256 is stored (user.passkey_enrolment_hash), it lasts 24 hours and is used up by the first passkey; the browser sends it as x-passkey-enrolment with verify-registration (asking for options only needs one to be pending), and Account shows an Enrolment code field while /v1/me says passkeyEnrolment. Non-admins without a passkey keep Better Auth's fresh-session rule. The account is emailed whenever a passkey is added or removed, and both are in the audit log. Recovery that needs none of the user's passkeys (a lost device, or a passkey someone else added with the first factor): an instance admin runs Reset passkeys on the user's page (user.resetPasskeys, audited; needs instance:admin, so never while impersonating): every passkey of the user is removed and all their sessions and AI agent setup links end in the same transaction, also when there was no passkey to remove (never on the admin's own account), they are emailed (an instance admin always, also with no passkey to remove), and an instance admin gets a new enrolment code. Granting instance admin to someone who already has passkeys lists them with their dates in the dialog, since they become the admin's second factor, and offers "Reset passkeys and make admin" instead. The last admin, or one without a working passkey, does the same on the server: pnpm --filter @linedesk/api user:passkeys --remove --email … (runs the same action as the operator; it says before and after that it signs them out and ends their setup links, with the counts). ADMIN_SECOND_FACTOR=off is not needed for any of this. A disabled user's passkey creates no session (the session.create hook). While impersonating, passkeys cannot be added, renamed, removed or listed (impersonation-guard.ts).
Caller languages. Settings › Assistant › Advanced › Languages sets assistants.languages ({ main, mode, allowed }, packages/actions/src/languages.ts): a main language (main, missing: English) and the languages besides it, english none (the name is from before the main language could be picked), allowed the picked ones, or any every supported one. The supported languages are one table, LANGUAGE_SUPPORT (LANGUAGES is code → English name from it): English, Spanish, French, German, Italian, Portuguese, Dutch, Russian, Hindi, Japanese (Deepgram Flux multilingual's 10), and since 2026-11-19 Chinese (Mandarin, Simplified), Korean, Polish, Turkish, Vietnamese, Indonesian, Swedish, Arabic, Ukrainian, Romanian, Czech, Greek, Danish, Finnish, Norwegian and Hungarian (Nova-3 multi, ElevenLabs Flash v2.5 and Cartesia Sonic 3 all confirm them; per row: Flux yes/no, ElevenLabs, Cartesia, provider codes where they differ, mapped by providerLanguageCode). An assistant is offered, and may save, only the languages a voice provider set up speaks with its model (spokenLanguages/voiceSpeaks: Eleven Multilingual v2 lacks Hungarian, Norwegian, Vietnamese; Cartesia Sonic 2 speaks 15; no voice provider, realtime only: Flux's 10): voice.options returns them as languages, Settings › Assistant › Languages lists only those (plus what the assistant already has) and assistant.update / assistant.restoreVersion refuse a new one the install can't speak (checkAssistantLanguages). Languages whose test calls failed are hidden (HIDDEN_LANGUAGES; none since 2026-11-19, Chinese and Korean were hidden until their test calls passed): voice.options and the pickers leave them out, any never covers them, assistant.update refuses them as a new choice and a hidden workspace language is no default main language; an assistant that already has one keeps it. The web app sends languages only when they changed. At call time the other languages are cut to what the call's voice providers speak (callLanguagesOf). any with a Deepgram Flux model covers only Flux's 10 (anyModeLanguages; decision of 2026-11-19: existing assistants are not moved off Flux), so a new language is used only when picked as the main language or in the allowed list; voice.options returns what any covers as anyLanguages, the settings page ticks only those under Any and says so in one line. With another speech model any covers every language the voice speaks. The prompt names the call's languages, not the stored setting (withCallLanguages). English only keeps the configured speech model. A Flux model whose call languages are all Flux's keeps Flux: flux-general-multi with a language_hint of the call's languages, same price and turn detection. Any language outside Flux's 10 (or a Nova model) takes Deepgram Nova-3 multi (code-switching across all of them), with the call's languages as hints (only the main one for any off Flux) and Deepgram's recommended 100 ms endpointing; Nova does not detect turns, so the session uses its own end-of-speech detection there (deepgramChoice, sttDetectsTurns in apps/agent/src/pipeline.ts). ElevenLabs Scribe and OpenAI transcription are unchanged: they detect the language themselves and cover all of the table. AssemblyAI (the recommended speech recognition) hears 32 languages; of the table it lacks Polish, Ukrainian, Czech, Greek, Hungarian and Indonesian (the assemblyai column, sttHears). With Deepgram set up too, a call whose languages include one of these hears with Deepgram Nova-3 instead (the agent config's stt_fallback, sttForCall in apps/agent/src/pipeline.ts), and every language stays offered. Without Deepgram they are not offered (voice.options leaves them out of languages; the workspace is not told why, the server admin reads it in the AssemblyAI provider's help), assistant.update refuses them as a new pick, and a call leaves out one an assistant already has (callLanguagesOf). The voice starts in the main language (createTts) and follows each final transcript's detected language when it is allowed, else goes back to the main one (followCallerLanguage, apps/agent/src/caller-language.ts); the prompt (languageInstructions) and the collection steps (collectLanguageRule) say the same. The fixed lines are translated in code for every supported language (packages/actions/src/spoken-lines.ts): the greeting and busy lines in the main language, the lines during the call (still there?, goodbye, call limit, the ready replies after take_message and flag_urgent) in the language spoken at that moment, the AI note and consent question (greetingWithDisclosure) in the main language. Owner-written texts stay as written; one that is still the English default (the greeting the app wrote, the returning-caller line, the closing line, the recording notice) is said as the main language's default (inMainLanguage in apps/agent/src/call-session.ts), and the settings page swaps such defaults in the draft when the main language changes (withMainLanguage). The team's language stays English: the summary is written in English and starts with "Call in ." when the call was not in English, messages and notes saved with tools are in English, the transcript keeps the language spoken. Needs a multilingual voice model (ElevenLabs Flash v2.5, the default, or Cartesia Sonic).
Assistant voices. Settings › Assistant › Voice picks assistants.voice ({ provider, voice_id }; empty id: the provider's default voice, providerDefaultVoices). The page lists the suggested voices (the curated ones and the workspace's clones) as compact rows with a play button, and under More voices every voice of every text-to-speech provider that has a key (voice.catalog, apps/api/src/voice-catalog.ts: each provider's list read with the install's key on the server, kept 5 minutes per provider and key, with search and filters for provider, language, gender and accent). Languages: every voice speaks every language an assistant supports (the agent tells the voice provider the language), a language it is not native in with its own accent, so the picker says how each voice speaks the assistant's main language. Each catalog voice carries languages (VoiceLanguage[]: { code, accent, native }): ElevenLabs' verified_languages, each native (fallback: the language label, English for premade voices); Cartesia's accents[] (API version 2026-08-14 for the list; locale, the accent id in words, is_native; fallback: the deprecated language). language and accent stay as the first native language for older clients. The picker (apps/web/src/settings/voiceModel.ts) ranks voices native in the main language first, then voices native in another language the assistant speaks, then the rest (languageFit), and labels each row "Native German", "German with an American accent" or "German, non-native" (languageLabel). For a main language other than English, Suggested lists the ranked voices (at most six) when some voice is native in it, else the default and curated voices with their accent line and one muted note with a "?": on a free ElevenLabs plan "Native voices need a paid ElevenLabs plan." (CatalogProvider.freePlan), else " has no native voice.". More voices opens filtered to the assistant's languages (main and the ones it may switch to), with "Show all languages" one click away. The catalog leaves out other workspaces' clones (live or released) and every clone the account itself made (ElevenLabs instant and professional clones) that Linedesk did not make for this workspace (no consent record); the provider's own voices, designed voices and voices added from ElevenLabs' Voice Library stay (a library copy: is_owner false, sharing.status copied with an original_voice_id; its consent is the library's sharing terms; a copy whose owner stopped sharing, copied_disabled, is left out). Provider-hosted samples are fetched only from the provider's sample host (SAMPLE_HOSTS, ElevenLabs: storage.googleapis.com), at most 2 MB, checked while streaming. A voice of another provider than the one in effect works too: the agent gets every voice provider with a key (tts_providers in GET /v1/agent/provider-config) and uses the assistant's provider when it has one (ttsFor in apps/agent/src/pipeline.ts), else the default voice. An assistant may only get the default, a curated voice, a voice of the catalog (curatedVoices in packages/actions/src/voices.ts: six American English ElevenLabs default voices; none for Cartesia yet) or a voice its own workspace cloned: assistant.update checks it on the server (checkAssistantVoice). voice.options lists them and whether the workspace can clone. Previews: GET /v1/voices/preview/<voiceId>[?language=<code>] (apps/api/src/voices.ts) says a fixed sentence in that voice, only for those voices, in the assistant's main language (PREVIEW_TEXTS, one per supported language; the language is passed to the provider: ElevenLabs language_code with Flash or Turbo v2.5, Cartesia language). The curated voices' English samples ship with the app (apps/api/assets/voice-previews/<provider>/<voiceId>.mp3, made with PREVIEW_TEXT, the English one; make them again when it changes), so in English they play without a provider key and never call the provider; in another language they are synthesized like any other; a catalog voice plays the sample its provider hosts (ElevenLabs preview_url, fetched by the API, free, no hourly limit; ?provider= names a provider other than the one in effect); any other sample is synthesized once per provider, model, voice, language and sentence and kept on disk (VOICE_PREVIEW_DIR, default the system temp dir; the newest 300 kept), browser-cached for a week; at most 20 new samples per workspace an hour (per API process). The Default voice row plays the voice the install's default stands for (installDefaultVoice: the provider's voice id setting, else the voice agent plugin's own default, providerDefaultVoices); voice.options returns it as defaultVoice and the preview endpoint allows it. The picker fetches a sample before playing it, so a refusal shows its reason (no provider: "Add a voice provider key in Server admin › Providers to hear samples.") instead of a generic error. Cloning is off until an instance admin turns it on (Server admin › Settings › Calls, voiceCloning.set, instance_settings.voice_cloning), and only for providers in cloningProviders (ElevenLabs instant voice cloning). voice.clone (settings:write) takes a recording (≤ 10 MB; the request body is capped before it is read, every other action at 4 MB), checks its first bytes against the claimed type, and calls the provider before the transaction (a Preparer, handler-context.ts; the clone is deleted again if the command does not commit). It stores a consent record in voice_clones (who confirmed, when, the exact statement CLONE_CONSENT_TEXT) and makes the voice the assistant's; the recording is not stored (sensitive, not in the command log either). A clone no assistant of its workspace uses any more (voice changed, assistant deleted, workspace deleted) is deleted at the provider by the voice.delete job and marked deleted_at here; the row stays as the consent record and the voice can no longer be picked. Vendor HTTP is in apps/api/src/voice-provider.ts. Realtime voices. While the realtime model answers an assistant's calls (Ultra), the same page shows the realtime model's voices instead (RealtimeVoiceSettings), with the same rows, samples and More voices: Default voice (the server's, voice.options realtimeDefaultVoice), then the ones OpenAI recommends (marin, cedar). The list is fixed in realtimeVoices (packages/actions/src/voices.ts): the ten voices of OpenAI's realtime conversations guide (alloy, ash, ballad, coral, echo, sage, shimmer, verse, marin, cedar), named by their id, native English (OpenAI: "optimized for English"), no gender or accent (OpenAI gives none). The pick is stored apart from the three stages' voice in assistants.realtime_voice (migration 0103, '' by default: the server's default voice, so nothing changes for existing assistants), set by assistant.update (realtime_voice, validated against the list), kept in versions and copies. The agent opens the realtime session with it (withAssistantRealtimeVoice in apps/agent/src/config.ts; the model's voice, sent in session.update) and says the fixed lines in it; the Realtime API fixes the voice once the model has produced audio in a session, so it is never changed during a call. Samples: GET /v1/voices/preview/<voice>?provider=openai_realtime makes one with OpenAI's speech model (gpt-4o-mini-tts, the model of the fixed lines, which speaks the same voice names) and the realtime model's key, in the assistant's main language, cached and counted like any synthesized sample; no samples ship with the app.
Support mailboxes:
- Why: the business's support mail shows the common requests, how support answers them and what it needs to know, so the assistant can answer the same requests on the phone. This step only connects mailboxes, read only; reading and analysing the mail comes later. Connecting stores no mail.
- Settings › Integrations › Gmail and › Outlook (cards
gmailandoutlook-mail, category Email, one per provider with its logo; the old#integrations/support-emailaddress goes to Gmail): an owner or admin connects Gmail or Microsoft 365 (mail.connectStart,mail.connectFinish,mail.disconnect; permissionsettings:write, a confirmed email, not while impersonating). A workspace may connect several mailboxes; the same account connected again updates its one row. - OAuth apps: Gmail has an OAuth app of its own (provider
google_mail, Server admin › Providers › Gmail API: client ID and secret,GOOGLE_MAIL_CLIENT_ID/GOOGLE_MAIL_CLIENT_SECRET), never the sign-in and calendar app:gmail.readonlyis a restricted scope (Google verification plus a yearly CASA security assessment for a public app), so the sign-in app's consent screen and verification stay as they are. Linedesk Cloud publishes the Gmail app unverified until it passes Google's verification and CASA: any Google account can connect after Google's "unverified app" warning, at most 100 accounts over the app's life (testing mode would need each account on a test list and ends a grant after 7 days). Microsoft uses the sign-in app (MICROSOFT_*) with the delegated permissionMail.Readadded (no assessment). - Scopes: Google
openid userinfo.email gmail.readonly(spelled out as in the Google Cloud Data Access list: Google's verification wants a string-for-string match); Microsoftopenid email offline_access User.Read Mail.Read. Nothing that sends, changes or deletes mail. A grant without the read scope or without a refresh token is refused and revoked. - Flow as the calendar's: state (32 random bytes,
mail_oauth_states) bound to member, provider and workspace, single use, 10 minutes; PKCE S256; the provider returns toGET /v1/mail/callback/<provider>, which runsmail.connectFinish(code and state redacted in the command log) and redirects to the provider's card,#integrations/gmail?mail=connectedor#integrations/outlook-mail?…, or?mail=error&reason=<code>(codesmailConnectErrorsinpackages/actions/src/mail.ts, worded by the web app; never server text). Before storing, one message is listed to prove the access works (for Gmail also that the Gmail API is on in the app's project; when not, the app gets a provider failure in Server admin). - Storage:
mail_connections(provider, account email, status, who connected it; synced, workspace-filtered) andmail_credentials(never synced; access and refresh token AES-256-GCM withSECRETS_KEYunder slotsmail.<connection id>.access|refresh; re-encrypted by the key rotation). Tokens with less than a minute left are refreshed on use (Microsoft's new refresh token replaces the old); a refused refresh marks the mailboxneeds_reconnect.mail.disconnectdeletes the mailbox and its tokens, then revokes the grant at Google unless another workspace holds the same account (Google withdraws the account's whole grant; Microsoft has no per-app revoke). A member who leaves takes the mailboxes they connected with them (mail_droppedin the audit log). - Adapters:
packages/mail(Gmail API v1, Microsoft Graph; plain fetch, list and read only, spam, trash and drafts left out, bodies as plain text).mailboxForinapps/api/src/mail-connections.tsgives the adapter of a workspace's mailbox to the analysis. - Analysis (
apps/api/src/mail-analysis.ts):mail.analyze { months: 6 | 12 }(settings:write, a confirmed email) queues the pg-boss jobmail.analyze(no retry, 30 minutes) and returns the analysis; one at a time per workspace (a queued or running one younger than an hour is returned instead; an older one is marked failed), at mostMAIL_ANALYSES_PER_DAY(3) a day. The job reads everyconnectedmailbox of the workspace: up to 3,000 messages listed per mailbox, threads with two messages or more, up to 300 support conversations over all mailboxes (the first message from outside the mailbox, not from an automated sender such as no-reply, and answered by the mailbox), up to 6 messages each, oldest first, quoted replies cut. Before anything reaches the language model,redactPersonal(packages/mail/src/redact.ts) replaces email addresses, phone numbers, links, street addresses, long numbers and the names of the people in the conversation (from the headers, greetings and sign-offs) with placeholders. The language model in effect (Server admin › Providers, its cheap default model, OpenRouter with zero data retention as everywhere) gets the conversations in batches of 40,000 characters (BATCH_SYSTEM; the mail fenced as data) and returns kinds of requests; with several batches one more request merges them (MERGE_SYSTEM). Stored inmail_analyses(not synced; deleted with the workspace): status, the months, conversations read and analyzed, the model, and at most 10 topics, most common first, each with a title, the number of conversations, a typical request, how support answers it and the facts support needs from the customer. Never a message. Failures are codes (mailAnalysisErrors:no_model,no_mailbox,account_refused,unavailable,no_conversations,failed).mail.getAnalysisreturns the latest. Owners review the topics in the next step, which turns accepted ones into FAQs and collection steps. - Demo mailbox:
createDemoMail(packages/mail/src/demo.ts), made-up support mail of Brightwater Plumbing over ten months, for the tests andpnpm --filter @linedesk/api mail:demo(runs the analysis on it with the install's model or--provider <name>with its key from the environment, prints the topics, stores nothing).
13. Integrations: API keys
A workspace's own integrations (REST, later MCP and webhooks) authenticate with a workspace API key (apps/api/src/api-keys.ts).
Owners and admins create (
apiKey.create { name, role }), list (apiKey.list) and revoke (apiKey.revoke) keys under Integrations › API keys. A key isld_+ 32 random bytes (base64url), shown once in the result ofapiKey.create; the command log stores that result without it (secretResult). Only its SHA-256 hash and its first 11 characters (to tell keys apart) are stored, inapi_keys, which is never synced.Authorization: Bearer ld_…on/v1/actions/<name>and every other/v1read. The actor isapikey:<id>in the key's workspace with the key's role (memberoradmin, never owner), withoutteam:write; keys never manage keys. The agent'sx-workspace-idheader does not apply. A revoked key, or one of a deleted or disabled workspace, is refused (401). A key is checked against its creator on every request: once they are removed from the workspace, disabled by an instance admin, or hold a lower role than the key (an admin key of someone demoted to member), the key is refused; it works again if that is undone, until it is revoked.last_used_atis written at most once a minute.300 requests a minute per key (in-memory sliding window per API process), then 429 with
retry-after: 60.Refused
ld_keys count per client address (client-ip.ts): from the 20th in 10 minutes, refused keys from that address get 429 withretry-after: 600. From then on only a key that worked in the last 24 hours (kept in memory by its hash) is looked up from that address, so a working integration behind a shared address is not locked out by another host there, and random keys from it cost no database query. A key that never worked before cannot start from a throttled address until it ages out.Personal API keys (
ldp_,personal_keys,apps/api/src/personal-keys.ts) are a person's, not a workspace's: the actor is worked out on every request from the maker's account as it is (personActor), in the workspacex-workspace-idnames, with the same limits as workspace keys. They run every action their maker may, minusPERSONAL_KEY_REFUSED, and only the GET routes inKEY_READ_ROUTES;account:own(managing keys) is in no role and only a person's own session has it. Details: docs/api.md, Personal API keys.
14. Call evaluations
After a phone call is finished (call.finish), a job (call.evaluate in pg-boss, apps/api/src/evaluations.ts) asks the language model in effect (Server admin › Providers) how the assistant handled it: one short request (max_tokens 300, the provider's cheap default model unless one is set) with the business instructions, the fixed call rules (CALL_RULES), transcript and summary. The answer is a score from 1 to 5 and at most three issues, stored in call_evaluations (not synced; one row per call, replaced on a new evaluation). Test calls are evaluated only when asked (call.evaluate from the call view). The model also names up to three questions about the business the caller asked that the assistant could not answer (call_evaluations.unanswered; new ones also become open knowledge_questions). The assistant's own faults are ours to fix, not the business's (decision of 2026-11-18): staff read the flagged calls (scored 3 or lower; 5 Handled well, 4 Mostly fine, 3 Missed something, 1-2 Went wrong) with their issues in Server admin › Call quality (GET /v1/admin/call-reviews, instance:admin; every workspace, newest first, workspace filter, read-only) and in a card under the summary of the call view ("How Maya did on this call"), shown only to server admins who are owner or admin there (call.getEvaluation, settings:write). call.listEvaluations, evaluation.markDone and evaluation.reopen stay in the registry; the web app no longer uses them. Owners and admins see "Open questions" in the Assistant area (#assistant/<id>/review, G R; the number of open question groups is the count on Assistant in the navigation; the inbox holds only caller work): the open questions grouped by questionKey (packages/actions: the same question whatever its case, punctuation, word order, order or reference number, plural endings or filler words; plain words, no language model), each with how often it was asked in the last 30 days and its last call (evaluation.listQuestions), most asked first. Add answer (knowledgeQuestion.answer) adds it to About the business once, Dismiss (knowledgeQuestion.dismiss) hides it; both close every question of the group (alsoIds), and a handled question is never added again. Without a language model nothing is evaluated.
15. Knowledge
What an assistant knows about the business: Settings › Assistant › Business info. Rosie's and fonio's shape (research/competitors-smb.md §2.11), local-first and with no new paid service.
- About the business is the assistant's free-text instructions (
business_profile.instructions; the same at any hour: after-hours behaviour comes from the outside greeting, the call rules and the transfer rules' "only during business hours"), part of the assistant draft and saved withassistant.update. Services, prices and common answers are written in it. Services and prices lists, FAQs and documents were removed (2026-11-12): migration 0066 folded stored lists into the About text, the agent no longer reads them, andknowledge_documents/knowledge_chunkswere dropped by migration 0117 (the original files stay in the recording store). The older structured fields (description, plainservicesnames, service area, address, hours) still stand in for an empty About text. - Write with help (button next to About the business;
knowledge.import, read-only,settings:write, 10 an hour per workspace, refused while impersonating): a three-step wizard asks what the business does (trade, offer, area), optionally its website, and what the assistant should do (take messages, book appointments, answer prices and common questions, screen spam, plus free text). With a website it reads the home page and up to five same-site pages it links to whose path or link text names services, prices, about, contact, FAQ or areas (apps/api/src/site-import.ts), after robots.txt (our groupLinedeskBot, else*; longest rule wins; checked before any page). Fetches go through the webhook guard (apps/api/src/public-fetch.ts: http(s) on 80/443 only, no credentials in the URL, every resolved address public viapublicLookup, redirects followed by hand and checked again, 8 s and 1.5 MB per page;WEBHOOK_ALLOW_PRIVATE_URLSlifts it for development, except for link-local and cloud metadata addresses). One request to the language model in effect (Server admin › Providers; up to 3,000 tokens) gets the owner's words between<owner>tags and the page text (scripts and styles dropped, JSON-LD kept, at most 40,000 characters) between<page>tags, never to be followed as instructions; the answer (an About text with the services, prices and common answers the owner or the pages give, and up to 8 "When a caller …" use cases) is checked and cut to the limits. Nothing is saved: the last step shows a word diff for a different About text (unpicked by default) and the use cases to pick; picked use cases are added to About the business under "Common calls", and everything goes into the draft, saved with Save. - The page (
apps/web/src/settings/Knowledge.tsx,aboutModel.ts) shows the About text in two parts and writes it back as one text: everyIf a caller asks "…": …line is a row under Questions and answers (a click opens the row for editing in place, Add makes a new one; search from six questions on, a Needs a look filter while the check finds something), all other lines stay one text field (What {name} should know). A row the owner did not change keeps its line byte for byte; a changed or new row is written withansweredQuestionLine; rows come after the business text. A health check marks near-duplicate questions, answers over 450 characters and rows in another language than the rest;knowledge.improve(read-only,settings:write) proposes a merge, a shorter answer or a translation as one question and answer, which goes straight into the draft (Cancel throws away unsaved changes). Try a question (a button next to Add;knowledge.try, read-only,settings:write) asks the language model in effect with the assistant's real call prompt (buildInstructions, built with the drafted text, the hours, booking and the instance's prompt texts; no caller, no transfers) and the question as the caller's turn, and points to the row the answer most likely came from. Both share 60 requests an hour per workspace. The topics of the support mail review not yet reviewed come right after the open questions as "Suggested" rows ("From 34 support emails", most emails first): opened in place with the topic's question and answer to adjust, Add to answers accepts it (mail.reviewTopic, the line goes into the text and the draft), Dismiss drops it; the Support email page reviews the same topics. Long lists show the first 4 suggestions and 10 answers, the rest behind Show more; search and the filter chips (No answer yet, Suggested, Needs a look) show every match. - Try a question with a store. For a workspace with a connected Shopify store, Try a question (
knowledge.try) gets the store's part of the call prompt and the two lookups of a call,find_ordersandfind_products, in the same words (packages/actions/src/shopify-call-text.ts, shared with the voice agent). It makes at most three lookups for one question and reads only: the tools that change an order are not offered, and there is no caller number. - On a call the prompt (
packages/actions/src/call-prompt.ts, re-exported byapps/agent/src/prompt.ts) has the About text and a fixed price rule (unless the owner turned it off in the checklist): only prices the business gave, exactly as written; anything else gets no price or estimate, the team calls back. - Questions the assistant could not answer: the call evaluation (§14) also returns up to three general questions the caller asked that the assistant could not answer. They are stored in
knowledge_questions(synced; skipped when already asked on that assistant, byquestionKey; at most 30 open per assistant) and listed, grouped, as the first rows of Business info's questions and answers ("No answer yet", with how often and when, the time linking to the last call) for owners and admins, counted on Business info and on Assistant in the navigation.knowledgeQuestion.answeraddsIf a caller asks "…": …to the About text in the same transaction (assistant row locked; refused when the text would pass its limit);knowledgeQuestion.dismisscloses it.
16. Assistant versions
Save is live: there is no separate publish step. Every save that changes what callers get becomes a version (assistant_versions, not synced; apps/api/src/assistant-versions.ts, shared parts in packages/actions/src/assistant-versions.ts): a whole copy of the assistant's call settings (the columns in VERSIONED_FIELDS: name, greetings, AI disclosure, style, checklist, about, transfer contacts, voice, languages, silence, recording) and its calendars with their notes, numbered per assistant, with who saved it and a short summary of what changed. The actions in VERSIONED_ACTIONS (assistant.update, assistantCalendar.*) run inside withVersion: the settings before the change are kept as a version first (an assistant from before versions gets "Settings as they were"), and the result becomes the next one when it differs (key-sorted JSON, numbers taken under a per-assistant advisory lock). assistant.create stores version 1. A call stores the version it ran with (calls.assistant_version, set by call.start and call.startTest; a change that skipped versioning, e.g. from an older release during an update, becomes a version of its own first); the call view shows "Assistant version N".
Settings › Assistant › History (assistant.versions, assistant.version, read-only, settings:write) lists the versions and compares one with now, line by line per part. assistant.restoreVersion writes the version's settings back with the same checks as assistant.update (voice usable, transfer numbers not Linedesk numbers, a confirmed email to put calls through to a number) and is itself saved as a new version ("Restored version 7"), so a restore is undone by restoring the one before. Calendars are matched by account and calendar id: one no longer connected is left out and named in the result, one added since is switched off. Appointment types, hours and notifications are workspace settings and are not versioned. Restore waits while the form has unsaved edits.
Billing provider (Linedesk Cloud only). packages/billing holds the BillingProvider interface, the none adapter and the stripe adapter; only packages/billing/src/stripe/ imports the Stripe SDK, through a dynamic import, with the API version pinned there (STRIPE_API_VERSION). apps/api/src/billing-settings.ts decides the provider in effect: stripe only when Server admin › Providers › Stripe has both Stripe keys and the instance setting billing.enabled is on (billingEnabled.get/.set, instance admins, audited; off by default, so keys alone bill nobody) and the ledger guards passed their last check (ledgerGuardsOk(), apps/api/src/ledger-guards.ts; the switch then says billing is paused), else none. A live key (sk_live_…, rk_live_…) is refused unless the server allows live keys (BILLING_LIVE_KEYS=1 in the server environment, set on production only, and never with LINEDESK_MODE=dev): when it is stored, by the provider test and by the switch, and it never counts elsewhere. The provider test reads GET /v1/account and shows the mode, country and default currency. The keys decide where money goes, so (moneyCategories in packages/actions/src/admin.ts): provider.setKeys, provider.clearKeys and provider.setActive for billing run only for an instance admin signed in as themselves whose session passed the passkey check, never through an AI agent's setup link (the setup MCP does not list billing), an API key or an impersonation; new Stripe keys are refused while billing is on; removing them turns billing off; turning billing on binds it to the keys' Stripe account and mode (billing.stripeAccount), and keys of another account or mode need rebind. A change of the keys and turning billing on or off email every instance admin. The billing keys are never read from .env (resolveProvider skips the environment for them).
17. Billing (Linedesk Cloud)
Decided 2026-11-15 and 2026-11-16. Built PR by PR; until a part is merged, the code behaves as without billing.
- A provider behind an interface (merged, #850): see "Billing provider" in §16. The provider in effect is
noneunless Stripe has both keys,billing.enabledis on and the ledger guards are intact. - The bill (
billing_accounts) sits above workspaces: 1 to n workspaces on a Cloud bill, a partner bill with its client workspaces. The Stripe customer, the subscription, the trial, the prepaid balance, the auto-recharge settings and the monthly recharge cap belong to the bill.organization.billing_account_idnull means unbilled (self-host, or comped). - Plan fee in advance, usage from a prepaid balance. Seats (and the partner base) are a Stripe subscription. Usage and extra numbers are debits on the bill's balance (
billing_balances, kept equal to the ledger's sum by a trigger). Auto-recharge is on by default: below $5 an off-session Stripe invoice (charge_automatically,automatic_taxwhen Stripe Tax is on) charges $25 by default, and the pre-tax amount is credited when it is paid (billing_recharges, at most one pending per bill). A monthly recharge cap ($50 plus $25 per further workspace) bounds the charges. - Our own ledger (
ledger_entries, append-only by trigger, idempotent per source) rates every call per second at two levels, Standard 5¢ and Premium 10¢ a minute, the same on Cloud and the partner plan; $0 on the customer's own keys. 50 Standard minutes per workspace and period are included; Premium uses them at 2×. Test, simulated and sample calls never count. The ledger guards (apps/api/src/ledger-guards.ts) check the triggers and money constraints at start, nightly and before billing jobs; billing is off while they fail. - The call gate is one local check in
openCallunder the bill's balance row lock: every call reserves its max length at its level, a concurrency cap per bill applies, and new calls are allowed down to a −$5 buffer. Stripe is never on the call path, and a running call is never cut. - Stripe webhooks go into a stored inbox (
stripe_events) in the same transaction as their pg-boss job, and are processed by a job that fetches the current object from Stripe before acting.
Usage levels (Linedesk Cloud only, decision of 2026-11-16). packages/actions/src/usage-level.ts is the one source of truth: the lists of voice models (VOICE_MODEL_LEVELS), language models (LANGUAGE_MODEL_LEVELS) and realtime models (REALTIME_MODEL_LEVELS: gpt-realtime and gpt-realtime-2) with their level, the price a minute (USAGE_CENTS_PER_MINUTE: Standard 5¢, Premium 10¢, Ultra 20¢, the same for every workspace; derived from LEVEL_PRICES in packages/db/src/billing-config.ts, the one price table) and usageLevel, which gives a call's level. Since call quality (decision of 2026-11-17) each assistant has one level (assistants.call_quality): Standard and Premium answer with the three stages, Ultra with a realtime model. Raising an assistant to Premium or Ultra is the consent to pay more; there are no Allow switches (removed in call quality 4/5, migration 0156 dropped workspace_settings.allow_premium, allow_ultra and assistants.voice_pipeline). Any workspace owner or admin raises a level, whoever pays the bill (refuseLevelChange in apps/api/src/level-raise.ts, decision of 2026-11-18; never through an API key, a personal key, a setup link or an impersonation, never in a disabled workspace). In a white-label client the partner's team changes it, and the client's owner and admins only where the partner lets them (workspace_settings.client_call_quality, docs/white-label.md). Lowering a level, or picking models within it, is anyone's who edits the assistant. voice.options returns callQuality.mayChange and mayRaise: the editor greys Premium and Ultra for whoever may not raise and shows no call quality to whoever may not change it. Levels apply only while the install bills usage (billingState in effect stripe): assistant.update and assistant.restoreVersion refuse a model outside the assistant's level, and call.start decides the level once, at call start (assistantForCall), and passes it to the agent (usageLevel in the start data) for billing. A call never runs unpriced: when its choices are not allowed (a level turned off since, a list changed), assistantForCall falls back to the install's Standard defaults on the three stages and logs one ALERT usage level line; when even that is not allowed (nothing Standard set up), the level stays not_allowed and the agent declines the call (filed as missed, like a call before the providers are set up). On Cloud the start data names the checked voice model, language model and pipeline on the assistant, so the agent answers with exactly those, and centsPerMinute(level) throws for a level without a price. A workspace that gets another bill owner (a hand-over or transfer of the bill, a move onto a bill of someone else) keeps its assistants' levels; the bill pays them (decision of 2026-11-18). On a self-hosted install any assistant may pick a realtime model, and the install-level realtime choice works as before. A long realtime call (research §8.6) keeps its cost and memory: the session is told to cut the conversation in one step past 4,000 tokens after the instructions, keeping half (REALTIME_TRUNCATION, apps/agent/src/pipeline.ts, sent on open and after every reconnect); every few minutes the turns before the last two become one text item (apps/agent/src/realtime-history.ts; at most about 1,500 tokens, the newest lines, each at most 200 characters, so with the last turns it stays well under the 4,000 the truncation keeps; no batch while the last turn to replace has no transcript yet); what the caller told the assistant stays in a call notes block at the end of the instructions, updated only when a field changes (apps/agent/src/call-notes.ts); and the usage line at hang-up has the cached share, the cuts and the text batches (realtime-usage.ts). The call test long-call-recall (phone only, 25 minutes) checks that the name and reason from minute one are still known at minute 24. Before Ultra is turned on for customers, check the cached share on long gpt-realtime-2 calls (the usage line's cachedSharePct, from long-call-recall and a few real calls past 15 minutes): the 20¢ price assumes most input tokens come from the cache, and a share that stays low means the truncation or the text batches break the cache too often. On an install that bills usage, the call test's own pipeline and realtime model (call-test --pipeline, --realtime-model) are ignored, with a warning: the call answers with what the API decided and priced. The default models per level are set in Server admin › Settings › Calls › Call quality (callQuality.set, which refuses a model not of its level); the providers have no model field. Speech recognition has a default per level too (Standard and Premium; STT_MODELS, the models of the install's speech recognition provider, the first its default): call.start names it (sttModel) and the agent hears with it (withSttModel in apps/agent/src/config.ts), else the provider's default; there is no per-assistant pick yet. A change of an assistant's voice model, language model or pipeline is in the audit log (data.usageLevelChange, kind team), and the language check follows the voice the call speaks with (its own voice model). assistants.max_call_minutes has a database check (1 to 30). A self-hosted install uses every option, with no levels, no labels and no checks; only an unlisted per-assistant id is refused there too (the install-level model ids stay free).
18. White-label partners
Design: white-label.md (decided 2026-11-17). A partner (partners) is its own row above workspaces with a team (partner_members, one owner, admins) that joins by email invitation (partner_invitations, token stored hashed). Client workspaces have organization.partner_id; every team member is an admin member of each of them, marked member.partner_id, so tenancy, read sync and permissions stay the workspace's own. syncPartnerMemberships (apps/api/src/partners.ts) keeps those memberships in step with the team and the partner's status, in the transaction of each change. The partner permission is given only to sessions of people on a partner team (or invited to one), never to keys or impersonations; each partner action checks the caller is on that partner's team (403 otherwise). Partner memberships are changed only on the partner (partner_managed), and someone in a client workspace through a partner makes nobody admin there until the client has an owner (S2). Accounts on a partner team are never deleted with a workspace or a removal. Server admin › Partners creates, approves and suspends partners and sets how many client workspaces a partner may make without billing; suspension removes the team from the client workspaces (and cancels the workspace invitations they sent there). Audit kind partners. Built: slice S1; the partner bill, brand and domains follow (white-label.md, "Not built yet").
19. Mobile apps (iOS, Android)
apps/mobile is a Capacitor shell around the web app (decision of 2026-11-28), not a second client: the app opens the server's own pages (server.url, Linedesk Cloud by default; LINEDESK_APP_URL at cap sync for another server), so sessions, sync, the outbox and every update work and ship as on the web. The web app finds out it runs inside the app with isNativeApp() (apps/web/src/native/mobile/platform.ts) and calls the native plugins only through apps/web/src/native/mobile/plugins.ts (Capacitor's registerPlugin; the plugin code lives in apps/mobile).
- Provider sign-in. Google refuses OAuth inside an app's web view, so in the app every provider sign-in (Google, Apple, Microsoft, GitHub, OIDC) runs in the system's sign-in browser: iOS
ASWebAuthenticationSession(iOS 17.4,.httpscallback), Android Chrome Custom Tabs (LinedeskAuthPlugin, our own plugin in both projects; it opens only the app's own server). The session comes back like an OAuth code with PKCE, tied to a provider sign-in of that same flow (apps/api/src/app-sign-in.ts, a Better Auth plugin; security review of #1997): the app keeps a random verifier and opens/app-sign-in?provider=…&challenge=<SHA-256 of it>. That page posts the challenge toPOST /api/auth/app-sign-in/start(kept with the time in a signed httpOnly cookie of that browser, 15 minutes) and signs in with the provider. Back from it, the page shows who signed in and asks for the person's OK; only thenPOST /api/auth/app-sign-in/codegives a one-use code (32 random bytes, stored hashed inverificationwith the user, the challenge and the browser's session; 2 minutes, one per start), and only for a session made after the start: a session the browser had before never counts, and an impersonation never. The code goes to the app on the server's own https address/app-sign-in/back?code=…, a universal link / verified app link that only the real app receives (no custom scheme another app could claim). The app's web view redeems it with the verifier (POST /api/auth/app-sign-in/redeem): the row is deleted in the same statement that reads it, a wrong verifier spends it, the browser's session must still exist (a password reset or "sign out everywhere" in between ends the hand-back) and is ended, the web view's own older session too, and the new session is made by Better Auth's adapter, so the session hooks run (disabled accounts, the host, the audit log with methodapp). All three endpoints check the origin like Better Auth's own sign-in endpoints (formCsrfMiddleware), so another site's form can neither start nor redeem. Everything the provider sign-in itself checks (address proof, sign-up gate, admin alerts) ran in the browser. Email codes, passwords and passkeys work inside the app's web view as on the web (passkeys through the app's associated domain). - Links.
GET /.well-known/apple-app-site-associationand/.well-known/assetlinks.json(apps/api/src/app-links.ts, fromMOBILE_IOS_APP_IDSandMOBILE_ANDROID_APP; 404 without them) let links to the start page/(every email link:/#call/…,/?invite=…) and the sign-in hand-back/app-sign-in/backopen the app; the app then shows that address (appUrlOpen,native/mobile/init.ts; the hand-back belongs to the waiting sign-in). Other paths (/app-sign-in, the API, Stripe's return) stay in the browser. - Push. The app gets its pushes from Apple (APNs, token-based with the
.p8key,apps/api/src/native-push.ts, over HTTP/2; production first, the sandbox for a build from Xcode) and Google (FCM HTTP v1, an access token from the service account), next to the browsers' Web Push and with the same payload and job (push.ts): who called and, for members who opted in, one line on what about; one notification per call (APNsapns-collapse-id, FCMcollapse_keyand tag), time-sensitive on iOS and the high-importance "Calls" channel on Android for urgent calls (channelcalls-v2, private on the lock screen: only that a notification came, not who called or why). Turning on notifications in the app asks the phone, registers it with Apple or Google and stores its token withpush.registerDeviceinpush_subscriptionsas the endpointapns:<token>orfcm:<token>(no keys; the same row rules as a browser: per member and workspace, at most 10, a token of someone else's row is taken over, gone tokens are deleted when APNs or FCM say so (FCM: onlyUNREGISTERED), sign-out removes it, and the row ends with the session that registered it:push_subscriptions.session_id, ON DELETE CASCADE, so a sign-out in Settings › Sessions, a password change or reset that ends the other sessions, or expiry stops its pushes too). The keys are Server admin › Providers › Mobile app push (Apple Push Notifications:.p8key, key ID, team ID, bundle ID; Firebase Cloud Messaging: the service account JSON), read at each push; Test connection sends to a made-up device. Unlike Web Push (encrypted end to end, RFC 8291), Apple and Google can read the app's notifications: the caller's name or number and, for members who opted in, the summary line. - Phone. Status bar, splash screen, the Android back button (closes what is open, then goes back, then puts the app in the background), the keyboard, safe areas (
viewport-fit=coverinside the app). - No buying in the apps. The store rules (App Store 3.1.1 and 3.1.3(b), Google Play payments) allow a multiplatform service whose plans are bought elsewhere, without calls to action. Inside the app every purchase step is hidden: Settings › Billing, the billing banner, the trial link, the plan step of onboarding (a neutral "Your plan is managed on the web" step that waits for the plan), extra paid phone numbers, the partner's activation and billing, prices of call quality levels, and trial wording on the sign-up and sign-in pages.
- Account deletion (App Store 5.1.1(v)): Account › Profile › Delete account opens Workspace settings › Danger zone, where leaving the last workspace or deleting an owned one deletes the account.
- Builds. CI builds both apps on a pull request that changes
apps/mobile; on the trunk the iOS build goes to TestFlight (App Store Connect API key, signed in the cloud) and the signed Android bundle (upload key) is kept for Google Play. - Desktop (macOS, Windows).
apps/desktopis an Electron shell around the same pages (decision of 2026-12-03; Electron over Tauri: TypeScript like the rest, the same Chromium on both systems, and its packaging signs, notarizes and makes the Windows installer). The web app finds it bywindow.linedeskDesktop(apps/web/src/native/desktop/bridge.ts; the preload gives it only to the server's own pages, and the main process checks every message's origin), not byisNativeApp(): it is no store app, so buying works as on the web. A provider sign-in runs in the system browser with the hand-back above, except that the code comes back on a loopback address only the app listens on (RFC 8252, 7.3): the app's start page carriesport, the browser page sends the code tohttp://127.0.0.1:<port>/app-sign-in/back(never another host) and then shows/app-sign-in/back?desktop=1("go back to the app"); the server is unchanged. No push service in Electron: while the app runs (its window closed too) it notifies from its own sync (useCallNotifications.ts: an urgent call as soon as it is flagged, every call when it ends; the main process shows them when its window is not in front).linedesk://open/<search><hash>opens the start page with that page; a browser on a Mac or PC hands links from emails to the app when "Open links in the desktop app" is on there (native/desktop/openInDesktop.ts, kept in that browser). Only the server's pages and a fixed list of consent and checkout sites that lead back to it stay in the window (IN_WINDOW_SITES); other links open in the browser. The browser page takesportonly in a computer's browser: on a phone another app could listen on a loopback port, so there the code goes only to the verified https address. A shipped app refuses a debugging port. Automatic updates are built in and off. CI builds a .dmg and a Windows installer, installs and tests them, and keeps them as artifacts; nothing is published.