All files / src/sub-agents sub-agent-runner.service.ts

75.39% Statements 190/252
54.36% Branches 81/149
66.66% Functions 12/18
77.04% Lines 188/244

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 7828x 8x 8x           8x 8x 8x 8x 8x 8x 8x   8x 8x 8x         8x 8x 8x 8x 8x 8x 8x                                 8x     8x 18x     18x 18x 18x 18x 18x 18x   18x 18x   18x   18x               10x             10x             10x               10x             9x                         12x         12x 12x 2x 1x   2x               10x 10x 10x 10x 10x       10x   10x   2x 2x 1x             1x         1x       1x     8x                     8x           9x                 9x 9x 9x         9x                   9x   9x   9x 9x 18x 18x 3x     9x       9x                                                                           9x           9x                   9x         9x 9x 9x   9x 9x   9x   9x 1011x 1011x           1011x     1011x                         1010x                       1010x       1010x 1004x   1010x     1010x     1010x                         1010x     1010x         1010x 6x     6x 6x       1004x 1004x 1004x   1004x         1004x   1004x 1004x   1004x       1004x     1004x 1x 1x 1x     1x                     1x   1x         1x       1003x 1003x     1x 1x                   1003x 1x     1x 1x             1x                 1x 1x         1002x 1002x   1x     1x                   1002x 1002x                           1002x     1002x 1001x               1002x   1002x 1002x       1002x             1002x               1004x 1004x                 1004x               1004x                   1004x       1004x 1x             8x 1x     1x 1x   1x         8x           8x       1x       1x 1x     1x     1x         9x 9x       9x                                                                             1x 1x 2x 1x       1x 1x 1x       1x                   1x       1x                                   1011x   1011x     1011x   1011x 1011x 1011x           1011x         1x     1x         1x 1x 1x                                                                                             1002x   1002x                
import { Injectable, Inject, Logger } from '@nestjs/common';
import { ModuleRef } from '@nestjs/core';
import {
  LlmProvider,
  LlmContent,
  LlmResponse,
  LLM_PROVIDER,
} from '../llm-provider/llm-provider.interface';
import { SubAgentsService } from './sub-agents.service';
import { SubAgentRunsService } from './sub-agent-runs.service';
import { SessionsService } from '../sessions/sessions.service';
import { SystemPromptsService } from '../system-prompts/system-prompts.service';
import { ToolSchemaService } from '../llm-orchestration/tool-schema.service';
import { HistoryCompressionService } from '../llm-orchestration/history-compression.service';
import { ApplicationStateService } from '../application-state/application-state.service';
import { ActionHandler } from '../llm-orchestration/action-handlers/action-handler.interface';
import { McpToolActionHandler } from '../llm-orchestration/action-handlers/mcp-tool-action.handler';
import { McpService } from '../mcp/mcp.service';
import {
  ActionExecutionResult,
  PlanExecutionContext,
} from '../llm-orchestration/llm-orchestration.interfaces';
import { Session } from '../core-entities/session.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SessionInput } from '../core-entities/session-input.entity';
import { AIAction } from '../core-entities/ai-action.entity';
import { AIActionStatus } from '../ai-actions/ai-actions.service';
import { ExecutionLogsService } from '../execution-logs/execution-logs.service';
import { EventsGateway } from '../events/events.gateway';
 
export interface RunAgentOptions {
  passContext?: boolean;
  contextFiles?: string[];
  masterContextDefinition?: any;
  /** If provided, reuse this existing session instead of creating a new one. */
  sessionId?: string;
}
 
export interface RunAgentResult {
  content: string;
  success: boolean;
  iterations: number;
  childSessionId: string;
}
 
const MAX_ITERATIONS = 1000;
 
@Injectable()
export class SubAgentRunner {
  private readonly logger = new Logger(SubAgentRunner.name);
 
  constructor(
    private readonly subAgentsService: SubAgentsService,
    private readonly subAgentRunsService: SubAgentRunsService,
    private readonly sessionsService: SessionsService,
    private readonly applicationStateService: ApplicationStateService,
    private readonly executionLogsService: ExecutionLogsService,
    private readonly eventsGateway: EventsGateway,
    @Inject(LLM_PROVIDER)
    private readonly llmProvider: LlmProvider,
    private readonly moduleRef: ModuleRef,
    @InjectRepository(SessionInput)
    private readonly sessionInputsRepository: Repository<SessionInput>,
    @InjectRepository(AIAction)
    private readonly aiActionsRepository: Repository<AIAction>,
  ) {}
 
