AI agents

Record every search

Record every query and every preflight with one plugin on the engine, so that your journal includes the searches from every tool.

Assume that a grant-awarding trust's AI agent tells a community choir that it cannot apply to the building repair fund, and that eight months later the choir's trustees ask which passage of the guidance the AI agent used. The trust's log holds one line, which is the search that its searchGuidance tool records. The AI agent also counts the matching sections with a second tool, which writes nothing to the log, so the log holds only part of the retrieval behind the answer.

The authors of a 2026 position paper on auditable agents state their claim in one line: 'no agent system can be accountable without auditability'. They add that 'error paths, retries, fallbacks, approvals, and inter-agent handoffs are often missing or weakly represented' in the records of agent systems (arXiv 2604.05485). When your code never logs a search, the record has the same kind of gap, because the engine answers the search while your code records none of it.

A mock model with a fixed script produces each answer below, so the journals are identical every time that you execute the file. Put a real model in the same place when you want it to choose the calls. Each code block below holds one whole file.

A journal that one tool writes

searchGuidance pushes an entry before it queries, while countGuidance pushes nothing, because its code has no such line. reply.steps holds the calls that the model makes, so the program prints the names of the tools that the model calls next to the journal.

import { createNarsil } from '@delali/narsil'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type GuidanceHit, QUESTION, trustModel } from './mock-model.ts'
 
const narsil = await createNarsil()
 
await narsil.createIndex('grant_guidance', {
  schema: { programme: 'enum', section: 'string', body: 'string' },
  language: 'english',
})
 
await narsil.insertBatch('grant_guidance', [
  {
    id: 'repair-eligibility',
    programme: 'building-repair',
    section: 'Who may apply to the building repair fund',
    body: 'The building repair fund is open to a charity or a community group that holds the freehold or a lease of at least fifteen years on the building it repairs.',
  },
  {
    id: 'repair-excluded-work',
    programme: 'building-repair',
    section: 'Work the building repair fund excludes',
    body: 'The fund pays for structural repair, roofing, and damp work, and it pays for no redecoration, furniture, or musical equipment.',
  },
  {
    id: 'performance-eligibility',
    programme: 'performance',
    section: 'Who may apply to the performance fund',
    body: 'The performance fund is open to a choir, an orchestra, or a theatre company that has performed in public in the last two years.',
  },
  {
    id: 'reporting',
    programme: 'all',
    section: 'Reporting on a grant',
    body: 'Every grant holder sends a report within three months of the final payment, with receipts for each item above 500 pounds.',
  },
])
 
interface JournalEntry {
  tool: string
  term: string
}
 
const journal: JournalEntry[] = []
 
const trustTools = {
  countGuidance: tool({
    description: 'Count the guidance sections that match some words, without reading them.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<number> => {
      const counted = await narsil.preflight('grant_guidance', { term: text })
      return counted.count
    },
  }),
  searchGuidance: tool({
    description: 'Search the grant guidance by what its text says.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<GuidanceHit[]> => {
      journal.push({ tool: 'searchGuidance', term: text })
      const found = await narsil.query<GuidanceHit>('grant_guidance', {
        term: text,
        document: { include: ['section', 'body'] },
        limit: 1,
      })
      return found.hits.map((hit) => hit.document)
    },
  }),
}
 
const askTrustAgent = async (): Promise<{ answer: string; toolsCalled: string[] }> => {
  const agent = new ToolLoopAgent({
    model: trustModel(),
    instructions: 'Answer the applicant from the grant guidance.',
    tools: trustTools,
  })
  const reply = await agent.generate({ prompt: QUESTION })
  const toolsCalled: string[] = []
  for (const step of reply.steps) {
    for (const call of step.toolCalls) toolsCalled.push(call.toolName)
  }
  return { answer: reply.text, toolsCalled }
}
 
const asked = await askTrustAgent()
 
console.log(
  JSON.stringify(
    { question: QUESTION, agentAnswered: asked.answer, toolsCalled: asked.toolsCalled, journal },
    null,
    2
  )
)
 
await narsil.shutdown()
{
  "question": "Can a community choir apply to the building repair fund?",
  "agentAnswered": "The building repair fund is open to a charity or a community group that holds the freehold or a lease of at least fifteen years on the building it repairs. That is the 'Who may apply to the building repair fund' section.",
  "toolsCalled": [
    "countGuidance",
    "searchGuidance"
  ],
  "journal": [
    {
      "tool": "searchGuidance",
      "term": "building repair eligibility"
    }
  ]
}

The AI agent calls two tools, while the journal holds one entry. You can add a line to countGuidance; however, the next tool that somebody writes will need the same line, because a journal kept this way stays complete only while the author of every tool remembers to write to it.

The plugins option of createNarsil takes hooks that the engine calls as it works. The engine calls afterSearch once a search returns, with a context that holds the index name, the query's parameters, and a copy of the results. One hook can therefore record the term and the hit ids of every query in the process.

