feat: inbound calls in cal ai (#23890)

* feat: lang support

* fix: type errors

* feat: select voice agent

* refactor: address feedback

* refactor: address feedback

* refactor: missing import

* fix: types

* feat: add inbound calls

* chore: formatting

* chore

* feat: finish inbound call

* chore: formatting

* fix: update bug

* fix: types

* refactor: Agent Configuration Sheet (#23930)

* refactor: agent configuration sheet

* chore: use default phone numbre

* refactor: improvements

* refactor: improvements

* fix: types

* fix: feedback

* chore:

* fix: feedback

* fix: prompt

* fix: review

* fix: review

* refactor: class

* refactor: class

* refactor: rename

* Update apps/web/public/static/locales/en/common.json

* Update apps/web/public/static/locales/en/common.json

* chore: update set value

* fix: remove index

* fix: type error

* fix: update tetss

* fix: use logger

* refactor: don't use static

* fix: type

* fix: schema

* refactor:

---------

Co-authored-by: Carina Wollendorfer <[email protected]>
This commit is contained in:
Udit TakkarandCarina Wollendorfer authored and GitHub committed 2025-10-09 11:40:37 +01:00
1 parent bec49ef417
commit aa48e72c12
74 files changed
+2980 -1680

No files matched your search

@@ -56,7 +56,7 @@ describe("AIPhoneServiceRegistry", () => {
updatePhoneNumberWithAgents: vi.fn().mockResolvedValue({ message: "test-message" }),
listAgents: vi.fn().mockResolvedValue({ totalCount: 1, filtered: [] }),
getAgentWithDetails: vi.fn().mockResolvedValue({ agent_id: "test-agent" }),
createAgent: vi
createOutboundAgent: vi
.fn()
.mockResolvedValue({ id: "test-id", providerAgentId: "test-provider-id", message: "test-message" }),
updateAgentConfiguration: vi.fn().mockResolvedValue({ message: "test-message" }),
@@ -285,7 +285,7 @@ describe("createAIPhoneServiceProvider", () => {
updatePhoneNumberWithAgents: vi.fn(),
listAgents: vi.fn(),
getAgentWithDetails: vi.fn(),
createAgent: vi.fn(),
createOutboundAgent: vi.fn(),
updateAgentConfiguration: vi.fn(),
deleteAgent: vi.fn(),
createTestCall: vi.fn(),
@@ -410,7 +410,7 @@ describe("createDefaultAIPhoneServiceProvider", () => {
updatePhoneNumberWithAgents: vi.fn(),
listAgents: vi.fn(),
getAgentWithDetails: vi.fn(),
createAgent: vi.fn(),
createOutboundAgent: vi.fn(),
updateAgentConfiguration: vi.fn(),
deleteAgent: vi.fn(),
createTestCall: vi.fn(),
@@ -285,7 +285,7 @@ export interface AIPhoneServiceProvider<T extends AIPhoneServiceProviderType = A
/**
* Create a new agent
*/
createAgent(params: {
createOutboundAgent(params: {
name?: string;
userId: number;
teamId?: number;
@@ -301,6 +301,22 @@ export interface AIPhoneServiceProvider<T extends AIPhoneServiceProviderType = A
message: string;
}>;
/**
* Create a new inbound agent
*/
createInboundAgent(params: {
name?: string;
phoneNumber: string;
userId: number;
teamId?: number;
workflowStepId: number;
userTimeZone: string;
}): Promise<{
id: string;
providerAgentId: string;
message: string;
}>;
/**
* Update agent configuration
*/
@@ -53,7 +53,7 @@ export const DEFAULT_PROMPT_VALUE = `## You are helping user set up a call with
- if availability exists, inform user about the availability range (do not repeat the detailed available slot) and ask user to choose from it. Make sure user chose a slot within detailed available slot.
- if availability does not exist, ask user to select another time range for the appointment, repeat this step 3.
5. Confirm the date and time selected by user: \"Just to confirm, you want to book the appointment at ...\".
6. Once confirmed, you can use {{NUMBER_TO_CALL}} as phone number for creating booking and call function book_appointment_{{eventTypeId}} to book the appointment.
6. Once confirmed, you can use {{user_number}} if it is not unknown else ask user for phone number in international format and use it for creating booking if it is a required field and call function book_appointment_{{eventTypeId}} to book the appointment.
- if booking returned booking detail, it means booking is successful, proceed to step 7.
- if booking returned error message, let user know why the booking was not successful, and maybe start over with step 3.
7. Inform the user booking is successful, and ask if user have any questions. Answer them if there are any.
@@ -1,5 +1,5 @@
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
import prisma from "@calcom/prisma";
import type {
AgentRepositoryInterface,
AgentData,
@@ -13,18 +13,21 @@ import type {
*/
export class PrismaAgentRepositoryAdapter implements AgentRepositoryInterface {
async canManageTeamResources(params: { userId: number; teamId: number }): Promise<boolean> {
return await PrismaAgentRepository.canManageTeamResources(params);
const agentRepo = new PrismaAgentRepository(prisma);
return await agentRepo.canManageTeamResources(params);
}
async findByIdWithUserAccess(params: { agentId: string; userId: number }): Promise<AgentData | null> {
return await PrismaAgentRepository.findByIdWithUserAccess(params);
const agentRepo = new PrismaAgentRepository(prisma);
return await agentRepo.findByIdWithUserAccess(params);
}
async findByProviderAgentIdWithUserAccess(params: {
providerAgentId: string;
userId: number;
}): Promise<AgentData | null> {
return await PrismaAgentRepository.findByProviderAgentIdWithUserAccess(params);
const agentRepo = new PrismaAgentRepository(prisma);
return await agentRepo.findByProviderAgentIdWithUserAccess(params);
}
async findManyWithUserAccess(params: {
@@ -32,7 +35,8 @@ export class PrismaAgentRepositoryAdapter implements AgentRepositoryInterface {
teamId?: number;
scope?: "personal" | "team" | "all";
}): Promise<AgentWithDetailsData[]> {
return await PrismaAgentRepository.findManyWithUserAccess(params);
const agentRepo = new PrismaAgentRepository(prisma);
return await agentRepo.findManyWithUserAccess(params);
}
async findByIdWithUserAccessAndDetails(params: {
@@ -40,7 +44,8 @@ export class PrismaAgentRepositoryAdapter implements AgentRepositoryInterface {
userId: number;
teamId?: number;
}): Promise<AgentWithDetailsData | null> {
return await PrismaAgentRepository.findByIdWithUserAccessAndDetails(params);
const agentRepo = new PrismaAgentRepository(prisma);
return await agentRepo.findByIdWithUserAccessAndDetails(params);
}
async create(params: {
@@ -49,7 +54,8 @@ export class PrismaAgentRepositoryAdapter implements AgentRepositoryInterface {
userId: number;
teamId?: number;
}): Promise<AgentData> {
return await PrismaAgentRepository.create(params);
const agentRepo = new PrismaAgentRepository(prisma);
return await agentRepo.create(params);
}
async findByIdWithAdminAccess(params: {
@@ -57,21 +63,30 @@ export class PrismaAgentRepositoryAdapter implements AgentRepositoryInterface {
userId: number;
teamId?: number;
}): Promise<AgentData | null> {
return await PrismaAgentRepository.findByIdWithAdminAccess(params);
const agentRepo = new PrismaAgentRepository(prisma);
return await agentRepo.findByIdWithAdminAccess(params);
}
async findByIdWithCallAccess(params: {
id: string;
userId: number;
}): Promise<AgentWithPhoneNumbersData | null> {
return await PrismaAgentRepository.findByIdWithCallAccess(params);
const agentRepo = new PrismaAgentRepository(prisma);
return await agentRepo.findByIdWithCallAccess(params);
}
async delete(params: { id: string }): Promise<void> {
await PrismaAgentRepository.delete(params);
const agentRepo = new PrismaAgentRepository(prisma);
await agentRepo.delete(params);
}
async linkToWorkflowStep(params: { workflowStepId: number; agentId: string }): Promise<void> {
await PrismaAgentRepository.linkToWorkflowStep(params);
async linkOutboundAgentToWorkflow(params: { workflowStepId: number; agentId: string }): Promise<void> {
const agentRepo = new PrismaAgentRepository(prisma);
await agentRepo.linkOutboundAgentToWorkflow(params);
}
async linkInboundAgentToWorkflow(params: { workflowStepId: number; agentId: string }): Promise<void> {
const agentRepo = new PrismaAgentRepository(prisma);
await agentRepo.linkInboundAgentToWorkflow(params);
}
}
@@ -1,4 +1,5 @@
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import prisma from "@calcom/prisma";
import type { PhoneNumberSubscriptionStatus } from "@calcom/prisma/enums";
import type {
@@ -15,7 +16,8 @@ export class PrismaPhoneNumberRepositoryAdapter implements PhoneNumberRepository
phoneNumber: string;
userId: number;
}): Promise<PhoneNumberData | null> {
return await PrismaPhoneNumberRepository.findByPhoneNumberAndUserId(params);
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
return await phoneNumberRepo.findByPhoneNumberAndUserId(params);
}
async findByPhoneNumberAndTeamId(params: {
@@ -23,11 +25,13 @@ export class PrismaPhoneNumberRepositoryAdapter implements PhoneNumberRepository
teamId: number;
userId: number;
}): Promise<PhoneNumberData | null> {
return await PrismaPhoneNumberRepository.findByPhoneNumberAndTeamId(params);
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
return await phoneNumberRepo.findByPhoneNumberAndTeamId(params);
}
async findByIdAndUserId(params: { id: number; userId: number }): Promise<PhoneNumberData | null> {
return await PrismaPhoneNumberRepository.findByIdAndUserId(params);
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
return await phoneNumberRepo.findByIdAndUserId(params);
}
async findByIdWithTeamAccess(params: {
@@ -35,7 +39,8 @@ export class PrismaPhoneNumberRepositoryAdapter implements PhoneNumberRepository
teamId: number;
userId: number;
}): Promise<PhoneNumberData | null> {
return await PrismaPhoneNumberRepository.findByIdWithTeamAccess(params);
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
return await phoneNumberRepo.findByIdWithTeamAccess(params);
}
async createPhoneNumber(params: {
@@ -45,6 +50,7 @@ export class PrismaPhoneNumberRepositoryAdapter implements PhoneNumberRepository
teamId?: number;
outboundAgentId?: string | null;
}): Promise<PhoneNumberData> {
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
const createParams = {
phoneNumber: params.phoneNumber,
provider: params.provider,
@@ -52,19 +58,21 @@ export class PrismaPhoneNumberRepositoryAdapter implements PhoneNumberRepository
teamId: params.teamId,
};
return await PrismaPhoneNumberRepository.createPhoneNumber(createParams);
return await phoneNumberRepo.createPhoneNumber(createParams);
}
async deletePhoneNumber(params: { phoneNumber: string }): Promise<void> {
await PrismaPhoneNumberRepository.deletePhoneNumber(params);
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
await phoneNumberRepo.deletePhoneNumber(params);
}
async updateSubscriptionStatus(params: {
id: number;
subscriptionStatus: PhoneNumberSubscriptionStatus;
disconnectOutboundAgent?: boolean;
disconnectAgents?: boolean;
}): Promise<void> {
await PrismaPhoneNumberRepository.updateSubscriptionStatus(params);
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
await phoneNumberRepo.updateSubscriptionStatus(params);
}
async updateAgents(params: {
@@ -72,10 +80,23 @@ export class PrismaPhoneNumberRepositoryAdapter implements PhoneNumberRepository
inboundProviderAgentId?: string | null;
outboundProviderAgentId?: string | null;
}): Promise<void> {
await PrismaPhoneNumberRepository.updateAgents({
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
await phoneNumberRepo.updateAgents({
id: params.id,
inboundProviderAgentId: params.inboundProviderAgentId,
outboundProviderAgentId: params.outboundProviderAgentId,
});
}
async updateInboundAgentId(params: { id: number; agentId: string }): Promise<{ count: number }> {
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
return await phoneNumberRepo.updateInboundAgentId(params);
}
async findInboundAgentIdByPhoneNumberId(params: {
phoneNumberId: number;
}): Promise<{ inboundAgentId: string | null } | null> {
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
return await phoneNumberRepo.findInboundAgentIdByPhoneNumberId(params);
}
}
@@ -68,7 +68,12 @@ export interface AgentRepositoryInterface {
/**
* Link agent to workflow step
*/
linkToWorkflowStep(params: { workflowStepId: number; agentId: string }): Promise<void>;
linkOutboundAgentToWorkflow(params: { workflowStepId: number; agentId: string }): Promise<void>;
/**
* Link inbound agent to workflow
*/
linkInboundAgentToWorkflow(params: { workflowStepId: number; agentId: string }): Promise<void>;
}
/**
@@ -81,6 +86,7 @@ export interface AgentData {
enabled: boolean;
userId: number | null;
teamId: number | null;
inboundEventTypeId?: number | null;
createdAt: Date;
updatedAt: Date;
}
@@ -63,7 +63,7 @@ export interface PhoneNumberRepositoryInterface {
updateSubscriptionStatus(params: {
id: number;
subscriptionStatus: PhoneNumberSubscriptionStatus;
disconnectOutboundAgent?: boolean;
disconnectAgents?: boolean;
}): Promise<void>;
/**
@@ -74,6 +74,16 @@ export interface PhoneNumberRepositoryInterface {
inboundProviderAgentId?: string | null;
outboundProviderAgentId?: string | null;
}): Promise<void>;
/**
* Conditionally set inbound agent only if currently unset (atomic operation to prevent race conditions)
*/
updateInboundAgentId(params: { id: number; agentId: string }): Promise<{ count: number }>;
/**
* Find inbound agent by phone number ID
*/
findInboundAgentIdByPhoneNumberId(params: { phoneNumberId: number }): Promise<{ inboundAgentId: string | null } | null>;
}
/**
@@ -42,7 +42,7 @@ function createMockRetellAIService(overrides: Partial<RetellAIService> = {}): Re
updatePhoneNumberWithAgents: vi.fn(),
listAgents: vi.fn(),
getAgentWithDetails: vi.fn(),
createAgent: vi.fn(),
createOutboundAgent: vi.fn(),
updateAgentConfiguration: vi.fn(),
deleteAgent: vi.fn(),
createTestCall: vi.fn(),
@@ -67,7 +67,7 @@ describe("RetellAIPhoneServiceProvider", () => {
deleteLLM: vi.fn().mockResolvedValue(undefined),
// Agent operations
createAgent: vi.fn().mockResolvedValue({ agent_id: "test-agent-id" }),
createOutboundAgent: vi.fn().mockResolvedValue({ agent_id: "test-agent-id" }),
getAgent: vi.fn().mockResolvedValue({ agent_id: "test-agent-id", agent_name: "Test Agent" }),
updateAgent: vi.fn().mockResolvedValue({ agent_id: "test-agent-id" }),
deleteAgent: vi.fn().mockResolvedValue(undefined),
@@ -94,7 +94,7 @@ describe("RetellAIPhoneServiceProvider", () => {
findByIdWithAdminAccess: vi.fn(),
findByIdWithCallAccess: vi.fn(),
delete: vi.fn(),
linkToWorkflowStep: vi.fn(),
linkOutboundAgentToWorkflow: vi.fn(),
} as unknown as AgentRepositoryInterface;
// Mock phone number repository
@@ -210,7 +210,7 @@ export class RetellAIPhoneServiceProvider
return await this.service.getAgentWithDetails(params);
}
async createAgent(params: {
async createOutboundAgent(params: {
name?: string;
userId: number;
teamId?: number;
@@ -225,7 +225,27 @@ export class RetellAIPhoneServiceProvider
providerAgentId: string;
message: string;
}> {
const result = await this.service.createAgent(params);
const result = await this.service.createOutboundAgent(params);
return {
id: result.id,
providerAgentId: result.providerAgentId,
message: result.message,
};
}
async createInboundAgent(params: {
name?: string;
phoneNumber: string;
userId: number;
teamId?: number;
workflowStepId: number;
userTimeZone: string;
}): Promise<{
id: string;
providerAgentId: string;
message: string;
}> {
const result = await this.service.createInboundAgent(params);
return {
id: result.id,
providerAgentId: result.providerAgentId,
@@ -25,7 +25,7 @@ vi.mock("./RetellSDKClient", () => ({
getLLM: vi.fn(),
updateLLM: vi.fn(),
deleteLLM: vi.fn(),
createAgent: vi.fn(),
createOutboundAgent: vi.fn(),
getAgent: vi.fn(),
updateAgent: vi.fn(),
deleteAgent: vi.fn(),
@@ -72,7 +72,7 @@ vi.mock("../adapters/PrismaAgentRepositoryAdapter", () => ({
findByIdWithAdminAccess: vi.fn(),
findByIdWithCallAccess: vi.fn(),
delete: vi.fn(),
linkToWorkflowStep: vi.fn(),
linkOutboundAgentToWorkflow: vi.fn(),
})),
}));
@@ -11,30 +11,6 @@ import { RetellAIError } from "./errors";
import { createMockDatabaseAgent } from "./services/__tests__/test-utils";
import type { RetellAIRepository } from "./types";
vi.mock("@calcom/lib/server/repository/PrismaPhoneNumberRepository", () => ({
PrismaPhoneNumberRepository: {
createPhoneNumber: vi.fn(),
findByPhoneNumberAndUserId: vi.fn(),
deletePhoneNumber: vi.fn(),
updateAgents: vi.fn(),
updateSubscriptionStatus: vi.fn(),
findByIdAndUserId: vi.fn(),
},
}));
vi.mock("@calcom/lib/server/repository/PrismaAgentRepository", () => ({
PrismaAgentRepository: {
findByIdWithUserAccess: vi.fn(),
findByProviderAgentIdWithUserAccess: vi.fn(),
findManyWithUserAccess: vi.fn(),
findByIdWithUserAccessAndDetails: vi.fn(),
canManageTeamResources: vi.fn(),
create: vi.fn(),
linkToWorkflowStep: vi.fn(),
findByIdWithAdminAccess: vi.fn(),
delete: vi.fn(),
findByIdWithCallAccess: vi.fn(),
},
}));
vi.mock("@calcom/app-store/stripepayment/lib/customer", () => ({
getStripeCustomerIdFromUserId: vi.fn(),
@@ -104,7 +80,7 @@ describe("RetellAIService", () => {
getLLM: vi.fn(),
updateLLM: vi.fn(),
deleteLLM: vi.fn(),
createAgent: vi.fn(),
createOutboundAgent: vi.fn(),
getAgent: vi.fn(),
updateAgent: vi.fn(),
deleteAgent: vi.fn(),
@@ -128,7 +104,7 @@ describe("RetellAIService", () => {
findByIdWithAdminAccess: vi.fn(),
findByIdWithCallAccess: vi.fn(),
delete: vi.fn(),
linkToWorkflowStep: vi.fn(),
linkOutboundAgentToWorkflow: vi.fn(),
};
mockAgentRepository = agentRepository as unknown as AgentRepositoryInterface;
@@ -192,7 +168,7 @@ describe("RetellAIService", () => {
const mockLLM = { llm_id: "llm-123" };
const mockAgent = { agent_id: "agent-123" };
mockRepository.createLLM.mockResolvedValue(mockLLM);
mockRepository.createAgent.mockResolvedValue(mockAgent);
mockRepository.createOutboundAgent.mockResolvedValue(mockAgent);
const result = await service.setupAIConfiguration({});
@@ -215,7 +191,7 @@ describe("RetellAIService", () => {
const mockAgent = { agent_id: "agent-123" };
mockRepository.createLLM.mockResolvedValue(mockLLM);
mockRepository.createAgent.mockResolvedValue(mockAgent);
mockRepository.createOutboundAgent.mockResolvedValue(mockAgent);
await service.setupAIConfiguration({
calApiKey: "cal-key",
@@ -566,7 +542,7 @@ describe("RetellAIService", () => {
expect(mockRepository.updateLLM).toHaveBeenCalledWith("llm-123", {
general_prompt: "Updated prompt",
begin_message: "Updated message",
general_tools: null,
general_tools: undefined,
});
});
});
@@ -732,7 +708,7 @@ describe("RetellAIService", () => {
expect(mockPhoneNumberRepository.updateSubscriptionStatus).toHaveBeenCalledWith({
id: 1,
subscriptionStatus: PhoneNumberSubscriptionStatus.CANCELLED,
disconnectOutboundAgent: true,
disconnectAgents: true,
});
});
});
@@ -813,10 +789,10 @@ describe("RetellAIService", () => {
});
});
describe("createAgent", () => {
describe("createOutboundAgent", () => {
it("should create agent successfully", async () => {
mockRepository.createLLM.mockResolvedValue({ llm_id: "llm-123" });
mockRepository.createAgent.mockResolvedValue({ agent_id: "agent-123" });
mockRepository.createOutboundAgent.mockResolvedValue({ agent_id: "agent-123" });
mockAgentRepository.create.mockResolvedValue({
id: "db-agent-123",
name: "Test Agent",
@@ -828,7 +804,7 @@ describe("RetellAIService", () => {
updatedAt: new Date(),
});
const result = await service.createAgent({
const result = await service.createOutboundAgent({
name: "Test Agent",
userId: 1,
userTimeZone: "America/New_York",
@@ -996,7 +972,6 @@ describe("RetellAIService", () => {
it("should throw error if agent not found", async () => {
const { CreditService } = await import("@calcom/features/ee/billing/credit-service");
const { checkRateLimitAndThrowError } = await import("@calcom/lib/checkRateLimitAndThrowError");
const { PrismaAgentRepository } = await import("@calcom/lib/server/repository/PrismaAgentRepository");
// Mock sufficient credits
const mockHasAvailableCredits = vi.fn().mockResolvedValue(true);
@@ -1005,7 +980,7 @@ describe("RetellAIService", () => {
}));
(checkRateLimitAndThrowError as any).mockResolvedValue(undefined);
(PrismaAgentRepository.findByIdWithCallAccess as any).mockResolvedValue(null);
mockAgentRepository.findByIdWithCallAccess.mockResolvedValue(null);
await expect(
service.createTestCall({
@@ -41,17 +41,27 @@ export class RetellAIService {
private phoneNumberRepository: PhoneNumberRepositoryInterface,
private transactionManager: TransactionInterface
) {
this.aiConfigurationService = new AIConfigurationService(repository);
this.agentService = new AgentService(repository, agentRepository);
this.billingService = new BillingService(phoneNumberRepository, repository);
this.callService = new CallService(repository, agentRepository);
this.phoneNumberService = new PhoneNumberService(
repository,
this.aiConfigurationService = new AIConfigurationService({ retellRepository: repository });
this.agentService = new AgentService({
retellRepository: repository,
agentRepository,
phoneNumberRepository,
transactionManager
);
this.voiceService = new VoiceService(repository);
});
this.billingService = new BillingService({
phoneNumberRepository,
retellRepository: repository,
});
this.callService = new CallService({
retellRepository: repository,
agentRepository,
});
this.phoneNumberService = new PhoneNumberService({
retellRepository: repository,
agentRepository,
phoneNumberRepository,
transactionManager,
});
this.voiceService = new VoiceService({ retellRepository: repository });
// Inject RetellAIService reference into CallService
this.callService.setRetellAIService(this);
@@ -141,7 +151,7 @@ export class RetellAIService {
return this.agentService.getAgentWithDetails(params);
}
async createAgent(params: {
async createOutboundAgent(params: {
name?: string;
userId: number;
teamId?: number;
@@ -151,7 +161,7 @@ export class RetellAIService {
generalTools?: RetellLLMGeneralTools;
userTimeZone: string;
}) {
return this.agentService.createAgent({
return this.agentService.createOutboundAgent({
...params,
setupAIConfiguration: () =>
this.setupAIConfiguration({
@@ -165,6 +175,20 @@ export class RetellAIService {
});
}
async createInboundAgent(params: {
name?: string;
phoneNumber: string;
userId: number;
teamId?: number;
workflowStepId: number;
userTimeZone: string;
}) {
return this.agentService.createInboundAgent({
...params,
aiConfigurationService: this.aiConfigurationService,
});
}
async updateAgentConfiguration(params: {
id: string;
userId: number;
@@ -102,7 +102,7 @@ export class RetellAIServiceMapper {
return {
general_prompt: data.general_prompt,
begin_message: data.begin_message,
general_tools: data.general_tools ?? null,
general_tools: data.general_tools ?? undefined,
};
}
@@ -173,6 +173,7 @@ export class RetellAIServiceMapper {
enabled: agent.enabled,
userId: agent.userId,
teamId: agent.teamId,
inboundEventTypeId: agent.inboundEventTypeId,
outboundPhoneNumbers: agent.outboundPhoneNumbers,
retellData: {
agentId: retellAgent.agent_id,
@@ -218,7 +218,7 @@ describe("RetellSDKClient", () => {
client = new RetellSDKClient(mockLogger);
});
describe("createAgent", () => {
describe("createOutboundAgent", () => {
it("should create agent", async () => {
const mockRequest: CreateAgentRequest = {
agent_name: "Test Agent",
@@ -229,7 +229,7 @@ describe("RetellSDKClient", () => {
mockRetellInstance.agent.create.mockResolvedValue(mockResponse);
const result = await client.createAgent(mockRequest);
const result = await client.createOutboundAgent(mockRequest);
expect(mockRetellInstance.agent.create).toHaveBeenCalledWith(mockRequest);
expect(result).toEqual(mockResponse);
@@ -95,7 +95,7 @@ export class RetellSDKClient implements RetellAIRepository {
}
}
async createAgent(data: CreateAgentRequest): Promise<RetellAgent> {
async createOutboundAgent(data: CreateAgentRequest): Promise<RetellAgent> {
this.logger.info("Creating agent via SDK", {
agentName: data.agent_name,
});
@@ -14,10 +14,13 @@ import type {
DeletionResult,
} from "../types";
type Dependencies = {
retellRepository: RetellAIRepository;
};
export class AIConfigurationService {
private logger = logger.getSubLogger({ prefix: ["AIConfigurationService"] });
constructor(private retellRepository: RetellAIRepository) {}
constructor(private deps: Dependencies) {}
async setupAIConfiguration(config: AIConfigurationSetup): Promise<{ llmId: string; agentId: string }> {
let llmId: string | null = null;
@@ -35,19 +38,19 @@ export class AIConfigurationService {
);
// Step 1: Create LLM
const llm = await this.retellRepository.createLLM(llmRequest);
const llm = await this.deps.retellRepository.createLLM(llmRequest);
llmId = llm.llm_id;
// Step 2: Create Agent
const agentRequest = RetellAIServiceMapper.mapToCreateAgentRequest(llm.llm_id, config.eventTypeId);
const agent = await this.retellRepository.createAgent(agentRequest);
const agent = await this.deps.retellRepository.createOutboundAgent(agentRequest);
return { llmId: llm.llm_id, agentId: agent.agent_id };
} catch (error) {
// Compensation: Clean up LLM if agent creation failed
if (llmId) {
try {
await this.retellRepository.deleteLLM(llmId);
await this.deps.retellRepository.deleteLLM(llmId);
this.logger.info(`Successfully cleaned up orphaned LLM ${llmId} after setup failure`);
} catch (cleanupError) {
const errorMessage = `Failed to cleanup LLM ${llmId} after AI configuration setup failure. This will cause billing charges.`;
@@ -86,7 +89,7 @@ export class AIConfigurationService {
if (config.agentId) {
try {
this.logger.info(`Attempting to delete agent: ${config.agentId}`);
await this.retellRepository.deleteAgent(config.agentId);
await this.deps.retellRepository.deleteAgent(config.agentId);
result.deleted.agent = true;
this.logger.info(`Successfully deleted agent: ${config.agentId}`);
} catch (error) {
@@ -108,7 +111,7 @@ export class AIConfigurationService {
if (config.llmId) {
try {
this.logger.info(`Attempting to delete LLM: ${config.llmId}`);
await this.retellRepository.deleteLLM(config.llmId);
await this.deps.retellRepository.deleteLLM(config.llmId);
result.deleted.llm = true;
this.logger.info(`Successfully deleted LLM: ${config.llmId}`);
} catch (error) {
@@ -152,20 +155,25 @@ export class AIConfigurationService {
try {
const updateRequest = RetellAIServiceMapper.mapToUpdateLLMRequest(data);
return await this.retellRepository.updateLLM(llmId, updateRequest);
return await this.deps.retellRepository.updateLLM(llmId, updateRequest);
} catch (error) {
const errorMessage = error instanceof Error ? error.message : String(error);
throw new Error(`Failed to update LLM configuration for ${llmId}: ${errorMessage}`);
}
}
async setupInboundAIConfiguration(): Promise<{ llmId: string; agentId: string }> {
return this.setupAIConfiguration({});
}
async getLLMDetails(llmId: string): Promise<AIPhoneServiceModel<AIPhoneServiceProviderType.RETELL_AI>> {
if (!llmId?.trim()) {
throw new Error("LLM ID is required and cannot be empty");
}
try {
return await this.retellRepository.getLLM(llmId);
return await this.deps.retellRepository.getLLM(llmId);
} catch (error) {
this.logger.error(`Failed to get LLM details for '${llmId}'`, {
llmId,
@@ -1,5 +1,7 @@
import { isValidPhoneNumber } from "libphonenumber-js";
import { v4 as uuidv4 } from "uuid";
import { replaceEventTypePlaceholders } from "@calcom/features/ee/workflows/components/agent-configuration/utils/promptUtils";
import { RETELL_AI_TEST_MODE, RETELL_AI_TEST_EVENT_TYPE_MAP } from "@calcom/lib/constants";
import { timeZoneSchema } from "@calcom/lib/dayjs/timeZone.schema";
import { HttpError } from "@calcom/lib/http-error";
@@ -14,17 +16,20 @@ import type {
AIPhoneServiceTools,
} from "../../../interfaces/AIPhoneService.interface";
import type { AgentRepositoryInterface } from "../../interfaces/AgentRepositoryInterface";
import type { PhoneNumberRepositoryInterface } from "../../interfaces/PhoneNumberRepositoryInterface";
import { RetellAIServiceMapper } from "../RetellAIServiceMapper";
import type { RetellAIRepository, Language } from "../types";
import { getLlmId } from "../types";
type Dependencies = {
retellRepository: RetellAIRepository;
agentRepository: AgentRepositoryInterface;
phoneNumberRepository: PhoneNumberRepositoryInterface;
};
export class AgentService {
private logger = logger.getSubLogger({ prefix: ["AgentService"] });
constructor(
private retellRepository: RetellAIRepository,
private agentRepository: AgentRepositoryInterface
) {}
constructor(private deps: Dependencies) {}
private async createApiKey({ userId, teamId }: { userId: number; teamId?: number }) {
const apiKeyRepository = await PrismaApiKeyRepository.withGlobalPrisma();
@@ -45,7 +50,7 @@ export class AgentService {
}
try {
return await this.retellRepository.getAgent(agentId);
return await this.deps.retellRepository.getAgent(agentId);
} catch (error) {
this.logger.error("Failed to get agent from external AI service", {
agentId,
@@ -100,7 +105,7 @@ export class AgentService {
message: "Agent does not have an LLM configured.",
});
}
const llmDetails = await this.retellRepository.getLLM(llmId);
const llmDetails = await this.deps.retellRepository.getLLM(llmId);
if (!llmDetails) {
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
@@ -160,7 +165,7 @@ export class AgentService {
const updatedGeneralTools = [...existing, ...newEventTools];
await this.retellRepository.updateLLM(llmId, { general_tools: updatedGeneralTools });
await this.deps.retellRepository.updateLLM(llmId, { general_tools: updatedGeneralTools });
} catch (error) {
if (error instanceof HttpError) {
throw error;
@@ -211,7 +216,7 @@ export class AgentService {
});
}
const llmDetails = await this.retellRepository.getLLM(llmId);
const llmDetails = await this.deps.retellRepository.getLLM(llmId);
if (!llmDetails) {
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
@@ -227,7 +232,7 @@ export class AgentService {
const filteredTools = existing.filter((tool) => !toolNamesToRemove.includes(tool.name));
if (filteredTools.length !== existing.length) {
await this.retellRepository.updateLLM(llmId, { general_tools: filteredTools });
await this.deps.retellRepository.updateLLM(llmId, { general_tools: filteredTools });
this.logger.info("Removed event-specific tools from agent", {
agentId,
llmId,
@@ -281,7 +286,7 @@ export class AgentService {
});
}
const llmDetails = await this.retellRepository.getLLM(llmId);
const llmDetails = await this.deps.retellRepository.getLLM(llmId);
if (!llmDetails) {
throw new HttpError({ statusCode: 404, message: "LLM details not found." });
@@ -306,7 +311,7 @@ export class AgentService {
const toolNamesToRemove = toolsToRemove.map((tool) => tool.name);
const filteredTools = existing.filter((tool) => !toolNamesToRemove.includes(tool.name));
await this.retellRepository.updateLLM(llmId, { general_tools: filteredTools });
await this.deps.retellRepository.updateLLM(llmId, { general_tools: filteredTools });
this.logger.info("Cleaned up unused event-specific tools", {
agentId,
@@ -363,7 +368,7 @@ export class AgentService {
try {
const updateRequest = RetellAIServiceMapper.mapToUpdateAgentRequest(data);
return await this.retellRepository.updateAgent(agentId, updateRequest);
return await this.deps.retellRepository.updateAgent(agentId, updateRequest);
} catch (error) {
this.logger.error("Failed to update agent in external AI service", {
agentId,
@@ -386,7 +391,7 @@ export class AgentService {
teamId?: number;
scope?: "personal" | "team" | "all";
}) {
const agents = await this.agentRepository.findManyWithUserAccess({
const agents = await this.deps.agentRepository.findManyWithUserAccess({
userId,
teamId,
scope,
@@ -401,7 +406,7 @@ export class AgentService {
}
async getAgentWithDetails({ id, userId, teamId }: { id: string; userId: number; teamId?: number }) {
const agent = await this.agentRepository.findByIdWithUserAccessAndDetails({
const agent = await this.deps.agentRepository.findByIdWithUserAccessAndDetails({
id,
userId,
teamId,
@@ -425,7 +430,7 @@ export class AgentService {
});
}
const llmDetails = await this.retellRepository.getLLM(llmId);
const llmDetails = await this.deps.retellRepository.getLLM(llmId);
return RetellAIServiceMapper.formatAgentDetails(agent, retellAgent, llmDetails);
} catch (error) {
@@ -447,7 +452,7 @@ export class AgentService {
}
}
async createAgent({
async createOutboundAgent({
name: _name,
userId,
teamId,
@@ -463,7 +468,7 @@ export class AgentService {
const agentName = _name || `Agent - ${userId} ${uuidv4()}`;
if (teamId) {
const canManage = await this.agentRepository.canManageTeamResources({
const canManage = await this.deps.agentRepository.canManageTeamResources({
userId,
teamId,
});
@@ -477,7 +482,7 @@ export class AgentService {
const llmConfig = await setupAIConfiguration();
const agent = await this.agentRepository.create({
const agent = await this.deps.agentRepository.create({
name: agentName,
providerAgentId: llmConfig.agentId,
userId,
@@ -485,7 +490,7 @@ export class AgentService {
});
if (workflowStepId) {
await this.agentRepository.linkToWorkflowStep({
await this.deps.agentRepository.linkOutboundAgentToWorkflow({
workflowStepId,
agentId: agent.id,
});
@@ -498,6 +503,116 @@ export class AgentService {
};
}
async createInboundAgent({
name,
phoneNumber,
userId,
teamId,
workflowStepId,
aiConfigurationService,
}: {
name?: string;
phoneNumber: string;
userId: number;
teamId?: number;
workflowStepId: number;
aiConfigurationService: {
setupInboundAIConfiguration: () => Promise<{ llmId: string; agentId: string }>;
};
}) {
if (teamId) {
const canManage = await this.deps.agentRepository.canManageTeamResources({
userId,
teamId,
});
if (!canManage) {
throw new HttpError({
statusCode: 403,
message: "You don't have permission to create agents for this team.",
});
}
}
const isPhoneNumberValid = isValidPhoneNumber(phoneNumber);
if (!isPhoneNumberValid) {
throw new HttpError({
statusCode: 400,
message: "Invalid phone number",
});
}
let phoneNumberRecord;
if (teamId) {
phoneNumberRecord = await this.deps.phoneNumberRepository.findByPhoneNumberAndTeamId({
phoneNumber,
teamId,
userId,
});
} else {
phoneNumberRecord = await this.deps.phoneNumberRepository.findByPhoneNumberAndUserId({
phoneNumber,
userId,
});
}
if (!phoneNumberRecord) {
throw new HttpError({
statusCode: 404,
message: "Phone number not found or you don't have access to it",
});
}
if (phoneNumberRecord.inboundAgentId) {
throw new HttpError({
statusCode: 400,
message: "Inbound agent already configured for this phone number",
});
}
const agentName = name || `Inbound Agent - ${workflowStepId}`;
const llmConfig = await aiConfigurationService.setupInboundAIConfiguration();
const agent = await this.deps.agentRepository.create({
name: agentName,
providerAgentId: llmConfig.agentId,
userId,
teamId,
});
await this.deps.agentRepository.linkInboundAgentToWorkflow({
workflowStepId,
agentId: agent.id,
});
// Update the Retell phone number with the new inbound agent ID
await this.deps.retellRepository.updatePhoneNumber(phoneNumber, {
inbound_agent_id: llmConfig.agentId,
});
const updateInboundAgentIdResult = await this.deps.phoneNumberRepository.updateInboundAgentId({
id: phoneNumberRecord.id,
agentId: agent.id,
});
if (updateInboundAgentIdResult.count === 0) {
const conflictingAgentId = await this.deps.phoneNumberRepository.findInboundAgentIdByPhoneNumberId({
phoneNumberId: phoneNumberRecord.id,
});
throw new HttpError({
statusCode: 409,
message: `Inbound agent was configured by another request. Conflicting agent: ${conflictingAgentId}`,
});
}
return {
id: agent.id,
providerAgentId: agent.providerAgentId,
message: "Inbound agent created successfully",
};
}
async updateAgentConfiguration({
id,
userId,
@@ -524,7 +639,7 @@ export class AgentService {
data: AIPhoneServiceUpdateModelParams<AIPhoneServiceProviderType.RETELL_AI>
) => Promise<AIPhoneServiceModel<AIPhoneServiceProviderType.RETELL_AI>>;
}) {
const agent = await this.agentRepository.findByIdWithAdminAccess({
const agent = await this.deps.agentRepository.findByIdWithAdminAccess({
id,
userId,
teamId,
@@ -537,8 +652,13 @@ export class AgentService {
});
}
const updatedPrompt =
agent.inboundEventTypeId && generalPrompt
? replaceEventTypePlaceholders(generalPrompt, agent.inboundEventTypeId)
: generalPrompt;
const hasRetellUpdates =
generalPrompt !== undefined ||
updatedPrompt !== undefined ||
beginMessage !== undefined ||
generalTools !== undefined ||
voiceId !== undefined ||
@@ -551,10 +671,10 @@ export class AgentService {
if (
llmId &&
(generalPrompt !== undefined || beginMessage !== undefined || generalTools !== undefined)
(updatedPrompt !== undefined || beginMessage !== undefined || generalTools !== undefined)
) {
const llmUpdateData = RetellAIServiceMapper.extractLLMUpdateData(
generalPrompt,
updatedPrompt,
beginMessage,
generalTools
);
@@ -606,7 +726,7 @@ export class AgentService {
teamId?: number;
deleteAIConfiguration: (config: { agentId: string; llmId?: string }) => Promise<void>;
}) {
const agent = await this.agentRepository.findByIdWithAdminAccess({
const agent = await this.deps.agentRepository.findByIdWithAdminAccess({
id,
userId,
teamId,
@@ -637,7 +757,7 @@ export class AgentService {
});
}
await this.agentRepository.delete({ id });
await this.deps.agentRepository.delete({ id });
return { message: "Agent deleted successfully" };
}
@@ -20,10 +20,11 @@ const stripeErrorSchema = z.object({
export class BillingService {
private logger = logger.getSubLogger({ prefix: ["BillingService"] });
constructor(
private phoneNumberRepository: PhoneNumberRepositoryInterface,
private retellRepository: RetellAIRepository
private deps: {
phoneNumberRepository: PhoneNumberRepositoryInterface;
retellRepository: RetellAIRepository;
}
) {}
async generatePhoneNumberCheckoutSession({
@@ -112,12 +113,12 @@ export class BillingService {
}) {
// Find phone number with proper team authorization
const phoneNumber = teamId
? await this.phoneNumberRepository.findByIdWithTeamAccess({
? await this.deps.phoneNumberRepository.findByIdWithTeamAccess({
id: phoneNumberId,
teamId,
userId,
})
: await this.phoneNumberRepository.findByIdAndUserId({
: await this.deps.phoneNumberRepository.findByIdAndUserId({
id: phoneNumberId,
userId,
});
@@ -137,10 +138,10 @@ export class BillingService {
}
try {
await this.phoneNumberRepository.updateSubscriptionStatus({
await this.deps.phoneNumberRepository.updateSubscriptionStatus({
id: phoneNumberId,
subscriptionStatus: PhoneNumberSubscriptionStatus.CANCELLED,
disconnectOutboundAgent: false,
disconnectAgents: false,
});
try {
@@ -154,7 +155,7 @@ export class BillingService {
stripeMessage: "Subscription resource not found",
});
} else {
await this.phoneNumberRepository.updateSubscriptionStatus({
await this.deps.phoneNumberRepository.updateSubscriptionStatus({
id: phoneNumberId,
subscriptionStatus: PhoneNumberSubscriptionStatus.ACTIVE,
});
@@ -163,15 +164,15 @@ export class BillingService {
}
// Disconnnect agent after cancelling from stripe
await this.phoneNumberRepository.updateSubscriptionStatus({
await this.deps.phoneNumberRepository.updateSubscriptionStatus({
id: phoneNumberId,
subscriptionStatus: PhoneNumberSubscriptionStatus.CANCELLED,
disconnectOutboundAgent: true,
disconnectAgents: true,
});
// Delete the phone number from Retell, DB
try {
await this.retellRepository.deletePhoneNumber(phoneNumber.phoneNumber);
await this.deps.retellRepository.deletePhoneNumber(phoneNumber.phoneNumber);
} catch (error) {
this.logger.error("Failed to delete phone number from AI service, but subscription was cancelled:", {
error,
@@ -16,14 +16,16 @@ interface RetellAIServiceInterface {
): Promise<void>;
}
type Dependencies = {
retellRepository: RetellAIRepository;
agentRepository: AgentRepositoryInterface;
};
export class CallService {
private logger = logger.getSubLogger({ prefix: ["CallService"] });
private retellAIService?: RetellAIServiceInterface;
constructor(
private retellRepository: RetellAIRepository,
private agentRepository: AgentRepositoryInterface
) {}
constructor(private deps: Dependencies) {}
setRetellAIService(service: RetellAIServiceInterface): void {
this.retellAIService = service;
@@ -51,7 +53,7 @@ export class CallService {
const { fromNumber, toNumber, dynamicVariables } = data;
try {
return await this.retellRepository.createPhoneCall({
return await this.deps.retellRepository.createPhoneCall({
fromNumber,
toNumber,
dynamicVariables,
@@ -106,7 +108,7 @@ export class CallService {
});
}
const agent = await this.agentRepository.findByIdWithCallAccess({
const agent = await this.deps.agentRepository.findByIdWithCallAccess({
id: agentId,
userId,
});
@@ -193,7 +195,7 @@ export class CallService {
identifier: `web-call:${userId}`,
});
const agent = await this.agentRepository.findByIdWithCallAccess({
const agent = await this.deps.agentRepository.findByIdWithCallAccess({
id: agentId,
userId,
});
@@ -233,7 +235,7 @@ export class CallService {
};
try {
const webCall = await this.retellRepository.createWebCall({
const webCall = await this.deps.retellRepository.createWebCall({
agentId: agent.providerAgentId,
dynamicVariables,
});
@@ -306,7 +308,7 @@ export class CallService {
return [];
}
const callsResponse = await this.retellRepository.listCalls({
const callsResponse = await this.deps.retellRepository.listCalls({
filter_criteria: {
from_number: filters.fromNumber,
...(filters?.toNumber && { to_number: filters.toNumber }),
@@ -14,15 +14,16 @@ import type { TransactionInterface } from "../../interfaces/TransactionInterface
import { RetellAIServiceMapper } from "../RetellAIServiceMapper";
import type { RetellAIRepository } from "../types";
type Dependencies = {
retellRepository: RetellAIRepository;
agentRepository: AgentRepositoryInterface;
phoneNumberRepository: PhoneNumberRepositoryInterface;
transactionManager: TransactionInterface;
};
export class PhoneNumberService {
private logger = logger.getSubLogger({ prefix: ["PhoneNumberService"] });
constructor(
private retellRepository: RetellAIRepository,
private agentRepository: AgentRepositoryInterface,
private phoneNumberRepository: PhoneNumberRepositoryInterface,
private transactionManager: TransactionInterface
) {}
constructor(private deps: Dependencies) {}
async importPhoneNumber(
data: AIPhoneServiceImportPhoneNumberParamsExtended
@@ -46,8 +47,8 @@ export class PhoneNumberService {
};
try {
return await this.transactionManager.executeInTransaction(async (txContext) => {
transactionState.retellPhoneNumber = await this.retellRepository.importPhoneNumber({
return await this.deps.transactionManager.executeInTransaction(async (txContext) => {
transactionState.retellPhoneNumber = await this.deps.retellRepository.importPhoneNumber({
phone_number: rest.phone_number,
termination_uri: rest.termination_uri,
sip_trunk_auth_username: rest.sip_trunk_auth_username,
@@ -65,9 +66,12 @@ export class PhoneNumberService {
transactionState.databaseRecordCreated = true;
if (agent) {
await this.retellRepository.updatePhoneNumber(transactionState.retellPhoneNumber.phone_number, {
outbound_agent_id: agent.providerAgentId,
});
await this.deps.retellRepository.updatePhoneNumber(
transactionState.retellPhoneNumber.phone_number,
{
outbound_agent_id: agent.providerAgentId,
}
);
transactionState.agentAssigned = true;
}
@@ -83,7 +87,7 @@ export class PhoneNumberService {
data: AIPhoneServiceCreatePhoneNumberParams
): Promise<AIPhoneServicePhoneNumber<AIPhoneServiceProviderType.RETELL_AI> & { provider: string }> {
try {
const phoneNumber = await this.retellRepository.createPhoneNumber(data);
const phoneNumber = await this.deps.retellRepository.createPhoneNumber(data);
return {
...phoneNumber,
provider: AIPhoneServiceProviderType.RETELL_AI,
@@ -119,12 +123,12 @@ export class PhoneNumberService {
}
const phoneNumberToDelete = teamId
? await this.phoneNumberRepository.findByPhoneNumberAndTeamId({
? await this.deps.phoneNumberRepository.findByPhoneNumberAndTeamId({
phoneNumber,
teamId,
userId,
})
: await this.phoneNumberRepository.findByPhoneNumberAndUserId({
: await this.deps.phoneNumberRepository.findByPhoneNumberAndUserId({
phoneNumber,
userId,
});
@@ -150,7 +154,7 @@ export class PhoneNumberService {
}
try {
await this.retellRepository.updatePhoneNumber(phoneNumber, {
await this.deps.retellRepository.updatePhoneNumber(phoneNumber, {
inbound_agent_id: null,
outbound_agent_id: null,
});
@@ -161,10 +165,10 @@ export class PhoneNumberService {
});
}
await this.retellRepository.deletePhoneNumber(phoneNumber);
await this.deps.retellRepository.deletePhoneNumber(phoneNumber);
if (deleteFromDB) {
await this.phoneNumberRepository.deletePhoneNumber({ phoneNumber });
await this.deps.phoneNumberRepository.deletePhoneNumber({ phoneNumber });
}
}
@@ -179,7 +183,7 @@ export class PhoneNumberService {
}
try {
return await this.retellRepository.getPhoneNumber(phoneNumber);
return await this.deps.retellRepository.getPhoneNumber(phoneNumber);
} catch (error) {
this.logger.error("Failed to get phone number from external AI service", {
phoneNumber,
@@ -211,7 +215,7 @@ export class PhoneNumberService {
}
try {
return await this.retellRepository.updatePhoneNumber(phoneNumber, data);
return await this.deps.retellRepository.updatePhoneNumber(phoneNumber, data);
} catch (error) {
this.logger.error("Failed to update phone number in external AI service", {
phoneNumber,
@@ -246,12 +250,12 @@ export class PhoneNumberService {
}
const phoneNumberRecord = teamId
? await this.phoneNumberRepository.findByPhoneNumberAndTeamId({
? await this.deps.phoneNumberRepository.findByPhoneNumberAndTeamId({
phoneNumber,
teamId,
userId,
})
: await this.phoneNumberRepository.findByPhoneNumberAndUserId({
: await this.deps.phoneNumberRepository.findByPhoneNumberAndUserId({
phoneNumber,
userId,
});
@@ -285,7 +289,7 @@ export class PhoneNumberService {
});
}
await this.phoneNumberRepository.updateAgents({
await this.deps.phoneNumberRepository.updateAgents({
id: phoneNumberRecord.id,
inboundProviderAgentId: inboundAgentId,
outboundProviderAgentId: outboundAgentId,
@@ -296,7 +300,7 @@ export class PhoneNumberService {
private async validateTeamPermissions(userId: number, teamId?: number) {
if (teamId) {
const canManage = await this.agentRepository.canManageTeamResources({
const canManage = await this.deps.agentRepository.canManageTeamResources({
userId,
teamId,
});
@@ -319,7 +323,7 @@ export class PhoneNumberService {
let agent = null;
if (agentId) {
agent = await this.agentRepository.findByIdWithUserAccess({
agent = await this.deps.agentRepository.findByIdWithUserAccess({
agentId,
userId,
});
@@ -341,7 +345,7 @@ export class PhoneNumberService {
type: "inbound" | "outbound"
) {
if (agentId) {
const agent = await this.agentRepository.findByProviderAgentIdWithUserAccess({
const agent = await this.deps.agentRepository.findByProviderAgentIdWithUserAccess({
providerAgentId: agentId,
userId,
});
@@ -376,7 +380,7 @@ export class PhoneNumberService {
this.logger.warn("Attempting cleanup of Retell phone number due to transaction failure", {
phoneNumber: transactionState.retellPhoneNumber.phone_number,
});
await this.retellRepository.deletePhoneNumber(transactionState.retellPhoneNumber.phone_number);
await this.deps.retellRepository.deletePhoneNumber(transactionState.retellPhoneNumber.phone_number);
this.logger.info("Successfully cleaned up Retell phone number", {
phoneNumber: transactionState.retellPhoneNumber.phone_number,
});
@@ -22,7 +22,7 @@ This directory contains the refactored RetellAI services that follow the Single
**Responsibility**: Agent CRUD operations
- `createAgent()` - Create new agents
- `createOutboundAgent()` - Create new agents
- `updateAgent()` - Update agent properties
- `deleteAgent()` - Remove agents
- `listAgents()` - Get agent lists
@@ -83,7 +83,7 @@ const { llmId, agentId } = await aiConfigService.setupAIConfiguration({
});
// Create agent
const agent = await agentService.createAgent({
const agent = await agentService.createOutboundAgent({
name: 'Support Agent',
userId: 1,
userTimeZone: 'America/New_York',
@@ -3,19 +3,22 @@ import logger from "@calcom/lib/logger";
import type { RetellAIRepository, RetellVoice } from "../types";
type Dependencies = {
retellRepository: RetellAIRepository;
};
export class VoiceService {
private logger = logger.getSubLogger({ prefix: ["VoiceService"] });
constructor(private retellRepository: RetellAIRepository) {}
constructor(private deps: Dependencies) {}
async listVoices(): Promise<RetellVoice[]> {
try {
const voices = await this.retellRepository.listVoices();
const voices = await this.deps.retellRepository.listVoices();
this.logger.info("Retrieved voices successfully", {
count: voices.length,
});
return voices;
} catch (error) {
this.logger.error("Failed to list voices from external AI service", {
@@ -27,4 +30,4 @@ export class VoiceService {
});
}
}
}
}
@@ -11,7 +11,9 @@ describe("AIConfigurationService", () => {
vi.clearAllMocks();
mocks = setupBasicMocks();
service = new AIConfigurationService(mocks.mockRetellRepository);
service = new AIConfigurationService({
retellRepository: mocks.mockRetellRepository,
});
});
afterEach(() => {
@@ -30,7 +32,7 @@ describe("AIConfigurationService", () => {
const mockAgent = createMockAgent();
mocks.mockRetellRepository.createLLM.mockResolvedValue(mockLLM);
mocks.mockRetellRepository.createAgent.mockResolvedValue(mockAgent);
mocks.mockRetellRepository.createOutboundAgent.mockResolvedValue(mockAgent);
const result = await service.setupAIConfiguration(validConfig);
@@ -40,7 +42,7 @@ describe("AIConfigurationService", () => {
});
expect(mocks.mockRetellRepository.createLLM).toHaveBeenCalled();
expect(mocks.mockRetellRepository.createAgent).toHaveBeenCalled();
expect(mocks.mockRetellRepository.createOutboundAgent).toHaveBeenCalled();
});
it("should handle LLM creation failure", async () => {
@@ -48,7 +48,10 @@ describe("BillingService", () => {
});
stripe.subscriptions.cancel.mockResolvedValue({});
service = new BillingService(mocks.mockPhoneNumberRepository, mocks.mockRetellRepository);
service = new BillingService({
phoneNumberRepository: mocks.mockPhoneNumberRepository,
retellRepository: mocks.mockRetellRepository,
});
});
afterEach(() => {
@@ -166,12 +169,12 @@ describe("BillingService", () => {
expect(mocks.mockPhoneNumberRepository.updateSubscriptionStatus).toHaveBeenNthCalledWith(1, {
id: 1,
subscriptionStatus: PhoneNumberSubscriptionStatus.CANCELLED,
disconnectOutboundAgent: false,
disconnectAgents: false,
});
expect(mocks.mockPhoneNumberRepository.updateSubscriptionStatus).toHaveBeenNthCalledWith(2, {
id: 1,
subscriptionStatus: PhoneNumberSubscriptionStatus.CANCELLED,
disconnectOutboundAgent: true,
disconnectAgents: true,
});
expect(mocks.mockRetellRepository.deletePhoneNumber).toHaveBeenCalledWith("+1234567890");
});
@@ -294,17 +297,17 @@ describe("BillingService", () => {
// Should attempt to cancel
expect(stripe.subscriptions.cancel).toHaveBeenCalledWith("sub_123");
// Should update database twice: first CANCELLED (disconnectOutboundAgent: false), then final CANCELLED (disconnectOutboundAgent: true)
// Should update database twice: first CANCELLED (disconnectAgents: false), then final CANCELLED (disconnectAgents: true)
expect(mocks.mockPhoneNumberRepository.updateSubscriptionStatus).toHaveBeenCalledTimes(2);
expect(mocks.mockPhoneNumberRepository.updateSubscriptionStatus).toHaveBeenNthCalledWith(1, {
id: 1,
subscriptionStatus: PhoneNumberSubscriptionStatus.CANCELLED,
disconnectOutboundAgent: false,
disconnectAgents: false,
});
expect(mocks.mockPhoneNumberRepository.updateSubscriptionStatus).toHaveBeenNthCalledWith(2, {
id: 1,
subscriptionStatus: PhoneNumberSubscriptionStatus.CANCELLED,
disconnectOutboundAgent: true,
disconnectAgents: true,
});
});
@@ -330,7 +333,7 @@ describe("BillingService", () => {
expect(mocks.mockPhoneNumberRepository.updateSubscriptionStatus).toHaveBeenNthCalledWith(1, {
id: 1,
subscriptionStatus: PhoneNumberSubscriptionStatus.CANCELLED,
disconnectOutboundAgent: false,
disconnectAgents: false,
});
expect(mocks.mockPhoneNumberRepository.updateSubscriptionStatus).toHaveBeenNthCalledWith(2, {
id: 1,
@@ -36,7 +36,10 @@ describe("CallService", () => {
updateToolsFromAgentId: vi.fn().mockResolvedValue(undefined),
};
service = new CallService(mocks.mockRetellRepository, mocks.mockAgentRepository);
service = new CallService({
retellRepository: mocks.mockRetellRepository,
agentRepository: mocks.mockAgentRepository,
});
service.setRetellAIService(mockRetellAIService);
});
@@ -20,12 +20,12 @@ describe("PhoneNumberService", () => {
vi.clearAllMocks();
mocks = setupBasicMocks();
service = new PhoneNumberService(
mocks.mockRetellRepository,
mocks.mockAgentRepository,
mocks.mockPhoneNumberRepository,
mocks.mockTransactionManager
);
service = new PhoneNumberService({
retellRepository: mocks.mockRetellRepository,
agentRepository: mocks.mockAgentRepository,
phoneNumberRepository: mocks.mockPhoneNumberRepository,
transactionManager: mocks.mockTransactionManager,
});
});
afterEach(() => {
@@ -91,7 +91,7 @@ export const createMockRetellRepository = (): RetellAIRepository & {
getLLM: vi.fn(),
updateLLM: vi.fn(),
deleteLLM: vi.fn(),
createAgent: vi.fn(),
createOutboundAgent: vi.fn(),
getAgent: vi.fn(),
updateAgent: vi.fn(),
deleteAgent: vi.fn(),
@@ -117,7 +117,7 @@ export const createMockAgentRepository = (): AgentRepositoryInterface & {
findByIdWithAdminAccess: vi.fn(),
findByIdWithCallAccess: vi.fn(),
delete: vi.fn(),
linkToWorkflowStep: vi.fn(),
linkOutboundAgentToWorkflow: vi.fn(),
};
};
@@ -103,7 +103,7 @@ export type CreateAgentRequest = Retell.AgentCreateParams;
export type UpdateLLMRequest = Retell.LlmUpdateParams;
export type UpdateAgentRequest = Retell.AgentUpdateParams;
export type Agent = NonNullable<
Awaited<ReturnType<typeof PrismaAgentRepository.findByIdWithUserAccessAndDetails>>
Awaited<ReturnType<PrismaAgentRepository["findByIdWithUserAccessAndDetails"]>>
>;
export type RetellAgentWithDetails = {
@@ -113,6 +113,7 @@ export type RetellAgentWithDetails = {
enabled: boolean;
userId: number | null;
teamId: number | null;
inboundEventTypeId?: number | null;
outboundPhoneNumbers: Array<{
id: number;
phoneNumber: string;
@@ -167,7 +168,7 @@ export interface RetellAIRepository {
deleteLLM(llmId: string): Promise<void>;
// Agent operations
createAgent(data: CreateAgentRequest): Promise<RetellAgent>;
createOutboundAgent(data: CreateAgentRequest): Promise<RetellAgent>;
getAgent(agentId: string): Promise<RetellAgent>;
updateAgent(agentId: string, data: UpdateAgentRequest): Promise<RetellAgent>;
deleteAgent(agentId: string): Promise<void>;
@@ -181,7 +182,7 @@ export interface RetellAIRepository {
// Call operations
createPhoneCall(data: CreatePhoneCallParams): Promise<RetellCall>;
listCalls(params: RetellCallListParams): Promise<RetellCallListResponse>;
createWebCall(