npm package: @oratio-ch/engine
Description: TypeScript SDK for Oratio Engine - Conversational workflow orchestration
Author: Oratio Team
Latest version: 2.2.0

# Oratio Engine SDK v2.0

> **Professional conversational AI workflow orchestration with TypeScript and tslog integration**

[![npm version](https://img.shields.io/npm/v/@oratio-ch/engine.svg)](https://www.npmjs.com/package/@oratio-ch/engine)
[![TypeScript](https://img.shields.io/badge/TypeScript-5.0-blue.svg)](https://www.typescriptlang.org/)
[![Jest](https://img.shields.io/badge/Tests-Jest-green.svg)](https://jestjs.io/)
[![Coverage](https://img.shields.io/badge/Coverage-85.59%25-brightgreen.svg)](./packages/oratio-engine/coverage)

## 🚀 Quick Start

### Installation

```bash
npm install @oratio-ch/engine tslog
```

### Basic Usage

```typescript
import { OratioEngine } from '@oratio-ch/engine';
import { Logger } from 'tslog';
import fs from 'fs';

// Professional logging setup
const log = new Logger({
  name: "MyApp",
  minLevel: "info"
});

// API Mode
const engine = new OratioEngine({
  apiKey: process.env.ORATIO_API_KEY,
  apiEndpoint: 'https://api.oratio.dev',
  logger: log
});

// Standalone Mode  
const engine = new OratioEngine({
  workflowYaml: fs.readFileSync('./workflows/booking.yaml', 'utf-8'),
  logger: log
});

// Register tools
engine.registerTools([
  {
    name: 'checkAvailability',
    handler: async (params, context) => {
      log.info('Checking availability', { params });
      return { available: true, slot: '14h00' };
    }
  }
]);

// Start conversation
await engine.startConversation();

// Send messages and get typed responses
const response = await engine.sendMessage("I need an appointment");
console.log(response.reply);
console.log(response.toolCalls); // Array of executed tools
```

## 🔧 Features

### ✅ **Dual Mode Operation**
- **API Mode**: Connect to Oratio Engine SaaS platform
- **Standalone Mode**: Run workflows locally with OpenAI integration

### ✅ **Professional Logging**  
- **tslog integration** with configurable levels (info, warn, error, debug)
- **JSON-friendly** output for production analytics
- **Structured logging** with timestamps and metadata

### ✅ **Typed Responses**
```typescript
interface EngineResponse {
  reply: string;                    // Human-readable response  
  nextStep?: string;               // Next workflow step
  context: ConversationState;      // Updated conversation state
  toolCalls: Array<{              // Executed tools with results
    name: string;
    params: any;
    result: any;
    duration?: number;
  }>;
  humanized?: boolean;             // If response was humanized
  debug?: {                        // Debug information
    stepName: string;
    executionTime: number;
    variablesUsed: string[];
  };
}
```

### ✅ **External YAML Workflows**
Keep your code clean by externalizing workflow definitions:

```typescript
// Clean separation of concerns
const workflowYaml = fs.readFileSync('./workflows/booking.yaml', 'utf-8');

const engine = new OratioEngine({
  workflowYaml,
  logger: customLogger
});
```

### ✅ **SaaS-Ready API**
Prepare for multi-tenant usage:

```typescript
// Load specific workflows by ID
await engine.useWorkflow('booking-salon-v1');
await engine.useWorkflow('booking-restaurant-v2');
```

### ✅ **Tool Registry System**
Dynamic tool registration with performance metrics:

```typescript
engine.registerTools([
  {
    name: 'bookAppointment',
    handler: async (params, context) => {
      // Your business logic
      return { confirmed: true, id: 'BK123' };
    },
    description: 'Books an appointment'
  }
]);
```

## 📖 Usage Examples

### CLI Interactive Mode

```bash
# API mode with interactive chat
node example.js --chat

# Standalone mode with debug logging
node example.js --standalone --debug --chat

# Demo mode for testing
node example.js --demo --standalone
```

### Custom Logger Configuration

```typescript
import { Logger } from 'tslog';

const log = new Logger({
  name: "SalonBooking",
  minLevel: process.env.NODE_ENV === 'production' ? "info" : "debug",
  hideLogPositionForProduction: true,
  prettyLogTemplate: "{{yyyy}}.{{mm}}.{{dd}} {{hh}}:{{MM}}:{{ss}} {{logLevelName}} [{{name}}] "
});

const engine = new OratioEngine({
  apiKey: process.env.ORATIO_API_KEY,
  logger: log
});

// Structured logging throughout the workflow
log.info("Booking initiated", { userId: 123, service: "haircut" });
log.debug("Step executed", { step: "detect_intent", duration: 245 });
log.warn("Tool handler missing", { tool: "checkAvailability" });
log.error("Workflow error", { error: "OpenAI API timeout" });
```

### Error Handling

```typescript
try {
  const response = await engine.sendMessage(userInput);
  
  // Handle successful response
  log.info('Message processed', {
    reply: response.reply,
    toolsUsed: response.toolCalls.length,
    nextStep: response.nextStep
  });
  
} catch (error) {
  if (error.code === 'OPENAI_ERROR') {
    log.error('OpenAI service unavailable', error);
  } else if (error.code === 'WORKFLOW_NOT_LOADED') {
    log.error('Configuration error', error);
  } else {
    log.error('Unexpected error', error);
  }
}
```

## 🧪 Testing

Comprehensive Jest test suite with 85.59% coverage:

```bash
# Run all tests
npm run test

# Watch mode for development  
npm run test:watch

# Coverage report
npm run test:coverage

# CI-friendly testing
npm run test:ci
```

## 📁 Project Structure

```
sdk/
├── packages/oratio-engine/     # Core SDK package
│   ├── src/
│   │   ├── OratioEngine.ts     # Main engine class
│   │   ├── ToolRegistry.ts     # Tool management
│   │   ├── types.ts            # TypeScript interfaces
│   │   └── utils.ts            # Utility functions
│   ├── tests/                  # Comprehensive test suite
│   └── package.json
├── workflows/                  # External YAML workflows
│   └── basic.yaml             # Basic booking workflow
├── examples/                   # Usage examples
│   └── salon-booking/
│       ├── simple-example-v3.ts # Complete example with tslog
│       └── tools/             # Tool implementations
└── README.md
```

## 🔑 Configuration Options

```typescript
interface OratioEngineConfig {
  // API Mode
  apiKey?: string;               // Oratio Engine API key
  apiEndpoint?: string;          // API endpoint URL
  
  // Standalone Mode  
  workflowYaml?: string;         // YAML workflow content
  
  // Common Options
  timeout?: number;              // Request timeout (ms)
  debug?: boolean;               // Enable debug mode
  silent?: boolean;              // Silent mode (no console output)
  logger?: Logger;               // Custom tslog logger instance
}
```

## 🚀 Deployment

### Production Setup

```typescript
import { Logger } from 'tslog';

const productionLogger = new Logger({
  name: "OratioEngine",
  minLevel: "info",
  hideLogPositionForProduction: true,
  type: "json"  // JSON output for log aggregation
});

const engine = new OratioEngine({
  apiKey: process.env.ORATIO_API_KEY,
  apiEndpoint: process.env.ORATIO_ENDPOINT || 'https://api.oratio.dev',
  timeout: 30000,
  logger: productionLogger
});
```

### Environment Variables

```bash
# Required for API mode
ORATIO_API_KEY=your-api-key-here

# Required for standalone mode  
OPENAI_API_KEY=your-openai-key-here

# Optional
ORATIO_ENDPOINT=https://api.oratio.dev
NODE_ENV=production
```

## 📚 Documentation

- [**API Reference**](./docs/api-reference.md) - Complete API documentation
- [**YAML Workflow Specification**](./docs/yaml-spec.md) - Workflow format guide  
- [**Tool Development Guide**](./docs/tools.md) - Building custom tools
- [**Examples Repository**](./examples/) - Real-world usage examples

## 🤝 Contributing

1. Fork the repository
2. Create your feature branch (`git checkout -b feature/amazing-feature`)
3. Run tests (`npm run test`)
4. Commit your changes (`git commit -m 'Add amazing feature'`)
5. Push to the branch (`git push origin feature/amazing-feature`)
6. Open a Pull Request

## 📄 License

MIT License - see [LICENSE](LICENSE) file for details.

## 🆘 Support

- **GitHub Issues**: [Report bugs and request features](https://github.com/oratio-ai/sdk/issues)
- **Documentation**: [Complete guides and API reference](./docs/)
- **Discord**: [Join our developer community](https://discord.gg/oratio-ai)

---

**Built with ❤️ by the Oratio AI team**