AgentNava · Run

Conversations

One conversation holds its own history, its own files and the version it pinned.

Starting one

const conversation = await agent.start({ endUserId: 'u_ananya' });
conversation.id;   // 'conv_5d3a'  store this

Store conversation.id against whoever you are talking to. Every later call is a method on it, and asking again is just the next turn. There is no resume call, because once you hold the id there is nothing to resume to.

endUserId is required: every conversation belongs to someone. Use your own id for the person, or a name for a job such as 'nightly-report'. Ids starting with member:, visitor: or job: (or the older webhook:, builder:, librarian:, in any case) are refused, because those name people and work the platform tracks itself.

The id is not checked. On an agent with memory on, it is also who the memory belongs to, so use one id per person. memory: false starts a conversation that uses nothing remembered and adds nothing.

const conversation = ws.agent(row.agentId).conversation(row.conversationId);   // no network call
await conversation.ask(message);

agent.start(...) always starts a new conversation. Which id you stored decides what you get: an agent id gives you a new conversation, a conversation id continues an existing one.

Asking

One method. Await it for the reply, or iterate it for the events as they happen.

const reply = await conversation.ask('Order 4471 was late. Refund?');
for await (const e of conversation.ask('...')) {
  if (e.type === 'text')     append(e.text);
  if (e.type === 'progress') showSteps(e.steps);
  if (e.type === 'file')     showArtifact(e.path);
  if (e.type === 'done')     save(e.reply);
}
Ask once

The message is sent when you call ask, not when you await or iterate, so calling it twice asks twice. Awaiting and iterating the same turn throws.

Loading a follow-up while someone writes it

Call warm when someone starts writing, then send the message under the same key. What the turn needs then loads before they press send, instead of while they wait.

const idempotencyKey = crypto.randomUUID();   // when they start writing
void conversation.warm(idempotencyKey);       // nothing waits on it
const reply = await conversation.ask(text, { idempotencyKey });

A warm costs no credit and is not a turn, so a message never sent leaves nothing behind. It fades within about a minute: warm again every 20 seconds, under the same key, while they keep writing. It never rejects, since nothing depends on it.

Sending while it works

A conversation works on one turn at a time, so your app never has to lock its message box. Ask while a turn is still running and the message waits for it, or steers it.

conversation.ask('Add a budget too.');                              // queue, the default
conversation.ask('Make it three days, not five.', { mode: 'steer' });
ModeWhat happens while a turn runs
queueThe message is stored at once and runs as the next turn when the running one ends, even if your app has closed. Several run in the order they were sent.
steerThe running turn reads it at its next step, between tool calls, and the agent carries on with it in mind. That turn ends there with what it had written, and the rest of the work is this message's reply. If the turn ends first, the message runs as the next turn, ahead of any queued one.

Iterate the turn to show where the message stands:

for await (const e of conversation.ask(text, { mode: 'steer' })) {
  if (e.type === 'queued')    showWaiting(e.mode);    // 'queue' or 'steer'
  if (e.type === 'picked_up') showRunning();          // its own turn started
  if (e.type === 'folded_in') showReadMidTurn();      // the running turn read it
  if (e.type === 'text')      append(e.text);
}

Until it runs, conversation.messages() lists the message last, with status: 'queued' and its mode. Awaiting the turn gives its own reply, whenever that comes. Each message is one turn, whether it waited or steered.

Events

EventWhenTimes
startthe turn is accepted, with its turnIdexactly once, first
queuedanother turn was running: the message waits (sending while it works)at most once
picked_upafter queued, its own turn startedat most once
folded_inafter queued with mode: 'steer', the running turn read itat most once
progressthe agent's step list changedzero or more
toola tool call begins, and endspaired
texta piece of the replyzero or more
filethe agent wrote a file you can readonce per file
widgeta card, table or chart in the reply grew (only with widgets: true)zero or more
donethe reply is finalonce, or error
errorthe turn failed, and the stream endsonce, or done

text arrives in fragments. Append each one as it comes. A short reply can arrive as one fragment. done carries the whole reply, so a client that only wants the answer can ignore every other event and still be correct.

A dropped connection does not end the turn. Since SDK 0.86.0, when the line to AgentNava breaks while a turn runs, the SDK picks the turn up again where it was, for about two minutes, and your loop never sees the break or an event twice. If it cannot, you get error as before, and the reply still lands in conversation.messages(). After a long break it may send a reset with the reply so far: replace what you show. Without the SDK, send the same request again (same body, same Idempotency-Key) with X-Turn-Resume set to the cursor of the last event you read, or start.

Your own page can lose the answer too: a phone leaves the app, a page reloads. Since SDK 0.99.0, ask again under the same idempotencyKey, with the same text and attachments. You get that turn back from its first word, and it never runs twice. Keep the key with the question until done. AgentNava keeps a turn for three days after it ends; asked again later, the key starts a new turn. A page that lost the key can call conversation.turn(): it says whether the latest turn is still running, and carries the reply once it has completed.

