Skip to main content
Version: v1 (Current)

Live AI architecture

Live AI spans the platform's Laravel application, its Vue client, the Mediasoup service and the model/provider connection. Each has separate state and failure modes. Start with the setup overview; this guide explains the current integration boundaries, persistence and callbacks. Deployment, secret rotation and recovery procedures belong in operator runbooks.

Responsibilities and identities​

LayerCurrent entry pointsResponsibility
BrowserGeminiLiveChat.vue, useLiveAi.jsProject context, initialization, local capture and user-visible state
Browser signalinguseLiveAiSignaling.jsWebSocket authentication and typed message dispatch
Browser transportuseLiveAiWebRTC.js, useLiveAiAudio.jsMediasoup client transports, capture and playback
Platform initializationMediaSessionController, LiveAiSessionServiceAI/media records, model capability, signed setup token and configuration
Media serviceSessionManager, TransportManager, GeminiClient, audio/video bridgesLive transport, provider connection and media-service session lifecycle
Platform callbacksMediaSessionWebhookController, MediaSessionFunctionControllerSigned event/asset/status submissions and supported tool actions/queries
PersistenceMediaSession, MediaSessionEvent, MediaSessionAssetPlatform session state, event rows and uploaded-asset metadata

An AI session and a media session are distinct records. ai_sessions.media_session_id links the AI session to media_sessions; the media model exposes multiple aiSessions(). Events and assets use media_session_events and media_session_assets. Do not create the old guide's live_sessions, ai_live_session_events or ai_live_assets schema.

Keep the AI session ID, numeric platform media-session ID, connection UUID, browser socket-session ID and media-service session ID distinct. SessionManager.createSession() generates its own UUID; its callback uses payload.session_id to address the platform media record. A log field named session_id needs its producer's context before it can be used for a lookup.

Initialization and browser connection​

  1. The internal Vue component sends the authenticated project/interface/session request described in the overview, including its browser socket-session ID.
  2. The controller creates or loads the AI session and rejects a related media session already initializing or active with HTTP 409. The service checks the associated System AI Model's supports_live_api flag.
  3. The service formats SystemAiModel.driver.live, creates a MediaSession, attaches it to the AI session, updates model activity and generates an HS256 token. These operations are not one atomic transaction with external media setup.
  4. HTTP 201 returns success: true and data with media_session_id, connection_id, status, signaling_url, token and max_duration. It does not return a separate ICE-server list.
  5. The client initializes audio, requests microphone capture and optionally attempts video capture. Video capture failure is logged and can continue without video. It then connects signaling and initializes WebRTC.
  6. On WebSocket open, the signaling composable sends {type: "auth", token} as its first message and waits for authenticated. Opening a socket is not authentication or media readiness.
  7. The WebRTC composable loads a Mediasoup Device, creates send/receive transports from transport-created responses and exchanges transport connection/production messages. It uses create-transport and connect-transport, not the old guide's generic hand-written SDP offer/answer API.

The media service constructs TransportManager with the connection UUID and token's TURN credentials, and creates its GeminiClient with the token payload. The browser receives transport parameters through signaling. Audio/video bridges connect media transport to the provider; declared sample rates do not prove successful resampling, codec negotiation or playback in a deployment.

The new-session controller's interface-use gate is commented out. Existing AI-session access uses a view gate, but route prefixes and global model lookups do not establish complete principal/project/interface consistency. Verify those boundaries before audience exposure. See the overview's access and controlled-acceptance checklist.

Token and configuration contract​

LiveAiSessionService.generateSessionToken() includes:

  • jti, iat, exp;
  • platform session_id, connection_id, user_id, project_id, interface_id and socket_session_id;
  • logging_level, formatted live_config, tools and max_duration;
  • turn_credentials when a TURN URL is configured, otherwise null.

Token expiry is the model live duration plus a 300-second buffer; this path defaults duration to 1,800 seconds. It does not use services.mediasoup.jwt_ttl as its expiry calculation. The media JWTValidator verifies HS256 with its configured secret, requires a session ID and, for an AI Live payload, a connection ID and live_config.mode. A signature proves integrity under the shared secret; it is not a fresh project permission lookup or a complete schema validation.

Tools come from the System AI Model's driver.tools, not an arbitrary interface custom_settings.live.tools object. Formatting supplies name, description, default type query, parameters and optional generation/rate/image-return settings. Defining a tool does not implement a new Laravel handler or prove that a provider can run it.

Treat the browser session token as a credential. It is signed, not encrypted, and carries configuration and temporary TURN credentials. Keep signing/provider secrets in deployment configuration and avoid recording tokens in screenshots or shared logs. The overview lists the actual Laravel configuration names; media-service secrets must match their corresponding platform consumers.

Callback paths and signatures​

The service's Laravel client uses these paths relative to its configured Laravel base URL:

Method/pathPurpose
POST /webhook/v1/live-sessions/eventsPersist an event
POST /webhook/v1/live-sessions/assetsCreate asset metadata and optionally upload content
POST /webhook/v1/live-sessions/{mediaSession}/statusUpdate media state/completion/failure
POST /webhook/v1/live-sessions/actionExecute a supported side effect
POST /webhook/v1/live-sessions/queryFetch supported query data

The sender signs the exact JSON payload with HMAC-SHA256 and sends its hex digest in X-Signature. Both reviewed Laravel controllers compare that header to an HMAC of the raw request body using services.live_ai.webhook_secret. Missing signature or secret fails validation. This is not X-Webhook-Signature.

