Public SDK interfaces use camelCase by default. Protocol-bound multimodal content keys (
media_type, blob_id, duration_ms) intentionally remain wire-shaped.Imports
The stable domain types and helpers are re-exported from the package root:Additional client wrappers
The package exports more than the core session lifecycle. TheMeerkatClient also exposes:
- auth-profile helpers:
authProfileList,authProfileGet,authProfileCreate,authProfileDelete - auth-login helpers:
authLoginStart,authLoginComplete,authLoginDeviceStart,authLoginDeviceComplete,authLoginProvisionApiKey,authStatusGet,authLogout - realm helpers:
realmList,realmGet - typed ingress helper:
sendPeerResponseTerminal - MCP live-op helpers:
mcpAdd,mcpRemove,mcpReload - blob/skill helpers:
getBlob,listSkills - runtime host helpers:
getRuntimeHostInfo,getRuntimeHostCapabilities,getRuntimeHostHealth - transcript and recovery helpers:
inputState,exportSessionAtif, revision read/list, fork-at/fork-replace, rewrite, system-prompt update, and restore - WorkGraph observability: item/ready/event listing, snapshot, goal status, and attention listing
- detached jobs and monitors: the
jobs*family plusmonitorsStartand the authority-checkedmobkitJob*worker mutations - approvals and artifacts: request/list/get/decide plus list/get/download artifacts
- projected event recovery:
latestEventCursor,listEventsSince,eventSnapshotwhen host event projection is enabled - live-channel helpers:
liveOpen,liveStatus,liveClose,liveSendInput,liveSendInputImage,liveSendInputVideoFrame,liveCommitInput,liveWebrtcAnswer,liveInterrupt,liveTruncate,liveRefresh, andparseLiveObservation
SessionOptions.authBinding
or in a mob member spec instead of embedding provider secrets. A remote member
host resolves that binding only inside its authorized realm.
Core types
RunResult
The result returned bysession.turn(), session.invokeSkill(), and deferred.startTurn(). Session creation returns runtime-backed Session or DeferredSession wrappers, and the latest RunResult remains available through session.lastResult or stream.result after an EventStream is fully consumed.
Session
client.createSession() returns a runtime-backed Session wrapper.
Session methods are thin conveniences over canonical runtime calls:
await session.turn(...)session.stream(...)await session.history(...)await session.archive()await session.interrupt()await session.stopRun(runId, reason)await session.invokeSkill(...)await session.subscribeEvents()
DeferredSession
client.createDeferredSession() reserves session identity now and runs the
first turn later through await deferred.startTurn(...), or streams it through
deferred.stream(...) -> EventStream. Although deferred creation reuses
SessionOptions, the server rejects transientTurnContext because no
immediate turn exists. Current DeferredTurnOptions omits injectedContext,
transientTurnContext, and selfHostedServerId. Set injected context during
deferred creation; transient first-turn context and a self-hosted server route
are not expressible through the current deferred TypeScript wrapper. Both
deferred turn methods accept skillRefs, turnToolOverlay,
additionalInstructions, keepAlive, model, provider, maxTokens,
systemPrompt, outputSchema, structuredOutputRetries, and
providerParams.
LiveChannel
LiveChannel is the session-bound helper for the live/* RPC surface.
RealtimeChannel was removed with the live-adapter surface; use
LiveChannel.session(client, sessionId, options?) instead.
channel_id returned by live/open. It does not own the
transport. Branch on opened.transport.transport: websocket carries url
and token; webrtc carries token, answer_method, and optional
http_url. Use client.liveWebrtcAnswer(...) to exchange a completed
browser-created SDP offer. Do not assume every bootstrap has a URL.
The Node SDK does not provide RTCPeerConnection; inject an implementation or
forward browser-created SDP to the Node process. Add an audio track or the
meerkat.live data channel, set the local description, wait for ICE gathering
to complete, and send peer.localDescription.sdp. The 0.8.24
answerLiveWebrtcOffer(...) helper does not perform that wait and sends the
original offer SDP, so use direct client.liveWebrtcAnswer(...) for the
canonical browser exchange. WebRTC also requires an rkat-rpc binary compiled
with the non-default live-webrtc Cargo feature. The 0.8.24 release binary
does not include that feature, so liveWebrtc: true requires a custom binary.
The direct helper has the same required identity:
client.liveSendInputImage(channelId, idempotencyKey, mime, dataBase64).
LiveChannelOptions.seedMaxChars forwards as LiveOpenParams.seed_max_chars.
It must be positive, bounds serialized seed messages, and requests a
core-owned whole-turn suffix; omission preserves the complete canonical seed.
Every ordered System message must fit. Runtime context and complete image identity,
tombstone, and accounting sidecars remain outside the window. Any truncation
reports degraded continuity, and the server rejects zero.
Usage
Token usage. All fields are camelCase - there is nototal_tokens field.
turn_completed this is per-call
usage: inputTokens is the raw provider counter (for Anthropic, uncached input
only) and accounting names the resolved provider/model plus the normalized
presentedTokens for that call. On RunResult.usage and run_completed it is
the session-cumulative total: inputTokens is already the sum of every
recorded call’s presentedTokens, it is persisted with the session so it keeps
growing across turns, and accounting is absent because a session may span
models.
Do not sum the cumulative value with anything - take the latest one - and sum
accounting.presentedTokens rather than per-call inputTokens. An
agent-loop call publishes a turn_completed row when its turn completes;
extraction requests publish theirs on the extraction outcome event, and
compaction summaries and turns that fail after the provider answered publish
none, even when the failed turn’s assistant row was already committed (a
committed row does not imply a turn_completed). So the turn_completed rows
need not reconcile with the cumulative total. See
Usage accounting for the worked example.
SessionInfo
Summary returned byclient.listSessions().
Capability
A single runtime capability entry, as returned byclient.capabilities.
{ DisabledByPolicy: { ... } }). The SDK normalizes these to the key string automatically.
ContentBlock
Content blocks are used in multimodal prompts and tool results. BothcreateSession() and session.turn() accept string | ContentBlock[] as the prompt parameter.
SchemaWarning
Emitted when a structured output response did not fully conform to the requested schema.Skill types
SkillKey
Structured skill identifier.SkillRef
A skill reference is a structuredSkillKey.
SkillRuntimeDiagnostics
Runtime diagnostics from the skill subsystem. Present onRunResult.skillDiagnostics when the server emits skill health data.
EventStream
EventStream is an AsyncIterable<StreamEvent> returned by
createSessionStreaming() and session.stream(). It yields events as the
agent runs, then makes the final RunResult available on stream.result.
StreamEvent includes AgentEvent and scoped wrappers. Use the exported type
guards for direct payloads because UnknownEvent keeps the event union
open-ended; the guards do not unwrap scoped events.
Iterating
collect()
Discards all events and returns the final result:collectText()
Accumulates alltext_delta events and returns the joined string alongside the result:
Typed events
All events are discriminated on thetype field (snake_case, matching the wire protocol). All other fields are camelCase.
AgentEvent union
type outside the generated
KNOWN_AGENT_EVENT_TYPES inventory throws a MeerkatError with code
UNKNOWN_EVENT_TYPE. An inventory-known type without a handwritten parser
case arrives as UnknownEvent, preserving the wire type in event.type and
the complete payload as fields on the event. A missing event type or a malformed
payload for a handwritten parser case is preserved as MalformedEvent
(type: "malformed_event").
The current inventory includes server_tool_content, all four
model_fallback_* events, transcript_rewrite_audit_receipt_committed,
boundary_append_applied, and boundary_appends_discarded. These currently
use the raw-preserving UnknownEvent path, as do reasoning_delta,
reasoning_complete, assistant_image_appended,
turn_usage_accounting_unmeasured,
turn_usage_accounting_identity_disputed, interaction_callback_pending,
peer_content_ingested, and provider_cache_breakpoints_discarded. See the
RPC event reference for their wire contracts.
live_channel_closed has a handwritten parser and arrives as a typed
LiveChannelClosedEvent: sessionId, channelId, reason and
reopenRecommended. It is published once for every committed close of one of
the session’s live channels. reason is a LiveChannelCloseReason:
client_requested, client_disconnected, provider_closed, error,
media_fault, replaced or open_abandoned; any other value is a malformed
payload. reopenRecommended is true only for a media_fault whose session
may still reopen the channel with its retained context.
RunStartedEvent.input preserves the typed RunInput: either
{ kind: "content", content: ... } or { kind: "pending_tool_results" }.
Content may be text or content blocks; the continuation variant does not
fabricate a prompt. RunFailedEvent accepts the current error_report and
derives its errorClass and error display fields from that report.
RetryingEvent parses the current wire shape, which carries one typed
retry schedule: attempt, maxAttempts, error and delayMs are
projections of retry.plan.attempt, retry.plan.max_retries,
retry.failure.message and retry.plan.selected_delay_ms, and the schedule
itself is kept in retry. The flat legacy shape is still accepted.
HookFailedEvent.reason contains a known native cause or an
UnknownHookFailureReason with reason_code: "unknown". Unknown wire reason
codes and confinement refusal strings retain the exact original object in
reason.raw and its original reason code in reason.rawReasonCode; their
error display is "unknown hook failure". Known native objects stay unchanged
and narrow normally by reason.reason_code, including their typed fields.
Inspect fields inside the unknown wrapper’s raw defensively. Use the typed
reason instead of parsing the display-only error.
The legacy flat error wire remains accepted with reason absent. A present
reason is authoritative even when error is also supplied. Malformed
required fields in a known cause still produce MalformedEvent with the raw
payload preserved, without falling back to the legacy error.
request_reasoning_lowered is likewise recognized through the generated
inventory and preserved by the raw-event path.
hook_launch_refused is recognized through the current generated inventory
and preserved by the existing raw-event path, including reason and the exact
optional tool_use_id. This mechanical prelaunch fact is separate from a
permission denial or a terminal run event.
TurnStartedEvent, TextDeltaEvent, TextCompleteEvent,
TurnCompletedEvent and RetryingEvent carry an optional
assistantMessageId. It equals assistantMessageId on the block_assistant
SessionMessage that history returns for the same message, so join live rows
to history by that id, never by text or position.
RunCompletedEvent.assistantMessageId names the message whose text result
repeats. The raw payloads of reasoning_delta, reasoning_complete,
server_tool_content and assistant_image_appended carry the same
assistant_message_id key. Only a history row carrying the id is the commit:
TurnCompletedEvent is a live signal that can arrive before work that still
fails the run, and can be missing for a committed row, so reconcile against
history when the run ends. Rows the realtime transcript materializer commits
have no id; their SessionMessage.realtimeOrigin.provider_item_ids match the
provider item ids on the live transport’s realtime observations. See
assistant message identity
for retry, compaction and rewrite semantics.
Session lifecycle events
Turn and LLM events
Tool execution events
Compaction events
Budget events
Retry events
Hook events
HookFailureReason and UnknownHookFailureReason are public adapter types.
ConfinementRefusal is also exported for the known native confinement causes.
Skill events
SkillResolutionFailureReason is a typed union discriminated on reasonType
(not_found, capability_unavailable, load, parse, source_uuid_collision,
source_uuid_mutation_without_lineage, missing_skill_remaps,
remap_without_lineage, unknown_skill_alias, remap_cycle,
no_skill_engine, unknown). no_skill_engine carries
requested: readonly SkillKey[], the explicit selection that could not
resolve because the agent was built without a skill engine. A reasonType
this SDK does not know is returned as unknown with rawReasonType set.
Comms events
Tool config events
Background job events
terminalStatus is the typed semantic status; detail is the human-readable description.
Stream management
Transcript rewrite events
New inventory-known events
The inventory-known rows without handwritten parser cases listed above arrive asUnknownEvent. Inspect event.type and the raw event fields using
the RPC event reference; generated wire types describe
their payloads even where no ergonomic event interface is exported.
Type guard utilities
The SDK exports type guards for the most commonly used events:Error handling
All errors extendMeerkatError. Catch it as a base class or use the specific subclasses for targeted handling.
Error classes
Common error codes
Skills
BothcreateSession() and session.turn() accept structured skill parameters.
key.source_uuid / key.skill_name fields,
which must be mapped to SkillRef’s camelCase keys. The turn examples require
an installed active skill and reject ambiguous names; select the intended
source UUID explicitly when multiple sources provide that name.
Version compatibility
- While the major version is
0, minor versions must match exactly between SDK and server. - From
1.0.0onwards, standard semver applies: major versions must match.
connect(). A MeerkatError with code VERSION_MISMATCH is thrown if versions are incompatible.
See also
- TypeScript SDK overview - getting started, client and session API
- Python SDK - Python SDK
- RPC reference - JSON-RPC protocol specification
