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

> Getting started with the Meerkat TypeScript SDK: sessions, turns, streaming events, and capabilities.

The TypeScript SDK (`@rkat/sdk`) brings Meerkat agents into Node.js
applications. Create and resume sessions, stream typed events, schedule work
or coordinate teams through `Session`, `DeferredSession` and `Mob` handles.
It spawns a local `rkat-rpc` subprocess using the same runtime as the CLI and
service APIs. For agents that run in the browser itself, use the
[Web SDK](https://docs.rkat.ai/examples/wasm.md).

## Getting started

**1. Install the SDK**

```bash theme={null}
npm install @rkat/sdk
```

The SDK needs Node.js 20.19+ or 22.12+ (`engines.node`). It ships only
an ES module, so `require()` from CommonJS relies on Node's
`require(esm)`, which those releases enable by default; Node 21 and
22.0-22.11 are outside the range.

**2. Install the RPC binary**

```bash theme={null}
brew install lukacf/meerkat/rkat
```

Homebrew installs `rkat-rpc` with the other binaries. Without Homebrew,
download the `rkat-rpc` release archive for your platform and put it on
your `PATH` (see [Linux without Homebrew](https://docs.rkat.ai/quickstart.md#linux-without-homebrew)).
Without one, the published SDK downloads the `rkat-rpc` release binary
of its own version for the current platform and verifies it against the
digests the package pins (see [The rkat-rpc binary](#the-rkat-rpc-binary)),
so a manual binary install is optional unless you want to control the
binary path yourself. Contributors working from a checkout can build it
with `make build` instead.

You also need an API key for at least one LLM provider (e.g. `ANTHROPIC_API_KEY`).

**3. Configure tsconfig**

The SDK is ESM. Your `tsconfig.json` must use Node16 module resolution:

```json theme={null}
{
  "compilerOptions": {
    "target": "ES2022",
    "module": "Node16",
    "moduleResolution": "Node16",
    "strict": true
  }
}
```

**4. Connect and run**

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

const client = new MeerkatClient();
await client.connect();

const session = await client.createSession("What is the capital of Sweden?");
console.log(session.text);
console.log(session.id);

const result = await session.turn("And what is its population?");
console.log(result.text);

await session.archive();
await client.close();
```

***

## Method overview

### MeerkatClient methods

| Method | Description |
| - | - |
| `connect(options?)` | Spawn `rkat-rpc`, handshake, fetch capabilities |
| `close()` | Stop the `rkat-rpc` child: end its stdin, signal it, wait up to 5 seconds for it to exit, then `SIGKILL`. Since 0.9.4 it resolves as soon as the child exits, so Node can exit at once instead of about 5 seconds later |
| `createSession(prompt, options?)` | Create a session, run the first turn, return a `Session` |
| `createSessionStreaming(prompt, options?)` | Create a session and stream typed events from the first turn |
| `listSessions(options?)` | List active sessions |
| `readSession(sessionId)` | Read typed session metadata (`SessionInfo`) |
| `readSessionHistory(sessionId, options?)` | Read committed session transcript history |
| `inputState/exportSessionAtif/readSessionTranscriptRevision/listSessionTranscriptRevisions/forkSessionAt/forkSessionReplace/rewriteSessionTranscript/updateSystemPrompt/restoreSessionTranscriptRevision` | Input reconciliation, export, branching, and guarded transcript edits |
| `sendExternalEvent(sessionId, eventType, payload, options?)` | Inject a canonical external event into a session |
| `injectContext(sessionId, text, options?)` | Append one ordinary durable ordered System message |
| `getModelsCatalog()` | Read config-backed model catalog |
| `createSchedule/getSchedule/listSchedules/updateSchedule/pauseSchedule/resumeSchedule/deleteSchedule/listScheduleOccurrences/listScheduleTools/callScheduleTool` | Schedule API wrappers |
| `getWorkGraphItem/listWorkGraphItems/listReadyWorkGraphItems/getWorkGraphSnapshot/listWorkGraphEvents/getWorkGraphGoalStatus/listWorkGraphAttention` | Read-only WorkGraph, goal, and attention projections |
| `jobsGet/jobsList/jobsCancel/jobsProgress/jobsResult/jobsArtifacts/jobsRetry/jobsHealth/jobsSubscribe/jobsUnsubscribe` | Detached job control and observation |
| `monitorsStart/metaJobHeartbeat/metaJobProgress/metaJobCheckpoint/metaJobComplete/metaJobFail/metaJobCancelAck` | Monitor creation and authority-checked Meta worker updates |
| `requestApproval/listApprovals/getApproval/decideApproval` | Approval record lifecycle; persists when the RPC bundle exposes a store path |
| `grantTool/revokeToolGrant/listToolGrants/toolGrantAudit` | Scoped tool grants of a session created with `grantGatedTools` |
| `listDecisions/getDecision/decisionRendering/presentDecision/withdrawDecision` | Durable decisions of a 0.9.11 or newer server whose persistence keeps them (an older server's `-32601` names the method); no SDK method decides one |
| `listArtifacts/getArtifact/downloadArtifact` | Artifact metadata and payload access |
| `latestEventCursor/listEventsSince/eventSnapshot` | Cursor replay and snapshots when host event projection is enabled |
| `createMob(options?)` | Create a mob, return a `Mob` |
| `createDeferredSession(prompt, options?)` | Create a session without running the first turn; returns a `DeferredSession` |
| `listMobs()` | List mobs |
| `listQuarantinedMobs()` / `mobRestoreRetry(mobId)` | List the persisted mobs whose stores did not restore; re-attempt one's restore after a repair |
| `getConfig()` | Read runtime configuration |
| `setConfig(config)` | Replace runtime configuration |
| `patchConfig(patch)` | Merge-patch runtime configuration |
| `liveOpen/liveWebrtcAnswer/liveStatus/liveClose/liveSendInput/liveCommitInput/liveInterrupt/liveTruncate/liveRefresh` | Direct wrappers for the `live/*` RPC surface |

Schedule methods parse the canonical flattened response shape: planning,
timestamps, labels, and other schedule configuration are top-level fields,
not a nested `config`, and internal `machine_state` is never public. Missing or
malformed schedule, occurrence, and tool arrays—or required facts within their
entries—throw `MeerkatError` with `INVALID_RESPONSE` instead of becoming empty
or zero-valued results.

### Auth wrappers

The SDK also exposes the auth-profile wrappers from the RPC surface:

* `authProfileList(...)`, `authProfileGet(...)`, `authProfileCreate(...)`, `authProfileDelete(...)`
* `authLoginStart(...)`, `authLoginComplete(...)`, `authLoginDeviceStart(...)`, `authLoginDeviceComplete(...)`, `authLoginProvisionApiKey(...)`
* `authStatusGet(...)`, `authLogout(...)`
* `realmList(...)`, `realmGet(...)`
* `sendPeerResponseTerminal(...)`
* `mcpAdd(...)`, `mcpRemove(...)`, `mcpReload(...)`
* `getBlob(...)`, `listSkills()`
* `getRuntimeHostInfo()`, `getRuntimeHostCapabilities()`, `getRuntimeHostHealth()`

Every public TypeScript RPC wrapper binds its request and response transport
boundary to generated RPC-schema contracts. In 0.8.24, generated names used by
the job, approval, artifact, and durable-event declarations are not re-exported
from the package root; callers can pass object literals matching the displayed
method signature.

Approval methods maintain audit records only. Requesting or deciding a record
does not automatically gate, authorize, or execute an action. See
[JSON-RPC approvals](https://docs.rkat.ai/api/rpc.md#approvals) for persistence and single-writer
details.

Auth profiles and credentials are realm-scoped. Login/provisioning yields an
auth binding that can be referenced by `SessionOptions.authBinding` or a mob
member spec without placing the provider secret in that spec. Remote hosts
resolve bindings only within their authorized realm.

### Generated assistant images

When a session model calls the built-in `generate_image` tool, generated images appear in committed history as `SessionAssistantBlock` entries with `blockType === "image"`. The SDK preserves `imageId`, `blobId`, `mediaType`, `width`, `height`, `revisedPrompt`, and provider metadata.

```typescript theme={null}
const history = await session.history();
const image = history.messages
  .flatMap((message) => [...message.blocks])
  .find((block) => block.blockType === "image");
const payload = image?.blobId ? await client.getBlob(image.blobId) : undefined;
```

Image-generation wire contracts are exported for integrations that inspect tool results directly: `WireGenerateImageRequest`, `WireGenerateImageExecutionPlan`, `WireImageGenerationToolResult`, `WireImageOperationPhase`, and `WireAssistantImageRef`.

### Capability methods

| Method | Description |
| - | - |
| `client.capabilities` | Read-only array of all `Capability` objects |
| `client.hasCapability(id)` | Returns `true` if capability is `"Available"` |
| `client.requireCapability(id)` | Throws `CapabilityUnavailableError` if unavailable |

### Session methods

| Method | Description |
| - | - |
| `session.turn(prompt, options?)` | Run another turn (non-streaming), returns `RunResult` |
| `session.stream(prompt, options?)` | Run another turn with streaming, returns `EventStream` |
| `session.history(options?)` | Read committed transcript history for this session |
| `session.injectContext(text, options?)` | Append one ordinary durable ordered System message |
| `session.interrupt()` | Cancel the currently running turn |
| `session.archive()` | Remove the session from the server |
| `session.invokeSkill(skillRef, prompt)` | Invoke a skill in this session |
| `session.send(command)` | Send a typed comms command scoped to this session |
| `session.peers()` | List peers visible to this session's comms runtime |
| `session.subscribeEvents()` | Open a standalone event subscription; returns `EventSubscription<AgentEventEnvelope>` |

### Live channel helper

`RealtimeChannel` and the old realtime convenience helpers are no longer part of
the public SDK. Use `LiveChannel.session(client, session.id, options?)` for a
session-bound wrapper around the `live/*` methods. The SDK returns a
discriminated transport bootstrap from `live/open`; callers own the WebSocket
or WebRTC connection. The example below requests WebRTC explicitly. For
WebSocket, connect with `liveWs: true` and request `transport: "websocket"`.

```typescript theme={null}
import {
  LiveChannel,
  MeerkatClient,
  isLiveWebrtcBootstrap,
} from "@rkat/sdk";

async function runLiveWebrtc(
  completedOfferSdp: string,
  installRemoteAnswer: (answerSdp: string) => Promise<void>,
  imageDataBase64: string,
): Promise<void> {
  const client = new MeerkatClient();
  await client.connect({ liveWebrtc: true });

  const session = await client.createSession("Open a live channel", {
    model: "gpt-realtime-2",
    provider: "openai",
  });
  const channel = LiveChannel.session(client, session.id, {
    turningMode: "explicit_commit",
    transport: "webrtc",
    seedMaxChars: 24_000,
  });

  const openResult = await channel.open();
  if (!isLiveWebrtcBootstrap(openResult.transport)) {
    throw new Error("server did not return the requested WebRTC bootstrap");
  }
  const answered = await client.liveWebrtcAnswer({
    channel_id: openResult.channel_id,
    token: openResult.transport.token,
    offer_sdp: completedOfferSdp,
  });
  await installRemoteAnswer(answered.answer_sdp);
  await channel.sendInputImage(
    "turn-42-diagram",
    "image/png",
    imageDataBase64,
  );
  // Promise resolution is queue acceptance. Wait for user_content_committed
  // carrying "turn-42-diagram" before treating the image as durable context.
  await channel.sendInputText("hello");
  await channel.commitInput("text");
  await channel.close();
  await client.close();
}
```

`@rkat/sdk` is Node-only and does not provide `RTCPeerConnection`. Keep the
peer connection in a browser or inject a Node WebRTC implementation. Add an
audio track or the `meerkat.live` data channel, call `setLocalDescription`,
wait for ICE gathering to complete, then forward `peer.localDescription.sdp`
to the Node process. Install the returned answer as the browser peer's remote
description. A media-less or pre-ICE SDP cannot establish the live channel.

> [!WARNING]
>
> The 0.8.24 `answerLiveWebrtcOffer(...)` convenience helper does not wait for
> ICE gathering and sends the original `createOffer()` SDP instead of the final
> local description. Use the direct `client.liveWebrtcAnswer(...)` exchange
> above for the canonical browser flow until the helper is fixed.

> [!WARNING]
>
> `liveWebrtc: true` passes the `--live-webrtc` process flag, which exists only
> when `rkat-rpc` was compiled with its non-default `live-webrtc` Cargo feature.
> The 0.8.24 release binary and a normal default-feature build do not include
> that flag. From the Meerkat repository, build an explicit binary with
> `./scripts/repo-cargo build -p meerkat-rpc --features live-webrtc`, then put it
> on `PATH` or pass its path to `new MeerkatClient(path)`.

Image keys are required, caller-stable, and session-scoped. See
[Live Channels](https://docs.rkat.ai/guides/realtime.md#sending-image-input) for same-key replay,
conflict handling, and reconnect hydration limits.

`seedMaxChars` maps to `live/open.seed_max_chars`. Use a positive value to
bound serialized seed messages and request a core-selected whole-turn suffix;
omit it for the complete canonical seed. Every ordered System message must fit; an existing
compaction summary may be retained, and any truncation reports
degraded continuity. Canonical image identity, tombstone, and accounting
sidecars remain complete. The server rejects zero.

### Mob methods

| Method | Description |
| - | - |
| `mob.mobId` | The mob's identifier |
| `mob.status()` | Get mob status |
| `mob.lifecycle(action)` | Stop, resume, complete, destroy, or reset the mob |
| `mob.spawn(spec)` | Spawn a member |
| `mob.spawnMany(specs)` | Batch-spawn members |
| `mob.retire(agentIdentity)` | Retire a member |
| `mob.respawn(agentIdentity)` | Respawn a member |
| `mob.wire(a, b)` | Wire two members |
| `mob.unwire(a, b)` | Remove wiring |
| `mob.listMembers()` | List mob members |
| `mob.member(agentIdentity).send(content, options?)` | Send work to a member |
| `mob.readEvents(options?)` | Read mob event history (`mob/events`) |
| `mob.listFlows()` | List available flows |
| `mob.run(params, options?)` | Invoke the mob as a typed callable run |
| `mob.runFlow(flowId, params)` | Start a flow run |
| `mob.flowStatus(runId)` | Get flow run status |
| `mob.runResult(runId)` | Read the typed run output envelope |
| `mob.cancelFlow(runId)` | Cancel a flow run |
| `mob.subscribeMemberEvents(agentIdentity)` | Subscribe to member events; returns `EventSubscription<AgentEventEnvelope>` |
| `mob.subscribeEvents()` | Subscribe to mob-wide events; returns `EventSubscription<AttributedMobEvent>` |
| `mob.hosts()` / `mob.routeInstalls()` | Inspect member hosts and pending cross-host routes |
| `mob.bindHost(...)` / `mob.revokeHost(...)` | Bind or revoke a remote member host |
| `mob.grantScopes(...)` / `mob.revokeScopes(...)` / `mob.grants()` | Manage trusted operator control grants |
| `mob.memberHistory(...)` / `mob.hardCancel(...)` | Read remote/local history or perform an immediate hard cancel |
| `mob.stopMemberRun(agentIdentity, runId, reason)` | Stop one exact member run and terminalize its contributors |
| `mob.memberLiveOpen/status/control/close(...)` | Control a live channel on a local or remote member |

Multi-host placement and host/grant mutation are trusted JSON-RPC operator
surfaces, not agent-callable mob tools. Agent-callable spawn also cannot carry
the Rust-only `resume_from_role` one-shot durable role-migration declaration.

***

## MeerkatClient

### Constructor

```typescript theme={null}
new MeerkatClient(rkatPath?: string)
```

`MEERKAT_BIN_PATH` wins when set, then an explicit `rkatPath`, then `rkat-rpc` on `$PATH`. Otherwise the SDK downloads the release binary of its own version for the current platform and caches it in `~/.cache/meerkat/bin/rkat-rpc`.

### The rkat-rpc binary

The SDK runs `MEERKAT_BIN_PATH`, an explicit `rkatPath` and `rkat-rpc` on
`$PATH` as they are: trusting a binary you chose is your decision. Only the
download is verified. A published `@rkat/sdk` package pins the sha256 of every
release archive it may download and of the `rkat-rpc` inside it: pinned when
the package is built, from the release's manifest, with each archive's build
attestation verified, and never fetched at download time. The download uses HTTPS only, redirects included, and
refuses an archive over 256 MiB (`BINARY_DOWNLOAD_TOO_LARGE`). The archive is checked before anything is written or
extracted, the binary before it is installed, and the cached binary again each
time it is reused. A mismatch throws `BinaryIntegrityError` (code
`BINARY_INTEGRITY_MISMATCH`, with `asset`, `path`, `expectedSha256` and
`actualSha256`): the SDK deletes what failed, runs nothing and does not fall
back to another binary.

> [!NOTE]
>
> A source or git install of the SDK pins no digests and refuses to download,
> throwing `MeerkatError` with code `BINARY_DIGEST_UNAVAILABLE`. Build or install
> `rkat-rpc` yourself and put it on `$PATH`, or pass its path to
> `new MeerkatClient(path)` or set `MEERKAT_BIN_PATH` to a binary you trust.

### connect()

```typescript theme={null}
async connect(options?: ConnectOptions): Promise<this>
```

Spawns `rkat-rpc`, performs `initialize` handshake, checks contract version compatibility, and fetches capabilities. Returns `this` for chaining.

```typescript theme={null}
export interface ConnectOptions {
  realmId?: string;
  instanceId?: string;
  realmBackend?: "jsonl" | "memory" | "sqlite";
  isolated?: boolean;
  stateRoot?: string;
  contextRoot?: string;
  userConfigRoot?: string;
  liveWs?: boolean;
  liveWebrtc?: boolean;
  liveToolTimeoutMs?: number;
}
```

`realmId` and `isolated` are mutually exclusive. If `realmId` is omitted and `isolated` is not set, the spawned `rkat-rpc` process uses its normal isolated-mode default rather than a shared default realm. Reuse `realmId` explicitly to share sessions and config across processes or surfaces.
Set `liveWs: true` for the WebSocket live adapter; the SDK starts `rkat-rpc`
with an ephemeral listener and `live/open` returns its URL/token bootstrap.
Set `liveWebrtc: true` for the WebRTC bootstrap/SDP-answer path, using a binary
built with the non-default `meerkat-rpc/live-webrtc` feature. When both are
enabled, select the requested transport through `LiveChannelOptions.transport`.

### createSession()

```typescript theme={null}
async createSession(
  prompt: string | ContentBlock[],
  options?: SessionOptions,
): Promise<Session>
```

Creates a new session, runs the first turn with `prompt`, and returns a `Session` object. The `Session` holds the last `RunResult` and exposes convenience accessors for the most recent text, usage, and tool call counts.

```typescript theme={null}
const session = await client.createSession("Summarise this project", {
  model: "claude-sonnet-4-6",
  systemPrompt: "You are a senior engineer.",
  maxTokens: 4096,
});

console.log(session.text);
console.log(session.usage.inputTokens);
```

### createSessionStreaming()

```typescript theme={null}
createSessionStreaming(
  prompt: string | ContentBlock[],
  options?: SessionOptions,
): EventStream
```

Creates a new session and returns an `EventStream` for the first turn. Iterate the stream to receive typed events as they arrive. The final `RunResult` is available on `stream.result` after iteration completes.

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

const stream = client.createSessionStreaming("Explain async/await in TypeScript");

for await (const event of stream) {
  if (isTextDelta(event)) {
    process.stdout.write(event.delta);
  }
}

console.log("\nTokens used:", stream.result.usage.outputTokens);
```

### SessionOptions

All fields are camelCase:

```typescript theme={null}
interface SessionOptions {
  injectedContext?: readonly ContentInput[];
  transientTurnContext?: string;
  model?: string;
  provider?: string;
  authBinding?: WireAuthBindingRef;
  systemPrompt?: string | { action: "disable" };
  maxTokens?: number;
  outputSchema?: Record<string, unknown>;
  structuredOutputRetries?: number;
  hooksOverride?: Record<string, unknown>;
  enableBuiltins?: boolean;
  enableShell?: boolean;
  enableMemory?: boolean;
  enableSchedule?: boolean;
  enableWorkGraph?: boolean;
  enableMob?: boolean;
  enableWebSearch?: boolean;
  toolFilter?: WireToolFilter;
  grantGatedTools?: { families?: string[]; tools?: string[] };
  keepAlive?: boolean;
  commsName?: string;
  peerMeta?: Record<string, unknown>;
  budgetLimits?: Record<string, unknown>;
  providerParams?: Record<string, unknown>;
  preloadSkills?: SkillRef[];
  skillRefs?: SkillRef[];
  labels?: Record<string, string>;
  additionalInstructions?: string[];
  appContext?: unknown;
  shellEnv?: Record<string, string>;
  externalTools?: Record<string, unknown>[];
}
```

`createDeferredSession(...)` reuses `SessionOptions`, but the server rejects
`transientTurnContext` when no immediate turn exists: pass it to the first
turn instead. `startTurn(...)` and `stream(...)` take `injectedContext`,
`transientTurnContext`, `skillRefs`, `turnToolOverlay`,
`additionalInstructions`, `keepAlive`, `model`, `provider`,
`selfHostedServerId`, `systemPrompt`, `providerParams`, and `authBinding`.
The turn options also carry `maxTokens`, `outputSchema`, and
`structuredOutputRetries`, but the server refuses them on a turn with
`INVALID_PARAMS`: they are build settings, so set them on `createSession(...)`
or `createDeferredSession(...)`.

`grantGatedTools` gates built-in tool families and tool names: the session
mounts them hidden and refuses their calls until `grantTool(sessionId, { family
}, { durationMs })` or `grantTool(sessionId, { tool }, { expiresAtMs })` opens
them; see [scoped tool grants](https://docs.rkat.ai/api/rpc.md#scoped-tool-grants). `grantTool`
rejects with `INVALID_ARGS`, before sending, a target that names both or
neither of `tool` and `family`, and a window that names both or neither of
`durationMs` and `expiresAtMs`. The client sends a gate only to a server whose
contract is 0.9.9 or later, and otherwise throws `CapabilityUnavailableError`:
an older server would build the session with the gated tools ungated.

***

## Session

`createSession()` resolves to a `Session` object that acts as the handle for
subsequent turns on the same conversation. `createSessionStreaming()` instead
returns an `EventStream`: after consumption, `stream.result` is the final
`RunResult` and `stream.sessionId` is the created session's identity. The
stream does not construct a `Session` wrapper or expose its methods. Both
creation paths use the canonical runtime session lifecycle.

### Identity

```typescript theme={null}
session.id    // stable UUID string
session.ref   // optional human-readable reference (string | undefined)
```

### Last-result shortcuts

These accessors always reflect the most recent completed turn:

```typescript theme={null}
session.text            // assistant text from the last turn
session.usage           // RunResult usage: the session-cumulative token total
session.turns           // number of LLM turns in the last run
session.toolCalls       // number of tool calls in the last run
session.structuredOutput // structured output from the last run (unknown | undefined)
session.lastResult      // the full RunResult object
```

> [!WARNING]
>
> `session.usage` is the cumulative token account for the whole session to date,
> not the last turn's usage, and it keeps growing across turns. Never add
> successive readings together. See
> [Usage accounting](https://docs.rkat.ai/reference/usage-accounting.md).

### turn()

```typescript theme={null}
async turn(
  prompt: string | ContentBlock[],
  options?: {
    injectedContext?: readonly ContentInput[];
    transientTurnContext?: string;
    skillRefs?: SkillRef[];
    turnToolOverlay?: TurnToolOverlay;
    additionalInstructions?: string[];
    keepAlive?: boolean;
    model?: string;
    provider?: string;
    selfHostedServerId?: string;
    maxTokens?: number;
    systemPrompt?: string;
    outputSchema?: Record<string, unknown>;
    structuredOutputRetries?: number;
    providerParams?: Record<string, unknown>;
    authBinding?: TurnAuthBindingOverride;
  },
): Promise<RunResult>
```

Sends another turn to the session and returns the `RunResult`. Also updates the session's last-result shortcuts. `maxTokens`, `outputSchema`, and `structuredOutputRetries` are build settings: the server refuses them on a turn with `INVALID_PARAMS`, so set them when you create the session.

```typescript theme={null}
const result = await session.turn("Now explain the second point in more detail");
console.log(result.text);
```

### stream()

```typescript theme={null}
stream(
  prompt: string | ContentBlock[],
  options?: {
    injectedContext?: readonly ContentInput[];
    transientTurnContext?: string;
    skillRefs?: SkillRef[];
    turnToolOverlay?: TurnToolOverlay;
    additionalInstructions?: string[];
    keepAlive?: boolean;
    model?: string;
    provider?: string;
    selfHostedServerId?: string;
    maxTokens?: number;
    systemPrompt?: string;
    outputSchema?: Record<string, unknown>;
    structuredOutputRetries?: number;
    providerParams?: Record<string, unknown>;
    authBinding?: TurnAuthBindingOverride;
  },
): EventStream
```

Sends another turn and returns an `EventStream`, whose iterator is typed as
`AsyncIterable<StreamEvent>`. The session's last-result shortcuts are updated
when iteration completes.

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

for await (const event of session.stream("Elaborate on point three")) {
  if (isTextDelta(event)) {
    process.stdout.write(event.delta);
  }
}
// session.text is now updated
```

Injected context is durable ordered user-channel context immediately before the
prompt. `transientTurnContext` carries request-only host facts and is not a
transcript message.

### interrupt()

```typescript theme={null}
async interrupt(): Promise<void>
```

Sends `turn/interrupt` for this session. Has no effect if no turn is running.

### stopRun()

```typescript theme={null}
async stopRun(runId: string, reason: string): Promise<StopRunResult>
```

Sends `turn/stop_run`. It stops exactly `runId` (read it from the `run_started`
event's `identity.run_id`) and terminalizes every input already bound to that
run, including durable steers that joined it. `receipt.outcome` is `stopped`
(with `contributors`), `not_current` (the run is no longer current; nothing
was touched), or `not_stoppable`. `mob.stopMemberRun(agentIdentity, runId,
reason)` does the same for one mob member.

### archive()

```typescript theme={null}
async archive(): Promise<void>
```

Removes this session from the server. The `Session` object should not be used after calling `archive()`.

### invokeSkill()

```typescript theme={null}
async invokeSkill(skillRef: SkillRef, prompt: string): Promise<RunResult>
```

Calls `requireCapability("skills")`, then runs a turn with the provided
structured `SkillKey` injected. Discover an installed active skill first;
names alone need not be unique across sources:

```typescript theme={null}
const matches = (await client.listSkills()).filter(
  (entry) => entry.is_active && entry.key.skill_name === "code-review",
);
const [skill] = matches;
if (!skill || matches.length !== 1) {
  throw new Error("Expected one active code-review skill; select a source UUID if ambiguous.");
}
const result = await session.invokeSkill(
  { sourceUuid: skill.key.source_uuid, skillName: skill.key.skill_name },
  "Review this function for safety issues",
);
```

`listSkills()` returns generated wire-shaped keys; invocation maps
`key.source_uuid` and `key.skill_name` to `sourceUuid` and `skillName`.

### send() and peers()

```typescript theme={null}
async send(command: CommsCommand): Promise<CommsSendReceipt>
async peers(): Promise<PeerDirectoryEntry[]>
```

Scope comms operations to this session. Requires the `comms` capability.
Directory entries retain wire-shaped fields, including `peer_id` and
`sendable_kinds`. Display names are not routing identities and may collide:
select the intended sendable peer and send to its `peer_id`.

```typescript theme={null}
const matches = (await session.peers()).filter(
  (peer) => peer.name === "agent-b" && peer.sendable_kinds.includes("peer_message"),
);
const [peer] = matches;
if (!peer || matches.length !== 1) {
  throw new Error("Expected one sendable agent-b peer; select a peer_id if ambiguous.");
}
await session.send({
  kind: "peer_message",
  to: peer.peer_id,
  body: "Hello!",
  handling_mode: "queue",
});
```

### subscribeEvents()

```typescript theme={null}
async subscribeEvents(): Promise<EventSubscription<AgentEventEnvelope>>
```

Open a standalone event subscription for this session. Returns an async-iterable `EventSubscription` that yields typed `AgentEventEnvelope` objects.

```typescript theme={null}
const sub = await session.subscribeEvents();
for await (const envelope of sub) {
  console.log(envelope.payload.type, envelope.seq);
}
await sub.close();
```

***

## Capabilities

Capabilities are fetched automatically during `connect()`. Use them to guard code paths that depend on optional features.

```typescript theme={null}
// Read all capabilities
console.log(client.capabilities);
// [{ id: "sessions", description: "...", status: "Available" }, ...]

// Check a single capability
if (client.hasCapability("comms")) {
  const matches = (await session.peers()).filter(
    (peer) => peer.name === "agent-b" && peer.sendable_kinds.includes("peer_message"),
  );
  const [peer] = matches;
  if (!peer || matches.length !== 1) {
    throw new Error("Expected one sendable agent-b peer; select a peer_id if ambiguous.");
  }
  await session.send({
    kind: "peer_message",
    to: peer.peer_id,
    body: "Hi",
    handling_mode: "queue",
  });
}

// Assert and throw if unavailable
client.requireCapability("skills");  // throws CapabilityUnavailableError if not available
```

> [accordion] Known capability IDs
>
> | ID | Description |
> | - | - |
> | `sessions` | Session lifecycle |
> | `streaming` | Real-time event streaming |
> | `structured_output` | JSON schema structured output |
> | `hooks` | Lifecycle hooks |
> | `builtins` | Built-in tools |
> | `shell` | Shell tool |
> | `comms` | Inter-agent communication |
> | `memory_store` | Semantic memory |
> | `schedule` | Durable scheduler |
> | `work_graph` | WorkGraph goal/attention surfaces |
> | `session_store` | Session persistence |
> | `session_compaction` | Context compaction |
> | `skills` | Skill loading |
> | `mcp_live` | Live MCP server controls |

***

## Config management

`getConfig()` returns a generated `ConfigEnvelope`; writes return
`ConfigWriteResult`. These preserve optional nullable snake\_case metadata
(`realm_id`, `instance_id`, `backend`, `resolved_paths`, and, for writes,
`live_propagation`). The `config` field is `unknown`, not a typed settings
object. Patch known fields without spreading it, and print the returned value
directly or validate it before reading properties.

```typescript theme={null}
const config = await client.getConfig();
const modelUpdate = await client.patchConfig(
  { agent: { model: "claude-opus-4-8" } },
  { expectedGeneration: config.generation },
);
const updated = await client.patchConfig(
  { max_tokens: 8192 },
  { expectedGeneration: modelUpdate.generation },
);
console.log(updated.config);
```

***

## Examples

> [accordion] Structured output
>
> ```typescript theme={null}
> import { MeerkatClient } from "@rkat/sdk";
>
> const client = new MeerkatClient();
> await client.connect();
>
> const session = await client.createSession("List three European capitals", {
>   outputSchema: {
>     type: "object",
>     properties: {
>       capitals: { type: "array", items: { type: "string" } },
>     },
>     required: ["capitals"],
>   },
>   structuredOutputRetries: 3,
> });
>
> console.log(session.structuredOutput);
> // { capitals: ["Paris", "Berlin", "Madrid"] }
>
> await client.close();
> ```

> [accordion] Multi-turn conversation
>
> ```typescript theme={null}
> import { MeerkatClient } from "@rkat/sdk";
>
> const client = new MeerkatClient();
> await client.connect();
>
> const session = await client.createSession("My name is Alice.", {
>   model: "claude-sonnet-4-6",
> });
>
> const result = await session.turn("What is my name?");
> console.log(result.text);  // Mentions "Alice"
>
> await session.archive();
> await client.close();
> ```

> [accordion] Streaming a turn
>
> ```typescript theme={null}
> import { MeerkatClient, isTextDelta, isTurnCompleted } from "@rkat/sdk";
>
> const client = new MeerkatClient();
> await client.connect();
>
> const session = await client.createSession("You are a helpful assistant.", {
>   systemPrompt: "Be concise.",
> });
>
> for await (const event of session.stream("Explain Rust lifetimes in two sentences")) {
>   if (isTextDelta(event)) {
>     process.stdout.write(event.delta);
>   } else if (isTurnCompleted(event)) {
>     console.log(`\nStop reason: ${event.stopReason}`);
>     // `accounting` names the resolved model and the normalized presented
>     // input for this one call; `inputTokens` is the raw provider counter.
>     if (event.usage) {
>       console.log(
>         `${event.usage.accounting?.model}: ` +
>           `${event.usage.accounting?.presentedTokens} in / ${event.usage.outputTokens} out`,
>       );
>     } else {
>       console.log("Usage: unmeasured");
>     }
>   }
> }
>
> await client.close();
> ```

> [accordion] Invoking a skill
>
> ```typescript theme={null}
> import { MeerkatClient } from "@rkat/sdk";
>
> const client = new MeerkatClient();
>
> try {
>   await client.connect();
>   client.requireCapability("skills");
>   const matches = (await client.listSkills()).filter(
>     (entry) => entry.is_active && entry.key.skill_name === "code-review",
>   );
>   const [skill] = matches;
>   if (!skill || matches.length !== 1) {
>     throw new Error("Expected one active code-review skill; select a source UUID if ambiguous.");
>   }
>   const session = await client.createSession("Let's review some code.");
>   const result = await session.invokeSkill(
>     { sourceUuid: skill.key.source_uuid, skillName: skill.key.skill_name },
>     "Review this function for correctness and safety",
>   );
>   console.log(result.text);
> } finally {
>   await client.close();
> }
> ```

> [accordion] Multimodal prompt (image input)
>
> ```typescript theme={null}
> import { MeerkatClient, ContentBlock } from "@rkat/sdk";
> import { readFileSync } from "fs";
>
> const client = new MeerkatClient();
> await client.connect();
>
> const imageData = readFileSync("screenshot.png").toString("base64");
>
> const session = await client.createSession([
>   { type: "text", text: "What do you see in this image?" },
>   { type: "image", media_type: "image/png", data: imageData },
> ]);
>
> console.log(session.text);
> await client.close();
> ```

> [accordion] Using collectText() for simple streaming
>
> ```typescript theme={null}
> import { MeerkatClient } from "@rkat/sdk";
>
> const client = new MeerkatClient();
> await client.connect();
>
> const stream = client.createSessionStreaming("Write a haiku about Rust");
> const [fullText, result] = await stream.collectText();
>
> console.log(fullText);
> console.log("Input tokens:", result.usage.inputTokens);
>
> await client.close();
> ```

***

## See also

* [TypeScript SDK reference](https://docs.rkat.ai/sdks/typescript/reference.md) - types, events, errors, and version compatibility
* [Rust SDK overview](https://docs.rkat.ai/rust/overview.md) - Rust library API
* [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.