Sync chat to user.md.

Give the next agent a current brief with the user’s decisions, reported tool outcomes and notes from this project. Sourced items link to their Originals.

Python
await sync_user_markdown("user.md", chat_batches, **authorized_scope)

Run the Python integration Build a TypeScript handoff

On this page

TypeScript staff handoff#

A short reply like “Thursday after four” makes sense alongside the question it answered. Compare the two briefs and open the original turns in the fictional pickup example.

On your Node 22+ server, set sdk_tarball to the supplied @brain/sdk 0.3.1 archive and run npm install "$sdk_tarball". Configure serverConfig with the authorized API origin (baseUrl), brainId, connectionId and server-only credential.

When a transcript is final, link its turns in their original order. Each turn needs its original ID, thread, case, role, author and text. Link the full transcript before splitting it into persisted batches of up to 24 turns. This example fits in one batch.

TypeScript
import { ApplicationConversations, linkDialogueTurns } from '@brain/sdk';

const memory = new ApplicationConversations(serverConfig);
const scope = {
  subjectId: customer.id,
  caseId: request.id,
  threadIds: authorizedCallIds,
  assistantAuthorId: receptionist.id,
};
const messages = await linkDialogueTurns(originalTurns);
const write = await memory.captureUserMarkdown(scope, messages, {
  idempotencyKey: batch.key, render: false,
});

Mark the batch delivered only on write.status === 'saved'. A rejection describes this attempt. For unknown, retain the original payload and key for explicit reconciliation.

When staff opens a request, authorize it again and select its customer and linked call IDs on the server. Keep the existing request details and full call history available. For a panel labeled Linked call exchanges, request the caller’s replies and their exact questions. The TypeScript client returns fresh Markdown in memory.

TypeScript
const brief = await memory.refreshUserMarkdown({ ...scope, evidenceScope: 'linked_dialogue' });
const evidence = {
  markdown: brief.status === 'ready' && brief.source_status === 'complete' && brief.version_ids.length > 0
    ? brief.markdown : null,
  omittedRows: brief.omitted_rows,
};

Clear the previous card when the request changes. Apply a response only to the request that issued it. Withhold the exchange card if sources are incomplete, rows were omitted, or refresh failed. A complete snapshot with no citations has no excerpts to display.

Open a citation through your server. Reauthorize the staff request, refresh its scope and check that brief.version_ids includes the selected version before calling memory.original(versionId). A version can become unavailable between reads. A caller can change their mind in a later standalone turn. Give staff access to the complete call history before they act on the earlier exchange. Read without evidenceScope for the broader brief. Booking status comes from the booking system.

Pickup handoff under load#

Can staff open the actual question and the caller’s correction when unrelated messages accumulate? Two fictional call histories put the correction at human turn 1 or 59. We read each at 59, 60 and 61 human turns, with room for either two or eight excerpts. The SDK saw the original speakers and text. It received no pickup value or grading key.

Same historyGeneral briefLinked exchanges
Correction visible under the example staff rule8/12 reads12/12 reads
61 human turns, early correctionBoth citations missingBoth citations open
61 human turns, recent correctionBoth citations present, card withheldBoth citations open
Room for only one excerptPair withheld in 6/6Pair withheld in 6/6

In a separate call the caller first named Jo at the café, then changed pickup to Sam at the side gate in a standalone statement. The general brief showed both. The linked view showed Jo and labeled its narrower scope. Staff need the later call wording to choose Sam. These runs measured access to evidence. No staff participated.

General results (JSON) · Linked results (JSON)

Run the Python integration#

Install the repository-local Python client. Configure the API origin, Brain ID, connection ID and producer credential in your backend environment. Authorize the signed-in user’s subject, case and threads before starting the sync.

Python
from brain.client.user_markdown_sync import sync_user_markdown

authorized_scope = {
    "subject_id": subject_id,
    "case_id": case_id,
    "thread_ids": thread_ids,
}

await sync_user_markdown("user.md", chat_batches, **authorized_scope)

