/ API Reference
v1.0.0

Kyro API

Self-hosted RAG API. Upload documents, embed them locally, and ask questions grounded in your own files — no data leaves your server.

Default URL http://localhost:3000/api/v1
License ISC (api) · MIT (SDK)
Spec format OpenAPI 3.0.3
Auth X-Api-Key

How to use Kyro

Kyro gives you three ways to interact with your documents — pick whichever fits your workflow. All three talk to the same backend running on your server.

01 no code

Dashboard

A web UI built into Kyro. Upload files, manage collections, create API keys, view usage analytics, and ask questions — all without writing any code. Best for non-technical teammates or quick one-off tasks.

Dashboard guide →
03 advanced

HTTP API

Raw REST endpoints — useful if you're building in a language other than TypeScript, scripting with curl, or need direct control over request shape and headers.

HTTP reference →

Dashboard

Kyro ships with a built-in web dashboard available at the root of your instance (e.g. http://localhost:3000). It's the fastest way to get started — no API calls required.

01

Register your organisation

On first run, navigate to your instance URL and register. This creates your organisation and owner account. Subsequent users are invited from the Settings page — the registration page locks after the first org is created.

02

Create an API key

Go to API Keys in the sidebar and create a key with the scopes you need. The full key is shown once — copy it immediately. You'll need it to use the SDK or HTTP API.

scopes
read   — list and download files, search, ask questions
write  — upload, delete and reprocess files; manage collections
03

Upload and manage files

The Files page lets you drag-and-drop uploads, track pipeline status per file, download originals, and add files to collections. Extraction and embedding run automatically — failed files can be re-run from the file row.

04

Organise with Collections

Collections group files so you can scope search and /ask to a specific set of documents — a matter, a product, a project. Create a collection, add files, and use its ID in the SDK or API to limit context.

05

Ask questions

The Ask page is a chat interface wired to the /ask endpoint. Select a scope (whole org or a specific collection), type a question, and get a streamed answer with source citations — no code required. Useful for testing retrieval quality before building your own UI.

06

Monitor usage

The Usage page shows total requests, data in/out, storage consumed, and a daily request chart. Switch between 7, 30, and 90-day windows to track trends.

ℹ
Dashboard vs API key scope — The dashboard authenticates with a session cookie (JWT). The API key is a separate credential used by the SDK and HTTP API. You manage API keys from the dashboard but use them outside it.
typescript sdk

TypeScript SDK

@kyroinfra/kyro is the official client library for Node.js and the browser. It wraps every HTTP endpoint with typed methods, handles streaming SSE responses, and throws structured errors you can catch and branch on. Current major version: 2.0.0.

Package @kyroinfra/kyro
Latest version 2.0.0
Install npm i @kyroinfra/kyro
Environments Node.js · Browser · Edge
Default API version v1
shell
npm i @kyroinfra/kyro
typescript
import { KyroClient } from "@kyroinfra/kyro";

const kyro = new KyroClient({ 
  baseURL: "http://localhost:3000/api/v1",
  apiKey:  "kyro_live_...",
});

// Upload a file — extraction + embedding run automatically
const file = await kyro.files.upload(blob, "report.pdf");

// Poll until the file is queryable (files.status)
const { status } = await kyro.files.getText(file.id);
// status: "pending" | "processing" | "ready" | "failed" | "skipped"

Typical workflow

End-to-end: upload → tag → organize → ask.

typescript
// 1. Upload — pipeline runs automatically (extract → chunk → embed)
const file = await kyro.files.upload(pdfBlob, "agreement.pdf");

// 2. Tag with metadata
await kyro.files.setMetadata(file.id, { 
  document_type: "contract",
  matter_number: "M-2024-001",
});

// 3. Add to a collection
await kyro.collections.addFiles(collectionId, { fileIds: [file.id] });

// 4. Poll until the file is queryable
let { status } = await kyro.files.getText(file.id);
while (status !== "ready") { 
  await new Promise(r => setTimeout(r, 2000));
  ({ status } = await kyro.files.getText(file.id));
}

// 5. Ask — grounded answer with source citations
const { answer, sources } = await kyro.ask({
  question:     "What are the termination conditions?",
  collectionId: collectionId,
});

SDK · Files

All file operations live on kyro.files. The ingest pipeline (extract → chunk → embed) runs automatically on upload — failed files re-run via kyro.files.reprocess(), and search/ask are client methods (kyro.search, kyro.ask, kyro.askStream — see SDK · Search & Ask).

kyro.files.upload(blob, filename)

Upload a file. Returns the file record including its ID and initial status. PDF, DOCX and TXT are extracted; CSV and JSON are stored with status "skipped"; other types are rejected with 415.

typescript
const file = await kyro.files.upload(blob, "contract.pdf");
// file.id, file.status
kyro.files.list(limit?, cursor?)

Paginated file list. Pass pagination.nextCursor as the cursor argument to fetch the next page.

typescript
const { data, pagination } = await kyro.files.list(50);
if (pagination.hasMore) {
  const next = await kyro.files.list(50, pagination.nextCursor);
}
kyro.files.download(fileId)

Download the original file as a Blob.

typescript
const blob = await kyro.files.download(fileId);
kyro.files.delete(fileId)

Delete a file permanently — the record, its chunks, metadata and collection memberships, and the blob on disk all go. There is no soft-delete.

typescript
await kyro.files.delete(fileId);\n// { message: "File deleted", id }
kyro.files.getText(fileId)

Get the file's pipeline status and extracted text. Poll this after upload to know when the file is queryable.

typescript
const { status, extractedText } = await kyro.files.getText(fileId);
// status: "pending" | "processing" | "ready" | "failed" | "skipped"
kyro.files.reprocess(fileId)

Set the file back to "pending" and re-run the full pipeline (extract → chunk → embed). Use after a failure — or to pick up a new extractor.

typescript
await kyro.files.reprocess(fileId);
// Sets the file back to "pending" and re-runs extraction + embedding
kyro.files.setMetadata(fileId, meta)

Upsert arbitrary key-value metadata on a file. Non-destructive — keys not in the payload are left untouched.

typescript
await kyro.files.setMetadata(fileId, {
  matter_number: "M-2024-001",
  document_type: "contract",
});
kyro.files.getMetadata(fileId)

Return all metadata keys and values for a file.

typescript
const meta = await kyro.files.getMetadata(fileId);
kyro.files.deleteMetadataKey(fileId, key)

Remove a single metadata key.

typescript
await kyro.files.deleteMetadataKey(fileId, "counterparty");

SDK · Collections

All collection operations live on kyro.collections. A collection is a named group of files — scope search and /ask to it by passing its ID.

kyro.collections.create({ name, description? })

Create a new collection. Name is required (1–255 chars); description is optional (up to 2000 chars). Duplicate names within an org are allowed.

typescript
const col = await kyro.collections.create({
  name:        "Q4 Contracts",
  description: "All contracts signed in Q4 2024",
});
kyro.collections.list()

List all collections. Each item includes fileCount, embeddedCount, pendingCount, and failedCount.

typescript
const collections = await kyro.collections.list();
kyro.collections.get(collectionId)

Get a collection with full status. col.queryReady is true when all files are embedded.

typescript
const col = await kyro.collections.get(collectionId);
// col.queryReady — true when ready to search
kyro.collections.update(collectionId, { name?, description? })

Update collection name or description.

typescript
await kyro.collections.update(collectionId, { name: "Q4 Agreements" });
kyro.collections.delete(collectionId)

Delete a collection. Does not delete the files themselves.

typescript
await kyro.collections.delete(collectionId);
kyro.collections.addFiles(collectionId, { fileIds })

Add up to 100 files to a collection in one call.

typescript
await kyro.collections.addFiles(collectionId, {
  fileIds: [fileId1, fileId2],
});
kyro.collections.listFiles(collectionId, limit?, offset?)

List files in a collection, offset-paginated. Each row carries the file's unified pipeline status.

typescript
const { data, pagination } = await kyro.collections.listFiles(collectionId, 20, 0);
// offset-paginated: pagination is { total, limit, offset, hasMore }
// data[i].status — per-file pipeline status
kyro.collections.removeFile(collectionId, fileId)

Remove a file from a collection without deleting it.

typescript
await kyro.collections.removeFile(collectionId, fileId);

SDK · Search & Ask

Retrieval and question answering are client methods. Scope with collectionId or fileIds — passing both throws a client-side TypeError before any request — or omit both for org-wide. filters (AND across keys, OR across values) combines with either scope.

kyro.search({ query })

Hybrid retrieval — pgvector cosine fused with ts_rank via Reciprocal Rank Fusion (k = 60). Returns chunk-level rows ranked by rrfScore: a small number, higher is better, no minimum-score filter. limit defaults to 10; the server caps it at 50.

typescript
const { data, query, limit } = await kyro.search({ query: "force majeure clause" });
// data[i]: { fileId, fileName, chunkIndex, content, rrfScore }
kyro.search({ query, collectionId | fileIds })

Scope to one collection or to specific files. The two are mutually exclusive — passing both throws before any request.

typescript
await kyro.search({
  query:        "termination rights",
  collectionId: collectionId,
});

await kyro.search({
  query:   "payment terms",
  fileIds: [fileId1, fileId2],
});
kyro.search({ query, filters })

Metadata filters: a single string is an exact match, an array is an OR match. AND across keys, OR across values — combinable with collectionId or fileIds.

typescript
const res = await kyro.search({
  query: "indemnification obligations",
  filters: {
    document_type: "contract",                     // exact match
    matter_number: ["M-2024-001", "M-2024-002"],   // OR match
  },
});
kyro.ask({ question })

Grounded answer with source citations. topK defaults to 8 (1–20); the question is 1–2000 chars. Sources carry fileId, fileName, chunkIndex, content and rrfScore.

typescript
const { answer, sources } = await kyro.ask({
  question:     "What is the total contract value across all agreements?",
  collectionId: collectionId,
});
// sources[i]: { fileId, fileName, chunkIndex, content, rrfScore }
kyro.ask({ question, history })

Follow-up questions: pass the last turns as history (max 10, content 1–2000 chars each). History is replayed to the LLM verbatim — read-only context that never affects retrieval.

typescript
const { answer } = await kyro.ask({
  question:     "Who are the parties?",
  collectionId: collectionId,
});

const followUp = await kyro.ask({
  question:     "Which of them indemnifies the other?",
  collectionId: collectionId,
  history: [
    { role: "user",      content: "Who are the parties?" },
    { role: "assistant", content: answer },
  ],
});
kyro.askStream({ question })

Streaming variant: an async iterable of SSE events. One sources frame opens the stream, chunk frames carry the answer text, done ends it, and error arrives in-band if the LLM fails after the stream is open.

typescript
for await (const event of kyro.askStream({ question: "Summarise the key risks." })) {
  switch (event.type) {
    case "sources": console.log("Sources:", event.sources); break;
    case "chunk":   process.stdout.write(event.text);       break;
    case "done":    console.log("\nDone");                  break;
    case "error":   console.error("Error:", event.message); break;
  }
}

Search & Ask — HTTP API

Retrieval and question answering live on the REST surface. Both accept X-Api-Key or Authorization: Bearer, and share the same scope rules: collectionId XOR fileIds, or org-wide when neither is given.

GET /api/v1/search

Ranked chunks without a generated answer — the same hybrid retrieval /ask uses: a ts_rank keyword arm fused with the pgvector cosine arm via Reciprocal Rank Fusion, optionally followed by cross-encoder reranking. Scope with collection_id or file_ids; filters takes a URL-encoded JSON object of metadata filters.

shell
curl "http://localhost:3000/api/v1/search?q=payment+terms&collection_id=c_xyz&limit=5" \
  -H "X-Api-Key: $API_KEY"
POST /api/v1/ask

Ask a natural language question and get an answer grounded in your documents, with source citations. stream: true (default) answers over Server-Sent Events; stream: false returns one JSON body.

non-streaming
const res = await fetch("http://localhost:3000/api/v1/ask", {
  method: "POST",
  headers: { "X-Api-Key": process.env.KYRO_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({ 
    question:     "What is the total contract value?",
    collectionId: collectionId,
    stream:       false,
  }),
});
const { answer, sources } = await res.json();

// sources[i]: { fileId, fileName, chunkIndex, content, rrfScore }
streaming (SSE)
const res = await fetch("http://localhost:3000/api/v1/ask", {
  method: "POST",
  headers: { "X-Api-Key": process.env.KYRO_KEY, "Content-Type": "application/json" },
  body: JSON.stringify({ question: "Summarise the risks." }),
});

for await (const event of parseSSE(res.body)) { 
  switch (event.type) { 
    case "sources": console.log(event.sources); break;
    case "chunk":   process.stdout.write(event.text); break;
    case "done":    console.log("\nDone"); break;
    case "error":   console.error(event.message); break;
  }
}
OptionTypeDefaultDescription
questionstring—The question to answer (1–2000 chars)
collectionIdstring—Scope to a collection. Mutually exclusive with fileIds
fileIdsstring[]—Scope to specific files (max 20). Mutually exclusive with collectionId
filtersobject—Metadata key-value filters. AND across keys, OR across values
topKnumber8Number of chunks to retrieve (1–20)
modelstringserver defaultOllama model override
streambooleantrueWhether to stream the response as SSE
historyarray—Up to 10 prior user/assistant turns for follow-ups — replayed to the LLM, never affects retrieval

SDK · Error Handling

All SDK methods throw typed errors. Import the specific class you want to catch — each maps to a distinct HTTP status code.

typescript
import {
  KyroApiError,
  KyroAuthError,
  KyroConflictError,
  KyroFileTooLargeError,
  KyroForbiddenError,
  KyroNotFoundError,
  KyroRateLimitError,
  KyroServiceUnavailableError,
  KyroStorageLimitError,
  KyroUnprocessableError,
  KyroUnsupportedMediaTypeError,
  KyroValidationError,
} from "@kyroinfra/kyro";

try {
  await kyro.files.upload(blob, "file.pdf");
} catch (err) {
  if (err instanceof KyroAuthError) {
    /* 401 — invalid or missing API key */ }
  else if (err instanceof KyroForbiddenError) {
    /* 403 — the API key lacks the required scope */ }
  else if (err instanceof KyroStorageLimitError) {
    /* 507 — deployment storage cap reached */ }
  else if (err instanceof KyroNotFoundError) {
    /* 404 — file or resource not found */ }
  else if (err instanceof KyroRateLimitError) {
    /* 429 — slow down; err.retryAfter is the wait in seconds */
    setTimeout(retry, err.retryAfter * 1000);
  }
  else if (err instanceof KyroValidationError) {
    /* 400 — bad input; err.details has per-field messages */
    console.error(err.details);
  }
  else if (err instanceof KyroConflictError) {
    /* 409 — a duplicate or conflicting resource */ }
  else if (err instanceof KyroFileTooLargeError) {
    /* 413 — upload exceeds the size limit */ }
  else if (err instanceof KyroUnsupportedMediaTypeError) {
    /* 415 — unsupported content type (err.data.supportedTypes) */ }
  else if (err instanceof KyroUnprocessableError) {
    /* 422 — the requested scope resolves to nothing */ }
  else if (err instanceof KyroServiceUnavailableError) {
    /* 503 — server busy or a degraded dependency */ }
  else if (err instanceof KyroApiError) {
    /* catch-all for anything unexpected */
    console.error(err.status, err.code, err.message);
  }
}
ClassHTTP statusWhen it's thrown
KyroValidationError400Bad input — err.details has per-field messages
KyroAuthError401Missing or invalid API key
KyroForbiddenError403The API key lacks the required scope
KyroNotFoundError404File, collection, or resource not found
KyroConflictError409The file's ingest pipeline is already running
KyroFileTooLargeError413Upload exceeds the 100 MB size limit
KyroUnsupportedMediaTypeError415Unsupported content type — err.data.supportedTypes lists what is accepted
KyroUnprocessableError422The requested scope resolves to nothing
KyroRateLimitError429Rate limit hit — err.retryAfter is seconds to wait
KyroServiceUnavailableError503Server busy or a degraded dependency
KyroStorageLimitError507Deployment storage cap reached
KyroApiErroranyCatch-all — err.status, err.code and err.message available

Self-hosting

Kyro runs entirely on your own infrastructure. Postgres (with pgvector) stores files, chunks and embeddings, the api runs the ingest pipeline and webhook delivery in-process, and Ollama runs your embedding and chat models locally. Nothing leaves your network.

01

Start the stack

One command brings up Postgres, nginx, the Kyro api, and the web dashboard — migrations run at api startup under a Postgres advisory lock.

shell
./scripts/prod.sh
02

Pull an Ollama model

Kyro uses nomic-embed-text for embeddings and llama3.2 for answering questions. Set OLLAMA_URL, EMBEDDING_MODEL, and CHAT_MODEL in your .env to use different models.

shell
ollama pull nomic-embed-text
ollama pull llama3.2
03

Create an account and API key

Register via POST /api/v1/auth/register (the first registration creates your organisation and owner), then create an API key from the dashboard or via POST /api/v1/keys. Keys carry one of two scopes.

scopes
read   — list and download files, search, ask questions
write  — upload, delete and reprocess files; manage collections

Authentication

One gate covers every org-scoped route: send either an X-Api-Key header or a Bearer JWT. An explicit X-Api-Key wins when both are present — it is the narrower credential. Key management (/auth, /org, /keys, /usage, /webhooks) uses the short-lived JWT obtained from /auth/login.

X-Api-Key header — file operations API Key
http
X-Api-Key: kyro_live_your_key_here
Authorization header — org & key management Bearer JWT
http
Authorization: Bearer <token from /auth/login>

RAG Pipeline

Every document goes through three stages before it can be queried. All processing runs on your server — no external API calls are made at any stage.

01

Upload

POST /files saves the file to disk and starts the in-process pipeline immediately — the file moves through pending → processing → ready (or failed, with the reason in files.error). Supported types: PDF, DOCX, TXT; CSV and JSON are stored without extraction (skipped).

02

Extract

The pipeline extracts text (PDF via unpdf, DOCX via mammoth), splits it into overlapping chunks (~1200 chars each), and stores them in Postgres. Poll GET /files/:id/text for status. Failed files re-run with POST /files/:id/reprocess.

03

Embed

Embedding is part of the same pipeline — no manual trigger. It calls your local Ollama embedding model (nomic-embed-text by default) and stores 768-dimensional vectors alongside each chunk in pgvector. When the file becomes queryable the terminal file.ready webhook fires (or file.failed if anything went wrong).

/ask — grounded answers

Send a question, get a cited answer. Kyro retrieves the most relevant chunks via hybrid search, builds a grounded prompt, and streams the response from your local LLM. The LLM only sees what is in your documents — it cannot fabricate facts from outside them.

Retrieval ts_rank + pgvector → RRF
Reranking Cross-encoder (opt-in)
Response SSE stream (or JSON)
Scope file IDs, collection, or entire org
typescript
const res = await fetch('/api/v1/ask', {
  method: 'POST',
  headers: { 'X-Api-Key': process.env.KYRO_KEY, 'Content-Type': 'application/json' },
  body: JSON.stringify({ 
    question: 'What are the payment terms?',
    collectionId: 'c_xyz',  // or fileIds: [...], or omit for org-wide
    topK: 8,
    stream: true,
  }),
});

for await (const event of parseSSE(res)) {
  if (event.type === 'sources')  console.log(event.sources);
  if (event.type === 'chunk')    process.stdout.write(event.text);
  if (event.type === 'done')     break;
}
SSE event typePayload
sourcesArray of retrieved chunks with file name, chunk index, content, and RRF score. Sent before the first answer token.
chunkA token fragment from the LLM. Accumulate these to build the full answer.
doneStream complete.
errorLLM or retrieval error. Includes a message field.

Metadata Filters

Every file can carry arbitrary key/value metadata — useful for tagging documents with vertical-specific fields like matter_number, document_type, product, or version. Set metadata with PUT /files/:id/metadata, then pass a filters object to /ask to scope retrieval.

set metadata
curl -X PUT http://localhost:3000/api/v1/files/3f1c2a4b-0000-0000-0000-000000000000/metadata \
  -H "X-Api-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{\"matter_number\": \"M-2024-001\", \"document_type\": \"contract\"}'
filter in /ask
{
  "question": "What are the termination clauses?",
  "filters": {
    "matter_number": "M-2024-001",
    "document_type": ["contract", "amendment"]
  }
}

Filters are AND across keys and OR across values. The example above matches files where matter_number is M-2024-001 and document_type is either contract or amendment.

Rate Limiting

The default limit is 100 requests per minute per API key, enforced by an in-memory sliding window inside each api process. It applies to the files, search and ask routes — collections is not rate-limited — and Bearer-JWT requests (which carry no API key) are keyed by client IP instead. Replicas do not share a budget — a documented trade-off of the no-Redis architecture. When the window is exhausted the api answers 429 with a retryAfter value in seconds.

100
requests / minute (default)
json
{
  "error": "Too many requests",
  "retryAfter": 42
}

Error Codes

Errors come in two shapes. Route handlers answer with the simple envelope; anything that reaches the central error handler returns the structured envelope (stack appears in development only).

json — simple envelope
{
  "error": "API key does not have write scope"
}
json — structured envelope
{
  "error": {
    "message": "Unsupported file type: application/zip"
  }
}
CodeLabelDescription
400Bad RequestInvalid input or missing required fields
401UnauthorizedMissing or invalid API key
403ForbiddenInsufficient scope for this operation — the key lacks the required read/write scope
404Not FoundResource does not exist
409ConflictThe file's ingest pipeline is already running
413Payload Too LargeFile exceeds the 100 MB size limit
415Unsupported Media TypeThe file's type is neither extractable (PDF, DOCX, TXT) nor storable without extraction (CSV, JSON)
422UnprocessableEmpty scope — the collection has no embedded files, no files match the metadata filters, or the intersection of all constraints is empty
429Too Many RequestsRate limit exceeded — the body carries retryAfter (seconds)
500Internal Server ErrorUnexpected server-side error
503Service UnavailableA dependency is degraded — typically the database (the health endpoint answers 503 when it is unreachable)
507Insufficient StorageDeployment storage limit reached
reference

HTTP API Reference

All endpoints documented below. Authenticate file and search operations with your API key in the X-Api-Key header (a Bearer JWT works too). Base URL defaults to http://localhost:3000/api/v1 — replace with whatever host you deployed Kyro on.

http
X-Api-Key: kyro_live_your_key_here

Auth

4 endpoints

Registration, login, session introspection and setup status.

POST /auth/register Register an organisation and its first owner
No auth

Request Body application/json

FieldTypeRequiredDescription
orgName string ✓
email string (email) ✓
password string ✓

Response Codes

201 Organisation and owner created; JWT issued.
400 Invalid input or email already registered.
403 Signup locked after the first organisation.
Request
curl -X POST \
  "http://localhost:3000/api/v1/auth/register" \
  -H "Content-Type: application/json" \
  -d '{
    "orgName": "\"orgName_value\"",
    "email": "\"email_value\"",
    "password": "\"password_value\""
  }'
Response 200
{
  "token": "eyJhbGciOi…",
  "user": {
    "id": "u_owner1",
    "email": "owner@example.com",
    "role": "owner",
    "orgId": "o_kyro"
  }
}
POST /auth/login Log in to an existing account
No auth

Request Body application/json

FieldTypeRequiredDescription
email string (email) ✓
password string ✓

Response Codes

200 Session token issued.
400 Invalid input.
401 Unknown email or wrong password.
Request
curl -X POST \
  "http://localhost:3000/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "\"email_value\"",
    "password": "\"password_value\""
  }'