  /**
   * Lazily resolves the ACTION_HANDLER_REGISTRY to avoid circular dependency
   * between SubAgentsModule and LlmOrchestrationModule at construction time.
   */
  private getHandlerRegistry(): Map<string, ActionHandler> {
    return this.moduleRef.get('ACTION_HANDLER_REGISTRY', { strict: false });
  }
 
  /**
   * Lazily resolves ToolSchemaService to avoid circular module dependency.
   */
  private getToolSchemaService(): ToolSchemaService {
    return this.moduleRef.get(ToolSchemaService, { strict: false });
  }
 
  /**
   * Lazily resolves HistoryCompressionService to avoid circular module dependency.
   */
  private getHistoryCompressionService(): HistoryCompressionService {
    return this.moduleRef.get(HistoryCompressionService, { strict: false });
  }
 
  /**
   * Lazily resolves SystemPromptsService to avoid circular module dependency
   * (SubAgentsModule → SystemPromptsModule → LlmOrchestrationModule → SubAgentsModule).
   */
  private getSystemPromptsService(): SystemPromptsService {
    return this.moduleRef.get(SystemPromptsService, { strict: false });
  }
 
  /**
   * Lazily resolves McpService to avoid circular module dependency.
   */
  private getMcpService(): McpService {
    return this.moduleRef.get(McpService, { strict: false });
  }
 
