> ## Documentation Index
> Fetch the complete documentation index at: https://docs.rkat.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# TypeScript SDK reference

> Types, events, error classes, and version compatibility for the @rkat/sdk TypeScript SDK.

> [!NOTE]
>
> 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:

```typescript theme={null}
import {
  MeerkatClient,
  Session,
  LiveChannel,
  Mob,
  EventStream,
  EventSubscription,
  MeerkatError,
  CapabilityUnavailableError,
  SessionNotFoundError,
  SkillNotFoundError,
  CONTRACT_VERSION,
} from "@rkat/sdk";

import type {
  RunResult,
  Usage,
  SessionInfo,
  SessionOptions,
  LiveChannelOptions,
  LiveOpenResult,
  LiveStatusResult,
  LiveInputChunkWire,
  ContentBlock,
  Capability,
  SkillKey,
  SkillRef,
  SkillRuntimeDiagnostics,
  SchemaWarning,
  AgentEvent,
  StreamEvent,
  AgentEventEnvelope,
  AttributedMobEvent,
  EventEnvelope,
  AttributedEvent,
  MobMember,
  MobStatus,
  MobSummary,
  SpawnSpec,
  MobFlowStatus,
  MobLifecycleAction,
  MobDefinition,
  TextDeltaEvent,
  TurnCompletedEvent,
  // ... all event types
} from "@rkat/sdk";
```

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`
* 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](https://docs.rkat.ai/api/rpc.md#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](https://docs.rkat.ai/api/rpc.md#approvals).

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.

```typescript theme={null}
interface RunResult {
  readonly sessionId: string;
  readonly sessionRef?: string;
  readonly text: string;
  readonly turns: number;
  readonly toolCalls: number;
  readonly usage: Usage;
  readonly terminalCauseKind?: TurnTerminalCauseKind;
  readonly structuredOutput?: unknown;
  readonly extractionError?: ExtractionError;
  readonly schemaWarnings?: readonly SchemaWarning[];
  readonly skillDiagnostics?: SkillRuntimeDiagnostics;
}
```

| Field | Type | Description |
| - | - | - |
| `sessionId` | `string` | Stable UUID for this session |
| `sessionRef` | `string \| undefined` | Optional human-readable reference |
| `text` | `string` | Full assistant text from the last LLM turn |
| `turns` | `number` | Number of LLM turns in this run |
| `toolCalls` | `number` | Total tool calls executed in this run |
| `usage` | `Usage` | Token usage for this run |
| `terminalCauseKind` | `TurnTerminalCauseKind \| undefined` | Machine-owned terminal cause when success carries a typed terminal condition (e.g. budget exhaustion) |
| `structuredOutput` | `unknown \| undefined` | Parsed structured output when `outputSchema` was provided |
| `extractionError` | `ExtractionError \| undefined` | Extraction failure details (`lastOutput`, `attempts`, `reason`) when schema extraction failed after a completed main run |
| `schemaWarnings` | `SchemaWarning[] \| undefined` | Warnings emitted when structured output didn't fully match the schema |
| `skillDiagnostics` | `SkillRuntimeDiagnostics \| undefined` | Runtime diagnostics from the skill subsystem |

### Session

`client.createSession()` returns a runtime-backed `Session` wrapper.

```typescript theme={null}
class Session {
  readonly id: string;
  readonly ref?: string;
  readonly text: string;
  readonly usage: Usage;
  readonly turns: number;
  readonly toolCalls: number;
  readonly structuredOutput?: unknown;
  readonly lastResult: RunResult;
}
```

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.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.

```typescript theme={null}
const channel = LiveChannel.session(client, session.id, {
  turningMode: "explicit_commit",
  seedMaxChars: 24_000,
});

const opened: LiveOpenResult = await channel.open();
await channel.sendInputImage("turn-42-diagram", "image/png", imageDataBase64);
// Queue acceptance is not durability; wait for user_content_committed with
// idempotency_key === "turn-42-diagram" before sending dependent input.
await channel.sendInputText("hello");
await channel.commitInput("text");
const status: LiveStatusResult = await channel.status();
const refresh = await channel.refresh();
await channel.close();
```

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](https://docs.rkat.ai/guides/realtime.md) for what the channel does next.

### Usage

Token usage. All fields are camelCase - there is no `total_tokens` field.

```typescript theme={null}
interface ProviderTokenAccounting {
  readonly provider: string;
  readonly model: string;
  readonly presentedTokens: number;
  readonly convention: string;
  readonly aggregation: string;
}

