> ## Documentation Index
> Fetch the complete documentation index at: https://docs.daycopilot.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Architecture Overview

> Understand DayCopilot's architecture and how the API integrates with your applications

## Overview

DayCopilot is an AI-powered productivity platform that automatically processes emails to extract tasks and events, and provides a comprehensive REST API for building productivity applications.

<Note>
  This document focuses on the aspects of DayCopilot's architecture that are relevant for API integrators. Internal implementation details are omitted for clarity.
</Note>

## System Architecture

```mermaid theme={null}
graph TB
    subgraph "Your Application"
        CLIENT[Your App] --> |HTTPS/REST| API[DayCopilot API]
    end

    subgraph "DayCopilot Platform"
        API --> AUTH[Authentication Layer]
        AUTH --> |Access Control| DATA[Data Layer]

        EMAIL[Email Processing] --> |AI Extraction| DATA
        CALENDAR[Calendar Sync] --> |CalDAV| DATA
    end

    subgraph "Core Services"
        SERVICES[REST API<br/>OAuth Service<br/>Email Processing<br/>Calendar Sync]
    end

    subgraph "Data Model"
        DATA --> TASKS[Tasks]
        DATA --> EVENTS[Events]
        DATA --> CONTEXTS[Contexts]
        DATA --> USERS[Users]
    end
```

## Core Services

DayCopilot exposes the following services through the API:

### REST API

* Standards-compliant REST endpoints
* OpenAPI 3.0 specification
* JSON request/response format
* Comprehensive error handling

### OAuth Service

* Industry-standard OAuth 2.0
* Fine-grained permission scopes
* JWT token-based authentication
* Automatic token refresh

### Email Processing

* AI-powered email parsing
* Automatic task/event extraction
* Async processing pipeline
* Real-time notifications

### Calendar Sync

* Bidirectional CalDAV integration
* RFC 5545 compliant (iCalendar)
* Timezone handling
* RSVP status tracking

## Data Model

Understanding the core data model helps you build effective integrations:

### Tasks

Tasks represent actionable items that need to be completed.

**Key Properties:**

* Unique ID (UUID)
* Title and description
* Priority levels (low, medium, high, urgent)
* Status (pending, in\_progress, completed, canceled)
* Due dates and time estimates
* Assignees (multiple users)
* Parent context
* Draft/publish versioning

### Events

Events represent calendar appointments and scheduled activities.

**Key Properties:**

* Unique ID (UUID)
* Title, description, and location
* Start and end timestamps
* All-day event flag
* Attendees list with RSVP status
* Recurrence rules (coming soon)
* Parent context

### Contexts

Contexts organize related tasks and events into logical groups.

**Key Properties:**

* Unique ID (UUID)
* Name and description
* Associated tasks and events
* Collaborators with permissions
* Sharing settings
* Activity feed

## Authentication & Security

### Access Control

DayCopilot implements database-level access control to ensure data security:

**What this means for you:**

* You don't need to filter by user ID in your queries
* All queries are automatically scoped to the authenticated user
* Shared resources are handled transparently
* No risk of accidentally accessing other users' data

See [Access Control & Permissions](/concepts/access-control) for detailed information on how data access works.

### JWT Tokens

All API requests use JSON Web Tokens (JWT) for authentication:

```javascript theme={null}
// Token structure (decoded)
{
  "sub": "user-uuid",
  "email": "user@example.com",
  "role": "authenticated",
  "iat": 1699564800,
  "exp": 1699651200
}
```

## API Design Principles

DayCopilot's API follows REST best practices:

### Resource-Oriented

```bash theme={null}
GET    /api/v1/tasks          # List tasks
POST   /api/v1/tasks          # Create task
GET    /api/v1/tasks/{id}     # Get specific task
PUT    /api/v1/tasks/{id}     # Update task
DELETE /api/v1/tasks/{id}     # Delete task
```

### Consistent Response Format

All successful responses follow this structure:

```json theme={null}
{
  "data": { /* resource or array of resources */ },
  "meta": {
    "pagination": {
      "limit": 50,
      "offset": 0,
      "total": 150
    }
  }
}
```

### Predictable Errors

All error responses include:

```json theme={null}
{
  "error": "Resource not found",
  "message": "Task with ID abc-123 does not exist",
  "status": 404,
  "correlationId": "req_abc123xyz"
}
```

