# Iris Integration Guide

> Practical integration guide for embedding Iris conversations, agents, memory,
> knowledge, tools, and streaming into applications and services.

This guide aligns with the current Iris API and SDK documentation:

- REST API: `/api/v1`
- GraphQL: `/graphql`
- REST docs/OpenAPI route: `/docs`
- Implemented streaming: server-sent events on
  `/api/v1/conversations/{id}/stream`
- WebSocket and gRPC: documented contracts; enable through a gateway before
  production use

## Table Of Contents

1. [Quick Start](#quick-start)
2. [Authentication Setup](#authentication-setup)
3. [Custom Agent Creation](#custom-agent-creation)
4. [Plugin Development](#plugin-development)
5. [Tool Integration](#tool-integration)
6. [Memory Systems](#memory-systems)
7. [Knowledge Base Integration](#knowledge-base-integration)
8. [Multi-LLM Orchestration](#multi-llm-orchestration)
9. [WebSocket Streaming Contract](#websocket-streaming-contract)
10. [Webhook Integration](#webhook-integration)
11. [Error Handling](#error-handling)
12. [Performance Optimization](#performance-optimization)
13. [Security Best Practices](#security-best-practices)
14. [Troubleshooting](#troubleshooting)

## Quick Start

### Choose An Integration Path

| Path           | Use when                                                          | Current status                             |
| -------------- | ----------------------------------------------------------------- | ------------------------------------------ |
| TypeScript SDK | Node.js, web backends, internal TypeScript services.              | Implemented in `libs/iris/sdk/typescript`. |
| REST           | Any language, server-to-server calls, simple resource operations. | Implemented.                               |
| GraphQL        | Product clients that need shaped reads and mutations.             | Implemented at `/graphql`.                 |
| SSE            | Token/event streaming for conversations.                          | Implemented.                               |
| WebSocket      | Bidirectional chat, task progress, live controls.                 | Contract documented; gateway required.     |
| gRPC           | Low-latency service-to-service calls.                             | Contract documented; server required.      |

### TypeScript SDK

```bash
pnpm add @iris/sdk
```

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

const iris = new IrisClient({
  apiKey: process.env.IRIS_API_KEY!,
  baseUrl: 'https://iris.oshun.dev/api/v1',
});

const conversation = await iris.conversations.create({
  title: 'Support triage',
  model: 'claude-3-5-sonnet-20241022',
});

const response = await iris.conversations.sendMessage(conversation.id, {
  role: 'user',
  content: 'Summarize the open customer issue.',
});

console.log(response.assistantMessage.content);
```

### REST

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

### Configuration

Set these values per environment:

| Setting         | Production example                      | Notes                                             |
| --------------- | --------------------------------------- | ------------------------------------------------- |
| REST base URL   | `https://iris.oshun.dev/api/v1`         | Use environment-specific hostnames.               |
| GraphQL URL     | `https://iris.oshun.dev/graphql`        | Same auth as REST.                                |
| API key/JWT     | Secret manager reference                | Never commit keys.                                |
| Request timeout | `30s` interactive, longer for ingestion | Keep chat responsive.                             |
| Retry policy    | Exponential backoff with jitter         | Retry only safe/idempotent operations by default. |
| Request ID      | UUID per operation                      | Send as `X-Request-ID`.                           |

## Authentication Setup

### API Keys

Use API keys for backend integrations:

```http
Authorization: Bearer iris_sk_live_xxxxxxxxxxxxx
```

Store keys in a secret manager and rotate them on a schedule. Scope keys to the
minimum required capabilities such as `conversation:write`, `memory:read`, or
`knowledge:write`.

### JWT

Use JWTs for first-party product clients. Required claims:

| Claim        | Purpose                                          |
| ------------ | ------------------------------------------------ |
| `iss`        | Trusted issuer such as `https://auth.oshun.dev`. |
| `sub`        | User ID.                                         |
| `aud`        | Must include `iris`.                             |
| `scope`      | Space-delimited scopes.                          |
| `iat`, `exp` | Token lifetime.                                  |

### OAuth 2.0

Use OAuth 2.0 for third-party integrations:

| Flow                      | Use case                           |
| ------------------------- | ---------------------------------- |
| Authorization code + PKCE | User-authorized apps.              |
| Client credentials        | Server-to-server automations.      |
| Refresh token             | Long-lived delegated integrations. |

Recommended scopes:

```text
conversation:read conversation:write
memory:read memory:write
agent:read agent:write
knowledge:read knowledge:write
```

### Sessions

Browser products can use the Oshun session cookie issued by the auth layer:

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

Do not rely on sessions for public server-to-server integrations.

### Webhook Signatures

When Iris sends events to your service, verify an HMAC signature:

```http
X-Iris-Webhook-Id: wh_123
X-Iris-Webhook-Timestamp: 1770000000
X-Iris-Webhook-Signature: v1=<hex-hmac-sha256>
```

Verification string:

```text
<timestamp>.<raw-request-body>
```

Reject webhooks when:

- Timestamp skew is greater than five minutes.
- Signature does not match any active secret.
- Webhook ID was already processed.
- Content type is not `application/json`.

## Custom Agent Creation

Agents combine instructions, model preferences, capabilities, tools, and memory
access.

### Agent Structure

```json
{
  "name": "Release Assistant",
  "description": "Validates production rollout readiness.",
  "model": "claude-3-5-sonnet-20241022",
  "systemPrompt": "Act as a careful release engineer. Ask before destructive actions.",
  "capabilities": ["planning", "reasoning", "tool_use", "memory_access"],
  "tools": [],
  "config": {
    "maxIterations": 25,
    "timeout": 300000,
    "temperature": 0.2,
    "autoApprove": false
  },
  "metadata": {
    "domain": "operations",
    "owner": "platform"
  }
}
```

Create the agent:

```bash
curl -X POST https://iris.oshun.dev/api/v1/agents \
  -H "Authorization: Bearer $IRIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d @agent.json
```

### Personalities And Expertise

Model agent behavior with explicit fields:

| Field                | Recommendation                                                             |
| -------------------- | -------------------------------------------------------------------------- |
| `systemPrompt`       | Define role, boundaries, escalation rules, and refusal behavior.           |
| `capabilities`       | Keep narrow. Add only capabilities required for the workflow.              |
| `tools`              | Prefer read-only tools first; require confirmation for mutations.          |
| `metadata.domain`    | Use for marketplace discovery and operational ownership.                   |
| `config.temperature` | Use low values for operations/compliance, higher values for creative work. |

### Task Execution

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

Task lifecycle endpoints:

| Operation | Endpoint                                    |
| --------- | ------------------------------------------- |
| Create    | `POST /api/v1/agents/tasks`                 |
| Run       | `POST /api/v1/agents/tasks/{taskId}/run`    |
| Pause     | `POST /api/v1/agents/tasks/{taskId}/pause`  |
| Resume    | `POST /api/v1/agents/tasks/{taskId}/resume` |
| Cancel    | `POST /api/v1/agents/tasks/{taskId}/cancel` |

## Plugin Development

Plugins package reusable capabilities for agents and marketplace distribution.

### Architecture

```text
plugin
  manifest
  tool definitions
  optional UI metadata
  optional webhook endpoints
  optional marketplace listing
```

Recommended structure:

```text
my-iris-plugin/
  plugin.json
  README.md
  tools/
    search.json
    create-ticket.json
  src/
    index.ts
  tests/
    plugin.test.ts
```

Manifest:

```json
{
  "id": "com.example.release-tools",
  "name": "Release Tools",
  "version": "0.1.0",
  "description": "Deployment and release management tools for Iris agents.",
  "owner": "platform",
  "capabilities": ["tool_use", "webhook"],
  "tools": ["tools/search.json", "tools/create-ticket.json"],
  "permissions": {
    "network": ["https://deployments.example.com"],
    "secrets": ["DEPLOYMENTS_API_KEY"]
  }
}
```

Registration flow:

1. Validate the manifest schema.
2. Register tool schemas with the target agent.
3. Configure required secrets.
4. Add marketplace metadata when the plugin is discoverable.
5. Run tool contract tests.

Marketplace metadata should include category, pricing model, support contact,
security review status, and compatibility version.

## Tool Integration

Tools expose deterministic capabilities to agents.

### Function Tool

```json
{
  "name": "ticket.lookup",
  "description": "Look up an engineering ticket by ID.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "ticketId": { "type": "string" }
    },
    "required": ["ticketId"]
  },
  "outputSchema": {
    "type": "object",
    "properties": {
      "status": { "type": "string" },
      "summary": { "type": "string" }
    }
  },
  "enabled": true,
  "requiresConfirmation": false
}
```

Attach to an agent:

```bash
curl -X POST https://iris.oshun.dev/api/v1/agents/$AGENT_ID/tools \
  -H "Authorization: Bearer $IRIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"tool": { "name": "ticket.lookup", "description": "Look up a ticket.", "inputSchema": {"type":"object"}, "enabled": true }}'
```

### Webhook Tool

Use webhook tools when execution happens in your system:

```json
{
  "name": "deploy.status",
  "description": "Fetch deployment status.",
  "inputSchema": {
    "type": "object",
    "properties": {
      "environment": { "type": "string", "enum": ["staging", "production"] }
    },
    "required": ["environment"]
  },
  "webhook": {
    "url": "https://integrations.example.com/iris/tools/deploy-status",
    "method": "POST",
    "signature": "hmac-sha256"
  },
  "requiresConfirmation": false
}
```

Tool design rules:

- Keep inputs small and JSON-schema validated.
- Return structured JSON with a stable schema.
- Make mutations explicit and confirmation-gated.
- Enforce server-side authorization even if Iris already checked scopes.
- Log tool call IDs and Iris request IDs.

## Memory Systems

Iris memory has multiple tiers:

| Tier     | API surface                               | Use case                                                                         |
| -------- | ----------------------------------------- | -------------------------------------------------------------------------------- |
| Core     | `/api/v1/memory/core`                     | Stable user or agent profile blocks such as persona, human, goals, instructions. |
| Working  | `/api/v1/memory/working`                  | Session/task state and short-lived context.                                      |
| Archival | `/api/v1/memory/archival`                 | Long-term facts, preferences, instructions, and verified records.                |
| Episodic | `/api/v1/memory/episodic`                 | Time-bound events and interaction history.                                       |
| Semantic | Memory search and Qdrant-backed retrieval | Conceptual recall and similarity search.                                         |

Create a memory:

```json
{
  "tier": "archival",
  "type": "preference",
  "content": "Prefers concise responses with deployment links.",
  "importance": "high",
  "tags": ["communication", "operations"],
  "source": "user"
}
```

Memory best practices:

- Ask before storing sensitive personal data.
- Prefer explicit user-confirmed memory for durable preferences.
- Attach tags and source IDs for later deletion/export.
- Search before writing to avoid duplicates.
- Use expiration for temporary facts.

## Knowledge Base Integration

Knowledge bases store documents and chunks for RAG.

### Create A Collection

```bash
curl -X POST https://iris.oshun.dev/api/v1/knowledge \
  -H "Authorization: Bearer $IRIS_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "Product Docs",
    "description": "Public and internal product documentation",
    "settings": {
      "chunkSize": 800,
      "chunkOverlap": 100,
      "embeddingModel": "text-embedding-3-large",
      "autoReindex": true
    }
  }'
```

### Upload A Document

```json
{
  "name": "release-runbook.md",
  "type": "markdown",
  "content": "# Release runbook\n...",
  "source": {
    "type": "upload",
    "fileName": "release-runbook.md",
    "mimeType": "text/markdown"
  },
  "metadata": {
    "team": "platform"
  }
}
```

### Search And RAG

| Operation    | Endpoint                                                   |
| ------------ | ---------------------------------------------------------- |
| Search       | `POST /api/v1/knowledge/search`                            |
| Quick search | `GET /api/v1/knowledge/search?q=<query>&kb=<id>`           |
| RAG context  | `POST /api/v1/knowledge/rag`                               |
| Chunks       | `GET /api/v1/knowledge/{id}/documents/{documentId}/chunks` |

RAG request:

```json
{
  "query": "How do we roll back production?",
  "knowledgeBaseIds": ["00000000-0000-0000-0000-000000000000"],
  "maxChunks": 8,
  "maxTokens": 4000,
  "minScore": 0.7
}
```

## Multi-LLM Orchestration

Model selection is currently exposed through conversation and agent
configuration. Omit `model` to use default routing.

| Use case                  | Suggested routing policy                                     |
| ------------------------- | ------------------------------------------------------------ |
| Support/chat              | Balanced quality and latency.                                |
| Operations/compliance     | Low temperature, strong reasoning model, explicit citations. |
| Cost-sensitive batch work | Lower-cost provider with fallback.                           |
| Sensitive content         | Local or approved provider route.                            |
| Long-context RAG          | Provider/model with sufficient context window.               |

Operational controls:

- Track provider latency, error rate, and token usage.
- Configure failover for transient provider failures.
- Use per-agent temperature and max-token limits.
- Use cost budgets for background worker and agent tasks.
- Store model choice in conversation/agent metadata for auditability.

## WebSocket Streaming Contract

The active production streaming path is SSE:

```text
POST /api/v1/conversations/{id}/stream
```

The WebSocket event contract is documented for gateway implementations.

### Client Events

| Event              | Purpose                         |
| ------------------ | ------------------------------- |
| `auth`             | Authenticate socket with token. |
| `chat.start`       | Start a streaming chat turn.    |
| `chat.cancel`      | Cancel an in-flight chat turn.  |
| `task.subscribe`   | Subscribe to task progress.     |
| `task.unsubscribe` | Stop task progress events.      |
| `memory.subscribe` | Subscribe to memory updates.    |
| `ping`             | Keepalive.                      |

### Server Events

| Event            | Purpose                            |
| ---------------- | ---------------------------------- |
| `auth.ok`        | Authentication accepted.           |
| `chat.delta`     | Partial assistant output.          |
| `chat.tool_call` | Tool call emitted.                 |
| `chat.complete`  | Final assistant message and usage. |
| `chat.error`     | Chat failure.                      |
| `task.updated`   | Task state changed.                |
| `task.completed` | Task completed.                    |
| `memory.updated` | Memory entry changed.              |
| `pong`           | Keepalive response.                |

Control commands must be idempotent and should carry a client-generated
`requestId`.

## Webhook Integration

Webhook delivery is the recommended pattern for external systems that need Iris
events or tool execution callbacks.

### Event Types

| Event                          | Description                              |
| ------------------------------ | ---------------------------------------- |
| `conversation.message.created` | A user or assistant message was created. |
| `conversation.completed`       | A conversation turn completed.           |
| `agent.task.created`           | A task was created.                      |
| `agent.task.updated`           | A task changed state.                    |
| `agent.task.completed`         | A task completed.                        |
| `memory.created`               | A memory was created.                    |
| `knowledge.document.indexed`   | A document finished indexing.            |
| `tool.invocation.requested`    | Iris requests external tool execution.   |

### Handler Pattern

```typescript
export async function handleIrisWebhook(request: Request): Promise<Response> {
  const rawBody = await request.text();
  verifyIrisSignature({
    body: rawBody,
    timestamp: request.headers.get('X-Iris-Webhook-Timestamp'),
    signature: request.headers.get('X-Iris-Webhook-Signature'),
    secret: process.env.IRIS_WEBHOOK_SECRET!,
  });

  const event = JSON.parse(rawBody);
  await processExactlyOnce(event.id, async () => {
    switch (event.type) {
      case 'agent.task.completed':
        await syncTaskResult(event.data);
        break;
      default:
        await storeEvent(event);
    }
  });

  return new Response(null, { status: 204 });
}
```

Retry policy:

- Return `2xx` only after durable processing or durable enqueue.
- Treat duplicate event IDs as success.
- Use exponential backoff for outbound calls.
- Dead-letter malformed or repeatedly failing events.

## Error Handling

REST errors use the envelope documented in the API reference:

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

Common codes:

| Code                  | Pattern                                         |
| --------------------- | ----------------------------------------------- |
| `VALIDATION_ERROR`    | Fix request body, path, or query.               |
| `UNAUTHORIZED`        | Refresh or rotate credential.                   |
| `FORBIDDEN`           | Check scopes, tenant, and resource permissions. |
| `NOT_FOUND`           | Confirm resource ID and ownership.              |
| `RATE_LIMITED`        | Retry after `Retry-After` with jitter.          |
| `MODEL_ERROR`         | Retry idempotent calls or fail over provider.   |
| `SERVICE_UNAVAILABLE` | Retry idempotent calls with backoff.            |
| `INTERNAL_ERROR`      | Log request ID and escalate.                    |

SDKs should map these to typed exceptions and preserve the Iris request ID.

## Performance Optimization

Latency:

- Stream long responses with SSE.
- Keep model `maxTokens` bounded.
- Use lower-latency models for interactive flows.
- Cache knowledge/RAG results that are safe to reuse.

Caching:

- Cache conversation list and knowledge metadata in clients.
- Do not cache sensitive memory by default.
- Use Redis-backed server caches for provider health and hot context.
- Invalidate knowledge search caches when documents are reindexed.

Resource management:

- Batch document ingestion.
- Keep tool payloads compact.
- Use background tasks for long-running agent work.
- Use request cancellation for abandoned UI interactions.

## Security Best Practices

- Use least-privilege scopes for every credential.
- Keep API keys server-side; mobile/browser clients should use user-bound JWTs
  or sessions.
- Verify webhook signatures and reject stale timestamps.
- Require confirmation for tools that mutate state, spend money, call external
  APIs, or write files.
- Redact secrets and sensitive memory content from logs.
- Store user memory only with appropriate consent and deletion support.
- Validate all tool inputs server-side.
- Treat model output as untrusted when it drives tools or database writes.
- Include tenant/user IDs in all persistence and search filters.

## Troubleshooting

| Symptom                               | Check                                                     | Fix                                                                    |
| ------------------------------------- | --------------------------------------------------------- | ---------------------------------------------------------------------- |
| `401 UNAUTHORIZED`                    | Token format, expiration, secret rotation.                | Refresh token or rotate API key.                                       |
| `403 FORBIDDEN`                       | Missing scope or tenant mismatch.                         | Add least-privilege scope and confirm user/resource ownership.         |
| `404 NOT_FOUND`                       | Wrong REST prefix or resource ID.                         | Use `/api/v1`, `/graphql`, and UUID resource IDs.                      |
| Streaming stops early                 | Client timeout, proxy buffering, aborted request.         | Increase timeout and disable proxy buffering for SSE.                  |
| Agent task never runs                 | Agent disabled, missing tool, or task not explicitly run. | Enable agent and call `POST /agents/tasks/{taskId}/run`.               |
| Memory search misses expected facts   | Wrong tier/type/tags or expired memory.                   | Search broader tiers and inspect memory metadata.                      |
| Knowledge search returns weak results | Chunks too large/small, stale index, low-quality source.  | Reindex, tune chunk settings, and improve source documents.            |
| Webhook duplicates                    | Retries after slow handler.                               | Process event IDs exactly once and return `2xx` after durable enqueue. |
| WebSocket unavailable                 | Gateway not deployed.                                     | Use SSE stream endpoint or deploy WebSocket gateway.                   |

_Last updated: 2026-04-28_
