> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bijection.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Knowledge

> Find cited passages in your own facts, files and held texts with cited passages, from code, from a client or as an agent tool.

`@bijectionhq/library-retrieval` finds cited passages in an app's own facts, files
and held texts. `retrieval({ … })` returns a subtree you place in
your tree. It runs as your app, its tables are your tables at the corpus
label, and its embedding calls spend your model receiver's meter.

```ts bijection/knowledge.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { label, role, t, table } from "@bijectionhq/bijection";
import { openaiReceiver } from "@bijectionhq/pack-providers";
import { catalog, models } from "@bijectionhq/library-models";
import { chunker, retrieval, source } from "@bijectionhq/library-retrieval";

export const desk = label();
export const notes = table({ title: t.string, body: t.text() }, { label: desk });
export const manuals = table({ name: t.string, document: t.file }, { label: desk });
export const answers = table({ question: t.string, passages: t.json }, { label: desk });

// Sending chunk text to a provider is egress: the receiver clears `desk`.
export const openai = openaiReceiver({ label: desk });
export const ai = models({
  openai,
  catalog: catalog({
    small: {
      kind: "embedding",
      model: "openai/text-embedding-3-small",
      generation: "openai/text-embedding-3-small@1536",
      maxInputs: 256,
      dimensions: 1536,
      contextTokens: 8_191,
      price: { currency: "USD", inputPerMillionTokens: "0.02", asOf: "2026-11-19" },
    },
  }),
});

export const librarian = role({ clear: [desk] });
export const reader = role({ clear: [desk] });

export const docs = retrieval({
  label: desk,
  operators: [librarian],
  readers: [reader],
  ai,
  generations: { g1: { model: "small" } },
  generation: "g1",
  chunker: chunker({ maxChars: 1_600, overlap: 200 }),
  sources: {
    notes: source(notes, { text: (fact) => `${fact.title}\n\n${fact.body}`, search: "textBody" }),
    manuals: source(manuals, { file: (fact) => fact.document as never }),
    faq: source(),
  },
});
```

Place `desk`, the tables (`notes`, `manuals`, `answers`), `openai`, the roles and `docs` in the app tree.
After each deploy, an operator calls `docs.control.sync`.

## Options

| Option | Meaning |
| - | - |
| `label` | The required corpus label. Chunks and vectors are stored under it, never lower. Each source table is at or below it. |
| `operators` | Roles for `control.sync` and `control.retry`. |
| `readers` | Roles for `status.get`, `texts.get` and `asks.*`. Default the operators. |
| `writers` | Roles for `texts.put` and `texts.retract`. Default the operators. |
| `ai`, `generations`, `generation` | The models instance, each generation's embedding model, and the generation to serve. A new generation builds beside the active one and switches when it has caught up. |
| `sources` | 1 to 16 sources: `source(table, { text?, file?, search? })` over an app table, or `source()` for texts the instance holds by key. |
| `chunker`, `revision` | The deterministic chunker, and a revision to raise when an extractor's code changes. Either change re-chunks every source. |
| `cache` | An `embeddingCache` under the same label, so cached texts are not embedded again. |
| `every`, `pageRows` | The worker's cadence (default `{ seconds: 10 }`) and the changes it lands per source per pass (default 64). |
| `deliver` | The agents app's `engine.deliver`, for a deferred agent tool. |

A source over an app table follows the table's change log
(`table.changes.since(version)`). A source with `search` also ranks that
table's own declared text index, exactly at the head. Files are read through
bounded parsers: CSV, JSON, XML, `message/rfc822` and UTF-8 `text/*`. Other
types yield no text; extract them with external compute into a fact and index
that fact.

## Held texts

`source()` declares a source the instance holds itself, one text per app key.
Use it for text that lives nowhere else in your app:

| Function | Who | Does |
| - | - | - |
| `docs.texts.put({ source, key, title, text })` | writers | Make the held text at `key` be this. A blind write: it returns `null`. |
| `docs.texts.retract({ source, key })` | writers | Make `key` hold nothing, and retract its chunks and vectors. Blind: it returns `null`. |
| `docs.texts.get({ source, key })` | readers | One text's `TextState` in any source, by held key or app fact key, or `null`. |

`TextState` is `{ title, generation, state, chunks, embedded, pending, failed, refusal, revision }`,
with `state` one of `waiting`, `embedding`, `failed` and `ready`. A failed
embedding request keeps a refusal with its code and message. Use
`refusalText` from `@bijectionhq/bijection/client` to display it. `texts.put`
and `texts.retract` refuse `UnknownSource`, `NotHeld` (a source over an app
table), `InvalidKey` and `InvalidText`.

## Retrieve from code

`docs.retrieve` is a target. Submit it with a continuation. Every option is
required, and `null` takes its default:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { mutation, t } from "@bijectionhq/bijection";

export const ask = mutation(
  { under: desk, allow: [librarian], args: { question: t.string } },
  async (ctx, { question }) => {
    const args = { query: question, indexes: null, k: 6, hybrid: null, coverage: "wait" as const, wait: Temporal.Duration.from({ minutes: 1 }) };
    await ctx.submit(docs.retrieve, args, { once: ["ask", question], then: answered.with({ question }) });
    return null;
  },
);