interface Usage {
  readonly inputTokens: number;
  readonly outputTokens: number;
  readonly cacheCreationTokens?: number;
  readonly cacheReadTokens?: number;
  readonly accounting?: ProviderTokenAccounting;
}
```

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](https://docs.rkat.ai/reference/usage-accounting.md) for the worked example.

### SessionInfo

Summary returned by `client.listSessions()`.

```typescript theme={null}
interface SessionInfo {
  readonly sessionId: string;
  readonly sessionRef?: string;
  readonly createdAt: number;
  readonly updatedAt: number;
  readonly messageCount: number;
  readonly totalTokens?: number;
  readonly isActive: boolean;
  readonly model?: string;
  readonly provider?: string;
  readonly lastAssistantText?: string;
  readonly resolvedCapabilities?: ResolvedModelCapabilities;
  readonly labels: Readonly<Record<string, string>>;
}
```

### Capability

A single runtime capability entry, as returned by `client.capabilities`.

```typescript theme={null}
interface Capability {
  readonly id: string;
  readonly description: string;
  readonly status: string;  // "Available", "DisabledByPolicy", "NotCompiled", etc.
}
```

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.

```typescript theme={null}
type ContentBlock =
  | { type: "text"; text: string }
  | { type: "image"; media_type: string; data: string; source?: "inline" }
  | { type: "image"; media_type: string; source: "blob"; blob_id: string }
  | { type: "video"; media_type: string; duration_ms: number; data: string; source?: "inline" }
  | { type: "video"; media_type: string; duration_ms: number; source: "uri"; uri: string };
```

| Variant | Fields | Description |
| - | - | - |
| `text` | `text: string` | Plain text content |
| `image` | `media_type: string`, `data: string` | Base64-encoded image with MIME type (e.g. `"image/png"`) |

```typescript theme={null}
// Multimodal prompt example
const session = await client.createSession([
  { type: "text", text: "Describe this image" },
  { type: "image", media_type: "image/png", data: base64Data },
]);
```

### SchemaWarning

Emitted when a structured output response did not fully conform to the requested schema.

```typescript theme={null}
interface SchemaWarning {
  readonly provider: string;
  readonly path: string;
  readonly message: string;
}
```

***

## Skill types

### SkillKey

Structured skill identifier.

```typescript theme={null}
interface SkillKey {
  readonly sourceUuid: string;
  readonly skillName: string;
}
```

### SkillRef

A skill reference is a structured `SkillKey`.

```typescript theme={null}
type SkillRef = SkillKey;
```

### SkillRuntimeDiagnostics

Runtime diagnostics from the skill subsystem. Present on `RunResult.skillDiagnostics` when the server emits skill health data.

```typescript theme={null}
interface SkillRuntimeDiagnostics {
  readonly sourceHealth: SourceHealthSnapshot;
  readonly quarantined: readonly SkillQuarantineDiagnostic[];
}

interface SourceHealthSnapshot {
  readonly state: string;
  readonly invalidRatio: number;
  readonly invalidCount: number;
  readonly totalCount: number;
  readonly failureStreak: number;
  readonly handshakeFailed: boolean;
}

interface SkillQuarantineDiagnostic {
  readonly sourceUuid: string;
  readonly skillId: string;
  readonly location: string;
  readonly errorCode: string;
  readonly errorClass: string;
  readonly message: string;
  readonly firstSeenUnixSecs: number;
  readonly lastSeenUnixSecs: number;
}
```

***

## 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.

```typescript theme={null}
class EventStream implements AsyncIterable<StreamEvent> {
  readonly sessionId: string;
  readonly result: RunResult;  // throws if accessed before iteration completes

  [Symbol.asyncIterator](): AsyncGenerator<StreamEvent, void, undefined>;

  /** Consume all events and return the final RunResult. */
  collect(): Promise<RunResult>;

  /** Consume events, accumulate text deltas, return [fullText, result]. */
  collectText(): Promise<[string, RunResult]>;
}
```

### Iterating

```typescript theme={null}
import { isTextDelta } from "@rkat/sdk";

