@memberjunction/ai-agent-manager 2.111.1 → 2.112.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.
@@ -1,7 +1,7 @@
1
1
  import { BaseAgent } from '@memberjunction/ai-agents';
2
2
  import { ExecuteAgentParams, AgentConfiguration, BaseAgentNextStep, AgentSpec } from '@memberjunction/ai-core-plus';
3
3
  import { RegisterClass } from '@memberjunction/global';
4
- import { Metadata } from '@memberjunction/core';
4
+ import { Metadata } from '@memberjunction/global';
5
5
  import { AIAgentRunStepEntityExtended } from '@memberjunction/core-entities';
6
6
  import { AgentSpecSync } from '../agent-spec-sync';
7
7
  import { TemplateEngineServer } from '@memberjunction/templates';
@@ -26,137 +26,128 @@ import { AIEngineBase } from '@memberjunction/ai-engine-base';
26
26
  */
27
27
  @RegisterClass(BaseAgent, 'AgentBuilderAgent')
28
28
  export class AgentBuilderAgent extends BaseAgent {
29
-
30
- /**
31
- * Override executeAgentInternal to run code instead of chat loop.
32
- *
33
- * Directly creates the AI Agent Run Step with mutations from AgentSpecSync.
34
- */
35
- protected override async executeAgentInternal<P = any>(
36
- params: ExecuteAgentParams<P>,
37
- _config: AgentConfiguration
38
- ): Promise<{ finalStep: BaseAgentNextStep<P>; stepCount: number }> {
39
-
40
- console.log('🔨 Builder Agent: Starting agent persistence...');
41
-
42
- try {
43
- // Validate payload
44
- const agentSpec = params.payload as AgentSpec;
45
- if (!agentSpec) {
46
- throw new Error('No AgentSpec found in payload - ensure Architect Agent provided valid AgentSpec');
47
- }
48
- if (!agentSpec.Name) {
49
- throw new Error('AgentSpec is missing required Name field');
50
- }
51
-
52
- console.log(`🔨 Builder Agent: Creating agent "${agentSpec.Name}"...`);
53
-
54
- // Create AgentSpecSync and save to database
55
- const specSync = new AgentSpecSync(agentSpec, params.contextUser);
56
- specSync.markDirty();
57
-
58
- // If updating existing agent (ID exists), mark as loaded so delete logic runs
59
- if (agentSpec.ID && agentSpec.ID !== '') {
60
- specSync.markLoaded();
61
- }
62
-
63
- const result = await specSync.SaveToDatabase();
64
-
65
- if (!result.success) {
66
- throw new Error('AgentSpecSync.SaveToDatabase() returned success=false');
67
- }
68
-
69
- console.log(`✅ Builder Agent: Successfully created agent with ID: ${result.agentId}`);
70
-
71
- // Refresh metadata and template caches
72
- console.log('🔄 Builder Agent: Refreshing metadata and template caches...');
73
- const md = new Metadata();
74
- await md.Refresh();
75
-
76
- const templateEngine = new TemplateEngineServer();
77
- await templateEngine.Config(true, params.contextUser);
78
- console.log('✅ Builder Agent: Metadata and template caches refreshed');
79
-
80
- // Refresh AIEngine cache so newly created agents are immediately available
81
- const aiEngine = AIEngineBase.Instance;
82
- await aiEngine.Config(true, params.contextUser);
83
- console.log('✅ Builder Agent: AIEngine cache refreshed');
84
-
85
- // Create AI Agent Run Step record directly
86
- const agentRunId = params.parentRun?.ID || 'unknown';
87
- const stepEntity = await md.GetEntityObject<AIAgentRunStepEntityExtended>(
88
- 'MJ: AI Agent Run Steps',
89
- params.contextUser
90
- );
91
-
92
- stepEntity.AgentRunID = agentRunId;
93
- stepEntity.StepNumber = 2; // Validation is step 1, this is step 2
94
- stepEntity.StepType = 'Decision';
95
- stepEntity.StepName = 'Sync Agent Spec';
96
- stepEntity.Status = 'Completed';
97
- stepEntity.Success = true;
98
- stepEntity.StartedAt = new Date();
99
- stepEntity.CompletedAt = new Date();
100
-
101
- // InputData = Full AgentSpec
102
- stepEntity.InputData = JSON.stringify(agentSpec, null, 2);
103
- stepEntity.PayloadAtStart = JSON.stringify(params.payload);
104
-
105
- // OutputData = Mutations array
106
- stepEntity.OutputData = JSON.stringify(result.mutations, null, 2);
107
- stepEntity.PayloadAtEnd = stepEntity.PayloadAtStart;
108
-
109
- await stepEntity.Save();
110
- console.log(`✅ Builder Agent: Created AI Agent Run Step with ID: ${stepEntity.ID}`);
111
-
112
- // Return success
113
- const updatedSpec = { ...agentSpec, ID: result.agentId };
114
- return {
115
- finalStep: {
116
- terminate: true,
117
- step: 'Success',
118
- reasoning: `Successfully created agent "${agentSpec.Name}" with ID: ${result.agentId}`,
119
- newPayload: updatedSpec as P
120
- },
121
- stepCount: 2
122
- };
123
-
124
- } catch (error: any) {
125
- console.error('❌ Builder Agent: Failed to create agent:', error);
126
-
127
- // Create failed AI Agent Run Step
128
- const agentRunId = params.parentRun?.ID || 'unknown';
129
- const md = new Metadata();
130
- const stepEntity = await md.GetEntityObject<AIAgentRunStepEntityExtended>(
131
- 'MJ: AI Agent Run Steps',
132
- params.contextUser
133
- );
134
-
135
- stepEntity.AgentRunID = agentRunId;
136
- stepEntity.StepNumber = 2;
137
- stepEntity.StepType = 'Decision';
138
- stepEntity.StepName = 'Sync Agent Spec';
139
- stepEntity.Status = 'Failed';
140
- stepEntity.Success = false;
141
- stepEntity.StartedAt = new Date();
142
- stepEntity.CompletedAt = new Date();
143
- stepEntity.ErrorMessage = error?.message || String(error);
144
-
145
- stepEntity.InputData = JSON.stringify(params.payload, null, 2);
146
- stepEntity.PayloadAtStart = JSON.stringify(params.payload);
147
- stepEntity.OutputData = JSON.stringify({ error: error?.message || String(error) });
148
- stepEntity.PayloadAtEnd = stepEntity.PayloadAtStart;
149
-
150
- await stepEntity.Save();
151
-
152
- return {
153
- finalStep: {
154
- terminate: true,
155
- step: 'Failed',
156
- reasoning: `Failed to create agent: ${error?.message || String(error)}`
157
- },
158
- stepCount: 2
159
- };
160
- }
29
+ /**
30
+ * Override executeAgentInternal to run code instead of chat loop.
31
+ *
32
+ * Directly creates the AI Agent Run Step with mutations from AgentSpecSync.
33
+ */
34
+ protected override async executeAgentInternal<P = any>(
35
+ params: ExecuteAgentParams<P>,
36
+ _config: AgentConfiguration
37
+ ): Promise<{ finalStep: BaseAgentNextStep<P>; stepCount: number }> {
38
+ console.log('🔨 Builder Agent: Starting agent persistence...');
39
+
40
+ try {
41
+ // Validate payload
42
+ const agentSpec = params.payload as AgentSpec;
43
+ if (!agentSpec) {
44
+ throw new Error('No AgentSpec found in payload - ensure Architect Agent provided valid AgentSpec');
45
+ }
46
+ if (!agentSpec.Name) {
47
+ throw new Error('AgentSpec is missing required Name field');
48
+ }
49
+
50
+ console.log(`🔨 Builder Agent: Creating agent "${agentSpec.Name}"...`);
51
+
52
+ // Create AgentSpecSync and save to database
53
+ const specSync = new AgentSpecSync(agentSpec, params.contextUser);
54
+ specSync.markDirty();
55
+
56
+ // If updating existing agent (ID exists), mark as loaded so delete logic runs
57
+ if (agentSpec.ID && agentSpec.ID !== '') {
58
+ specSync.markLoaded();
59
+ }
60
+
61
+ const result = await specSync.SaveToDatabase();
62
+
63
+ if (!result.success) {
64
+ throw new Error('AgentSpecSync.SaveToDatabase() returned success=false');
65
+ }
66
+
67
+ console.log(`✅ Builder Agent: Successfully created agent with ID: ${result.agentId}`);
68
+
69
+ // Refresh metadata and template caches
70
+ console.log('🔄 Builder Agent: Refreshing metadata and template caches...');
71
+ const md = new Metadata();
72
+ await md.Refresh();
73
+
74
+ const templateEngine = new TemplateEngineServer();
75
+ await templateEngine.Config(true, params.contextUser);
76
+ console.log('✅ Builder Agent: Metadata and template caches refreshed');
77
+
78
+ // Refresh AIEngine cache so newly created agents are immediately available
79
+ const aiEngine = AIEngineBase.Instance;
80
+ await aiEngine.Config(true, params.contextUser);
81
+ console.log('✅ Builder Agent: AIEngine cache refreshed');
82
+
83
+ // Create AI Agent Run Step record directly
84
+ const agentRunId = params.parentRun?.ID || 'unknown';
85
+ const stepEntity = await md.GetEntityObject<AIAgentRunStepEntityExtended>('MJ: AI Agent Run Steps', params.contextUser);
86
+
87
+ stepEntity.AgentRunID = agentRunId;
88
+ stepEntity.StepNumber = 2; // Validation is step 1, this is step 2
89
+ stepEntity.StepType = 'Decision';
90
+ stepEntity.StepName = 'Sync Agent Spec';
91
+ stepEntity.Status = 'Completed';
92
+ stepEntity.Success = true;
93
+ stepEntity.StartedAt = new Date();
94
+ stepEntity.CompletedAt = new Date();
95
+
96
+ // InputData = Full AgentSpec
97
+ stepEntity.InputData = JSON.stringify(agentSpec, null, 2);
98
+ stepEntity.PayloadAtStart = JSON.stringify(params.payload);
99
+
100
+ // OutputData = Mutations array
101
+ stepEntity.OutputData = JSON.stringify(result.mutations, null, 2);
102
+ stepEntity.PayloadAtEnd = stepEntity.PayloadAtStart;
103
+
104
+ await stepEntity.Save();
105
+ console.log(`✅ Builder Agent: Created AI Agent Run Step with ID: ${stepEntity.ID}`);
106
+
107
+ // Return success
108
+ const updatedSpec = { ...agentSpec, ID: result.agentId };
109
+ return {
110
+ finalStep: {
111
+ terminate: true,
112
+ step: 'Success',
113
+ reasoning: `Successfully created agent "${agentSpec.Name}" with ID: ${result.agentId}`,
114
+ newPayload: updatedSpec as P,
115
+ },
116
+ stepCount: 2,
117
+ };
118
+ } catch (error: any) {
119
+ console.error('❌ Builder Agent: Failed to create agent:', error);
120
+
121
+ // Create failed AI Agent Run Step
122
+ const agentRunId = params.parentRun?.ID || 'unknown';
123
+ const md = new Metadata();
124
+ const stepEntity = await md.GetEntityObject<AIAgentRunStepEntityExtended>('MJ: AI Agent Run Steps', params.contextUser);
125
+
126
+ stepEntity.AgentRunID = agentRunId;
127
+ stepEntity.StepNumber = 2;
128
+ stepEntity.StepType = 'Decision';
129
+ stepEntity.StepName = 'Sync Agent Spec';
130
+ stepEntity.Status = 'Failed';
131
+ stepEntity.Success = false;
132
+ stepEntity.StartedAt = new Date();
133
+ stepEntity.CompletedAt = new Date();
134
+ stepEntity.ErrorMessage = error?.message || String(error);
135
+
136
+ stepEntity.InputData = JSON.stringify(params.payload, null, 2);
137
+ stepEntity.PayloadAtStart = JSON.stringify(params.payload);
138
+ stepEntity.OutputData = JSON.stringify({ error: error?.message || String(error) });
139
+ stepEntity.PayloadAtEnd = stepEntity.PayloadAtStart;
140
+
141
+ await stepEntity.Save();
142
+
143
+ return {
144
+ finalStep: {
145
+ terminate: true,
146
+ step: 'Failed',
147
+ reasoning: `Failed to create agent: ${error?.message || String(error)}`,
148
+ },
149
+ stepCount: 2,
150
+ };
161
151
  }
152
+ }
162
153
  }