npm package: @loic.farge/sail-core
Description: Standard Agent Interface Language - A universal framework for structured human-agent communication
Author: Loic Farge
Latest version: 1.0.1

# SAIL: Standard Agent Interface Language

A TypeScript library implementing the **Standard Agent Interface Language** - a universal framework for structured human-agent communication. SAIL provides a standardized way to create, validate, and manage messages between services, agents, or any communicating entities.

## 📜 Specification & Attribution

This implementation is based on the SAIL specification:
- **Author**: Loic Farge
- **Contributors**: The SAIL Initiative Contributors  
- **Date**: June 2025
- **Specification License**: Creative Commons Attribution 4.0 International License (CC BY 4.0)

The SAIL specification document is © 2025 Loic Farge & The SAIL Initiative Contributors and is licensed under CC BY 4.0. You are free to share, adapt, and build upon the specification for any purpose, provided you give appropriate credit to the original authors and contributors.

## 🎯 Features

- **📦 Structured Communication**: Standardized message format for easy routing, parsing, and archiving
- **🔍 Comprehensive Validation**: Schema validation with detailed error reporting
- **🧠 Reduced Cognitive Load**: Clear context and intent structure
- **↻ Replayability & Auditing**: Thread tracking and message lifecycle management
- **🔐 Security & Permission Clarity**: Explicit sender, recipient, and intent specification
- **🤖 Agent Interoperability**: Common language for different systems to communicate

## 📦 Installation

```bash
npm install @loic.farge/sail-core
```

## 🚀 Quick Start

```typescript
import { createSAILMessage, validateSAILMessage } from '@loic.farge/sail-core';

// Create a message
const message = createSAILMessage({
  sender: "service-a@domain.com",
  recipient: "service-b@domain.com", 
  intent: "process_data",
  payload: {
    data: "Hello World",
    priority: "high"
  },
  responseRequired: true,
  expiryHours: 24
});

// Validate the message
const result = validateSAILMessage(message);
if (result.valid) {
  console.log("Message is valid!");
} else {
  console.error("Validation errors:", result.errors);
}
```

## 📋 Message Structure

Every SAIL message follows this structure:

```typescript
interface SAILMessage {
  sender: string;           // Who sent the message
  recipient: string;        // Who should receive it
  intent: string;          // What action is requested (lowercase_with_underscores)
  context: {
    thread: string;        // Conversation thread ID
    timestamp: string;     // ISO 8601 timestamp
    role?: string;         // Optional role context
  };
  payload: Record<string, any>;  // Message data
  response_required: boolean;    // Whether response is needed
  expiry: string;               // When message expires (ISO 8601)
  status: 'pending' | 'acknowledged' | 'executed' | 'failed' | 'expired';
}
```

## 🔧 API Reference

### Core Functions

#### `createSAILMessage(options)`
Creates a new SAIL message with validation.

```typescript
const message = createSAILMessage({
  sender: "user@company.com",
  recipient: "system@company.com",
  intent: "submit_report", 
  payload: { reportId: "R001", data: {...} },
  thread: "reports/monthly", // optional
  expiryHours: 48,          // optional, defaults to 24
  responseRequired: true     // optional, defaults to false
});
```

#### `validateSAILMessage(message)`
Validates a message and returns detailed results.

```typescript
const result = validateSAILMessage(message);
// result: { valid: boolean, errors: ValidationError[], warnings: ValidationWarning[] }
```

### Utility Classes

#### `SAILTimeUtils`
Time and date utilities for message handling.

```typescript
import { SAILTimeUtils } from '@loic.farge/sail-core';

SAILTimeUtils.now();                    // Current ISO timestamp
SAILTimeUtils.hoursFromNow(24);         // 24 hours from now
SAILTimeUtils.minutesFromNow(30);       // 30 minutes from now
SAILTimeUtils.isFuture("2025-01-01T00:00:00Z");  // Check if date is future
SAILTimeUtils.hoursUntil("2025-01-01T00:00:00Z"); // Hours until date
```

#### `SAILThreadUtils`
Thread ID generation and management.

