AI agents

Give each client a separate index

Give each client's AI agent a separate index, because the engine ranks passages by relevance and can put another client's handbook first.

Consider staff at a joinery who ask their payroll bureau's AI agent an ordinary question, which is how much notice to give for annual leave. The agent can tell them four weeks, which is the rule at another of the bureau's clients, although the rule in their handbook is two weeks. Because all three handbooks are in one index, the engine ranks the sections of every client together. The other client's section contains the words 'notice' and 'annual leave' in its heading and in its body, so the engine scores it at 5.94 against 2.15 for the joinery's section.

The authors of a 2026 paper on multitenant enterprise retrieval explain that a retrieval system ranks by relevance alone, whether it matches keywords, vectors, or both, so an ordinary question can return the highest-scoring passage from another tenant (arXiv 2605.05287).

The model in each file is a mock that follows a fixed script, so every answer below has the same wording on any machine. Put a real model in its place when you want a model to choose the calls. Each code block below contains one whole file.

One index over every client

Every section here has a client field of type enum, so a filter on that field can remove the other clients' sections before the engine scores anything. However, the tool sets no filter, since an application built for one client has no need of one until a second client signs up.

import { createNarsil } from '@delali/narsil'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type HandbookHit, QUESTION, staffModel } from './mock-model.ts'
 
const narsil = await createNarsil()
 
await narsil.createIndex('handbooks', {
  schema: { client: 'enum', section: 'string', body: 'string' },
  language: 'english',
})
 
await narsil.insertBatch('handbooks', [
  {
    id: 'joinery-leave',
    client: 'joinery',
    section: 'Annual leave',
    body: 'Book annual leave through the workshop diary two weeks ahead, and the foreman confirms it the same day.',
  },
  {
    id: 'joinery-overtime',
    client: 'joinery',
    section: 'Overtime',
    body: 'Overtime on a Saturday pays time and a half, agreed with the foreman before the shift.',
  },
  {
    id: 'optics-firm-leave',
    client: 'optics-firm',
    section: 'Annual leave notice',
    body: 'Give four weeks of notice for annual leave of a week or more, and two weeks of notice for a single day of annual leave.',
  },
  {
    id: 'haulage-firm-leave',
    client: 'haulage-firm',
    section: 'Leave and rest days',
    body: 'A driver takes leave in blocks of seven days, agreed with the transport manager a month ahead.',
  },
])
 
const askFor = async (client: string): Promise<string> => {
  const staffAgent = new ToolLoopAgent({
    model: staffModel(),
    instructions: `Answer a member of staff at ${client} from the staff handbook.`,
    tools: {
      searchHandbook: tool({
        description: 'Search the staff handbook by what its text says.',
        inputSchema: z.object({ text: z.string() }),
        execute: async ({ text }: { text: string }): Promise<HandbookHit[]> => {
          const found = await narsil.query<HandbookHit>('handbooks', {
            term: text,
            document: { include: ['section', 'body'] },
            limit: 1,
          })
          return found.hits.map((hit) => hit.document)
        },
      }),
    },
  })
  const reply = await staffAgent.generate({ prompt: QUESTION })
  return reply.text
}
 
console.log(JSON.stringify({ question: QUESTION, joineryStaffHeard: await askFor('the joinery') }, null, 2))
 
await narsil.shutdown()
{
  "question": "How much notice do I give for annual leave?",
  "joineryStaffHeard": "Under 'Annual leave notice': Give four weeks of notice for annual leave of a week or more, and two weeks of notice for a single day of annual leave."
}

Staff at the joinery hear the optics firm's notice period, because the engine ranks the sections by the words in the question. The client field on each section changes the results only once a query filters on it.

Inside one trusted process, a filter is enough, because your code fills in the client identifier from an authenticated session. Once an AI agent queries the engine from outside the process, however, the filter protects each client only while every caller sends the right value in that field.

An index for each client

indexFor turns a client identifier into an index name. An index name can contain up to 255 letters, digits, dots, hyphens, and underscores, as long as it starts with a letter or a digit. Each AI agent's tool closes over the identifier of one client, which means that only your code sets the index name.

With one index for each client, you have to plan for the hundredth client and the thousandth. Two lifecycle settings limit the number of open indexes:

  • With lifecycle.idleTimeoutMs, the engine closes an index after that many milliseconds without activity.
  • With lifecycle.maxOpenIndexes, the engine closes the least recently used index whenever more than that many indexes are open.

The engine reopens a closed index at the next request to that index. The engine can close an index only when it has a durability directory, so without one, close throws CONFIG_INVALID with the message 'An index needs durability before it can close'. Set up the directory and those lifecycle settings with the steps in Persistence and durability.

import { createNarsil } from '@delali/narsil'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type HandbookHit, QUESTION, staffModel } from './mock-model.ts'
 
const CLIENTS = ['joinery', 'optics-firm', 'haulage-firm'] as const
 
type Client = (typeof CLIENTS)[number]
 
const indexFor = (client: Client): string => `handbook-${client}`
 
