kletso_core library
Pure-Dart Kletso client: sessions, realtime connection with reconnect and replay, conversation state and typed events.
Hosts on Flutter use package:kletso_flutter, which builds on this. Use
this package directly for Dart servers, CLIs and tests. The fake backend
for demos and tests lives in package:kletso_core/fake.dart.
Classes
- Kletso
-
Process-wide entry point:
Kletso.init(config)once, thenKletso.instanceeverywhere. A thin wrapper over KletsoClient; create clients directly for tests or multi-tenant hosts. - KletsoAction
-
An action attached to a component. The
kinddecides where it goes:localstays on the device, every other kind is sent to the runtime as anactionframe. - KletsoActionFrame
- A non-local action taken on a surface.
- KletsoAgentAction
- Posts value back to the agent as a structured user turn.
- KletsoAgentInfo
- Public information about the agent serving the session.
- KletsoAgentTyping
-
agent.typing. - KletsoApi
-
The REST side of the runtime (
/v1). Implemented byKletsoHttpApiagainst the network and by the fake backend for tests and demos. - KletsoAppCommand
-
app.command: server-initiated local action. - KletsoAppNotification
-
app.notify: a proactive notification for the host app. Rendered by the SDK's notification host (banner/toast/alert), handed to the OS tray through the host's system notifier, or silent (open the chat / run the action only). Never a chat message; the same envelope may also arrive in a push payload under thekletsokey. - KletsoAudioFrame
-
A binary WebSocket frame of
kletso.realtime/v1: one byte of kind followed by PCM16 little-endian mono audio at 24 kHz. - KletsoAudioIo
-
Microphone capture and speaker playback for voice sessions, implemented
outside this package (
package:kletso_voiceon Flutter, or the host's own audio stack; D82). All audio is PCM16 little-endian mono 24 kHz. - KletsoAuthFrame
- First frame after the socket opens; carries the session token.
- KletsoAutoTransport
-
Tries the primary transport (WebSocket) and, after failuresBeforeFallback
consecutive handshake failures that are not auth errors, uses the fallback
(SSE) for the rest of this instance's life. A fresh
KletsoClient(cold start) tries WebSocket again. - KletsoAvatarMoodEvent
-
avatar.mood: a mood for the avatar. Moods are open strings on the wire; renderers map unknown ones to neutral. - KletsoBackoff
-
Exponential backoff with full jitter: each delay is uniform in
[0, min(cap, base * 2^attempt)]. - KletsoBinding
-
A reference from a component prop into the surface
datamodel, written on the wire as{ "path": "/json/pointer" }(RFC 6901). - KletsoBuiltinTypes
- Names of the component types every conforming renderer ships.
- KletsoClient
-
The Kletso client: one per app (through
Kletso.init) or one per test. - KletsoClientError
- An error the SDK handled or surfaced. Also thrown from the public future that caused it, when there was one.
- KletsoClientFrame
- A frame the client sends to the runtime.
- KletsoCloseCodes
- WebSocket close codes the runtime uses.
- KletsoCloseInfo
- Why a socket ended.
- KletsoComponentSpec
-
Declares a custom component type next to the widget that renders it:
what the model may put in
props, how to describe it to the model, and which actions it carries.dart run kletso_flutter:synccollects specs into a manifest for the dashboard, so the render_ui tool schema and the Flutter builder never drift apart. - KletsoConfig
-
Immutable SDK configuration, passed once to
Kletso.initorKletsoClient. - KletsoConfirmAction
-
Answers a
confirmblock for a tool call that requires confirmation. - KletsoConnection
-
Owns one realtime connection: the reconnect loop with jittered backoff,
first-frame auth (delegated to the transport), heartbeat,
seqreplay and dedupe, and a bounded outbound queue that flushes afterready. - KletsoConnectionChanged
- The realtime connection changed state.
- KletsoContextFrame
- Runtime context change: either merge keys into the current context or replace it wholesale. Exactly one of merge or replace is set.
- KletsoConversationEvent
-
conversation.created/.updated/.closed. - KletsoConversationInfo
-
Conversation metadata as carried by
conversation.*events. - KletsoConversationScript
-
Builds the canonical scripted conversation used by every fake: a
deterministic
kletso.events/v1log with 20 messages that walks through greeting, flight search with a rendered card, quick replies, a chart, a hotel, product cards, a confirmed tool call and a human handoff. - KletsoConversationState
-
Reduces a conversation's event log into a message list. Pure with respect
to its inputs; one instance per conversation, kept by
KletsoClientso switching back to a conversation is instant. - KletsoDevice
- Describes the device to the runtime when a session is created.
- KletsoEndUser
- The end user the session belongs to.
- KletsoErrorEvent
-
error. - KletsoErrorFrame
- A non-fatal error on the connection (fatal ones close the socket).
- KletsoEvent
-
Everything the SDK reports on
KletsoClient.events: protocol events from the runtime plus client-side happenings (connection changes, errors, unknown components). - KletsoEventEnvelope
-
One
kletso.events/v1event as it appears in a conversation log, a realtimeeventframe or a webhook batch. - KletsoEventFrame
- An event envelope.
- KletsoEventPayload
-
Typed view of an envelope's
data. Every constructor is total: missing or mistyped fields becomenull/defaults, never exceptions, because clients must keep working when the runtime ships a newer minor version. - KletsoEvents
- Names of the silent app events the SDK sends on its own.
- KletsoEventTypes
-
The
typestrings ofkletso.events/v1. - KletsoFixtureGenerators
- Deterministic builders for surfaces that break one protocol limit each.
- KletsoFixtures
-
The conformance fixtures, as text, keyed by their path under
fixtures/. Files over 64 KB are not embedded (seeKletsoFixtureGenerators). - KletsoHandoffEvent
-
handoff.started/.completed. - KletsoHttpApi
-
KletsoApi over HTTP with
package:http. Works on every platform (BrowserClienton the web). - KletsoIdGenerator
-
Generates ULID-style ids: 10 chars of millisecond time + 16 random chars
in Crockford base32, so ids sort by creation time and never collide in
practice. Time comes from
package:clockso tests can control it. - KletsoLocalAction
- Runs a host-registered callback by name; never leaves the device.
- KletsoLocalActionRan
-
A
localaction ran on the device (reported for analytics). - KletsoLog
- Level-filtered logger used throughout the SDK.
- KletsoMemoryTokenStore
- KletsoTokenStore that forgets everything when the process ends.
- KletsoMessage
- One message in the active conversation, materialised from events.
- KletsoMessageCompleted
-
message.completed. - KletsoMessageCreated
-
message.created. - KletsoMessageDelta
-
message.delta. - KletsoMessageFrame
- A user message.
- KletsoNode
- One component in a surface: a type, a bag of props and its actions.
- KletsoNotification
-
An
app.notifyevent as seen by the host: the payload plus where it belongs and how it arrived. Deduped onnotificationId. - KletsoOutbound
-
Something the user sends: text, a structured value, or an action on a
surface. The client assigns the
clientIdand turns it into a frame. - KletsoOutboundAction
- See KletsoOutbound.action.
- KletsoOutboundText
- See KletsoOutbound.text.
- KletsoOutboundValue
- See KletsoOutbound.value.
- KletsoPendingComponent
-
One component announced by
ui.pending: its id and type, so the renderer can show a type-specific loader before the surface arrives. - KletsoPingFrame
- Application-level heartbeat.
- KletsoPongFrame
- Heartbeat reply.
- KletsoPushToken
-
A device push token registered for the current end user. The host
obtains it from its own push plugin (e.g.
firebase_messaging) and hands it toKletsoClient.registerPushToken; the SDK never bundles a push plugin. - KletsoReadyFrame
- Auth accepted; the client may send. seq is the server's current cursor for the attached conversation.
- KletsoSchemas
- The JSON Schemas of the protocol, as text.
- KletsoScreenFrame
- Screen trigger.
- KletsoServerEvent
-
A
kletso.events/v1envelope received from the runtime, after dedupe. - KletsoServerFrame
- A frame the runtime sends to the client.
- KletsoSession
- A device session: the short-lived token that authorises realtime and REST calls.
- KletsoSessionBootstrap
-
Everything
POST /v1/sessionsreturns. - KletsoSocket
- One attached realtime session. Produced by KletsoTransport.open only after the server acknowledged authentication, so readySeq is always known.
- KletsoSseEvent
- One server-sent event.
- KletsoSseParser
-
Parses a
text/event-streambody per the WHATWG spec: events end at a blank line,data:lines accumulate,id:andretry:are tracked, comment lines (:) are ignored, and events split across chunks are reassembled. Bytes go in, events come out. - KletsoSseTransport
-
KletsoTransport for environments that block WebSockets: downstream is a
text/event-streamGET /v1/conversations/:id/events?stream=1&after=Nwith the token in theAuthorizationheader; upstream frames become REST calls through KletsoApi.pingis a no-op (the server sends: pingcomments to keep the stream alive),switchreopens the stream. - KletsoSubmitAction
- Submits the values of the form with formId as a structured user turn.
- KletsoSurface
-
A
kletso.ui/v1surface document: flat components keyed by id, a root, a data model and the plain-text fallback every client can show. - KletsoSurfaceOk
- The surface may be rendered. issues may still contain non-fatal findings the renderer degrades around (unknown types, dangling children).
- KletsoSurfaceRejected
- The surface must not be rendered; show fallbackText when present.
- KletsoSurfaceResult
- Outcome of KletsoSurface.parse.
- KletsoSwitchFrame
- Attach the socket to another conversation.
- KletsoTokenStore
- Persists the anonymous visitor id (and nothing else by default) so a returning visitor keeps their conversations. Hosts that want secure storage implement this; the default keeps values in memory.
- KletsoToolCall
- A tool call shown in the transcript ("Searching flights…").
- KletsoToolConfirmationRequired
-
tool.confirmation_required. - KletsoToolFinished
-
tool.completedandtool.failed. - KletsoToolStarted
-
tool.started. - KletsoTrackFrame
- Event trigger.
- KletsoTransport
-
Opens realtime sockets. Implementations:
KletsoWebSocketTransport,KletsoSseTransport,KletsoAutoTransport, andFakeTransportinfake.dart. - KletsoTransportRequest
- What a transport needs to attach to a conversation.
- KletsoTriggerFired
-
trigger.fired. - KletsoTypingFrame
- The user is typing.
- KletsoUiActionEvent
-
ui.action. - KletsoUiIssue
- One validation finding.
- KletsoUiLimits
-
Size and shape limits for a
kletso.ui/v1surface. - KletsoUiPatch
-
ui.patch: partial update of an already rendered surface.datais deep-merged into the surface data;componentsreplaces nodes by id (nullremoves one). Apply with KletsoSurface.patched. - KletsoUiPending
-
ui.pending: arender_uicall is streaming. Carries the surface id and the component ids/types seen so far, in order; repeated as more appear and replaced by theui.renderwith the same toolCallId. - KletsoUiRender
-
ui.render. The surface is kept raw so the renderer can apply its own limits and known-type set via parse. - KletsoUnknownAction
- An action whose kind this client does not know. Preserved verbatim so the surface round-trips; renderers ignore it.
- KletsoUnknownComponent
- A surface referenced a component type nobody can render; the fallback text was shown instead.
- KletsoUnknownEvent
- Any event type this package does not know.
- KletsoUnknownServerFrame
- A server frame this client does not know; ignored by the SDK.
- KletsoUrlAction
- Opens url; the host allowlist is checked client- and server-side.
-
KletsoValueListenable<
T> - A value that notifies listeners when it changes.
-
KletsoValueNotifier<
T> -
A mutable KletsoValueListenable. Notifies only when the new value is not
==to the old one. - KletsoVoiceCommitFrame
- Push-to-talk release: the buffered audio is one utterance, answer it.
- KletsoVoiceController
-
Drives one voice session on the active conversation (D78): sends the
voice.*frames, forwards microphone audio, plays assistant audio through the installed KletsoAudioIo, tracks the state the server reports and exposes captions and levels for the UI. - KletsoVoiceEnded
-
voice.ended. - KletsoVoiceInfo
-
Voice capability of the agent, from the session bootstrap. enabled
only says the customer switched voice on; whether their key works is
learned when a session starts (
error not_configured). - KletsoVoiceInterrupted
-
voice.interrupted: the user started speaking while the assistant was; clients stop playback and drop buffered audio immediately. - KletsoVoicePlayedFrame
- Playback progress of an assistant audio item, so the runtime can cut the model's transcript where the user interrupted.
- KletsoVoiceStarted
-
voice.started: a voice session is open on this conversation. - KletsoVoiceStartFrame
- Opens a voice session on the attached conversation. Audio then travels as binary frames (see KletsoAudioFrame).
- KletsoVoiceStateEvent
-
voice.state. - KletsoVoiceStopFrame
- Ends the voice session.
- KletsoVoiceTextFrame
- Typed text during a voice session; routed to the voice model, not the text agent.
- KletsoVoiceTranscript
-
voice.transcript: what the user said. Partial transcripts are replaced by the next one; the final transcript also arrives as a usermessage.createdwithmodality: voice. - KletsoWebSocketTransport
-
KletsoTransport over
package:web_socket(IO, browser and Cupertino implementations, Wasm-ready). Authenticates with a firstauthframe and resolves oncereadyarrives. - KletsoWorkflowAction
- Starts a workflow run tied to the conversation.
- KletsoWorkflowEvent
-
workflow.started/.completed/.failed.
Enums
- KletsoConnectionState
- Observable state of the realtime connection.
- KletsoConversationStatus
- Lifecycle state of a conversation.
- KletsoEnvironment
- Which Kletso environment a session belongs to.
- KletsoFinishReason
- Why the model stopped generating.
- KletsoLogLevel
- Verbosity of the SDK log.
- KletsoMessageModality
- How a message was produced.
- KletsoMessageStatus
- Delivery state of a message.
- KletsoMoodSource
-
Who chose an
avatar.mood. - KletsoNotificationChannel
-
How the SDK presents an
app.notifyevent. - KletsoNotificationSource
- Where a notification came from.
- KletsoPushPlatform
- Push providers the runtime can deliver through.
- KletsoRole
- Who authored a message.
- KletsoToolCallStatus
- State of a tool call inside an assistant turn.
- KletsoTransportMode
- How the SDK reaches the realtime endpoint.
- KletsoTriggerKind
- What started a triggered conversation.
- KletsoUiIssueCode
- What went wrong with a surface during validation.
- KletsoVoiceEndReason
- Why a voice session ended.
- KletsoVoiceMode
- Turn-taking mode of a voice session.
- KletsoVoiceState
-
What the voice session is doing, as reported by
voice.state. - KletsoVoiceStatus
- Lifecycle of a voice session as seen by the UI.
- KletsoVoiceStopReason
- Why the client stops a voice session.
- KletsoWorkflowStatus
-
State of a workflow run as reported by
workflow.*events.
Functions
-
jsonEquals(
Object? a, Object? b) → bool - Deep structural equality for decoded JSON values.
Typedefs
-
JsonMap
= Map<
String, Object?> -
A JSON object as decoded by
dart:convert. - KletsoBindingResolver = Object? Function(KletsoBinding binding)
-
Supplies values for bindings the surface data does not hold (host app
state such as
/host/cart/total). Returnnullwhen unknown. - KletsoConversation = KletsoConversationInfo
-
A conversation as listed for the end user. Same shape as the
conversation.*event payloads, so one type serves both. - KletsoLogger = void Function(KletsoLogLevel level, String message, {Object? error, StackTrace? stackTrace})
-
Receives SDK log lines. The default logger writes to
dart:developerunder the namekletso. -
KletsoTokenRefresher
= Future<
String?> Function() -
Called when the server reports the session token expired (4403). Return
the new token, or
nullto give up. -
KletsoUserTokenRefresher
= Future<
String?> Function() - Returns a fresh host-signed user token when the current one expired.
-
KletsoWebSocketConnector
= Future<
WebSocket> Function(Uri url, {Iterable<String> ? protocols}) -
Opens a
WebSocketand connects to the socket factory; injectable so tests can supply a fake without a network.
Exceptions / Errors
- KletsoAuthException
- The key, user token or session token was rejected.
- KletsoException
-
Base of every error the SDK surfaces. Public futures throw these; every
one is also emitted on the event stream as
KletsoClientError. - KletsoNetworkException
- The network was unreachable or the connection dropped.
- KletsoProtocolException
- A frame or response did not match the protocol.
- KletsoQueueOverflowException
- The outbound queue was full and the oldest frame was dropped.
- KletsoRateLimitException
- The runtime asked the client to slow down.
- KletsoSchemaException
-
Thrown when a wire payload does not have the structure the protocol
requires (missing field, wrong type, wrong
schemamarker). - KletsoServerException
- The runtime returned an error envelope.
- KletsoStateException
-
The SDK was used before
init/authenticate, or afterdispose. - KletsoTimeoutException
- A connection attempt or request did not complete in time.
- KletsoToolException
-
A tool call failed during a turn (
tool.failed). - KletsoWorkflowException
-
A workflow run failed (
workflow.failed).