Run this in your async app worker using an app-owned private destination. chat_batches yields dictionaries with idempotency_key and messages. Persist each ordered batch and its stable key before yielding it.

The default renders per batch and writes the file when its revision changes. To defer ordinary renders, choose an interval_seconds value. The timer can refresh with zero new messages while the stream is open. Corrections and withdrawals refresh immediately, and ordinary stream completion flushes pending changes by default.

interval_seconds=86400 sets a 24-hour interval. The installed producer lease lasts at most one hour. Continuous daily operation requires same-bearer renewal before expiry. The owner renewal tool has offline coverage only, and the SDK does not perform renewal. This release proved the two-second idle refresh below. Rotating a bearer requires a newly bound private destination.

Fictional Mosaic Saffron Trailer#

In the default call, Mosaic sends three turns. Brain writes a 1,008-byte file with a confirmed 9:16 setting, a typed export failure and an attributed title-card note. All three Originals opened. Exact replay wrote the file zero times.

Exact default input (JSON) Exact default output (Markdown)

The timed run starts from a newer, unconfirmed 9:16 direction that replaces 4:5. Mosaic’s export tool reports that saffron-redo-p9 failed. Delivery is unobserved. While the stream is open, Mosaic saves “Use the French title card for the review copy.”

StepMessages in requestPrivate file
Capture the title-card note1845 bytes
First idle tick01,165 bytes, updated 2.028 seconds after the capture request
Second idle tick0Same revision, bytes and file identity

Exact timed inputs (JSON) Before the tick (Markdown) After the tick (Markdown) Timing and readback (JSON)

In this installed Brain Local run, the three current Originals returned HTTP 200 and the superseded Original returned 404. The example links record those exact version IDs. The temporary fictional scope has since been erased. The run made zero model or external queue calls.

What belongs in the file#

  • Confirmed settings. Your app supplies an explicit confirmation tied to a literal quote. With selectors omitted, Brain discovers current typed settings and tool outcomes within the authorized scope.
  • Attributed wording. Brain can quote bounded recent notes and label them unconfirmed. The output preserves a distinction between what a person said and what the app has confirmed.
  • Reported outcomes. Send typed tool outcomes by default. To use raw tool lifecycle events, supply explicit operation_ids and the app’s trusted tool_author_id.

Mosaic authorizes the project and any retry, checks the current run and deduplicates acceptance. Treat the brief as evidence for that decision. Before handing context to another agent, request a fresh empty-batch render under current authority and use that response. Open its Original paths through your authenticated backend. Your app controls any disclosure to a model provider.

One API for chat and refresh#

POST /v1/brains/{brain_id}/application-conversations/{connection_id}/user-md

Use the producer bearer credential and JSON content type. Send subject_id, case_id, 1–16 thread_ids and up to 24 ordered messages or withdrawals. A nonempty batch requires Idempotency-Key. For correction or withdrawal, send the exact expected version.

render: false captures a nonempty batch and returns ordered custody receipts. For a read-only refresh, omit messages or send [] with rendering enabled. A rendered response returns markdown, revision, scoped version IDs and omission counts. Check for partial before relying on coverage.

The whole document defaults to 8,192 UTF-8 bytes and eight excerpts. Use max_bytes (1,024–32,000) and max_excerpts (0–20) to adjust those bounds. Explicit field_ids and operation_ids limit their sections. Empty lists turn those sections off. Download the canonical OpenAPI.

Custody and recovery#

Brain saves the batch atomically in the existing application conversation store. The projection reads current authorized versions and fits whole rows inside the output budget. Exact replay with the same key and ordered messages returns the original receipts and can render current evidence.

If acknowledgement is uncertain, the Python file sync retires the file and pauses. Keep the original batch and resume explicitly with reconcile_idempotency_key, yielding the exact pending batch first. A file on disk is a snapshot. The default refreshes on each batch, so a quiet stream can leave that snapshot unchanged until the next batch or a refresh. A configured duration can end with a captured change awaiting its next render.

For the older workflow that explicitly confirms and corrects individual fields from the command line, use the confirmed-state CLI guide.