Response 200
{
  "token": "eyJhbGciOi…",
  "user": {
    "id": "u_owner1",
    "email": "test@example.com",
    "role": "owner",
    "orgId": "o_kyro"
  }
}
GET /auth/me Current user
Bearer JWT

Response Codes

200 The authenticated user.
401 Missing or invalid token.
404 User no longer exists.
Request
curl -X GET \
  "http://localhost:3000/api/v1/auth/me" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
{
  "id": "u_owner1",
  "email": "test@example.com",
  "role": "owner",
  "orgId": "o_kyro"
}
GET /auth/setup-status Whether the deployment has been bootstrapped
No auth

Response Codes

200 Setup state.
500 Database outage, reported as unconfigured.
Request
curl -X GET \
  "http://localhost:3000/api/v1/auth/setup-status"
Response 200
{
  "configured": true
}

Organisation

4 endpoints

Workspace profile and member management (owner/admin actions).

GET /org Current organisation
Bearer JWT

Response Codes

200 The authenticated user's organisation.
401 Missing or invalid token.
404 Organisation not found.
Request
curl -X GET \
  "http://localhost:3000/api/v1/org" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
{
  "id": "o_kyro",
  "name": "Kyro",
  "slug": "kyro",
  "createdAt": "2026-01-10T09:00:00.000Z"
}
GET /org/members List members
Bearer JWT

