All files / core/mcp squad.service.ts

97.41% Statements 151/155
85.13% Branches 63/74
94.44% Functions 17/18
97.31% Lines 145/149

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 4841x 1x 1x 1x 1x                             1x 1x 1x 1x 1x 1x     1x   102x 102x 102x 102x 102x 102x       2x 2x 2x                     36x       42x 36x 36x 36x 36x   36x       36x   36x 4x 8x 8x 8x               8x     8x       2x 2x         32x   34x 34x               27x     25x     29x           22x       24x 22x 22x 22x 22x   22x       22x   22x 2x 4x 4x 4x               4x     4x       2x 2x         20x   20x 20x               9x     9x     11x               57x                                         42x 42x 3x     39x       39x 39x 39x 39x           39x     39x       39x   39x   39x             37x   2x             37x 2x         35x               35x 35x 35x 35x 35x                         35x                                             24x 24x       24x       24x 24x   24x 20x         20x 20x 20x           2x                 18x       1x             17x             17x   2x 2x     15x 15x 1x       18x     18x 18x 18x 18x           18x     18x   18x   18x               2x             16x 2x         14x             13x 13x 13x 13x 13x                         13x                               66x             96x 6x   90x 78x   12x             58x 58x 2x   56x     56x 4x   52x 52x            
import { Injectable } from '@nestjs/common';
import { readFile } from 'fs/promises';
import { resolve } from 'path';
import { render } from 'ejs';
import { randomUUID } from 'crypto';
import { IListRolesResponse } from
  '@gs-squad-mcp/core/mcp/contracts';
import { IStartSquadMembersStatelessPayload } from
  '@gs-squad-mcp/core/mcp/contracts';
import { IStartSquadMembersStatelessResponse } from
  '@gs-squad-mcp/core/mcp/contracts';
import { IStartSquadMemberOutputBase } from
  '@gs-squad-mcp/core/mcp/contracts';
import { IStartSquadMembersStatefulPayload } from
  '@gs-squad-mcp/core/mcp/contracts';
import { IStartSquadMembersStatefulResponse } from
  '@gs-squad-mcp/core/mcp/contracts';
import { IStartSquadMemberStatefulOutput } from
  '@gs-squad-mcp/core/mcp/contracts';
import { RoleRepositoryService } from '@gs-squad-mcp/core/roles';
import { PromptBuilderService } from '@gs-squad-mcp/core/prompt';
import { TemplateRendererService } from '@gs-squad-mcp/core/engine';
import { ProcessRunnerService } from '@gs-squad-mcp/core/engine';
import { SquadConfigService } from '@gs-squad-mcp/core/config';
import { SquadTelemetryService } from '../telemetry/squad-telemetry.service';
 
@Injectable()
export class SquadService {
  constructor(
    private readonly roleRepository: RoleRepositoryService,
    private readonly promptBuilder: PromptBuilderService,
    private readonly templateRenderer: TemplateRendererService,
    private readonly processRunner: ProcessRunnerService,
    private readonly configService: SquadConfigService,
    private readonly telemetry: SquadTelemetryService
  ) {}
 
  async listRoles(): Promise<IListRolesResponse> {
    const roles = await this.roleRepository.getAllRoles();
    return {
      roles: roles.map((role) => ({
        id: role.id,
        name: role.name,
        description: role.description
      }))
    };
  }
 
