---
title: "@octabits-io/assistant"
summary: "A conversation a person has with an assistant that acts for them: the store (conversations and messages, read by their owner only, encrypted under the owner's key through a cipher you plug in, kept for a retention period, one turn at a time), a turn answered as the AI SDK's UI message stream with the host's MCP tools, every write a proposal the person confirms, the data-subject sources and steps, and the page's messages read back."
install: "pnpm add @octabits-io/assistant"
availability: "Available from November 2026"
version: "0.2.1"
license: "MIT"
related:
  - name: "@octabits-io/models"
    url: "https://octabits.io/platform/models.md"
  - name: "@octabits-io/postgres"
    url: "https://octabits.io/platform/postgres.md"
  - name: "@octabits-io/result"
    url: "https://octabits.io/platform/result.md"
canonical_url: "https://octabits.io/platform/assistant"
---

# `@octabits-io/assistant`

A conversation a person has with an assistant that **acts for them**: it answers from the
app's data and starts work, and every write it makes is a proposal the person confirms. The
package keeps the conversation and runs one turn of it:

- **The conversations**: read by their owner only, encrypted under the owner's key through a
  cipher you plug in, kept for a retention period (30 days after the last message by default),
  one turn at a time.
- **A turn** (`./ai-sdk`): the person's words stored, the model and the actor's tools run
  (`streamAgentTurn` of `@octabits-io/models`), every round stored as it ends, and the answer
  streamed as the AI SDK's UI message stream, so `useChat` reads it.
- **Data subjects**: the two sources and two steps an access or an erasure request needs.
- **The page**: what was stored read back as `UIMessage`s, a proposal included.

```bash
npm i @octabits-io/assistant zod     # + ai @octabits-io/models for ./ai-sdk, @octabits-io/postgres for ./postgres
```

```ts
import { createConversations } from '@octabits-io/assistant';
import { createAssistant, toUIMessages } from '@octabits-io/assistant/ai-sdk';
import { createPostgresConversationStore } from '@octabits-io/assistant/postgres';
import { mcpToolsForAgent } from '@octabits-io/server/mcp/ai-sdk';

const conversations = createConversations({
  store: createPostgresConversationStore({ db, scope: { column: 'org_id', value: orgId } }),
  cipher,                                       // a key per owner; see "What is kept" below
});
const assistant = createAssistant({
  conversations,
  model: () => gatedModel,                      // behind the disclosure gate and the meter
  system: 'You help the people of this office. You propose; they decide.',
  tools: () => mcpToolsForAgent(registerTools, () => scope, { audit, disclosure }),
  mask: (_turn, text) => veil.scrub(text),
  reveal: () => (stream) => stream.pipeThrough(createPseudonymRevealTransform({ vault })),
});

// POST /api/assistant — one turn
const turn = await assistant.turn({ owner: actor.userId, text, conversationId });
if (!turn.ok) return problem(turn.error);       // conversation_not_found, conversation_busy, assistant_tool_refused
return turn.value.response;                     // the UI message stream

// GET /api/assistant/:id — the page reads it back
const read = await conversations.get(actor.userId, id);
if (read.ok) return { conversation: toConversationView(read.value.conversation), messages: toUIMessages(read.value.messages) };
```

| Entry | Peer | What it is |
|---|---|---|
| `.` | `zod` | the store contract and its in-memory reference (`createInMemoryConversationStore`), the conversations (`createConversations`), the data-subject pieces (`conversationSubject`), the views (`toConversationView`, `conversationViewSchema`) |
| `./ai-sdk` | `ai`, `@octabits-io/models` (optional) | the turn (`createAssistant`), the stored messages as `UIMessage`s (`toUIMessages`), the transcript a model is sent (`transcriptFor`) |
| `./postgres` | `@octabits-io/postgres` (optional, the executor type) | the store over plain SQL (`createPostgresConversationStore`), `conversationDdl()` and `conversationMessageDdl()` |
| `./drizzle` | `drizzle-orm` (optional) | `conversationColumns` and `conversationMessageColumns`, to declare the tables for drizzle-kit |
| `./schema/*` | — | a conversation and an owner's counts as JSON Schema |

The root imports nothing but `zod` and `@octabits-io/result`, so a browser bundle may import
it; the boundary lint holds that.

## When not to use it

- **An agent that runs on its own**, with no person waiting: that is a step of a workflow
  (`defineAgentStep` of `@octabits-io/models/octaflow`), durable and retried, not a chat.
- **A chat with no tools and nothing to keep**: `streamText` is enough.
- **An agent outside the app**, in someone's IDE: serve it the same tools over MCP
  (`@octabits-io/server/mcp`). This package is the agent inside the app, with the same tools.

## A turn

`assistant.turn({ owner, text, conversationId?, focus? })` starts a conversation when there is
no `conversationId`. It answers the `Response` to send, or why the turn did not start. In order:

1. **The owner.** A conversation that is not the owner's is `conversation_not_found`. One that
   is still answering is `conversation_busy`: a conversation runs one turn at a time. Resolve
   who is asking before you call `turn`, and refuse a person under an impersonation grant
   there: support looking at an organisation does not get its people's conversations.
2. **The person's words**, through `mask`, are stored as masked and sent as masked. Names from
   your records reach the model as pseudonym tokens (`@octabits-io/pii/pseudonym`).
3. **The budget.** `admit(turn)` is asked before the first model call. A refusal is the answer:
   it is stored, streamed and nothing more happens.
4. **The transcript**: the stored messages, newest first, up to what the model's window leaves
   for them (step 6) or `maxContextChars` (48 000) when the window is unknown, and
   starting at a person's message. A message whose key is gone is left out. `focus` (what is on
   the person's screen) goes in as a sentence after the system prompt.
5. **The tools**: `tools(turn)` answers them with their effects, which `mcpToolsForAgent`
   gives you from the registration your MCP endpoint serves.
   - Only `reads` and `writes` are accepted. An outward tool is refused before any model call
     (`assistant_tool_refused`).
   - Beside them, `agentTools` takes tools that declare themselves (`agentTool`): a connection's
     reviewed tools (`connectionTools` of `@octabits-io/connections/ai-sdk`), each with its effect,
     whether it answers what was written outside (`untrusted`) and the class of its answers.
     - An `outward` one needs `propose(turn)`: its call becomes a proposal with exactly the
       arguments the model gave, which the person's confirmation runs once
       (`runProposedToolCall`). Without `propose` it is refused before any model call.
     - A tool that declares its class needs `modelClass(turn)`, what the turn's model is cleared
       for. One whose answers are above it is withheld: never offered, the model told it is and
       why (so it says so), and `onWithheld(turn, withheld)` told, for your disclosure log.
     - Once an `untrusted` tool answered, the conversation is tainted for good: the stored tool
       message carries `tainted` (sealed with its content), every later turn starts tainted, and
       a proposal names every untrusted tool the conversation read in its `after` — what it was
       drafted after. A tainted turn may not fetch an address the model chose.
   - A `writes` tool from that bridge is a `proposingTool`: its result is a Proposal or a
     pending run, and the person's confirmation goes through your ordinary approve path; or,
     under a standing authorization of that person's, the act it applied (`applied`).
   - A `directTool` never gets here.
   - The person cannot approve their own request through the chat any more than through your
     inbox: the four eyes your approvals hold still hold.
6. **The loop** (`streamAgentTurn`) caps the rounds (`maxRounds`, default 8) and the tokens
   (`maxTokens`). What a turn sends fits the model's window when the host gives it
   (`contextTokens(turn)`: `knownContextTokens` for a vendor's model, `discoverContextTokens`
   for one you run): the earlier conversation up to 35 % of it, and each tool's answer up to
   15 %, shortened for the model past that and kept whole for the page — the transcript keeps
   the shortened one, so a later turn does not carry it again in full. On a 1M window that is
   more than a conversation holds, so nothing is shortened; with no window given, the
   conversation is held to `maxContextChars` (48 000) as before and no answer is shortened.
   `maxContextChars` and `maxToolResultChars` set either outright. Every round is stored as it
   ends. A turn a cap stopped ends with a stored note that says so.
7. **The answer** streams through `reveal`: the person reads names, and the model saw tokens.
   The turn runs to its end on the server whether or not the page keeps reading. A turn that
   fails ends with a sentence — streamed in place of the SDK's "An error occurred." and stored —
   so the person never reads a tool call with nothing after it: `failedTurnSentence` reads the
   model's refusal, and a conversation grown longer than the model reads
   (`provider_context_exceeded`) asks for a new one; `failed(turn, error)` says it the host's way.
   The conversation is stored `interrupted`, and so is one whose process died, once it has gone
   quiet for 15 minutes (`staleAfterMs`).
8. **Costs and context**: `around(turn, run)` runs the turn inside yours, for example
   `metering.withUsage({ feature: 'assistant', runId: turn.conversationId, scopeKey }, run)`, so
   every model call is booked to the conversation. `onTurn` hears how it ended.

The model you return from `model(turn)` is the one every call goes to. Hand it the model
behind the disclosure gate (`@octabits-io/disclosure`) and the meter
(`@octabits-io/metering`), as every other model call in the app is.

## What is kept

| Table | Columns |
|---|---|
| `conversation` | `id`, `owner`, `title` (ciphertext), `status` (`open`, `answering`, `interrupted`), `created_at`, `last_activity_at`, `expires_at` |
| `conversation_message` | `id`, `conversation_id`, `seq`, `role`, `content` (ciphertext), `model`, `input_tokens`, `output_tokens`, `created_at` |

Declare both from the column sets, with your scope column, and own the migration:

```ts
import { conversationColumns, conversationMessageColumns } from '@octabits-io/assistant/drizzle';

export const conversation = pgTable('conversation', { orgId: text('org_id').notNull(), ...conversationColumns });
export const conversationMessage = pgTable('conversation_message', { orgId: text('org_id').notNull(), ...conversationMessageColumns },
  (t) => [uniqueIndex().on(t.conversationId, t.seq)]);
const store = createPostgresConversationStore({ db: drizzleExecutor(tx), scope: { column: 'org_id', value: orgId } });
```

Without an ORM, run `conversationDdl({ scope: { column: 'org_id' } })` and
`conversationMessageDdl(…)`. There is no Drizzle store: the SQL store is the store, and
`drizzleExecutor` from `@octabits-io/postgres/drizzle` runs it on your Drizzle database or
transaction. The store deletes messages before their conversation, so a foreign key between
them is yours to add or leave out.

- **Encrypted under the owner's key.** The cipher is `{ encrypt(owner, text), decrypt(owner,
  text) }`. With `@octabits-io/pii`, use a key whose scope is the owner. Destroying it, when
  the person leaves or is erased, makes every conversation of theirs unreadable at once: a
  title reads back `null`, and a message reads back `unreadable`, never as an error.
- **Pseudonyms, not names.** Record fields reach a conversation as tokens. When a person is
  erased, their pseudonym rows go, and their tokens in old conversations no longer resolve:
  the page shows the token, and no message is rewritten.
- **Retention.** Every write moves `expires_at` to the last activity plus `retentionDays`
  (default 30). `conversations.purgeExpired()` deletes what has passed it. Call it from your
  retention runner (`@octabits-io/data-lifecycle`), on an unscoped store for the whole
  platform.
- **Owner only.** No read crosses owners. `stats()` gives an administrator counts and the last
  activity per person, never a title or a message.

## Who proposed it

When a person confirms what the assistant proposed, the ledger should say who drafted it: not the
person alone, and not an outside agent. An MCP client's model runs on its own side, while the
assistant's calls pass your disclosure gate. Record the proposal under

```ts
assistantPrincipal(conversationId, onBehalfOf)  // { kind: 'agent', id: 'assistant:<conversationId>', label: 'The assistant', onBehalfOf }
```

(the shape of `@octabits-io/proposal`'s `Principal`). The person's confirmation stays the decision.
The assistant's model calls are logged under its conversation, not under the run it proposed, so
tell `@octabits-io/evidence` where to find them: `collectEvidence({ …, agentCorrelation:
conversationOf })`. Its actions then carry the conversation's calls, and are never
`no_model_calls_recorded` while those calls are in the log, nor `outside_agent_action`.

The tools are usually the MCP registration, so hand each tool the principal it acts as on its
scope: `outsideAgent(…)` on the endpoint, `assistantPrincipal(…)` in the chat. A tool then records
whichever it is given and never names a principal itself.

## Access and erasure requests

```ts
const { sources, steps } = conversationSubject(conversations, { ownerOf: (ctx) => ctx.userId, retentionDays: 30 });
// beside your other sources and steps; checkErasureCoverage({ sources, steps }) passes
```

- `assistant_conversations`: the subject's own conversations, exported read back and erased
  by deleting them.
- `assistant_mentions`: words someone else typed about the subject in their own conversation.
  Nothing searches other people's conversations for a name, so the step is a `retain` whose
  basis says how long such words live and under whose key. The erasure is `partial` and says
  why, rather than reporting a `completed` it cannot stand behind.

## The page

The protocol is the AI SDK's UI message stream, so the browser uses `@ai-sdk/react`'s
`useChat`. `toUIMessages(messages)` turns what was stored into its `messages`:
- a person's words become text;
- the model's text stays text;
- each tool call becomes a `tool-<name>` part with the result its tool returned, so a proposal
  reads back exactly as it streamed (`output.structuredContent.proposal`).

`toConversationView` and `schema/conversation.schema.json` describe the list.

## What is tested

- **Conformance:** one suite over three stores — the in-memory reference, the SQL store on
  PGlite, and the SQL store through `drizzleExecutor` on tables declared from the column sets —
  covering owner-only reads and writes, ordering, deletion with messages, retention, counts,
  and scope isolation.
- **Store halves:** each column set is held equal to its DDL.
- **The service:** ciphertext at rest, a destroyed key read back as unreadable, retention, and
  one turn at a time with stale turns interrupted.
- **The turn,** on a scripted model with tools from the real `mcpToolsForAgent`:
  - a read answers;
  - a proposal changes nothing and reads back on the page;
  - a direct writer and an outward tool never reach the model;
  - a connection's outward tool is a proposal with exactly the model's arguments, drafted after
    what the conversation read, in this turn or an earlier one; none without `propose`;
  - a tool above the model's class is withheld and the model told why; none that declares a
    class without `modelClass`;
  - a masked name never reaches the model, and the person reads it revealed;
  - a budget refuses before the first call;
  - a turn nobody reads, one that fails and one a cap stops are each stored as what they were.
- **Data subjects:** the sources and steps run through `@octabits-io/data-subject` itself.

## Stability

0.x: patches never break, minors say so in the changelog.

## License

MIT