@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 (streamAgentTurnof@octabits-io/models), every round stored as it ends, and the answer streamed as the AI SDK’s UI message stream, souseChatreads it. - Data subjects: the two sources and two steps an access or an erasure request needs.
- The page: what was stored read back as
UIMessages, a proposal included.
npm i @octabits-io/assistant zod # + ai @octabits-io/models for ./ai-sdk, @octabits-io/postgres for ./postgres
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 UIMessages (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
(
defineAgentStepof@octabits-io/models/octaflow), durable and retried, not a chat. - A chat with no tools and nothing to keep:
streamTextis 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:
- The owner. A conversation that is not the owner’s is
conversation_not_found. One that is still answering isconversation_busy: a conversation runs one turn at a time. Resolve who is asking before you callturn, and refuse a person under an impersonation grant there: support looking at an organisation does not get its people’s conversations. - 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). - The budget.
admit(turn)is asked before the first model call. A refusal is the answer: it is stored, streamed and nothing more happens. - 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. - The tools:
tools(turn)answers them with their effects, whichmcpToolsForAgentgives you from the registration your MCP endpoint serves.- Only
readsandwritesare accepted. An outward tool is refused before any model call (assistant_tool_refused). - Beside them,
agentToolstakes tools that declare themselves (agentTool): a connection’s reviewed tools (connectionToolsof@octabits-io/connections/ai-sdk), each with its effect, whether it answers what was written outside (untrusted) and the class of its answers.- An
outwardone needspropose(turn): its call becomes a proposal with exactly the arguments the model gave, which the person’s confirmation runs once (runProposedToolCall). Withoutproposeit 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), andonWithheld(turn, withheld)told, for your disclosure log. - Once an
untrustedtool answered, the conversation is tainted for good: the stored tool message carriestainted(sealed with its content), every later turn starts tainted, and a proposal names every untrusted tool the conversation read in itsafter— what it was drafted after. A tainted turn may not fetch an address the model chose.
- An
- A
writestool from that bridge is aproposingTool: 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
directToolnever 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.
- Only
- 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):knownContextTokensfor a vendor’s model,discoverContextTokensfor 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 tomaxContextChars(48 000) as before and no answer is shortened.maxContextCharsandmaxToolResultCharsset either outright. Every round is stored as it ends. A turn a cap stopped ends with a stored note that says so. - 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:failedTurnSentencereads 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 storedinterrupted, and so is one whose process died, once it has gone quiet for 15 minutes (staleAfterMs). - Costs and context:
around(turn, run)runs the turn inside yours, for examplemetering.withUsage({ feature: 'assistant', runId: turn.conversationId, scopeKey }, run), so every model call is booked to the conversation.onTurnhears 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:
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 backnull, and a message reads backunreadable, 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_atto the last activity plusretentionDays(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
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
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 aretainwhose basis says how long such words live and under whose key. The erasure ispartialand says why, rather than reporting acompletedit 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
drizzleExecutoron 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-subjectitself.
Stability
0.x: patches never break, minors say so in the changelog.
License
MIT
From @octabits-io/assistant@0.2.1 in the platform repository.