# Shared Communication Schemas for ACP Protocol

## Table of Contents
- [Overview](#overview)
- [Schema Definitions](#schema-definitions)
  - [Message Schema](#message-schema)
  - [Part Schema](#part-schema)
  - [Artifact Schema](#artifact-schema)
- [Communication Patterns](#communication-patterns)
- [Multimodal Content Guidelines](#multimodal-content-guidelines)
- [Best Practices](#best-practices)
- [Examples](#examples)
- [Integration with ACP Operations](#integration-with-acp-operations)

---

## Overview

The **Shared Communication** schemas form the foundation for all content exchange in the ACP (Agent Communication Protocol). These three interconnected schemas enable rich, multimodal communication between AI agents while maintaining structure, flexibility, and extensibility.

### Core Components

1. **Message** - Universal communication envelope used across all ACP operations
2. **Part** - Multimodal content building blocks supporting text, files, images, audio, and data
3. **Artifact** - Structured deliverables and outputs generated by agent processing

### Design Philosophy

- **Universal Reusability**: Same schemas used in tasks, streams, and notifications
- **Multimodal Support**: Rich content types beyond simple text
- **Structured Flexibility**: Well-defined schemas with extensibility points
- **Attribution & Audit**: Clear tracking of content origin and lifecycle
- **Progressive Enhancement**: Start simple, add complexity as needed

---

## Schema Definitions

### Message Schema

The **Message** schema is the universal communication format used throughout the entire ACP system. Every piece of communication between agents, whether in tasks, streams, or notifications, uses this consistent structure.

#### Schema Structure
```yaml
Message:
  type: object
  required: [role, parts]
  properties:
    role:
      type: string
      enum: [user, agent, system]
    parts:
      type: array
      minItems: 1
      items:
        $ref: '#/components/schemas/Part'
    timestamp:
      type: string
      format: date-time
    agentId:
      type: string
      description: ID of agent that sent this message
```

#### Field Reference

| Field | Required | Type | Description |
|-------|----------|------|-------------|
| `role` | ✅ | `enum` | Identifies sender type: user, agent, or system |
| `parts` | ✅ | `Part[]` | Content array (minimum 1 part required) |
| `timestamp` | ❌ | `datetime` | ISO 8601 timestamp of message creation |
| `agentId` | ❌ | `string` | Specific agent identifier for attribution |

#### Role Types

**👤 User Role**
- **Purpose**: Messages originating from human users
- **Usage**: Initial requests, clarifications, feedback
- **Context**: User-initiated tasks, user input in streams

**🤖 Agent Role**
- **Purpose**: Messages from AI agents
- **Usage**: Responses, analysis results, intermediate updates
- **Context**: Task processing, stream participation, agent-to-agent communication

**⚙️ System Role**
- **Purpose**: System-generated messages
- **Usage**: Status updates, notifications, error messages
- **Context**: Task lifecycle events, system notifications

#### Message Examples

**User Request:**
```json
{
  "role": "user",
  "parts": [
    {
      "type": "TextPart",
      "content": "Please analyze the customer satisfaction data from Q4 and provide insights on improvement opportunities.",
      "encoding": "utf8"
    }
  ],
  "timestamp": "2024-01-15T10:30:00Z"
}
```

**Agent Response with Multiple Content Types:**
```json
{
  "role": "agent", 
  "parts": [
    {
      "type": "TextPart",
      "content": "I've completed the customer satisfaction analysis. Here are the key findings:",
      "encoding": "utf8"
    },
    {
      "type": "DataPart",
      "content": {
        "overall_satisfaction": 7.2,
        "response_rate": 0.68,
        "key_issues": ["response_time", "product_quality", "support_availability"],
        "improvement_potential": 1.8
      },
      "mimeType": "application/json",
      "encoding": "utf8"
    },
    {
      "type": "ImagePart",
      "content": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAAB...",
      "mimeType": "image/png",
      "filename": "satisfaction_trends.png",
      "size": 156432,
      "encoding": "base64"
    }
  ],
  "timestamp": "2024-01-15T10:45:00Z",
  "agentId": "agent-analytics-001"
}
```

**System Notification:**
```json
{
  "role": "system",
  "parts": [
    {
      "type": "TextPart",
      "content": "Task processing completed successfully. Generated 3 artifacts including analysis report and visualizations.",
      "encoding": "utf8"
    }
  ],
  "timestamp": "2024-01-15T10:47:00Z"
}
```

---

### Part Schema

The **Part** schema defines the building blocks for multimodal content. Each part represents a specific type of content with its own metadata and encoding information.

#### Schema Structure
```yaml
Part:
  type: object
  required: [type]
  properties:
    type:
      type: string
      enum: [TextPart, DataPart, FilePart, ImagePart, AudioPart]
    content:
      nullable: true
      description: Text content or data payload
    mimeType:
      type: string
      description: MIME type for data/file parts
    filename:
      type: string
      description: Original filename for file parts
    size:
      type: integer
      description: Size in bytes for data/file parts
    encoding:
      type: string
      enum: [base64, utf8, binary]
      description: Encoding for data parts
  additionalProperties: true
```

#### Part Types

##### 🔤 TextPart
**Purpose**: Plain text, formatted text, code, markdown
**Common MIME Types**: `text/plain`, `text/markdown`, `text/html`, `text/css`, `text/javascript`

```json
{
  "type": "TextPart",
  "content": "# Analysis Summary\n\nThe data shows a **15% increase** in customer satisfaction...",
  "mimeType": "text/markdown",
  "encoding": "utf8"
}
```

##### 📊 DataPart  
**Purpose**: Structured data, JSON objects, XML, API responses
**Common MIME Types**: `application/json`, `application/xml`, `text/csv`

```json
{
  "type": "DataPart",
  "content": {
    "metrics": {
      "conversion_rate": 0.234,
      "customer_lifetime_value": 1250.50,
      "churn_risk": 0.12
    },
    "recommendations": ["optimize_onboarding", "improve_support"]
  },
  "mimeType": "application/json",
  "encoding": "utf8"
}
```

##### 📄 FilePart
**Purpose**: Documents, spreadsheets, presentations, archives
**Common MIME Types**: `application/pdf`, `application/vnd.ms-excel`, `application/zip`

```json
{
  "type": "FilePart",
  "content": "JVBERi0xLjQKMSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZw...",
  "mimeType": "application/pdf",
  "filename": "customer_analysis_report.pdf",
  "size": 2048576,
  "encoding": "base64"
}
```

##### 🖼️ ImagePart
**Purpose**: Charts, diagrams, screenshots, photos
**Common MIME Types**: `image/png`, `image/jpeg`, `image/svg+xml`, `image/gif`

```json
{
  "type": "ImagePart",
  "content": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8...",
  "mimeType": "image/png",
  "filename": "trend_visualization.png",
  "size": 524288,
  "encoding": "base64",
  "width": 1024,
  "height": 768,
  "alt": "Customer satisfaction trend chart showing improvement over time"
}
```

##### 🎵 AudioPart
**Purpose**: Voice messages, audio reports, generated speech
**Common MIME Types**: `audio/mp3`, `audio/wav`, `audio/ogg`

```json
{
  "type": "AudioPart", 
  "content": "UklGRnoGAABXQVZFZm10IBAAAAABAAEAQB8AAEAfAAABAAgAZGF0YQoGAAC...",
  "mimeType": "audio/wav",
  "filename": "analysis_summary.wav",
  "size": 1048576,
  "encoding": "base64",
  "duration": 45.2,
  "sampleRate": 44100,
  "transcript": "The customer satisfaction analysis reveals three key areas for improvement..."
}
```

#### Encoding Types

| Encoding | Use Case | Content Type |
|----------|----------|--------------|
| `utf8` | Text content | Plain text, JSON, CSV, code |
| `base64` | Binary data | Images, files, audio, documents |
| `binary` | Raw binary | Direct binary transmission |

#### Extended Properties

The `additionalProperties: true` allows part-specific metadata:

**Image Properties:**
```json
{
  "type": "ImagePart",
  "width": 1920,
  "height": 1080,
  "dpi": 300,
  "colorSpace": "RGB",
  "alt": "Description for accessibility"
}
```

**Audio Properties:**
```json
{
  "type": "AudioPart",
  "duration": 120.5,
  "sampleRate": 44100,
  "channels": 2,
  "bitrate": 320,
  "transcript": "Auto-generated transcript"
}
```

**Data Properties:**
```json
{
  "type": "DataPart",
  "schema": "customer_metrics_v2",
  "validation": "passed",
  "source": "analytics_pipeline"
}
```

---

### Artifact Schema

The **Artifact** schema represents structured deliverables and outputs generated during agent processing. Artifacts are the tangible results of agent work, packaged with rich metadata for tracking and management.

#### Schema Structure
```yaml
Artifact:
  type: object
  required: [artifactId, name, parts]
  properties:
    artifactId:
      type: string
      description: Unique identifier for artifact
    name:
      type: string
      description: Human-readable artifact name
    description:
      type: string
      description: Description of artifact contents/purpose
    parts:
      type: array
      items:
        $ref: '#/components/schemas/Part'
    createdAt:
      type: string
      format: date-time
    createdBy:
      type: string
      description: Agent ID that created this artifact
    version:
      type: string
      description: Artifact version number
    metadata:
      type: object
      additionalProperties: true
```

#### Field Reference

| Field | Required | Type | Description |
|-------|----------|------|-------------|
| `artifactId` | ✅ | `string` | Unique identifier for tracking and referencing |
| `name` | ✅ | `string` | Human-readable name for display |
| `description` | ❌ | `string` | Detailed explanation of artifact purpose |
| `parts` | ✅ | `Part[]` | Content components using Part schema |
| `createdAt` | ❌ | `datetime` | Creation timestamp |
| `createdBy` | ❌ | `string` | Agent ID that created this artifact |
| `version` | ❌ | `string` | Version identifier for tracking changes |
| `metadata` | ❌ | `object` | Custom properties and processing information |

#### Artifact Categories

##### 📊 Analysis Artifacts
**Purpose**: Reports, insights, data analysis results
**Components**: PDF reports, data files, visualizations

```json
{
  "artifactId": "analysis-customer-satisfaction-20240115",
  "name": "Customer Satisfaction Analysis Q4 2023",
  "description": "Comprehensive analysis of customer satisfaction metrics with actionable recommendations",
  "parts": [
    {
      "type": "FilePart",
      "content": "...",
      "mimeType": "application/pdf",
      "filename": "satisfaction_analysis.pdf"
    },
    {
      "type": "DataPart",
      "content": {...},
      "mimeType": "application/json"
    }
  ],
  "createdAt": "2024-01-15T10:45:00Z",
  "createdBy": "agent-analytics-001",
  "version": "1.0",
  "metadata": {
    "analysisType": "customer_satisfaction",
    "dataPeriod": "2023-Q4",
    "confidenceScore": 0.94,
    "processingTimeMs": 45000
  }
}
```

##### 🎨 Visualization Artifacts
**Purpose**: Charts, graphs, dashboards, visual representations
**Components**: Images, interactive elements, data definitions

```json
{
  "artifactId": "viz-trends-dashboard-001",
  "name": "Customer Trends Dashboard",
  "description": "Interactive dashboard showing customer behavior trends and key metrics",
  "parts": [
    {
      "type": "ImagePart",
      "content": "...",
      "mimeType": "image/svg+xml",
      "filename": "dashboard.svg"
    },
    {
      "type": "DataPart",
      "content": {...},
      "mimeType": "application/json"
    }
  ],
  "metadata": {
    "chartType": "dashboard",
    "interactivity": true,
    "dataPoints": 15000,
    "refreshRate": "hourly"
  }
}
```

##### 💾 Data Artifacts
**Purpose**: Processed datasets, cleaned data, data transformations
**Components**: Data files, processing logs, quality reports

```json
{
  "artifactId": "data-cleaned-transactions-xyz789",
  "name": "Cleaned Transaction Dataset",
  "description": "Customer transaction data cleaned and validated for analysis",
  "parts": [
    {
      "type": "FilePart",
      "content": null,
      "mimeType": "application/parquet",
      "filename": "transactions_clean.parquet",
      "size": 15728640
    }
  ],
  "metadata": {
    "originalRecords": 1245678,
    "cleanedRecords": 1198432,
    "qualityScore": 0.96,
    "processingSteps": ["deduplication", "validation", "standardization"]
  }
}
```

##### 🔧 Code Artifacts
**Purpose**: Generated code, scripts, configurations
**Components**: Source files, documentation, tests

```json
{
  "artifactId": "code-api-client-python-001",
  "name": "Python ACP Client Library",
        "description": "Generated Python client library for ACP API integration",
  "parts": [
    {
      "type": "FilePart",
      "content": "...",
      "mimeType": "text/x-python",
      "filename": "acp_client.py"
    },
    {
      "type": "FilePart",
      "content": "...",
      "mimeType": "text/markdown", 
      "filename": "README.md"
    }
  ],
  "metadata": {
    "language": "python",
    "targetVersion": "3.8+",
    "linesOfCode": 245,
    "testCoverage": 0.85
  }
}
```

---

## Communication Patterns

### Single-Part Messages
**Use Case**: Simple text communication, single file transfer

```json
{
  "role": "user",
  "parts": [
    {
      "type": "TextPart",
      "content": "Please analyze the attached dataset"
    }
  ]
}
```

### Multi-Part Messages
**Use Case**: Rich communication with multiple content types

```json
{
  "role": "agent",
  "parts": [
    {
      "type": "TextPart", 
      "content": "Analysis complete. Here are the results:"
    },
    {
      "type": "DataPart",
      "content": {"summary": "..."},
      "mimeType": "application/json"
    },
    {
      "type": "ImagePart",
      "content": "...",
      "filename": "results_chart.png"
    }
  ]
}
```

### Progressive Content Building
**Use Case**: Building complex artifacts through multiple messages

```json
// Message 1: Initial data
{
  "role": "agent",
  "parts": [
    {
      "type": "TextPart",
      "content": "Starting analysis, here's the raw data summary:"
    },
    {
      "type": "DataPart",
      "content": {...}
    }
  ]
}

// Message 2: Processed results
{
  "role": "agent", 
  "parts": [
    {
      "type": "TextPart",
      "content": "Analysis complete, generating visualizations:"
    },
    {
      "type": "ImagePart",
      "content": "...",
      "filename": "analysis_chart.png"
    }
  ]
}

// Final: Complete artifact
{
  "artifactId": "complete-analysis-001",
  "name": "Complete Data Analysis",
  "parts": [
    // All previous parts consolidated
  ]
}
```

### Reference-Based Content
**Use Case**: Large files stored externally with metadata

```json
{
  "type": "FilePart",
  "content": null,
  "mimeType": "application/parquet",
  "filename": "large_dataset.parquet", 
  "size": 1073741824,
  "reference": "s3://bucket/path/large_dataset.parquet",
  "checksum": "sha256:abcd1234...",
  "expiresAt": "2024-02-15T10:30:00Z"
}
```

---

## Multimodal Content Guidelines

### Content Size Recommendations

| Content Type | Inline Limit | Recommended Action |
|--------------|---------------|-------------------|
| Text | < 1MB | Include directly in content |
| Images | < 5MB | Base64 encode in content |
| Audio | < 10MB | Base64 encode in content |
| Files | < 25MB | Base64 encode in content |
| Large Files | > 25MB | Use external storage with reference |

### MIME Type Standards

**Text Content:**
- `text/plain` - Plain text
- `text/markdown` - Markdown formatted text
- `text/html` - HTML content
- `text/csv` - Comma-separated values
- `text/javascript`, `text/css` - Code files

**Structured Data:**
- `application/json` - JSON data
- `application/xml` - XML data
- `application/yaml` - YAML configuration

**Documents:**
- `application/pdf` - PDF documents
- `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet` - Excel files
- `application/vnd.openxmlformats-officedocument.wordprocessingml.document` - Word docs

**Images:**
- `image/png` - PNG images (recommended for charts/diagrams)
- `image/jpeg` - JPEG photos
- `image/svg+xml` - SVG vector graphics
- `image/gif` - Animated GIFs

**Audio:**
- `audio/mp3` - MP3 audio
- `audio/wav` - WAV audio (uncompressed)
- `audio/ogg` - OGG Vorbis

### Encoding Best Practices

#### Base64 Encoding
```javascript
// Encoding binary data for transmission
const fileBuffer = fs.readFileSync('report.pdf');
const base64Content = fileBuffer.toString('base64');

const filePart = {
  type: 'FilePart',
  content: base64Content,
  mimeType: 'application/pdf',
  filename: 'report.pdf',
  size: fileBuffer.length,
  encoding: 'base64'
};
```

#### UTF-8 Text Handling
```javascript
// Ensure proper UTF-8 encoding for text content
const textContent = fs.readFileSync('data.csv', 'utf8');

const textPart = {
  type: 'FilePart',
  content: textContent,
  mimeType: 'text/csv',
  filename: 'data.csv',
  size: Buffer.byteLength(textContent, 'utf8'),
  encoding: 'utf8'
};
```

#### JSON Data Structuring
```javascript
// Structured data as DataPart
const analysisResults = {
  metrics: {
    accuracy: 0.94,
    precision: 0.87,
    recall: 0.91
  },
  recommendations: [
    'increase_training_data',
    'tune_hyperparameters'
  ],
  confidence: 0.92
};

const dataPart = {
  type: 'DataPart',
  content: analysisResults,
  mimeType: 'application/json',
  encoding: 'utf8'
};
```

---

## Best Practices

### Message Design

#### 1. Role Assignment
```javascript
// Good: Clear role identification
const userMessage = {
  role: 'user',
  parts: [...],
  timestamp: new Date().toISOString()
};

const agentMessage = {
  role: 'agent',
  parts: [...],
  timestamp: new Date().toISOString(),
  agentId: 'agent-analytics-001'
};

// Include agentId for agent messages for attribution
```

#### 2. Timestamp Management
```javascript
// Good: Consistent timestamp handling
const createMessage = (role, parts, agentId = null) => ({
  role,
  parts,
  timestamp: new Date().toISOString(),
  ...(agentId && { agentId })
});
```

#### 3. Content Organization
```javascript
// Good: Logical part ordering
const multiPartMessage = {
  role: 'agent',
  parts: [
    // 1. Start with summary text
    { type: 'TextPart', content: 'Analysis complete. Key findings:' },
    // 2. Follow with structured data
    { type: 'DataPart', content: results, mimeType: 'application/json' },
    // 3. End with supporting visuals/files
    { type: 'ImagePart', content: chartData, filename: 'results.png' }
  ]
};
```

### Part Optimization

#### 1. Content Validation
```javascript
// Validate content before creating parts
const createTextPart = (content) => {
  if (!content || typeof content !== 'string') {
    throw new Error('Text content must be a non-empty string');
  }
  
  return {
    type: 'TextPart',
    content: content.trim(),
    encoding: 'utf8',
    size: Buffer.byteLength(content, 'utf8')
  };
};
```

#### 2. File Size Management
```javascript
// Handle large files appropriately
const createFilePart = async (filePath, options = {}) => {
  const stats = await fs.stat(filePath);
  const maxInlineSize = options.maxInlineSize || 25 * 1024 * 1024; // 25MB
  
  if (stats.size > maxInlineSize) {
    // Use external storage for large files
    const reference = await uploadToExternalStorage(filePath);
    return {
      type: 'FilePart',
      content: null,
      mimeType: getMimeType(filePath),
      filename: path.basename(filePath),
      size: stats.size,
      reference: reference.url,
      checksum: reference.checksum
    };
  } else {
    // Include content directly for smaller files
    const content = await fs.readFile(filePath, 'base64');
    return {
      type: 'FilePart',
      content,
      mimeType: getMimeType(filePath),
      filename: path.basename(filePath),
      size: stats.size,
      encoding: 'base64'
    };
  }
};
```

#### 3. MIME Type Detection
```javascript
// Accurate MIME type detection
const getMimeType = (filename) => {
  const ext = path.extname(filename).toLowerCase();
  const mimeTypes = {
    '.pdf': 'application/pdf',
    '.png': 'image/png',
    '.jpg': 'image/jpeg',
    '.jpeg': 'image/jpeg',
    '.csv': 'text/csv',
    '.json': 'application/json',
    '.mp3': 'audio/mp3',
    '.wav': 'audio/wav'
  };
  
  return mimeTypes[ext] || 'application/octet-stream';
};
```

### Artifact Management

#### 1. Unique ID Generation
```javascript
// Generate meaningful artifact IDs
const generateArtifactId = (type, agentId, timestamp = Date.now()) => {
  const prefix = type.toLowerCase().replace(/\s+/g, '-');
  const agentPrefix = agentId.replace(/[^a-z0-9]/gi, '');
  const timeStr = new Date(timestamp).toISOString().slice(0, 10).replace(/-/g, '');
  const random = Math.random().toString(36).substr(2, 6);
  
  return `${prefix}-${agentPrefix}-${timeStr}-${random}`;
};

// Example: "analysis-agent001-20240115-x7k2m9"
```

#### 2. Version Management
```javascript
// Semantic versioning for artifacts
const createVersionedArtifact = (baseArtifact, changes) => {
  const [major, minor, patch] = (baseArtifact.version || '1.0.0').split('.').map(Number);
  
  let newVersion;
  if (changes.breaking) {
    newVersion = `${major + 1}.0.0`;
  } else if (changes.features) {
    newVersion = `${major}.${minor + 1}.0`;
  } else {
    newVersion = `${major}.${minor}.${patch + 1}`;
  }
  
  return {
    ...baseArtifact,
    version: newVersion,
    createdAt: new Date().toISOString(),
    metadata: {
      ...baseArtifact.metadata,
      previousVersion: baseArtifact.version,
      changeType: changes.breaking ? 'major' : changes.features ? 'minor' : 'patch'
    }
  };
};
```

#### 3. Metadata Standards
```javascript
// Consistent metadata structure
const createArtifactMetadata = (options) => ({
  // Processing information
  processingTimeMs: options.processingTime,
  processingVersion: options.agentVersion,
  
  // Quality metrics
  confidenceScore: options.confidence,
  qualityScore: options.quality,
  
  // Data lineage
  dataSources: options.sources || [],
  dependencies: options.dependencies || [],
  
  // Content metrics
  dataPoints: options.dataPoints,
  size: options.totalSize,
  
  // Custom properties
  ...options.customMetadata
});
```

### Error Handling

#### 1. Content Validation
```javascript
// Validate message structure
const validateMessage = (message) => {
  const errors = [];
  
  if (!message.role || !['user', 'agent', 'system'].includes(message.role)) {
    errors.push('Invalid or missing role');
  }
  
  if (!message.parts || !Array.isArray(message.parts) || message.parts.length === 0) {
    errors.push('Parts array must contain at least one part');
  }
  
  message.parts?.forEach((part, index) => {
    if (!part.type || !['TextPart', 'DataPart', 'FilePart', 'ImagePart', 'AudioPart'].includes(part.type)) {
      errors.push(`Invalid part type at index ${index}`);
    }
  });
  
  if (errors.length > 0) {
    throw new ValidationError('Message validation failed', errors);
  }
};
```

#### 2. Graceful Degradation
```javascript
// Handle missing or corrupted content
const safeGetContent = (part) => {
  try {
    if (part.content === null || part.content === undefined) {
      return {
        available: false,
        reason: 'Content not available',
        fallback: part.filename || 'Unknown content'
      };
    }
    
    if (part.encoding === 'base64') {
      // Validate base64 content
      const decoded = Buffer.from(part.content, 'base64');
      return {
        available: true,
        content: part.content,
        size: decoded.length
      };
    }
    
    return {
      available: true,
      content: part.content,
      size: part.size || Buffer.byteLength(part.content, 'utf8')
    };
  } catch (error) {
    return {
      available: false,
      reason: error.message,
      fallback: 'Content could not be processed'
    };
  }
};
```

---

## Examples

### Complete Task Communication Flow

#### 1. User Initiates Task
```json
{
  "jsonrpc": "2.0",
  "method": "tasks.create",
  "params": {
    "initialMessage": {
      "role": "user",
      "parts": [
        {
          "type": "TextPart",
          "content": "Please analyze the customer churn data and create a predictive model. I've attached the dataset from our CRM system.",
          "encoding": "utf8"
        },
        {
          "type": "FilePart",
          "content": "dXNlcklkLGFnZSxnZW5kZXIsY3VycmVudF9zdGF0dXMsY2h1cm5lZA0KMSwyNSxNLGFjdGl2ZSxOb...",
          "mimeType": "text/csv",
          "filename": "customer_data.csv",
          "size": 2048576,
          "encoding": "base64"
        }
      ],
      "timestamp": "2024-01-15T10:00:00Z"
    },
    "priority": "HIGH"
  },
  "id": "req-churn-analysis-001"
}
```

#### 2. Agent Acknowledges and Provides Progress
```json
{
  "jsonrpc": "2.0",
  "method": "tasks.send", 
  "params": {
    "taskId": "task-churn-analysis-abc123",
    "message": {
      "role": "agent",
      "parts": [
        {
          "type": "TextPart",
          "content": "I've received your customer churn analysis request. Starting data preprocessing and exploratory analysis.",
          "encoding": "utf8"
        },
        {
          "type": "DataPart",
          "content": {
            "dataset_info": {
              "total_records": 15000,
              "features": 12,
              "missing_values": 0.023,
              "churn_rate": 0.187
            },
            "preprocessing_steps": [
              "data_validation",
              "missing_value_handling", 
              "feature_engineering",
              "data_splitting"
            ],
            "estimated_completion": "2024-01-15T11:30:00Z"
          },
          "mimeType": "application/json",
          "encoding": "utf8"
        }
      ],
      "timestamp": "2024-01-15T10:15:00Z",
      "agentId": "agent-ml-analyst-002"
    }
  },
  "id": "req-progress-001"
}
```

#### 3. Agent Provides Intermediate Results
```json
{
  "jsonrpc": "2.0",
  "method": "tasks.send",
  "params": {
    "taskId": "task-churn-analysis-abc123", 
    "message": {
      "role": "agent",
      "parts": [
        {
          "type": "TextPart",
          "content": "Exploratory data analysis complete. I've identified key patterns in customer behavior that correlate with churn. Proceeding with model training.",
          "encoding": "utf8"
        },
        {
          "type": "ImagePart",
          "content": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
          "mimeType": "image/png",
          "filename": "churn_correlations.png",
          "size": 567890,
          "encoding": "base64",
          "width": 1200,
          "height": 800,
          "alt": "Correlation matrix showing relationships between customer features and churn probability"
        },
        {
          "type": "DataPart",
          "content": {
            "key_findings": {
              "strongest_predictors": ["tenure", "monthly_charges", "support_calls"],
              "churn_segments": [
                {"name": "High-Risk New Customers", "size": 0.12, "churn_rate": 0.45},
                {"name": "Price-Sensitive Long-term", "size": 0.08, "churn_rate": 0.38},
                {"name": "Service-Dissatisfied", "size": 0.15, "churn_rate": 0.52}
              ]
            },
            "model_performance_preview": {
              "precision": 0.84,
              "recall": 0.79,
              "f1_score": 0.81
            }
          },
          "mimeType": "application/json",
          "encoding": "utf8"
        }
      ],
      "timestamp": "2024-01-15T11:00:00Z",
      "agentId": "agent-ml-analyst-002"
    }
  },
  "id": "req-intermediate-001"
}
```

#### 4. Task Completion with Artifacts
```json
{
  "jsonrpc": "2.0",
  "id": "task-completion-notification",
  "result": {
    "type": "task",
    "task": {
      "taskId": "task-churn-analysis-abc123",
      "status": "COMPLETED",
      "messages": [
        {
          "role": "agent",
          "parts": [
            {
              "type": "TextPart",
              "content": "Customer churn analysis and predictive modeling completed successfully. I've created a comprehensive analysis package including the trained model, performance metrics, and actionable recommendations.",
              "encoding": "utf8"
            }
          ],
          "timestamp": "2024-01-15T11:45:00Z",
          "agentId": "agent-ml-analyst-002"
        }
      ],
      "artifacts": [
        {
          "artifactId": "churn-model-package-20240115-x7k2m9",
          "name": "Customer Churn Prediction Model Package",
          "description": "Complete machine learning solution for predicting customer churn including trained model, validation results, and implementation guide",
          "parts": [
            {
              "type": "FilePart",
              "content": "H4sIAAAAAAAAA+3cf2zT5xnH8Xt+jp04Nk7sJHYSO3ES0pCEtLQhDSmlLaW0tKUt...",
              "mimeType": "application/octet-stream",
              "filename": "churn_model.pkl",
              "size": 15728640,
              "encoding": "base64"
            },
            {
              "type": "FilePart",
              "content": "JVBERi0xLjQKMSAwIG9iago8PAovVHlwZSAvQ2F0YWxvZw0KL1BhZ2VzIDIgMCBSDQo+Pg0K...",
              "mimeType": "application/pdf", 
              "filename": "churn_analysis_report.pdf",
              "size": 3145728,
              "encoding": "base64"
            },
            {
              "type": "DataPart",
              "content": {
                "model_metadata": {
                  "algorithm": "gradient_boosting",
                  "features": ["tenure", "monthly_charges", "total_charges", "support_calls", "contract_type"],
                  "performance": {
                    "accuracy": 0.87,
                    "precision": 0.84,
                    "recall": 0.82,
                    "f1_score": 0.83,
                    "auc_roc": 0.91
                  },
                  "validation": {
                    "method": "5_fold_cross_validation",
                    "mean_score": 0.856,
                    "std_score": 0.023
                  }
                },
                "business_impact": {
                  "potential_savings": 450000,
                  "identified_at_risk": 2847,
                  "recommended_interventions": [
                    "targeted_retention_campaign",
                    "pricing_optimization",
                    "service_quality_improvement"
                  ]
                }
              },
              "mimeType": "application/json",
              "encoding": "utf8"
            }
          ],
          "createdAt": "2024-01-15T11:45:00Z",
          "createdBy": "agent-ml-analyst-002",
          "version": "1.0",
          "metadata": {
            "modelType": "churn_prediction",
            "trainingDataSize": 15000,
            "validationDataSize": 3000,
            "processingTimeMs": 5400000,
            "confidenceScore": 0.91,
            "businessValue": "high",
            "deploymentReady": true,
            "tags": ["churn", "prediction", "ml", "customer_retention"]
          }
        }
      ]
    }
  }
}
```

### Stream Communication Example

#### Multi-Agent Collaborative Analysis
```json
// Agent A initiates collaboration
{
  "role": "agent",
  "parts": [
    {
      "type": "TextPart",
      "content": "I need assistance with this complex financial analysis. The dataset shows unusual patterns that require domain expertise.",
      "encoding": "utf8"
    },
    {
      "type": "DataPart",
      "content": {
        "anomalies_detected": 47,
        "severity": "medium",
        "affected_accounts": ["ACC-001", "ACC-045", "ACC-127"],
        "pattern_type": "transaction_frequency_spike"
      },
      "mimeType": "application/json"
    }
  ],
  "timestamp": "2024-01-15T14:00:00Z",
  "agentId": "agent-data-analyst"
}

// Agent B responds with expertise
{
  "role": "agent",
  "parts": [
    {
      "type": "TextPart",
      "content": "I've seen similar patterns in Q3. This typically indicates seasonal business changes rather than fraud. Let me run additional validation checks.",
      "encoding": "utf8"
    },
    {
      "type": "ImagePart",
      "content": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNk+M9QDwADhgGAWjR9awAAAABJRU5ErkJggg==",
      "mimeType": "image/png",
      "filename": "seasonal_comparison.png",
      "size": 234567,
      "encoding": "base64"
    }
  ],
  "timestamp": "2024-01-15T14:02:00Z", 
  "agentId": "agent-financial-expert"
}
```

---

## Integration with ACP Operations

### Task Integration

**Initial Task Creation:**
```json
{
  "method": "tasks.create",
  "params": {
    "initialMessage": {
      "role": "user",
      "parts": [...],
      "timestamp": "..."
    }
  }
}
```

**Task Progress Updates:**
```json
{
  "method": "tasks.send",
  "params": {
    "taskId": "...",
    "message": {
      "role": "agent", 
      "parts": [...],
      "agentId": "..."
    }
  }
}
```

**Task Results:**
```json
{
  "result": {
    "type": "task",
    "task": {
      "messages": [...],
      "artifacts": [...]
    }
  }
}
```

### Stream Integration

**Stream Messages:**
```json
{
  "method": "stream.message",
  "params": {
    "streamId": "...",
    "message": {
      "role": "agent",
      "parts": [...],
      "agentId": "..."
    }
  }
}
```

**Stream Chunks (Real-time):**
```json
{
  "method": "stream.chunk", 
  "params": {
    "streamId": "...",
    "chunk": {
      "role": "agent",
      "parts": [...],
      "agentId": "..."
    },
    "sequence": 1,
    "isLast": false
  }
}
```

### Notification Integration

**Task Notifications:**
```json
{
  "method": "task.notification",
  "params": {
    "taskId": "...",
    "event": "NEW_ARTIFACT",
    "data": {
      "artifactId": "...",
      "name": "...",
      "parts": [...]
    }
  }
}
```

---

## Conclusion

The Shared Communication schemas provide a robust foundation for rich, multimodal agent-to-agent communication. These schemas enable:

- **Universal Message Format**: Consistent structure across all ACP operations
- **Multimodal Content**: Support for text, files, images, audio, and structured data
- **Structured Deliverables**: Professional artifact packaging with rich metadata
- **Attribution & Audit**: Clear tracking of content origin and processing
- **Extensibility**: Future-proof design with custom metadata support

By following the patterns and best practices outlined in this document, you can build sophisticated agent communication systems that handle complex, real-world use cases while maintaining clarity, performance, and reliability.

The schemas work seamlessly with the JSON-RPC foundation to provide a complete communication framework for your ACP agent ecosystem. 