## Draft/Publish Workflow

DayCopilot implements a versioning system for collaborative editing:

```mermaid theme={null}
sequenceDiagram
    participant User
    participant API
    participant Data

    User->>API: PUT /tasks/123 (update)
    API->>Data: Create draft version (v1.2)
    Data-->>User: Returns draft

    User->>API: POST /tasks/123/draft (action: accept)
    API->>Data: Publish draft (v2.0)
    Data-->>User: Published version
```

**Key Concepts:**

* `version_major`: Published version number
* `version_minor`: Draft version number
* `is_published`: Whether current version is live
* `last_live`: Snapshot of last published state

## Email Processing Flow

When users forward emails to DayCopilot, the platform processes them through an AI pipeline:

```mermaid theme={null}
graph LR
    EMAIL[Email Received] --> PARSE[Parse Content]
    PARSE --> AI[AI Extraction]
    AI --> VALIDATE[Validate Schema]
    VALIDATE --> WRITE[Create Tasks/Events]
    WRITE --> NOTIFY[Notify User]
```

**API Integration Points:**

* Tasks and events created via email appear in the API immediately
* API-created items don't trigger email processing
* You can query email metadata for items created from emails

## Calendar Integration (CalDAV)

DayCopilot supports bidirectional calendar sync via CalDAV:

```
https://app.daycopilot.ai/caldav/
```

**Features:**

* Two-way sync with external calendars
* RFC 5545 compliant (iCalendar format)
* Support for recurring events
* Timezone handling
* RSVP status tracking

## Performance & Scalability

### Caching Strategy

DayCopilot implements intelligent caching:

* API responses are cacheable (check `Cache-Control` headers)
* ETags for conditional requests
* Pagination for large datasets

### Rate Limits

See [Rate Limits](/rate-limits) for detailed information on request limits by tier.

### Pagination

All list endpoints support pagination:

```bash theme={null}
GET /api/v1/tasks?limit=50&offset=100
```

Response includes pagination metadata:

```json theme={null}
{
  "data": [...],
  "meta": {
    "pagination": {
      "limit": 50,
      "offset": 100,
      "total": 250,
      "hasMore": true
    }
  }
}
```

## Integration Patterns

### Webhooks (Coming Soon)

Subscribe to real-time updates instead of polling:

```javascript theme={null}
// Future webhook payload example
{
  "event": "task.updated",
  "data": {
    "taskId": "123",
    "changes": ["status", "assignees"]
  },
  "timestamp": "2025-11-02T12:00:00Z"
}
```

### Batch Operations

For efficiency, batch multiple operations:

```javascript theme={null}
// Create multiple tasks in one request (coming soon)
POST /api/v1/tasks/batch
{
  "tasks": [
    { "title": "Task 1", ... },
    { "title": "Task 2", ... }
  ]
}
```

## Best Practices

<AccordionGroup>
  <Accordion title="Use Appropriate HTTP Methods">
    * `GET` for fetching data (never modify)
    * `POST` for creating resources
    * `PUT` for full updates
    * `PATCH` for partial updates
    * `DELETE` for removing resources
  </Accordion>

  <Accordion title="Handle Errors Gracefully">
    Always check response status codes and handle errors appropriately. Use the `correlationId` when contacting support for faster troubleshooting.
  </Accordion>

  <Accordion title="Respect Rate Limits">
    Monitor `X-RateLimit-*` headers and implement backoff strategies. Cache responses when possible.
  </Accordion>

  <Accordion title="Use Pagination">
    Don't fetch all records at once. Use `limit` and `offset` parameters to paginate through large datasets.
  </Accordion>

  <Accordion title="Keep Tokens Secure">
    Never expose JWT tokens in client-side code, URLs, or version control. Use environment variables and secure storage.
  </Accordion>
</AccordionGroup>

## Next Steps

<CardGroup cols={2}>
  <Card title="Authentication" icon="key" href="/authentication">
    Learn about OAuth 2.0 and JWT tokens
  </Card>

  <Card title="API Reference" icon="code" href="/api-reference/introduction">
    Explore all available endpoints
  </Card>

  <Card title="Quick Start" icon="rocket" href="/quickstart">
    Make your first API call
  </Card>

  <Card title="Tasks, Events & Contexts" icon="folder-tree" href="/concepts/tasks-events-contexts">
    Understand the core data models
  </Card>
</CardGroup>
