# @lemma/crewai

CrewAI integration for Lemma agent orchestration hub.

## Installation

```bash
npm install @lemma/crewai
```

## Quick Start

```typescript
import { LemmaCrewAgent } from '@lemma/crewai';

// Create an agent connected to Lemma
const agent = new LemmaCrewAgent({
  routerUrl: 'ws://localhost:8080',
  agentId: 'research-agent',
  role: 'Researcher',
  goal: 'Find and analyze information',
  backstory: 'Expert researcher with deep analytical skills',
  capabilities: ['research', 'analysis', 'web-search'],
});

// Connect to the hub
await agent.connect();

// Execute a task
const result = await agent.execute({
  description: 'Research the latest trends in AI',
  expectedOutput: 'A comprehensive report on AI trends',
});

console.log(result);

// Disconnect when done
agent.disconnect();
```

## Features

- **Semantic Caching**: Automatic caching of similar tasks
- **Agent Collaboration**: Discover and delegate to other agents
- **Task Routing**: Receive tasks from the orchestration hub
- **Real-time Monitoring**: Track performance through Lemma dashboard
- **CrewAI Compatible**: Works with existing CrewAI patterns

## Configuration

```typescript
interface LemmaCrewConfig {
  routerUrl: string;        // WebSocket URL of Lemma router
  agentId: string;          // Unique agent identifier
  role: string;             // Agent role (CrewAI concept)
  goal: string;             // Agent goal
  backstory?: string;       // Agent backstory
  capabilities?: string[];  // Agent capabilities
  verbose?: boolean;        // Enable verbose logging
  allowDelegation?: boolean; // Allow task delegation
}
```

## Advanced Usage

### Multi-Agent Crew

```typescript
import { EngramCrew } from '@engram/crewai';

const crew = new EngramCrew({
  routerUrl: 'ws://localhost:8080',
  agents: [
    {
      agentId: 'researcher',
      role: 'Researcher',
      goal: 'Research information',
      capabilities: ['research', 'web-search'],
    },
    {
      agentId: 'writer',
      role: 'Writer',
      goal: 'Write compelling content',
      capabilities: ['writing', 'editing'],
    },
    {
      agentId: 'reviewer',
      role: 'Reviewer',
      goal: 'Review and improve content',
      capabilities: ['review', 'quality-assurance'],
    },
  ],
});

await crew.connect();

// Execute a multi-step workflow
const result = await crew.kickoff({
  task: 'Create a blog post about quantum computing',
  process: 'sequential', // or 'hierarchical'
});

console.log(result);
```

### Task Delegation

```typescript
const agent = new EngramCrewAgent({
  routerUrl: 'ws://localhost:8080',
  agentId: 'manager-agent',
  role: 'Manager',
  goal: 'Coordinate team tasks',
  allowDelegation: true,
  capabilities: ['management', 'coordination'],
});

await agent.connect();

// Agent can delegate subtasks to other agents
const result = await agent.execute({
  description: 'Create a marketing campaign',
  allowDelegation: true,
});
```

## Benefits

1. **60-80% Cost Reduction**: Semantic caching eliminates redundant LLM calls
2. **Sub-50ms Responses**: Cached results return instantly
3. **Agent Discovery**: Automatically find capable agents for tasks
4. **Centralized Monitoring**: Real-time visibility through dashboard
5. **Fault Tolerance**: Auto-reconnection and error handling

## Examples

### Research Agent

```typescript
const researcher = new EngramCrewAgent({
  routerUrl: 'ws://localhost:8080',
  agentId: 'researcher-001',
  role: 'Senior Researcher',
  goal: 'Conduct thorough research on any topic',
  backstory: 'PhD in Computer Science with 10 years of research experience',
  capabilities: ['research', 'analysis', 'fact-checking'],
});

await researcher.connect();

const findings = await researcher.execute({
  description: 'Research the impact of AI on healthcare',
  expectedOutput: 'Detailed research report with citations',
});
```

### Code Review Agent

```typescript
const reviewer = new EngramCrewAgent({
  routerUrl: 'ws://localhost:8080',
  agentId: 'code-reviewer',
  role: 'Senior Code Reviewer',
  goal: 'Review code for quality and security',
  capabilities: ['code-review', 'security-audit', 'best-practices'],
});

await reviewer.connect();

const review = await reviewer.execute({
  description: 'Review this TypeScript code for issues',
  context: { code: '...' },
});
```

## Verifiable Memory for CrewAI (memory that doesn't rot)

Separate from `LemmaCrewAgent` above (the WebSocket orchestration router) —
this is a CrewAI-style tool backed by Lemma's `/v2` Verifiable Memory API:

```typescript
import { LemmaMemoryTool } from '@lemma/crewai';

const memoryTool = new LemmaMemoryTool({ apiKey: process.env.LEMMA_API_KEY! });

// wire memoryTool into your crew's tools the way you wire any other tool —
// agents call memoryTool.func({ action: 'recall', query, filePaths })

const result = await memoryTool.func({ action: 'recall', query: 'how does auth work?', filePaths: ['src/auth/login.ts'] });
if (result.state === 'stale') {
  // re-verify before trusting it — result.staleFiles names what changed
}
```

`func()` never collapses the result to a string: a `'recall'` call returns
`{ state, staleFiles, results }`. See
[`examples/memory-tool-demo.ts`](./examples/memory-tool-demo.ts) for a full
runnable example (stores a memory, edits the file it depends on, shows the
tool call receive `'stale'`).

## License

MIT
