Skip to content

Project NOMAD is an offline-first knowledge and education server. Wikipedia, thousands of books, courses, maps, and optional local AI, all running on hardware you own with no internet required.

TypeScript
42.0 KB
Raw Blame
import axios, { AxiosError, AxiosInstance } from 'axios'
import {
  ListCatalogLanguagesResponse,
  ListRemoteZimFilesResponse,
  ListZimFilesResponse,
} from '../../types/zim'
import { ServiceSlim } from '../../types/services'
import { FileEntry } from '../../types/files'
import { AppAutoUpdateStatus, AutoUpdateStatus, CheckLatestVersionResult, ContentAutoUpdateStatus, SystemInformationResponse, SystemUpdateStatus } from '../../types/system'
import { DownloadJobWithProgress, WikipediaState } from '../../types/downloads'
import type { Country, CountryCode, CountryGroup, MapExtractPreflight } from '../../types/maps'
import { EmbedJobWithProgress, FileWarningsResult, StoredFileInfo } from '../../types/rag'
import type { CategoryWithStatus, CollectionWithStatus, ContentUpdateCheckResult, CreatorPackWithStatus, ResourceUpdateInfo } from '../../types/collections'
import { catchInternal } from './util'
import { NomadChatResponse, NomadInstalledModel, NomadOllamaModel, OllamaChatRequest } from '../../types/ollama'
import BenchmarkResult from '#models/benchmark_result'
import { BenchmarkType, RunBenchmarkResponse, SubmitBenchmarkResponse, UpdateBuilderTagResponse } from '../../types/benchmark'
import type { CreateMapMarkerPayload, MapMarkerResponse, UpdateMapMarkerPayload } from '../../types/maps'
import type { ChatSource } from '../../types/chat'
import { chatStreamErrorMessage } from './chat_stream.js'

type OllamaChatRequestWithImages = OllamaChatRequest & { images?: File[] }

function serializeChatRequest(chatRequest: OllamaChatRequestWithImages): {
  body: BodyInit
  headers?: Record<string, string>
} {
  const { images = [], ...payload } = chatRequest
  if (images.length === 0) {
    return {
      body: JSON.stringify(payload),
      headers: { 'Content-Type': 'application/json' },
    }
  }

  const formData = new FormData()
  formData.append('payload', JSON.stringify(payload))
  images.forEach((image) => formData.append('images', image, image.name))
  return { body: formData }
}

class API {
  private client: AxiosInstance

  constructor() {
    this.client = axios.create({
      baseURL: '/api',
      headers: {
        'Content-Type': 'application/json',
      },
    })
  }

