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

@@ -7,8 +7,10 @@ import { ZDeleteInputSchema } from "./delete.schema";
import { ZGetInputSchema } from "./get.schema";
import { ZListInputSchema } from "./list.schema";
import { ZListCallsInputSchema } from "./listCalls.schema";
import { ZSetupInboundAgentInputSchema } from "./setupInboundAgent.schema";
import { ZTestCallInputSchema } from "./testCall.schema";
import { ZUpdateInputSchema } from "./update.schema";
import { ZUpdateInboundAgentEventTypeInputSchema } from "./updateInboundAgentEventType.schema";
export const aiVoiceAgentRouter = router({
list: authedProcedure.input(ZListInputSchema).query(async ({ ctx, input }) => {
@@ -72,7 +74,7 @@ export const aiVoiceAgentRouter = router({
ctx,
input,
});
}),
}),
createWebCall: eventOwnerProcedure.input(ZCreateWebCallInputSchema).mutation(async ({ ctx, input }) => {
const { createWebCallHandler } = await import("./createWebCall.handler");
@@ -90,4 +92,24 @@ export const aiVoiceAgentRouter = router({
ctx,
});
}),
setupInboundAgent: authedProcedure.input(ZSetupInboundAgentInputSchema).mutation(async ({ ctx, input }) => {
const { setupInboundAgentHandler } = await import("./setupInboundAgent.handler");
return setupInboundAgentHandler({
ctx,
input,
});
}),
updateInboundAgentEventType: eventOwnerProcedure
.input(ZUpdateInboundAgentEventTypeInputSchema)
.mutation(async ({ ctx, input }) => {
const { updateInboundAgentEventTypeHandler } = await import("./updateInboundAgentEventType.handler");
return updateInboundAgentEventTypeHandler({
ctx,
input,
});
}),
});
@@ -22,7 +22,7 @@ export const createHandler = async ({ ctx, input }: CreateHandlerOptions) => {
?.generalPrompt
: undefined;
return await aiService.createAgent({
return await aiService.createOutboundAgent({
name,
userId: ctx.user.id,
teamId,
@@ -0,0 +1,53 @@
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import { HttpError } from "@calcom/lib/http-error";
import logger from "@calcom/lib/logger";
import { TRPCError } from "@trpc/server";
import type { TrpcSessionUser } from "../../../types";
import type { TSetupInboundAgentInputSchema } from "./setupInboundAgent.schema";
type SetupInboundAgentHandlerOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TSetupInboundAgentInputSchema;
};
export const setupInboundAgentHandler = async ({ ctx, input }: SetupInboundAgentHandlerOptions) => {
const log = logger.getSubLogger({ prefix: ["setupInboundAgentHandler"] });
try {
const { phoneNumber, teamId, workflowStepId } = input;
const userId = ctx.user.id;
const userTimeZone = ctx.user.timeZone || "UTC";
const aiService = createDefaultAIPhoneServiceProvider();
const createAgentResult = await aiService.createInboundAgent({
name: `Inbound Agent - ${phoneNumber}`,
phoneNumber,
userId,
teamId,
workflowStepId,
userTimeZone,
});
return {
success: true,
agentId: createAgentResult.id,
message: "Inbound agent configured successfully",
};
} catch (error) {
log.error("Failed to setup inbound agent", { error });
if (error instanceof HttpError) {
throw error;
}
throw new TRPCError({
code: "INTERNAL_SERVER_ERROR",
message: "Failed to setup inbound agent",
});
}
};
@@ -0,0 +1,9 @@
import { z } from "zod";
export const ZSetupInboundAgentInputSchema = z.object({
phoneNumber: z.string(),
teamId: z.number().optional(),
workflowStepId: z.number(),
});
export type TSetupInboundAgentInputSchema = z.infer<typeof ZSetupInboundAgentInputSchema>;
@@ -2,7 +2,7 @@ import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone
import { FeaturesRepository } from "@calcom/features/flags/features.repository";
import logger from "@calcom/lib/logger";
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
import { prisma } from "@calcom/prisma";
import prisma from "@calcom/prisma";
import { TRPCError } from "@trpc/server";
@@ -27,7 +27,8 @@ export const testCallHandler = async ({ ctx, input }: TestCallHandlerOptions) =>
return;
}
const agent = await PrismaAgentRepository.findByIdWithCallAccess({
const agentRepo = new PrismaAgentRepository(prisma);
const agent = await agentRepo.findByIdWithCallAccess({
id: input.agentId,
userId: ctx.user.id,
});
@@ -0,0 +1,71 @@
import { createDefaultAIPhoneServiceProvider } from "@calcom/features/calAIPhone";
import { replaceEventTypePlaceholders } from "@calcom/features/ee/workflows/components/agent-configuration/utils/promptUtils";
import logger from "@calcom/lib/logger";
import { PrismaAgentRepository } from "@calcom/lib/server/repository/PrismaAgentRepository";
import prisma from "@calcom/prisma";
import type { TrpcSessionUser } from "../../../types";
import type { TUpdateInboundAgentEventTypeInputSchema } from "./updateInboundAgentEventType.schema";
type UpdateInboundAgentEventTypeHandlerOptions = {
ctx: {
user: NonNullable<TrpcSessionUser>;
};
input: TUpdateInboundAgentEventTypeInputSchema;
};
export const updateInboundAgentEventTypeHandler = async ({
ctx,
input,
}: UpdateInboundAgentEventTypeHandlerOptions) => {
const log = logger.getSubLogger({ prefix: ["updateInboundAgentEventTypeHandler"] });
try {
const { agentId, eventTypeId, teamId } = input;
const userId = ctx.user.id;
const userTimeZone = ctx.user.timeZone || "UTC";
const aiService = createDefaultAIPhoneServiceProvider();
const agentDetails = await aiService.getAgentWithDetails({
id: agentId,
userId,
teamId,
});
if (!agentDetails.retellData.generalPrompt) {
throw new Error("Agent configuration not found");
}
// Replace placeholders in the prompt with the specific event type ID
const updatedPrompt = replaceEventTypePlaceholders(agentDetails.retellData.generalPrompt, eventTypeId);
// Update tools and prompt using existing updateAgentConfiguration method
await aiService.updateToolsFromAgentId(agentDetails.retellData.agentId, {
eventTypeId,
timeZone: userTimeZone,
userId,
teamId,
});
const result = await aiService.updateAgentConfiguration({
id: agentId,
userId,
teamId,
generalPrompt: updatedPrompt,
});
const agentRepo = new PrismaAgentRepository(prisma);
await agentRepo.updateEventTypeId({
agentId,
eventTypeId,
});
return {
success: true,
message: result.message,
};
} catch (error) {
log.error("Failed to update inbound agent prompt", { error });
throw error;
}
};
@@ -0,0 +1,9 @@
import { z } from "zod";
export const ZUpdateInboundAgentEventTypeInputSchema = z.object({
agentId: z.string(),
eventTypeId: z.number(),
teamId: z.number().optional(),
});
export type TUpdateInboundAgentEventTypeInputSchema = z.infer<typeof ZUpdateInboundAgentEventTypeInputSchema>;
@@ -1,4 +1,5 @@
import { PrismaPhoneNumberRepository } from "@calcom/lib/server/repository/PrismaPhoneNumberRepository";
import prisma from "@calcom/prisma";
import type { TrpcSessionUser } from "../../../types";
import type { TListInputSchema } from "./list.schema";
@@ -11,7 +12,8 @@ type ListHandlerOptions = {
};
export const listHandler = async ({ ctx, input }: ListHandlerOptions) => {
return await PrismaPhoneNumberRepository.findManyWithUserAccess({
const phoneNumberRepo = new PrismaPhoneNumberRepository(prisma);
return await phoneNumberRepo.findManyWithUserAccess({
userId: ctx.user.id,
teamId: input?.teamId,
scope: input?.scope || "all",
@@ -3,6 +3,7 @@ import { WorkflowRepository } from "@calcom/lib/server/repository/workflow";
import { prisma } from "@calcom/prisma";
import { WorkflowActions } from "@calcom/prisma/enums";
import type { TrpcSessionUser } from "@calcom/trpc/server/types";
import logger from "@calcom/lib/logger";
import { TRPCError } from "@trpc/server";
@@ -22,6 +23,7 @@ type DeleteOptions = {
export const deleteHandler = async ({ ctx, input }: DeleteOptions) => {
const { id } = input;
const log = logger.getSubLogger({ prefix: ["workflows/deleteHandler"] });
const workflowToDelete = await prisma.workflow.findUnique({
where: {
@@ -56,6 +58,11 @@ export const deleteHandler = async ({ ctx, input }: DeleteOptions) => {
},
},
},
inboundAgent: {
select: {
id: true,
},
},
},
},
team: {
@@ -100,7 +107,7 @@ export const deleteHandler = async ({ ctx, input }: DeleteOptions) => {
});
}
} catch (error) {
console.error(`Failed to handle phone number ${phoneNumber.phoneNumber}:`, error);
log.error(`Failed to handle phone number ${phoneNumber.phoneNumber}:`, error);
}
}
}
@@ -113,8 +120,19 @@ export const deleteHandler = async ({ ctx, input }: DeleteOptions) => {
teamId: workflowToDelete.teamId ?? undefined,
});
} catch (error) {
console.error(`Failed to delete agent ${step.agent.id}:`, error);
// Continue with deletion even if agent deletion fails
log.error(`Failed to delete agent ${step.agent.id}:`, error);
}
}
if (step.inboundAgent) {
try {
await aiPhoneService.deleteAgent({
id: step.inboundAgent.id,
userId: ctx.user.id,
teamId: workflowToDelete.teamId ?? undefined,
});
} catch (error) {
log.error(`Failed to delete inbound agent ${step.inboundAgent.id}:`, error);
}
}
}
@@ -440,6 +440,22 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
log.error(message);
}
if (oldStep.inboundAgentId) {
try {
await aiPhoneService.deleteAgent({
id: oldStep.inboundAgentId,
userId: user.id,
teamId: userWorkflow.teamId ?? undefined,
});
} catch (error) {
const message = `Failed to delete inbound agent ${
oldStep.inboundAgentId
} from external service: ${error instanceof Error ? error.message : "Unknown error"}`;
externalErrors.push(message);
log.error(message);
}
}
// If there were external errors, we should log them for manual cleanup
// but the operation is considered successful since DB is consistent
if (externalErrors.length > 0) {
@@ -459,6 +475,7 @@ export const updateHandler = async ({ ctx, input }: UpdateOptions) => {
...newStep,
verifiedAt: oldStep.verifiedAt,
agentId: newStep.agentId || null,
inboundAgentId: newStep.inboundAgentId || null,
})
) {
// check if step that require team plan already existed before
@@ -26,6 +26,7 @@ export const ZUpdateInputSchema = z.object({
senderName: z.string().nullable(),
includeCalendarEvent: z.boolean(),
agentId: z.string().nullish(),
inboundAgentId: z.string().nullish(),
})
.array(),
trigger: z.enum(WORKFLOW_TRIGGER_EVENTS),