Skip to main content
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:
Every public TypeScript RPC wrapper binds its request and response transport boundary to generated RPC-schema contracts. Generated job, approval, artifact, and durable-event parameter/result names appear in the public client declarations but are not re-exported from the package root in 0.8.24. Pass structural object literals to those methods. This is an export/code-generation gap, not a second wire contract.

Additional client wrappers

The package exports more than the core session lifecycle. The MeerkatClient 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 plus monitorsStart and the authority-checked metaJob* worker mutations
  • approvals and artifacts: request/list/get/decide plus list/get/download artifacts
  • scoped tool grants: grantTool, revokeToolGrant, listToolGrants, toolGrantAudit
  • operator instructions (since 0.9.11): setSessionInstruction, revokeSessionInstruction, sessionInstructionStatus, setMobInstruction, revokeMobInstruction and mobInstructionStatus, and on Session and Mob setInstruction, revokeInstruction and instructionStatus
  • durable decisions: listDecisions, getDecision, decisionRendering, presentDecision, withdrawDecision (a 0.9.11 or newer server; an older one’s method not found, -32601, is raised naming the method)
  • projected event recovery: latestEventCursor, listEventsSince, eventSnapshot when host event projection is enabled
  • live-channel helpers: liveOpen, liveStatus, liveClose, liveSendInput, liveSendInputImage, liveSendInputVideoFrame, liveCommitInput, liveWebrtcAnswer, liveInterrupt, liveTruncate, liveRefresh, and parseLiveObservation
forkSessionAt and forkSessionReplace take inheritedInstructions in their options, the fork instruction policy for the instruction activations the prefix carries: "require_explicit_activation" (the default), "reactivate_inherited" or "refuse". A forked child is not materialized, so under the default and under "refuse" a prefix that carries activation rows is refused before anything is committed with FORK_INSTRUCTION_REFUSED, whose details carry the typed fork_instruction_refusal (cause and keys). With "reactivate_inherited" the child gets its own activation of every key that was effective in the source, and SessionForkResult.reactivatedInstructionCount counts those rows. A child runs under its source’s session configuration; see what a fork child inherits. Approval calls maintain audit records only; they do not automatically gate, authorize, or execute an action. Records persist when the RPC persistence bundle exposes a store path. See JSON-RPC approvals. Operator instructions are standing System-plane instructions a host sets by slot, revision and body, for one session or for the members of a mob:
A member target ({ kind: "member", agent_identity: "worker-1" }) may carry include_forks: true since 0.9.15: the record then also selects the forks of the member’s fork family, and a status read shows the field on such a record (see operator instructions). The results keep the wire shape (snake_case fields) and are checked on read: a disposition, effect, entry kind or state kind this SDK does not know fails the read (INVALID_RESPONSE), while an advisory value it does not know (a pending or blocked reason, residency, lowering) reads as { unknown: <the value> }. A refused write rejects with MeerkatError; instructionSetCode(error) reads its closed code (for example stale_revision, owned_by_mob or prepared_authorization_required), undefined for any other error. See RPC operator instructions. Auth profiles and persisted credentials are realm-scoped. Auth login or API key provisioning yields an auth binding; pass it as 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 by session.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.
The 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.recallInput({ inputId }) / await session.recallInput({ idempotencyKey }) (from 0.9.15)
  • await session.compact()
  • 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; pass it to the first turn instead. Both deferred turn methods accept injectedContext, transientTurnContext, skillRefs, turnToolOverlay, additionalInstructions, keepAlive, model, provider, selfHostedServerId, systemPrompt, providerParams, and authBinding. Their maxTokens, outputSchema, and structuredOutputRetries options are refused by the server on a turn (INVALID_PARAMS): set those build settings at creation.

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.
The helper stores the 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. MeerkatClient.parseLiveObservation(raw) types a frame from the live transport as a WireLiveAdapterObservation. Since 0.9.4 the union includes turn_failed, a response the provider ended without completing. Its failure is a WireLiveResponseFailure: route on status ("failed", "incomplete", "in_progress", or { unknown: { debug } } for a status without a wire name); reason, code and message are diagnostics only. WireLiveResponseFailure and WireLiveResponseFailureStatus are exported from @rkat/sdk. See the realtime guide for what the channel does next.

Usage

Token usage. All fields are camelCase - there is no total_tokens field.
One type serves two different accounts. When present on 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 by client.listSessions().

Capability

A single runtime capability entry, as returned by client.capabilities.
Status values may be emitted as externally-tagged Rust enum objects (e.g. { DisabledByPolicy: { ... } }). The SDK normalizes these to the key string automatically.

ContentBlock

Content blocks are used in multimodal prompts and tool results. Both createSession() 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 structured SkillKey.

SkillRuntimeDiagnostics

Runtime diagnostics from the skill subsystem. Present on RunResult.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 all text_delta events and returns the joined string alongside the result:

Typed events

All events are discriminated on the type field (snake_case, matching the wire protocol). All other fields are camelCase.

AgentEvent union

Event parsing fails closed: a present 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, provider_cache_breakpoints_discarded, tool_results_bounded_for_request, requested_compaction_skipped, and operator_instructions_applied. 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. Since 0.9.4 a run that failed because the provider refused or filtered the response (errorClass content_filtered) carries errorReport.reason as a ContentFilteredAgentErrorReason: reasonType: "content_filtered", stop ("refusal" or "content_filter") and an optional detail, the provider’s own account tagged by provider (anthropic, open_ai or gemini). A detail that is not a provider-tagged object reads as absent, and a stop the SDK does not know reads as an unknown reason with the wire object in raw. SDKs before 0.9.4 read every such reason as unknown and keep it raw.
ToolConfigChangedPayload.settled replaces persisted in 0.9.4 (see Tool config events): the parser derives it from status_info and uses a stored bit (settled, or persisted from rkat-rpc 0.9.3 and earlier) only for a status it does not know. It says nothing about configuration: whether a change was written there is the persisted of the mcpAdd, mcpRemove and mcpReload responses. A 0.9.3 SDK requires persisted and fails on every tool_config_changed event from a 0.9.4 rkat-rpc. The binary the SDK downloads always matches it, so this happens only with a binary you supply (MEERKAT_BIN_PATH, an explicit path, or rkat-rpc on PATH); upgrade the SDK with the binary. CompactionCompletedEvent.summarySource and CompactionCompletedEvent.estimatedHistoryTokensAfter (see Compaction events) are new in 0.9.4. Both are absent on completions recorded before 0.9.4; estimatedHistoryTokensAfter is also absent when the rewritten history could not be measured. A summary source or source bound kind the SDK does not know parses to { kind: "unknown", rawKind, raw }. 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 as UnknownEvent. 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 extend MeerkatError. Catch it as a base class or use the specific subclasses for targeted handling.

Error classes

Common error codes

Typed comms/send errors

A failed session.send() carries the server’s typed CommsSendErrorData in err.details, tagged on code: peer_not_found_or_not_trusted, peer_unreachable (reason is offline_or_no_ack or transport_error; a transport error’s text is in details), peer_admission_dropped, peer_input_rejected (with the envelope_id), peer_wake_refused (a seated member whose wake was refused: nothing was delivered, refusal.kind says why and retryable whether a later send can succeed), send_ambiguous (the delivery may already have landed: retry_safe is false and required_action is "reconcile", so reconcile by its envelope_id before any new attempt, since a retry can duplicate it), send_failed and invalid_command. commsSendError(err) returns it typed, or undefined for any other error. Branch on code, never on the message text.

Incomplete mob destroys

A mob destroy that did not finish (mobDestroy(), or mobLifecycle() with "destroy") rejects with code mob_destroy_incomplete; its details carry the destroy_report and retryable: true. mobDestroyIncompleteReport(err) returns that report as a WireMobDestroyReport, or undefined for any other error. Retry the destroy later: member_reload_refusals names each member whose reload the runtime refused, with its typed refusal (a kind this SDK does not know reads as { kind: "unknown" }). mobDestroy() returns the report of a finished destroy as a WireMobDestroyReport too. @rkat/web exports the same function for the rejections of mob.lifecycle("destroy"), session.destroy() and runtime.destroy().

Quarantined mobs

A call that addresses a quarantined mob (a persisted mob whose store did not restore; see Quarantined mobs and degraded members) rejects with details of kind mob_quarantined. mobQuarantined(err) returns a MobQuarantinedRefusal (mobId, quarantineClass, retryable, cause, code), or undefined for any other error. A store_unavailable mob is re-attempted by the next call that addresses it; repair the store of any other class, then call mobRestoreRetry(mobId). listQuarantinedMobs() lists the quarantined mobs (listMobs() lists only the managed ones). @rkat/web exports mobQuarantined too.

Skills

Both createSession() and session.turn() accept structured skill parameters.
Known issue, noted 2026-11-13. The four binaries in the Linux x86_64 release archives (rkat, rkat-rpc, rkat-rest, rkat-mcp) start without the built-in skills and report an empty capability list, with no error. The Python and TypeScript SDKs download and start the same rkat-rpc on Linux x86_64, so session.invokeSkill() throws CapabilityUnavailableError there, also for a skill of your own, because it checks the capability report first. A skill of your own that declares requires_capabilities is dropped by those archives without a message. See the known issue on the 0.9.14 release page for the releases and platforms that were checked and for a workaround.
Discovery returns generated 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.0 onwards, standard semver applies: major versions must match.
Version checking happens automatically during connect(). A MeerkatError with code VERSION_MISMATCH is thrown if versions are incompatible.

See also