The engine passes a copy so that a change inside afterSearch leaves the caller's result as it is. When the hook throws, the engine logs a warning and returns the results to the caller all the same, since the search is already over. A journal that has to be complete therefore needs writes that succeed, because the engine answers the query whether the hook succeeds or not.

import { createNarsil } from '@delali/narsil'
import { createNarsil, type NarsilPlugin } from '@delali/narsil'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type GuidanceHit, QUESTION, trustModel } from './mock-model.ts'
 
interface JournalEntry { 
  hook: string
  index: string
  term: string
  hits?: string[]
}
 
const journal: JournalEntry[] = []
 
const searchJournal: NarsilPlugin = {
  name: 'grant-search-journal',
  afterSearch: (ctx) => {
    journal.push({
      hook: 'afterSearch',
      index: ctx.indexName,
      term: ctx.params.term ?? '',
      hits: (ctx.results?.hits ?? []).map((hit) => hit.id),
    })
  },
}
 
const narsil = await createNarsil() 
const narsil = await createNarsil({ plugins: [searchJournal] }) 
 
await narsil.createIndex('grant_guidance', {
  schema: { programme: 'enum', section: 'string', body: 'string' },
  language: 'english',
})
 
await narsil.insertBatch('grant_guidance', [
  {
    id: 'repair-eligibility',
    programme: 'building-repair',
    section: 'Who may apply to the building repair fund',
    body: 'The building repair fund is open to a charity or a community group that holds the freehold or a lease of at least fifteen years on the building it repairs.',
  },
  {
    id: 'repair-excluded-work',
    programme: 'building-repair',
    section: 'Work the building repair fund excludes',
    body: 'The fund pays for structural repair, roofing, and damp work, and it pays for no redecoration, furniture, or musical equipment.',
  },
  {
    id: 'performance-eligibility',
    programme: 'performance',
    section: 'Who may apply to the performance fund',
    body: 'The performance fund is open to a choir, an orchestra, or a theatre company that has performed in public in the last two years.',
  },
  {
    id: 'reporting',
    programme: 'all',
    section: 'Reporting on a grant',
    body: 'Every grant holder sends a report within three months of the final payment, with receipts for each item above 500 pounds.',
  },
])
 
interface JournalEntry { 
  tool: string
  term: string
} 
 
const journal: JournalEntry[] = [] 
 
const trustTools = {
  countGuidance: tool({
    description: 'Count the guidance sections that match some words, without reading them.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<number> => {
      const counted = await narsil.preflight('grant_guidance', { term: text })
      return counted.count
    },
  }),
  searchGuidance: tool({
    description: 'Search the grant guidance by what its text says.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<GuidanceHit[]> => {
      journal.push({ tool: 'searchGuidance', term: text }) 
      const found = await narsil.query<GuidanceHit>('grant_guidance', {
        term: text,
        document: { include: ['section', 'body'] },
        limit: 1,
      })
      return found.hits.map((hit) => hit.document)
    },
  }),
}
 
const askTrustAgent = async (): Promise<{ answer: string; toolsCalled: string[] }> => {
  const agent = new ToolLoopAgent({
    model: trustModel(),
    instructions: 'Answer the applicant from the grant guidance.',
    tools: trustTools,
  })
  const reply = await agent.generate({ prompt: QUESTION })
  const toolsCalled: string[] = []
  for (const step of reply.steps) {
    for (const call of step.toolCalls) toolsCalled.push(call.toolName)
  }
  return { answer: reply.text, toolsCalled }
}
 
const asked = await askTrustAgent()
 
console.log(
  JSON.stringify(
    { question: QUESTION, agentAnswered: asked.answer, toolsCalled: asked.toolsCalled, journal },
    null,
    2
  )
)
 
await narsil.shutdown()
{
  "question": "Can a community choir apply to the building repair fund?",
  "agentAnswered": "The building repair fund is open to a charity or a community group that holds the freehold or a lease of at least fifteen years on the building it repairs. That is the 'Who may apply to the building repair fund' section.",
  "toolsCalled": [
    "countGuidance",
    "searchGuidance"
  ],
  "journal": [
    {
      "hook": "afterSearch",
      "index": "grant_guidance",
      "term": "building repair eligibility",
      "hits": [
        "repair-eligibility"
      ]
    }
  ]
}

With the plugin, the journal holds the hit behind the answer, while the tools contain no logging code. However, the journal has no entry for the count from countGuidance, because a preflight returns a count and no hits, so the engine stops after beforeSearch and calls no afterSearch for it.

Record the request as well as the result

The engine calls beforeSearch before every search and before every preflight, so a beforeSearch hook records the count as well. The engine also calls it before it embeds a vector.text query, so when the hook throws there, the engine makes no call to the embedding provider. At that point, ctx.params.vector holds the text that the caller passed.

When beforeSearch throws, the engine rejects the query, so if the hook throws whenever its write fails, the journal holds every search that the engine answers. The engine calls neither hook for suggest, because suggest scans the term dictionary and searches no document.

