Skip to content

TypeScript API

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

TypeScript API

Ragmir publishes three ESM packages for Node.js 22 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. Older generated tables remain available for searches that already opened them; destroyIndex removes all generated index storage.

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 and waits for active operations before closing. Ragmir also serializes writers across local OS processes with a private heartbeat lock under storageDir; this is not a distributed lock for a shared network filesystem. Use the top-level functions for one-shot scripts.

signal and timeoutMs are available on client retrieval, ingestion, status, and source-catalog operations, and on the corresponding diagnostic and evaluation functions that may scan local state. 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
Team and upgrades syncTeamKnowledge, createTeamSnapshot, writeTeamSnapshot, readTeamSnapshot, compareTeamSnapshots, inspectUpgrade, upgradeProject
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.

syncTeamKnowledge({ cwd }) fetches the current upstream, applies only a safe fast-forward, and refreshes the local index. Options expose check-only, no-pull, no-fetch, strict, timeout, and progress behavior. The report separates Git and index state so automation can explain one safe next action without rewriting branch history or discarding the last valid index.

createTeamSnapshot and its file helpers expose the advanced metadata-only team workflow. TeamSnapshot.ready describes operational index readiness. TeamComparison.securityAdvisories reports local and peer privacy-warning counts separately, so advisory-only differences do not prevent status: "synchronized". compareTeamSnapshots accepts existing v2.19 snapshots and derives their operational state from stored corpus and health fields without a schema migration.

inspectUpgrade previews compatibility; upgradeProject refreshes helpers and safely ingests or rebuilds before the new runtime accepts retrieval. A long-running host can keep its already loaded runtime serving until the result reports status: "current" and ready: true. The result keeps independent privacy follow-ups in privacyCompliant and advisories.

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. Rendering accepts an AbortSignal; Edge rendering also accepts edgeTimeoutMs and defaults to DEFAULT_EDGE_TTS_TIMEOUT_MS. 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