diff --git a/src/app/actions/cancelMeeting.ts b/src/app/actions/cancelMeeting.ts
new file mode 100644
index 0000000..2758988
--- /dev/null
+++ b/src/app/actions/cancelMeeting.ts
@@ -0,0 +1,25 @@
+'use server'
+import { getGoogleCalendarClient, getGoogleCalendarId } from '~/server/googleCalendar'
+
+export async function cancelMeeting({ eventId }: { eventId: string }) {
+ try {
+ const calendar = getGoogleCalendarClient()
+
+ await calendar.events.delete({
+ calendarId: getGoogleCalendarId(),
+ eventId,
+ })
+
+ return {
+ success: true,
+ eventId,
+ message: 'Meeting removed from Gregor availability calendar.',
+ }
+ } catch (error) {
+ console.error('Failed to cancel meeting:', error)
+ return {
+ success: false,
+ error: 'Failed to remove the meeting from Gregor availability calendar.',
+ }
+ }
+}
diff --git a/src/app/actions/scheduleMeeting.ts b/src/app/actions/scheduleMeeting.ts
index 523ec4a..9455394 100644
--- a/src/app/actions/scheduleMeeting.ts
+++ b/src/app/actions/scheduleMeeting.ts
@@ -1,7 +1,34 @@
'use server'
-import { clerkClient, auth } from '@clerk/nextjs/server'
-import { google } from 'googleapis'
import { env } from '~/env'
+import { getGoogleCalendarClient, getGoogleCalendarId } from '~/server/googleCalendar'
+
+function googleCalendarDate(date: Date) {
+ return date.toISOString().replace(/[-:]|\.\d{3}/g, '')
+}
+
+function createGoogleCalendarTemplateLink({
+ title,
+ description,
+ startTime,
+ endTime,
+ gregorEmail,
+}: {
+ title: string
+ description: string
+ startTime: Date
+ endTime: Date
+ gregorEmail: string
+}) {
+ const params = new URLSearchParams({
+ action: 'TEMPLATE',
+ text: title,
+ dates: `${googleCalendarDate(startTime)}/${googleCalendarDate(endTime)}`,
+ details: description,
+ add: gregorEmail,
+ })
+
+ return `https://calendar.google.com/calendar/render?${params.toString()}`
+}
export async function scheduleMeeting({
title,
@@ -19,59 +46,39 @@ export async function scheduleMeeting({
attendeeName?: string
}) {
try {
- const clerk = await clerkClient()
- const userAuth = await auth()
- const user = await clerk.users.getUser(userAuth.userId?userAuth.userId:"")
- // Get admin's Google OAuth token to create the event on Gregor's calendar
- const adminTokenResponse = await clerk.users.getUserOauthAccessToken(
- env.ADMIN_USER_CLERK_ID,
- 'oauth_google',
- )
- const adminToken = adminTokenResponse.data[0]
-
- if (!adminToken?.token) {
- return { success: false, error: 'Admin Google Calendar not connected. Ensure the admin account is linked with Google and has calendar scope enabled.' }
- }
-
- // Try to resolve visitor's Google email for the invite
- let visitorEmail: string | undefined = attendeeEmail
- if (!visitorEmail) {
- visitorEmail = user?.emailAddresses.at(0)?.emailAddress ?? undefined
- }
-
- const oAuth2Client = new google.auth.OAuth2()
- oAuth2Client.setCredentials({ access_token: adminToken.token })
- const calendar = google.calendar({ version: 'v3', auth: oAuth2Client })
+ const calendar = getGoogleCalendarClient()
const startTime = new Date(dateTime)
const endTime = new Date(startTime.getTime() + durationMinutes * 60 * 1000)
+ const attendeeNote = attendeeEmail
+ ? `\n\nVisitor: ${attendeeName ?? 'Unknown'} <${attendeeEmail}>`
+ : ''
+ const eventDescription = `${description}${attendeeNote}`
- const attendees: { email: string; displayName?: string }[] = []
- if (visitorEmail) {
- attendees.push({ email: visitorEmail, displayName: attendeeName })
+ const eventRequest = {
+ summary: title,
+ description: eventDescription,
+ start: { dateTime: startTime.toISOString(), timeZone: 'UTC' },
+ end: { dateTime: endTime.toISOString(), timeZone: 'UTC' },
}
-
const event = await calendar.events.insert({
- calendarId: 'primary',
- sendUpdates: 'all',
- requestBody: {
- summary: title,
- description,
- start: { dateTime: startTime.toISOString(), timeZone: 'UTC' },
- end: { dateTime: endTime.toISOString(), timeZone: 'UTC' },
- attendees,
- },
- sendNotifications: true
+ calendarId: getGoogleCalendarId(),
+ requestBody: eventRequest,
})
- const inviteLink = event.data.htmlLink ?? undefined
+ const addToCalendarLink = createGoogleCalendarTemplateLink({
+ title,
+ description,
+ startTime,
+ endTime,
+ gregorEmail: env.GREGOR_MEETING_EMAIL,
+ })
return {
success: true,
eventId: event.data.id,
- htmlLink: inviteLink,
- inviteLink,
- message: `Meeting "${title}" scheduled for ${startTime.toLocaleString()}${visitorEmail ? `. Invite sent to ${visitorEmail}.` : '.'}${inviteLink ? ` Calendar invite: ${inviteLink}` : ''}`,
+ addToCalendarLink,
+ message: `Meeting "${title}" scheduled for ${startTime.toLocaleString()}.${attendeeEmail ? ` Visitor email noted: ${attendeeEmail}.` : ''} The add-to-calendar link invites ${env.GREGOR_MEETING_EMAIL}.`,
}
} catch (error) {
console.error('Failed to schedule meeting:', error)
diff --git a/src/app/api/chat/route.ts b/src/app/api/chat/route.ts
index 396fb9c..6ef952c 100644
--- a/src/app/api/chat/route.ts
+++ b/src/app/api/chat/route.ts
@@ -36,7 +36,9 @@ Runtime context:
- Current server time: ${new Date().toISOString()}.
- Default meeting timezone: Europe/Berlin.
- For availability questions like "next open spot", call getAvailability once. It defaults to checking from now. Use nextAvailableSlot for the next opening, or the first item in availableSlots if needed. Do not call getAvailability again just to get more slots.
-- After scheduleMeeting succeeds, include the returned inviteLink or htmlLink in your response.
+- After scheduleMeeting succeeds, include only the returned addToCalendarLink for the visitor. Format it as a Markdown link like [Add this meeting to your Google Calendar](URL); do not paste the raw URL. Explain briefly that this link lets them add the meeting to their own calendar and invite Gregor. Do not mention internal Google Calendar event links.
+- You can remove meetings from Gregor's availability calendar with cancelMeeting only when you have the exact eventId from a previous scheduleMeeting result. If a visitor asks to reschedule and you have both the old eventId and a confirmed new slot, call cancelMeeting once for the old event and scheduleMeeting once for the new event. If you do not have the old eventId, ask for clarification instead of guessing.
+- When rescheduling, make clear that cancelMeeting only removes the old slot from Gregor's availability calendar. If the visitor already added the old link to their own calendar, they may need to remove that copy themselves.
- Do not calculate or invent calendar availability yourself.`
const model = await servTrpc.chat.getModel()
@@ -57,7 +59,7 @@ Runtime context:
system: systemPrompt,
messages: await convertToModelMessages(messages),
tools: createChatTools(),
- stopWhen: stepCountIs(2),
+ stopWhen: stepCountIs(3),
onFinish: async ({ text, finishReason }) => {
console.log('[ai:chat:onFinish]', {
finishReason,
diff --git a/src/app/chat/_components/AssistantMessage.tsx b/src/app/chat/_components/AssistantMessage.tsx
index d222be2..d217a03 100644
--- a/src/app/chat/_components/AssistantMessage.tsx
+++ b/src/app/chat/_components/AssistantMessage.tsx
@@ -11,6 +11,8 @@ function toolLabel(type: string) {
return "Loading project details";
case "tool-getAvailability":
return "Checking availability";
+ case "tool-cancelMeeting":
+ return "Removing meeting";
case "tool-getCurrentUnixTime":
return "Checking current time";
default:
@@ -27,7 +29,7 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
>
{message.parts.map((part, i) => {
if (part.type === 'text') {
@@ -35,12 +37,12 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
)
}
- if (part.type === 'tool-scheduleMeeting') {
+ if (part.type === 'tool-scheduleMeeting') {
const toolPart = part as unknown as {
type: 'tool-scheduleMeeting'
state: string
input: unknown
- output?: { success: boolean; message?: string; htmlLink?: string; inviteLink?: string; error?: string }
+ output?: { success: boolean; error?: string }
}
if (toolPart.state === 'input-available' || toolPart.state === 'input-streaming') {
return (
@@ -48,33 +50,39 @@ export const AssistantMessage = (props: { message: UIMessage }) => {
Scheduling meeting…
)
- }
+ }
if (toolPart.state === 'output-available' && toolPart.output) {
const result = toolPart.output
- const inviteLink = result.inviteLink ?? result.htmlLink
+ if (result.success) return null
return (
- {result.success ? (
-
- ✓ {result.message}{' '}
- {inviteLink && (
-
- Open calendar invite
-
- )}
-
- ) : (
-
✗ {result.error}
- )}
+
✗ {result.error}
)
}
}
+ if (part.type === 'tool-cancelMeeting') {
+ const toolPart = part as unknown as {
+ type: 'tool-cancelMeeting'
+ state: string
+ output?: { success: boolean; error?: string }
+ }
+ if (toolPart.state === 'input-available' || toolPart.state === 'input-streaming') {
+ return (
+
+ Removing meeting…
+
+ )
+ }
+ if (toolPart.state === 'output-available' && toolPart.output) {
+ if (toolPart.output.success) return null
+ return (
+
+ ✗ {toolPart.output.error}
+
+ )
+ }
+ }
if (part.type.startsWith('tool-')) {
const toolPart = part as unknown as {
type: string
diff --git a/src/app/chat/_components/UserMessage.tsx b/src/app/chat/_components/UserMessage.tsx
index 8cd5175..400c63a 100644
--- a/src/app/chat/_components/UserMessage.tsx
+++ b/src/app/chat/_components/UserMessage.tsx
@@ -14,7 +14,7 @@ export const UserMessage = (props:{message: UIMessage}) => {
>
{message}
diff --git a/src/components/mdx-components.tsx b/src/components/mdx-components.tsx
index 2dedce9..7b85a5e 100644
--- a/src/components/mdx-components.tsx
+++ b/src/components/mdx-components.tsx
@@ -100,12 +100,19 @@ function PullQuote({ children }: { children: ReactNode }) {
}
function ExternalLink(props: ComponentPropsWithoutRef<"a">) {
- const href = props.href ?? "";
- const isExternal = /^https?:\/\//.test(href);
+ const { className, ...rest } = props;
- if (!isExternal) return
;
-
- return
;
+ return (
+
+ );
}
const blockComponents = new Set
([Callout, Figure, PullQuote, TagList]);
diff --git a/src/env.js b/src/env.js
index 1f7f199..0b7232f 100644
--- a/src/env.js
+++ b/src/env.js
@@ -31,6 +31,10 @@ export const env = createEnv({
CLERK_SECRET_KEY: z.string(),
ADMIN_USER_CLERK_ID: z.string(),
OPENAI_API_KEY: z.string(),
+ GOOGLE_SERVICE_ACCOUNT_EMAIL: z.string().email(),
+ GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY: z.string(),
+ GOOGLE_CALENDAR_ID: z.string(),
+ GREGOR_MEETING_EMAIL: z.string().email(),
NODE_ENV: z
.enum(["development", "test", "production"])
.default("development"),
@@ -72,6 +76,10 @@ export const env = createEnv({
POSTGRES_PRISMA_URL: process.env.POSTGRES_PRISMA_URL,
ADMIN_USER_CLERK_ID: process.env.ADMIN_USER_CLERK_ID,
OPENAI_API_KEY: process.env.OPENAI_API_KEY,
+ GOOGLE_SERVICE_ACCOUNT_EMAIL: process.env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
+ GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY: process.env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY,
+ GOOGLE_CALENDAR_ID: process.env.GOOGLE_CALENDAR_ID,
+ GREGOR_MEETING_EMAIL: process.env.GREGOR_MEETING_EMAIL,
NEXT_PUBLIC_ADMIN_USER_CLERK_ID: process.env.NEXT_PUBLIC_ADMIN_USER_CLERK_ID,
CLERK_SECRET_KEY: process.env.CLERK_SECRET_KEY,
NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY,
diff --git a/src/server/ai/tools.ts b/src/server/ai/tools.ts
index 764fe30..fe92ad4 100644
--- a/src/server/ai/tools.ts
+++ b/src/server/ai/tools.ts
@@ -1,14 +1,13 @@
import "server-only";
-import { clerkClient } from "@clerk/nextjs/server";
import { tool } from "ai";
import { desc } from "drizzle-orm";
-import { google } from "googleapis";
import { z } from "zod";
+import { cancelMeeting } from "~/app/actions/cancelMeeting";
import { scheduleMeeting } from "~/app/actions/scheduleMeeting";
-import { env } from "~/env";
import { db } from "~/server/db";
import { blogPost, music } from "~/server/dbschema/schema";
+import { getGoogleCalendarClient, getGoogleCalendarId } from "~/server/googleCalendar";
const contentTypeSchema = z.enum(["cv", "project", "blog", "music"]);
@@ -25,9 +24,6 @@ type SearchResult = {
type ProjectWithStack = Awaited>[number];
-let cachedAdminGoogleToken: { token: string; expiresAt: number } | undefined;
-let adminGoogleTokenRequest: Promise | undefined;
-
function stripMarkup(value: string | null | undefined) {
return (value ?? "")
.replace(/```[\s\S]*?```/g, " ")
@@ -364,83 +360,6 @@ function logAvailability(requestId: string, message: string, data?: Record(promise: Promise, timeoutMs: number, message: string) {
- return Promise.race([
- promise,
- new Promise((_, reject) => {
- setTimeout(() => reject(new Error(message)), timeoutMs);
- }),
- ]);
-}
-
-async function getAdminGoogleToken(requestId: string) {
- if (cachedAdminGoogleToken && cachedAdminGoogleToken.expiresAt > Date.now()) {
- logAvailability(requestId, "admin oauth token cache hit");
- return cachedAdminGoogleToken.token;
- }
-
- if (!adminGoogleTokenRequest) {
- adminGoogleTokenRequest = (async () => {
- logAvailability(requestId, "admin oauth token request start");
- const clerk = await clerkClient();
- const adminTokenResponse = await clerk.users.getUserOauthAccessToken(
- env.ADMIN_USER_CLERK_ID,
- "oauth_google",
- );
- const token = adminTokenResponse.data[0]?.token;
- if (token) {
- cachedAdminGoogleToken = {
- token,
- expiresAt: Date.now() + 5 * 60 * 1000,
- };
- }
- return token;
- })().finally(() => {
- adminGoogleTokenRequest = undefined;
- });
- } else {
- logAvailability(requestId, "admin oauth token request joined");
- }
-
- return withTimeout(
- adminGoogleTokenRequest,
- 5000,
- "Timed out while loading the admin Google OAuth token.",
- );
-}
-
-async function getAdminCalendar(requestId: string) {
- let adminToken: string | undefined;
- try {
- adminToken = await getAdminGoogleToken(requestId);
- } catch (error) {
- console.error(`[ai:getAvailability:${requestId}] admin oauth token failed`, error);
- return {
- success: false as const,
- error: "Timed out while loading Gregor's Google Calendar connection.",
- };
- }
-
- logAvailability(requestId, "admin oauth token resolved", {
- hasToken: Boolean(adminToken),
- });
-
- if (!adminToken) {
- return {
- success: false as const,
- error: "Admin Google Calendar is not connected or does not expose a Google OAuth token.",
- };
- }
-
- const oAuth2Client = new google.auth.OAuth2();
- oAuth2Client.setCredentials({ access_token: adminToken });
-
- return {
- success: true as const,
- calendar: google.calendar({ version: "v3", auth: oAuth2Client }),
- };
-}
-
export function createChatTools() {
return {
scheduleMeeting: tool({
@@ -474,6 +393,13 @@ export function createChatTools() {
return scheduleMeeting({ ...input });
},
}),
+ cancelMeeting: tool({
+ description: "Remove a previously scheduled meeting from Gregor's dedicated availability calendar. Use only when you have the exact eventId returned by scheduleMeeting.",
+ inputSchema: z.object({
+ eventId: z.string().min(1).describe("Google Calendar event id returned by a previous scheduleMeeting tool call."),
+ }),
+ execute: async ({ eventId }) => cancelMeeting({ eventId }),
+ }),
searchSiteContent: tool({
description: "Search Gregor Lohaus's own website content across CV entries, projects, blog posts, and music. Use this for questions about Gregor's work, skills, writing, projects, or site content. For broad questions about Gregor's projects, use types ['project'] so the tool returns the project catalog.",
inputSchema: z.object({
@@ -589,27 +515,24 @@ export function createChatTools() {
rangeEnd: rangeEnd.toISOString(),
});
- const adminCalendar = await getAdminCalendar(requestId);
-
- if (!adminCalendar.success) {
- logAvailability(requestId, "admin calendar unavailable", {
- error: adminCalendar.error,
- });
- return adminCalendar;
- }
+ const calendar = getGoogleCalendarClient();
+ const calendarId = getGoogleCalendarId();
+ logAvailability(requestId, "service account calendar ready", {
+ calendarId,
+ });
let busy: Array<{ start: Date; end: Date }>;
try {
logAvailability(requestId, "freebusy request");
- const response = await adminCalendar.calendar.freebusy.query({
+ const response = await calendar.freebusy.query({
requestBody: {
timeMin: rangeStart.toISOString(),
timeMax: rangeEnd.toISOString(),
timeZone,
- items: [{ id: "primary" }],
+ items: [{ id: calendarId }],
},
});
- busy = (response.data.calendars?.["primary"]?.busy ?? [])
+ busy = (response.data.calendars?.[calendarId]?.busy ?? [])
.map((item) => ({
start: parseDate(item.start ?? undefined, rangeStart),
end: parseDate(item.end ?? undefined, rangeStart),
diff --git a/src/server/googleCalendar.ts b/src/server/googleCalendar.ts
new file mode 100644
index 0000000..811ca29
--- /dev/null
+++ b/src/server/googleCalendar.ts
@@ -0,0 +1,20 @@
+import "server-only";
+
+import { google } from "googleapis";
+import { env } from "~/env";
+
+const calendarScope = "https://www.googleapis.com/auth/calendar";
+
+export function getGoogleCalendarClient() {
+ const auth = new google.auth.JWT({
+ email: env.GOOGLE_SERVICE_ACCOUNT_EMAIL,
+ key: env.GOOGLE_SERVICE_ACCOUNT_PRIVATE_KEY.replace(/\\n/g, "\n"),
+ scopes: [calendarScope],
+ });
+
+ return google.calendar({ version: "v3", auth });
+}
+
+export function getGoogleCalendarId() {
+ return env.GOOGLE_CALENDAR_ID;
+}