Eve library

Complete AI Service API Reference

Guide

Revision 1

On this page

Version: 0.1.0 Consolidated API documentation for all features

Generated: 2025-10-03T08:54:16.166Z


Content Templates#

Auto-generated API documentation

Last Updated: 2025-10-03


API Reference#

API Types#

Interfaces#

ContentTemplate#

Content Templates Module Lecture and meditation templates with self-assessment capabilities

typescript
export type TemplateType = 'lecture' | 'meditation' | 'practice' | 'reflection';
export type DifficultyLevel =
  | 'beginner'
  | 'intermediate'
  | 'advanced'
  | 'expert';
export type ChecklistItemStatus =
  | 'pending'
  | 'in-progress'
  | 'completed'
  | 'skipped';
export type RatingScale = 1 | 2 | 3 | 4 | 5;

/**
 * Template metadata and structure
 */
export interface ContentTemplate {
  id: string;
  type: TemplateType;
  title: string;
  description: string;
  tradition?: string;
  difficulty: DifficultyLevel;
  duration: number; // in minutes
  tags: string[];
  sections: TemplateSection[];
  checklist?: ChecklistItem[];
  ratingCriteria?: RatingCriterion[];
  createdAt: Date;
  updatedAt: Date;
  version: string;
}

TemplateSection#

Template section (introduction, main content, conclusion, etc.)

typescript
export interface TemplateSection {
  id: string;
  title: string;
  content: string;
  type:
    | 'text'
    | 'audio_cue'
    | 'visual_cue'
    | 'instruction'
    | 'reflection_prompt';
  duration?: number; // section duration in seconds
  order: number;
  metadata?: Record<string, unknown>;
}

ChecklistItem#

Self-assessment checklist item

typescript
export interface ChecklistItem {
  id: string;
  text: string;
  category: string;
  order: number;
  required: boolean;
  status: ChecklistItemStatus;
  completedAt?: Date;
  notes?: string;
}

RatingCriterion#

Self-rating criterion

typescript
export interface RatingCriterion {
  id: string;
  dimension: string; // e.g., "focus", "relaxation", "understanding"
  question: string;
  scale: {
    min: RatingScale;
    max: RatingScale;
    labels: Record<RatingScale, string>;
  };
  order: number;
}

TemplateSession#

User's session with a template

typescript
export interface TemplateSession {
  id: string;
  templateId: string;
  userId: string;
  startedAt: Date;
  completedAt?: Date;
  checklistProgress: Map<string, ChecklistItemStatus>;
  ratings: Map<string, RatingScale>;
  notes: string;
  duration: number; // actual duration in minutes
}

CreateTemplateInput#

Template creation/update input

typescript
export interface CreateTemplateInput {
  type: TemplateType;
  title: string;
  description: string;
  tradition?: string;
  difficulty: DifficultyLevel;
  duration: number;
  tags: string[];
  sections: Omit<TemplateSection, 'id'>[];
  checklist?: Omit<ChecklistItem, 'id' | 'status' | 'completedAt'>[];
  ratingCriteria?: Omit<RatingCriterion, 'id'>[];
}

TemplateSearchOptions#

Template search/filter options

typescript
export interface TemplateSearchOptions {
  type?: TemplateType;
  tradition?: string;
  difficulty?: DifficultyLevel;
  minDuration?: number;
  maxDuration?: number;
  tags?: string[];
  limit?: number;
  offset?: number;
}

Type Aliases#

TemplateType#

Content Templates Module Lecture and meditation templates with self-assessment capabilities

typescript
export type TemplateType = 'lecture' | 'meditation' | 'practice' | 'reflection';

DifficultyLevel#

typescript
export type DifficultyLevel =
  | 'beginner'
  | 'intermediate'
  | 'advanced'
  | 'expert';

ChecklistItemStatus#

typescript
export type ChecklistItemStatus =
  | 'pending'
  | 'in-progress'
  | 'completed'
  | 'skipped';

RatingScale#

typescript
export type RatingScale = 1 | 2 | 3 | 4 | 5;

Classes#

ContentTemplateRegistry#

Content Templates Module Lecture and meditation templates with self-assessment capabilities

typescript
export type TemplateType = 'lecture' | 'meditation' | 'practice' | 'reflection';
export type DifficultyLevel = 'beginner' | 'intermediate' | 'advanced' | 'expert';
export type ChecklistItemStatus = 'pending' | 'in-progress' | 'completed' | 'skipped';
export type RatingScale = 1 | 2 | 3 | 4 | 5;

/**
 * Template metadata and structure
 */
export interface ContentTemplate {
  id: string;
  type: TemplateType;
  title: string;
  description: string;
  tradition?: string;
  difficulty: DifficultyLev...

Endpoints#

Overview#

The Content Templates API provides endpoints for creating, managing, and using structured lecture and meditation templates with built-in self-assessment capabilities.

Base URL#

text
http://localhost:3007/v1/ai

Authentication#

All endpoints require authentication via Bearer token in the Authorization header.

Endpoints#

Create Template#

POST /content-templates

Creates a new content template.

Request Body:

json
{
  "type": "lecture" | "meditation" | "practice" | "reflection",
  "title": "string",
  "description": "string",
  "tradition": "string (optional)",
  "difficulty": "beginner" | "intermediate" | "advanced" | "expert",
  "duration": number,
  "tags": ["string"],
  "sections": [{
    "title": "string",
    "content": "string",
    "type": "text" | "audio_cue" | "visual_cue" | "instruction" | "reflection_prompt",
    "duration": number (optional),
    "order": number
  }],
  "checklist": [{
    "text": "string",
    "category": "string",
    "order": number,
    "required": boolean
  }] (optional),
  "ratingCriteria": [{
    "dimension": "string",
    "question": "string",
    "scale": {
      "min": 1,
      "max": 5,
      "labels": {
        "1": "string",
        "2": "string",
        "3": "string",
        "4": "string",
        "5": "string"
      }
    },
    "order": number
  }] (optional)
}

Response: 201 Created

json
{
  "id": "tpl_xyz",
  "type": "lecture",
  "title": "Introduction to Mindfulness",
  "version": "1.0.0",
  "createdAt": "2025-10-03T00:00:00Z",
  ...
}

List All Templates#

GET /content-templates

Returns all available templates.

Response: 200 OK

json
{
  "templates": [...],
  "count": number
}

Search Templates#

GET /content-templates/search?type={type}&tradition={tradition}&difficulty={difficulty}&minDuration={min}&maxDuration={max}&tags={tag1,tag2}

Search templates with filters.

Query Parameters:

  • type (optional): Template type
  • tradition (optional): Spiritual tradition
  • difficulty (optional): Difficulty level
  • minDuration (optional): Minimum duration in minutes
  • maxDuration (optional): Maximum duration in minutes
  • tags (optional): Comma-separated tags

Response: 200 OK

json
{
  "templates": [...],
  "count": number
}

Get Template#

GET /content-templates/:id

Retrieve a specific template by ID.

Response: 200 OK or 404 Not Found

Update Template#

PUT /content-templates/:id

Update an existing template. Increments version.

Request Body: Same as Create Template (partial updates supported)

Response: 200 OK or 404 Not Found

Delete Template#

DELETE /content-templates/:id

Delete a template.

Response: 204 No Content or 404 Not Found

Start Session#

POST /content-templates/:id/sessions

Start a practice session with a template.

Request Body:

json
{
  "userId": "string"
}

Response: 201 Created

json
{
  "sessionId": "ses_xyz",
  "templateId": "tpl_abc",
  "userId": "user_123",
  "startedAt": "2025-10-03T00:00:00Z"
}

Update Checklist Item#

PUT /sessions/:sessionId/checklist/:itemId

Update a checklist item status during a session.

Request Body:

json
{
  "status": "pending" | "in-progress" | "completed" | "skipped",
  "notes": "string (optional)"
}

Response: 200 OK

Add Rating#

POST /sessions/:sessionId/ratings

Submit a self-rating for a session.

Request Body:

json
{
  "criterionId": "string",
  "value": 1 | 2 | 3 | 4 | 5
}

Response: 200 OK

Complete Session#

POST /sessions/:sessionId/complete

Mark a session as completed.

Request Body:

json
{
  "notes": "string (optional)"
}

Response: 200 OK

Get User Sessions#

GET /users/:userId/sessions

Retrieve session history for a user.

Response: 200 OK

json
{
  "sessions": [...],
  "count": number
}

Data Models#

ContentTemplate#

typescript
{
  id: string;
  type: "lecture" | "meditation" | "practice" | "reflection";
  title: string;
  description: string;
  tradition?: string;
  difficulty: "beginner" | "intermediate" | "advanced" | "expert";
  duration: number; // in minutes
  tags: string[];
  sections: TemplateSection[];
  checklist?: ChecklistItem[];
  ratingCriteria?: RatingCriterion[];
  createdAt: Date;
  updatedAt: Date;
  version: string;
}

TemplateSection#

typescript
{
  id: string;
  title: string;
  content: string;
  type: "text" | "audio_cue" | "visual_cue" | "instruction" | "reflection_prompt";
  duration?: number; // in seconds
  order: number;
  metadata?: Record<string, unknown>;
}

ChecklistItem#

typescript
{
  id: string;
  text: string;
  category: string;
  order: number;
  required: boolean;
  status: "pending" | "in-progress" | "completed" | "skipped";
  completedAt?: Date;
  notes?: string;
}

RatingCriterion#

typescript
{
  id: string;
  dimension: string;
  question: string;
  scale: {
    min: 1 | 2 | 3 | 4 | 5;
    max: 1 | 2 | 3 | 4 | 5;
    labels: Record<1 | 2 | 3 | 4 | 5, string>;
  }
  order: number;
}

TemplateSession#

typescript
{
  id: string;
  templateId: string;
  userId: string;
  startedAt: Date;
  completedAt?: Date;
  checklistProgress: Map<string, ChecklistItemStatus>;
  ratings: Map<string, RatingScale>;
  notes: string;
  duration: number; // actual duration in minutes
}

Error Responses#

All endpoints return standard error responses:

400 Bad Request

json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Template title cannot be empty"
  }
}