  /**
   * Runs a sub-agent synchronously within the parent's tool execution.
   * Creates a child session, enters an LLM loop, and returns the result directly.
   */
  async runAgent(
    agentName: string,
    prompt: string,
    parentSessionId: string,
    options?: RunAgentOptions,
  ): Promise<RunAgentResult> {
    this.logger.log(
      `runAgent called for "${agentName}" from parent session ${parentSessionId}`,
    );
 
    // 1. Look up sub-agent
    const subAgent = await this.subAgentsService.getAgentByName(agentName);
    if (!subAgent) {
      const availableAgents = (await this.subAgentsService.findActive())
        .map((a) => a.name)
        .join(', ');
      return {
        content: `Sub-agent "${agentName}" not found or not active. Available: ${availableAgents}`,
        success: false,
        iterations: 0,
        childSessionId: '',
      };
    }
 
    const startTime = Date.now();
    const handlerRegistry = this.getHandlerRegistry();
    const toolSchemaService = this.getToolSchemaService();
    const historyCompressionService = this.getHistoryCompressionService();
    const systemPromptsService = this.getSystemPromptsService();
 
    // 2. Get or create child session
    let childSession: Session;
    let existingHistory: LlmContent[] = [];
 
    if (options?.sessionId) {
      // Reuse existing session
      childSession = await this.sessionsService.findOne(options.sessionId);
      if (!childSession) {
        return {
          content: `Session "${options.sessionId}" not found. Cannot reuse a non-existent session.`,
          success: false,
          iterations: 0,
          childSessionId: options.sessionId,
        };
      }
      this.logger.log(
        `Reusing existing session ${childSession.id} for sub-agent "${agentName}"`,
      );
 
      // Load existing session history for context continuity
      const existingInputs = await this.sessionInputsRepository.find({
        where: { session: { id: childSession.id } },
        order: { sequence_number: 'ASC' as const },
      });
      existingHistory = this.reconstructHistory(existingInputs);
    } else {
      // Create new child session
      childSession = await this.sessionsService.create({
        session_title: `Sub-Agent: ${agentName}`,
        system_prompt_id: subAgent.system_prompt_id || undefined,
        default_initial_context_template_id:
          subAgent.context_template_id || undefined,
        default_followup_context_template_id:
          subAgent.followup_context_template_id || undefined,
        model_id: subAgent.model_id || undefined,
        sub_agent_id: subAgent.id,
        parent_session_id: parentSessionId,
      });
      this.logger.log(
        `Created child session ${childSession.id} for sub-agent "${agentName}"`,
      );
    }
 
    // 3. Create SubAgentRun record
    await this.subAgentRunsService.create({
      parent_session_id: parentSessionId,
      child_session_id: childSession.id,
      sub_agent_id: subAgent.id,
      agent_name: agentName,
      initial_prompt: prompt,
    });
 
    // 4. Load & render system prompt
    let systemInstruction = '';
    if (subAgent.system_prompt_id) {
      const rendered = await systemPromptsService.findOneWithSession(
        subAgent.system_prompt_id,
        childSession.id,
        childSession.session_title,
      );
      systemInstruction = rendered?.prompt_content || '';
    } else E{
      const defaultPrompt = await systemPromptsService.findDefaultWithSession(
        childSession.id,
        childSession.session_title,
      );
      systemInstruction = defaultPrompt?.prompt_content || '';
    }
 
    // 5. Generate tool definitions
    const mcpService = this.getMcpService();
    let tools: any[] | undefined;
    if (subAgent.enabled_tools && subAgent.enabled_tools.length > 0) {
      // Build a filtered handler map
      const filteredHandlers = new Map<string, ActionHandler>();
      for (const toolName of subAgent.enabled_tools) {
        const handler = handlerRegistry.get(toolName);
        if (handler) {
          filteredHandlers.set(toolName, handler);
        }
      }
      tools = toolSchemaService.generateToolDefinitions(filteredHandlers);
    }
 
    // Add MCP tool definitions (same pattern as main agent via ToolSchemaService.generateToolDefinitionsForPrompt)
    Iif (
      subAgent.enabled_mcp_tools !== null &&
      subAgent.enabled_mcp_tools !== undefined
    ) {
      try {
        const allMcpTools = await mcpService.getActiveMcpToolDefinitions();
        Iif (allMcpTools.length > 0) {
          let enabledMcpToolNames: string[];
          if (subAgent.enabled_mcp_tools === 'all') {
            enabledMcpToolNames = allMcpTools.map((t) => t.function.name);
          } else {
            // Parse from stored string, resolving server prefixes
            const parsedMcpTools =
              (this.subAgentsService.parseEnabledMcpTools(
                subAgent.enabled_mcp_tools,
              ) as string[]) || [];
            const allToolNames = allMcpTools.map((t) => t.function.name);
            enabledMcpToolNames =
              this.resolveMcpToolNames(parsedMcpTools, allToolNames);
          }
          const filteredMcpTools = allMcpTools.filter((tool) =>
            enabledMcpToolNames.includes(tool.function.name),
          );
          Iif (filteredMcpTools.length > 0) {
            tools = [...(tools || []), ...filteredMcpTools];
            this.logger.log(
              `Added ${filteredMcpTools.length} MCP tool definitions for sub-agent "${agentName}".`,
            );
          }
        }
      } catch (error) {
        this.logger.warn(
          `Failed to load MCP tool definitions for sub-agent "${agentName}": ${error.message}. Continuing without MCP tools.`,
        );
      }
    }
 
    // 6. Build initial history (prepend existing history if reusing session)
    const history: LlmContent[] = [
      ...existingHistory,
      { role: 'user', parts: [{ text: prompt }] },
    ];
 
    // 7. Create initial user SessionInput
    await this.sessionInputsRepository.save(
      this.sessionInputsRepository.create({
        session: { id: childSession.id },
        role: 'user',
        user_prompt: prompt,
        execution_strategy: 'auto_apply',
      }),
    );
 
    // Notify frontend that sub-agent session has started
    this.eventsGateway.sendToAll('refresh-ui', {
      sessionId: childSession.id,
    });
 
    // 8. LLM loop
    let iterations = 0;
    let finalContent = '';
    let success = true;
 
    try {
      const abortController = new AbortController();
      const executionStrategy =
        await this.applicationStateService.getExecutionStrategy();
 
      while (iterations < MAX_ITERATIONS) {
        iterations++;
        this.logger.log(
          `Sub-agent "${agentName}" iteration ${iterations}/${MAX_ITERATIONS}`,
        );
 
        // Compress history
        const compressedHistory =
          await historyCompressionService.compress(history);
 
        // Call LLM
        const llmResponse: LlmResponse = await this.callWithRetry(
          {
            prompt: '',
            systemInstruction,
            history: compressedHistory,
            modelId: childSession.model_id || undefined,
            tools,
            abortController,
          },
          childSession.id,
        );
 
        // Check for empty response
        Iif (
          !llmResponse.text &&
          (!llmResponse.tool_calls || llmResponse.tool_calls.length === 0)
        ) {
          this.logger.log(
            `Sub-agent "${agentName}" returned empty response with no tool calls. Ending loop.`,
          );
          finalContent = llmResponse.text || '(No response from sub-agent)';
          break;
        }
 
        // Build model message for history
        const modelMessage: LlmContent = {
          role: 'model',
          parts: [{ text: llmResponse.text || '' }],
        };
        if (llmResponse.tool_calls && llmResponse.tool_calls.length > 0) {
          modelMessage.tool_calls = llmResponse.tool_calls;
        }
        Iif (llmResponse.thoughts) {
          modelMessage.thoughts = llmResponse.thoughts;
        }
        history.push(modelMessage);
 
        // Persist model turn as SessionInput
        const modelInput = this.sessionInputsRepository.create({
          session: { id: childSession.id },
          role: 'model',
          raw_llm_response: llmResponse.text || '',
          tool_calls: llmResponse.tool_calls
            ? JSON.stringify(llmResponse.tool_calls)
            : null,
          thoughts: llmResponse.thoughts || null,
          input_token_count: llmResponse.usage?.inputTokens || null,
          output_token_count: llmResponse.usage?.outputTokens || null,
          cached_token_count: llmResponse.usage?.cachedTokens || null,
          execution_strategy: 'auto_apply',
        });
        await this.sessionInputsRepository.save(modelInput);
 
        // Notify frontend that model turn is available
        this.eventsGateway.sendToAll('refresh-ui', {
          sessionId: childSession.id,
        });
 
        // Check for no tool calls → done
        if (!llmResponse.tool_calls || llmResponse.tool_calls.length === 0) {
          this.logger.log(
            `Sub-agent "${agentName}" returned text with no tool calls. Ending loop.`,
          );
          finalContent = llmResponse.text || '';
          break;
        }
 
        // Parse and execute tool calls
        const executionContext = new PlanExecutionContext();
        executionContext.session_id = childSession.id;
        executionContext.system_prompt_id = subAgent.system_prompt_id || null;
 
        let shouldBreak = false;
        const toolResults: {
          toolCallId: string;
          toolName: string;
          result: string;
        }[] = [];
 
        for (const toolCall of llmResponse.tool_calls) {
          const toolName = toolCall.function.name;
          const args =
            typeof toolCall.function.arguments === 'string'
              ? JSON.parse(toolCall.function.arguments)
              : toolCall.function.arguments;
 
          this.logger.log(`Sub-agent "${agentName}" calling tool: ${toolName}`);
 
          // Check for final() — extract result and break
          if (toolName === 'final') {
            const plainText = args.plain || args.content || '';
            finalContent = plainText;
            shouldBreak = true;
 
            // Create AIAction record for final
            const actionEntity = this.aiActionsRepository.create({
              input_id: modelInput.id,
              sessionInput: { id: modelInput.id },
              action_type: 'final',
              status: AIActionStatus.CONFIRMED_KEPT,
              order_of_execution: toolResults.length,
              original_content_for_revert: null,
              tool_call_id: toolCall.id || null,
              plain: plainText,
              selections: args.selections || null,
            });
            await this.aiActionsRepository.save(actionEntity);
 
            toolResults.push({
              toolCallId: toolCall.id || '',
              toolName,
              result: 'Task completed.',
            });
            continue;
          }
 
          // Find handler
          let handler = handlerRegistry.get(toolName);
          if (!handler) {
            // Check if this is an MCP tool call (serverName__toolName pattern)
            // Same pattern as LlmTurnProcessorService
            const mcpMatch = toolName.match(/^([^_]+)__(.+)$/);
            Iif (mcpMatch) {
              const [, serverName, toolNameRaw] = mcpMatch;
              handler = new McpToolActionHandler(
                serverName,
                toolNameRaw,
                mcpService,
                '',
              );
            }
          }
          if (!handler) {
            this.logger.warn(
              `No handler found for tool: ${toolName}. Skipping.`,
            );
            const errorMsg = `Tool '${toolName}' is not a valid tool. Please use a valid tool.`;
            toolResults.push({
              toolCallId: toolCall.id || '',
              toolName,
              result: errorMsg,
            });
 
            // Create AIAction record for invalid tool
            const actionEntity = this.aiActionsRepository.create({
              input_id: modelInput.id,
              sessionInput: { id: modelInput.id },
              action_type: toolName,
              status: AIActionStatus.EXECUTION_FAILED,
              order_of_execution: toolResults.length,
              original_content_for_revert: null,
              tool_call_id: toolCall.id || null,
            });
            await this.aiActionsRepository.save(actionEntity);
            continue;
          }
 
          // Execute handler
          let result: ActionExecutionResult;
          try {
            result = await handler.execute(args, executionContext);
          } catch (error) {
            this.logger.error(
              `Handler for ${toolName} failed: ${error.message}`,
            );
            result = {
              status: 'FAILURE',
              summary: `An unexpected error occurred: ${error.message}`,
              error_message: error.message,
              persisted_args: args,
            };
          }
 
          // Create AIAction record
          const successStatus =
            this.getSuccessStatusForStrategy(executionStrategy);
          const actionEntity = this.aiActionsRepository.create({
            input_id: modelInput.id,
            sessionInput: { id: modelInput.id },
            action_type: toolName,
            status:
              result.status === 'SUCCESS'
                ? successStatus
                : AIActionStatus.EXECUTION_FAILED,
            order_of_execution: toolResults.length,
            original_content_for_revert:
              result.original_content_for_revert || null,
            tool_call_id: toolCall.id || null,
            ...result.persisted_args,
          });
          const savedAction = await this.aiActionsRepository.save(actionEntity);
 
          // Create execution log
          if (result.execution_log) {
            await this.executionLogsService.createLog({
              action_id: savedAction.id,
              output: result.execution_log.output,
              error_message: result.execution_log.error_message,
            });
          }
 
          // Collect tool result
          const output = result.execution_log?.output || '';
          const error =
            result.execution_log?.error_message || result.error_message || '';
          const combinedResult = error
            ? `${output}\n\nError: ${error}`.trim()
            : output;
 
          toolResults.push({
            toolCallId: toolCall.id || '',
            toolName,
            result: combinedResult,
          });
 
          // Break if execution context halted
          Iif (executionContext.flags.should_halt) {
            this.logger.log(`Execution context halted. Ending sub-agent loop.`);
            shouldBreak = true;
            break;
          }
        }
 
        // Add tool results to history
        for (const tr of toolResults) {
          history.push({
            role: 'tool',
            tool_call_id: tr.toolCallId,
            tool_name: tr.toolName,
            parts: [{ text: tr.result }],
          });
        }
 
        // Persist tool results as a user-turn SessionInput
        await this.sessionInputsRepository.save(
          this.sessionInputsRepository.create({
            session: { id: childSession.id },
            role: 'user',
            user_prompt: '',
            execution_strategy: 'auto_apply',
            raw_llm_response: null,
            tool_calls: JSON.stringify(
              toolResults.map((tr) => ({
                id: tr.toolCallId,
                type: 'function',
                function: { name: tr.toolName, arguments: '{}' },
              })),
            ),
          }),
        );
 
        // Notify frontend that tool results are available
        this.eventsGateway.sendToAll('refresh-ui', {
          sessionId: childSession.id,
        });
 
        if (shouldBreak) {
          break;
        }
 
        // Continue loop
      }
 
      // Max iterations reached
      if (iterations >= MAX_ITERATIONS) {
        this.logger.warn(
          `Sub-agent "${agentName}" reached max iterations (${MAX_ITERATIONS}).`,
        );
        if (!finalContent) {
          finalContent =
            'Sub-agent reached maximum iterations without completing.';
          success = false;
        }
      }
 
      // Mark run as completed
      await this.subAgentRunsService.markCompleted(
        childSession.id,
        finalContent.substring(0, 5000), // Truncate result for storage
      );
 
      // Notify frontend of final state
      this.eventsGateway.sendToAll('refresh-ui', {
        sessionId: childSession.id,
      });
    } catch (error) {
      this.logger.error(
        `Sub-agent "${agentName}" failed: ${error.message}`,
        error.stack,
      );
      success = false;
      finalContent = `Sub-agent "${agentName}" encountered an error: ${error.message}`;
 
      // Mark run as failed
      await this.subAgentRunsService.markFailed(childSession.id, error.message);
 
      // Notify frontend of error state
      this.eventsGateway.sendToAll('refresh-ui', {
        sessionId: childSession.id,
      });
    }
 
    const durationMs = Date.now() - startTime;
    this.logger.log(
      `Sub-agent "${agentName}" completed in ${durationMs}ms, ${iterations} iterations, success: ${success}`,
    );
 
    return {
      content: finalContent,
      success,
      iterations,
      childSessionId: childSession.id,
    };
  }
 