const stream = session.stream("Summarise this");
for await (const event of stream) {
  if (isTextDelta(event)) {
    process.stdout.write(event.delta);
  }
}
const result = stream.result;
```

### collect()

Discards all events and returns the final result:

```typescript theme={null}
const result = await stream.collect();
```

### collectText()

Accumulates all `text_delta` events and returns the joined string alongside the result:

```typescript theme={null}
const [fullText, result] = await stream.collectText();
console.log(fullText);
console.log("Output tokens:", result.usage.outputTokens);
```

***

## Typed events

All events are discriminated on the `type` field (snake\_case, matching the wire protocol). All other fields are camelCase.

### AgentEvent union

```typescript theme={null}
type AgentEvent =
  | RunStartedEvent
  | RunCompletedEvent
  | ExtractionSucceededEvent
  | ExtractionFailedEvent
  | RunFailedEvent
  | TurnStartedEvent
  | TextDeltaEvent
  | TextCompleteEvent
  | ToolCallRequestedEvent
  | ToolResultReceivedEvent
  | TurnCompletedEvent
  | ToolExecutionStartedEvent
  | ToolExecutionCompletedEvent
  | ToolExecutionTimedOutEvent
  | CompactionStartedEvent
  | CompactionCompletedEvent
  | CompactionFailedEvent
  | BudgetWarningEvent
  | RetryingEvent
  | HookStartedEvent
  | HookCompletedEvent
  | HookFailedEvent
  | HookDeniedEvent
  | SkillsResolvedEvent
  | SkillResolutionFailedEvent
  | InteractionCompleteEvent
  | InteractionFailedEvent
  | StreamTruncatedEvent
  | ToolConfigChangedEvent
  | BackgroundJobCompletedEvent
  | LiveChannelClosedEvent
  | TranscriptRewriteCommittedEvent
  | MalformedEvent
  | UnknownEvent;
