import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http'; import { Injectable, inject } from '@angular/core'; import { firstValueFrom, Observable } from 'rxjs'; import { VOICE_STREAM_CONFIG } from './voice-stream.types'; /** Error envelope from the catalog: { error: { code, message, request_id, retryable, details } }. */ export class VoiceApiError extends Error { constructor( readonly status: number, readonly code: string, message: string, readonly retryable = false, readonly requestId?: string, ) { super(message); this.name = 'VoiceApiError'; } } export interface MeResponse { user: { id: string; username: string; role: string; organization_id: string }; csrf_token: string; expires_at: string; } export interface ConfigurationResponse { capabilities: { text: boolean; voice: boolean; captions: boolean }; } export interface ConversationResponse { id: string; mode: 'voice'; title: string; status: string; } export interface VoiceSessionResponse { session_id: string; conversation_id: string; status: string; stream_path: string; expires_at: string; poll_url: string; } /** * Thin client for the endpoints the live voice call needs (A03, F01, C01, V01, V04). * Uses HttpClient so the app's existing interceptors (401 → login redirect, etc.) still apply. * Auth is the HttpOnly `rag_session` cookie; state-changing calls also need `X-CSRF-Token`. */ @Injectable({ providedIn: 'root' }) export class VoiceApiService { private readonly http = inject(HttpClient); private readonly config = inject(VOICE_STREAM_CONFIG); /** A03: identity + a fresh CSRF token. 401 AUTH_REQUIRED when not logged in. */ me(): Promise { return this.send(this.http.get(this.url('/me'), { withCredentials: true })); } /** F01: capabilities (the UI must check `voice` before offering a call). */ configuration(): Promise { return this.send( this.http.get(this.url('/configuration'), { withCredentials: true }), ); } /** C01: only `mode: "voice"` exists in the MVP. */ createConversation(csrf: string, title: string): Promise { return this.send( this.http.post( this.url('/conversations'), { client_request_id: crypto.randomUUID(), mode: 'voice', title }, this.options(csrf), ), ); } /** V01: reserves a live session; connect the WebSocket to the returned `stream_path`. */ createVoiceSession(csrf: string, conversationId: string): Promise { return this.send( this.http.post( this.url('/voice/sessions'), { conversation_id: conversationId, client_request_id: crypto.randomUUID() }, this.options(csrf), ), ); } /** V04: closes the session (idempotent from the UI's point of view). */ async closeVoiceSession(csrf: string, sessionId: string): Promise { await this.send( this.http.post( this.url(`/voice/sessions/${encodeURIComponent(sessionId)}/close`), {}, this.options(csrf), ), ); } /** `wss://…` URL for a V01 `stream_path`. */ streamUrl(streamPath: string): string { const base = this.config.apiOrigin || window.location.origin; const url = new URL(streamPath, base); url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:'; return url.toString(); } // --------------------------------------------------------------------------- private url(path: string): string { return `${this.config.apiOrigin}${this.config.apiBase}${path}`; } private options(csrf: string) { return { withCredentials: true, headers: new HttpHeaders({ 'X-CSRF-Token': csrf, 'X-Request-ID': crypto.randomUUID() }), }; } private async send(request: Observable): Promise { try { return await firstValueFrom(request); } catch (err) { throw this.toApiError(err); } } private toApiError(err: unknown): VoiceApiError { if (err instanceof HttpErrorResponse) { const envelope = (err.error as { error?: Record } | null)?.error; return new VoiceApiError( err.status, typeof envelope?.['code'] === 'string' ? envelope['code'] : err.status === 0 ? 'NETWORK' : 'UNKNOWN', typeof envelope?.['message'] === 'string' ? envelope['message'] : err.message, envelope?.['retryable'] === true, typeof envelope?.['request_id'] === 'string' ? envelope['request_id'] : undefined, ); } return new VoiceApiError(0, 'UNKNOWN', err instanceof Error ? err.message : 'unknown error'); } }