```typescript
import { SAILThreadUtils } from '@loic.farge/sail-core';

SAILThreadUtils.generateThreadId();                    // thread/abc123/def456
SAILThreadUtils.generateThreadId("orders");            // orders/abc123/def456
SAILThreadUtils.generateHierarchicalId("main", "sub"); // main/sub
SAILThreadUtils.parseThreadId("orders/abc123/def456"); // { prefix: "orders", timestamp: "abc123", random: "def456" }
```

#### `SAILIntentUtils`
Intent validation and formatting.

```typescript
import { SAILIntentUtils } from '@loic.farge/sail-core';

SAILIntentUtils.isValidFormat("process_data");    // true
SAILIntentUtils.isValidFormat("ProcessData");     // false
SAILIntentUtils.normalize("Process Data!");       // "process_data"
SAILIntentUtils.isEmpty("");                      // true
```

#### `SAILTransformUtils`
Message transformation utilities.

```typescript
import { SAILTransformUtils } from '@loic.farge/sail-core';

SAILTransformUtils.toJSON(message);              // Pretty JSON string
SAILTransformUtils.fromJSON(jsonString);         // Parse back to message
SAILTransformUtils.clone(message);               // Deep clone message
SAILTransformUtils.updateStatus(message, 'executed'); // Update status
SAILTransformUtils.getSummary(message);          // "sender → recipient: intent (status)"
```

## 📚 Usage Examples

### 1. Task Assignment System

```typescript
import { createSAILMessage, SAILMessageBuilder } from '@loic.farge/sail-core';

// Simple task assignment
const taskMessage = createSAILMessage({
  sender: "project.manager@company.com",
  recipient: "developer@company.com",
  intent: "assign_task",
  payload: {
    task: "Implement user authentication",
    deadline: "2025-07-01T17:00:00Z",
    priority: "high",
    estimatedHours: 16
  },
  responseRequired: true,
  expiryHours: 48
});

// Using the builder pattern for more control
const complexTask = SAILMessageBuilder.create()
  .setSender("lead.dev@company.com")
  .setRecipient("team@company.com")
  .setIntent("code_review")
  .setContext({
    thread: "projects/auth_system/reviews",
    timestamp: new Date().toISOString(),
    role: "technical_lead"
  })
  .setPayload({
    pullRequest: "PR-123",
    branch: "feature/auth",
    reviewers: ["senior1@company.com", "senior2@company.com"],
    priority: "high"
  })
  .setResponseRequired(true)
  .setExpiry(new Date(Date.now() + 8 * 60 * 60 * 1000)) // 8 hours
  .setStatus('pending')
  .build();
```

### 2. Document Request System

```typescript
const docRequest = createSAILMessage({
  sender: "new.developer@company.com",
  recipient: "documentation.system@company.com",
  intent: "request_documentation",
  payload: {
    topic: "API authentication flow",
    type: "technical_guide",
    format: "markdown",
    urgency: "medium"
  },
  responseRequired: true,
  expiryHours: 24
});
```

### 3. Approval Workflow

```typescript
const approvalRequest = createSAILMessage({
  sender: "employee@company.com", 
  recipient: "manager@company.com",
  intent: "request_approval",
  payload: {
    type: "expense_claim",
    amount: 1250.00,
    currency: "USD",
    category: "travel",
    description: "Client meeting in NYC",
    receipts: ["receipt1.pdf", "receipt2.pdf"],
    businessJustification: "Required for Q3 deal closure"
  },
  thread: "finance/expenses/Q3",
  responseRequired: true,
  expiryHours: 72
});
```

### 4. Agent Communication

```typescript
// Command to an autonomous agent
const agentCommand = createSAILMessage({
  sender: "orchestrator@company.com",
  recipient: "data.processor.agent@company.com", 
  intent: "process_batch",
  payload: {
    batchId: "batch_20250620_001",
    inputPath: "/data/raw/customer_data.csv",
    outputPath: "/data/processed/",
    transformations: ["normalize", "validate", "enrich"],
    priority: "high"
  },
  responseRequired: true,
  expiryHours: 2
});

// Meeting summary request
const summaryRequest = createSAILMessage({
  sender: "calendar.system@company.com",
  recipient: "meeting.summarizer@company.com",
  intent: "generate_summary", 
  payload: {
    meetingId: "meet_20250620_standup",
    participants: ["alice@company.com", "bob@company.com"],
    duration: 30,
    transcript: "...",
    requestedSections: ["action_items", "decisions", "next_steps"]
  },
  responseRequired: true,
  expiryHours: 4
});
```

