aiexecode 1.0.88 → 1.0.89

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/index.js CHANGED
@@ -164,7 +164,7 @@ if (viewerMode) {
164
164
  console.log(chalk.green(`✓ Payload viewer is running`));
165
165
  console.log(chalk.yellow(`Press Ctrl+C to stop the server`));
166
166
  // Keep process alive
167
- await new Promise(() => {});
167
+ await new Promise(() => { });
168
168
  }
169
169
 
170
170
  // 전역 설정
@@ -175,7 +175,7 @@ process.app_custom.__dirname = dirname(fileURLToPath(import.meta.url));
175
175
  // (글로벌 설치 후 aiexecode 명령으로 실행 시에는 다른 경로에서 실행됨)
176
176
  const packageJsonPath = join(process.app_custom.__dirname, 'package.json');
177
177
  const isDevelopment = existsSync(packageJsonPath) &&
178
- process.app_custom.__dirname === dirname(fileURLToPath(import.meta.url));
178
+ process.app_custom.__dirname === dirname(fileURLToPath(import.meta.url));
179
179
  process.env.IS_DEVELOPMENT = isDevelopment ? 'true' : 'false';
180
180
 
181
181
  // Session ID 생성 함수 (16자리 hex)
@@ -307,19 +307,100 @@ if (!process.env.OPENAI_API_KEY) {
307
307
  process.exit(1);
308
308
  }
309
309
 
310
- // MCP Integration 초기화 (백그라운드에서 실행)
311
- let mcpIntegration = null;
312
- let mcpToolFunctions = {};
313
- let mcpToolSchemas = [];
310
+ // ========================================
311
+ // MCP Integration 초기화
312
+ // ========================================
313
+ // MCP (Model Context Protocol) 서버들과의 연결을 설정하고 사용 가능한 도구 목록을 준비
314
+ // 프로그램 시작 시 백그라운드에서 비동기로 실행되어 UI 로딩을 블로킹하지 않음
314
315
 
