npm package: @mdp-framework/agents
Description: Multi-agent orchestration framework for MDP
Author: MDP Framework Contributors
Latest version: 1.1.99

# @mdp-framework/agents

Multi-agent orchestration framework for MDP (Modular Development Process).

**Status**: Phase 1 Complete (Architecture + Base Classes)
**Stream**: 5a - Multi-Agent Architecture
**Contract**: See [STREAM-5-MULTI-AGENT.md](/Docs/contracts/STREAM-5-MULTI-AGENT.md)

## Overview

This package implements a multi-agent orchestration framework enabling PM → Architect → Engineer → Designer workflows. Agents coordinate via the blackboard pattern, make decisions captured in StateCapsules, and handoff context between stages.

## Features

- **Agent Base Class**: Abstract base class for implementing custom agents
- **Blackboard Pattern**: Shared state coordination for multi-agent systems
- **Workflow Orchestration**: Sequential workflow execution with handoffs
- **Handoff Protocol**: Structured agent-to-agent context transfer
- **Type Safety**: Full TypeScript support with frozen contracts

## Installation

```bash
npm install @mdp-framework/agents
```

## Quick Start

```typescript
import {
  BaseAgent,
  SequentialAgentWorkflow,
  type AgentResult,
  type StateCapsule,
} from '@mdp-framework/agents';

// 1. Define a custom agent
class PMAgent extends BaseAgent {
  constructor() {
    super('product-manager', 'pm');
  }

  protected async executeImpl(capsule: StateCapsule): Promise<Omit<AgentResult, 'agent' | 'execution_time_ms'>> {
    // Analyze requirements
    return {
      decisions: [
        {
          question: 'What is the feature scope?',
          answer: 'Medium complexity feature',
          reasoning: 'Based on requirements analysis',
          confidence: 0.85,
        },
      ],
      artifacts: [
        {
          uri: 'artifact://pm/requirements.md',
          type: 'document',
          description: 'Requirements document',
        },
      ],
      can_handoff: true,
      next_agent: 'architect',
    };
  }

  protected getNextAgentRole(): string | null {
    return 'architect';
  }
}

// 2. Create workflow
const workflow = new SequentialAgentWorkflow();

// 3. Add agents
const pmAgent = new PMAgent();
const architectAgent = new ArchitectAgent();
const engineerAgent = new EngineerAgent();

workflow.addAgent(pmAgent);
workflow.addAgent(architectAgent);
workflow.addAgent(engineerAgent);

// 4. Execute workflow
const capsule: StateCapsule = {
  id: 'capsule://proj/team/feature/auth-123',
  kind: 'feature',
  version: 1,
  created_at: new Date().toISOString(),
  decisions: [],
  evidence: [],
  policy_ids: [],
  metadata: {},
};

const result = await workflow.execute(capsule);

console.log('Workflow status:', result.status);
console.log('Agents invoked:', result.agents_invoked);
console.log('Total decisions:', result.final_decisions.length);
console.log('Handoffs:', result.handoffs.length);
```

## Core Concepts

### Agent

An agent is an autonomous unit that:
- Executes logic based on a StateCapsule
- Makes decisions and produces artifacts
- Can hand off to the next agent in the workflow

**Interface (FROZEN)**:
```typescript
interface Agent {
  readonly name: string;
  readonly role: 'pm' | 'architect' | 'engineer' | 'designer';
  execute(capsule: StateCapsule): Promise<AgentResult>;
  canHandoffTo(agent: Agent): boolean;
  prepareHandoff(capsule: StateCapsule, result: AgentResult): Promise<AgentHandoff>;
}
```

### Blackboard

