@@ -60,6 +60,7 @@ import fs from "fs";
60
60
import path from "path" ;
61
61
import { fileURLToPath } from "url" ;
62
62
import yargs from "yargs" ;
63
+ import net from "net" ;
63
64
64
65
const __filename = fileURLToPath ( import . meta. url ) ; // get the resolved path to the file
65
66
const __dirname = path . dirname ( __filename ) ; // get the name of the directory
@@ -692,13 +693,30 @@ async function startAgent(
692
693
}
693
694
}
694
695
696
+ const checkPortAvailable = ( port : number ) : Promise < boolean > => {
697
+ return new Promise ( ( resolve ) => {
698
+ const server = net . createServer ( ) ;
699
+
700
+ server . once ( "error" , ( err : NodeJS . ErrnoException ) => {
701
+ if ( err . code === "EADDRINUSE" ) {
702
+ resolve ( false ) ;
703
+ }
704
+ } ) ;
705
+
706
+ server . once ( "listening" , ( ) => {
707
+ server . close ( ) ;
708
+ resolve ( true ) ;
709
+ } ) ;
710
+
711
+ server . listen ( port ) ;
712
+ } ) ;
713
+ } ;
714
+
695
715
const startAgents = async ( ) => {
696
716
const directClient = new DirectClient ( ) ;
697
- const serverPort = parseInt ( settings . SERVER_PORT || "3000" ) ;
717
+ let serverPort = parseInt ( settings . SERVER_PORT || "3000" ) ;
698
718
const args = parseArguments ( ) ;
699
-
700
719
let charactersArg = args . characters || args . character ;
701
-
702
720
let characters = [ defaultCharacter ] ;
703
721
704
722
if ( charactersArg ) {
@@ -713,19 +731,32 @@ const startAgents = async () => {
713
731
elizaLogger . error ( "Error starting agents:" , error ) ;
714
732
}
715
733
734
+ // Find available port
735
+ while ( ! ( await checkPortAvailable ( serverPort ) ) ) {
736
+ elizaLogger . warn (
737
+ `Port ${ serverPort } is in use, trying ${ serverPort + 1 } `
738
+ ) ;
739
+ serverPort ++ ;
740
+ }
741
+
716
742
// upload some agent functionality into directClient
717
743
directClient . startAgent = async ( character : Character ) => {
718
744
// wrap it so we don't have to inject directClient later
719
745
return startAgent ( character , directClient ) ;
720
746
} ;
747
+
721
748
directClient . start ( serverPort ) ;
722
749
750
+ if ( serverPort !== parseInt ( settings . SERVER_PORT || "3000" ) ) {
751
+ elizaLogger . log ( `Server started on alternate port ${ serverPort } ` ) ;
752
+ }
753
+
723
754
elizaLogger . log (
724
755
"Run `pnpm start:client` to start the client and visit the outputted URL (http://localhost:5173) to chat with your agents"
725
756
) ;
726
757
} ;
727
758
728
759
startAgents ( ) . catch ( ( error ) => {
729
760
elizaLogger . error ( "Unhandled error in startAgents:" , error ) ;
730
- process . exit ( 1 ) ; // Exit the process after logging
761
+ process . exit ( 1 ) ;
731
762
} ) ;
0 commit comments