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

50% Statements 28/56
7.14% Branches 1/14
50% Functions 6/12
48.14% Lines 26/54

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 17919x         19x 19x 19x         19x     16x                                                                                                                                         8x       8x     8x       1x                   2x     2x 1x           1x 1x 1x         1x 1x       2x   2x                                     4x     4x 4x 4x               4x                           4x      
import {
  Injectable,
  NotFoundException,
  ForbiddenException,
} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SubAgent } from './sub-agent.entity';
import { CreateSubAgentDto } from './dto/create-sub-agent.dto';
import { UpdateSubAgentDto } from './dto/update-sub-agent.dto';
 
@Injectable()
export class SubAgentsService {
  constructor(
    @InjectRepository(SubAgent)
    private readonly subAgentsRepository: Repository<SubAgent>,
  ) {}
 
  /**
   * Parse enabled_mcp_tools from string storage.
   * Returns null (no MCP), 'all', or string[] of serverName__toolName identifiers.
   */
  parseEnabledMcpTools(value: string | null): string[] | 'all' | null {
    Iif (!value) {
      return null;
    }
    Iif (value === 'all') {
      return 'all';
    }
    try {
      const tools = JSON.parse(value);
      Iif (Array.isArray(tools)) {
        return tools;
      }
      return null;
    } catch (e) {
      return null;
    }
  }
 
  /**
   * Serialize enabled_mcp_tools for storage.
   */
  serializeEnabledMcpTools(value: string[] | 'all' | null): string | null {
    Iif (value === null || value === undefined) {
      return null;
    }
    Iif (value === 'all') {
      return 'all';
    }
    return JSON.stringify(value);
  }
 
  async create(createSubAgentDto: CreateSubAgentDto): Promise<SubAgent> {
    const { enabled_mcp_tools, ...rest } = createSubAgentDto;
    const subAgent = this.subAgentsRepository.create({
      ...rest,
      enabled_mcp_tools:
        enabled_mcp_tools !== undefined
          ? this.serializeEnabledMcpTools(enabled_mcp_tools)
          : null,
    });
    return this.subAgentsRepository.save(subAgent);
  }
 
  async findAll(activeOnly = false): Promise<SubAgent[]> {
    const query = this.subAgentsRepository.createQueryBuilder('sub_agent');
 
    Iif (activeOnly) {
      query.where('sub_agent.is_active = :isActive', { isActive: true });
    }
 
    return query
      .leftJoinAndSelect('sub_agent.systemPrompt', 'systemPrompt')
      .leftJoinAndSelect('sub_agent.contextTemplate', 'contextTemplate')
      .leftJoinAndSelect(
        'sub_agent.followupContextTemplate',
        'followupContextTemplate',
      )
      .orderBy('sub_agent.name', 'ASC')
      .getMany();
  }
 
  async findOne(id: string): Promise<SubAgent> {
    const subAgent = await this.subAgentsRepository.findOne({
      where: { id },
      relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
    });
    Iif (!subAgent) {
      throw new NotFoundException(`SubAgent with ID "${id}" not found`);
    }
    return subAgent;
  }
 
  async findByBuiltinKey(builtinKey: string): Promise<SubAgent | null> {
    return this.subAgentsRepository.findOne({
      where: { builtin_key: builtinKey },
      relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
    });
  }
 
  async update(
    id: string,
    updateSubAgentDto: UpdateSubAgentDto,
  ): Promise<SubAgent> {
    const subAgent = await this.findOne(id);
 
    // Check if builtin - forbid modification
    if (subAgent.is_builtin) {
      throw new ForbiddenException(
        `Cannot modify built-in sub-agent "${subAgent.name}". Duplicate it to create your own version.`,
      );
    }
 
    // Serialize enabled_mcp_tools if provided (convert string[] | 'all' to string | null)
    const { enabled_mcp_tools, ...rest } = updateSubAgentDto;
    const updateData: any = { ...rest };
    Iif (enabled_mcp_tools !== undefined) {
      updateData.enabled_mcp_tools =
        this.serializeEnabledMcpTools(enabled_mcp_tools);
    }
 
    this.subAgentsRepository.merge(subAgent, updateData);
    return this.subAgentsRepository.save(subAgent);
  }
 
  async remove(id: string): Promise<void> {
    const subAgent = await this.findOne(id);
 
    await this.subAgentsRepository.remove(subAgent);
  }
 
  async findActive(): Promise<SubAgent[]> {
    return this.findAll(true);
  }
 
  async getAgentByName(name: string): Promise<SubAgent | null> {
    return this.subAgentsRepository.findOne({
      where: { name, is_active: true },
      relations: ['systemPrompt', 'contextTemplate', 'followupContextTemplate'],
    });
  }
 
  /**
   * Duplicate a sub-agent (allowed for built-in sub-agents).
   * Creates a user-owned copy with is_builtin=false.
   */
  async duplicate(id: string): Promise<SubAgent> {
    const original = await this.findOne(id);
 
    // Generate unique name for the duplicate
    let newName = `${original.name} (Copy)`;
    let suffix = 2;
    while (
      await this.subAgentsRepository.findOne({ where: { name: newName } })
    ) {
      newName = `${original.name} (Copy ${suffix})`;
      suffix++;
    }
 
    // Create duplicate with user ownership
    const duplicate = this.subAgentsRepository.create({
      name: newName,
      description: original.description,
      system_prompt_id: original.system_prompt_id,
      context_template_id: original.context_template_id,
      followup_context_template_id: original.followup_context_template_id,
      enabled_tools: original.enabled_tools,
      enabled_mcp_tools: original.enabled_mcp_tools,
      is_active: true,
      model_id: original.model_id,
      is_builtin: false,
      builtin_key: null,
    });
 
    return this.subAgentsRepository.save(duplicate);
  }
}