/** * Shared AgentBuilder API access for the chat UI. * * Local AgentBuilder instances refuse cross-origin requests, so the chat talks * to the runtime same-origin by default: Vite proxies `/api` in development * and Next.js rewrites it. A deployment served from a different origin than a * remote runtime sets the base URL from its entry point via `configureApi()`. */ export const TOKEN_KEY = 'agentbuilder_auth_token' let baseUrl = '' export function configureApi(options: { baseUrl?: string }) { baseUrl = (options.baseUrl || '').replace(/\/$/, '') } export function getBaseUrl(): string { return baseUrl } /** Endpoint passed to `AgentBuilderProvider` for SDK routes. */ export function getSdkEndpoint(): string { return `${getBaseUrl()}/api` } export function apiUrl(path: string): string { return `${getBaseUrl()}${path}` } export function getToken(): string { try { return localStorage.getItem(TOKEN_KEY) || '' } catch { return '' } } /** * Fetch an AgentBuilder route. Same-origin requests carry the HttpOnly session * cookie; a stored bearer token (password login) is sent when present. */ export function apiFetch(path: string, init: RequestInit = {}): Promise { const headers = new Headers(init.headers) if (init.body && !(init.body instanceof FormData) && !headers.has('Content-Type')) { headers.set('Content-Type', 'application/json') } const token = getToken() if (token && !headers.has('Authorization')) { headers.set('Authorization', `Bearer ${token}`) } return fetch(apiUrl(path), { credentials: 'include', ...init, headers }) }