@memberjunction/ai-agents 2.47.0 → 2.48.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,18 +1,19 @@
1
1
  # @memberjunction/ai-agents
2
2
 
3
- The MemberJunction AI Agents package provides a comprehensive framework for creating, managing, and executing AI agents within the MemberJunction ecosystem. This package serves as the foundation for building sophisticated agentic AI applications with hierarchical composition, context management, and intelligent execution strategies.
3
+ The MemberJunction AI Agents package provides a comprehensive framework for creating, managing, and executing AI agents within the MemberJunction ecosystem. This package implements a clean separation of concerns architecture that separates domain execution from orchestration decision-making.
4
4
 
5
5
  ## Features
6
6
 
7
- - **🤖 BaseAgent Class**: Core foundation for all AI agent implementations
7
+ - **🎯 Separation of Concerns**: Clean architecture separating BaseAgent (execution), ConductorAgent (decisions), and AgentRunner (coordination)
8
+ - **🤖 Hierarchical Prompt Execution**: Advanced prompt system with depth-first traversal and parallel execution at each level
8
9
  - **🏗️ Agent Composition**: Hierarchical agent architecture with parent-child relationships
10
+ - **🔄 Mixed Execution**: Action execution and sub-agent delegation with parallel/sequential coordination
11
+ - **📝 Comprehensive Tracking**: Agent run and prompt run linking for complete execution visibility
12
+ - **🎯 Action Framework**: Extensible action system integrated with ActionEngine
9
13
  - **🧠 Context Management**: Intelligent conversation context handling and compression
10
- - **🔄 Execution Strategies**: Sequential and parallel agent execution modes
11
- - **📝 Learning System**: Agent note-taking and knowledge retention capabilities
12
- - **🎯 Action Framework**: Extensible action system for agent capabilities
13
- - **🔧 Subclassing Support**: Easy extension and customization of agent behavior
14
- - **🔐 Metadata-Driven**: Database-driven configuration for agents and behaviors
15
- - **📊 Analytics**: Comprehensive execution logging and performance tracking
14
+ - **🔧 Factory Pattern**: Enhanced AgentFactory for dynamic agent instantiation and extensibility
15
+ - **🔐 Metadata-Driven**: Database-driven configuration for agents, types, and prompts
16
+ - **📊 Analytics**: Hierarchical execution logging with performance tracking across agent workflows
16
17
 
17
18
  ## Installation
18
19
 
@@ -29,53 +30,50 @@ npm install @memberjunction/ai-agents
29
30
 
30
31
  ## Core Architecture
31
32
 
32
- ### BaseAgent Class
33
+ The AI Agents framework implements a clean separation of concerns architecture:
33
34
 
34
- The `BaseAgent` class is the central component of the AI Agents framework, providing:
35
+ ### BaseAgent - Domain Execution
36
+ - Focuses solely on executing agent-specific prompts and tasks
37
+ - Handles template rendering with data context
38
+ - Manages conversation context and compression
39
+ - Returns standardized execution results
35
40
 
36
- - **Standard Interface**: Consistent API for all agent implementations
37
- - **Lifecycle Management**: Initialization, execution, and cleanup workflows
38
- - **Context Handling**: Automatic conversation context management
39
- - **Error Handling**: Robust error recovery and logging
40
- - **Extensibility**: Clean extension points for custom behavior
41
+ ### ConductorAgent - Decision Making
42
+ - Specialized agent for making orchestration decisions
43
+ - Analyzes current state and available resources
44
+ - Makes autonomous decisions about next steps
45
+ - Plans execution sequences with proper ordering
41
46
 
