Advanced ExamplesEnterprise Patterns

Advanced Agent-Pass Implementation

Master complex Agent-Pass scenarios including multi-agent workflows, enterprise constraints, custom verification logic, and production-ready deployment patterns.

Multi-Agent

Coordinate multiple AI agents with hierarchical permissions and delegation

Enterprise

Production patterns with databases, caching, and monitoring integration

Custom Logic

Build custom verification logic and constraint evaluation systems

Federation

Cross-domain agent authentication and distributed credential management

Advanced Implementation Patterns

multi-agent-cms.ts
/**
 * Multi-Agent Content Management System
 * 
 * Demonstrates Agent-Pass coordination between multiple AI agents:
 * - Content Writer Agent (creates/edits content)
 * - SEO Optimizer Agent (optimizes metadata)
 * - Social Media Agent (posts to platforms)
 * - Analytics Agent (tracks performance)
 */

import { AgentPass } from '@agent-pass/core';

class MultiAgentCMS {
  private agentPass: AgentPass;
  private agents: Map<string, any> = new Map();

  constructor() {
    this.agentPass = new AgentPass();
  }

  async setupAgentHierarchy(organizationController: any) {
    console.log('🏒 Setting up multi-agent CMS hierarchy...');

    // Create specialized agents
    const contentWriter = await this.agentPass.createAgentIdentity({
      alias: 'content-writer-ai',
      keyType: 'Ed25519'
    });

    const seoOptimizer = await this.agentPass.createAgentIdentity({
      alias: 'seo-optimizer-ai',
      keyType: 'Ed25519'
    });

    const socialAgent = await this.agentPass.createAgentIdentity({
      alias: 'social-media-ai',
      keyType: 'Ed25519'
    });

    // Issue hierarchical credentials
    const writerCredential = await this.agentPass.createAgentCapabilityCredential(
      organizationController,
      contentWriter,
      {
        scope: ['write:articles', 'edit:drafts', 'read:templates'],
        constraints: {
          contentTypes: ['blog', 'article', 'documentation'],
          maxPostsPerDay: 10,
          requiresApproval: false,
          timeWindow: { start: '09:00', end: '17:00' }
        },
        expirationDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
      }
    );

    const seoCredential = await this.agentPass.createAgentCapabilityCredential(
      organizationController,
      seoOptimizer,
      {
        scope: ['read:content', 'write:metadata', 'analyze:keywords'],
        constraints: {
          contentTypes: ['blog', 'article', 'product'],
          maxOptimizationsPerDay: 50,
          requiresApproval: false
        },
        expirationDate: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
      }
    );

    // Store agents and credentials
    this.agents.set('writer', { agent: contentWriter, credential: writerCredential });
    this.agents.set('seo', { agent: seoOptimizer, credential: seoCredential });

    console.log('βœ… Multi-agent hierarchy established');
    return { contentWriter, seoOptimizer, socialAgent };
  }

  async executeCoordinatedWorkflow(content: string, organizationController: any) {
    console.log('πŸ”„ Starting coordinated multi-agent workflow...');

    try {
      // Step 1: Content Writer creates article
      const writerAuth = await this.authenticateAgent('writer', organizationController);
      const article = await this.createContent(content, writerAuth);

      // Step 2: SEO Optimizer enhances metadata
      const seoAuth = await this.authenticateAgent('seo', organizationController);
      const optimizedArticle = await this.optimizeSEO(article, seoAuth);

      console.log('βœ… Multi-agent workflow completed successfully');
      return optimizedArticle;

    } catch (error) {
      console.error(`❌ Workflow failed: ${error.message}`);
      throw error;
    }
  }

  async authenticateAgent(agentType: string, controller: any) {
    const agentData = this.agents.get(agentType);
    if (!agentData) throw new Error(`Agent ${agentType} not found`);

    const challenge = await this.agentPass.createChallenge({
      domain: 'cms.company.com'
    });

    const presentation = await this.agentPass.createPresentation(
      agentData.agent,
      controller,
      [agentData.credential],
      challenge
    );

    const verification = await this.agentPass.verifyPresentation(
      presentation,
      challenge,
      {
        domain: 'cms.company.com',
        enforceConstraints: true
      }
    );

    if (!verification.verified) {
      throw new Error(`${agentType} authentication failed`);
    }

    return verification;
  }

  async createContent(content: string, auth: any) {
    if (!await this.agentPass.hasScope(auth, 'write:articles')) {
      throw new Error('Insufficient permissions for content creation');
    }

    console.log('πŸ“ Content Writer: Creating article...');
    const article = {
      id: Math.random().toString(36).substr(2, 9),
      content,
      title: content.substring(0, 50) + '...',
      status: 'draft',
      createdBy: auth.agentDid,
      timestamp: new Date().toISOString()
    };

    console.log(`βœ… Article created: ${article.id}`);
    return article;
  }

  async optimizeSEO(article: any, auth: any) {
    if (!await this.agentPass.hasScope(auth, 'write:metadata')) {
      throw new Error('Insufficient permissions for SEO optimization');
    }

    console.log('πŸ” SEO Optimizer: Enhancing metadata...');
    article.seo = {
      metaTitle: article.title + ' | Company Blog',
      metaDescription: article.content.substring(0, 160),
      keywords: ['ai', 'agent-pass', 'authentication'],
      optimizedBy: auth.agentDid
    };

    console.log('βœ… SEO optimization completed');
    return article;
  }
}

// Demo Usage
async function demonstrateMultiAgentCMS() {
  const cms = new MultiAgentCMS();
  const agentPass = new AgentPass();

  // Create organization controller
  const orgController = await agentPass.createControllerIdentity({
    alias: 'cms-organization',
    keyType: 'Ed25519'
  });

  // Setup and execute workflow
  await cms.setupAgentHierarchy(orgController);
  const content = 'Guide to implementing secure AI agent authentication...';
  await cms.executeCoordinatedWorkflow(content, orgController);
}

demonstrateMultiAgentCMS();

Production Best Practices

Security Best Practices
Rotate Credentials Regularly

Implement automatic credential rotation and expiration policies

Monitor All Actions

Log every agent action with full context and user attribution

Use Principle of Least Privilege

Grant minimal necessary permissions and review regularly

Performance Best Practices
Cache Verification Results

Use Redis for recent verifications to improve performance

Optimize Database Queries

Index audit logs and credential tables for fast lookups

Async Processing

Handle audit logging and notifications asynchronously

Implementation Roadmap

Ready to implement these advanced patterns? Follow this roadmap for production deployment:

1Start Simple

Begin with basic authentication flows and gradually add complexity

2Add Persistence

Implement database storage and caching for production scalability

3Custom Logic

Build domain-specific verification and compliance systems

4Scale & Federate

Deploy federation for multi-organization agent coordination