404 Not Found

json
{
  "error": {
    "code": "NOT_FOUND",
    "message": "Template 'tpl_xyz' not found"
  }
}

500 Internal Server Error

json
{
  "error": {
    "code": "INTERNAL_ERROR",
    "message": "An unexpected error occurred"
  }
}

Examples#

Create a Meditation Template#

bash
curl -X POST http://localhost:3007/v1/ai/content-templates \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "meditation",
    "title": "Mindful Breathing Practice",
    "description": "A guided breathing meditation for beginners",
    "tradition": "Buddhist",
    "difficulty": "beginner",
    "duration": 10,
    "tags": ["breathing", "mindfulness", "beginner"],
    "sections": [
      {
        "title": "Introduction",
        "content": "Find a comfortable seated position...",
        "type": "instruction",
        "order": 1
      },
      {
        "title": "Main Practice",
        "content": "Focus on your natural breath...",
        "type": "audio_cue",
        "duration": 480,
        "order": 2
      },
      {
        "title": "Closing",
        "content": "Slowly return your awareness...",
        "type": "instruction",
        "order": 3
      }
    ],
    "checklist": [
      {
        "text": "Did you maintain focus on your breath?",
        "category": "practice",
        "order": 1,
        "required": false
      },
      {
        "text": "Did you notice when your mind wandered?",
        "category": "awareness",
        "order": 2,
        "required": false
      }
    ],
    "ratingCriteria": [
      {
        "dimension": "relaxation",
        "question": "How relaxed did you feel during the practice?",
        "scale": {
          "min": 1,
          "max": 5,
          "labels": {
            "1": "Very tense",
            "2": "Somewhat tense",
            "3": "Neutral",
            "4": "Somewhat relaxed",
            "5": "Very relaxed"
          }
        },
        "order": 1
      }
    ]
  }'

Search for Beginner Meditations#

bash
curl -X GET "http://localhost:3007/v1/ai/content-templates/search?type=meditation&difficulty=beginner" \
  -H "Authorization: Bearer YOUR_TOKEN"

Start a Practice Session#

bash
curl -X POST http://localhost:3007/v1/ai/content-templates/tpl_xyz/sessions \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "userId": "user_123"
  }'

Test Coverage#

The Content Templates feature has comprehensive test coverage:

  • Unit Tests: 41 tests (100% code coverage)
  • Integration Tests: 20 tests (all HTTP endpoints)
  • Total: 61 tests passing

Implementation#

  • Language: TypeScript with strict type safety
  • File: apps/lilith/svc-ai/src/content-templates.ts
  • Lines of Code: 356
  • Dependencies: None (in-memory storage)

Limitations#

  • Templates are stored in-memory (not persisted to database)
  • No pagination on list endpoints
  • Session data is not persisted
  • No real-time synchronization across instances

Future Enhancements#

  • Database persistence (PostgreSQL)
  • Pagination and cursor-based navigation
  • Real-time session updates via WebSocket
  • Template versioning and rollback
  • Template sharing and publishing
  • Community ratings and reviews

Implementation Status#

Implementation Status#

Current Status: 14/15 Criteria Met (93% Complete) ✅

Completion: 14/15 criteria met (93%)


Usage Ledger#

Auto-generated API documentation

Last Updated: 2025-10-03


API Reference#

API Types#

Classes#

UsageLedger#

Record usage

typescript
export class UsageLedger {
  private ledger: Map<string, UsageEntry[]> = new Map(); // user_id -> entries
  private budgetCaps: Map<string, BudgetCap> = new Map(); // cap_id -> cap
  private userBudgetCaps: Map<string, Set<string>> = new Map(); // user_id -> Set<cap_id>

  recordUsage(userId: string, tokens: number, feature?: string, persona?: string): void {
    const entry: UsageEntry = {
      timestamp: new Date(),
      tokens,
      feature,
      persona,
      request_id: crypto.randomUU...

Endpoints#

Overview#

The Usage Ledger API provides comprehensive usage tracking and budget enforcement for AI features. Track token consumption and request counts per user, feature, and persona with flexible budget caps supporting hourly, daily, weekly, and monthly periods. Includes GDPR-compliant data export capabilities.

Base URL#

text
http://localhost:3007/v1/ai

Authentication#

All endpoints require authentication via Bearer token in the Authorization header.

Endpoints#

Get User Usage#

GET /usage/:userId

Retrieve usage statistics for a specific user, optionally filtered by feature and/or persona.

Path Parameters:

  • userId (required): User ID to query

Query Parameters:

  • feature (optional): Filter by specific feature
  • persona (optional): Filter by specific persona

Response: 200 OK

Example 1: All Usage

bash
curl -X GET "http://localhost:3007/v1/ai/usage/user_123" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "total_tokens": 15000,
  "request_count": 150,
  "by_feature": {
    "chat": {
      "total_tokens": 8000,
      "request_count": 80,
      "last_used": "2025-10-03T14:30:00.000Z"
    },
    "search": {
      "total_tokens": 7000,
      "request_count": 70,
      "last_used": "2025-10-03T14:25:00.000Z"
    }
  },
  "by_persona": {
    "meditation_guide": {
      "total_tokens": 5000,
      "request_count": 50,
      "last_used": "2025-10-03T14:30:00.000Z"
    },
    "teacher": {
      "total_tokens": 10000,
      "request_count": 100,
      "last_used": "2025-10-03T14:20:00.000Z"
    }
  },
  "by_feature_persona": {
    "chat:meditation_guide": {
      "total_tokens": 3000,
      "request_count": 30,
      "last_used": "2025-10-03T14:30:00.000Z"
    },
    "search:teacher": {
      "total_tokens": 2000,
      "request_count": 20,
      "last_used": "2025-10-03T14:15:00.000Z"
    }
  }
}

Example 2: Feature-Specific Usage

bash
curl -X GET "http://localhost:3007/v1/ai/usage/user_123?feature=chat" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "total_tokens": 8000,
  "request_count": 80,
  "by_feature": {
    "chat": {
      "total_tokens": 8000,
      "request_count": 80,
      "last_used": "2025-10-03T14:30:00.000Z"
    }
  }
}

Example 3: Feature-Persona Combination

bash
curl -X GET "http://localhost:3007/v1/ai/usage/user_123?feature=chat&persona=meditation_guide" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "total_tokens": 3000,
  "request_count": 30
}

Get Usage Breakdown#

GET /usage/:userId/breakdown

Get usage breakdown grouped by feature, persona, or feature-persona combination.

Path Parameters:

  • userId (required): User ID to query

Query Parameters:

  • group_by (optional): Grouping type (feature, persona, or default for feature-persona combinations)

Response: 200 OK

Example: Group by Feature

bash
curl -X GET "http://localhost:3007/v1/ai/usage/user_123/breakdown?group_by=feature" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "breakdown": {
    "chat": {
      "total_tokens": 8000,
      "request_count": 80,
      "last_used": "2025-10-03T14:30:00.000Z"
    },
    "search": {
      "total_tokens": 7000,
      "request_count": 70,
      "last_used": "2025-10-03T14:25:00.000Z"
    }
  }
}

Example: Group by Persona

bash
curl -X GET "http://localhost:3007/v1/ai/usage/user_123/breakdown?group_by=persona" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "breakdown": {
    "meditation_guide": {
      "total_tokens": 5000,
      "request_count": 50,
      "last_used": "2025-10-03T14:30:00.000Z"
    },
    "teacher": {
      "total_tokens": 10000,
      "request_count": 100,
      "last_used": "2025-10-03T14:20:00.000Z"
    }
  }
}

Export Usage Data#

GET /usage/:userId/export

Export usage data in JSON or CSV format for GDPR compliance and data portability.

Path Parameters:

  • userId (required): User ID to export

Query Parameters:

  • format (optional): Export format (json or csv, default: json)

Response: 200 OK

Example: JSON Export

bash
curl -X GET "http://localhost:3007/v1/ai/usage/user_123/export" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "user_id": "user_123",
  "exported_at": "2025-10-03T14:35:00.000Z",
  "total_tokens": 15000,
  "request_count": 150,
  "by_feature": {
    "chat": {
      "total_tokens": 8000,
      "request_count": 80,
      "last_used": "2025-10-03T14:30:00.000Z"
    }
  },
  "by_persona": {
    "meditation_guide": {
      "total_tokens": 5000,
      "request_count": 50,
      "last_used": "2025-10-03T14:30:00.000Z"
    }
  },
  "by_feature_persona": {}
}

Example: CSV Export

bash
curl -X GET "http://localhost:3007/v1/ai/usage/user_123/export?format=csv" \
  -H "Authorization: Bearer YOUR_TOKEN"

Response: text/csv

csv
timestamp,feature,persona,tokens
2025-10-03T14:00:00.000Z,chat,meditation_guide,150
2025-10-03T14:05:00.000Z,search,teacher,200
2025-10-03T14:10:00.000Z,chat,meditation_guide,180

Create Budget Cap#

POST /budget/caps

Create a new budget cap to enforce usage limits per user, feature, and/or persona.

Request Body:

typescript
{
  user_id: string;           // Required: User ID
  feature?: string;          // Optional: Specific feature
  persona?: string;          // Optional: Specific persona
  budget_type: 'tokens' | 'requests';  // Required: Budget metric
  limit: number;             // Required: Budget limit
  period?: 'hourly' | 'daily' | 'weekly' | 'monthly';  // Optional: Reset period (default: 'daily')
  reset_time?: string;       // Optional: Custom reset time (ISO 8601)
}

Response: 201 Created

Example 1: Daily Token Budget

bash
curl -X POST http://localhost:3007/v1/ai/budget/caps \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user_123",
    "budget_type": "tokens",
    "limit": 10000,
    "period": "daily"
  }'