42
- ```typescript
43
- import { BaseAgent } from '@memberjunction/ai-agents';
44
- import { AIAgentEntity } from '@memberjunction/core-entities';
47
+ ### AgentRunner - Coordination
48
+ - Orchestrates interaction between BaseAgent and ConductorAgent
49
+ - Implements the core execution loop
50
+ - Manages progress tracking and cancellation
51
+ - Provides user interface abstraction
45
52
 
46
- // Create a custom agent by extending BaseAgent
47
- class CustomerSupportAgent extends BaseAgent {
48
- // Agent metadata from database
49
- private agentEntity: AIAgentEntity;
50
-
51
- constructor(agentEntity: AIAgentEntity) {
52
- super();
53
- this.agentEntity = agentEntity;
54
- }
55
-
56
- async initialize(): Promise<void> {
57
- // Custom initialization logic
58
- await super.initialize();
59
- this.setupCustomCapabilities();
60
- }
53
+ ```typescript
54
+ import { GetAgentFactory } from '@memberjunction/ai-agents';
55
+ import { UserInfo } from '@memberjunction/core';
56
+
57
+ // Get agent factory and create agents
58
+ const factory = GetAgentFactory();
59
+ const baseAgent = await factory.CreateAgent("Customer Support", null, contextUser);
60
+ const conductorAgent = await factory.CreateAgent("Conductor", null, contextUser);
61
+
62
+ // Create runner and execute with separation of concerns
63
+ const runner = new AgentRunner(conductorAgent, contextUser);
64
+ const result = await runner.Run({
65
+ agent: baseAgent,
66
+ goal: "Help customer with their order",
67
+ data: { customerQuery: "Where is my order?" },
68
+ conversationMessages: [...],
69
+ onProgress: (progress) => console.log(progress.message),
70
+ cancellationToken: controller.signal
71
+ });
61
72
 
62
- async execute(context: AgentContext): Promise<AgentResult> {
63
- // Custom execution logic
64
- const result = await super.execute(context);
65
- return this.enhanceResult(result);
66
- }
67
-
68
- async handleAction(actionName: string, params: any): Promise<any> {
69
- // Handle agent-specific actions
70
- switch(actionName) {
71
- case 'searchKnowledgeBase':
72
- return this.searchKnowledgeBase(params);
73
- case 'createTicket':
74
- return this.createSupportTicket(params);
75
- default:
76
- return super.handleAction(actionName, params);
77
- }
78
- }
73
+ if (result.success) {
74
+ console.log("Task completed:", result.finalDecision?.finalResponse);
75
+ console.log("Decisions made:", result.decisionHistory?.length);
76
+ console.log("Actions executed:", result.actionResults?.length);
79
77
  }
80
78
  ```
81
79
 
@@ -97,190 +95,266 @@ Key architectural concepts covered include:
97
95
  ### Basic Agent Implementation
98
96
 
99
97
  ```typescript
