Messages and Parts
Understand canonical Messages, Parts, pagination, and live Mutations
session.messages() reads complete canonical SQLite snapshots, paginated on Message boundaries. Use subscribe() for live changes. Tool Parts preserve complete output, including structured failures, separately from the actual model_output, disclosure_version, and result_ref. The model execution boundary returns business values unchanged up to 16 KiB of final UTF-8 JSON; larger results return a head-and-tail preview and an immutable reference. The general lookup({ result_ref, cursor?, limit? }) tool reads that saved result without executing the operation again. It defaults to 100 lines, accepts up to 200, and returns a complete packet of at most 16 KiB, with opaque continuation cursors even for long lines. History replay and summaries consume only disclosed content and pages already read. Direct SDK tool calls retain complete business data. The model-facing Session Power provides a historical message directory, Part pagination, and original-field text segments; its directory source-page budget is 64 KiB and all model-visible results use the shared disclosure boundary.
const page = await session.messages({ limit: 50 });
for (const message of page.items) render_message(message);interface SessionMessagePage {
items: SessionMessage[];
total: number;
start_sequence?: number;
end_sequence?: number;
next_before_sequence?: number;
has_more: boolean;
}total is the number of real Messages in the Session, not items.length. limit defaults to 50 and is capped at 200.
Two top-level Message types
type SessionMessage = SessionUserMessage | SessionAgentMessage;role | Meaning | Top-level state |
|---|---|---|
user | Input submitted by a person | No state field; complete when written |
agent | Agent output and runtime records | state: "streaming" | "done" |
A User Message does not distinguish prompt from steer. Whether it starts a Turn or joins the current Turn is represented by turn_id and decided by SessionLoop, not duplicated in message content.
An Agent Message's state only answers whether Parts can still be appended. Success, stop, and failure belong to the Turn result. Persisted stop and failure reasons use an error Part.
A Session has one two-party Message sequence ordered by sequence. Tools, runtime input inputs, Actions, and Errors are Agent Parts rather than independent Messages. Interactions are nested in their owning Tool Part's interactions array. Multiple model Steps in a Tool Loop may append to the same Agent Message; model-produced Parts carry their source step_id.
Action ownership rule: while the target Turn still has a streaming Agent Message, the Action Part is appended directly to that Message and shares its canonical identity (for example, changing the model or approval mode mid-run). Only when the Session is idle, the target Turn has no Agent Message yet, or the existing Message is already closed does an Action fall back to a standalone Agent Message containing just the Action Part.
User Parts
type | Key fields | Meaning |
|---|---|---|
text | text | User body |
context | tag, context | Semantically tagged model context |
file | url, media_type, filename | A user-submitted file |
data | data_type, data, data_id | Persisted host/UI data not sent to the model |
A User Message can also carry a meta field: message-level request bookkeeping recording who started this input and the bindings unique to this request. It holds from (the originator, required), plus optional powers and callback. It is not a Part, so it never enters the model context and is never rendered in chat; a message editor cannot restore, edit, or send it back. Runtime requests carry the same bookkeeping on their individual input Part, so requests sharing an Agent Message retain independent actor, Powers, and callback bindings.
User Parts have no streaming state. A context Part becomes safely tagged text only at the model boundary:
// Canonical User Part
{ part_id: "user-context:1", sequence: 1, type: "context", tag: "reference", context: "Earlier message" }
// Model Content
{ type: "text", text: "<reference>Earlier message</reference>" }Runtime input
Task instructions, Session delegation, background results, tool media, and recovery or finalization instructions are persisted as Agent input Parts. Runtime results remain input inputs even when the current Turn is occupied by a user actor. The runtime commits queued inputs in FIFO order at complete Step checkpoints and keeps the current Assistant writer open. Only a new human input creates a User Message and establishes a new reply boundary.
An input Part has input_id, kind, content, created_at, optional source (tool_call_id, turn_id), and optional request meta, in addition to its canonical part_id, sequence, and optional step_id. input_id identifies the input independently of its containing Agent Message and supports idempotent reception.
For model requests, input content is projected into a user-role protocol message wrapped in a runtime_input block. The wrapper identifies runtime input; it does not turn it into a human canonical User Message or increase its instruction priority. Source metadata is serialized as JSON inside the wrapper; text nodes escape &, <, and >, and context content uses safe semantic tags. Native file media stays in separate model content items; text wrappers never embed binary payloads. Summary projection retains file references and excludes media binary content.
Attachment references and content disclosure
Every attachment retains a path and metadata reference. Static PNG, JPEG, and WebP images verified from file headers can also be included automatically when each is at most 2 MiB and all request media together fit within 4 MiB and the remaining model input budget. Recent images are selected first while message order is preserved. Current and historical attachments follow the same rules. Other files, including PDFs, remain references until the Agent explicitly calls read; automatic images omitted for budget also retain their references. The canonical file Part stores a file reference; model requests derive the following information from it:
| Field | Meaning |
|---|---|
filename | File name |
path | Tool-readable file path or remote reference |
media_type | File media type |
size_bytes | Actual byte size when known; may be unknown for missing or undownloaded files |
status | Actual attachment availability |
content_delivery | reference_only, automatic_image, or explicit_media for this request |
Data URLs are used only for drafts and upload transport. Once saved by the Session, attachments use canonical file paths. Attachment paths are derived from file Parts and require no additional persisted attachment_path context. Projection deduplicates framework-generated path contexts against their associated canonical files while preserving user-defined context semantics.
Explicit image and PDF reads have a 2 MiB per-file limit. Successfully delivered native media enters the next model Step through an input Part with source.tool_call_id linking it to the tool call. Its canonical content retains the media reference and media_version. A path alone does not mean the model has seen the media. Oversized files return media_too_large and explicitly report no delivery. read provides no image conversion, PDF pagination, OCR, or Office parsing.
Remote URLs remain references and are not implicitly downloaded. Missing attachments retain their paths and unavailable status; one missing file does not block the entire Session. See Tools and Powers for access boundaries and text continuation parameters.
Agent Parts
type | Key fields | Meaning |
|---|---|---|
text | text, state | Visible output, streaming -> done |
reasoning | text, state | Reasoning output |
tool | tool_call_id, tool_name, state, input, output | Complete Tool lifecycle |
input | input_id, kind, source, content, meta | Runtime input for a subsequent model Step |
view | power_id, schema_version, data, fallback_text, source_tool_call_id? | Structured display content rendered by its provider |
file | url, media_type, filename | Agent file result |
data | data_type, data, data_id | Structured UI data |
action | action_id, action_type, state, title | Session operation state |
error | scope, code, message, recoverable | Session or Turn error |
Every Part has a stable part_id and immutable sequence. A Tool state transition updates the same Part instead of creating duplicate request/result messages. A Tool's interactions array holds approvals and questions with their interaction_id, status, request, and response. Tool and Interaction transitions commit together in one checkpoint transaction.
Streaming and persistence boundary
Events drive live rendering
Memory assembles the stream
The database stores stable semantic checkpointsModel stream start, delta, and finish events first update the current Agent Message's in-memory projection and publish part / delta Mutations. Ordinary chunks do not write SQLite. When a model Step completes, the SDK validates Part identity and commits the complete Step snapshot in one transaction.
Message reads and returned Interactions are independent snapshots that applications can display or transform. Changing these objects does not write back to the Session; use the corresponding Session API to update messages or respond to interactions. Apply live changes by Part or delta while retaining complete results from finished tools.
When concurrent model streams drain buffered events, the SDK yields between events so Stop and other Session operations can run. Event order and per-event backpressure remain intact within each stream. An individual synchronous tool or callback still determines how long its own execution takes.
Agent Messages persist a stable_part_sequence watermark: Parts at or below it form an immutable committed prefix. A complete Step commit or input commit can advance this watermark while the Message remains open. Unfinished Tools, Actions, or streaming text stop the prefix before their complete unit; the boundary cannot split a Step or its tool-call/result group.
The Composer can summarize complete Step and input units inside that stable prefix. It retains the newest request unit in original form and stops at an open Message's watermark, rather than crossing into later Messages. A summary boundary may lie inside one Agent Message, but never inside a Step. Canonical Parts remain intact.
Tool transitions, Interaction changes, Actions/Errors, and Message closure are durable semantic checkpoints and may commit independently. A committed message Mutation replaces the live projection with a complete snapshot.
Ordering, revision, and reconnects
Every Message has a stable message_id, immutable sequence, and increasing revision. Clients should:
- Subscribe and buffer Mutations before loading the initial snapshot.
- Merge complete
messagesnapshots bymessage_id + revision. - Apply
partanddeltaonly while the live stream is continuous. - Reload snapshots after disconnect instead of assuming Deltas can be replayed.
An interrupted, unfinished Step projection may be discarded. The Session closes the persisted streaming Agent Message as done and appends an Error Part, so SQLite is authoritative after reconnect.
Loading older history
let page = await session.messages({ limit: 50 });
while (page.has_more && page.next_before_sequence !== undefined) {
page = await session.messages({
before_sequence: page.next_before_sequence,
limit: 50,
});
prepend_messages(page.items);
}History returns canonical User and Agent Messages, including input Parts within Agent Messages. Composer Policy summaries are derived data: they consume no Message sequence and never appear in messages().
See Reconnect and sync for synchronization and Metadata and storage for persistence details.