import { defineTool, Type } from "@toolpal/tool"; // Common names that are not the last segment of an IANA zone id. const ALIASES: Record = { utc: "UTC", gmt: "UTC", z: "UTC", india: "Asia/Kolkata", ist: "Asia/Kolkata", delhi: "Asia/Kolkata", "new delhi": "Asia/Kolkata", mumbai: "Asia/Kolkata", bangalore: "Asia/Kolkata", bengaluru: "Asia/Kolkata", chennai: "Asia/Kolkata", hyderabad: "Asia/Kolkata", pune: "Asia/Kolkata", "san francisco": "America/Los_Angeles", sf: "America/Los_Angeles", seattle: "America/Los_Angeles", la: "America/Los_Angeles", pt: "America/Los_Angeles", pst: "America/Los_Angeles", pdt: "America/Los_Angeles", boston: "America/New_York", washington: "America/New_York", dc: "America/New_York", miami: "America/New_York", atlanta: "America/New_York", nyc: "America/New_York", et: "America/New_York", est: "America/New_York", edt: "America/New_York", austin: "America/Chicago", dallas: "America/Chicago", houston: "America/Chicago", ct: "America/Chicago", cst: "America/Chicago", cdt: "America/Chicago", mt: "America/Denver", mst: "America/Denver", mdt: "America/Denver", montreal: "America/Toronto", uk: "Europe/London", edinburgh: "Europe/London", manchester: "Europe/London", germany: "Europe/Berlin", munich: "Europe/Berlin", frankfurt: "Europe/Berlin", hamburg: "Europe/Berlin", barcelona: "Europe/Madrid", milan: "Europe/Rome", geneva: "Europe/Zurich", kyiv: "Europe/Kyiv", kiev: "Europe/Kyiv", china: "Asia/Shanghai", beijing: "Asia/Shanghai", shenzhen: "Asia/Shanghai", japan: "Asia/Tokyo", osaka: "Asia/Tokyo", jst: "Asia/Tokyo", korea: "Asia/Seoul", uae: "Asia/Dubai", "abu dhabi": "Asia/Dubai", "tel aviv": "Asia/Jerusalem", saigon: "Asia/Ho_Chi_Minh", "cape town": "Africa/Johannesburg", canberra: "Australia/Sydney", }; const WEEKDAYS = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; const COMBINING_MARKS = new RegExp("[\\u0300-\\u036f]", "g"); const normalize = (s: string) => s .normalize("NFD") .replace(COMBINING_MARKS, "") .trim() .toLowerCase() .replace(/[\s_]+/g, " "); function assertValidCalendarDate(date: string): void { const m = date.match(/^(\d{4})-(\d{2})-(\d{2})$/); if (!m) throw new Error(`Invalid date "${date}". Use YYYY-MM-DD.`); const year = Number(m[1]); const month = Number(m[2]); const day = Number(m[3]); const d = new Date(Date.UTC(year, month - 1, day)); if (d.getUTCFullYear() !== year || d.getUTCMonth() !== month - 1 || d.getUTCDate() !== day) { throw new Error(`"${date}" is not a real calendar date.`); } } function isZone(zone: string): boolean { try { new Intl.DateTimeFormat("en-US", { timeZone: zone }); return true; } catch { return false; } } function resolveZone(input: string): string { const key = normalize(input); const alias = ALIASES[key]; if (alias && isZone(alias)) return alias; if (isZone(input.trim())) { return new Intl.DateTimeFormat("en-US", { timeZone: input.trim() }).resolvedOptions().timeZone; } const match = Intl.supportedValuesOf("timeZone").find( (z) => normalize(z.split("/").pop() as string) === key, ); if (match) return match; throw new Error( `Unknown city or time zone "${input}". Use a major city name or an IANA zone such as Europe/Paris.`, ); } const formatters = new Map(); function wallClock(zone: string, ts: number) { let f = formatters.get(zone); if (!f) { f = new Intl.DateTimeFormat("en-US", { timeZone: zone, hourCycle: "h23", year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", minute: "2-digit", }); formatters.set(zone, f); } const p = Object.fromEntries(f.formatToParts(new Date(ts)).map((x) => [x.type, Number(x.value)])); const asUtc = Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute); return { date: new Date(asUtc).toISOString().slice(0, 10), weekday: new Date(asUtc).getUTCDay(), minutes: p.hour * 60 + p.minute, offset: Math.round((asUtc - Math.floor(ts / 60000) * 60000) / 60000), }; } // The UTC instant at which the clock in `zone` shows the given wall time. function zonedToUtc(zone: string, date: string, minutes: number): number { const guess = Date.parse(`${date}T00:00:00Z`) + minutes * 60000; let ts = guess - wallClock(zone, guess).offset * 60000; ts = guess - wallClock(zone, ts).offset * 60000; return ts; } const hhmm = (m: number) => `${String(Math.floor(m / 60)).padStart(2, "0")}:${String(m % 60).padStart(2, "0")}`; const utcOffset = (m: number) => `UTC${m < 0 ? "-" : "+"}${hhmm(Math.abs(m))}`; const label = (zone: string, ts: number) => { const w = wallClock(zone, ts); return `${WEEKDAYS[w.weekday]} ${w.date} ${hhmm(w.minutes)}`; }; const STEP = 15; export default defineTool({ description: "Finds meeting times across cities and time zones, with daylight saving time handled exactly. Lists the windows on a given day when everyone is within working hours (or, if there are none, the windows that suit the most people), and converts a proposed time into every participant's local time. Offline, no API key needed.", input: Type.Object({ zones: Type.Array(Type.String({ maxLength: 60 }), { minItems: 1, maxItems: 12, description: 'Cities or IANA time zones, e.g. ["New York", "London", "Asia/Kolkata"]. The first is the reference for date and time.', }), date: Type.Optional( Type.String({ pattern: "^\\d{4}-\\d{2}-\\d{2}$", description: "Day to plan, YYYY-MM-DD in the first zone; today there by default", }), ), time: Type.Optional( Type.String({ pattern: "^([01]?\\d|2[0-3]):[0-5]\\d$", description: "A proposed meeting time, HH:MM in the first zone, to convert for everyone", }), ), workdayStart: Type.Optional( Type.Integer({ minimum: 0, maximum: 23, description: "Start of working hours, 9 by default", }), ), workdayEnd: Type.Optional( Type.Integer({ minimum: 1, maximum: 24, description: "End of working hours, 18 by default" }), ), includeWeekends: Type.Optional( Type.Boolean({ description: "Count Saturday and Sunday as working days; false by default" }), ), }), output: Type.Object({ date: Type.String(), workingHours: Type.String(), zones: Type.Array( Type.Object({ input: Type.String(), timeZone: Type.String(), utcOffset: Type.String({ description: "Offset in effect on that day" }), proposedTime: Type.Optional(Type.String()), proposedTimeIsWorkingHours: Type.Optional(Type.Boolean()), }), ), everyoneAvailable: Type.Boolean({ description: "Whether some window has every participant within working hours", }), windows: Type.Array( Type.Object({ startUtc: Type.String(), endUtc: Type.String(), durationMinutes: Type.Integer(), local: Type.Array( Type.Object({ timeZone: Type.String(), from: Type.String(), to: Type.String(), working: Type.Boolean(), }), ), }), ), summary: Type.String(), }), examples: [ { title: "New York & London overlap", prompt: "Find working-hour overlap between New York and London on 2026-11-24 and check 10:00 AM NY", input: { zones: ["New York", "London"], date: "2026-11-24", time: "10:00", }, }, { title: "Three continents (best partial windows)", prompt: "Find the best meeting windows for San Francisco, London, and Bengaluru on 2026-11-24", input: { zones: ["San Francisco", "London", "Bengaluru"], date: "2026-11-24", time: "09:00", }, }, ], handler: async ({ zones: inputs, date, time, workdayStart = 9, workdayEnd = 18, includeWeekends = false, }) => { if (workdayEnd <= workdayStart) throw new Error("workdayEnd must be later than workdayStart."); if (date) assertValidCalendarDate(date); const zones = inputs.map(resolveZone); const reference = zones[0]; const day = date ?? wallClock(reference, Date.now()).date; const dayStart = zonedToUtc(reference, day, 0); const nextDay = new Date(Date.parse(`${day}T00:00:00Z`) + 86400000).toISOString().slice(0, 10); const dayEnd = zonedToUtc(reference, nextDay, 0); const working = (zone: string, ts: number) => { const w = wallClock(zone, ts); const weekday = includeWeekends || (w.weekday !== 0 && w.weekday !== 6); return weekday && w.minutes >= workdayStart * 60 && w.minutes < workdayEnd * 60; }; // Score each 15-minute slot and record which exact participant subset is working so // adjacent partial-overlap runs with different working subsets are never merged together. const slots: { ts: number; score: number; mask: number }[] = []; for (let ts = dayStart; ts < dayEnd; ts += STEP * 60000) { let score = 0; let mask = 0; for (let i = 0; i < zones.length; i++) { if (working(zones[i], ts)) { score++; mask |= 1 << i; } } slots.push({ ts, score, mask }); } const bestScore = slots.reduce((max, s) => (s.score > max ? s.score : max), 0); const runs: { start: number; end: number; mask: number }[] = []; if (bestScore > 0) { for (const s of slots) { if (s.score !== bestScore) continue; const last = runs[runs.length - 1]; if (last && last.end === s.ts && last.mask === s.mask) { last.end = s.ts + STEP * 60000; } else { runs.push({ start: s.ts, end: s.ts + STEP * 60000, mask: s.mask }); } } } const windows = runs.map(({ start, end, mask }) => ({ startUtc: new Date(start).toISOString().replace(":00.000Z", "Z"), endUtc: new Date(end).toISOString().replace(":00.000Z", "Z"), durationMinutes: Math.round((end - start) / 60000), local: zones.map((zone, i) => ({ timeZone: zone, from: label(zone, start), to: label(zone, end), working: (mask & (1 << i)) !== 0, })), })); const proposed = time ? zonedToUtc(reference, day, Number(time.split(":")[0]) * 60 + Number(time.split(":")[1])) : undefined; const noon = zonedToUtc(reference, day, 12 * 60); const everyoneAvailable = bestScore === zones.length; const total = windows.reduce((acc, w) => acc + w.durationMinutes, 0); const summary = bestScore === 0 ? `Nobody is within working hours on ${day} (${WEEKDAYS[wallClock(reference, noon).weekday]}).` : everyoneAvailable ? `All ${zones.length} participants are within working hours for ${Math.floor(total / 60)}h ${total % 60}m on ${day}, in ${windows.length} window(s).` : `No time on ${day} suits everyone; the windows below keep ${bestScore} of ${zones.length} participants within working hours.`; return { date: day, workingHours: `${hhmm(workdayStart * 60)}–${hhmm(workdayEnd * 60)}${includeWeekends ? ", every day" : ", Mon–Fri"}`, zones: zones.map((zone, i) => ({ input: inputs[i], timeZone: zone, utcOffset: utcOffset(wallClock(zone, proposed ?? noon).offset), ...(proposed !== undefined && { proposedTime: label(zone, proposed), proposedTimeIsWorkingHours: working(zone, proposed), }), })), everyoneAvailable, windows, summary, }; }, });