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

97.91% Statements 47/48
75% Branches 6/8
100% Functions 11/11
100% Lines 44/44

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 15610x 10x 10x 10x     10x 21x       21x                   1x         1x       2x           2x       1x                   2x                           3x                 2x 2x   1x 1x       1x 1x 1x 1x   1x       1x             1x 1x   1x 1x 1x   1x   1x       2x                     2x 2x 1x         2x       2x       2x 1x     1x 1x   1x   1x       2x            
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { SubAgentRun, SubAgentRunStatus } from './sub-agent-run.entity';
 
@Injectable()
export class SubAgentRunsService {
  private readonly logger = new Logger(SubAgentRunsService.name);
 
  constructor(
    @InjectRepository(SubAgentRun)
    private readonly runsRepository: Repository<SubAgentRun>,
  ) {}
 
  async create(data: {
    parent_session_id: string;
    child_session_id: string;
    sub_agent_id: string;
    agent_name: string;
    initial_prompt: string;
  }): Promise<SubAgentRun> {
    const run = this.runsRepository.create({
      ...data,
      status: SubAgentRunStatus.RUNNING,
      started_at: new Date(),
    });
    return this.runsRepository.save(run);
  }
 
  async hasActiveRuns(parentSessionId: string): Promise<boolean> {
    const count = await this.runsRepository.count({
      where: {
        parent_session_id: parentSessionId,
        status: SubAgentRunStatus.RUNNING,
      },
    });
    return count > 0;
  }
 
  async getActiveRuns(parentSessionId: string): Promise<SubAgentRun[]> {
    return this.runsRepository.find({
      where: {
        parent_session_id: parentSessionId,
        status: SubAgentRunStatus.RUNNING,
      },
      relations: ['subAgent', 'childSession'],
    });
  }
 
  async getAllActiveRuns(): Promise<SubAgentRun[]> {
    return this.runsRepository.find({
      where: {
        status: SubAgentRunStatus.RUNNING,
      },
      relations: ['subAgent', 'childSession', 'parentSession'],
      order: {
        created_at: 'DESC',
      },
    });
  }
 
  async findByChildSessionId(
    childSessionId: string,
  ): Promise<SubAgentRun | null> {
    return this.runsRepository.findOne({
      where: { child_session_id: childSessionId },
    });
  }
 
  async markCompleted(
    childSessionId: string,
    result: string,
  ): Promise<SubAgentRun | null> {
    const run = await this.findByChildSessionId(childSessionId);
    if (!run) return null;
 
    const completedAt = new Date();
    const durationMs = run.started_at
      ? completedAt.getTime() - run.started_at.getTime()
      : null;
 
    run.status = SubAgentRunStatus.COMPLETED;
    run.completed_at = completedAt;
    run.result = result;
    run.duration_ms = durationMs;
 
    this.logger.log(
      `SubAgentRun ${run.id} completed. Duration: ${durationMs}ms`,
    );
 
    return this.runsRepository.save(run);
  }
 
  async markFailed(
    childSessionId: string,
    errorMessage: string,
  ): Promise<SubAgentRun | null> {
    const run = await this.findByChildSessionId(childSessionId);
    Iif (!run) return null;
 
    run.status = SubAgentRunStatus.FAILED;
    run.completed_at = new Date();
    run.error_message = errorMessage;
 
    this.logger.log(`SubAgentRun ${run.id} failed: ${errorMessage}`);
 
    return this.runsRepository.save(run);
  }
 
  async cancelAllActiveRuns(parentSessionId: string): Promise<number> {
    const result = await this.runsRepository.update(
      {
        parent_session_id: parentSessionId,
        status: SubAgentRunStatus.RUNNING,
      },
      {
        status: SubAgentRunStatus.CANCELLED,
        completed_at: new Date(),
      },
    );
 
    const count = result.affected || 0;
    if (count > 0) {
      this.logger.log(
        `Cancelled ${count} active subagent runs for session ${parentSessionId}`,
      );
    }
 
    return count;
  }
 
  async cancel(runId: string): Promise<SubAgentRun | null> {
    const run = await this.runsRepository.findOne({
      where: { id: runId, status: SubAgentRunStatus.RUNNING },
    });
 
    if (!run) {
      return null;
    }
 
    run.status = SubAgentRunStatus.CANCELLED;
    run.completed_at = new Date();
 
    this.logger.log(`Cancelled SubAgentRun ${runId}`);
 
    return this.runsRepository.save(run);
  }
 
  async findOne(runId: string): Promise<SubAgentRun | null> {
    return this.runsRepository.findOne({
      where: { id: runId },
      relations: ['subAgent', 'childSession'],
    });
  }
}