const narsil = await createNarsil()
 
await narsil.createIndex('handbooks', { 
  schema: { client: 'enum', section: 'string', body: 'string' }, 
  language: 'english', 
}) 
for (const client of CLIENTS) { 
  await narsil.createIndex(indexFor(client), {
    schema: { section: 'string', body: 'string' },
    language: 'english',
  })
}
 
await narsil.insertBatch('handbooks', [ 
const SECTIONS: Array<{ id: string; client: Client; section: string; body: string }> = [ 
  {
    id: 'joinery-leave',
    client: 'joinery',
    section: 'Annual leave',
    body: 'Book annual leave through the workshop diary two weeks ahead, and the foreman confirms it the same day.',
  },
  {
    id: 'joinery-overtime',
    client: 'joinery',
    section: 'Overtime',
    body: 'Overtime on a Saturday pays time and a half, agreed with the foreman before the shift.',
  },
  {
    id: 'optics-firm-leave',
    client: 'optics-firm',
    section: 'Annual leave notice',
    body: 'Give four weeks of notice for annual leave of a week or more, and two weeks of notice for a single day of annual leave.',
  },
  {
    id: 'haulage-firm-leave',
    client: 'haulage-firm',
    section: 'Leave and rest days',
    body: 'A driver takes leave in blocks of seven days, agreed with the transport manager a month ahead.',
  },
]) 
] 
 
for (const entry of SECTIONS) {
  await narsil.insert(indexFor(entry.client), { id: entry.id, section: entry.section, body: entry.body })
}
 