Query Parameters

NameTypeRequiredDescription
limitinteger—Max results (default 50, max 100).
offsetinteger—Rows to skip (default 0).

Response Codes

200 Members of the org.
401 Missing or invalid token.
Request
curl -X GET \
  "http://localhost:3000/api/v1/org/members" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
{
  "data": [
    {
      "id": "u_1",
      "email": "owner@example.com",
      "role": "owner",
      "createdAt": "2026-01-10T09:00:00.000Z"
    },
    {
      "id": "u_2",
      "email": "member@example.com",
      "role": "member",
      "createdAt": "2026-01-12T10:20:00.000Z"
    }
  ],
  "pagination": {
    "total": 2,
    "limit": 50,
    "offset": 0,
    "hasMore": false
  }
}
POST /org/members Create a member
Bearer JWT

Request Body application/json

FieldTypeRequiredDescription
email string (email) ✓
password string ✓
role default: "member"string
adminmember
—

Response Codes

201 Member created.
400 Invalid input or email already in use.
401 Missing or invalid token.
403 Only the owner may create members.
Request
curl -X POST \
  "http://localhost:3000/api/v1/org/members" \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "email": "\"email_value\"",
    "password": "\"password_value\""
  }'
Response 200
{
  "id": "u_3",
  "email": "new@example.com",
  "role": "member"
}
DELETE /org/members/{id} Remove a member
Bearer JWT

