# Iris SDK Documentation

> SDK and reference-client guide for integrating with the Iris Universal
> Intelligent Assistant Platform.

The repository currently includes a TypeScript SDK package at
`libs/iris/sdk/typescript` plus SDK code generation, documentation, versioning,
and testing utilities under `libs/iris/platform/*`. This guide documents the
implemented TypeScript SDK and gives production-ready reference patterns for
Python, Swift, Kotlin, and Rust clients against the current Iris API.

## Table Of Contents

1. [SDK Status](#sdk-status)
2. [TypeScript SDK](#typescript-sdk)
3. [Python SDK Guide](#python-sdk-guide)
4. [Swift SDK Guide](#swift-sdk-guide)
5. [Kotlin SDK Guide](#kotlin-sdk-guide)
6. [Rust SDK Guide](#rust-sdk-guide)
7. [Common Patterns](#common-patterns)
8. [Error Handling](#error-handling)
9. [Best Practices](#best-practices)
10. [Implementation Sources](#implementation-sources)

## SDK Status

| Language              | Current status         | Package/source                               | Notes                                                                                                                   |
| --------------------- | ---------------------- | -------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| TypeScript/JavaScript | Implemented in repo    | `@iris/sdk` in `libs/iris/sdk/typescript`    | Version `0.1.0`; covers conversations, memory, agents, knowledge, streaming, retries, typed errors, and custom `fetch`. |
| Python                | Reference client guide | Generated package target: `iris-sdk`         | Use the patterns below until a generated package is published.                                                          |
| Swift                 | Reference client guide | Generated package target: `IrisSDK`          | Includes Swift concurrency, SwiftUI, and Combine integration patterns.                                                  |
| Kotlin                | Reference client guide | Generated package target: `ai.iris:iris-sdk` | Includes Android and Jetpack Compose integration patterns.                                                              |
| Rust                  | Reference client guide | Generated crate target: `iris-sdk`           | Includes async/await, `reqwest`, `serde`, and feature flag patterns.                                                    |

The canonical API surface is documented in `docs/domains/iris/api/README.md`.
All examples use the current REST mount: `https://iris.oshun.dev/api/v1`.

## TypeScript SDK

### Installation

The TypeScript SDK package is maintained in the monorepo:

```bash
pnpm --filter @iris/sdk build
pnpm --filter @iris/sdk test
```

Consumer install target after publishing:

```bash
pnpm add @iris/sdk
# or
npm install @iris/sdk
```

### Configuration

```typescript
import { IrisClient, Iris, createClient } from '@iris/sdk';

const client = new IrisClient({
  apiKey: process.env.IRIS_API_KEY!,
  baseUrl: 'https://iris.oshun.dev/api/v1',
  timeout: 30_000,
  maxRetries: 3,
  headers: {
    'X-Request-ID': crypto.randomUUID(),
  },
  debug: false,
});

const alias = new Iris({ apiKey: process.env.IRIS_API_KEY! });
const factoryClient = createClient({ apiKey: process.env.IRIS_API_KEY! });
```

Configuration options:

| Option       | Required | Default        | Description                                                               |
| ------------ | -------- | -------------- | ------------------------------------------------------------------------- |
| `apiKey`     | Yes      | None           | Bearer credential for Iris.                                               |
| `baseUrl`    | No       | SDK default    | REST base URL. Set to `/api/v1` in production.                            |
| `timeout`    | No       | `30000`        | Request timeout in milliseconds.                                          |
| `maxRetries` | No       | `3`            | Retry attempts for transient failures.                                    |
| `headers`    | No       | `{}`           | Headers sent with each request.                                           |
| `debug`      | No       | `false`        | Enable SDK debug logging.                                                 |
| `fetch`      | No       | global `fetch` | Custom fetch implementation for tests, proxies, and non-browser runtimes. |
| `signal`     | No       | None           | Default abort signal.                                                     |

### Chat

Quick chat creates a conversation when needed and sends a message.

```typescript
const response = await client.chat('Summarize the release risk.');
console.log(response.assistantMessage.content);
```

Continue an existing conversation:

```typescript
const response = await client.chat('What changed since the last rollout?', {
  conversationId: '00000000-0000-0000-0000-000000000000',
  role: 'user',
  metadata: { source: 'release-dashboard' },
});
```

Simple completion returns assistant text:

```typescript
const text = await client.complete('Write a one-paragraph incident summary.', {
  temperature: 0.2,
  maxTokens: 512,
});
```

### Streaming

`chatStream` uses the conversation SSE endpoint and returns `MessageStream`.

```typescript
const stream = await client.chatStream('Stream a concise launch checklist.', {
  onText: (text) => process.stdout.write(text),
  onToolUse: (toolUse) => console.log('tool:', toolUse.name),
  onEvent: (event) => console.debug(event.type),
});

stream.on('end', (message) => {
  console.log('\nfinal:', message.text);
});

stream.on('error', (error) => {
  console.error(error);
});
```

Collecting stream text:

```typescript
import { collectStreamText } from '@iris/sdk';

const stream = await client.chatStream('Explain the deployment plan.');
const text = await collectStreamText(stream);
```

Cancellation:

```typescript
const controller = new AbortController();
const stream = await client.chatStream('Long response', {
  signal: controller.signal,
});

setTimeout(() => controller.abort(), 5_000);
```

### Conversations

```typescript
const conversation = await client.conversations.create({
  title: 'Staging readiness',
  model: 'claude-3-5-sonnet-20241022',
  metadata: { environment: 'staging' },
});

const messageResponse = await client.conversations.sendMessage(
  conversation.id,
  {
    role: 'user',
    content: 'Check the release notes for missing verification.',
  }
);

const messages = await client.conversations.getMessages(conversation.id, {
  limit: 50,
});

await client.conversations.archive(conversation.id);
```

### Memory

```typescript
const memory = await client.memory.create({
  type: 'preference',
  content: 'Prefers concise TypeScript examples with strict typing.',
  importance: 'high',
  tags: ['developer-experience'],
});

const results = await client.memory.search({
  query: 'coding preferences',
  types: ['preference', 'instruction'],
  limit: 10,
});

await client.memory.remember('Use UTC timestamps in examples.', 'instruction');
const recalled = await client.memory.recall('timestamp preferences', 5);
```

### Agents And Tools

```typescript
const agent = await client.agents.create({
  name: 'Release Assistant',
  description: 'Validates rollout readiness.',
  model: 'claude-3-5-sonnet-20241022',
  capabilities: ['planning', 'reasoning', 'tool_use'],
});

await client.agents.addTool(agent.id, {
  name: 'deploy.status',
  description: 'Read deployment status.',
  parameters: {
    type: 'object',
    properties: {
      environment: { type: 'string' },
    },
    required: ['environment'],
  },
  enabled: true,
});

const answer = await client.ask(agent.id, 'Is staging ready?');
```

### Knowledge

```typescript
const kb = await client.knowledge.create({
  name: 'Runbooks',
  description: 'Operations runbooks',
});

await client.knowledge.addText(kb.id, {
  title: 'API incident runbook',
  content: '# API incident\nFollow the rollback checklist...',
  mimeType: 'text/markdown',
});

const hits = await client.knowledge.search({
  query: 'rollback checklist',
  knowledgeBaseIds: [kb.id],
  limit: 5,
});
```

### Type Imports

```typescript
import type {
  Agent,
  Conversation,
  IrisConfig,
  Memory,
  Message,
  MessageResponse,
  PaginatedResponse,
  StreamEvent,
} from '@iris/sdk';
```

## Python SDK Guide

Until the generated Python package is published, use a small typed wrapper over
`httpx`. The same structure can be promoted into `iris-sdk`.

### Installation

```bash
pip install httpx pydantic
```

### Sync Client

```python
from __future__ import annotations

from dataclasses import dataclass
from typing import Any
import httpx


@dataclass(frozen=True)
class IrisConfig:
    api_key: str
    base_url: str = "https://iris.oshun.dev/api/v1"
    timeout: float = 30.0


class IrisClient:
    def __init__(self, config: IrisConfig):
        self.config = config
        self._client = httpx.Client(
            base_url=config.base_url,
            timeout=config.timeout,
            headers={"Authorization": f"Bearer {config.api_key}"},
        )

    def close(self) -> None:
        self._client.close()

    def __enter__(self) -> "IrisClient":
        return self

    def __exit__(self, *_: object) -> None:
        self.close()

    def create_conversation(self, title: str | None = None, model: str | None = None) -> dict[str, Any]:
        response = self._client.post("/conversations", json={"title": title, "model": model})
        response.raise_for_status()
        return response.json()

    def send_message(self, conversation_id: str, content: str) -> dict[str, Any]:
        response = self._client.post(
            f"/conversations/{conversation_id}/messages",
            json={"role": "user", "content": content},
        )
        response.raise_for_status()
        return response.json()


with IrisClient(IrisConfig(api_key="iris_sk_live_xxx")) as iris:
    conversation = iris.create_conversation("Release planning")
    response = iris.send_message(conversation["id"], "Summarize the launch risks.")
    print(response["assistantMessage"]["content"])
```

### Async Client And Streaming

```python
from collections.abc import AsyncIterator
import json
import httpx


class AsyncIrisClient:
    def __init__(self, api_key: str, base_url: str = "https://iris.oshun.dev/api/v1"):
        self._client = httpx.AsyncClient(
            base_url=base_url,
            headers={"Authorization": f"Bearer {api_key}"},
            timeout=30.0,
        )

    async def __aenter__(self) -> "AsyncIrisClient":
        return self

    async def __aexit__(self, *_: object) -> None:
        await self._client.aclose()

    async def stream_message(self, conversation_id: str, content: str) -> AsyncIterator[dict]:
        async with self._client.stream(
            "POST",
            f"/conversations/{conversation_id}/stream",
            json={"role": "user", "content": content},
        ) as response:
            response.raise_for_status()
            async for line in response.aiter_lines():
                if line.startswith("data: "):
                    yield json.loads(line.removeprefix("data: "))
```

## Swift SDK Guide

The Swift reference client uses Swift concurrency and can be wrapped in a Swift
Package when the generated SDK is published.

### Swift Concurrency Client

```swift
import Foundation

struct IrisClient {
    let apiKey: String
    let baseURL = URL(string: "https://iris.oshun.dev/api/v1")!

    func sendMessage(conversationId: String, content: String) async throws -> Data {
        var request = URLRequest(url: baseURL.appending(path: "conversations/\(conversationId)/messages"))
        request.httpMethod = "POST"
        request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
        request.setValue("application/json", forHTTPHeaderField: "Content-Type")
        request.httpBody = try JSONSerialization.data(withJSONObject: [
            "role": "user",
            "content": content
        ])

        let (data, response) = try await URLSession.shared.data(for: request)
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
            throw URLError(.badServerResponse)
        }
        return data
    }
}
```

### SwiftUI Integration

```swift
import SwiftUI

@MainActor
final class IrisChatViewModel: ObservableObject {
    @Published var messages: [String] = []
    @Published var draft = ""
    @Published var isSending = false

    private let client = IrisClient(apiKey: "iris_sk_live_xxx")
    private let conversationId: String

    init(conversationId: String) {
        self.conversationId = conversationId
    }

    func send() async {
        guard !draft.isEmpty else { return }
        let content = draft
        draft = ""
        messages.append(content)
        isSending = true
        defer { isSending = false }

        do {
            let data = try await client.sendMessage(conversationId: conversationId, content: content)
            messages.append(String(decoding: data, as: UTF8.self))
        } catch {
            messages.append("Request failed: \(error.localizedDescription)")
        }
    }
}
```

### Combine Integration

```swift
import Combine
import Foundation

extension IrisClient {
    func sendMessagePublisher(conversationId: String, content: String) -> AnyPublisher<Data, Error> {
        Future { promise in
            Task {
                do {
                    promise(.success(try await sendMessage(conversationId: conversationId, content: content)))
                } catch {
                    promise(.failure(error))
                }
            }
        }
        .eraseToAnyPublisher()
    }
}
```

## Kotlin SDK Guide

The Kotlin reference client uses `OkHttp` and `kotlinx.serialization`; Android
apps can expose it through a repository and Compose view model.

### Gradle

```kotlin
dependencies {
    implementation("com.squareup.okhttp3:okhttp:4.12.0")
    implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.3")
}
```

### Client

```kotlin
import kotlinx.serialization.Serializable
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody

@Serializable
data class SendMessageBody(val role: String = "user", val content: String)

class IrisClient(
    private val apiKey: String,
    private val baseUrl: String = "https://iris.oshun.dev/api/v1",
    private val http: OkHttpClient = OkHttpClient()
) {
    private val json = Json { ignoreUnknownKeys = true }
    private val mediaType = "application/json".toMediaType()

    fun sendMessage(conversationId: String, content: String): String {
        val body = json.encodeToString(SendMessageBody(content = content)).toRequestBody(mediaType)
        val request = Request.Builder()
            .url("$baseUrl/conversations/$conversationId/messages")
            .header("Authorization", "Bearer $apiKey")
            .post(body)
            .build()

        http.newCall(request).execute().use { response ->
            if (!response.isSuccessful) error("Iris request failed: ${response.code}")
            return response.body?.string().orEmpty()
        }
    }
}
```

### Jetpack Compose

```kotlin
class IrisChatViewModel(
    private val client: IrisClient,
    private val conversationId: String
) : ViewModel() {
    var messages by mutableStateOf(listOf<String>())
        private set

    fun send(content: String) {
        viewModelScope.launch(Dispatchers.IO) {
            val response = client.sendMessage(conversationId, content)
            withContext(Dispatchers.Main) {
                messages = messages + content + response
            }
        }
    }
}
```

## Rust SDK Guide

The Rust reference client uses `reqwest` and `serde`; feature flags can separate
blocking, streaming, and WebSocket support in a generated crate.

### Cargo

```toml
[dependencies]
reqwest = { version = "0.12", features = ["json", "stream", "rustls-tls"] }
serde = { version = "1", features = ["derive"] }
serde_json = "1"
thiserror = "1"
tokio = { version = "1", features = ["macros", "rt-multi-thread"] }

[features]
default = ["async"]
async = []
streaming = []
websocket = []
```

### Async Client

```rust
use reqwest::Client;
use serde::{Deserialize, Serialize};

#[derive(Clone)]
pub struct IrisClient {
    http: Client,
    api_key: String,
    base_url: String,
}

#[derive(Serialize)]
struct SendMessageRequest<'a> {
    role: &'a str,
    content: &'a str,
}

#[derive(Deserialize)]
pub struct MessageResponse {
    #[serde(rename = "assistantMessage")]
    pub assistant_message: serde_json::Value,
}

impl IrisClient {
    pub fn new(api_key: impl Into<String>) -> Self {
        Self {
            http: Client::new(),
            api_key: api_key.into(),
            base_url: "https://iris.oshun.dev/api/v1".to_string(),
        }
    }

    pub async fn send_message(
        &self,
        conversation_id: &str,
        content: &str,
    ) -> reqwest::Result<MessageResponse> {
        self.http
            .post(format!("{}/conversations/{}/messages", self.base_url, conversation_id))
            .bearer_auth(&self.api_key)
            .json(&SendMessageRequest { role: "user", content })
            .send()
            .await?
            .error_for_status()?
            .json()
            .await
    }
}
```

### Feature Flags

| Feature     | Enables                                               |
| ----------- | ----------------------------------------------------- |
| `async`     | Tokio/async `reqwest` client.                         |
| `streaming` | SSE parsing helpers for `/conversations/{id}/stream`. |
| `websocket` | WebSocket event contract once the gateway is enabled. |
| `blocking`  | Optional blocking client for CLI tools.               |

## Common Patterns

### Request IDs

Generate a request ID for every user-visible operation and pass it through
headers:

```typescript
await client.conversations.sendMessage(id, body, {
  headers: { 'X-Request-ID': crypto.randomUUID() },
});
```

### Idempotency

Use idempotency keys for retried writes when the SDK supports per-request
headers:

```typescript
await client.memory.create(memory, {
  idempotencyKey: `memory-${conversationId}-${hash}`,
});
```

### Cancellation

Propagate cancellation through `AbortSignal`, Swift `Task` cancellation, Kotlin
coroutine cancellation, Python timeout/cancel scopes, or Rust dropped futures.

### Streaming Fallback

Prefer SSE streaming for current production clients. Use the WebSocket contract
only when a WebSocket gateway is enabled in the target environment.

## Error Handling

### TypeScript Typed Errors

The TypeScript SDK exports:

```typescript
import {
  AuthenticationError,
  AuthorizationError,
  IrisError,
  NotFoundError,
  RateLimitError,
  TimeoutError,
  ValidationError,
} from '@iris/sdk';
```

```typescript
try {
  await client.chat('Hello');
} catch (error) {
  if (error instanceof RateLimitError) {
    await delay(error.retryAfterMs ?? 1_000);
  } else if (error instanceof AuthenticationError) {
    rotateCredential();
  } else {
    throw error;
  }
}
```

### Cross-Language Error Mapping

| HTTP status         | SDK error                      | Action                                 |
| ------------------- | ------------------------------ | -------------------------------------- |
| `400`               | `ValidationError`              | Fix request body or schema.            |
| `401`               | `AuthenticationError`          | Refresh or rotate credential.          |
| `403`               | `AuthorizationError`           | Check scopes and resource permissions. |
| `404`               | `NotFoundError`                | Confirm resource ID and tenant scope.  |
| `429`               | `RateLimitError`               | Retry after `Retry-After` with jitter. |
| `500`, `502`, `503` | `IrisError` or transport error | Retry idempotent calls with backoff.   |

## Best Practices

- Configure `baseUrl` explicitly per environment.
- Store API keys in a secret manager; never ship long-lived server keys in
  mobile, desktop, or browser bundles.
- Use short request timeouts for interactive chat and longer timeouts for
  document ingestion and agent tasks.
- Prefer streaming for long assistant responses to improve perceived latency.
- Include `X-Request-ID` in every request and persist it with user-visible
  errors.
- Retry only idempotent operations by default; use idempotency keys for writes
  that may be replayed.
- Keep memory writes small, explicit, and tagged; use search before creating
  duplicate long-term memories.
- Treat tool execution as privileged. Require explicit confirmation for tools
  that write files, call external APIs, mutate databases, or spend money.
- Keep SDK versions pinned in production applications and run compatibility
  tests before upgrading generated clients.

## Implementation Sources

| Area                     | Source                                                 |
| ------------------------ | ------------------------------------------------------ |
| TypeScript SDK package   | `libs/iris/sdk/typescript/package.json`                |
| Main TypeScript client   | `libs/iris/sdk/typescript/src/client.ts`               |
| Conversation client      | `libs/iris/sdk/typescript/src/clients/conversation.ts` |
| Memory client            | `libs/iris/sdk/typescript/src/clients/memory.ts`       |
| Agent client             | `libs/iris/sdk/typescript/src/clients/agent.ts`        |
| Knowledge client         | `libs/iris/sdk/typescript/src/clients/knowledge.ts`    |
| HTTP and typed errors    | `libs/iris/sdk/typescript/src/http`                    |
| Streaming helpers        | `libs/iris/sdk/typescript/src/streaming`               |
| SDK tests                | `libs/iris/sdk/typescript/src/sdk.spec.ts`             |
| SDK code generation      | `libs/iris/platform/codegen`                           |
| SDK docs generation      | `libs/iris/platform/sdk-docs`                          |
| SDK testing utilities    | `libs/iris/platform/sdk-testing`                       |
| SDK versioning utilities | `libs/iris/platform/sdk-versioning`                    |

_Last updated: 2026-04-28_