  async startSquadMembersStateless(
    payload: IStartSquadMembersStatelessPayload
  ): Promise<IStartSquadMembersStatelessResponse> {
    const originatorId = await this.telemetry.ensureSession({
      orchestratorChatId: payload.orchestratorChatId,
      workspaceId: payload.workspaceId
    });
    const label = payload.members.map((m) => m.roleId).join(' + ');
    const squad = await this.telemetry.createSquad(originatorId, label);
    const squadId = squad.squadId;
    const config = this.configService.getConfig();
    const workspaceRoot = process.cwd();
 
    const requiresSerial = this.requiresSerialExecution(
      config.engine,
      config.executionMode
    );
    const members: IStartSquadMemberOutputBase[] = [];
 
    if (requiresSerial) {
      for (let index = 0; index < payload.members.length; index += 1) {
        const memberInput = payload.members[index];
        const memberId = this.generateMemberId(squadId, index);
        const result = await this.executeStatelessMember(
          memberInput,
          memberId,
          squadId,
          originatorId,
          config,
          workspaceRoot
        );
        members.push(result);
 
        // If not last member, delay before next execution
        if (
          index < payload.members.length - 1 &&
          config.sequentialDelayMs > 0
        ) {
          await new Promise((resolve) =>
            setTimeout(resolve, config.sequentialDelayMs)
          );
        }
      }
    } else {
      const parallelResults = await Promise.all(
        payload.members.map(async (memberInput, index) => {
          const memberId = this.generateMemberId(squadId, index);
          const res = await this.executeStatelessMember(
          memberInput,
          memberId,
          squadId,
          originatorId,
          config,
          workspaceRoot
        );
          return res;
      })
    );
      members.push(...parallelResults);
    }
 
    return { squadId, members };
  }
 
  async startSquadMembersStateful(
    payload: IStartSquadMembersStatefulPayload
  ): Promise<IStartSquadMembersStatefulResponse> {
    const originatorId = await this.telemetry.ensureSession({
      orchestratorChatId: payload.orchestratorChatId,
      workspaceId: payload.workspaceId
    });
    const label = payload.members.map((m) => m.roleId).join(' + ');
    const squad = await this.telemetry.createSquad(originatorId, label);
    const squadId = squad.squadId;
    const config = this.configService.getConfig();
    const workspaceRoot = process.cwd();
 
    const requiresSerial = this.requiresSerialExecution(
      config.engine,
      config.executionMode
    );
    const members: IStartSquadMemberStatefulOutput[] = [];
 
    if (requiresSerial) {
      for (let index = 0; index < payload.members.length; index += 1) {
        const memberInput = payload.members[index];
        const memberId = this.generateMemberId(squadId, index);
        const result = await this.executeStatefulMember(
          memberInput,
          memberId,
          squadId,
          originatorId,
          config,
          workspaceRoot
        );
        members.push(result);
 
        // If not last member, delay before next execution
        if (
          index < payload.members.length - 1 &&
          config.sequentialDelayMs > 0
        ) {
          await new Promise((resolve) =>
            setTimeout(resolve, config.sequentialDelayMs)
          );
        }
      }
    } else {
      const parallelResults = await Promise.all(
        payload.members.map(async (memberInput, index) => {
          const memberId = this.generateMemberId(squadId, index);
          const res = await this.executeStatefulMember(
          memberInput,
          memberId,
          squadId,
          originatorId,
          config,
          workspaceRoot
        );
          return res;
      })
    );
      members.push(...parallelResults);
    }
 
    return { squadId, members };
  }
 