Path Parameters

NameTypeRequiredDescription
iduuid✓Member user UUID.

Response Codes

204 Member removed.
401 Missing or invalid token.
403 Owners are irremovable; admins cannot remove admins.
404 Member not found.
Request
curl -X DELETE \
  "http://localhost:3000/api/v1/org/members/{id}" \
  -H "Authorization: Bearer $JWT_TOKEN"

API Keys

3 endpoints

Org-scoped API keys and their scopes.

GET /keys List API keys
Bearer JWT

Query Parameters

NameTypeRequiredDescription
limitinteger—Max results (default 50, max 100).
offsetinteger—Rows to skip (default 0).

Response Codes

200 The org's keys; the secret value is never returned here.
401 Missing or invalid token.
Request
curl -X GET \
  "http://localhost:3000/api/v1/keys" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
{
  "data": [
    {
      "id": "k_1",
      "name": "docs-exporter",
      "key_prefix": "kyro_live_abcd",
      "scopes": [
        "read"
      ],
      "last_used_at": "2026-02-01T08:00:00.000Z",
      "revoked_at": null,
      "created_at": "2026-01-15T11:00:00.000Z"
    }
  ],
  "pagination": {
    "total": 1,
    "limit": 50,
    "offset": 0,
    "hasMore": false
  }
}
POST /keys Create an API key
Bearer JWT