100
- import { BaseAgent } from '@memberjunction/ai-agents';
101
- import { Metadata } from '@memberjunction/core';
102
- import { AIAgentEntity } from '@memberjunction/core-entities';
103
-
104
- // Load agent metadata from database
105
- const md = new Metadata();
106
- const agentEntity = await md.GetEntityObject<AIAgentEntity>('AI Agents');
107
- await agentEntity.Load('Customer Support Agent');
108
-
109
- // Create agent instance
110
- const agent = new CustomerSupportAgent(agentEntity);
111
- await agent.initialize();
112
-
113
- // Execute agent with context
114
- const result = await agent.execute({
115
- conversationId: 'conv-123',
116
- messages: [
98
+ import { GetAgentFactory } from '@memberjunction/ai-agents';
99
+ import { AIEngine } from '@memberjunction/aiengine';
100
+ import { AgentRunner } from '@memberjunction/ai-agents';
101
+ import { UserInfo } from '@memberjunction/core';
102
+
103
+ // Initialize AI Engine to access agents and types
104
+ await AIEngine.Instance.Config(false, contextUser);
105
+
106
+ // Get agent factory and create agents
107
+ const factory = GetAgentFactory();
108
+ const baseAgent = await factory.CreateAgent('Customer Support', null, contextUser);
109
+ const conductorAgent = await factory.CreateAgent('Conductor', null, contextUser);
110
+
111
+ // Create and run with separation of concerns architecture
112
+ const runner = new AgentRunner(conductorAgent, contextUser);
113
+ const result = await runner.Run({
114
+ agent: baseAgent,
115
+ goal: 'Help customer with their order',
116
+ data: {
117
+ customerQuery: 'I need help with my order',
118
+ customerId: 'cust-123'
119
+ },
120
+ conversationMessages: [
117
121
  { role: 'user', content: 'I need help with my order' }
118
- ],
119
- metadata: {
120
- userId: 'user-456',
121
- sessionId: 'session-789'
122
- }
122
+ ]
123
123
  });
124
124
 
125
- console.log(result.response);
125
+ if (result.success) {
126
+ console.log('Task completed:', result.finalDecision?.finalResponse);
127
+ console.log('Execution summary:', result.metadata);
128
+ }
126
129
  ```
127
130
 
128
131
  ### Hierarchical Agent Composition
129
132
 
130
133
  ```typescript
131
- import { BaseAgent, ConductorAgent } from '@memberjunction/ai-agents';
132
-
133
- // Create a conductor agent that manages other agents
134
- class CustomerServiceConductor extends ConductorAgent {
135
- async routeToSubAgent(context: AgentContext): Promise<string> {
136
- // Analyze context to determine which sub-agent to use
137
- const intent = await this.analyzeIntent(context);
138
-
139
- switch(intent.category) {
140
- case 'billing':
141
- return 'BillingAgent';
142
- case 'technical':
143
- return 'TechnicalSupportAgent';
144
- case 'general':
145
- return 'GeneralInquiryAgent';
146
- default:
147
- return 'DefaultAgent';
134
+ import { GetAgentFactory, AgentRunner } from '@memberjunction/ai-agents';
135
+
136
+ // Hierarchical agents are handled through conductor decision-making
137
+ // Parent agents delegate to child agents based on AI decisions
138
+
139
+ // Get factory and create hierarchical agents
140
+ const factory = GetAgentFactory();
141
+ const managerAgent = await factory.CreateAgent('Customer Service Manager', null, contextUser);
142
+ const conductorAgent = await factory.CreateAgent('Conductor', null, contextUser);
143
+
144
+ // Create runner and execute - conductor will make autonomous delegation decisions
145
+ const runner = new AgentRunner(conductorAgent, contextUser);
146
+ const result = await runner.Run({
147
+ agent: managerAgent,
148
+ goal: 'Resolve complex customer issue',
149
+ data: {
150
+ customerQuery: 'Complex billing and technical issue',
151
+ priority: 'high'
152
+ },
153
+ conversationMessages: [...],
154
+ onProgress: (progress) => {
155
+ if (progress.step === 'prompt_execution') {
156
+ console.log('Agent coordinating execution:', progress.metadata);
148
157
  }
149
158
  }
150
- }
151
-
152
- // Use the conductor
153
- const conductor = new CustomerServiceConductor(conductorEntity);
154
- await conductor.initialize();
155
-
156
- // Add child agents
157
- await conductor.addChildAgent(billingAgent);
158
- await conductor.addChildAgent(technicalAgent);
159
- await conductor.addChildAgent(generalAgent);
159
+ });
160
160
 
161
- // Execute - conductor will route to appropriate sub-agent
162
- const result = await conductor.execute(context);
161
+ // The conductor's decision history shows which sub-agents were chosen
162
+ result.decisionHistory?.forEach((decision, i) => {
163
+ console.log(`Decision ${i + 1}: ${decision.decision}`);
164
+ console.log(`Reasoning: ${decision.reasoning}`);
165
+ if (decision.executionPlan.length > 0) {
166
+ console.log('Execution plan:', decision.executionPlan);
167
+ }
168
+ });
163
169
  ```
164
170
 
165
171
  ### Context Management and Compression
166
172
 
167
173
  ```typescript
168
- import { BaseAgent } from '@memberjunction/ai-agents';
174
+ import { GetAgentFactory, AgentRunner } from '@memberjunction/ai-agents';
169
175
 
170
- class LongConversationAgent extends BaseAgent {
171
- async execute(context: AgentContext): Promise<AgentResult> {
172
- // Check if context needs compression
173
- if (context.messages.length > this.agentEntity.ContextCompressionMessageThreshold) {
174
- // Compress older messages while keeping recent ones
175
- context = await this.compressContext(context);
176
+ // Context compression is automatically handled by BaseAgent
177
+ // Configure compression through the agent entity properties
178
+
179
+ const factory = GetAgentFactory();
180
+ const longConversationAgent = AIEngine.Instance.Agents.find(a => {
181
+ return a.EnableContextCompression &&
182
+ a.ContextCompressionMessageThreshold === 50 &&
183
+ a.ContextCompressionMessageRetentionCount === 10;
184
+ });
185
+
186
+ const baseAgent = factory.CreateAgentFromEntity(longConversationAgent, null, contextUser);
187
+ const conductorAgent = await factory.CreateAgent('Conductor', null, contextUser);
188
+ const runner = new AgentRunner(conductorAgent, contextUser);
189
+
190
+ // Execute with long conversation - compression happens automatically in BaseAgent
191
+ const longConversation = Array(60).fill(null).map((_, i) => ({
192
+ role: i % 2 === 0 ? 'user' : 'assistant',
193
+ content: `Message ${i + 1} in a very long conversation`
194
+ }));
195
+
196
+ const result = await runner.Run({
197
+ agent: baseAgent,
198
+ goal: 'Handle long conversation with compression',
199
+ conversationMessages: longConversation,
200
+ onProgress: (progress) => {
201
+ if (progress.step === 'prompt_execution') {
202
+ console.log('Processing context (may include compression):', progress.message);
176
203
  }
177
-
178
- // Continue with execution
179
- return super.execute(context);
180
204
  }
181
-
182
- private async compressContext(context: AgentContext): Promise<AgentContext> {
183
- // Use configured compression prompt
184
- const compressionPrompt = await this.getCompressionPrompt();
185
- const compressed = await compressionPrompt.execute({
186
- messages: context.messages.slice(0, -this.agentEntity.ContextCompressionMessageRetentionCount)
187
- });
188
-
189
- // Return new context with compressed history
190
- return {
191
- ...context,
192
- messages: [
193
- { role: 'system', content: compressed.summary },
194
- ...context.messages.slice(-this.agentEntity.ContextCompressionMessageRetentionCount)
195
- ]
196
- };
197
- }
198
- }
205
+ });
206
+
207
+ // Compression is applied automatically by BaseAgent based on agent configuration
208
+ // The agent run record tracks the compression activity
199
209
  ```
200
210
 
201
211
  ## API Reference
202
212
 
203
- ### BaseAgent Class
213
+ ### AgentRunner Class
204
214
 
205
- The foundation class for all AI agents.
215
+ The core coordination engine for orchestrating BaseAgent and ConductorAgent interactions.
206
216
 
207
217
  #### Constructor
208
218
  ```typescript
209
- constructor(agentEntity?: AIAgentEntity)
219
+ constructor(conductor: ConductorAgent, contextUser: UserInfo)
210
220
  ```
211
221
 
212
- #### Properties
213
-
214
- | Property | Type | Description |
215
- |----------|------|-------------|
216
- | `agentEntity` | `AIAgentEntity` | The database entity containing agent configuration |
217
- | `isInitialized` | `boolean` | Whether the agent has been initialized |
218
- | `actions` | `AIAgentActionEntity[]` | Available actions for this agent |
219
- | `notes` | `AIAgentNoteEntity[]` | Learning notes accumulated by the agent |
222
+ **Parameters:**
223
+ - `conductor: ConductorAgent` - The conductor agent that makes orchestration decisions
224
+ - `contextUser: UserInfo` - User context for authentication and permissions
220
225
 
221
226
  #### Methods
222
227
 
223
- ##### `initialize(): Promise<void>`
224
- Initializes the agent, loading configuration and preparing for execution.
228
+ ##### `Run(params: AgentRunnerParams): Promise<AgentRunnerResult>`
229
+ Runs the agent using the BaseAgent + ConductorAgent separation of concerns pattern.
225
230
 
226
- ##### `execute(context: AgentContext): Promise<AgentResult>`
227
- Executes the agent with the provided context.
231
+ **Parameters:**
232
+ - `params: AgentRunnerParams` - Execution parameters including base agent, goal, and configuration
233
+
234
+ **Returns:** `Promise<AgentRunnerResult>` - Enhanced execution result with decision history and outcomes
235
+
236
+ **Key Features:**
237
+ - Clean separation between execution and decision-making
238
+ - Iterative BaseAgent → ConductorAgent → Action execution pattern
239
+ - Mixed action and sub-agent execution with proper ordering
240
+ - Progress tracking and cancellation support
241
+ - Comprehensive execution step tracking
242
+
243
+ ### BaseAgent Class
244
+
245
+ The domain execution engine that focuses solely on executing agent-specific prompts.
246
+
247
+ #### Constructor
248
+ ```typescript
249
+ constructor(agent: AIAgentEntityExtended, factory: IAgentFactory, contextUser: UserInfo, promptRunner?: AIPromptRunner)
250
+ ```
228
251
 
229
252
  **Parameters:**
230
- - `context: AgentContext` - The execution context containing conversation history and metadata
253
+ - `agent: AIAgentEntityExtended` - The agent entity definition
254
+ - `factory: IAgentFactory` - Factory for creating additional agent instances
255
+ - `contextUser: UserInfo` - User context for authentication and permissions
256
+ - `promptRunner: AIPromptRunner` - Optional prompt runner instance
231
257
 
232
- **Returns:** `Promise<AgentResult>` - The agent's response and metadata
258
+ #### Methods
233
259
 
234
- ##### `handleAction(actionName: string, params: any): Promise<any>`
235
- Handles agent-specific actions.
260
+ ##### `Execute(params: AgentExecutionParams): Promise<AgentExecutionResult>`
261
+ Executes the agent's specific prompts and returns the result.
236
262
 
237
263
  **Parameters:**
238
- - `actionName: string` - The name of the action to execute
239
- - `params: any` - Parameters for the action
264
+ - `params: AgentExecutionParams` - Execution parameters including context, data, and callbacks
265
+
266
+ **Returns:** `Promise<AgentExecutionResult>` - The execution result
240
267
 
241
- **Returns:** `Promise<any>` - The action result
268
+ **Key Features:**
269
+ - Single responsibility: execute agent-specific prompts only
270
+ - Conversation context management and compression
271
+ - Progress monitoring and streaming response support
272
+ - Cancellation support with graceful cleanup
242
273
 
243
- ##### `addNote(content: string, type: string): Promise<void>`
244
- Adds a learning note for the agent.
274
+ ### ConductorAgent Class
275
+
276
+ The decision-making engine that analyzes context and makes orchestration decisions.
277
+
278
+ #### Constructor
279
+ ```typescript
280
+ constructor(agent: AIAgentEntityExtended, factory: IAgentFactory, contextUser: UserInfo)
281
+ ```
282
+
283
+ #### Methods
284
+
285
+ ##### `MakeDecision(decisionInput: ConductorDecisionInput): Promise<ConductorDecisionResponse>`
286
+ Makes an autonomous decision about what to do next based on current context.
245
287
 
246
288
  **Parameters:**
247
- - `content: string` - The note content
248
- - `type: string` - The type of note (e.g., 'learning', 'error', 'improvement')
289
+ - `decisionInput: ConductorDecisionInput` - Complete context for decision-making
290
+
291
+ **Returns:** `Promise<ConductorDecisionResponse>` - Structured decision response
292
+
293
+ ##### `executeAction(actionId: string, parameters: Record<string, unknown>): Promise<ActionResult>`
294
+ Executes an action using the ActionEngine.
295
+
296
+ ##### `executeSubAgent(subAgentId: string, parameters: Record<string, unknown>, parentContext?: Record<string, unknown>): Promise<AgentExecutionResult>`
297
+ Executes a sub-agent with the provided parameters.
249
298
 
250
299
  ### Types and Interfaces
251
300
 
252
- #### AgentContext
301
+ #### AgentRunnerParams
253
302
  ```typescript
254
- interface AgentContext {
255
- conversationId: string;
256
- messages: Message[];
257
- metadata?: Record<string, any>;
258
- parentContext?: AgentContext;
303
+ interface AgentRunnerParams extends AgentExecutionParams {
304
+ agent: BaseAgent;
305
+ maxIterations?: number;
306
+ goal?: string;
307
+ enableDetailedLogging?: boolean;
259
308
  }
260
309
  ```
261
310
 
262
- #### AgentResult
311
+ #### AgentRunnerResult
263
312
  ```typescript
264
- interface AgentResult {
265
- response: string;
266
- success: boolean;
313
+ interface AgentRunnerResult extends AgentExecutionResult {
314
+ decisionHistory?: ConductorDecisionResponse[];
315
+ actionResults?: ActionResult[];
316
+ finalDecision?: ConductorDecisionResponse;
317
+ iterationCount?: number;
318
+ executionSteps?: ExecutionHistoryItem[];
319
+ }
320
+ ```
321
+
322
+ #### ConductorDecisionResponse
323
+ ```typescript
324
+ interface ConductorDecisionResponse {
325
+ decision: ConductorDecisionType;
326
+ reasoning: string;
327
+ executionPlan: ExecutionStep[];
328
+ isTaskComplete: boolean;
329
+ finalResponse?: string;
330
+ confidence: number;
267
331
  metadata?: {
268
- tokensUsed?: number;
269
- executionTimeMs?: number;
270
- modelUsed?: string;
271
- childAgentResults?: AgentResult[];
332
+ estimatedDuration?: number;
333
+ riskLevel?: 'low' | 'medium' | 'high';
334
+ failureStrategy?: string;
272
335
  };
273
- error?: string;
274
336
  }
275
337
  ```
276
338
 
277
- #### Message
339
+ #### ExecutionStep
340
+ ```typescript
341
+ interface ExecutionStep {
342
+ type: 'action' | 'subagent';
343
+ targetId: string;
344
+ parameters?: Record<string, unknown>;
345
+ executionOrder: number;
346
+ allowParallel?: boolean;
347
+ description?: string;
348
+ }
349
+ ```
350
+
351
+ #### AgentProgressUpdate
278
352
  ```typescript
279
- interface Message {
280
- role: 'system' | 'user' | 'assistant';
281
- content: string;
282
- timestamp?: Date;
283
- metadata?: Record<string, any>;
353
+ interface AgentProgressUpdate {
354
+ step: 'initialization' | 'prompt_execution' | 'completion';
355
+ percentage: number;
356
+ message: string;
357
+ metadata?: Record<string, unknown>;
284
358
  }
285
359
  ```
286
360
 
@@ -441,25 +515,69 @@ try {
441
515
 
442
516
  ## Development Status
443
517
 
444
- 🚧 **Under Active Development** - This package is currently being built and will house all functionality for the MJ AI Agent framework. The `BaseAgent` class and core infrastructure are being implemented to provide the foundation for all agentic execution work in the MemberJunction ecosystem.
518
+ ✅ **Core Framework Complete** - The MJ AI Agent framework now provides a comprehensive, metadata-driven system for creating and executing AI agents.
445
519
 
446
520
  ### Current Implementation Status
447
521
 
448
522
  - ✅ Package structure and configuration
449
- - 🚧 BaseAgent class implementation (in progress)
450
- - 📋 ConductorAgent for hierarchical composition (planned)
451
- - 📋 Context management and compression (planned)
452
- - 📋 Action framework integration (planned)
453
- - 📋 Learning and note system (planned)
454
- - 📋 Execution logging and analytics (planned)
455
-
456
- ### Roadmap
457
-
458
- 1. **Phase 1**: Core BaseAgent implementation with basic execution
459
- 2. **Phase 2**: Hierarchical agent composition and conductor pattern
460
- 3. **Phase 3**: Advanced context management and compression
461
- 4. **Phase 4**: Action framework and extensibility
462
- 5. **Phase 5**: Learning system and performance optimization
523
+ - ✅ BaseAgent class implementation with full metadata-driven execution
524
+ - ✅ AgentFactory for dynamic agent instantiation
525
+ - ✅ Hierarchical agent composition with parent-child relationships
526
+ - ✅ Context management and compression
527
+ - ✅ AI Prompt system integration
528
+ - ✅ Progress tracking and streaming support
529
+ - ✅ ClassFactory integration for extensible agent types
530
+ - ✅ Comprehensive error handling and cancellation support
531
+ - ✅ Example agents and usage patterns
532
+
533
+ ### Architecture Highlights
534
+
535
+ 1. **Metadata-Driven**: Agents configured through database entities (AIAgent, AIAgentPrompt, etc.)
536
+ 2. **Hierarchical Composition**: Support for conductor patterns with child agents
537
+ 3. **Intelligent Context Management**: Automatic compression and filtering
538
+ 4. **Advanced Prompt Integration**: Full integration with AI Prompt system
539
+ 5. **Extensible Design**: Easy custom agent creation through class registration
540
+
541
+ ### Current Architecture (Implemented)
542
+
543
+ The framework provides a separation of concerns architecture with specialized responsibilities:
544
+
545
+ ```typescript
546
+ // Get factory and create specialized agents
547
+ const factory = GetAgentFactory();
548
+ const baseAgent = await factory.CreateAgent("CustomerSupport", null, contextUser);
549
+ const conductorAgent = await factory.CreateAgent("Conductor", null, contextUser);
550
+
551
+ // Execute with clean separation of concerns
552
+ const runner = new AgentRunner(conductorAgent, contextUser);
553
+ const result = await runner.Run({
554
+ agent: baseAgent,
555
+ goal: "Help customer with their issue",
556
+ data: { customerName: "John" },
557
+ conversationMessages: [...],
558
+ onProgress: (progress) => console.log(progress),
559
+ cancellationToken: controller.signal
560
+ });
561
+
562
+ // BaseAgent handles domain execution, ConductorAgent makes decisions
563
+ // AgentRunner coordinates the interaction between them
564
+ ```
565
+
566
+ ### Hierarchical Prompt Integration
567
+
568
+ The framework integrates with the AI Prompts system through hierarchical prompt execution:
569
+
570
+ ```typescript
571
+ // Agent types define system prompts for behavioral characteristics
572
+ AIAgentType.SystemPromptID -> AIPrompt (system template)
573
+
574
+ // Agent-specific prompts provide domain logic
575
+ AIAgent -> AIAgentPrompt -> AIPrompt (agent-specific instructions)
576
+
577
+ // Runtime: Hierarchical execution with parent-child relationships
578
+ // Parent prompts specify children via childPrompts array
579
+ // Depth-first traversal with parallel execution at each level
580
+ ```
463
581
 
464
582
  ## License
465
583
 
@@ -0,0 +1,19 @@
1
+ import { UserInfo } from '@memberjunction/core';
2
+ import { AIAgentEntityExtended } from '@memberjunction/core-entities';
3
+ import { BaseAgent, IAgentFactory } from './base-agent';
4
+ import { ConductorAgent } from './conductor-agent';
5
+ import { AgentRunner } from './agent-runner';
6
+ export declare class AgentFactory implements IAgentFactory {
7
+ private _metadata;
8
+ constructor();
9
+ CreateAgent(agentName: string, key?: string, contextUser?: UserInfo, ...additionalParams: any[]): Promise<BaseAgent | null>;
10
+ CreateAgentFromEntity(agentEntity: AIAgentEntityExtended, key?: string, ...additionalParams: any[]): BaseAgent;
11
+ GetAvailableAgents(contextUser?: UserInfo): Promise<AIAgentEntityExtended[]>;
12
+ AgentExists(agentName: string, contextUser?: UserInfo): Promise<boolean>;
13
+ GetAgentEntity(agentName: string, contextUser: UserInfo): Promise<AIAgentEntityExtended | null>;
14
+ GetConductorAgent(contextUser: UserInfo): Promise<ConductorAgent>;
15
+ GetAgentRunner(contextUser: UserInfo, key?: string): Promise<AgentRunner>;
16
+ }
17
+ export declare function GetAgentFactory(): AgentFactory;
18
+ export declare function LoadAgentFactory(): void;
19
+ //# sourceMappingURL=agent-factory.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"agent-factory.d.ts","sourceRoot":"","sources":["../src/agent-factory.ts"],"names":[],"mappings":"AAAA,OAAO,EAAsB,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAEpE,OAAO,EAAE,qBAAqB,EAAE,MAAM,+BAA+B,CAAC;AAEtE,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,MAAM,cAAc,CAAC;AACxD,OAAO,EAAE,cAAc,EAAwB,MAAM,mBAAmB,CAAC;AACzE,OAAO,EAAE,WAAW,EAAE,MAAM,gBAAgB,CAAC;AA0B7C,qBAAa,YAAa,YAAW,aAAa;IAChD,OAAO,CAAC,SAAS,CAAW;;IAoBf,WAAW,CACtB,SAAS,EAAE,MAAM,EACjB,GAAG,CAAC,EAAE,MAAM,EACZ,WAAW,CAAC,EAAE,QAAQ,EACtB,GAAG,gBAAgB,EAAE,GAAG,EAAE,GACzB,OAAO,CAAC,SAAS,GAAG,IAAI,CAAC;IAiDrB,qBAAqB,CAC1B,WAAW,EAAE,qBAAqB,EAClC,GAAG,CAAC,EAAE,MAAM,EACZ,GAAG,gBAAgB,EAAE,GAAG,EAAE,GACzB,SAAS;IAgCC,kBAAkB,CAAC,WAAW,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,qBAAqB,EAAE,CAAC;IAkB5E,WAAW,CAAC,SAAS,EAAE,MAAM,EAAE,WAAW,CAAC,EAAE,QAAQ,GAAG,OAAO,CAAC,OAAO,CAAC;IAsBxE,cAAc,CACzB,SAAS,EAAE,MAAM,EACjB,WAAW,EAAE,QAAQ,GACpB,OAAO,CAAC,qBAAqB,GAAG,IAAI,CAAC;IAqB3B,iBAAiB,CAC5B,WAAW,EAAE,QAAQ,GACpB,OAAO,CAAC,cAAc,CAAC;IAwCb,cAAc,CACzB,WAAW,EAAE,QAAQ,EACrB,GAAG,CAAC,EAAE,MAAM,GACX,OAAO,CAAC,WAAW,CAAC;CAqBxB;AASD,wBAAgB,eAAe,IAAI,YAAY,CAO9C;AAED,wBAAgB,gBAAgB,SAE/B"}