export const answered = mutation(
  { under: desk, args: { question: t.string, result: t.result(docs.retrieve) } },
  async (ctx, { question, result }) => {
    if (result.ok && result.value.status === "ok") {
      await ctx.insert(answers, { question, passages: result.value.passages });
    }
    return null;
  },
);
```

| Option | Meaning |
| - | - |
| `indexes` | The sources to search. Default all. |
| `k` | Passages, 1 to 50. Default 8. |
| `hybrid` | `true` (default) fuses text and vector rankings with equal weight, `false` uses vectors only, and `{ text, vector }` sets the weights. |
| `coverage` | `partial` (default) returns what is embedded. `wait` waits up to `wait` milliseconds (default a minute, at most 15) for the generation to cover every change. `refuse` returns `building` when it does not. |

The result is a `Retrieved`:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import type { Version } from "@bijectionhq/bijection";
import type { Coverage, Passage } from "@bijectionhq/library-retrieval";

type Retrieved =
  | { status: "ok"; cut: Version; coverage: Coverage; approximate: boolean; passages: readonly Passage[] }
  | { status: "building"; code: "DerivativeBuilding"; cut: Version; coverage: Coverage }
  | { status: "failed"; detail: string };
```

A citation is `{ source, table, id, revision, file, chunk, chunker, start, end, digest }`.
The answering frame rereads the source under current authority. Its exact
read version is both `revision` and `cut`. To replay a passage while that
version is retained, reopen the fact and any cited File under current
authority. Match the File ID, SHA-256, size and media type, then run the
named extractor and chunker and verify the range and digest.

## Ask from a client

`asks.insert` takes the same arguments, submits `retrieve` and returns the
ask's key. `asks.get` reads it back: `{ args, asked, result }`, where
`result` is the `Retrieved` once settled. Only the asker reads an ask, and it
lives a day. Each read checks that the cited passages still match source
content the asker can read.

```ts bijection/app.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { app } from "@bijectionhq/bijection";
import { answers, desk, docs, librarian, manuals, notes, openai, reader } from "./knowledge";

export default app({ answers, desk, docs, librarian, manuals, notes, openai, reader });
```

```ts bijection/client.ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { api, connect } from "@bijectionhq/bijection/client";
import type app from "./app";

export async function refundPolicy(url: string, token: string) {
  const entries = api<typeof app>();
  const client = connect(url, { contract: "discover", token }).under(entries.desk);
  try {
    const asked = await client.mutate(
      entries.docs.asks.insert,
      { query: "refund policy", indexes: null, k: 6, hybrid: null, coverage: null, wait: null },
      { once: crypto.randomUUID() },
    );
    if (!asked.ok) return asked;
    for await (const read of client.watch(entries.docs.asks.get, { ask: asked.value })) {
      if (read.ok && read.value?.result) return read.value.result;
    }
  } finally {
    await client.close();
  }
}
```

In React, hold the insert with `useMutation(app.docs.asks.insert)` and the
answer with `useWatch(app.docs.asks.get, ask === null ? null : { ask })`.

## As an agent tool

Give the instance the agents app's `engine.deliver`, and offer a deferred
tool that starts a retrieval for the call. The `Retrieved` is delivered to
the turn:

```ts theme={"theme":{"light":"github-light-default","dark":"github-dark-default"}}
import { agents } from "@bijectionhq/app-agents";
import { deferred, toolbelt } from "@bijectionhq/app-agents/install";
import { retrieveArgs } from "@bijectionhq/library-retrieval";

const belt = toolbelt(desk, {
  search: deferred((ctx, input, call) => docs.beginCall(ctx, input, call), {
    description: "Search the desk's notes and manuals",
    input: retrieveArgs,
  }),
});
export const assistant = agents({ transcript: desk, tool: belt.dispatch, ask, settings });
export const docs = retrieval({ /* … */ deliver: assistant.engine.deliver });
```

The corpus and the transcript should share a label, so the delivery commits
under the transcript. The result includes as many complete cited passages
as fit in one tool message.

## Operate the index

| Function | Who | Does |
| - | - | - |
| `docs.control.sync({})` | operators | Install the sources, generations and worker after a deploy. |
| `docs.control.retry({ source })` | operators | Submit again the embedding requests held `failed` after four attempts: those of `source`, or every source's when `null`. Returns how many. Refuses `UnknownSource`. |
| `docs.status.get({})` | readers | Per source: phase, version landed through and error. Per generation: state, model, pending and failed requests. |

## Labels and erasure

Chunks and vectors are under the corpus label, so they carry its protection,
and the embedding receiver must clear that label. A change whose `after` is
`null` in a source's log (a delete, an expiry or an erasure) retracts the
fact's chunks and vectors in every generation when the worker lands it.
The worker also revisits independently retired Files. The answer path
checks facts and Files before returning passages.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.