Request Body application/json

FieldTypeRequiredDescription
name string ✓
scopes default: ["read"]string[] —

Response Codes

201 Key created; key is the only copy of the secret.
400 Invalid input.
401 Missing or invalid token.
403 Owner or admin only.
Request
curl -X POST \
  "http://localhost:3000/api/v1/keys" \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "\"name_value\""
  }'
Response 200
{
  "id": "k_2",
  "name": "docs-exporter",
  "key_prefix": "kyro_live_wxyz",
  "scopes": [
    "read"
  ],
  "created_at": "2026-02-02T09:30:00.000Z",
  "key": "kyro_live_wxyz…full…value…"
}
DELETE /keys/{id} Revoke an API key
Bearer JWT

Path Parameters

NameTypeRequiredDescription
iduuid✓API key UUID.

Response Codes

200 Key revoked.
401 Missing or invalid token.
403 Owner or admin only.
404 Key unknown for the org or already revoked.
Request
curl -X DELETE \
  "http://localhost:3000/api/v1/keys/{id}" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
{
  "message": "API key revoked",
  "id": "k_2"
}

Usage

2 endpoints

Aggregate and per-day request/byte metrics.

GET /usage Usage summary
Bearer JWT

Query Parameters

NameTypeRequiredDescription
start_datedate—Window start (YYYY-MM-DD).
end_datedate—Window end (YYYY-MM-DD), inclusive whole day.

Response Codes

200 Aggregated usage.
401 Missing or invalid token.
Request
curl -X GET \
  "http://localhost:3000/api/v1/usage" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
{
  "total_requests": 1520,
  "total_bytes_in": 209715200,
  "total_bytes_out": 1048576000,
  "total_storage": 52428800,
  "active_api_keys": 3,
  "storage_limit": 107374182400
}
GET /usage/daily Daily usage series, newest first
Bearer JWT