  /**
   * Escapes a prompt string for safe use in double-quoted shell arguments.
   * Escapes special characters and converts newlines to literal \n.
   */
  private escapePromptForShell(prompt: string): string {
    return prompt
      .replace(/\\/g, '\\\\') // Escape backslashes first
      .replace(/\$/g, '\\$') // Escape dollar signs
      .replace(/`/g, '\\`') // Escape backticks
      .replace(/"/g, '\\"') // Escape double quotes
      .replace(/\n/g, '\\n') // Convert newlines to literal \n
      .replace(/\r/g, ''); // Remove carriage returns
  }
 
  private async executeStatelessMember(
    memberInput: {
      roleId: string;
      task: string;
      cwd?: string;
    },
    memberId: string,
    squadId: string,
    originatorId: string,
    config: ReturnType<typeof this.configService.getConfig>,
    workspaceRoot: string
  ): Promise<IStartSquadMemberOutputBase> {
    const role = await this.roleRepository.getRoleById(memberInput.roleId);
    if (!role) {
      throw new Error(`Role not found: ${memberInput.roleId}`);
    }
 
    const rawPrompt = this.promptBuilder.buildPromptStateless(
      role,
      memberInput.task
    );
    const prompt = this.escapePromptForShell(rawPrompt);
    let agentIdForTelemetry: string | null = null;
    try {
      const agent = await this.telemetry.createAgent(
        squadId,
        role.name,
        memberInput.task,
        rawPrompt
      );
      agentIdForTelemetry = agent.agentId;
    } catch {}
 
    const resolvedCwd = memberInput.cwd
      ? resolve(workspaceRoot, memberInput.cwd)
      : workspaceRoot;
 
    const templateContent = await readFile(config.runTemplatePath, 'utf-8');
    let renderedCommand: string;
    try {
      // Render the template to get the full command string
      const rendered = render(templateContent, {
        prompt,
        cwd: resolvedCwd,
        roleId: memberInput.roleId,
        task: memberInput.task,
        chatId: undefined // Not used in stateless mode, but needed for template
      });
      renderedCommand = rendered.trim();
    } catch (error) {
      throw new Error(
        `Failed to render template ${config.runTemplatePath}: ${
          error instanceof Error ? error.message : String(error)
        }`
      );
    }
 
    if (!renderedCommand || renderedCommand.length === 0) {
      throw new Error(
        `Template ${config.runTemplatePath} rendered to empty command`
      );
    }
 
    const result = await this.processRunner.runProcess(
      renderedCommand,
      [],
      resolvedCwd,
      config.processTimeoutMs
    );
 
    // Update telemetry
    Eif (agentIdForTelemetry) {
      const finishedIso = new Date().toISOString();
      const statusNow = this.mapStatus(result.exitCode, result.timedOut);
      try {
        await this.telemetry.updateAgentStatus(
          originatorId,
          agentIdForTelemetry,
          {
            status: statusNow === 'completed' ? 'done' : 'error',
            result: result.stdout,
            error: result.stderr,
            finishedAt: finishedIso
          }
        );
      } catch {}
    }
 
    return {
      memberId,
      roleId: memberInput.roleId,
      cwd: memberInput.cwd,
      status: this.mapStatus(result.exitCode, result.timedOut),
      rawStdout: result.stdout,
      rawStderr: result.stderr
    };
  }
 
  private async executeStatefulMember(
    memberInput: {
      roleId: string;
      task: string;
      cwd?: string;
      chatId?: string | null;
    },
    memberId: string,
    squadId: string,
    originatorId: string,
    config: ReturnType<typeof this.configService.getConfig>,
    workspaceRoot: string
  ): Promise<IStartSquadMemberStatefulOutput> {
    const role = await this.roleRepository.getRoleById(memberInput.roleId);
    Iif (!role) {
      throw new Error(`Role not found: ${memberInput.roleId}`);
    }
 
    const resolvedCwd = memberInput.cwd
      ? resolve(workspaceRoot, memberInput.cwd)
      : workspaceRoot;
 
    const hadChatId = !!memberInput.chatId;
    let chatId = memberInput.chatId || null;
 
    if (!chatId && config.createChatTemplatePath) {
      const createChatTemplate = await readFile(
        config.createChatTemplatePath,
        'utf-8'
      );
      let renderedCreateChatCommand: string;
      try {
        const generatedUuid = randomUUID();
        renderedCreateChatCommand = render(createChatTemplate, {
          roleId: memberInput.roleId,
          cwd: resolvedCwd,
          generatedUuid
        }).trim();
      } catch (error) {
        throw new Error(
          `Failed to render create-chat template ${
            config.createChatTemplatePath
          }: ${
            error instanceof Error ? error.message : String(error)
          }`
        );
      }
 
      if (
        !renderedCreateChatCommand ||
        renderedCreateChatCommand.length === 0
      ) {
        throw new Error(
          `Create-chat template ${
            config.createChatTemplatePath
          } rendered to empty command`
        );
      }
 
      const createChatResult = await this.processRunner.runProcess(
        renderedCreateChatCommand,
        [],
        resolvedCwd,
        config.processTimeoutMs
      );
 
      if (createChatResult.exitCode !== 0) {
        const errorMsg =
          createChatResult.stderr || createChatResult.stdout;
        throw new Error(`Failed to create chat: ${errorMsg}`);
      }
 
      chatId = createChatResult.stdout.trim();
      if (!chatId) {
        throw new Error('Failed to extract chatId from create-chat output');
      }
    }
 
    const rawPrompt = hadChatId
      ? this.promptBuilder.buildPromptStatefulExistingChat(memberInput.task)
      : this.promptBuilder.buildPromptStatefulNewChat(role, memberInput.task);
    const prompt = this.escapePromptForShell(rawPrompt);
    let agentIdForTelemetry: string | null = null;
    try {
      const agent = await this.telemetry.createAgent(
        squadId,
        role.name,
        memberInput.task,
        rawPrompt
      );
      agentIdForTelemetry = agent.agentId;
    } catch {}
 
    const runTemplateContent = await readFile(config.runTemplatePath, 'utf-8');
    let renderedRunCommand: string;
    try {
      // Render the template to get the full command string
      renderedRunCommand = render(runTemplateContent, {
        prompt,
        chatId: chatId || undefined,
        cwd: resolvedCwd,
        roleId: memberInput.roleId,
        task: memberInput.task
      }).trim();
    } catch (error) {
      throw new Error(
        `Failed to render template ${config.runTemplatePath}: ${
          error instanceof Error ? error.message : String(error)
        }`
      );
    }
 
    if (!renderedRunCommand || renderedRunCommand.length === 0) {
      throw new Error(
        `Template ${config.runTemplatePath} rendered to empty command`
      );
    }
 
    const result = await this.processRunner.runProcess(
      renderedRunCommand,
      [],
      resolvedCwd,
      config.processTimeoutMs
    );
 
    Eif (agentIdForTelemetry) {
      const finishedIso = new Date().toISOString();
      const statusNow = this.mapStatus(result.exitCode, result.timedOut);
      try {
        await this.telemetry.updateAgentStatus(
          originatorId,
          agentIdForTelemetry,
          {
            status: statusNow === 'completed' ? 'done' : 'error',
            result: result.stdout,
            error: result.stderr,
            finishedAt: finishedIso
          }
        );
      } catch {}
    }
 
    return {
      memberId,
      roleId: memberInput.roleId,
      cwd: memberInput.cwd,
      chatId: chatId!,
      status: this.mapStatus(result.exitCode, result.timedOut),
      rawStdout: result.stdout,
      rawStderr: result.stderr
    };
  }
 
  private generateSquadId(): string {
    return `squad-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
  }
 
  private generateMemberId(squadId: string, index: number): string {
    return `${squadId}-m${index}`;
  }
 
  private mapStatus(
    exitCode: number | null,
    timedOut: boolean
  ): 'completed' | 'error' | 'timeout' {
    if (timedOut) {
      return 'timeout';
    }
    if (exitCode === 0) {
      return 'completed';
    }
    return 'error';
  }
 
  private requiresSerialExecution(
    engine: 'cursor-agent' | 'claude' | 'codex',
    executionMode?: 'sequential' | 'parallel'
  ): boolean {
    const envOverride = process.env.PROCESS_RUNNER_SERIALIZE;
    if (envOverride === 'true') {
      return true;
    }
    Iif (envOverride === 'false') {
      return false;
    }
    if (executionMode === 'sequential') {
      return true;
    }
    Eif (executionMode === 'parallel') {
      return false;
    }
    return engine === 'cursor-agent';
  }
}