import type { AgentRecord, CompanyRecord, GlobalProviderConfig } from "../types.js"; type PluginConfigResponse = { id: string; pluginId: string; configJson: Record; lastError: string | null; createdAt: string; updatedAt: string; } | null; type ApiErrorPayload = { error?: string; message?: string; }; async function parseError(response: Response): Promise { try { const json = await response.json() as ApiErrorPayload; return json.error ?? json.message ?? `Request failed (${response.status})`; } catch { const text = await response.text(); return text || `Request failed (${response.status})`; } } export async function apiFetchJson(path: string, init?: RequestInit): Promise { const response = await fetch(`/api${path}`, { credentials: "include", headers: { "Content-Type": "application/json", ...(init?.headers ?? {}), }, ...init, }); if (!response.ok) { throw new Error(await parseError(response)); } if (response.status === 204) { return undefined as T; } return await response.json() as T; } export async function loadPluginConfig(pluginId: string): Promise { const payload = await apiFetchJson(`/plugins/${encodeURIComponent(pluginId)}/config`); if (!payload) return null; return payload.configJson as GlobalProviderConfig; } export async function savePluginConfig(pluginId: string, config: GlobalProviderConfig): Promise { const payload = await apiFetchJson>( `/plugins/${encodeURIComponent(pluginId)}/config`, { method: "POST", body: JSON.stringify({ configJson: config }), }, ); return payload.configJson as GlobalProviderConfig; } export async function listCompanies(): Promise { return await apiFetchJson("/companies"); } export async function listCompanyAgents(companyId: string): Promise { return await apiFetchJson(`/companies/${encodeURIComponent(companyId)}/agents`); } export async function patchAgent( agentId: string, companyId: string, patch: Record, ): Promise { return await apiFetchJson( `/agents/${encodeURIComponent(agentId)}?companyId=${encodeURIComponent(companyId)}`, { method: "PATCH", body: JSON.stringify(patch), }, ); } export async function invokeFetchModelsAction( pluginId: string, input: { baseUrl: string; apiKey: string }, ): Promise<{ baseUrl: string; modelCatalog: Array<{ id: string; label: string; raw?: Record | null }> }> { const payload = await apiFetchJson<{ data: unknown }>( `/plugins/${encodeURIComponent(pluginId)}/actions/fetch-openai-models`, { method: "POST", body: JSON.stringify({ params: input, }), }, ); return payload.data as { baseUrl: string; modelCatalog: Array<{ id: string; label: string; raw?: Record | null }>; }; }