json
{
  "success": true,
  "cap": {
    "id": "cap_abc123",
    "user_id": "user_123",
    "budget_type": "tokens",
    "limit": 10000,
    "period": "daily",
    "reset_time": "2025-10-04T00:00:00.000Z",
    "created_at": "2025-10-03T14:35:00.000Z"
  }
}

Example 2: Feature-Specific Request Budget

bash
curl -X POST http://localhost:3007/v1/ai/budget/caps \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user_123",
    "feature": "chat",
    "budget_type": "requests",
    "limit": 100,
    "period": "hourly"
  }'
json
{
  "success": true,
  "cap": {
    "id": "cap_def456",
    "user_id": "user_123",
    "feature": "chat",
    "budget_type": "requests",
    "limit": 100,
    "period": "hourly",
    "reset_time": "2025-10-03T15:00:00.000Z",
    "created_at": "2025-10-03T14:35:00.000Z"
  }
}

Example 3: Persona-Specific Token Budget

bash
curl -X POST http://localhost:3007/v1/ai/budget/caps \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user_123",
    "persona": "meditation_guide",
    "budget_type": "tokens",
    "limit": 5000,
    "period": "weekly"
  }'
json
{
  "success": true,
  "cap": {
    "id": "cap_ghi789",
    "user_id": "user_123",
    "persona": "meditation_guide",
    "budget_type": "tokens",
    "limit": 5000,
    "period": "weekly",
    "reset_time": "2025-10-06T00:00:00.000Z",
    "created_at": "2025-10-03T14:35:00.000Z"
  }
}

Error Response: 400 Bad Request

json
{
  "error": "Missing required fields: user_id, budget_type, limit",
  "code": "validation.missing_fields"
}

List Budget Caps#

GET /budget/caps/:userId

Retrieve all budget caps for a specific user.

Path Parameters:

  • userId (required): User ID to query

Response: 200 OK

Example:

bash
curl -X GET "http://localhost:3007/v1/ai/budget/caps/user_123" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "caps": [
    {
      "id": "cap_abc123",
      "user_id": "user_123",
      "budget_type": "tokens",
      "limit": 10000,
      "period": "daily",
      "reset_time": "2025-10-04T00:00:00.000Z",
      "created_at": "2025-10-03T14:00:00.000Z"
    },
    {
      "id": "cap_def456",
      "user_id": "user_123",
      "feature": "chat",
      "budget_type": "requests",
      "limit": 100,
      "period": "hourly",
      "reset_time": "2025-10-03T15:00:00.000Z",
      "created_at": "2025-10-03T14:10:00.000Z"
    },
    {
      "id": "cap_ghi789",
      "user_id": "user_123",
      "persona": "meditation_guide",
      "budget_type": "tokens",
      "limit": 5000,
      "period": "weekly",
      "reset_time": "2025-10-06T00:00:00.000Z",
      "created_at": "2025-10-03T14:20:00.000Z"
    }
  ],
  "count": 3
}

Update Budget Cap#

PUT /budget/caps/:capId

Update an existing budget cap. All fields except id, user_id, and created_at can be updated.

Path Parameters:

  • capId (required): Budget cap ID

Request Body:

typescript
{
  limit?: number;
  period?: 'hourly' | 'daily' | 'weekly' | 'monthly';
  reset_time?: string;  // ISO 8601 format
}

Response: 200 OK

Example: Update Limit

bash
curl -X PUT http://localhost:3007/v1/ai/budget/caps/cap_abc123 \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "limit": 15000
  }'
json
{
  "success": true,
  "cap": {
    "id": "cap_abc123",
    "user_id": "user_123",
    "budget_type": "tokens",
    "limit": 15000,
    "period": "daily",
    "reset_time": "2025-10-04T00:00:00.000Z",
    "created_at": "2025-10-03T14:00:00.000Z"
  }
}

Error Response: 404 Not Found

json
{
  "error": "Budget cap not found",
  "code": "budget.not_found"
}

Delete Budget Cap#

DELETE /budget/caps/:capId

Delete a budget cap.

Path Parameters:

  • capId (required): Budget cap ID

Response: 200 OK

Example:

bash
curl -X DELETE http://localhost:3007/v1/ai/budget/caps/cap_abc123 \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "success": true,
  "message": "Budget cap deleted successfully"
}

Error Response: 404 Not Found

json
{
  "error": "Budget cap not found",
  "code": "budget.not_found"
}

Data Models#

UsageEntry#

typescript
interface UsageEntry {
  timestamp: Date; // When usage occurred
  tokens: number; // Token count
  feature?: string; // Optional feature identifier
  persona?: string; // Optional persona identifier
  request_id: string; // Unique request ID (UUID)
}

BudgetCap#

typescript
interface BudgetCap {
  id: string; // Unique cap ID (UUID)
  user_id: string; // User ID
  feature?: string; // Optional feature filter
  persona?: string; // Optional persona filter
  budget_type: 'tokens' | 'requests'; // Budget metric
  limit: number; // Budget limit
  period: 'hourly' | 'daily' | 'weekly' | 'monthly'; // Reset period
  reset_time: Date; // Next reset time
  created_at: Date; // Creation timestamp
}

UsageResponse#

typescript
interface UsageResponse {
  total_tokens: number;
  request_count: number;
  by_feature?: Record<string, FeatureUsage>;
  by_persona?: Record<string, PersonaUsage>;
  by_feature_persona?: Record<string, CombinedUsage>;
}

interface FeatureUsage {
  total_tokens: number;
  request_count: number;
  last_used: Date;
}

interface PersonaUsage {
  total_tokens: number;
  request_count: number;
  last_used: Date;
}

interface CombinedUsage {
  total_tokens: number;
  request_count: number;
  last_used: Date;
}

Budget Enforcement#

Pre-Emptive Budget Checking#

The Usage Ledger uses pre-emptive budget checking to prevent budget overruns:

javascript
// Before recording usage, check if it would exceed budget
const budgetCheck = await checkBudget(userId, proposedTokens, feature, persona);

if (!budgetCheck.allowed) {
  throw new Error('Budget exceeded: ' + budgetCheck.exceeded_caps);
}

// Only record usage if budget allows
recordUsage(userId, tokens, feature, persona);

Budget Period Mechanics#

Reset Times: Each budget cap has a reset_time field representing when the current period ends:

  • Hourly: Resets at the top of the next hour (e.g., 15:00:00)
  • Daily: Resets at midnight (00:00:00) of the next day
  • Weekly: Resets at midnight on Sunday
  • Monthly: Resets at midnight on the 1st of the next month

Auto-Reset Logic: When checkBudget() is called:

  1. If current_time >= reset_time, the budget period has expired
  2. The system automatically calculates the next reset_time
  3. Only usage entries with timestamp >= reset_time are counted

Example Timeline:

text
Budget Created: Oct 3, 14:00 (daily period)
Reset Time:     Oct 4, 00:00

Usage at 15:00 (Oct 3): Counted toward Oct 3 period
Usage at 22:00 (Oct 3): Counted toward Oct 3 period
Usage at 02:00 (Oct 4): NOT counted (period auto-reset)
New Reset Time:         Oct 5, 00:00

Multiple Budget Caps#

Users can have multiple budget caps applied simultaneously:

javascript
// User has 3 caps:
// 1. 10,000 tokens/day (global)
// 2. 100 requests/hour for "chat" feature
// 3. 5,000 tokens/week for "meditation_guide" persona

// A request for "chat" with "meditation_guide" must satisfy ALL applicable caps
checkBudget(userId, 150, 'chat', 'meditation_guide');
// Checks: global daily cap, chat hourly cap, meditation_guide weekly cap

All applicable caps must pass for the request to be allowed.

Budget Scopes#

Budget caps can be applied at three scopes:

  1. Global (no feature/persona): Applies to all usage
  2. Feature-Specific (feature only): Applies to specific feature regardless of persona
  3. Persona-Specific (persona only): Applies to specific persona regardless of feature
  4. Combined (feature + persona): Applies only to specific feature-persona combination

Applicability Logic:

  • Global cap: Always applies
  • Feature cap: Applies if request feature matches
  • Persona cap: Applies if request persona matches
  • Combined cap: Applies if both feature AND persona match

Error Handling#

Validation Errors#

Missing Required Fields

json
{
  "error": "Missing required fields: user_id, budget_type, limit",
  "code": "validation.missing_fields"
}

Budget Exceeded#

When a budget check fails, the response includes:

typescript
{
  allowed: false,
  exceeded_caps: ['cap_abc123', 'cap_def456']
}

Application code should handle this by:

  1. Denying the request
  2. Logging the exceeded caps
  3. Notifying the user with appropriate messaging

Not Found Errors#

Budget Cap Not Found

json
{
  "error": "Budget cap not found",
  "code": "budget.not_found"
}

Usage Examples#

Complete Workflow: Create Budget & Track Usage#

bash
# 1. Create daily token budget
curl -X POST http://localhost:3007/v1/ai/budget/caps \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "user_id": "user_123",
    "budget_type": "tokens",
    "limit": 10000,
    "period": "daily"
  }'

# 2. Before recording usage, check budget (in application code)
budgetCheck = checkBudget('user_123', 150);
if (!budgetCheck.allowed) {
  throw new Error('Daily budget exceeded');
}

# 3. Record usage (in application code)
recordUsage('user_123', 150, 'chat', 'meditation_guide');

# 4. Query current usage
curl -X GET "http://localhost:3007/v1/ai/usage/user_123" \
  -H "Authorization: Bearer YOUR_TOKEN"

# 5. Export usage data for compliance
curl -X GET "http://localhost:3007/v1/ai/usage/user_123/export?format=csv" \
  -H "Authorization: Bearer YOUR_TOKEN" > usage_export.csv

Multi-Budget Strategy#

bash
# Create tiered budgets for different use cases:

# 1. Global daily limit (safety net)
curl -X POST http://localhost:3007/v1/ai/budget/caps \
  -d '{"user_id": "user_123", "budget_type": "tokens", "limit": 50000, "period": "daily"}'

# 2. Feature-specific hourly limit (rate limiting)
curl -X POST http://localhost:3007/v1/ai/budget/caps \
  -d '{"user_id": "user_123", "feature": "image_gen", "budget_type": "requests", "limit": 10, "period": "hourly"}'

# 3. Persona-specific weekly limit (cost control)
curl -X POST http://localhost:3007/v1/ai/budget/caps \
  -d '{"user_id": "user_123", "persona": "advanced_tutor", "budget_type": "tokens", "limit": 100000, "period": "weekly"}'

GDPR Compliance: Data Export & Deletion#

bash
# 1. Export user data (GDPR Article 20: Right to Data Portability)
curl -X GET "http://localhost:3007/v1/ai/usage/user_123/export?format=json" \
  -H "Authorization: Bearer YOUR_TOKEN" > user_123_data.json

# 2. Delete all budget caps (GDPR Article 17: Right to Erasure)
# Get all caps
CAPS=$(curl -X GET "http://localhost:3007/v1/ai/budget/caps/user_123" \
  -H "Authorization: Bearer YOUR_TOKEN" | jq -r '.caps[].id')

# Delete each cap
for cap in $CAPS; do
  curl -X DELETE "http://localhost:3007/v1/ai/budget/caps/$cap" \
    -H "Authorization: Bearer YOUR_TOKEN"
done

Test Coverage#

The Usage Ledger feature has comprehensive test coverage:

  • Unit Tests: 46 tests (100% code coverage)
  • Integration Tests: 32 tests (all HTTP endpoints)
  • Multi-Agent Workflow Tests: 100 tests (autonomous agent scenarios)
  • E2E Tests: 15 Playwright tests
  • Total: 193 tests passing

Multi-Agent Test Scenarios#

The 100 multi-agent workflow tests cover:

  1. Agent Usage Tracking (10 tests): Recording, querying, aggregation
  2. Agent Budget Management (10 tests): Creating, updating, deleting caps
  3. Agent Budget Enforcement (10 tests): Pre-emptive checking, multi-cap validation
  4. Multi-Agent Coordination (10 tests): Shared budgets, cross-agent enforcement
  5. Budget Period & Reset (10 tests): Hourly, daily, weekly, monthly periods
  6. Export & Reporting (10 tests): JSON/CSV export, breakdowns
  7. Performance & Scalability (10 tests): Concurrent access, large datasets
  8. Error Handling & Edge Cases (10 tests): Validation, missing data
  9. Compliance & GDPR (10 tests): Data portability, right to erasure
  10. Learning & Optimization (10 tests): Pattern analysis, recommendations

Implementation Details#

  • Language: TypeScript with strict type safety
  • File: apps/lilith/svc-ai/src/usage-ledger.ts
  • Lines of Code: 464
  • Dependencies: None (in-memory storage with crypto for UUIDs)
  • Storage: Map<string, UsageEntry[]> for ledger, Map<string, BudgetCap> for caps

Performance Characteristics#

  • Usage Recording: O(1) insertion
  • Usage Query: O(n) where n = number of entries for user
  • Budget Check: O(m × n) where m = caps, n = entries since reset
  • Memory: Linear with usage history (no automatic cleanup)

Recommendations:

  • Archive old entries periodically
  • Consider pagination for large datasets
  • Add indexing for frequent queries

Limitations#

  • In-Memory Storage: Data not persisted to database (lost on restart)
  • No Pagination: All usage entries returned (could be large)
  • No Automatic Cleanup: Old entries accumulate indefinitely
  • No Real-Time Alerts: Budget exceeded detection is synchronous only
  • No Audit Trail: Budget cap changes not logged

Future Enhancements#

  • Database Persistence: PostgreSQL with time-series optimization
  • Real-Time Alerting: WebSocket notifications for budget thresholds
  • Historical Analytics: Usage trends, forecasting, anomaly detection
  • Budget Recommendations: ML-based optimal budget suggestions
  • Audit Logging: Complete change history for compliance
  • Automatic Archival: Archive entries older than 90 days
  • Budget Templates: Pre-configured caps for common use cases
  • Cost Attribution: Map token usage to actual costs

GDPR Compliance Features#

The Usage Ledger fully supports GDPR requirements:

Article 15: Right of Access

  • ✅ GET /usage/:userId - Users can access their usage data

Article 17: Right to Erasure

  • ✅ DELETE /budget/caps/:capId - Users can delete their budget caps
  • ⚠️ Note: Usage history deletion not implemented (add DELETE /usage/:userId)

Article 20: Right to Data Portability

  • ✅ GET /usage/:userId/export?format=csv - Machine-readable export
  • ✅ GET /usage/:userId/export - Structured JSON export

Article 25: Data Protection by Design

  • ✅ No PII stored in usage entries (only user_id references)
  • ✅ Minimal data collection (timestamp, tokens, feature, persona)

Generated: 2025-10-03 API Version: 1.0.0 Test Coverage: 193 tests passing Multi-Agent Tests: 100/100 passing

Code Examples#

Usage Examples#

These examples are extracted from actual test cases to ensure accuracy.

Example 1: should track usage by feature#