Query Parameters

NameTypeRequiredDescription
start_datedate—Series start (YYYY-MM-DD).
end_datedate—Series end (YYYY-MM-DD), inclusive whole day.

Response Codes

200 One row per day with activity.
401 Missing or invalid token.
Request
curl -X GET \
  "http://localhost:3000/api/v1/usage/daily" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
[
  {
    "date": "2026-02-02",
    "requests": "42",
    "bytes_in": 5242880,
    "bytes_out": 26214400
  },
  {
    "date": "2026-02-01",
    "requests": "120",
    "bytes_in": 15728640,
    "bytes_out": 78643200
  }
]

Webhooks

6 endpoints

HTTP webhook subscriptions for file pipeline events.

GET /webhooks List webhooks, newest first
Bearer JWT

Response Codes

200 The org's webhooks (no secrets).
401 Missing or invalid token.
Request
curl -X GET \
  "http://localhost:3000/api/v1/webhooks" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
[
  {
    "id": "wh_1",
    "url": "https://ops.example.com/hooks/kyro",
    "events": [
      "file.ready",
      "file.failed"
    ],
    "enabled": true,
    "createdAt": "2026-01-20T08:00:00.000Z"
  }
]
POST /webhooks Create a webhook
Bearer JWT

Request Body application/json

FieldTypeRequiredDescription
url string (uri) ✓
events string[] ✓

Response Codes

201 Webhook created with its signing secret.
400 Invalid input.
401 Missing or invalid token.
403 Owner or admin only.
Request
curl -X POST \
  "http://localhost:3000/api/v1/webhooks" \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "url": "\"url_value\"",
    "events": "\"events_value\""
  }'
Response 200
{
  "id": "wh_2",
  "url": "https://ops.example.com/hooks/kyro",
  "events": [
    "file.ready"
  ],
  "enabled": true,
  "createdAt": "2026-02-02T09:40:00.000Z",
  "secret": "9f2c…64hex…"
}
PATCH /webhooks/{id} Update a webhook
Bearer JWT

Path Parameters

NameTypeRequiredDescription
iduuid✓Webhook UUID.

Request Body application/json

FieldTypeRequiredDescription
url string (uri) —
events string[] —
enabled default: trueboolean —

Response Codes

200 Updated webhook.
400 Invalid input.
401 Missing or invalid token.
403 Owner or admin only.
404 Webhook not found in the org.
Request
curl -X PATCH \
  "http://localhost:3000/api/v1/webhooks/{id}" \
  -H "Authorization: Bearer $JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{}'
Response 200
{
  "id": "wh_2",
  "url": "https://ops.example.com/hooks/kyro",
  "events": [
    "file.ready"
  ],
  "enabled": false
}
DELETE /webhooks/{id} Delete a webhook
Bearer JWT

Path Parameters

NameTypeRequiredDescription
iduuid✓Webhook UUID.

Response Codes

204 Webhook deleted.
401 Missing or invalid token.
403 Owner or admin only.
404 Webhook not found in the org.
Request
curl -X DELETE \
  "http://localhost:3000/api/v1/webhooks/{id}" \
  -H "Authorization: Bearer $JWT_TOKEN"
GET /webhooks/{id}/deliveries Delivery history for a webhook (latest 50)
Bearer JWT

Path Parameters

NameTypeRequiredDescription
iduuid✓Webhook UUID.

Response Codes

200 Recent delivery attempts, newest first.
401 Missing or invalid token.
404 Webhook not found in the org.
Request
curl -X GET \
  "http://localhost:3000/api/v1/webhooks/{id}/deliveries" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
[
  {
    "id": "whd_1",
    "event": "file.ready",
    "status": "delivered",
    "statusCode": 200,
    "attempts": 1,
    "lastAttemptAt": "2026-02-02T09:41:00.000Z",
    "createdAt": "2026-02-02T09:40:59.000Z"
  }
]
GET /webhooks/events Subscribable events
Bearer JWT

Response Codes

200 Event names with human descriptions.
401 Missing or invalid token.
Request
curl -X GET \
  "http://localhost:3000/api/v1/webhooks/events" \
  -H "Authorization: Bearer $JWT_TOKEN"
Response 200
{
  "events": [
    "file.ready",
    "file.failed"
  ],
  "descriptions": {
    "file.ready": "A file is queryable — its chunks are persisted and searchable.",
    "file.failed": "A file will never become queryable in this pass. Re-run via POST /files/:id/reprocess"
  }
}

Files

9 endpoints

Upload, download, delete, text, reprocess and metadata.

GET /files List files
X-Api-Key scope: read

Query Parameters

NameTypeRequiredDescription
limitinteger—Max results (default 100, max 100).
cursorstring—Opaque cursor from pagination.nextCursor of the previous page (base64url of {"createdAt","id"}).

Response Codes

200 Paginated file list, newest first. Failed rows additionally carry error.
400 Malformed or expired cursor.
401 Missing or invalid credentials.
Request
curl -X GET \
  "http://localhost:3000/api/v1/files" \
  -H "X-Api-Key: $API_KEY"
Response 200
{
  "data": [
    {
      "id": "f_1",
      "name": "contract.pdf",
      "mimeType": "application/pdf",
      "sizeBytes": 204800,
      "createdAt": "2026-02-01T12:00:00.000Z",
      "status": "ready"
    },
    {
      "id": "f_2",
      "name": "broken.pdf",
      "mimeType": "application/pdf",
      "sizeBytes": 4096,
      "createdAt": "2026-01-31T12:00:00.000Z",
      "status": "failed",
      "error": "PDF parse error"
    }
  ],
  "pagination": {
    "limit": 100,
    "hasMore": false,
    "nextCursor": null
  }
}
POST /files Upload file
X-Api-Key scope: write

Request Body multipart/form-data

FieldTypeRequiredDescription
file File (binary) ✓PDF, DOCX and TXT are extracted; CSV and JSON are stored as "skipped"; other types are rejected with 415.

