All files / src/seeding sub-agent-seeding.service.ts

17.64% Statements 15/85
0% Branches 0/50
25% Functions 1/4
16.04% Lines 13/81

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 2206x 6x 6x 6x 6x 6x 6x 6x     6x 6x       6x 6x 6x                                                                                                                                                                                                                                                                                                                                                                                                                    
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SubAgent } from '../sub-agents/sub-agent.entity';
import { SystemPromptsService } from '../system-prompts/system-prompts.service';
import { ContextTemplatesService } from '../context-templates/context-templates.service';
import * as path from 'path';
import { glob } from 'glob';
 
@Injectable()
export class SubAgentSeedingService {
  private readonly logger = new Logger(SubAgentSeedingService.name);
 
  constructor(
    @InjectRepository(SubAgent)
    private readonly subAgentRepository: Repository<SubAgent>,
    private readonly systemPromptsService: SystemPromptsService,
    private readonly contextTemplatesService: ContextTemplatesService,
  ) {}
 
  async seed() {
    const existingAgents = await this.subAgentRepository.find({
      where: { is_active: true },
    });
    const existingAgentMap = new Map<string, SubAgent>();
    existingAgents.forEach((a) => existingAgentMap.set(a.name, a));
 
    this.logger.log('Syncing sub-agents from files...');
    const seedFiles = await glob(
      path.join(__dirname, 'data', 'sub-agents', '*.{ts,js}'),
    );
 
    Iif (seedFiles.length === 0) {
      this.logger.warn('No sub-agent seed files found.');
      return;
    }
 
    for (const filePath of seedFiles) {
      try {
        const agentModule = await import(filePath);
        const {
          name,
          description,
          system_prompt_name,
          context_template_name,
          followup_context_template_name,
          enabled_tools,
          enabled_mcp_tools,
          model_id,
          is_active,
        } = agentModule;
        const fileName = path.basename(filePath);
 
        // Generate builtin_key from filename (e.g., "explore-codebase.ts" -> "explore-codebase")
        const builtinKey = fileName
          .replace(/\.(ts|js)$/, '')
          .replace(/_/g, '-');
 
        Iif (!name) {
          this.logger.warn(
            `Skipping malformed seed file: ${fileName} (missing name)`,
          );
          continue;
        }
 
        // Find existing by builtin_key (for version updates)
        const existingAgent = await this.subAgentRepository.findOne({
          where: { builtin_key: builtinKey },
        });
 
        if (existingAgent && existingAgent.is_builtin) {
          // Update existing builtin sub-agent (version upgrade)
          // Resolve references again (they may have changed)
          let system_prompt_id: string | null = existingAgent.system_prompt_id;
          Iif (system_prompt_name) {
            const systemPrompt =
              await this.systemPromptsService.findByBuiltinKey(
                system_prompt_name.replace(/_/g, '-'),
              );
            system_prompt_id = systemPrompt?.id || null;
          }
 
          let context_template_id: string | null =
            existingAgent.context_template_id;
          Iif (context_template_name) {
            const contextTemplate =
              await this.contextTemplatesService.findByBuiltinKey(
                context_template_name.replace(/_/g, '-'),
              );
            context_template_id = contextTemplate?.id || null;
          }
 
          let followup_context_template_id: string | null =
            existingAgent.followup_context_template_id;
          Iif (followup_context_template_name) {
            const followupContextTemplate =
              await this.contextTemplatesService.findByBuiltinKey(
                followup_context_template_name.replace(/_/g, '-'),
              );
            followup_context_template_id = followupContextTemplate?.id || null;
          }
 
          // Update the builtin sub-agent
          existingAgent.description = description || existingAgent.description;
          existingAgent.system_prompt_id = system_prompt_id;
          existingAgent.context_template_id = context_template_id;
          existingAgent.followup_context_template_id =
            followup_context_template_id;
          existingAgent.enabled_tools =
            enabled_tools || existingAgent.enabled_tools;
          existingAgent.enabled_mcp_tools =
            enabled_mcp_tools !== undefined
              ? enabled_mcp_tools === 'all'
                ? 'all'
                : enabled_mcp_tools
                  ? JSON.stringify(enabled_mcp_tools)
                  : null
              : existingAgent.enabled_mcp_tools;
          existingAgent.model_id = model_id || existingAgent.model_id;
          existingAgent.is_active = is_active !== false;
 
          await this.subAgentRepository.save(existingAgent);
          this.logger.log(
            `Built-in sub-agent "${name}" updated (version upgrade).`,
          );
        } else if (existingAgent) {
          // User-created sub-agent with same builtin_key
          this.logger.warn(
            `Sub-agent with builtin_key "${builtinKey}" exists but is not built-in. Skipping.`,
          );
        } else {
          // Check if sub-agent with same name exists (legacy compatibility)
          const legacyAgent = existingAgentMap.get(name);
          if (legacyAgent) {
            // Legacy sub-agent without builtin_key - leave it alone
            this.logger.log(
              `Legacy sub-agent "${name}" exists without builtin_key. Skipping seed.`,
            );
          } else {
            // Resolve system prompt if specified
            let system_prompt_id: string | null = null;
            Iif (system_prompt_name) {
              const systemPrompt =
                await this.systemPromptsService.findByBuiltinKey(
                  system_prompt_name.replace(/_/g, '-'),
                );
              if (!systemPrompt) {
                this.logger.warn(
                  `System prompt with builtin_key "${system_prompt_name.replace(/_/g, '-')}" not found for sub-agent "${name}"`,
                );
              } else {
                system_prompt_id = systemPrompt.id;
              }
            }
 
            // Resolve context template if specified
            let context_template_id: string | null = null;
            Iif (context_template_name) {
              const contextTemplate =
                await this.contextTemplatesService.findByBuiltinKey(
                  context_template_name.replace(/_/g, '-'),
                );
              if (!contextTemplate) {
                this.logger.warn(
                  `Context template with builtin_key "${context_template_name.replace(/_/g, '-')}" not found for sub-agent "${name}"`,
                );
              } else {
                context_template_id = contextTemplate.id;
              }
            }
            // Resolve followup context template if specified
            let followup_context_template_id: string | null = null;
            Iif (followup_context_template_name) {
              const followupContextTemplate =
                await this.contextTemplatesService.findByBuiltinKey(
                  followup_context_template_name.replace(/_/g, '-'),
                );
              if (!followupContextTemplate) {
                this.logger.warn(
                  `Followup context template with builtin_key "${followup_context_template_name.replace(/_/g, '-')}" not found for sub-agent "${name}"`,
                );
              } else {
                followup_context_template_id = followupContextTemplate.id;
              }
            }
 
            // Create new builtin sub-agent
            const newAgent = this.subAgentRepository.create({
              name,
              description: description || null,
              system_prompt_id,
              context_template_id,
              followup_context_template_id,
              enabled_tools: enabled_tools || null,
              enabled_mcp_tools:
                enabled_mcp_tools === 'all'
                  ? 'all'
                  : enabled_mcp_tools
                    ? JSON.stringify(enabled_mcp_tools)
                    : null,
              model_id: model_id || null,
              is_active: is_active !== false, // Default to true
              is_builtin: true,
              builtin_key: builtinKey,
            });
 
            await this.subAgentRepository.save(newAgent);
            this.logger.log(`Built-in sub-agent "${name}" seeded.`);
          }
        }
      } catch (error) {
        this.logger.error(
          `Failed to seed sub-agent from ${filePath}`,
          error.stack,
        );
      }
    }
  }
}