src/index.js
// AgentRove native agent: calendar-assistant (MIT).
// Tools: parse_ics, find_free_slots, propose_meeting (all local, no side effects) and
// create_google_event (external_write; requires "confirm": true and GOOGLE_CALENDAR_ACCESS_TOKEN).
import { readFileSync } from "node:fs";
import { createHash } from "node:crypto";
import { defineAgent, makeContext, handleMcpMessage, runCli, runMcpStdio } from "../sdk/index.js";
import { ToolError } from "./errors.js";
import { parseIcs } from "./ics.js";
import { isValidTimeZone, zonedToUtc, fromDayNum, weekday, parseYmd, isoUtc, isoLocal, parseInstant } from "./tz.js";
export { makeContext, handleMcpMessage, runCli, runMcpStdio };
const manifest = JSON.parse(readFileSync(new URL("../agent.json", import.meta.url), "utf8"));
const DAY = 86400000;
const WD = { SU: 0, MO: 1, TU: 2, WE: 3, TH: 4, FR: 5, SA: 6 };
const EMAIL_RE = /^[^\s@<>"(),;:\\[\]]+@[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?(?:\.[A-Za-z0-9](?:[A-Za-z0-9-]*[A-Za-z0-9])?)+$/;
function requireTz(tz, field) {
if (!isValidTimeZone(tz)) throw new ToolError("invalid_input", `${field}: unknown IANA time zone "${String(tz).slice(0, 64)}"`);
return tz;
}
// ------------------------------------------------------------------------------------------------
// parse_ics
// ------------------------------------------------------------------------------------------------
async function parse_ics(input, ctx) {
const defaultTz = requireTz(input.default_timezone ?? "UTC", "default_timezone");
const now = ctx.now().getTime();
const explicit = input.expand_from !== undefined || input.expand_until !== undefined;
const start = input.expand_from !== undefined ? Date.parse(input.expand_from) : now - 31 * DAY;
const end = input.expand_until !== undefined ? Date.parse(input.expand_until) : now + 366 * DAY;
if (!(end > start)) throw new ToolError("invalid_input", "expand_until must be after expand_from");
if (end - start > 3 * 366 * DAY) throw new ToolError("invalid_input", "The expansion window may span at most 3 years");
const res = parseIcs(input.ics, { defaultTz, window: { start, end }, filterSingles: explicit, maxEvents: input.max_events ?? 5000 });
const notes = [];
if (!explicit) notes.push(`Recurring series were expanded from ${isoUtc(start)} to ${isoUtc(end)}; pass expand_from/expand_until to choose another window. Non-recurring events are all returned.`);
return { events: res.events, window: { start: isoUtc(start), end: isoUtc(end) }, vevent_count: res.vevent_count, warnings: [...res.warnings, ...notes] };
}
// ------------------------------------------------------------------------------------------------
// find_free_slots
// ------------------------------------------------------------------------------------------------
function mergeIntervals(list) {
const sorted = list.filter(([s, e]) => Number.isFinite(s) && Number.isFinite(e) && e > s).sort((a, b) => a[0] - b[0] || a[1] - b[1]);
const out = [];
for (const [s, e] of sorted) {
const last = out[out.length - 1];
if (last && s <= last[1]) last[1] = Math.max(last[1], e);
else out.push([s, e]);
}
return out;
}
async function find_free_slots(input, ctx) {
const wh = input.working_hours;
const tz = requireTz(wh.timezone, "working_hours.timezone");
const fromDay = parseYmd(input.date_from);
const toDay = parseYmd(input.date_to);
if (fromDay === null || toDay === null) throw new ToolError("invalid_input", "date_from/date_to must be real calendar dates (YYYY-MM-DD)");
if (toDay < fromDay) throw new ToolError("invalid_input", "date_to must not be before date_from");
if (toDay - fromDay > 92) throw new ToolError("invalid_input", "The date range may span at most 93 days");
const days = new Set((wh.days ?? ["MO", "TU", "WE", "TH", "FR"]).map((d) => WD[d]));
const [sh, sm] = wh.start.split(":").map(Number);
const [eh, em] = wh.end.split(":").map(Number);
const startMin = sh * 60 + sm;
const endMin = eh * 60 + em;
if (endMin === startMin) throw new ToolError("invalid_input", "working_hours.start and end must differ");
const overnight = endMin < startMin;
const durationMs = input.duration_minutes * 60000;
const bufferMs = (input.buffer_minutes ?? 0) * 60000;
const warnings = [];
const windows = [];
for (let day = fromDay; day <= toDay; day++) {
if (!days.has(weekday(day))) continue;
const f = fromDayNum(day);
const ws = zonedToUtc(f.y, f.m, f.d, sh, sm, 0, tz);
const endDay = overnight || endMin === 1440 ? day + 1 : day;
const ef = fromDayNum(endDay);
const we = endMin === 1440 ? zonedToUtc(ef.y, ef.m, ef.d, 0, 0, 0, tz) : zonedToUtc(ef.y, ef.m, ef.d, eh, em, 0, tz);
if (we > ws) windows.push({ ws, we });
}
const rf = fromDayNum(fromDay);
const rt = fromDayNum(toDay + 2);
const range = { start: zonedToUtc(rf.y, rf.m, rf.d, 0, 0, 0, tz) - DAY, end: zonedToUtc(rt.y, rt.m, rt.d, 0, 0, 0, tz) + DAY };
const events = [];
for (const [i, cal] of (input.calendars ?? []).entries()) {
const label = cal.name ? `calendar "${String(cal.name).slice(0, 60)}"` : `calendar #${i + 1}`;
if (cal.ics === undefined && cal.events === undefined) throw new ToolError("invalid_input", `${label}: provide ics or events`);
if (cal.ics !== undefined) {
const r = parseIcs(cal.ics, { defaultTz: tz, window: range, filterSingles: true, maxEvents: 20000 });
for (const w of r.warnings) warnings.push(`${label}: ${w}`);
events.push(...r.events);
}
if (cal.events !== undefined) events.push(...cal.events);
}
const blockAllDay = input.all_day_events_block ?? true;
const busy = [];
let considered = 0;
for (const ev of events) {
if (String(ev.status ?? "").toUpperCase() === "CANCELLED" || ev.transparent === true) continue;
const allDay = ev.all_day === true || /^\d{4}-\d{2}-\d{2}$/.test(String(ev.start));
if (allDay) {
if (!blockAllDay) continue;
const s = parseYmd(String(ev.start).slice(0, 10));
const e = parseYmd(String(ev.end ?? "").slice(0, 10)) ?? (s === null ? null : s + 1);
if (s === null || e === null) {
warnings.push(`Skipped an all-day event with unreadable dates (${String(ev.uid ?? ev.summary ?? "").slice(0, 60)}).`);
continue;
}
const sf = fromDayNum(s);
const efd = fromDayNum(Math.max(e, s + 1));
busy.push([zonedToUtc(sf.y, sf.m, sf.d, 0, 0, 0, tz), zonedToUtc(efd.y, efd.m, efd.d, 0, 0, 0, tz)]);
} else {
const s = parseInstant(ev.start, tz);
const e = parseInstant(ev.end, tz);
if (s === null || e === null) {
warnings.push(`Skipped an event with unreadable start/end (${String(ev.uid ?? ev.summary ?? "").slice(0, 60)}).`);
continue;
}
busy.push([s, Math.max(s, e)]);
}
considered++;
}
for (const b of input.busy ?? []) {
const s = parseInstant(b.start, tz);
const e = parseInstant(b.end, tz);
if (s === null || e === null) throw new ToolError("invalid_input", "busy[] entries need ISO date-times with Z or an offset");
busy.push([s, e]);
considered++;
}
const merged = mergeIntervals(busy.map(([s, e]) => [s - bufferMs, e + bufferMs]));
const nowMs = ctx.now().getTime();
const excludePast = input.exclude_past ?? true;
const notBefore = excludePast ? Math.ceil(nowMs / 300000) * 300000 : -Infinity;
const free = [];
for (const w of windows) {
let cursor = Math.max(w.ws, notBefore);
for (const [bs, be] of merged) {
if (cursor >= w.we) break;
if (be <= cursor) continue;
if (bs >= w.we) break;
if (bs > cursor) free.push({ s: cursor, e: Math.min(bs, w.we), ws: w.ws });
cursor = Math.max(cursor, be);
}
if (cursor < w.we) free.push({ s: cursor, e: w.we, ws: w.ws });
}
const g = input.granularity_minutes ? input.granularity_minutes * 60000 : null;
const maxSlots = input.max_slots ?? 50;
const slots = [];
let truncated = false;
outer: for (const f of free) {
if (f.e - f.s < durationMs) continue;
if (!g) {
if (slots.length >= maxSlots) {
truncated = true;
break;
}
slots.push([f.s, f.e]);
continue;
}
// Candidate meetings aligned to the local working-day start, every `granularity` minutes.
for (let t = f.ws + Math.ceil(Math.max(0, f.s - f.ws) / g) * g; t + durationMs <= f.e; t += g) {
if (slots.length >= maxSlots) {
truncated = true;
break outer;
}
slots.push([t, t + durationMs]);
}
}
if (truncated) warnings.push(`Result truncated to ${maxSlots} slots; raise max_slots or narrow the range.`);
if (!windows.length) warnings.push("No working-hour windows fall inside the date range (check working_hours.days).");
return {
timezone: tz,
slots: slots.map(([s, e]) => ({ start: isoUtc(s), end: isoUtc(e), local_start: isoLocal(s, tz), local_end: isoLocal(e, tz) })),
busy_intervals_considered: considered,
warnings,
};
}
// ------------------------------------------------------------------------------------------------
// propose_meeting (draft .ics text only; nothing is written or sent)
// ------------------------------------------------------------------------------------------------
const escapeText = (v) =>
String(v)
.replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "")
.replace(/\\/g, "\\\\")
.replace(/;/g, "\\;")
.replace(/,/g, "\\,")
.replace(/\r\n|\r|\n/g, "\\n");
function foldLine(line) {
if (Buffer.byteLength(line, "utf8") <= 75) return line;
const out = [];
let cur = "";
let bytes = 0;
let limit = 75;
for (const ch of line) {
const b = Buffer.byteLength(ch, "utf8");
if (bytes + b > limit) {
out.push(cur);
cur = "";
bytes = 0;
limit = 74; // continuation lines start with one space
}
cur += ch;
bytes += b;
}
out.push(cur);
return out.join("\r\n ");
}
const icsUtc = (ms) => new Date(ms).toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "Z");
function checkEmail(e, field) {
if (typeof e !== "string" || e.length > 254 || !EMAIL_RE.test(e)) throw new ToolError("invalid_input", `${field}: not a valid email address`);
return e;
}
function resolveTimes(input) {
const tz = input.timezone ?? input.time_zone;
if (tz !== undefined) requireTz(tz, "timezone");
const startMs = parseInstant(input.start, tz);
if (startMs === null) throw new ToolError("invalid_input", "start must be an ISO date-time with Z or an offset, or a local YYYY-MM-DDTHH:MM together with timezone");
let endMs;
if (input.end !== undefined) {
endMs = parseInstant(input.end, tz);
if (endMs === null) throw new ToolError("invalid_input", "end must be an ISO date-time with Z or an offset, or a local YYYY-MM-DDTHH:MM together with timezone");
} else if (input.duration_minutes !== undefined) endMs = startMs + input.duration_minutes * 60000;
else throw new ToolError("invalid_input", "Provide end or duration_minutes");
if (endMs <= startMs) throw new ToolError("invalid_input", "end must be after start");
if (endMs - startMs > 14 * DAY) throw new ToolError("invalid_input", "Meetings longer than 14 days are not supported");
return { startMs, endMs, tz };
}
async function propose_meeting(input, ctx) {
const { startMs, endMs, tz } = resolveTimes(input);
const attendees = (input.attendees ?? []).map((a, i) => checkEmail(a, `attendees[${i}]`));
const organizer = input.organizer !== undefined ? checkEmail(input.organizer, "organizer") : null;
const uid =
input.uid ??
`${createHash("sha256").update(JSON.stringify([input.title, startMs, endMs, [...attendees].sort(), organizer])).digest("hex").slice(0, 32)}@agentrove.calendar-assistant`;
const lines = [
"BEGIN:VCALENDAR",
"VERSION:2.0",
`PRODID:-//AgentRove//calendar-assistant ${manifest.version}//EN`,
"CALSCALE:GREGORIAN",
"BEGIN:VEVENT",
`UID:${uid}`,
`DTSTAMP:${icsUtc(ctx.now().getTime())}`,
`DTSTART:${icsUtc(startMs)}`,
`DTEND:${icsUtc(endMs)}`,
`SUMMARY:${escapeText(input.title)}`,
];
if (input.description) lines.push(`DESCRIPTION:${escapeText(input.description)}`);
if (input.location) lines.push(`LOCATION:${escapeText(input.location)}`);
if (organizer) lines.push(`ORGANIZER:mailto:${organizer}`);
for (const a of attendees) lines.push(`ATTENDEE;ROLE=REQ-PARTICIPANT;PARTSTAT=NEEDS-ACTION;RSVP=TRUE:mailto:${a}`);
lines.push("STATUS:TENTATIVE", "TRANSP:OPAQUE", "END:VEVENT", "END:VCALENDAR");
const ics = lines.map(foldLine).join("\r\n") + "\r\n";
const event = { uid, summary: input.title, start: isoUtc(startMs), end: isoUtc(endMs), all_day: false };
if (tz) event.timezone = tz;
if (input.location) event.location = input.location;
const notes = ["Draft only: nothing was saved, sent or added to any calendar. Times are written in UTC so any client can import them."];
if (tz) notes.push(`Local time: ${isoLocal(startMs, tz)} to ${isoLocal(endMs, tz)} (${tz}).`);
if (attendees.length) notes.push("Importing this file does not email attendees; sending invitations is up to you or your calendar client.");
return { ics, event, notes };
}
// ------------------------------------------------------------------------------------------------
// create_google_event (external_write; the SDK refuses to run it unless input.confirm === true)
// ------------------------------------------------------------------------------------------------
const B32HEX = "0123456789abcdefghijklmnopqrstuv";
function base32hex(buf) {
let bits = 0;
let value = 0;
let out = "";
for (const byte of buf) {
value = (value << 8) | byte;
bits += 8;
while (bits >= 5) {
out += B32HEX[(value >>> (bits - 5)) & 31];
bits -= 5;
}
value &= (1 << bits) - 1;
}
return out;
}
async function readJsonCapped(res, maxBytes = 1_000_000) {
const text = await res.text();
if (text.length > maxBytes) throw new ToolError("google_api_error", "Google response was unexpectedly large");
try {
return JSON.parse(text);
} catch {
return null;
}
}
async function create_google_event(input, ctx) {
const token = ctx.env.GOOGLE_CALENDAR_ACCESS_TOKEN;
if (!token) {
throw new ToolError(
"missing_credential",
"Set GOOGLE_CALENDAR_ACCESS_TOKEN to an OAuth 2.0 access token you obtained for your own Google account (scope https://www.googleapis.com/auth/calendar.events).",
);
}
const { startMs, endMs, tz } = resolveTimes({ ...input, timezone: input.time_zone });
const attendees = (input.attendees ?? []).map((a, i) => checkEmail(a, `attendees[${i}]`));
const calendarId = input.calendar_id ?? "primary";
const sendUpdates = input.send_updates ?? "none";
const eventId =
input.event_id ?? `ar${base32hex(createHash("sha256").update(JSON.stringify([calendarId, input.summary, startMs, endMs])).digest()).slice(0, 24)}`;
const body = {
id: eventId,
summary: input.summary,
start: tz ? { dateTime: isoUtc(startMs), timeZone: tz } : { dateTime: isoUtc(startMs) },
end: tz ? { dateTime: isoUtc(endMs), timeZone: tz } : { dateTime: isoUtc(endMs) },
};
if (input.description) body.description = input.description;
if (input.location) body.location = input.location;
if (attendees.length) body.attendees = attendees.map((email) => ({ email }));
const url = `https://www.googleapis.com/calendar/v3/calendars/${encodeURIComponent(calendarId)}/events?sendUpdates=${encodeURIComponent(sendUpdates)}`;
const res = await ctx.fetch(url, {
method: "POST",
redirect: "error",
headers: { authorization: `Bearer ${token}`, "content-type": "application/json", accept: "application/json" },
body: JSON.stringify(body),
});
const json = await readJsonCapped(res);
const request = { method: "POST", url, event_id: eventId, send_updates: sendUpdates };
if (res.status === 409) {
return { created: false, already_exists: true, id: eventId, calendar_id: calendarId, request };
}
if (res.status === 401 || res.status === 403) {
throw new ToolError("google_auth_error", `Google Calendar rejected the request (HTTP ${res.status}). Check that the access token is valid and has the calendar.events scope.`);
}
if (!res.ok) {
const msg = typeof json?.error?.message === "string" ? json.error.message.slice(0, 300) : "no error message";
throw new ToolError("google_api_error", `Google Calendar API returned HTTP ${res.status}: ${msg}`);
}
const out = { created: true, already_exists: false, id: typeof json?.id === "string" ? json.id : eventId, calendar_id: calendarId, request };
if (typeof json?.htmlLink === "string") out.html_link = json.htmlLink;
if (typeof json?.status === "string") out.status = json.status;
return out;
}
const agent = defineAgent(manifest, { parse_ics, find_free_slots, propose_meeting, create_google_event });
export default agent;