Shared state coordination mechanism where agents:
- Write decisions and artifacts
- Read context from previous agents
- Maintain isolation (agents don't see their own data in context)

```typescript
import { InMemoryBlackboard } from '@mdp-framework/agents';

const blackboard = new InMemoryBlackboard();

// Write decision
blackboard.writeDecision('pm-agent', {
  question: 'What is the scope?',
  answer: 'Medium',
  confidence: 0.8,
});

// Read all decisions
const decisions = blackboard.readDecisions();

// Get context for agent
const context = blackboard.getContextFor(agent);
```

### Workflow

Orchestrates sequential agent execution with:
- Automatic handoffs between agents
- Error handling and retry logic
- Timeout management
- Status tracking

```typescript
import { SequentialAgentWorkflow, type WorkflowConfig } from '@mdp-framework/agents';

const config: WorkflowConfig = {
  maxAgentTimeoutMs: 60_000,    // 60s per agent
  maxWorkflowTimeoutMs: 300_000, // 5 min total
  continueOnError: false,
  maxRetries: 1,
};

const workflow = new SequentialAgentWorkflow(config);
```

## API Reference

### BaseAgent

```typescript
abstract class BaseAgent implements Agent {
  constructor(name: string, role: 'pm' | 'architect' | 'engineer' | 'designer');

  // Implement these methods:
  protected abstract executeImpl(capsule: StateCapsule): Promise<Omit<AgentResult, 'agent' | 'execution_time_ms'>>;
  protected abstract getNextAgentRole(): string | null;
}
```

### SequentialAgentWorkflow

```typescript
class SequentialAgentWorkflow implements AgentWorkflow {
  constructor(config?: WorkflowConfig);

  addAgent(agent: Agent, position?: number): void;
  removeAgent(agentName: string): void;
  execute(capsule: StateCapsule, agents?: Agent[]): Promise<WorkflowResult>;
  getStatus(): WorkflowStatus;
  reset(): void;
}
```

### InMemoryBlackboard

```typescript
class InMemoryBlackboard implements Blackboard {
  writeDecision(agent: string, decision: Decision): void;
  readDecisions(): Decision[];
  getDecisionsByAgent(agentName: string): Decision[];

  writeArtifact(agent: string, artifact: Artifact): void;
  readArtifacts(): Artifact[];
  getArtifactsByAgent(agentName: string): Artifact[];

  getContextFor(agent: Agent): string;
  getStats(): { totalDecisions: number; totalArtifacts: number; agentCounts: Record<string, any> };
  clear(): void;
}
```

### HandoffManager

```typescript
class HandoffManager {
  constructor(blackboard: Blackboard);

  executeHandoff(
    fromAgent: Agent,
    toAgent: Agent,
    capsule: StateCapsule,
    result: AgentResult
  ): Promise<AgentHandoff>;

  getHandoffs(): AgentHandoff[];
  getHandoffsForAgent(agentName: string): AgentHandoff[];
  getHandoffChain(): string[];
}
```

## Architecture

```
┌─────────────────┐
│  Workflow       │
│  Orchestrator   │
└────────┬────────┘
         │
    ┌────┴────┐
    │         │
    ▼         ▼
┌────────┐ ┌────────┐
│ Agent  │→│ Agent  │
│  (PM)  │ │(Arch)  │
└───┬────┘ └───┬────┘
    │          │
    └──┬───┬───┘
       │   │
       ▼   ▼
  ┌──────────────┐
  │  Blackboard  │
  │ (Shared State)
  └──────────────┘
```

## Testing

```bash
# Run all tests
npm test

# Run tests in watch mode
npm run test:watch

# Run with coverage
npm test -- --coverage
```

## Phase 1 Deliverables (COMPLETE)

- ✅ Agent base class with execute/handoff methods
- ✅ AgentWorkflow orchestrator (SequentialAgentWorkflow)
- ✅ Blackboard shared state implementation
- ✅ Handoff protocol (prepare → receive)
- ✅ Comprehensive unit tests (53 tests passing)
- ✅ Integration tests for full workflows

## Future Phases

**Phase 2 (Weeks 4-5)**: Reference Agents
- PM Agent with prompts and schemas
- Architect Agent with MCP policy integration

**Phase 3 (Weeks 6-7)**: Engineer + Designer + Golden Tests
- Engineer and Designer agents
- Golden test suite (PM → Arch → Eng)
- Full MCP Server integration

## Contract Compliance

All FROZEN interfaces from [STREAM-5-MULTI-AGENT.md](/Docs/contracts/STREAM-5-MULTI-AGENT.md) are implemented:

- ✅ `Agent` interface
- ✅ `AgentWorkflow` interface
- ✅ `Blackboard` interface
- ✅ `AgentHandoff` schema
- ✅ `WorkflowResult` schema
- ✅ `AgentResult` type

## Dependencies

- `@mdp-framework/schemas` - Type definitions and validation
- `@mdp-framework/ai-services` - AI provider abstraction (for future agent implementations)

## Integration Points

**Provides to**:
- CLI: Workflow execution commands (`mlang workflow run`)
- Gateway: Orchestration layer for multi-agent workflows

**Depends on**:
- Stream 1 (AI Services): AIProvider for LLM completions
- Stream 3 (MCP Server): Policy queries (TODO - will use stubs initially)

## License

MIT

## Contributing

See [CONTRIBUTING.md](/CONTRIBUTING.md) for development guidelines.

---

**TODO-STREAM-5A**: Phase 1 complete - architecture and base classes implemented with full test coverage.