  async affectService(service_name: string, action: 'start' | 'stop' | 'restart') {
    try {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/services/affect',
        { service_name, action }
      )
      return response.data
    } catch (error) {
      if (error instanceof AxiosError && error.response?.data?.message) {
        return { success: false, message: error.response.data.message }
      }
      console.error('Error affecting service:', error)
      return undefined
    }
  }

  async checkLatestVersion(force: boolean = false) {
    return catchInternal(async () => {
      const response = await this.client.get<CheckLatestVersionResult>('/system/latest-version', {
        params: { force },
      })
      return response.data
    })()
  }

  async getRemoteOllamaStatus(): Promise<{ configured: boolean; connected: boolean }> {
    return catchInternal(async () => {
      const response = await this.client.get<{ configured: boolean; connected: boolean }>(
        '/ollama/remote-status'
      )
      return response.data
    })()
  }

  async configureRemoteOllama(remoteUrl: string | null): Promise<{ success: boolean; message: string }> {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/ollama/configure-remote',
        { remoteUrl }
      )
      return response.data
    })()
  }

  async deleteModel(model: string): Promise<{ success: boolean; message: string }> {
    return catchInternal(async () => {
      const response = await this.client.delete('/ollama/models', { data: { model } })
      return response.data
    })()
  }

  async downloadBaseMapAssets() {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean }>('/maps/download-base-assets')
      return response.data
    })()
  }

  async setupWorldBasemap() {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean }>('/maps/setup-world-basemap')
      return response.data
    })()
  }

  async downloadMapCollection(slug: string): Promise<{
    message: string
    slug: string
    resources: string[] | null
  }> {
    return catchInternal(async () => {
      const response = await this.client.post('/maps/download-collection', { slug })
      return response.data
    })()
  }

  async downloadModel(model: string): Promise<{ success: boolean; message: string }> {
    return catchInternal(async () => {
      const response = await this.client.post('/ollama/models', { model })
      return response.data
    })()
  }

  async downloadCategoryTier(categorySlug: string, tierSlug: string): Promise<{
    message: string
    categorySlug: string
    tierSlug: string
    resources: string[] | null
  }> {
    return catchInternal(async () => {
      const response = await this.client.post('/zim/download-category-tier', { categorySlug, tierSlug })
      return response.data
    })()
  }

  async downloadRemoteMapRegion(url: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string; filename: string; url: string }>(
        '/maps/download-remote',
        { url }
      )
      return response.data
    })()
  }

  async downloadRemoteMapRegionPreflight(url: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{ filename: string; size: number } | { message: string }>(
        '/maps/download-remote-preflight',
        { url }
      )
      return response.data
    })()
  }

  async deleteMapRegionFile(filename: string): Promise<{ message: string }> {
    return catchInternal(async () => {
      const response = await this.client.delete<{ message: string }>(
        `/maps/${encodeURIComponent(filename)}`
      )
      return response.data
    })()
  }

  async downloadRemoteZimFile(
    url: string,
    metadata?: { title: string; summary?: string; author?: string; size_bytes?: number }
  ) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string; filename: string; url: string }>(
        '/zim/download-remote',
        { url, metadata }
      )
      return response.data
    })()
  }

  async fetchLatestMapCollections(): Promise<{ success: boolean } | undefined> {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean }>(
        '/maps/fetch-latest-collections'
      )
      return response.data
    })()
  }

  async checkForContentUpdates() {
    return catchInternal(async () => {
      const response = await this.client.post<ContentUpdateCheckResult>('/content-updates/check')
      return response.data
    })()
  }

  async applyContentUpdate(update: ResourceUpdateInfo) {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; jobId?: string; error?: string }>(
        '/content-updates/apply',
        update
      )
      return response.data
    })()
  }

  async applyAllContentUpdates(updates: ResourceUpdateInfo[]) {
    return catchInternal(async () => {
      const response = await this.client.post<{
        results: Array<{ resource_id: string; success: boolean; jobId?: string; error?: string }>
      }>('/content-updates/apply-all', { updates })
      return response.data
    })()
  }

  async refreshManifests(): Promise<{ success: boolean; changed: Record<string, boolean> } | undefined> {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; changed: Record<string, boolean> }>(
        '/manifests/refresh'
      )
      return response.data
    })()
  }

  async checkServiceUpdates() {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/services/check-updates'
      )
      return response.data
    })()
  }

  async getAvailableVersions(serviceName: string) {
    return catchInternal(async () => {
      const response = await this.client.get<{
        versions: Array<{ tag: string; isLatest: boolean; releaseUrl?: string }>
      }>(`/system/services/${serviceName}/available-versions`)
      return response.data
    })()
  }

  async updateService(serviceName: string, targetVersion: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/services/update',
        { service_name: serviceName, target_version: targetVersion }
      )
      return response.data
    })()
  }

  async forceReinstallService(service_name: string) {
    try {
      const response = await this.client.post<{ success: boolean; message: string }>(
        `/system/services/force-reinstall`,
        { service_name }
      )
      return response.data
    } catch (error) {
      if (error instanceof AxiosError && error.response?.data?.message) {
        return { success: false, message: error.response.data.message }
      }
      console.error('Error force reinstalling service:', error)
      return undefined
    }
  }

  async getChatSuggestions(signal?: AbortSignal) {
    return catchInternal(async () => {
      const response = await this.client.get<{ suggestions: string[] }>(
        '/chat/suggestions',
        { signal }
      )
      return response.data.suggestions
    })()
  }

  async getDebugInfo() {
    return catchInternal(async () => {
      const response = await this.client.get<{ debugInfo: string }>('/system/debug-info')
      return response.data.debugInfo
    })()
  }

  async getInternetStatus() {
    return catchInternal(async () => {
      const response = await this.client.get<boolean>('/system/internet-status')
      return response.data
    })()
  }

  async getInstalledModels() {
    return catchInternal(async () => {
      const response = await this.client.get<NomadInstalledModel[]>('/ollama/installed-models')
      return response.data
    })()
  }

  /**
   * Ask the backend to send Ollama `keep_alive: 0` to every currently-loaded
   * chat model except `targetModel` (and the embedding model, which is always
   * exempt server-side). Fire-and-forget -- the chat UI doesn't await this
   * before creating a new session, since unload is housekeeping.
   *
   * Pass `null` to unload every chat model.
   */
  async unloadChatModels(targetModel: string | null) {
    return catchInternal(async () => {
      const response = await this.client.post<{ unloaded: string[] }>(
        '/ollama/unload-chat-models',
        { targetModel }
      )
      return response.data
    })()
  }

  async getAvailableModels(params: { query?: string; recommendedOnly?: boolean; limit?: number; force?: boolean }) {
    return catchInternal(async () => {
      const response = await this.client.get<{
        models: NomadOllamaModel[]
        hasMore: boolean
      }>('/ollama/models', {
        params: { sort: 'pulls', ...params },
      })
      return response.data
    })()
  }

  async sendChatMessage(chatRequest: OllamaChatRequestWithImages) {
    return catchInternal(async () => {
      if (chatRequest.images?.length) {
        const serialized = serializeChatRequest({ ...chatRequest, stream: false })
        const response = await fetch('/api/ollama/chat', {
          method: 'POST',
          headers: serialized.headers,
          body: serialized.body,
        })
        const responseBody = await response.json().catch(() => null)
        if (!response.ok) {
          throw new Error(responseBody?.message ?? `HTTP error: ${response.status}`)
        }
        return responseBody as NomadChatResponse
      }

      const response = await this.client.post<NomadChatResponse>('/ollama/chat', chatRequest)
      return response.data
    })()
  }

  async streamChatMessage(
    chatRequest: OllamaChatRequestWithImages,
    onChunk: (content: string, thinking: string, done: boolean) => void,
    signal?: AbortSignal,
    onSources?: (sources: ChatSource[]) => void,
    onDoneReason?: (reason: string) => void
  ): Promise<void> {
    // Axios doesn't support ReadableStream in browser, so need to use fetch
    const serialized = serializeChatRequest({ ...chatRequest, stream: true })
    const response = await fetch('/api/ollama/chat', {
      method: 'POST',
      headers: serialized.headers,
      body: serialized.body,
      signal,
    })

    if (!response.ok || !response.body) {
      const errorBody = await response.json().catch(() => null)
      throw new Error(errorBody?.message ?? `HTTP error: ${response.status}`)
    }

    const reader = response.body.getReader()
    const decoder = new TextDecoder()
    let buffer = ''

    try {
      while (true) {
        const { done, value } = await reader.read()
        if (done) break

        buffer += decoder.decode(value, { stream: true })
        const lines = buffer.split('\n')
        buffer = lines.pop() || ''

        for (const line of lines) {
          if (!line.startsWith('data: ')) continue
          let data: any
          try {
            data = JSON.parse(line.slice(6))
          } catch { continue /* skip malformed chunks */ }

          const streamError = chatStreamErrorMessage(data)
          if (streamError) throw new Error(streamError)

          // Citation metadata (#1179) arrives as a distinct trailing event with no
          // `message` key -- route it separately rather than through onChunk.
          if (data.sources) {
            onSources?.(data.sources)
            continue
          }

          // Only the chunk that ends generation carries it; 'length' means the
          // answer was cut off rather than finished (#1342).
          if (data.done_reason) {
            onDoneReason?.(data.done_reason)
          }

          onChunk(
            data.message?.content ?? '',
            data.message?.thinking ?? '',
            data.done ?? false
          )
        }
      }
    } finally {
      reader.releaseLock()
    }
  }

  async getBenchmarkResults() {
    return catchInternal(async () => {
      const response = await this.client.get<{ results: BenchmarkResult[], total: number }>('/benchmark/results')
      return response.data
    })()
  }

  async getLatestBenchmarkResult() {
    return catchInternal(async () => {
      const response = await this.client.get<{ result: BenchmarkResult | null }>('/benchmark/results/latest')
      return response.data
    })()
  }

  async checkBenchmarkRerunBanner() {
    return catchInternal(async () => {
      const response = await this.client.get<{ show: boolean }>('/benchmark/rerun-banner')
      return response.data
    })()
  }

  async getChatSessions() {
    return catchInternal(async () => {
      const response = await this.client.get<Array<{
        id: string
        title: string
        model: string | null
        timestamp: string
        lastMessage: string | null
      }>>('/chat/sessions')
      return response.data
    })()
  }

  async getChatSession(sessionId: string) {
    return catchInternal(async () => {
      const response = await this.client.get<{
        id: string
        title: string
        model: string | null
        timestamp: string
        messages: Array<{
          id: string
          role: 'system' | 'user' | 'assistant'
          content: string
          timestamp: string
        }>
      }>(`/chat/sessions/${sessionId}`)
      return response.data
    })()
  }

  async createChatSession(title: string, model?: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{
        id: string
        title: string
        model: string | null
        timestamp: string
      }>('/chat/sessions', { title, model })
      return response.data
    })()
  }

  async updateChatSession(sessionId: string, data: { title?: string; model?: string }) {
    return catchInternal(async () => {
      const response = await this.client.put<{
        id: string
        title: string
        model: string | null
        timestamp: string
      }>(`/chat/sessions/${sessionId}`, data)
      return response.data
    })()
  }

  async deleteChatSession(sessionId: string) {
    return catchInternal(async () => {
      await this.client.delete(`/chat/sessions/${sessionId}`)
    })()
  }

  async deleteAllChatSessions() {
    return catchInternal(async () => {
      const response = await this.client.delete<{ success: boolean; message: string }>(
        '/chat/sessions/all'
      )
      return response.data
    })()
  }

  async addChatMessage(sessionId: string, role: 'system' | 'user' | 'assistant', content: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{
        id: string
        role: 'system' | 'user' | 'assistant'
        content: string
        timestamp: string
      }>(`/chat/sessions/${sessionId}/messages`, { role, content })
      return response.data
    })()
  }

  async getActiveEmbedJobs(): Promise<EmbedJobWithProgress[] | undefined> {
    return catchInternal(async () => {
      const response = await this.client.get<EmbedJobWithProgress[]>('/rag/active-jobs')
      return response.data
    })()
  }

  async getFailedEmbedJobs(): Promise<EmbedJobWithProgress[] | undefined> {
    return catchInternal(async () => {
      const response = await this.client.get<EmbedJobWithProgress[]>('/rag/failed-jobs')
      return response.data
    })()
  }

  async cleanupFailedEmbedJobs(): Promise<{ message: string; cleaned: number; filesDeleted: number } | undefined> {
    return catchInternal(async () => {
      const response = await this.client.delete<{ message: string; cleaned: number; filesDeleted: number }>('/rag/failed-jobs')
      return response.data
    })()
  }

  async cancelAllEmbedJobs(): Promise<{ message: string; cancelled: number; filesDeleted: number } | undefined> {
    return catchInternal(async () => {
      const response = await this.client.delete<{ message: string; cancelled: number; filesDeleted: number }>('/rag/jobs')
      return response.data
    })()
  }

  async checkRAGHealth() {
    return catchInternal(async () => {
      const response = await this.client.get<{ online: boolean; message?: string }>('/rag/health')
      return response.data
    })()
  }

  async getStoredRAGFiles() {
    return catchInternal(async () => {
      const response = await this.client.get<{ files: StoredFileInfo[] }>('/rag/files')
      return response.data.files
    })()
  }

  async embedSingleRAGFile(source: string, force: boolean = false) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string }>('/rag/files/embed', { source, force })
      return response.data
    })()
  }

  async getKbFileWarnings() {
    return catchInternal(async () => {
      const response = await this.client.get<FileWarningsResult>('/rag/file-warnings')
      return response.data
    })()
  }

  async deleteRAGFile(source: string) {
    return catchInternal(async () => {
      const response = await this.client.delete<{ message: string }>('/rag/files', { data: { source } })
      return response.data
    })()
  }

  async getFileContent(source: string) {
    return catchInternal(async () => {
      const response = await this.client.get<{
        content: string
        extension: string
        fileName: string
      }>('/rag/files/content', { params: { source } })
      return response.data
    })()
  }

  async getSystemInfo() {
    return catchInternal(async () => {
      const response = await this.client.get<SystemInformationResponse>('/system/info')
      return response.data
    })()
  }

  async getSystemServices() {
    return catchInternal(async () => {
      const response = await this.client.get<Array<ServiceSlim>>('/system/services')
      return response.data
    })()
  }

  async getSystemUpdateStatus() {
    return catchInternal(async () => {
      const response = await this.client.get<SystemUpdateStatus>('/system/update/status')
      return response.data
    })()
  }

  async getSystemUpdateLogs() {
    return catchInternal(async () => {
      const response = await this.client.get<{ logs: string }>('/system/update/logs')
      return response.data
    })()
  }

  async getAutoUpdateStatus() {
    return catchInternal(async () => {
      const response = await this.client.get<AutoUpdateStatus>('/system/auto-update/status')
      return response.data
    })()
  }

  async getAppAutoUpdateStatus() {
    return catchInternal(async () => {
      const response = await this.client.get<AppAutoUpdateStatus>('/system/apps/auto-update/status')
      return response.data
    })()
  }

  async getContentAutoUpdateStatus() {
    return catchInternal(async () => {
      const response = await this.client.get<ContentAutoUpdateStatus>(
        '/system/content/auto-update/status'
      )
      return response.data
    })()
  }

  async setServiceAutoUpdate(serviceName: string, enabled: boolean) {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/services/auto-update',
        { service_name: serviceName, enabled }
      )
      return response.data
    })()
  }

  async healthCheck() {
    return catchInternal(async () => {
      const response = await this.client.get<{ status: string }>('/health', {
        timeout: 5000,
      })
      return response.data
    })()
  }

  async installService(service_name: string) {
    try {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/services/install',
        { service_name }
      )
      return response.data
    } catch (error) {
      if (error instanceof AxiosError && error.response?.data?.message) {
        return { success: false, message: error.response.data.message }
      }
      console.error('Error installing service:', error)
      return undefined
    }
  }

  async getGlobalMapInfo() {
    return catchInternal(async () => {
      const response = await this.client.get<{
        url: string
        date: string
        size: number
        key: string
      }>('/maps/global-map-info')
      return response.data
    })()
  }

  async downloadGlobalMap() {
    return catchInternal(async () => {
      const response = await this.client.post<{
        message: string
        filename: string
        jobId?: string
      }>('/maps/download-global-map')
      return response.data
    })()
  }

  async listCountries() {
    return catchInternal(async () => {
      const response = await this.client.get<{ countries: Country[] }>('/maps/countries')
      return response.data.countries
    })()
  }

  async listCountryGroups() {
    return catchInternal(async () => {
      const response = await this.client.get<{ groups: CountryGroup[] }>('/maps/country-groups')
      return response.data.groups
    })()
  }

  async extractMapPreflight(params: { countries: CountryCode[]; maxzoom?: number }) {
    return catchInternal(async () => {
      const response = await this.client.post<MapExtractPreflight>(
        '/maps/extract-preflight',
        params
      )
      return response.data
    })()
  }

  async extractMapRegion(params: {
    countries: CountryCode[]
    maxzoom?: number
    label?: string
    estimatedBytes?: number
  }) {
    return catchInternal(async () => {
      const response = await this.client.post<{
        message: string
        filename: string
        jobId?: string
      }>('/maps/extract', params)
      return response.data
    })()
  }

  async listCuratedMapCollections() {
    return catchInternal(async () => {
      const response = await this.client.get<CollectionWithStatus[]>(
        '/maps/curated-collections'
      )
      return response.data
    })()
  }

  async listCuratedCategories() {
    return catchInternal(async () => {
      const response = await this.client.get<CategoryWithStatus[]>('/easy-setup/curated-categories')
      return response.data
    })()
  }

  async getCreatorPacks() {
    return catchInternal(async () => {
      const response = await this.client.get<{
        configured: boolean
        packs: CreatorPackWithStatus[]
        downloads: DownloadJobWithProgress[]
      }>('/creator-packs')
      return response.data
    })()
  }

  async installCreatorPack(id: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string; filename?: string }>(
        `/creator-packs/${id}/install`
      )
      return response.data
    })()
  }

  async uninstallCreatorPack(id: string) {
    return catchInternal(async () => {
      const response = await this.client.delete<{ message: string; filename?: string }>(
        `/creator-packs/${id}`
      )
      return response.data
    })()
  }

  async listDocs() {
    return catchInternal(async () => {
      const response = await this.client.get<Array<{ title: string; slug: string }>>('/docs/list')
      return response.data
    })()
  }

  async listMapRegionFiles() {
    return catchInternal(async () => {
      const response = await this.client.get<{ files: FileEntry[] }>('/maps/regions')
      return response.data.files
    })()
  }

  async listMapMarkers() {
    return catchInternal(async () => {
      const response = await this.client.get<MapMarkerResponse[]>('/maps/markers')
      return response.data
    })()
  }

  async createMapMarker(data: CreateMapMarkerPayload) {
    return catchInternal(async () => {
      const response = await this.client.post<MapMarkerResponse>('/maps/markers', data)
      return response.data
    })()
  }

  async updateMapMarker(id: number, data: UpdateMapMarkerPayload) {
    return catchInternal(async () => {
      const response = await this.client.patch<MapMarkerResponse>(`/maps/markers/${id}`, data)
      return response.data
    })()
  }

  async deleteMapMarker(id: number) {
    return catchInternal(async () => {
      await this.client.delete(`/maps/markers/${id}`)
    })()
  }

  async listRemoteZimFiles({
    start = 0,
    count = 12,
    query,
    language,
  }: {
    start?: number
    count?: number
    query?: string
    language?: string
  }) {
    return catchInternal(async () => {
      return await this.client.get<ListRemoteZimFilesResponse>('/zim/list-remote', {
        params: {
          start,
          count,
          query,
          language,
        },
      })
    })()
  }

  async listCatalogLanguages() {
    return catchInternal(async () => {
      const response =
        await this.client.get<ListCatalogLanguagesResponse>('/zim/catalog-languages')
      return response.data.languages
    })()
  }

  async listCustomLibraries() {
    return catchInternal(async () => {
      const response = await this.client.get<{ id: number; name: string; base_url: string; is_default: boolean }[]>(
        '/zim/custom-libraries'
      )
      return response.data
    })()
  }

  async addCustomLibrary(name: string, base_url: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{
        message: string
        library: { id: number; name: string; base_url: string }
      }>('/zim/custom-libraries', { name, base_url })
      return response.data
    })()
  }

  async removeCustomLibrary(id: number) {
    return catchInternal(async () => {
      const response = await this.client.delete<{ message: string }>(`/zim/custom-libraries/${id}`)
      return response.data
    })()
  }

  async browseLibrary(url: string) {
    return catchInternal(async () => {
      const response = await this.client.get<{
        directories: { name: string; url: string }[]
        files: { name: string; url: string; size_bytes: number | null }[]
      }>('/zim/browse-library', { params: { url } })
      return response.data
    })()
  }

  async deleteZimFile(filename: string) {
    return catchInternal(async () => {
      const response = await this.client.delete<{ message: string }>(`/zim/${filename}`)
      return response.data
    })()
  }

  async listZimFiles() {
    return catchInternal(async () => {
      return await this.client.get<ListZimFilesResponse>('/zim/list')
    })()
  }

  async rescanZimLibrary() {
    return catchInternal(async () => {
      const response = await this.client.post<{
        message: string
        before: number
        after: number
        added: number
      }>('/zim/rescan-library')
      return response.data
    })()
  }

  async listDownloadJobs(filetype?: string): Promise<DownloadJobWithProgress[] | undefined> {
    return catchInternal(async () => {
      const endpoint = filetype ? `/downloads/jobs/${filetype}` : '/downloads/jobs'
      const response = await this.client.get<DownloadJobWithProgress[]>(endpoint)
      return response.data
    })()
  }

  async removeDownloadJob(jobId: string): Promise<void> {
    return catchInternal(async () => {
      await this.client.delete(`/downloads/jobs/${jobId}`)
    })()
  }

  async cancelDownloadJob(jobId: string): Promise<{ success: boolean; message: string } | undefined> {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        `/downloads/jobs/${jobId}/cancel`
      )
      return response.data
    })()
  }

  async retryDownloadJob(jobId: string): Promise<{ success: boolean; message: string } | undefined> {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        `/downloads/jobs/${jobId}/retry`
      )
      return response.data
    })()
  }

  async runBenchmark(type: BenchmarkType, sync: boolean = false) {
    return catchInternal(async () => {
      const response = await this.client.post<RunBenchmarkResponse>(
        `/benchmark/run${sync ? '?sync=true' : ''}`,
        { benchmark_type: type },
      )
      return response.data
    })()
  }

  async startSystemUpdate() {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/update'
      )
      return response.data
    })()
  }

  async submitBenchmark(benchmark_id: string, anonymous: boolean) {
    try {
      const response = await this.client.post<SubmitBenchmarkResponse>('/benchmark/submit', { benchmark_id, anonymous })
      return response.data
    } catch (error: any) {
      // For 409 Conflict errors, throw a specific error that the UI can handle
      if (error.response?.status === 409) {
        const err = new Error(error.response?.data?.error || 'This benchmark has already been submitted to the repository')
          ; (err as any).status = 409
        throw err
      }
      // For other errors, extract the message and throw
      const errorMessage = error.response?.data?.error || error.message || 'Failed to submit benchmark'
      throw new Error(errorMessage)
    }
  }

  async subscribeToReleaseNotes(email: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/subscribe-release-notes',
        { email }
      )
      return response.data
    })()
  }

  async syncRAGStorage() {
    return catchInternal(async () => {
      const response = await this.client.post<{
        success: boolean
        message: string
        filesScanned?: number
        filesQueued?: number
      }>('/rag/sync')
      return response.data
    })()
  }

  async reembedAllRAG() {
    return catchInternal(async () => {
      const response = await this.client.post<{
        success: boolean
        message: string
        filesScanned?: number
        filesQueued?: number
      }>('/rag/re-embed-all')
      return response.data
    })()
  }

  async resetAndRebuildRAG() {
    return catchInternal(async () => {
      const response = await this.client.post<{
        success: boolean
        message: string
        filesScanned?: number
        filesQueued?: number
      }>('/rag/reset-and-rebuild')
      return response.data
    })()
  }

  async estimateEmbeddingBatch(files: { filename: string; sizeBytes: number }[]) {
    return catchInternal(async () => {
      const response = await this.client.post<{
        totalChunks: number
        totalBytes: number
        hasUnknown: boolean
      }>('/rag/estimate-batch', { files })
      return response.data
    })()
  }

  async getKbPolicyPromptState() {
    return catchInternal(async () => {
      const response = await this.client.get<{
        shouldPrompt: boolean
        hasContent: boolean
        totalFiles: number
      }>('/rag/policy-prompt-state')
      return response.data
    })()
  }

  // Wikipedia selector methods

  async getWikipediaState(): Promise<WikipediaState | undefined> {
    return catchInternal(async () => {
      const response = await this.client.get<WikipediaState>('/zim/wikipedia')
      return response.data
    })()
  }

  async selectWikipedia(
    optionId: string
  ): Promise<{ success: boolean; jobId?: string; message?: string } | undefined> {
    return catchInternal(async () => {
      const response = await this.client.post<{
        success: boolean
        jobId?: string
        message?: string
      }>('/zim/wikipedia/select', { optionId })
      return response.data
    })()
  }

  async updateBuilderTag(benchmark_id: string, builder_tag: string) {
    return catchInternal(async () => {
      const response = await this.client.post<UpdateBuilderTagResponse>(
        '/benchmark/builder-tag',
        { benchmark_id, builder_tag }
      )
      return response.data
    })()
  }

  async uploadDocument(file: File, collection?: string) {
    return catchInternal(async () => {
      const formData = new FormData()
      formData.append('file', file)
      if (collection) formData.append('collection', collection)
      const response = await this.client.post<{ message: string; file_path: string }>(
        '/rag/upload',
        formData,
        {
          headers: {
            'Content-Type': 'multipart/form-data',
          },
        }
      )
      return response.data
    })()
  }

  async getKnowledgeCollections() {
    return catchInternal(async () => {
      const response = await this.client.get<{ collections: string[] }>('/rag/collections')
      return response.data
    })()
  }

  async updateFileCollection(source: string, collection: string | null) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string }>('/rag/update-collection', {
        source,
        collection,
      })
      return response.data
    })()
  }

  async setFileActive(source: string, active: boolean) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string }>('/rag/files/active', {
        source,
        active,
      })
      return response.data
    })()
  }

  async renameCollection(oldName: string, newName: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string }>('/rag/rename-collection', {
        oldName,
        newName,
      })
      return response.data
    })()
  }

  async deleteCollection(name: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string }>('/rag/delete-collection', {
        name,
      })
      return response.data
    })()
  }

  async setKnowledgeCollectionActive(collection: string | null, active: boolean) {
    return catchInternal(async () => {
      const response = await this.client.post<{ message: string; affectedCount: number }>(
        '/rag/collection-active',
        { collection, active }
      )
      return response.data
    })()
  }

  async createLinkTile(data: {
    friendly_name: string
    url: string
    description?: string | null
    icon?: string | null
    display_order?: number
    link_color?: string
  }) {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; service_name: string }>(
        '/system/services/links',
        data
      )
      return response.data
    })()
  }

  async updateLinkTile(data: {
    service_name: string
    friendly_name: string
    url: string
    description?: string | null
    icon?: string | null
    display_order?: number
    link_color?: string
  }) {
    return catchInternal(async () => {
      const response = await this.client.put<{ success: boolean }>('/system/services/links', data)
      return response.data
    })()
  }

  async deleteLinkTile(service_name: string) {
    return catchInternal(async () => {
      const response = await this.client.delete<{ success: boolean }>('/system/services/links', {
        data: { service_name },
      })
      return response.data
    })()
  }

  async getSetting(key: string) {
    return catchInternal(async () => {
      const response = await this.client.get<{ key: string; value: any }>(
        '/system/settings',
        { params: { key } }
      )
      return response.data
    })()
  }

  async updateSetting(key: string, value: any) {
    return catchInternal(async () => {
      const response = await this.client.patch<{ success: boolean; message: string }>(
        '/system/settings',
        { key, value }
      )
      return response.data
    })()
  }

  async getNomadMd() {
    return catchInternal(async () => {
      const response = await this.client.get<{ content: string }>('/ai/nomad-md')
      return response.data
    })()
  }

  async saveNomadMd(content: string) {
    return catchInternal(async () => {
      const response = await this.client.put<{ success: boolean; message: string }>(
        '/ai/nomad-md',
        { content }
      )
      return response.data
    })()
  }

  async preflightCheck(service_name: string) {
    return catchInternal(async () => {
      const response = await this.client.get<{
        portConflicts: Array<{ port: number; usedBy: string }>
        resourceWarnings: string[]
      }>('/system/services/preflight', { params: { service_name } })
      return response.data
    })()
  }

  async suggestCustomPort() {
    return catchInternal(async () => {
      const response = await this.client.get<{ port: number }>('/system/services/suggest-port')
      return response.data
    })()
  }

  async preflightCustomApp(payload: {
    image?: string
    ports?: number[]
    volumes?: Array<{ host_path: string; container_path: string }>
    exclude_service?: string
  }) {
    return catchInternal(async () => {
      const response = await this.client.post<{
        portConflicts: Array<{ port: number; usedBy: string }>
        resourceWarnings: string[]
        blocked: string[]
      }>('/system/services/preflight-custom', payload)
      return response.data
    })()
  }

  async createCustomApp(payload: {
    friendly_name: string
    image: string
    ports?: Array<{ container: number; host: number }>
    volumes?: Array<{ host_path: string; container_path: string }>
    env?: string[]
    category?: string
    icon?: string
    memory_mb?: number
    cpus?: number
    force?: boolean
  }) {
    return catchInternal(async () => {
      const response = await this.client.post<{
        success: boolean
        message: string
        service_name: string
      }>('/system/services/custom', payload)
      return response.data
    })()
  }

  async setServiceCustomUrl(service_name: string, custom_url: string | null) {
    return catchInternal(async () => {
      const response = await this.client.put<{ success: boolean; custom_url: string | null }>(
        '/system/services/custom-url',
        { service_name, custom_url }
      )
      return response.data
    })()
  }

  async deleteCustomApp(service_name: string, remove_image = false) {
    return catchInternal(async () => {
      const response = await this.client.delete<{ success: boolean; message: string }>(
        '/system/services/custom',
        { data: { service_name, remove_image } }
      )
      return response.data
    })()
  }

  async uninstallService(service_name: string, remove_image = false) {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/services/uninstall',
        { service_name, remove_image }
      )
      return response.data
    })()
  }

  async updateCustomAppImage(service_name: string) {
    return catchInternal(async () => {
      const response = await this.client.post<{ success: boolean; message: string }>(
        '/system/services/custom/update',
        { service_name }
      )
      return response.data
    })()
  }

  async getServiceLogs(service_name: string, tail = 200) {
    return catchInternal(async () => {
      const response = await this.client.get<{ success: boolean; logs: string }>(
        `/system/services/${service_name}/logs`,
        { params: { tail } }
      )
      return response.data
    })()
  }

  async getServiceStats(service_name: string) {
    return catchInternal(async () => {
      const response = await this.client.get<{
        success: boolean
        running: boolean
        stats: {
          cpuPercent: number
          memUsageBytes: number
          memLimitBytes: number
          memPercent: number
        } | null
      }>(`/system/services/${service_name}/stats`)
      return response.data
    })()
  }

  async getCustomApp(service_name: string) {
    return catchInternal(async () => {
      const response = await this.client.get<{
        success: boolean
        app: {
          service_name: string
          friendly_name: string | null
          image: string
          category: string
          icon: string
          ports: Array<{ container: number; host: number }>
          volumes: Array<{ host_path: string; container_path: string }>
          env: string[]
          memory_mb?: number
          cpus?: number
        }
      }>(`/system/services/custom/${service_name}`)
      return response.data
    })()
  }

  async updateCustomApp(payload: {
    service_name: string
    friendly_name: string
    image: string
    ports?: Array<{ container: number; host: number }>
    volumes?: Array<{ host_path: string; container_path: string }>
    env?: string[]
    category?: string
    icon?: string
    memory_mb?: number
    cpus?: number
    force?: boolean
  }) {
    return catchInternal(async () => {
      const response = await this.client.put<{
        success: boolean
        message: string
        service_name: string
      }>('/system/services/custom', payload)
      return response.data
    })()
  }
}

export default new API()