typescript
// Make AI request for specific feature
      const response = await app.inject({
        method: 'POST',
        url: '/v1/ai/chat',
        payload: {
          user_id: 'user-123',
          feature: 'meditation_guidance',
          messages: [
            { role: 'user', content: 'Guide me through meditation' }
          ],
          max_tokens: 100
        }

Example 2: should track usage by persona#

typescript
const response = await app.inject({
        method: 'POST',
        url: '/v1/ai/chat',
        payload: {
          user_id: 'user-123',
          persona: 'zen_master',
          messages: [
            { role: 'user', content: 'Teach me about mindfulness' }
          ]
        }

Example 3: should track combined feature and persona usage#

typescript
await app.inject({
        method: 'POST',
        url: '/v1/ai/chat',
        payload: {
          user_id: 'user-123',
          feature: 'yoga_instruction',
          persona: 'yoga_teacher',
          messages: [
            { role: 'user', content: 'Help me with yoga poses' }
          ]
        }

Example 4: should track token usage accurately#

typescript
const response = await app.inject({
        method: 'POST',
        url: '/v1/ai/chat',
        payload: {
          user_id: 'user-123',
          feature: 'test_feature',
          messages: [
            { role: 'user', content: 'Test message' }
          ]
        }

Example 5: should set feature budget cap#

typescript
const response = await app.inject({
        method: 'POST',
        url: '/v1/ai/budget/caps',
        payload: {
          user_id: 'user-123',
          feature: 'meditation_guidance',
          budget_type: 'tokens',
          limit: 1000,
          period: 'daily'
        }

Implementation Status#

Implementation Status#

Current Status: ✅ 13/15 CRITERIA MET (87% COMPLETE)

Completion: 13/15 criteria met (87%)


Tool Schemas#

Auto-generated API documentation

Last Updated: 2025-10-03


API Reference#

API Types#

Interfaces#

ToolParameter#

Tool Schemas Module Defines JSON schemas for tools available to AI agents Tools: search, KG query, calc, TTS, STT, scheduler

typescript
export interface ToolParameter {
  name: string;
  type: 'string' | 'number' | 'boolean' | 'object' | 'array';
  description: string;
  required: boolean;
  default?: any;
  enum?: any[];
  pattern?: string;
  minLength?: number;
  maxLength?: number;
  minimum?: number;
  maximum?: number;
}

ToolSchema#

typescript
export interface ToolSchema {
  name: string;
  description: string;
  category:
    | 'search'
    | 'knowledge'
    | 'computation'
    | 'speech'
    | 'scheduling'
    | 'system';
  parameters: ToolParameter[];
  returns: {
    type: string;
    description: string;
    schema?: any;
  };
  examples: Array<{
    input: Record<string, any>;
    output: any;
    description: string;
  }>;
  permissions?: string[];
  rateLimit?: {
    calls: number;
    period: 'second' | 'minute' | 'hour' | 'day';
  };
}

Classes#

ToolSchemaRegistry#

Register a tool schema

typescript
export class ToolSchemaRegistry {
  private schemas: Map<string, ToolSchema> = new Map();
  private toolsByCategory: Map<string, Set<string>> = new Map();

  constructor() {
    // Register default tools
    this.registerDefaultTools();
  }

  registerTool(schema: ToolSchema): void {
    // Validate schema
    if (!schema.name || !schema.description) {
      throw new Error('Tool schema must have name and description');
    }

    if (this.schemas.has(schema.name)) {
      throw new Error(`Tool ...

Endpoints#

Overview#

The Tool Schemas API provides endpoints for discovering, validating, and using structured schemas for AI agent tools. The system includes 6 default tools (search, kg_query, calc, tts, stt, scheduler) with comprehensive parameter validation, constraint enforcement, and OpenAPI schema export capabilities.

Base URL#

text
http://localhost:3007/v1/ai

Authentication#

All endpoints require authentication via Bearer token in the Authorization header.

Endpoints#

List All Tools#

GET /tools

Returns all available tool schemas.

Query Parameters:

  • category (optional): Filter by category (search, knowledge, computation, speech, scheduling, system)

Response: 200 OK

json
{
  "tools": [
    {
      "name": "search",
      "description": "Search the knowledge base",
      "category": "search",
      "parameters": [...],
      "returns": {...},
      "examples": [...]
    }
  ],
  "count": 6
}

Get Tool Schema#

GET /tools/:name

Retrieve a specific tool schema by name.

Response: 200 OK or 404 Not Found

json
{
  "name": "search",
  "description": "Search the knowledge base",
  "category": "search",
  "parameters": [
    {
      "name": "query",
      "type": "string",
      "description": "Search query",
      "required": true,
      "maxLength": 500
    }
  ],
  "returns": {
    "type": "object",
    "description": "Search results",
    "schema": {
      "results": "array",
      "count": "number"
    }
  },
  "examples": [
    {
      "input": { "query": "meditation techniques" },
      "output": { "results": [...], "count": 5 },
      "description": "Search for meditation content"
    }
  ],
  "permissions": ["read:content"],
  "rateLimit": {
    "calls": 100,
    "period": "minute"
  }
}

Validate Tool Input#

POST /tools/:name/validate

Validate input parameters against tool schema.

Request Body:

json
{
  "input": {
    "query": "example search",
    "limit": 10
  }
}

Response: 200 OK

json
{
  "valid": true,
  "errors": []
}

Error Response:

json
{
  "valid": false,
  "errors": [
    "Missing required parameter: query",
    "Parameter 'limit' exceeds maximum: 100"
  ]
}

Get Tools by Category#

GET /tools/category/:category

Retrieve all tools in a specific category.

Categories:

  • search - Search and retrieval tools
  • knowledge - Knowledge graph queries
  • computation - Mathematical calculations
  • speech - Text-to-speech and speech-to-text
  • scheduling - Time-based scheduling
  • system - System utilities

Response: 200 OK

json
{
  "category": "speech",
  "tools": [
    {
      "name": "tts",
      "description": "Text-to-speech synthesis",
      "category": "speech",
      ...
    },
    {
      "name": "stt",
      "description": "Speech-to-text transcription",
      "category": "speech",
      ...
    }
  ],
  "count": 2
}

Export OpenAPI Schema#

GET /tools/:name/openapi

Export tool schema in OpenAPI 3.0 format.

Response: 200 OK

json
{
  "openapi": "3.0.0",
  "info": {
    "title": "search",
    "description": "Search the knowledge base",
    "version": "1.0.0"
  },
  "paths": {
    "/search": {
      "post": {
        "summary": "Search the knowledge base",
        "requestBody": {
          "content": {
            "application/json": {
              "schema": {
                "type": "object",
                "properties": {
                  "query": {
                    "type": "string",
                    "description": "Search query",
                    "maxLength": 500
                  }
                },
                "required": ["query"]
              }
            }
          }
        },
        "responses": {
          "200": {
            "description": "Search results",
            "content": {
              "application/json": {
                "schema": {
                  "type": "object"
                }
              }
            }
          }
        }
      }
    }
  }
}

Export All Schemas#

GET /tools/openapi

Export OpenAPI schemas for all tools.

Response: 200 OK

json
{
  "openapi": "3.0.0",
  "info": {
    "title": "AI Tools API",
    "description": "All available AI agent tools",
    "version": "1.0.0"
  },
  "paths": {
    "/search": {...},
    "/kg_query": {...},
    "/calc": {...},
    "/tts": {...},
    "/stt": {...},
    "/scheduler": {...}
  }
}

Default Tools#

1. Search Tool#

typescript
{
  name: "search",
  description: "Search the knowledge base",
  category: "search",
  parameters: [
    {
      name: "query",
      type: "string",
      description: "Search query",
      required: true,
      maxLength: 500
    },
    {
      name: "limit",
      type: "number",
      description: "Maximum results",
      required: false,
      default: 10,
      minimum: 1,
      maximum: 100
    }
  ],
  returns: {
    type: "object",
    description: "Search results with metadata",
    schema: {
      results: "array",
      count: "number",
      query: "string"
    }
  },
  permissions: ["read:content"],
  rateLimit: {
    calls: 100,
    period: "minute"
  }
}

2. Knowledge Graph Query Tool#

typescript
{
  name: "kg_query",
  description: "Query the knowledge graph",
  category: "knowledge",
  parameters: [
    {
      name: "query",
      type: "string",
      description: "SPARQL or Cypher query",
      required: true,
      maxLength: 2000
    },
    {
      name: "queryType",
      type: "string",
      description: "Query language",
      required: false,
      enum: ["sparql", "cypher"],
      default: "sparql"
    }
  ],
  returns: {
    type: "object",
    description: "Query results",
    schema: {
      bindings: "array",
      count: "number"
    }
  },
  permissions: ["read:knowledge_graph"],
  rateLimit: {
    calls: 50,
    period: "minute"
  }
}

3. Calculator Tool#

typescript
{
  name: "calc",
  description: "Evaluate mathematical expressions",
  category: "computation",
  parameters: [
    {
      name: "expression",
      type: "string",
      description: "Mathematical expression to evaluate",
      required: true,
      pattern: "^[0-9+\\-*/()\\s.]+$",
      maxLength: 200
    }
  ],
  returns: {
    type: "number",
    description: "Calculation result"
  },
  permissions: [],
  rateLimit: {
    calls: 1000,
    period: "minute"
  }
}

4. Text-to-Speech Tool#

typescript
{
  name: "tts",
  description: "Convert text to speech",
  category: "speech",
  parameters: [
    {
      name: "text",
      type: "string",
      description: "Text to synthesize",
      required: true,
      maxLength: 5000
    },
    {
      name: "voice",
      type: "string",
      description: "Voice ID",
      required: false,
      default: "default"
    },
    {
      name: "format",
      type: "string",
      description: "Audio format",
      required: false,
      enum: ["mp3", "wav", "ogg"],
      default: "mp3"
    }
  ],
  returns: {
    type: "object",
    description: "Audio file URL and metadata",
    schema: {
      url: "string",
      duration: "number",
      format: "string"
    }
  },
  permissions: ["use:tts"],
  rateLimit: {
    calls: 100,
    period: "hour"
  }
}

5. Speech-to-Text Tool#

typescript
{
  name: "stt",
  description: "Transcribe speech to text",
  category: "speech",
  parameters: [
    {
      name: "audioUrl",
      type: "string",
      description: "URL of audio file",
      required: true,
      pattern: "^https?://.+\\.(mp3|wav|ogg)$"
    },
    {
      name: "language",
      type: "string",
      description: "Audio language",
      required: false,
      default: "en"
    }
  ],
  returns: {
    type: "object",
    description: "Transcription result",
    schema: {
      text: "string",
      confidence: "number",
      words: "array"
    }
  },
  permissions: ["use:stt"],
  rateLimit: {
    calls: 50,
    period: "hour"
  }
}

6. Scheduler Tool#

typescript
{
  name: "scheduler",
  description: "Schedule tasks and reminders",
  category: "scheduling",
  parameters: [
    {
      name: "action",
      type: "string",
      description: "Scheduler action",
      required: true,
      enum: ["schedule", "cancel", "list"]
    },
    {
      name: "taskId",
      type: "string",
      description: "Task ID for cancel operation",
      required: false
    },
    {
      name: "schedule",
      type: "object",
      description: "Schedule details for scheduling",
      required: false
    }
  ],
  returns: {
    type: "object",
    description: "Scheduler response",
    schema: {
      taskId: "string",
      status: "string",
      scheduledAt: "string"
    }
  },
  permissions: ["use:scheduler"],
  rateLimit: {
    calls: 100,
    period: "minute"
  }
}

Data Models#

ToolParameter#

typescript
interface ToolParameter {
  name: string;
  type: 'string' | 'number' | 'boolean' | 'object' | 'array';
  description: string;
  required: boolean;
  default?: any;
  enum?: any[];
  pattern?: string;
  minLength?: number;
  maxLength?: number;
  minimum?: number;
  maximum?: number;
}

ToolSchema#

typescript
interface ToolSchema {
  name: string;
  description: string;
  category:
    | 'search'
    | 'knowledge'
    | 'computation'
    | 'speech'
    | 'scheduling'
    | 'system';
  parameters: ToolParameter[];
  returns: {
    type: string;
    description: string;
    schema?: any;
  };
  examples: Array<{
    input: Record<string, any>;
    output: any;
    description: string;
  }>;
  permissions?: string[];
  rateLimit?: {
    calls: number;
    period: 'second' | 'minute' | 'hour' | 'day';
  };
}

Validation Rules#

Parameter Validation#

  • Required: Must be present if required: true
  • Type: Must match specified type (string, number, boolean, object, array)
  • Enum: Must be one of the allowed values
  • Pattern: Must match regex pattern
  • Length: String length must be within minLength/maxLength
  • Range: Number must be within minimum/maximum

Schema Validation#

  • Name: Must be unique across all tools
  • Description: Required, non-empty
  • Category: Must be valid category
  • Parameters: Each parameter must have name, type, description

Error Responses#

400 Bad Request

json
{
  "error": {
    "code": "VALIDATION_ERROR",
    "message": "Invalid tool parameters",
    "details": {
      "valid": false,
      "errors": ["Missing required parameter: query"]
    }
  }
}

404 Not Found

json
{
  "error": {
    "code": "TOOL_NOT_FOUND",
    "message": "Tool 'unknown_tool' not found"
  }
}

500 Internal Server Error

json
{
  "error": {
    "code": "INTERNAL_ERROR",
    "message": "An unexpected error occurred"
  }
}

Examples#

Register Custom Tool#

bash
curl -X POST http://localhost:3007/v1/ai/tools \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "translator",
    "description": "Translate text between languages",
    "category": "system",
    "parameters": [
      {
        "name": "text",
        "type": "string",
        "description": "Text to translate",
        "required": true,
        "maxLength": 5000
      },
      {
        "name": "targetLang",
        "type": "string",
        "description": "Target language code",
        "required": true,
        "enum": ["en", "es", "fr", "de", "zh", "ja"]
      }
    ],
    "returns": {
      "type": "object",
      "description": "Translation result",
      "schema": {
        "translatedText": "string",
        "sourceLanguage": "string",
        "confidence": "number"
      }
    },
    "examples": [
      {
        "input": { "text": "Hello world", "targetLang": "es" },
        "output": { "translatedText": "Hola mundo", "sourceLanguage": "en", "confidence": 0.99 },
        "description": "English to Spanish translation"
      }
    ]
  }'

Validate Search Input#

bash
curl -X POST http://localhost:3007/v1/ai/tools/search/validate \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "input": {
      "query": "meditation techniques",
      "limit": 10
    }
  }'

Get Speech Tools#

bash
curl -X GET "http://localhost:3007/v1/ai/tools?category=speech" \
  -H "Authorization: Bearer YOUR_TOKEN"

Export OpenAPI Schema#

bash
curl -X GET "http://localhost:3007/v1/ai/tools/search/openapi" \
  -H "Authorization: Bearer YOUR_TOKEN"

Test Coverage#

The Tool Schemas feature has comprehensive test coverage:

  • Unit Tests: 54 tests (100% code coverage)
  • Integration Tests: 19 tests (all HTTP endpoints)
  • E2E Tests: 23 Playwright tests
  • Total: 96 tests passing

Implementation#

  • Language: TypeScript with strict type safety
  • File: apps/lilith/svc-ai/src/tool-schemas.ts
  • Lines of Code: 609
  • Dependencies: None (in-memory storage)

Limitations#

  • Tools are stored in-memory (not persisted to database)
  • No pagination on list endpoints
  • Tool schemas cannot be deleted after registration
  • Rate limiting is metadata only (not enforced)

Future Enhancements#

  • Database persistence (PostgreSQL)
  • Dynamic tool loading from external sources
  • Tool execution engine integration
  • Real-time schema validation
  • Tool versioning and deprecation
  • Usage analytics and monitoring

Generated: 2025-10-03 API Version: 1.0.0 Test Coverage: 96 tests passing

Implementation Status#

Implementation Status#

Current Status: 11/15 Criteria Met (73% Complete) ✅

Completion: 11/15 criteria met (73%)


Domain Agents#

Auto-generated API documentation

Last Updated: 2025-10-03


API Reference#

API Types#

Interfaces#

AgentToolAccess#

typescript
export interface AgentToolAccess {
  toolName: ToolCapability;
  permissions: string[];
  rateLimit?: {
    calls: number;
    period: 'minute' | 'hour' | 'day';
  };
}

DomainAgent#

typescript
export interface DomainAgent {
  id: string;
  role: AgentRole;
  name: string;
  description: string;
  capabilities: string[];
  toolAccess: AgentToolAccess[];
  personality: {
    tone: string;
    style: string;
    expertise: string[];
  };
  status: 'idle' | 'busy' | 'error';
  metrics: {
    tasksCompleted: number;
    toolsUsed: number;
    successRate: number;
    averageResponseTime: number;
  };
  createdAt: Date;
}

AgentTask#

typescript
export interface AgentTask {
  id: string;
  agentId: string;
  type: string;
  input: Record<string, unknown>;
  status: 'pending' | 'running' | 'completed' | 'failed';
  result?: unknown;
  error?: string;
  toolsUsed: string[];
  startedAt?: Date;
  completedAt?: Date;
  duration?: number;
}

AgentToolExecution#

typescript
export interface AgentToolExecution {
  agentId: string;
  toolName: ToolCapability;
  input: Record<string, unknown>;
  output?: unknown;
  success: boolean;
  duration: number;
  timestamp: Date;
}

Type Aliases#

AgentRole#

Domain-Specific Agent System Specialized agents for meditation, knowledge, and learning tasks

typescript
export type AgentRole =
  | 'librarian'
  | 'curator'
  | 'scholar'
  | 'socratic_coach'
  | 'persona_engine'
  | 'safety_moderator'
  | 'narrator';

ToolCapability#

typescript
export type ToolCapability =
  | 'search'
  | 'kg_query'
  | 'calc'
  | 'tts'
  | 'stt'
  | 'scheduler';

Classes#

DomainAgentRegistry#

Domain-Specific Agent System Specialized agents for meditation, knowledge, and learning tasks

typescript
export type AgentRole =
  | 'librarian'
  | 'curator'
  | 'scholar'
  | 'socratic_coach'
  | 'persona_engine'
  | 'safety_moderator'
  | 'narrator';

export type ToolCapability =
  | 'search'
  | 'kg_query'
  | 'calc'
  | 'tts'
  | 'stt'
  | 'scheduler';

export interface AgentToolAccess {
  toolName: ToolCapability;
  permissions: string[];
  rateLimit?: {
    calls: number;
    period: 'minute' | 'hour' | 'day';
  };
}...

Endpoints#

Overview#

The Domain Agents API provides specialized AI agents for meditation, knowledge management, and learning tasks. The system includes 7 default agents (Librarian, Curator, Scholar, Socratic Coach, Persona Engine, Safety Moderator, Narrator) with distinct capabilities, tool access, and personality configurations. Each agent can execute tasks, use tools, and collaborate with other agents in multi-agent workflows.

Base URL#

text
http://localhost:3007/v1/ai

Authentication#

All endpoints require authentication via Bearer token in the Authorization header.

Endpoints#

List All Agents#

GET /agents

Retrieve all registered domain agents in the system.

Response: 200 OK

Example:

bash
curl -X GET "http://localhost:3007/v1/ai/agents" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "agents": [
    {
      "id": "agent_1730000000000_abc123",
      "role": "librarian",
      "name": "Knowledge Librarian",
      "description": "Discovers, organizes, and retrieves knowledge from vast collections",
      "capabilities": ["knowledge_search", "cataloging", "metadata_extraction"],
      "toolAccess": [
        {
          "toolName": "search",
          "permissions": ["search.execute"],
          "rateLimit": { "calls": 100, "period": "minute" }
        },
        {
          "toolName": "kg_query",
          "permissions": ["kg.read"],
          "rateLimit": { "calls": 50, "period": "minute" }
        }
      ],
      "personality": {
        "tone": "helpful",
        "style": "precise",
        "expertise": ["cataloging", "information_retrieval", "taxonomy"]
      },
      "status": "idle",
      "metrics": {
        "tasksCompleted": 0,
        "toolsUsed": 0,
        "successRate": 0,
        "averageResponseTime": 0
      },
      "createdAt": "2025-10-03T10:00:00.000Z"
    }
  ],
  "count": 7
}

Get Agent by ID#

GET /agents/:agentId

Retrieve a specific agent by ID.

Path Parameters:

  • agentId (required): Agent ID

Response: 200 OK or 404 Not Found

Example:

bash
curl -X GET "http://localhost:3007/v1/ai/agents/agent_123" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "agent": {
    "id": "agent_123",
    "role": "scholar",
    "name": "Academic Scholar",
    "description": "Conducts deep research and provides scholarly analysis",
    "capabilities": ["research", "analysis", "citation", "synthesis"],
    "toolAccess": [
      {
        "toolName": "search",
        "permissions": ["search.execute"],
        "rateLimit": { "calls": 200, "period": "hour" }
      },
      {
        "toolName": "kg_query",
        "permissions": ["kg.read", "kg.traverse"],
        "rateLimit": { "calls": 100, "period": "hour" }
      },
      {
        "toolName": "calc",
        "permissions": ["calc.execute"]
      }
    ],
    "personality": {
      "tone": "academic",
      "style": "analytical",
      "expertise": ["research", "analysis", "synthesis", "critical_thinking"]
    },
    "status": "idle",
    "metrics": {
      "tasksCompleted": 42,
      "toolsUsed": 156,
      "successRate": 0.98,
      "averageResponseTime": 1250
    },
    "createdAt": "2025-10-01T08:00:00.000Z"
  }
}

Error Response: 404 Not Found

json
{
  "error": "Agent not found",
  "code": "agents.not_found"
}

Get Agents by Role#

GET /agents/role/:role

Retrieve all agents with a specific role.

Path Parameters:

  • role (required): Agent role (librarian, curator, scholar, socratic_coach, persona_engine, safety_moderator, narrator)

Response: 200 OK

Example: Get all librarians

bash
curl -X GET "http://localhost:3007/v1/ai/agents/role/librarian" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "role": "librarian",
  "agents": [
    {
      "id": "agent_abc",
      "role": "librarian",
      "name": "Knowledge Librarian",
      "capabilities": ["knowledge_search", "cataloging", "metadata_extraction"],
      ...
    }
  ],
  "count": 1
}

Get Agents by Capability#

GET /agents/capability/:capability

Find all agents with a specific capability.

Path Parameters:

  • capability (required): Capability name (e.g., research, narration, knowledge_search)

Response: 200 OK

Example: Find research-capable agents

bash
curl -X GET "http://localhost:3007/v1/ai/agents/capability/research" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "capability": "research",
  "agents": [
    {
      "id": "agent_scholar_123",
      "role": "scholar",
      "name": "Academic Scholar",
      "capabilities": ["research", "analysis", "citation", "synthesis"],
      ...
    }
  ],
  "count": 1
}

Get Agents by Tool Access#

GET /agents/tool/:toolName

Find all agents with access to a specific tool.

Path Parameters:

  • toolName (required): Tool name (search, kg_query, calc, tts, stt, scheduler)

Response: 200 OK

Example: Find agents with search tool

bash
curl -X GET "http://localhost:3007/v1/ai/agents/tool/search" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "toolName": "search",
  "agents": [
    {
      "id": "agent_librarian_123",
      "role": "librarian",
      "name": "Knowledge Librarian",
      "toolAccess": [
        {
          "toolName": "search",
          "permissions": ["search.execute"],
          "rateLimit": { "calls": 100, "period": "minute" }
        }
      ],
      ...
    },
    {
      "id": "agent_scholar_456",
      "role": "scholar",
      "name": "Academic Scholar",
      "toolAccess": [
        {
          "toolName": "search",
          "permissions": ["search.execute"],
          "rateLimit": { "calls": 200, "period": "hour" }
        }
      ],
      ...
    }
  ],
  "count": 5
}

Create Agent Task#

POST /agents/:agentId/tasks

Create a new task for a specific agent.

Path Parameters:

  • agentId (required): Agent ID

Request Body:

typescript
{
  type: string; // Required: Task type
  input: Record<string, unknown>; // Required: Task input data
}

Response: 201 Created

Example: Create search task

bash
curl -X POST http://localhost:3007/v1/ai/agents/agent_librarian_123/tasks \
  -H "Authorization: Bearer YOUR_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "type": "knowledge_search",
    "input": {
      "query": "mindfulness meditation techniques",
      "limit": 10,
      "filters": {
        "tradition": "buddhist",
        "language": "en"
      }
    }
  }'
json
{
  "success": true,
  "task": {
    "id": "task_1730000123456_xyz",
    "agentId": "agent_librarian_123",
    "type": "knowledge_search",
    "input": {
      "query": "mindfulness meditation techniques",
      "limit": 10,
      "filters": {
        "tradition": "buddhist",
        "language": "en"
      }
    },
    "status": "pending",
    "toolsUsed": [],
    "createdAt": "2025-10-03T14:30:00.000Z"
  }
}

Error Response: 400 Bad Request

json
{
  "error": "Missing required field: type",
  "code": "validation.missing_field"
}

Error Response: 404 Not Found

json
{
  "error": "Agent not found",
  "code": "agents.not_found"
}

Execute Agent Task#

POST /tasks/:taskId/execute

Execute a pending task.

Path Parameters:

  • taskId (required): Task ID

Response: 200 OK

Example:

bash
curl -X POST http://localhost:3007/v1/ai/tasks/task_123/execute \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "success": true,
  "task": {
    "id": "task_123",
    "agentId": "agent_librarian_456",
    "type": "knowledge_search",
    "input": {
      "query": "mindfulness meditation"
    },
    "status": "completed",
    "result": {
      "success": true,
      "output": "Agent Knowledge Librarian completed task: knowledge_search",
      "data": {
        "results": [...],
        "count": 10
      }
    },
    "toolsUsed": ["search", "kg_query"],
    "startedAt": "2025-10-03T14:30:00.000Z",
    "completedAt": "2025-10-03T14:30:01.250Z",
    "duration": 1250
  }
}

Error Response: 404 Not Found

json
{
  "error": "Task not found",
  "code": "tasks.not_found"
}

Get Agent Tool History#

GET /agents/:agentId/tool-history

Retrieve tool execution history for an agent.

Path Parameters:

  • agentId (required): Agent ID

Response: 200 OK

Example:

bash
curl -X GET "http://localhost:3007/v1/ai/agents/agent_scholar_123/tool-history" \
  -H "Authorization: Bearer YOUR_TOKEN"
json
{
  "agentId": "agent_scholar_123",
  "executions": [
    {
      "agentId": "agent_scholar_123",
      "toolName": "search",
      "input": {
        "query": "Zen meditation",
        "limit": 20
      },
      "output": {
        "results": [...],
        "count": 18
      },
      "success": true,
      "duration": 245,
      "timestamp": "2025-10-03T14:25:00.000Z"
    },
    {
      "agentId": "agent_scholar_123",
      "toolName": "kg_query",
      "input": {
        "query": "MATCH (n:Tradition {name: 'Zen'}) RETURN n",
        "queryType": "cypher"
      },
      "output": {
        "bindings": [...],
        "count": 5
      },
      "success": true,
      "duration": 180,
      "timestamp": "2025-10-03T14:26:00.000Z"
    }
  ],
  "count": 2
}

Default Agents#

1. Librarian (knowledge_search, cataloging)#

typescript
{
  role: "librarian",
  capabilities: [
    "knowledge_search",
    "cataloging",
    "metadata_extraction"
  ],
  toolAccess: [
    {
      toolName: "search",
      permissions: ["search.execute"],
      rateLimit: { calls: 100, period: "minute" }
    },
    {
      toolName: "kg_query",
      permissions: ["kg.read"],
      rateLimit: { calls: 50, period: "minute" }
    }
  ],
  personality: {
    tone: "helpful",
    style: "precise",
    expertise: ["cataloging", "information_retrieval", "taxonomy"]
  }
}

2. Curator (content_evaluation, quality_assessment)#

typescript
{
  role: "curator",
  capabilities: [
    "content_evaluation",
    "quality_assessment",
    "relevance_scoring"
  ],
  toolAccess: [
    { toolName: "search", permissions: ["search.execute"] },
    { toolName: "kg_query", permissions: ["kg.read"] }
  ],
  personality: {
    tone: "discerning",
    style: "evaluative",
    expertise: ["quality_assessment", "content_selection", "relevance"]
  }
}

3. Scholar (research, analysis, synthesis)#

typescript
{
  role: "scholar",
  capabilities: [
    "research",
    "analysis",
    "citation",
    "synthesis"
  ],
  toolAccess: [
    {
      toolName: "search",
      permissions: ["search.execute"],
      rateLimit: { calls: 200, period: "hour" }
    },
    {
      toolName: "kg_query",
      permissions: ["kg.read", "kg.traverse"],
      rateLimit: { calls: 100, period: "hour" }
    },
    { toolName: "calc", permissions: ["calc.execute"] }
  ],
  personality: {
    tone: "academic",
    style: "analytical",
    expertise: ["research", "analysis", "synthesis", "critical_thinking"]
  }
}

4. Socratic Coach (guided_inquiry, learning_facilitation)#

typescript
{
  role: "socratic_coach",
  capabilities: [
    "questioning",
    "guided_inquiry",
    "learning_facilitation"
  ],
  toolAccess: [
    { toolName: "search", permissions: ["search.execute"] },
    {
      toolName: "scheduler",
      permissions: ["scheduler.create", "scheduler.read"]
    }
  ],
  personality: {
    tone: "questioning",
    style: "socratic",
    expertise: ["pedagogy", "inquiry", "facilitation"]
  }
}

5. Persona Engine (persona_selection, style_adaptation)#

typescript
{
  role: "persona_engine",
  capabilities: [
    "persona_selection",
    "style_adaptation",
    "tone_matching"
  ],
  toolAccess: [
    { toolName: "search", permissions: ["search.execute"] }
  ],
  personality: {
    tone: "adaptive",
    style: "contextual",
    expertise: ["persona_modeling", "style_adaptation", "context_awareness"]
  }
}

6. Safety Moderator (safety_checking, moderation)#

typescript
{
  role: "safety_moderator",
  capabilities: [
    "safety_checking",
    "moderation",
    "cultural_sensitivity"
  ],
  toolAccess: [],  // No tool access - focuses on content analysis
  personality: {
    tone: "protective",
    style: "careful",
    expertise: ["safety", "moderation", "cultural_awareness"]
  }
}

7. Narrator (narration, voice_synthesis, audio_guidance)#

typescript
{
  role: "narrator",
  capabilities: [
    "narration",
    "voice_synthesis",
    "audio_guidance"
  ],
  toolAccess: [
    {
      toolName: "tts",
      permissions: ["tts.generate"],
      rateLimit: { calls: 100, period: "hour" }
    },
    {
      toolName: "stt",
      permissions: ["stt.transcribe"],
      rateLimit: { calls: 50, period: "hour" }
    }
  ],
  personality: {
    tone: "calming",
    style: "narrative",
    expertise: ["narration", "voice", "guidance"]
  }
}

Data Models#

DomainAgent#

typescript
interface DomainAgent {
  id: string; // Unique agent ID
  role: AgentRole; // Agent role
  name: string; // Human-readable name
  description: string; // Agent description
  capabilities: string[]; // Agent capabilities
  toolAccess: AgentToolAccess[]; // Tools the agent can use
  personality: {
    tone: string; // Communication tone
    style: string; // Interaction style
    expertise: string[]; // Areas of expertise
  };
  status: 'idle' | 'busy' | 'error'; // Current status
  metrics: {
    tasksCompleted: number; // Total tasks completed
    toolsUsed: number; // Total tools used
    successRate: number; // Task success rate (0-1)
    averageResponseTime: number; // Avg response time in ms
  };
  createdAt: Date; // Creation timestamp
}

AgentTask#

typescript
interface AgentTask {
  id: string; // Unique task ID
  agentId: string; // Agent ID
  type: string; // Task type
  input: Record<string, unknown>; // Task input
  status: 'pending' | 'running' | 'completed' | 'failed';
  result?: unknown; // Task result
  error?: string; // Error message if failed
  toolsUsed: string[]; // Tools used during execution
  startedAt?: Date; // Execution start time
  completedAt?: Date; // Execution completion time
  duration?: number; // Execution duration in ms
}

AgentToolExecution#

typescript
interface AgentToolExecution {
  agentId: string; // Agent ID
  toolName: ToolCapability; // Tool name
  input: Record<string, unknown>; // Tool input
  output?: unknown; // Tool output
  success: boolean; // Execution success
  duration: number; // Duration in ms
  timestamp: Date; // Execution timestamp
}

AgentToolAccess#

typescript
interface AgentToolAccess {
  toolName: ToolCapability; // Tool name
  permissions: string[]; // Required permissions
  rateLimit?: {
    calls: number; // Max calls
    period: 'minute' | 'hour' | 'day'; // Time period
  };
}

Multi-Agent Workflows#

Workflow 1: Complete Meditation Content Creation#

bash
# 1. Librarian searches for meditation content
curl -X POST http://localhost:3007/v1/ai/agents/librarian_123/tasks \
  -d '{"type": "search_content", "input": {"query": "mindfulness meditation"}}'
# Response: { "task": { "id": "task_1" } }

# 2. Scholar analyzes and structures content
curl -X POST http://localhost:3007/v1/ai/agents/scholar_456/tasks \
  -d '{"type": "analyze_structure", "input": {"source": "task_1"}}'
# Response: { "task": { "id": "task_2" } }

# 3. Safety Moderator reviews for appropriateness
curl -X POST http://localhost:3007/v1/ai/agents/moderator_789/tasks \
  -d '{"type": "safety_check", "input": {"content": "task_2"}}'
# Response: { "task": { "id": "task_3" } }

# 4. Narrator creates audio narration
curl -X POST http://localhost:3007/v1/ai/agents/narrator_012/tasks \
  -d '{"type": "create_narration", "input": {"script": "task_2", "approved": "task_3"}}'
# Response: { "task": { "id": "task_4" } }

# Execute all tasks
curl -X POST http://localhost:3007/v1/ai/tasks/task_1/execute
curl -X POST http://localhost:3007/v1/ai/tasks/task_2/execute
curl -X POST http://localhost:3007/v1/ai/tasks/task_3/execute
curl -X POST http://localhost:3007/v1/ai/tasks/task_4/execute

Workflow 2: Adaptive Learning Journey#

bash
# 1. Socratic Coach creates learning plan
curl -X POST http://localhost:3007/v1/ai/agents/coach_123/tasks \
  -d '{"type": "create_learning_plan", "input": {"topic": "Buddhist philosophy", "level": "beginner"}}'

# 2. Librarian provides resources
curl -X POST http://localhost:3007/v1/ai/agents/librarian_456/tasks \
  -d '{"type": "find_resources", "input": {"plan": "task_1"}}'

# 3. Coach schedules learning sessions
curl -X POST http://localhost:3007/v1/ai/agents/coach_123/tasks \
  -d '{"type": "schedule_sessions", "input": {"resources": "task_2", "frequency": "weekly"}}'

Workflow 3: Research Collaboration#

bash
# 1. Scholar conducts deep research
curl -X POST http://localhost:3007/v1/ai/agents/scholar_123/tasks \
  -d '{"type": "deep_research", "input": {"topic": "Zen meditation lineages"}}'

# 2. Curator evaluates quality
curl -X POST http://localhost:3007/v1/ai/agents/curator_456/tasks \
  -d '{"type": "evaluate_research", "input": {"research": "task_1", "criteria": ["accuracy", "comprehensiveness"]}}'

# 3. Scholar refines based on feedback
curl -X POST http://localhost:3007/v1/ai/agents/scholar_123/tasks \
  -d '{"type": "refine_research", "input": {"original": "task_1", "feedback": "task_2"}}'

Agent Discovery Patterns#

Find the Right Agent for a Task#

javascript
// Pattern 1: Find by capability
const searchAgents = await fetch('/v1/ai/agents/capability/knowledge_search');
const bestAgent = searchAgents.agents[0]; // Librarian

// Pattern 2: Find by tool access
const ttsAgents = await fetch('/v1/ai/agents/tool/tts');
const narrator = ttsAgents.agents.find((a) => a.role === 'narrator');

// Pattern 3: Find by role
const scholars = await fetch('/v1/ai/agents/role/scholar');
const researchAgent = scholars.agents[0];

// Pattern 4: Find by multiple criteria
const allAgents = await fetch('/v1/ai/agents');
const researchWithCalc = allAgents.agents.filter(
  (a) =>
    a.capabilities.includes('research') &&
    a.toolAccess.some((t) => t.toolName === 'calc')
);

Error Handling#

Common Error Codes#

Agent Not Found

json
{
  "error": "Agent not found",
  "code": "agents.not_found",
  "statusCode": 404
}

Task Not Found

json
{
  "error": "Task not found",
  "code": "tasks.not_found",
  "statusCode": 404
}

Missing Required Field

json
{
  "error": "Missing required field: type",
  "code": "validation.missing_field",
  "statusCode": 400
}

Agent Busy

json
{
  "error": "Agent is currently busy",
  "code": "agents.busy",
  "statusCode": 409
}

Test Coverage#

The Domain Agents feature has comprehensive test coverage:

  • Unit Tests: 44 tests (100% code coverage)
  • Integration Tests: 20 tests (all HTTP endpoints)
  • Multi-Agent Workflow Tests: 100 tests (autonomous agent scenarios)
  • E2E Tests: 15 Playwright tests
  • Total: 179 tests passing

Multi-Agent Test Scenarios (100 tests)#

  1. Agent Discovery & Registration (10 tests): Finding agents, registration, capability queries
  2. Task Creation & Management (10 tests): Creating, executing, tracking tasks
  3. Tool Access & Permissions (10 tests): Tool usage, permissions, execution history
  4. Multi-Agent Coordination (10 tests): Agent collaboration, delegation, workflows
  5. Agent Metrics & Monitoring (10 tests): Performance tracking, success rates
  6. Agent Capabilities & Specialization (10 tests): Capability-specific behaviors
  7. Error Handling & Resilience (10 tests): Graceful degradation, error recovery
  8. Performance & Scalability (10 tests): High-volume operations, concurrent execution
  9. Agent Lifecycle & State Management (10 tests): Status transitions, state preservation
  10. Integration & Real-World Scenarios (10 tests): Complete workflows, production scenarios

Implementation#

  • Language: TypeScript with strict type safety
  • File: apps/lilith/svc-ai/src/domain-agents.ts
  • Lines of Code: 484
  • Dependencies: None (in-memory storage)
  • Default Agents: 7 specialized agents

Performance Characteristics#

  • Agent Registration: O(1) insertion
  • Agent Query by ID: O(1) lookup
  • Agent Query by Role: O(n) filtering with indexing
  • Agent Query by Capability: O(n) filtering
  • Task Creation: O(1) insertion
  • Task Execution: O(1) + task duration
  • Tool History Query: O(n) filtering

Recommendations:

  • Suitable for 100s of agents and 1000s of tasks
  • Add pagination for large result sets
  • Consider database persistence for production

Limitations#

  • In-Memory Storage: Data lost on service restart (not persisted)
  • No Pagination: All results returned in single response
  • No Real-Time Updates: No WebSocket notifications for task updates
  • No Task Cancellation: Once started, tasks cannot be cancelled
  • No Agent Load Balancing: Manual task distribution required

Future Enhancements#

High Priority:

  1. Database persistence (PostgreSQL with agent/task tables)
  2. Real-time task notifications via WebSocket
  3. Task cancellation and timeout support
  4. Automatic agent load balancing

Medium Priority: 5. Agent performance analytics dashboard 6. ML-based agent recommendation for tasks 7. Cross-agent knowledge sharing 8. Agent learning from task outcomes

Low Priority: 9. Dynamic agent creation via API 10. Agent personality customization 11. Multi-tenant agent isolation 12. Agent federation across services

Best Practices#

Agent Selection#

javascript
// ✅ Good: Select agent by specific capability
const agents = await fetch('/v1/ai/agents/capability/research');
const scholar = agents.agents.find((a) => a.role === 'scholar');

// ❌ Bad: Assume agent ID or position
const agent = allAgents[0]; // Don't assume array order

Task Management#

javascript
// ✅ Good: Create task, then execute separately
const taskResponse = await createTask(agentId, 'research', input);
const result = await executeTask(taskResponse.task.id);

// ❌ Bad: Assume immediate execution
const result = await createTask(agentId, 'research', input);
// Task is created but not executed

Multi-Agent Workflows#

javascript
// ✅ Good: Sequential execution with dependency tracking
const task1 = await createAndExecute(librarian, 'search', {});
const task2 = await createAndExecute(scholar, 'analyze', { source: task1.id });
const task3 = await createAndExecute(narrator, 'narrate', { script: task2.id });

// ❌ Bad: Parallel execution without dependencies
Promise.all([
  createAndExecute(librarian, 'search', {}),
  createAndExecute(scholar, 'analyze', {}), // Missing source!
  createAndExecute(narrator, 'narrate', {}), // Missing script!
]);

Tool Access Verification#

javascript
// ✅ Good: Verify agent has tool access before creating task
const agent = await getAgent(agentId);
const hasSearchTool = agent.toolAccess.some((t) => t.toolName === 'search');
if (hasSearchTool) {
  await createTask(agentId, 'search_task', {});
}

// ❌ Bad: Assume agent has tool access
await createTask(agentId, 'search_task', {}); // May fail if no access

Generated: 2025-10-03 API Version: 1.0.0 Test Coverage: 179 tests passing Multi-Agent Tests: 100/100 passing

Code Examples#

Usage Examples#

These examples are extracted from actual test cases to ensure accuracy.

Example 1: should execute task successfully#

typescript
const task = registry.createTask(agentId, 'search', {
        query: 'mindfulness'

Example 2: should update agent status during task execution#

typescript
const task = registry.createTask(agentId, 'test', {});
const agent = registry.getAgent(agentId)!;

expect(agent.status).toBe('idle');

const promise = registry.executeTask(task.id);

// Status should be busy during execution
// Note: Due to async timing, we check after completion
const executed = await promise;

// After completion, should be idle again
expect(agent.status).toBe('idle');
expect(agent.metrics.tasksCompleted).toBe(1);

Example 3: should get agent tasks#

typescript
const task1 = registry.createTask(agentId, 'task1', {});
const task2 = registry.createTask(agentId, 'task2', {});

await registry.executeTask(task1.id);
await registry.executeTask(task2.id);

const tasks = registry.getAgentTasks(agentId);
expect(tasks).toHaveLength(2);
expect(tasks.every((t) => t.agentId === agentId)).toBe(true);

Example 4: should sort tasks by start date (newest first)#

typescript
const task1 = registry.createTask(agentId, 'task1', {});
await registry.executeTask(task1.id);

// Small delay to ensure different timestamp
await new Promise((resolve) => setTimeout(resolve, 10));

const task2 = registry.createTask(agentId, 'task2', {});
await registry.executeTask(task2.id);

const tasks = registry.getAgentTasks(agentId);
expect(tasks[0].id).toBe(task2.id);
expect(tasks[1].id).toBe(task1.id);

Example 5: should throw error for non-existent task#

typescript
await expect(registry.executeTask('non-existent')).rejects.toThrow(
  "Task 'non-existent' not found"
);

Implementation Status#

Implementation Status#

Current Status: ✅ 11/15 CRITERIA MET (73% COMPLETE)

Completion: 11/15 criteria met (73%)


Multi-Agent System#

Auto-generated API documentation

Last Updated: 2025-10-03