import { createNarsil, type NarsilPlugin } from '@delali/narsil'
import { ToolLoopAgent, tool } from 'ai'
import { z } from 'zod'
import { type GuidanceHit, QUESTION, trustModel } from './mock-model.ts'
 
interface JournalEntry {
  hook: string
  index: string
  term: string
  hits?: string[]
}
 
const journal: JournalEntry[] = []
 
const searchJournal: NarsilPlugin = {
  name: 'grant-search-journal',
  beforeSearch: (ctx) => { 
    journal.push({ hook: 'beforeSearch', index: ctx.indexName, term: ctx.params.term ?? '' })
  },
  afterSearch: (ctx) => {
    journal.push({
      hook: 'afterSearch',
      index: ctx.indexName,
      term: ctx.params.term ?? '',
      hits: (ctx.results?.hits ?? []).map((hit) => hit.id),
    })
  },
}
 
const narsil = await createNarsil({ plugins: [searchJournal] })
 
await narsil.createIndex('grant_guidance', {
  schema: { programme: 'enum', section: 'string', body: 'string' },
  language: 'english',
})
 
await narsil.insertBatch('grant_guidance', [
  {
    id: 'repair-eligibility',
    programme: 'building-repair',
    section: 'Who may apply to the building repair fund',
    body: 'The building repair fund is open to a charity or a community group that holds the freehold or a lease of at least fifteen years on the building it repairs.',
  },
  {
    id: 'repair-excluded-work',
    programme: 'building-repair',
    section: 'Work the building repair fund excludes',
    body: 'The fund pays for structural repair, roofing, and damp work, and it pays for no redecoration, furniture, or musical equipment.',
  },
  {
    id: 'performance-eligibility',
    programme: 'performance',
    section: 'Who may apply to the performance fund',
    body: 'The performance fund is open to a choir, an orchestra, or a theatre company that has performed in public in the last two years.',
  },
  {
    id: 'reporting',
    programme: 'all',
    section: 'Reporting on a grant',
    body: 'Every grant holder sends a report within three months of the final payment, with receipts for each item above 500 pounds.',
  },
])
 
const trustTools = {
  countGuidance: tool({
    description: 'Count the guidance sections that match some words, without reading them.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<number> => {
      const counted = await narsil.preflight('grant_guidance', { term: text })
      return counted.count
    },
  }),
  searchGuidance: tool({
    description: 'Search the grant guidance by what its text says.',
    inputSchema: z.object({ text: z.string() }),
    execute: async ({ text }: { text: string }): Promise<GuidanceHit[]> => {
      const found = await narsil.query<GuidanceHit>('grant_guidance', {
        term: text,
        document: { include: ['section', 'body'] },
        limit: 1,
      })
      return found.hits.map((hit) => hit.document)
    },
  }),
}
 
const askTrustAgent = async (): Promise<{ answer: string; toolsCalled: string[] }> => {
  const agent = new ToolLoopAgent({
    model: trustModel(),
    instructions: 'Answer the applicant from the grant guidance.',
    tools: trustTools,
  })
  const reply = await agent.generate({ prompt: QUESTION })
  const toolsCalled: string[] = []
  for (const step of reply.steps) {
    for (const call of step.toolCalls) toolsCalled.push(call.toolName)
  }
  return { answer: reply.text, toolsCalled }
}
 
const asked = await askTrustAgent()
 
console.log(
  JSON.stringify(
    { question: QUESTION, agentAnswered: asked.answer, toolsCalled: asked.toolsCalled, journal },
    null,
    2
  )
)
 
await narsil.shutdown()
{
  "question": "Can a community choir apply to the building repair fund?",
  "agentAnswered": "The building repair fund is open to a charity or a community group that holds the freehold or a lease of at least fifteen years on the building it repairs. That is the 'Who may apply to the building repair fund' section.",
  "toolsCalled": [
    "countGuidance",
    "searchGuidance"
  ],
  "journal": [
    {
      "hook": "beforeSearch",
      "index": "grant_guidance",
      "term": "building repair choir"
    },
    {
      "hook": "beforeSearch",
      "index": "grant_guidance",
      "term": "building repair eligibility"
    },
    {
      "hook": "afterSearch",
      "index": "grant_guidance",
      "term": "building repair eligibility",
      "hits": [
        "repair-eligibility"
      ]
    }
  ]
}

The three entries hold the whole retrieval behind one answer, which is the count that the AI agent asks for first, the search after it, and the section that the search returns. With this record, the trust can answer the trustees' question from entries that the plugin writes inside the engine, whichever tools the model chooses.

  • querybeforeSearchsearchafterSearch
  • preflightbeforeSearchcountafterSearch
  • suggestbeforeSearchdictionaryafterSearch
The engine calls each filled hook and skips each dashed one. A journal built on afterSearch alone holds only the query, while a record of suggest has to come from your code.

A journal in memory lasts only as long as the process. Send each entry to the store that holds your other records, with the index name and the hit ids in it. When you store those ids with the revision of each document from Keep the index current, a reader can find the exact version of the passage behind an answer months later.

Where to go next