# Iris API Documentation

> Implementation-aligned API reference for the Iris Universal Intelligent
> Assistant Platform.

This document covers the Iris REST, GraphQL, streaming, WebSocket contract, gRPC
contract, authentication, error handling, rate limiting, and SDK examples. It is
grounded in the current API implementation under `apps/iris/api/src`.

## Table Of Contents

1. [Overview](#overview)
2. [Authentication](#authentication)
3. [REST API](#rest-api)
4. [GraphQL API](#graphql-api)
5. [WebSocket Events](#websocket-events)
6. [gRPC API](#grpc-api)
7. [Error Handling](#error-handling)
8. [Rate Limiting](#rate-limiting)
9. [SDK Examples](#sdk-examples)
10. [Implementation Sources](#implementation-sources)

## Overview

### Transport Status

| Transport          | Status                                                                                | Endpoint                                                                         |
| ------------------ | ------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
| REST               | Implemented                                                                           | `/api/v1/conversations`, `/api/v1/memory`, `/api/v1/agents`, `/api/v1/knowledge` |
| GraphQL            | Implemented                                                                           | `/graphql`                                                                       |
| REST docs/OpenAPI  | Implemented                                                                           | `/docs`                                                                          |
| Health             | Implemented                                                                           | `/health`, `/health/ready`, `/health/live`                                       |
| Server-sent events | Implemented for conversation streaming                                                | `POST /api/v1/conversations/{id}/stream`                                         |
| WebSocket          | Contract documented; not mounted by the current Hono process                          | Recommended path: `/ws`                                                          |
| gRPC               | Proto contract documented; no generated server is mounted by the current Hono process | Recommended package: `iris.v1`                                                   |

### Base URLs

| Environment | REST                                    | GraphQL                                  | Streaming                                                         |
| ----------- | --------------------------------------- | ---------------------------------------- | ----------------------------------------------------------------- |
| Production  | `https://iris.oshun.dev/api/v1`         | `https://iris.oshun.dev/graphql`         | `https://iris.oshun.dev/api/v1/conversations/{id}/stream`         |
| Staging     | `https://staging.iris.oshun.dev/api/v1` | `https://staging.iris.oshun.dev/graphql` | `https://staging.iris.oshun.dev/api/v1/conversations/{id}/stream` |
| Development | `http://localhost:3000/api/v1`          | `http://localhost:3000/graphql`          | `http://localhost:3000/api/v1/conversations/{id}/stream`          |

### Common Headers

| Header                           | Direction        | Required                                                      | Description                                             |
| -------------------------------- | ---------------- | ------------------------------------------------------------- | ------------------------------------------------------- |
| `Authorization: Bearer <token>`  | Request          | Yes for protected resources                                   | API key, JWT, or OAuth access token.                    |
| `Content-Type: application/json` | Request          | Yes for JSON requests                                         | Required for POST, PATCH, and PUT bodies.               |
| `X-Request-ID`                   | Request/response | Optional request, always response when middleware assigns one | Client-supplied or generated request correlation ID.    |
| `traceparent`                    | Request/response | Optional                                                      | W3C trace context propagated by the tracing middleware. |
| `tracestate`                     | Request/response | Optional                                                      | W3C vendor trace state.                                 |

### Pagination

REST collection endpoints use page pagination unless otherwise noted:

| Parameter  | Type    | Default | Description               |
| ---------- | ------- | ------- | ------------------------- |
| `page`     | integer | `1`     | One-based page number.    |
| `pageSize` | integer | `20`    | Number of items per page. |

GraphQL uses Relay-style `first` and `after` cursor pagination.

## Authentication

The API accepts standard bearer credentials at the edge. The current local
service code uses placeholder user resolution until the production auth layer is
wired into every route, so clients should still send production-compatible
credentials.

### API Key

Use API keys for server-to-server integrations.

```http
Authorization: Bearer iris_sk_live_xxxxxxxxxxxxx
```

```bash
curl -X POST https://iris.oshun.dev/api/v1/conversations \
  -H "Authorization: Bearer iris_sk_live_xxxxxxxxxxxxx" \
  -H "Content-Type: application/json" \
  -d '{"title":"Planning","model":"claude-3-5-sonnet-20241022"}'
```

### JWT

Use JWTs for first-party product clients.

```json
{
  "iss": "https://auth.oshun.dev",
  "sub": "user_abc123",
  "aud": "iris",
  "scope": "conversation:write memory:read agent:execute",
  "iat": 1770000000,
  "exp": 1770003600
}
```

### OAuth 2.0

Use OAuth for delegated third-party access.

| Flow                         | Use case                                       |
| ---------------------------- | ---------------------------------------------- |
| Authorization code with PKCE | Browser and mobile applications.               |
| Client credentials           | Backend integrations.                          |
| Refresh token                | Long-lived integrations with revocable access. |

Recommended scopes:

| Scope                | Description                                  |
| -------------------- | -------------------------------------------- |
| `conversation:read`  | Read conversations and messages.             |
| `conversation:write` | Create conversations and send messages.      |
| `memory:read`        | Read memory state.                           |
| `memory:write`       | Create, update, and delete memory entries.   |
| `agent:read`         | Read agents, tools, and tasks.               |
| `agent:write`        | Create and update agents and tasks.          |
| `knowledge:read`     | Search knowledge bases and documents.        |
| `knowledge:write`    | Create knowledge bases and ingest documents. |

### Session Cookies

Browser clients may use an authenticated session cookie issued by the Oshun auth
layer:

```http
Cookie: iris_session=<opaque-session-id>
```

Session-backed calls should still include `X-Request-ID` for supportability.

## REST API

All REST paths below are relative to the REST base URL, `/api/v1`.

### Health And Documentation

| Method | Path            | Description                             |
| ------ | --------------- | --------------------------------------- |
| `GET`  | `/health`       | Service health summary.                 |
| `GET`  | `/health/live`  | Liveness probe.                         |
| `GET`  | `/health/ready` | Readiness probe with dependency checks. |
| `GET`  | `/docs`         | Interactive/API documentation route.    |

### Chat And Conversations

Iris models chat as conversations plus messages. A client creates a
conversation, sends messages into it, and optionally uses the SSE stream
endpoint for token/event streaming.

| Method   | Path                                     | Description                                                                               |
| -------- | ---------------------------------------- | ----------------------------------------------------------------------------------------- |
| `GET`    | `/conversations`                         | List conversations. Query: `page`, `pageSize`, `status`, `search`, `sortBy`, `sortOrder`. |
| `POST`   | `/conversations`                         | Create a conversation.                                                                    |
| `GET`    | `/conversations/stats/summary`           | Conversation summary statistics.                                                          |
| `GET`    | `/conversations/{id}`                    | Get one conversation by UUID.                                                             |
| `PATCH`  | `/conversations/{id}`                    | Update title, system prompt, settings, or metadata.                                       |
| `DELETE` | `/conversations/{id}`                    | Delete a conversation.                                                                    |
| `POST`   | `/conversations/{id}/archive`            | Archive a conversation.                                                                   |
| `POST`   | `/conversations/{id}/branch/{messageId}` | Branch a conversation from a message UUID.                                                |
| `GET`    | `/conversations/{id}/messages`           | List messages. Query: `limit`, `before`, `after`.                                         |
| `POST`   | `/conversations/{id}/messages`           | Send a user or system message and receive the assistant response.                         |
| `POST`   | `/conversations/{id}/regenerate`         | Regenerate the latest assistant response.                                                 |
| `POST`   | `/conversations/{id}/stream`             | Send a message and stream conversation events as `text/event-stream`.                     |

Create conversation:

```json
{
  "title": "Launch planning",
  "systemPrompt": "You are a concise project assistant.",
  "model": "claude-3-5-sonnet-20241022",
  "settings": {
    "temperature": 0.7,
    "maxTokens": 4096,
    "topP": 0.95
  },
  "metadata": {
    "project": "iris"
  }
}
```

Send message:

```json
{
  "role": "user",
  "content": "Summarize the rollout risks.",
  "contentBlocks": [
    {
      "type": "text",
      "content": "Focus on deployment, data, and observability."
    }
  ],
  "metadata": {
    "source": "web"
  }
}
```

SSE stream events are JSON payloads framed as `data: <json>\n\n`:

```text
data: {"type":"start","conversationId":"..."}

data: {"type":"delta","content":"The main risk is"}

data: {"type":"complete","messageId":"...","usage":{"totalTokens":410}}
```

### Memory

Memory is hierarchical: core, working, archival, episodic, and general memory
search. The REST implementation validates requests with Zod schemas.

| Method   | Path                            | Description                                                                            |
| -------- | ------------------------------- | -------------------------------------------------------------------------------------- |
| `GET`    | `/memory/core`                  | Get all core memory blocks and token totals.                                           |
| `GET`    | `/memory/core/{section}`        | Get one core block. Sections: `persona`, `human`, `goals`, `instructions`, `custom`.   |
| `PUT`    | `/memory/core/{section}`        | Replace a core block. Body: `{ "content": "..." }`.                                    |
| `POST`   | `/memory/core/{section}/append` | Append text to a core block.                                                           |
| `GET`    | `/memory/working/{sessionId}`   | List working memory for a session. Query: `limit`.                                     |
| `POST`   | `/memory/working`               | Add a working memory entry.                                                            |
| `DELETE` | `/memory/working/{sessionId}`   | Clear working memory for a session.                                                    |
| `GET`    | `/memory/archival`              | List archival memory. Query: `limit`, `offset`, `types`.                               |
| `GET`    | `/memory/archival/search`       | Search archival memory. Query: `query`, `limit`, `verified`, `minConfidence`, `types`. |
| `POST`   | `/memory/archival`              | Add archival memory.                                                                   |
| `GET`    | `/memory/episodic`              | List episodic events. Query: `startTime`, `endTime`, `eventTypes`, `limit`.            |
| `POST`   | `/memory/episodic`              | Record an episodic event.                                                              |
| `POST`   | `/memory`                       | Create a general memory entry.                                                         |
| `GET`    | `/memory/{id}`                  | Get a memory entry.                                                                    |
| `PATCH`  | `/memory/{id}`                  | Update a memory entry.                                                                 |
| `DELETE` | `/memory/{id}`                  | Delete a memory entry.                                                                 |
| `POST`   | `/memory/search`                | Search memories across tiers.                                                          |
| `GET`    | `/memory/stats/summary`         | Memory statistics.                                                                     |
| `POST`   | `/memory/cleanup`               | Delete expired memory entries.                                                         |

Create memory:

```json
{
  "tier": "archival",
  "type": "preference",
  "content": "Prefers TypeScript examples with strict typing.",
  "importance": "high",
  "tags": ["developer-experience"],
  "source": "user",
  "sourceId": "conversation-uuid"
}
```

Search memory:

```json
{
  "query": "coding preferences",
  "tier": "archival",
  "types": ["preference", "instruction"],
  "minImportance": "medium",
  "limit": 10,
  "includeExpired": false
}
```

### Agents And Tasks

Agents own tools and tasks. Task operations are separate collection routes under
`/agents/tasks`.

| Method   | Path                            | Description                                                             |
| -------- | ------------------------------- | ----------------------------------------------------------------------- |
| `GET`    | `/agents`                       | List agents. Query: `page`, `pageSize`, `status`, `capabilities`.       |
| `POST`   | `/agents`                       | Create an agent.                                                        |
| `GET`    | `/agents/{id}`                  | Get an agent.                                                           |
| `PATCH`  | `/agents/{id}`                  | Update an agent.                                                        |
| `DELETE` | `/agents/{id}`                  | Delete an agent.                                                        |
| `POST`   | `/agents/{id}/enable`           | Enable an agent.                                                        |
| `POST`   | `/agents/{id}/disable`          | Disable an agent.                                                       |
| `GET`    | `/agents/{id}/stats`            | Agent statistics.                                                       |
| `GET`    | `/agents/{id}/tools`            | List agent tools.                                                       |
| `POST`   | `/agents/{id}/tools`            | Add a tool to an agent.                                                 |
| `PATCH`  | `/agents/{id}/tools/{toolName}` | Enable or disable a tool.                                               |
| `DELETE` | `/agents/{id}/tools/{toolName}` | Remove a tool.                                                          |
| `GET`    | `/agents/tasks`                 | List tasks. Query: `agentId`, `status`, `priority`, `page`, `pageSize`. |
| `POST`   | `/agents/tasks`                 | Create a task.                                                          |
| `GET`    | `/agents/tasks/{taskId}`        | Get a task.                                                             |
| `POST`   | `/agents/tasks/{taskId}/run`    | Run a task.                                                             |
| `POST`   | `/agents/tasks/{taskId}/pause`  | Pause a task.                                                           |
| `POST`   | `/agents/tasks/{taskId}/resume` | Resume a task.                                                          |
| `POST`   | `/agents/tasks/{taskId}/cancel` | Cancel a task.                                                          |
| `GET`    | `/agents/{id}/tasks`            | List tasks for one agent.                                               |

Create agent:

```json
{
  "name": "Release Assistant",
  "description": "Plans, checks, and summarizes release work.",
  "model": "claude-3-5-sonnet-20241022",
  "systemPrompt": "Operate as a careful release engineer.",
  "capabilities": ["planning", "reasoning", "tool_use", "memory_access"],
  "tools": [
    {
      "name": "ticket.lookup",
      "description": "Look up a release ticket.",
      "inputSchema": { "type": "object" },
      "enabled": true,
      "requiresConfirmation": false
    }
  ],
  "config": {
    "maxIterations": 25,
    "timeout": 300000,
    "temperature": 0.2,
    "autoApprove": false
  }
}
```

Create task:

```json
{
  "agentId": "00000000-0000-0000-0000-000000000000",
  "name": "Validate staging rollout",
  "description": "Check service health, logs, and SLO dashboards.",
  "priority": "high",
  "input": {
    "environment": "staging"
  }
}
```

### Knowledge

Knowledge endpoints manage knowledge bases, documents, chunks, search, and RAG
context.

| Method   | Path                                            | Description                                                  |
| -------- | ----------------------------------------------- | ------------------------------------------------------------ |
| `GET`    | `/knowledge`                                    | List knowledge bases. Query: `page`, `pageSize`.             |
| `POST`   | `/knowledge`                                    | Create a knowledge base.                                     |
| `GET`    | `/knowledge/{id}`                               | Get a knowledge base.                                        |
| `PATCH`  | `/knowledge/{id}`                               | Update a knowledge base.                                     |
| `DELETE` | `/knowledge/{id}`                               | Delete a knowledge base.                                     |
| `GET`    | `/knowledge/{id}/documents`                     | List documents. Query: `status`, `type`, `page`, `pageSize`. |
| `POST`   | `/knowledge/{id}/documents`                     | Add a document.                                              |
| `GET`    | `/knowledge/{id}/documents/{documentId}`        | Get a document.                                              |
| `PATCH`  | `/knowledge/{id}/documents/{documentId}`        | Update a document.                                           |
| `DELETE` | `/knowledge/{id}/documents/{documentId}`        | Delete a document.                                           |
| `GET`    | `/knowledge/{id}/documents/{documentId}/chunks` | List document chunks.                                        |
| `POST`   | `/knowledge/search`                             | Semantic search.                                             |
| `GET`    | `/knowledge/search`                             | Quick search. Query: `q`, `kb`, `limit`.                     |
| `POST`   | `/knowledge/rag`                                | Build RAG context.                                           |
| `GET`    | `/knowledge/{id}/stats`                         | Knowledge base statistics.                                   |

Create knowledge base:

```json
{
  "name": "Runbooks",
  "description": "Operational runbooks and incident notes.",
  "settings": {
    "chunkSize": 800,
    "chunkOverlap": 100,
    "embeddingModel": "text-embedding-3-large",
    "autoReindex": true
  }
}
```

Add document:

```json
{
  "name": "api-incident.md",
  "type": "markdown",
  "content": "# API incident\n...",
  "source": {
    "type": "upload",
    "fileName": "api-incident.md",
    "mimeType": "text/markdown"
  }
}
```

### Models

The current REST process does not mount a standalone `/models` catalog route.
Model selection is part of the conversation and agent configuration surfaces:

| Surface                           | Field            | Behavior                                            |
| --------------------------------- | ---------------- | --------------------------------------------------- |
| `POST /conversations`             | `model`          | Optional. Defaults to `claude-3-5-sonnet-20241022`. |
| `PATCH /conversations/{id}`       | `settings.model` | Updates the conversation model when supplied.       |
| `POST /agents`                    | `model`          | Optional. Defaults to the agent service default.    |
| `PATCH /agents/{id}`              | `model`          | Updates the agent model when supplied.              |
| GraphQL `CreateConversationInput` | `model`          | Optional conversation model.                        |
| GraphQL `CreateAgentInput`        | `model`          | Optional agent model.                               |

Provider availability is controlled by deployment configuration and injected
provider credentials. Clients should omit `model` for default routing unless
they need a specific provider/model contract.

## GraphQL API

GraphQL is served by GraphQL Yoga at `/graphql`.

### Operation Surface

The canonical schema lives in `apps/iris/api/src/graphql/schema.ts`. The root
operation surface is:

```graphql
type Query {
  conversation(id: ID!): Conversation
  conversations(
    first: Int
    after: String
    last: Int
    before: String
    filter: ConversationFilterInput
    sort: SortInput
  ): ConversationConnection!

  message(id: ID!): Message
  messages(
    conversationId: ID!
    first: Int
    after: String
    filter: MessageFilterInput
  ): MessageConnection!

  agent(id: ID!): Agent
  agents(first: Int, after: String, filter: AgentFilterInput): AgentConnection!

  task(id: ID!): Task
  tasks(
    agentId: ID
    first: Int
    after: String
    filter: TaskFilterInput
  ): TaskConnection!

  coreMemory: CoreMemory!
  coreMemoryBlock(section: CoreMemorySection!): CoreMemoryBlock
  workingMemory(sessionId: String!, limit: Int): [WorkingMemoryEntry!]!
  archivalMemory(
    query: String
    limit: Int
    types: [MemoryType!]
    verified: Boolean
    minConfidence: Float
  ): [ArchivalMemoryEntry!]!
  episodicMemory(
    startTime: DateTime
    endTime: DateTime
    eventTypes: [String!]
    limit: Int
  ): [EpisodicMemoryEntry!]!
  searchMemory(input: MemorySearchInput!): [MemoryEntry!]!
  memoryStats: MemoryStats!

  knowledgeBase(id: ID!): KnowledgeBase
  knowledgeBases(
    first: Int
    after: String
    filter: KnowledgeFilterInput
  ): KnowledgeBaseConnection!
  document(id: ID!): Document
  documents(
    knowledgeBaseId: ID!
    first: Int
    after: String
    filter: DocumentFilterInput
  ): DocumentConnection!
  searchKnowledge(input: KnowledgeSearchInput!): [SearchResult!]!
  ragContext(input: RAGContextInput!): RAGContext!
}

type Mutation {
  createConversation(input: CreateConversationInput!): Conversation!
  updateConversation(id: ID!, input: UpdateConversationInput!): Conversation!
  deleteConversation(id: ID!): DeleteResult!
  archiveConversation(id: ID!): Conversation!
  branchConversation(id: ID!, fromMessageId: ID!): Conversation!

  sendMessage(conversationId: ID!, input: CreateMessageInput!): Message!
  regenerateMessage(messageId: ID!): Message!
  branchFromMessage(messageId: ID!): Conversation!

  createAgent(input: CreateAgentInput!): Agent!
  updateAgent(id: ID!, input: UpdateAgentInput!): Agent!
  deleteAgent(id: ID!): DeleteResult!
  enableAgent(id: ID!): Agent!
  disableAgent(id: ID!): Agent!
  addAgentTool(agentId: ID!, tool: CreateToolDefinitionInput!): Agent!
  removeAgentTool(agentId: ID!, toolName: String!): Agent!
  enableAgentTool(agentId: ID!, toolName: String!): Agent!
  disableAgentTool(agentId: ID!, toolName: String!): Agent!

  createTask(agentId: ID!, input: CreateTaskInput!): Task!
  runTask(taskId: ID!): Task!
  pauseTask(taskId: ID!): Task!
  resumeTask(taskId: ID!): Task!
  cancelTask(taskId: ID!): Task!

  updateCoreMemory(input: UpdateCoreMemoryInput!): CoreMemoryBlock!
  appendToCoreMemory(
    section: CoreMemorySection!
    content: String!
  ): CoreMemoryBlock!
  addToWorkingMemory(input: AddWorkingMemoryInput!): WorkingMemoryEntry!
  clearWorkingMemory(sessionId: String!): DeleteResult!
  addToArchival(input: AddArchivalMemoryInput!): ArchivalMemoryEntry!
  recordEpisodicEvent(input: RecordEpisodicEventInput!): EpisodicMemoryEntry!
  deleteMemory(id: ID!): DeleteResult!
  cleanupExpiredMemories: Int!

  createKnowledgeBase(input: CreateKnowledgeBaseInput!): KnowledgeBase!
  updateKnowledgeBase(id: ID!, input: UpdateKnowledgeBaseInput!): KnowledgeBase!
  deleteKnowledgeBase(id: ID!): DeleteResult!
  addDocument(knowledgeBaseId: ID!, input: CreateDocumentInput!): Document!
  updateDocument(id: ID!, input: CreateDocumentInput!): Document!
  deleteDocument(id: ID!): DeleteResult!
  reindexKnowledgeBase(id: ID!): KnowledgeBase!
}

type Subscription {
  messageStream(conversationId: ID!): MessageStreamEvent!
  conversationUpdated(filter: ConversationFilterInput): ConversationUpdateEvent!
  agentUpdated(filter: AgentFilterInput): AgentUpdateEvent!
  taskUpdated(agentId: ID, taskId: ID): TaskUpdateEvent!
}
```

### Schema Families

| Family              | Types                                                                                                                             |
| ------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Conversation        | `Conversation`, `Message`, `Attachment`, `ToolCall`, `ConversationConnection`, `MessageConnection`                                |
| Agent               | `Agent`, `ToolDefinition`, `Task`, `TaskStep`, `AgentConnection`, `TaskConnection`                                                |
| Memory              | `CoreMemory`, `CoreMemoryBlock`, `WorkingMemoryEntry`, `ArchivalMemoryEntry`, `EpisodicMemoryEntry`, `MemoryEntry`, `MemoryStats` |
| Knowledge           | `KnowledgeBase`, `Document`, `DocumentChunk`, `SearchResult`, `RAGContext`, `KnowledgeBaseConnection`, `DocumentConnection`       |
| Shared              | `PageInfo`, `DeleteResult`, `TokenUsage`, `DateTime`, `JSON`                                                                      |
| Subscription events | `MessageStreamEvent`, `ConversationUpdateEvent`, `AgentUpdateEvent`, `TaskUpdateEvent`                                            |

### Enums

`ConversationStatus`, `MessageRole`, `AttachmentType`, `ToolCallStatus`,
`TaskStatus`, `TaskStepType`, `TaskStepStatus`, `MemoryTier`, `MemoryType`,
`MemoryImportance`, `MemorySource`, `CoreMemorySection`, `KnowledgeBaseType`,
`KnowledgeBaseStatus`, `DocumentStatus`, `SortDirection`,
`MessageStreamEventType`, `ConversationUpdateType`, `AgentUpdateType`, and
`TaskUpdateType`.

### Example Query

```graphql
query ConversationWithMessages($id: ID!) {
  conversation(id: $id) {
    id
    title
    model
    messageCount
    messages(first: 20) {
      edges {
        node {
          id
          role
          content
          tokens
          createdAt
        }
      }
      pageInfo {
        hasNextPage
        endCursor
      }
    }
  }
}
```

### Example Mutation

```graphql
mutation SendMessage($conversationId: ID!, $input: CreateMessageInput!) {
  sendMessage(conversationId: $conversationId, input: $input) {
    id
    role
    content
    createdAt
  }
}
```

## WebSocket Events

The current API process exposes SSE for conversation streaming. The WebSocket
contract below is the stable event model for clients that need bidirectional
real-time chat, task progress, and control commands once the WebSocket gateway
is enabled.

### Connection

Recommended URL:

```text
wss://iris.oshun.dev/ws
```

Authentication options:

- `Authorization: Bearer <token>` during the WebSocket upgrade.
- First message `{ "type": "auth", "payload": { "token": "..." } }` for clients
  that cannot set upgrade headers.

### Client Events

| Event              | Purpose                        | Required payload                                                   |
| ------------------ | ------------------------------ | ------------------------------------------------------------------ |
| `auth`             | Authenticate a socket.         | `{ "token": "..." }`                                               |
| `chat.start`       | Start a streaming chat turn.   | `conversationId`, `content`, optional `contentBlocks`, `metadata`. |
| `chat.cancel`      | Cancel an in-flight chat turn. | `requestId` or message `id`.                                       |
| `task.subscribe`   | Subscribe to task updates.     | `taskId`.                                                          |
| `task.unsubscribe` | Stop task updates.             | `taskId`.                                                          |
| `memory.subscribe` | Subscribe to memory changes.   | Optional `tiers`.                                                  |
| `ping`             | Keepalive.                     | Optional timestamp.                                                |

### Server Events

| Event            | Purpose                              | Payload                                 |
| ---------------- | ------------------------------------ | --------------------------------------- |
| `auth.ok`        | Authentication accepted.             | `userId`, `sessionId`.                  |
| `chat.start`     | Chat stream opened.                  | `conversationId`, `messageId`.          |
| `chat.delta`     | Partial assistant output.            | `delta`, optional `messageId`.          |
| `chat.tool_call` | Tool call emitted by an agent/model. | `toolCall`.                             |
| `chat.complete`  | Final message and token usage.       | `message`, `usage`.                     |
| `chat.error`     | Chat stream failed.                  | `code`, `message`, `requestId`.         |
| `task.updated`   | Task state changed.                  | `taskId`, `status`, `step`, `progress`. |
| `task.completed` | Task finished.                       | `taskId`, `output`.                     |
| `memory.updated` | Memory entry changed.                | `id`, `tier`, `type`, `operation`.      |
| `pong`           | Keepalive response.                  | Optional timestamp.                     |

Example:

```json
{
  "type": "chat.start",
  "id": "req_01",
  "payload": {
    "conversationId": "00000000-0000-0000-0000-000000000000",
    "content": "Stream a concise release summary."
  }
}
```

## gRPC API

The gRPC contract mirrors the REST/GraphQL resource model. It is documented for
SDK generation and service-to-service integrations; the current Hono API process
does not mount a gRPC server.

```protobuf
syntax = "proto3";

package iris.v1;

service IrisService {
  rpc CreateConversation(CreateConversationRequest) returns (Conversation);
  rpc GetConversation(GetConversationRequest) returns (Conversation);
  rpc ListConversations(ListConversationsRequest) returns (ListConversationsResponse);
  rpc UpdateConversation(UpdateConversationRequest) returns (Conversation);
  rpc DeleteConversation(DeleteConversationRequest) returns (DeleteResult);
  rpc ArchiveConversation(ArchiveConversationRequest) returns (Conversation);
  rpc BranchConversation(BranchConversationRequest) returns (Conversation);

  rpc SendMessage(SendMessageRequest) returns (SendMessageResponse);
  rpc StreamMessage(SendMessageRequest) returns (stream MessageStreamEvent);
  rpc ListMessages(ListMessagesRequest) returns (ListMessagesResponse);
  rpc RegenerateMessage(RegenerateMessageRequest) returns (Message);

  rpc GetCoreMemory(GetCoreMemoryRequest) returns (CoreMemory);
  rpc UpdateCoreMemory(UpdateCoreMemoryRequest) returns (CoreMemoryBlock);
  rpc AddWorkingMemory(AddWorkingMemoryRequest) returns (WorkingMemoryEntry);
  rpc ClearWorkingMemory(ClearWorkingMemoryRequest) returns (DeleteResult);
  rpc AddArchivalMemory(AddArchivalMemoryRequest) returns (ArchivalMemoryEntry);
  rpc RecordEpisodicEvent(RecordEpisodicEventRequest) returns (EpisodicMemoryEntry);
  rpc SearchMemory(SearchMemoryRequest) returns (SearchMemoryResponse);
  rpc DeleteMemory(DeleteMemoryRequest) returns (DeleteResult);

  rpc CreateAgent(CreateAgentRequest) returns (Agent);
  rpc GetAgent(GetAgentRequest) returns (Agent);
  rpc ListAgents(ListAgentsRequest) returns (ListAgentsResponse);
  rpc UpdateAgent(UpdateAgentRequest) returns (Agent);
  rpc DeleteAgent(DeleteAgentRequest) returns (DeleteResult);
  rpc AddAgentTool(AddAgentToolRequest) returns (Agent);
  rpc SetAgentToolEnabled(SetAgentToolEnabledRequest) returns (Agent);

  rpc CreateTask(CreateTaskRequest) returns (Task);
  rpc GetTask(GetTaskRequest) returns (Task);
  rpc ListTasks(ListTasksRequest) returns (ListTasksResponse);
  rpc RunTask(TaskRequest) returns (Task);
  rpc PauseTask(TaskRequest) returns (Task);
  rpc ResumeTask(TaskRequest) returns (Task);
  rpc CancelTask(TaskRequest) returns (Task);
  rpc StreamTaskProgress(TaskRequest) returns (stream TaskUpdateEvent);

  rpc CreateKnowledgeBase(CreateKnowledgeBaseRequest) returns (KnowledgeBase);
  rpc AddDocument(AddDocumentRequest) returns (Document);
  rpc SearchKnowledge(SearchKnowledgeRequest) returns (SearchKnowledgeResponse);
  rpc GetRagContext(RagContextRequest) returns (RagContext);
}

message Conversation {
  string id = 1;
  string user_id = 2;
  string title = 3;
  string model = 4;
  string system_prompt = 5;
  double temperature = 6;
  int32 max_tokens = 7;
  string status = 8;
  string metadata_json = 9;
  int32 message_count = 10;
  int32 token_count = 11;
  string created_at = 12;
  string updated_at = 13;
}

message Message {
  string id = 1;
  string conversation_id = 2;
  string role = 3;
  string content = 4;
  string model = 5;
  int32 tokens = 6;
  string metadata_json = 7;
  string created_at = 8;
}

message CreateConversationRequest {
  string title = 1;
  string model = 2;
  string system_prompt = 3;
  double temperature = 4;
  int32 max_tokens = 5;
  string metadata_json = 6;
}

message GetConversationRequest { string id = 1; }
message ListConversationsRequest { int32 page = 1; int32 page_size = 2; string status = 3; }
message ListConversationsResponse { repeated Conversation conversations = 1; int32 total = 2; }
message UpdateConversationRequest { string id = 1; CreateConversationRequest patch = 2; }
message DeleteConversationRequest { string id = 1; }
message ArchiveConversationRequest { string id = 1; }
message BranchConversationRequest { string id = 1; string message_id = 2; }

message SendMessageRequest {
  string conversation_id = 1;
  string role = 2;
  string content = 3;
  string metadata_json = 4;
  string parent_message_id = 5;
}

message SendMessageResponse {
  Message user_message = 1;
  Message assistant_message = 2;
}

message MessageStreamEvent {
  string type = 1;
  string conversation_id = 2;
  string message_id = 3;
  string delta = 4;
  Message message = 5;
  TokenUsage usage = 6;
  string error = 7;
}

message ListMessagesRequest { string conversation_id = 1; int32 limit = 2; string before = 3; string after = 4; }
message ListMessagesResponse { repeated Message messages = 1; int32 total = 2; }
message RegenerateMessageRequest { string conversation_id = 1; }

message CoreMemory { repeated CoreMemoryBlock blocks = 1; int32 total_tokens = 2; int32 max_tokens = 3; }
message CoreMemoryBlock { string section = 1; string content = 2; int32 token_count = 3; int32 max_tokens = 4; string updated_at = 5; }
message WorkingMemoryEntry { string id = 1; string session_id = 2; string content = 3; string type = 4; string importance = 5; double relevance_score = 6; }
message ArchivalMemoryEntry { string id = 1; string content = 2; string type = 3; string importance = 4; string source = 5; bool verified = 6; double confidence = 7; }
message EpisodicMemoryEntry { string id = 1; string event_type = 2; string content = 3; string timestamp = 4; string importance = 5; }
message MemoryEntry { string id = 1; string tier = 2; string type = 3; string content = 4; string importance = 5; double relevance_score = 6; }
message GetCoreMemoryRequest {}
message UpdateCoreMemoryRequest { string section = 1; string content = 2; }
message AddWorkingMemoryRequest { string session_id = 1; string content = 2; string conversation_id = 3; string type = 4; string importance = 5; }
message ClearWorkingMemoryRequest { string session_id = 1; }
message AddArchivalMemoryRequest { string content = 1; string type = 2; string importance = 3; string source = 4; repeated string tags = 5; }
message RecordEpisodicEventRequest { string event_type = 1; string content = 2; string timestamp = 3; repeated string participants = 4; }
message SearchMemoryRequest { string query = 1; string tier = 2; repeated string types = 3; int32 limit = 4; }
message SearchMemoryResponse { repeated MemoryEntry results = 1; int32 count = 2; }
message DeleteMemoryRequest { string id = 1; }

message Agent { string id = 1; string user_id = 2; string name = 3; string description = 4; string model = 5; bool enabled = 6; repeated ToolDefinition tools = 7; }
message ToolDefinition { string name = 1; string description = 2; string parameters_json = 3; bool enabled = 4; }
message Task { string id = 1; string agent_id = 2; string name = 3; string description = 4; string status = 5; string input_json = 6; string output_json = 7; }
message CreateAgentRequest { string name = 1; string description = 2; string model = 3; string system_prompt = 4; repeated ToolDefinition tools = 5; }
message GetAgentRequest { string id = 1; }
message ListAgentsRequest { int32 page = 1; int32 page_size = 2; string status = 3; }
message ListAgentsResponse { repeated Agent agents = 1; int32 total = 2; }
message UpdateAgentRequest { string id = 1; CreateAgentRequest patch = 2; }
message DeleteAgentRequest { string id = 1; }
message AddAgentToolRequest { string agent_id = 1; ToolDefinition tool = 2; }
message SetAgentToolEnabledRequest { string agent_id = 1; string tool_name = 2; bool enabled = 3; }
message CreateTaskRequest { string agent_id = 1; string name = 2; string description = 3; string input_json = 4; string priority = 5; }
message GetTaskRequest { string id = 1; }
message ListTasksRequest { string agent_id = 1; string status = 2; string priority = 3; int32 page = 4; int32 page_size = 5; }
message ListTasksResponse { repeated Task tasks = 1; int32 total = 2; }
message TaskRequest { string task_id = 1; }
message TaskUpdateEvent { string type = 1; Task task = 2; string timestamp = 3; }

message KnowledgeBase { string id = 1; string name = 2; string description = 3; string status = 4; int32 document_count = 5; int32 chunk_count = 6; }
message Document { string id = 1; string knowledge_base_id = 2; string name = 3; string type = 4; string status = 5; int32 chunk_count = 6; }
message SearchResult { string document_id = 1; string chunk_id = 2; string content = 3; double score = 4; }
message RagContext { string query = 1; repeated SearchResult chunks = 2; int32 total_tokens = 3; }
message CreateKnowledgeBaseRequest { string name = 1; string description = 2; string metadata_json = 3; }
message AddDocumentRequest { string knowledge_base_id = 1; string name = 2; string type = 3; string content = 4; string metadata_json = 5; }
message SearchKnowledgeRequest { string query = 1; repeated string knowledge_base_ids = 2; int32 limit = 3; double min_score = 4; }
message SearchKnowledgeResponse { repeated SearchResult results = 1; int32 count = 2; }
message RagContextRequest { string query = 1; repeated string knowledge_base_ids = 2; int32 max_chunks = 3; int32 max_tokens = 4; }

message TokenUsage { int32 prompt_tokens = 1; int32 completion_tokens = 2; int32 total_tokens = 3; }
message DeleteResult { bool success = 1; string id = 2; }
```

## Error Handling

Errors use a stable envelope:

```json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid request body",
    "details": {
      "field": "content"
    },
    "requestId": "req_abc123"
  }
}
```

| Code                  | HTTP status | Meaning                                              | Retry                        |
| --------------------- | ----------- | ---------------------------------------------------- | ---------------------------- |
| `VALIDATION_ERROR`    | 400         | Request body, path, or query failed validation.      | No                           |
| `UNAUTHORIZED`        | 401         | Missing or invalid authentication.                   | After refreshing credentials |
| `FORBIDDEN`           | 403         | Authenticated caller lacks permission.               | No                           |
| `NOT_FOUND`           | 404         | Resource does not exist or is not visible to caller. | No                           |
| `RATE_LIMITED`        | 429         | Request exceeded rate limits.                        | Yes, after `Retry-After`     |
| `MODEL_ERROR`         | 502         | Provider/model call failed.                          | Yes, with backoff            |
| `SERVICE_UNAVAILABLE` | 503         | Dependency or service unavailable.                   | Yes, with backoff            |
| `INTERNAL_ERROR`      | 500         | Unhandled server error.                              | Yes, if idempotent           |

Recommended retry policy: exponential backoff with jitter for `429`, `502`, and
`503`; never retry non-idempotent writes without an idempotency key.

## Rate Limiting

Routes use presets from `apps/iris/api/src/middleware/rate-limiter.ts`.

| Preset      | Typical routes                                       | Behavior                                  |
| ----------- | ---------------------------------------------------- | ----------------------------------------- |
| `readonly`  | `GET` list/detail/stat endpoints                     | Higher read allowance.                    |
| `standard`  | Create/update/delete configuration endpoints         | Normal write allowance.                   |
| `heavy`     | Message send, task run, document ingest, RAG context | Lower allowance for expensive operations. |
| `streaming` | SSE stream endpoint                                  | Protects long-lived streams.              |
| `search`    | Knowledge and memory search                          | Tuned for vector/search pressure.         |

Responses include rate-limit headers when enforced by the middleware:

```http
X-RateLimit-Limit: 100
X-RateLimit-Remaining: 95
X-RateLimit-Reset: 1770000300
Retry-After: 30
```

## SDK Examples

### TypeScript

```typescript
const baseUrl = 'https://iris.oshun.dev/api/v1';

async function sendMessage(
  apiKey: string,
  conversationId: string,
  content: string
) {
  const response = await fetch(
    `${baseUrl}/conversations/${conversationId}/messages`,
    {
      method: 'POST',
      headers: {
        authorization: `Bearer ${apiKey}`,
        'content-type': 'application/json',
      },
      body: JSON.stringify({ role: 'user', content }),
    }
  );

  if (!response.ok) {
    throw new Error(await response.text());
  }

  return response.json();
}
```

### Python

```python
import requests

BASE_URL = "https://iris.oshun.dev/api/v1"

def create_memory(api_key: str, content: str) -> dict:
    response = requests.post(
        f"{BASE_URL}/memory",
        headers={"Authorization": f"Bearer {api_key}"},
        json={
            "tier": "archival",
            "type": "preference",
            "content": content,
            "importance": "medium",
        },
        timeout=30,
    )
    response.raise_for_status()
    return response.json()
```

### Swift

```swift
import Foundation

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

    func listConversations() async throws -> Data {
        var request = URLRequest(url: baseURL.appending(path: "conversations"))
        request.setValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")
        let (data, response) = try await URLSession.shared.data(for: request)
        guard (response as? HTTPURLResponse)?.statusCode == 200 else {
            throw URLError(.badServerResponse)
        }
        return data
    }
}
```

### Kotlin

```kotlin
import java.net.URI
import java.net.http.HttpClient
import java.net.http.HttpRequest
import java.net.http.HttpResponse

fun getAgent(apiKey: String, agentId: String): String {
    val request = HttpRequest.newBuilder()
        .uri(URI.create("https://iris.oshun.dev/api/v1/agents/$agentId"))
        .header("Authorization", "Bearer $apiKey")
        .GET()
        .build()

    return HttpClient.newHttpClient()
        .send(request, HttpResponse.BodyHandlers.ofString())
        .body()
}
```

### Rust

```rust
use reqwest::Client;
use serde_json::json;

async fn search_knowledge(api_key: &str, query: &str) -> reqwest::Result<serde_json::Value> {
    let client = Client::new();
    client
        .post("https://iris.oshun.dev/api/v1/knowledge/search")
        .bearer_auth(api_key)
        .json(&json!({
            "query": query,
            "limit": 10,
            "includeContent": true
        }))
        .send()
        .await?
        .error_for_status()?
        .json()
        .await
}
```

## Implementation Sources

| Area                     | Source                                                                                  |
| ------------------------ | --------------------------------------------------------------------------------------- |
| API mount points         | `apps/iris/api/src/index.ts`                                                            |
| REST conversation routes | `apps/iris/api/src/routes/conversation.ts`                                              |
| REST memory routes       | `apps/iris/api/src/routes/memory.ts`                                                    |
| REST agent routes        | `apps/iris/api/src/routes/agent.ts`                                                     |
| REST knowledge routes    | `apps/iris/api/src/routes/knowledge.ts`                                                 |
| GraphQL schema           | `apps/iris/api/src/graphql/schema.ts`                                                   |
| GraphQL data sources     | `apps/iris/api/src/graphql/service-data-sources.ts`                                     |
| Error middleware         | `apps/iris/api/src/middleware/error-handler.ts`                                         |
| Rate limiting            | `apps/iris/api/src/middleware/rate-limiter.ts`                                          |
| Request IDs and tracing  | `apps/iris/api/src/middleware/request-id.ts`, `apps/iris/api/src/middleware/tracing.ts` |

_Last updated: 2026-04-28_
