All files / src/llm-orchestration/action-handlers invoke-subagent.handler.ts

100% Statements 20/20
100% Branches 6/6
100% Functions 4/4
100% Lines 18/18

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 1667x               7x     7x 13x 13x   13x     1x                                                         3x                                                                                             5x   5x       5x 5x             4x   4x 2x                                     2x                                     1x       1x                        
import { Injectable, Logger } from '@nestjs/common';
import { ActionHandler } from './action-handler.interface';
import {
  ActionExecutionResult,
  PlanExecutionContext,
  ToolArgument,
  ToolMetadata,
} from '../llm-orchestration.interfaces';
import { SubAgentRunner } from '../../sub-agents/sub-agent-runner.service';
 
@Injectable()
export class InvokeSubAgentHandler implements ActionHandler {
  readonly toolName = 'invoke_subagent';
  private readonly logger = new Logger(InvokeSubAgentHandler.name);
 
  constructor(private readonly subAgentRunner: SubAgentRunner) {}
 
  getMetadata(): ToolMetadata {
    return {
      name: this.toolName,
      description:
        'Delegate a task to a specialized sub-agent. The sub-agent runs synchronously and returns its result directly.',
      arguments: [
        {
          name: 'agent_name',
          type: 'string' as const,
          description: 'The name of the sub-agent to invoke',
          required: true,
        },
        {
          name: 'prompt',
          type: 'string' as const,
          description: 'The task or question to pass to the sub-agent',
          required: true,
        },
        {
          name: 'session_id',
          type: 'string' as const,
          description:
            'Optional existing session ID to reuse. If provided, the sub-agent continues in that session with its prior history.',
          required: false,
        },
      ] as ToolArgument[],
    };
  }
 
  getDefinition(): string {
    return `## invoke_subagent
 
Delegate a task to a specialized sub-agent. The sub-agent runs synchronously and returns its result directly.
 
### Behavior:
- The sub-agent runs inline — this tool call blocks until the sub-agent completes.
- The sub-agent has its own system prompt, enabled tools, and LLM loop.
- Results are returned directly as the tool response — no follow-up needed.
- **Parallel invocation:** You can invoke multiple sub-agents in the same tool call block to run them in parallel. Use this when tasks are independent of each other.
- **Follow-up:** Each invocation returns a \`[Session ID: ...]\` in the output. Pass this as the \`session_id\` parameter on a subsequent call to continue that sub-agent's session with its prior history.
 
### Parameters:
- **agent_name** (required): The name of the sub-agent to invoke (e.g., "explore-codebase")
- **prompt** (required): The task or question to pass to the sub-agent
- **session_id** (optional): An existing session ID to reuse. If provided, the sub-agent continues in that session with its prior history instead of creating a new one.
 
### Example (single invocation):
\`\`\`typescript
tool: invoke_subagent
args: {
  agent_name: "explore-codebase",
  prompt: "Find all files related to authentication in the codebase"
}
\`\`\`
 
### Example (parallel invocation):
\`\`\`typescript
// Invoke two independent sub-agents in the same tool call block:
tool: invoke_subagent
args: { agent_name: "explore-codebase", prompt: "Find auth files" }
 
tool: invoke_subagent
args: { agent_name: "explore-codebase", prompt: "Find database models" }
\`\`\`
 
### Example (follow-up with session_id):
\`\`\`typescript
// Continue a prior sub-agent session using the Session ID from a previous result:
tool: invoke_subagent
args: { agent_name: "explore-codebase", prompt: "Now find the tests for those files", session_id: "abc-123" }
\`\`\``;
  }
 
  async execute(
    args: Record<string, any>,
    context: PlanExecutionContext,
  ): Promise<ActionExecutionResult> {
    const { agent_name, prompt, session_id } = args;
 
    this.logger.log(
      `Invoking sub-agent "${agent_name}" from session ${context.session_id}${session_id ? ` (reusing session ${session_id})` : ''}`,
    );
 
    try {
      const result = await this.subAgentRunner.runAgent(
        agent_name,
        prompt,
        context.session_id,
        session_id ? { sessionId: session_id } : undefined,
      );
 
      const outputWithSessionId = `${result.content}\n\n[Session ID: ${result.childSessionId}]`;
 
      if (result.success) {
        return {
          status: 'SUCCESS',
          summary: `Sub-agent "${agent_name}" completed successfully in ${result.iterations} iteration(s).`,
          persisted_args: {
            arguments: JSON.stringify(args),
            agentName: agent_name,
            prompt,
            childSessionId: result.childSessionId,
            // Store result in `plain` so it's always available without loading executionLogs
            plain: result.content,
            // Store session ID in `reason` so it's always available
            reason: `Sub-agent session: ${result.childSessionId}`,
          },
          execution_log: {
            output: outputWithSessionId,
            error_message: '',
          },
        };
      } else {
        return {
          status: 'FAILURE',
          summary: `Sub-agent "${agent_name}" failed or could not complete.`,
          error_message: result.content,
          persisted_args: {
            arguments: JSON.stringify(args),
            agentName: agent_name,
            prompt,
            childSessionId: result.childSessionId,
            plain: result.content,
            reason: `Sub-agent session: ${result.childSessionId}`,
          },
          execution_log: {
            output: outputWithSessionId,
            error_message: result.content,
          },
        };
      }
    } catch (error) {
      this.logger.error(
        `Sub-agent "${agent_name}" execution error: ${error.message}`,
        error.stack,
      );
      return {
        status: 'FAILURE',
        summary: `Failed to invoke sub-agent "${agent_name}"`,
        error_message: error.message,
        execution_log: {
          output: '',
          error_message: error.message,
        },
      };
    }
  }
}