Skip to content

TypeScript API

Jean-Baptiste THERY edited this page Jul 14, 2026 · 7 revisions

TypeScript API

Ragmir publishes three ESM packages for Node.js 20 or later:

Package Use it for
@jcode.labs/ragmir Index and retrieve cited project evidence
@jcode.labs/ragmir-chat Generate a cited answer from supplied passages with a local GGUF model
@jcode.labs/ragmir-tts Render reviewed text as local WAV or explicit online MP3 audio

Use the CLI or MCP server when an agent only needs evidence. Use these APIs when a Node.js process owns the workflow. All project paths resolve from cwd or the current working directory. With the default local-hash provider, Core indexes and retrieves private files locally and offline. Only passages a caller explicitly hands to an external consumer cross that boundary.

Core retrieval

import { ingest, search, type SearchOptions } from "@jcode.labs/ragmir"

const cwd = process.cwd()
await ingest({ cwd })

const options: SearchOptions = { cwd, topK: 5, explain: true }
const results = await search("Which decision changed the rollout?", options)

Results include relativePath, citation, chunkIndex, exact text, line ranges, page ranges when available, structural context, and optional score explanations.

Resumable ingestion

import { getIngestionProgress, ingest, loadConfig } from "@jcode.labs/ragmir"

const cwd = process.cwd()
await ingest({
  cwd,
  batchSize: 10,
  onProgress(progress) {
    console.log(progress.indexedFiles, progress.totalFiles)
  },
})

const progress = await getIngestionProgress(await loadConfig(cwd))
console.log(progress?.runId, progress?.status, progress?.resumed)

IngestOptions.batchSize defaults to 25 files. onProgress receives durable progress after state transitions. A later ingest call resumes a compatible interrupted run and reconciles files already written to the index before doing more parsing or embedding. rebuild: true uses an isolated table generation and activates it only after validation.

Persistent client

Use one persistent client per project root when a stateful Node.js process performs repeated retrieval:

import { createRagmirClient, isRagmirError } from "@jcode.labs/ragmir"

const controller = new AbortController()
const ragmir = await createRagmirClient({ cwd: process.cwd() })

try {
  await ragmir.ingest({ signal: controller.signal, timeoutMs: 120_000 })
  const results = await ragmir.search("release approval", {
    topK: 5,
    signal: controller.signal,
    timeoutMs: 10_000,
  })
  console.log(results.map(({ citation }) => citation))
} catch (error) {
  if (isRagmirError(error)) console.error(error.code, error.retryable)
  else throw error
} finally {
  await ragmir.close()
}

The client exposes ingest, search, ask, research, expandCitation, status, sources, and an idempotent close. It reuses one local LanceDB connection, serializes ingestion for the same index inside one Node.js process, and waits for active operations before closing. Use the top-level functions for one-shot scripts.

signal and timeoutMs are available on ingestion, search, ask, research, and citation expansion. Client failures use RagmirError with stable ABORTED, CLIENT_CLOSED, INTERNAL, INVALID_ARGUMENT, or TIMEOUT codes. Cancellation is cooperative between operation phases.

Ragmir targets a stateful Node.js process with a local filesystem. It does not provide an HTTP listener or a fixed port. A network-facing application owns authentication, authorization, rate limits, and transport security.

Main Core operations

Area Exports
Project and sources initProject, setupProject, loadConfig, knowledgeBaseIdentity, discoverKnowledgeBases, getKnowledgeBaseContext, getKnowledgeBaseSourceCatalog, listSourceEntries, addSourceEntries
Index and retrieve ingest, getIngestionProgress, audit, previewChunks, search, ask, research, expandCitation, compactSearchResults, compactResearchReport, evaluateGoldenQueries
Operations doctor, securityAudit, ingestionLimits, accessLogUsageReport, destroyIndex, redactText, routePrompt
Optional local capabilities enableSemanticEmbeddings, pullEmbeddingModel, clearTransformersCache, inspectPdfOcr, configurePdfOcr, extractPdfPage
Integrations createMcpServer, connectMcpServer, serveMcp, installAgentSkills, installSkill, inspectAgentIntegration, parseAgentTargets, rgrCommand

Core exports named option and result types for every public signature, including RagmirClientOptions, OperationOptions, RagmirErrorCode, IngestOptions, IngestResult, IngestionProgress, IngestionFileStage, IngestionRunMode, IngestionRunStatus, SearchOptions, EnableSemanticEmbeddingsResult, PullEmbeddingModelResult, and RedactionCount.

Local Chat

import { generateChatAnswer, type ChatSource } from "@jcode.labs/ragmir-chat"

const sources: ChatSource[] = [
  {
    relativePath: "docs/rollout.md",
    chunkIndex: 0,
    text: "The rollout moved from Friday to Monday after the review.",
  },
]

const result = await generateChatAnswer({
  question: "What changed?",
  profile: "lite",
  sources,
})

Use setupChatModel once, then generateChatAnswer for normal generation. doctor and modelCacheExists verify local readiness. Advanced exports cover custom runtimes, the line-delimited JSON server, model verification, prompt construction, and citation validation. Normal generation never enables remote model resolution.

TTS

import { renderSpeech } from "@jcode.labs/ragmir-tts"

await renderSpeech({
  cwd: process.cwd(),
  text: "Non-sensitive model preload text.",
  outputPath: "/tmp/ragmir-tts-preload.wav",
  engine: "transformers",
  language: "en",
  allowRemoteModels: true,
})

const result = await renderSpeech({
  cwd: process.cwd(),
  textFile: ".ragmir/reports/release-brief.md",
  outputPath: ".ragmir/audio/release-brief.wav",
  engine: "transformers",
  language: "en",
  allowRemoteModels: false,
})

renderSpeech renders caller-supplied text. It does not retrieve evidence or create a summary. The first call explicitly prepares the model with non-sensitive text. Later calls can keep allowRemoteModels: false for confidential content. doctor, isTtsLanguage, mmsModelForLanguage, edgeVoiceForLanguage, and modelCacheExists support runtime inspection and custom integrations.

The complete list of runtime exports, constants, option types, and result types is versioned in the canonical API reference.

Clone this wiki locally