The route group also runs AuthenticateWebhook before these controller validators. Live-session routes are not in that middleware's self-authenticated exemptions: it checks X-Webhook-Secret against app.ef_webhook_secret or services.orchestrator.secret. The reviewed media callback sender sends X-Signature but no X-Webhook-Secret. This is a current integration mismatch when the missing header does not match either configured outer secret; a valid HMAC alone does not prove the routed request is admitted. Coordinate and test a platform/service correction before relying on callback storage. Do not solve it by publishing shared secrets or disabling authentication.

These validators do not perform timestamp/nonce checking or replay deduplication. Do not describe the shared-secret check as replay protection. Signed callbacks are privileged service traffic; the signature does not separately validate every supplied project/user/session relationship.

The shared client has a 30-second HTTP timeout. Event/status wrappers catch and log callback failures; asset storage returns null on failure. Those paths do not establish a durable retry queue or guaranteed eventual storage. A live conversation can succeed while platform callbacks fail.

Events, assets and completion​

Event submissions require an existing numeric media-session ID, string event type and inbound/outbound direction; transcription, content type, payload and metadata are optional. The service creates an event through the media session's relationship. Event storage does not by itself create an ordinary AiSessionMessage transcript.

Asset submissions accept audio, video, image or audio_chunk. The current interface store_audio check in the webhook controller is commented out; do not rely on that old opt-out as an enforced storage restriction. The service first creates an asset with pending upload status and retention_until based on configured retention days. If file_data is supplied, it decodes the base64 content, attaches a temporary upload and can return a signed URL and image thumbnail.

The callback response's stored: true is not proof of a usable uploaded file: file_data is nullable, and metadata creation can precede upload failure. Check asset_id, returned URL, upload state and actual file availability. A retention timestamp and the model's expired scope do not prove that a scheduled deletion ran. Asset payloads/transcripts may be sensitive; current code logs asset data in the service, so establish acceptable logging and retention before real audience use.

Status callbacks accept active, completed, disconnected and failed, plus supported optional connection/statistics fields. Completed calls completeSession(), failed calls terminateSession(), and the other states use updateSessionStatus(). Completion writes disconnected time/reason and supplied statistics. Termination writes failed, or admin_terminated for the service's admin-action branch.

The service completion path can increment project daily-minute counters when enabled and a related AI interface exists. No idempotency guard is present in that method: repeated completion calls must not be assumed to count only once. Admission validation's project/user checks remain commented out; counters and configured limits do not establish enforced caps.

Media-service closure stops bridges, disconnects Gemini, closes transports, submits final statistics and removes its local session. An exception or failed callback can leave the platform and service views different. Conversely, a completed database row does not prove every browser track or remote resource has stopped. Verify both sides.

Function calls​

FunctionCaller distinguishes action, query and generation tool paths. Actions/queries call the separate signed Laravel endpoints above; generation uses its configured media-side generator path. Generation availability, provider credentials and any durable output require their own acceptance.

The reviewed Laravel action dispatcher supports sendSocketEvent. It requires a socket-session ID and event name and broadcasts MediaSessionSocketEvent; this is not an implementation of every notification/integration action described by a tool prompt.

The query dispatcher supports getDayAgenda, getProjectInfo, getAttendeeProfile and searchSessions. Unknown handlers throw. getDayAgenda returns the attendee's project agenda for the requested date, not a personalized enrollment list. Attendee/profile queries use the supplied user ID as an attendee ID within the project; ensure the token's principal/attendee attribution fits that expectation. Project search and profile disclosure still need project/access acceptance.

Successful action responses return success/message; query responses return success/data. Execution failures return HTTP 500 with failure details, and function-call event logging is best-effort. A provider tool declaration, successful socket broadcast or logged function call does not prove the browser applied a business action.

Diagnostics and acceptance​

Trace one controlled session across the identities above. Inspect initialization, local capture, signaling authentication, transport creation, provider input/output, transcript display, callbacks and terminal cleanup separately. Browser reconnect logic reuses the existing token; it does not prove token renewal, expired-token recovery or restoration of lost media-service state.

FailureEvidence to inspect
HTTP initialization succeeded, no conversationCapture permission, authenticated signaling, transport parameters and provider error separately
Callback rejectedOuter X-Webhook-Secret admission separately from controller X-Signature, actual base/path and matching secret; do not publish payloads or secrets
Playback works, transcript/assets absentCallback result, event identity, upload state and platform storage
Platform completed, media remains activeBrowser tracks, service session and transport/provider cleanup
Duplicate events or minute countsCallback replay/repeated completion and lack of idempotency guarantee
Transcript ends early or repeatsProvider turn events versus service/browser finalization timers; see audio turns

Source review is not deployed acceptance. Exercise denied/cross-project access, capture denial, ICE/TURN failure, interruption, token expiry, disconnect/reconnect, callback failure and repeated completion with controlled data before release. Confirm expected terminal records and stored assets without assuming exactly-once delivery or automatic retention cleanup.

Source map​

The named PHP classes are under app/Http/Controllers/{Api,Webhooks}/Ver1, app/Services and app/Models. Browser composables live in resources/js/Composables. Media-service implementations live under services/mediasoup/src/{auth,signaling,media,gemini,webhooks}. Route definitions are routes/api/v1/routes.php, routes/admin/dashboard.php and routes/webhook/v1/routes.php.

Use the current monitoring guide for application diagnostics. This article does not prescribe production pod topology, health/metrics exposure or scaling policy. The prior architecture proposal is preserved in repository design history.