```

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`, and
`tool_results_bounded_for_request`. See the
[RPC event reference](https://docs.rkat.ai/api/rpc.md#notifications) 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.

```typescript theme={null}
interface ContentFilteredAgentErrorReason {
  readonly reasonType: "content_filtered";
  readonly stop: "refusal" | "content_filter";
  readonly detail?: ContentFilteredStopDetail; // { provider: string, ... }
}
```

`ToolConfigChangedPayload.settled` replaces `persisted` in 0.9.4 (see
[Tool config events](#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](#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](https://docs.rkat.ai/reference/session-contracts.md#assistant-message-identity)
for retry, compaction and rewrite semantics.

### Session lifecycle events

```typescript theme={null}
interface RunStartedEvent   { type: "run_started";   sessionId: string; input: RunInput; identity?: TranscriptMessageIdentity }
interface RunCompletedEvent {
  type: "run_completed";
  sessionId: string;
  result: string;
  structuredOutput?: unknown;
  extractionRequired?: boolean;
  usage: Usage;
  terminalCauseKind?: TurnTerminalCauseKind;
  assistantMessageId?: string;
}
interface ExtractionSucceededEvent {
  type: "extraction_succeeded";
  sessionId: string;
  structuredOutput: unknown;
  schemaWarnings?: readonly SchemaWarning[];
}
interface ExtractionFailedEvent {
  type: "extraction_failed";
  sessionId: string;
  lastOutput: string;
  attempts: number;
  reason: string;
}
interface RunFailedEvent {
  type: "run_failed";
  sessionId: string;
  errorClass: string;
  error: string;
  terminalCauseKind?: TurnTerminalCauseKind;
  errorReport?: AgentErrorReport | null;
}
```

### Turn and LLM events

```typescript theme={null}
interface TurnStartedEvent        { type: "turn_started";         turnNumber: number; assistantMessageId?: string }
interface TextDeltaEvent          { type: "text_delta";            delta: string; assistantMessageId?: string }
interface TextCompleteEvent       { type: "text_complete";         content: string; assistantMessageId?: string }
interface ToolCallRequestedEvent  { type: "tool_call_requested";   id: string; name: string; args: ToolCallArguments }
interface ToolResultReceivedEvent { type: "tool_result_received";  id: string; name: string; content: readonly ContentBlock[]; isError?: boolean }
interface TurnCompletedEvent      { type: "turn_completed";        stopReason?: StopReason; usage?: Usage; assistantMessageId?: string }
```

```typescript theme={null}
type StopReason =
  | "end_turn"
  | "tool_use"
  | "max_tokens"
  | "stop_sequence"
  | "content_filter"
  | "cancelled"
  | "refusal"
  | "pause_turn"
  | "context_window_exceeded";
```

### Tool execution events

```typescript theme={null}
interface ToolExecutionStartedEvent   { type: "tool_execution_started";    id: string; name: string }
interface ToolExecutionCompletedEvent { type: "tool_execution_completed";   id: string; name: string; isError?: boolean; durationMs?: number }
interface ToolExecutionTimedOutEvent  { type: "tool_execution_timed_out";   id: string; name: string; timeoutMs: number }
```

### Compaction events

```typescript theme={null}
interface CompactionStartedEvent   { type: "compaction_started";   inputTokens: number; estimatedHistoryTokens: number; messageCount: number }
interface CompactionCompletedEvent { type: "compaction_completed";  summaryTokens: number; messagesBefore: number; messagesAfter: number; summarySource?: CompactionSummarySource; estimatedHistoryTokensAfter?: number }
// Who wrote the summary; a provider call says how much of the history its source carried.
type CompactionSummarySource =
  | { kind: "provider_call"; sourceBound: SummarizationSourceBound }
  | { kind: "host_curator" } | { kind: "mechanical_fallback" }
  | { kind: "unknown"; rawKind: string; raw: Record<string, unknown> }
type SummarizationSourceBound =
  | { kind: "whole" }
  | { kind: "trimmed"; through: "tool_results" | "context" | "user_requests" }
  | { kind: "requests_only"; kept: number; of: number }
  | { kind: "unknown"; rawKind: string; raw: Record<string, unknown> }
// `reason` mirrors the Rust CompactionFailureReason tagged enum ({ kind, ... }).
interface CompactionFailedEvent    { type: "compaction_failed";     reason: Record<string, unknown> }
```

### Budget events

```typescript theme={null}
interface BudgetWarningEvent { type: "budget_warning"; budgetType: BudgetType; used: number; limit: number; percent: number }

type BudgetType = "tokens" | "time" | "tool_calls";
```

### Retry events

```typescript theme={null}
interface RetryingEvent { type: "retrying"; attempt: number; maxAttempts: number; error: string; delayMs: number; retry?: Record<string, unknown>; assistantMessageId?: string }
```

### Hook events

```typescript theme={null}
import type { HookFailureReason } from "@rkat/sdk";
type HookPoint =
  | "run_started" | "run_completed" | "run_failed"
  | "pre_llm_request" | "post_llm_response"
  | "pre_tool_execution" | "post_tool_execution"
  | "turn_boundary";

interface HookStartedEvent        { type: "hook_started";         hookId: string; point: HookPoint }
interface HookCompletedEvent      { type: "hook_completed";        hookId: string; point: HookPoint; durationMs: number }
interface HookFailedEvent         { type: "hook_failed";           hookId: string; point: HookPoint; error: string; reason?: HookFailureReason }
interface HookDeniedEvent         { type: "hook_denied";           hookId: string; point: HookPoint; reasonCode: string; message: string; payload?: unknown }
```

`HookFailureReason` and `UnknownHookFailureReason` are public adapter types.
`ConfinementRefusal` is also exported for the known native confinement causes.

### Skill events

```typescript theme={null}
interface SkillsResolvedEvent       { type: "skills_resolved";         skills: readonly SkillKey[]; injectionBytes: number }
interface SkillResolutionFailedEvent { type: "skill_resolution_failed"; skillKey?: SkillKey; reason?: SkillResolutionFailureReason }
```

`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

```typescript theme={null}
interface InteractionCompleteEvent { type: "interaction_complete"; interactionId: string; result: string; structuredOutput?: unknown }
interface InteractionFailedEvent   { type: "interaction_failed";   interactionId: string; reason: InteractionFailureReason }
```

### Tool config events

```typescript theme={null}
interface ToolConfigChangedEvent { type: "tool_config_changed"; payload: ToolConfigChangedPayload }

// Payload keys intentionally remain wire-shaped (snake_case).
interface ToolConfigChangedPayload {
  operation?: "add" | "remove" | "reload";
  target?: string;
  status_info?: ToolConfigChangeStatus;
  // A settled lifecycle fact (not pending or draining), derived from
  // status_info the way rkat-rpc derives it. Not a configuration write: that
  // is the `persisted` of the mcp/add, mcp/remove and mcp/reload responses.
  // Payloads stored by rkat-rpc 0.9.3 and earlier are served back with their
  // stored `persisted` bit; the parser derives the fact for them too.
  settled?: boolean;
  applied_at_turn?: number;
}

type ToolConfigChangeStatus =
  | { kind: "boundary_applied"; base_changed: boolean; visible_changed: boolean; revision: number }
  | { kind: "deferred_catalog_delta"; added_hidden_count: number; removed_hidden_count: number; pending_source_count: number }
  | { kind: "warning_failed_closed"; error: string }
  | { kind: "external_tool_delta"; phase: "pending" | "applied" | "draining" | "forced" | "failed"; detail?: string };
```

### Background job events

```typescript theme={null}
type BackgroundJobTerminalStatus =
  | "completed"
  | "failed"
  | "aborted"
  | "cancelled"
  | "retired"
  | "terminated";

interface BackgroundJobCompletedEvent {
  type: "background_job_completed";
  jobId: string;
  displayName: string;
  terminalStatus: BackgroundJobTerminalStatus;
  detail: string;
}
```

`terminalStatus` is the typed semantic status; `detail` is the human-readable description.

### Stream management

```typescript theme={null}
interface StreamTruncatedEvent { type: "stream_truncated"; reason: StreamTruncationReason }
```

### Transcript rewrite events

```typescript theme={null}
interface TranscriptRewriteCommittedEvent {
  type: "transcript_rewrite_committed";
  sessionId: string;
  record: Record<string, unknown>;
}
```

### 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](https://docs.rkat.ai/api/rpc.md#notifications); 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:

```typescript theme={null}
import {
  isTextDelta,
  isTextComplete,
  isTurnCompleted,
  isToolCallRequested,
  isRunCompleted,
  isRunFailed,
} from "@rkat/sdk";

for await (const event of session.stream("prompt")) {
  if (isTextDelta(event)) {
    process.stdout.write(event.delta);  // TypeScript knows event.delta exists
  }
  if (isTurnCompleted(event)) {
    console.log(event.stopReason, event.usage?.inputTokens ?? "unmeasured");
  }
}
```

***

## Error handling

All errors extend `MeerkatError`. Catch it as a base class or use the specific subclasses for targeted handling.

```typescript theme={null}
import { MeerkatError, CapabilityUnavailableError } from "@rkat/sdk";

try {
  await client.connect();
  const session = await client.createSession("Hello");
  await session.turn("Next");
} catch (err) {
  if (err instanceof CapabilityUnavailableError) {
    console.error("Missing capability:", err.message, err.capabilityHint);
  } else if (err instanceof MeerkatError) {
    console.error(`[${err.code}] ${err.message}`);
  }
} finally {
  await client.close();
}
```

### Error classes

```typescript theme={null}
class MeerkatError extends Error {
  readonly code: string;
  readonly details?: unknown;
  readonly capabilityHint?: { capability_id: string; message: string };
}

class CapabilityUnavailableError extends MeerkatError {}
class SessionNotFoundError extends MeerkatError {}
class SkillNotFoundError extends MeerkatError {}
class BinaryIntegrityError extends MeerkatError {
  readonly asset: string;
  readonly path: string | null;
  readonly expectedSha256: string;
  readonly actualSha256: string;
}
```

| Class | When thrown |
| - | - |
| `MeerkatError` | Base class for all SDK errors |
| `CapabilityUnavailableError` | `client.requireCapability()` or `session.invokeSkill()` when the required capability is not available |
| `SessionNotFoundError` | Server reports that the requested session does not exist |
| `SkillNotFoundError` | Server reports that a skill reference cannot be resolved |
| `BinaryIntegrityError` | The auto-downloaded `rkat-rpc` archive, the binary inside it or its cached copy does not match the sha256 the package pins ([The rkat-rpc binary](https://docs.rkat.ai/sdks/typescript/overview.md#the-rkat-rpc-binary)) |

### Common error codes

| Code | Cause |
| - | - |
| `NOT_CONNECTED` | Method called before `connect()` |
| `VERSION_MISMATCH` | Server contract version incompatible with SDK |
| `CAPABILITY_UNAVAILABLE` | Required capability not enabled in this build |
| `CLIENT_CLOSED` | Method called after `close()` |
| `STREAM_NOT_CONSUMED` | `stream.result` accessed before iteration completed |
| `BINARY_NOT_FOUND` | `rkat-rpc` not found and auto-download failed |
| `BINARY_DIGEST_UNAVAILABLE` | The package pins no `rkat-rpc` digest for its version and platform (a source or git install), so it will not download one |
| `BINARY_INTEGRITY_MISMATCH` | `BinaryIntegrityError`: a downloaded or cached `rkat-rpc` does not match its pinned digest |
| `BINARY_DOWNLOAD_FAILED` | The release download failed (a transport fault or a cut-off body), or redirected to a non-HTTPS URL |
| `BINARY_DOWNLOAD_TOO_LARGE` | The release archive is over 256 MiB, far above any `rkat-rpc` release archive |
| `UNKNOWN_EVENT_TYPE` | Streamed event `type` not in the generated known-event inventory |
| `PROCESS_EXITED` | The `rkat-rpc` child exited before replying (a crash, for example). Since 0.9.4 pending requests fail with it at most about a second after the exit, even while a process the child started still holds its pipes |
| `PROTOCOL_ERROR` | A reply line was not JSON, so the stream can no longer be trusted. Since 0.9.4 the client then stops the child the way `close()` does |

### 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.

```typescript theme={null}
import { commsSendError } from "@rkat/sdk";

try {
  await session.send({ kind: "peer_message", to: peerId, body: "Hello!", handling_mode: "queue" });
} catch (err) {
  const failure = commsSendError(err);
  if (failure?.code !== "peer_unreachable") throw err;
  console.error(`${failure.peer} is unreachable: ${failure.reason}`);
}
```

### 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()`.

```typescript theme={null}
import { mobDestroyIncompleteReport } from "@rkat/sdk";

try {
  await client.mobDestroy(mobId);
} catch (err) {
  const report = mobDestroyIncompleteReport(err);
  if (report === undefined) throw err;
  for (const { member, refusal } of report.member_reload_refusals ?? []) {
    console.warn(`${member}: ${refusal.kind}`);
  }
}
```

### Quarantined mobs

A call that addresses a quarantined mob (a persisted mob whose store did not
restore; see [Quarantined mobs and degraded members](https://docs.rkat.ai/guides/mobs.md#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.

```typescript theme={null}
import { mobQuarantined } from "@rkat/sdk";

try {
  await client.mobStatus(mobId);
} catch (err) {
  const refusal = mobQuarantined(err);
  if (refusal === undefined) throw err;
  if (!refusal.retryable) {
    // After repairing the store:
    await client.mobRestoreRetry(refusal.mobId);
  }
}
```

***

## Skills

Both `createSession()` and `session.turn()` accept structured skill parameters.

```typescript theme={null}
// Preload skills into the system prompt at session creation
const session = await client.createSession("Hello!", {
  preloadSkills: [
    { sourceUuid: "dc256086-0d2f-4f61-a307-320d4148107f", skillName: "extraction-email" },
    { sourceUuid: "dc256086-0d2f-4f61-a307-320d4148107f", skillName: "formatting-markdown" },
  ],
});

// Inject a skill for a specific turn via session.turn()
const matches = (await client.listSkills()).filter(
  (entry) => entry.is_active && entry.key.skill_name === "extraction-email",
);
const [skill] = matches;
if (!skill || matches.length !== 1) {
  throw new Error("Expected one active extraction-email skill; select a source UUID if ambiguous.");
}
const skillRef = {
  sourceUuid: skill.key.source_uuid,
  skillName: skill.key.skill_name,
};
const result = await session.turn("Extract emails from this text", {
  skillRefs: [skillRef],
});

// Convenience method on Session — wraps turn() with requireCapability check
const result2 = await session.invokeSkill(
  skillRef,
  "Extract emails from this text",
);
```

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

```typescript theme={null}
import { CONTRACT_VERSION } from "@rkat/sdk";
console.log(CONTRACT_VERSION);  // "0.9.10"
```

* 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

* [TypeScript SDK overview](https://docs.rkat.ai/sdks/typescript/overview.md) - getting started, client and session API
* [Python SDK](https://docs.rkat.ai/sdks/python/overview.md) - Python SDK
* [RPC reference](https://docs.rkat.ai/api/rpc.md) - JSON-RPC protocol specification


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.