OCaml Claude SDK using Eio and Jsont
at main 112 lines 5.3 kB view raw view rendered
1# Claude Library Architecture Summary 2 3This document summarizes the architecture of the OCaml Eio Claude library located in `../lib`. 4 5## Overview 6 7The Claude library is a high-quality OCaml Eio wrapper around the Claude Code CLI that provides structured JSON streaming communication with Claude. It follows a clean layered architecture with strong typing and comprehensive error handling. 8 9## Core Architecture 10 11The library is organized into several focused modules that work together to provide a complete Claude integration: 12 13### 1. Transport Layer (`Transport`) 14- **Purpose**: Low-level CLI process management and communication 15- **Key Functions**: 16 - Spawns and manages the `claude` CLI process using Eio's process manager 17 - Handles bidirectional JSON streaming via stdin/stdout 18 - Provides `send`/`receive_line` primitives with proper resource cleanup 19- **Integration**: Forms the foundation for all Claude communication 20 21### 2. Message Protocol Layer 22 23#### Content Blocks (`Content_block`) 24- **Purpose**: Defines the building blocks of Claude messages 25- **Types**: Text, Tool_use, Tool_result, Thinking blocks 26- **Key Features**: Each block type has specialized accessors and JSON serialization 27- **Integration**: Used by messages to represent diverse content types 28 29#### Messages (`Message`) 30- **Purpose**: Structured message types for Claude communication 31- **Types**: User, Assistant, System, Result messages 32- **Key Features**: 33 - User messages support both simple strings and complex content blocks 34 - Assistant messages include model info and mixed content 35 - System messages handle session control 36 - Result messages provide conversation metadata and usage stats 37- **Integration**: Primary data structures exchanged between client and Claude 38 39#### Control Messages (`Control`) 40- **Purpose**: Session management and control flow 41- **Key Features**: Request IDs, subtypes, and arbitrary JSON data payload 42- **Integration**: Used for session initialization, cancellation, and other operational commands 43 44### 3. Permission System (`Permissions`) 45- **Purpose**: Fine-grained control over Claude's tool usage 46- **Components**: 47 - **Modes**: Default, Accept_edits, Plan, Bypass_permissions 48 - **Rules**: Tool-specific permission specifications 49 - **Callbacks**: Custom permission logic with context and suggestions 50 - **Results**: Allow/Deny decisions with optional modifications 51- **Integration**: Consulted by client before allowing tool invocations 52 53### 4. Configuration (`Options`) 54- **Purpose**: Session configuration and behavior control 55- **Features**: 56 - Tool allow/disallow lists 57 - System prompt customization (replace or append) 58 - Model selection and thinking token limits 59 - Working directory and environment variables 60- **Integration**: Passed to transport layer and used throughout the session 61- **Pattern**: Builder pattern with `with_*` functions for immutable updates 62 63### 5. Client Interface (`Client`) 64- **Purpose**: High-level API for Claude interactions 65- **Key Functions**: 66 - Session creation and management 67 - Message sending (`query`, `send_message`, `send_user_message`) 68 - Response streaming (`receive`, `receive_all`) 69 - Permission discovery and callback management 70- **Integration**: Orchestrates all other modules to provide the main user API 71 72### 6. Main Module (`Claude`) 73- **Purpose**: Public API facade with comprehensive documentation 74- **Features**: 75 - Re-exports all sub-modules 76 - Extensive usage examples and architectural documentation 77 - Logging configuration guidance 78- **Integration**: Single entry point for library users 79 80## Data Flow 81 821. **Configuration**: Options are created with desired settings 832. **Transport**: Client creates transport layer with CLI process 843. **Message Exchange**: 85 - User messages are sent via JSON streaming 86 - Claude responses are received as streaming JSON 87 - Messages are parsed into strongly-typed structures 884. **Permission Checking**: Tool usage is filtered through permission system 895. **Content Processing**: Response content blocks are extracted and processed 906. **Session Management**: Control messages handle session lifecycle 91 92## Key Design Principles 93 94- **Eio Integration**: Native use of Eio's concurrency primitives (Switch, Process.mgr) 95- **Type Safety**: Comprehensive typing with specific error exceptions 96- **Streaming**: Efficient processing via `Message.t Seq.t` sequences 97- **Modularity**: Clear separation of concerns with minimal inter-dependencies 98- **Documentation**: Extensive interface documentation with usage examples 99- **Error Handling**: Specific exception types for different failure modes 100- **Logging**: Structured logging with per-module sources using the Logs library 101 102## Usage Patterns 103 104The library supports both simple text queries and complex multi-turn conversations: 105 106- **Simple Queries**: `Client.query` with text input 107- **Tool Control**: Permission callbacks and allow/disallow lists 108- **Streaming**: Process responses as they arrive via sequences 109- **Session Management**: Full control over Claude's execution environment 110- **Custom Prompts**: System prompt replacement and augmentation 111 112The architecture enables fine-grained control over Claude's capabilities while maintaining ease of use for common scenarios.