315
- // MCP 초기화를 백그라운드에서 실행하되 Promise만 저장 (이벤트는 UI 시작 후에 발생)
316
- const mcpInitPromise = initializeMCPIntegration(process.cwd()).then(integration => {
316
+ let mcpIntegration = null; // MCP Integration 인스턴스 (서버 관리 도구 실행)
317
+ let mcpToolFunctions = {}; // MCP 도구 실행 함수들 (toolName -> async function)
318
+ let mcpToolSchemas = []; // MCP 도구 스키마들 (AI 모델에 전달할 도구 정의)
319
+
320
+ // MCP 초기화를 백그라운드에서 실행
321
+ // Promise만 저장하고 실제 UI 이벤트는 UI 시작 후에 발생시킨다
322
+ const mcpInitPromise = initializeMCPIntegration().then(async integration => {
323
+ // 초기화 성공 시 결과 저장
317
324
  mcpIntegration = integration;
325
+
326
+ // MCP 도구 실행 함수들을 가져옴 (session.js에서 도구 실행 시 사용)
318
327
  mcpToolFunctions = integration ? integration.getToolFunctions() : {};
328
+
329
+ // MCP 도구 스키마들을 가져옴 (orchestrator.js에서 AI에게 전달)
319
330
  mcpToolSchemas = integration ? integration.getToolSchemas() : [];
320
331
 
332
+ // 초기화 결과 로깅
321
333
  if (integration) {
322
334
  const servers = integration.getConnectedServers();
335
+ const logLines = [];
336
+
337
+ logLines.push('');
338
+ logLines.push(`MCP INTEGRATION COMPLETE`);
339
+ logLines.push(`Timestamp: ${new Date().toISOString()}`);
340
+ logLines.push(`Total Servers: ${servers.length}`);
341
+ logLines.push(`Total Tools: ${Object.keys(mcpToolFunctions).length}`);
342
+ logLines.push(`Total Schemas: ${mcpToolSchemas.length}`);
343
+ logLines.push('');
344
+
345
+ // MCP 서버별 상세 정보
346
+ if (servers.length > 0) {
347
+ logLines.push('Connected MCP Servers:');
348
+ servers.forEach((server, idx) => {
349
+ if (idx > 0) logLines.push('');
350
+ logLines.push(`[${idx + 1}] ${server.name}`);
351
+ logLines.push(` Status: ${server.status}`);
352
+ logLines.push(` Tool Count: ${server.toolCount}`);
353
+ if (server.transport) {
354
+ logLines.push(` Transport: ${JSON.stringify(server.transport, null, 2).split('\n').join('\n ')}`);
355
+ }
356
+ if (server.tools && server.tools.length > 0) {
357
+ logLines.push(` Available Tools:`);
358
+ server.tools.forEach(tool => {
359
+ logLines.push(` - ${tool.name}: ${tool.description || 'No description'}`);
360
+ });
361
+ }
362
+ });
363
+ logLines.push('');
364
+ }
365
+
366
+ // mcpToolFunctions 구조 로깅
367
+ if (Object.keys(mcpToolFunctions).length > 0) {
368
+ logLines.push('MCP Tool Functions:');
369
+ Object.keys(mcpToolFunctions).forEach((toolName, idx) => {
370
+ const func = mcpToolFunctions[toolName];
371
+ logLines.push(` [${idx + 1}] ${toolName}`);
372
+ logLines.push(` Type: ${typeof func}`);
373
+ logLines.push(` Function Name: ${func?.name || 'anonymous'}`);
374
+ });
375
+ logLines.push('');
376
+ }
377
+
378
+ // mcpToolSchemas 구조 로깅
379
+ if (mcpToolSchemas.length > 0) {
380
+ logLines.push('MCP Tool Schemas:');
381
+ mcpToolSchemas.forEach((schema, idx) => {
382
+ logLines.push(` [${idx + 1}] ${schema.name}`);
383
+ logLines.push(` Description: ${schema.description || 'No description'}`);
384
+ if (schema.inputSchema) {
385
+ const props = schema.inputSchema.properties || {};
386
+ const propCount = Object.keys(props).length;
387
+ logLines.push(` Input Properties: ${propCount}`);
388
+ if (propCount > 0) {
389
+ Object.entries(props).forEach(([key, value]) => {
390
+ const required = schema.inputSchema.required?.includes(key) ? ' (required)' : '';
391
+ logLines.push(` - ${key}: ${value.type || 'unknown'}${required}`);
392
+ });
393
+ }
394
+ }
395
+ });
396
+ logLines.push('');
397
+ }
398
+
399
+ // 별도 파일에 기록 (createDebugLogger 사용)
400
+ const mcpLogger = createDebugLogger('mcp_initialization.log', 'MCP');
401
+ logLines.forEach(line => mcpLogger(line));
402
+
403
+ // 기존 디버그 로그에도 간략하게 출력
323
404
  debugLog(`MCP integration complete: ${servers.length} server(s), ${Object.keys(mcpToolFunctions).length} tool(s)`);
324
405
  servers.forEach(server => {
325
406
  debugLog(` - ${server.name}: ${server.toolCount} tool(s) (${server.status})`);
@@ -327,16 +408,28 @@ const mcpInitPromise = initializeMCPIntegration(process.cwd()).then(integration
327
408
  }
328
409
  return integration;
329
410
  }).catch(err => {
411
+ // 초기화 실패 시에도 프로그램은 계속 실행 (MCP 없이도 동작)
330
412
  debugLog(`MCP initialization failed: ${err.message}`);
331
413
  return null;
332
414
  });
333
415
 
416
+ // ========================================
334
417
  // 커맨드 레지스트리 초기화
418
+ // ========================================
419
+ // 사용자가 입력하는 슬래시 커맨드들(/mcp, /exit 등)을 관리
335
420
  const commandRegistry = new CommandRegistry();
336
- await loadCommands(commandRegistry, {
421
+
422
+ // context 객체를 생성 - getter를 사용하여 mcpIntegration을 동적으로 참조
423
+ // 이렇게 하면 나중에 MCP가 초기화되어도 최신 값을 참조할 수 있음
424
+ const commandContext = {
337
425
  commandRegistry,
338
- mcpIntegration
339
- });
426
+ get mcpIntegration() {
427
+ return mcpIntegration; // 현재 mcpIntegration 값을 반환 (null이거나 초기화된 값)
428
+ }
429
+ };
430
+
431
+ // src/commands/ 디렉토리의 모든 커맨드 파일들을 자동으로 로드하고 등록
432
+ await loadCommands(commandRegistry, commandContext);
340
433
 
341
434
  // 커맨드 목록 준비
342
435
  const commandList = Array.from(commandRegistry.commands.entries()).map(([name, cmd]) => ({
@@ -364,13 +457,14 @@ async function handleSubmit(text) {
364
457
  return;
365
458
  }
366
459
 
367
- // 세션 실행 (시작/종료 알림 저장은 runSession 내부에서 처리)
460
+ // 세션 실행 (AI Agent의 미션 수행)
461
+ // 시작/종료 알림 및 저장은 runSession 내부에서 처리
368
462
  try {
369
463
  await runSession({
370
- mission: text,
371
- maxIterations: 50,
372
- mcpToolSchemas,
373
- mcpToolFunctions
464
+ mission: text, // 사용자가 입력한 미션
465
+ maxIterations: 50, // 최대 반복 횟수
466
+ mcpToolSchemas, // AI 모델에 전달할 MCP 도구 스키마들
467
+ mcpToolFunctions // 실제 MCP 도구 실행 함수들
374
468
  });
375
469
  } catch (err) {
376
470
  // API 인증 에러 등 세션 실행 중 발생한 에러를 history에 표시
@@ -483,23 +577,34 @@ uiInstance = startUI({
483
577
  updateInfo: null // 초기에는 null, 나중에 업데이트됨
484
578
  });
485
579
 
486
- // UI가 시작된 후 로딩 태스크 추가
580
+ // ========================================
581
+ // 백그라운드 초기화 태스크 UI 연동
582
+ // ========================================
583
+ // UI가 시작된 후 백그라운드에서 실행 중인 초기화 작업들을 사용자에게 표시
584
+
585
+ // 버전 체크 로딩 표시
487
586
  uiEvents.emit('loading:task_add', {
488
587
  id: 'version_check',
489
588
  text: 'Checking for updates...'
490
589
  });
491
590
 
591
+ // MCP 초기화 로딩 표시
492
592
  uiEvents.emit('loading:task_add', {
493
593
  id: 'mcp_init',
494
594
  text: 'Initializing MCP servers...'
495
595
  });
496
596
 
497
- // UI가 준비된 비동기 초기화 이벤트 발생 (Promise가 이미 완료된 경우에도 처리됨)
498
- // 번째 catch에서 null을 반환하므로 항상 resolved 상태로 then이 실행됨
597
+ // 백그라운드 초기화 완료 UI에 이벤트 발생
598
+ // Promise가 이미 완료된 경우에도 then이 실행되어 UI가 업데이트됨
599
+ // catch에서 null을 반환하므로 항상 resolved 상태로 then이 실행됨
600
+
601
+ // 버전 체크 완료 이벤트
499
602
  versionCheckPromise.then(info => {
500
603
  uiEvents.emit('version:update', { updateInfo: info });
501
604
  });
502
605
 
606
+ // MCP 초기화 완료 이벤트
607
+ // 이 시점에서 MCP 서버들과의 연결이 완료되고 도구 목록이 준비됨
503
608
  mcpInitPromise.then(integration => {
504
609
  uiEvents.emit('mcp:initialized', { integration });
505
610
  });
@@ -515,7 +620,10 @@ process.on('SIGINT', handleExit);
515
620
  // UI가 종료될 때까지 대기
516
621
  await uiInstance.waitUntilExit();
517
622
 
518
- // MCP Integration 정리
623
+ // ========================================
624
+ // 프로그램 종료 시 MCP 정리
625
+ // ========================================
626
+ // 모든 MCP 서버와의 연결을 정상적으로 종료하고 리소스 정리
519
627
  if (mcpIntegration) {
520
628
  await mcpIntegration.cleanup();
521
629
  }