## 🔍 Validation & Error Handling

SAIL provides comprehensive validation with detailed error reporting:

```typescript
import { SAILValidator, ValidationResult } from '@loic.farge/sail-core';

const validator = new SAILValidator();
const report = validator.getValidationReport(message);

console.log('Overall valid:', report.overall.valid);
console.log('Schema errors:', report.schema.errors);
console.log('MCP layer errors:', report.mcp.errors);
console.log('Layer results:', report.layers);

// Handle specific validation errors
if (!report.overall.valid) {
  report.overall.errors.forEach(error => {
    console.log(`${error.layer} layer - ${error.field}: ${error.message}`);
  });
}

// Handle warnings
if (report.overall.warnings.length > 0) {
  console.log('⚠️ Warnings:');
  report.overall.warnings.forEach(warning => {
    console.log(`${warning.field}: ${warning.message}`);
    if (warning.suggestion) {
      console.log(`  Suggestion: ${warning.suggestion}`);
    }
  });
}
```

## 🏗️ Advanced Usage

### Custom Validation Configuration

```typescript
import { SAILValidator, SAILConfig } from '@loic.farge/sail-core';

const config: SAILConfig = {
  strictMode: true,
  allowedIntents: ['process_data', 'send_notification', 'request_approval'],
  requiredFields: ['sender', 'recipient', 'intent', 'payload'],
  timezone: 'UTC'
};

const validator = new SAILValidator(config);
```

### Message Lifecycle Management

```typescript
import { SAILTransformUtils } from '@loic.farge/sail-core';

// Track message through its lifecycle
let message = createSAILMessage({...});

// When message is received
message = SAILTransformUtils.updateStatus(message, 'acknowledged');

// During processing
message = SAILTransformUtils.updateStatus(message, 'executing');

// When complete
message = SAILTransformUtils.updateStatus(message, 'executed');

// Get human-readable summary
console.log(SAILTransformUtils.getSummary(message));
// "service-a@domain.com → service-b@domain.com: process_data (executed)"
```

### Thread Management

```typescript
import { SAILThreadUtils } from '@loic.farge/sail-core';

// Create main conversation thread
const mainThread = SAILThreadUtils.generateThreadId("project_alpha");

// Create sub-conversations
const designThread = SAILThreadUtils.generateHierarchicalId(mainThread, "design");
const devThread = SAILThreadUtils.generateHierarchicalId(mainThread, "development");
const testThread = SAILThreadUtils.generateHierarchicalId(mainThread, "testing");

// Use in messages
const designMessage = createSAILMessage({
  sender: "designer@company.com",
  recipient: "team@company.com",
  intent: "share_mockups",
  payload: { designs: ["login.fig", "dashboard.fig"] },
  thread: designThread,
  responseRequired: true
});
```

## 🧪 Testing

```bash
npm test                 # Run tests
npm run test:coverage    # Run with coverage
```

## 📄 License

**Code License**: MIT License

```
MIT License

Copyright (c) 2025 Loic Farge & The SAIL Initiative Contributors

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
```

**Specification License**: The SAIL specification document is licensed under Creative Commons Attribution 4.0 International License (CC BY 4.0).

## 🤝 Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Commit your changes (`git commit -m 'Add some amazing feature'`) 
4. Push to the branch (`git push origin feature/amazing-feature`)
5. Open a Pull Request

## Documentation

- **[SAIL Framework Specification](./docs/SAIL_Framework_Proposal_PRO_Cover.pdf)** - Complete specification document (PDF)
- **API Reference** - See sections above for detailed API documentation
- **Examples** - Usage examples throughout this README demonstrate real-world applications