  /**
   * Resolve enabled MCP tool entries against all active tools.
   * Each entry can be either:
   * - An exact tool name: 'playwright__browser_navigate'
   * - A server prefix: 'playwright' (matches all 'playwright__*' tools)
   */
  private resolveMcpToolNames(
    entries: string[],
    allActiveMcpToolNames: string[],
  ): string[] {
    const result: string[] = [];
    for (const entry of entries) {
      for (const toolName of allActiveMcpToolNames) {
        Iif (toolName === entry || toolName.startsWith(entry + '__')) {
          Iif (!result.includes(toolName)) {
            result.push(toolName);
          }
        }
      }
    }
    return result;
  }
 
  /**
   * Reconstructs LlmContent[] history from existing SessionInput records.
/**
   * Reconstructs LlmContent[] history from existing SessionInput records.
   * Used when reusing a session to provide context continuity.
   * Tool results are represented as user-role messages with tool call JSON.
   */
  private reconstructHistory(inputs: SessionInput[]): LlmContent[] {
    const history: LlmContent[] = [];
    for (const input of inputs) {
      if (input.role === 'user') {
        const content: LlmContent = {
          role: 'user',
          parts: [{ text: input.user_prompt || input.raw_llm_response || '' }],
        };
        history.push(content);
      } else if (input.role === 'model') {
        const content: LlmContent = {
          role: 'model',
          parts: [{ text: input.raw_llm_response || '' }],
        };
        Iif (input.tool_calls) {
          try {
            const parsed = JSON.parse(input.tool_calls);
            Iif (Array.isArray(parsed)) {
              content.tool_calls = parsed;
            }
          } catch {
            // Not valid JSON, skip
          }
        }
        history.push(content);
      }
      // Skip other roles — they're represented as user/model turns
    }
    return history;
  }
 