A progress event carries the whole step list, every time. Replace what you were showing. That is what makes reconnecting safe: one event and you are correct again.

The steps are the ones the AgentNava app shows while an agent works, in the same words: one per tool call, in the order they started. Each has an id, a label such as Searching the web: steel tariffs, a kind for an icon (read, web, shell and so on), and a status of active, done or error. A call that only draws on screen is not a step.

A tool event carries the tool's name, for your code, and the same label, for a person. A file event's path is what conversation.readFile() takes.

for await (const e of conversation.ask('Research steel tariffs and save a summary.')) {
  if (e.type === 'progress') {
    for (const step of e.steps) console.log(step.status, step.label);
  }
  if (e.type === 'file') console.log(await conversation.readFile(e.path));
}
Your connection can drop

It runs on our side. If your connection drops it keeps going and settles, read the answer with conversation.messages() when you reconnect.

Widgets

If your screen can draw cards, tables and charts, start the conversation with widgets: true, and the agent may answer with them, unless its Widgets setting is off. Continue one the same way, with agent.conversation(id, { widgets: true }).

const conversation = await agent.start({ endUserId: row.userId, widgets: true });

for await (const e of conversation.ask('How did October spend compare with budget?')) {
  if (e.type === 'widget') draw(e.widget);           // sent whole each time: replace by surfaceId
  if (e.type === 'done')   keep(e.reply, e.widgets);  // the final list
}

Without widgets: true nothing changes: no widget events, and the agent is never asked to draw.

Ready-made React views

On a React screen, the SDK draws widgets for you. ReplyView shows a reply's words with each widget in place, in a default look you can theme with CSS variables. React is optional: only this entry needs it.

import { ReplyView } from '@cerebro-labs/agentnava-sdk/react';
import '@cerebro-labs/agentnava-sdk/react/styles.css';

<ReplyView text={reply} widgets={widgets} onAsk={send} />

onAsk receives a pressed button's label or a tapped suggestion, to send as the next message. Pass renderText to draw the words with your own markdown renderer, currency and locale for numbers, and parts to swap any kind of part for your own component, such as parts={{ Stat: MyStat }}. WidgetView draws a single widget.

The parts an agent draws

Numbers and lists: Stat, KeyValue, Table, Chart, List. Layout and words: Column, Row, Card, Text, Note, Badge, Image, Link, Divider. Answers the reader taps: Button, Suggestions. And six for work:

PartWhat it shows
MessageAn email the way a mail app shows it (subject, sender, To and Cc, date, paragraphs with the signature kept, files, the earlier message behind a tap), or a Slack, text or chat message. state is received, draft or sent.
ApprovalAn action waiting for the reader's OK: what will happen, what it holds (a Message, a Meeting), what they agree to, and buttons whose words say what happens ("Send it", "Not now", optionally "Change it").
MeetingWhen and where, a Join button, who comes, what is still open, what was promised, notes.
SlotsTimes to pick from, by day, in the time zone the agent names; busy times struck out.
PersonSomeone, a one-line read of them, a status ("Waiting on you") and one action.
ChecklistThings to do, with who owns each and when it is due.

Text and Note keep the line breaks the agent writes.

The six are taught only to a screen that says it draws them: start or continue the conversation with widgets: 2 instead of true (SDK 0.87 and up, whose ReplyView and WidgetView draw them). With widgets: true the agent keeps to the sixteen parts above them, so a screen built before these parts never receives one it cannot draw. The same goes for your own widgets below.

const conversation = await agent.start({ endUserId: row.userId, widgets: 2 });

When the reader taps

An Approval's buttons, a Slots pick, a Person's action and a Button that carries an event can go to your own code. Pass onAction and you get what was tapped with the agent's own ids for it, such as the draft an Approval would send. Without it, a tap sends its words as the next message through onAsk. Either way, a part rests after one tap, so a second tap cannot send twice.

<ReplyView
  text={reply}
  widgets={widgets}
  onAsk={send}
  onAction={(a) => {
    // a.name: 'approve' | 'decline' | 'change' | 'pick' | the part's own event
    if (a.name === 'approve' && a.context.draft) sendDraft(a.context.draft);
    else send(a.words);                    // tell the agent what was chosen
  }}
/>

Editing a draft before approving it

A Message inside an Approval with editable: true is drawn as a box the reader can change before tapping approve, with a way to undo their changes. The approve then carries each such draft as it was approved, in a.edits: its part id, its body (the original when they changed nothing) and whether they edited it. Approve stays off while a draft is empty. Act on that body, never on your own copy of the draft. Without onAction, the words sent to the agent carry the changed text, so the agent sends exactly what was approved.

The agent is taught to mark its drafts editable only on a screen that asked for widgets: 3 (SDK 0.88 and up). With widgets: 2, or on a phone chat, the draft is shown as words, as before.

