Repository: ai16z/eliza
File: packages/cli/src/commands/start/index.ts (TypeScript)

Code before:
              for (const agent of project.agents) {
                if (agent.character) {
                  logger.info(`Loaded character: ${agent.character.name}`);
                }
              }
            }
          }
        } catch (e) {
          logger.debug({ error: e }, 'Failed to load project agents, will use default character:');
        }
      }

      // Use AgentServer from server package
      const moduleLoader = getModuleLoader();
      const { AgentServer } = await moduleLoader.load('@elizaos/server');

      const server = new AgentServer();

      // Initialize server with database configuration
      await server.initialize({
        dataDir: process.env.PGLITE_DATA_DIR,
        postgresUrl: process.env.POSTGRES_URL,
      });

      // Start HTTP server
      await server.start(options.port || parseInt(process.env.SERVER_PORT ?? '') || 3000);

      // Handle project agents with their init functions
      if (projectAgents && projectAgents.length > 0) {
        // Phase 1: Start all agents first (collect runtimes)
        const runtimes: IAgentRuntime[] = [];
        const agentRuntimeMap = new Map<ProjectAgent, IAgentRuntime>();

        for (const projectAgent of projectAgents) {
          try {
            // Validate and safely access the agent's plugins array
            const agentPlugins = Array.isArray(projectAgent.plugins) ? projectAgent.plugins : [];

            const [runtime] = await server.startAgents([projectAgent.character], agentPlugins);

            if (runtime) {
              runtimes.push(runtime);
              agentRuntimeMap.set(projectAgent, runtime);
              logger.info(
                `Started agent: ${projectAgent.character.name || 'Unnamed'} (${runtime.agentId})`
              );
            } else {
              logger.error(
                `Failed to start agent: ${projectAgent.character.name || 'Unnamed'} - runtime is undefined`
              );
            }

Review comment (suggestion):
```suggestion
      const port = options.port || parseInt(process.env.SERVER_PORT || '3000', 10);
      await server.start(port);
```

Code after:
              for (const agent of project.agents) {
                if (agent.character) {
                  logger.info(`Loaded character: ${agent.character.name}`);
                }
              }
            }
          }
        } catch (e) {
          logger.debug({ error: e }, 'Failed to load project agents, will use default character:');
        }
      }

      // Use AgentServer from server package
      const moduleLoader = getModuleLoader();
      const { AgentServer } = await moduleLoader.load('@elizaos/server');

      const server = new AgentServer();

      // Initialize server with database configuration
      await server.initialize({
        dataDir: process.env.PGLITE_DATA_DIR,
        postgresUrl: process.env.POSTGRES_URL,
      });

      // Start HTTP server with robust port resolution
      let port: number;
      if (options.port !== undefined) {
        // Already validated by Commander using validatePort
        port = options.port;
      } else {
        const envPort = process.env.SERVER_PORT;
        if (envPort) {
          try {
            port = validatePort(envPort);
          } catch {
            logger.warn(`Invalid SERVER_PORT "${envPort}", falling back to 3000`);
            port = 3000;
          }
        } else {
          port = 3000;
        }
      }
      await server.start(port);

      // Handle project agents with their init functions
      if (projectAgents && projectAgents.length > 0) {
        // Phase 1: Start all agents first (collect runtimes)
        const runtimes: IAgentRuntime[] = [];
        const agentRuntimeMap = new Map<ProjectAgent, IAgentRuntime>();

        for (const projectAgent of projectAgents) {