  /**
   * Calls LLM with exponential backoff retry.
   */
  private async callWithRetry(
    request: {
      prompt: string;
      systemInstruction: string;
      history: LlmContent[];
      modelId?: string;
      tools?: any[];
      abortController: AbortController;
    },
    sessionId: string,
  ): Promise<LlmResponse> {
    const retryEnabled =
      await this.applicationStateService.getLlmRetryEnabled();
    const maxAttempts =
      await this.applicationStateService.getLlmRetryMaxAttempts();
 
    let lastError: Error | undefined;
    let attempt = 1;
 
    while (attempt <= maxAttempts) {
      try {
        Iif (attempt > 1) {
          this.logger.log(
            `Retry attempt ${attempt}/${maxAttempts} for sub-agent session ${sessionId}`,
          );
        }
 
        return await this.llmProvider.generateContent({
          ...request,
          abortController: request.abortController,
        });
      } catch (error) {
        lastError = error as Error;
 
        // Check for abort
        Iif (error.name === 'AbortError' || error.code === 'ABORT_ERR') {
          throw error;
        }
 
        const shouldRetry =
          retryEnabled && attempt < maxAttempts && this.isRetryableError(error);
        if (!shouldRetry) {
          throw error;
        }
 
        const backoffMs = Math.pow(2, attempt - 1) * 1000;
        this.logger.log(
          `LLM call failed (attempt ${attempt}/${maxAttempts}): ${error.message}. Retrying in ${backoffMs}ms...`,
        );
        await new Promise((resolve) => setTimeout(resolve, backoffMs));
        attempt++;
      }
    }
 
    throw lastError;
  }
 
  private isRetryableError(error: any): boolean {
    const errorMessage = error.message?.toLowerCase() || '';
    const errorCode = error.code;
    const status = error.status;
 
    Iif (error.name === 'AbortError' || error.code === 'ABORT_ERR') return false;
 
    const networkErrors = [
      'ECONNRESET',
      'ETIMEDOUT',
      'ENOTFOUND',
      'ENETUNREACH',
      'ECONNREFUSED',
    ];
    Iif (errorCode && networkErrors.includes(errorCode)) return true;
    Iif (
      status === 429 ||
      errorMessage.includes('rate limit') ||
      errorMessage.includes('too many requests')
    )
      return true;
    Iif (status >= 500 && status < 600) return true;
    Iif (
      errorMessage.includes('empty response') ||
      errorMessage.includes('timeout')
    )
      return true;
 
    return false;
  }
 
  private getSuccessStatusForStrategy(strategy: string): AIActionStatus {
    switch (strategy) {
      case 'auto_apply':
        return AIActionStatus.CONFIRMED_KEPT;
      case 'review_first':
      case 'apply_revert':
      default:
        return AIActionStatus.APPLIED_PENDING_REVIEW;
    }
  }
}