-
Notifications
You must be signed in to change notification settings - Fork 87
Expand file tree
/
Copy pathCalendarService.ts
More file actions
935 lines (857 loc) · 27.7 KB
/
CalendarService.ts
File metadata and controls
935 lines (857 loc) · 27.7 KB
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
/**
* @license
* Copyright 2025 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
import crypto from 'node:crypto';
import { calendar_v3, google } from 'googleapis';
import { logToFile } from '../utils/logger';
import { gaxiosOptions } from '../utils/GaxiosConfig';
import { iso8601DateTimeSchema, emailArraySchema } from '../utils/validation';
import { z } from 'zod';
/**
* Google Drive file attachment for calendar events.
* Attachments are fully replaced (not appended) when provided.
*/
interface EventAttachment {
fileUrl: string;
title?: string;
mimeType?: string;
}
export interface CreateEventInput {
calendarId?: string;
summary: string;
description?: string;
start: { dateTime: string };
end: { dateTime: string };
attendees?: string[];
sendUpdates?: 'all' | 'externalOnly' | 'none';
addGoogleMeet?: boolean;
attachments?: EventAttachment[];
}
export interface ListEventsInput {
calendarId?: string;
timeMin?: string;
timeMax?: string;
attendeeResponseStatus?: string[];
}
export interface GetEventInput {
eventId: string;
calendarId?: string;
}
export interface DeleteEventInput {
eventId: string;
calendarId?: string;
}
export interface UpdateEventInput {
eventId: string;
calendarId?: string;
summary?: string;
description?: string;
start?: { dateTime: string };
end?: { dateTime: string };
attendees?: string[];
sendUpdates?: 'all' | 'externalOnly' | 'none';
addGoogleMeet?: boolean;
attachments?: EventAttachment[];
}
export interface RespondToEventInput {
eventId: string;
calendarId?: string;
responseStatus: 'accepted' | 'declined' | 'tentative';
sendNotification?: boolean;
responseMessage?: string;
}
export interface FindFreeTimeInput {
attendees: string[];
timeMin: string;
timeMax: string;
duration: number;
}
export interface CreateRecurringEventInput {
calendarId?: string;
summary: string;
description?: string;
start: { dateTime: string };
end: { dateTime: string };
attendees?: string[];
recurrence: string[];
sendUpdates?: 'all' | 'externalOnly' | 'none';
reminders?: {
useDefault?: boolean;
overrides?: Array<{ method: 'email' | 'popup'; minutes: number }>;
};
}
export interface CreateCalendarInput {
summary: string;
description?: string;
timeZone?: string;
}
export interface SetEventRemindersInput {
eventId: string;
calendarId?: string;
useDefault?: boolean;
overrides?: Array<{ method: 'email' | 'popup'; minutes: number }>;
}
export class CalendarService {
private primaryCalendarId: string | null = null;
constructor(private authManager: any) {}
/**
* Adds conferenceData and attachments to an event body and its API params.
*
* IMPORTANT: Attachments are fully REPLACED, not appended. When attachments
* are provided, any existing attachments on the event will be removed.
*/
private applyMeetAndAttachments(
event: calendar_v3.Schema$Event,
params: { conferenceDataVersion?: number; supportsAttachments?: boolean },
addGoogleMeet?: boolean,
attachments?: EventAttachment[],
): void {
if (addGoogleMeet) {
event.conferenceData = {
createRequest: {
requestId: crypto.randomUUID(),
conferenceSolutionKey: { type: 'hangoutsMeet' },
},
};
params.conferenceDataVersion = 1;
}
if (attachments && attachments.length > 0) {
event.attachments = attachments.map((a) => ({
fileUrl: a.fileUrl,
title: a.title,
mimeType: a.mimeType,
}));
params.supportsAttachments = true;
}
}
/**
* Standardized error message extraction helper.
* Converts any error to a string message safely.
*/
private getErrorMessage(error: unknown): string {
return error instanceof Error ? error.message : String(error);
}
private createApiErrorResponse(error: unknown, toolName: string) {
const errorMessage = this.getErrorMessage(error);
logToFile(`Error during ${toolName}: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
private createValidationErrorResponse(error: unknown) {
const errorMessage =
error instanceof Error ? this.getErrorMessage(error) : 'Validation failed';
let helpMessage =
'Please use strict ISO 8601 format with seconds and timezone. Examples: 2024-01-15T10:30:00Z (UTC) or 2024-01-15T10:30:00-05:00 (EST)';
if (
error instanceof z.ZodError &&
error.issues.some(
(issue) =>
issue.path.includes('attendees') || issue.message.includes('email'),
)
) {
helpMessage = 'Please ensure all attendee emails are in a valid format.';
}
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
error: 'Invalid input format',
details: errorMessage,
help: helpMessage,
}),
},
],
};
}
private async getCalendar(): Promise<calendar_v3.Calendar> {
logToFile('Getting authenticated client for calendar...');
const auth = await this.authManager.getAuthenticatedClient();
logToFile('Got auth client, creating calendar instance...');
const options = { ...gaxiosOptions, auth };
return google.calendar({ version: 'v3', ...options });
}
private async getPrimaryCalendarId(): Promise<string> {
if (this.primaryCalendarId) {
return this.primaryCalendarId;
}
logToFile('Getting primary calendar ID...');
const calendar = await this.getCalendar();
const res = await calendar.calendarList.list();
const primaryCalendar = res.data.items?.find((c) => c.primary);
if (primaryCalendar && primaryCalendar.id) {
logToFile(`Found primary calendar: ${primaryCalendar.id}`);
this.primaryCalendarId = primaryCalendar.id;
return primaryCalendar.id;
}
logToFile('No primary calendar found, defaulting to "primary"');
return 'primary';
}
listCalendars = async () => {
logToFile('listCalendars called');
try {
logToFile('Getting calendar instance...');
const calendar = await this.getCalendar();
logToFile('Making API call to calendar.calendarList.list()...');
const res = await calendar.calendarList.list();
logToFile(`Found ${res.data.items?.length} calendars.`);
const calendars = res.data.items || [];
logToFile(
`Returning calendar data: ${JSON.stringify(calendars.map((c) => ({ id: c?.id, summary: c?.summary })))}`,
);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify(
calendars.map((c) => ({ id: c?.id, summary: c?.summary })),
),
},
],
};
} catch (error) {
const errorMessage = this.getErrorMessage(error);
logToFile(`Error during calendar.list: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
};
createEvent = async (input: CreateEventInput) => {
const {
calendarId,
summary,
description,
start,
end,
attendees,
sendUpdates,
addGoogleMeet,
attachments,
} = input;
// Validate datetime formats
try {
iso8601DateTimeSchema.parse(start.dateTime);
iso8601DateTimeSchema.parse(end.dateTime);
if (attendees) {
emailArraySchema.parse(attendees);
}
} catch (error) {
return this.createValidationErrorResponse(error);
}
const finalCalendarId = calendarId || (await this.getPrimaryCalendarId());
logToFile(`Creating event in calendar: ${finalCalendarId}`);
logToFile(`Event summary: ${summary}`);
if (description) logToFile(`Event description: ${description}`);
logToFile(`Event start: ${start.dateTime}`);
logToFile(`Event end: ${end.dateTime}`);
logToFile(`Event attendees: ${attendees?.join(', ')}`);
if (addGoogleMeet) logToFile('Adding Google Meet link');
if (attachments?.length)
logToFile(`Attachments: ${attachments.length} file(s)`);
// Determine sendUpdates value
let finalSendUpdates = sendUpdates;
if (finalSendUpdates === undefined) {
finalSendUpdates = attendees?.length ? 'all' : 'none';
}
if (finalSendUpdates) {
logToFile(`Sending updates: ${finalSendUpdates}`);
}
try {
const event: calendar_v3.Schema$Event = {
summary,
description,
start,
end,
attendees: attendees?.map((email) => ({ email })),
};
const calendar = await this.getCalendar();
const insertParams: calendar_v3.Params$Resource$Events$Insert = {
calendarId: finalCalendarId,
requestBody: event,
sendUpdates: finalSendUpdates,
};
this.applyMeetAndAttachments(
event,
insertParams,
addGoogleMeet,
attachments,
);
const res = await calendar.events.insert(insertParams);
logToFile(`Successfully created event: ${res.data.id}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify(res.data),
},
],
};
} catch (error) {
const errorMessage = this.getErrorMessage(error);
logToFile(`Error during calendar.createEvent: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
};
createCalendar = async (input: CreateCalendarInput) => {
const { summary, description, timeZone } = input;
logToFile(`Creating calendar with summary: ${summary}`);
try {
const calendar = await this.getCalendar();
const res = await calendar.calendars.insert({
requestBody: { summary, description, timeZone },
});
return { content: [{ type: 'text' as const, text: JSON.stringify(res.data) }] };
} catch (error) {
return this.createApiErrorResponse(error, 'calendar.createCalendar');
}
};
createRecurringEvent = async (input: CreateRecurringEventInput) => {
const { calendarId, summary, description, start, end, attendees, recurrence, sendUpdates, reminders } = input;
try {
iso8601DateTimeSchema.parse(start.dateTime);
iso8601DateTimeSchema.parse(end.dateTime);
if (attendees) emailArraySchema.parse(attendees);
if (!recurrence || recurrence.length === 0) throw new Error('recurrence must contain at least one RRULE string');
} catch (error) {
return this.createValidationErrorResponse(error);
}
const finalCalendarId = calendarId || (await this.getPrimaryCalendarId());
logToFile(`Creating recurring event in calendar: ${finalCalendarId}`);
// Determine sendUpdates value
let finalSendUpdates = sendUpdates;
if (finalSendUpdates === undefined) {
finalSendUpdates = attendees?.length ? 'all' : 'none';
}
if (finalSendUpdates) {
logToFile(`Sending updates: ${finalSendUpdates}`);
}
try {
const event: calendar_v3.Schema$Event = { summary, description, start, end, attendees: attendees?.map((email) => ({ email })), recurrence };
if (reminders) event.reminders = { useDefault: reminders.useDefault, overrides: reminders.overrides };
const calendar = await this.getCalendar();
const res = await calendar.events.insert({ calendarId: finalCalendarId, requestBody: event, sendUpdates: finalSendUpdates });
logToFile(`Successfully created recurring event: ${res.data.id}`);
return { content: [{ type: 'text' as const, text: JSON.stringify(res.data) }] };
} catch (error) {
return this.createApiErrorResponse(error, 'calendar.createRecurringEvent');
}
};
setEventReminders = async (input: SetEventRemindersInput) => {
const { eventId, calendarId, useDefault = true, overrides } = input;
const finalCalendarId = calendarId || (await this.getPrimaryCalendarId());
logToFile(`Setting reminders for event ${eventId} in ${finalCalendarId}`);
try {
const calendar = await this.getCalendar();
const res = await calendar.events.patch({ calendarId: finalCalendarId, eventId, requestBody: { reminders: { useDefault, overrides } } });
return { content: [{ type: 'text' as const, text: JSON.stringify(res.data) }] };
} catch (error) {
return this.createApiErrorResponse(error, 'calendar.setEventReminders');
}
};
listEvents = async (input: ListEventsInput) => {
const {
calendarId,
timeMin = new Date().toISOString(),
attendeeResponseStatus = ['accepted', 'tentative', 'needsAction'],
} = input;
let timeMax = input.timeMax;
if (!timeMax) {
const thirtyDaysFromNow = new Date();
thirtyDaysFromNow.setDate(thirtyDaysFromNow.getDate() + 30);
timeMax = thirtyDaysFromNow.toISOString();
}
const finalCalendarId = calendarId || (await this.getPrimaryCalendarId());
logToFile(`Listing events for calendar: ${finalCalendarId}`);
try {
const calendar = await this.getCalendar();
const res = await calendar.events.list({
calendarId: finalCalendarId,
timeMin,
timeMax,
singleEvents: true,
fields:
'items(id,summary,start,end,description,htmlLink,attendees,status)',
});
const events = res.data.items
?.filter((event) => event.status !== 'cancelled' && !!event.summary)
.filter((event) => {
if (!event.attendees || event.attendees.length === 0) {
return true; // No attendees, so we can't filter, include it
}
if (event.attendees.length === 1 && event.attendees[0].self) {
return true; // I'm the only one, always include it
}
const self = event.attendees.find((a) => a.self);
if (!self) {
return true; // We are not an attendee, include it
}
return attendeeResponseStatus.includes(
self.responseStatus || 'needsAction',
);
});
logToFile(`Found ${events?.length} events after filtering.`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify(events),
},
],
};
} catch (error) {
const errorMessage = this.getErrorMessage(error);
logToFile(`Error during calendar.listEvents: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
};
getEvent = async (input: GetEventInput) => {
const { eventId, calendarId } = input;
const finalCalendarId = calendarId || (await this.getPrimaryCalendarId());
logToFile(`Getting event ${eventId} from calendar: ${finalCalendarId}`);
try {
const calendar = await this.getCalendar();
const res = await calendar.events.get({
calendarId: finalCalendarId,
eventId,
});
logToFile(`Successfully retrieved event: ${res.data.id}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify(res.data),
},
],
};
} catch (error) {
const errorMessage =
(error as any).response?.data?.error?.message ||
this.getErrorMessage(error);
logToFile(`Error during calendar.getEvent: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
};
deleteEvent = async (input: DeleteEventInput) => {
const { eventId, calendarId } = input;
const finalCalendarId = calendarId || (await this.getPrimaryCalendarId());
logToFile(`Deleting event ${eventId} from calendar: ${finalCalendarId}`);
try {
const calendar = await this.getCalendar();
await calendar.events.delete({
calendarId: finalCalendarId,
eventId,
});
logToFile(`Successfully deleted event: ${eventId}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
message: `Successfully deleted event ${eventId}`,
}),
},
],
};
} catch (error) {
const errorMessage =
(error as any).response?.data?.error?.message ||
this.getErrorMessage(error);
logToFile(`Error during calendar.deleteEvent: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
};
updateEvent = async (input: UpdateEventInput) => {
const {
eventId,
calendarId,
summary,
description,
start,
end,
attendees,
sendUpdates,
addGoogleMeet,
attachments,
} = input;
// Validate datetime formats if provided
try {
if (start) {
iso8601DateTimeSchema.parse(start.dateTime);
}
if (end) {
iso8601DateTimeSchema.parse(end.dateTime);
}
if (attendees) {
emailArraySchema.parse(attendees);
}
} catch (error) {
return this.createValidationErrorResponse(error);
}
const finalCalendarId = calendarId || (await this.getPrimaryCalendarId());
logToFile(`Updating event ${eventId} in calendar: ${finalCalendarId}`);
if (addGoogleMeet) logToFile('Adding Google Meet link');
if (attachments?.length)
logToFile(`Attachments: ${attachments.length} file(s)`);
// Determine sendUpdates value
let finalSendUpdates = sendUpdates;
if (finalSendUpdates === undefined) {
finalSendUpdates = attendees?.length ? 'all' : 'none';
}
if (finalSendUpdates) {
logToFile(`Sending updates: ${finalSendUpdates}`);
}
try {
const calendar = await this.getCalendar();
// Build request body with only the fields to update (patch semantics)
const requestBody: calendar_v3.Schema$Event = {};
if (summary !== undefined) requestBody.summary = summary;
if (description !== undefined) requestBody.description = description;
if (start) requestBody.start = start;
if (end) requestBody.end = end;
if (attendees)
requestBody.attendees = attendees.map((email) => ({ email }));
const updateParams: calendar_v3.Params$Resource$Events$Update = {
calendarId: finalCalendarId,
eventId,
requestBody,
sendUpdates: finalSendUpdates,
};
this.applyMeetAndAttachments(
requestBody,
updateParams,
addGoogleMeet,
attachments,
);
const res = await calendar.events.update(updateParams);
logToFile(`Successfully updated event: ${res.data.id}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify(res.data),
},
],
};
} catch (error) {
const errorMessage = this.getErrorMessage(error);
logToFile(`Error during calendar.updateEvent: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
};
respondToEvent = async (input: RespondToEventInput) => {
const {
eventId,
calendarId,
responseStatus,
sendNotification = true,
responseMessage,
} = input;
const finalCalendarId = calendarId || (await this.getPrimaryCalendarId());
logToFile(
`Responding to event ${eventId} in calendar: ${finalCalendarId} with status: ${responseStatus}`,
);
if (responseMessage) {
logToFile(`Response message: ${responseMessage}`);
}
try {
const calendar = await this.getCalendar();
// First, get the current event to find the attendee entry
const event = await calendar.events.get({
calendarId: finalCalendarId,
eventId,
});
if (!event.data.attendees || event.data.attendees.length === 0) {
logToFile('Event has no attendees');
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: 'Event has no attendees' }),
},
],
};
}
// Find the current user's attendee entry
const selfAttendee = event.data.attendees.find((a) => a.self === true);
if (!selfAttendee) {
logToFile('User is not an attendee of this event');
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
error: 'You are not an attendee of this event',
}),
},
],
};
}
// Update the response status for the current user
selfAttendee.responseStatus = responseStatus;
if (responseMessage !== undefined) {
selfAttendee.comment = responseMessage;
}
// Patch the event with the updated attendee list
const res = await calendar.events.patch({
calendarId: finalCalendarId,
eventId,
sendNotifications: sendNotification,
requestBody: {
attendees: event.data.attendees,
},
});
logToFile(
`Successfully responded to event: ${res.data.id} with status: ${responseStatus}`,
);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
eventId: res.data.id,
summary: res.data.summary,
responseStatus,
message: `Successfully ${responseStatus} the meeting invitation${responseMessage ? ' with message' : ''}`,
}),
},
],
};
} catch (error) {
const errorMessage = this.getErrorMessage(error);
logToFile(`Error during calendar.respondToEvent: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
};
findFreeTime = async (input: FindFreeTimeInput) => {
const { attendees, timeMin, timeMax, duration } = input;
// Validate datetime formats
try {
iso8601DateTimeSchema.parse(timeMin);
iso8601DateTimeSchema.parse(timeMax);
// Note: attendees can include 'me' as a special value, so we don't validate as emails
} catch (error) {
return this.createValidationErrorResponse(error);
}
logToFile(`Finding free time for attendees: ${attendees.join(', ')}`);
logToFile(`Time range: ${timeMin} - ${timeMax}`);
logToFile(`Duration: ${duration} minutes`);
try {
const calendar = await this.getCalendar();
const items = await Promise.all(
attendees.map(async (email) => {
if (email === 'me') {
const primaryId = await this.getPrimaryCalendarId();
return { id: primaryId };
}
return { id: email };
}),
);
const res = await calendar.freebusy.query({
requestBody: {
items,
timeMin,
timeMax,
},
});
const busyTimes = Object.values(res.data.calendars || {}).flatMap(
(cal) => cal.busy || [],
);
if (busyTimes.length === 0) {
logToFile(
'No busy times found, returning the start of the time range.',
);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
start: timeMin,
end: new Date(
new Date(timeMin).getTime() + duration * 60000,
).toISOString(),
}),
},
],
};
}
// Sort and merge overlapping busy intervals for better performance
const sortedBusyTimes = busyTimes
.filter((busy) => busy.start && busy.end)
.map((busy) => ({
start: new Date(busy.start!).getTime(),
end: new Date(busy.end!).getTime(),
}))
.sort((a, b) => a.start - b.start);
const mergedBusyTimes: { start: number; end: number }[] = [];
for (const busy of sortedBusyTimes) {
if (mergedBusyTimes.length === 0) {
mergedBusyTimes.push(busy);
} else {
const last = mergedBusyTimes[mergedBusyTimes.length - 1];
if (busy.start <= last.end) {
// Overlapping or adjacent intervals - merge them
last.end = Math.max(last.end, busy.end);
} else {
mergedBusyTimes.push(busy);
}
}
}
const startTime = new Date(timeMin).getTime();
const endTime = new Date(timeMax).getTime();
const durationMs = duration * 60000;
// If no busy times, return the start of the range
if (mergedBusyTimes.length === 0) {
const slotEnd = new Date(startTime + durationMs);
logToFile(
`No busy times, found free time: ${timeMin} - ${slotEnd.toISOString()}`,
);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
start: timeMin,
end: slotEnd.toISOString(),
}),
},
],
};
}
// Check if we can fit the meeting before the first busy slot
if (startTime + durationMs <= mergedBusyTimes[0].start) {
const slotEnd = new Date(startTime + durationMs);
logToFile(`Found free time: ${timeMin} - ${slotEnd.toISOString()}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
start: timeMin,
end: slotEnd.toISOString(),
}),
},
],
};
}
// Check gaps between busy slots
for (let i = 0; i < mergedBusyTimes.length - 1; i++) {
const gapStart = mergedBusyTimes[i].end;
const gapEnd = mergedBusyTimes[i + 1].start;
if (gapEnd - gapStart >= durationMs) {
const slotStart = new Date(gapStart);
const slotEnd = new Date(gapStart + durationMs);
logToFile(
`Found free time: ${slotStart.toISOString()} - ${slotEnd.toISOString()}`,
);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
start: slotStart.toISOString(),
end: slotEnd.toISOString(),
}),
},
],
};
}
}
// Check if we can fit after the last busy slot
const lastBusyEnd = mergedBusyTimes[mergedBusyTimes.length - 1].end;
if (lastBusyEnd + durationMs <= endTime) {
const slotStart = new Date(lastBusyEnd);
const slotEnd = new Date(lastBusyEnd + durationMs);
logToFile(
`Found free time: ${slotStart.toISOString()} - ${slotEnd.toISOString()}`,
);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({
start: slotStart.toISOString(),
end: slotEnd.toISOString(),
}),
},
],
};
}
logToFile('No available free time found');
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: 'No available free time found' }),
},
],
};
} catch (error) {
const errorMessage = this.getErrorMessage(error);
logToFile(`Error during calendar.findFreeTime: ${errorMessage}`);
return {
content: [
{
type: 'text' as const,
text: JSON.stringify({ error: errorMessage }),
},
],
};
}
};
}