Response Codes

201 File stored; the pipeline is queued for extractable types.
400 No file field in the multipart body.
401 Missing or invalid credentials.
403 Not write-scoped (`Required scope: write`).
413 File exceeds the 100 MB limit.
415 Unsupported file type.
507 Deployment storage limit reached.
Request
curl -X POST \
  "http://localhost:3000/api/v1/files" \
  -H "X-Api-Key: $API_KEY" \
  -F "file=@./your-file.pdf"
Response 200
{
  "id": "f_1",
  "name": "contract.pdf",
  "mimeType": "application/pdf",
  "sizeBytes": 204800,
  "createdAt": "2026-02-01T12:00:00.000Z",
  "status": "pending"
}
GET /files/{id} Download file
X-Api-Key scope: read

Path Parameters

NameTypeRequiredDescription
iduuid✓File UUID.

Response Codes

200 Binary file stream (attachment).
401 Missing or invalid credentials.
404 Unknown file, or the bytes are missing on disk.
Request
curl -X GET \
  "http://localhost:3000/api/v1/files/{id}" \
  -H "X-Api-Key: $API_KEY"
Response 200
Binary file stream (attachment).
DELETE /files/{id} Delete file
X-Api-Key scope: write

Path Parameters

NameTypeRequiredDescription
iduuid✓File UUID.

Response Codes

200 Deleted.
401 Missing or invalid credentials.
403 Not write-scoped.
404 File not found.
Request
curl -X DELETE \
  "http://localhost:3000/api/v1/files/{id}" \
  -H "X-Api-Key: $API_KEY"
Response 200
{
  "message": "File deleted",
  "id": "f_1"
}
GET /files/{id}/text Extracted text for a file
X-Api-Key scope: read

Path Parameters

NameTypeRequiredDescription
iduuid✓File UUID.

Response Codes

200 Extraction state and (where present) the text.
401 Missing or invalid credentials.
404 File not found.
Request
curl -X GET \
  "http://localhost:3000/api/v1/files/{id}/text" \
  -H "X-Api-Key: $API_KEY"
Response 200
{
  "fileId": "f_1",
  "status": "ready",
  "extractedText": "The payment terms are payable within 30 days…"
}
POST /files/{id}/reprocess Re-run the pipeline for a file
X-Api-Key scope: write

Path Parameters

NameTypeRequiredDescription
iduuid✓File UUID.

Response Codes

202 Reprocess started.
400 Type with nothing to reprocess; supportedTypes lists accepted MIMEs.
401 Missing or invalid credentials.
403 Not write-scoped.
404 File not found.
409 Pipeline already in progress; body carries the current status.
Request
curl -X POST \
  "http://localhost:3000/api/v1/files/{id}/reprocess" \
  -H "X-Api-Key: $API_KEY"
Response 200
{
  "fileId": "f_1",
  "status": "pending",
  "message": "Reprocessing queued. Poll GET /files/:id/text for status."
}
GET /files/{id}/metadata File metadata
X-Api-Key scope: read

Path Parameters

NameTypeRequiredDescription
iduuid✓File UUID.

Response Codes

200 Flat metadata map.
401 Missing or invalid credentials.
404 File not found.
Request
curl -X GET \
  "http://localhost:3000/api/v1/files/{id}/metadata" \
  -H "X-Api-Key: $API_KEY"
Response 200
{
  "document_type": "contract",
  "effective_date": "2026-01-01"
}
PUT /files/{id}/metadata Upsert file metadata
X-Api-Key scope: write

Path Parameters

NameTypeRequiredDescription
iduuid✓File UUID.

Request Body application/json

FieldTypeRequiredDescription

Response Codes

200 The upserted keys (the body, as stored).
400 Body is not a flat object of string values.
401 Missing or invalid credentials.
403 Not write-scoped.
404 File not found.
Request
curl -X PUT \
  "http://localhost:3000/api/v1/files/{id}/metadata" \
  -H "X-Api-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'
Response 200
{
  "document_type": "contract"
}
DELETE /files/{id}/metadata/{key} Delete one metadata key
X-Api-Key scope: write

Path Parameters

NameTypeRequiredDescription
iduuid✓File UUID.
keystring✓Metadata key.

Response Codes

204 Key removed (or was already absent).
401 Missing or invalid credentials.
403 Not write-scoped.
404 File not found.
Request
curl -X DELETE \
  "http://localhost:3000/api/v1/files/{id}/metadata/{key}" \
  -H "X-Api-Key: $API_KEY"

Collections

8 endpoints

Named groups of files queried as a unit.

GET /collections List collections, newest first
X-Api-Key scope: read

Response Codes

200 Collections with file-count roll-ups.
401 Missing or invalid credentials.
Request
curl -X GET \
  "http://localhost:3000/api/v1/collections" \
  -H "X-Api-Key: $API_KEY"
Response 200
[
  {
    "id": "c_1",
    "name": "Mergers",
    "description": "Deal documents",
    "createdAt": "2026-01-25T10:00:00.000Z",
    "updatedAt": "2026-02-01T10:00:00.000Z",
    "fileCount": 3,
    "embeddedCount": 2,
    "pendingCount": 1,
    "failedCount": 0
  }
]
POST /collections Create a collection
X-Api-Key scope: write

Request Body application/json

FieldTypeRequiredDescription
name string ✓
description string —

Response Codes

201 Collection created.
400 Invalid input.
401 Missing or invalid credentials.
Request
curl -X POST \
  "http://localhost:3000/api/v1/collections" \
  -H "X-Api-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "\"name_value\""
  }'
Response 200
{
  "id": "c_1",
  "name": "Mergers",
  "description": "Deal documents",
  "createdAt": "2026-01-25T10:00:00.000Z"
}
GET /collections/{id} Collection detail
X-Api-Key scope: read

Path Parameters

NameTypeRequiredDescription
iduuid✓Collection UUID.

Response Codes