const askFor = async (client: string): Promise<string> => { 
const askFor = async (client: Client): Promise<string> => { 
  const staffAgent = new ToolLoopAgent({
    model: staffModel(),
    instructions: `Answer a member of staff at ${client} from the staff handbook.`,
    tools: {
      searchHandbook: tool({
        description: 'Search the staff handbook by what its text says.',
        inputSchema: z.object({ text: z.string() }),
        execute: async ({ text }: { text: string }): Promise<HandbookHit[]> => {
          const found = await narsil.query<HandbookHit>('handbooks', { 
          const found = await narsil.query<HandbookHit>(indexFor(client), { 
            term: text,
            document: { include: ['section', 'body'] },
            limit: 1,
          })
          return found.hits.map((hit) => hit.document)
        },
      }),
    },
  })
  const reply = await staffAgent.generate({ prompt: QUESTION })
  return reply.text
}
 
console.log(JSON.stringify({ question: QUESTION, joineryStaffHeard: await askFor('the joinery') }, null, 2)) 
console.log( 
  JSON.stringify(
    {
      question: QUESTION,
      indexes: narsil.listIndexes().map((index) => index.name),
      joineryStaffHeard: await askFor('joinery'),
      opticsFirmStaffHeard: await askFor('optics-firm'),
    },
    null,
    2
  )
)
 
await narsil.shutdown()
{
  "question": "How much notice do I give for annual leave?",
  "indexes": [
    "handbook-joinery",
    "handbook-optics-firm",
    "handbook-haulage-firm"
  ],
  "joineryStaffHeard": "Under 'Annual leave': Book annual leave through the workshop diary two weeks ahead, and the foreman confirms it the same day.",
  "opticsFirmStaffHeard": "Under 'Annual leave notice': Give four weeks of notice for annual leave of a week or more, and two weeks of notice for a single day of annual leave."
}

Staff at the joinery and at the optics firm each hear their notice period from one engine with three indexes. listIndexes() returns the indexes in that engine, so the bureau's staff can check whose handbooks are loaded.

Hold each token to one index over HTTP

createServer puts a REST API in front of the same engine. Before every request outside the health and discovery routes, the server calls onRequest with the method, the path, the headers keyed by lower-case name, and the peer address. Return undefined to let a request through, or a status, a code, and a message to refuse it.

The hook resolves the bearer token to a client, then compares the path with that client's index. When a request has one client's token and another client's index in its path, the server returns a 403 before the engine parses the body. TOKEN_HOLDERS is a literal in this file, whereas in production you can look the token up in the database that stores your client records.

The server needs uWebSockets.js installed alongside Narsil. Before you open an address, set the limits from the HTTP server page.

import { createNarsil } from '@delali/narsil'
import { createServer } from '@delali/narsil/server'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type HandbookHit, QUESTION, staffModel } from './mock-model.ts'
 
const CLIENTS = ['joinery', 'optics-firm', 'haulage-firm'] as const
 
type Client = (typeof CLIENTS)[number]
 
const indexFor = (client: Client): string => `handbook-${client}`
 
const TOKEN_HOLDERS: Record<string, Client> = { 
  'joinery-9f21': 'joinery',
  'optics-firm-4c07': 'optics-firm',
  'haulage-firm-71be': 'haulage-firm',
}
 
const narsil = await createNarsil()
 
for (const client of CLIENTS) {
  await narsil.createIndex(indexFor(client), {
    schema: { section: 'string', body: 'string' },
    language: 'english',
  })
}
 
const SECTIONS: Array<{ id: string; client: Client; section: string; body: string }> = [
  {
    id: 'joinery-leave',
    client: 'joinery',
    section: 'Annual leave',
    body: 'Book annual leave through the workshop diary two weeks ahead, and the foreman confirms it the same day.',
  },
  {
    id: 'joinery-overtime',
    client: 'joinery',
    section: 'Overtime',
    body: 'Overtime on a Saturday pays time and a half, agreed with the foreman before the shift.',
  },
  {
    id: 'optics-firm-leave',
    client: 'optics-firm',
    section: 'Annual leave notice',
    body: 'Give four weeks of notice for annual leave of a week or more, and two weeks of notice for a single day of annual leave.',
  },
  {
    id: 'haulage-firm-leave',
    client: 'haulage-firm',
    section: 'Leave and rest days',
    body: 'A driver takes leave in blocks of seven days, agreed with the transport manager a month ahead.',
  },
]
 
for (const entry of SECTIONS) {
  await narsil.insert(indexFor(entry.client), { id: entry.id, section: entry.section, body: entry.body })
}
 
const server = createServer(narsil, { 
  host: '127.0.0.1',
  port: 7711,
  onRequest: (request) => {
    const token = request.headers.authorization?.replace('Bearer ', '') ?? ''
    const client = TOKEN_HOLDERS[token]
    if (client === undefined) return { status: 401, code: 'UNAUTHORISED', message: 'Send a bureau token.' }
    if (request.path.startsWith(`/indexes/${indexFor(client)}/`)) return undefined
    return { status: 403, code: 'INDEX_FORBIDDEN', message: `That token reaches ${indexFor(client)} alone.` }
  },
})
 
await server.listen()
 
const search = (token: string, indexName: string, text: string): Promise<Response> =>
  fetch(`http://127.0.0.1:7711/indexes/${indexName}/search`, {
    method: 'POST',
    headers: { 'content-type': 'application/json', authorization: `Bearer ${token}` },
    body: JSON.stringify({ term: text, document: { include: ['section', 'body'] }, limit: 1 }),
  })
 
const askFor = async (client: Client): Promise<string> => { 
const askFor = async (token: string, client: Client): Promise<string> => { 
  const staffAgent = new ToolLoopAgent({
    model: staffModel(),
    instructions: `Answer a member of staff at ${client} from the staff handbook.`,
    tools: {
      searchHandbook: tool({
        description: 'Search the staff handbook by what its text says.',
        inputSchema: z.object({ text: z.string() }),
        execute: async ({ text }: { text: string }): Promise<HandbookHit[]> => {
          const found = await narsil.query<HandbookHit>(indexFor(client), { 
            term: text, 
            document: { include: ['section', 'body'] }, 
            limit: 1, 
          }) 
          return found.hits.map((hit) => hit.document) 
          const response = await search(token, indexFor(client), text) 
          const body = (await response.json()) as { hits?: Array<{ document: HandbookHit }> }
          return (body.hits ?? []).map((hit) => hit.document)
        },
      }),
    },
  })
  const reply = await staffAgent.generate({ prompt: QUESTION })
  return reply.text
}
 
const reachedAcross = await search('joinery-9f21', indexFor('optics-firm'), 'annual leave') 
 
console.log(
  JSON.stringify(
    {
      question: QUESTION,
      indexes: narsil.listIndexes().map((index) => index.name), 
      joineryStaffHeard: await askFor('joinery'), 
      opticsFirmStaffHeard: await askFor('optics-firm'), 
      joineryStaffHeard: await askFor('joinery-9f21', 'joinery'), 
      joineryTokenOnAnotherIndex: { status: reachedAcross.status, body: await reachedAcross.json() }, 
    },
    null,
    2
  )
)
 
await narsil.shutdown() 
await server.shutdown() 
{
  "question": "How much notice do I give for annual leave?",
  "joineryStaffHeard": "Under 'Annual leave': Book annual leave through the workshop diary two weeks ahead, and the foreman confirms it the same day.",
  "joineryTokenOnAnotherIndex": {
    "status": 403,
    "body": {
      "error": {
        "code": "INDEX_FORBIDDEN",
        "message": "That token reaches handbook-joinery alone."
      }
    }
  }
}

server.shutdown() closes the server and then shuts the engine down, so the process can exit.

  • 200POST /indexes/handbook-joinery/searchBearer joinery-9f21
  • 403POST /indexes/handbook-optics-firm/searchBearer joinery-9f21
  • 401POST /indexes/handbook-joinery/searchno authorization header
The hook compares the index name in each path with the index of the token's client, which is why the query body needs no client argument. The server calls the hook on every route except /livez, /readyz, /health, /version, and /capabilities.

Where to go next

  • Read The HTTP server for onRequest, the request limits, and the shutdown call to make before the process exits.
  • Read Persistence and durability for the durability directory and the lifecycle settings for idle indexes.
  • Read Record every search for a journal that records the index name with every search.