const conversation = await agent.start({ endUserId: row.userId, widgets: 3 });

onAction={(a) => {
  if (a.name === 'approve' && a.edits?.length) saveAndSend(a.context.draft, a.edits[0].body);
}}

Your own widgets

When an agent should show something the same way every time, give it a composite: a widget of your own, built only from the parts above. The agent learns it by name and draws it as one part. AgentNava turns that part into built-in parts before any screen sees it, so every screen (yours, the web chat, a phone) draws it with no new code, and a reply looks the same after a reload.

await agent.update({
  composites: [{
    name: 'EmailReply',
    use: 'a reply to an email, waiting for their OK to send',
    props: {
      title:    { doc: 'what will happen: "Send your reply to Priya"', required: true },
      theirs:   { doc: 'their email: {from, subject, at, body}', required: true },
      reply:    { doc: 'your reply, paragraphs split by blank lines', required: true },
      promises: { doc: 'what sending it commits them to' },
      draft:    { doc: 'the draft id', required: true },
    },
    body: [
      { id: 'root', component: 'Approval', title: { path: '/title' }, approve: 'Send it', change: 'Change it',
        agree: { path: '/promises' }, context: { draft: { path: '/draft' } }, children: ['theirs', 'mine'] },
      { id: 'theirs', component: 'Message', from: { path: '/theirs/from' }, subject: { path: '/theirs/subject' },
        at: { path: '/theirs/at' }, body: { path: '/theirs/body' } },
      { id: 'mine', component: 'Message', state: 'draft', editable: true, body: { path: '/reply' } },
    ],
  }],
});

The body is a widget written with A2UI's own placeholders: { path: '/title' } takes a prop's value, and a container's children written { componentId: 'row', path: '/people' } repeats that part for each item of a list, where { path: 'name' } reads the item. A part whose required value the agent leaves out is dropped with what it holds, so a section can be optional. Put a prop only where its value fits: one prop cannot fill both a field of words and a list such as an Approval's agree. The agent is told the form each prop takes, from where the body puts it. A composite that could never draw is refused when you save it, with the reason: a prop placed where no one value fits, two Approvals, an Approval inside a repeat, two buttons with the same words (a button you leave out counts as the words it shows, such as "Not now"), or placeholders inside repeats that could copy the agent's values too many times. A composite you saved earlier is checked again only when you change it, so a rule added since never blocks a save of something else. Each conversation keeps the composites of the version it started on. The agent draws them only on a screen that asked for widgets: 2 or 3. In the builder, ask the Agent Builder for one ("show email replies as a card with their email and mine").

Drawing a widget yourself

Widgets use A2UI, Google's open format for interfaces an agent draws, with AgentNava's own set of parts. A widget is a flat list of parts. Each part has an id and a component, which says what kind of part it is. Containers name their children by id, and the part called root is the top. at is where the widget sits in the reply's text, as a character count, so it goes between the right sentences. closed is false while it is still arriving.

{
  surfaceId: 'w1',
  at: 31,
  closed: true,
  components: [
    { id: 'root',   component: 'Row',  children: ['earned', 'casual'] },
    { id: 'earned', component: 'Stat', value: '9 days', label: 'Earned leave', caption: '4 pending' },
    { id: 'casual', component: 'Stat', value: '7 days', label: 'Casual leave' },
  ],
}

To draw one, start at root, draw its part, and draw each child the same way, mapping each kind (Stat, Table, Chart and so on) to a component in your own look.

Draw it defensively

A widget is written by the model, so treat it like any other input. Skip a kind you do not know and a part that is missing a field. Draw each part once, even if two containers name it. Open only https:// links and pictures. A widget you cannot draw at all can simply be left out: the reply's words still make sense without it.

Sending an image or a file

await conversation.ask('What is wrong in this screenshot?', {
  attachments: [{ kind: 'image', mimeType: 'image/png', data: base64 }],
});

await conversation.ask('Which of these are overdue?', {
  attachments: [{ kind: 'file', name: 'invoices.csv',
                  mimeType: 'text/csv', data: base64 }],
});

An image goes to the model as an image. Anything else is written into the conversation's drive before the turn starts, so the agent can parse it, compute over it, and still have it next turn.

Reading it back

await conversation.messages();   // [{ role, content, at, widgets? }, ...]
await agent.conversations();     // this agent's newest 50, each with its startedAt and title
await agent.conversations({ of: 'customers', limit: 5 });   // only your end users', not the team's own
await agent.conversations({ of: 'team' });   // only your team's own tests
await agent.conversations({ of: 'jobs' });   // only work nobody typed: schedules, webhooks, API runs

Every conversation has its own history and its own filesystem. Two conversations share nothing, with one exception: on an agent with memory on, what it remembers about an end user reaches all of that person's conversations on that agent.