200 The collection.
401 Missing or invalid credentials.
404 Collection not found.
Request
curl -X GET \
  "http://localhost:3000/api/v1/collections/{id}" \
  -H "X-Api-Key: $API_KEY"
Response 200
{
  "id": "c_1",
  "name": "Mergers",
  "description": "Deal documents",
  "createdAt": "2026-01-25T10:00:00.000Z",
  "updatedAt": "2026-02-01T10:00:00.000Z",
  "fileCount": 3,
  "embeddedCount": 2,
  "pendingCount": 1,
  "failedCount": 0,
  "skippedCount": 0,
  "queryReady": false
}
PATCH /collections/{id} Update a collection
X-Api-Key scope: write

Path Parameters

NameTypeRequiredDescription
iduuid✓Collection UUID.

Request Body application/json

FieldTypeRequiredDescription
name string —
description string —

Response Codes

200 Updated collection.
400 Invalid input.
401 Missing or invalid credentials.
403 Not write-scoped.
404 Collection not found.
Request
curl -X PATCH \
  "http://localhost:3000/api/v1/collections/{id}" \
  -H "X-Api-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{}'
Response 200
{
  "id": "c_1",
  "name": "Mergers 2026",
  "description": "Deal documents",
  "updatedAt": "2026-02-02T11:00:00.000Z"
}
DELETE /collections/{id} Delete a collection
X-Api-Key scope: write

Path Parameters

NameTypeRequiredDescription
iduuid✓Collection UUID.

Response Codes

204 Collection deleted.
401 Missing or invalid credentials.
403 Not write-scoped.
404 Collection not found.
Request
curl -X DELETE \
  "http://localhost:3000/api/v1/collections/{id}" \
  -H "X-Api-Key: $API_KEY"
GET /collections/{id}/files List a collection's files
X-Api-Key scope: read

Path Parameters

NameTypeRequiredDescription
iduuid✓Collection UUID.

Query Parameters

NameTypeRequiredDescription
limitinteger—Max results (default 100, max 100).
offsetinteger—Rows to skip (default 0).

Response Codes

200 Files in the collection, newest added first.
401 Missing or invalid credentials.
404 Collection not found.
Request
curl -X GET \
  "http://localhost:3000/api/v1/collections/{id}/files" \
  -H "X-Api-Key: $API_KEY"
Response 200
{
  "data": [
    {
      "id": "f_1",
      "name": "contract.pdf",
      "mimeType": "application/pdf",
      "sizeBytes": 204800,
      "status": "ready",
      "createdAt": "2026-02-01T12:00:00.000Z",
      "addedAt": "2026-02-01T12:05:00.000Z"
    }
  ],
  "pagination": {
    "total": 1,
    "limit": 100,
    "offset": 0,
    "hasMore": false
  }
}
POST /collections/{id}/files Add files to a collection
X-Api-Key scope: write

Path Parameters

NameTypeRequiredDescription
iduuid✓Collection UUID.

Request Body application/json

FieldTypeRequiredDescription
fileIds string (uuid)[] ✓

Response Codes

200 Files added.
400 Invalid input, or some file IDs are unknown/not org-owned (then invalidFileIds lists them).
401 Missing or invalid credentials.
403 Not write-scoped.
404 Collection not found.
Request
curl -X POST \
  "http://localhost:3000/api/v1/collections/{id}/files" \
  -H "X-Api-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "fileIds": "\"fileIds_value\""
  }'
Response 200
{
  "added": 3,
  "collectionId": "c_1"
}
DELETE /collections/{id}/files/{fileId} Remove a file from a collection
X-Api-Key scope: write

Path Parameters

NameTypeRequiredDescription
iduuid✓Collection UUID.
fileIduuid✓File UUID.

Response Codes

204 File removed from the collection.
401 Missing or invalid credentials.
403 Not write-scoped.
404 Collection unknown, or the file is not a member.
Request
curl -X DELETE \
  "http://localhost:3000/api/v1/collections/{id}/files/{fileId}" \
  -H "X-Api-Key: $API_KEY"

Ask

1 endpoint

RAG question answering with SSE streaming.

POST /ask Answer a question from retrieved context
X-Api-Key scope: read

Request Body application/json

FieldTypeRequiredDescription
question string ✓
fileIds string (uuid)[] —Scope to specific files (mutually exclusive with collectionId).
collectionId string (uuid) —Scope to one collection (mutually exclusive with fileIds).
filters object —Metadata filters, same shape as the /search query parameter (string or string[] values).
topK default: 8integer —
model string —Chat model override; defaults to the deployment's configured model.
stream default: trueboolean —
history object[] —Prior user/assistant turns for multi-turn conversations.

Response Codes

200 Answer as an SSE stream when the body requested streaming, or one JSON object otherwise.
400 Invalid input, or the endpoint is disabled (OLLAMA_URL unset).
401 Missing or invalid credentials.
403 Not read-scoped.
404 Unknown collection or no owned files among file_ids.
422 Empty collection, no filter match, or empty intersection.
Request
curl -X POST \
  "http://localhost:3000/api/v1/ask" \
  -H "X-Api-Key: $API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "question": "\"question_value\""
  }'
Response 200
// SSE stream:
data: {"type":"sources","sources":[{"fileId":"f_1","fileName":"contract.pdf","chunkIndex":3,"content":"The payment terms…","rrfScore":0.032}]}
data: {"type":"chunk","text":"According to [1], the payment terms…"}
data: {"type":"done"}

// stream: false → application/json:
{"answer":"According to [1], payment is due in 30 days.","sources":[{"fileId":"f_1","fileName":"contract.pdf","chunkIndex":3,"content":"The payment terms…","rrfScore":0.032}]}

Health

1 endpoint

Backend readiness of the deployment.

GET /health Backend health
No auth

Response Codes

200 Healthy.
503 Degraded (database unreachable).
Request
curl -X GET \
  "http://localhost:3000/api/v1/health"
Response 200
{
  "status": "ok",
  "uptime": 86400,
  "timestamp": "2026-02-02T12:00:00.000Z",
  "database": "connected"
}